Beispiel #1
0
class externQWidget(QWidget):
	def __init__(self, parent):
		QWidget.__init__(self, parent)
		
		self.checkBoxExtern = QCheckBox('undock', self)
		self.checkBoxExtern.setGeometry(5, 5, 70, 20)
		self.checkBoxExtern.setChecked(False)

		self.checkBoxExtern.toggled[bool].connect(self.onExtern)
		
		self.__v_pos = QPoint(100, 100)
	# end __init__
	
	def closeEvent(self, event):
		event.ignore()

		self.checkBoxExtern.setChecked(False)
		#self.__onExtern(False)

		#QWidget.closeEvent(self, event)
	# end closeEvent
	
	def onExtern(self, b):
		if (b):
			self.setWindowFlags(Qt.Dialog)
			self.move(self.__v_pos)
		else:
			self.__v_pos = self.pos()
			self.setWindowFlags(Qt.Widget)
			self.move(0, 0)
		# end if

		self.show()
Beispiel #2
0
class LoginForm(QMainWindow):
    def __init__(self, parent=None):
        super(LoginForm, self).__init__(parent)
        self.width, self.height = 800, 650
        self.crear_interfaz(self.width, self.height)
        self.checkbox_rememberme.clicked.connect(self.remember_me)
        self.button_login.clicked.connect(self.logging)
        # self.div_create.setVisible(False)
        self.database = Database()
        """self.label_rememberme.mousePressEvent = self.do_remember

	def do_remember(self, event):
		# TDE FIXME: Create another remember_me method for remember me label 
		self.remember_me(event)
		"""

    def loading(self):
        print "loading..."

    def logging(self):
        self.valid_fields()

    def valid_fields(self):
        username = self.username.text()
        password = self.password.text()

        if username == '':
            self.username.setFocus(True)
        elif password == '':
            self.password.setFocus(True)
        else:
            self.loading()
            self.username.setEnabled(False)
            self.password.setEnabled(False)
            print "Logging validation username"
            if self.database.login(username, password):
                print "Bienvenido %s" % username
            else:
                print "Datos incorrectos!"

        # return True in end of statement

    def anim_left(self):
        animation = QPropertyAnimation(self.label_icon, "geometry")
        animation.setDuration(250)
        animation.setStartValue(QRect(0, 0, 20, 20))
        animation.setEndValue(QRect(20, 0, 20, 20))
        animation.start()
        self.animation = animation

    def anim_right(self):
        animation = QPropertyAnimation(self.label_icon, "geometry")
        animation.setDuration(250)
        animation.setStartValue(QRect(20, 0, 20, 20))
        animation.setEndValue(QRect(0, 0, 20, 20))
        animation.start()
        self.animation = animation

    def remember_me(self):
        if self.checkbox_rememberme.isChecked():
            self.anim_left()
            self.label_icon.setGeometry(20, 0, 20, 20)
        else:
            self.anim_right()
            self.label_icon.setGeometry(0, 0, 20, 20)

    def crear_interfaz(self, width, height):
        self.setMinimumSize(width, height)
        self.setMaximumSize(width, height)
        self.setWindowTitle('I n i c i a  s e s i ó n | SN')
        self.setObjectName('login_form_window')

        self.container = QWidget(self)
        self.container.setMinimumSize(width, height)
        self.container.setMaximumSize(width, height)
        self.container.setObjectName('login_container')

        self.title = QLabel(self)
        self.title.setText('I N I C I A   S E S I Ó N   G R Á T I S')
        self.title.setGeometry(210, 130, 400, 40)
        self.title.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.title.setObjectName('login_title')

        self.username = QLineEdit(self)
        self.username.setPlaceholderText('N O M B R E  D E  U S U A R I O')
        self.username.setGeometry(260, 230, 300, 40)
        self.username.setObjectName('login_username')
        self.username.setAcceptDrops(False)

        self.password = QLineEdit(self)
        self.password.setPlaceholderText('C O N T R A S E Ñ A')
        self.password.setGeometry(260, 290, 300, 40)
        self.password.setObjectName('login_password')
        self.password.setEchoMode(QLineEdit.Password)

        self.checkbox_rememberme = QCheckBox(self)
        self.checkbox_rememberme.setLayoutDirection(Qt.RightToLeft)
        self.checkbox_rememberme.setGeometry(260, 360, 40, 20)
        self.checkbox_rememberme.setObjectName("login_rememberme")
        self.checkbox_rememberme.setCursor(QCursor(Qt.PointingHandCursor))

        self.label_icon = QLabel(self.checkbox_rememberme)
        self.label_icon.setGeometry(0, 0, 20, 20)
        self.label_icon.setObjectName("label_icon")

        self.label_rememberme = QLabel(self)
        self.label_rememberme.setText("R E C U É R D A M E")
        self.label_rememberme.setGeometry(310, 360, 165, 20)
        self.label_rememberme.setObjectName("label_rememberme")

        self.button_login = QPushButton(self)
        self.button_login.setGeometry(315, 420, 200, 40)
        self.button_login.setText("I N I C I A R  S E S I Ó N")
        self.button_login.setObjectName("button_login")

        self.layout = QGridLayout(self.container)
Beispiel #3
0
class Chat(QFrame):

    # =======================================================================
    def __init__(self, parent=None, _PARENT=None):

        # -------------------------------------------------------------------
        QFrame.__init__(self, parent);
        # -------------------------------------------------------------------
        self.PARENT                         = _PARENT;
        self.CONF                           = _PARENT.CONF;

        self.setGeometry(3, 5, 975, 548);
        self.setStyleSheet( "QFrame{ font: 12px 'monospace'; color: #000; background-color: transparent; background-image: url('./data/imgs/TAB_Chat.png'); }" );

        # -------------------------------------------------------------------
        self.CHAT_URL                       = "https://btc-e.com/";
        self.CHAT_DATA                      = [];
        self.CHAT_LANG                      = self.CONF["USER"]["CHAT_LANG"];

        self.CHAT_HEADERS = {
            "User-Agent"        : "Mozilla/5.0 (Win-32; rv:24.0) Gecko/20140723 Firefox/24.0 Iceweasel/24.7.0",
            "Accept"            : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "Accept-Language"   : "en-US,en;q=0.5",
            "Referer"           : "https://btc-e.com/",
            "Connection"        : "keep-alive",
            "Cache-Control"     : "max-age=0",
            "Cookie"            : ""
        }

        self.CHAT_TIMER                     = QTimer();
        #self.CHAT_BG_COLOR                  = "#555";
        self.CHAT_BG_COLOR                  = "#0F0";
        self.CHAT_ALLOW_UPD                 = False;
        # -------------------------------------------------------------------
        self.CHAT_WIDGET                    = QTextEdit( self );
        self.CHAT_WIDGET.setGeometry( 13, 116, 690, 388 );
        self.CHAT_WIDGET.setStyleSheet( "QTextEdit{ background-color: transparent; color: #fff; background-image: url(''); }" );
        self.CHAT_WIDGET.setReadOnly( True );

        self.LANG_COMBO                     = QComboBox( self);
        self.LANG_COMBO.setGeometry( 86, 20, 108, 44 ); 
        self.connect( self.LANG_COMBO, SIGNAL('currentIndexChanged(int)'), self.CHANGE_CHAT_LANG );
        self.LANG_COMBO.setEditable(False);
        

        self.NEW_MSG                    = QLineEdit("", self);
        self.NEW_MSG.setGeometry( 20, 510, 500, 30 );
        self.NEW_MSG.setStyleSheet(" QLineEdit{ border-style: none; background-color: #333; color: #fff; background-image: url(''); }");
        self.NEW_MSG.setPlaceholderText(" Enter message:");



        self.SEND                       = QPushButton(" Send", self); 
        self.SEND.setGeometry( 593, 510, 90, 30 );
        #self.SEND.setStyleSheet( "QPushButton{ background-color: transparent; border-style: none; }" ); 
        #self.connect( self.SEND, SIGNAL('clicked()'), lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SEND_VALUES") );

        # -------------------------------------------------------------------
        self.ALLOW_UPDATE_CHECKBOX        = QCheckBox("", self);
        self.ALLOW_UPDATE_CHECKBOX.setGeometry( 335, 83, 17, 17 );
        self.ALLOW_UPDATE_CHECKBOX.setCheckState(Qt.Unchecked);
        self.connect(self.ALLOW_UPDATE_CHECKBOX, SIGNAL('stateChanged(int)'), self.CHANGE_VALUES );


        self.UPDATE_NOW_BTN               = QPushButton("Update Now!", self);
        self.UPDATE_NOW_BTN.setGeometry( 360, 74, 94, 24 );
        self.connect( self.UPDATE_NOW_BTN, SIGNAL('clicked()'), self.UPDATE_NOW );

        # -------------------------------------------------------------------
        self.INIT();
        # -------------------------------------------------------------------

    # =======================================================================
    def INIT(self):

        # -------------------------------------------------------------------
        try:
            self.INIT_CHAT_COMBO();
            self.UPDATE();

        except Exception as _exception:

            print("-----------------------------------------------------");
            print("[INIT]"+str(_exception));
        # -------------------------------------------------------------------

    # =======================================================================
    def UPDATE_NOW(self):

        # -------------------------------------------------------------------
        self.CHAT_ALLOW_UPD = True;

        self.UPDATE();

        self.CHAT_ALLOW_UPD = False;
        # -------------------------------------------------------------------

    # =======================================================================
    def UPDATE(self):

        # -------------------------------------------------------------------
        #print("UPDATE:")
        # -------------------------------------------------------------------
        try:

            if self.CHAT_ALLOW_UPD:

                self.GET_DATA();
                self.CHAT_WIDGET.clear();

                for msg in self.CHAT_DATA:

                    # ---------------------------------------------------------------
                    """
                    print(msg["time"]);
                    print(msg["nick"]);
                    print(msg["msg"]);
                    """

                    # ---------------------------------------------------------------
                    item = '<p style="background-color: #555;">';                
                    item += "[<span style='color: #000;'>"+msg["time"].split(" ")[1]+"</span>] : ";

                    if msg["nick"] == "admin":
                        item += "[<span style='color: #f00; font-weight: bold;'>"+msg["nick"]+"</span>]<br/><br/>";
                    else:
                        item += "[<span style='color: #000; font-weight: bold;'>"+msg["nick"]+"</span>]<br/><br/>";

                    item += msg["msg"]+"<br/>";
                    item += "</p>";

                    self.CHAT_WIDGET.append(item);


                    # ---------------------------------------------------------------

            self.CHAT_TIMER.singleShot( self.CONF["SYS"]["UPD_DELAY"], self.UPDATE );

        except Exception as e:
            
            print("CHAT[0:0]"+str(e))
            self.CHAT_TIMER.singleShot( self.CONF["SYS"]["UPD_DELAY"], self.UPDATE );

        # -------------------------------------------------------------------

    # =======================================================================
    def CHANGE_VALUES(self):

        # -------------------------------------------------------------------
        if self.ALLOW_UPDATE_CHECKBOX.isChecked():
            self.CHAT_ALLOW_UPD = True;

        else:
            self.CHAT_ALLOW_UPD = False;

        # -------------------------------------------------------------------

    # =======================================================================
    def GET_DATA(self):
        
        # -------------------------------------------------------------------
        try:

            self.CHAT_HEADERS["Cookie"] = "chatRefresh=1; locale="+self.CHAT_LANG+";"

            req = urllib2.Request(self.CHAT_URL, headers=self.CHAT_HEADERS);
            resp = urllib2.urlopen(req).read();

            CHAT = BeautifulSoup( resp ).body.find('div', attrs={'id':'nChat'});

            self.CHAT_DATA = [];

            for data in CHAT:

                self.CHAT_DATA.append( { "msg_id": data["id"], "nick":data.a.string, "time": data.a["title"], "msg": data.span.string } );


        except Exception as e:
            
            print("CHAT[0:1]"+str(e))
        # -------------------------------------------------------------------

    # =======================================================================
    def CHANGE_CHAT_LANG(self):

        # -------------------------------------------------------------------
        self.CHAT_LANG = str(self.LANG_COMBO.currentText()).lower().strip();
        #print(self.CHAT_LANG);
        # -------------------------------------------------------------------

    # =======================================================================
    def INIT_CHAT_COMBO(self):

        # -------------------------------------------------------------------
        for LANG in self.CONF["USER"]["CHAT_LANGS"]:
            self.LANG_COMBO.addItem(LANG.upper());

        for i in xrange(0, self.LANG_COMBO.__len__()):

            self.LANG_COMBO.setItemData( i, QColor("#333"),Qt.BackgroundRole );
            self.LANG_COMBO.setItemData( i, QColor("#fff"),Qt.ForegroundRole );
