Ejemplo n.º 1
0
class BotTab(TabWidget):

    key = 'BotTab'

    def __init__(self, parent=None):
        super(BotTab, self).__init__(parent)

        self.parent = parent
        self.layout = VBoxLayout()
        self.buildUI()
        self.setLayout(self.layout)

    def buildUI(self):

        self.botTab1 = BotTab1(self.parent)
        self.botTab2 = BotTab2(self.parent)

        self.tabs = DAMGLIST(listData=[self.botTab1, self.botTab2])
        self.tabNames = DAMGLIST(listData=['General', 'Debug'])

        for layout in self.tabs:
            # layout.signals.connect('executing', self.signals.executing)
            # layout.signals.connect('regisLayout', self.signals.regisLayout)
            # layout.signals.connect('openBrowser', self.signals.openBrowser)
            # layout.signals.connect('setSetting', self.signals.setSetting)
            # layout.signals.connect('showLayout', self.signals.showLayout)
            # layout.settings._settingEnable = True

            self.addTab(layout,
                        AppIcon(32, self.tabNames[self.tabs.index(layout)]),
                        self.tabNames[self.tabs.index(layout)])
            self.setTabIcon(
                self.tabs.index(layout),
                AppIcon(32, self.tabNames[self.tabs.index(layout)]))
Ejemplo n.º 2
0
    def checkSignalRepeat(self, old, data):
        new = [i for i in data]

        if self.print_checkRepeat:
            print(new, old)

        if len(new) == 0:
            repeat = False
        elif len(new) == len(old):
            repeat = True
            for i in range(len(new)):
                if not new[i] == old[i]:
                    repeat = False
                    break
        else:
            repeat = False

        old = DAMGLIST()
        old.appendList(new)
        return old, repeat


# -------------------------------------------------------------------------------------------------------------
# Created by panda on 25/10/2019 - 6:59 AM
# © 2017 - 2018 DAMGteam. All rights reserved
Ejemplo n.º 3
0
    def buildUI(self):

        self.tab1 = TopTab1.TopTab1(self.buttonManager, self.parent)
        self.tab2 = TopTab2.TopTab2(self.buttonManager, self.parent)
        self.tab3 = TopTap3.TopTap3(self.buttonManager, self.parent)

        self.tabs = DAMGLIST(listData=[self.tab1, self.tab2, self.tab3])
        self.tabNames = DAMGLIST(listData=['Common', 'User', 'Cmd'])

        for tab in self.tabs:
            # tab.signals.connect('executing', self.signals.executing)
            # tab.signals.connect('regisLayout', self.signals.regisLayout)
            # tab.signals.connect('openBrowser', self.signals.openBrowser)
            # tab.signals.connect('setSetting', self.signals.setSetting)
            # tab.signals.connect('showLayout', self.signals.showLayout)
            # tab.settings._settingEnable = True
            if self.mode == 'Offline':
                if tab.key == 'TopTab2':
                    pass
                else:
                    self.addTab(tab, self.tabNames[self.tabs.index(tab)])
                    self.setTabIcon(
                        self.tabs.index(tab),
                        AppIcon(32, self.tabNames[self.tabs.index(tab)]))
            else:
                self.addTab(tab, self.tabNames[self.tabs.index(tab)])
                self.setTabIcon(
                    self.tabs.index(tab),
                    AppIcon(32, self.tabNames[self.tabs.index(tab)]))

        self.signals.updateAvatar.connect(self.tab2.update_avatar)
Ejemplo n.º 4
0
class InspectLayout(DAMG):

    key = 'InspectLayout'
    layoutTypes = DAMGLIST()
    layoutKeys = DAMGLIST()

    def __init__(self, parent=None):
        super(InspectLayout, self).__init__(parent)

        self.layoutTypes.appendList(layoutTypes)

    def doInspection(self, layout):
        self.layoutTypes.append(layout.Type)
        self.layoutKeys.append(layout.key)
        return layout

    def checkType(self, layout):
        if not self.haveType(layout):
            try:
                layout.show()
            except AttributeError:
                layoutType = 'Object'
            else:
                layoutType = 'UI'
            layout.__setattr__('Type', layoutType)

        return self.checkKey(layout)

    def checkKey(self, layout):
        if not self.haveKey(layout):
            key = layout.__class__.__name__
            layout.__setattr__('key', key)

        return layout

    def haveType(self, layout):
        try:
            layout.Type
        except AttributeError:
            return False
        else:
            return True

    def haveKey(self, layout):
        try:
            layout.key
        except KeyError:
            return False
        else:
            return True
Ejemplo n.º 5
0
class ThreadManager(DAMGTHREADPOOL):

    tasks = DAMGLIST()

    def __init__(self):
        super(ThreadManager, self).__init__()

        self.counter = Counting()

    def startCounting(self):
        self.counter.begin()

    def stopCounting(self):
        self.counter.finish()

    def serviceThread(self):
        thread = BackgroundService()
        self.threads.append(thread)
        return thread

    def setCountLimited(self, val):
        return self.counter.setCountLimited(val)

    def setPrintCounter(self, bool):
        return self.counter.setPrintCounter(bool)

    def isCounting(self):
        return self.counter.isCounting


# -------------------------------------------------------------------------------------------------------------
# Created by panda on 20/10/2019 - 6:23 PM
# © 2017 - 2018 DAMGteam. All rights reserved
Ejemplo n.º 6
0
    def buildUI(self):

        self.botTab1 = BotTab1(self.parent)
        self.botTab2 = BotTab2(self.parent)

        self.tabs = DAMGLIST(listData=[self.botTab1, self.botTab2])
        self.tabNames = DAMGLIST(listData=['General', 'Debug'])

        for layout in self.tabs:
            # layout.signals.connect('executing', self.signals.executing)
            # layout.signals.connect('regisLayout', self.signals.regisLayout)
            # layout.signals.connect('openBrowser', self.signals.openBrowser)
            # layout.signals.connect('setSetting', self.signals.setSetting)
            # layout.signals.connect('showLayout', self.signals.showLayout)
            # layout.settings._settingEnable = True

            self.addTab(layout,
                        AppIcon(32, self.tabNames[self.tabs.index(layout)]),
                        self.tabNames[self.tabs.index(layout)])
            self.setTabIcon(
                self.tabs.index(layout),
                AppIcon(32, self.tabNames[self.tabs.index(layout)]))
Ejemplo n.º 7
0
class TopTab(TabWidget):

    key = 'TopTab'

    def __init__(self, buttonManager, parent=None):
        super(TopTab, self).__init__(parent)

        self.parent = parent
        self.layout = VBoxLayout()
        self.buttonManager = buttonManager
        self.mode = self.parent.mode
        self.buildUI()
        self.setLayout(self.layout)

    def buildUI(self):

        self.tab1 = TopTab1.TopTab1(self.buttonManager, self.parent)
        self.tab2 = TopTab2.TopTab2(self.buttonManager, self.parent)
        self.tab3 = TopTap3.TopTap3(self.buttonManager, self.parent)

        self.tabs = DAMGLIST(listData=[self.tab1, self.tab2, self.tab3])
        self.tabNames = DAMGLIST(listData=['Common', 'User', 'Cmd'])

        for tab in self.tabs:
            # tab.signals.connect('executing', self.signals.executing)
            # tab.signals.connect('regisLayout', self.signals.regisLayout)
            # tab.signals.connect('openBrowser', self.signals.openBrowser)
            # tab.signals.connect('setSetting', self.signals.setSetting)
            # tab.signals.connect('showLayout', self.signals.showLayout)
            # tab.settings._settingEnable = True
            if self.mode == 'Offline':
                if tab.key == 'TopTab2':
                    pass
                else:
                    self.addTab(tab, self.tabNames[self.tabs.index(tab)])
                    self.setTabIcon(
                        self.tabs.index(tab),
                        AppIcon(32, self.tabNames[self.tabs.index(tab)]))
            else:
                self.addTab(tab, self.tabNames[self.tabs.index(tab)])
                self.setTabIcon(
                    self.tabs.index(tab),
                    AppIcon(32, self.tabNames[self.tabs.index(tab)]))

        self.signals.updateAvatar.connect(self.tab2.update_avatar)

    def resizeEvent(self, event):
        w = self.width()
        h = self.height()
        for tab in self.tabs:
            tab.resize(w - 4, h - 4)
Ejemplo n.º 8
0
class RegistryLayout(DAMGDICT):

    awaitingSlots = DAMGLIST()
    layout_names = DAMGLIST()
    layout_ids = DAMGLIST()
    layout_datetimes = DAMGLIST()
    layout_keys = DAMGLIST()

    def __init__(self):
        super(RegistryLayout, self).__init__(self)

        self.inspect = InspectLayout(self)

    def regisLayout(self, layout):

        ui = self.inspect.doInspection(layout)
        key = ui.key
        if self.isLayout(ui):
            if self.isAwaitingSlot(ui):
                self.awaitingSlots.remove(key)
                self.doRegister(ui)
            else:
                if not self.isRegistered(ui):
                    self.doRegister(ui)
                else:
                    print("Already registered: {0}".format(key))
                    return False

    def isAwaitingSlot(self, layout):
        key = layout.key
        if key in self.awaitingSlots:
            return True
        else:
            return False

    def doRegister(self, layout):
        key = layout.key

        self.layout_names.append(layout.name)
        self.layout_ids.append(id(layout))
        self.layout_datetimes.append(
            str(
                datetime.datetime.fromtimestamp(
                    time.time()).strftime('%H:%M:%S|%d.%m.%Y')))
        self.layout_keys.append(layout.key)

        # print("Registing layout: {0} : {1}".format(layout.key, layout))
        self[key] = layout
        return True

    def deRegister(self, layout):
        key = layout.key
        index = self.layout_names.index(layout.name)

        if self.isRegistered(layout):
            self.awaitingSlots.append(key)
            try:
                del self[key]
            except KeyError:
                self.pop(key, None)
            self.layout_names.remove(self.layout_names[index])
            self.layout_ids.remove(self.layout_ids[index])
            self.layout_datetimes.remove(self.layout_datetimes[index])
            return True
        else:
            return False

    def isRegistered(self, layout):
        key = layout.key
        if key in self.keys():
            return True
        else:
            return False

    def isLayout(self, layout):
        if layout.Type in self.inspect.layoutTypes:
            return True
        else:
            return False


