Example #1
0
    def on_touch_up(self, touch):
        # Warning: usually, we are checking if grab_current is ourself first. On
        # this case, we might need to call on_touch_down. If we call it inside
        # the on_touch_up + grab state, any widget that grab the touch will be
        # never ungrabed, cause their on_touch_up will be never called.
        # base.py: the me.grab_list[:] => it's a copy, and we are already
        # iterate on it.
        if "button" in touch.profile and not touch.button.startswith("scroll"):
            self._scroll_y_mouse = self.scroll_y

        if self in [x() for x in touch.grab_list]:
            touch.ungrab(self)
            self._touch = None
            uid = self._get_uid()
            mode = touch.ud[uid]["mode"]
            if mode == "unknown":
                # we must do the click at least..
                super(ScrollView, self).on_touch_down(touch)
                Clock.schedule_once(partial(self._do_touch_up, touch), 0.1)
            elif self.auto_scroll:
                self._do_animation(touch)
        else:
            if self._touch is not touch:
                super(ScrollView, self).on_touch_up(touch)
        return self._get_uid() in touch.ud
Example #2
0
    def __init__(self, **kwargs):
        self.ratio = Metrics.dpi / 100

        self.texture_hard = Image("atlas://" + kivymd.images_path + "el_c_shadows.atlas/h_shadow", mipmap=True).texture
        self.texture_soft = Image("atlas://" + kivymd.images_path + "el_c:shadows.atlas/s_shadow", mipmap=True).texture
        super(ElevationBehaviour, self).__init__(**kwargs)
        self.b_soft = BorderImage(texture=self.texture_soft)
        self.b_hard = BorderImage(texture=self.texture_hard)

        with self.canvas.before:
            # StencilPush()
            # Ellipse(size=self.size,
            # 		pos=self.pos)
            # StencilUse()
            self._soft_col = Color(rgba=(1, 1, 1, 0.4))
            self.border_soft = Ellipse(texture=self.b_soft.texture)
            self._hard_col = Color(rgba=(1, 1, 1, 0.16))
            self.border_hard = Ellipse(texture=self.b_hard.texture)
            # StencilUnUse()
            #
            # StencilPop()

        self.bind(pos=self.update_shadow, size=self.update_shadow, elevation=self.update_shadow)

        Clock.schedule_once(self.update_shadow, 0)
    def __init__(self, **kwargs):
        # initialize variables
        self._clipboard = None
        self.info_bubble = None
        self.qrscanner = None
        self.nfcscanner = None
        self.tabs = None

        super(ElectrumWindow, self).__init__(**kwargs)

        title = _("Electrum-GMC App")
        self.electrum_config = config = kwargs.get("config", None)
        self.network = network = kwargs.get("network", None)
        self.plugins = kwargs.get("plugins", [])

        self.gui_object = kwargs.get("gui_object", None)

        # self.config = self.gui_object.config
        self.contacts = Contacts(self.electrum_config)

        self.bind(url=self.set_url)
        # were we sent a url?
        url = self.electrum_config.get("url", None)
        if url:
            self.set_url(url)

        # create triggers so as to minimize updation a max of 2 times a sec
        self._trigger_update_wallet = Clock.create_trigger(self.update_wallet, 0.5)
        self._trigger_update_status = Clock.create_trigger(self.update_status, 0.5)
        self._trigger_notify_transactions = Clock.create_trigger(self.notify_transactions, 5)
 def upload(self, btn):
     self.file_list = []
     self.file_names = []
     root_dir = App.get_running_app().user_data_dir  # +'/'
     print root_dir
     for key, value in self.check_boxes.iteritems():
         if key.active == True:
             print value
             self.file_list.append(root_dir + "/" + value)
             self.file_names.append(value)
     if len(self.file_names) != 0:
         self.popup_uploading = Popup(
             title="", content=Label(text="Uploading right now.."), size_hint=(1, 0.75), auto_dismiss=True
         )
         self.popup_uploading.open()
         t = threading.Thread(target=self.upload_files)
         t.start()
     else:
         error = Popup(
             title="Error",
             content=Label(text="Please select files to be uploaded"),
             size_hint=(0.50, 0.50),
             auto_dismiss=True,
         )
         error.open()
         Clock.schedule_interval(error.dismiss, 3)
