예제 #1
0
 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)
예제 #2
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 );
예제 #3
0
class MyMainWindow(QMainWindow):
    ' Main Window '
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.statusBar().showMessage(__doc__)
        self.setWindowTitle(__doc__)
        self.setMinimumSize(250, 280)
        self.setMaximumSize(300, 300)
        self.resize(250, 290)
        self.setWindowIcon(QIcon.fromTheme("face-monkey"))
        self.setStyleSheet('''QWidget { color: rgba( 0, 255, 255, 255 );
            background-color: #323232; font-family: 'Ubuntu Light';
            font-size: 14px;
            }

            QToolTip {
                border: 1px solid black;
                background-color: #ffa02f;
                background-image: None;
                padding: 1px;
                border-radius: 3px;
                opacity: 100;
            }

            QWidget:item:hover {
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #ca0619
                );
                color: #000000;
            }

            QWidget:item:selected {
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QWidget:disabled {
                color: #404040;
                background-color: #323232;
            }

            QWidget:focus {
                background-image: None;
                border: 2px solid QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QPushButton {
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #565656,
                    stop: 0.1 #525252,
                    stop: 0.5 #4e4e4e,
                    stop: 0.9 #4a4a4a,
                    stop: 1 #464646
                );
                border-width: 1px;
                border-color: #1e1e1e;
                border-style: solid;
                border-radius: 6;
                padding: 3px;
                font-size: 12px;
                padding-left: 5px;
                padding-right: 5px;
                background-image: None;
            }

            QPushButton:pressed {
                background-image: None;
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #2d2d2d,
                    stop: 0.1 #2b2b2b,
                    stop: 0.5 #292929,
                    stop: 0.9 #282828,
                    stop: 1 #252525
                );
            }

            QComboBox {
                background-image: None;
                selection-background-color: #ffaa00;
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #565656,
                    stop: 0.1 #525252,
                    stop: 0.5 #4e4e4e,
                    stop: 0.9 #4a4a4a,
                    stop: 1 #464646
                );
                border-style: solid;
                border: 1px solid #1e1e1e;
                border-radius: 5;
            }

            QComboBox:hover, QPushButton:hover {
                background-image: url(.bg.png);
                border: 2px solid QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QComboBox:on {
                padding-top: 3px;
                padding-left: 4px;
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #2d2d2d,
                    stop: 0.1 #2b2b2b,
                    stop: 0.5 #292929,
                    stop: 0.9 #282828,
                    stop: 1 #252525
                );
                selection-background-color: #ffaa00;
                background-image: None;
            }

            QComboBox QAbstractItemView {
                background-image: None;
                border: 2px solid darkgray;
                selection-background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QComboBox::drop-down {
                 subcontrol-origin: padding;
                 subcontrol-position: top right;
                 width: 15px;
                 border-left-width: 0px;
                 border-left-color: darkgray;
                 border-left-style: solid;
                 border-top-right-radius: 3px;
                 border-bottom-right-radius: 3px;
                 background-image: None;
             }

            QComboBox::down-arrow { background-image: None; }

            QSlider {
                border-width: 2px;
                border-color: #1e1e1e;
                border-style: solid;
                padding: 3px;
                font-size: 8px;
                padding-left: 5px;
                padding-right: 5px;
                width: 25px;
                border-radius: 5px;
            }

            QSlider::sub-page:vertical {
                background: red;
                border: none;
                width: 25px;
            }

            QSlider::add-page:vertical {
                background: green;
                border: none;
                width: 25px;
            }

            QSlider::handle:vertical {
                background-color: QLinearGradient(spread:pad, x1:0, y1:0, x2:1,
                    y2:0.273, stop:0 rgba(0, 0, 0, 255),
                    stop:1 rgba(150, 255, 255, 255)
                    );
                width: 10px;
                height: 25px;
                border: 1px solid grey;
                text-align: center;
                border-top-left-radius: 2px;
                border-bottom-left-radius: 2px;
                border-top-right-radius: 2px;
                border-bottom-right-radius 2px;
                margin-left: 2px;
                margin-right: 2px;
            }

            QSlider::handle:vertical:hover {
                border: 2px solid #ffaa00;
                margin-left: 2px;
                margin-right: 2px;
            }

            QSlider::sub-page:vertical:disabled {
                background: #bbb;
                border-color: #999;
            }

            QSlider::add-page:vertical:disabled {
                background: #eee;
                border-color: #999;
            }

            QSlider::handle:vertical:disabled {
                background: #eee;
                border: 1px solid #aaa;
                border-radius: 4px;
            } ''')

        self.label1 = QLabel(self)
        self.label1.setText('Use Debug')
        self.label1.setGeometry(QtCore.QRect(25, 25, 125, 25))

        self.slider1 = QSlider(self)
        self.slider1.setGeometry(QtCore.QRect(150, 25, 25, 25))
        self.slider1.setTickInterval(1)
        self.slider1.setCursor(QCursor(QtCore.Qt.OpenHandCursor))
        self.slider1.TickPosition(QSlider.TicksBothSides)
        self.slider1.setRange(0, 1)
        self.slider1.setValue(1)
        self.sli1lbl = QLabel(str(self.slider1.value()), self.slider1)
        self.sli1lbl.move(9, 5)
        self.sli1lbl.setAutoFillBackground(False)
        self.slider1.valueChanged.connect(
            lambda: self.sli1lbl.setText(str(self.slider1.value())))
        self.slider1.sliderPressed.connect(
            lambda: self.slider1.setCursor(QCursor(QtCore.Qt.ClosedHandCursor)))
        self.slider1.sliderReleased.connect(
            lambda: self.slider1.setCursor(QCursor(QtCore.Qt.OpenHandCursor)))

        self.label2 = QLabel(self)
        self.label2.setText('Make Executable')
        self.label2.setGeometry(QtCore.QRect(25, 75, 125, 25))

        self.slider2 = QSlider(self)
        self.slider2.setGeometry(QtCore.QRect(150, 75, 25, 25))
        self.slider2.setTickInterval(1)
        self.slider2.setCursor(QCursor(QtCore.Qt.OpenHandCursor))
        self.slider2.TickPosition(QSlider.TicksBothSides)
        self.slider2.setRange(0, 1)
        self.slider2.setValue(1)
        self.sli2lbl = QLabel(str(self.slider2.value()), self.slider2)
        self.sli2lbl.move(9, 5)
        self.sli2lbl.setAutoFillBackground(False)
        self.slider2.valueChanged.connect(
            lambda: self.sli2lbl.setText(str(self.slider2.value())))
        self.slider2.sliderPressed.connect(
            lambda: self.slider2.setCursor(QCursor(QtCore.Qt.ClosedHandCursor)))
        self.slider2.sliderReleased.connect(
            lambda: self.slider2.setCursor(QCursor(QtCore.Qt.OpenHandCursor)))

        self.label3 = QLabel(self)
        self.label3.setText('Relative Imports')
        self.label3.setGeometry(QtCore.QRect(25, 125, 125, 25))

        self.slider3 = QSlider(self)
        self.slider3.setGeometry(QtCore.QRect(150, 125, 25, 25))
        self.slider3.setTickInterval(1)
        self.slider3.setCursor(QCursor(QtCore.Qt.OpenHandCursor))
        self.slider3.TickPosition(QSlider.TicksBothSides)
        self.slider3.setRange(0, 1)
        self.slider3.setValue(0)
        self.sli3lbl = QLabel(str(self.slider3.value()), self.slider3)
        self.sli3lbl.move(9, 5)
        self.sli3lbl.setAutoFillBackground(False)
        self.slider3.valueChanged.connect(
            lambda: self.sli3lbl.setText(str(self.slider3.value())))
        self.slider3.sliderPressed.connect(
            lambda: self.slider3.setCursor(QCursor(QtCore.Qt.ClosedHandCursor)))
        self.slider3.sliderReleased.connect(
            lambda: self.slider3.setCursor(QCursor(QtCore.Qt.OpenHandCursor)))

        self.label4 = QLabel(self)
        self.label4.setText('Indent Spaces')
        self.label4.setGeometry(QtCore.QRect(25, 175, 125, 25))

        self.combo1 = QComboBox(self)
        self.combo1.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
        self.combo1.addItems(['4', '0', '2', '6', '8'])
        self.combo1.setGeometry(QtCore.QRect(150, 175, 50, 25))

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setGeometry(QtCore.QRect(25, 225, 200, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel |
            QDialogButtonBox.Close | QDialogButtonBox.Help)
        self.buttonBox.setCenterButtons(False)
        self.buttonBox.helpRequested.connect(lambda: QMessageBox.about(
            self, __doc__, str(__doc__ + ', ' + ',\nversion ' + __version__ +
                               '(' + __license__ + '),\nby ' + __author__ + ', '
                               + __email__)))
        self.buttonBox.accepted.connect(self.run)
        self.buttonBox.rejected.connect(self.close)
        palette = self.palette()
        palette.setBrush(QPalette.Base, Qt.transparent)
        self.setPalette(palette)
        self.setAttribute(Qt.WA_OpaquePaintEvent, False)

    def run(self):
        'Run the actual conversion.'
        # Ask the User for the source .ui file as input
        filein = str(QFileDialog.getOpenFileName(
            self, __doc__, path.expanduser("~"), 'UI(*.ui)')).strip()
        # Parse Value of Slider1 as the Debug flag parameter
        if self.slider1.value() == 0:
            arg1 = ''
        else:
            arg1 = '--debug '
        # Parse Value of Slider2 as the Execute flag parameter
        if self.slider2.value() == 0:
            arg2 = ''
        else:
            arg2 = '--execute '
        # Parse Value of Slider3 as the relative imports flag parameter
        if self.slider3.value() == 0:
            arg3 = ''
        else:
            arg3 = '--from-imports '
        # debug
        #print(arg1, arg2, arg3, str(self.combo1.currentText()))
        # run the subprocesses
        subprocess.Popen(
            'nice --adjustment=19 pyuic4 ' + arg1 + arg2 + arg3 +
            '--indent=' + str(self.combo1.currentText()) +
            ' --output=' + str(filein).lower().replace('.ui', '.py') +
            ' ' + filein +
            ' && chmod -v +x ' + str(filein).lower().replace('.ui', '.py'),
            shell=True)

    def paintEvent(self, event):
        ' Paint semi-transparent background '
        painter = QPainter(self)
        painter.fillRect(event.rect(), Qt.transparent)
        painter.setPen(Qt.NoPen)
        painter.setBrush(QColor(0, 0, 0))
        painter.setOpacity(0.75)
        painter.drawRoundedRect(self.rect(), 75, 50)
        painter.end()
예제 #4
0
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()
예제 #5
0
class ComboBoxDelegate(QItemDelegate):
    def __init__(self, parent, itemslist=["a", "b", "c"]):
        QItemDelegate.__init__(self, parent)
        # itemslist = ["a", "b", "c"]
        self.itemslist = itemslist
        self.parent = parent

    # def paint(self, painter, option, index):        
    #     # Get Item Data
    #     value = index.data(Qt.DisplayRole).toInt()[0]
    #     # value = self.itemslist[index.data(QtCore.Qt.DisplayRole).toInt()[0]]
    #     # fill style options with item data
    #     style = QApplication.style()
    #     opt = QStyleOptionComboBox()
    #     opt.currentText = str(self.itemslist[value])
    #     opt.rect = option.rect


    #     # draw item data as ComboBox
    #     style.drawComplexControl(QStyle.CC_ComboBox, opt, painter)
    #     self.parent.openPersistentEditor(index)

    def createEditor(self, parent, option, index):

        ##get the "check" value of the row
        # for row in range(self.parent.model.rowCount(self.parent)):
            # print row

        self.editor = QComboBox(parent)
        self.editor.addItems(self.itemslist)
        self.editor.setCurrentIndex(0)
        self.editor.installEventFilter(self)    
        # self.connect(self.editor, SIGNAL("currentIndexChanged(int)"), self.editorChanged)

        return self.editor

    # def setEditorData(self, editor, index):
        # value = index.data(QtCore.Qt.DisplayRole).toInt()[0]
        # editor.setCurrentIndex(value)

    def setEditorData(self, editor, index): 
        curtxt = index.data(Qt.DisplayRole)
        # print(type(curtxt)== QPyNullVariant )
        if type(curtxt) == type(1):
            curindx = int(index.data(Qt.DisplayRole))
            curtxt = self.itemslist[curindx]
        elif type(curtxt)== QPyNullVariant:
            curtxt = ""
        pos = self.editor.findText(curtxt)
        if pos == -1:  
            pos = 0
        self.editor.setCurrentIndex(pos)


    def setModelData(self,editor,model,index):
        curindx = self.editor.currentIndex()
        text = self.itemslist[curindx]
        model.setData(index, text)


    def updateEditorGeometry(self, editor, option, index):
        self.editor.setGeometry(option.rect)

    def editorChanged(self, index):
        check = self.editor.itemText(index)
        id_seq = self.parent.selectedIndexes[0][0]
        update.updateCheckSeq(self.parent.db, id_seq, check)
        
예제 #6
0
class ViewDataToolsHistory(QMainWindow):
    def __init__(self, parent=None):
        super(ViewDataToolsHistory, self).__init__(parent)

        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # DATATOOLS HISTORY WINDOWS:
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        self.setWindowTitle(ui_strings.DATATOOLS_HISTORY_TITLE)
        self._width = 700
        self._height = 380
        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)

        # toolbar
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # add toolbar options
        self.export_action = QAction(QIcon(resources.ICON_EXPORT),
                                     'Export (Ctrl+E)', self)
        self.export_action.setShortcut('Ctrl+E')

        self.print_action = QAction(QIcon(resources.ICON_PRINT),
                                    'Print (Ctrl+P)', self)
        self.print_action.setShortcut('Ctrl+P')

        self.toolbar = self.addToolBar('Options')
        self.toolbar.addAction(self.export_action)
        self.toolbar.addAction(self.print_action)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        # group input files
        self.group_period = QGroupBox(self.central_widget)
        self.group_period.setGeometry(
            QtCore.QRect(self._left_margin, 10, 250, 50))
        self.group_period.setTitle(ui_strings.DATATOOLS_HISTORY_FILTER)

        # group by:
        self.group_group_by = QGroupBox(self.central_widget)
        self.group_group_by.setGeometry(QtCore.QRect(270, 10, 250, 50))
        self.group_group_by.setTitle(ui_strings.DATATOOLS_HISTORY_GROUP)

        # group by: errors
        self.rbtn_by_errors = QRadioButton(
            ui_strings.DATATOOLS_HISTORY_GROUP_ERROR, self.group_group_by)
        self.rbtn_by_errors.setGeometry(QtCore.QRect(10, 10, 80, 50))

        # group by: status
        #self.group_by_status = QRadioButton(ui_strings.DATATOOLS_HISTORY_GROUP_STATUS, self.group_group_by)
        #self.group_by_status.setGeometry(QtCore.QRect(100, 10, 80, 50))

        # group by: no group
        #self.group_by_no = QRadioButton(ui_strings.DATATOOLS_HISTORY_GROUP_NO, self.group_group_by)
        #self.group_by_no.setGeometry(QtCore.QRect(190, 10, 80, 50))

        # push button to update table
        #self.btn_view_group = QPushButton(self.group_group_by)
        #self.btn_view_group.setGeometry(QtCore.QRect(160, 20, 50, 20))
        #self.btn_view_group.setText(ui_strings.DATATOOLS_HISTORY_VIEW)

        # combobox periods
        self.cbo_period = QComboBox(self.group_period)
        self.cbo_period.setGeometry(
            QtCore.QRect(self._left_margin, 20, 130, 20))

        # push button to update table
        #self.btn_view = QPushButton(self.group_period)
        #self.btn_view.setGeometry(QtCore.QRect(160, 20, 50, 20))
        #self.btn_view.setText(ui_strings.DATATOOLS_HISTORY_VIEW)

        # table history
        self.tbl_uploads = QTableWidget(self.central_widget)
        self.tbl_uploads.setGeometry(
            QtCore.QRect(self._left_margin, 70, 680, 120))

        # chart
        self.plot_widget = PlotWidget(self.central_widget, 8, 2)
        self.plot_widget.setGeometry(
            QtCore.QRect(self._left_margin, 200, 680, 130))

        # records - "x records found"

        self.setCentralWidget(self.central_widget)