# -------------------------------------------------------------------------------------------------------------
# Created by panda on 8/11/2019 - 4:18 PM
# © 2017 - 2018 DAMGteam. All rights reserved
Ejemplo n.º 9
0
class BodyCheckBoxes(GridLayout):

    key = 'BodyCheckBoxes'
    notificationCBs = DAMGLIST()
    checkboxes = DAMGDICT()

    def __init__(self, parent=None):
        super(BodyCheckBoxes, self).__init__(parent)
        self.parent = parent
        self.la = 0
        self.buildBodyCheckBoxes()

        cbs = [self.notificationCBs, [self.bodyCB]]

        for i in range(len(cbs)):
            if i == 0:
                prefix = 'Notification'
            else:
                prefix = 'Body'

            for cb in cbs[i]:
                cb.key = '{0}_{1}_CheckBox_{2}'.format(self.parent.key, prefix, cb.text())
                cb._name = '{0} {1} Check Box: {2}'.format(self.parent.key, prefix, cb.text())

                cb.settings._settingEnable = True
                state = cb.getValue('checkState')
                if state is None:
                    state = True
                cb.setValue('checkState', state)
                cb.setChecked(str2bool(state))
                self.checkboxes.add(cb.key, cb)

    def buildBodyCheckBoxes(self):
        self.buildNotificationCheckBoxes()
        self.bodyCB = CheckBox('Body')
        self.bodyCB.stateChanged.connect(self.bodyStateChanged)

        ntl = self.la
        bdl = ntl + 1

        self.addWidget(Label({'txt': 'Notification'}), ntl, 0, 1, 1)
        self.addWidget(self.allNotifiCB, ntl, 1, 1, 1)
        self.addWidget(self.cpuCB, ntl, 2, 1, 1)
        self.addWidget(self.ramCB, ntl, 3, 1, 1)
        self.addWidget(self.gpuCB, ntl, 4, 1, 1)
        self.addWidget(self.diskCB, ntl, 5, 1, 1)
        self.addWidget(self.timeCB, ntl, 6, 1, 1)
        self.addWidget(self.dateCB, ntl, 7, 1, 1)

        self.addWidget(Label({'txt': 'Body'}), bdl, 0, 1, 1)
        self.addWidget(self.bodyCB, bdl, 1, 1, 1)


        self.la = bdl + 1
        return self.la

    def buildNotificationCheckBoxes(self):
        self.cpuCB = CheckBox('cpu')
        self.ramCB = CheckBox('ram')
        self.gpuCB = CheckBox('gpu')
        self.diskCB = CheckBox('disk')
        self.timeCB = CheckBox('clock')
        self.dateCB = CheckBox('date')
        self.allNotifiCB = CheckBox("All: ")
        self.allNotifiCB.stateChanged.connect(self.allNotifiStateChanged)
        for cb in [self.cpuCB, self.ramCB, self.gpuCB, self.diskCB, self.timeCB, self.dateCB, self.allNotifiCB]:
            self.notificationCBs.append(cb)

    def allNotifiStateChanged(self, bool):
        for cb in self.notificationCBs:
            cb.setChecked(bool)

    def bodyStateChanged(self, bool):
        self.allNotifiStateChanged(bool)
Ejemplo n.º 10
0
class LocalDatabase(DAMG):

    key = 'LocalDatabase'
    _dbPath = DB_PTH
    conn = lite.connect(_dbPath)
    conn.text_factory = str
    cur = conn.cursor()
    tableNames = DAMGLIST()
    tables = DAMGDICT()
    db_types = DB_ATTRIBUTE_TYPE

    def __init__(self):
        super(LocalDatabase, self).__init__(self)

        self.date = DAMGDATE()
        self.time = DAMGTIMER()
        self.update()

    def update(self):
        self.tableNames = self.tableList()
        for table in self.tableNames:
            columnLst = self.columnList(table)
            self.tables.add(table, columnLst)
        self.tables.update()
        return self.tables

    def remove_data(self, tableName):
        self.cur.execute("SELECT * FROM {0}".format(tableName))
        self.cur.fetchall()
        self.cur.execute("DELETE FROM {0}".format(tableName))
        self.conn.commit()
        return

    def timelog(self, details):
        self.username, token, cookie, remember = self.query_table("curUser")
        time = self.time.currentTime()
        date = self.date.currentDate()

        self.cur.execute(
            "INSERT INTO timelog (username, time, date, details) VALUES (?,?,?,?)",
            (self.username, time, date, details))
        self.conn.commit()
        return

    def update_table(self, tableName, values):
        columns = self.columnList(tableName)
        prefix = "INSERT INTO {0}".format(tableName)
        midfix = "VALUES"

        cmd = ""
        vcmd = ""
        for i in range(len(columns)):
            cmd += columns[i] + ", "
            vcmd += values[i] + ", "
        command = "{0} ({1}) {2} ({3})".format(prefix, cmd, midfix, vcmd)
        self.cur.execute("{0}".format(command))
        self.conn.commit()
        return

    def columnList(self, tableName):
        result = self.cur.execute(
            "PRAGMA table_info({0})".format(tableName)).fetchall()
        columnLst = list(zip(*result))[1]
        return columnLst

    def tableList(self):
        result = self.cur.execute(
            "SELECT name FROM sqlite_master WHERE type='table';").fetchall()
        if result == []:
            table_names = result
        else:
            table_names = sorted(list(zip(*result))[0])
        return table_names

    def query_table(self, tableName="curUser"):
        self.cur.execute("SELECT * FROM {0}".format(tableName))
        data = self.cur.fetchall()
        return list(data[0])

    def generate_command(self, tableDetails):
        columnLst = [c for c in tableDetails.keys()]
        cmd = ""
        for i in range(len(columnLst)):
            column_name = columnLst[i]
            attribute_key = tableDetails[columnLst[i]]
            column_attribute = self.db_types[attribute_key]
            cmd += "{0} {1}".format(column_name, column_attribute)
        cmd = cmd[:-2]
        return cmd

    def create_table(self, tableName, tableDetails):
        cmd = self.generate_command(tableDetails)
        self.cur.execute("CREATE TABLE IF NOT EXISTS `{0}` ({1})".format(
            tableName, cmd))
        self.conn.commit()
        self.update()
        return

    def remove_table(self, tableName):
        self.cur.execute('DROP TABLE {0}'.format(tableName))
        self.conn.commit()
        self.update()
        return

    def create_foreign(self, id_name, table_name):
        value = 'INTERGER, FOREIGN KEY ({0}) REFERENCES {1} ({0}), '.format(
            id_name, table_name)
        return value


# -------------------------------------------------------------------------------------------------------------
# Created by panda on 3/06/2018 - 3:58 AM
# Pipeline manager - DAMGteam
Ejemplo n.º 11
0
class TopTap3(Widget):

    key = 'TerminalLayout'
    _name = 'TerminalLayout'

    commands = DAMGLIST()
    shotcuts = DAMGLIST()
    tracker = 0
    _cwd = os.getcwd().replace('\\', '/')
    _user = getpass.getuser()
    _host = socket.gethostname()

    def __init__(self, buttonManager, parent=None):
        super(TopTap3, self).__init__(parent)

        self.buttonManager = buttonManager
        self.parent = parent

        self.layout = VBoxLayout()

        self.buildUI()
        # QApplication.setCursorFlashTime(1000)
        self.setLayout(self.layout)
        self.setStyleSheet(mystylesheet(self))

    def buildUI(self):
        self.process = Process(self.dataReady, self.onError, self.onOutput,
                               self.isFinished, self)
        self.cmdField = PlainTextEdit({
            'lwm': QPlainTextEdit.NoWrap,
            'sfh': 25,
            'vsbp': SCROLLBAROFF,
            'adr': True
        })
        self.textWindow = PlainTextEdit({'rol': True}, self)
        self.cursor = self.cmdField.textCursor()
        self.copySelectedTextAction = ShortCut('Copy', 'Copy', 'Shift+Ctrl+c',
                                               self.copyText, self)
        self.cancelAction = ShortCut('Cancel', 'Cancel', 'Ctrl+c',
                                     self.killProcess, self)
        self.pasteTextAction = ShortCut('Paste', 'Paste', 'Shift+Ctrl+v',
                                        self.pasteText, self)
        self.textWindow.addActions(
            [self.cancelAction, self.copySelectedTextAction])
        self.cmdField.addAction(self.pasteTextAction)
        self.cmdField.installEventFilter(self)
        self.cursorEnd()
        sysinfo = QSysInfo()
        myMachine = "CPU Architecture: {0}***{1}***{2}***{3}".format(
            sysinfo.currentCpuArchitecture(), sysinfo.prettyProductName(),
            sysinfo.kernelType(), sysinfo.kernelVersion())
        self.statusBar = StatusBar(self)
        self.statusBar.showMessage(myMachine, 0)
        self.layout.addWidget(self.textWindow)
        self.layout.addWidget(self.cmdField)
        self.layout.addWidget(self.statusBar)

    def getUsername(self):
        return "{0}@{1}:{2}$".format(self._user, self._host, self._cwd)

    def cursorEnd(self):
        self.cmdField.setPlainText(self.getUsername())
        self.cursor.movePosition(11, 0)
        self.cmdField.setTextCursor(self.cursor)
        self.cmdField.setFocus()

    def eventFilter(self, source, event):
        if source == self.cmdField:
            if (event.type() == QEvent.DragEnter):
                event.accept()
                return True
            elif (event.type() == QEvent.Drop):
                # print('Drop')
                self.setDropEvent(event)
                return True
            elif (event.type() == QEvent.KeyPress):
                cursor = self.cmdField.textCursor()
                # print('key press:', (event.key(), event.text()))
                if event.key() == Qt.Key_Backspace:
                    if cursor.positionInBlock() <= len(self.getUsername()):
                        return True
                    else:
                        return False

                elif event.key() == Qt.Key_Return:
                    self.run()
                    return True

                elif event.key() == Qt.Key_Left:
                    if cursor.positionInBlock() <= len(self.getUsername()):
                        return True
                    else:
                        return False

                elif event.key() == Qt.Key_Delete:
                    if cursor.positionInBlock() <= len(self.getUsername()) - 1:
                        return True
                    else:
                        return False

                elif event.modifiers() == Qt.ControlModifier and event.key(
                ) == Qt.Key_C:
                    self.killProcess()
                    return True

                elif event.key() == Qt.Key_Up:
                    try:
                        if self.tracker != 0:
                            cursor.select(QTextCursor.BlockUnderCursor)
                            cursor.removeSelectedText()
                            self.cmdField.appendPlainText(self.getUsername())

                        self.cmdField.insertPlainText(
                            self.commands[self.tracker])
                        self.tracker -= 1

                    except IndexError:
                        self.tracker = 0
                    return True

                elif event.key() == Qt.Key_Down:
                    try:
                        if self.tracker != 0:
                            cursor.select(QTextCursor.BlockUnderCursor)
                            cursor.removeSelectedText()
                            self.cmdField.appendPlainText(self.getUsername())

                        self.cmdField.insertPlainText(
                            self.commands[self.tracker])
                        self.tracker += 1

                    except IndexError:
                        self.tracker = 0
                    return True

                else:
                    return False
            else:
                return False
        else:
            return False

    def copyText(self):
        self.textWindow.copy()

    def pasteText(self):
        self.cmdField.paste()

    def killProcess(self):
        # print("cancelled")
        self.process.kill()
        self.textWindow.appendPlainText("cancelled")
        self.cursorEnd()

    def setDropEvent(self, event):
        self.cmdField.setFocus()
        if event.mimeData().hasUrls():
            f = str(event.mimeData().urls()[0].toLocalFile())
            # print("is file:", f)
            if " " in f:
                self.cmdField.insertPlainText("'{}'".format(f))
            else:
                self.cmdField.insertPlainText(f)
            event.accept()
        elif event.mimeData().hasText():
            ft = event.mimeData().text()
            # print("is text:", ft)
            if " " in ft:
                self.cmdField.insertPlainText("'{}'".format(ft))
            else:
                self.cmdField.insertPlainText(ft)
        else:
            event.ignore()

    def run(self):

        self.textWindow.setFocus()
        self.textWindow.appendPlainText(self.cmdField.toPlainText())
        cli = shlex.split(self.cmdField.toPlainText().replace(
            self.getUsername(), '').replace("'", '"'),
                          posix=False)
        cmd = str(cli[0])  ### is the executable

        if cmd == "exit":
            quit()
        elif 'cd' in cmd:
            if len(cli) == 1:
                command_argument = cmd.split('cd')[1]
            else:
                command_argument = cli[1]

            if cmd == 'cd' or cmd == 'cd.':
                if len(cli) == 1:
                    pass
                else:
                    if os.path.isdir(command_argument):
                        # print('{0} is dir'.format(command_argument))
                        check = True
                        for char in command_argument:
                            if not char == '.':
                                check = False
                                break
                        if not check:
                            pth = os.path.join(self._cwd, command_argument)
                            if os.path.exists(pth):
                                self._cwd = pth
                            else:
                                self.command_not_found(cmd)
                        else:
                            # print('{0} is not dir'.format(command_argument))
                            pass
                    else:
                        if os.path.exists(command_argument):
                            # print('{0} is path'.format(command_argument))
                            self._cwd = command_argument
                        else:
                            # print('{0} is path but not exists'.format(command_argument))
                            pth = os.path.join(self._cwd, command_argument)
                            # print(pth, self._cwd)
                            if os.path.exists(pth):
                                self._cwd = pth
                            else:
                                self.command_not_found(cmd)
            else:
                if len(command_argument) <= 1:
                    if command_argument == '/' or command_argument == '\\':
                        self._cwd = os.path.splitdrive(self._cwd)[0] + '/'
                    else:
                        self.command_not_found()
                elif len(command_argument) >= 2:
                    if command_argument[0:2] == '..':
                        check = True
                        for char in command_argument:
                            if not char == '.':
                                check = False
                        if check:
                            for i in range(len(command_argument) - 1):
                                self._cwd = os.path.dirname(self._cwd)
                        else:
                            self.command_not_found(cmd)
                    else:
                        self.command_not_found(cmd)
                else:
                    self.command_not_found(cmd)

            self.updateWorkingDirectory(self._cwd)
        else:
            if (QStandardPaths.findExecutable(cmd)):
                self.commands.append(self.cmdField.toPlainText().replace(
                    self.getUsername(), ""))
                # print("command", cmd, "found")
                t = " ".join(cli)
                if self.process.state() != 2:
                    self.process.waitForStarted()
                    self.process.waitForFinished()
                    if "|" in t or ">" in t or "<" in t:
                        # print("special characters")
                        self.process.start('sh -c "' + cmd + ' ' + t + '"')
                        # print("running", ('sh -c "' + cmd + ' ' + t + '"'))
                    else:
                        self.process.start(cmd + " " + t)
                        # print("running", (cmd + " " + t))
            else:
                self.command_not_found(cmd)

    def command_not_found(self, cmd):
        self.textWindow.appendPlainText("command not found: {0}".format(cmd))
        self.cursorEnd()

    def dataReady(self):
        try:
            out = str(self.process.readAll(), encoding='utf8').rstrip()
        except TypeError:
            out = str(self.process.readAll()).rstrip()
            self.textWindow.moveCursor(self.cursor.Start)  ### changed
        self.textWindow.appendPlainText(out)

    def onError(self):
        self.error = self.process.readAllStandardError().data().decode()
        self.textWindow.appendPlainText(self.error.strip('\n'))
        self.cursorEnd()

    def onOutput(self):
        self.result = self.process.readAllStandardOutput().data().decode()
        self.textWindow.appendPlainText(self.result.strip('\n'))
        self.cursorEnd()
        self.state = self.process.state()
        # print(self.state)

    def isFinished(self):
        # print("finished")
        self.cmdField.setPlainText(self.getUsername())
        self.cursorEnd()

    def updateWorkingDirectory(self, pth=os.getcwd()):
        # print('Working Dir: {0}'.format(pth))
        fixName = os.path.basename(pth)
        fixPath = os.path.dirname(pth)
        self._cwd = os.path.join(fixPath, fixName).replace('\\', '/')
        self.process.setWorkingDirectory(self._cwd)
        self.cursorEnd()