Example #5
0
    def update_frame(self, value=None):
        """
        Update the frame on the screen
        """

        if not value is None:
            self.current_frame_index = int(value)

        if self.current_frame_index <= 0:
            if not self.reverse_clock is None:
                Clock.unschedule(self.reverse_clock)
                self.reverse_clock = None
                return

        if self.current_frame_index >= self.sequence.n_frames - 1:
            self.current_frame_index = self.sequence.n_frames - 1
            if not self.play_clock is None:
                Clock.unschedule(self.play_clock)
                self.play_clock = None
                return

        if not self.loaded:
            self.ui_screen.texture = self.sequence.get_blurred_frame(self.current_frame_index)
        else:
            self.ui_screen.texture = self.sequence.textures[self.current_frame_index]
Example #6
0
    def move_topdown(self, top):
        r = range(3, -1, -1) if top else range(4)
        grid = self.grid
        moved = False

        for ix in range(4):
            # get all the cube for the current line
            cubes = []
            for iy in r:
                cube = grid[ix][iy]
                if cube:
                    cubes.append(cube)

            # combine them
            self.combine(cubes)

            # update the grid
            for iy in r:
                cube = cubes.pop(0) if cubes else None
                if grid[ix][iy] != cube:
                    moved = True
                grid[ix][iy] = cube
                if not cube:
                    continue
                pos = self.index_to_pos(ix, iy)
                if cube.pos != pos:
                    cube.move_to(pos)

        if not self.check_end() and moved:
            Clock.schedule_once(self.spawn_number, 0.20)
 def select_experiment(self):
     file_system = FileSystemLocal()
     file_list = file_system.listdir(
         App.get_running_app().user_data_dir + "/"
     )  # this returns a list of files in dir
     file_list = [x for x in file_list if x[-4:] == ".csv"]
     if len(file_list) > 0:
         box = BoxLayout(orientation="vertical")
         s = ScrollView(size_hint_y=0.80)
         g = GridLayout(cols=1, size_hint_y=None)
         for exp_file in file_list:
             g.add_widget(ToggleButton(text=exp_file, group="experiment", size_hint_y=None, height=90))
         g.bind(minimum_height=g.setter("height"))
         s.add_widget(g)
         box.add_widget(s)
         close_button = Button(text="Ok", size_hint=(0.25, 0.15), pos_hint={"right": (0.75 + 0.5) / 2})
         box.add_widget(close_button)
         close_button.bind(on_release=self.file_button_clicked)
         self.select_exp = Popup(title="Select Experiment", content=box, size_hint=(0.75, 0.75), auto_dismiss=True)
         self.select_exp.open()
     else:
         error_popup = Popup(
             title="Error",
             content=Label(text="Please create a experiment before."),
             size_hint=(0.80, 0.40),
             auto_dismiss=True,
         )
         error_popup.open()
         Clock.schedule_interval(error_popup.dismiss, 3)
Example #8
0
    def __init__(self, **kwargs):
        kwargs.setdefault("filename", None)
        kwargs.setdefault("eos", "pause")
        kwargs.setdefault("async", True)
        kwargs.setdefault("autoplay", False)

        self.register_event_type("on_eos")
        self.register_event_type("on_load")
        self.register_event_type("on_frame")

        super(VideoBase, self).__init__()

        self._wantplay = False
        self._buffer = None
        self._filename = None
        self._texture = None
        self._volume = 1.0
        self._state = ""

        self._autoplay = kwargs.get("autoplay")
        self._async = kwargs.get("async")
        self.eos = kwargs.get("eos")
        self.filename = kwargs.get("filename")

        Clock.schedule_interval(self._update, 1 / 30.0)

        if self._autoplay:
            self.play()
Example #9
0
 def _update(dt=None, remaining=0):
     self.grid.cells = anim.next()
     remaining -= 1
     if remaining:
         Clock.schedule_once(partial(_update, remaining=remaining), timeout=(1 / speed))
     elif callback is not None:
         callback()