예제 #7
0
class ParamSpinBox(QAbstractSpinBox):
    def __init__(self, parent):
        QAbstractSpinBox.__init__(self, parent)

        self.fMinimum = 0.0
        self.fMaximum = 1.0
        self.fDefault = 0.0
        self.fValue   = None
        self.fStep    = 0.0
        self.fStepSmall = 0.0
        self.fStepLarge = 0.0

        self.fReadOnly = False
        self.fScalePoints = None
        self.fHaveScalePoints = False

        self.fBar = ParamProgressBar(self)
        self.fBar.setContextMenuPolicy(Qt.NoContextMenu)
        self.fBar.show()

        self.fName = ""

        self.lineEdit().setVisible(False)

        self.connect(self, SIGNAL("customContextMenuRequested(QPoint)"), SLOT("slot_showCustomMenu()"))
        self.connect(self.fBar, SIGNAL("valueChanged(double)"), SLOT("slot_progressBarValueChanged(double)"))

        QTimer.singleShot(0, self, SLOT("slot_updateProgressBarGeometry()"))

    def setDefault(self, value):
        value = fixValue(value, self.fMinimum, self.fMaximum)
        self.fDefault = value

    def setMinimum(self, value):
        self.fMinimum = value
        self.fBar.setMinimum(value)

    def setMaximum(self, value):
        self.fMaximum = value
        self.fBar.setMaximum(value)

    def setValue(self, value, send=True):
        value = fixValue(value, self.fMinimum, self.fMaximum)

        if self.fValue == value:
            return False

        self.fValue = value
        self.fBar.setValue(value)

        if self.fHaveScalePoints:
            self._setScalePointValue(value)

        if send:
            self.emit(SIGNAL("valueChanged(double)"), value)

        self.update()

        return True

    def setStep(self, value):
        if value == 0.0:
            self.fStep = 0.001
        else:
            self.fStep = value

        if self.fStepSmall > value:
            self.fStepSmall = value
        if self.fStepLarge < value:
            self.fStepLarge = value

    def setStepSmall(self, value):
        if value == 0.0:
            self.fStepSmall = 0.0001
        elif value > self.fStep:
            self.fStepSmall = self.fStep
        else:
            self.fStepSmall = value

    def setStepLarge(self, value):
        if value == 0.0:
            self.fStepLarge = 0.1
        elif value < self.fStep:
            self.fStepLarge = self.fStep
        else:
            self.fStepLarge = value

    def setLabel(self, label):
        self.fBar.setLabel(label)

    def setName(self, name):
        self.fName = name

    def setTextCallback(self, textCall):
        self.fBar.setTextCall(textCall)

    def setReadOnly(self, yesNo):
        self.setButtonSymbols(QAbstractSpinBox.UpDownArrows if yesNo else QAbstractSpinBox.NoButtons)
        self.fReadOnly = yesNo
        QAbstractSpinBox.setReadOnly(self, yesNo)

    def setScalePoints(self, scalePoints, useScalePoints):
        if len(scalePoints) == 0:
            self.fScalePoints     = None
            self.fHaveScalePoints = False
            return

        self.fScalePoints     = scalePoints
        self.fHaveScalePoints = useScalePoints

        if useScalePoints:
            # Hide ProgressBar and create a ComboBox
            self.fBar.close()
            self.fBox = QComboBox(self)
            self.fBox.setContextMenuPolicy(Qt.NoContextMenu)
            self.fBox.show()
            self.slot_updateProgressBarGeometry()

            for scalePoint in scalePoints:
                self.fBox.addItem("%f - %s" % (scalePoint['value'], scalePoint['label']))

            if self.fValue != None:
                self._setScalePointValue(self.fValue)

            self.connect(self.fBox, SIGNAL("currentIndexChanged(QString)"), SLOT("slot_comboBoxIndexChanged(QString)"))

    def stepBy(self, steps):
        if steps == 0 or self.fValue is None:
            return

        value = self.fValue + (self.fStep * steps)

        if value < self.fMinimum:
            value = self.fMinimum
        elif value > self.fMaximum:
            value = self.fMaximum

        self.setValue(value)

    def stepEnabled(self):
        if self.fReadOnly or self.fValue is None:
            return QAbstractSpinBox.StepNone
        if self.fValue <= self.fMinimum:
            return QAbstractSpinBox.StepUpEnabled
        if self.fValue >= self.fMaximum:
            return QAbstractSpinBox.StepDownEnabled
        return (QAbstractSpinBox.StepUpEnabled | QAbstractSpinBox.StepDownEnabled)

    def updateAll(self):
        self.update()
        self.fBar.update()
        if self.fHaveScalePoints:
            self.fBox.update()

    def resizeEvent(self, event):
        QTimer.singleShot(0, self, SLOT("slot_updateProgressBarGeometry()"))
        QAbstractSpinBox.resizeEvent(self, event)

    @pyqtSlot(str)
    def slot_comboBoxIndexChanged(self, boxText):
        if self.fReadOnly:
            return

        value          = float(boxText.split(" - ", 1)[0])
        lastScaleValue = self.fScalePoints[-1]["value"]

        if value == lastScaleValue:
            value = self.fMaximum

        self.setValue(value)

    @pyqtSlot(float)
    def slot_progressBarValueChanged(self, value):
        if self.fReadOnly:
            return

        step      = int((value - self.fMinimum) / self.fStep + 0.5)
        realValue = self.fMinimum + (step * self.fStep)

        self.setValue(realValue)

    @pyqtSlot()
    def slot_showCustomMenu(self):
        menu     = QMenu(self)
        actReset = menu.addAction(self.tr("Reset (%f)" % self.fDefault))
        menu.addSeparator()
        actCopy  = menu.addAction(self.tr("Copy (%f)" % self.fValue))

        clipboard  = QApplication.instance().clipboard()
        pasteText  = clipboard.text()
        pasteValue = None

        if pasteText:
            try:
                pasteValue = float(pasteText)
            except:
                pass

        if pasteValue is None:
            actPaste = menu.addAction(self.tr("Paste"))
        else:
            actPaste = menu.addAction(self.tr("Paste (%s)" % pasteValue))

        menu.addSeparator()

        actSet = menu.addAction(self.tr("Set value..."))

        if self.fReadOnly:
            actReset.setEnabled(False)
            actPaste.setEnabled(False)
            actSet.setEnabled(False)

        actSel = menu.exec_(QCursor.pos())

        if actSel == actSet:
            dialog = CustomInputDialog(self, self.fName, self.fValue, self.fMinimum, self.fMaximum, self.fStep, self.fScalePoints)
            if dialog.exec_():
                value = dialog.returnValue()
                self.setValue(value)

        elif actSel == actCopy:
            clipboard.setText("%f" % self.fValue)

        elif actSel == actPaste:
            self.setValue(pasteValue)

        elif actSel == actReset:
            self.setValue(self.fDefault)

    @pyqtSlot()
    def slot_updateProgressBarGeometry(self):
        self.fBar.setGeometry(self.lineEdit().geometry())
        if self.fHaveScalePoints:
            self.fBox.setGeometry(self.lineEdit().geometry())

    def _getNearestScalePoint(self, realValue):
        finalValue = 0.0

        for i in range(len(self.fScalePoints)):
            scaleValue = self.fScalePoints[i]["value"]
            if i == 0:
                finalValue = scaleValue
            else:
                srange1 = abs(realValue - scaleValue)
                srange2 = abs(realValue - finalValue)

                if srange2 > srange1:
                    finalValue = scaleValue

        return finalValue

    def _setScalePointValue(self, value):
        value = self._getNearestScalePoint(value)

        for i in range(self.fBox.count()):
            if float(self.fBox.itemText(i).split(" - ", 1)[0]) == value:
                self.fBox.setCurrentIndex(i)
                break