class ReactionProfile(QWidget):
    def __init__(self, reaction, readonly):
        super(ReactionProfile, self).__init__()
        self._painter = QPainter()
        self._canshowreaction = True
        self._IsReadOnly = readonly
        # Show labels checkbox widget
        self._showlabels = QCheckBox("Show data", self)
        self._showlabels.setChecked(False)
        self._showlabels.setGeometry(0, 0, 80, 20)
        self._showlabels.clicked.connect(self.update)
        # The buttons
        if self._IsReadOnly:
            self._CurrentReaction = copy.deepcopy(reaction)
        else:
            self._CurrentReaction = reaction
            self._rcolbtn = QPushButton("Set reactant colour", self)
            self._rcolbtn.setGeometry(140, 60, 110, 30)
            self._rcolbtn.clicked.connect(self.SetReactantColour)
            self._pcolbtn = QPushButton("Set product colour", self)
            self._pcolbtn.setGeometry(350, 60, 110, 30)
            self._pcolbtn.clicked.connect(self.SetProductColour)
            self._clonebtn = QPushButton("Compare reaction", self)
            self._clonebtn.setGeometry(10, 310, 120, 30)
            self._clonebtn.clicked.connect(self.Clone)
            self._concbtn = QPushButton("Concentration graphs", self)
            self._concbtn.setGeometry(10, 100, 120, 30)
            self._concbtn.clicked.connect(self.MakeConcGraphs)
            self._ratebtn = QPushButton("Rate graphs", self)
            self._ratebtn.setGeometry(10, 130, 120, 30)
            self._ratebtn.clicked.connect(self.MakeRateGraphs)
        self._getkcbtn = QPushButton("Calculate Kc", self)
        self._getkcbtn.setGeometry(10, 180, 120, 30)
        self._getkcbtn.clicked.connect(self.GetKc)
        self._workingbtn = QPushButton("Show working", self)
        self._workingbtn.setGeometry(10, 225, 120, 30)
        self._workingbtn.clicked.connect(self.ShowWorking)
        self._startanim = QPushButton("Start animation", self)
        self._startanim.setGeometry(10, 260, 120, 30)
        self._startanim.clicked.connect(self.StartAnimation)
        # The labels
        self._catalabel = QLabel("", self)
        self._catalabel.setGeometry(250, 60, 100, 40)
        self._catalabel.setAlignment(Qt.AlignCenter)
        self._kclabel = QLabel(self)
        self._kclabel.setGeometry(20, 205, 140, 20)
        self._volumelabel = QLabel(self)
        self._volumelabel.setGeometry(200, 317, 140, 20)
        # Set up reactant and product labels
        formulafont = QFont()
        formulafont.setBold(True)
        formulafont.setPointSize(12)
        self._rpalette = QPalette()
        self._ppalette = QPalette()
        self._reactantlabel = QLabel("", self)
        self._reactantlabel.setGeometry(0, 20, 268, 32)
        self._reactantlabel.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self._reactantlabel.setFont(formulafont)
        self._reactantlabel.setPalette(self._rpalette)
        self._reactantlabel.show()
        self._productlabel = QLabel("", self)
        self._productlabel.setGeometry(332, 20, 268, 32)
        self._productlabel.setAlignment(Qt.AlignVCenter)
        self._productlabel.setFont(formulafont)
        self._productlabel.setPalette(self._ppalette)
        self._productlabel.show()
        # Other properties
        self._Squares = []
        for x in range(100):
            self._Squares.append(Square(200+((x % 10) * 20), 120 + ((x // 10) * 20), self._CurrentReaction))
        self._timer = QTimer(self)
        self._timer.setInterval(30)
        self._timer.setSingleShot(False)
        self._timer.timeout.connect(self.ContinueAnimation)
        self._no_of_anim_updates = 0
        self._ExtraWindows = []
        self._kcdifference = ""
        self._rflipchance = 0
        self._pflipchance = 0
        self._graphs = None

    def paintEvent(self, e):
        reactantside = ""
        productside = ""
        for x in range(len(self._CurrentReaction.GetReactants())):
            reactant = self._CurrentReaction.GetReactants()[x]
            if reactant.GetUsed():
                if x > 0:
                    reactantside += " + "
                reactantside += reactant.GetFormulaForLabels()
        for x in range(len(self._CurrentReaction.GetProducts())):
            product = self._CurrentReaction.GetProducts()[x]
            if product.GetUsed():
                if x > 0:
                    productside += " + "
                productside += product.GetFormulaForLabels()
        self._rpalette.setColor(QPalette.WindowText, self._CurrentReaction.GetReactantColour())
        self._ppalette.setColor(QPalette.WindowText, self._CurrentReaction.GetProductColour())
        self._reactantlabel.setPalette(self._rpalette)
        self._productlabel.setPalette(self._ppalette)
        self._painter.begin(self)
        self._painter.setFont(QFont("Arial", 20, 50, False))
        self._painter.setPen(QPen(self._CurrentReaction.GetReactantColour()))
        if self._CurrentReaction.GetCatalyst().GetUsed():
            self._catalabel.setText("Catalyst: "+
                                    self._CurrentReaction.GetCatalyst().GetFormulaForLabels()+"<br>Moles: "+
                                    str(self._CurrentReaction.GetCatalyst().GetInitialMoles())+"<br>Strength: "+
                                    self._CurrentReaction.GetCatalyst().GetEfficacyAsString())
            self._catalabel.show()
        else:
            self._catalabel.hide()
        self._reactantlabel.setText(reactantside)
        self._productlabel.setText(productside)
        target = QRectF(278, 20, 44, 32)
        arrows = QPixmap("assets/double arrow h.png")
        portion = QRectF(10, 0, 44, 32)
        self._painter.drawPixmap(target, arrows, portion)
        self._painter.setPen(QPen(self._CurrentReaction.GetProductColour()))
        self._painter.setPen(QPen(QColor(0, 0, 0, 255)))
        self._painter.setFont(QFont("Arial", 8, 50, False))
        self._volumelabel.setText("Vessel volume: "+str(self._CurrentReaction.GetVolume())+" dm<sup>3</sup>")
        self._painter.drawText(200, 340, "Vessel temperature: "+str(self._CurrentReaction.GetTemperature())+" K")
        if self._CurrentReaction.GetEndothermic():
            self._painter.drawText(200, 350, "Reaction is endothermic")
        else:
            self._painter.drawText(200, 350, "Reaction is exothermic")
        if self._showlabels.isChecked():
            if self._kcdifference == "":
                self._kclabel.show()
            else:
                self._kclabel.hide()
            self._painter.drawText(420, 330, self._kcdifference)
        else:
            self._kclabel.hide()
        for x in self._Squares:
            x.Draw(self._painter)
        self._painter.end()

    def SetReaction(self, reaction):
        if self._IsReadOnly:
            self._CurrentReaction = copy.deepcopy(reaction)
        else:
            self._CurrentReaction = reaction
        self.update()

    def GetReaction(self):
        return self._CurrentReaction

    def MakeConcGraphs(self):
        gwg = GraphWindowGroup(GraphWindow(self._CurrentReaction, "Concentration", self, False),
                               GraphWindow(self.parent().parent().parent().GetComparingReaction(), "Concentration", self, False),
                               self)
        gwg.setGeometry(0, 400, 800, 320)
        self._ExtraWindows.append(gwg)
        self._ExtraWindows[-1].show()

    def MakeRateGraphs(self):
        gwg = GraphWindowGroup(GraphWindow(self._CurrentReaction, "Rate", self, False),
                               GraphWindow(self.parent().parent().parent().GetComparingReaction(), "Rate", self, False),
                               self)
        gwg.setGeometry(420, 400, 800, 320)
        self._ExtraWindows.append(gwg)
        self._ExtraWindows[-1].show()

    def SetReactantColour(self):
        picker = QColorDialog()
        picker.exec_()
        if picker.selectedColor() is not None:
            self._CurrentReaction.SetReactantColour(picker.selectedColor())

    def SetProductColour(self):
        picker = QColorDialog()
        picker.exec_()
        if picker.selectedColor() is not None:
            self._CurrentReaction.SetProductColour(picker.selectedColor())

    def GetKc(self):
        kc = self._CurrentReaction.GetKc()
        newkc = "K<sub>c</sub>"
        x = 2
        while x in range(len(kc)):
            if kc[x] == "^":
                x += 1
                newkc += "<sup>"
                newkc += kc[x]
                newkc += "</sup>"
            else:
                newkc += kc[x]
            x += 1
        self._kclabel.setText(newkc)
        self.update()

    def ShowWorking(self):
        getcontext().prec = 3
        working = QPlainTextEdit()
        working.setWindowTitle("Kc calculation")
        reactants = []
        products = []
        for x in self._CurrentReaction.GetReactants():
            if x.GetUsed():
                reactants.append(x)
        for x in self._CurrentReaction.GetProducts():
            if x.GetUsed():
                products.append(x)
        working.appendPlainText("Concentration = moles / volume")
        volume = self._CurrentReaction.GetVolume()
        working.appendPlainText("Volume = "+str(volume)+" dm^3")
        pvalues = []
        rvalues = []
        for x in products:
            working.appendPlainText("Concentration of "+x.GetFormula()+" = "+str(Decimal(x.GetConcentration(volume)) + Decimal(0.0))+" mol dm^-3")
            pvalues.append(x.GetConcentration(volume))
            pvalues.append(x.GetSRatio())
        for x in reactants:
            working.appendPlainText("Concentration of "+x.GetFormula()+" = "+str(Decimal(x.GetConcentration(volume)) + Decimal(0.0))+" mol dm^-3")
            rvalues.append(x.GetConcentration(volume))
            rvalues.append(x.GetSRatio())
        kcvalue = "Value of Kc ="
        x = 0
        while x < len(pvalues):
            kcvalue += " ("+str(Decimal(pvalues[x]) + Decimal(0.0))+")^"
            x += 1
            kcvalue += str(pvalues[x])
            x += 1
        kcvalue += " /"
        x = 0
        while x < len(rvalues):
            kcvalue += " ("+str(Decimal(rvalues[x]) + Decimal(0.0))+")^"
            x += 1
            kcvalue += str(rvalues[x])
            x += 1
        working.appendPlainText(kcvalue)
        rproductsum = 0
        for x in reactants:
            rproductsum += x.GetSRatio()
        pproductsum = 0
        for x in products:
            pproductsum += x.GetSRatio()
        working.appendPlainText("There are "+str(len(reactants))+" reactants, with units mol dm^-3.")
        working.appendPlainText("The product of these units is mol^"+str(rproductsum)+" dm^"+str(rproductsum * -3)+".")
        working.appendPlainText("There are "+str(len(products))+" products, with units mol dm^-3.")
        working.appendPlainText("The product of these units is mol^"+str(pproductsum)+" dm^"+str(pproductsum * -3)+".")
        working.appendPlainText("The product units must be divided by the reactant units, so")
        working.appendPlainText(self._CurrentReaction.GetKc())
        self._ExtraWindows.append(working)
        working.show()

    def StartAnimation(self):
        self._no_of_anim_updates = 0
        reactants = []
        for x in self._CurrentReaction.GetReactants():
            if x.GetUsed():
                reactants.append(x)
        products = []
        for x in self._CurrentReaction.GetProducts():
            if x.GetUsed():
                products.append(x)
        self._eqmratio = self.GetRPRatio(reactants, products)
        self._rflipchance = int(self._eqmratio * 100)
        # self._pflipchance = int((1 / self._eqmratio) * 100)
        self._pflipchance = int((1 - self._eqmratio) * 100)
        if self._CurrentReaction.GetCatalyst().GetUsed():
            efficacy = self._CurrentReaction.GetCatalyst().GetEfficacy()
            self._rflipchance /= efficacy
            self._pflipchance /= efficacy
            flipchancechangefromcata = 2.0 * (self._CurrentReaction.GetCatalyst().GetInitialMoles() / 100)
            if efficacy > 1:
                flipchancechangefromcata *= -1
            self._rflipchance = int(self._rflipchance + flipchancechangefromcata)
            self._pflipchance = int(self._pflipchance + flipchancechangefromcata)
        for x in self._Squares:
            x.Reset()
        self._timer.start()

    def ContinueAnimation(self):
        self._no_of_anim_updates += 1
        reactantsquares = 0
        for x in self._Squares:
            if x.GetIsReactant():
                reactantsquares += 1
        print("Reactant squares: "+str(reactantsquares))
        # currentratio = reactantsquares / (101 - reactantsquares)
        currentratio = reactantsquares / 100
        newrflipchance = self._rflipchance
        newpflipchance = self._pflipchance
        if currentratio < int(self._eqmratio * 100):
            newrflipchance -= currentratio * 0.2
            newpflipchance += currentratio * 0.2
        elif currentratio > int(self._eqmratio * 100):
            newrflipchance += currentratio * 0.2
            newpflipchance -= currentratio * 0.2
        for x in self._Squares:
            x.Flip(newrflipchance, newpflipchance)
        self.update()
        for x in self._ExtraWindows:
            if type(x) == GraphWindowGroup:
                x.update()
        if self._no_of_anim_updates > 1000:
            self._timer.stop()

    def RemoveMe(self, qwidg):
        self._ExtraWindows.remove(qwidg)

    def Clone(self):
        self.parent().parent().parent().SetComparingReaction(self._CurrentReaction)

    def SetKcDifference(self, string):
        self._kcdifference = string

    def PrintGraph(self, painter, graphof):
        GraphWindow(self._CurrentReaction, graphof, self, True).render(painter)

    def GetRPRatio(self, reactants, products):
        # volume = self._CurrentReaction.GetVolume()
        # arc = 0
        # for x in reactants:
        #     arc += x.GetConcentration(volume)
        # arc /= len(reactants)
        # apc = 0
        # for x in products:
        #     apc += x.GetConcentration(volume)
        # apc /= len(products)
        # return arc / apc
        rm = 0
        for x in reactants:
            rm += x.GetInitialMoles()
        pm = 0
        for x in products:
            pm += x.GetInitialMoles()
        return rm / (rm + pm)

    def GetAnimUpdates(self):
        return self._no_of_anim_updates
Beispiel #5
0
class GuiMain(object):
    def __init__(self, data):
        
        self.data = data
        self.loadSave = False
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        
        #Set size of window and make it non-resizeable
        MainWindow.resize(818, 665)
        MainWindow.setFixedHeight(665)
        MainWindow.setFixedWidth(818)
        
        MainWindow.setWindowTitle("Map Master: Search for the Lost City")
        MainWindow.setWindowIcon(QIcon("icon_medium.ico"))

        #Set window backgrounds
        self.background = QLabel(MainWindow)
        
        
        self.backgroundPixmapMenu = QPixmap(normpath("images/gameMenu2.png"))
        self.backgroundPixmapSettings = QPixmap(normpath("images/gameMenuSettings2.png"))
        self.background.setPixmap(self.backgroundPixmapMenu)       
        
        self.background.setGeometry(QtCore.QRect(0, 0, 818, 665))
        
        #Stylesheet settings for labels and buttons
        self.fg = "QLabel {color:black}"
        self.fgb = "QPushButton {color:black}"

        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.stackedWidget = QStackedWidget(self.centralwidget)
        self.stackedWidget.setEnabled(True)
        self.stackedWidget.setObjectName("stackedWidget")
        
        #Main Menu page
        self.menuPage = QWidget()
        self.menuPage.setObjectName("menuPage")
        self.startButton = QPushButton(self.menuPage)
        self.startButton.setStyleSheet(self.fgb)
        self.startButton.setGeometry(QtCore.QRect(600, 200, 180, 60))
        self.startButton.setText(QApplication.translate("MainWindow", "Start Game", None, QApplication.UnicodeUTF8))
        self.startButton.setObjectName("startButton")
        self.loadButton = QPushButton(self.menuPage)
        self.loadButton.setStyleSheet(self.fgb)
        self.loadButton.setGeometry(QtCore.QRect(600, 280, 180, 60))
        self.loadButton.setText(QApplication.translate("MainWindow", "Load Game", None, QApplication.UnicodeUTF8))
        self.loadButton.setObjectName("loadButton")
        self.settingsButton = QPushButton(self.menuPage)
        self.settingsButton.setStyleSheet(self.fgb)
        self.settingsButton.setGeometry(QtCore.QRect(600, 440, 180, 60))
        self.settingsButton.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8))
        self.settingsButton.setObjectName("settingsButton")
        self.quitButton = QPushButton(self.menuPage)
        self.quitButton.setStyleSheet(self.fgb)
        self.quitButton.setGeometry(QtCore.QRect(600, 520, 180, 60))
        self.quitButton.setText(QApplication.translate("MainWindow", "Quit", None, QApplication.UnicodeUTF8))
        self.quitButton.setObjectName("quitButton")
        self.instrButton = QPushButton(self.menuPage)
        self.instrButton.setStyleSheet(self.fgb)
        self.instrButton.setGeometry(QtCore.QRect(600, 360, 180, 60))
        self.instrButton.setText(QApplication.translate("MainWindow", "Instructions", None, QApplication.UnicodeUTF8))
        self.instrButton.setObjectName("instrButton")
        self.stackedWidget.addWidget(self.menuPage)
        
        #Settings page
        self.settingsPage = QWidget()
        self.settingsPage.setObjectName("settingsPage")
        self.volumeSlider = QSlider(self.settingsPage)
        self.volumeSlider.setGeometry(QtCore.QRect(200, 200, 400, 30))
        self.volumeSlider.setProperty("value", 50)
        self.volumeSlider.setOrientation(QtCore.Qt.Horizontal)
        self.volumeSlider.setObjectName("volumeSlider")
        self.soundLabel = QLabel(self.settingsPage)
        self.soundLabel.setGeometry(QtCore.QRect(340, 160, 120, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.soundLabel.setFont(font)
        self.soundLabel.setStyleSheet(self.fg)
        self.soundLabel.setText(QApplication.translate("MainWindow", "Volume", None, QApplication.UnicodeUTF8))
        self.soundLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.soundLabel.setObjectName("soundLabel")
        
        #Quiet Sound Graphic
        self.quietGraphic = QLabel(self.settingsPage)
        self.quietGraphic.setPixmap(QPixmap(normpath("images/speakerQuiet.png")))
        self.quietGraphic.setGeometry(QtCore.QRect(90, 180, 80, 80))
        self.quietGraphic.setObjectName("quietGraphic")
        
        #Loud Sound Graphic
        self.loudGraphic = QLabel(self.settingsPage)
        self.loudGraphic.setPixmap(QPixmap(normpath("images/speakerLoud.png")))
        self.loudGraphic.setEnabled(True)
        self.loudGraphic.setGeometry(QtCore.QRect(630, 180, 80, 80))
        self.loudGraphic.setObjectName("loudGraphic")
        
        self.settingsLabel = QLabel(self.settingsPage)
        self.settingsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(36)
        self.settingsLabel.setFont(font)
        self.settingsLabel.setStyleSheet(self.fg)
        self.settingsLabel.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8))
        self.settingsLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.settingsLabel.setObjectName("settingsLabel")
        self.doneButton = QPushButton(self.settingsPage)
        self.doneButton.setStyleSheet(self.fgb)
        self.doneButton.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8))
        self.doneButton.setObjectName("doneButton")
        self.stackedWidget.addWidget(self.settingsPage)
        
        self.soundManager = Sounds(self.volumeSlider.sliderPosition())
        
        #Main Game page
        self.mainPage = QWidget()
        self.mainPage.setObjectName("mainPage")
        
        #Person View
        self.personView = ViewGraphics(self.mainPage)
        self.personView.setGeometry(QtCore.QRect(0, 0, 390, 500))
        self.personView.setObjectName("personView")
        
        #Map View
        self.mapView = ViewGraphics(self.mainPage)
        self.mapView.setGeometry(QtCore.QRect(410, 0, 390, 500))
        self.mapView.setObjectName("mapView")
        
        #ClueView
        self.clueView = QLabel(self.mainPage)
        self.clueView.setGeometry(QtCore.QRect(0, 510, 390, 91))
        self.clueView.setObjectName("clueView")
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.clueView.setFont(font)
        self.clueView.setStyleSheet(self.fg)
        
        #Map Toggles
        self.latLongCheck = QCheckBox(self.mainPage)
        self.latLongCheck.setGeometry(QtCore.QRect(420, 510, 97, 41))
        self.latLongCheck.setText(QApplication.translate("MainWindow", "Latitude/ \n"
        "Longitude", None, QApplication.UnicodeUTF8))
        self.latLongCheck.setObjectName("latLongCheck")

        self.colorCheck = QCheckBox(self.mainPage)
        self.colorCheck.setGeometry(QtCore.QRect(560, 510, 97, 41))
        self.colorCheck.setText(QApplication.translate("MainWindow", "Color\n"
        "Coding", None, QApplication.UnicodeUTF8))
        self.colorCheck.setObjectName("colorCheck")
        self.legendCheck = QCheckBox(self.mainPage)
        self.legendCheck.setGeometry(QtCore.QRect(680, 520, 97, 22))
        self.legendCheck.setText(QApplication.translate("MainWindow", "Legend", None, QApplication.UnicodeUTF8))
        self.legendCheck.setObjectName("legendCheck")
        self.searchButton = QPushButton(self.mainPage)
        self.searchButton.setStyleSheet(self.fgb)
        self.searchButton.setGeometry(QtCore.QRect(420, 560, 211, 41))
        self.searchButton.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8))
        self.searchButton.setObjectName("searchButton")
        
        #Score pieces
        self.scoreBox = QLabel(self.mainPage)
        self.scoreBox.setStyleSheet(self.fg)
        self.scoreBox.setGeometry(QtCore.QRect(720, 560, 71, 41))
        self.scoreBox.setObjectName("scoreBox")
        self.scoreBox.setText(QApplication.translate("MainWindow", "0", None, QApplication.UnicodeUTF8))
        self.scoreLabel = QLabel(self.mainPage)
        self.scoreLabel.setStyleSheet(self.fg)
        self.scoreLabel.setGeometry(QtCore.QRect(660, 570, 51, 17))
        self.scoreLabel.setText(QApplication.translate("MainWindow", "Score:", None, QApplication.UnicodeUTF8))
        self.scoreLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.scoreLabel.setObjectName("scoreLabel")
        self.stackedWidget.addWidget(self.mainPage)
        
        #Help page
        self.helpPage = QWidget()
        self.helpPage.setObjectName("helpPage")
        self.HelpLabel = QLabel(self.helpPage)
        self.HelpLabel.setStyleSheet(self.fg)
        self.HelpLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(36)
        self.HelpLabel.setFont(font)
        self.HelpLabel.setText(QApplication.translate("MainWindow", "Instructions", None, QApplication.UnicodeUTF8))
        self.HelpLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.HelpLabel.setObjectName("HelpLabel")
        self.wInstr = QLabel(self.helpPage)
        self.wInstr.setStyleSheet(self.fg)
        self.wInstr.setGeometry(QtCore.QRect(200, 150, 40, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.wInstr.setFont(font)
        self.wInstr.setText(QApplication.translate("MainWindow", "W", None, QApplication.UnicodeUTF8))
        self.wInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.wInstr.setObjectName("wInstr")
        self.sInstr = QLabel(self.helpPage)
        self.sInstr.setStyleSheet(self.fg)
        self.sInstr.setGeometry(QtCore.QRect(200, 200, 40, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.sInstr.setFont(font)
        self.sInstr.setText(QApplication.translate("MainWindow", "S", None, QApplication.UnicodeUTF8))
        self.sInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.sInstr.setObjectName("sInstr")
        self.aInstr = QLabel(self.helpPage)
        self.aInstr.setStyleSheet(self.fg)
        self.aInstr.setGeometry(QtCore.QRect(200, 250, 40, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.aInstr.setFont(font)
        self.aInstr.setText(QApplication.translate("MainWindow", "A", None, QApplication.UnicodeUTF8))
        self.aInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.aInstr.setObjectName("aInstr")
        self.dInstr = QLabel(self.helpPage)
        self.dInstr.setStyleSheet(self.fg)
        self.dInstr.setGeometry(QtCore.QRect(200, 300, 40, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.dInstr.setFont(font)
        self.dInstr.setText(QApplication.translate("MainWindow", "D", None, QApplication.UnicodeUTF8))
        self.dInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr.setObjectName("dInstr")
        self.wInstr2 = QLabel(self.helpPage)
        self.wInstr2.setStyleSheet(self.fg)
        self.wInstr2.setGeometry(QtCore.QRect(400, 150, 180, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.wInstr2.setFont(font)
        self.wInstr2.setText(QApplication.translate("MainWindow", "Move North", None, QApplication.UnicodeUTF8))
        self.wInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.wInstr2.setObjectName("wInstr2")
        self.sInstr2 = QLabel(self.helpPage)
        self.sInstr2.setStyleSheet(self.fg)
        self.sInstr2.setGeometry(QtCore.QRect(400, 200, 180, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.sInstr2.setFont(font)
        self.sInstr2.setText(QApplication.translate("MainWindow", "Move South", None, QApplication.UnicodeUTF8))
        self.sInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.sInstr2.setObjectName("sInstr2")
        self.aInstr2 = QLabel(self.helpPage)
        self.aInstr2.setStyleSheet(self.fg)
        self.aInstr2.setGeometry(QtCore.QRect(400, 250, 180, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.aInstr2.setFont(font)
        self.aInstr2.setText(QApplication.translate("MainWindow", "Move West", None, QApplication.UnicodeUTF8))
        self.aInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.aInstr2.setObjectName("aInstr2")
        self.dInstr2 = QLabel(self.helpPage)
        self.dInstr2.setStyleSheet(self.fg)
        self.dInstr2.setGeometry(QtCore.QRect(400, 300, 180, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.dInstr2.setFont(font)
        self.dInstr2.setText(QApplication.translate("MainWindow", "Move East", None, QApplication.UnicodeUTF8))
        self.dInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr2.setObjectName("dInstr2")
        self.searchInstr = QPushButton(self.helpPage)
        self.searchInstr.setStyleSheet(self.fgb)
        self.searchInstr.setEnabled(True)
        self.searchInstr.setGeometry(QtCore.QRect(170, 350, 100, 30))
        self.searchInstr.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8))
        self.searchInstr.setAutoDefault(False)
        self.searchInstr.setDefault(False)
        self.searchInstr.setFlat(False)
        self.searchInstr.setObjectName("searchInstr")
        self.dInstr2_2 = QLabel(self.helpPage)
        self.dInstr2_2.setStyleSheet(self.fg)
        self.dInstr2_2.setGeometry(QtCore.QRect(380, 350, 211, 30))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.dInstr2_2.setFont(font)
        self.dInstr2_2.setText(QApplication.translate("MainWindow", "Search for clues", None, QApplication.UnicodeUTF8))
        self.dInstr2_2.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr2_2.setObjectName("dInstr2_2")
        self.doneButton2 = QPushButton(self.helpPage)
        self.doneButton2.setStyleSheet(self.fgb)
        self.doneButton2.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton2.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8))
        self.doneButton2.setObjectName("doneButton2")
        self.stackedWidget.addWidget(self.helpPage)
        
        #Credits page
        self.creditsPage = QWidget()
        self.creditsPage.setObjectName("creditsPage")
        self.creditsLabel = QLabel(self.creditsPage)
        self.creditsLabel.setStyleSheet(self.fg)
        self.creditsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(36)
        self.creditsLabel.setFont(font)
        self.creditsLabel.setText(QApplication.translate("MainWindow", "Credits", None, QApplication.UnicodeUTF8))
        self.creditsLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.creditsLabel.setObjectName("creditsLabel")
        self.credits = QLabel(self.creditsPage)
        self.credits.setStyleSheet(self.fg)
        self.credits.setGeometry(QtCore.QRect(180, 150, 500, 400))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(20)
        self.credits.setFont(font)
        self.credits.setText(QApplication.translate("MainWindow", 
        "Gary Lent\n"
        "Grant Stafford\n"
        "Jessie Liu\n"
        "Peter Andrien\n"
        "Nokia (Qt4 framework)\n"
        "Riverbank Computing Ltd (PyQt)\n"
        "Celestial Aeon Project", None, QApplication.UnicodeUTF8))
        self.credits.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.credits.setObjectName("credits")
        self.doneButton3 = QPushButton(self.creditsPage)
        self.doneButton3.setStyleSheet(self.fgb)
        self.doneButton3.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton3.setText(QApplication.translate("MainWindow", "Done", None, QApplication.UnicodeUTF8))
        self.doneButton3.setObjectName("doneButton3")
        self.stackedWidget.addWidget(self.creditsPage)
        
        #Story page
        self.storyPage = QWidget()
        self.storyPage.setObjectName("storyPage")
        self.storyLabel = QLabel(self.storyPage)
        self.storyLabel.setStyleSheet(self.fg)
        self.storyLabel.setGeometry(QtCore.QRect(100, 50, 600, 400))
        font = QFont()
        font.setFamily("Century Schoolbook L")
        font.setPointSize(25)
        self.storyLabel.setFont(font)
        self.storyLabel.setText(QApplication.translate("MainWindow", "My name is Travis Sinclair.\n I'm a skilled cartographer.\n I recently lost my job, but stumbled\n on a clue that may change my life \nforever. I've set off on a quest - a quest\n to find a lost city. I've found a clue,\n and believe there may be more.\n Help me find the lost city.  ", None, QApplication.UnicodeUTF8))
        self.storyLabel.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.storyLabel.setObjectName("storyLabel")
        self.nextButton = QPushButton(self.storyPage)
        self.nextButton.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.nextButton.setText(QApplication.translate("MainWindow", "Next", None, QApplication.UnicodeUTF8))
        self.nextButton.setObjectName("nextButton")
        self.stackedWidget.addWidget(self.storyPage)
        
        self.gridLayout.addWidget(self.stackedWidget, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        
        #Menu bar
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 818, 25))
        self.menubar.setObjectName("menubar")
        self.menuMenu = QMenu(self.menubar)
        self.menuMenu.setTitle(QApplication.translate("MainWindow", "Menu", None, QApplication.UnicodeUTF8))
        self.menuMenu.setObjectName("menuMenu")
        MainWindow.setMenuBar(self.menubar)
        self.actionSave_Game = QAction(MainWindow)
        self.actionSave_Game.setText(QApplication.translate("MainWindow", "Save Game", None, QApplication.UnicodeUTF8))
        self.actionSave_Game.setObjectName("actionSave_Game")
        self.actionCredits = QAction(MainWindow)
        self.actionCredits.setText(QApplication.translate("MainWindow", "Credits", None, QApplication.UnicodeUTF8))
        self.actionCredits.setObjectName("actionCredits")
        self.actionQuit = QAction(MainWindow)
        self.actionQuit.setText(QApplication.translate("MainWindow", "Quit", None, QApplication.UnicodeUTF8))
        self.actionQuit.setObjectName("actionQuit")
        self.actionSettings = QAction(MainWindow)
        self.actionSettings.setText(QApplication.translate("MainWindow", "Settings", None, QApplication.UnicodeUTF8))
        self.actionSettings.setObjectName("actionSettings")
        self.actionHelp = QAction(MainWindow)
        self.actionHelp.setText(QApplication.translate("MainWindow", "Help", None, QApplication.UnicodeUTF8))
        self.actionHelp.setObjectName("actionHelp")
        self.actionMain_Menu = QAction(MainWindow)
        self.actionMain_Menu.setText(QApplication.translate("MainWindow", "Main Menu", None, QApplication.UnicodeUTF8))
        self.actionMain_Menu.setObjectName("actionMain_Menu")
        self.menuMenu.addAction(self.actionSettings)
        self.menuMenu.addAction(self.actionHelp)
        self.menuMenu.addAction(self.actionSave_Game)
        self.menuMenu.addAction(self.actionCredits)
        self.menuMenu.addAction(self.actionMain_Menu)
        self.menuMenu.addAction(self.actionQuit)
        self.menubar.addAction(self.menuMenu.menuAction())
        

        self.retranslateUi(MainWindow)
        self.stackedWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        #These are the slots and signals to connect buttons to other functions
        self.location = 0
        QtCore.QObject.connect(self.actionQuit, QtCore.SIGNAL("triggered()"), MainWindow.close)
        QtCore.QObject.connect(self.quitButton, QtCore.SIGNAL("released()"), MainWindow.close)
        QtCore.QObject.connect(self.settingsButton, QtCore.SIGNAL("released()"), self.setSettings)
        QtCore.QObject.connect(self.actionSettings, QtCore.SIGNAL("triggered()"), self.setSettings)
        QtCore.QObject.connect(self.loadButton, QtCore.SIGNAL("released()"), self.load_file_dialog)
        QtCore.QObject.connect(self.actionSave_Game, QtCore.SIGNAL("triggered()"),self.save_file_dialog)
        QtCore.QObject.connect(self.doneButton, QtCore.SIGNAL("released()"), self.goBack)
        QtCore.QObject.connect(self.startButton, QtCore.SIGNAL("released()"), self.newGame)
        QtCore.QObject.connect(self.actionMain_Menu, QtCore.SIGNAL("triggered()"), self.setMain)
        QtCore.QObject.connect(self.actionHelp, QtCore.SIGNAL("triggered()"), self.setInstructions)
        QtCore.QObject.connect(self.instrButton, QtCore.SIGNAL("released()"), self.setInstructions)
        QtCore.QObject.connect(self.doneButton2, QtCore.SIGNAL("released()"), self.goBack)
        QtCore.QObject.connect(self.doneButton3, QtCore.SIGNAL("released()"), self.goBack)
        QtCore.QObject.connect(self.actionCredits, QtCore.SIGNAL("triggered()"), self.setCredits)
        self.latLongCheck.stateChanged.connect(self.latLong)
        self.colorCheck.stateChanged.connect(self.colorize)
        self.legendCheck.stateChanged.connect(self.legend)
        QtCore.QObject.connect(self.searchButton, QtCore.SIGNAL("released()"), self.doSearch)
        QtCore.QObject.connect(self.nextButton, QtCore.SIGNAL("released()"), self.storyButton)
        self.volumeSlider.sliderMoved.connect(self.setVol)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        pass

    #Custom signals are here        
    def setSettings(self):
        self.background.setPixmap(self.backgroundPixmapSettings)    
        self.stackedWidget.setCurrentIndex(1)
        
    def setInstructions(self):
        self.background.setPixmap(self.backgroundPixmapSettings)    
        self.stackedWidget.setCurrentIndex(3)
        
    def setCredits(self):
        self.background.setPixmap(self.backgroundPixmapSettings)       
        self.stackedWidget.setCurrentIndex(4)
        
    def goBack(self):
        self.stackedWidget.setCurrentIndex(self.location)
        if self.location == 0:
            self.background.setPixmap(self.backgroundPixmapMenu)
        else:
            None
            #Should be something here later.
        
    def load_file_dialog(self):
        fd = QFileDialog()
        self.filename = fd.getOpenFileName(None, "Load Saved Game", "saves", "MapMaster Save files (*.save)")
        if isfile(self.filename):
            self.loadSaved = True
            self.stackedWidget.setCurrentIndex(2)
            self.location = 2
            self.soundManager.switchSongs(self.location)
            
            
    def save_file_dialog(self):
        filename = QtGui.QFileDialog.getSaveFileName(None,"Save Game", "saves", "MapMaster Save files (*.save)")
        if filename == "":
            print "No file specified!"
        else:
           
            if ".save" in filename:
                self.fname = open(filename, "w")
            else:
                self.fname = open(filename + ".save",'w')
                
            score = str(self.data.score)
            numClues = str(len(self.data.clueStack))
            charX, charY = self.data.character.getCenter()
            whiteSpace = "       "
            toWriteList = whiteSpace + str(charX) + whiteSpace + str(charY) + whiteSpace + numClues + whiteSpace + score
            self.fname.write(toWriteList)     
            self.fname.close()
            
    
        
       
    def newGame(self):
        self.background.setPixmap(self.backgroundPixmapSettings)
        self.filename = None    
        self.stackedWidget.setCurrentIndex(5)
        self.location = 5
        
    def storyButton(self):
    
        self.stackedWidget.setCurrentIndex(2)
        self.location = 2
        self.soundManager.switchSongs(self.location)
       
    def setMain(self):
        self.save_file_dialog()
        self.background.setPixmap(self.backgroundPixmapMenu)
        self.stackedWidget.setCurrentIndex(0)
        self.location = 0
        self.soundManager.switchSongs(self.location)      
           
        
    def latLong(self):
        if self.latLongCheck.isChecked():
            print "Lat/long overlay on"
        else:
            print "Lat/long overlay off"
        self.data.overlays['latLongOverlay'].mViewObj.setVisible(self.latLongCheck.isChecked())
        
    def colorize(self):
        if self.colorCheck.isChecked():
            print "Color overlay on"
        else:
            print "Color overlay off"
        self.data.overlays['colorOverlay'].mViewObj.setVisible(self.colorCheck.isChecked())
        
    def legend(self):
        if self.legendCheck.isChecked():
            print "Legend overlay on"
        else:
            print "Legend overlay off"
        self.data.overlays['legendOverlay'].mViewObj.setVisible(self.legendCheck.isChecked())
    
    def setVol(self):
        self.soundManager.setVolume(self.volumeSlider.sliderPosition())
    
    def doSearch(self):
        searchLandmark(self.data)
Beispiel #6
0
class Gui(object):

    def __init__(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        
        #Set size of window and make it non-resizeable
        MainWindow.resize(818, 665)
        MainWindow.setFixedHeight(665)
        MainWindow.setFixedWidth(818)
        
        MainWindow.setWindowTitle("Map Master: Search for the Lost City")
        MainWindow.setWindowIcon(QIcon("icon_medium.ico"))

        #Set window backgrounds
        self.background = QLabel(MainWindow)
        
        
        self.backgroundPixmapMenu = QPixmap(normpath("images/gameMenu2.png"))
        self.backgroundPixmapSettings = QPixmap(normpath(
                                            "images/gameMenuSettings2.png"))
        self.background.setPixmap(self.backgroundPixmapMenu)       
        
        self.background.setGeometry(QtCore.QRect(0, 0, 818, 665))
        
        self.popupPixmap = QPixmap(normpath("images/popupBG.png"))
        
        font = QFont()
        if "linux" in platform:
            font.setFamily("Century Schoolbook L")
        else:
            font.setFamily("Century Schoolbook")
        
        
        #Stylesheet settings for labels and buttons
        self.fg = "QLabel {color:black}"
        self.fgb = "QPushButton {color:black}"

        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.stackedWidget = QStackedWidget(self.centralwidget)
        self.stackedWidget.setEnabled(True)
        self.stackedWidget.setObjectName("stackedWidget")
        
        #Main Menu page
        self.menuPage = QWidget()
        self.menuPage.setObjectName("menuPage")
        
        self.startButton = QPushButton(self.menuPage)
        self.startButton.setStyleSheet(self.fgb)
        self.startButton.setGeometry(QtCore.QRect(600, 200, 180, 60))
        self.startButton.setText(QApplication.translate("MainWindow", 
                                 "Start Game", None, QApplication.UnicodeUTF8))
        self.startButton.setObjectName("startButton")
        font.setPointSize(15)
        
        self.startButton.setFont(font)
        self.loadButton = QPushButton(self.menuPage)
        self.loadButton.setStyleSheet(self.fgb)
        self.loadButton.setGeometry(QtCore.QRect(600, 280, 180, 60))
        self.loadButton.setText(QApplication.translate("MainWindow", 
                                "Load Game", None, QApplication.UnicodeUTF8))
        self.loadButton.setObjectName("loadButton")
        self.loadButton.setFont(font)
        
        self.settingsButton = QPushButton(self.menuPage)
        self.settingsButton.setStyleSheet(self.fgb)
        self.settingsButton.setGeometry(QtCore.QRect(600, 440, 180, 60))
        self.settingsButton.setText(QApplication.translate("MainWindow", 
                                   "Settings", None, QApplication.UnicodeUTF8))
        self.settingsButton.setObjectName("settingsButton")
        self.settingsButton.setFont(font)
        
        self.quitButton = QPushButton(self.menuPage)
        self.quitButton.setStyleSheet(self.fgb)
        self.quitButton.setGeometry(QtCore.QRect(600, 520, 180, 60))
        self.quitButton.setText(QApplication.translate("MainWindow", 
                                "Quit", None, QApplication.UnicodeUTF8))
        self.quitButton.setObjectName("quitButton")
        self.quitButton.setFont(font)
        
        self.instrButton = QPushButton(self.menuPage)
        self.instrButton.setStyleSheet(self.fgb)
        self.instrButton.setGeometry(QtCore.QRect(600, 360, 180, 60))
        self.instrButton.setText(QApplication.translate("MainWindow", 
                               "Instructions", None, QApplication.UnicodeUTF8))
        self.instrButton.setObjectName("instrButton")
        self.instrButton.setFont(font)
        self.stackedWidget.addWidget(self.menuPage)
        
        #Settings page
        self.settingsPage = QWidget()
        self.settingsPage.setObjectName("settingsPage")
        self.volumeSlider = QSlider(self.settingsPage)
        self.volumeSlider.setGeometry(QtCore.QRect(200, 200, 400, 30))
        self.volumeSlider.setProperty("value", 50)
        self.volumeSlider.setOrientation(QtCore.Qt.Horizontal)
        self.volumeSlider.setObjectName("volumeSlider")
        self.soundLabel = QLabel(self.settingsPage)
        self.soundLabel.setGeometry(QtCore.QRect(340, 160, 120, 30))
        font.setPointSize(20)
        self.soundLabel.setFont(font)
        self.soundLabel.setStyleSheet(self.fg)
        self.soundLabel.setText(QApplication.translate("MainWindow", 
                                "Volume", None, QApplication.UnicodeUTF8))
        self.soundLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.soundLabel.setObjectName("soundLabel")
        
        #Quiet Sound Graphic
        self.quietGraphic = QLabel(self.settingsPage)
        self.quietGraphic.setPixmap(QPixmap(normpath(
                                    "images/speakerQuiet.png")))
        self.quietGraphic.setGeometry(QtCore.QRect(90, 180, 80, 80))
        self.quietGraphic.setObjectName("quietGraphic")
        
        #Loud Sound Graphic
        self.loudGraphic = QLabel(self.settingsPage)
        self.loudGraphic.setPixmap(QPixmap(normpath("images/speakerLoud.png")))
        self.loudGraphic.setEnabled(True)
        self.loudGraphic.setGeometry(QtCore.QRect(630, 180, 80, 80))
        self.loudGraphic.setObjectName("loudGraphic")
        
        self.settingsLabel = QLabel(self.settingsPage)
        self.settingsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font.setPointSize(36)
        self.settingsLabel.setFont(font)
        self.settingsLabel.setStyleSheet(self.fg)
        self.settingsLabel.setText(QApplication.translate("MainWindow", 
                                   "Settings", None, QApplication.UnicodeUTF8))
        self.settingsLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.settingsLabel.setObjectName("settingsLabel")
        self.doneButton = QPushButton(self.settingsPage)
        self.doneButton.setStyleSheet(self.fgb)
        self.doneButton.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton.setText(QApplication.translate("MainWindow", 
                                "Done", None, QApplication.UnicodeUTF8))
        self.doneButton.setObjectName("doneButton")
        font.setPointSize(15)
        self.doneButton.setFont(font)
        self.stackedWidget.addWidget(self.settingsPage)
        
        self.soundManager = Sounds(self.volumeSlider.sliderPosition())
        
        #Main Game page
        self.mainPage = QWidget()
        self.mainPage.setObjectName("mainPage")
        
        #Person View
        self.personView = ViewGraphics(self.mainPage)
        self.personView.setGeometry(QtCore.QRect(0, 0, 390, 500))
        self.personView.setObjectName("personView")
        
        #Map View
        self.mapView = ViewGraphics(self.mainPage)
        self.mapView.setGeometry(QtCore.QRect(410, 0, 390, 500))
        self.mapView.setObjectName("mapView")
        
        #ClueView
        self.clueView = QLabel(self.mainPage)
        self.clueView.setGeometry(QtCore.QRect(0, 510, 390, 91))
        self.clueView.setObjectName("clueView")
        font.setPointSize(20)
        self.clueView.setFont(font)
        self.clueView.setStyleSheet(self.fg)
        
        #Map Toggles
        self.latLongCheck = QCheckBox(self.mainPage)
        self.latLongCheck.setGeometry(QtCore.QRect(420, 510, 103, 41))
        self.latLongCheck.setText(QApplication.translate("MainWindow", 
                                  "Latitude/ \n"
                                  "Longitude", None, QApplication.UnicodeUTF8))
        self.latLongCheck.setObjectName("latLongCheck")
        font.setPointSize(12)
        self.latLongCheck.setFont(font)
        self.latLongCheck.setFocusPolicy(QtCore.Qt.NoFocus)

        self.colorCheck = QCheckBox(self.mainPage)
        self.colorCheck.setGeometry(QtCore.QRect(560, 510, 97, 41))
        self.colorCheck.setText(QApplication.translate("MainWindow", 
                                "Color\n"
                                "Coding", None, QApplication.UnicodeUTF8))
        self.colorCheck.setObjectName("colorCheck")
        self.colorCheck.setFont(font)
        self.colorCheck.setFocusPolicy(QtCore.Qt.NoFocus)
        
        self.legendCheck = QCheckBox(self.mainPage)
        self.legendCheck.setGeometry(QtCore.QRect(680, 520, 97, 22))
        self.legendCheck.setText(QApplication.translate("MainWindow", 
                                 "Legend", None, QApplication.UnicodeUTF8))
        self.legendCheck.setObjectName("legendCheck")
        self.legendCheck.setFocusPolicy(QtCore.Qt.NoFocus)
        
        font.setPointSize(12)
        self.legendCheck.setFont(font)
        self.searchButton = QPushButton(self.mainPage)
        self.searchButton.setStyleSheet(self.fgb)
        self.searchButton.setGeometry(QtCore.QRect(420, 560, 211, 55))
        self.searchButton.setText(QApplication.translate("MainWindow", 
                                  "Search", None, QApplication.UnicodeUTF8))
        self.searchButton.setObjectName("searchButton")
        font.setPointSize(15)
        self.searchButton.setFont(font)
        self.searchButton.setFocusPolicy(QtCore.Qt.NoFocus)
        
        #Score pieces
        self.scoreBox = QLabel(self.mainPage)
        self.scoreBox.setStyleSheet(self.fg)
        self.scoreBox.setGeometry(QtCore.QRect(720, 570, 71, 41))
        self.scoreBox.setObjectName("scoreBox")
        self.scoreBox.setText(QApplication.translate("MainWindow", 
                              "0", None, QApplication.UnicodeUTF8))
        self.scoreBox.setFont(font)
        self.scoreLabel = QLabel(self.mainPage)
        self.scoreLabel.setStyleSheet(self.fg)
        self.scoreLabel.setGeometry(QtCore.QRect(650, 580, 70, 17))
        self.scoreLabel.setText(QApplication.translate("MainWindow", 
                                "Score:", None, QApplication.UnicodeUTF8))
        self.scoreLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.scoreLabel.setObjectName("scoreLabel")
        self.scoreLabel.setFont(font)
        
        self.popup = ViewGraphics(self.mainPage)
        self.popup.setStyleSheet(
                "QGraphicsView {background:transparent;border-style:none}")
        self.popupImage = self.popup.scene.addPixmap(self.popupPixmap)
        self.popup.setGeometry(QtCore.QRect(25, 25, 750, 450))
        self.popup.setObjectName("popupLabel")
        font.setPointSize(25)
        self.popupText = self.popup.scene.addText("", font)
        self.textColor = QColor('black')
        self.popupText.setDefaultTextColor(self.textColor)
        self.popupText.setX(350)
        self.popupText.setY(225)
        self.popupImage.setOpacity(0)
        self.popupText.setOpacity(0)
        self.stackedWidget.addWidget(self.mainPage)
        
        #Help page
        self.helpPage = QWidget()
        self.helpPage.setObjectName("helpPage")
        self.HelpLabel = QLabel(self.helpPage)
        self.HelpLabel.setStyleSheet(self.fg)
        self.HelpLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font.setPointSize(36)
        self.HelpLabel.setFont(font)
        self.HelpLabel.setText(QApplication.translate("MainWindow", 
                               "Instructions", None, QApplication.UnicodeUTF8))
        self.HelpLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.HelpLabel.setObjectName("HelpLabel")
        self.wInstr = QLabel(self.helpPage)
        self.wInstr.setStyleSheet(self.fg)
        self.wInstr.setGeometry(QtCore.QRect(200, 150, 40, 30))
        font.setPointSize(20)
        self.wInstr.setFont(font)
        self.wInstr.setText(QApplication.translate("MainWindow", 
                            "W", None, QApplication.UnicodeUTF8))
        self.wInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.wInstr.setObjectName("wInstr")
        self.sInstr = QLabel(self.helpPage)
        self.sInstr.setStyleSheet(self.fg)
        self.sInstr.setGeometry(QtCore.QRect(200, 200, 40, 30))
        self.sInstr.setFont(font)
        self.sInstr.setText(QApplication.translate("MainWindow", 
                            "S", None, QApplication.UnicodeUTF8))
        self.sInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.sInstr.setObjectName("sInstr")
        self.aInstr = QLabel(self.helpPage)
        self.aInstr.setStyleSheet(self.fg)
        self.aInstr.setGeometry(QtCore.QRect(200, 250, 40, 30))
        self.aInstr.setFont(font)
        self.aInstr.setText(QApplication.translate("MainWindow", 
                            "A", None, QApplication.UnicodeUTF8))
        self.aInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.aInstr.setObjectName("aInstr")
        self.dInstr = QLabel(self.helpPage)
        self.dInstr.setStyleSheet(self.fg)
        self.dInstr.setGeometry(QtCore.QRect(200, 300, 40, 30))
        self.dInstr.setFont(font)
        self.dInstr.setText(QApplication.translate("MainWindow", 
                            "D", None, QApplication.UnicodeUTF8))
        self.dInstr.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr.setObjectName("dInstr")
        self.wInstr2 = QLabel(self.helpPage)
        self.wInstr2.setStyleSheet(self.fg)
        self.wInstr2.setGeometry(QtCore.QRect(400, 150, 180, 30))
        self.wInstr2.setFont(font)
        self.wInstr2.setText(QApplication.translate("MainWindow", 
                            "Move North", None, QApplication.UnicodeUTF8))
        self.wInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.wInstr2.setObjectName("wInstr2")
        self.sInstr2 = QLabel(self.helpPage)
        self.sInstr2.setStyleSheet(self.fg)
        self.sInstr2.setGeometry(QtCore.QRect(400, 200, 180, 30))
        self.sInstr2.setFont(font)
        self.sInstr2.setText(QApplication.translate("MainWindow", 
                            "Move South", None, QApplication.UnicodeUTF8))
        self.sInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.sInstr2.setObjectName("sInstr2")
        self.aInstr2 = QLabel(self.helpPage)
        self.aInstr2.setStyleSheet(self.fg)
        self.aInstr2.setGeometry(QtCore.QRect(400, 250, 180, 30))
        self.aInstr2.setFont(font)
        self.aInstr2.setText(QApplication.translate("MainWindow", 
                            "Move West", None, QApplication.UnicodeUTF8))
        self.aInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.aInstr2.setObjectName("aInstr2")
        self.dInstr2 = QLabel(self.helpPage)
        self.dInstr2.setStyleSheet(self.fg)
        self.dInstr2.setGeometry(QtCore.QRect(400, 300, 180, 30))
        self.dInstr2.setFont(font)
        self.dInstr2.setText(QApplication.translate("MainWindow", 
                            "Move East", None, QApplication.UnicodeUTF8))
        self.dInstr2.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr2.setObjectName("dInstr2")
        self.searchInstr = QPushButton(self.helpPage)
        self.searchInstr.setStyleSheet(self.fgb)
        self.searchInstr.setEnabled(True)
        self.searchInstr.setGeometry(QtCore.QRect(170, 350, 100, 30))
        self.searchInstr.setText(QApplication.translate("MainWindow", 
                                "Search", None, QApplication.UnicodeUTF8))
        self.searchInstr.setAutoDefault(False)
        self.searchInstr.setDefault(False)
        self.searchInstr.setFlat(False)
        self.searchInstr.setObjectName("searchInstr")
        font.setPointSize(15)
        self.searchInstr.setFont(font)
        self.dInstr2_2 = QLabel(self.helpPage)
        self.dInstr2_2.setStyleSheet(self.fg)
        self.dInstr2_2.setGeometry(QtCore.QRect(380, 350, 211, 30))
        font.setPointSize(20)
        self.dInstr2_2.setFont(font)
        self.dInstr2_2.setText(QApplication.translate("MainWindow", 
                           "Search for clues", None, QApplication.UnicodeUTF8))
        self.dInstr2_2.setAlignment(QtCore.Qt.AlignCenter)
        self.dInstr2_2.setObjectName("dInstr2_2")
        self.doneButton2 = QPushButton(self.helpPage)
        self.doneButton2.setStyleSheet(self.fgb)
        self.doneButton2.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton2.setText(QApplication.translate("MainWindow", 
                                 "Done", None, QApplication.UnicodeUTF8))
        self.doneButton2.setObjectName("doneButton2")
        font.setPointSize(15)
        self.doneButton2.setFont(font)
        self.stackedWidget.addWidget(self.helpPage)
        
        #Credits page
        self.creditsPage = QWidget()
        self.creditsPage.setObjectName("creditsPage")
        self.creditsLabel = QLabel(self.creditsPage)
        self.creditsLabel.setStyleSheet(self.fg)
        self.creditsLabel.setGeometry(QtCore.QRect(260, 30, 280, 60))
        font.setPointSize(36)
        self.creditsLabel.setFont(font)
        self.creditsLabel.setText(QApplication.translate("MainWindow", 
                                  "Credits", None, QApplication.UnicodeUTF8))
        self.creditsLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.creditsLabel.setObjectName("creditsLabel")
        self.credits = QLabel(self.creditsPage)
        self.credits.setStyleSheet(self.fg)
        self.credits.setGeometry(QtCore.QRect(180, 150, 500, 400))
        font.setPointSize(20)
        self.credits.setFont(font)
        self.credits.setText(QApplication.translate("MainWindow", 
        "Gary Lent\n"
        "Grant Stafford\n"
        "Jessie Liu\n"
        "Peter Andrien\n"
        "Nokia (Qt4 framework)\n"
        "Riverbank Computing Ltd (PyQt)\n"
        "Celestial Aeon Project", None, QApplication.UnicodeUTF8))
        self.credits.setAlignment(
                QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.credits.setObjectName("credits")
        self.doneButton3 = QPushButton(self.creditsPage)
        self.doneButton3.setStyleSheet(self.fgb)
        self.doneButton3.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.doneButton3.setText(QApplication.translate("MainWindow", 
                                "Done", None, QApplication.UnicodeUTF8))
        self.doneButton3.setObjectName("doneButton3")
        font.setPointSize(15)
        self.doneButton3.setFont(font)
        self.stackedWidget.addWidget(self.creditsPage)
        
        #Story page
        self.storyPage = QWidget()
        self.storyPage.setObjectName("storyPage")
        self.storyLabel = QLabel(self.storyPage)
        self.storyLabel.setStyleSheet(self.fg)
        self.storyLabel.setGeometry(QtCore.QRect(100, 50, 600, 400))
        font.setPointSize(25)
        self.storyLabel.setFont(font)
        self.storyLabel.setText(QApplication.translate("MainWindow", 
        "My name is Travis Sinclair.\n I'm a skilled cartographer.\n I recently"
        " lost my job, but stumbled\n on a clue that may change my life"
        " \nforever. I've set off on a quest - a quest\n to find a lost city. "
        "I've found a clue,\n and believe there may be more.\n Help me find "
        "the lost city.  ", None, QApplication.UnicodeUTF8))
        self.storyLabel.setAlignment(
                QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.storyLabel.setObjectName("storyLabel")
        self.nextButton = QPushButton(self.storyPage)
        self.nextButton.setGeometry(QtCore.QRect(600, 520, 161, 61))
        self.nextButton.setText(QApplication.translate("MainWindow", 
                                "Next", None, QApplication.UnicodeUTF8))
        self.nextButton.setObjectName("nextButton")
        self.nextButton.setStyleSheet(self.fgb)
        font.setPointSize(15)
        self.nextButton.setFont(font)
        self.stackedWidget.addWidget(self.storyPage)
        
        self.gridLayout.addWidget(self.stackedWidget, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        
        #Menu bar
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 818, 25))
        self.menubar.setObjectName("menubar")
        self.menuMenu = QMenu(self.menubar)
        self.menuMenu.setTitle(QApplication.translate("MainWindow", 
                               "Menu", None, QApplication.UnicodeUTF8))
        self.menuMenu.setObjectName("menuMenu")
        MainWindow.setMenuBar(self.menubar)
        self.actionSave_Game = QAction(MainWindow)
        self.actionSave_Game.setText(QApplication.translate("MainWindow", 
                                  "Save Game", None, QApplication.UnicodeUTF8))
        self.actionSave_Game.setObjectName("actionSave_Game")
        self.actionCredits = QAction(MainWindow)
        self.actionCredits.setText(QApplication.translate("MainWindow", 
                                   "Credits", None, QApplication.UnicodeUTF8))
        self.actionCredits.setObjectName("actionCredits")
        self.actionQuit = QAction(MainWindow)
        self.actionQuit.setText(QApplication.translate("MainWindow", 
                                "Quit", None, QApplication.UnicodeUTF8))
        self.actionQuit.setObjectName("actionQuit")
        self.actionSettings = QAction(MainWindow)
        self.actionSettings.setText(QApplication.translate("MainWindow", 
                                   "Settings", None, QApplication.UnicodeUTF8))
        self.actionSettings.setObjectName("actionSettings")
        self.actionHelp = QAction(MainWindow)
        self.actionHelp.setText(QApplication.translate("MainWindow", 
                                "Help", None, QApplication.UnicodeUTF8))
        self.actionHelp.setObjectName("actionHelp")
        self.actionMain_Menu = QAction(MainWindow)
        self.actionMain_Menu.setText(QApplication.translate("MainWindow", 
                                "Main Menu", None, QApplication.UnicodeUTF8))
        self.actionMain_Menu.setObjectName("actionMain_Menu")
        self.menuMenu.addAction(self.actionSettings)
        self.menuMenu.addAction(self.actionHelp)
        self.menuMenu.addAction(self.actionSave_Game)
        self.menuMenu.addAction(self.actionCredits)
        self.menuMenu.addAction(self.actionMain_Menu)
        self.menuMenu.addAction(self.actionQuit)
        self.menubar.addAction(self.menuMenu.menuAction())
        

        self.retranslateUi(MainWindow)
        self.stackedWidget.setCurrentIndex(0)

        self.stackIndex = 0

    def retranslateUi(self, MainWindow):
        pass
Beispiel #7
0
class History(QFrame):

    # =======================================================================
    def __init__(self, parent=None, _PARENT=None):

        # -------------------------------------------------------------------
        QFrame.__init__(self, parent)
        # -------------------------------------------------------------------
        self.PARENT = _PARENT
        self.CONF = _PARENT.CONF

        self.BOOK = {
            "bought": [],
            "sold": []
        }

        # -------------------------------------------------------------------
        self.setGeometry(3, 5, 975, 555)
        self.setStyleSheet(
            "QFrame{ font: 12px 'monospace'; color: #000; background-color: transparent; background-image: url('./data/imgs/TAB_History.png'); }"
        )

        self.PAIR_COMBO = QComboBox(self)
        self.PAIR_COMBO.setGeometry(86, 20, 108, 44)
        self.connect(self.PAIR_COMBO, SIGNAL('currentIndexChanged(int)'),
                     self.CREATE_LISTS)
        #self.PAIR_COMBO.setStyleSheet( "QComboBox{ font: 16px 'monospace'; background-color: #333; color: #FFF; border-style: solid; border-width: 1px; border-color: #000; border-radius: none; }" );
        self.PAIR_COMBO.setEditable(False)
        """
        #self.PAIR_COMBO.setItemIcon( 0, QIcon("./data/imgs/500.png") );
        print(self.PAIR_COMBO.__len__());
        #set at tooltip
        combo.setItemData(0,"a tooltip",Qt.ToolTipRole)
        # set the Font Color
        combo.setItemData(0,QColor("#FF333D"), Qt.BackgroundColorRole)
        #set the font
        combo.setItemData(0, QtGui.QFont('Verdana', bold=True), Qt.FontRole)
        """

        # -------------------------------------------------------------------
        list_style = "QListWidget{ font: 10px 'monospace'; color: #fff;  background-color: #000; border-style: none; background-image: url('./data/imgs/TAB_History_line.png'); }"
        # ./data/imgs/BookKeeping_line.png
        lable_style = "QLabel{ font: 10px 'monospace'; color: #fff;  background-color: transparent; border-style: none; background-image: url(''); }"
        # -------------------------------------------------------------------

        # Bought
        self.BOOKKEEPING_BOUGHT_WIDGET = QListWidget(self)
        self.BOOKKEEPING_BOUGHT_WIDGET.setGeometry(13, 144, 469, 400)
        self.BOOKKEEPING_BOUGHT_WIDGET.setStyleSheet(list_style)

        self.connect(
            self.BOOKKEEPING_BOUGHT_WIDGET, SIGNAL('itemSelectionChanged()'),
            lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("BOUGHT_WIDGET"))
        self.BOOKKEEPING_BOUGHT_WIDGET.itemClicked.connect(
            lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("BOUGHT_WIDGET"))

        self.BOUGHT_TTL_LABLE = QLabel("0.0", self)
        self.BOUGHT_TTL_LABLE.setGeometry(272, 406, 85, 17)
        #self.BOUGHT_TTL_LABLE.setEditable( False );
        self.BOUGHT_TTL_LABLE.setStyleSheet(lable_style)
        self.BOUGHT_TTL_LABLE.hide()
        self.BOUGHT_TTL = 0

        self.BOUGHT_TTL_PLUS_FEE_LABLE = QLabel("0.0", self)
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setGeometry(362, 406, 118, 17)
        #self.BOUGHT_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setStyleSheet(lable_style)
        self.BOUGHT_TTL_PLUS_FEE_LABLE.hide()
        self.BOUGHT_TTL_PLUS_FEE = 0

        # -------------------------------------------------------------------
        # Sold
        self.LAST_ACTIVE_WIDGET = None

        self.BOOKKEEPING_SOLD_WIDGET = QListWidget(self)
        self.BOOKKEEPING_SOLD_WIDGET.setGeometry(493, 144, 469, 400)
        self.BOOKKEEPING_SOLD_WIDGET.setStyleSheet(list_style)

        self.connect(self.BOOKKEEPING_SOLD_WIDGET,
                     SIGNAL('itemSelectionChanged()'),
                     lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SOLD_WIDGET"))
        self.BOOKKEEPING_SOLD_WIDGET.itemClicked.connect(
            lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SOLD_WIDGET"))

        self.SOLD_TTL_LABLE = QLabel("0.0", self)
        self.SOLD_TTL_LABLE.setGeometry(752, 406, 85, 17)
        #self.SOLD_TTL_LABLE.setEditable( False );
        self.SOLD_TTL_LABLE.setStyleSheet(lable_style)
        self.SOLD_TTL_LABLE.hide()
        self.SOLD_TTL = 0

        self.SOLD_TTL_PLUS_FEE_LABLE = QLabel("0.0", self)
        self.SOLD_TTL_PLUS_FEE_LABLE.setGeometry(842, 406, 118, 17)
        #self.SOLD_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.SOLD_TTL_PLUS_FEE_LABLE.setStyleSheet(lable_style)
        self.SOLD_TTL_PLUS_FEE_LABLE.hide()
        self.SOLD_TTL_PLUS_FEE = 0

        # -------------------------------------------------------------------
        """
        self.DATA_TO_SEND                   = None;

        self.SEND_ID_LABLE                  = QLabel("n/a", self);
        self.SEND_ID_LABLE.setGeometry( 18, 467, 43, 17 );
        self.SEND_ID_LABLE.setStyleSheet( lable_style );

        self.SEND_AMOUNT_LABLE              = QLabel("n/a", self);
        self.SEND_AMOUNT_LABLE.setGeometry( 66, 467, 85, 17 );
        self.SEND_AMOUNT_LABLE.setStyleSheet( lable_style );

        self.SEND_AT_PRICE_LABLE            = QLabel("n/a", self);
        self.SEND_AT_PRICE_LABLE.setGeometry( 156, 467, 43, 17 );
        self.SEND_AT_PRICE_LABLE.setStyleSheet( lable_style );

        self.SEND_VALUES_BTN                = QPushButton("", self); 
        self.SEND_VALUES_BTN.setGeometry( 60, 502, 131, 33 );
        self.SEND_VALUES_BTN.setStyleSheet( "QPushButton{ background-color: transparent; border-style: none; }" ); 
        self.connect( self.SEND_VALUES_BTN, SIGNAL('clicked()'), lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SEND_VALUES") );
        """

        # -------------------------------------------------------------------
        self._i_ = "|"
        # List delimiter

        # -------------------------------------------------------------------
        self.ONLY_FILLED_CHECKBOX = QCheckBox("", self)
        self.ONLY_FILLED_CHECKBOX.setGeometry(647, 444, 17, 17)
        self.ONLY_FILLED_CHECKBOX.setCheckState(Qt.Checked)
        #self.ONLY_FILLED_CHECKBOX.setEnabled(False);
        self.connect(self.ONLY_FILLED_CHECKBOX, SIGNAL('stateChanged(int)'),
                     lambda: self.CHANGE_VALUES("only_filled"))
        self.ONLY_FILLED_CHECKBOX.hide()

        self.CALCULATE_ONLY_FILLED = True
        # -------------------------------------------------------------------
        self.INIT()
        # -------------------------------------------------------------------

    # =======================================================================
    def INIT(self):

        # -------------------------------------------------------------------
        try:

            self.CREATE_PAIRS_SELECTOR()
            self.CREATE_LISTS()

        except Exception as _exception:
            print("-----------------------------------------------------")
            print(_exception)
        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_LISTS(self):

        # -------------------------------------------------------------------
        CURR_PAIR = str(self.PAIR_COMBO.currentText()).lower()

        # -------------------------------------------------------------------
        self.BOOK = {
            "bought": [],
            "sold": []
        }

        self.BOUGHT_TTL = 0
        self.BOUGHT_TTL_PLUS_FEE = 0

        self.SOLD_TTL = 0
        self.SOLD_TTL_PLUS_FEE = 0

        # -------------------------------------------------------------------
        # Bought List
        # id, order_id, unix_time, action, filled, amount, at_price, fee, ttl, grand_ttl

        #self.PARENT.DB.EXEC( "HISTORY_DB", "DELETE FROM "+CURR_PAIR+" WHERE id>7" );

        DATA = self.PARENT.DB.FETCH("HISTORY_DB",
                                    "SELECT * FROM " + CURR_PAIR +
                                    " WHERE action='bought' ORDER BY id DESC",
                                    ALL=True)
        self.BOOKKEEPING_BOUGHT_WIDGET.clear()

        for data in DATA:

            # ---------------------------------------------------------------
            # In-Memory DATA

            self.BOOK[data[3]].append({
                "id": data[0],
                "order_id": data[1],
                "unix_time": data[2],
                "action": data[3],
                "filled": data[4],
                "amount": data[5],
                "at_price": data[6],
                "fee": data[7],
                "ttl": data[8],
                "grand_ttl": data[9]
            })

            if self.CALCULATE_ONLY_FILLED:
                if data[4] == 1:
                    self.BOUGHT_TTL += data[8]
                    self.BOUGHT_TTL_PLUS_FEE += data[9]

            else:
                self.BOUGHT_TTL += data[8]
                self.BOUGHT_TTL_PLUS_FEE += data[9]

            # ---------------------------------------------------------------
            # Formatinf data to Display in BookKeeping Wodget

            item = ""

            item += "DEL{:6} DEL".format(str(data[0]))
            # id
            #item += "{:11} DEL".format( data[1] ); # order_id
            #item += "{:11} DEL".format( data[2] ); # unix_time
            #item += "{:11} DEL".format( data[3] ); # action
            #item += "{:11} DEL".format( data[4] ); # filed
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[5])).strip())
            # Amount
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[6])).strip())
            # at_price
            #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[8])).strip())
            # ttl
            item += "{:13}".format(str("{:10,.6f}".format(data[9])).strip())
            # grand_ttl

            #self.BOOKKEEPING_BOUGHT_WIDGET.addItem( item.replace("DEL", self._i_) );
            newItem = QListWidgetItem(
                QIcon("./data/imgs/icon_filled_status_" + str(data[4]) +
                      ".png"), item.replace("DEL", self._i_),
                self.BOOKKEEPING_BOUGHT_WIDGET, 0)
            newItemToolTip = "Order ID: #" + str(
                data[1]) + " Created: " + time.ctime(int(data[2]))

            newItem.setToolTip(newItemToolTip)

            # ---------------------------------------------------------------
        # / for
        # -------------------------------------------------------------------
        self.BOUGHT_TTL_LABLE.setText(
            str("{:10,.6f}".format(self.BOUGHT_TTL).strip()))
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setText(
            str("{:10,.6f}".format(self.BOUGHT_TTL_PLUS_FEE).strip()))

        # -------------------------------------------------------------------
        # Sold List
        # id, order_id, unix_time, action, filled, amount, at_price, fee, ttl, grand_ttl

        DATA = self.PARENT.DB.FETCH("HISTORY_DB",
                                    "SELECT * FROM " + CURR_PAIR +
                                    " WHERE action='sold' ORDER BY id DESC",
                                    ALL=True)
        self.BOOKKEEPING_SOLD_WIDGET.clear()

        for data in DATA:

            # ---------------------------------------------------------------
            # In-Memory DATA

            self.BOOK[data[3]].append({
                "id": data[0],
                "order_id": data[1],
                "unix_time": data[2],
                "action": data[3],
                "filled": data[4],
                "amount": data[5],
                "at_price": data[6],
                "fee": data[7],
                "ttl": data[8],
                "grand_ttl": data[9]
            })

            if self.CALCULATE_ONLY_FILLED:
                if data[4] == 1:
                    self.SOLD_TTL += data[8]
                    self.SOLD_TTL_PLUS_FEE += data[9]

            else:
                self.SOLD_TTL += data[8]
                self.SOLD_TTL_PLUS_FEE += data[9]

            # ---------------------------------------------------------------
            # Formatinf data to Display in BookKeeping Wodget

            item = ""

            item += "DEL{:6} DEL".format(str(data[0]))
            # id
            #item += "{:11} DEL".format( data[1] ); # order_id
            #item += "{:11} DEL".format( data[2] ); # unix_time
            #item += "{:11} DEL".format( data[3] ); # action
            #item += "{:11} DEL".format( data[4] ); # filed
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[5])).strip())
            # Amount
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[6])).strip())
            # at_price
            #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
            item += "{:13} DEL".format(
                str("{:10,.6f}".format(data[8])).strip())
            # ttl
            item += "{:13}".format(str("{:10,.6f}".format(data[9])).strip())
            # grand_ttl

            #self.BOOKKEEPING_SOLD_WIDGET.addItem( item.replace("DEL", self._i_) );
            newItem = QListWidgetItem(
                QIcon("./data/imgs/icon_filled_status_" + str(data[4]) +
                      ".png"), item.replace("DEL", self._i_),
                self.BOOKKEEPING_SOLD_WIDGET, 0)

            newItemToolTip = "Order ID: #" + str(
                data[1]) + " Created: " + time.ctime(int(data[2]))

            newItem.setToolTip(newItemToolTip)
            # ---------------------------------------------------------------
        # / for
        # -------------------------------------------------------------------
        self.SOLD_TTL_LABLE.setText(
            str("{:10,.6f}".format(self.SOLD_TTL).strip()))
        self.SOLD_TTL_PLUS_FEE_LABLE.setText(
            str("{:10,.6f}".format(self.SOLD_TTL_PLUS_FEE).strip()))

        # -------------------------------------------------------------------

    # =======================================================================
    def CHANGE_VALUES(self, _this):

        # -------------------------------------------------------------------
        if _this == "only_filled":
            if self.ONLY_FILLED_CHECKBOX.isChecked():
                self.CALCULATE_ONLY_FILLED = True
            else:
                self.CALCULATE_ONLY_FILLED = False

        # -------------------------------------------------------------------
        self.CREATE_LISTS()
        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_PAIRS_SELECTOR(self, ALL=False):

        # -------------------------------------------------------------------
        if not ALL:
            for PAIR in self.CONF["API"]["PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper())

        else:
            for PAIR in self.CONF["API"]["ALL_PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper())

        for i in xrange(0, self.PAIR_COMBO.__len__()):

            self.PAIR_COMBO.setItemData(i, QColor("#333"), Qt.BackgroundRole)
            self.PAIR_COMBO.setItemData(i, QColor("#fff"), Qt.ForegroundRole)
            #self.PAIR_COMBO.setItemData( i, QFont('monospace', 16, -1, False), Qt.FontRole);
        # -------------------------------------------------------------------

    # =======================================================================
    def SEND_VALUES_TO_TRADE_TERMINAL(self, _action):

        # -------------------------------------------------------------------
        if _action == "BOUGHT_WIDGET":

            self.LAST_ACTIVE_WIDGET = "BOUGHT_WIDGET"
            self.DATA_TO_SEND = str(self.BOOKKEEPING_BOUGHT_WIDGET.currentItem(
            ).text()).strip().split("|")

            #self.SEND_ID_LABLE.setFocus();

        elif _action == "SOLD_WIDGET":

            self.LAST_ACTIVE_WIDGET = "SOLD_WIDGET"
            self.DATA_TO_SEND = str(self.BOOKKEEPING_SOLD_WIDGET.currentItem().
                                    text()).strip().split("|")

            #self.SEND_ID_LABLE.setFocus();

        elif _action == "SEND_VALUES":

            if self.LAST_ACTIVE_WIDGET is not None:

                self.PARENT.GUI.USER_SELL_AMOUNT.setText(
                    self.DATA_TO_SEND[2].strip())
                self.PARENT.GUI.USER_SELL_AT_PRICE.setText(
                    self.DATA_TO_SEND[3].strip())

                self.PARENT.GUI.USER_BUY_AMOUNT.setText(
                    self.DATA_TO_SEND[2].strip())
                self.PARENT.GUI.USER_BUY_AT_PRICE.setText(
                    self.DATA_TO_SEND[3].strip())

                self.LAST_ACTIVE_WIDGET = None
                self.DATA_TO_SEND = None

                # Show Tradeer Tab
                self.PARENT.GUI.MAIN_TABS.setCurrentIndex(0)

                # Clear Lables
                self.SEND_ID_LABLE.setText("n/a")
                self.SEND_AMOUNT_LABLE.setText("n/a")
                self.SEND_AT_PRICE_LABLE.setText("n/a")

            else:

                self.PARENT.GUI.SHOW_QMESSAGE(
                    "info",
                    " Select first item which one you would like<br/> send to the Trade-Terminal !"
                )
                return

        # -------------------------------------------------------------------
        if self.DATA_TO_SEND is not None:

            self.SEND_ID_LABLE.setText(self.DATA_TO_SEND[1])
            self.SEND_AMOUNT_LABLE.setText(self.DATA_TO_SEND[2])
            self.SEND_AT_PRICE_LABLE.setText(self.DATA_TO_SEND[3])

        # -------------------------------------------------------------------

    # =======================================================================
    def DELETE_ORDER(self, _order_id, _pair, _type):

        # ------------------------------------------------------------------
        self.PARENT.DB.EXEC(
            "HISTORY_DB",
            "DELETE FROM " + _pair + " WHERE order_id=" + str(_order_id))
class BaseSectionWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.resize(400,80)

        self.sectionNameEdit = QLineEdit(self)
        self.sectionNameEdit.setGeometry(QRect(0,5,110,30))
        self.sectionNameEdit.setPlaceholderText("Section name")
        self.sectionNameEdit.setToolTip("Name of new section")

        self.sizeEdit = QDoubleSpinBox(self)
        self.sizeEdit.setGeometry(QRect(115,5,65,30))
        self.sizeEdit.setMaximum(100.0)
        self.sizeEdit.setToolTip("Size of section in percent")

        self.colorLabel = ColorChooser(self)
        self.colorLabel.setGeometry(QRect(185,8,25,25))

        self.displayedNameCheckBox = QCheckBox(self)
        self.displayedNameCheckBox.setGeometry(215, 5, 185, 30)
        self.displayedNameCheckBox.setText("Change displayed name")
        self.displayedNameCheckBox.setStyleSheet("font-size:11px;")

        self.displayedNameEdit = QLineEdit(self)
        self.displayedNameEdit.setGeometry(QRect(235,5,120,30))
        self.displayedNameEdit.setPlaceholderText("Displayed name")
        self.displayedNameEdit.setToolTip("Displayed name of new section")
        self.displayedNameEdit.setVisible(False)

        self.removeButton = QPushButton(self)
        self.removeButton.setGeometry(QRect(385,5,35,30))
        self.removeButton.setToolTip("Remove section")
        pixmap = QPixmap("./removeIcon.png")
        buttonIcon = QIcon(pixmap)
        self.removeButton.setIcon(buttonIcon)
        self.removeButton.setIconSize(QSize(25,25))

        self.connect(self.displayedNameCheckBox, QtCore.SIGNAL("clicked()"), self.changeDisplayedName)
        self.connect(self.removeButton, QtCore.SIGNAL("clicked()"), QtCore.SIGNAL("remove()"))
        self.connect(self.sizeEdit, QtCore.SIGNAL("valueChanged(double)"), self.changeSizeValue)

    def changeSizeValue(self):
        self.emit(QtCore.SIGNAL("sizeValueChanged(QWidget*)"), self)

    def changeDisplayedName(self):
        if self.displayedNameCheckBox.isChecked():
            self.displayedNameEdit.setVisible(True)
            self.displayedNameCheckBox.setText("")
        else:
            self.displayedNameEdit.setVisible((False))
            self.displayedNameCheckBox.setText("Change displayed name")

    def getName(self):
        return self.sectionNameEdit.text()

    def setSize(self, size):
        self.sizeEdit.setValue(size)

    def getSize(self):
        return self.sizeEdit.value()

    def getSectionData(self):
        name = self.sectionNameEdit.text()
        size = self.sizeEdit.text()
        color = self.colorLabel.getSelectedColor()
        displayedNameFlag = self.displayedNameCheckBox.isChecked()
        displayedName = self.displayedNameEdit.text()
        return [name, size, color, displayedNameFlag, displayedName]
Beispiel #9
0
class EncryptDialog(QDialog):
    def __init__(self):
        self.techniquesClass = {
            'caesar cipher': caesarCipher,
            'mono alphabetic cipher': monoAlphabeticCipher,
            'vigenere cipher': vigenereCipher,
            'vernan cipher': vernanCipher,
            'one time pad': oneTimePad
        }

        self.rowsview = []
        self.filesview = []
        self.techniques = []

        QDialog.__init__(self)
        self.setWindowTitle("CryptoSystems")
        self.resize(1024, 600)
        self.setMinimumSize(QSize(1024, 600))
        self.setMaximumSize(QSize(1024, 600))

        self.checkBox_2 = QCheckBox(self)
        self.checkBox_2.setGeometry(QRect(620, 10, 130, 20))
        self.checkBox_2.setText('Select All')
        self.checkBox_2.clicked.connect(self.__selectAllFiles)

        self.treeView = QTreeView(self)
        self.treeView.setGeometry(QRect(10, 10, 230, 580))
        self.treeView.setObjectName("treeView")

        self.fileSystemModel = QFileSystemModel(self.treeView)
        self.fileSystemModel.setReadOnly(False)

        self.fileSystemModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
        root = self.fileSystemModel.setRootPath("/")
        self.treeView.setModel(self.fileSystemModel)
        self.treeView.setRootIndex(root)
        self.treeView.hideColumn(1)
        self.treeView.hideColumn(2)
        self.treeView.hideColumn(3)
        self.treeView.clicked.connect(self.__eventDirectoryChanged)

        self.mygroupbox = QGroupBox(self)
        self.mygroupbox.setGeometry(QRect(0, 0, 1000, 1000))
        self.myform = QFormLayout()
        for j in list(range(100)):
            horizontalLayout = QHBoxLayout()
            self.myform.addRow(horizontalLayout)
            self.rowsview.append(horizontalLayout)

        self.mygroupbox.setLayout(self.myform)
        scroll = QScrollArea(self)
        scroll.setWidget(self.mygroupbox)
        scroll.setWidgetResizable(True)
        scroll.setGeometry(QRect(250, 30, 500, 580))
        scroll.setWidgetResizable(True)

        self.label_4 = QLabel(self)
        self.label_4.setGeometry(QRect(780, 30, 31, 16))
        self.label_4.setPixmap(QPixmap("images/key.png"))
        self.label_4.setScaledContents(True)

        self.lineEdit = QLineEdit(self)
        self.lineEdit.setGeometry(QRect(820, 30, 180, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit.setPlaceholderText(_fromUtf8('write your password'))
        self.lineEdit.setEchoMode(QLineEdit.Password)

        self.techniquesGroup = QGroupBox(self)
        self.tecniquesform = QFormLayout()
        self.techniquesGroup.setLayout(self.tecniquesform)

        self.techniquesScroll = QScrollArea(self)
        self.techniquesScroll.setGeometry(QRect(770, 100, 230, 300))
        self.techniquesScroll.setWidget(self.techniquesGroup)
        self.techniquesScroll.setWidgetResizable(True)

        self.rowsTechiques = []
        for i in list(range(8)):
            horizontalLayout = QHBoxLayout()
            self.tecniquesform.addRow(horizontalLayout)
            self.rowsTechiques.append(horizontalLayout)

        techniquesCombo = QComboBox()
        techniquesCombo.setGeometry(QRect(10, 50, 171, 22))
        techniquesCombo.addItems(self.techniquesClass.keys())
        self.techniques.append(techniquesCombo)
        self.rowsTechiques[0].addWidget(techniquesCombo)
        self.techniquesNumber = 1

        self.addTechnique = QPushButton()
        self.addTechnique.setGeometry(QRect(90, 90, 31, 21))
        self.addTechnique.setFixedSize(31, 21)
        self.addTechnique.setText('+')
        self.connect(self.addTechnique, SIGNAL("clicked()"),
                     self.__eventAddTechnique)
        self.rowsTechiques[len(self.rowsTechiques) - 1].addWidget(
            self.addTechnique)

        self.okButton = QPushButton(self)
        self.okButton.setGeometry(QRect(920, 560, 80, 20))
        self.okButton.setText('Start...')
        self.connect(self.okButton, SIGNAL("clicked()"),
                     self.__eventInitEncryption)

    def __eventAddTechnique(self):
        techniquesCombo = QComboBox()
        techniquesCombo.setGeometry(QRect(10, 50, 171, 22))
        techniquesCombo.addItems(self.techniquesClass.keys())
        self.techniques.append(techniquesCombo)
        self.rowsTechiques[self.techniquesNumber].addWidget(techniquesCombo)
        self.techniquesNumber = self.techniquesNumber + 1
        if ((len(self.rowsTechiques) - 1) == self.techniquesNumber):
            self.addTechnique.setEnabled(False)

    def __eventDirectoryChanged(self):
        index = self.treeView.currentIndex()
        self.__changeDirectory(self.fileSystemModel.filePath(index))

    def __changeDirectory(self, path):
        for c in self.filesview:
            c.setParent(None)
            c.deleteLater()
        self.filesview = []
        self.checkBox_2.setChecked(False)

        self.progressBars = {}
        for f in self.__getFiles(path):
            try:
                group = QGroupBox(f, self)
                group.setGeometry(QRect(20, 20, 100, 150))
                group.setCheckable(True)
                group.setChecked(False)
                group.setFixedSize(100, 150)
                group.setFlat(True)
                group.setToolTip(f)

                label = QLabel(group)
                label.setScaledContents(True)
                label.setGeometry(QRect(5, 25, 90, 90))
                label.setToolTip(f)

                progressBar = QProgressBar(group)
                progressBar.setGeometry(QRect(0, 70, 111, 10))
                progressBar.setProperty("value", 0)
                progressBar.setTextVisible(False)
                progressBar.setToolTip('0%')
                progressBar.setVisible(False)
                self.progressBars[f] = progressBar

                self.filesview.append(group)
                from os.path import isfile
                if isfile(path + '/' + f):
                    ext = f.split('.')[-1]
                    if isfile('icons/' + ext.lower() + '.png'):
                        label.setPixmap(
                            QPixmap('icons/' + ext.lower() + '.png'))
                    else:
                        label.setPixmap(QPixmap('icons/default.png'))
                else:
                    label.setPixmap(QPixmap('icons/folder.png'))
                self.connect(group, SIGNAL("clicked()"), self.__deselectFile)
            except ValueError:
                pass

        i = 0
        for x in list(range(len(self.filesview))):
            if (x % 4) == 0:
                i = i + 1
            self.rowsview[i].addWidget(self.filesview[x])

    def __selectAllFiles(self):
        for o in self.filesview:
            o.setChecked(self.checkBox_2.isChecked())

    def __deselectFile(self):
        #print 'deselect'
        self.checkBox_2.setChecked(False)

    def __arrozconpollo(self):
        self.__obtainSelectedFIles()

    def __obtainSelectedFIles(self):
        files = []
        for o in self.filesview:
            if o.isChecked():
                files.append(str(o.title()))
                self.progressBars[str(o.title())].setVisible(True)
        return files

    def __getFiles(self, path):
        from os import listdir
        from os.path import isfile

        f = []

        for base in listdir(path):
            try:
                if isfile(path + '/' + base):
                    f.append(base)
            except ValueError:
                pass
        f.sort()
        return f

    def __eventInitEncryption(self):
        if len(self.__obtainSelectedFIles()) == 0:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText("You must specify the files you want to encrypt")
            msg.setWindowTitle("CryptoSystems")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
            return

        if str(self.lineEdit.text()).strip() == '':
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText("You must specify a key")
            msg.setWindowTitle("CryptoSystems")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
            return

        self.okButton.setEnabled(False)
        self.techniquesGroup.setEnabled(False)
        self.lineEdit.setEnabled(False)

        index = self.treeView.currentIndex()

        path = self.fileSystemModel.filePath(index)
        selectedFiles = self.__obtainSelectedFIles()

        from os.path import getsize
        blockSize = 4096

        from hashlib import md5
        Hash = md5()
        Hash.update(str(self.lineEdit.text()))
        key = Hash.hexdigest()

        for f in selectedFiles:

            f_in = open(path + '/' + f, 'rb')
            f_out = open(
                path + '/' + reduceMd5(checksum(path + '/' + f)) + '.cry',
                'wb')

            f_out.write('CRYOGENESIS' + unhexlify('00') + 'ARCHIVE' +
                        unhexlify('01'))

            header_list = ''
            techniquesObjects = []
            for t in self.techniques:
                header_list = header_list + t.currentText() + ':'
                techniquesObjects.append(self.techniquesClass[str(
                    t.currentText())](key))

            file_header = str('header|' + str(f_in.name.split('/')[-1]) + '|' +
                              str(header_list) + '|' +
                              str(checksum(path + '/' + f)))

            aes = AES(key)
            f_out.write(aes.encrypt(file_header))
            f_out.write(unhexlify('02'))

            in_size = getsize(path + '/' + f)
            in_progress = 0.0

            block = f_in.read(blockSize)
            while (block):
                block_c = block
                for t in techniquesObjects:
                    block_c = t.encrypt(block_c)
                f_out.write(block_c)
                in_progress = in_progress + blockSize

                progress = (in_progress / in_size) * 100
                #print progress
                self.progressBars[str(f)].setProperty("value", int(progress))
                self.progressBars[str(f)].setToolTip(str(progress) + '%')
                block = f_in.read(blockSize)

            f_in.close()
            f_out.close()

        msg = QMessageBox()

        msg.setIcon(QMessageBox.Information)

        msg.setText("Encryption has successfully concluded")
        msg.setWindowTitle("CryptoSystems")
        msg.setStandardButtons(QMessageBox.Ok)
        msg.exec_()

        self.hide()
Beispiel #10
0
class DecryptDialog(QDialog):
    def __init__(self):
        self.techniquesClass = {
            'caesar cipher': caesarCipher,
            'mono alphabetic cipher': monoAlphabeticCipher,
            'vigenere cipher': vigenereCipher,
            'vernan cipher': vernanCipher,
            'one time pad': oneTimePad
        }

        self.rowsview = []
        self.filesview = []
        #self.techniques = []

        QDialog.__init__(self)
        self.setWindowTitle("Desencriptador de Cryogenesis Systems.")
        self.resize(1024, 600)
        self.setMinimumSize(QSize(1024, 600))
        self.setMaximumSize(QSize(1024, 600))

        self.checkBox_2 = QCheckBox(self)
        self.checkBox_2.setGeometry(QRect(620, 10, 130, 20))
        self.checkBox_2.setText('seleccionar todos')
        self.checkBox_2.clicked.connect(self.__selectAllFiles)

        self.treeView = QTreeView(self)
        self.treeView.setGeometry(QRect(10, 10, 230, 580))
        self.treeView.setObjectName("treeView")

        self.fileSystemModel = QFileSystemModel(self.treeView)
        self.fileSystemModel.setReadOnly(False)

        self.fileSystemModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
        root = self.fileSystemModel.setRootPath("/")
        self.treeView.setModel(self.fileSystemModel)
        self.treeView.setRootIndex(root)
        self.treeView.hideColumn(1)
        self.treeView.hideColumn(2)
        self.treeView.hideColumn(3)
        self.treeView.clicked.connect(self.__eventDirectoryChanged)

        self.mygroupbox = QGroupBox(self)
        self.mygroupbox.setGeometry(QRect(0, 0, 1000, 1000))
        self.myform = QFormLayout()
        for j in list(range(100)):
            horizontalLayout = QHBoxLayout()
            self.myform.addRow(horizontalLayout)
            self.rowsview.append(horizontalLayout)

        self.mygroupbox.setLayout(self.myform)
        scroll = QScrollArea(self)
        scroll.setWidget(self.mygroupbox)
        scroll.setWidgetResizable(True)
        scroll.setGeometry(QRect(250, 30, 500, 580))
        scroll.setWidgetResizable(True)

        self.label_4 = QLabel(self)
        self.label_4.setGeometry(QRect(780, 30, 31, 16))
        self.label_4.setPixmap(QPixmap("images/key.png"))
        self.label_4.setScaledContents(True)

        self.lineEdit = QLineEdit(self)
        self.lineEdit.setGeometry(QRect(820, 30, 180, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.lineEdit.setPlaceholderText(_fromUtf8('escriba su contraseña'))
        self.lineEdit.setEchoMode(QLineEdit.Password)

        self.okButton = QPushButton(self)
        self.okButton.setGeometry(QRect(920, 560, 80, 20))
        self.okButton.setText('Iniciar...')
        self.connect(self.okButton, SIGNAL("clicked()"),
                     self.__eventInitDecryption)

    def __eventDirectoryChanged(self):
        index = self.treeView.currentIndex()
        self.__changeDirectory(self.fileSystemModel.filePath(index))

    def __changeDirectory(self, path):
        for c in self.filesview:
            c.setParent(None)
            c.deleteLater()
        self.filesview = []
        self.checkBox_2.setChecked(False)

        self.progressBars = {}
        for f in self.__getFiles(path):
            try:
                group = QGroupBox(f, self)
                group.setGeometry(QRect(20, 20, 100, 150))
                group.setCheckable(True)
                group.setChecked(False)
                group.setFixedSize(100, 150)
                group.setFlat(True)
                group.setToolTip(f)

                label = QLabel(group)
                label.setScaledContents(True)
                label.setGeometry(QRect(5, 25, 90, 90))
                label.setToolTip(f)

                progressBar = QProgressBar(group)
                progressBar.setGeometry(QRect(0, 70, 111, 10))
                progressBar.setProperty("value", 0)
                progressBar.setTextVisible(False)
                progressBar.setToolTip('0%')
                progressBar.setVisible(False)
                self.progressBars[f] = progressBar

                self.filesview.append(group)
                from os.path import isfile
                if isfile(path + '/' + f):
                    ext = f.split('.')[-1]
                    if isfile('icons/' + ext.lower() + '.png'):
                        label.setPixmap(
                            QPixmap('icons/' + ext.lower() + '.png'))
                    else:
                        label.setPixmap(QPixmap('icons/default.png'))
                else:
                    label.setPixmap(QPixmap('icons/folder.png'))
                self.connect(group, SIGNAL("clicked()"), self.__deselectFile)
            except ValueError:
                pass

        i = 0
        for x in list(range(len(self.filesview))):
            if (x % 4) == 0:
                i = i + 1
            self.rowsview[i].addWidget(self.filesview[x])

    def __selectAllFiles(self):
        for o in self.filesview:
            o.setChecked(self.checkBox_2.isChecked())

    def __deselectFile(self):
        #print 'deselect'
        self.checkBox_2.setChecked(False)

    def __arrozconpollo(self):
        self.__obtainSelectedFIles()

    def __obtainSelectedFIles(self):
        files = []
        for o in self.filesview:
            if o.isChecked():
                files.append(str(o.title()))
                self.progressBars[str(o.title())].setVisible(True)
        return files

    def __getFiles(self, path):
        from os import listdir
        from os.path import isfile

        f = []

        for base in listdir(path):
            try:
                if isfile(path + '/' + base) and base.split('.')[-1] == 'cry':
                    f.append(base)
            except ValueError:
                pass
        f.sort()
        return f

    def __eventInitDecryption(self):
        if len(self.__obtainSelectedFIles()) == 0:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText(
                "Debes especificar los archivos que quieres desencriptar")
            msg.setWindowTitle("Cryosystems")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
            return

        if str(self.lineEdit.text()).strip() == '':
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Critical)
            msg.setText("Debes especificar una clave")
            msg.setWindowTitle("Cryosystems")
            msg.setStandardButtons(QMessageBox.Ok)
            msg.exec_()
            return

        self.okButton.setEnabled(False)
        self.lineEdit.setEnabled(False)

        index = self.treeView.currentIndex()

        path = self.fileSystemModel.filePath(index)
        selectedFiles = self.__obtainSelectedFIles()

        from hashlib import md5
        Hash = md5()
        Hash.update(str(self.lineEdit.text()))
        key = Hash.hexdigest()

        errors = 0

        from os.path import getsize
        blockSize = 4096
        for f in selectedFiles:

            f_in = open(path + '/' + f, 'rb')
            print path + '/' + f

            header = ''
            if (f_in.read(20) == ('CRYOGENESIS' + unhexlify('00') + 'ARCHIVE' +
                                  unhexlify('01'))):
                while (True):
                    c = f_in.read(1)
                    if c == unhexlify('02'):
                        break
                    else:
                        header = header + c
            else:
                print 'esto no es un archivo cifradodo de Cryogenesis Systems'

            #print key
            aes = AES(key)
            #print aes.decrypt(header)
            header_sections = aes.decrypt(header).split('|')

            if header_sections[0] != 'header':
                msg = QMessageBox()
                msg.setIcon(QMessageBox.Critical)
                msg.setText("La clave no es correcta para el archivo:" + f)
                msg.setWindowTitle("Cryosystems")
                msg.setStandardButtons(QMessageBox.Ok)
                msg.exec_()
                errors = errors + 1
                continue

            f_out = open(path + '/' + header_sections[1], 'wb')

            techniques = header_sections[2].split(':')[:-1]

            techniquesObjects = []

            for t in techniques:
                techniquesObjects.append(self.techniquesClass[t](key))
            techniquesObjects.reverse()

            in_size = getsize(path + '/' + f)
            in_progress = 0.0

            block = f_in.read(blockSize)
            while (block):
                block_p = block
                for t in techniquesObjects:
                    block_p = t.decrypt(block_p)
                f_out.write(block_p)
                in_progress = in_progress + blockSize
                progress = (in_progress / in_size) * 100
                self.progressBars[str(f)].setProperty("value", int(progress))
                self.progressBars[str(f)].setToolTip(str(progress) + '%')
                block = f_in.read(blockSize)

            f_in.close()
            f_out.close()

            if (checksum(path + '/' + header_sections[1]) !=
                    header_sections[3]):
                msg = QMessageBox()
                msg.setIcon(QMessageBox.Critical)
                msg.setText("El archivo" + f + 'se ha corrompido')
                msg.setWindowTitle("Cryosystems")
                msg.setStandardButtons(QMessageBox.Ok)
                msg.exec_()
                errors = errors + 1
                from os import remove
                remove(header_sections[1])

        msg = QMessageBox()
        msg.setWindowTitle("Cryosystems")
        msg.setStandardButtons(QMessageBox.Ok)

        if (errors == 0):
            msg.setIcon(QMessageBox.Information)
            msg.setText("La desencriptacion ha concluido exitosamente")
        else:
            msg.setIcon(QMessageBox.Warning)
            msg.setText("La desencriptacion ha concluido con " + str(errors) +
                        ' error(es)')

        msg.exec_()
        self.hide()
Beispiel #11
0
class DockWidgetTitleBar(QWidget):
    def __init__(self, dockWidget, hasCheckState = False):
        super(DockWidgetTitleBar, self).__init__(dockWidget)
        q = dockWidget
        self.floatButton = DockWidgetTitleBarButton(self)
        self.floatButton.setIcon(q.style().standardIcon(QStyle.SP_TitleBarNormalButton, None, q))
        self.floatButton.clicked.connect(self.toggleFloating)
        self.floatButton.setVisible(True)
        self.floatButton.setToolTip(self.tr("Undock"))
        self.closeButton = DockWidgetTitleBarButton(self)
        self.closeButton.setIcon(q.style().standardIcon(QStyle.SP_TitleBarCloseButton, None, q))
        self.closeButton.clicked.connect(dockWidget.close)
        self.closeButton.setVisible(True)
        self.closeButton.setToolTip(self.tr("Close"))

	if hasCheckState:
          self.checkStateButton = QCheckBox(self)
	  self.checkStateButton.setCheckState(2)
	  self.checkStateButton.setToolTip(self.tr("Disable this window"))
	  self.connect(self.checkStateButton, SIGNAL("stateChanged(int)"), self.toggleCheckState)
        else:
	  self.checkStateButton = False 
        dockWidget.featuresChanged.connect(self.featuresChanged)
        self.featuresChanged(0)
  
    def hasFeature(self, dockwidget, feature):
      return dockwidget.features() & feature == feature
 
    def minimumSizeHint(self):
        return self.sizeHint()
    
    def sizeHint(self):
        q = self.parentWidget()
        mw = q.style().pixelMetric(QStyle.PM_DockWidgetTitleMargin, None, q)
        fw = q.style().pixelMetric(QStyle.PM_DockWidgetFrameWidth, None, q)
        closeSize = QSize(0, 0)
        if self.closeButton:
            closeSize = self.closeButton.sizeHint()

        floatSize = QSize(0, 0)
        if self.floatButton:
            floatSize = self.floatButton.sizeHint()
        hideSize = self.hideSizeHint()

        buttonHeight = max(max(closeSize.height(), floatSize.height()), hideSize.height()) + 2
        buttonWidth = closeSize.width() + floatSize.width() + hideSize.width()
        titleFontMetrics = q.fontMetrics()
        fontHeight = titleFontMetrics.lineSpacing() + 2 * mw
        height = max(buttonHeight, fontHeight)
        return QSize(buttonWidth + height + 4 * mw + 2 * fw, height)
 
    def hideSizeHint(self):
       if self.checkStateButton:
	 return self.checkStateButton.sizeHint()
       else:
         return QSize(0, 0)
 
    def paintEvent(self, _event):
        p = QStylePainter(self)
        q = self.parentWidget()
        fw = q.isFloating() and q.style().pixelMetric(QStyle.PM_DockWidgetFrameWidth, None, q) or 0
        mw = q.style().pixelMetric( QStyle.PM_DockWidgetTitleMargin, None, q)
        titleOpt = QStyleOptionDockWidgetV2()
        titleOpt.initFrom(q)
        titleOpt.rect = self.titleOptionRect(fw, mw)
        titleOpt.title = q.windowTitle()
        titleOpt.closable = self.hasFeature(q, QDockWidget.DockWidgetClosable)
        titleOpt.floatable = self.hasFeature(q, QDockWidget.DockWidgetFloatable)
        p.drawControl(QStyle.CE_DockWidgetTitle, titleOpt)
 
    def titleOptionRect(self, fw, mw):
 	if self.checkStateButton:
	  return  QRect(QPoint(fw + mw + self.checkStateButton.size().width(), fw), QSize(self.geometry().width() - ( fw * 2 ) - mw - self.checkStateButton.size().width(), self.geometry().height() - ( fw * 2 )))
        else:
          return QRect(QPoint(fw + mw, fw), QSize(self.geometry().width() - ( fw * 2 ) - mw, self.geometry().height() - ( fw * 2 )))
 
    def resizeEvent(self, _event):
        q = self.parentWidget()
        fw = q.isFloating() and q.style().pixelMetric(QStyle.PM_DockWidgetFrameWidth, None, q) or 0
        opt = QStyleOptionDockWidgetV2()
        opt.initFrom(q)
        opt.rect = QRect(QPoint(fw, fw), QSize(self.geometry().width() - (fw * 2), self.geometry().height() - (fw * 2)))
        opt.title = q.windowTitle()
        opt.closable = self.hasFeature(q, QDockWidget.DockWidgetClosable)
        opt.floatable = self.hasFeature(q, QDockWidget.DockWidgetFloatable)
        floatRect = q.style().subElementRect(QStyle.SE_DockWidgetFloatButton, opt, q)
        if not floatRect.isNull():
            self.floatButton.setGeometry(floatRect)
        closeRect = q.style().subElementRect(QStyle.SE_DockWidgetCloseButton, opt, q)
        if not closeRect.isNull():
            self.closeButton.setGeometry(closeRect)
        top = fw
        if not floatRect.isNull():
            top = floatRect.y()
        elif not closeRect.isNull():
            top = closeRect.y()
        if self.checkStateButton:
          size = self.checkStateButton.size()
          if not closeRect.isNull():
            size = self.closeButton.size()
          elif not floatRect.isNull():
            size = self.floatButton.size()
          checkStateRect = QRect(QPoint(fw, top), size)
          self.checkStateButton.setGeometry(checkStateRect)
  
    def toggleFloating( self ):
        parent = self.parentWidget()
        parent.setFloating(not parent.isFloating())
 
    def toggleCheckState(self, state):
       parent = self.parentWidget()
       if parent:
         if state != 0:
           parent.updateCheckState(True)
         else:
	   parent.updateCheckState(False)
 
    def featuresChanged(self, _features):
        parent = self.parentWidget()
        self.closeButton.setVisible(self.hasFeature(parent, QDockWidget.DockWidgetClosable))
        self.floatButton.setVisible(self.hasFeature(parent, QDockWidget.DockWidgetFloatable))
Beispiel #12
0
class BookKeeping(QFrame):

    # =======================================================================
    def __init__(self, parent=None, _PARENT=None):

        # -------------------------------------------------------------------
        QFrame.__init__(self, parent)
        # -------------------------------------------------------------------
        self.PARENT = _PARENT
        self.CONF = _PARENT.CONF

        #self.SHA256                         = hashlib.sha256;
        #UID_SHA256 = self.SHA256( str(time.time()) ).hexdigest();
        self.SELECTED_BKKPG_UID = None

        # -------------------------------------------------------------------
        self.setGeometry(3, 5, 975, 555)
        self.setStyleSheet(
            "QFrame{ font: 12px 'monospace'; color: #000; background-color: transparent; background-image: url('./data/imgs/TAB_BookKeeping.png'); }"
        )

        self.PAIR_COMBO = QComboBox(self)
        self.PAIR_COMBO.setGeometry(86, 20, 108, 44)
        self.connect(self.PAIR_COMBO, SIGNAL('currentIndexChanged(int)'),
                     self.CREATE_LISTS)
        #self.PAIR_COMBO.setStyleSheet( "QComboBox{ font: 16px 'monospace'; background-color: #333; color: #FFF; border-style: solid; border-width: 1px; border-color: #000; border-radius: none; }" );
        self.PAIR_COMBO.setEditable(False)
        """
        #self.PAIR_COMBO.setItemIcon( 0, QIcon("./data/imgs/500.png") );
        print(self.PAIR_COMBO.__len__());
        #set at tooltip
        combo.setItemData(0,"a tooltip",Qt.ToolTipRole)
        # set the Font Color
        combo.setItemData(0,QColor("#FF333D"), Qt.BackgroundColorRole)
        #set the font
        combo.setItemData(0, QtGui.QFont('Verdana', bold=True), Qt.FontRole)
        """

        # -------------------------------------------------------------------
        list_style = "QListWidget{ font: 10px 'monospace'; color: #fff;  background-color: #000; border-style: none; background-image: url('./data/imgs/TAB_BookKeeping_line.png'); }"
        # ./data/imgs/BookKeeping_line.png
        lable_style = "QLabel{ font: 10px 'monospace'; color: #fff;  background-color: transparent; border-style: none; background-image: url(''); }"

        # -------------------------------------------------------------------
        self.DATA_TO_SEND = None
        self._i_ = "|"
        # List delimiter
        self.CALCULATE_ONLY_COMPLETED = True
        self.DATA_TO_SEND_SELECTED = False

        # -------------------------------------------------------------------
        self.BOOKKEEPING_WIDGET = QListWidget(self)
        self.BOOKKEEPING_WIDGET.setGeometry(13, 144, 949, 259)
        self.BOOKKEEPING_WIDGET.setStyleSheet(list_style)

        self.connect(self.BOOKKEEPING_WIDGET, SIGNAL('itemSelectionChanged()'),
                     lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SOLD_WIDGET"))
        self.BOOKKEEPING_WIDGET.itemClicked.connect(
            lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SELECT_VALUES"))

        self.BOUGHT_TTL_LABLE = QLabel("0.0", self)
        self.BOUGHT_TTL_LABLE.setGeometry(304, 406, 85, 17)
        #self.BOUGHT_TTL_LABLE.setEditable( False );
        self.BOUGHT_TTL_LABLE.setStyleSheet(lable_style)
        self.BOUGHT_TTL = 0

        self.BOUGHT_TTL_PLUS_FEE_LABLE = QLabel("0.0", self)
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setGeometry(396, 406, 85, 17)
        #self.BOUGHT_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setStyleSheet(lable_style)
        self.BOUGHT_TTL_PLUS_FEE = 0

        self.SOLD_TTL_LABLE = QLabel("0.0", self)
        self.SOLD_TTL_LABLE.setGeometry(694, 406, 85, 17)
        #self.SOLD_TTL_LABLE.setEditable( False );
        self.SOLD_TTL_LABLE.setStyleSheet(lable_style)
        self.SOLD_TTL = 0

        self.SOLD_TTL_PLUS_FEE_LABLE = QLabel("0.0", self)
        self.SOLD_TTL_PLUS_FEE_LABLE.setGeometry(784, 406, 85, 17)
        #self.SOLD_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.SOLD_TTL_PLUS_FEE_LABLE.setStyleSheet(lable_style)
        self.SOLD_TTL_PLUS_FEE = 0

        self.PROFIT_TTL_LABLE = QLabel("0.0", self)
        self.PROFIT_TTL_LABLE.setGeometry(874, 406, 88, 17)
        #self.PROFIT_TTL_LABLE.setEditable( False );
        self.PROFIT_TTL_LABLE.setStyleSheet(lable_style)
        self.PROFIT_TTL = 0

        # -------------------------------------------------------------------
        self.SEND_ID_LABLE = QLabel("n/a", self)
        self.SEND_ID_LABLE.setGeometry(18, 467, 43, 17)
        self.SEND_ID_LABLE.setStyleSheet(lable_style)

        self.SEND_AMOUNT_LABLE = QLabel("n/a", self)
        self.SEND_AMOUNT_LABLE.setGeometry(66, 467, 85, 17)
        self.SEND_AMOUNT_LABLE.setStyleSheet(lable_style)

        self.SEND_AT_PRICE_LABLE = QLabel("n/a", self)
        self.SEND_AT_PRICE_LABLE.setGeometry(156, 467, 43, 17)
        self.SEND_AT_PRICE_LABLE.setStyleSheet(lable_style)

        self.SEND_VALUES_BTN = QPushButton("", self)
        self.SEND_VALUES_BTN.setGeometry(60, 502, 131, 33)
        self.SEND_VALUES_BTN.setStyleSheet(
            "QPushButton{ background-color: transparent; border-style: none; }"
        )
        self.connect(self.SEND_VALUES_BTN, SIGNAL('clicked()'),
                     lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SEND_VALUES"))

        # -------------------------------------------------------------------
        self.ONLY_COMPLETED_CHECKBOX = QCheckBox("", self)
        self.ONLY_COMPLETED_CHECKBOX.setGeometry(665, 444, 17, 17)
        self.ONLY_COMPLETED_CHECKBOX.setCheckState(Qt.Checked)
        #self.ONLY_COMPLETED_CHECKBOX.setEnabled(False);
        self.connect(self.ONLY_COMPLETED_CHECKBOX, SIGNAL('stateChanged(int)'),
                     lambda: self.CHANGE_VALUES("only_completed"))

        # -------------------------------------------------------------------
        self.INIT()
        # -------------------------------------------------------------------

    # =======================================================================
    def INIT(self):

        # -------------------------------------------------------------------
        try:

            self.CREATE_PAIRS_SELECTOR()
            self.CREATE_LISTS()

        except Exception as _exception:

            print("-----------------------------------------------------")
            print("[INIT]" + str(_exception))
        # -------------------------------------------------------------------

    # =======================================================================
    def BKKPG_UID_ACTION(self, _ACTION, BKKPG_UID, _D):

        # -------------------------------------------------------------------
        #print("_ACTION: ", _ACTION, "BKKPG_UID: ", BKKPG_UID)
        # -------------------------------------------------------------------
        try:

            CURR_PAIR = str(self.PAIR_COMBO.currentText()).lower().strip()

            order_id = _D[0]
            unix_time = _D[1]
            filled = _D[2]
            amount = _D[3]
            at_price = _D[4]

            if _ACTION == "buy":

                # For CRYPTO
                ttl = amount
                fee = (ttl / 100 * self.PARENT.FEE)

            elif _ACTION == "sell":

                # For USD
                ttl = amount * at_price
                fee = (ttl / 100 * self.PARENT.FEE)

            grand_ttl = ttl - fee

            # -------------------------------------------------------------------
            if BKKPG_UID == "":  # Is New Record

                TPL = "buy_order_id, buy_unix_time, buy_filled, buy_amount, buy_at_price, buy_fee, buy_ttl, buy_grand_ttl, sell_order_id, sell_unix_time, sell_filled, sell_amount, sell_at_price, sell_fee, sell_ttl, sell_grand_ttl "

                _SQL = "INSERT INTO " + CURR_PAIR + "( BKKPG_UID, completed, started, " + TPL + ", profit_ttl ) "

                if _ACTION == "buy":
                    _SQL += "VALUES( NULL,0,1,{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}, 0 )".format(
                        _D[0], _D[1], _D[2], _D[3], _D[4], fee, ttl, grand_ttl,
                        0, 0, 0, 0, 0, 0, 0, 0)

                else:
                    _SQL += "VALUES( NULL,0,1,{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}, 0 )".format(
                        0, 0, 0, 0, 0, 0, 0, 0, _D[0], _D[1], _D[2], _D[3],
                        _D[4], fee, ttl, grand_ttl)

                self.PARENT.DB.EXEC("BOOK_DB", _SQL)

            else:  # Existing Record

                # ------------------------------------------------
                if filled == 1:

                    completed = 1

                    _SQL = "SELECT ACT_grand_ttl from " + CURR_PAIR + " WHERE BKKPG_UID=" + BKKPG_UID

                    if _ACTION == "buy":

                        DATA = self.PARENT.DB.FETCH("BOOK_DB",
                                                    _SQL.replace(
                                                        "ACT", "sell"),
                                                    ALL=False)
                        profit_ttl = DATA - grand_ttl

                    else:

                        DATA = self.PARENT.DB.FETCH("BOOK_DB",
                                                    _SQL.replace("ACT", "buy"),
                                                    ALL=False)
                        profit_ttl = grand_ttl - DATA
                else:
                    profit_ttl = 0
                    completed = 0

                # ------------------------------------------------
                A = _ACTION

                _SQL = "UPDATE " + CURR_PAIR + " SET completed={0}, " + A + "_order_id={1}, " + A + "_unix_time={2}, " + A + "_filled={3}, "
                _SQL += A + "_amount={4}, " + A + "_at_price={5}, " + A + "_fee={6}, " + A + "_ttl={7}, " + A + "_grand_ttl={8}"
                _SQL += " WHERE BKKPG_UID=" + BKKPG_UID

                _SQL = _SQL.format(completed, order_id, unix_time, filled,
                                   amount, at_price, fee, ttl, grand_ttl)

                self.PARENT.DB.EXEC("BOOK_DB", _SQL)

        except Exception as _exception:

            print(" BOOKKEEPING[0:0]")
            print(_exception)
        # -------------------------------------------------------------------
        """
        BKKPG_UID, completed, started, 
        
        buy_order_id, buy_unix_time, buy_filled, buy_amount, buy_at_price, buy_fee, buy_ttl, buy_grand_ttl, 
        sell_order_id, sell_unix_time, sell_filled, sell_amount, sell_at_price, sell_fee, sell_ttl, sell_grand_ttl, 
        
        profit_ttl
        """
        # -------------------------------------------------------------------

    # =======================================================================
    def DELETE_ORDER(self, _order_id, _pair, _type):

        # -------------------------------------------------------------------

        _SQL = "SELECT buy_order_id, sell_order_id FROM " + _pair
        _SQL += " WHERE buy_order_id=" + str(
            _order_id) + " OR sell_order_id=" + str(_order_id)

        DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL, ALL=False)

        if DATA is None:
            pass

        if _type == "buy" and DATA[1] == 0:

            _SQL = "DELETE FROM " + _pair + " WHERE buy_order_id=" + str(
                _order_id) + " OR sell_order_id=" + str(_order_id)
            self.PARENT.DB.EXEC("BOOK_DB", _SQL)
            self.CREATE_LISTS()

        elif _type == "sell" and DATA[0] == 0:

            _SQL = "DELETE FROM " + _pair + " WHERE buy_order_id=" + str(
                _order_id) + " OR sell_order_id=" + str(_order_id)
            self.PARENT.DB.EXEC("BOOK_DB", _SQL)
            self.CREATE_LISTS()

        else:

            A = _type

            _SQL = "UPDATE " + self.PARENT.CURR_PAIR + " SET "
            _SQL += " completed=0, " + A + "_order_id=0, " + A + "_unix_time=0, " + A + "_filled=0, "
            _SQL += A + "_amount=0, " + A + "_at_price=0, " + A + "_fee=0, " + A + "_ttl=0, " + A + "_grand_ttl=0 "
            _SQL += "WHERE " + A + "_order_id=" + str(_order_id)

            self.PARENT.DB.EXEC("BOOK_DB", _SQL)

        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_LISTS(self):

        # -------------------------------------------------------------------
        try:
            CURR_PAIR = str(self.PAIR_COMBO.currentText()).lower()

            # -------------------------------------------------------------------
            self.BOOK = {
                "bought": [],
                "sold": []
            }

            self.BOUGHT_TTL = 0
            self.BOUGHT_TTL_PLUS_FEE = 0

            self.SOLD_TTL = 0
            self.SOLD_TTL_PLUS_FEE = 0

            # -------------------------------------------------------------------
            #self.PARENT.DB.EXEC( "BOOK_DB", "DELETE FROM "+CURR_PAIR+" WHERE BKKPG_UID>7" );

            DATA = self.PARENT.DB.FETCH("BOOK_DB",
                                        "SELECT * FROM " + CURR_PAIR +
                                        " ORDER BY BKKPG_UID DESC",
                                        ALL=True)
            self.BOOKKEEPING_WIDGET.clear()

            for data in DATA:

                # ---------------------------------------------------------------
                """ " "" 
                print( data )
                for d in data:
                    print( d )
                exit();
                "" " """
                # ---------------------------------------------------------------
                # In-Memory DATA
                BKKPG_UID = data[0]
                completed = data[1]
                started = data[2]

                buy_order_id = data[3]
                buy_unix_time = data[4]
                buy_filled = data[5]
                buy_amount = data[6]
                buy_at_price = data[7]
                #buy_fee         = data[8]
                buy_ttl = data[9]
                buy_grand_ttl = data[10]

                sell_order_id = data[11]
                sell_unix_time = data[12]
                sell_filled = data[13]
                sell_amount = data[14]

                sell_at_price = data[15]
                #sell_fee        = data[16]
                sell_ttl = data[17]
                sell_grand_ttl = data[18]

                profit_ttl = data[19]

                # ---------------------------------------------------------------

                # ---------------------------------------------------------------
                """
                self.BOOK[ data[3] ].append( {
                                            
                                        BKKPG_UID,
                                        completed,
                                        started,

                                        buy_order_id,
                                        buy_unix_time,
                                        buy_filled,
                                        buy_amount,
                                        buy_at_price,
                                        buy_fee,
                                        buy_ttl,
                                        buy_grand_ttl,

                                        sell_order_id,
                                        sell_unix_time,
                                        sell_filled,
                                        sell_amount,
                                        sell_at_price,
                                        sell_fee,
                                        sell_ttl,
                                        sell_grand_ttl,

                                        profit_ttl

                                            } );

                """
                # ---------------------------------------------------------------
                if self.CALCULATE_ONLY_COMPLETED:

                    if buy_filled == 1 and sell_filled == 1:

                        self.BOUGHT_TTL += buy_ttl
                        self.BOUGHT_TTL_PLUS_FEE += buy_grand_ttl * buy_at_price

                        self.SOLD_TTL += sell_ttl
                        self.SOLD_TTL_PLUS_FEE += sell_grand_ttl

                else:

                    self.BOUGHT_TTL += buy_ttl
                    self.BOUGHT_TTL_PLUS_FEE += buy_grand_ttl * buy_at_price

                    self.SOLD_TTL += sell_ttl
                    self.SOLD_TTL_PLUS_FEE += sell_grand_ttl

                self.PROFIT_TTL_LABLE.setText(
                    "{:10,.6f}".format(self.SOLD_TTL_PLUS_FEE -
                                       self.BOUGHT_TTL_PLUS_FEE))

                # ---------------------------------------------------------------
                # Formating data to Display in BookKeeping Wodget

                item = ""

                item += "DEL{:7} ".format(str(BKKPG_UID))
                # id

                # BUY / BOUGHT
                item += "#{:11} DEL".format(str(buy_order_id))
                # order_id
                item += "{:4} DEL".format(str(buy_filled))
                # filed
                item += "{:13} DEL".format(
                    str("{:10,.6f}".format(float(buy_amount))).strip())
                # Amount
                item += "{:13} DEL".format(
                    str("{:10,.6f}".format(buy_at_price)).strip())
                # at_price
                #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
                #item += "{:13} DEL".format( str("{:10,.6f}".format( buy_ttl )).strip() ); # ttl
                item += "{:14} ".format(
                    str("{:10,.6f}".format(buy_grand_ttl)).strip())
                # grand_ttl

                # SELL / SOLD
                item += "#{:11} DEL".format(str(sell_order_id))
                # order_id
                item += "{:4} DEL".format(str(sell_filled))
                # filed
                item += "{:13} DEL".format(
                    str("{:10,.6f}".format(sell_amount)).strip())
                # Amount
                item += "{:13} DEL".format(
                    str("{:10,.6f}".format(sell_at_price)).strip())
                # at_price
                #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
                #item += "{:13} DEL".format( str("{:10,.6f}".format( sell_ttl )).strip() ); # ttl
                item += "{:14} ".format(
                    str("{:10,.6f}".format(sell_grand_ttl)).strip())
                # grand_ttl

                # PROFIT
                item += "{:13}".format(
                    str("{:10,.6f}".format(profit_ttl)).strip())
                # grand_ttl

                newItem = QListWidgetItem(
                    QIcon("./data/imgs/icon_filled_status_0.png"),
                    item.replace("DEL", self._i_), self.BOOKKEEPING_WIDGET, 0)
                #newItemToolTip = "Order ID: #"+str()+" Created: "+time.ctime(int(data[2]));
                #newItem.setToolTip(newItemToolTip);

                # ---------------------------------------------------------------

            # / for
            # -------------------------------------------------------------------
            try:
                self.BOUGHT_TTL_LABLE.setText(
                    str("{:10,.6f}".format(self.BOUGHT_TTL).strip()))
                self.BOUGHT_TTL_PLUS_FEE_LABLE.setText(
                    str("{:10,.6f}".format(self.BOUGHT_TTL_PLUS_FEE).strip()))

                self.SOLD_TTL_LABLE.setText(
                    str("{:10,.6f}".format(self.SOLD_TTL).strip()))
                self.SOLD_TTL_PLUS_FEE_LABLE.setText(
                    str("{:10,.6f}".format(self.SOLD_TTL_PLUS_FEE).strip()))

            except Exception as e:
                print("BOOKKEEPING[3:0]" + str(e))

        except Exception as _exception:

            print(" BOOKKEEPING[1:0]")
            print(_exception)
        # -------------------------------------------------------------------

    # =======================================================================
    def RESET_BKKPG_UID(self):

        # -------------------------------------------------------------------
        #CURR_PAIR =  str(self.PAIR_COMBO.currentText()).lower();
        self.PARENT.GUI.BKKPG_UID_VALUE.setText("")
        self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "show")
        self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "show")
        # -------------------------------------------------------------------

    # =======================================================================
    def CHANGE_VALUES(self, _this):

        # -------------------------------------------------------------------
        if _this == "only_completed":
            if self.ONLY_COMPLETED_CHECKBOX.isChecked():
                self.CALCULATE_ONLY_COMPLETED = True
            else:
                self.CALCULATE_ONLY_COMPLETED = False

        # -------------------------------------------------------------------
        self.CREATE_LISTS()
        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_PAIRS_SELECTOR(self, ALL=False):

        # -------------------------------------------------------------------
        if not ALL:
            for PAIR in self.CONF["API"]["PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper())

        else:
            for PAIR in self.CONF["API"]["ALL_PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper())

        for i in xrange(0, self.PAIR_COMBO.__len__()):

            self.PAIR_COMBO.setItemData(i, QColor("#333"), Qt.BackgroundRole)
            self.PAIR_COMBO.setItemData(i, QColor("#fff"), Qt.ForegroundRole)
            #self.PAIR_COMBO.setItemData( i, QFont('monospace', 16, -1, False), Qt.FontRole);
        # -------------------------------------------------------------------

    # =======================================================================
    def SEND_VALUES_TO_TRADE_TERMINAL(self, _action):

        # -------------------------------------------------------------------
        if _action == "SELECT_VALUES":

            self.DATA_TO_SEND_SELECTED = True
            #self.DATA_TO_SEND = [ str(item).stip() for iten in str(self.BOOKKEEPING_WIDGET.currentItem().text()).strip().split("|")];
            self.DATA_TO_SEND = str(
                self.BOOKKEEPING_WIDGET.currentItem().text()).strip().split(
                    "|")[1].split("#")[0].strip()

        elif _action == "SEND_VALUES":

            if self.DATA_TO_SEND_SELECTED:

                _SQL = "SELECT buy_order_id, sell_order_id FROM " + self.PARENT.CURR_PAIR
                _SQL += " WHERE BKKPG_UID=" + self.DATA_TO_SEND

                DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL, ALL=False)

                if DATA[0] != 0 and DATA[1] != 0:

                    self.PARENT.GUI.SHOW_QMESSAGE(
                        "info",
                        "This UID is Full!<br> You can't add data to it enymore.<br>Bud You can delete sell and/or buy part<br/> and add new part."
                    )
                    return

                self.PARENT.GUI.BKKPG_UID_VALUE.setText(self.DATA_TO_SEND)

                self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "show")
                self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "show")

                self.DATA_TO_SEND_SELECTED = False
                self.DATA_TO_SEND = None

                # Clear Lables
                self.SEND_ID_LABLE.setText("n/a")
                self.SEND_AMOUNT_LABLE.setText("n/a")
                self.SEND_AT_PRICE_LABLE.setText("n/a")

                if DATA[0] == 0:
                    self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "hide")

                else:
                    self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "hide")

                # Switch to Trader-Tab
                self.PARENT.GUI.MAIN_TABS.setCurrentIndex(0)

            else:

                self.PARENT.GUI.SHOW_QMESSAGE(
                    "info",
                    " Select first item which one you would like<br/> send to the Trade-Terminal !"
                )
                return

        # -------------------------------------------------------------------
        if self.DATA_TO_SEND is not None:

            self.SEND_ID_LABLE.setText(self.DATA_TO_SEND)
Beispiel #13
0
class ViewDataTools(QMainWindow):
    def __init__(self, parent=None):
        super(ViewDataTools, self).__init__(parent)

        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # DATATOOLS WINDOWS:
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        self.setWindowTitle(ui_strings.DATATOOLS_TITLE)
        self._width = 680
        self._height = 560
        self._left_margin = 10
        self.resize(self._width, self._height)
        size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(size_policy)
        self.setMinimumSize(QtCore.QSize(self._width, self._height))
        self.setMaximumSize(QtCore.QSize(self._width, self._height))
        self.setWindowIcon(QIcon(resources.ICON_LOGO))

        # central widget
        self.central_widget = QWidget(self)

        # DataTools description
        self.lbl_description = QLabel(self.central_widget)
        self.lbl_description.setGeometry(QtCore.QRect(0, 0, self._width, 30))
        self.lbl_description.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_description.setText(ui_strings.DATATOOLS_DESCRIPTION)

        # group input files
        self.group_input_file = QGroupBox(self.central_widget)
        self.group_input_file.setGeometry(
            QtCore.QRect(self._left_margin, 30, 660, 80))
        self.group_input_file.setTitle(ui_strings.DATATOOLS_GROUP_INPUT)

        # frame input files
        self.frame_inputs = QFrame(self.group_input_file)
        self.frame_inputs.setGeometry(
            QtCore.QRect(self._left_margin, 0, 270, 80))
        self.frame_inputs.setFrameShape(QFrame.StyledPanel)
        self.frame_inputs.setFrameShadow(QFrame.Raised)

        # label input type
        self.lbl_input_type = QLabel(self.frame_inputs)
        self.lbl_input_type.setGeometry(QtCore.QRect(20, 20, 60, 15))
        self.lbl_input_type.setText(ui_strings.DATATOOLS_INPUT_TYPE)

        # button xls
        self.btn_xls = QToolButton(self.frame_inputs)
        self.btn_xls.setGeometry(QtCore.QRect(20, 35, 35, 35))
        icon_xls = QIcon()
        icon_xls.addPixmap(QPixmap(resources.ICON_XLS), QIcon.Normal,
                           QIcon.Off)
        self.btn_xls.setIcon(icon_xls)
        self.btn_xls.setIconSize(QtCore.QSize(24, 24))
        self.btn_xls.setCheckable(True)
        self.btn_xls.setAutoExclusive(True)
        self.btn_xls.setObjectName("xls_button")

        # button csv
        self.btn_csv = QToolButton(self.frame_inputs)
        self.btn_csv.setGeometry(QtCore.QRect(60, 35, 35, 35))
        icon_csv = QIcon()
        icon_csv.addPixmap(QPixmap(resources.ICON_CSV), QIcon.Normal,
                           QIcon.Off)
        self.btn_csv.setIcon(icon_csv)
        self.btn_csv.setIconSize(QtCore.QSize(24, 24))
        self.btn_csv.setCheckable(True)
        self.btn_csv.setAutoExclusive(True)
        self.btn_csv.setObjectName("csv_button")

        # checkbox csv with headers
        self.chk_csv_headers = QCheckBox(ui_strings.DATATOOLS_WITH_HEADERS,
                                         self.frame_inputs)
        self.chk_csv_headers.setGeometry(QtCore.QRect(100, 45, 110, 15))
        self.chk_csv_headers.setEnabled(False)

        # TextEdit + PushButton (FindFolder)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # lbl sheet name
        self.lbl_file_path = QLabel(self.group_input_file)
        self.lbl_file_path.setGeometry(QtCore.QRect(250, 20, 120, 15))
        self.lbl_file_path.setText(ui_strings.DATATOOLS_SELECT_FILE)

        self.txt_file = QLineEdit(self.group_input_file)
        self.txt_file.setGeometry(QtCore.QRect(250, 35, 160, 20))
        self.txt_file.setReadOnly(True)

        self.btn_path = QPushButton(self.group_input_file)
        self.btn_path.setGeometry(QtCore.QRect(410, 34, 50, 22))
        self.btn_path.setText(ui_strings.DATATOOLS_SELECT_BUTTON)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        # lbl sheet name
        self.lbl_sheet_name = QLabel(self.group_input_file)
        self.lbl_sheet_name.setGeometry(QtCore.QRect(500, 20, 120, 15))
        self.lbl_sheet_name.setText(ui_strings.DATATOOLS_SHEET_NAME)

        # Combobox select sheet - initially does not contain values
        self.cbo_sheet = QComboBox(self.group_input_file)
        self.cbo_sheet.setGeometry(QtCore.QRect(500, 35, 130, 20))

        # data grid to visualize error messages
        self.tbl_errors = QTableWidget(self.central_widget)
        self.tbl_errors.setGeometry(
            QtCore.QRect(self._left_margin, 420, 660, 100))

        # data grid to visualize those records with errors.
        self.tbl_uploaded_data = QTableWidget(self.central_widget)
        self.tbl_uploaded_data.setGeometry(
            QtCore.QRect(self._left_margin, 120, 500, 220))

        # group run options
        self.group_run_options = QGroupBox(self.central_widget)
        self.group_run_options.setGeometry(QtCore.QRect(520, 120, 150, 220))
        self.group_run_options.setTitle(ui_strings.DATATOOLS_GROUP_RUN)

        # Errors summary:
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # group summary errors
        self.group_errors = QGroupBox(self.central_widget)
        self.group_errors.setGeometry(
            QtCore.QRect(self._left_margin, 350, 660, 60))
        self.group_errors.setTitle(ui_strings.DATATOOLS_HEADER_ERRORS)

        # lbl records
        self.lbl_records = QLabel(self.group_errors)
        self.lbl_records.setGeometry(QtCore.QRect(165, 15, 80, 15))
        self.lbl_records.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_records.setText(ui_strings.DATATOOLS_RECORDS)

        self.txt_records = QLineEdit(self.group_errors)
        self.txt_records.setGeometry(QtCore.QRect(165, 30, 80, 20))
        self.txt_records.setAlignment(QtCore.Qt.AlignCenter)
        self.txt_records.setReadOnly(True)

        # lbl errors
        self.lbl_errors = QLabel(self.group_errors)
        self.lbl_errors.setGeometry(QtCore.QRect(275, 15, 80, 15))
        self.lbl_errors.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_errors.setText(ui_strings.DATATOOLS_ERRORS)

        self.txt_errors = QLineEdit(self.group_errors)
        self.txt_errors.setGeometry(QtCore.QRect(275, 30, 80, 20))
        self.txt_errors.setAlignment(QtCore.Qt.AlignCenter)
        self.txt_errors.setReadOnly(True)

        # lbl time
        self.lbl_time = QLabel(self.group_errors)
        self.lbl_time.setGeometry(QtCore.QRect(385, 15, 80, 15))
        self.lbl_time.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_time.setText(ui_strings.DATATOOLS_TIME)

        self.txt_time = QLineEdit(self.group_errors)
        self.txt_time.setGeometry(QtCore.QRect(385, 30, 80, 20))
        self.txt_time.setAlignment(QtCore.Qt.AlignCenter)
        self.txt_time.setReadOnly(True)

        # history button
        self.btn_history = QToolButton(self.group_errors)
        self.btn_history.setGeometry(QtCore.QRect(500, 25, 100, 25))
        icon_history = QIcon()
        icon_history.addPixmap(QPixmap(resources.ICON_HISTORY), QIcon.Normal,
                               QIcon.Off)
        self.btn_history.setIcon(icon_history)
        self.btn_history.setIconSize(QtCore.QSize(20, 20))
        self.btn_history.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
        self.btn_history.setText(ui_strings.DATATOOLS_HISTORY)
        self.btn_history.setCheckable(True)
        self.btn_history.setAutoExclusive(True)
        self.btn_history.setObjectName("history_button")
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        # btn data uploader
        self.btn_data_uploader = QPushButton(
            ui_strings.DATATOOLS_DATA_UPLOADER, self.group_run_options)
        self.btn_data_uploader.setGeometry(QtCore.QRect(10, 120, 90, 25))
        self.btn_data_uploader.setCheckable(True)
        self.btn_data_uploader.setAutoExclusive(True)
        self.btn_data_uploader.setFlat(False)

        # btn data testing
        self.btn_data_testing = QPushButton(ui_strings.DATATOOLS_DATA_TESTING,
                                            self.group_run_options)
        self.btn_data_testing.setEnabled(False)
        self.btn_data_testing.setGeometry(QtCore.QRect(10, 150, 90, 25))
        self.btn_data_testing.setCheckable(True)
        self.btn_data_testing.setAutoExclusive(True)

        # btn data to database
        self.btn_data_db = QPushButton(ui_strings.DATATOOLS_DATA_DB,
                                       self.group_run_options)
        self.btn_data_db.setEnabled(False)
        self.btn_data_db.setGeometry(QtCore.QRect(10, 179, 91, 23))
        self.btn_data_db.setCheckable(True)
        self.btn_data_db.setAutoExclusive(True)

        # frame run options
        self.frame_run = QFrame(self.group_run_options)
        self.frame_run.setGeometry(QtCore.QRect(10, 30, 130, 80))
        self.frame_run.setFrameShape(QFrame.StyledPanel)
        self.frame_run.setFrameShadow(QFrame.Raised)

        # option process until first error
        self.rbtn_process_error = QRadioButton(
            ui_strings.DATATOOLS_PROCESS_ERROR, self.frame_run)
        self.rbtn_process_error.setGeometry(QtCore.QRect(0, 0, 150, 20))

        # option process all data
        self.rbtn_process_all = QRadioButton(ui_strings.DATATOOLS_PROCESS_ALL,
                                             self.frame_run)
        self.rbtn_process_all.setGeometry(QtCore.QRect(0, 20, 150, 30))

        # checkbox to filter by records with errors.
        #self.chk_filter_errors = QCheckBox(ui_strings.DATATOOLS_FILTER_ERRORS, self.frame_run)
        #self.chk_filter_errors.setGeometry(QtCore.QRect(0, 50, 100, 15))
        #self.chk_filter_errors.setEnabled(False)

        # icons -> pass - error: Initially are empty labels
        # if not started -> ICON_MINI_WAIT
        # if error -> ICON_DELETE
        # if pass -> ICON_CHECK

        # state icon data uploader
        self.lbl_state_du = QLabel(self.group_run_options)
        self.lbl_state_du.setGeometry(QtCore.QRect(110, 120, 20, 20))
        self.lbl_state_du.setPixmap(QPixmap(resources.ICON_MINI_WAIT))
        self.lbl_state_du.setScaledContents(True)

        # state icon data to database
        self.lbl_state_dt = QLabel(self.group_run_options)
        self.lbl_state_dt.setGeometry(QtCore.QRect(110, 150, 20, 20))
        self.lbl_state_dt.setPixmap(QPixmap(resources.ICON_MINI_WAIT))
        self.lbl_state_dt.setScaledContents(True)

        # state icon data testing
        self.lbl_state_db = QLabel(self.group_run_options)
        self.lbl_state_db.setGeometry(QtCore.QRect(110, 180, 20, 20))
        self.lbl_state_db.setPixmap(QPixmap(resources.ICON_MINI_WAIT))
        self.lbl_state_db.setScaledContents(True)

        # progress bar
        self.progress_bar = QProgressBar(self.central_widget)
        self.progress_bar.setGeometry(
            QtCore.QRect(self._left_margin, 530, 660, 15))
        self.progress_bar.setMaximum(100)
        self.progress_bar.setProperty("value", 0)
        self.progress_bar.setTextVisible(True)
        self.progress_bar.setOrientation(QtCore.Qt.Horizontal)
        self.progress_bar.setInvertedAppearance(False)
        self.progress_bar.setTextDirection(QProgressBar.TopToBottom)

        self.setCentralWidget(self.central_widget)
Beispiel #14
0
class DockWidgetTitleBar(QWidget):
    def __init__(self, dockWidget, hasCheckState=False, hasReport=False):
        super(DockWidgetTitleBar, self).__init__(dockWidget)
        q = dockWidget
        self.floatButton = DockWidgetTitleBarButton(self)
        self.floatButton.setIcon(q.style().standardIcon(
            QStyle.SP_TitleBarNormalButton, None, q))
        self.floatButton.clicked.connect(self.toggleFloating)
        self.floatButton.setVisible(True)
        self.floatButton.setToolTip(self.tr("Undock"))
        self.closeButton = DockWidgetTitleBarButton(self)
        self.closeButton.setIcon(q.style().standardIcon(
            QStyle.SP_TitleBarCloseButton, None, q))
        self.closeButton.clicked.connect(dockWidget.close)
        self.closeButton.setVisible(True)
        self.closeButton.setToolTip(self.tr("Close"))

        if hasCheckState:
            self.checkStateButton = QCheckBox(self)
            self.checkStateButton.setCheckState(2)
            self.checkStateButton.setToolTip(self.tr("Disable this window"))
            self.connect(self.checkStateButton, SIGNAL("stateChanged(int)"),
                         self.toggleCheckState)
        else:
            self.checkStateButton = False
        dockWidget.featuresChanged.connect(self.featuresChanged)
        self.featuresChanged(0)
        self.reportIcon = QIcon(":report")
        if hasReport:
            self.reportButton = DockWidgetTitleBarButton(self)
            self.reportButton.setIcon(self.reportIcon)
            self.reportButton.clicked.connect(self.toggleReport)
            self.reportButton.setVisible(True)
            self.reportButton.setToolTip(self.tr("Add content to report"))
        else:
            self.reportButton = None

    def hasFeature(self, dockwidget, feature):
        return dockwidget.features() & feature == feature

    def minimumSizeHint(self):
        return self.sizeHint()

    def sizeHint(self):
        q = self.parentWidget()
        mw = q.style().pixelMetric(QStyle.PM_DockWidgetTitleMargin, None, q)
        fw = q.style().pixelMetric(QStyle.PM_DockWidgetFrameWidth, None, q)
        closeSize = QSize(0, 0)
        if self.closeButton:
            closeSize = self.closeButton.sizeHint()

        floatSize = QSize(0, 0)
        if self.floatButton:
            floatSize = self.floatButton.sizeHint()
        hideSize = self.hideSizeHint()

        buttonHeight = max(max(closeSize.height(), floatSize.height()),
                           hideSize.height()) + 2
        buttonWidth = closeSize.width() + floatSize.width() + hideSize.width()
        titleFontMetrics = q.fontMetrics()
        fontHeight = titleFontMetrics.lineSpacing() + 2 * mw
        height = max(buttonHeight, fontHeight)
        return QSize(buttonWidth + height + 4 * mw + 2 * fw, height)

    def hideSizeHint(self):
        if self.reportButton and self.checkStateButton:
            return self.reportButton.sizeHint(
            ) + self.checkStateButton.sizeHint()
        elif self.reportButton:
            return self.reportButton.sizeHint()
        elif self.checkStateButton:
            return self.checkStateButton.sizeHint()
        else:
            return QSize(0, 0)

    def paintEvent(self, _event):
        p = QStylePainter(self)
        q = self.parentWidget()
        fw = q.isFloating() and q.style().pixelMetric(
            QStyle.PM_DockWidgetFrameWidth, None, q) or 0
        mw = q.style().pixelMetric(QStyle.PM_DockWidgetTitleMargin, None, q)
        titleOpt = QStyleOptionDockWidgetV2()
        titleOpt.initFrom(q)
        titleOpt.rect = self.titleOptionRect(fw, mw)
        titleOpt.title = q.windowTitle()
        titleOpt.closable = self.hasFeature(q, QDockWidget.DockWidgetClosable)
        titleOpt.floatable = self.hasFeature(q,
                                             QDockWidget.DockWidgetFloatable)
        p.drawControl(QStyle.CE_DockWidgetTitle, titleOpt)

    def titleOptionRect(self, fw, mw):
        if self.reportButton and self.checkStateButton:
            return QRect(
                QPoint(
                    fw + mw + self.reportButton.size().width() +
                    self.checkStateButton.size().width(), fw),
                QSize(
                    self.geometry().width() - (fw * 2) - mw -
                    self.reportButton.size().width() -
                    self.checkStateButton.size().width(),
                    self.geometry().height() - (fw * 2)))
        elif self.reportButton:
            return QRect(
                QPoint(fw + mw + self.reportButton.size().width(), fw),
                QSize(
                    self.geometry().width() - (fw * 2) - mw -
                    self.reportButton.size().width(),
                    self.geometry().height() - (fw * 2)))
        elif self.checkStateButton:
            return QRect(
                QPoint(fw + mw + self.checkStateButton.size().width(), fw),
                QSize(
                    self.geometry().width() - (fw * 2) - mw -
                    self.checkStateButton.size().width(),
                    self.geometry().height() - (fw * 2)))
        else:
            return QRect(
                QPoint(fw + mw, fw),
                QSize(self.geometry().width() - (fw * 2) - mw,
                      self.geometry().height() - (fw * 2)))

    def resizeEvent(self, _event):
        q = self.parentWidget()
        fw = q.isFloating() and q.style().pixelMetric(
            QStyle.PM_DockWidgetFrameWidth, None, q) or 0
        opt = QStyleOptionDockWidgetV2()
        opt.initFrom(q)
        opt.rect = QRect(
            QPoint(fw, fw),
            QSize(self.geometry().width() - (fw * 2),
                  self.geometry().height() - (fw * 2)))
        opt.title = q.windowTitle()
        opt.closable = self.hasFeature(q, QDockWidget.DockWidgetClosable)
        opt.floatable = self.hasFeature(q, QDockWidget.DockWidgetFloatable)
        floatRect = q.style().subElementRect(QStyle.SE_DockWidgetFloatButton,
                                             opt, q)
        if not floatRect.isNull():
            self.floatButton.setGeometry(floatRect)
        closeRect = q.style().subElementRect(QStyle.SE_DockWidgetCloseButton,
                                             opt, q)
        if not closeRect.isNull():
            self.closeButton.setGeometry(closeRect)
        top = fw
        if not floatRect.isNull():
            top = floatRect.y()
        elif not closeRect.isNull():
            top = closeRect.y()
        if self.checkStateButton:
            size = self.checkStateButton.size()
            if not closeRect.isNull():
                size = self.closeButton.size()
            elif not floatRect.isNull():
                size = self.floatButton.size()
            checkStateRect = QRect(QPoint(fw, top), size)
            self.checkStateButton.setGeometry(checkStateRect)
        if self.reportButton:
            size = self.reportButton.size()
            if not closeRect.isNull():
                size = self.closeButton.size()
            elif not floatRect.isNull():
                size = self.floatButton.size()
            reportRect = QRect(QPoint(fw, top), size)
            self.reportButton.setGeometry(reportRect)

    def toggleFloating(self):
        parent = self.parentWidget()
        parent.setFloating(not parent.isFloating())

    def toggleCheckState(self, state):
        parent = self.parentWidget()
        if parent:
            if state != 0:
                parent.updateCheckState(True)
            else:
                parent.updateCheckState(False)

    def toggleReport(self):
        parent = self.parentWidget()
        if parent:
            parent.report()

    def featuresChanged(self, _features):
        parent = self.parentWidget()
        self.closeButton.setVisible(
            self.hasFeature(parent, QDockWidget.DockWidgetClosable))
        self.floatButton.setVisible(
            self.hasFeature(parent, QDockWidget.DockWidgetFloatable))
Beispiel #15
0
class ViewDataTools(QMainWindow):
    def __init__(self, parent=None):
        super(ViewDataTools, self).__init__(parent)

        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # DATATOOLS WINDOWS:
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        self.setWindowTitle(ui_strings.DATATOOLS_TITLE)
        self._width = 680
        self._height = 560
        self._left_margin = 10
        self.resize(self._width, self._height)
        size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)
        size_policy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(size_policy)
        self.setMinimumSize(QtCore.QSize(self._width, self._height))
        self.setMaximumSize(QtCore.QSize(self._width, self._height))
        self.setWindowIcon(QIcon(resources.ICON_LOGO))

        # central widget
        self.central_widget = QWidget(self)

        # DataTools description
        self.lbl_description = QLabel(self.central_widget)
        self.lbl_description.setGeometry(QtCore.QRect(0, 0, self._width, 30))
        self.lbl_description.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_description.setText(ui_strings.DATATOOLS_DESCRIPTION)

        # group input files
        self.group_input_file = QGroupBox(self.central_widget)
        self.group_input_file.setGeometry(QtCore.QRect(self._left_margin, 30, 660, 80))
        self.group_input_file.setTitle(ui_strings.DATATOOLS_GROUP_INPUT)

        # frame input files
        self.frame_inputs = QFrame(self.group_input_file)
        self.frame_inputs.setGeometry(QtCore.QRect(self._left_margin, 0, 270, 80))
        self.frame_inputs.setFrameShape(QFrame.StyledPanel)
        self.frame_inputs.setFrameShadow(QFrame.Raised)

        # label input type
        self.lbl_input_type = QLabel(self.frame_inputs)
        self.lbl_input_type.setGeometry(QtCore.QRect(20, 20, 60, 15))
        self.lbl_input_type.setText(ui_strings.DATATOOLS_INPUT_TYPE)

        # button xls
        self.btn_xls = QToolButton(self.frame_inputs)
        self.btn_xls.setGeometry(QtCore.QRect(20, 35, 35, 35))
        icon_xls = QIcon()
        icon_xls.addPixmap(QPixmap(resources.ICON_XLS), QIcon.Normal, QIcon.Off)
        self.btn_xls.setIcon(icon_xls)
        self.btn_xls.setIconSize(QtCore.QSize(24, 24))
        self.btn_xls.setCheckable(True)
        self.btn_xls.setAutoExclusive(True)
        self.btn_xls.setObjectName("xls_button")

        # button csv
        self.btn_csv = QToolButton(self.frame_inputs)
        self.btn_csv.setGeometry(QtCore.QRect(60, 35, 35, 35))
        icon_csv = QIcon()
        icon_csv.addPixmap(QPixmap(resources.ICON_CSV), QIcon.Normal, QIcon.Off)
        self.btn_csv.setIcon(icon_csv)
        self.btn_csv.setIconSize(QtCore.QSize(24, 24))
        self.btn_csv.setCheckable(True)
        self.btn_csv.setAutoExclusive(True)
        self.btn_csv.setObjectName("csv_button")

        # checkbox csv with headers
        self.chk_csv_headers = QCheckBox(ui_strings.DATATOOLS_WITH_HEADERS, self.frame_inputs)
        self.chk_csv_headers.setGeometry(QtCore.QRect(100, 45, 110, 15))
        self.chk_csv_headers.setEnabled(False)

        # TextEdit + PushButton (FindFolder)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # lbl sheet name
        self.lbl_file_path = QLabel(self.group_input_file)
        self.lbl_file_path.setGeometry(QtCore.QRect(250, 20, 120, 15))
        self.lbl_file_path.setText(ui_strings.DATATOOLS_SELECT_FILE)

        self.txt_file = QLineEdit(self.group_input_file)
        self.txt_file.setGeometry(QtCore.QRect(250, 35, 160, 20))
        self.txt_file.setReadOnly(True)

        self.btn_path = QPushButton(self.group_input_file)
        self.btn_path.setGeometry(QtCore.QRect(410, 34, 50, 22))
        self.btn_path.setText(ui_strings.DATATOOLS_SELECT_BUTTON)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        # lbl sheet name
        self.lbl_sheet_name = QLabel(self.group_input_file)
        self.lbl_sheet_name.setGeometry(QtCore.QRect(500, 20, 120, 15))
        self.lbl_sheet_name.setText(ui_strings.DATATOOLS_SHEET_NAME)

        # Combobox select sheet - initially does not contain values
        self.cbo_sheet = QComboBox(self.group_input_file)
        self.cbo_sheet.setGeometry(QtCore.QRect(500, 35, 130, 20))

        # data grid to visualize error messages
        self.tbl_errors = QTableWidget(self.central_widget)
        self.tbl_errors.setGeometry(QtCore.QRect(self._left_margin, 420, 660, 100))

        # data grid to visualize those records with errors.
        self.tbl_uploaded_data = QTableWidget(self.central_widget)
        self.tbl_uploaded_data.setGeometry(QtCore.QRect(self._left_margin, 120, 500, 220))

        # group run options
        self.group_run_options = QGroupBox(self.central_widget)
        self.group_run_options.setGeometry(QtCore.QRect(520, 120, 150, 220))
        self.group_run_options.setTitle(ui_strings.DATATOOLS_GROUP_RUN)

        # Errors summary:
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # group summary errors
        self.group_errors = QGroupBox(self.central_widget)
        self.group_errors.setGeometry(QtCore.QRect(self._left_margin, 350, 660, 60))
        self.group_errors.setTitle(ui_strings.DATATOOLS_HEADER_ERRORS)

        # lbl records
        self.lbl_records = QLabel(self.group_errors)
        self.lbl_records.setGeometry(QtCore.QRect(165, 15, 80, 15))
        self.lbl_records.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_records.setText(ui_strings.DATATOOLS_RECORDS)

        self.txt_records = QLineEdit(self.group_errors)
        self.txt_records.setGeometry(QtCore.QRect(165, 30, 80, 20))
        self.txt_records.setAlignment(QtCore.Qt.AlignCenter)
        self.txt_records.setReadOnly(True)

        # lbl errors
        self.lbl_errors = QLabel(self.group_errors)
        self.lbl_errors.setGeometry(QtCore.QRect(275, 15, 80, 15))
        self.lbl_errors.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_errors.setText(ui_strings.DATATOOLS_ERRORS)

        self.txt_errors = QLineEdit(self.group_errors)
        self.txt_errors.setGeometry(QtCore.QRect(275, 30, 80, 20))
        self.txt_errors.setAlignment(QtCore.Qt.AlignCenter)
        self.txt_errors.setReadOnly(True)

        # lbl time
        self.lbl_time = QLabel(self.group_errors)
        self.lbl_time.setGeometry(QtCore.QRect(385, 15, 80, 15))
        self.lbl_time.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_time.setText(ui_strings.DATATOOLS_TIME)

        self.txt_time = QLineEdit(self.group_errors)
        self.txt_time.setGeometry(QtCore.QRect(385, 30, 80, 20))
        self.txt_time.setAlignment(QtCore.Qt.AlignCenter)
        self.txt_time.setReadOnly(True)

        # history button
        self.btn_history = QToolButton(self.group_errors)
        self.btn_history.setGeometry(QtCore.QRect(500, 25, 100, 25))
        icon_history = QIcon()
        icon_history.addPixmap(QPixmap(resources.ICON_HISTORY), QIcon.Normal, QIcon.Off)
        self.btn_history.setIcon(icon_history)
        self.btn_history.setIconSize(QtCore.QSize(20, 20))
        self.btn_history.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
        self.btn_history.setText(ui_strings.DATATOOLS_HISTORY)
        self.btn_history.setCheckable(True)
        self.btn_history.setAutoExclusive(True)
        self.btn_history.setObjectName("history_button")
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        # btn data uploader
        self.btn_data_uploader = QPushButton(ui_strings.DATATOOLS_DATA_UPLOADER, self.group_run_options)
        self.btn_data_uploader.setGeometry(QtCore.QRect(10, 120, 90, 25))
        self.btn_data_uploader.setCheckable(True)
        self.btn_data_uploader.setAutoExclusive(True)
        self.btn_data_uploader.setFlat(False)

        # btn data testing
        self.btn_data_testing = QPushButton(ui_strings.DATATOOLS_DATA_TESTING, self.group_run_options)
        self.btn_data_testing.setEnabled(False)
        self.btn_data_testing.setGeometry(QtCore.QRect(10, 150, 90, 25))
        self.btn_data_testing.setCheckable(True)
        self.btn_data_testing.setAutoExclusive(True)

        # btn data to database
        self.btn_data_db = QPushButton(ui_strings.DATATOOLS_DATA_DB, self.group_run_options)
        self.btn_data_db.setEnabled(False)
        self.btn_data_db.setGeometry(QtCore.QRect(10, 179, 91, 23))
        self.btn_data_db.setCheckable(True)
        self.btn_data_db.setAutoExclusive(True)

        # frame run options
        self.frame_run = QFrame(self.group_run_options)
        self.frame_run.setGeometry(QtCore.QRect(10, 30, 130, 80))
        self.frame_run.setFrameShape(QFrame.StyledPanel)
        self.frame_run.setFrameShadow(QFrame.Raised)

        # option process until first error
        self.rbtn_process_error = QRadioButton(ui_strings.DATATOOLS_PROCESS_ERROR, self.frame_run)
        self.rbtn_process_error.setGeometry(QtCore.QRect(0, 0, 150, 20))

        # option process all data
        self.rbtn_process_all = QRadioButton(ui_strings.DATATOOLS_PROCESS_ALL, self.frame_run)
        self.rbtn_process_all.setGeometry(QtCore.QRect(0, 20, 150, 30))

        # checkbox to filter by records with errors.
        #self.chk_filter_errors = QCheckBox(ui_strings.DATATOOLS_FILTER_ERRORS, self.frame_run)
        #self.chk_filter_errors.setGeometry(QtCore.QRect(0, 50, 100, 15))
        #self.chk_filter_errors.setEnabled(False)

        # icons -> pass - error: Initially are empty labels
        # if not started -> ICON_MINI_WAIT
        # if error -> ICON_DELETE
        # if pass -> ICON_CHECK

        # state icon data uploader
        self.lbl_state_du = QLabel(self.group_run_options)
        self.lbl_state_du.setGeometry(QtCore.QRect(110, 120, 20, 20))
        self.lbl_state_du.setPixmap(QPixmap(resources.ICON_MINI_WAIT))
        self.lbl_state_du.setScaledContents(True)

        # state icon data to database
        self.lbl_state_dt = QLabel(self.group_run_options)
        self.lbl_state_dt.setGeometry(QtCore.QRect(110, 150, 20, 20))
        self.lbl_state_dt.setPixmap(QPixmap(resources.ICON_MINI_WAIT))
        self.lbl_state_dt.setScaledContents(True)

         # state icon data testing
        self.lbl_state_db = QLabel(self.group_run_options)
        self.lbl_state_db.setGeometry(QtCore.QRect(110, 180, 20, 20))
        self.lbl_state_db.setPixmap(QPixmap(resources.ICON_MINI_WAIT))
        self.lbl_state_db.setScaledContents(True)

        # progress bar
        self.progress_bar = QProgressBar(self.central_widget)
        self.progress_bar.setGeometry(QtCore.QRect(self._left_margin, 530, 660, 15))
        self.progress_bar.setMaximum(100)
        self.progress_bar.setProperty("value", 0)
        self.progress_bar.setTextVisible(True)
        self.progress_bar.setOrientation(QtCore.Qt.Horizontal)
        self.progress_bar.setInvertedAppearance(False)
        self.progress_bar.setTextDirection(QProgressBar.TopToBottom)

        self.setCentralWidget(self.central_widget)
Beispiel #16
0
class BookKeeping(QFrame):

    # =======================================================================
    def __init__(self, parent=None, _PARENT=None):

        # -------------------------------------------------------------------
        QFrame.__init__(self, parent);
        # -------------------------------------------------------------------
        self.PARENT                         = _PARENT;
        self.CONF                           = _PARENT.CONF;

        #self.SHA256                         = hashlib.sha256;
        #UID_SHA256 = self.SHA256( str(time.time()) ).hexdigest();
        self.SELECTED_BKKPG_UID             = None;

        # -------------------------------------------------------------------
        self.setGeometry( 3, 5, 975, 555 );
        self.setStyleSheet( "QFrame{ font: 12px 'monospace'; color: #000; background-color: transparent; background-image: url('./data/imgs/TAB_BookKeeping.png'); }" );

        self.PAIR_COMBO                     = QComboBox( self);
        self.PAIR_COMBO.setGeometry( 86, 20, 108, 44 ); 
        self.connect( self.PAIR_COMBO, SIGNAL('currentIndexChanged(int)'), self.CREATE_LISTS );
        #self.PAIR_COMBO.setStyleSheet( "QComboBox{ font: 16px 'monospace'; background-color: #333; color: #FFF; border-style: solid; border-width: 1px; border-color: #000; border-radius: none; }" );
        self.PAIR_COMBO.setEditable(False);

        """
        #self.PAIR_COMBO.setItemIcon( 0, QIcon("./data/imgs/500.png") );
        print(self.PAIR_COMBO.__len__());
        #set at tooltip
        combo.setItemData(0,"a tooltip",Qt.ToolTipRole)
        # set the Font Color
        combo.setItemData(0,QColor("#FF333D"), Qt.BackgroundColorRole)
        #set the font
        combo.setItemData(0, QtGui.QFont('Verdana', bold=True), Qt.FontRole)
        """

        # -------------------------------------------------------------------
        list_style                          = "QListWidget{ font: 10px 'monospace'; color: #fff;  background-color: #000; border-style: none; background-image: url('./data/imgs/TAB_BookKeeping_line.png'); }"; # ./data/imgs/BookKeeping_line.png
        lable_style                         = "QLabel{ font: 10px 'monospace'; color: #fff;  background-color: transparent; border-style: none; background-image: url(''); }"; 

        # -------------------------------------------------------------------
        self.DATA_TO_SEND                   = None;
        self._i_                            = "|"; # List delimiter
        self.CALCULATE_ONLY_COMPLETED       = True;
        self.DATA_TO_SEND_SELECTED          = False;
        
        # -------------------------------------------------------------------
        self.BOOKKEEPING_WIDGET             = QListWidget( self );
        self.BOOKKEEPING_WIDGET.setGeometry( 13, 144, 949, 259 );
        self.BOOKKEEPING_WIDGET.setStyleSheet( list_style );

        self.connect( self.BOOKKEEPING_WIDGET, SIGNAL('itemSelectionChanged()'), lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SOLD_WIDGET") );
        self.BOOKKEEPING_WIDGET.itemClicked.connect( lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SELECT_VALUES") );


        self.BOUGHT_TTL_LABLE               = QLabel("0.0", self);
        self.BOUGHT_TTL_LABLE.setGeometry( 304, 406, 85, 17 );
        #self.BOUGHT_TTL_LABLE.setEditable( False );
        self.BOUGHT_TTL_LABLE.setStyleSheet( lable_style );
        self.BOUGHT_TTL                     = 0;

        self.BOUGHT_TTL_PLUS_FEE_LABLE      = QLabel("0.0", self);
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setGeometry( 396, 406, 85, 17 );
        #self.BOUGHT_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.BOUGHT_TTL_PLUS_FEE_LABLE.setStyleSheet( lable_style );
        self.BOUGHT_TTL_PLUS_FEE            = 0;


        self.SOLD_TTL_LABLE                 = QLabel("0.0", self);
        self.SOLD_TTL_LABLE.setGeometry( 694, 406, 85, 17 );
        #self.SOLD_TTL_LABLE.setEditable( False );
        self.SOLD_TTL_LABLE.setStyleSheet( lable_style );
        self.SOLD_TTL                       = 0;

        self.SOLD_TTL_PLUS_FEE_LABLE        = QLabel("0.0", self);
        self.SOLD_TTL_PLUS_FEE_LABLE.setGeometry( 784, 406, 85, 17 );
        #self.SOLD_TTL_PLUS_FEE_LABLE.setEditable( False );
        self.SOLD_TTL_PLUS_FEE_LABLE.setStyleSheet( lable_style );
        self.SOLD_TTL_PLUS_FEE              = 0;

        self.PROFIT_TTL_LABLE               = QLabel("0.0", self);
        self.PROFIT_TTL_LABLE.setGeometry( 874, 406, 88, 17 );
        #self.PROFIT_TTL_LABLE.setEditable( False );
        self.PROFIT_TTL_LABLE.setStyleSheet( lable_style );
        self.PROFIT_TTL                     = 0;

        # -------------------------------------------------------------------
        self.SEND_ID_LABLE                  = QLabel("n/a", self);
        self.SEND_ID_LABLE.setGeometry( 18, 467, 43, 17 );
        self.SEND_ID_LABLE.setStyleSheet( lable_style );

        self.SEND_AMOUNT_LABLE              = QLabel("n/a", self);
        self.SEND_AMOUNT_LABLE.setGeometry( 66, 467, 85, 17 );
        self.SEND_AMOUNT_LABLE.setStyleSheet( lable_style );

        self.SEND_AT_PRICE_LABLE            = QLabel("n/a", self);
        self.SEND_AT_PRICE_LABLE.setGeometry( 156, 467, 43, 17 );
        self.SEND_AT_PRICE_LABLE.setStyleSheet( lable_style );

        self.SEND_VALUES_BTN                = QPushButton("", self); 
        self.SEND_VALUES_BTN.setGeometry( 60, 502, 131, 33 );
        self.SEND_VALUES_BTN.setStyleSheet( "QPushButton{ background-color: transparent; border-style: none; }" ); 
        self.connect( self.SEND_VALUES_BTN, SIGNAL('clicked()'), lambda: self.SEND_VALUES_TO_TRADE_TERMINAL("SEND_VALUES") );

        # -------------------------------------------------------------------
        self.ONLY_COMPLETED_CHECKBOX        = QCheckBox("", self);
        self.ONLY_COMPLETED_CHECKBOX.setGeometry( 665, 444, 17, 17 );
        self.ONLY_COMPLETED_CHECKBOX.setCheckState(Qt.Checked);
        #self.ONLY_COMPLETED_CHECKBOX.setEnabled(False);
        self.connect(self.ONLY_COMPLETED_CHECKBOX, SIGNAL('stateChanged(int)'), lambda: self.CHANGE_VALUES("only_completed") );

        # -------------------------------------------------------------------
        self.INIT();
        # -------------------------------------------------------------------

    # =======================================================================
    def INIT(self):

        # -------------------------------------------------------------------
        try:

            self.CREATE_PAIRS_SELECTOR();
            self.CREATE_LISTS();

        except Exception as _exception:

            print("-----------------------------------------------------");
            print("[INIT]"+str(_exception));
        # -------------------------------------------------------------------

    # =======================================================================
    def BKKPG_UID_ACTION(self, _ACTION, BKKPG_UID, _D):

        # -------------------------------------------------------------------
        #print("_ACTION: ", _ACTION, "BKKPG_UID: ", BKKPG_UID)
        # -------------------------------------------------------------------
        try:

            CURR_PAIR =  str(self.PAIR_COMBO.currentText()).lower().strip();

            order_id    = _D[0];
            unix_time   = _D[1];
            filled      = _D[2];
            amount      = _D[3];
            at_price    = _D[4];

            if _ACTION == "buy":

                # For CRYPTO
                ttl = amount;
                fee = ( ttl/100*self.PARENT.FEE );
            
            elif _ACTION == "sell":

                # For USD
                ttl = amount*at_price;
                fee = ( ttl/100*self.PARENT.FEE );

            grand_ttl = ttl-fee;

            # -------------------------------------------------------------------
            if BKKPG_UID == "": # Is New Record

                TPL = "buy_order_id, buy_unix_time, buy_filled, buy_amount, buy_at_price, buy_fee, buy_ttl, buy_grand_ttl, sell_order_id, sell_unix_time, sell_filled, sell_amount, sell_at_price, sell_fee, sell_ttl, sell_grand_ttl ";
                
                _SQL = "INSERT INTO "+CURR_PAIR+"( BKKPG_UID, completed, started, "+TPL+", profit_ttl ) ";

                if _ACTION == "buy":
                    _SQL += "VALUES( NULL,0,1,{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}, 0 )".format( _D[0],_D[1],_D[2],_D[3],_D[4],fee, ttl, grand_ttl, 0, 0, 0, 0, 0, 0, 0, 0 );

                else:
                    _SQL += "VALUES( NULL,0,1,{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}, 0 )".format( 0, 0, 0, 0, 0, 0, 0, 0, _D[0], _D[1],_D[2],_D[3],_D[4],fee, ttl, grand_ttl );


                self.PARENT.DB.EXEC("BOOK_DB", _SQL);

            else: # Existing Record

                # ------------------------------------------------
                if filled == 1:

                    completed = 1;

                    _SQL = "SELECT ACT_grand_ttl from "+CURR_PAIR+" WHERE BKKPG_UID="+BKKPG_UID;
                    
                    if _ACTION == "buy":

                        DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL.replace("ACT","sell"), ALL=False);
                        profit_ttl = DATA - grand_ttl;

                    else:

                        DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL.replace("ACT","buy"), ALL=False);
                        profit_ttl = grand_ttl - DATA;
                else:
                    profit_ttl = 0;
                    completed = 0;

                # ------------------------------------------------
                A = _ACTION;
                
                _SQL = "UPDATE "+CURR_PAIR+" SET completed={0}, "+A+"_order_id={1}, "+A+"_unix_time={2}, "+A+"_filled={3}, ";
                _SQL += A+"_amount={4}, "+A+"_at_price={5}, "+A+"_fee={6}, "+A+"_ttl={7}, "+A+"_grand_ttl={8}";
                _SQL += " WHERE BKKPG_UID="+BKKPG_UID;

                _SQL = _SQL.format( completed, order_id, unix_time, filled, amount, at_price, fee, ttl, grand_ttl );

                self.PARENT.DB.EXEC("BOOK_DB", _SQL);

        except Exception as _exception:

            print(" BOOKKEEPING[0:0]");
            print(_exception);
        # -------------------------------------------------------------------
        """
        BKKPG_UID, completed, started, 
        
        buy_order_id, buy_unix_time, buy_filled, buy_amount, buy_at_price, buy_fee, buy_ttl, buy_grand_ttl, 
        sell_order_id, sell_unix_time, sell_filled, sell_amount, sell_at_price, sell_fee, sell_ttl, sell_grand_ttl, 
        
        profit_ttl
        """
        # -------------------------------------------------------------------

    # =======================================================================
    def DELETE_ORDER(self, _order_id, _pair, _type):

        # -------------------------------------------------------------------

        _SQL = "SELECT buy_order_id, sell_order_id FROM "+_pair;
        _SQL += " WHERE buy_order_id="+str(_order_id)+" OR sell_order_id="+str(_order_id);

        DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL, ALL=False);

        if DATA is None:
            pass;

        if _type == "buy" and DATA[1] == 0:

            _SQL = "DELETE FROM "+_pair+" WHERE buy_order_id="+str(_order_id)+" OR sell_order_id="+str(_order_id);
            self.PARENT.DB.EXEC("BOOK_DB", _SQL);
            self.CREATE_LISTS();

        elif _type == "sell" and DATA[0] == 0:

            _SQL = "DELETE FROM "+_pair+" WHERE buy_order_id="+str(_order_id)+" OR sell_order_id="+str(_order_id);
            self.PARENT.DB.EXEC("BOOK_DB", _SQL);
            self.CREATE_LISTS();

        else:

            A = _type;

            _SQL = "UPDATE "+self.PARENT.CURR_PAIR+" SET ";
            _SQL += " completed=0, "+A+"_order_id=0, "+A+"_unix_time=0, "+A+"_filled=0, ";
            _SQL += A+"_amount=0, "+A+"_at_price=0, "+A+"_fee=0, "+A+"_ttl=0, "+A+"_grand_ttl=0 ";
            _SQL += "WHERE "+A+"_order_id="+str(_order_id);

            self.PARENT.DB.EXEC("BOOK_DB", _SQL);

        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_LISTS(self):

        # -------------------------------------------------------------------
        try:
            CURR_PAIR =  str(self.PAIR_COMBO.currentText()).lower();

            # -------------------------------------------------------------------
            self.BOOK = { "bought" : [], "sold" : [] };

            self.BOUGHT_TTL = 0;
            self.BOUGHT_TTL_PLUS_FEE = 0;

            self.SOLD_TTL = 0;
            self.SOLD_TTL_PLUS_FEE = 0;

            # -------------------------------------------------------------------
            #self.PARENT.DB.EXEC( "BOOK_DB", "DELETE FROM "+CURR_PAIR+" WHERE BKKPG_UID>7" );

            DATA = self.PARENT.DB.FETCH("BOOK_DB", "SELECT * FROM "+CURR_PAIR+" ORDER BY BKKPG_UID DESC", ALL=True);
            self.BOOKKEEPING_WIDGET.clear();

            for data in DATA:

                # ---------------------------------------------------------------
                """ " "" 
                print( data )
                for d in data:
                    print( d )
                exit();
                "" " """ 
                # ---------------------------------------------------------------
                # In-Memory DATA
                BKKPG_UID       = data[0]
                completed       = data[1]
                started         = data[2]

                buy_order_id    = data[3]
                buy_unix_time   = data[4]
                buy_filled      = data[5]
                buy_amount      = data[6]
                buy_at_price    = data[7]
                #buy_fee         = data[8]
                buy_ttl         = data[9]
                buy_grand_ttl   = data[10]

                sell_order_id   = data[11]
                sell_unix_time  = data[12]
                sell_filled     = data[13]
                sell_amount     = data[14]

                sell_at_price   = data[15]
                #sell_fee        = data[16]
                sell_ttl        = data[17]
                sell_grand_ttl  = data[18]

                profit_ttl      = data[19]

                # ---------------------------------------------------------------

                # ---------------------------------------------------------------
                """
                self.BOOK[ data[3] ].append( {
                                            
                                        BKKPG_UID,
                                        completed,
                                        started,

                                        buy_order_id,
                                        buy_unix_time,
                                        buy_filled,
                                        buy_amount,
                                        buy_at_price,
                                        buy_fee,
                                        buy_ttl,
                                        buy_grand_ttl,

                                        sell_order_id,
                                        sell_unix_time,
                                        sell_filled,
                                        sell_amount,
                                        sell_at_price,
                                        sell_fee,
                                        sell_ttl,
                                        sell_grand_ttl,

                                        profit_ttl

                                            } );

                """
                # ---------------------------------------------------------------
                if self.CALCULATE_ONLY_COMPLETED:

                    if buy_filled == 1 and sell_filled == 1:

                        self.BOUGHT_TTL += buy_ttl;
                        self.BOUGHT_TTL_PLUS_FEE += buy_grand_ttl*buy_at_price;

                        self.SOLD_TTL += sell_ttl;
                        self.SOLD_TTL_PLUS_FEE += sell_grand_ttl;

                else:

                    self.BOUGHT_TTL += buy_ttl;
                    self.BOUGHT_TTL_PLUS_FEE += buy_grand_ttl*buy_at_price;

                    self.SOLD_TTL += sell_ttl;
                    self.SOLD_TTL_PLUS_FEE += sell_grand_ttl;


                self.PROFIT_TTL_LABLE.setText( "{:10,.6f}".format(self.SOLD_TTL_PLUS_FEE - self.BOUGHT_TTL_PLUS_FEE) );


                # ---------------------------------------------------------------
                # Formating data to Display in BookKeeping Wodget

                item = "";

                item += "DEL{:7} ".format(str( BKKPG_UID )); # id

                # BUY / BOUGHT
                item += "#{:11} DEL".format( str(buy_order_id) ); # order_id
                item += "{:4} DEL".format( str(buy_filled) ); # filed
                item += "{:13} DEL".format( str("{:10,.6f}".format( float(buy_amount) )).strip() ); # Amount
                item += "{:13} DEL".format( str("{:10,.6f}".format( buy_at_price )).strip() ); # at_price
                #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
                #item += "{:13} DEL".format( str("{:10,.6f}".format( buy_ttl )).strip() ); # ttl
                item += "{:14} ".format( str("{:10,.6f}".format( buy_grand_ttl )).strip() ); # grand_ttl

                # SELL / SOLD
                item += "#{:11} DEL".format( str(sell_order_id) ); # order_id
                item += "{:4} DEL".format( str(sell_filled) ); # filed
                item += "{:13} DEL".format( str("{:10,.6f}".format( sell_amount )).strip() ); # Amount
                item += "{:13} DEL".format( str("{:10,.6f}".format( sell_at_price )).strip() ); # at_price
                #item += "{:13} DEL".format( str("{:10,.6f}".format( data[7] )).strip() ); # fee
                #item += "{:13} DEL".format( str("{:10,.6f}".format( sell_ttl )).strip() ); # ttl
                item += "{:14} ".format( str("{:10,.6f}".format( sell_grand_ttl )).strip() ); # grand_ttl
                
                # PROFIT
                item += "{:13}".format( str("{:10,.6f}".format( profit_ttl )).strip() ); # grand_ttl

                newItem = QListWidgetItem( QIcon("./data/imgs/icon_filled_status_0.png"), item.replace("DEL", self._i_), self.BOOKKEEPING_WIDGET, 0);
                #newItemToolTip = "Order ID: #"+str()+" Created: "+time.ctime(int(data[2]));
                #newItem.setToolTip(newItemToolTip);

                # ---------------------------------------------------------------

            # / for
            # -------------------------------------------------------------------
            try: 
                self.BOUGHT_TTL_LABLE.setText( str("{:10,.6f}".format( self.BOUGHT_TTL ).strip()) );
                self.BOUGHT_TTL_PLUS_FEE_LABLE.setText( str("{:10,.6f}".format( self.BOUGHT_TTL_PLUS_FEE ).strip()) );

                self.SOLD_TTL_LABLE.setText( str("{:10,.6f}".format( self.SOLD_TTL ).strip()) );
                self.SOLD_TTL_PLUS_FEE_LABLE.setText( str("{:10,.6f}".format( self.SOLD_TTL_PLUS_FEE ).strip()) );

            except Exception as e:
                print("BOOKKEEPING[3:0]"+str(e))


        except Exception as _exception:

            print(" BOOKKEEPING[1:0]");
            print(_exception);
        # -------------------------------------------------------------------

    # =======================================================================
    def RESET_BKKPG_UID(self):

        # -------------------------------------------------------------------
        #CURR_PAIR =  str(self.PAIR_COMBO.currentText()).lower();
        self.PARENT.GUI.BKKPG_UID_VALUE.setText("");
        self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "show");
        self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "show");
        # -------------------------------------------------------------------

    # =======================================================================
    def CHANGE_VALUES(self, _this):

        # -------------------------------------------------------------------
        if _this == "only_completed":
            if self.ONLY_COMPLETED_CHECKBOX.isChecked():
                self.CALCULATE_ONLY_COMPLETED = True;
            else:
                self.CALCULATE_ONLY_COMPLETED = False;

        # -------------------------------------------------------------------
        self.CREATE_LISTS();
        # -------------------------------------------------------------------

    # =======================================================================
    def CREATE_PAIRS_SELECTOR(self, ALL=False):

        # -------------------------------------------------------------------
        if not ALL:
            for PAIR in self.CONF["API"]["PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper());

        else:
            for PAIR in self.CONF["API"]["ALL_PAIRS"]:
                self.PAIR_COMBO.addItem(PAIR.upper());

        for i in xrange(0, self.PAIR_COMBO.__len__()):

            self.PAIR_COMBO.setItemData( i, QColor("#333"),Qt.BackgroundRole );
            self.PAIR_COMBO.setItemData( i, QColor("#fff"),Qt.ForegroundRole );
            #self.PAIR_COMBO.setItemData( i, QFont('monospace', 16, -1, False), Qt.FontRole);
        # -------------------------------------------------------------------

    # =======================================================================
    def SEND_VALUES_TO_TRADE_TERMINAL(self, _action):

        # -------------------------------------------------------------------
        if _action == "SELECT_VALUES":

            self.DATA_TO_SEND_SELECTED = True;
            #self.DATA_TO_SEND = [ str(item).stip() for iten in str(self.BOOKKEEPING_WIDGET.currentItem().text()).strip().split("|")];
            self.DATA_TO_SEND = str(self.BOOKKEEPING_WIDGET.currentItem().text()).strip().split("|")[1].split("#")[0].strip();

        elif _action == "SEND_VALUES":

            if self.DATA_TO_SEND_SELECTED:

                _SQL = "SELECT buy_order_id, sell_order_id FROM "+self.PARENT.CURR_PAIR;
                _SQL += " WHERE BKKPG_UID="+self.DATA_TO_SEND;

                DATA = self.PARENT.DB.FETCH("BOOK_DB", _SQL, ALL=False);

                if DATA[0] != 0 and DATA[1] != 0:

                    self.PARENT.GUI.SHOW_QMESSAGE("info", "This UID is Full!<br> You can't add data to it enymore.<br>Bud You can delete sell and/or buy part<br/> and add new part.");
                    return;

                self.PARENT.GUI.BKKPG_UID_VALUE.setText( self.DATA_TO_SEND );

                self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "show");
                self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "show");

                self.DATA_TO_SEND_SELECTED = False;
                self.DATA_TO_SEND = None;

                # Clear Lables 
                self.SEND_ID_LABLE.setText( "n/a" );
                self.SEND_AMOUNT_LABLE.setText( "n/a" );
                self.SEND_AT_PRICE_LABLE.setText( "n/a" );


                if DATA[0] == 0:
                    self.PARENT.GUI.CONTROL_TRADINGS_BTNS("sell", "hide");

                else:
                    self.PARENT.GUI.CONTROL_TRADINGS_BTNS("buy", "hide");


                # Switch to Trader-Tab
                self.PARENT.GUI.MAIN_TABS.setCurrentIndex(0);

            else:

                self.PARENT.GUI.SHOW_QMESSAGE("info", " Select first item which one you would like<br/> send to the Trade-Terminal !");
                return; 
                
        # -------------------------------------------------------------------
        if self.DATA_TO_SEND is not None:
    
            self.SEND_ID_LABLE.setText( self.DATA_TO_SEND );
