Example #1
0
File: text.py Project: Farb/calibre
    def font(self, text_style):
        device_font = text_style.fontfacename in LIBERATION_FONT_MAP
        try:
            if device_font:
                face = self.font_map[text_style.fontfacename]
            else:
                face = self.face_map[text_style.fontfacename]
        except KeyError:  # Bad fontfacename field in LRF
            face = self.font_map['Dutch801 Rm BT Roman']

        sz = text_style.fontsize
        wt = text_style.fontweight
        style = text_style.fontstyle
        font = (face, wt, style, sz,)
        if font in self.cache:
            rfont = self.cache[font]
        else:
            italic = font[2] == QFont.StyleItalic
            rfont = QFont(font[0], font[3], font[1], italic)
            rfont.setPixelSize(font[3])
            rfont.setBold(wt>=69)
            self.cache[font] = rfont
        qfont = rfont
        if text_style.emplinetype != 'none':
            qfont = QFont(rfont)
            qfont.setOverline(text_style.emplineposition == 'before')
            qfont.setUnderline(text_style.emplineposition == 'after')
        return qfont
Example #2
0
    def font(self, text_style):
        device_font = text_style.fontfacename in LIBERATION_FONT_MAP
        try:
            if device_font:
                face = self.font_map[text_style.fontfacename]
            else:
                face = self.face_map[text_style.fontfacename]
        except KeyError:  # Bad fontfacename field in LRF
            face = self.font_map['Dutch801 Rm BT Roman']

        sz = text_style.fontsize
        wt = text_style.fontweight
        style = text_style.fontstyle
        font = (
            face,
            wt,
            style,
            sz,
        )
        if font in self.cache:
            rfont = self.cache[font]
        else:
            italic = font[2] == QFont.StyleItalic
            rfont = QFont(font[0], font[3], font[1], italic)
            rfont.setPixelSize(font[3])
            rfont.setBold(wt >= 69)
            self.cache[font] = rfont
        qfont = rfont
        if text_style.emplinetype != 'none':
            qfont = QFont(rfont)
            qfont.setOverline(text_style.emplineposition == 'before')
            qfont.setUnderline(text_style.emplineposition == 'after')
        return qfont