class AwindowMotherFucker(QtGui.QMainWindow):
    " A Window M**********r ! "
    def __init__(self):
        " Initialize the Class "
        QtGui.QWidget.__init__(self)
        # Main Window initial Geometry
        self.setGeometry(100, 100, 640, 400)
        # Main Window initial Title
        self.setWindowTitle('CMYK2RGB')
        # Main Window Minimum Size
        self.setMinimumSize(640, 350)
        # Main Window Maximum Size
        self.setMaximumSize(800, 480)
        # Main Window initial StatusBar Message
        self.statusBar().showMessage('CMYK2RGB (Grafica Libre Tool)')
        # Main Window initial ToolTip
        self.setToolTip('Grafica Libre Tools for Ubuntu')
        # Main Window initial Font type
        self.setFont(QtGui.QFont('Ubuntu Light', 10))
        # Main Window Icon
        self.setWindowIcon(QtGui.QIcon('.icon.svg'))
        # Tux image decoration, a QLabel with a QPixmap inside
        self.label = QLabel(self)
        pixmap = QPixmap('.icon.svg')
        self.label.setPixmap(pixmap)
        self.label.setGeometry(405, 12, 300, 300)
        # this always gives the current user Home Folder, cross-platform
        homedir = os.path.expanduser("~")
        # this is the supported file extensions y *.* wildcard
        extensions = ';;'.join(['(*%s)' % e for e in ['.psd', '.icc', '']])
        # print homedir and extensions variables for debug
        print(' INFO: My Home is ' + homedir + ',im using: ' + str(extensions))
        # Menu Bar inicialization and detail definitions
        menu_salir = QtGui.QAction(QtGui.QIcon.fromTheme("application-exit"),
            'Quit | Salir', self)
        menu_salir.setShortcut('Ctrl+Q')
        menu_salir.setStatusTip('Menu Salir')
        self.connect(menu_salir, QtCore.SIGNAL('triggered()'),
            QtGui.qApp, QtCore.SLOT('quit()'))
        # about self
        menu_self = QtGui.QAction(QtGui.QIcon.fromTheme("help-contents"),
            'About | Acerca de', self)
        menu_self.setStatusTip('About self')
        self.connect(menu_self, QtCore.SIGNAL('triggered()'),
            lambda: QMessageBox.about(self, ' CMYK2RGB ',
            unicode(__doc__ + ',\nversion ' + __version__ + '(' + __license__ +
            '),\n by ' + __author__ + ', ( ' + __email__ + ' ). \n\n ' +
            'This program takes proprietary closed canned files\n ' +
            'and produce libre open files, and other magics !; \n' +
            'nothing but Pure, Clean, Open Source Software!.\n\n' +
            'Built for Grafica Libre + Ubuntu-AR community...')))
        # about Qt
        menu_qt = QtGui.QAction(QtGui.QIcon.fromTheme("help-contents"),
            'About Qt | Acerca de Qt', self)
        menu_qt.setStatusTip('About Qt')
        self.connect(menu_qt, QtCore.SIGNAL('triggered()'),
            lambda: QMessageBox.aboutQt(self))

        # about python
        menu_py = QtGui.QAction(QtGui.QIcon.fromTheme("help-contents"),
            'About Python | Acerca de Python', self)
        # set the status tip for this menu item
        menu_py.setStatusTip('About Python...')
        # set the triggered signal to lambda for online about python
        self.connect(menu_py, QtCore.SIGNAL('triggered()'),
            lambda: webbrowser.open_new_tab('http://www.python.org/about'))

        # get support help
        menu_support = QtGui.QAction(QtGui.QIcon.fromTheme("help-faq"),
            'Get Help Online | Obtener Ayuda en Linea', self)
        # set the status tip for this menu item
        menu_support.setStatusTip('Get Help Online...')
        # set the triggered signal to lambda for online help
        self.connect(menu_support, QtCore.SIGNAL('triggered()'),
            lambda: webbrowser.open('mailto:[email protected]'))

        # qt color setting via qcolordialog menu item
        menu_color = QtGui.QAction(
            QtGui.QIcon.fromTheme("preferences-system"),
            'Set GUI Colors | Configurar Colores de GUI', self)
        # set the status tip for this menu item
        menu_color.setStatusTip('Manually set GUI Colors...')
        # set the triggered signal to the showQColorDialog
        self.connect(menu_color, QtCore.SIGNAL('triggered()'),
            self.showQColorDialog)

        # theme setting
        menu_theme = QtGui.QAction(QtGui.QIcon.fromTheme("preferences-system"),
            'Use App GUI Skin | Usar Skin de la App', self)
        # set the status tip for this menu item
        menu_theme.setStatusTip('Use App GUI Skin...')
        # set the triggered signal to the applySkin
        self.connect(menu_theme, QtCore.SIGNAL('triggered()'), self.applySkin)

        # define the menu
        menu = self.menuBar()
        menu.setToolTip('Menu')
        archivo = menu.addMenu('&Archivo')
        archivo.addAction(menu_salir)

        # Settings menu
        settings = menu.addMenu('&Settings')
        settings.addAction(menu_color)
        settings.addAction(menu_theme)

        # Help menu items
        jelp = menu.addMenu('&Help')
        jelp.addAction(menu_support)
        jelp.addSeparator()
        jelp.addAction(menu_self)
        jelp.addAction(menu_qt)
        jelp.addAction(menu_py)

        #
        # Main Input Widgets
        self.label1 = QtGui.QLabel(
            'Elije 2 Archivos .ICC (1 CMYK, 1 RGB) y 1 Archivo .PSD (CMYK)...',
            self)
        self.label1.setGeometry(5, 25, 390, 25)
        self.label1.setAutoFillBackground(True)
        # this is the QFileDialog to open files using a open file dialog gui
        self.btn1 = QtGui.QPushButton('Abrir Archivo .ICC CMYK Origen', self)
        self.btn1.setGeometry(5, 50, 390, 25)
        self.btn1.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.connect(self.btn1, QtCore.SIGNAL('clicked()'),
            lambda: open('.cmyk2rgb-cmyk-icc.txt', 'w').write(unicode(
            QFileDialog.getOpenFileName(self, self.tr("Open File... "),
            homedir, extensions))))
        self.connect(self.btn1, QtCore.SIGNAL('released()'),
         lambda: self.btn1.setText(open('.cmyk2rgb-cmyk-icc.txt', 'r').read()))
        # .ICC
        self.btn2 = QtGui.QPushButton('Abrir Archivo .ICC RGB Destino', self)
        self.btn2.setGeometry(5, 75, 390, 25)
        self.btn2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.connect(self.btn2, QtCore.SIGNAL('clicked()'),
            lambda: open('.cmyk2rgb-rgb-icc.txt', 'w').write(unicode(
            QFileDialog.getOpenFileName(self, self.tr("Open File... "),
            homedir, extensions))))
        self.connect(self.btn2, QtCore.SIGNAL('released()'),
         lambda: self.btn2.setText(open('.cmyk2rgb-rgb-icc.txt', 'r').read()))
        # .PSD
        self.btn3 = QtGui.QPushButton('Abrir Archivo .PSD CMYK', self)
        self.btn3.setGeometry(5, 100, 390, 25)
        self.btn3.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.connect(self.btn3, QtCore.SIGNAL('clicked()'),
            lambda: open('.cmyk2rgb-cmyk-psd.txt', 'w').write(unicode(
            QFileDialog.getOpenFileName(self, self.tr("Open File... "),
            homedir, extensions))))
        self.connect(self.btn3, QtCore.SIGNAL('released()'),
         lambda: self.btn3.setText(open('.cmyk2rgb-cmyk-psd.txt', 'r').read()))
        # Conversion Intents settings
        self.label2 = QtGui.QLabel('Intent: ', self)
        self.label2.setGeometry(535, 25, 100, 25)
        self.label2.setAutoFillBackground(True)
        # -intent
        self.combo1 = QComboBox(self)
        self.combo1.setGeometry(535, 50, 100, 25)
        self.combo1.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.combo1.addItems(['relative', 'absolute',
                              'perceptual', 'saturation'])
        # Color Depth settings
        self.label3 = QtGui.QLabel('Depth: ', self)
        self.label3.setGeometry(535, 75, 100, 25)
        self.label3.setAutoFillBackground(True)
        # -depth
        self.combo2 = QComboBox(self)
        self.combo2.setGeometry(535, 100, 100, 25)
        self.combo2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.combo2.addItems(['8', '16', '4', '2'])
        # Alpha settings
        self.label4 = QtGui.QLabel('Alpha: ', self)
        self.label4.setGeometry(535, 125, 100, 25)
        self.label4.setAutoFillBackground(True)
        # -alpha
        self.combo3 = QComboBox(self)
        self.combo3.setGeometry(535, 150, 100, 25)
        self.combo3.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.combo3.addItems(['on', 'activate', 'off', 'deactivate', '0', '1',
                              'opaque', 'copy', 'transparent', 'extract',
                              'background', 'shape'])
        # AutoMagical Extras
        self.label5 = QtGui.QLabel('Magical Extras: ', self)
        self.label5.setGeometry(535, 175, 100, 25)
        self.label5.setAutoFillBackground(True)
        # this enumerates ALL the so called Auto-Magical flag settings
        self.combo4 = QComboBox(self)
        self.combo4.setGeometry(535, 200, 100, 25)
        self.combo4.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.combo4.addItems(['NINGUNO!', 'TODAS JUNTAS?',
                             ' -antialias ', ' -auto-gamma ', ' -auto-level ',
                             ' -clamp ', ' -clip ', ' -despeckle ', ' -fft ',
                             ' -enhance ', ' -equalize ', ' -flip ', ' -flop ',
                             ' -ift ', ' -monochrome ', ' -negate ', ' -trim ',
                             ' -normalize ', ' -transpose ', ' -transverse ',
                             ' -unique-colors ', ' -flatten ', ' -reverse '
                             ])
        # this are the commands to run from the gui
        self.label6 = QtGui.QLabel(
            'Luego, puedes ejecutar alguna de estas Acciones...', self)
        self.label6.setGeometry(5, 150, 390, 25)
        self.label6.setAutoFillBackground(True)
        # LIBERAR PSD CMYK HACIA RGB GIMP
        self.boton1 = QtGui.QPushButton(
            'LIBERAR PSD CMYK HACIA RGB GIMP', self)
        self.boton1.setGeometry(5, 175, 390, 25)
        self.boton1.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.connect(self.boton1, QtCore.SIGNAL('clicked()'), self.komberty)
        # IDENTIFICAR DATOS DE .PSD CMYK
        self.boton2 = QtGui.QPushButton('IDENTIFICAR DATOS DE .PSD CMYK', self)
        self.boton2.setGeometry(5, 200, 390, 25)
        self.boton2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.connect(self.boton2, QtCore.SIGNAL('clicked()'), self.identy)
        # EXTRAER ARCHIVO .ICC DE .PSD CMYK
        self.boton3 = QtGui.QPushButton(
            'EXTRAER ARCHIVO .ICC DE .PSD CMYK', self)
        self.boton3.setGeometry(5, 225, 390, 25)
        self.boton3.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.connect(self.boton3, QtCore.SIGNAL('clicked()'), self.xtract)
        # Make a HTML5  W.WEBP file and a uncompressed .PNG file
        self.boton4 = QtGui.QPushButton(
            'LIBERAR PSD CMYK HACIA HTML5 .WEBP + .PNG', self)
        self.boton4.setGeometry(5, 250, 390, 25)
        self.boton4.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.connect(self.boton4, QtCore.SIGNAL('clicked()'), self.webpify)
        # Imagen a texto plano base64
        self.boton5 = QtGui.QPushButton(
            'CONVERTIR IMAGEN A TEXTO PLANO BASE64', self)
        self.boton5.setGeometry(5, 275, 390, 25)
        self.boton5.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        # NOTE: hardcoded Chromium web browser call command, not my Bug,
        # for some reason cant use webbrowser.open(),because on some systems it
        # try to open the base64 with incorrect programs (like gvfs, etc)
        self.connect(self.boton5, QtCore.SIGNAL('clicked()'),
            lambda: commands.getoutput(
            'chromium-browser "data:image/jpg;base64,' + base64.b64encode(open(
            QFileDialog.getOpenFileName(self, "Open a Image File to Encode...",
            os.path.expanduser("~"),
            ';;'.join(['(*%s)' % e for e in ['.jpg', '.png', '.webp', '']])),
            "rb").read()) + '"'))
        # Imagen a NormalMap
        self.boton6 = QtGui.QPushButton(
            'CONVERTIR IMAGEN A NORMALMAP PNG', self)
        self.boton6.setGeometry(5, 300, 390, 25)
        self.boton6.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.connect(self.boton6, QtCore.SIGNAL('clicked()'), self.normalify)

    def komberty(self):
        " Main Conversion Function, dont Complain, Patch! "
        print('\n WAIT!!!, WORKING . . . ')
        self.statusBar().showMessage('WAIT!!!, WORKING . . . ')
        # get vars
        arg1 = unicode(open('.cmyk2rgb-cmyk-icc.txt', 'r').read())
        arg2 = unicode(open('.cmyk2rgb-rgb-icc.txt', 'r').read())
        arg3 = unicode(open('.cmyk2rgb-cmyk-psd.txt', 'r').read())
        arg4 = unicode(self.combo1.currentText())
        arg5 = unicode(self.combo2.currentText())
        arg6 = unicode(self.combo3.currentText())
        # handle special auto-magical settings
        if self.combo4.currentText() == 'NINGUNO!':
            # no magic!, low Mana ?
            arg7 = ''
            print(' INFO: NOT using AutoMagical Extras or Flying Unicorns...')
        elif self.combo4.currentText() == 'TODAS JUNTAS?':
            # this is an internal/backend debugging and benchmarking tool...
            arg7 = ' -antialias -auto-gamma -auto-level -enhance -normalize '
            print('\n INFO: RUN FOR YOUR LIFE!, THIS IS GOING TO EXPLODE!! \n')
        else:
            arg7 = unicode(self.combo4.currentText())
            print(' INFO: using AutoMagical Extras of ' + arg7 + '...')
        # convert
        print(' INFO: Working with ' + arg1 + ', ' + arg2 + ', ' + arg3)
        print(' INFO: My Intent is ' + arg4 + ', using Color Depth of ' + arg5)
        print(' INFO: The Alpha Channel Setting is ' + arg6 + '...')
        self.statusBar().showMessage('Working:' + arg1 + arg2 + arg3)
        commands.getoutput('convert -profile ' + arg1 + ' -profile ' + arg2 +
                         ' -intent ' + arg4 + ' -depth ' + arg5 + ' -alpha ' +
                         arg6 + arg7 + ' -strip -colorspace RGB ' + arg3 + ' '
                         + arg3 + '.tiff' +
              ' ; sleep 1 ; gimp --no-data --no-fonts --no-splash --as-new ' +
                         arg3 + '.tiff')
        self.statusBar().showMessage('Done.')
        print(' INFO: Done. ')

    def identy(self):
        " Identification of the input .PSD file "
        print('\n WAIT!!!, WORKING . . . ')
        self.statusBar().showMessage('WAIT!!!, WORKING . . . ')
        arg3 = unicode(open('.cmyk2rgb-cmyk-psd.txt', 'r').read())
        # print arg3
        cmd1 = commands.getoutput('identify -verbose ' + arg3)
        # print cmd1
        filename = "cmyk2rgb_report.txt"
        try:
            # write Report
            print(' Saving Report to ' + filename + "...")
            self.statusBar().showMessage('Saving Report to ' + filename)
            fout = open(filename, "w")
            fout.write(cmd1)
            fout.close()
            # open Report
            print(' Opening Report ' + filename + "...")
            self.statusBar().showMessage('Opening Report ' + filename + "...")
            webbrowser.open_new_tab(filename)
            self.statusBar().showMessage('Done.')
            print(' INFO: Done. ')
        # except if IO has an error, print an error
        except IOError:
            print " ERROR: File %s could not be saved!" % filename
            self.statusBar().showMessage("ERROR: File could not be saved!")

    def xtract(self):
        " Extract .ICC File from .PSD CMYK File "
        print('\n WAIT!!!, WORKING . . . ')
        self.statusBar().showMessage('WAIT!!!, WORKING . . . ')
        # get vars
        arg3 = unicode(open('.cmyk2rgb-cmyk-psd.txt', 'r').read())
        # print info
        print(' INFO: Working with ' + arg3 + ' . . . ')
        self.statusBar().showMessage(' Working with ' + arg3 + ' . . . ')
        # extract the .icc files from the .psd file
        commands.getoutput('convert ' + arg3 + ' ' + arg3 + '.icc')
        print(' INFO: Done. ')
        self.statusBar().showMessage('Done.')

    def webpify(self):
        'Make a .WEBP file for HTML5 web development and design, on base64 '
        print('\n WAIT!!!, WORKING . . . ')
        self.statusBar().showMessage('WAIT!!!, WORKING . . . ')
        # get vars
        arg1 = unicode(open('.cmyk2rgb-cmyk-icc.txt', 'r').read())
        arg2 = unicode(open('.cmyk2rgb-rgb-icc.txt', 'r').read())
        arg3 = unicode(open('.cmyk2rgb-cmyk-psd.txt', 'r').read())
        arg4 = unicode(self.combo1.currentText())
        arg5 = unicode(self.combo2.currentText())
        arg6 = unicode(self.combo3.currentText())
        # print info
        print(' INFO: Working with ' + arg1 + ', ' + arg2 + ', ' + arg3)
        print(' INFO: My Intent is ' + arg4 + ', using Color Depth of ' + arg5)
        print(' INFO: The Alpha Channel Setting is ' + arg6 + '...')
        self.statusBar().showMessage('Working:' + arg1 + arg2 + arg3)
        # try to get version of WebP and print the info
        try:
            cmd1 = commands.getoutput('cwebp -version')
            print(' INFO: WORKING WITH: \n' + cmd1)
        # except if it has an error, print an error, and quit
        except:
            print(' ERROR: No WEBP Converter!\n ( sudo apt-get install webp )')
            exit()
        # NOTE: hardcoded Chromium web browser call command, not my Bug,
        # Firefox dont want to open .WEBP images, go complain to Mozilla.
        #
        # Convert
        commands.getoutput('convert -profile ' + arg1 + ' -profile ' + arg2 +
                         ' -intent ' + arg4 + ' -depth ' + arg5 + ' -alpha ' +
                         arg6 + ' -strip -flatten -colorspace RGB ' + arg3 +
                         ' ' + arg3 + '.png' +
                    ' ; sleep 1 ; cwebp -preset text -m 6 -strong -pass 10 ' +
                         arg3 + '.png -o ' + arg3 +
                         '.webp ; sleep 1 ; chromium-browser ' + arg3 +
                         '.webp'
                         )
        self.statusBar().showMessage('Done.')
        print(' INFO: Done. ')

    def normalify(self):
        ' make a normal map from image '
        def height2bump(heightBand, filter="Random"):
            ' oooooh, look a nested function!, are they bad ? '
            if filter == "Sobel":
                a1 = 500
                a2 = 64
                a3 = 0
                b1 = 1
                b2 = 250
                b3 = 666
            elif filter == "Scharr":
                a1 = 21.38
                a2 = 85.24
                a3 = 0
                b1 = 5.96
                b2 = 61.81
                b3 = 255
            elif filter == "Random":           # 5x5 random filter
                a1 = float(randint(0, 255))
                a2 = float(randint(0, 255))
                a3 = float(randint(0, 255))
                b1 = float(randint(0, 255))
                b2 = float(randint(0, 255))
                b3 = float(randint(0, 255))
                print(unicode((a1, a2, a3, b1, b2, b3)))
            else:
                raise ValueError(" ERROR: Unknown Filter arguments !")
            print("Filter: ", filter)
            a4 = -a2
            a5 = -a1
            b4 = b2
            b5 = b1
            kernel = []
            kernel.append((a1 * b1, a2 * b1, a3 * b1, a4 * b1, a5 * b1,
                           a1 * b2, a2 * b2, a3 * b2, a4 * b2, a5 * b2,
                           a1 * b3, a2 * b3, a3 * b3, a4 * b3, a5 * b3,
                           a1 * b4, a2 * b4, a3 * b4, a4 * b4, a5 * b4,
                           a1 * b5, a2 * b5, a3 * b5, a4 * b5, a5 * b5))  # x
            kernel.append((b1 * a1, b2 * a1, b3 * a1, b4 * a1, b5 * a1,
                           b1 * a2, b2 * a2, b3 * a2, b4 * a2, b5 * a2,
                           b1 * a3, b2 * a3, b3 * a3, b4 * a3, b5 * a3,
                           b1 * a4, b2 * a4, b3 * a4, b4 * a4, b5 * a4,
                           b1 * a5, b2 * a5, b3 * a5, b4 * a5, b5 * a5))  # y
            # scale factor, vertical fall from 255 to 0
            scale = 0.0
            for i, val in enumerate(kernel[0]):
                if i % 5 < 5 // 2:
                    scale += 255.0 * val
            scale /= 128.0
            print("Scale = ", scale)
            r = heightBand.filter(ImageFilter.Kernel((5, 5),
                kernel[0], scale=scale, offset=128.0))
            g = heightBand.filter(ImageFilter.Kernel((5, 5),
                kernel[1], scale=scale, offset=128.0))
            b = ImageChops.constant(g, 128)
            rr = r.load()
            gg = g.load()
            bb = b.load()
            for y in range(r.size[1]):
                for x in range(r.size[0]):
                    op = 1.0 - (rr[x, y] * 2.0 / 255.0 - 1.0) ** 2 - (
                            gg[x, y] * 2.0 / 255.0 - 1.0) ** 2
                    if op > 0.0:
                        bb[x, y] = 128.0 + 128.0 * sqrt(op)
                    else:
                        bb[x, y] = 128.0
            return([r, g, b])

        # make a dialog gui
        dialog = QtGui.QDialog(self)
        #
        label1 = QtGui.QLabel('Tipo de algoritmo de procesamiento: ', dialog)
        label1.setAutoFillBackground(True)
        combo1 = QComboBox(dialog)
        combo1.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        combo1.addItems(['Sobel 5x5 (Strong, Fuerte)',
                         'Random ??? (Variable, entropic)',
                         'Scharr 5x5 (Soft, Suave)'
                         ])
        #
        label2 = QtGui.QLabel('Procesamiento de Canal Alpha: ', dialog)
        label2.setAutoFillBackground(True)
        combo2 = QComboBox(dialog)
        combo2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        combo2.addItems(['HeightMap (Usar Alpha)', 'Ignored (Ignorar Alpha)'])
        #
        label3 = QtGui.QLabel('\n Nombre de archivo de salida sera igual al ' +
        'de entrada con el prefijo " _n ". \n Output filename will be equal ' +
        'to input filename with the " _n " prefix. \n ', dialog)
        label3.setAutoFillBackground(True)
        # make a button
        ok = QtGui.QPushButton(dialog)
        # set the text on the button to ok
        ok.setText('&O K')
        ok.setDefault(True)
        # connect the clicked signal to an accept slot
        self.connect(ok, QtCore.SIGNAL('clicked()'), dialog.accept)
        # make a local layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(label1)
        layout.addWidget(combo1)
        layout.addWidget(label2)
        layout.addWidget(combo2)
        layout.addWidget(label3)
        layout.addWidget(ok)
        dialog.setLayout(layout)
        # run the dialog
        dialog.exec_()

        # Process the Algorythm string value
        if combo1.currentText() == 'Sobel 5x5 (Strong, Fuerte)':
            arg1 = 'Sobel'
            print(' INFO: Using Sobel for NormalMapping . . . ')
        elif combo1.currentText() == 'Random ??? (Variable, entropic)':
            arg1 = 'Random'
            print(' INFO: Using Random for NormalMapping . . . ')
        else:
            arg1 = 'Scharr'
            print(' INFO: using Scharr for NormalMapping . . . ')

        # Process the HeightMap Boolean
        if combo2.currentText() == 'HeightMap (Usar Alpha)':
            alphaheight = True
        else:
            alphaheight = False

        # try to read input filename and save the output file
        try:
            infile = unicode(QFileDialog.getOpenFileName(self,
              "Open an Image File to make a Normal Map... ",
              os.path.expanduser("~"),
              ';;'.join(['(*%s)' % e for e in ['.jpg', '.png', '']])))
            print(infile)
            im = Image.open(infile)
            print(im)
        except:
            sys.exit(" \n ERROR: Could not open an Image File ! \n ")
        height = im.split()[0]
        normal = height2bump(height, filter=arg1)
        if alphaheight:
            normal.extend([height])
            im = Image.merge("RGBA", normal)
        else:
            im = Image.merge("RGB", normal)
        try:
            outfile = unicode(infile.split('.')[0] + '_n.png')
            print(outfile)
            im.save(outfile)
        except:
            sys.exit(" \n ERROR: Could not save the Output Image File ! \n ")
        print(" INFO: Function completed !")
        return(im)

    def showQColorDialog(self):
        ' Choose a Color for Qt '
        color = QtGui.QColorDialog.getColor()
        # print info
        print(' INFO: Using User requested color ' + str(color.name()) + '...')
        # if the color is a valid color use it into an CSS and apply it
        if color.isValid():
            self.setStyleSheet(" * { background-color: %s } " % color.name())

    def applySkin(self):
        ' Apply a Customized Dark Sexy Skin '
        print(' INFO: Using Built-In CSS . . .')
        # complete CSS for Qt widgets
        self.setStyleSheet('''
            QToolTip {
                border: 1px solid black;
                background-color: #ffa02f;
                padding: 1px;
                border-radius: 3px;
                opacity: 100;
            }

            QWidget{
                color: #b1b1b1;
                background-color: #323232;
            }

            QWidget:item:hover {
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #ca0619
                );
                color: #000000;
            }

            QWidget:item:selected {
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QMenuBar::item { background: transparent; }

            QMenuBar::item:selected {
                background: transparent;
                border: 1px solid #ffaa00;
            }

            QMenuBar::item:pressed {
                background: #444;
                border: 1px solid #000;
                background-color: QLinearGradient(
                    x1:0, y1:0,
                    x2:0, y2:1,
                    stop:1 #212121,
                    stop:0.4 #343434,
                    stop:0.2 #343434,
                    stop:0.1 #ffaa00
                );
                margin-bottom:-1px;
                padding-bottom:1px;
            }

            QMenu { border: 1px solid #000; }

            QMenu::item { padding: 2px 20px 2px 20px; }

            QMenu::item:selected { color: #000000; }

            QWidget:disabled {
                color: #404040;
                background-color: #323232;
            }

            QAbstractItemView {
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #4d4d4d,
                    stop: 0.1 #646464,
                    stop: 1 #5d5d5d
                );
            }

            QWidget:focus {
                border: 2px solid QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QLineEdit {
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #4d4d4d,
                    stop: 0 #646464,
                    stop: 1 #5d5d5d
                );
                padding: 1px;
                border-style: solid;
                border: 1px solid #1e1e1e;
                border-radius: 5;
            }

            QPushButton {
                color: #b1b1b1;
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #565656,
                    stop: 0.1 #525252,
                    stop: 0.5 #4e4e4e,
                    stop: 0.9 #4a4a4a,
                    stop: 1 #464646
                );
                border-width: 1px;
                border-color: #1e1e1e;
                border-style: solid;
                border-radius: 6;
                padding: 3px;
                font-size: 12px;
                padding-left: 5px;
                padding-right: 5px;
            }

            QPushButton:pressed {
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #2d2d2d,
                    stop: 0.1 #2b2b2b,
                    stop: 0.5 #292929,
                    stop: 0.9 #282828,
                    stop: 1 #252525
                );
            }

            QComboBox {
                selection-background-color: #ffaa00;
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #565656,
                    stop: 0.1 #525252,
                    stop: 0.5 #4e4e4e,
                    stop: 0.9 #4a4a4a,
                    stop: 1 #464646
                );
                border-style: solid;
                border: 1px solid #1e1e1e;
                border-radius: 5;
            }

            QComboBox:hover,QPushButton:hover {
                border: 2px solid QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QComboBox:on {
                padding-top: 3px;
                padding-left: 4px;
                background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #2d2d2d,
                    stop: 0.1 #2b2b2b,
                    stop: 0.5 #292929,
                    stop: 0.9 #282828,
                    stop: 1 #252525
                );
                selection-background-color: #ffaa00;
            }

            QComboBox QAbstractItemView {
                border: 2px solid darkgray;
                selection-background-color: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QComboBox::drop-down {
                 subcontrol-origin: padding;
                 subcontrol-position: top right;
                 width: 15px;
                 border-left-width: 0px;
                 border-left-color: darkgray;
                 border-left-style: solid;
                 border-top-right-radius: 3px;
                 border-bottom-right-radius: 3px;
             }

            QComboBox::down-arrow { }

            QGroupBox:focus {
                border: 2px solid QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QTextEdit:focus {
                border: 2px solid QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
            }

            QScrollBar:horizontal {
                border: 1px solid #222222;
                background: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0.0 #121212,
                    stop: 0.2 #282828,
                    stop: 1 #484848
                );
                height: 7px;
                margin: 0px 16px 0 16px;
            }

            QScrollBar::handle:horizontal {
                background: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 1, y2: 0,
                    stop: 0 #ffa02f,
                    stop: 0.5 #d7801a,
                    stop: 1 #ffa02f
                );
                min-height: 20px;
                border-radius: 2px;
            }

            QScrollBar::add-line:horizontal {
                border: 1px solid #1b1b19;
                border-radius: 2px;
                background: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 1, y2: 0,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
                width: 14px;
                subcontrol-position: right;
                subcontrol-origin: margin;
            }

            QScrollBar::sub-line:horizontal {
                border: 1px solid #1b1b19;
                border-radius: 2px;
                background: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 1, y2: 0,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
                width: 14px;
                subcontrol-position: left;
                subcontrol-origin: margin;
            }

            QScrollBar::right-arrow:horizontal,
            QScrollBar::left-arrow:horizontal {
                border: 1px solid black;
                width: 1px;
                height: 1px;
                background: white;
            }

            QScrollBar::add-page:horizontal,
            QScrollBar::sub-page:horizontal { background: none; }

            QScrollBar:vertical {
                background: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 1, y2: 0,
                    stop: 0.0 #121212,
                    stop: 0.2 #282828,
                    stop: 1 #484848
                );
                width: 7px;
                margin: 16px 0 16px 0;
                border: 1px solid #222222;
            }

            QScrollBar::handle:vertical {
                background: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 0.5 #d7801a,
                    stop: 1 #ffa02f
                );
                min-height: 20px;
                border-radius: 2px;
            }

            QScrollBar::add-line:vertical {
                border: 1px solid #1b1b19;
                border-radius: 2px;
                background: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #ffa02f,
                    stop: 1 #d7801a
                );
                height: 14px;
                subcontrol-position: bottom;
                subcontrol-origin: margin;
            }

            QScrollBar::sub-line:vertical {
                border: 1px solid #1b1b19;
                border-radius: 2px;
                background: QLinearGradient(
                    x1: 0, y1: 0,
                    x2: 0, y2: 1,
                    stop: 0 #d7801a,
                    stop: 1 #ffa02f
                );
                height: 14px;
                subcontrol-position: top;
                subcontrol-origin: margin;
            }

            QScrollBar::up-arrow:vertical,
            QScrollBar::down-arrow:vertical {
                border: 1px solid black;
                width: 1px;
                height: 1px;
                background: white;
            }

            QScrollBar::add-page:vertical,
            QScrollBar::sub-page:vertical { background: none; }

            QTextEdit { background-color: #242424; }

            QPlainTextEdit { background-color: #242424; }

            QHeaderView::section {
                background-color: QLinearGradient(
                    x1:0, y1:0,
                    x2:0, y2:1,
                    stop:0 #616161,
                    stop: 0.5 #505050,
                    stop: 0.6 #434343,
                    stop:1 #656565
                );
                color: white;
                padding-left: 4px;
                border: 1px solid #6c6c6c;
            }

            QCheckBox:disabled { color: #414141; }

            QDockWidget::title {
                text-align: center;
                spacing: 3px;
                background-color: QLinearGradient(
                    x1:0, y1:0,
                    x2:0, y2:1,
                    stop:0 #323232,
                    stop: 0.5 #242424,
                    stop:1 #323232
                    );
            }

            QDockWidget::close-button,
            QDockWidget::float-button {
                text-align: center;
                spacing: 1px;
                background-color: QLinearGradient(
                    x1:0, y1:0,
                    x2:0, y2:1,
                    stop:0 #323232,
                    stop: 0.5 #242424,
                    stop:1 #323232
                );
            }

            QDockWidget::close-button:hover,
            QDockWidget::float-button:hover { background: #242424; }

            QDockWidget::close-button:pressed,
            QDockWidget::float-button:pressed { padding: 1px -1px -1px 1px;}

            QMainWindow::separator {
                background-color: QLinearGradient(
                    x1:0, y1:0,
                    x2:0, y2:1,
                    stop:0 #161616,
                    stop: 0.5 #151515,
                    stop: 0.6 #212121,
                    stop:1 #343434
                );
                color: white;
                padding-left: 4px;
                border: 1px solid #4c4c4c;
                spacing: 3px;
            }

            QMainWindow::separator:hover {
                background-color: QLinearGradient(
                    x1:0, y1:0,
                    x2:0, y2:1,
                    stop:0 #d7801a,
                    stop:0.5 #b56c17,
                    stop:1 #ffa02f
                );
                color: white;
                padding-left: 4px;
                border: 1px solid #6c6c6c;
                spacing: 3px;
            }

            QToolBar::handle { spacing: 3px; }

            QMenu::separator {
                height: 2px;
                background-color: QLinearGradient(
                    x1:0, y1:0,
                    x2:0, y2:1,
                    stop:0 #161616,
                    stop: 0.5 #151515,
                    stop: 0.6 #212121,
                    stop:1 #343434
                );
                color: white;
                padding-left: 4px;
                margin-left: 10px;
                margin-right: 5px;
            }

            QProgressBar {
                border: 2px solid grey;
                border-radius: 5px;
                text-align: center;
            }

            QProgressBar::chunk {
                background-color: #d7801a;
                width: 2.15px;
                margin: 0.5px;
            }

            QTabBar::tab {
                color: #b1b1b1;
                border: 1px solid #444;
                border-bottom-style: none;
                background-color: #323232;
                padding-left: 10px;
                padding-right: 10px;
                padding-top: 3px;
                padding-bottom: 2px;
                margin-right: -1px;
            }

            QTabWidget::pane {
                border: 1px solid #444;
                top: 1px;
            }

            QTabBar::tab:last {
                margin-right: 0;
                border-top-right-radius: 3px;
            }

            QTabBar::tab:first:!selected {
                margin-left: 0px;
                border-top-left-radius: 3px;
            }

            QTabBar::tab:!selected {
                color: #b1b1b1;
                border-bottom-style: solid;
                margin-top: 3px;
                background-color: QLinearGradient(
                    x1:0, y1:0,
                    x2:0, y2:1,
                    stop:1 #212121,
                    stop:.4 #343434
                );
            }

            QTabBar::tab:selected {
                border-top-left-radius: 3px;
                border-top-right-radius: 3px;
                margin-bottom: 0px;
            }

            QTabBar::tab:!selected:hover {
                border-top: 2px solid #ffaa00;
                padding-bottom: 3px;
                border-top-left-radius: 3px;
                border-top-right-radius: 3px;
                background-color: QLinearGradient(
                    x1:0, y1:0,
                    x2:0, y2:1,
                    stop:1 #212121,
                    stop:0.4 #343434,
                    stop:0.2 #343434,
                    stop:0.1 #ffaa00
                );
            }

            QRadioButton::indicator:checked, QRadioButton::indicator:unchecked{
                color: #b1b1b1;
                background-color: #323232;
                border: 1px solid #b1b1b1;
                border-radius: 6px;
            }

            QRadioButton::indicator:checked {
                background-color: qradialgradient(
                    cx: 0.5, cy: 0.5,
                    fx: 0.5, fy: 0.5,
                    radius: 1.0,
                    stop: 0.25 #ffaa00,
                    stop: 0.3 #323232
                );
            }

            QCheckBox::indicator {
                color: #b1b1b1;
                background-color: #323232;
                border: 1px solid #b1b1b1;
                width: 9px;
                height: 9px;
            }

            QRadioButton::indicator { border-radius: 6px; }

            QRadioButton::indicator:hover, QCheckBox::indicator:hover {
                border: 1px solid #ffaa00;
            }

            QCheckBox::indicator:checked { }

            QCheckBox::indicator:disabled,
            QRadioButton::indicator:disabled {
                border: 1px solid #444;
            }
        ''')
