コード例 #1
0
 def styleHelper(self):
     # self.setFixedSize(*CFG.SIZE_TODO())
     self.setMinimumSize(*CFG.SIZE_TODO())
     self.setMaximumHeight(105)
     self.setVisible(True)
     self.verticalScrollBar().setStyleSheet(CFG.STYLE_SCROLLBAR())
     pass
コード例 #2
0
ファイル: MFPreviewWidget.py プロジェクト: iamhyc/mind-flash
 def __init__(self, parent=None, pixmap=None):
     super().__init__(parent, Qt.Dialog)
     self.parent = parent
     self.min_width = 100  #px
     self.max_width = pixmap.width() * 3
     _width = min(pixmap.width(),
                  QDesktopWidget().availableGeometry().width())
     pixmap = pixmap.scaledToWidth(_width, Qt.SmoothTransformation)
     self.pixmap = pixmap
     self.now_width = pixmap.width()
     #
     self.grid = QGridLayout()
     self.grid.setSpacing(0)
     self.grid.setContentsMargins(0, 0, 0, 0)
     self.label = QLabel('ImagePreviewer', self)
     self.label.setPixmap(pixmap)
     self.grid.addWidget(self.label, 0, 0)
     self.grid.setSizeConstraint(QLayout.SetFixedSize)
     self.setLayout(self.grid)
     self.resize(self.sizeHint())
     #
     qr = self.frameGeometry()
     cp = QDesktopWidget().availableGeometry().center()
     qr.moveCenter(cp)
     self.move(qr.topLeft())
     #
     self.keysFn = KeysReactor(self)
     self.keysFn.register(CFG.KEYS_CLOSE(), lambda: self.close())
     self.keysFn.register(CFG.KEYS_CLOSE1(self), lambda: self.close())
     self.keysFn.register(CFG.KEYS_CLOSE2(self), lambda: self.close())
     #
     self.styleHelper()
     self.setFocus()
     self.show()
     pass
コード例 #3
0
    def updateItem(self, todo_item):
        self.todo_item = todo_item
        stat, text = todo_item
        if stat == 'title':
            self.setToolTip(
                'Add: <Alt+Q>\nToggle: right click\nDelete: double click')
            self.setFlags(self.flags() & (not Qt.ItemIsSelectable))
            self.setFont(CFG.FONT_TITLE_ON('MFTodoWidget'))
            self.setText(text)
            pass
        elif stat == '+':  #https://www.compart.com/en/unicode/U+25A1
            self.setFont(CFG.FONT_ITEM('MFTodoWidget'))
            _prefix = b'\xE2\x96\xA1'.decode('utf-8')
            self.setText('{}  {}'.format(_prefix, text))
            pass
        elif stat == '-':  #https://www.compart.com/en/unicode/U+25A0
            _font = CFG.FONT_ITEM('MFTodoWidget')
            _font.setStrikeOut(True)
            self.setFont(_font)
            _prefix = b'\xE2\x96\xA0'.decode('utf-8')
            self.setText('{}  {}'.format(_prefix, text))
            pass
        else:
            pass

        size_hint = QSize(0, QFontMetrics(self.font()).height())
        self.setSizeHint(size_hint)
        pass
コード例 #4
0
ファイル: MFHistoryWidget.py プロジェクト: iamhyc/mind-flash
 def getHeightHint(self, label_ref, pos):
     _text = ''
     if label_ref.text():
         _doc = QTextDocument()
         _doc.setHtml(label_ref.text())
         _text = _doc.toPlainText()
         fm = QFontMetrics(label_ref.font())
         if label_ref.type == 'item_hint':
             fm_rect = QRect(*CFG.SIZE_ITEM_FULL())
             _height = fm.boundingRect(fm_rect, Qt.TextWordWrap,
                                       _text).size().height()
             size = QSize(_height, _height)
         else:
             fm_rect = QRect(
                 *CFG.SIZE_ITEM_FULL()) if not self.draw_image else QRect(
                     *CFG.SIZE_ITEM_SIDE())
             _height = fm.boundingRect(fm_rect, Qt.TextWordWrap,
                                       _text).size().height()
             size = QSize(0, _height)
         pass
     else:
         _height = min(
             label_ref.pixmap().height() + CFG.SIZE_IMG_ONLY_HEIGHT(self),
             CFG.SIZE_HISTORY_ITEM()[1])
         size = QSize(_height, 0)
         pass
     return size