Example #10
0
    def update_page_on_forum(self, next_answers=0, current_number_page=0, *args):
        # После добавления/удаления ответа в форум закрываем текущую страницу
        # и удаляем ее из списка экранов, чтобы с последующим вызовом
        # функции self.show_topics_forum была выведена обновленая
        # страница форума с последним ответом.

        name_forum = args[0]
        forum_id = args[1]
        number_posts = args[2]
        flag = args[3]  # если None - обновляем последнюю страницу форума -
        # добавление нового поста, если True - текущую - удаление поста

        self.screen.screen_manager.screens.pop()
        self.screen.screen_manager.current = self.screen.screen_manager.screen_names[-1]

        progress = self.create_window(text=core.string_lang_forum_update)

        if not flag:  # если происходит добавление поста в форум
            next_answers = number_posts * 20
            current_number_page = number_posts
        if isinstance(flag, str):  # раздел файлов, например "articles"
            flag = flag

        Clock.schedule_once(
            lambda *args: self.show_topics_forum(
                progress, name_forum, forum_id, next_answers, number_posts, current_number_page, flag
            ),
            1,
        )
Example #11
0
 def game_over(self, dt):
     self.score = self.thing_list[0].square_size - SQUARESIZE
     self.clear_widgets()
     self.thing_list = []
     self.playing = False
     self.menu_clickable = False
     Clock.schedule_once(self.menu)
Example #12
0
        def dialog_answer_handler(*args):
            """Функция обработки сигналов диалогового окна.

            type answer: str;
            param answer: имя нажатой кнопки или введенного текта;

            """

            if len(args) == 1:  # нажата кнопка
                answer = args[0]

                if answer == core.string_lang_yes:
                    open("{}/README.md".format(core.prog_path), "w").write(
                        re.sub("\[.*?]", "", license).replace("\n\n\n", "\n")
                    )
                    self.open_dialog = False

                    # Устанавливаем подпись на домашней странице клиента -
                    # "Мобильный клиент сайта dimonvideo.ru"
                    self.start_screen.mobile_client_label.text = core.string_lang_mobile_client_label

                    # Автоматическое подключение при старте.
                    if (
                        self.authoconnect
                        and self.user_reg["login"] != "login"
                        and self.user_reg["password"] != "password"
                    ):
                        Clock.schedule_once(self.connect, 0)
                elif answer == core.string_lang_no:
                    sys.exit(1)
            else:  # нажата ссылка
                link = args[1]
                webbrowser.open(link)
Example #13
0
    def build(self):
        self.title = core.string_lang_title[:-1]  # заголовок окна программы
        self.icon = "Data/Images/logo.png"  # иконка окна программы
        self.use_kivy_settings = False

        self.config = ConfigParser()
        self.config.read("{}/program.ini".format(core.prog_path))
        self.beep = SoundLoader.load("Data/mess_unread.wav")
        self.set_variable_from_settings()

        # Домашняя страница клиента.
        self.start_screen = StartScreen(
            name_buttons_menu=core.name_buttons_menu,
            buttons_menu=core.buttons_menu,
            buttons_group=core.buttons_group,
            previous="Data/Images/logo.png",
            title_previous=core.string_lang_title[:-1],
            title_image="Data/Images/DV.png",
            overflow_image="Data/Images/overflow_image.png",
            previous_image="Data/Images/previous_image.png",
            events_callback=self.events_program,
        )
        self.screen = self.start_screen

        Clock.schedule_once(self.read_license, 3)
        return self.start_screen