class GUI(QWidget):
    def __init__(self, parent=None):
        global f
        f = open(filename, "a")
        f.write("Widget init.\n")
        f.close()
        QWidget.__init__(self, parent, Qt.WindowStaysOnTopHint)
        self.__setup_gui__(self)
        self._flag = False
        self._change = False
        f = open(filename, "a")
        f.write("End of widget init.\n")
        f.close()

    def closeEvent(self, event):
        reply = QMessageBox.question(self, "Confirm",
                                     "Are you sure You want to quit?",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes: event.accept()
        else: event.ignore()

    def __setup_gui__(self, Dialog):
        global f
        f = open(filename, "a")
        f.write("Setup of gui.\n")
        f.close()
        Dialog.setObjectName("Dialog")
        Dialog.resize(270, 145)
        self.setWindowTitle("Map Layer")
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)
        self.Render = QPushButton("Render", Dialog)
        self.Render.setGeometry(QRect(85, 90, 100, 25))
        self.Render.setObjectName("Render")
        self.comboBox = QComboBox(Dialog)
        self.comboBox.setGeometry(QRect(100, 34, 115, 18))
        self.comboBox.setEditable(False)
        self.comboBox.setMaxVisibleItems(11)
        self.comboBox.setInsertPolicy(QComboBox.InsertAtBottom)
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItems([
            "Google Roadmap", "Google Terrain", "Google Satellite",
            "Google Hybrid", "Yahoo Roadmap", "Yahoo Satellite",
            "Yahoo Hybrid", "Bing Roadmap", "Bing Satellite", "Bing Hybrid",
            "Open Street Maps"
        ])
        self.comboBox.setCurrentIndex(10)
        self.label1 = QLabel("Source:", Dialog)
        self.label1.setGeometry(QRect(55, 35, 35, 16))
        self.label1.setObjectName("label1")
        self.slider = QSlider(Dialog)
        self.slider.setOrientation(Qt.Horizontal)
        self.slider.setMinimum(1)
        self.slider.setMaximum(12)
        self.slider.setValue(4)
        self.slider.setGeometry(QRect(110, 61, 114, 16))
        self.label2 = QLabel("Quality: " + str(self.slider.value()), Dialog)
        self.label2.setGeometry(QRect(47, 61, 54, 16))
        self.label2.setObjectName("label2")
        self.doubleSpinBox = QDoubleSpinBox(Dialog)
        self.doubleSpinBox.setGeometry(QRect(160, 5, 40, 20))
        self.doubleSpinBox.setDecimals(0)
        self.doubleSpinBox.setObjectName("doubleSpinBox")
        self.doubleSpinBox.setMinimum(10.0)
        self.doubleSpinBox.setValue(20.0)
        self.doubleSpinBox.setEnabled(False)
        self.checkBox = QCheckBox("Auto refresh", Dialog)
        self.checkBox.setGeometry(QRect(50, 6, 100, 20))
        self.checkBox.setLayoutDirection(Qt.RightToLeft)
        self.checkBox.setObjectName("checkBox")
        self.progressBar = QProgressBar(Dialog)
        self.progressBar.setGeometry(QRect(5, 130, 260, 10))
        self.progressBar.setProperty("value", 0)
        self.progressBar.setTextVisible(False)
        self.progressBar.setObjectName("progressBar")
        self.progressBar.setVisible(False)
        QObject.connect(self.Render, SIGNAL("clicked()"), Dialog.__repaint__)
        QMetaObject.connectSlotsByName(Dialog)
        QObject.connect(self.slider, SIGNAL("valueChanged(int)"),
                        self.__update_slider_label__)
        QObject.connect(self.comboBox, SIGNAL("activated(int)"),
                        self.__combobox_changed__)
        self.timerRepaint = QTimer()
        QObject.connect(self.checkBox, SIGNAL("clicked()"),
                        self.__activate_timer__)
        QObject.connect(self.timerRepaint, SIGNAL("timeout()"),
                        self.__on_timer__)
        f = open(filename, "a")
        f.write("End of setup of gui.\n")
        f.close()

    def __combobox_changed__(self):
        self._change = True

    def __activate_timer__(self):
        self.doubleSpinBox.setEnabled(self.checkBox.isChecked())
        if self.checkBox.isChecked():
            self.timerRepaint.start(self.doubleSpinBox.value() * 1000)
            self.Render.setEnabled(False)
            if _progress == 0: self.__repaint__()
        else:
            self.timerRepaint.stop()
            self.Render.setEnabled(True)

    def __get_net_size__(self):
        global f
        f = open(filename, "a")
        f.write("Geting net size...\n")
        f.close()
        if not os.path.exists(Paths["Screenshot"]):
            Visum.Graphic.Screenshot(Paths["Screenshot"])
        size = Image.open(Paths["Screenshot"]).size
        f = open(filename, "a")
        f.write("Read net size:" + str(size) + ".\n")
        f.close()
        return size

    def __on_timer__(self):
        global _paramGlobal
        self._flag = False
        Visum.Graphic.MaximizeNetWindow()
        param = _paramGlobal
        _paramGlobal = Visum.Graphic.GetWindow()
        shift = abs((param[0] - _paramGlobal[0]) / (param[2] - param[0]))
        zoom = abs((param[2] - param[0]) /
                   (_paramGlobal[2] - _paramGlobal[0]) - 1)
        print _windowSizeGlobal
        if _windowSizeGlobal[2:4] != Visum.Graphic.GetMainWindowPos()[2:4]:
            self.__get_net_size__()
            self._flag = True
        elif shift > 0.4 or zoom > 0.2:
            self._flag = True
        if self._flag or self._change and _progress == 0:
            self.__repaint__()
            self._change = False

    def __update_slider_label__(self, value):
        self.label2.setText("Quality: " + str(value))
        self._change = True

    def __update_progress_bar__(self):
        if _progress != 0:
            self.progressBar.setVisible(True)
            self.progressBar.setValue(_progress)
        else:
            self.progressBar.setVisible(False)

    def __rebuild_paths__(self):
        global Paths
        Paths["Images"] = []
        list = os.listdir(Paths["ScriptFolder"])
        imageList = []
        for i in range(len(list)):
            if list[i][-3:] == "png": imageList.append(list[i])
        for i in range(len(imageList)):
            try:
                Visum.Graphic.Backgrounds.ItemByKey(imageList[i])
                Paths["Images"].append(Paths["ScriptFolder"] + "\\" +
                                       imageList[i])
            except:
                pass

    def __repaint__(self):
        global _progress, f
        if len(Visum.Graphic.Backgrounds.GetAll) != len(Paths["Images"]):
            self.__rebuild_paths__()
        if _progress == 0:
            f = open(filename, "a")
            f.write("Doing repaint...\n")
            f.close()
            QWebSettings.clearMemoryCaches()
            timer = QTimer()
            timer.start(100)
            QObject.connect(timer, SIGNAL("timeout()"),
                            self.__update_progress_bar__)
            Main(self.comboBox.currentIndex(), Visum.Graphic.GetWindow(),
                 self.slider.value() / 4.0, self.__get_net_size__())
        Visum.Graphic.Draw()
        self.__update_progress_bar__()
        _progress = 0
        QTimer().singleShot(1500, self.__update_progress_bar__)
        f = open(filename, "a")
        f.write("End of doing repaint.\n")
        f.close()