コード例 #5
0
ファイル: MFHistoryWidget.py プロジェクト: iamhyc/mind-flash
 def getFileIcon(self):
     #
     _text = Path(self.alt).name
     _suffix = Path(self.alt).suffix.upper()
     _suffix = _suffix[1:] if _suffix else "(Unknown)"
     _pixmap = QPixmap(120, 120)
     _pixmap.fill(QColor(0, 0, 0, 0))
     _painter = QPainter(_pixmap)
     _painter.setRenderHints(QPainter.Antialiasing
                             | QPainter.TextAntialiasing)
     # draw rounded rect
     _pen = _painter.pen()
     _pen.setWidth(2)
     _painter.setPen(_pen)
     _painter.drawRoundedRect(QRect(1, 1, 118, 118), 15, 15)
     # draw suffix text
     _rect = QRect(8, 10, 108, 35)  #100*25
     _painter.setPen(QPen(QColor("#0f59a4")))
     _painter.setFont(CFG.FONT_ICON_SUFFIX('MFHistoryItem'))
     _painter.drawText(_rect, Qt.AlignHCenter | Qt.TextSingleLine, _suffix)
     _painter.setPen(_pen)
     # draw splitter
     _painter.drawLine(1, 40, 118, 40)
     # draw suffix text
     _rect = QRect(8, 45, 108, 110)  #100*65
     _painter.setFont(CFG.FONT_ICON_NAME('MFHistoryItem'))
     _fm = QFontMetrics(_painter.font())
     # _elided_text = _fm.elidedText(_text, Qt.ElideMiddle, _rect.width(), Qt.TextWrapAnywhere)
     _painter.drawText(_rect, Qt.AlignHCenter | Qt.TextWrapAnywhere, _text)
     del _painter
     return _pixmap
コード例 #6
0
 def styleHelper(self):
     self.setFont(CFG.FONT_DEFAULT(self))
     self.setPlaceholderText("Search with Regex ...")
     self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     self.setFixedSize(*CFG.SIZE_TOPBAR_MAIN())
     self.setVisible(False)
     pass
コード例 #7
0
ファイル: MFHistoryWidget.py プロジェクト: iamhyc/mind-flash
 def styleHelper(self):
     self.setStyleSheet(CFG.STYLESHEET(self))
     self.verticalScrollBar().setStyleSheet(CFG.STYLE_SCROLLBAR())
     self.setSpacing(0)
     self.setContentsMargins(0, 0, 0, 0)
     self.setFixedWidth(CFG.SIZE_HISTORY_MAIN()[0])
     self.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)
     pass
コード例 #8
0
 def styleHelper(self):
     self.grid = QGridLayout()
     self.grid.setSpacing(0)
     self.grid.setContentsMargins(0, 0, 0, 0)
     self.grid.addWidget(self.w_display, 0, 0)
     self.setLayout(self.grid)
     self.setFixedSize(*CFG.SIZE_TOPBAR_MAIN())
     self.setStyleSheet(CFG.STYLESHEET(self))
     pass
コード例 #9
0
ファイル: MFHistoryWidget.py プロジェクト: iamhyc/mind-flash
 def styleHelper(self):
     self.size_height = QSize(0,
                              0)  #two column, (image_height, text_height)
     self.layout = QGridLayout()
     self.setLayout(self.layout)
     self.layout.setSpacing(0)
     self.layout.setContentsMargins(0, 0, 0, 0)
     self.setFixedWidth(CFG.SIZE_HISTORY_ITEM()[0])
     self.setStyleSheet(CFG.STYLESHEET(self))
     pass