Ejemplo n.º 12
0
class ActionManager(DAMGDICT):

    key = 'ActionManager'
    _name = 'ActionManager'

    appInfo = data_handler(filePath=mainConfig)

    actionKeys = DAMGLIST()
    showLayoutKeys = DAMGLIST()
    showRestoreKeys = DAMGLIST()
    showMaximizeKeys = DAMGLIST()
    showMinimizeKeys = DAMGLIST()
    startFileKeys = DAMGLIST()
    openBrowserKeys = DAMGLIST()
    executingKeys = DAMGLIST()

    orgActions = ['NewOrganisation', 'EditOrganisation']
    teamActions = ['NewTeam', 'EditTeam']
    prjActions = ['NewProject', 'EditProject']
    appActions = ['SettingUI', 'Configuration', 'Preferences', 'Exit']
    goActions = ['ConfigFolder', 'IconFolder', 'SettingFolder', 'AppFolder']
    officeActions = ['TextEditor', 'NoteReminder'] + CONFIG_OFFICE
    toolsActions = CONFIG_TOOLS + ['CleanPyc', 'ReConfig', 'Debug']
    devActions = CONFIG_DEV
    libActions = ['Alpha', 'HDRI', 'Texture']
    helpActions = [
        'PLM wiki',
        'About',
        'CodeOfConduct',
        'Contributing',
        'Credit',
        'Reference',
        'Version',
        'Feedback',
        'ContactUs',
    ]

    tdActions = CONFIG_TDS
    artActions = CONFIG_ART
    texActions = CONFIG_TEX
    postActions = CONFIG_POST
    vfxActions = CONFIG_VFX
    extraActions = CONFIG_EXTRA
    sysTrayActions = CONFIG_SYSTRAY

    def __init__(self, parent=None):
        super(ActionManager, self).__init__(self)

        self.parent = parent
        self.showLayoutKeys.appendList(SHOWLAYOUT_KEY)
        self.startFileKeys.appendList(START_FILE_KEY)
        self.executingKeys.appendList(EXECUTING_KEY)
        self.openBrowserKeys.appendList(OPEN_BROWSER_KEY)
        self.showRestoreKeys.appendList(RESTORE_KEY)
        self.showMaximizeKeys.appendList(SHOWMAX_KEY)
        self.showMinimizeKeys.appendList(SHOWMIN_KEY)

        self.actionKeys = self.showLayoutKeys + self.startFileKeys + self.executingKeys + self.officeActions + \
                          self.showRestoreKeys + self.showMaximizeKeys + self.showMinimizeKeys

    def actionConfigError(self, key):
        return print(
            'ActionKeyConfigError: This key is not registered: {0}'.format(
                key))

    def actionRegisterError(self, key):
        return print(
            'ActionRegisterError: This action is already registered: {0}'.
            format(key))

    def extraToolActions(self, parent):
        return self.createActions(self.extraActions, parent)

    def tdToolBarActions(self, parent):
        return self.createActions(self.tdActions, parent)

    def artToolBarActions(self, parent):
        return self.createActions(self.artActions, parent)

    def texToolBarActions(self, parent):
        return self.createActions(self.texActions, parent)

    def postToolBarActions(self, parent):
        return self.createActions(self.postActions, parent)

    def vfxToolBarActions(self, parent):
        return self.createActions(self.vfxActions, parent)

    def sysTrayMenuActions(self, parent):
        return self.createActions(self.sysTrayActions, parent)

    def appMenuActions(self, parent):
        return self.createActions(self.appActions, parent)

    def orgMenuActions(self, parent):
        return self.createActions(self.orgActions, parent)

    def teamMenuActions(self, parent):
        return self.createActions(self.teamActions, parent)

    def projectMenuActions(self, parent):
        return self.createActions(self.prjActions, parent)

    def goMenuActions(self, parent):
        return self.createActions(self.goActions, parent)

    def officeMenuActions(self, parent):
        return self.createActions(self.officeActions, parent)

    def toolsMenuActions(self, parent):
        return self.createActions(self.toolsActions, parent)

    def devMenuActions(self, parent):
        return self.createActions(self.devActions, parent)

    def libMenuActions(self, parent):
        return self.createActions(self.libActions, parent)

    def helpMenuActions(self, parent):
        return self.createActions(self.helpActions, parent)

    def createActions(self, keys, parent):
        actions = []
        for key in keys:
            if key in self.appInfo.keys():
                if is_string(key):
                    action = self.createAction(key, parent)
                    actions.append(action)
                elif is_action(key):
                    action = key
                    action.setParent(parent)
                    self.register(action)
                    actions.append(action)
                else:
                    print(
                        "DATATYPEERROR: Could not add action: {0}".format(key))

        return actions

    def createAction(self, key, parent):
        if key in self.showLayoutKeys:
            # print('{0} is set to {1} action'.format(key, 'showlayout'))
            return self.showLayoutAction(key, parent)
        elif key in self.startFileKeys:
            # print('{0} is set to {1} action'.format(key, 'startfile'))
            return self.startFileAction(key, parent)
        elif key in self.executingKeys:
            # print('{0} is set to {1} action'.format(key, 'executing'))
            return self.executingAction(key, parent)
        elif key in self.openBrowserKeys:
            # print('{0} is set to {1} action'.format(key, 'openBrowser'))
            return self.openBrowserAction(key, parent)
        elif key in self.showMinimizeKeys:
            # print('{0} is set to {1} action'.format(key, 'showminimized'))
            return self.showMinAction(key, parent)
        elif key in self.showMaximizeKeys:
            # print('{0} is set to {1} action'.format(key, 'showmaximized'))
            return self.showMaxAction(key, parent)
        elif key in self.showRestoreKeys:
            # print('{0} is set to {1} action'.format(key, 'showrestore'))
            return self.showRestoreAction(key, parent)
        else:
            return self.actionConfigError(key)

    def showLayoutAction(self, key, parent):
        if key in self.appInfo.keys():
            action = Action(
                {
                    'icon': self.appInfo[key][1],
                    'txt': '&{0}'.format(key),
                    'stt': self.appInfo[key][0],
                    'trg': partial(parent.signals.emit, 'showLayout', key,
                                   'show'),
                }, parent)
            action.key = '{0}_{1}_Action'.format(parent.key, key)
            action._name = action.key
            if action.key in self.actionKeys:
                return self[action.key]
            else:
                action._name = '{0} Action'.format(key)
                action.Type = 'DAMGShowLayoutAction'
                self.register(action)
                return action
        else:
            return self.actionConfigError(key)

    def showRestoreAction(self, key, parent):
        if key in self.appInfo.keys():
            action = Action(
                {
                    'icon':
                    self.appInfo[key][1],
                    'txt':
                    '&{0}'.format(key),
                    'stt':
                    self.appInfo[key][0],
                    'trg':
                    partial(parent.signals.emit, 'showLayout',
                            self.appInfo[key][2], 'showRestore'),
                }, parent)
            action.key = '{0}_{1}_Action'.format(parent.key, key)
            action._name = action.key
            if action.key in self.actionKeys:
                return self[action.key]
            else:
                action._name = '{0} Action'.format(key)
                action.Type = 'DAMGShowNormalAction'
                self.register(action)
                return action
        else:
            return self.actionConfigError(key)

    def showMaxAction(self, key, parent):
        if key in self.appInfo.keys():
            action = Action(
                {
                    'icon':
                    self.appInfo[key][1],
                    'txt':
                    '&{0}'.format(key),
                    'stt':
                    self.appInfo[key][0],
                    'trg':
                    partial(parent.signals.emit, 'showLayout',
                            self.appInfo[key][2], 'showMax'),
                }, parent)
            action.key = '{0}_{1}_Action'.format(parent.key, key)
            action._name = action.key
            if action.key in self.actionKeys:
                return self[action.key]
            else:
                action._name = '{0} Action'.format(key)
                action.Type = 'DAMGShowMaximizeAction'
                self.register(action)
                return action
        else:
            return self.actionConfigError(key)

    def showMinAction(self, key, parent):
        if key in self.appInfo.keys():
            action = Action(
                {
                    'icon':
                    self.appInfo[key][1],
                    'txt':
                    '&{0}'.format(key),
                    'stt':
                    self.appInfo[key][0],
                    'trg':
                    partial(parent.signals.emit, 'showLayout',
                            self.appInfo[key][2], 'showMin'),
                }, parent)
            action.key = '{0}_{1}_Action'.format(parent.key, key)
            action._name = action.key
            if action.key in self.actionKeys:
                return self[action.key]
            else:
                action._name = '{0} Action'.format(key)
                action.Type = 'DAMGShowMinimizeAction'
                self.register(action)
                return action
        else:
            return self.actionConfigError(key)

    def startFileAction(self, key, parent):
        if key in self.appInfo.keys():
            # print('create start file action: {} {}'.format(key, self.appInfo[key][2]))
            action = Action(
                {
                    'icon': self.appInfo[key][1],
                    'txt': '&{0}'.format(key),
                    'stt': self.appInfo[key][0],
                    'trg': partial(os.startfile, self.appInfo[key][2])
                }, parent)
            action.key = '{0}_{1}_Action'.format(parent.key, key)
            action._name = action.key
            if action.key in self.actionKeys:
                return self[action.key]
            else:
                action._name = '{0} Action'.format(key)
                action.Type = 'DAMGStartFileAction'
                self.register(action)
                return action
        else:
            return self.actionConfigError(key)

    def executingAction(self, key, parent):
        if key in self.appInfo.keys():
            action = Action(
                {
                    'icon':
                    self.appInfo[key][1],
                    'txt':
                    '&{0}'.format(key),
                    'stt':
                    self.appInfo[key][0],
                    'trg':
                    partial(parent.signals.emit, 'executing',
                            self.appInfo[key][2]),
                }, parent)
            action.key = '{0}_{1}_Action'.format(parent.key, key)
            action._name = '{0} Action'.format(key)
            if action.key in self.actionKeys:
                return self[action.key]
            else:
                action.Type = 'DAMGExecutingAction'
                self.register(action)
                return action
        else:
            return self.actionConfigError(key)

    def openBrowserAction(self, key, parent):
        if key in self.appInfo.keys():
            action = Action(
                {
                    'icon':
                    self.appInfo[key][1],
                    'txt':
                    '&{0}'.format(key),
                    'stt':
                    self.appInfo[key][0],
                    'trg':
                    partial(parent.signals.emit, 'openBrowser',
                            self.appInfo[key][2]),
                }, parent)
            action.key = '{0}_{1}_Action'.format(parent.key, key)
            action._name = action.key
            if action.key in self.actionKeys:
                return self[action.key]
            else:
                action._name = '{0} Action'.format(key)
                action.Type = 'DAMGOpenBrowserAction'
                self.register(action)
                return action
        else:
            return self.actionConfigError(key)

    def register(self, action):
        # print('register action: {}'.format(action))
        if not action.key in self.actionKeys:
            self.actionKeys.append(action.key)
            self[action.key] = action
        else:
            return self.actionRegisterError(action.key)

    def actions(self):
        return self.values()