Beispiel #18
0
class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.init_UI()

    def init_UI(self):
        self.save_folder = ""
        self.box = ""
        self.all_data, self.curr_data = self.readfile()
        self.setFixedSize(1200, 950)
        self.dates()
        self.info()
        self.buttons()
        self.sim_list()
        self.curr_list()
        self.add_plot()
        self.log_flag = False
        self.setWindowTitle("SIMULATION TOOL")
        self.error = False
        self.error_box()


#    self.radio_buttons()

    """UI FUNCTIONS"""
    def paintEvent(self, event):
        lines = QtGui.QPainter(self)
        #    pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine)
        #    lines.setPen(pen)
        lines.begin(self)
        lines.drawRect(20, 20, 230, 110)
        lines.drawRect(250, 20, 340, 110)
        lines.drawRect(620, 20, 560, 110)
        lines.drawRect(10, 10, 1180, 930)
        lines.drawRect(10, 149, 1180, 701)
        lines.end()

    def info(self):  #Create a label where trades stats can be appended
        self.stats_info = QtGui.QLabel(self)
        self.stats_info.setGeometry(20, 860, 300, 80)
        self.stats_info.setText("")

        self.brute_lab = QtGui.QLabel(self)
        self.brute_lab.setGeometry(300, 870, 300, 60)
        self.brute_lab.setText("")

    def error_box(self):
        self.errb = QCheckBox("Error checking", self)
        self.errb.setGeometry(1080, 20, 100, 90)
        self.errb.setChecked(False)
        self.errb.stateChanged.connect(self.error_truth)

    def dates(self):  #Create date input boxes
        self.from_lab = QtGui.QLabel(self)
        self.from_lab.setGeometry(30, 30, 71, 16)
        self.from_lab.setText('Date from')
        self.from_edit = QtGui.QLineEdit(self)
        self.from_edit.setGeometry(30, 50, 61, 20)
        self.from_edit.setPlaceholderText('20170101')
        self.to_lab = QtGui.QLabel(self)
        self.to_lab.setGeometry(120, 30, 71, 16)
        self.to_lab.setText('Date to')
        self.to_edit = QtGui.QLineEdit(self)
        self.to_edit.setGeometry(120, 50, 61, 20)
        self.to_edit.setPlaceholderText('20170630')

    def sim_list(self):  #Create list of indices
        self.cb = QComboBox(self)
        self.cb.addItems(list(self.all_data.columns))
        self.cb.currentIndexChanged.connect(self.plot_chart)
        self.cb.setGeometry(140, 80, 100, 40)

    def curr_list(self):  #Create list of currrncies
        self.cl = QComboBox(self)
        self.cl.addItems(list(self.curr_data.columns))
        self.cl.setGeometry(30, 80, 100, 40)

    def buttons(self):  #Create all buttons and connect to appropiate functions

        #Row 1 starts

        self.a = QtGui.QPushButton('IMPLEMENT STRAT', self)
        self.a.clicked.connect(self.tester)
        self.a.setGeometry(260, 30, 100, 40)

        self.mov = QtGui.QPushButton('Derivative', self)
        self.mov.clicked.connect(self.deriv_strat)
        self.mov.setGeometry(370, 30, 100, 40)

        self.mov = QtGui.QPushButton('Moving Average', self)
        self.mov.clicked.connect(self.moving_average)
        self.mov.setGeometry(480, 30, 100, 40)

        #Row 2 strats

        self.b = QtGui.QPushButton('IMPLEMENT STRAT', self)
        self.b.clicked.connect(self.tester)
        self.b.setGeometry(260, 80, 100, 40)

        self.gc = QtGui.QPushButton('Golden Cross', self)
        self.gc.clicked.connect(self.gd)
        self.gc.setGeometry(370, 80, 100, 40)

        self.mr = QtGui.QPushButton('Mean Reversal', self)
        self.mr.clicked.connect(self.mean_reversion)
        self.mr.setGeometry(480, 80, 100, 40)

        #Row 1 funcs

        self.mavg = QtGui.QPushButton('Moving Average\nIndex', self)
        self.mavg.clicked.connect(self.plot_mov_avg)
        self.mavg.setGeometry(630, 30, 100, 40)

        self.log = QtGui.QPushButton('Scale', self)
        self.log.clicked.connect(self.log_scale)
        self.log.setGeometry(740, 30, 100, 40)

        self.repl = QtGui.QPushButton('Reset', self)
        self.repl.clicked.connect(self.plot_chart)
        self.repl.setGeometry(850, 30, 100, 40)

        self.sf = QtGui.QPushButton('Save Figure', self)
        self.sf.clicked.connect(self.save_fig)
        self.sf.setGeometry(960, 30, 100, 40)

        #Row 2 funcs

        self.opt = QtGui.QPushButton('Optimal\nMoving Average', self)
        self.opt.clicked.connect(self.brutefor)
        self.opt.setGeometry(630, 80, 100, 40)

        self.cur = QtGui.QPushButton('Currency\nPerformance', self)
        self.cur.clicked.connect(self.currperf)
        self.cur.setGeometry(740, 80, 100, 40)

        self.plot = QtGui.QPushButton('Plot', self)
        self.plot.clicked.connect(self.plot_chart_diff_curr)
        self.plot.setGeometry(850, 80, 100, 40)

        self.sf = QtGui.QPushButton('Save Folder', self)
        self.sf.clicked.connect(self.set_save_folder)
        self.sf.setGeometry(960, 80, 100, 40)

    """PLOTTING FUNCTIONS"""

    def plot_stats(self, ml):  #Fetch trade stats and write to UI
        print(ml)
        trades = int(ml[0])
        avg = int(ml[1])
        maxval = int(ml[2])
        minval = int(ml[3])
        med = int(ml[4])
        text = "Amount of trades: %.1f \nAverage amount of days between trades: %.1f \nMedian amount of days between trades: %.1f \nLongest period of days between trades: %.1f \nShortest amount of days between trades: %.1f" % (
            trades, med, avg, maxval, minval)
        print(self.error)
        if self.error:
            errnum = ml[5]
            text2 = "\nAmount of error trades: %d" % errnum
            text = text + text2
            print(text)
        self.stats_info.setText(text)

    def add_plot(self):  #Intialise matplotlib in the UI
        currency = self.cl.currentText()
        index = self.cb.currentText()
        self.figure = Figure()  #Create fig
        self.canvas = FigureCanvasQTAgg(self.figure)
        self.canvas.setParent(self)
        self.canvas.setGeometry(11, 150, 1179, 700)
        self.axis = self.figure.add_subplot(111)
        self.axis.set_xlabel("")
        self.axis.legend(loc=2)
        to_plot = self.all_data[
            self.cb.currentText()]  #Plotting data is first item in list

        to_plot = self.reindex(to_plot)  #Plot from 100
        self.first_date = to_plot.index[
            0]  #Set universal variable for currency plotting

        text = index + " " + currency
        self.plotter(to_plot, text)  #Plot

    def plot_strat(self, to_plot,
                   name):  #Plot each individual strategy (E.g movin avg)
        currency = self.cl.currentText()
        to_plot = self.date_cut(to_plot)
        to_plot = self.to_series(to_plot)
        to_plot = self.reindex(to_plot)
        text = name + " " + currency
        self.plotter(to_plot, text)

    def plot_chart(self):  #Plot a new base chart and clear everything
        self.cl.setCurrentIndex(0)
        currency = self.cl.currentText()
        column = self.cb.currentText()
        all_curr_data = self.curr_data[currency]
        to_plot = self.all_data[column]
        to_plot = to_plot.dropna()

        to_plot = self.date_cut(to_plot)
        all_curr_data = self.date_cut(all_curr_data)

        to_plot = self.to_series(to_plot)
        all_curr_data = self.to_series(all_curr_data)
        to_plot = to_plot.div(all_curr_data)

        to_plot = self.reindex(to_plot)
        self.first_date = to_plot.index[0]

        self.axis.clear()
        text = column + " " + currency
        self.plotter(to_plot, text)
        self.stats_info.setText("")

    def plot_chart_diff_curr(self):  #Plot base chart in a different curenncy
        currency = self.cl.currentText()
        column = self.cb.currentText()
        all_curr_data = self.curr_data[currency]
        to_plot = self.all_data[column]
        to_plot = to_plot.dropna()
        to_plot = self.date_cut(to_plot)
        all_curr_data = self.date_cut(all_curr_data)
        to_plot = self.to_series(to_plot)
        all_curr_data = self.to_series(all_curr_data)

        to_plot = to_plot.div(all_curr_data)

        to_plot = self.reindex(to_plot)

        text = column + " " + currency
        self.plotter(to_plot, text)

    def currperf(self):
        currency = self.cl.currentText()
        curr = self.curr_data[currency]
        to_plot = curr
        to_plot = self.date_cut(to_plot)
        to_plot = to_plot.truncate(before=self.first_date)
        to_plot = self.reindex(to_plot)
        text = "USD : " + currency
        self.plotter(to_plot, text)

    def plot_mov_avg(self):
        currency = self.cl.currentText()
        curr = self.curr_data[currency]
        column = self.cb.currentText()
        number = self.getint("Enter moving average")
        text = "%s %s %d Moving Average" % (column, currency, number)
        data = self.all_data[column]
        data = data.div(curr)
        data = data.dropna()
        to_plot = data.rolling(window=number).mean()

        if self.from_edit.text() != '' and self.from_edit.text() != '':
            to_plot = self.date_cut(to_plot)
        else:
            to_plot = to_plot.truncate(before=self.first_date)

        firstval = self.to_series(
            self.date_cut(self.all_data[column].div(curr))).dropna()[0]
        print(firstval)
        to_plot = self.to_series(to_plot)
        to_plot = to_plot / firstval * 100
        self.plotter(to_plot, text)

    def plotter(self, to_plot, text):  #Plots to_plot on plot
        self.axis.plot(to_plot, label=text)
        self.axis.legend(loc=2)
        self.canvas.draw()

    """Strategies"""

    def mean_reversion(self):
        currency = self.cl.currentText()
        curr = self.curr_data[currency]
        column = self.cb.currentText()
        func = mean_reversal
        nr_stdev = self.getfloat("Number of standard deviations")
        number = self.getint("Enter moving average")
        text = " " + str(nr_stdev) + " Deviation - Mean Reversion"
        data = self.all_data[column]
        signals, diffs = func(data, number, curr, nr_stdev)

        self.simulate(data, number, curr, text, signals, diffs)

    def moving_average(self):
        func = mov_avg
        self.strats(func)

    def gd(self):
        func = golden_cross
        text = ":50 GC"
        self.strats(func, text)

    def deriv_strat(self):
        func = derivative_strat
        text = ":200 Derivative"
        self.strats(func, text)

    def brutefor(self):  #Find the best moving avarge
        lower = self.getint("Enter lower bound")
        upper = self.getint("Enter upper bound")
        self.complaint_box("This might take a while...\n")
        currency = self.cl.currentText()
        curr = self.curr_data[currency]
        column = self.cb.currentText()
        data = self.all_data[column]
        data = optimizer(column, currency, data, curr, lower, upper)
        print(data)
        self.bruteplot(data)

    def strats(self, func, text="", number=200):
        currency = self.cl.currentText()
        curr = self.curr_data[currency]
        column = self.cb.currentText()
        if number == 200:
            number = self.getint("Enter moving average")
        data = self.all_data[column]
        signals, diffs = func(data, number, curr)
        if self.error:
            self.error_checking(data, number, curr, text, signals, diffs)
        else:
            self.simulate(data, number, curr, text, signals, diffs)

    def simulate(self, data, number, curr, text, signals, diffs):
        if self.from_edit.text() != '' and self.from_edit.text() != '':
            signals = self.date_cut(signals)
        signals = self.to_series(signals)
        to_plot, masterlist = simulator(data, signals, diffs, curr)
        text = str(number) + text
        self.plot_strat(to_plot, text)
        self.plot_stats(masterlist)

    def error_checking(self, data, number, curr, text, signals, diffs):
        print("ERROR CHECK")
        if self.from_edit.text() != '' and self.from_edit.text() != '':
            signals = self.date_cut(signals)
        signals = self.to_series(signals)
        errnum = self.getint("Enter days for error check")
        to_plot, masterlist, days_between_trades = simulator_error_check(
            data, signals, diffs, curr, errnum)
        text = str(number) + text
        self.plot_strat(to_plot, text)
        self.plot_stats(masterlist)
        self.histogram(days_between_trades)

    """Underlying UI"""

    def histogram(self, data):
        print('test')
        window = QtGui.QMainWindow(self)
        window.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        window.setWindowTitle(self.tr('Histogram'))
        window.setFixedSize(600, 600)
        figure = Figure()  #Create fig
        canvas = FigureCanvasQTAgg(figure)
        canvas.setParent(window)
        canvas.setGeometry(10, 10, 580, 580)
        ax = figure.add_subplot(111)
        ax.hist(data, 100)
        canvas.draw()
        window.show()

    def bruteplot(self, data):

        window = QtGui.QMainWindow(self)
        window.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        window.setWindowTitle(self.tr('Best Moving Average'))
        window.setFixedSize(1000, 600)
        figure = Figure()  #Create fig
        canvas = FigureCanvasQTAgg(figure)
        canvas.setParent(window)
        canvas.setGeometry(10, 10, 980, 580)
        ax = figure.add_subplot(111)
        ax.plot(data)
        canvas.draw()
        window.show()

    def set_save_folder(self):
        self.save_folder = str(
            QtGui.QFileDialog.getExistingDirectory(self, "Select Directory"))
        return None

    def complaint_box(self, text):  #Create an angry box when users f**** up
        error_dialog = QtGui.QErrorMessage(self)
        error_dialog.setWindowModality(QtCore.Qt.WindowModal)
        error_dialog.showMessage(text)

    def getint(self, text):
        print(text)
        num, ok = QtGui.QInputDialog.getInt(self, "Integer Input", text)
        if ok:
            print(num)
            return num

    def getfloat(self, text):
        print(text)
        num, ok = QtGui.QInputDialog.getDouble(self, "Float Input", text)
        if ok:
            print(num)
            return num

    def save_fig(self):  #Save figure
        if self.save_folder != "":
            self.figure.savefig(self.save_folder + '/test.png')
            self.complaint_box('Figure saved in ' + self.save_folder)
        else:
            self.complaint_box('Choose a folder to save in')

    def log_scale(self):
        if self.log_flag:  #Change y-scale to linear
            self.axis.set_yscale('linear')
            self.log_flag = False
            self.canvas.draw()
        else:  #Change y-scale to log
            self.axis.set_yscale('log')

            self.log_flag = True
            self.canvas.draw()

    def error_truth(self):  #Inlcude error stats or not
        self.error = not self.error

    """Short data funtions"""

    def reindex(self, data):
        data = self.to_series(data)
        data = data.dropna()
        data = data / data[0] * 100
        return data

    def to_series(
            self, data
    ):  #If input is pandas DF, return series based on first columns.
        if isinstance(data, pd.DataFrame):
            data = data[data.columns[0]]
        return data

    def date_cut(self, data):  #Cut datframe to specified dates
        if self.from_edit.text() != '' and self.from_edit.text(
        ) != '':  #Check input boxes
            if not isinstance(
                    data,
                    pd.DataFrame):  #Make sire input actually is a dataframe
                data = data.to_frame()
            try:
                data.index = data.index.to_datetime()
                from_date = pd.to_datetime(str(self.from_edit.text()),
                                           format='%Y%m%d')
                to_date = pd.to_datetime(str(self.to_edit.text()),
                                         format='%Y%m%d')
                data = data.truncate(before=from_date, after=to_date)  #Cut
            except:
                err = sys.exc_info()[0]
                err2 = sys.exc_info()[1]
                print(err, err2)
                self.complaint_box(
                    "Invalid date, plotting all \n The index starts " +
                    data.index[0] + " and ends " + data.index[-1] + ".")
        return data

    def readfile(self):  #Read input data
        data = pd.read_excel("file path to index data")
        #    data.index = data.index.to_datetime()
        curr_data = pd.read_excel("file path to currency data")
        #    curr_data.index = data.index.to_datetime()
        return data, curr_data

    def tester(self):  #Test function for UI elemtents
        print("Something happens")