コード例 #10
0
 def alterBackground(self):
     if self.count() > 1:
         self.setStyleSheet(CFG.STYLE_TITLE_ON(self))
         self.item(0).setFont(CFG.FONT_TITLE_ON(self))
         self.item(0).setForeground(QColor('black'))
     else:
         self.setStyleSheet(CFG.STYLE_TITLE_OFF(self))
         self.item(0).setFont(CFG.FONT_TITLE_OFF(self))
         self.item(0).setForeground(QColor('#BDC3C7'))
     pass
コード例 #11
0
    def registerGlobalKeys(self):
        ### Escape / Ctrl+W ###
        self.keysFn.register(CFG.KEYS_CLOSE(), lambda: self.close())
        self.keysFn.register(CFG.KEYS_CLOSE(self), lambda: self.close())
        ### Ctrl+L ###
        self.keysFn.register(CFG.KEYS_TO_EDIT(self), lambda: self.setFocus())

        ### Ctrl+F ###
        def mf_search_binding():
            if self.w_history.isVisible():
                _topbar = self.w_history.w_topbar
                _topbar.switch(_topbar.input_box)
                _topbar.input_box.setFocus()
            pass

        self.keysFn.register(CFG.KEYS_SEARCH(self), mf_search_binding)
        ### Alt+V ###
        self.keysFn.register(
            CFG.KEYS_RANGE_SWITCH(),
            lambda: self.w_history.updateHistory(+1, None, True))
        ### Alt+J ###
        self.keysFn.register(CFG.KEYS_JUMP_FORWARD(),
                             lambda: self.w_history.updateHistory(0, +1))
        ### Alt+K ###
        self.keysFn.register(CFG.KEYS_JUMP_BACKWARD(),
                             lambda: self.w_history.updateHistory(0, -1))
        ### Alt+H ###
        self.keysFn.register(CFG.KEYS_TOGGLE(),
                             lambda: self.w_history.toggleHistoryWidget())
        pass
コード例 #12
0
 def styleHelper(self):
     layout = QBoxLayout(QBoxLayout.LeftToRight)
     layout.setSpacing(0)
     layout.setContentsMargins(0, 0, 0, 0)
     for item in TOOL_ICONS.items():
         _name, _attr = item
         self.items[_name] = ToolBarIcon(self, item)
         layout.addWidget(self.items[_name], 0, Qt.AlignJustify)
         pass
     self.setLayout(layout)
     #
     self.setFixedSize(*CFG.SIZE_TOPBAR_MAIN())
     self.setVisible(False)
     self.setStyleSheet(CFG.STYLESHEET(self))
     pass
コード例 #13
0
ファイル: MFHistoryWidget.py プロジェクト: iamhyc/mind-flash
 def styleHelper(self):
     # set main window layout as grid
     self.grid = QGridLayout()
     self.grid.setSpacing(0)
     self.grid.setContentsMargins(0, 0, 0, 0)
     # add widget into main layout
     self.w_topbar = TopbarManager(self)
     self.w_history_list = MFHistoryList(self, self.base_path)
     self.grid.addWidget(self.w_topbar, 0, 0)
     self.grid.addWidget(self.w_history_list, 1, 0)
     self.setLayout(self.grid)
     self.setFixedSize(*CFG.SIZE_HISTORY_MAIN())
     self.setVisible(False)
     self.setStyleSheet(CFG.STYLESHEET(self))
     pass
