Пример #1
0
    def __init__(self):
        def initHandle(handle):
            self.handles.append(handle)
            QObject.connect(handle, SIGNAL("moved(QGraphicsObject*)"), self.handleMoved)

        Shape.__init__(self, BubbleItem(self))
        # Item
        self.item.setFlag(QGraphicsItem.ItemIsSelectable)
        self.item.setBrush(COLOR)

        # Text item
        self.textItem = QGraphicsTextItem(self.item)
        self.textItem.setTextInteractionFlags(Qt.TextEditorInteraction)
        QObject.connect(self.textItem.document(), SIGNAL("contentsChanged()"), \
            self.adjustSizeFromText)

        # Handles
        self.anchorHandle = Handle(self.item, 0, 0)
        # Position the bubble to the right of the anchor so that it can grow
        # vertically without overflowing the anchor
        self.bubbleHandle = Handle(self.item, ANCHOR_THICKNESS, -ANCHOR_THICKNESS)
        initHandle(self.anchorHandle)
        initHandle(self.bubbleHandle)
        self.setHandlesVisible(False)

        self.adjustSizeFromText()
Пример #2
0
 def testSpecific(self):
     testDiameter: float = 2.75
     testMaterial: str = 'Silver'
     handle = Handle(material=testMaterial, diameter=testDiameter)
     handle.finish = testMaterial
     self.assertEqual(handle.diameter, testDiameter)
     self.assertEqual(handle.material, testMaterial)
     self.assertEqual(handle.finish, 'Polished')
Пример #3
0
class HubClient(Protocol, ProtocolTaskMixin):
    def __init__(self):
        self._buffer = bytes()
        self._hub = empty
        self._handle = Handle()

    def connectionMade(self):
        print(f"连接到服务器: {self.transport.getPeer()}")
        self._buffer = bytes()
        self.send_verify()

    def dataReceived(self, data):
        print(f"接收数据: {data}")

    def send(self, command_id, content):
        length = 12 + len(content)
        header = [length, __version__, command_id]
        header_pack = struct.pack("!3I", *header)
        self.transport.write(header_pack + content.encode("UTF-8"))

    def send_heartbeat(self):
        header = [12, __version__, 5]
        content = struct.pack("!3I", *header)
        self.transport.write(content)

    def report_status(self):
        if self._hub is not empty:
            body = self._handle.report_status(self._hub)
            content = self._serializer_data(body)
            print(f"上报电能数据: {content}")
            self.send(2, content)

    def report_weather_data(self):
        if self._hub is not empty:
            body = self._handle.report_weather_data()
            content = self._serializer_data(body)
            print(f"上报气象站数据: {content}")
            self.send(2, content)

    def send_verify(self):
        is_empty = self.factory.queue.empty()
        if not is_empty:
            self._hub = self.factory.queue.get()
            body = self._handle.register(self._hub)
            content = self._serializer_data(body)
            print(f"注册: {content}")
            self.send(1, content)

    def _serializer_data(self, body):
        content = {"sender": self._hub.hid, "receiver": "NS", "body": body}
        return json.dumps(content)
Пример #4
0
    def __create_ui(self):
        # create move handle
        self.__handle = gtk.ToolItem()
        handle = Handle()
        self.__handle.add(handle)
        self.insert(self.__handle, -1)
        handle.connect("move-end", self.__handle_move_end_cb)

        # create input methods menu
        prop = ibus.Property(key = "", type = ibus.PROP_TYPE_TOGGLE, icon = "ibus", tooltip = _("Switch input method"))
        self.__im_menu = ToggleToolButton(prop)
        self.__im_menu.set_homogeneous(False)
        self.__im_menu.connect("toggled", self.__im_menu_toggled_cb)
        self.insert(self.__im_menu, -1)