class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setWindowFlags(Qt.FramelessWindowHint
                            | Qt.WindowMinimizeButtonHint)
        self.setWindowTitle(u"鱿鱼")
        self.setFixedSize(800, 600)
        self.setObjectName('principal')
        self.createGUI()

    def createGUI(self):
        self.frame_window = QWidget(self)
        self.frame_window.setGeometry(0, 0, 800, 40)
        self.frame_window.setObjectName('frame_window')
        self.title_frame = QLabel(self.frame_window)
        self.title_frame.setGeometry(0, 0, 800, 40)
        self.title_frame.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.title_frame.setFont(QFont("微软雅黑", 20, QFont.Bold))
        self.title_frame.setText(u" 鱿鱼-阿里云白名单设置")
        self.title_frame.setObjectName('title_frame')
        # buttons
        clsfont = self.font() or QFont()
        clsfont.setFamily('Webdings')
        self.button_close = QPushButton('r', self.frame_window, font=clsfont)
        self.button_close.setGeometry(760, 0, 40, 40)
        self.button_close.setObjectName('button_close')
        self.button_close.setToolTip(u'关闭')
        self.button_close.enterEvent(
            self.button_close.setCursor(Qt.PointingHandCursor))
        self.button_min = QPushButton('0', self.frame_window, font=clsfont)
        self.button_min.setGeometry(720, 0, 40, 40)
        self.button_min.setObjectName('button_min')
        self.button_min.setToolTip(u'最小化')
        self.button_min.enterEvent(
            self.button_min.setCursor(Qt.PointingHandCursor))
        ###左边选择栏部分
        self.GroupBox_checkbox = QGroupBox(self)
        self.GroupBox_checkbox.setTitle(u'选择白名单组')
        self.GroupBox_checkbox.setGeometry(10, 50, 200, 540)
        self.ecs_test = QCheckBox(u'测试环境服务器', self.GroupBox_checkbox)
        self.ecs_test.enterEvent(self.ecs_test.setCursor(
            Qt.PointingHandCursor))
        self.ecs_test.setChecked(True)
        self.ecs_test.setGeometry(20, 30, 150, 30)
        self.rds_mysql = QCheckBox(u'MySQL数据库', self.GroupBox_checkbox)
        self.rds_mysql.enterEvent(
            self.rds_mysql.setCursor(Qt.PointingHandCursor))
        self.rds_mysql.setChecked(True)
        self.rds_mysql.setGeometry(20, 60, 150, 30)
        self.rds_sqlserver = QCheckBox(u'SQLServer数据库', self.GroupBox_checkbox)
        self.rds_sqlserver.enterEvent(
            self.rds_sqlserver.setCursor(Qt.PointingHandCursor))
        self.rds_sqlserver.setChecked(True)
        self.rds_sqlserver.setGeometry(20, 90, 150, 30)
        ###右边IP设置部分
        self.GroupBox_ipset = QGroupBox(self)
        self.GroupBox_ipset.setTitle(u'公网IP配置')
        self.GroupBox_ipset.setGeometry(220, 50, 570, 200)
        self.label_outip = QLabel(self.GroupBox_ipset,
                                  objectName="label_outip")
        self.label_outip.setText(u'公网IP:')
        self.label_outip.setGeometry(15, 30, 75, 30)
        self.line_outip = QLineEdit(self.GroupBox_ipset)
        self.line_outip.setMinimumWidth(200)
        self.line_outip.setGeometry(85, 30, 150, 30)
        self.line_outip.setFont(QFont("Timers", 13, QFont.Bold))
        self.line_outip.setStyleSheet("color:green")
        self.button_getip = QPushButton(u'自动获取公网IP',
                                        self.GroupBox_ipset,
                                        objectName="button_getip")
        self.button_getip.setToolTip(u'从ip138上抓取本机公网IP')
        self.button_getip.enterEvent(
            self.button_getip.setCursor(Qt.PointingHandCursor))
        self.button_getip.setGeometry(300, 30, 110, 30)
        self.button_setup = QPushButton(u'添加',
                                        self.GroupBox_ipset,
                                        objectName="button_setup")
        self.button_setup.enterEvent(
            self.button_setup.setCursor(Qt.PointingHandCursor))
        self.button_setup.setToolTip(u'将该IP添加至已选白名单组中')
        self.button_setup.setGeometry(430, 30, 110, 30)
        ###右边消息输出部分
        self.GroupBox_text = QGroupBox(self)
        self.GroupBox_text.setGeometry(220, 260, 570, 330)
        self.browser_text = QTextBrowser(self.GroupBox_text)
        self.browser_text.setGeometry(0, 0, 570, 330)
        self.browser_text.setFont(QFont("Roman times", 12))
        self.browser_text.setObjectName('browser_text')

        # conexiones
        self.button_close.clicked.connect(self.close)
        self.button_min.clicked.connect(self.showMinimized)
        self.button_getip.clicked.connect(self.auto_ip)
        self.button_setup.clicked.connect(self.setup)

    def auto_ip(self):
        self.line_outip.clear()
        self.button_getip.setEnabled(False)
        self.th_get_ip = GETIP()
        self.th_get_ip.ip_line_Signal.connect(self.show_ip_info)
        self.th_get_ip.start()

    def show_ip_info(self, ip=None, status=1):
        self.button_getip.setEnabled(True)
        if status:
            self.line_outip.setText(ip)
        else:
            self.browser_text.append(ip)

    def setup(self):
        myip = self.line_outip.text()
        if myip and validate_ip(myip):
            check_list = []
            if self.ecs_test.isChecked():
                check_list.append('ecs_test')
            if self.rds_mysql.isChecked():
                check_list.append('rds_mysql')
            if self.rds_sqlserver.isChecked():
                check_list.append('rds_sqlserver')
            if len(check_list) == 0:
                self.browser_text.append(u'没什么事可做的~')
            else:
                self.button_setup.setEnabled(False)
                self.th_setup = SETIP(myip, check_list)
                self.th_setup.text_browser_Signal.connect(self.show_text)
                self.th_setup.start()
        else:
            self.browser_text.append(u'请填入正确的IP地址!')

    def show_text(self, text=None, end=0):
        if end:
            self.button_setup.setEnabled(True)
        if text:
            self.browser_text.append(text)

    def mousePressEvent(self, event):
        self.offset = event.pos()

    def mouseMoveEvent(self, event):
        x = event.globalX()
        y = event.globalY()
        x_w = self.offset.x()
        y_w = self.offset.y()
        self.move(x - x_w, y - y_w)