コード例 #14
0
    def styleHelper(self):
        if self.name == '_':
            _width = CFG.SIZE_TOPBAR_MAIN(
            )[0] - CFG.SIZE_TOPBAR_ICON()[0] * TOOL_ICON_NUM - (
                CFG.SIZE_ICON(self)[0] + 1)  #33 for one rightmost icon
            self.setFixedSize(_width, CFG.SIZE_TOPBAR_MAIN()[1])
            self.setStyleSheet('QLabel { border-width: 1px 0px 1px 0px; }')
            self.setTextFormat(Qt.RichText)
            self.setTextInteractionFlags(Qt.TextBrowserInteraction)
            self.setOpenExternalLinks(True)
            self.callback = None  #TODO: impl. MouseReactor
            return

        self.icon_name = self.name
        _icon = QIcon('./res/svg/{}.svg'.format(self.icon_name)).pixmap(
            QSize(*CFG.SIZE_ICON(self)))
        self.setPixmap(_icon)
        self.setToolTip(self.attr['hint'])
        self.callback = self.__getattribute__(self.attr['func'])
        self.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

        if self.attr['pos'] < 0:  #leftmost position
            self.setFixedSize(*CFG.SIZE_TOPBAR_ICON())
            self.setStyleSheet('QLabel { border-width: 1px 1px 1px 1px; }')
        elif self.attr['pos'] > 0:  #rightmost position
            self.setAlignment(Qt.AlignRight | Qt.AlignTop)
            self.setStyleSheet('QLabel { border-width: 1px 1px 1px 0px; }')
        else:  #middle position
            self.setFixedSize(*CFG.SIZE_TOPBAR_ICON())
            self.setStyleSheet('QLabel { border-width: 1px 1px 1px 0px; }')
        pass
コード例 #15
0
 def textChangedEvent(self):
     _lines = min(self.getLineCount(), len(INPUTBOX_RESIZE) - 1)
     _width, _height = CFG.SIZE_EDIT()
     _size = QSize(_width, int(_height / 2) * (2 + INPUTBOX_RESIZE[_lines]))
     if _size != self.size():
         self.setFixedSize(_size)
         self.parent.adjustSize()
         self.parent.resize(self.size())
     pass
コード例 #16
0
 def styleHelper(self):
     # Basic Style
     self.setStyleSheet(CFG.STYLESHEET(self))
     self.setFixedSize(*CFG.SIZE_EDIT())
     self.setTabChangesFocus(True)
     self.setWordWrapMode(QTextOption.WrapAtWordBoundaryOrAnywhere)
     self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     # Font Style
     self.setFont(self.font_style)
     # Cursor Style
     QApplication.setOverrideCursor(Qt.ArrowCursor)
     self.ensureCursorVisible()
     self.lastKeyStroke = time.time() - 1.0
     self.hideCaret()
     # Placeholder Text
     self.showHelpText()
     pass
コード例 #17
0
 def historyIconEvent(self):
     _icons = ['history', 'history-week', 'history-month', 'history-year']
     #
     _idx = self.topbar.parent.updateHistory(+1, None, True)
     self.icon_name = _icons[_idx]
     _icon = QIcon('./res/svg/{}.svg'.format(self.icon_name)).pixmap(
         QSize(*CFG.SIZE_ICON(self)))
     self.setPixmap(_icon)
     pass
コード例 #18
0
ファイル: MFHistoryWidget.py プロジェクト: iamhyc/mind-flash
 def mousePressEvent(self, ev):
     if self.type == 'img_label' and ev.buttons() & Qt.RightButton:
         _clipboard = QApplication.clipboard()
         if self.alt:
             _clipboard.setPixmap(self.alt)
         else:
             _clipboard.setPixmap(self.pixmap())
         try:
             w_history = self.parent.parent
             _text = "Image copied."
             self.worker = MFWorker(w_history.showHint,
                                    args=(_text,
                                          int(CFG.CFG_HINT_SHOW_MS())))
             self.worker.start()
         except Exception:
             pass
         pass
     elif self.type == 'img_label' and ev.buttons() & Qt.LeftButton:
         _pixmap = self.alt if self.alt else self.pixmap()
         w_preview = MFImagePreviewer(self, _pixmap)
         pass
     elif self.type == 'file_label' and ev.buttons() & Qt.RightButton:
         _clipboard = QApplication.clipboard()
         _mimeData = QMimeData()
         _mimeData.setUrls([QUrl.fromLocalFile(str(self.alt))])
         _clipboard.setMimeData(_mimeData)
         try:
             w_history = self.parent.parent
             _text = "File <u>%s</u> copied." % self.alt.name
             self.worker = MFWorker(w_history.showHint,
                                    args=(_text,
                                          int(CFG.CFG_HINT_SHOW_MS())))
             self.worker.start()
         except:
             pass
         pass
     elif self.type == 'file_label' and ev.buttons() & Qt.LeftButton:
         QDesktopServices.openUrl(QUrl.fromLocalFile(POSIX(
             self.alt.parent)))
         pass
     return super().mousePressEvent(ev)