class WellExportDialog(QDialog):
    def __init__(self):
        super(WellExportDialog, self).__init__()
        self.resize(400, 300)
        self.initUI()
        self.export_Button.clicked.connect(self.export_well)
        self.button_box.rejected.connect(self.close)
        self.select_Button.clicked.connect(self.select_file)
        self.well_comboBox.currentIndexChanged.connect(
            self.populate_log_listWidget)

        self.update_well_comboBox()

    def initUI(self):
        self.setWindowIcon(QIcon(':/icon/export'))
        self.setWindowTitle("Export Well")
        self.layout = QGridLayout(self)
        # add QLabel
        self.label_0 = QLabel(self)
        self.label_0.setGeometry(QRect(0, 24, 31, 20))
        self.label_0.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                                  | Qt.AlignVCenter)
        self.label_0.setText("Well to export:")
        self.layout.addWidget(self.label_0, 0, 0)
        # add QComboBox
        self.well_comboBox = QComboBox(self)
        self.well_comboBox.setGeometry(QRect(10, 10, 101, 24))
        self.layout.addWidget(self.well_comboBox, 0, 1, 1, 1)
        # add QCheckBox
        self.checkbox = QCheckBox(self)
        self.checkbox.setText("Full LAS")
        self.checkbox.setCheckState(Qt.Unchecked)
        self.layout.addWidget(self.checkbox, 0, 2)
        # add QListWidget
        self.logs_listWidget = QListWidget(self)
        self.logs_listWidget.setGeometry(QRect(0, 0, 101, 201))
        # self.well_comboBox.setMaximumHeight(151)
        self.layout.addWidget(self.logs_listWidget, 1, 1)
        # add QLabel
        self.label_1 = QLabel(self)
        self.label_1.setGeometry(QRect(0, 24, 31, 20))
        self.label_1.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                                  | Qt.AlignVCenter)
        self.label_1.setText("Output File:")
        self.layout.addWidget(self.label_1, 2, 0)
        # add QLineEdit
        self.file_path_lineEdit = QLineEdit(self)
        self.file_path_lineEdit.setGeometry(QRect(50, 24, 81, 20))
        self.layout.addWidget(self.file_path_lineEdit, 2, 1)
        # add Button
        self.select_Button = QPushButton(self)
        self.select_Button.setMaximumSize(QSize(61, 24))
        self.select_Button.setText("Select")
        self.layout.addWidget(self.select_Button, 2, 2)
        # add QDialogButtonBox
        self.button_box = QDialogButtonBox(self)
        self.export_Button = self.button_box.addButton(
            "Export", QDialogButtonBox.ApplyRole)
        self.button_box.addButton(QDialogButtonBox.Cancel)
        self.layout.addWidget(self.button_box, 3, 0, 1, 3)

    def update_well_comboBox(self):
        survey_file = CONF.survey_dir / '.survey'
        if survey_file.exists():
            dnames = get_data_files(CONF.well_dir)
            self.well_comboBox.addItems(dnames)

    def populate_log_listWidget(self):
        self.logs_listWidget.clear()
        well = ppp.Well(
            str(CONF.well_dir /
                ".{}".format(self.well_comboBox.currentText())))
        # self.logs_listWidget.addItems(well.logs)
        for name in well.logs:
            new_item = QListWidgetItem(name, self.logs_listWidget)
            new_item.setFlags(new_item.flags() | Qt.ItemIsUserCheckable)
            new_item.setCheckState(Qt.Unchecked)

    def export_well(self):
        file_name = str(self.file_path_lineEdit.text())
        if not file_name:
            QMessageBox().information(self, "Info",
                                      "Please select ouput file.")
            pass
        else:
            well = well = ppp.Well(
                str(CONF.well_dir /
                    ".{}".format(self.well_comboBox.currentText())))
            logs_to_export = []
            for i in range(self.logs_listWidget.count()):
                item = self.logs_listWidget.item(i)
                if item.checkState() == Qt.Checked:
                    logs_to_export.append(str(item.text()))
            full = True if self.checkbox.checkState() == Qt.Checked \
                else False
            well.export(file_name, logs_to_export, full)
            QMessageBox().information(self, "Info", "Succeed!")

    def select_file(self):
        fl = QFileDialog.getSaveFileName(self, 'Save File', str(CONF.well_dir))
        self.file_path_lineEdit.setText(fl)