Пример #5
0
class BubbleShape(Shape):
    def __init__(self):
        def initHandle(handle):
            self.handles.append(handle)
            QObject.connect(handle, SIGNAL("moved(QGraphicsObject*)"), self.handleMoved)

        Shape.__init__(self, BubbleItem(self))
        # Item
        self.item.setFlag(QGraphicsItem.ItemIsSelectable)
        self.item.setBrush(COLOR)

        # Text item
        self.textItem = QGraphicsTextItem(self.item)
        self.textItem.setTextInteractionFlags(Qt.TextEditorInteraction)
        QObject.connect(self.textItem.document(), SIGNAL("contentsChanged()"), \
            self.adjustSizeFromText)

        # Handles
        self.anchorHandle = Handle(self.item, 0, 0)
        # Position the bubble to the right of the anchor so that it can grow
        # vertically without overflowing the anchor
        self.bubbleHandle = Handle(self.item, ANCHOR_THICKNESS, -ANCHOR_THICKNESS)
        initHandle(self.anchorHandle)
        initHandle(self.bubbleHandle)
        self.setHandlesVisible(False)

        self.adjustSizeFromText()

    def adjustSizeFromText(self):
        # Compute text rect
        self.textItem.adjustSize()
        if self.textItem.textWidth() < MIN_TEXT_WIDTH:
            self.textItem.setTextWidth(MIN_TEXT_WIDTH)
        textSize = self.textItem.document().size()
        rect = QRectF(self.bubbleHandle.pos(), textSize)
        rect.adjust(0, 0, 2*MARGIN, 2*MARGIN)

        # Position textItem in text rect
        self.textItem.setPos(rect.left() + MARGIN, rect.top() + MARGIN)

        # Compute path
        path = QPainterPath()
        path.addRoundedRect(rect, BUBBLE_RADIUS, BUBBLE_RADIUS)
        path = path.united(createAnchorPath(rect.center(), self.anchorHandle.pos()))
        path.translate(0.5, 0.5)
        self.item.setPath(path)

    def handleMoved(self, handle):
        self.adjustSizeFromText()
 def _getpidclass(type, baseval):
     baseval = baseval.strip().replace('\n', '')
     if type.strip().lower() == "doi":
         return Doi(baseval)
     if type.strip().lower() == "urn" or type.strip().lower(
     ) == "urn:nbn" or type.strip().lower() == "urn:nbn:nl" or type.strip(
     ).lower() == "urnnbn" or type.strip().lower() == "nbn":
         return Nbn(baseval)
     if type.strip().lower() == "arxiv":
         return ArXiv(baseval)
     if type.strip().lower() == "href" or type.strip().lower(
     ) == "http" or type.strip().lower() == "url" or type.strip().lower(
     ) == "purl":  # :mods:relatedItem/@xlink:href wordt met type 'url' opgezet...
         if ("doi.org/" in baseval.lower()):
             return Doi(baseval)
         return Purl(baseval)
     if type.strip().lower() == "issn":
         return Issn(baseval)
     if type.strip().lower() == "isbn":
         return Isbn(baseval)
     if type.strip().lower() == "pmid" or type.strip().lower() == "pubmed":
         return Pmid(baseval)
     if type.strip().lower() == "pure" or "pure" in type.lower():
         return Pure(baseval)
     if type.strip().lower() == "wos":
         return Wos(baseval)
     if type.strip().lower() == "scopus":
         return Scopus(baseval)
     if type.strip().lower() == "uri":
         if ("issn" in baseval.lower()):
             return Issn(baseval)
         if ("isbn" in baseval.lower()):
             return Isbn(baseval)
         if ("doi" in baseval.lower()):
             return Doi(baseval)
         if (
                 "/handle/" in baseval.lower() or "hdl/" in baseval.lower()
                 or "handle.net" in baseval.lower()
         ):  #handle may resolve locally, prefixed with local url-resolver, so return url type if given so.
             return Handle(baseval)
         if ("urn:nbn:nl" in baseval.lower()):
             return Nbn(baseval)
         if ("http" in baseval.lower() or "ftp" in baseval.lower()):
             return Purl(baseval)
     if type.strip().lower() == "handle" or type.strip().lower(
     ) == "handle.net" or type.strip().lower() == "hdl":
         return Handle(baseval)
     return Unknown(type.strip().replace('\n', ''), baseval)
Пример #7
0
def init_handles(u, proplist=proplist, handleNumbers=handleNumbers):
    im.reload(handle)
    hs = []
    for i in range(len(handleNumbers)):
        h = Handle.with_properties(u, *[prop[i] for prop in proplist])
        hs.append(h)
    return hs