コード例 #19
0
    def setDateHint(self, stp=None, postfix=''):
        if stp is None:
            self.hint = self.hint  #not change
        elif stp.mf_type == MF_RNG.WEEK or stp.mf_type == MF_RNG.MONTH:
            _month = stp.end.month
            if _month in range(2, 5):
                _color = CFG.COLOR_SPRING()
            elif _month in range(5, 8):
                _color = CFG.COLOR_SUMMER()
            elif _month in range(8, 11):
                _color = CFG.COLOR_AUTUMN()
            else:
                _color = CFG.COLOR_WINTER()
            self.hint = '<a style="color:%s">%s</a>' % (_color, stp.hint)
        elif stp.mf_type == MF_RNG.DAY:
            _color = COLOR_WEEKDAY[stp.end.weekday()]
            self.hint = stp.end.strftime(
                '%Y-%m-%d <a style="color:{}">(%a)</a>'.format(_color))
        else:
            self.hint = '<a style="color:black">%s</a>' % (stp.hint)

        if self.lock is None:
            self.setText(self.hint + ' ' + postfix)
        pass
コード例 #20
0
ファイル: MFHistoryWidget.py プロジェクト: iamhyc/mind-flash
 def wheelEvent(self, e):
     _offset = self.verticalOffset()
     _move_up = e.angleDelta().y() > 0
     if (_move_up and self.offset == 0) or (not _move_up
                                            and self.offset == _offset):
         self.to_bound += 1
     else:
         self.to_bound = 0
     self.offset = _offset
     #
     if self.to_bound >= int(CFG.CFG_SCROLL_TO_GO()):
         self.to_bound = 0
         _direction = -1 if _move_up else +1
         self.parent.updateHistory(0, _direction)
         pass
     return super().wheelEvent(e)
コード例 #21
0
ファイル: MFHistoryWidget.py プロジェクト: iamhyc/mind-flash
    def renderHistory(self, items):
        self.w_history_list.clear()

        for item in items:
            (_user, _stp,
             _text) = item[1]  #TODO: match user/timestamp/content/<theme>
            if (self.filter is None) or self.filter.search(_text):
                w_item = QListWidgetItem(self.w_history_list)
                w_item_widget = MFHistoryItem(self, w_item, self.base_path,
                                              item)
                size_hint = QSize(0,
                                  w_item_widget.sizeHint().height() +
                                  CFG.SIZE_ITEM_MARGIN('MFHistoryItem')
                                  )  # do not adjust width
                w_item.setSizeHint(size_hint)
                self.w_history_list.addItem(w_item)
                self.w_history_list.setItemWidget(w_item, w_item_widget)
            pass
        pass
コード例 #22
0
 def __init__(self, parent, w_history, w_todo):
     super().__init__(parent)
     self.parent = parent
     self.w_history = w_history
     self.w_todo = w_todo
     self.clipboard = QApplication.clipboard()
     #
     self.pressed = False
     self.press_pos = QPoint(0, 0)
     self.init_pos = self.parent.pos()
     self.font_style = QFont(CFG.FONT_DEFAULT(self))
     self.font_metric = QFontMetrics(self.font_style)
     self.styleHelper()
     #
     self.setAcceptDrops(True)
     self.textChanged.connect(self.textChangedEvent)
     self.keysFn = KeysReactor(self, 'MFTextEdit')
     self.keysFn.setKeyPressHook(self.showCaret)
     self.registerKeys()
     pass