# -------------------------------------------------------------------------------------------------------------
# Created by panda on 3/11/2019 - 5:26 PM
# © 2017 - 2018 DAMGteam. All rights reserved
Ejemplo n.º 13
0
class ButtonManager(DAMGDICT):

    key = 'ButtonManager'
    _name = 'ButtonManager'

    mainInfo = data_handler(filePath=mainConfig)

    buttonKeys = DAMGLIST()
    showLayoutKeys = DAMGLIST()
    showRestoreKeys = DAMGLIST()
    showMaximizeKeys = DAMGLIST()
    showMinimizeKeys = DAMGLIST()
    startFileKeys = DAMGLIST()
    openBrowserKeys = DAMGLIST()
    executingKeys = DAMGLIST()
    tagKeys = DAMGLIST()

    tags = dict(
        pythonTag="https://docs.anaconda.com/anaconda/reference/release-notes/",
        licenceTag="https://github.com/vtta2008/damgteam/blob/master/LICENCE",
        versionTag=
        "https://github.com/vtta2008/damgteam/blob/master/appData/documentations/version.rst"
    )

    tagButtons = ['pythonTag', 'licenceTag', 'versionTag']

    orgButtons = ['NewOrganisation', 'EditOrganisation']
    taskButtons = ['NewTask', 'EditTask']
    teamButtons = ['NewTeam', 'EditTeam']
    prjButtons = ['NewProject', 'EditProject']
    userButtons = ['UserSetting', 'SignUp', 'SwitchAccount', 'SignOut']

    checkedKeys = teamButtons + prjButtons + userButtons + tagButtons + taskButtons

    def __init__(self, parent=None):
        super(ButtonManager, self).__init__(self)

        self.parent = parent
        self.showLayoutKeys.appendList(SHOWLAYOUT_KEY)
        self.startFileKeys.appendList(START_FILE_KEY)
        self.executingKeys.appendList(EXECUTING_KEY)
        self.openBrowserKeys.appendList(OPEN_BROWSER_KEY)
        self.showRestoreKeys.appendList(RESTORE_KEY)
        self.showMaximizeKeys.appendList(SHOWMAX_KEY)
        self.showMinimizeKeys.appendList(SHOWMIN_KEY)
        self.tagKeys.appendList(self.tagButtons)

        self.buttonKeys = self.showLayoutKeys + self.startFileKeys + self.executingKeys + self.showRestoreKeys + \
                          self.showMaximizeKeys + self.showMinimizeKeys + self.tagKeys

    def buttonConfigError(self, key):
        return print(
            'ButtonKeyConfigError: This key is not registered: {0}'.format(
                key))

    def buttonRegisterError(self, key):
        return print(
            'ButtonRegisterError: This action is already registered: {0}'.
            format(key))

    def taskButtonsGroupBox(self, parent):
        return self.createButtons(self.taskButtons, parent)

    def projectButtonsGroupBox(self, parent):
        return self.createButtons(self.prjButtons, parent)

    def tagButtonsFooterWidget(self, parent):
        return self.createButtons(self.tagButtons, parent)

    def teamButtonsGroupBox(self, parent):
        return self.createButtons(self.teamButtons, parent)

    def userButtonGroupBox(self, parent):
        return self.createButtons(self.userButtons, parent)

    def createButtons(self, keys, parent):
        buttons = []
        for key in keys:
            if key in self.mainInfo.keys():
                if not key in self.checkedKeys:
                    print('key: {0} is in mainInfo: {1}'.format(
                        key, self.mainInfo[key]))
                if is_string(key):
                    button = self.createButton(key, parent)
                    buttons.append(button)
                elif is_button(key):
                    button = key
                    button.setParent(parent)
                    self.register(Button)
                    buttons.append(Button)
                else:
                    print(
                        "DataTypeError: Could not add Button: {0}".format(key))
            else:
                print('key: {0} NOT in mainInfo: {1}'.format(
                    key, self.mainInfo[key]))

        return buttons

    def createButton(self, key, parent):
        if key in self.showLayoutKeys:
            return self.showLayoutButton(key, parent)
        elif key in self.startFileKeys:
            return self.showLayoutButton(key, parent)
        elif key in self.executingKeys:
            return self.executingButton(key, parent)
        elif key in self.openBrowserKeys:
            return self.openBrowserButton(key, parent)
        elif key in self.showMinimizeKeys:
            return self.showMinButton(key, parent)
        elif key in self.showMaximizeKeys:
            return self.showMaxButton(key, parent)
        elif key in self.showRestoreKeys:
            return self.showRestoreButton(key, parent)
        elif key in self.tagKeys:
            return self.tagOpenBrowserButton(key, parent)
        else:
            # print('key come here: {}'.format(key))
            return self.buttonConfigError(key)

    def showLayoutButton(self, key, parent):
        if key in self.mainInfo.keys():
            if key in ['SignIn', 'SignOut', 'SignUp', 'SwitchAccount']:
                show = key
            else:
                show = 'show'

            button = Button({
                'txt':
                self.mainInfo[key][0],
                'stt':
                self.mainInfo[key][2],
                'cl':
                partial(parent.signals.emit, 'showLayout', key, show),
            })
            button.key = '{0}_{1}_Button'.format(parent.key, key)
            button._name = button.key
            if button.key in self.buttonKeys:
                return self[button.key]
            else:
                button._name = '{0} Button'.format(key)
                button.Type = 'DAMGShowLayoutButton'
                self.register(button)
                return button
        else:
            return self.buttonConfigError(key)

    def showRestoreButton(self, key, parent):
        if key in self.mainInfo.keys():
            button = Button({
                'txt':
                self.mainInfo[key][0],
                'stt':
                self.mainInfo[key][2],
                'cl':
                partial(parent.signals.emit, 'showLayout', key, 'showRestore'),
            })
            button.key = '{0}_{1}_Button'.format(parent.key, key)
            button._name = button.key
            if button.key in self.buttonKeys:
                return self[button.key]
            else:
                button._name = '{0} Button'.format(key)
                button.Type = 'DAMGShowNormalButton'
                self.register(button)
                return button
        else:
            return self.buttonConfigError(key)

    def showMaxButton(self, key, parent):
        if key in self.mainInfo.keys():
            button = Button({
                'txt':
                self.mainInfo[key][0],
                'stt':
                self.mainInfo[key][2],
                'cl':
                partial(parent.signals.emit, 'showLayout', key,
                        'showMaximized'),
            })
            button.key = '{0}_{1}_Button'.format(parent.key, key)
            button._name = button.key
            if button.key in self.buttonKeys:
                return self[button.key]
            else:
                button._name = '{0} Button'.format(key)
                button.Type = 'DAMGShowMaximizeButton'
                self.register(button)
                return button
        else:
            return self.buttonConfigError(key)

    def showMinButton(self, key, parent):
        if key in self.mainInfo.keys():
            button = Button({
                'txt':
                self.mainInfo[key][0],
                'stt':
                self.mainInfo[key][2],
                'cl':
                partial(parent.signals.emit, 'showLayout', key,
                        'showMinimized'),
            })
            button.key = '{0}_{1}_Button'.format(parent.key, key)
            button._name = button.key
            if button.key in self.buttonKeys:
                return self[button.key]
            else:
                button._name = '{0} Button'.format(key)
                button.Type = 'DAMGShowMinimizeButton'
                self.register(button)
                return button
        else:
            return self.buttonConfigError(key)

    def startFileButton(self, key, parent):
        if key in self.mainInfo.keys():
            button = Button({
                'txt': self.mainInfo[key][0],
                'stt': self.mainInfo[key][2],
                'cl': partial(os.startfile, key)
            })
            button.key = '{0}_{1}_Button'.format(parent.key, key)
            button._name = button.key
            if button.key in self.buttonKeys:
                return self[button.key]
            else:
                button._name = '{0} Button'.format(key)
                button.Type = 'DAMGStartFileButton'
                self.register(button)
                return button
        else:
            return self.buttonConfigError(key)

    def executingButton(self, key, parent):
        if key in self.mainInfo.keys():
            button = Button({
                'txt':
                self.mainInfo[key][0],
                'stt':
                self.mainInfo[key][2],
                'cl':
                partial(parent.signals.emit, 'executing', key),
            })
            button.key = '{0}_{1}_Button'.format(parent.key, key)
            button._name = button.key
            if button.key in self.buttonKeys:
                return self[button.key]
            else:
                button.Type = 'DAMGExecutingButton'
                self.register(button)
                return button
        else:
            return self.buttonConfigError(key)

    def openBrowserButton(self, key, parent):
        if key in self.mainInfo.keys():
            button = Button({
                'txt':
                self.mainInfo[key][0],
                'stt':
                self.mainInfo[key][2],
                'cl':
                partial(parent.signals.emit, 'openBrowser', key),
            })
            button.key = '{0}_{1}_Button'.format(parent.key, key)
            button._name = button.key
            if button.key in self.buttonKeys:
                return self[button.key]
            else:
                button._name = '{0} Button'.format(key)
                button.Type = 'DAMGOpenBrowserButton'
                self.register(button)
                return button
        else:
            return self.buttonConfigError(key)

    def iconShowLayoutButton(self, key, parent):
        if key in self.mainInfo.keys():
            button = Button({
                'icon':
                key,
                'tt':
                self.mainInfo[key][2],
                'fix':
                BTNICONSIZE,
                'ics':
                ICONBTNSIZE,
                'cl':
                partial(parent.signals.emit, 'showLayout', key, 'show')
            })
            button.key = '{0}_{1}_Button'.format(parent.key, key)
            button._name = button.key
            if button.key in self.buttonKeys:
                return self[button.key]
            else:
                button._name = '{0} Button'.format(key)
                button.Type = 'DAMGOpenBrowserButton'
                self.register(button)
                return button
        else:
            return self.buttonConfigError(key)

    def tagOpenBrowserButton(self, tagName, parent):
        if tagName in self.tags.keys():
            button = Button({
                'tag':
                tagName,
                'fix':
                BTNTAGSIZE,
                'ics':
                TAGBTNSIZE,
                'cl':
                partial(parent.signals.emit, 'openBrowser', self.tags[tagName])
            })
            button.key = '{0}_{1}_Button'.format(parent.key, tagName)
            button._name = button.key
            if button.key in self.buttonKeys:
                return self[button.key]
            else:
                button._name = '{0} Button'.format(tagName)
                button.Type = 'DAMGOpenBrowserButton'
                self.register(button)
                return button
        else:
            return self.buttonConfigError(tagName)

    def register(self, button):
        if not button.key in self.buttonKeys:
            self.buttonKeys.append(button.key)
            self[button.key] = button
        else:
            return self.buttonRegisterError(button.key)

    def buttons(self):
        return self.values()