Пример #8
0
    def __init__(self):
        super(CandidatePanel, self).__init__()
        self.set_name("IBusCandidate")

        self.__focusedAreaIndicator = ORIG_WORDS_AREA 
        self.__toplevel = gtk.Window(gtk.WINDOW_POPUP)
        self.__viewport = gtk.Viewport()
        self.__viewport.set_shadow_type(gtk.SHADOW_IN)
        self.__toplevel.add(self.__viewport)

        hbox = gtk.HBox()
        handle = Handle()
        handle.connect("move-end", self.__handle_move_end_cb)
        hbox.pack_start(handle)
        hbox.pack_start(self)

        self.__viewport.add(hbox)
        self.__toplevel.add_events(
            gdk.BUTTON_PRESS_MASK | \
            gdk.BUTTON_RELEASE_MASK | \
            gdk.BUTTON1_MOTION_MASK)
        self.__begin_move = False
        self.__toplevel.connect("size-allocate", lambda w, a: self.__check_position())

        self.__orientation = ibus.ORIENTATION_VERTICAL
        self.__current_orientation = self.__orientation
        self.__preedit_visible = False
        self.__aux_string_visible = False
        self.__lookup_table_visible = False
        self.__preedit_string = ""
        self.__preedit_attrs = pango.AttrList()
        self.__aux_string = ""
        self.__aux_attrs = pango.AttrList()
        self.__lookup_table = None
       
        # David
        self.__lookup_table_rec_words = None
        self.__lookup_table_rec_sentences = None

        self.__cursor_location = (0, 0, 0, 0)
        self.__moved_cursor_location = None

        self.__recreate_ui()
Пример #9
0
    def call_soon(self, cb, *args):
        """
        Add the callback to the loops ready queue
        for it to be executed.
        """
        if inspect.isgeneratorfunction(cb):
            raise NotRegularFunction()

        hndl = Handle(cb, self, args)
        self._ready.append(hndl)
        return hndl
Пример #10
0
    def __create_ui(self):
        # create move handle
        self.__handle = gtk.ToolItem()
        handle = Handle()
        self.__handle.add(handle)
        self.insert(self.__handle, -1)
        handle.connect("move-end", self.__handle_move_end_cb)

        # create input methods menu
        # prop = ibus.Property(key = "", type = ibus.PROP_TYPE_TOGGLE, icon = "ibus", tooltip = _("Switch input method"))
        self.__im_menu = gtk.ToggleToolButton()
        self.__im_menu.set_homogeneous(False)
        self.__im_menu.connect("toggled", self.__im_menu_toggled_cb)
        self.insert(self.__im_menu, -1)

        self.__about_button = gtk.ToolButton(gtk.STOCK_ABOUT)
        self.__about_button.set_no_show_all(True)
        self.__about_button.set_tooltip_text(_("About the input method"))
        self.__about_button.connect("clicked", self.__about_button_clicked_cb)
        self.insert(self.__about_button, -1)
Пример #11
0
    def __create_ui(self):
        # create move handle
        self.__handle = gtk.ToolItem()
        handle = Handle()
        self.__handle.add(handle)
        self.insert(self.__handle, -1)
        handle.connect("move-end", self.__handle_move_end_cb)

        # create input methods menu
        # prop = ibus.Property(key = "", type = ibus.PROP_TYPE_TOGGLE, icon = "ibus", tooltip = _("Switch input method"))
        self.__im_menu = gtk.ToggleToolButton()
        self.__im_menu.set_homogeneous(False)
        self.__im_menu.connect("toggled", self.__im_menu_toggled_cb)
        self.insert(self.__im_menu, -1)

        self.__about_button = gtk.ToolButton(gtk.STOCK_ABOUT)
        self.__about_button.set_no_show_all(True)
        self.__about_button.set_tooltip_text(_("About the input method"))
        self.__about_button.connect("clicked", self.__about_button_clicked_cb)
        self.insert(self.__about_button, -1)
Пример #12
0
 def __init__(self,
              woodType: str = DEFAULT_WOOD,
              height: float = DEFAULT_HEIGHT,
              width: float = DEFAULT_WIDTH,
              lockdiameter: float = Lock.DEFAULT_DIAMETER,
              state: bool = Lock.DEFAULT_STATE,
              handlediameter: float = Handle.DEFAULT_DIAMETER):
     self._woodType: str = woodType
     self._height: float = height
     self._width: float = width
     self._lock: Lock = Lock(lockdiameter)
     self._handle: Handle = Handle(handlediameter)