Example #14
0
File: main.py Project: rs/scanman
 def done():
     Logger.info("Scanman: processing document")
     self.custom_status_text = "Processing document…"
     self._update_status()
     filename = datetime.now().strftime(self.settings.get("filename", "%Y%m%d-%H%M%S"))
     msg = MIMEMultipart()
     msg["Subject"] = filename
     msg["From"] = profile["email_from"]
     msg["To"] = profile["email_to"]
     att = MIMEApplication(pdf.tostring(), _subtype="pdf")
     att.add_header("content-disposition", "attachment", filename=("utf-8", "", filename + ".pdf"))
     msg.attach(att)
     Logger.info("Scanman: sending email: %s", profile)
     self.custom_status_text = "Sending email…"
     s = smtplib.SMTP(profile.get("smtp_server", self.settings.get("smtp_server", "localhost")))
     if profile.get("smtp_tls", self.settings.get("smtp_tls", False)):
         s.starttls()
     cred = profile.get("smtp_credentials", self.settings.get("smtp_credentials"))
     if cred:
         s.login(*cred)
     s.sendmail(profile["email_from"], [profile["email_to"]], msg.as_string())
     s.quit()
     self.custom_status_text = "Done."
     Clock.schedule_once(self.reset_custom_status, 5)
     self.scanning = False
Example #15
0
    def set_new_bpm(self, *args):
        self.beat_value = self.sample_time_to_BPM(self.avg_sample_time)

        self.beat_counter_screen.setScreenValue(self.beat_value)
        if self.avg_sample_time > 0.0:
            Clock.unschedule(self.on_beat)
            self.on_beat()
Example #16
0
    def run(self):
        discover = SonosDiscovery()
        speakers = []
        prev_found = []
        prev_known = set()

        def call_callback(*args):
            self.callback(speakers)

        while True:
            self.interrupted = False
            try:
                found = discover.get_speaker_ips()
            except Exception as e:
                print e
                sleep(60)
                continue
            known = set(prev_found + found)
            if known != prev_known:
                speakers = [SoCo(ip) for ip in known]
                for sonos in speakers:
                    sonos.name = sonos.get_speaker_info()["zone_name"]
                speakers.sort(key=lambda o: o.name)
                if not self.interrupted:
                    Clock.schedule_once(call_callback)
                    sleep(60)
            else:
                sleep(60)
            prev_known = known
            prev_found = found
Example #17
0
    def on_beat(self, *args):
        self.dispatch("on_beat_trigger")
        self.beat_counter_screen.flash()

        nextUpdateIn = 60 / self.beat_value

        Clock.schedule_once(self.on_beat, nextUpdateIn)
Example #18
0
 def build(self):
     self.title = "hello world"
     Clock.schedule_interval(self._update_clock, 1 / 60.0)
     self.screens = {}
     self.available_screens = sorted(
         [
             "Buttons",
             "ToggleButton",
             "Sliders",
             "ProgressBar",
             "Switches",
             "CheckBoxes",
             "TextInputs",
             "Accordions",
             "FileChoosers",
             "Carousel",
             "Bubbles",
             "CodeInput",
             "DropDown",
             "Spinner",
             "Scatter",
             "Splitter",
             "TabbedPanel + Layouts",
             "RstDocument",
             "Popups",
             "ScreenManager",
         ]
     )
     self.screen_names = self.available_screens
     curdir = dirname(__file__)
     self.available_screens = [join(curdir, "data", "screens", "{}.kv".format(fn)) for fn in self.available_screens]
     self.go_next_screen()
Example #19
0
 def on_leave(self):
     Clock.unschedule(self.update)
     self.player1.score = 0
     self.player2.score = 0
     for c in self.pongfloat.children:
         if isinstance(c, WinLabel):
             self.pongfloat.remove_widget(c)
Example #20
0
 def build(self):
     self.title = "hello world"
     Clock.schedule_interval(self._update_clock, 1 / 60.0)
     self.screens = {}
     self.available_screens = [
         "buttons",
         "togglebutton",
         "sliders",
         "progressbar",
         "switches",
         "checkboxes",
         "textinputs",
         "accordions",
         "filechoosers",
         "carousel",
         "bubbles",
         "codeinput",
         "dropdown",
         "spinner",
         "scatter",
         "splitter",
         "tabbedpanel + layouts",
         "rstdocument",
         "screenmanager",
     ]
     self.screen_names = self.available_screens
     curdir = dirname(__file__)
     self.available_screens = [join(curdir, "data", "screens", "{}.kv".format(fn)) for fn in self.available_screens]
     self.go_next_screen()
 def uploaded(self):
     self.popup_uploading.dismiss()
     self.popup_uploaded = Popup(title="", content=Label(text="Uploaded!"), size_hint=(1, 0.75), auto_dismiss=True)
     self.popup_uploaded.open()
     for check_box in self.check_boxes:
         check_box.active = False
     Clock.schedule_once(self.popup_uploaded.dismiss, 1)