# -------------------------------------------------------------------------------------------------------------
# Created by panda on 6/11/2019 - 10:22 AM
# © 2017 - 2018 DAMGteam. All rights reserved
Ejemplo n.º 14
0
class GeneralSetting(GridLayout):

    key                                     = 'GeneralSetting'
    statusCBs                               = DAMGLIST()
    notificationCBs                         = DAMGLIST()
    checkboxes                              = DAMGDICT()

    def __init__(self, parent=None):
        super(GeneralSetting, self).__init__(parent)
        self.parent = parent
        self.la = 0
        self.buildUI()

    def buildUI(self):

        # self.buildHeaderCheckBoxes()

        self.buildBodyCheckBoxes()

        self.footerCB       = CheckBox('Footer')

        self.statusBarCB    = CheckBox("Status Bar")

        for cb in [self.statusBarCB, ]:
            self.statusCBs.append(cb)

        cbs = [self.toolBarCBs, self.menuCBs, self.connectCBs, self.notificationCBs, self.statusCBs, ]

        for i in range(len(cbs)):
            if i == 0:
                prefix = 'ToolBar'
            elif i == 1:
                prefix = 'Menu'
            elif i == 2:
                prefix = 'Network'
            elif i == 3:
                prefix = 'Notification'
            elif i == 4:
                prefix = 'StatusBar'
            else:
                prefix = 'NoDefine'

            for cb in cbs[i]:
                cb.key = '{0}_{1}_CheckBox_{2}'.format(self.parent.key, prefix, cb.text())
                cb._name = '{0} {1} Check Box: {2}'.format(self.parent.key, prefix, cb.text())

                cb.settings._settingEnable = True
                state = cb.getValue('checkState')
                if state is None:
                    state = True
                cb.setValue('checkState', state)
                cb.setChecked(str2bool(state))
                self.checkboxes.add(cb.key, cb)

    def buildBodyCheckBoxes(self):
        self.buildNotificationCheckBoxes()
        self.bodyCB = CheckBox('Body')
        self.bodyCB.stateChanged.connect(self.bodyStateChanged)
        ntl = self.la
        bdl = ntl + 1
        self.addWidget(Label({'txt': 'Notification'}), ntl, 0, 1, 1)
        self.addWidget(self.allNotifiCB, ntl, 1, 1, 1)
        self.addWidget(self.cpuCB, ntl, 2, 1, 1)
        self.addWidget(self.ramCB, ntl, 3, 1, 1)
        self.addWidget(self.gpuCB, ntl, 4, 1, 1)
        self.addWidget(self.prjNameCB, ntl, 5, 1, 1)
        self.addWidget(self.dueDateCB, ntl, 6, 1, 1)
        self.addWidget(self.dueTimeCB, ntl, 7, 1, 1)
        self.addWidget(self.countdownCB, ntl, 8, 1, 1)
        self.addWidget(self.timeCB, ntl, 9, 1, 1)
        self.addWidget(self.dateCB, ntl, 10, 1, 1)
        self.addWidget(self.bodyCB, bdl, 0, 1, 1)

        self.la = bdl + 1
        return self.la

    def buildNotificationCheckBoxes(self):
        self.cpuCB = CheckBox('cpu')
        self.ramCB = CheckBox('ram')
        self.gpuCB = CheckBox('gpu')
        self.diskCB = CheckBox('disk')
        self.prjNameCB = CheckBox('Project Name')
        self.dueDateCB = CheckBox('Due Date')
        self.dueTimeCB = CheckBox('Due Time')
        self.countdownCB = CheckBox('Time Counting')
        self.timeCB = CheckBox('clock')
        self.dateCB = CheckBox('date')
        self.allNotifiCB = CheckBox("All: ")
        self.allNotifiCB.stateChanged.connect(self.allNotifiStateChanged)
        for cb in [self.cpuCB, self.ramCB, self.gpuCB, self.diskCB, self.prjNameCB, self.dueDateCB, self.dueTimeCB,
                   self.countdownCB, self.timeCB, self.dateCB, self.allNotifiCB]:
            self.notificationCBs.append(cb)

    def allNotifiStateChanged(self, bool):
        for cb in self.notificationCBs:
            cb.setChecked(bool)

    def bodyStateChanged(self, bool):
        self.allNotifiStateChanged(bool)