コード例 #23
0
 def styleHelper(self):
     self.setWordWrap(True)
     self.setFont(CFG.FONT_DEFAULT(self))
     self.setFixedSize(*CFG.SIZE_TOPBAR_MAIN())
     # self.setAlignment(Qt.AlignHCenter | Qt.AlignCenter)
     pass
コード例 #24
0
 def sizeHint(self):
     height = sum([self.sizeHintForRow(i)
                   for i in range(self.todo_count)])  #self.count()
     return QSize(CFG.SIZE_EDIT()[0], height)
コード例 #25
0
        self.w_editor.showCaret(force=True)
        self.w_editor.setFocus()
        pass

    pass


if __name__ == '__main__':
    global mf_exec, mf_sock
    # singleton instance restriction using local socket
    try:
        mf_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        mf_sock.bind(('', 19216))
    except:
        exit()
    # ignore interrupt signal
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    # change workspace root
    chdir(Path(__file__).resolve().parent)
    CFG.read('res/config.ini')
    # init MF Entity
    mf_exec = MFEntity(MF_DIR)
    CFG.read(Path(MF_DIR, 'config.ini').as_posix())
    # init MF GUI
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    app.setStyle('Fusion')
    mf = MFGui()
    sys.exit(app.exec_())
    pass
コード例 #26
0
ファイル: MFHistoryWidget.py プロジェクト: iamhyc/mind-flash
 def styleHelper(self):
     self.setWordWrap(True)
     if self.type == 'item_hint':
         self.setFont(CFG.FONT_ITEM_HINT('MFHistoryItem'))
         self.setStyleSheet(CFG.STYLE_HINT('MFHistoryItem'))
         self.setFixedHeight(
             QFontMetrics(self.font()).height() +
             CFG.SIZE_HINT_HEIGHT_FIX('MFHistoryItem'))
         #
         _user, _date, _time = self.text().split()
         t_rng = int(_time.split(':')[0])
         if t_rng in range(0, 6):
             _time_color = CFG.COLOR_LATE_NIGHT()
         elif t_rng in range(6, 12):
             _time_color = CFG.COLOR_MORNING()
         elif t_rng in range(12, 18):
             _time_color = CFG.COLOR_AFTERNOON()
         else:
             _time_color = CFG.COLOR_NIGHT()
         #
         self.setText('''
                     <a style="color:{date_color}">{date}</a>
                     <a style="color:{time_color}">{time}</a>
                     <a style="color:{user_color}">@ {user}</a>
                     '''.format(
             user=_user,
             user_color=CFG.COLOR_HINT_USER('MFHistoryItem'),
             date=_date,
             date_color=CFG.COLOR_HINT_DATE('MFHistoryItem'),
             time_color=_time_color,
             time=_time))
         self.setToolTip(self.alt)
         pass
     elif self.type == 'item_text':
         self.setFont(CFG.FONT_ITEM_TEXT('MFHistoryItem'))
         self.setAlignment(Qt.AlignLeft | Qt.AlignTop)
         self.setTextFormat(Qt.RichText)
         self.setTextInteractionFlags(Qt.TextBrowserInteraction)
         self.setOpenExternalLinks(True)
         self.setStyleSheet(CFG.STYLE_TEXT('MFHistoryItem'))
         pass
     elif self.type == 'img_label':
         self.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
         self.setToolTip("View: Left-Click\nCopy: Right-Click")
         pass
     elif self.type == 'file_label':
         _pixmap = self.getFileIcon()
         _icon_size = CFG.SIZE_FILE_ICON('MFHistoryItem')
         self.setPixmap(
             _pixmap.scaledToWidth(_icon_size[0], Qt.SmoothTransformation))
         self.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
         pass
     else:
         raise Exception
         pass
     pass