Пример #13
0
    def __init__(self,
                 interactor,
                 point_1,
                 point_2,
                 color=(0, 0, 0),
                 set_points=None,
                 normalize=False):
        self.interactor = interactor

        self.normalize = normalize

        self.x1, self.y1 = point_1
        self.x2, self.y2 = point_2

        self.color = color

        handle_kwargs = {
            "color": self.color,
            "dragged": self.dragged,
            "clicked": self.clicked,
            "released": self.released
        }

        self.set_points = set_points

        self.top_left = Handle(interactor, (self.x1, self.y1), **handle_kwargs)
        self.top_right = Handle(interactor, (self.x2, self.y1),
                                **handle_kwargs)
        self.bottom_left = Handle(interactor, (self.x1, self.y2),
                                  **handle_kwargs)
        self.bottom_right = Handle(interactor, (self.x2, self.y2),
                                   **handle_kwargs)
        self.center = Handle(interactor, self.get_center(), **handle_kwargs)

        self.handles = [
            self.top_left, self.top_right, self.bottom_left, self.bottom_right,
            self.center
        ]

        self.place()
Пример #14
0
def main():
  # grind to look for errors
  GRINDS = 10000
  MAX_POWER = 20
  for i in xrange(GRINDS):
    power_d = random.randint(0,MAX_POWER-2)
    belt_a = [random.randint(1,1000) for j in xrange(power_d)]
    belt_b = [random.randint(1,1000) for j in xrange(MAX_POWER-2-power_d)]
    h = Handle(belt_a[:], belt_b[:], MAX_POWER)
    max_sum = sum(sorted(belt_a + belt_b, reverse=True)[:2])
    poor_sum_msgs = []
    poor_sum_r = []
    try:
      h.run()
      if (h.sum() < max_sum):
        poor_sum_msgs.append(\
          "%d < %d: %s, %s" % (h.sum(), max_sum, belt_a, belt_b))
        poor_sum_r.append("Report %d" % len(poor_sum_msgs))
        poor_sum_r.append("=====")
        poor_sum_r.extend(h.msgs)
    except:
      print '\n'.join(h.report())
      raise

  print "POOR SUMS @MAX_POWER: (%d of %d)" % (len(poor_sum_msgs), GRINDS)
  for line in poor_sum_msgs[:100]:
    print line
    
#  for line in poor_sum_r[:200]:
#    print line
      
  unittest.main()
Пример #15
0
    def __init__(self):
        super(CandidatePanel, self).__init__()
        self.set_name("IBusCandidate")

        self.__toplevel = gtk.Window(gtk.WINDOW_POPUP)
        self.__viewport = gtk.Viewport()
        self.__viewport.set_shadow_type(gtk.SHADOW_IN)
        self.__toplevel.add(self.__viewport)

        hbox = gtk.HBox()
        handle = Handle()
        handle.connect("move-end", self.__handle_move_end_cb)
        hbox.pack_start(handle)
        hbox.pack_start(self)

        self.__viewport.add(hbox)
        self.__toplevel.add_events(
            gdk.BUTTON_PRESS_MASK | \
            gdk.BUTTON_RELEASE_MASK | \
            gdk.BUTTON1_MOTION_MASK)
        self.__begin_move = False
        self.__toplevel.connect("size-allocate",
                                lambda w, a: self.__check_position())

        self.__orientation = ibus.ORIENTATION_VERTICAL
        self.__current_orientation = self.__orientation
        self.__preedit_visible = False
        self.__aux_string_visible = False
        self.__lookup_table_visible = False
        self.__preedit_string = ""
        self.__preedit_attrs = pango.AttrList()
        self.__aux_string = ""
        self.__aux_attrs = pango.AttrList()
        self.__lookup_table = None

        self.__cursor_location = (0, 0, 0, 0)
        self.__moved_cursor_location = None

        self.__recreate_ui()
Пример #16
0
 def _run(self):
     while True:
         self._update()
         for i in self.message_queue:
             print(i)
             if i.get('message'):
                 i = i['message']
                 arg = i.get('text', '').split(' ')[0]
                 if not arg: continue
                 key = self.commands['keys'].get(arg, None)
                 if key:
                     self.worker.push(
                         self.commands['functions'][key]['callback'],
                         Handle(i['chat']['id'], None), i)
             elif i.get('callback_query'):
                 i = i['callback_query']
                 key = self.callbacks['keys'].get(i['data'], None)
                 if key:
                     self.worker.push(
                         self.callbacks['functions'][key]['callback'],
                         Handle(i['message']['chat']['id'], None), i)
             self.message_queue.pop(0)