Ejemplo n.º 15
0
class Calculator(Widget):

    key = 'Calculator'
    NumDigitButtons = 10
    digitButtons = DAMGLIST()

    def __init__(self, parent=None):
        super(Calculator, self).__init__(parent)

        self.setWindowIcon(AppIcon(32, 'Calculator'))
        self.setWindowTitle(self.key)
        self.buildUI()

    def buildUI(self):
        self.layout = QGridLayout(self)

        self.pendingAdditiveOperator            = ''
        self.pendingMultiplicativeOperator      = ''
        self.sumInMemory                        = 0.0
        self.sumSoFar                           = 0.0
        self.factorSoFar                        = 0.0
        self.waitingForOperand                  = True

        self.display = LineEdit({'txt': '0'})
        self.display.setReadOnly(True)
        self.display.setAlignment(Qt.AlignRight)

        for i in range(self.NumDigitButtons):
            self.digitButtons.append(self.createButton(str(i), self.digitClicked))

        self.pointButton            = self.createButton(".", self.pointClicked)
        self.changeSignButton       = self.createButton(u"\N{PLUS-MINUS SIGN}",  self.changeSignClicked)
        self.backspaceButton        = self.createButton("Backspace", self.backspaceClicked)
        self.clearButton            = self.createButton("Clear", self.clear)
        self.clearAllButton         = self.createButton("Clear All", self.clearAll)
        self.clearMemoryButton      = self.createButton("MC", self.clearMemory)
        self.readMemoryButton       = self.createButton("MR", self.readMemory)
        self.setMemoryButton        = self.createButton("MS", self.setMemory)
        self.addToMemoryButton      = self.createButton("M+", self.addToMemory)
        self.divisionButton         = self.createButton(u"\N{DIVISION SIGN}", self.multiplicativeOperatorClicked)
        self.timesButton            = self.createButton(u"\N{MULTIPLICATION SIGN}", self.multiplicativeOperatorClicked)
        self.minusButton            = self.createButton("-", self.additiveOperatorClicked)
        self.plusButton             = self.createButton("+", self.additiveOperatorClicked)
        self.squareRootButton       = self.createButton("Sqrt", self.unaryOperatorClicked)
        self.powerButton            = self.createButton(u"x\N{SUPERSCRIPT TWO}", self.unaryOperatorClicked)
        self.reciprocalButton       = self.createButton("1/x", self.unaryOperatorClicked)
        self.equalButton            = self.createButton("=", self.equalClicked)

        self.layout.addWidget(self.display, 0,0,1,6)
        self.layout.addWidget(self.backspaceButton, 1,0,1,2)
        self.layout.addWidget(self.clearButton, 1,2,1,2)
        self.layout.addWidget(self.clearAllButton, 1,4,1,2)
        self.layout.addWidget(self.clearMemoryButton,2,0)
        self.layout.addWidget(self.readMemoryButton,3,0)
        self.layout.addWidget(self.setMemoryButton,4,0)
        self.layout.addWidget(self.addToMemoryButton,5,0)

        for i in range(1, self.NumDigitButtons):
            row = ((9 - i) / 3) + 2
            column = ((i - 1) % 3) + 1
            self.layout.addWidget(self.digitButtons[i], row, column)

        self.layout.addWidget(self.digitButtons[0],5,1)
        self.layout.addWidget(self.pointButton,5,2)
        self.layout.addWidget(self.changeSignButton,5,3)
        self.layout.addWidget(self.divisionButton,2,4)
        self.layout.addWidget(self.timesButton,3,4)
        self.layout.addWidget(self.minusButton,4,4)
        self.layout.addWidget(self.plusButton,5,4)
        self.layout.addWidget(self.squareRootButton,2,5)
        self.layout.addWidget(self.powerButton,3,5)
        self.layout.addWidget(self.reciprocalButton,4,5)
        self.layout.addWidget(self.equalButton,5,5)

        self.display.setMaxLength(15)
        font = self.display.font()
        font.setPointSize(font.pointSize() + 8)
        self.display.setFont(font)

        self.setLayout(self.layout)

    def digitClicked(self):
        clickedButton = self.sender()
        digitValue = int(clickedButton.text())

        if self.display.text() == '0' and digitValue == 0.0:
            return

        if self.waitingForOperand:
            self.display.clear()
            self.waitingForOperand = False

        self.display.setText(self.display.text() + str(digitValue))

    def unaryOperatorClicked(self):
        clickedButton = self.sender()
        clickedOperator = clickedButton.text()
        operand = float(self.display.text())

        if clickedOperator == "Sqrt":
            if operand < 0.0:
                self.abortOperation()
                return

            result = math.sqrt(operand)
        elif clickedOperator == u"x\N{SUPERSCRIPT TWO}":
            result = math.pow(operand, 2.0)
        elif clickedOperator == "1/x":
            if operand == 0.0:
                self.abortOperation()
                return

            result = 1.0 / operand

        self.display.setText(str(result))
        self.waitingForOperand = True

    def additiveOperatorClicked(self):
        clickedButton = self.sender()
        clickedOperator = clickedButton.text()
        operand = float(self.display.text())

        if self.pendingMultiplicativeOperator:
            if not self.calculate(operand, self.pendingMultiplicativeOperator):
                self.abortOperation()
                return

            self.display.setText(str(self.factorSoFar))
            operand = self.factorSoFar
            self.factorSoFar = 0.0
            self.pendingMultiplicativeOperator = ''

        if self.pendingAdditiveOperator:
            if not self.calculate(operand, self.pendingAdditiveOperator):
                self.abortOperation()
                return

            self.display.setText(str(self.sumSoFar))
        else:
            self.sumSoFar = operand

        self.pendingAdditiveOperator = clickedOperator
        self.waitingForOperand = True

    def multiplicativeOperatorClicked(self):
        clickedButton = self.sender()
        clickedOperator = clickedButton.text()
        operand = float(self.display.text())

        if self.pendingMultiplicativeOperator:
            if not self.calculate(operand, self.pendingMultiplicativeOperator):
                self.abortOperation()
                return

            self.display.setText(str(self.factorSoFar))
        else:
            self.factorSoFar = operand

        self.pendingMultiplicativeOperator = clickedOperator
        self.waitingForOperand = True

    def equalClicked(self):
        operand = float(self.display.text())

        if self.pendingMultiplicativeOperator:
            if not self.calculate(operand, self.pendingMultiplicativeOperator):
                self.abortOperation()
                return

            operand = self.factorSoFar
            self.factorSoFar = 0.0
            self.pendingMultiplicativeOperator = ''

        if self.pendingAdditiveOperator:
            if not self.calculate(operand, self.pendingAdditiveOperator):
                self.abortOperation()
                return

            self.pendingAdditiveOperator = ''
        else:
            self.sumSoFar = operand

        self.display.setText(str(self.sumSoFar))
        self.sumSoFar = 0.0
        self.waitingForOperand = True

    def pointClicked(self):
        if self.waitingForOperand:
            self.display.setText('0')

        if "." not in self.display.text():
            self.display.setText(self.display.text() + ".")

        self.waitingForOperand = False

    def changeSignClicked(self):
        text = self.display.text()
        value = float(text)

        if value > 0.0:
            text = "-" + text
        elif value < 0.0:
            text = text[1:]

        self.display.setText(text)

    def backspaceClicked(self):
        if self.waitingForOperand:
            return

        text = self.display.text()[:-1]
        if not text:
            text = '0'
            self.waitingForOperand = True

        self.display.setText(text)

    def clear(self):
        # type: () -> object
        if self.waitingForOperand:
            return

        self.display.setText('0')
        self.waitingForOperand = True

    def clearAll(self):
        self.sumSoFar = 0.0
        self.factorSoFar = 0.0
        self.pendingAdditiveOperator = ''
        self.pendingMultiplicativeOperator = ''
        self.display.setText('0')
        self.waitingForOperand = True

    def clearMemory(self):
        self.sumInMemory = 0.0

    def readMemory(self):
        self.display.setText(str(self.sumInMemory))
        self.waitingForOperand = True

    def setMemory(self):
        self.equalClicked()
        self.sumInMemory = float(self.display.text())

    def addToMemory(self):
        self.equalClicked()
        self.sumInMemory += float(self.display.text())

    def createButton(self, text, member):
        button = ToolButton(text)
        button.clicked.connect(member)
        return button

    def abortOperation(self):
        self.clearAll()
        self.display.setText("####")

    def calculate(self, rightOperand, pendingOperator):
        if pendingOperator == "+":
            self.sumSoFar += rightOperand
        elif pendingOperator == "-":
            self.sumSoFar -= rightOperand
        elif pendingOperator == u"\N{MULTIPLICATION SIGN}":
            self.factorSoFar *= rightOperand
        elif pendingOperator == u"\N{DIVISION SIGN}":
            if rightOperand == 0.0:
                return False

            self.factorSoFar /= rightOperand

        return True
Ejemplo n.º 16
0
class HeaderCheckBoxes(GridLayout):

    key = 'HeaderCheckBoxes'
    toolBarCBs = DAMGLIST()
    menuCBs = DAMGLIST()
    connectCBs = DAMGLIST()
    checkboxes = DAMGDICT()
    def __init__(self, parent=None):
        super(HeaderCheckBoxes, self).__init__(parent)
        self.parent = parent
        self.la = 0
        self.buildHeaderCheckBoxes()

        cbs = [self.toolBarCBs, self.menuCBs, self.connectCBs, [self.headerCB]]

        for i in range(len(cbs)):
            if i == 0:
                prefix = 'ToolBar'
            elif i == 1:
                prefix = 'Menu'
            elif i == 2:
                prefix = 'Network'
            else:
                prefix = 'Header'

            for cb in cbs[i]:
                cb.key = '{0}_{1}_CheckBox_{2}'.format(self.parent.key, prefix, cb.text())
                cb._name = '{0} {1} Check Box: {2}'.format(self.parent.key, prefix, cb.text())

                cb.settings._settingEnable = True
                state = cb.getValue('checkState')
                if state is None:
                    state = True
                cb.setValue('checkState', state)
                cb.setChecked(str2bool(state))
                self.checkboxes.add(cb.key, cb)

    def buildHeaderCheckBoxes(self):
        self.buildToolBarCheckBoxes()
        self.buildMenuCheckBoxes()
        self.buildServerStatusCheckBoxes()
        self.headerCB = CheckBox('Header')
        self.headerCB.stateChanged.connect(self.headerStateChanged)

        mnl = self.la
        csl = mnl + 1
        tbl = csl + 1
        hdl = tbl + 1

        self.addWidget(Label({'txt': 'Menus'}), mnl, 0, 1, 1)
        self.addWidget(self.allMenuCB, mnl, 1, 1, 1)
        self.addWidget(self.mnAppCB, mnl, 2, 1, 1)
        self.addWidget(self.mnGoCB, mnl, 3, 1, 1)
        self.addWidget(self.mnOfficeCB, mnl, 4, 1, 1)
        self.addWidget(self.mnToolsCB, mnl, 5, 1, 1)
        self.addWidget(self.mnDevCB, mnl, 6, 1, 1)
        self.addWidget(self.mnLibCB, mnl, 7, 1, 1)
        self.addWidget(self.mnHelpCB, mnl, 8, 1, 1)

        self.addWidget(Label({'txt': 'Tool Bar: '}), tbl, 0, 1, 1)
        self.addWidget(self.allToolBarCB, tbl, 1, 1, 1)
        self.addWidget(self.tbTDCB, tbl, 2, 1, 1)
        self.addWidget(self.tbVfxCB, tbl, 3, 1, 1)
        self.addWidget(self.tbArtCB, tbl, 4, 1, 1)
        self.addWidget(self.tbTexCB, tbl, 5, 1, 1)
        self.addWidget(self.tbPostCB, tbl, 6, 1, 1)

        self.addWidget(Label({'txt': 'Connect Status'}), csl, 0, 1, 1)
        self.addWidget(self.allConnectCB, csl, 1, 1, 1)
        self.addWidget(self.serverCB, csl, 2, 1, 1)
        self.addWidget(self.onlineCB, csl, 3, 1, 1)
        self.addWidget(self.modeCB, csl, 4, 1, 1)

        self.addWidget(Label({'txt': 'Header'}), hdl, 0, 1, 1)
        self.addWidget(self.headerCB, hdl, 1, 1, 1)

    def buildServerStatusCheckBoxes(self):
        self.serverCB = CheckBox('Server')
        self.onlineCB = CheckBox('Internet')
        self.modeCB = CheckBox('Mode')
        self.allConnectCB = CheckBox("All: ")
        self.allConnectCB.stateChanged.connect(self.allConnectStateChanged)
        for cb in [self.serverCB, self.onlineCB, self.modeCB, self.allConnectCB]:
            self.connectCBs.append(cb)

    def buildMenuCheckBoxes(self):
        self.mnAppCB = CheckBox('&App')
        self.mnGoCB = CheckBox('&Go')
        self.mnOfficeCB = CheckBox('&Office')
        self.mnToolsCB = CheckBox('&Tools')
        self.mnDevCB = CheckBox('&Dev')
        self.mnLibCB = CheckBox('&Lib')
        self.mnHelpCB = CheckBox('&Help')
        self.allMenuCB = CheckBox('All: ')
        self.allMenuCB.stateChanged.connect(self.allMenuStateChanged)
        for cb in [self.mnAppCB, self.mnGoCB, self.mnOfficeCB, self.mnToolsCB, self.mnDevCB, self.mnLibCB,
                   self.mnHelpCB, self.allMenuCB]:
            self.menuCBs.append(cb)

    def buildToolBarCheckBoxes(self):
        self.tbTDCB = CheckBox("TD")
        self.tbVfxCB = CheckBox("VFX")
        self.tbArtCB = CheckBox("Art")
        self.tbTexCB = CheckBox("Tex")
        self.tbPostCB = CheckBox('Post')
        self.allToolBarCB = CheckBox("All: ")
        self.allToolBarCB.stateChanged.connect(self.allToolBarStateChanged)
        for cb in [self.tbTDCB, self.tbVfxCB, self.tbArtCB, self.tbTexCB, self.tbPostCB, self.allToolBarCB]:
            self.toolBarCBs.append(cb)

    def allToolBarStateChanged(self, bool):
        for cb in self.toolBarCBs:
            cb.setChecked(bool)

    def allMenuStateChanged(self, bool):
        for cb in self.menuCBs:
            cb.setChecked(bool)

    def allConnectStateChanged(self, bool):
        for cb in self.connectCBs:
            cb.setChecked(bool)

    def headerStateChanged(self, bool):
        self.allToolBarCB.setChecked(bool)
        self.allMenuCB.setChecked(bool)
        self.allConnectCB.setChecked(bool)