Example #3
0
def generate_masthead(title,
                      output_path=None,
                      width=600,
                      height=60,
                      as_qimage=False,
                      font_family=None):
    init_environment()
    font_family = font_family or cprefs[
        'title_font_family'] or 'Liberation Serif'
    img = QImage(width, height, QImage.Format_ARGB32)
    img.fill(Qt.white)
    p = QPainter(img)
    p.setRenderHints(QPainter.Antialiasing | QPainter.TextAntialiasing)
    f = QFont(font_family)
    f.setStyleStrategy(QFont.PreferAntialias)
    f.setPixelSize((height * 3) // 4), f.setBold(True)
    p.setFont(f)
    p.drawText(img.rect(), Qt.AlignLeft | Qt.AlignVCenter, sanitize(title))
    p.end()
    if as_qimage:
        return img
    data = pixmap_to_data(img)
    if output_path is None:
        return data
    with open(output_path, 'wb') as f:
        f.write(data)
Example #4
0
 def initUI(self):
     font = QFont()
     font.setWeight(50)
     font.setPixelSize(15)
     self.human_machine.setFont(font)
     self.machine_machine.setFont(font)
     self.vs_group.addButton(self.human_machine, 1)
     self.vs_group.addButton(self.machine_machine, 2)
     self.vs_group.buttonClicked.connect(self.radioClicked)
class TextLine(object):

    def __init__(self, text, font_name, font_size,
                 bottom_margin=30, align='center'):
        self.text = force_unicode(text)
        self.bottom_margin = bottom_margin
        from PyQt5.Qt import QFont, Qt
        self.font = QFont(font_name) if font_name else QFont()
        self.font.setPixelSize(font_size)
        self._align = {'center': Qt.AlignHCenter,
                       'left': Qt.AlignLeft, 'right': Qt.AlignRight}[align]
Example #6
0
def message_image(text, width=500, height=400, font_size=20):
    init_environment()
    img = QImage(width, height, QImage.Format_ARGB32)
    img.fill(Qt.white)
    p = QPainter(img)
    f = QFont()
    f.setPixelSize(font_size)
    p.setFont(f)
    r = img.rect().adjusted(10, 10, -10, -10)
    p.drawText(r, Qt.AlignJustify | Qt.AlignVCenter | Qt.TextWordWrap, text)
    p.end()
    return pixmap_to_data(img)
Example #7
0
def message_image(text, width=500, height=400, font_size=20):
    init_environment()
    img = QImage(width, height, QImage.Format_ARGB32)
    img.fill(Qt.white)
    p = QPainter(img)
    f = QFont()
    f.setPixelSize(font_size)
    p.setFont(f)
    r = img.rect().adjusted(10, 10, -10, -10)
    p.drawText(r, Qt.AlignJustify | Qt.AlignVCenter | Qt.TextWordWrap, text)
    p.end()
    return pixmap_to_data(img)
Example #8
0
    def popup(self, select_first=True):
        if self.disable_popup:
            return
        p = self
        m = p.model()
        widget = self.completer_widget()
        if widget is None:
            return
        screen = QApplication.desktop().availableGeometry(widget)
        h = (p.sizeHintForRow(0) * min(self.max_visible_items, m.rowCount()) + 3) + 3
        hsb = p.horizontalScrollBar()
        if hsb and hsb.isVisible():
            h += hsb.sizeHint().height()

        rh = widget.height()
        pos = widget.mapToGlobal(QPoint(0, widget.height() - 2))
        w = min(widget.width(), screen.width())

        if (pos.x() + w) > (screen.x() + screen.width()):
            pos.setX(screen.x() + screen.width() - w)
        if pos.x() < screen.x():
            pos.setX(screen.x())

        top = pos.y() - rh - screen.top() + 2
        bottom = screen.bottom() - pos.y()
        h = max(h, p.minimumHeight())
        if h > bottom:
            h = min(max(top, bottom), h)

            if top > bottom:
                pos.setY(pos.y() - h - rh + 2)

        p.setGeometry(pos.x(), pos.y(), w, h)

        if (
            tweaks["preselect_first_completion"]
            and select_first
            and not self.currentIndex().isValid()
            and self.model().rowCount() > 0
        ):
            self.setCurrentIndex(self.model().index(0))

        if not p.isVisible():
            if isosx and get_osx_version() >= (10, 9, 0):
                # On mavericks the popup menu seems to use a font smaller than
                # the widgets font, see for example:
                # https://bugs.launchpad.net/bugs/1243761
                fp = QFontInfo(widget.font())
                f = QFont()
                f.setPixelSize(fp.pixelSize())
                self.setFont(f)
            p.show()
Example #9
0
 def create_launch_button(self):
     """
     Configure the launch button
     :return: 
     """
     self.launchButton.setGeometry(19, 275, 352, 40)
     self.launchButton.setText('Launch the game')
     self.launchButton.setDisabled(True)
     font = QFont()
     font.setBold(True)
     font.setPixelSize(12)
     self.launchButton.setFont(font)
     self.launchButton.clicked.connect(self.launch_game)
Example #10
0
    def popup(self, select_first=True):
        if self.disable_popup:
            return
        p = self
        m = p.model()
        widget = self.completer_widget()
        if widget is None:
            return
        screen = QApplication.desktop().availableGeometry(widget)
        h = (p.sizeHintForRow(0) * min(self.max_visible_items, m.rowCount()) +
             3) + 3
        hsb = p.horizontalScrollBar()
        if hsb and hsb.isVisible():
            h += hsb.sizeHint().height()

        rh = widget.height()
        pos = widget.mapToGlobal(QPoint(0, widget.height() - 2))
        w = min(widget.width(), screen.width())

        if (pos.x() + w) > (screen.x() + screen.width()):
            pos.setX(screen.x() + screen.width() - w)
        if pos.x() < screen.x():
            pos.setX(screen.x())

        top = pos.y() - rh - screen.top() + 2
        bottom = screen.bottom() - pos.y()
        h = max(h, p.minimumHeight())
        if h > bottom:
            h = min(max(top, bottom), h)

            if top > bottom:
                pos.setY(pos.y() - h - rh + 2)

        p.setGeometry(pos.x(), pos.y(), w, h)

        if (tweaks['preselect_first_completion'] and select_first
                and not self.currentIndex().isValid()
                and self.model().rowCount() > 0):
            self.setCurrentIndex(self.model().index(0))

        if not p.isVisible():
            if isosx and get_osx_version() >= (10, 9, 0):
                # On mavericks the popup menu seems to use a font smaller than
                # the widgets font, see for example:
                # https://bugs.launchpad.net/bugs/1243761
                fp = QFontInfo(widget.font())
                f = QFont()
                f.setPixelSize(fp.pixelSize())
                self.setFont(f)
            p.show()
Example #11
0
File: text.py Project: Farb/calibre
    def populate(self, phrase, ts, process_space=True):
        phrase_pos = 0
        processed = False
        matches = self.__class__.whitespace.finditer(phrase)
        font = QFont(ts.font)
        if self.valign is not None:
            font.setPixelSize(font.pixelSize()/1.5)
        fm = QFontMetrics(font)
        single_space_width = fm.width(' ')
        height, descent = fm.height(), fm.descent()
        for match in matches:
            processed = True
            left, right = match.span()
            if not process_space:
                right = left
            space_width = single_space_width * (right-left)
            word = phrase[phrase_pos:left]
            width = fm.width(word)
            if self.current_width + width < self.line_length:
                self.commit(word, width, height, descent, ts, font)
                if space_width > 0 and self.current_width + space_width < self.line_length:
                    self.add_space(space_width)
                phrase_pos = right
                continue

            # Word doesn't fit on line
            if self.hyphenate and len(word) > 3:
                tokens = hyphenate_word(word)
                for i in range(len(tokens)-2, -1, -1):
                    word = ''.join(tokens[0:i+1])+'-'
                    width = fm.width(word)
                    if self.current_width + width < self.line_length:
                        self.commit(word, width, height, descent, ts, font)
                        return phrase_pos + len(word)-1, True
            if self.current_width < 5:  # Force hyphenation as word is longer than line
                for i in range(len(word)-5, 0, -5):
                    part = word[:i] + '-'
                    width = fm.width(part)
                    if self.current_width + width < self.line_length:
                        self.commit(part, width, height, descent, ts, font)
                        return phrase_pos + len(part)-1, True
            # Failed to add word.
            return phrase_pos, True

        if not processed:
            return self.populate(phrase+' ', ts, False)

        return phrase_pos, False
Example #12
0
    def populate(self, phrase, ts, process_space=True):
        phrase_pos = 0
        processed = False
        matches = self.__class__.whitespace.finditer(phrase)
        font = QFont(ts.font)
        if self.valign is not None:
            font.setPixelSize(font.pixelSize() / 1.5)
        fm = QFontMetrics(font)
        single_space_width = fm.width(' ')
        height, descent = fm.height(), fm.descent()
        for match in matches:
            processed = True
            left, right = match.span()
            if not process_space:
                right = left
            space_width = single_space_width * (right - left)
            word = phrase[phrase_pos:left]
            width = fm.width(word)
            if self.current_width + width < self.line_length:
                self.commit(word, width, height, descent, ts, font)
                if space_width > 0 and self.current_width + space_width < self.line_length:
                    self.add_space(space_width)
                phrase_pos = right
                continue

            # Word doesn't fit on line
            if self.hyphenate and len(word) > 3:
                tokens = hyphenate_word(word)
                for i in range(len(tokens) - 2, -1, -1):
                    word = ''.join(tokens[0:i + 1]) + '-'
                    width = fm.width(word)
                    if self.current_width + width < self.line_length:
                        self.commit(word, width, height, descent, ts, font)
                        return phrase_pos + len(word) - 1, True
            if self.current_width < 5:  # Force hyphenation as word is longer than line
                for i in range(len(word) - 5, 0, -5):
                    part = word[:i] + '-'
                    width = fm.width(part)
                    if self.current_width + width < self.line_length:
                        self.commit(part, width, height, descent, ts, font)
                        return phrase_pos + len(part) - 1, True
            # Failed to add word.
            return phrase_pos, True

        if not processed:
            return self.populate(phrase + ' ', ts, False)

        return phrase_pos, False
Example #13
0
 def _generate_loading_map(self):
     text = 'Loading...'
     pixmap = QPixmap(self._w, self._h)
     pixmap.fill(self.palette().dark().color())
     painter = QPainter(pixmap)
     painter.setRenderHint(QPainter.TextAntialiasing)
     font = QFont()
     font.setPixelSize(60)
     painter.setFont(font)
     painter.setPen(self.palette().text().color())
     text_size = painter.fontMetrics().size(0, text)
     painter.drawText((self._w - text_size.width()) / 2,
                      (self._h - text_size.height()) / 2, text_size.width(),
                      text_size.height(), Qt.AlignCenter, text)
     painter.end()
     return pixmap
Example #14
0
    def setTopLayout(self):
        # list menu
        self.list_widget = QListWidget()
        self.list_widget.setMinimumHeight(25)
        self.list_widget.setFlow(QListWidget.LeftToRight)
        self.list_widget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.list_widget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.list_widget.setFrameShape(QListWidget.NoFrame)
        # list item for menu
        self.list_items = QStackedWidget()

        self.top_layout.addWidget(self.list_widget)
        self.top_layout.addWidget(self.list_items)
        self.top_layout.setStretchFactor(self.list_widget, 1)
        self.top_layout.setStretchFactor(self.list_items, 3)

        self.list_widget.currentRowChanged.connect(
            self.list_items.setCurrentIndex)
        self.list_widget.currentRowChanged.connect(
            self.item_choose)
        self.list_str = [
            strings.PATTERN,
            strings.OPERATIONAL_PLANNING,
            strings.MAPS,
            strings.REPLAY,
            strings.SITUATION_INFORMATION,
            strings.MODEL_TRAIN]
        self.item_view = [
            strings.CLASS_PATTERN,
            strings.CLASS_OPERATIONAL_PLANNING,
            strings.CLASS_MAPS,
            strings.CLASS_REPLAY,
            strings.CLASS_SITUATION_INFORMATION,
            strings.CLASS_MODEL_TRAIN]
        for i in range(len(self.list_str)):
            font = QFont()
            font.setBold(True)
            font.setWeight(50)
            font.setPixelSize(14)
            # add item to menu
            item = QListWidgetItem(self.list_str[i], self.list_widget)
            item.setFont(font)
            item.setTextAlignment(Qt.AlignCenter)
            if i == 0:
                item.setSelected(True)
            self.list_items.addWidget(eval(self.item_view[i]))
Example #15
0
    def initItems(self):
        font = QFont()
        font.setPixelSize(16)

        self.prepareModel(os.getcwd())

        self.setToolTip(os.getcwd())

        # prepare drag and drop
        self.setDragEnabled(False)

        sizePolicy = QSizePolicy(QSizePolicy.MinimumExpanding,
                                 QSizePolicy.MinimumExpanding)
        self.setSizePolicy(sizePolicy)
        self.setAutoExpandDelay(2)
        self.setAlternatingRowColors(False)
        self.setAnimated(False)
        self.setIndentation(20)
        self.setSortingEnabled(False)
        self.setRootIsDecorated(False)
        self.setPalette(QPalette(Qt.black))

        self.verticalScrollBar().setStyleSheet("""border: 20px solid black;
            background-color: darkgreen;
            alternate-background-color: #FFFFFF;""")

        self.horizontalScrollBar().setStyleSheet("""border: 20px solid black;
            background-color: darkgreen;
            alternate-background-color: #FFFFFF;""")

        self.setFont(font)

        # signals
        self.doubleClicked.connect(self.onDoubleClicked)
        self.clicked.connect(self.onClicked)
        self.pressed.connect(self.onClicked)
        #self.entered.connect(self.onEntered)
        self.columnMoved()

        # that hides the size, file type and last modified colomns
        self.setHeaderHidden(True)
        self.hideColumn(1)
        self.hideColumn(2)
        self.hideColumn(3)
        self.resize(400, 400)
Example #16
0
def generate_masthead(title, output_path=None, width=600, height=60, as_qimage=False, font_family=None):
    init_environment()
    font_family = font_family or cprefs['title_font_family'] or 'Liberation Serif'
    img = QImage(width, height, QImage.Format_ARGB32)
    img.fill(Qt.white)
    p = QPainter(img)
    f = QFont(font_family)
    f.setPixelSize((height * 3) // 4), f.setBold(True)
    p.setFont(f)
    p.drawText(img.rect(), Qt.AlignLeft | Qt.AlignVCenter, sanitize(title))
    p.end()
    if as_qimage:
        return img
    data = pixmap_to_data(img)
    if output_path is None:
        return data
    with open(output_path, 'wb') as f:
        f.write(data)
Example #17
0
def layout_text(prefs, img, title, subtitle, footer, max_height, style):
    width = img.width() - 2 * style.hmargin
    title, subtitle, footer = title, subtitle, footer
    title_font = QFont(prefs.title_font_family or 'Liberation Serif')
    title_font.setPixelSize(prefs.title_font_size)
    title_font.setStyleStrategy(QFont.PreferAntialias)
    title_block = Block(title, width, title_font, img, max_height, style.TITLE_ALIGN)
    title_block.position = style.hmargin, style.vmargin
    subtitle_block = Block()
    if subtitle:
        subtitle_font = QFont(prefs.subtitle_font_family or 'Liberation Sans')
        subtitle_font.setPixelSize(prefs.subtitle_font_size)
        subtitle_font.setStyleStrategy(QFont.PreferAntialias)
        gap = 2 * title_block.leading
        mh = max_height - title_block.height - gap
        subtitle_block = Block(subtitle, width, subtitle_font, img, mh, style.SUBTITLE_ALIGN)
        subtitle_block.position = style.hmargin, title_block.position.y + title_block.height + gap

    footer_font = QFont(prefs.footer_font_family or 'Liberation Serif')
    footer_font.setStyleStrategy(QFont.PreferAntialias)
    footer_font.setPixelSize(prefs.footer_font_size)
    footer_block = Block(footer, width, footer_font, img, max_height, style.FOOTER_ALIGN)
    footer_block.position = style.hmargin, img.height() - style.vmargin - footer_block.height

    return title_block, subtitle_block, footer_block
Example #18
0
def layout_text(prefs, img, title, subtitle, footer, max_height, style):
    width = img.width() - 2 * style.hmargin
    title, subtitle, footer = title, subtitle, footer
    title_font = QFont(prefs.title_font_family or 'Liberation Serif')
    title_font.setPixelSize(prefs.title_font_size)
    title_block = Block(title, width, title_font, img, max_height,
                        style.TITLE_ALIGN)
    title_block.position = style.hmargin, style.vmargin
    subtitle_block = Block()
    if subtitle:
        subtitle_font = QFont(prefs.subtitle_font_family or 'Liberation Sans')
        subtitle_font.setPixelSize(prefs.subtitle_font_size)
        gap = 2 * title_block.leading
        mh = max_height - title_block.height - gap
        subtitle_block = Block(subtitle, width, subtitle_font, img, mh,
                               style.SUBTITLE_ALIGN)
        subtitle_block.position = style.hmargin, title_block.position.y + title_block.height + gap

    footer_font = QFont(prefs.footer_font_family or 'Liberation Serif')
    footer_font.setPixelSize(prefs.footer_font_size)
    footer_block = Block(footer, width, footer_font, img, max_height,
                         style.FOOTER_ALIGN)
    footer_block.position = style.hmargin, img.height(
    ) - style.vmargin - footer_block.height

    return title_block, subtitle_block, footer_block
Example #19
0
    def initTab(self):
        # connect tab and item
        self.tab_widget.currentRowChanged.connect(self.item_widget.setCurrentIndex)
        self.tab_widget.currentRowChanged.connect(self.map_choose)
        for i in range(len(self.list_str)):
            # add item to tab
            font = QFont()
            font.setBold(True)
            font.setWeight(50)
            font.setPixelSize(14)

            item = QListWidgetItem(self.list_str[i], self.tab_widget)
            item.setSizeHint(QSize(30, 50))
            item.setFont(font)
            item.setTextAlignment(Qt.AlignCenter)
            if i == 0:
                item.setSelected(True)
            # add item content
            if self.name == strings.TYPE_POLICY:
                self.item_widget.addWidget(eval(self.list_item[i]))
            elif self.name == strings.TYPE_MAP:
                self.item_widget.addWidget(MapDescription(self.list_str[i]))
Example #20
0
    def __init__(self):
        super(ModelTrain, self).__init__()
        self.setObjectName('ModelTrain')
        self.setStyleSheet(
            GetQssFile.readQss('../resource/qss/modelTrain.qss'))

        self.log = logging.getLogger('StarCraftII')

        # font
        font = QFont()
        font.setWeight(50)
        font.setPixelSize(15)

        # set widget of layout
        self.frame = QFrame(self)
        self.frame.setGeometry(QDesktopWidget().screenGeometry())
        self.main_layout = QHBoxLayout(self)
        self.main_layout.setSpacing(20)
        self.setLayout(self.main_layout)

        # model tarin
        self.modelTrain = QPushButton()
        self.modelTrain.setObjectName('modelTrain')
        self.modelTrainLabel = QLabel('model train')
        self.modelTrainLabel.setFont(font)
        self.modelTrain_layout = QVBoxLayout()
        self.modelTrain_layout.addWidget(self.modelTrain,
                                         alignment=Qt.AlignCenter)
        self.modelTrain_layout.addWidget(self.modelTrainLabel,
                                         alignment=Qt.AlignCenter)
        self.main_layout.addLayout(self.modelTrain_layout)

        # a description dialog
        self.dialog = None
        # add stretch
        self.main_layout.addStretch(1)

        # initialization
        self.initUI()
Example #21
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        if self.isDown():
            painter.translate(1, 1)

        font = QFont()
        font.setPixelSize(14)
        painter.setFont(font)
        if self._hover or self.isChecked():
            color = self.palette().highlight().color()
            icon = self._hover_icon
        else:
            color = self.palette().text().color()
            icon = self._icon
        painter.setPen(color)

        icon_size = self._icon.size()

        if self._text:
            text_size = painter.fontMetrics().size(0, self._text)
            label_height = (text_size.height() + self._spacing +
                            icon_size.height())
        else:
            label_height = icon_size.height()

        center = self.contentsRect().center()

        painter.drawPixmap(center.x() - icon_size.width() / 2,
                           center.y() - label_height / 2, icon)

        if self._text:
            painter.drawText(center.x() - text_size.width() / 2,
                             center.y() - label_height / 2, text_size.width(),
                             label_height, Qt.AlignBottom | Qt.AlignVCenter,
                             self._text)
    def __init__(self):
        super(OperationalPlanning, self).__init__()
        self.setObjectName('OperationalPlanning')
        self.setStyleSheet(GetQssFile.readQss('../resource/qss/operationalPlanning.qss'))

        self.log = logging.getLogger('StarCraftII')
        # test fix algorithm
        self.algorithm = None
        self.algorithmThread = None

        # font
        font = QFont()
        font.setWeight(50)
        font.setPixelSize(15)

        # set widget of layout
        self.frame = QFrame(self)
        self.frame.setGeometry(QDesktopWidget().screenGeometry())
        self.main_layout = QHBoxLayout(self)
        self.main_layout.setSpacing(20)
        self.setLayout(self.main_layout)

        # start action
        self.start = QPushButton()
        self.start.setObjectName('start')
        self.startLabel = QLabel('start')
        self.startLabel.setFont(font)
        self.start_layout = QVBoxLayout()
        self.start_layout.addWidget(self.start, alignment=Qt.AlignCenter)
        self.start_layout.addWidget(self.startLabel, alignment=Qt.AlignCenter)
        self.main_layout.addLayout(self.start_layout)

        # pause action
        # self.pause = QPushButton()
        # self.pause.setObjectName('pause')
        # self.pauseLabel = QLabel('pause')
        # self.pauseLabel.setFont(font)
        # self.pause_layout = QVBoxLayout()
        # self.pause_layout.addWidget(self.pause, alignment=Qt.AlignCenter)
        # self.pause_layout.addWidget(self.pauseLabel, alignment=Qt.AlignCenter)
        # self.main_layout.addLayout(self.pause_layout)

        # stop action
        self.stop = QPushButton()
        self.stop.setObjectName('stop')
        self.stopLabel = QLabel('stop')
        self.stopLabel.setFont(font)
        self.stop_layout = QVBoxLayout()
        self.stop_layout.addWidget(self.stop, alignment=Qt.AlignCenter)
        self.stop_layout.addWidget(self.stopLabel, alignment=Qt.AlignCenter)
        self.main_layout.addLayout(self.stop_layout)

        # switch policy action
        self.switch = QPushButton()
        self.switch.setObjectName('switch')
        self.switchLabel = QLabel('switch policy')
        self.switchLabel.setFont(font)
        self.switch_layout = QVBoxLayout()
        self.switch_layout.addWidget(self.switch, alignment=Qt.AlignCenter)
        self.switch_layout.addWidget(self.switchLabel, alignment=Qt.AlignCenter)
        self.main_layout.addLayout(self.switch_layout)

        # simulation time
        self.lcd = QLCDNumber()
        self.lcd.setObjectName('lcd')
        self.lcd.setDigitCount(10)
        self.lcd.setMode(QLCDNumber.Dec)
        self.lcd.setSegmentStyle(QLCDNumber.Flat)
        self.lcd.setFrameStyle(QFrame.Panel | QFrame.Raised)
        self.lcd.display(time.strftime("%X", time.localtime()))
        self.lcdLabel = QLabel('simulation time')
        self.lcdLabel.setFont(font)
        self.lcd_layout = QVBoxLayout()
        self.lcd_layout.addWidget(self.lcd, alignment=Qt.AlignBottom)
        self.lcd_layout.addWidget(self.lcdLabel, alignment=Qt.AlignBottom)
        self.main_layout.addLayout(self.lcd_layout)

        # define time
        self.qtime = QTimer()
        self.qtime.timeout.connect(self.refresh)

        # define global variable
        global interval
        interval = 0
        global start_or_pause
        start_or_pause = False
        global stop
        stop = True

        # map description
        self.map = QPushButton()
        self.map.setObjectName('map')
        self.mapLabel = QLabel('map description')
        self.mapLabel.setFont(font)
        self.map_layout = QVBoxLayout()
        self.map_layout.addWidget(self.map, alignment=Qt.AlignCenter)
        self.map_layout.addWidget(self.mapLabel, alignment=Qt.AlignCenter)
        self.main_layout.addLayout(self.map_layout)

        # add stretch
        self.main_layout.addStretch(1)

        # popup window
        self.dialog = None

        # initialization
        self.initUI()
Example #23
0
    def __init__(self):
        super(Maps, self).__init__()
        self.setObjectName('Maps')
        self.setStyleSheet(GetQssFile.readQss('../resource/qss/maps.qss'))

        # font
        font = QFont("Roman times", 36, QFont.Bold)
        # font.setWeight(50)
        # font.setFamily('Helvetica')
        font.setPixelSize(15)

        # set widget of layout
        self.frame = QFrame(self)
        self.frame.setGeometry(QDesktopWidget().screenGeometry())
        self.main_layout = QHBoxLayout(self)
        self.main_layout.setSpacing(20)
        self.setLayout(self.main_layout)

        # choose map
        self.chooseMap = QPushButton()
        self.chooseMap.setObjectName('chooseMap')
        self.chooseMapLabel = QLabel('choose map')
        self.chooseMapLabel.setFont(font)
        self.chooseMap_layout = QVBoxLayout()
        self.chooseMap_layout.addWidget(self.chooseMap,
                                        alignment=Qt.AlignCenter)
        self.chooseMap_layout.addWidget(self.chooseMapLabel,
                                        alignment=Qt.AlignCenter)
        self.main_layout.addLayout(self.chooseMap_layout)

        # map design
        self.mapDesign = QPushButton()
        self.mapDesign.setObjectName('mapDesign')
        self.mapDesignLabel = QLabel('map design')
        self.mapDesignLabel.setFont(font)
        self.mapDesign_layout = QVBoxLayout()
        self.mapDesign_layout.addWidget(self.mapDesign,
                                        alignment=Qt.AlignCenter)
        self.mapDesign_layout.addWidget(self.mapDesignLabel,
                                        alignment=Qt.AlignCenter)
        self.main_layout.addLayout(self.mapDesign_layout)

        # dialog
        self.dialog = None

        # add stretch
        self.main_layout.addStretch(1)

        # initialization
        self.initUI()

        self.list_str = [
            strings.MAP_MOVE_TO_BEACON, strings.MAP_COLLECT_MINERAL_SHARDS,
            strings.MAP_FIND_AND_DEFEAT_ZERGLINGS, strings.MAP_DEFEAT_ROACHES,
            strings.MAP_DEFEAT_ZERGLINGS_AND_BANELINGS,
            strings.MAP_COLLECT_MINERALS_AND_GAS, strings.MAP_BUILD_MARINES,
            strings.MAP_2C_VS_64ZG, strings.MAP_2M_VS_1Z, strings.MAP_2S3Z,
            strings.MAP_2S_VS_1SC, strings.MAP_3M, strings.MAP_3S5Z,
            strings.MAP_3S5Z_VS_3S6Z, strings.MAP_3S_VS_3Z,
            strings.MAP_3S_VS_4Z, strings.MAP_3S_VS_5Z, strings.MAP_5M_VS_6M,
            strings.MAP_6H_VS_8Z, strings.MAP_8M, strings.MAP_8M_VS_9M,
            strings.MAP_10M_VS_11M, strings.MAP_25M, strings.MAP_27M_VS_30M,
            strings.MAP_BANE_VS_BANE, strings.MAP_CORRIDOR, strings.MAP_MMM,
            strings.MAP_MMM2, strings.MAP_SO_MANY_BANELINGS
        ]
    def draw(self, event, qp):
        #         self.angle += 0.04
        #         self._set_current_angle_in_radians(self.angle)

        #--------------------------------------------------------------------
        # Draw X axis
        #--------------------------------------------------------------------
        pen = QPen(QColor(120, 120, 120))
        pen.setWidth(2)
        pen.setCapStyle(Qt.RoundCap)
        qp.setPen(pen)
        qp.drawLine(0, self.x_axis_y_coordinate,
                    self.width() - self.x_axis_offset_from_right,
                    self.x_axis_y_coordinate)

        #--------------------------------------------------------------------
        # Draw rectangle that will have the vector's shadow
        #--------------------------------------------------------------------
        pen = QPen(QColor(100, 100, 100))
        pen.setWidth(2)
        pen.setCapStyle(Qt.RoundCap)
        qp.setPen(pen)
        qp.setOpacity(0.2)
        qp.drawRect(
            self.width() - self.x_axis_offset_from_right -
            self.pen_width // 2 - 2, self.x_axis_y_coordinate -
            self.amplitude - self.pen_width // 2 - 2, self.pen_width + 2,
            self.amplitude * 2 + self.pen_width + 2)
        qp.setOpacity(1)

        #--------------------------------------------------------------------
        # Draw vector shadow, if enabled
        #--------------------------------------------------------------------
        if self.draw_shadow:
            pen = QPen(QColor(220, 20, 20))
            pen.setWidth(2)
            pen.setCapStyle(Qt.RoundCap)
            qp.setPen(pen)
            qp.setBrush(QColor(220, 20, 20))
            qp.setOpacity(1)
            qp.drawRect(
                self.width() - self.x_axis_offset_from_right -
                self.pen_width // 2,
                self.x_axis_y_coordinate - self.current_height, self.pen_width,
                self.current_height)
            qp.setOpacity(1)

        #--------------------------------------------------------------------
        # Draw rotating vector, if enabled
        #--------------------------------------------------------------------
        if self.draw_rotating_vector:
            vector_origin = Point()
            vector_origin.x = self.width(
            ) - self.x_axis_offset_from_right + 20 + self.amplitude
            vector_origin.y = self.x_axis_y_coordinate

            vector_width = self.amplitude * math.cos(
                self.current_angle_in_radians)
            vector_height = self.amplitude * math.sin(
                self.current_angle_in_radians)

            vector_tip = Point()
            vector_tip.x = vector_origin.x + vector_width
            vector_tip.y = vector_origin.y - vector_height

            #----------------------------------------------------
            # Draw vector axis and tracing circle
            pen = QPen(QColor(120, 120, 120))
            pen.setWidth(2)
            pen.setCapStyle(Qt.RoundCap)
            qp.setPen(pen)
            qp.setBrush(QColor(220, 20, 20))
            qp.setOpacity(0.1)
            qp.drawEllipse(vector_origin.x - self.amplitude,
                           vector_origin.y - self.amplitude,
                           2 * self.amplitude, 2 * self.amplitude)

            qp.setOpacity(0.3)
            # vector's x axis
            qp.drawLine(vector_origin.x - self.amplitude - 10, vector_origin.y,
                        vector_origin.x + self.amplitude + 10, vector_origin.y)
            # vector's y axis
            qp.drawLine(vector_origin.x, vector_origin.y - self.amplitude - 10,
                        vector_origin.x, vector_origin.y + self.amplitude + 10)

            qp.setOpacity(1)

            #----------------------------------------------------
            # Draw vector itself.
            pen = QPen(QColor(220, 20, 20))
            pen.setWidth(self.pen_width)
            pen.setCapStyle(Qt.RoundCap)
            qp.setPen(pen)
            qp.setBrush(QColor(220, 20, 20))
            qp.setOpacity(1)
            qp.drawLine(vector_origin.x, vector_origin.y, vector_tip.x,
                        vector_tip.y)
            qp.setOpacity(1)

            #----------------------------------------------------
            # Draw vector tip projection
            pen = QPen(QColor(20, 20, 20))
            pen.setWidth(self.pen_width)
            pen.setStyle(Qt.DotLine)
            qp.setPen(pen)
            qp.setOpacity(0.2)
            qp.drawLine(vector_tip.x, vector_tip.y,
                        self.width() - self.x_axis_offset_from_right,
                        self.x_axis_y_coordinate - vector_height)
            qp.setOpacity(1)

        #--------------------------------------------------------------------
        # Draw background
        #--------------------------------------------------------------------
        font = QFont()
        font.setPixelSize(30)
        pen = QPen(QColor(100, 100, 100))
        qp.setPen(pen)
        qp.setBrush(Qt.green)
        qp.setFont(font)
        qp.setOpacity(0.2)
        for p in self.bkTextPoints + self.timeTextPoints:
            #             qp.rotate(45)
            qp.drawText(p.x, p.y, p.text)
            #             qp.drawEllipse(p.x, p.y, 50, 30)
            #             qp.rotate(-45)

            #--------------------------------------------------
            # If time isn't paused, shift all background objects left
            if not self.time_paused:
                p.x -= self.time_x_increment
                if p.x <= -150:
                    p.x = 2000

        qp.setOpacity(1)

        #--------------------------------------------------------------------
        # Draw points
        #--------------------------------------------------------------------
        #         pen = QPen(QColor(120, 60, 60))
        pen = QPen(QColor(220, 20, 20))
        pen.setWidth(self.pen_width)
        pen.setCapStyle(Qt.RoundCap)
        qp.setPen(pen)
        #         qp.setBrush(QBrush(Qt.black))

        if not self.time_paused:
            # Copy height of each point to the point on its left (older point)
            for i in reversed(range(len(self.ordinates) - 1)):
                self.ordinates[i + 1] = self.ordinates[i]

        #print("Using current height of " + str(self.current_height))
        self.ordinates[
            0] = -self.current_height  # set height of "current" (rightmost) sample

        for i in range(len(self.ordinates) - 1):
            qp.drawLine(
                self.width() - self.x_axis_offset_from_right -
                i * self.time_x_increment,
                self.ordinates[i] + self.x_axis_y_coordinate,
                self.width() - self.x_axis_offset_from_right -
                (i + 1) * self.time_x_increment,
                self.ordinates[i + 1] + self.x_axis_y_coordinate)
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        # Login on the account
        login(self)

        # Create the title font
        self.titleFont = QFont()
        self.titleFont.setBold(True)
        self.titleFont.setPixelSize(24)

        # Create the window
        self.width = 750
        self.height = 475

        self.setGeometry(10, 10, self.width, self.height)
        self.setFixedSize(self.width, self.height)

        self.initUI()

        self.show()

    def initUI(self):
        # Title
        title = QLabel(self)
        title.setFont(self.titleFont)
        title.setText("TEXT TO THREAD")
        title.setMinimumWidth(int(self.width / 2))
        title.move(5, 22)

        # Text box
        self.text = QTextEdit(self)
        self.text.setMinimumWidth(self.width - 10)
        self.text.setMinimumHeight(self.height - 110)
        self.text.move(5, 50)

        # Publish button
        self.send = QPushButton(self)
        self.send.setText("Publish")
        self.send.setMinimumWidth(self.width - 10)
        self.send.move(5, self.height - 35)
        self.send.clicked.connect(self.convertToThread)

        # Add images checkbox
        self.images = QCheckBox(self)
        self.images.setText("Add images")
        self.images.move(10, self.height - 62)

        # Create the menu bar
        menu = self.menuBar()
        actions = menu.addMenu("&Actions")

        # Clear the text box
        new = QAction("&New", self)
        new.setShortcut("Ctrl+N")
        new.setStatusTip("Clear the window")
        new.triggered.connect(self.text.clear)
        actions.addAction(new)

        # Send the tweets
        send = QAction("&Send", self)
        send.setShortcut("Ctrl+Return")
        send.setStatusTip("Send the tweets")
        send.triggered.connect(self.convertToThread)
        actions.addAction(send)

        # Rewrite the access credentials
        credentials = QAction("&Change credentials", self)
        credentials.setShortcut("Ctrl+R")
        credentials.setStatusTip("Change the credentials, restart required")
        credentials.triggered.connect(self.changeKeys)
        actions.addAction(credentials)

        # Exit from the app
        exit = QAction("&Exit", self)
        exit.setShortcut("Ctrl+Q")
        exit.setStatusTip("Exit from the app")
        exit.triggered.connect(sys.exit)
        actions.addAction(exit)

    def changeKeys(self):
        # Ask if user wants to continue
        # If true, change credentials and close the app
        yesNo = QMessageBox.question(self, "", "Restart required, continue?",
                                     QMessageBox.Yes | QMessageBox.No)

        if yesNo == QMessageBox.Yes:
            changeKeys(self)
            sys.exit()

    def convertToThread(self):
        # Get the text from the input
        text = self.text.toPlainText()

        # Create a list and fill it with the paragraphs
        listPar = []

        initChar = 0
        i = 0

        for char in text:
            # Check if change of line, if true, add the paragraph to the list
            if char == "\n":
                listPar.append(text[initChar:i])

                initChar = i + 1

            # Check if end of the text, if true, add the paragraph to the list
            if i == len(text) - 1:
                listPar.append(text[initChar:i + 1])

            i += 1

        # Dividing the text into 280 or less characters strings
        self.listTweets = []
        listDots = []

        for par in listPar:
            # Remove from the list the paragraph without text
            if len(par) <= 280:
                self.listTweets.append(par)
            else:
                # Select the points where are "."
                listDots = []
                initChar = 0

                for i in range(0, len(par)):
                    if par[i] == ".":
                        listDots.append(i)

                # Pass in the dots list
                for i in range(0, len(listDots)):
                    # Check if the dot position is more than 280
                    # If true add it to the tweets list
                    if listDots[i] - initChar > 280:
                        self.listTweets.append(par[initChar:listDots[i - 1] +
                                                   1])

                        initChar = listDots[i - 1] + 2

                    # Check is the dot is the last one in the list
                    # If true, add it to the list
                    if i == len(listDots) - 1:
                        self.listTweets.append(par[initChar:listDots[i] + 1])

        # Check if checkbox is checked, if true, execute add images function
        # If not, convert tweets format and publish them
        if self.images.isChecked():
            self.addImages()
        else:
            self.tweets = []
            for tweet in self.listTweets:
                self.tweets.append({"tweet": tweet, "image": ""})

            self.publish()

    def addImages(self):
        self.tweets = []

        for tweet in self.listTweets:
            # Ignore empty tweets
            if tweet != "":
                # Ask if add add image
                message = 'Add an image to the tweet: "' + tweet + '"?'

                yesNo = QMessageBox.question(self,
                                             "Do you want to add an image?",
                                             message,
                                             QMessageBox.Yes | QMessageBox.No)

                # Ask the link of the image
                if yesNo == QMessageBox.Yes:
                    url, ok = QInputDialog.getText(self, "Image URL",
                                                   "Image URL: ",
                                                   QLineEdit.Normal, "")

                    self.tweets.append({"tweet": tweet, "image": url})

                else:
                    self.tweets.append({"tweet": tweet, "image": ""})

        self.publish()

    def publish(self):
        i = 0

        # Pass into the tweets
        for tweet in self.tweets:
            # Ignore empty tweets
            if tweet["tweet"] != "":
                i += 1

                # Check if the tweet has an image
                if tweet["image"] == "":
                    # Check if the tweet is a response or the first and send it
                    if i == 1:
                        status = api.update_status(tweet["tweet"])
                    else:
                        status = api.update_status(tweet["tweet"],
                                                   in_reply_to_status_id=ID)
                else:
                    # Download the image
                    file = filename(tweet["image"])

                    # Check if the tweet is a response or the first and send it
                    if i == 1:
                        status = api.update_with_media(file,
                                                       status=tweet["tweet"])
                    else:
                        status = api.update_with_media(
                            file,
                            status=tweet["tweet"],
                            in_reply_to_status_id=ID)

                    os.remove(file)

                ID = status.id
    def __init__(self):
        super(SituationInformation, self).__init__()
        self.setObjectName('SituationInformation')
        self.setStyleSheet(
            GetQssFile.readQss('../resource/qss/situationInformation.qss'))

        self.log = logging.getLogger('StarCraftII')

        # font
        font = QFont()
        font.setWeight(50)
        font.setPixelSize(15)

        # set widget of layout
        self.frame = QFrame(self)
        self.frame.setGeometry(QDesktopWidget().screenGeometry())
        self.main_layout = QHBoxLayout(self)
        self.main_layout.setSpacing(20)
        self.setLayout(self.main_layout)

        # consumption action
        self.consumption = QPushButton()
        self.consumption.setObjectName('consumption')
        self.consumptionLabel = QLabel('consumption')
        self.consumptionLabel.setFont(font)
        self.consumption_layout = QVBoxLayout()
        self.consumption_layout.addWidget(self.consumption,
                                          alignment=Qt.AlignCenter)
        self.consumption_layout.addWidget(self.consumptionLabel,
                                          alignment=Qt.AlignCenter)
        self.main_layout.addLayout(self.consumption_layout)

        # resource action
        self.resource = QPushButton()
        self.resource.setObjectName('resource')
        self.resourceLabel = QLabel('resource')
        self.resourceLabel.setFont(font)
        self.resource_layout = QVBoxLayout()
        self.resource_layout.addWidget(self.resource, alignment=Qt.AlignCenter)
        self.resource_layout.addWidget(self.resourceLabel,
                                       alignment=Qt.AlignCenter)
        self.main_layout.addLayout(self.resource_layout)

        # score action
        self.score = QPushButton()
        self.score.setObjectName('score')
        self.scoreLabel = QLabel('score')
        self.scoreLabel.setFont(font)
        self.score_layout = QVBoxLayout()
        self.score_layout.addWidget(self.score, alignment=Qt.AlignCenter)
        self.score_layout.addWidget(self.scoreLabel, alignment=Qt.AlignCenter)
        self.main_layout.addLayout(self.score_layout)

        # output action
        self.output = QPushButton()
        self.output.setObjectName('output')
        self.outputLabel = QLabel('output')
        self.outputLabel.setFont(font)
        self.output_layout = QVBoxLayout()
        self.output_layout.addWidget(self.output, alignment=Qt.AlignCenter)
        self.output_layout.addWidget(self.outputLabel,
                                     alignment=Qt.AlignCenter)
        self.main_layout.addLayout(self.output_layout)

        # a description dialog
        self.dialog = None

        # add stretch
        self.main_layout.addStretch(1)

        # initialization
        self.initUI()
Example #27
0
            cmd = 'python demo_monitor.py -l'
            p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
            (output, err) = p.communicate()
            p_status = p.wait()

            # Vong lap quet tung tep tin/ thu muc
            if (p_status == 0):
                data = json.loads(output.decode('ASCII'))['check_list']
                for d in data:
                    cmd = 'python demo_monitor.py -s ' + '"' + d[
                        2] + '"' + " " + str(d[1])
                    p = subprocess.Popen(cmd,
                                         stdout=subprocess.PIPE,
                                         shell=True)
                    (output, err) = p.communicate()
                    p_status = p.wait()

            time.sleep(3600)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    font = QFont()
    font.setPixelSize(13)
    font.setFamily(font.defaultFamily())
    app.setFont(font)
    window = LoadingApp()
    window.show()

    sys.exit(app.exec_())
Example #28
0
    def initChart(self):
        series = QLineSeries()

        data = [
            QPoint(0, 4),
            QPoint(3, 2),
            QPoint(7, 7),
            QPoint(9, 10),
            QPoint(12, 17),
            QPoint(17, 9),
            QPoint(20, 22),
            QPoint(22, 2),
            QPoint(28, 13)
        ]

        series.append(data)

        # creating chart object
        chart = QChart()
        chart.legend().hide()
        chart.addSeries(series)

        pen = QPen(QColor(0, 0, 128))
        pen.setWidth(3)
        series.setPen(pen)

        font = QFont("Open Sans")
        font.setPixelSize(40)
        font.setBold(True)
        chart.setTitleFont(font)
        chart.setTitleBrush(QBrush(Qt.yellow))
        chart.setTitle("Custom Chart Demo")

        backgroundGradient = QLinearGradient()
        backgroundGradient.setStart(QPoint(0, 0))
        backgroundGradient.setFinalStop(QPoint(0, 1))
        backgroundGradient.setColorAt(0.0, QColor(175, 201, 182))
        backgroundGradient.setColorAt(1.0, QColor(51, 105, 66))
        backgroundGradient.setCoordinateMode(QGradient.ObjectBoundingMode)
        chart.setBackgroundBrush(backgroundGradient)

        plotAreaGraident = QLinearGradient()
        plotAreaGraident.setStart(QPoint(0, 1))
        plotAreaGraident.setFinalStop(QPoint(1, 0))
        plotAreaGraident.setColorAt(0.0, QColor(222, 222, 222))
        plotAreaGraident.setColorAt(1.0, QColor(51, 105, 66))
        plotAreaGraident.setCoordinateMode(QGradient.ObjectBoundingMode)
        chart.setPlotAreaBackgroundBrush(plotAreaGraident)
        chart.setPlotAreaBackgroundVisible(True)

        # customize axis
        axisX = QCategoryAxis()
        axisY = QCategoryAxis()

        labelFont = QFont("Open Sans")
        labelFont.setPixelSize(25)

        axisX.setLabelsFont(labelFont)
        axisY.setLabelsFont(labelFont)

        axisPen = QPen(Qt.white)
        axisPen.setWidth(2)

        axisX.setLinePen(axisPen)
        axisY.setLinePen(axisPen)

        axisBrush = QBrush(Qt.white)
        axisX.setLabelsBrush(axisBrush)
        axisY.setLabelsBrush(axisBrush)

        axisX.setRange(0, 30)
        axisX.append("low", 10)
        axisX.append("medium", 20)
        axisX.append("high", 30)

        axisY.setRange(0, 30)
        axisY.append("slow", 10)
        axisY.append("average", 20)
        axisY.append("fast", 30)

        axisX.setGridLineVisible(False)
        axisY.setGridLineVisible(False)

        chart.addAxis(axisX, Qt.AlignBottom)
        chart.addAxis(axisY, Qt.AlignLeft)

        series.attachAxis(axisX)
        series.attachAxis(axisY)

        self.chartView = QChartView(chart)
        self.chartView.setRenderHint(QPainter.Antialiasing)