Example #22
0
    def idle(self):
        """This function is called every frames. By default :
        * it "tick" the clock to the next frame
        * read all input and dispatch event
        * dispatch on_update + on_draw + on_flip on window
        """

        # update dt
        Clock.tick()

        # read and dispatch input from providers
        self.dispatch_input()

        # flush all the canvas operation
        Builder.sync()

        # tick before draw
        Clock.tick_draw()

        # flush all the canvas operation
        Builder.sync()

        window = self.window
        if window and window.canvas.needs_redraw:
            window.dispatch("on_draw")
            window.dispatch("on_flip")

        # don't loop if we don't have listeners !
        if len(self.event_listeners) == 0:
            Logger.error("Base: No event listeners have been created")
            Logger.error("Base: Application will leave")
            self.exit()
            return False

        return self.quit
 def write_data(self):
     with open(self.exp_file_path, "a") as csvfile:
         data = [
             str(self.num_of_steps),
             self.centre,
             str(self.time_to_exit),
             str(self.num_of_exit_ppl),
             str(self.date),
             str(self.time),
             self.location,
             self.valid,
             self.username,
         ]
         csvfile.write(",".join(data) + "\n")
         print self.username, "___"
     save_popup = Popup(
         title="Confirmation",
         content=Label(
             text="Data added to Experiment:\n"
             + "'"
             + self.exp_file_name[:-4]
             + "'"
             + ".\n Saved at\n"
             + self.exp_file_path
         ),
         size_hint=(1, 0.50),
         auto_dismiss=True,
     )
     save_popup.open()
     Clock.schedule_interval(save_popup.dismiss, 3)
Example #24
0
File: map.py Project: fresk/shs
    def __init__(self, **kwargs):
        self.counties = App.get_running_app().counties

        self.canvas = Canvas()
        with self.canvas:
            fbo_size = self.width, self.height
            self.fbo = Fbo(size=fbo_size, with_depthbuffer=True, do_clear=True)
            self.fbo_color = Color(1, 1, 1, 1)
            self.fbo_rect = Rectangle()
        with self.fbo:
            self.cb = Callback(self.setup_gl_context)
            self.render_ctx = RenderContext()
            self.cb2 = Callback(self.reset_gl_context)
        with self.render_ctx:
            PushMatrix()
            self.setup_scene()
            PopMatrix()

        self.texture = self.fbo.texture
        super(CountyMap, self).__init__(**kwargs)

        # must be set in right order on some gpu, or fs will fail linking
        self.vs = open(resource_find("data/shaders/map.vs")).read()
        self.fs = open(resource_find("data/shaders/map.fs")).read()
        self._p_render_ctx.shader.vs = open(resource_find("data/shaders/picking.vs")).read()
        self._p_render_ctx.shader.fs = open(resource_find("data/shaders/picking.fs")).read()

        Clock.schedule_interval(self.update_glsl, 1 / 60.0)
Example #25
0
 def __init__(self, **kwargs):
     self.slides = []
     super(Slides, self).__init__(**kwargs)
     Window.bind(on_keyboard=self.on_keyboard)
     Clock.schedule_interval(self.increase_time, 1 / 30.0)
     Clock.schedule_once(self.init, 0)
     self.add_widget(SlidesForeground(slides=self))
Example #26
0
    def anim_reset(self, allow_anim):
        """Reset an animation if available.

        .. versionadded:: 1.0.8

        :Parameters:
            `allow_anim`: bool
                Indicate whether the animation should restart playing or not.

        Usage::

            # start/reset animation
            image.anim_reset(True)

            # or stop the animation
            image.anim_reset(False)

        You can change the animation speed whilst it is playing::

            # Set to 20 FPS
            image.anim_delay = 1 / 20.

        """
        # stop animation
        Clock.unschedule(self._anim)
        if allow_anim and self._anim_available and self._anim_delay >= 0:
            Clock.schedule_interval(self._anim, self.anim_delay)
            self._anim()