Ejemplo n.º 17
0
class ConnectStatus(GridLayout):

    key = 'ConnectStatus'
    _allowLocalMode = True
    _updatting = False
    _mode = None
    _server = None
    labels = DAMGLIST()

    def __init__(self, parent=None):
        super(ConnectStatus, self).__init__(parent)

        self.parent = parent
        self._server = self.getServer()
        self.serverStatus = Label({
            'wmax': 20,
            'sst': 'Server Connection Status',
        })
        self.internetStatus = Label({
            'wmax': 20,
            'sst': 'Internet Connection Status',
        })
        self.modeStatus = Label({
            'txt': self._mode,
            'sst': 'Operating Mode Status'
        })
        self.updateTimer = DAMGTIMER()
        self.updateTimer.setParent(self)
        self.updateTimer.timeout.connect(self.update_icon)

        self.server_status()
        self.internet_status()
        self.mode_status()
        self.addWidget(self.serverStatus, 0, 0, 1, 1)
        self.addWidget(self.internetStatus, 0, 1, 1, 1)
        self.addWidget(self.modeStatus, 0, 2, 1, 1)

        self.labels.appendList(
            [self.serverStatus, self.internetStatus, self.modeStatus])

        if not self._updatting:
            self.updateTimer.stop()
        else:
            self.updateTimer.start(1000)

    def server_status(self):

        try:
            r = requests.get(__localServer__)
        except Exception:
            if not self._allowLocalMode:
                MessageBox(None, 'Connection Failed', 'critical',
                           SERVER_CONNECT_FAIL, 'close')
                sys.exit()
            else:
                self.parent.signals.emit('sysNotify', 'Offline',
                                         'Can not connect to Server', 'crit',
                                         500)
                self.serverIcon = get_app_icon(16, 'Disconnected')
        else:
            if r.status_code == 200:
                self.serverIcon = get_app_icon(16, 'Connected')
            else:
                self.serverIcon = get_app_icon(16, 'Disconnected')

        self.serverStatus.setPixmap(QPixmap(self.serverIcon))
        self.serverStatus.update()

    def internet_status(self):

        try:
            r = requests.get(__google__)
        except requests.ConnectionError:
            self.parent.signals.emit('sysNotify', 'Offline',
                                     'Can not connect to Internet', 'crit',
                                     500)
            self.internetIcon = get_app_icon(16, 'Disconnected')
            self.internetStatus.setToolTip('Disconnected')
        else:
            self.parent.signals.emit('sysNotify', 'Online',
                                     'Internet connected', 'info', 500)
            self.internetIcon = get_app_icon(16, 'Connected')
            self.internetStatus.setStatusTip('Connected')

        self.internetStatus.setPixmap(QPixmap(self.internetIcon))
        self.internetStatus.update()

    def mode_status(self):
        self.getServer()
        self.modeStatus.setText(self._mode)
        self.modeStatus.setToolTip(self._mode)
        self.modeStatus.update()

    def update_icon(self):
        # print('update Icon')
        self.internet_status()
        self.server_status()
        self.mode_status()

    def setMode(self, mode):
        self._mode = mode

    def getServer(self):
        try:
            r = requests.get(__globalServer__)
        except Exception:
            try:
                r = requests.get(__localServer__)
            except Exception:
                if not self._allowLocalMode:
                    MessageBox(None, 'Connection Failed', 'critical',
                               SERVER_CONNECT_FAIL, 'close')
                    sys.exit()
                else:
                    self.setMode('Offline')
            else:
                if r.status_code == 200:
                    self._server = __localServer__
                    self.setMode('Local')
                else:
                    self.setMode('Offline')
        else:
            if r.status_code == 200:
                self._server = __globalServer__
                self.setMode('GLobal')
            else:
                self.setMode('Offline')

        return self._server

    @property
    def updatting(self):
        return self._updatting

    @property
    def allowOfflineMode(self):
        return self._allowLocalMode

    @property
    def mode(self):
        return self._mode

    @property
    def server(self):
        return self._server

    @server.setter
    def server(self, val):
        self._server = val

    @mode.setter
    def mode(self, val):
        self._mode = val

    @updatting.setter
    def updatting(self, val):
        self._updatting = val

    @allowOfflineMode.setter
    def allowOfflineMode(self, val):
        self._allowLocalMode = val


# -------------------------------------------------------------------------------------------------------------
# Created by panda on 25/05/2018
Ejemplo n.º 18
0
class SignalManager(Signal):

    key = "SignalManager"

    showLayoutOld = DAMGLIST()
    executingOld = DAMGLIST()
    regisLayoutOld = DAMGLIST()
    openBrowserOld = DAMGLIST()
    setSettingOld = DAMGLIST()
    sysNotifyOld = DAMGLIST()
    updateAvatarOld = DAMGLIST()
    loginChangedOld = DAMGLIST()

    def __init__(self, parent=None):
        super(SignalManager, self).__init__(parent)

        self.parent = parent

        try:
            self.parent.children()
        except AttributeError:
            pass
        else:
            self.setParent(self.parent)
        finally:
            self.key = '{0}_{1}'.format(self.parent.key, self.key)

    def emit(self, signal, op1=None, op2=None, op3=None, op4=None):

        if self._emittable:
            sig = self.getSignal(signal)
            self.loadState()
            if signal == 'showLayout':
                self.showLayoutOld, repeat = self.checkSignalRepeat(
                    self.showLayoutOld, [op1, op2])
                old = self.showLayoutOld
                if repeat:
                    if self.print_checkState:
                        print(self.key, self.states)
                    if not self.states[op1] == op2:
                        self.states.add(op1, op2)
                        self.updateState()
                        sig.emit(op1, op2)
                else:
                    if self.print_checkState:
                        print(self.key, self.states)
                    self.states.add(op1, op2)
                    self.updateState()
                    sig.emit(op1, op2)
            elif signal == 'executing':
                self.executingOld, repeat = self.checkSignalRepeat(
                    self.executingOld, [op1])
                old = self.executingOld
                if not repeat:
                    sig.emit(op1)
            elif signal == 'regisLayout':
                self.regisLayoutOld, repeat = self.checkSignalRepeat(
                    self.regisLayoutOld, [op1])
                old = self.regisLayoutOld
                if not repeat:
                    sig.emit(op1)
            elif signal == 'openBrowser':
                self.openBrowserOld, repeat = self.checkSignalRepeat(
                    self.openBrowserOld, [op1])
                old = self.openBrowserOld
                if not repeat:
                    sig.emit(op1)
            elif signal == 'setSetting':
                self.setSettingOld, repeat = self.checkSignalRepeat(
                    self.setSettingOld, [op1, op2, op3])
                old = self.setSettingOld
                if not repeat:
                    sig.emit(op1, op2, op3)
            elif signal == 'sysNotify':
                self.sysNotifyOld, repeat = self.checkSignalRepeat(
                    self.sysNotifyOld, [op1, op2, op3, op4])
                old = self.sysNotifyOld
                if not repeat:
                    sig.emit(op1, op2, op3, op4)
            elif signal == 'updateAvatar':
                self.updateAvatarOld, repeat = self.checkSignalRepeat(
                    self.updateAvatarOld, [op1])
                old = self.updateAvatarOld
                if not repeat:
                    sig.emit(op1)
            elif signal == 'loginChanged':
                self.loginChangedOld, repeat = self.checkSignalRepeat(
                    self.loginChangedOld, [op1])
                old = self.loginChangedOld
                if not repeat:
                    sig.emit(op1)
            else:
                repeat = False
                old = []

            if repeat:
                if self.print_block:
                    print('{2}: block signal {0}: {1}'.format(
                        signal, old, self.key))
                return
            else:
                if self.print_emit:
                    print('{0} signal {1} emmited'.format(
                        self.parent.key, signal))
                return
        else:
            if self.print_emittable:
                print('UnEmittableError: {0} is not allowed to emit'.format(
                    self.key))
            return

    def getSignal(self, signal):
        if self.print_getSignal:
            print('{0} get signal: {1}'.format(self.parent.key, signal))
        return self.signals[signal][0]

    def connect(self, signal, target):
        sig = self.getSignal(signal)
        if self.auto_changeEmmittable:
            self._emittable = True
            return sig.connect(target)
        else:
            print('EmittableAllowError: Signal is not allowed to emit: {0}'.
                  format(signal))

    def checkSignalRepeat(self, old, data):
        new = [i for i in data]

        if self.print_checkRepeat:
            print(new, old)

        if len(new) == 0:
            repeat = False
        elif len(new) == len(old):
            repeat = True
            for i in range(len(new)):
                if not new[i] == old[i]:
                    repeat = False
                    break
        else:
            repeat = False

        old = DAMGLIST()
        old.appendList(new)
        return old, repeat