Пример #17
0
    def add_to_toolbar(self, toolbar):
        if self.handle is not None:
            self.handle.hide()

        point = self()
        self.handle = Handle(toolbar.interactor,
                             point,
                             color=(0, 0, 0),
                             normalize=self.normalize)
        toolbar.add_toggle_button(self.name,
                                  on=self.on,
                                  off=self.off,
                                  on_prefix="Move",
                                  off_prefix="Save")
Пример #18
0
    def __init__(self):
        print "I am a constructor of the class Game"
        self.running = True
        self.w = World(self)

        # Add a signal handler:
        # When you press Control + C, python will call self.signal_handler
        signal.signal(signal.SIGINT, self.signal_handler)

        h = Handle(self.w)
        self.w.run()

        print "World exited."
        sys.exit(0)
Пример #19
0
 def __init__(self):
     super(MainWindow, self).__init__()
     ti = TrayIcon(self)
     ti.show()
     self.handler = Handle(self)
     self.m_flag = None
     self.m_Position = None
     self.setupUi(self)
     self.init_ui()
     self.click_handler()
     self.shadow = QGraphicsDropShadowEffect()
     self.shadow.setBlurRadius(15)
     self.shadow.setColor(QColor(0, 0, 0, 255))
     self.shadow.setOffset(0, 0)
     self.shadow1 = QGraphicsDropShadowEffect()
     self.shadow1.setBlurRadius(15)
     self.shadow1.setOffset(0, 0)
     self.shadow1.setColor(QColor(0, 0, 0, 255))
     self.shadow2 = QGraphicsDropShadowEffect()
     self.shadow2.setBlurRadius(15)
     self.shadow2.setOffset(0, 0)
     self.shadow2.setColor(QColor(0, 0, 0, 255))
     self.widget_2.setGraphicsEffect(self.shadow)
     self.widget.setGraphicsEffect(self.shadow1)  # 加阴影,更立体
Пример #20
0
 def testDefaults(self):
     handle = Handle()
     self.assertEqual(handle._material, Handle.DEFAULT_MATERIAL)
     self.assertEqual(handle._diameter, Handle.DEFAULT_DIAMETER)
     self.assertEqual(handle._finish, Handle.DEFAULT_FINISH)
Пример #21
0
 def __init__(self):
     self._buffer = bytes()
     self._hub = empty
     self._handle = Handle()
Пример #22
0
# ---coding:utf-8----
from flask import Flask, render_template, request
from handle import Handle
app = Flask(__name__)

handles = Handle()


@app.route('/', methods=['POST', 'GET'])
def index():
    dic_list = handles.dic_ls()
    if request.method == 'GET':
        dic_con = handles.dic_content(dic_list[0])
        return render_template("index.html", dic_list=dic_list, dic_con=dic_con, dic_sele=dic_list[0])
    if request.method == 'POST':
        dic_name = request.form['dic_name']
        dic_con = handles.dic_content(dic_name)
        return render_template("index.html", dic_list=dic_list, dic_con=dic_con, dic_sele=dic_name)


@app.route('/upload', methods=['POST', 'GET'])
def upload():
    if request.method == 'POST':
        file = request.files['file']
        name = request.form['dic_name']
        handles.dic_add(file, name)
        dic_list = handles.dic_ls()
        return render_template('index.html', upload="upload success!!", dic_list=dic_list, dic_sele=dic_list[0])