コード例 #27
0
ファイル: MFHistoryWidget.py プロジェクト: iamhyc/mind-flash
    def updateItem(self):
        (_user, _stp, _text) = self.item
        _user = '******' if _user == MF_HOSTNAME else _user
        _time = datetime.fromtimestamp(int(_stp), tz=tzlocal()).strftime(
            '%m-%d %H:%M')  #%Y-%m-%d %H:%M:%S
        _text = eval(_text).strip()  #mod
        _text = bold_filter.sub(r'<b>\1</b>', _text)
        _text = italic_filter.sub(r'<i>\1</i>', _text)

        #NOTE: 1. get rich text with regex
        self.draw_image = False
        self.rich_text = list()
        icon_iter = icon_filter.finditer(_text)
        for _icon in icon_iter:
            _path = Path(_icon.groups()[0])
            if img_filter.match(_path.suffix):
                self.draw_image = True
                self.rich_text.append((_icon.span(), 'img', POSIX(_path)))
            else:
                self.draw_image = True
                self.rich_text.append((_icon.span(), 'file', POSIX(_path)))
            pass
        link_iter = link_filter.finditer(_text)
        for _link in link_iter:
            _tag, _alt, _path = _link.groups()
            if _tag == '!' or _alt == 'img':
                self.draw_image = True
                self.rich_text.append((_link.span(), 'img', _path))
            elif _alt == 'file':
                self.draw_image = True
                self.rich_text.append((_link.span(), 'file', _path))
            else:
                self.rich_text.append((_link.span(), _alt, _path))
            pass
        self.rich_text.sort(key=lambda x: x[0][0])  #sort by start of span

        #NOTE: 2. get plain text with segment tree
        self.plain_text = list()
        draw_text = str()
        last_span = (0, 0)
        for _item in self.rich_text:
            this_span = _item[0]
            self.plain_text.append(_text[last_span[1]:this_span[0]])
            last_span = this_span
            draw_text += self.plain_text[-1]
            if _item[1] not in ['img', 'file']:
                _alt = _item[2] if (_item[1] in ['', 'url']) else _item[1]
                draw_text += '<a href={path}>{alt}</a>'.format(alt=_alt,
                                                               path=_item[2])
            pass
        self.plain_text.append(_text[last_span[1]:])
        draw_text += self.plain_text[-1]
        #
        draw_text = draw_text.strip()
        draw_text += '\n' if draw_text else ''  # for QFontMetrics.boundingRect correction
        draw_text = draw_text.replace('\n', '<br>')

        #NOTE: 3. create hint_label and text_label
        hint_alt = datetime.fromtimestamp(
            int(_stp), tz=tzlocal()).strftime('%Y-%m-%d %H:%M:%S')
        hint_label = QLabelWrapper('item_hint',
                                   '%s %s' % (_user, _time),
                                   alt=hint_alt)
        text_label = QLabelWrapper('item_text', draw_text)

        #NOTE: 4. adjust gridlayout
        self.wrapWidget(hint_label, [0, 0, 1, 3])
        if not self.draw_image:  #text only
            self.wrapWidget(text_label, [1, 0, 1, 3])
            pass
        else:
            if not draw_text:
                CropRect = lambda x: QRect(
                    0, 0,
                    min(
                        CFG.SIZE_HISTORY_ITEM()[0] - CFG.SIZE_ITEM_MARGIN(self)
                        * 2, x.width()),
                    CFG.SIZE_HISTORY_ITEM()[1])
                IconSize = (1, 3)
                ImgWidth = CFG.SIZE_HISTORY_ITEM()[0] - CFG.SIZE_ITEM_MARGIN(
                    self) * 2 - CFG.SIZE_ITEM_WIDTH_FIX(self)
            else:
                CropRect = lambda x: QRect(
                    0, 0,
                    min(
                        CFG.SIZE_HISTORY_ITEM()[0] / 3 - CFG.SIZE_ITEM_MARGIN(
                            self) * 1, x.width()),
                    CFG.SIZE_HISTORY_ITEM()[1])
                IconSize = (1, 1)
                ImgWidth = CFG.SIZE_HISTORY_ITEM(
                )[0] / 3 - CFG.SIZE_ITEM_MARGIN(
                    self) * 1 - CFG.SIZE_ITEM_WIDTH_FIX(self)
            #
            for (i, _item) in enumerate(self.rich_text):
                if _item[1] == 'img':
                    _file = Path(self.base_path, _item[2]).as_posix()
                    _pixmap = QPixmap(POSIX(_file))
                    cropped_pixmap = _pixmap.copy(CropRect(_pixmap))
                    icon_label = QLabelWrapper('img_label',
                                               pixmap=cropped_pixmap,
                                               alt=_pixmap,
                                               parent=self)
                elif _item[1] == 'file':
                    _file = Path(self.base_path, _item[2])
                    icon_label = QLabelWrapper('file_label',
                                               alt=_file,
                                               parent=self)
                    icon_label.setToolTip(_file.name)
                else:
                    icon_label = None
                    pass
                #
                self.wrapWidget(icon_label, [*(i + 1, 0), *IconSize])
                icon_label.setFixedWidth(ImgWidth)
                pass
            #
            if draw_text: self.wrapWidget(text_label, [1, 1, -1, -1])
            pass
        pass