# -------------------------------------------------------------------------------------------------------------
# Created by panda on 25/10/2019 - 6:59 AM
# © 2017 - 2018 DAMGteam. All rights reserved
Ejemplo n.º 19
0
class LayoutManager(DAMG):

    key                                 = 'LayoutManager'

    _buildAll                           = False

    noShowHideAttrs                     = DAMGLIST()
    unHidableLayouts                    = DAMGLIST()
    unShowableLayouts                   = DAMGLIST()

    ignoreIDs = ['MainMenuSection', 'MainMenuBar', 'MainToolBarSection', 'MainToolBar',
                 'Notification', 'TopTab', 'BotTab', 'Footer', 'TopTab2', 'TopTab1',
                 'TopTab3', 'MainStatusBar', 'ConnectStatus', 'GridLayout']

    def __init__(self, setting, registryLayout, actionManager, buttonManager, eventManager, threadManager, parent=None):
        super(LayoutManager, self).__init__(parent)

        self.parent                     = parent
        self.settings                   = setting
        self.actionManager              = actionManager
        self.buttonManager              = buttonManager
        self._register                  = registryLayout
        self.eventManager               = eventManager
        self.threadManager              = threadManager

        self.globalSetting()

    def layouts(self):
        return self._register.values()

    def keys(self):
        return self._register.keys()

    def buildLayouts(self):
        self.mains                      = self.mainLayouts()
        self.funcs                      = self.functionLayouts()

        self.infos                      = self.infoLayouts()
        self.setts                      = self.settingLayouts()
        self.tools                      = self.toolLayouts()
        self.prjs                       = self.projectLayouts()

        tbcbs = self.preferences.headerGrid.toolBarCBs
        tbs = self.mainUI.mainToolBar.tbs

        cncbs = self.preferences.headerGrid.connectCBs
        cns = self.mainUI.connectStatus.labels

        mncbs = self.preferences.headerGrid.menuCBs
        mns = self.mainUI.mainMenuBar.mns

        for i in range(len(tbs)):
            cb = tbcbs[i]
            tb = tbs[i]
            cb.stateChanged.connect(tb.setVisible)
        tbcbs[-1].stateChanged.connect(self.mainUI.mainToolBarSec.setVisible)

        for i in range(len(mncbs)):
            cb = mncbs[i]
            mn = mns[i]
            cb.stateChanged.connect(self.mainUI.mainMenuBar.showMenu)
        mncbs[-1].stateChanged.connect(self.mainUI.mainMenuSec.setVisible)

        for i in range(len(cns)):
            cb = cncbs[i]
            lb = cns[i]
            cb.stateChanged.connect(lb.setVisible)
        cncbs[-1].stateChanged.connect(self.mainUI.connectStatusSec.setVisible)

        ntcbs = self.preferences.bodyGrid.notificationCBs
        nts = self.mainUI.notification.labels

        for i in range(len(nts)):
            cb = ntcbs[i]
            lb = nts[i]
            cb.stateChanged.connect(lb.setVisible)
        ntcbs[-1].stateChanged.connect(self.mainUI.notifiSec.setVisible)

        for layout in self.layouts():
            try:
                layout.isHidden()
            except AttributeError:
                self.noShowHideAttrs.append(layout)

        layouts = []
        for listLayout in [self.mains, self.funcs, self.infos, self.setts, self.tools, self.prjs]:
            layouts = layouts + list(listLayout)
        self._buildAll = True

        return layouts

    def functionLayouts(self):
        from ui.subUI.Funcs.SignIn          import SignIn
        from ui.subUI.Funcs.SignUp          import SignUp
        from ui.subUI.Funcs.ForgotPassword  import ForgotPassword

        self.signin     = SignIn()
        self.forgotPW   = ForgotPassword()
        self.signup     = SignUp()

        for layout in [self.signin, self.signup, self.forgotPW]:
            self.registLayout(layout)

        return self.signin, self.signup, self.forgotPW

    def mainLayouts(self):
        from ui.PipelineManager             import PipelineManager
        from ui.SysTray                     import SysTray
        from ui.subUI.ShortcutCommand       import ShortcutCommand

        self.mainUI                         = PipelineManager(self.actionManager, self.buttonManager, self.threadManager)
        self.sysTray                        = SysTray(self.actionManager, self.eventManager)
        self.shortcutLayout                 = ShortcutCommand()
        self.setLayoutUnHidable(self.sysTray)

        layouts = [self.mainUI, self.sysTray, self.shortcutLayout]

        for layout in layouts:
            layout.settings._settingEnable = True
            self.registLayout(layout)

        # for layout in self.mainUI.layouts:
        #     self.registLayout(layout)
        #
        # for layout in self.mainUI.topTabUI.tabs:
        #     key = layout.key
        #     if not key in self._register.keys():
        #         self._register[key] = layout

        return layouts

    def infoLayouts(self):
        from ui.subUI.Info.InfoWidget       import InfoWidget

        self.about                          = InfoWidget(key='About')
        self.codeConduct                    = InfoWidget(key='CodeOfConduct')
        self.contributing                   = InfoWidget(key='Contributing')
        self.credit                         = InfoWidget(key="Credit")
        self.licence                        = InfoWidget(key='Licence')
        self.reference                      = InfoWidget(key='Reference')
        self.version                        = InfoWidget(key='Version')

        layouts = [self.about, self.codeConduct, self.contributing, self.credit, self.licence,
                    self. reference, self.version]

        for layout in layouts:
            layout.settings._settingEnable = True
            self.registLayout(layout)

        return layouts

    def settingLayouts(self):
        from ui.subUI.Settings.SettingUI    import SettingUI
        from ui.subUI.Settings.UserSetting  import UserSetting

        self.settingUI                      = SettingUI()
        self.userSetting                    = UserSetting()

        layouts = [self.settingUI, self.userSetting]

        for layout in layouts:
            self.registLayout(layout)

        return layouts

    def toolLayouts(self):
        from ui.subUI.Tools                 import (Screenshot, NoteReminder, ImageViewer, FindFiles, EnglishDictionary,
                                                    Calendar, Calculator)
        from ui.subUI.Tools.NodeGraph       import NodeGraph
        from ui.subUI.Tools.TextEditor      import TextEditor
        from ui.Header.Menus.config         import Preferences
        from ui.Header.Menus.config         import Configuration
        from ui.subUI.TaskManager           import TaskManager

        self.calculator                     = Calculator.Calculator()
        self.calendar                       = Calendar.Calendar()
        self.configuration                  = Configuration.Configuration()
        self.engDict                        = EnglishDictionary.EnglishDictionary()
        self.findFile                       = FindFiles.FindFiles()
        self.imageViewer                    = ImageViewer.ImageViewer()
        self.nodeGraph                      = NodeGraph.NodeGraph()
        self.noteReminder                   = NoteReminder.NoteReminder()
        self.preferences                    = Preferences.Preferences()
        self.screenShot                     = Screenshot.Screenshot()
        self.textEditor                     = TextEditor.TextEditor()
        self.taskManager                    = TaskManager(self.mainUI)

        layouts     = [self.calculator, self.calendar, self.configuration, self.engDict, self.findFile,
                       self.imageViewer, self.nodeGraph, self.noteReminder, self.preferences, self.screenShot,
                       self.textEditor, self.taskManager]

        for layout in layouts:
            layout.settings._settingEnable = True
            self.registLayout(layout)

        return layouts

    def projectLayouts(self):
        from ui.subUI.Projects.NewProject   import NewProject

        self.newProject                     = NewProject()

        for layout in [self.newProject, ]:
            layout.settings._settingEnable = True
            self.registLayout(layout)

        layouts = [self.newProject]
        return layouts

    def showOnlyLayout(self, layout):
        layouts = [l for l in self.layouts() if not l is layout and not l in self.unHidableLayouts]
        if self.isHidable(layout):
            self.show(layout)

        for l in layouts:
            self.hide(l)

    def hideOnlyLayout(self, layout):
        layouts = [l for l in self.layouts() if not l is layout and not l in self.unHidableLayouts]
        if self.isHidable(layout):
            self.hide(layout)

        for l in layouts:
            self.show(l)

    def setLayoutUnHidable(self, layout):
        if not layout in self.unHidableLayouts:
            layout.show()
            layout.setVisible(True)
            return self.unHidableLayouts.append(layout)

    def setLayoutUnShowable(self, layout):
        if not layout in self.unShowableLayouts:
            self.hide(layout)
            return self.unShowableLayouts.append(layout)

    def setLayoutHidable(self, layout):
        if layout in self.unHidableLayouts:
            self.show(layout)
            return self.unHidableLayouts.remove(layout)

    def isHidable(self, layout):
        if not layout in self.noShowHideAttrs:
            if not layout in self.unHidableLayouts:
                try:
                    layout.isHidden()
                except AttributeError:
                    return False
                else:
                    return True
            elif layout in self.unShowableLayouts:
                return False
            else:
                return False
        else:
            return False

    def hide(self, layout):
        if not layout.key in self.ignoreIDs:
            layout.hide()
            return layout.setValue('state', 'hide')

    def show(self, layout):
        if not layout.key in self.ignoreIDs:
            layout.show()
            return layout.setValue('state', 'show')

    def showNormal(self, layout):
        if not layout.key in self.ignoreIDs:
            layout.showNormal()
            return layout.setValue('state', 'showNormal')

    def showMinnimize(self, layout):
        if not layout.key in self.ignoreIDs:
            layout.showMinimize()
            return layout.setValue('state', 'showMinimize')

    def showMaximized(self, layout):
        if not layout.key in self.ignoreIDs:
            layout.showMaximized()
            return layout.setValue('state', 'showMaximized')

    def showAllLayout(self):
        for layout in self.layouts():
            self.show(layout)

    def registLayout(self, layout):
        return self._register.regisLayout(layout)

    def globalSetting(self):
        for layout in self.layouts():
            # print(layout.key)
            try:
                layout.setContentMargin(1,1,1,1)
            except AttributeError:
                pass

            try:
                layout.setSizePolicy(SiPoMin, SiPoMin)
            except AttributeError:
                pass

            try:
                layout.setSpacing(2)
            except AttributeError:
                pass

            if layout.key == 'PipelineManager':
                layout.setFixedWidth(475)
                # layout.setFixedHeight(850)
                # self.parent.setWindowFlags(STAY_ON_TOP)
                pass

            if layout.key in ['TobTab', 'BotTab']:
                layout.setMovable(True)
                layout.setElideMode(Qt.ElideRight)
                layout.setUsesScrollButtons(True)
                pass

    @property
    def buildAll(self):
        return self._buildAll

    @property
    def register(self):
        return self._register

    @buildAll.setter
    def buildAll(self, val):
        self._buildAll = val

    @register.setter
    def register(self, val):
        self._register = val

# -------------------------------------------------------------------------------------------------------------
# Created by panda on 6/07/2018 - 11:31 AM
# © 2017 - 2018 DAMGteam. All rights reserved