Example #27
0
File: model.py Project: fresk/shs
    def __init__(self, **kwargs):
        self.canvas = RenderContext()
        super(Renderer, self).__init__(**kwargs)
        Clock.schedule_interval(self.update_glsl, 1 / 60.0)

        self.vertex_format = [("vPosition", 3, "float"), ("vTexCoords0", 2, "float")]
        self.vertices = [
            #   X     Y      Z        S    T
            0.0,
            0.0,
            -2.0,
            0.0,
            0.0,
            1.0,
            0.0,
            -8.0,
            1.0,
            0.0,
            0.0,
            1.0,
            -2.0,
            0.0,
            1.0,
        ]
        self.indices = [0, 1, 2]
        with self.canvas:
            self.mesh = Mesh(vertices=self.vertices, indices=self.indices, fmt=self.vertex_format, mode="triangles")
Example #28
0
    def update(self, dt):
        self.ball.move()

        self.player1.bounce_ball(self.ball)
        self.player2.bounce_ball(self.ball)

        if self.opponent == 1:
            self.player1.center_y = self.ball.center_y

        if (self.ball.y < self.y) or (self.ball.top > self.top):
            self.ball.velocity_y *= -1

        if self.ball.x < self.x - 10:
            self.player2.score += 1
            if self.player2.score == 10:
                Clock.unschedule(self.update)
                self._popup = Popup(title="About", content=Won1(), size_hint=(0.4, 0.5), auto_dismiss=False)
                self._popup.open()
            self.serve_ball(vel=(4, 0))

        if self.ball.x > self.width:
            self.player1.score += 1
            if self.player1.score == 10:
                Clock.unschedule(self.update)
                self._popup = Popup(title="About", content=Won2(), size_hint=(0.4, 0.5), auto_dismiss=False)
                self._popup.open()
            self.serve_ball(vel=(-4, 0))
    def send_payment(self, address, amount=0, label="", message=""):
        tabs = self.tabs
        screen_send = tabs.ids.screen_send

        if label and self.wallet.labels.get(address) != label:
            # if self.question('Give label "%s" to address %s ?'%(label,address)):
            if address not in self.wallet.addressbook and not self.wallet.is_mine(address):
                self.wallet.addressbook.append(address)
            self.wallet.set_label(address, label)

        # switch_to the send screen
        tabs.ids.panel.switch_to(tabs.ids.tab_send)

        label = self.wallet.labels.get(address)
        m_addr = label + "  <" + address + ">" if label else address

        # populate
        def set_address(*l):
            content = screen_send.ids
            content.payto_e.text = m_addr
            content.message_e.text = message
            if amount:
                content.amount_e.text = amount

        # wait for screen to load
        Clock.schedule_once(set_address, 0.5)
Example #30
0
    def on_touch_down(self, touch):
        if self._touch:
            return super(ScrollView, self).on_touch_down(touch)
        if not self.collide_point(*touch.pos):
            return
        # support scrolling !
        if self._viewport and "button" in touch.profile and touch.button.startswith("scroll"):
            # distance available to move, if no distance, do nothing
            vp = self._viewport
            if vp.height > self.height:
                # let's say we want to move over 40 pixels each scroll
                d = vp.height - self.height
                d = self.scroll_distance / float(d)
                if touch.button == "scrollup":
                    syd = self._scroll_y_mouse - d
                elif touch.button == "scrolldown":
                    syd = self._scroll_y_mouse + d
                self._scroll_y_mouse = scroll_y = min(max(syd, 0), 1)
                Animation.stop_all(self, "scroll_y")
                Animation(scroll_y=scroll_y, d=0.3, t="out_quart").start(self)
                Clock.unschedule(self._update_animation)
                return True

        self._touch = touch
        uid = self._get_uid()
        touch.grab(self)
        touch.ud[uid] = {
            "mode": "unknown",
            "sx": self.scroll_x,
            "sy": self.scroll_y,
            "dt": None,
            "time": touch.time_start,
        }
        Clock.schedule_once(self._change_touch_mode, self.scroll_timeout / 1000.0)
        return True