@app.route('/delete', methods=['POST', 'GET'])
Пример #23
0
class MainWindow(QMainWindow, Ui_MainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()
        ti = TrayIcon(self)
        ti.show()
        self.handler = Handle(self)
        self.m_flag = None
        self.m_Position = None
        self.setupUi(self)
        self.init_ui()
        self.click_handler()
        self.shadow = QGraphicsDropShadowEffect()
        self.shadow.setBlurRadius(15)
        self.shadow.setColor(QColor(0, 0, 0, 255))
        self.shadow.setOffset(0, 0)
        self.shadow1 = QGraphicsDropShadowEffect()
        self.shadow1.setBlurRadius(15)
        self.shadow1.setOffset(0, 0)
        self.shadow1.setColor(QColor(0, 0, 0, 255))
        self.shadow2 = QGraphicsDropShadowEffect()
        self.shadow2.setBlurRadius(15)
        self.shadow2.setOffset(0, 0)
        self.shadow2.setColor(QColor(0, 0, 0, 255))
        self.widget_2.setGraphicsEffect(self.shadow)
        self.widget.setGraphicsEffect(self.shadow1)  # 加阴影,更立体

    def init_ui(self):
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)  # 去边框
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)  # 设置窗口背景透明
        self.centralwidget.setAttribute(QtCore.Qt.WA_TranslucentBackground)  # 设置pyqt自动生成的centralwidget背景透明
        self.centralwidget.setAutoFillBackground(True)
        self.pushButton.setFixedSize(QSize(BUTTON_WIDTH, BUTTON_HEIGHT))  # 设置按钮大小
        self.pushButton_2.setFixedSize(QSize(BUTTON_WIDTH, BUTTON_HEIGHT))  # 设置按钮大小
        btn_close_normal = resource_path(join("img", "btn_close_normal.png"))
        btn_close_down2 = resource_path(join("img", "btn_close_down2.png"))
        btn_close_down = resource_path(join("img", "btn_close_down.png"))
        btn_set_normal = resource_path(join("img", "btn_set_normal.png"))
        btn_min_normal = resource_path(join("img", "btn_min_normal.png"))
        Qss = 'QWidget#widget_2{background-color: %s;}' % BACKGROUND_COLOR
        Qss += 'QWidget#widget{background-color: %s;border-top-right-radius:5 ;border-top-left-radius:5 ;}' % TITLE_COLOR
        Qss += 'QWidget#widget_3{background-color: %s;}' % TITLE_COLOR
        Qss += 'QPushButton#pushButton{margin-top:6;background-color: %s;border-image:url(%s);border-top-right-radius:5 ;}' % (
            TITLE_COLOR, btn_close_normal)
        Qss += 'QPushButton#pushButton:hover{border-image:url(%s); border-top-right-radius:5 ;}' % btn_close_down2
        Qss += 'QPushButton#pushButton:pressed{border-image:url(%s);border-top-right-radius:5 ;}' % btn_close_down
        Qss += 'QPushButton#pushButton_2{margin-top:8;background-color: %s;border-image:url(%s);}' % (
            TITLE_COLOR, btn_min_normal)
        Qss += 'QPushButton#pushButton_2:hover{background-color: %s;border-image:url(%s);}' % (BACKGROUND_COLOR,
                                                                                               btn_min_normal)
        Qss += 'QPushButton#pushButton_2:pressed{background-color: %s;border-top-left-radius:5 ;}' % BACKGROUND_COLOR
        Qss += 'QPushButton#pushButton_3{border-image:url(%s);background-color: %s;border-top-left-radius:5}' % (
            btn_set_normal, TITLE_COLOR)
        Qss += '#label{background-color:rbga(0,0,0,0);color:#111111;}'
        self.setStyleSheet(Qss)  # 边框部分qss重载
        self.setWindowIcon(QIcon(resource_path("icon.ico")))
        self.setWindowTitle('神秘鸭')
        self.textBrowser.append("欢迎使用神秘鸭 smya.cn")
        self.read_login_info()
        _thread.start_new_thread(self.handler.ad, ())
        _translate = QtCore.QCoreApplication.translate
        self.label.setText(_translate("MainWindow", "神秘鸭 v{}".format(APP_VERSION)))
        self.progressBar.setHidden(True)

    def click_handler(self):
        """
        按钮点击事件
        :return:
        """
        self.pushButton.clicked.connect(self.exit_app)  # 关闭
        self.pushButton_2.clicked.connect(self.ButtonMinSlot)  # 最小化
        self.login.clicked.connect(self.handler.login)
        self.video_script.clicked.connect(self.start_script)
        self.ad1.mousePressEvent = self.handler.jump_ad
        _thread.start_new_thread(self.info_window_scroll, ())

    def exit_app(self):
        box = QMessageBox(QMessageBox.Information, "提示!", "你是要退出还是最小化?")
        yes = box.addButton(self.tr("退出"), QMessageBox.YesRole)
        no = box.addButton(self.tr("最小化"), QMessageBox.NoRole)
        box.exec_()
        if box.clickedButton() == yes:
            self.close()
        else:
            self.hide()

    def read_login_info(self):
        login_file = join(os.path.expanduser('~'), 'smya.json')
        _thread.start_new_thread(self.check_old_script, ())
        try:
            if exists(login_file) is True:
                with open(login_file, 'r') as f:
                    info = json.loads(f.readline())
                    device_id = info['device_id']
                    safe_code = info['safe_code']

                    if len(device_id) and len(safe_code) > 5:
                        self.device_id.setText(device_id)
                        self.safe_code.setText(safe_code)
                        self.handler.login()
        except:
            pass

    def check_old_script(self):
        """下个版本可以删掉"""
        new_path = os.path.join(os.path.expanduser('~'), 'smyascript')
        old_path = resource_path('scripts')
        if os.path.exists(new_path) is False and os.path.exists(old_path) is True:
            shutil.copytree(old_path, new_path)

    def send_key_event(self, data):
        self.show()

    def start_script(self):
        try:
            tools_path = os.path.join(os.path.expanduser('~'), 'smyatoolsv2')
            if os.path.exists(join(tools_path, "smyatools.exe")) is True:
                subprocess.Popen(join(tools_path, "smyatools.exe"))
            else:
                if os.path.exists(tools_path) is True:
                    os.rmdir(tools_path)
                box = QMessageBox(QMessageBox.Warning, "提示!", "神秘鸭录制工具未安装或需要更新,现在是否安装!")
                yes = box.addButton(self.tr("安装"), QMessageBox.YesRole)
                no = box.addButton(self.tr("取消"), QMessageBox.NoRole)
                box.exec_()
                if box.clickedButton() == yes:
                    self.progressBar.setHidden(False)
                    self.progressBar.setValue(0)
                    f = requests.get("https://cdn.monyuan.com/smya/smyatoolsv2.zip", stream=True)
                    length = float(f.headers['content-length'])
                    count = 0
                    time1 = time.time()
                    down_file = join(tools_path, "smyatoolsv2.zip")
                    os.mkdir(tools_path)
                    with open(down_file, "wb") as F:
                        for chunk in f.iter_content(chunk_size=1024):
                            if chunk:
                                F.write(chunk)
                                count += len(chunk)
                                if time.time() - time1 > 2:
                                    p = int(count / length * 100)
                                    self.progressBar.setValue(p)
                                    if p == 100:
                                        self.progressBar.setHidden(True)
                    F.close()
                    zipFile = zipfile.ZipFile(down_file)
                    for file in zipFile.namelist():
                        zipFile.extract(file, os.path.expanduser('~'))
                    zipFile.close()
                    os.remove(down_file)
                    QMessageBox.information(self, '提示!', '你已下载完成,可以使用啦!')
        except Exception as E:
            self.textBrowser.append(
                '<span style="color: red">{} {}</span>'.format(datetime.strftime(datetime.now(), '%H:%M:%S'),
                                                               E))
            QMessageBox.warning(self, '错误!', '出现问题,请看运行日志!')

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.m_flag = True
            self.m_Position = event.globalPos() - self.pos()  # 获取鼠标相对窗口的位置
            event.accept()
            self.setCursor(QCursor(QtCore.Qt.OpenHandCursor))

    def mouseReleaseEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.m_flag = False
            self.setCursor(QCursor(QtCore.Qt.ArrowCursor))

    def mouseMoveEvent(self, event):
        """
        拖动事件
        :param event:
        :return:
        """
        if QtCore.Qt.LeftButton and self.m_flag:
            self.move(event.globalPos() - self.m_Position)  # 更改窗口位置
            event.accept()

    def keyPressEvent(self, QKeyEvent):
        if QKeyEvent.key() == QtCore.Qt.Key_Escape:
            self.hide()

    def ButtonMinSlot(self):
        self.showMinimized()

    def info_window_scroll(self):
        sleep(3.5)
        while True:
            self.textBrowser.moveCursor(self.textBrowser.textCursor().End)
            sleep(0.5)
Пример #24
0
 def __init__(self, chatBotName, telegramTokenAPI):  # done
     self.botHandle = Handle(chatBotName, telegramTokenAPI)
     self.startBot()