예제 #10
0
    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)
예제 #11
0
class ViewDataToolsHistory(QMainWindow):
    def __init__(self, parent=None):
        super(ViewDataToolsHistory, self).__init__(parent)

        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # DATATOOLS HISTORY WINDOWS:
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        self.setWindowTitle(ui_strings.DATATOOLS_HISTORY_TITLE)
        self._width = 700
        self._height = 380
        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)

        # toolbar
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # add toolbar options
        self.export_action = QAction(QIcon(resources.ICON_EXPORT), 'Export (Ctrl+E)', self)
        self.export_action.setShortcut('Ctrl+E')

        self.print_action = QAction(QIcon(resources.ICON_PRINT), 'Print (Ctrl+P)', self)
        self.print_action.setShortcut('Ctrl+P')

        self.toolbar = self.addToolBar('Options')
        self.toolbar.addAction(self.export_action)
        self.toolbar.addAction(self.print_action)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        # group input files
        self.group_period = QGroupBox(self.central_widget)
        self.group_period.setGeometry(QtCore.QRect(self._left_margin, 10, 250, 50))
        self.group_period.setTitle(ui_strings.DATATOOLS_HISTORY_FILTER)

        # group by:
        self.group_group_by = QGroupBox(self.central_widget)
        self.group_group_by.setGeometry(QtCore.QRect(270, 10, 250, 50))
        self.group_group_by.setTitle(ui_strings.DATATOOLS_HISTORY_GROUP)

        # group by: errors
        self.rbtn_by_errors = QRadioButton(ui_strings.DATATOOLS_HISTORY_GROUP_ERROR, self.group_group_by)
        self.rbtn_by_errors.setGeometry(QtCore.QRect(10, 10, 80, 50))

        # group by: status
        #self.group_by_status = QRadioButton(ui_strings.DATATOOLS_HISTORY_GROUP_STATUS, self.group_group_by)
        #self.group_by_status.setGeometry(QtCore.QRect(100, 10, 80, 50))

        # group by: no group
        #self.group_by_no = QRadioButton(ui_strings.DATATOOLS_HISTORY_GROUP_NO, self.group_group_by)
        #self.group_by_no.setGeometry(QtCore.QRect(190, 10, 80, 50))

        # push button to update table
        #self.btn_view_group = QPushButton(self.group_group_by)
        #self.btn_view_group.setGeometry(QtCore.QRect(160, 20, 50, 20))
        #self.btn_view_group.setText(ui_strings.DATATOOLS_HISTORY_VIEW)

        # combobox periods
        self.cbo_period = QComboBox(self.group_period)
        self.cbo_period.setGeometry(QtCore.QRect(self._left_margin, 20, 130, 20))

        # push button to update table
        #self.btn_view = QPushButton(self.group_period)
        #self.btn_view.setGeometry(QtCore.QRect(160, 20, 50, 20))
        #self.btn_view.setText(ui_strings.DATATOOLS_HISTORY_VIEW)

        # table history
        self.tbl_uploads = QTableWidget(self.central_widget)
        self.tbl_uploads.setGeometry(QtCore.QRect(self._left_margin, 70, 680, 120))

        # chart
        self.plot_widget = PlotWidget(self.central_widget, 8, 2)
        self.plot_widget.setGeometry(QtCore.QRect(self._left_margin, 200, 680, 130))

        # records - "x records found"

        self.setCentralWidget(self.central_widget)