コード例 #28
0
 def registerKeys(self):
     self.keysFn.register(CFG.KEYS_EDIT(self), lambda: self.setFilter())
     self.keysFn.register(CFG.KEYS_CLOSE(), lambda: self.focusOut())
     pass
コード例 #29
0
ファイル: MFPreviewWidget.py プロジェクト: iamhyc/mind-flash
 def styleHelper(self):
     self.setWindowTitle('Image Previewer')
     self.setWindowFlags(Qt.Dialog | Qt.FramelessWindowHint)
     self.setStyleSheet(CFG.STYLESHEET(self))
     pass
コード例 #30
0
    def registerKeys(self):
        #NOTE: Ctrl+Return; insert newline
        def mf_edit_binding():
            self.showCaret()
            self.insertPlainText('\n')
            pass

        self.keysFn.register(CFG.KEYS_EDIT(self), mf_edit_binding)

        #NOTE: Return; flash recording
        def mf_flush_binding():
            mf_text = self.toPlainText().encode('utf-8').decode('utf-8')
            if mf_text:
                self.saveFileCache()
                mf_exec.mf_record(repr(mf_text.strip()))
            #
            if mf_text and self.w_history.isVisible():
                self.clear()
                self.w_history.updateHistory(None, None)
            else:
                self.parent.close()
            pass

        self.keysFn.register(CFG.KEYS_FLUSH(self), mf_flush_binding)

        #NOTE: Ctrl+V; paste actions
        def mf_paste_binding():
            if self.canPaste():
                self.dropEvent(self.clipboard)
            else:
                pixmap = self.clipboard.mimeData().imageData()
                if pixmap:
                    fake_path = mdm.savePixmap(pixmap)
                    _text = "![img]({})".format(fake_path)
                    self.insertPlainText(_text)
                pass
            pass

        self.keysFn.register(CFG.KEYS_PASTE(self), mf_paste_binding)

        #NOTE: Alt+Q; add to todo list
        def mf_add_todo():
            todo_text = self.toPlainText().encode('utf-8').decode('utf-8')
            if todo_text:
                self.clear()
                self.w_todo.todos.append(['+', todo_text])
                self.w_todo.saveTodoList()
                self.w_todo.renderTodos()
                pass
            pass

        self.keysFn.register(CFG.KEYS_ADD_TODO(self), mf_add_todo)

        ### Alt+V ###
        self.keysFn.register(
            CFG.KEYS_RANGE_SWITCH(),
            lambda: self.w_history.updateHistory(+1, None, True))
        ### Alt+J ###
        self.keysFn.register(CFG.KEYS_JUMP_FORWARD(),
                             lambda: self.w_history.updateHistory(0, +1))
        ### Alt+K ###
        self.keysFn.register(CFG.KEYS_JUMP_BACKWARD(),
                             lambda: self.w_history.updateHistory(0, -1))
        ### Alt+H ###
        self.keysFn.register(CFG.KEYS_TOGGLE(),
                             lambda: self.toggleHistoryWidget())
        ### Escape ###
        self.keysFn.register(CFG.KEYS_CLOSE(), lambda: self.parent.close())
        pass