예제 #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)
예제 #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)
예제 #14
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))
예제 #15
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 );
예제 #16
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)
예제 #17
0
파일: GUI.py 프로젝트: fimad/TextToKill
class GUI(object):

    def __init__(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        
        # Set size of window
        MainWindow.resize(800, 589)
        MainWindow.setFocusPolicy(QtCore.Qt.NoFocus)
        MainWindow.setWindowTitle("Text to Kill")
        
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.gridLayout = QGridLayout(self.centralwidget)
        self.gridLayout.setMargin(0)
        self.gridLayout.setObjectName("gridLayout")
        self.stackedWidget = QStackedWidget(self.centralwidget)
        self.stackedWidget.setEnabled(True)
        self.stackedWidget.setObjectName("stackedWidget")
        
        font = QFont()
        font.setFamily("Times New Roman")
        
        # Main menu page
        self.menuPage = QWidget()
        self.menuPage.setObjectName("menuPage")
        self.titleLabel = QLabel(self.menuPage)
        self.titleLabel.setGeometry(QtCore.QRect(250, 60, 300, 50))
        font.setPointSize(45)
        self.titleLabel.setFont(font)
        self.titleLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.titleLabel.setObjectName("titleLabel")
        self.titleLabel.setText("Text to Kill")
        self.subtitleLabel = QLabel(self.menuPage)
        self.subtitleLabel.setGeometry(QtCore.QRect(100, 140, 600, 40))
        font.setPointSize(25)
        self.subtitleLabel.setFont(font)
        self.subtitleLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.subtitleLabel.setObjectName("subtitleLabel")
        self.subtitleLabel.setText("The Murder Mystery Automation System")
        self.createButton = QPushButton(self.menuPage)
        self.createButton.setGeometry(QtCore.QRect(310, 260, 180, 60))
        self.createButton.setObjectName("createButton")
        self.createButton.setText("Create Game")
        self.runButton = QPushButton(self.menuPage)
        self.runButton.setGeometry(QtCore.QRect(310, 350, 180, 60))
        self.runButton.setObjectName("runButton")
        self.runButton.setText("Run Game")
        self.stackedWidget.addWidget(self.menuPage)
        
        # Create page
        self.createPage = QWidget()
        self.createPage.setObjectName("createPage")
        self.createTabWidget = QTabWidget(self.createPage)
        self.createTabWidget.setGeometry(QtCore.QRect(0, 0, 800, 600))

        self.createTabWidget.setFocusPolicy(QtCore.Qt.NoFocus)
        self.createTabWidget.setObjectName("createTabWidget")
        
        # Create game tab
        self.createTab = QWidget()
        self.createTab.setObjectName("createTab")
        self.createDoneButton = QPushButton(self.createTab)
        self.createDoneButton.setGeometry(QtCore.QRect(580, 470, 180, 60))
        self.createDoneButton.setObjectName("createDoneButton")
        self.createDoneButton.setText("Done")
        self.gameNameEdit = QLineEdit(self.createTab)
        self.gameNameEdit.setGeometry(QtCore.QRect(140, 20, 160, 30))
        self.gameNameEdit.setObjectName("gameNameEdit")
        self.gameNameLabel = QLabel(self.createTab)
        self.gameNameLabel.setGeometry(QtCore.QRect(20, 25, 110, 20))

        font.setPointSize(15)
        self.gameNameLabel.setFont(font)
        self.gameNameLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.gameNameLabel.setObjectName("gameNameLabel")
        self.gameNameLabel.setText("Game name")
        self.line = QFrame(self.createTab)
        self.line.setGeometry(QtCore.QRect(20, 150, 311, 20))
        self.line.setFrameShape(QFrame.HLine)
        self.line.setFrameShadow(QFrame.Sunken)
        self.line.setObjectName("line")
        self.addCharLabel = QLabel(self.createTab)
        self.addCharLabel.setGeometry(QtCore.QRect(20, 180, 160, 20))
        
        font.setPointSize(20)
        self.addCharLabel.setFont(font)
        self.addCharLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.addCharLabel.setObjectName("addCharLabel")
        self.addCharLabel.setText("Add Character")
        self.charNameLabel = QLabel(self.createTab)
        self.charNameLabel.setGeometry(QtCore.QRect(20, 230, 66, 20))

        font.setPointSize(15)
        self.charNameLabel.setFont(font)
        self.charNameLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.charNameLabel.setObjectName("charNameLabel")
        self.charNameLabel.setText("Name")
        self.charNameEdit = QLineEdit(self.createTab)
        self.charNameEdit.setGeometry(QtCore.QRect(140, 220, 160, 30))
        self.charNameEdit.setObjectName("charNameEdit")
        self.charAbilScroll = QListWidget(self.createTab)
        self.charAbilScroll.setGeometry(QtCore.QRect(140, 260, 161, 51))
        self.charAbilScroll.setObjectName("charAbilScroll")
        self.characterTable = QTableWidget(self.createTab)
        self.characterTable.setGeometry(QtCore.QRect(405, 20, 381, 401))
        self.characterTable.setFocusPolicy(QtCore.Qt.NoFocus)
        self.characterTable.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.characterTable.setRowCount(1)
        self.characterTable.setColumnCount(2)
        self.characterTable.setObjectName("characterTable")
        self.characterTable.horizontalHeader().setVisible(False)
        self.characterTable.horizontalHeader().setCascadingSectionResizes(False)
        self.characterTable.horizontalHeader().setMinimumSectionSize(50)
        self.characterTable.horizontalHeader().setStretchLastSection(True)
        self.characterTable.verticalHeader().setVisible(False)
        self.characterTable.verticalHeader().setDefaultSectionSize(30)
        self.scrollArea = QListWidget(self.createTab)
        self.scrollArea.setGeometry(QtCore.QRect(140, 60, 161, 71))
        self.scrollArea.setObjectName("scrollArea")
        self.scrollArea.setSelectionMode(3)
        self.createSaveButton = QPushButton(self.createTab)
        self.createSaveButton.setGeometry(QtCore.QRect(380, 470, 180, 60))
        self.createSaveButton.setObjectName("createSaveButton")
        self.createSaveButton.setText("Save")
        self.charAbilitiesLabel = QLabel(self.createTab)
        self.charAbilitiesLabel.setGeometry(QtCore.QRect(30, 280, 71, 20))

        font.setPointSize(15)
        self.charAbilitiesLabel.setFont(font)
        self.charAbilitiesLabel.setObjectName("charAbilitiesLabel")
        self.charAbilitiesLabel.setText("Abilities")
        self.abilitiesDropdown = QComboBox(self.createTab)
        self.abilitiesDropdown.setGeometry(QtCore.QRect(140, 330, 151, 25))
        self.abilitiesDropdown.setObjectName("abilitiesDropdown")
        
        self.addCharButton = QPushButton(self.createTab)
        self.addCharButton.setGeometry(QtCore.QRect(30, 370, 98, 27))
        self.addCharButton.setObjectName("addCharButton")
        self.addCharButton.setText("Add")
        self.gameAbilitiesLabel = QLabel(self.createTab)
        self.gameAbilitiesLabel.setGeometry(QtCore.QRect(30, 80, 71, 20))
        
        self.setGameAbilButton = QPushButton(self.createTab)
        self.setGameAbilButton.setGeometry(QtCore.QRect(30, 110, 71, 27))
        self.setGameAbilButton.setObjectName("setGameAbilButton")
        self.setGameAbilButton.setText("Set")
        
        self.saveCharButton = QPushButton(self.createTab)
        self.saveCharButton.setGeometry(QtCore.QRect(70, 430, 180, 60))
        self.saveCharButton.setObjectName("saveCharButton")
        self.saveCharButton.setText("Save Character")

        font.setPointSize(15)
        self.gameAbilitiesLabel.setFont(font)
        self.gameAbilitiesLabel.setObjectName("gameAbilitiesLabel")
        self.gameAbilitiesLabel.setText("Abilities")
        self.createTabWidget.addTab(self.createTab, "")
        
        # Setup tab widget
        self.setupTab = QWidget()
        self.setupTab.setObjectName("setupTab")
        self.setupDoneButton = QPushButton(self.setupTab)
        self.setupDoneButton.setGeometry(QtCore.QRect(580, 470, 180, 60))
        self.setupDoneButton.setObjectName("setupDoneButton")
        self.setupDoneButton.setText("Done")
        self.setupTable = QTableWidget(self.setupTab)
        self.setupTable.setGeometry(QtCore.QRect(20, 20, 750, 400))
        self.setupTable.setFocusPolicy(QtCore.Qt.TabFocus)
        self.setupTable.setRowCount(1)
        self.setupTable.setColumnCount(3)
        self.setupTable.setObjectName("setupTable")
        self.setupTable.horizontalHeader().setVisible(False)
        self.setupTable.horizontalHeader().setCascadingSectionResizes(False)
        self.setupTable.horizontalHeader().setDefaultSectionSize(187)
        self.setupTable.horizontalHeader().setHighlightSections(False)
        self.setupTable.horizontalHeader().setStretchLastSection(True)
        self.setupTable.verticalHeader().setVisible(False)
        self.setupTable.verticalHeader().setHighlightSections(False)
        self.setupSaveButton = QPushButton(self.setupTab)
        self.setupSaveButton.setGeometry(QtCore.QRect(380, 470, 180, 60))
        self.setupSaveButton.setObjectName("setupSaveButton")
        self.setupSaveButton.setText("Save")
        self.createTabWidget.addTab(self.setupTab, "")
        self.createTabWidget.setTabText(self.createTabWidget.indexOf(self.createTab), "Create New Game")
        self.createTabWidget.setTabText(self.createTabWidget.indexOf(self.setupTab), "Set Up Game")
        self.stackedWidget.addWidget(self.createPage)
        
        # Game page
        self.gamePage = QWidget()
        self.gamePage.setObjectName("gamePage")
        self.gameTabWidget = QTabWidget(self.gamePage)
        self.gameTabWidget.setGeometry(QtCore.QRect(0, 0, 800, 600))
        self.gameTabWidget.setFocusPolicy(QtCore.Qt.NoFocus)
        self.gameTabWidget.setObjectName("gameTabWidget")
        self.statusTab = QWidget()
        self.statusTab.setObjectName("statusTab")
        self.startGameButton = QPushButton(self.statusTab)
        self.startGameButton.setGeometry(QtCore.QRect(60, 180, 180, 60))
        self.startGameButton.setObjectName("startGameButton")
        self.startGameButton.setText("Start Game")
        self.endGameButton = QPushButton(self.statusTab)
        self.endGameButton.setGeometry(QtCore.QRect(60, 260, 180, 60))
        self.endGameButton.setObjectName("endGameButton")
        self.endGameButton.setText("End Game")
        self.loadGameLabel = QLabel(self.statusTab)
        self.loadGameLabel.setGeometry(QtCore.QRect(20, 65, 101, 21))

        font.setPointSize(15)
        self.loadGameLabel.setFont(font)
        self.loadGameLabel.setObjectName("loadGameLabel")
        self.loadGameLabel.setText("Load Game")
        self.gameTabWidget.addTab(self.statusTab, "")
        self.logTab = QWidget()
        self.logTab.setObjectName("logTab")
        self.logList = QListWidget(self.logTab)
        self.logList.setGeometry(QtCore.QRect(30, 30, 730, 500))
        self.logList.setObjectName("logList")
        self.gameTabWidget.addTab(self.logTab, "")
        self.inputTab = QWidget()
        self.inputTab.setObjectName("inputTab")
        self.gameTabWidget.addTab(self.inputTab, "")
        self.gameTabWidget.setTabText(self.gameTabWidget.indexOf(self.statusTab), "Game Status")
        self.gameTabWidget.setTabText(self.gameTabWidget.indexOf(self.logTab), "Game Log")
        self.gameTabWidget.setTabText(self.gameTabWidget.indexOf(self.inputTab), "Input")
        self.stackedWidget.addWidget(self.gamePage)
        self.gridLayout.addWidget(self.stackedWidget, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)

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

    def retranslateUi(self, MainWindow):
        pass
예제 #18
0
class ParamSpinBox(QAbstractSpinBox):
    def __init__(self, parent):
        QAbstractSpinBox.__init__(self, parent)

        self._minimum = 0.0
        self._maximum = 1.0
        self._default = 0.0
        self._value = None
        self._step = 0.0
        self._step_small = 0.0
        self._step_large = 0.0

        self._read_only = False
        self._scalepoints = None
        self._have_scalepoints = False

        self.bar = ParamProgressBar(self)
        self.bar.setContextMenuPolicy(Qt.NoContextMenu)
        self.bar.show()

        self.lineEdit().setVisible(False)

        self.connect(self.bar, SIGNAL("valueChangedFromBar(double)"), self.handleValueChangedFromBar)
        self.connect(self, SIGNAL("customContextMenuRequested(QPoint)"), self.showCustomMenu)

        QTimer.singleShot(0, self, SLOT("slot_updateBarGeometry()"))

    def force_plastique_style(self):
        self.setStyle(QPlastiqueStyle)

    def set_minimum(self, value):
        self._minimum = value
        self.bar.set_minimum(value)

    def set_maximum(self, value):
        self._maximum = value
        self.bar.set_maximum(value)

    def set_default(self, value):
        value = fix_value(value, self._minimum, self._maximum)
        self._default = value

    def set_value(self, value, send=True):
        value = fix_value(value, self._minimum, self._maximum)
        if self._value != value:
            self._value = value
            self.bar.set_value(value)

            if self._have_scalepoints:
                self.set_scalepoint_value(value)

            if send:
                self.emit(SIGNAL("valueChanged(double)"), value)

            self.update()

            return True

        else:
            return False

    def set_step(self, value):
        if value == 0.0:
            self._step = 0.001
        else:
            self._step = value

    def set_step_small(self, value):
        if value == 0.0:
            self._step_small = 0.0001
        else:
            self._step_small = value

    def set_step_large(self, value):
        if value == 0.0:
            self._step_large = 0.1
        else:
            self._step_large = value

    def set_label(self, label):
        self.bar.set_label(label)

    def set_text_call(self, textCall):
        self.bar.set_text_call(textCall)

    def set_read_only(self, yesno):
        self.setButtonSymbols(QAbstractSpinBox.UpDownArrows if yesno else QAbstractSpinBox.NoButtons)
        self._read_only = yesno
        self.setReadOnly(yesno)

    def set_scalepoints(self, scalepoints, use_scalepoints):
        if len(scalepoints) > 0:
            self._scalepoints = scalepoints
            self._have_scalepoints = use_scalepoints

            if use_scalepoints:
                # Hide ProgressBar and create a ComboBox
                self.bar.close()
                self.box = QComboBox(self)
                self.box.setContextMenuPolicy(Qt.NoContextMenu)
                self.box.show()
                self.slot_updateBarGeometry()

                for scalepoint in scalepoints:
                    self.box.addItem("%f - %s" % (scalepoint['value'], scalepoint['label']))

                if self._value != None:
                    self.set_scalepoint_value(self._value)

                self.connect(self.box, SIGNAL("currentIndexChanged(QString)"), self.handleValueChangedFromBox)

        else:
            self._scalepoints = None

    def set_scalepoint_value(self, value):
        value = self.get_nearest_scalepoint(value)
        for i in range(self.box.count()):
            if float(self.box.itemText(i).split(" - ", 1)[0] == value):
                self.box.setCurrentIndex(i)
                break

    def get_nearest_scalepoint(self, real_value):
        final_value = 0.0
        for i in range(len(self._scalepoints)):
            scale_value = self._scalepoints[i]['value']
            if i == 0:
                final_value = scale_value
            else:
                srange1 = abs(real_value - scale_value)
                srange2 = abs(real_value - final_value)

                if srange2 > srange1:
                    final_value = scale_value

        return final_value

    def handleValueChangedFromBar(self, value):
        if self._read_only:
            return

        step = int(0.5 + ((value - self._minimum) / self._step))
        real_value = self._minimum + (step * self._step)

        self.set_value(real_value)

    def handleValueChangedFromBox(self, box_text):
        if self._read_only:
            return

        value = float(box_text.split(" - ", 1)[0])
        last_scale_value = self._scalepoints[len(self._scalepoints) - 1]['value']

        if value == last_scale_value:
            value = self._maximum

        self.set_value(value)

    def showCustomMenu(self, pos):
        menu = QMenu(self)
        act_x_reset = menu.addAction(self.tr("Reset (%f)" % self._default))
        menu.addSeparator()
        act_x_copy = menu.addAction(self.tr("Copy (%f)" % self._value))
        if False and not self._read_only:
            act_x_paste = menu.addAction(self.tr("Paste (%s)" % "TODO"))
        else:
            act_x_paste = menu.addAction(self.tr("Paste"))
            act_x_paste.setEnabled(False)
        menu.addSeparator()
        act_x_set = menu.addAction(self.tr("Set value..."))

        if self._read_only:
            act_x_reset.setEnabled(False)
            act_x_paste.setEnabled(False)
            act_x_set.setEnabled(False)

        # TODO - NOT IMPLEMENTED YET
        act_x_copy.setEnabled(False)

        act_x_sel = menu.exec_(QCursor.pos())

        if act_x_sel == act_x_set:
            dialog = CustomInputDialog(self, self.parent().label.text(), self._value, self._minimum, self._maximum, self._step, self._scalepoints)
            if dialog.exec_():
                value = dialog.ret_value
                self.set_value(value)

        elif act_x_sel == act_x_copy:
            pass

        elif act_x_sel == act_x_paste:
            pass

        elif act_x_sel == act_x_reset:
            self.set_value(self._default)

    def stepBy(self, steps):
        if steps == 0 or self._value == None:
            return

        value = self._value + (steps * self._step)

        if value < self._minimum:
            value = self._minimum
        elif value > self._maximum:
            value = self._maximum

        self.set_value(value)

    def stepEnabled(self):
        if self._read_only or self._value == None:
            return QAbstractSpinBox.StepNone
        elif self._value <= self._minimum:
            return QAbstractSpinBox.StepUpEnabled
        elif self._value >= self._maximum:
            return QAbstractSpinBox.StepDownEnabled
        else:
            return QAbstractSpinBox.StepUpEnabled | QAbstractSpinBox.StepDownEnabled

    def updateAll(self):
        self.update()
        self.bar.update()
        if self._have_scalepoints:
            self.box.update()

    @pyqtSlot()
    def slot_updateBarGeometry(self):
        self.bar.setGeometry(self.lineEdit().geometry())
        if self._have_scalepoints:
            self.box.setGeometry(self.lineEdit().geometry())

    def resizeEvent(self, event):
        QTimer.singleShot(0, self, SLOT("slot_updateBarGeometry()"))
        QAbstractSpinBox.resizeEvent(self, event)
예제 #19
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")
예제 #20
0
class SentenceFillDlg(QDialog, ui_sentencefilldlg.Ui_SentenceFillDlg):
	
	def __init__(self, tableName, rangeValues, parent=None):
		super(SentenceFillDlg, self).__init__(parent)
		self.tableName = tableName
		self.rangeValues = rangeValues
		self.setupUi(self)
		self.initUI()
		
	def initUI(self):
		fontLabel = QFont('SansSerif', 14)
		
		self.setMinimumSize(1200, 600)
		self.resize(1200, 600)
		
		self.sentenceToFillTable = QTableWidget(5, 1, self)
		self.sentenceToFillTable.setGeometry(QRect(70, 60, 800, 400))
		
		self.sentenceToFillTable.setColumnCount(1)
		
		item = QTableWidgetItem()
		item.setText('Sentences To Match')
		font = QFont()
		font.setBold(True)
		font.setWeight(75)
		item.setFont(font)
		self.sentenceToFillTable.setHorizontalHeaderItem(0, item)
		self.sentenceToFillTable.resizeColumnsToContents()
		self.sentenceToFillTable.horizontalHeader().setStretchLastSection(True)
		self.sentenceToFillTable.verticalHeader().setStretchLastSection(True)
		
		self.sentenceList = []
		self.getSentencesFromDatabase()
		
		# split the sentences into chunks of 5
		# Map to hold the anwers
		self.rightWordList = {}
		
		self.iteration = 0
		self.sentenceMasterList = []
		self.sentenceSlaveList = []
		
		if len(self.sentenceList) > 0:			
			for sentence in self.sentenceList:
				if len(self.sentenceSlaveList) < 5:
					self.sentenceSlaveList.append(sentence)
				else:
					self.sentenceMasterList.append(self.sentenceSlaveList)
					self.sentenceSlaveList = []
					self.sentenceSlaveList.append(sentence)
					
			if len(self.sentenceSlaveList) <= 5:
				self.sentenceMasterList.append(self.sentenceSlaveList)
				
			self.maxIteration = len(self.sentenceMasterList)
		
		
		## set the row height
		self.tableHeightSize = 0
		## Only if there is atleast one sentence fetched from the database
		if len(self.sentenceList) > 0:			
			for index in range(0, 5):
				if len(self.sentenceList[index]) < 150:
					self.sentenceToFillTable.verticalHeader().resizeSection(index, 80)
					self.tableHeightSize = self.tableHeightSize + 90
				elif len(self.sentenceList[index]) < 200:
					self.sentenceToFillTable.verticalHeader().resizeSection(index, 100)
					self.tableHeightSize = self.tableHeightSize + 100
				else:
					self.sentenceToFillTable.verticalHeader().resizeSection(index, 120)
					self.tableHeightSize = self.tableHeightSize + 120
			
				
			# split words from databse into chunks of 5
		
			self.refIteration = 0
			self.refWordMasterList = []
			self.refWordSlaveList = []
			for wordList in self.wordMap.values():
				if len(self.refWordSlaveList) < 5:
					self.refWordSlaveList.append(wordList)
				else:
					self.refWordMasterList.append(self.refWordSlaveList)
					self.refWordSlaveList = []
					self.refWordSlaveList.append(wordList)
			
			if len(self.refWordSlaveList) <= 5:
				self.refWordMasterList.append(self.refWordSlaveList)
				
			self.refMaxIteration = len(self.refWordMasterList)
		
			self.insertSentencesInTable()
		
		self.connect(self.sentenceToFillTable, SIGNAL("cellClicked(int, int)"), self.itemSelect)
		
		# create next, submit and close buttons
		self.nextButton = QPushButton('Next', self)
		self.nextButton.move(170, 520)
		self.nextButton.setEnabled(False)  
		
		self.submitButton = QPushButton('Submit', self)
		self.submitButton.move(380, 520)
		
		self.closeButton = QPushButton('Close', self)
		self.closeButton.move(600, 520)
		
		self.connect(self.closeButton, SIGNAL('clicked()'), self.closeClicked)
		
		self.connect(self.submitButton, SIGNAL('clicked()'), self.onSubmitClicked)
		
		self.connect(self.nextButton, SIGNAL('clicked()'), self.onNextClicked)
		
		self.setWindowTitle('Sentence Fill')
		
		#self.setGeometry(10, 80, 1100, 750)


	def getSentencesFromDatabase(self):
		self.twoTypeList = data.Data().getSentencesFromDatabase(self.tableName, self.rangeValues)
		if len(self.twoTypeList) == 2:
			self.sentenceList = self.twoTypeList[0]
			self.wordMap = self.twoTypeList[1]

	def closeClicked(self):
		reply = QMessageBox.question(self,
					"Fill the Sentences",
					"You want to close the application",
					QMessageBox.Yes | QMessageBox.No)
		if reply == QMessageBox.Yes:
			self.reject()
			
	def onNextClicked(self):
		if not self.iteration < self.maxIteration:
			QMessageBox.information(self,
					"Fill the Sentences",
					"All Sentences are matched",
					QMessageBox.Ok)
		else:
			self.sentenceToFillTable.clearContents()
			## Fetch the next records
			self.refIteration = self.refIteration + 1
			self.rightWordList = {}
			## clear the contents of the combo box
			self.wordListComboBox.clear()
			self.insertSentencesInTable()
	
	# validate whether the user has matched the blanks with a value during next and submit button clicks
	def onNextSubmitValidation(self):
		self.textNotFilled = False
		for row in range(0, len(self.currentSentenceListInTable)):
			if self.sentenceToFillTable.item(row, 0).text() == self.currentSentenceListInTable[row]:
				self.textNotFilled = True
		if self.textNotFilled:
			QMessageBox.information(self,
						"Fill the sentences",
						"Match all the sentences in the table",
						QMessageBox.Ok)
			self.nextButton.setEnabled(False)
			
			
	def onSubmitClicked(self):
		self.wordsMatched = True
		self.allWordsMatched = True
		brushRed = QBrush(QColor(255,0,0))
		brushRed.setStyle(Qt.SolidPattern)
		
		brushGreen = QBrush(QColor(0,255,0))
		brushGreen.setStyle(Qt.SolidPattern)
		
		# validate whether the user all matched the blanks with a value
		#self.onNextSubmitValidation()
		textNotFilled = False
		for row in range(0, len(self.currentSentenceListInTable)):
			if self.sentenceToFillTable.item(row, 0).text() == self.currentSentenceListInTable[row]:
				textNotFilled = True
		if textNotFilled:
			QMessageBox.information(self,
						"Fill the sentences",
						"Match all the sentences in the table",
						QMessageBox.Ok)
		else:
			splittedSentence = []
			foundWordInSentence = ""
			self.rightWordListCopy = self.rightWordList
			for row in range(0, len(self.currentSentenceListInTable)):
				sentenceFilled = str(self.sentenceToFillTable.item(row, 0).text())
				newSplittedSentence = [word.strip() for word in sentenceFilled.split()]
				splittedSentence = []
				for word in newSplittedSentence:
					match = re.search(r'\w+', word)
					if match:
						splittedSentence.append(str(match.group()))
				
				wordList = self.rightWordListCopy[row]
				
				if len(wordList) > 1:
					firstWord = wordList[0].strip()
					secondWord = wordList[1].strip()
					if ' ' in firstWord:
						for word in firstWord.split():
							if word not in splittedSentence:
								self.wordsMatched = False
					else:
						if firstWord not in splittedSentence:
							self.wordsMatched = False
					
					if self.wordsMatched: ## check is valid only if the first word is matched
						if ' ' in secondWord:
							for word in secondWord.split():
								if word not in splittedSentence:
									self.wordsMatched = False
						else:
							if secondWord not in splittedSentence:
								self.wordsMatched = False
				elif len(wordList) == 1:
					word = wordList[0].strip()
					if word not in splittedSentence:
						self.wordsMatched = False
				
				if self.wordsMatched:
					self.sentenceToFillTable.item(row, 0).setBackground(brushGreen)
				else:
					self.sentenceToFillTable.item(row, 0).setBackground(brushRed)
					self.allWordsMatched = False
				
				self.wordsMatched = True
					
			if self.allWordsMatched:
				self.nextButton.setEnabled(True)
				QMessageBox.information(self,
								"Fill the sentences",
								"All sentences are matched",
								QMessageBox.Ok)

	def insertSentencesInTable(self):
		if self.iteration < self.maxIteration:
			cellList = []
			self.col = 0
			self.currentSentenceListInTable = self.sentenceMasterList[self.iteration]
			for sentence in self.currentSentenceListInTable:
				item = QTableWidgetItem(QString(sentence))
				item.setFlags(Qt.ItemFlags(Qt.ItemIsSelectable |
								Qt.ItemIsEnabled))
				cellList.append(item)
			cellList.reverse()
			
			for index in range(0, len(self.currentSentenceListInTable)):
				self.sentenceToFillTable.setItem(index, self.col, cellList.pop())
				
			self.sentenceToFillTable.setRowCount(len(self.sentenceMasterList[self.iteration]))
			
			self.sentenceToFillTable.setFixedHeight(self.tableHeightSize)
			
			# increment the count for the next button click
			self.iteration = self.iteration + 1
			
	def createComboBox(self, rowIndex):
		self.xAxis = 1000
		self.yAxis = 80
		
		if self.refIteration < self.refMaxIteration:
			wordListWithFiveArrays = self.refWordMasterList[self.refIteration]
			requiredWordList = wordListWithFiveArrays[rowIndex]
			
			## Create a combo box
			self.wordListComboBox = QComboBox(self)
			self.wordListComboBox.setGeometry(900, 80, 100, 20)
			self.connect(self.wordListComboBox, SIGNAL("currentIndexChanged(int)"),
							self.wordSelected)
			self.wordListComboBox.show()
			
			## save the right word
			if len(requiredWordList) > 0:
				if rowIndex not in self.rightWordList.keys():
					if len(requiredWordList) > 0:
						wordList = requiredWordList[0].split('&')
						self.rightWordList[rowIndex] = wordList

			## insert words in the combo box
			random.shuffle(requiredWordList)
			random.shuffle(requiredWordList)
			
			self.wordListComboBox.addItem('         ')
			self.wordListComboBox.addItems(requiredWordList)
	
	def wordSelected(self):
		## Avoid the blank option
		if len(str(self.wordListComboBox.currentText()).strip()) > 0:
			sentence = self.currentSentenceListInTable[self.selectedSentenceIndex]
			splittedText = sentence.split('-')
			if len(splittedText) == 2:
				item = QTableWidgetItem(QString(splittedText[0] +
						str(self.wordListComboBox.currentText()) + ' ' + splittedText[1].strip()))
				item.setFlags(Qt.ItemFlags(Qt.ItemIsSelectable | 
								Qt.ItemIsEnabled))
				self.sentenceToFillTable.setItem(self.selectedSentenceIndex, 0, item)
			elif len(splittedText) > 2:
				wordsFromCombobox = str(self.wordListComboBox.currentText()).split('&')
				item = QTableWidgetItem(QString(splittedText[0] + wordsFromCombobox[0]
							+ splittedText[1] + wordsFromCombobox[1] + ' ' + splittedText[2].strip()))
				item.setFlags(Qt.ItemFlags(Qt.ItemIsSelectable | 
							Qt.ItemIsEnabled))
				self.sentenceToFillTable.setItem(self.selectedSentenceIndex, 0, item)
	
	def createIndexForWords(self):
		self.indexForWords = {}
		self.nextIndex = 0
		for word in self.refWordListForIndex:
			if self.nextIndex == 5:
				break
			self.indexForWords[word] = self.nextIndex
			self.nextIndex = self.nextIndex + 1
	
	def itemSelect(self,rowIndex):
		self.createComboBox(rowIndex)
		self.selectedSentenceIndex = rowIndex