Exemplo n.º 1
0
class CellAutomatonApp(App):
    modes = {
        "Main Menu": "MainController",
        "Binary Rule": "BinaryRuleSetController",
        "Game of Life": "GameOfLifeController",
        "Nucleation": "NucleationController"
    }

    def __init__(self):
        super(CellAutomatonApp, self).__init__()
        Window.clearcolor = (0.2, 0.2, 0.2, 1)
        Window.size = (1150, 700)
        Window.top = 75
        Window.left = 200

    def build(self):
        self.root = BoxLayout()
        self.view = BaseView(MainController.modes, 150)
        self.set_view(self.view)
        self.controller = MainController(self)

        return self.root

    def set_view(self, view):
        self.view = view
        self.root.clear_widgets()
        self.root.add_widget(view)

    def set_controller(self, mode):
        self.controller = eval(self.modes[mode])(self)

    def get_modes(self):
        return self.modes
Exemplo n.º 2
0
class DataGrid(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.orientation = 'vertical'

        self._header = BoxLayout()
        self._header.size_hint_y = None
        self._header.height = dp(40)
        self._header.orientation = 'horizontal'
        self.add_widget(self._header)

        self._rows = DataGridRows()
        self.add_widget(self._rows)

    def set_header(self, *headers):
        self._header.clear_widgets()
        for header in headers:
            self._header.add_widget(Label(text=header))

        with self._header.canvas.before:
            Color(0.5, 0.5, 0.5, 1)
            Rectangle(pos=self._header.pos, size=self._header.size)

    def clear_data(self):
        self._rows.data = []

    def add_row(self, *rows):
        if self._rows.data is None:
            self._rows.data = []

        for row in rows:
            self._rows.data.append({"data": row})
Exemplo n.º 3
0
    def next_label(self):
        global list_tasks
        global list_completed
        global check_ref_box
        global whole_box

        lay = BoxLayout(orientation='vertical',
                        size=self.size,
                        size_hint=(1, .4),
                        pos_hint={
                            'center_x': .4,
                            'center_y': .5
                        })
        lay.clear_widgets()
        for i, task in enumerate(list_tasks):
            layout = BoxLayout(orientation="horizontal",
                               size_hint=(.5, 1),
                               pos_hint={
                                   'center_x': .5,
                                   'center_y': .5
                               })
            check_ref_box.append(layout)
            check = CheckBox()
            self.check_ref[f'checkbox_{i}'] = [check, task]
            check.bind(active=lambda checkid, checkval: on_checkbox_active(
                self.check_ref))
            layout.add_widget(check)
            layout.add_widget(Label(text=task, color=(1, 1, 1, 1)))
            lay.add_widget(layout)
        self.add_widget(lay)
        event_3 = Clock.create_trigger(self.speaker_end,
                                       timeout=1,
                                       interval=False)
        event_3()
        whole_box = lay
Exemplo n.º 4
0
class GUI:
    root = None
    _properties = None
    _window = None
    
    def __init__(self, kvFile):
        self.root = BoxLayout()
        Builder.load_file(kvFile)
        self._properties = {}
        
    def setWindow(self, window):
        self.root.clear_widgets()
        self._window = window()
        self._window.setProperty(self._properties)
        self.root.add_widget(self._window)
    
    def getWindow(self):
        return self._window.__class__
    
    def setProperty(self, key, value):
        self._properties[key] = value
        if self._window <> None: self._window.setProperty({key:value})
    
    def getProperty(self, key):
        return self._properties[key]
Exemplo n.º 5
0
class NyanCell(BoxLayout):
    def __init__(self, nyan_pos):
        super().__init__()
        # self.width, self.height = SK.CELL_WIDTH, SK.CELL_HEIGHT
        self.angle = 0
        self.cell_x, self.cell_y = nyan_pos

        self.orientation = "vertical"
        self.status_label = Label(
            text="[size=12]" + "cell x:" + str(self.cell_x) + " y:" + str(self.cell_y) + "[/size]",
            markup=True,
            size_hint_y=1,
        )

        # self.add_widget(self.status_label)

        self.space = BoxLayout(size_hint_y=8, background_normal="", background_color=(0.5, 0.9, 0.1, 1))
        self.add_widget(self.space)

    def check_updates(self, stater):
        # with self.canvas.before:
        #     Color(0, 0, 0)
        #     br = 1
        #     self.rect = Rectangle(x=self.x + br, y=self.y + br, width=self.width - 2 * br,
        #                           height=self.height - 2 * br)

        self.space.clear_widgets()
        if stater.hunter_p is not None and self.cell_x == stater.hunter_p[0] and self.cell_y == stater.hunter_p[1]:
            if stater.cat_direction in [CM.RIGHT, CM.UP, CM.LEFT, CM.DOWN]:
                angle = 90 * [CM.RIGHT, CM.UP, CM.LEFT, CM.DOWN].index(stater.cat_direction)
                self.space.add_widget(NyanArrow(nyan_angle=angle, source="helpers/images/arrow.png"))
            self.space.add_widget(Label(text=stater.cat_direction))

        if stater.cat_p is not None and self.cell_x == stater.cat_p[0] and self.cell_y == stater.cat_p[1]:
            self.space.add_widget(Image(source="helpers/images/min_cat.png"))
Exemplo n.º 6
0
class RevealedAnswersBox(BoxLayout):
    expected_answers_in_latex = DictProperty({'x_placeholder': 'placeholder'})
    reveal_button = ObjectProperty()
    answers_input_box = ObjectProperty()
    check_answers_button = ObjectProperty()

    def __init__(self, **kwargs):
        super(RevealedAnswersBox, self).__init__(**kwargs)
        self.latex_widg = LatexWidget()
        self.special_answer_label = Label()
        self.main_content_box = BoxLayout(orientation='vertical')
        self.main_content_box.add_widget(
            Label(text=languages.CORRECT_ANSWER_IS_MSG))
        self.main_label_box = BoxLayout()
        self.main_content_box.add_widget(self.main_label_box)

        self.user_reaction_options_box = UserReactionToRevealedAnswersBox()
        self.user_reaction_options_box.ids.ok_button.bind(
            on_release=self.on_ok_button_release)
        self.main_content_box.add_widget(self.user_reaction_options_box)

    def _main_label(self):
        special_found = set(arbitrary_pieces.SPECIAL_ANSWERS_TYPES) & set(
            self.expected_answers_in_latex.values())
        if special_found:
            w = self.special_answer_label
            w.text = list(special_found)[0].long_description
        else:
            w = self.latex_widg
            w.text = self.all_answers_as_latex_str()
        return w

    def create_main_label(self, *args):
        self.main_label_box.clear_widgets()
        self.main_label_box.add_widget(self._main_label())

    def show_main_content(self, *args):
        self.clear_widgets()
        self.create_main_label()
        self.add_widget(self.main_content_box)

    def all_answers_as_latex_str(self):
        non_latex_s = ''
        for a_name in sorted(self.expected_answers_in_latex):
            a_val = self.expected_answers_in_latex[a_name]
            # (simply places "z=" at the start;
            # different type of answers would need different implementation elsewhere too)
            if non_latex_s:
                non_latex_s += ', '
            non_latex_s += ANSWER_KEY_EQUALS.format(a_name) + r'{}'.format(
                a_val.strip('$'))
        return '${}$'.format(non_latex_s)

    def on_ok_button_release(self, *args):
        self.clear_widgets()
        self.add_widget(Label())
        self.reveal_button.disabled = False
        self.check_answers_button.disabled = False
        self.answers_input_box.disabled = False
        app.root.exercise = exercises.SolveForXLinear(difficulty=2)
Exemplo n.º 7
0
class AnswersInputBox(BoxLayout):
    exercise = ObjectProperty()
    answers_given = DictProperty()

    def __init__(self, **kwargs):
        super(AnswersInputBox, self).__init__(**kwargs)
        self.textinputs_box = BoxLayout(orientation='vertical', padding='3sp')
        self.textinputs_lst = []
        self.add_widget(self.textinputs_box)
        self.specials_buttons_box = BoxLayout(orientation='vertical',
                                              size_hint_x=.3)
        self.add_widget(self.specials_buttons_box)
        Clock.schedule_once(self.populate_textinputs_box, .5)
        Clock.schedule_once(self.populate_specials_buttons_box, .5)

    def set_input_text_to_answer(self, *args):
        obj = args[0]
        self.answers_given[obj.answer_name] = obj.text

    def populate_textinputs_box(self, *args):
        self.textinputs_box.clear_widgets()
        self.textinputs_lst = []
        for answer_name in self.exercise.expected_answers:
            box = BoxLayout(size_hint_y=None, height=STANDARD_BUTTON_HEIGHT)
            self.textinputs_box.add_widget(box)

            label_text = ANSWER_KEY_EQUALS.format(answer_name)
            box.add_widget(Label(text=label_text, size_hint_x=.2))

            t_input = TextInput(hint_text=languages.TYPE_ANSWER_PROMPT_MSG,
                                multiline=False)
            t_input.answer_name = answer_name
            t_input.bind(text=self.set_input_text_to_answer)
            box.add_widget(t_input)
            self.textinputs_lst.append(t_input)

    def set_special_answer_to_answers(self, *args):
        obj = args[0]
        # (text must be changed first otherwise answers will change twice `on_text`)
        for i in self.textinputs_lst:
            i.text = ''
        for a in self.answers_given:
            self.answers_given[a] = obj.special_val_

    def populate_specials_buttons_box(self, *args):
        self.specials_buttons_box.clear_widgets()
        for a_class in self.exercise.special_answers_allowed:
            b = Button(text=a_class.button_text,
                       size_hint_y=None,
                       height=STANDARD_BUTTON_HEIGHT)
            b.special_val_ = a_class
            b.bind(on_release=self.set_special_answer_to_answers)
            self.specials_buttons_box.add_widget(b)

    def populate_everything(self, *args):
        self.populate_textinputs_box()
        self.populate_specials_buttons_box()

    def on_exercise(self, *args):
        self.populate_everything()
Exemplo n.º 8
0
class MainWindow(BoxLayout):
    def __init__(self, **kwargs):
        kwargs['orientation'] = 'vertical'
        super(MainWindow, self).__init__(**kwargs)

        spinner = Spinner(
            # default value shown
            text='Home',
            # available values
            values=('Home', 'Test', 'AddWord'),
            # just for positioning in our example
            size_hint=(1, None),
            size=(100, 44),
            pos_hint={
                'center_x': .5,
                'center_y': .5
            })

        spinner.bind(text=self.set_page_vidget)

        self.add_widget(spinner)

        self.work_area = BoxLayout()
        self.work_area.add_widget(Home())
        self.add_widget(self.work_area)

    def set_page_vidget(self, _, name):
        self.work_area.clear_widgets()
        vidget = globals()[name]
        self.work_area.add_widget(vidget())
Exemplo n.º 9
0
class MainWindow(BoxLayout):

    def __init__(self, **kwargs):
        kwargs['orientation'] = 'vertical'
        super(MainWindow, self).__init__(**kwargs)

        spinner = Spinner(
            # default value shown
            text='Home',
            # available values
            values=('Home', 'Test', 'AddWord'),
            # just for positioning in our example
            size_hint=(1, None),
            size=(100, 44),
            pos_hint={'center_x': .5, 'center_y': .5})

        spinner.bind(text=self.set_page_vidget)

        self.add_widget(spinner)

        self.work_area = BoxLayout()
        self.work_area.add_widget(Home())
        self.add_widget(self.work_area)

    def set_page_vidget(self, _, name):
        self.work_area.clear_widgets()
        vidget = globals()[name]
        self.work_area.add_widget(vidget())
Exemplo n.º 10
0
class DatePicker(BoxLayout):
    def __init__(self, **kwargs):
        super(DatePicker, self).__init__(**kwargs)
        self.date = date.today()
        self.orientation = "vertical"

        self.header = BoxLayout(orientation='horizontal', size_hint=(1, 0.2))
        self.body = GridLayout(cols=7)
        self.add_widget(self.header)
        self.add_widget(self.body)

        self.populate_body()
        self.populate_header()

    def populate_header(self):
        self.header.clear_widgets()
        self.previous_month = Button(text="<")
        self.next_month = Button(text=">")
        self.current_month = Label(text=repr(self.date), size_hint=(2, 1))

        self.header.add_widget(self.previous_month)
        self.header.add_widget(self.current_month)
        self.header.add_widget(self.next_month)

    def populate_body(self):
        self.body.clear_widgets()
        date_cursor = date(self.date.year, self.date.month, 1)
        while date_cursor.month == self.date.month:
            self.date_label = Label(text=str(date_cursor.day))
            self.body.add_widget(self.date_label)
            date_cursor += timedelta(days=1)
def createPopupWidget2(sm,dictOfStatus,size):

	mainBox = BoxLayout(orientation='vertical',id="mainBox")
	mainBox.clear_widgets()
	label = Label(text='Completed',color=(1,0,0,1),size_hint=(1,.3),id="label")
	mainBox.add_widget(label)
	for eachScript in dictOfStatus:
		textContent = "Filename containing scripts: " + os.path.basename(eachScript) + '\n' + "Total number of scripts generated: " + str((dictOfStatus[eachScript])[2]) +'\n' +"Number of Scripts that ran to success: " + str((dictOfStatus[eachScript])[0]) + '\n' + "Number of Scripts that did not run:    " + str((dictOfStatus[eachScript])[1]) + '\n\n'
		labelScript = Label(text=textContent,multiline=True,color=(1,0,0,1))
		mainBox.add_widget(labelScript)

	innerButtonControlBox = BoxLayout(orientation='horizontal', size_hint=(1,.25))
	btn_ok = Button(text='Ok. Take me back to Run Control Screen',background_color=(1,0,0,1), size_hint=(.6,1))
	btn_cancel = Button(text='Cancel',background_color=(1,0,0,1),size_hint=(.2,1))
	innerButtonControlBox.add_widget(btn_ok)
	innerButtonControlBox.add_widget(btn_cancel)

	
	mainBox.add_widget(innerButtonControlBox)

	popup1 = Popup(title='Status of test suits run screen', content=mainBox, size_hint=(None,None), size=size, auto_dismiss=False)
	btn_ok.bind(on_press=popup1.dismiss)
	btn_ok.bind(on_press=Par(backApp1,sm))
	btn_cancel.bind(on_press=popup1.dismiss)
	btn_cancel.bind(on_press=Par(backApp1,sm))

	return popup1
Exemplo n.º 12
0
class SideMenu(BoxLayout):
    def __init__(self, map, **kwargs):
        super().__init__(**kwargs)
        self.width = 0
        self.scrollView = ScrollView(do_scroll_y=True)
        self.scrollView.clear_widgets()
        self.sideMenuItems = []

        self.boxView = BoxLayout(orientation="vertical", size_hint_y=None)
        self.boxView.bind(minimum_height=self.boxView.setter('height'))

        self.scrollView.add_widget(self.boxView)

        self.add_widget(self.scrollView)

    def close(self):
        self.width = 0

    def open(self):
        self.width = 200

    def up(self):
        for i in range(len(self.sideMenuItems)):
            if(self.sideMenuItems[i].selected and i > 0):
                self.selectByIndex(i-1)
                break

    def down(self):
        for i in range(len(self.sideMenuItems)):
            if(self.sideMenuItems[i].selected and i < len(self.sideMenuItems)):
                self.selectByIndex(i+1)
                break


    def resetColors(self):
        for sideMenuItem in self.sideMenuItems:
            sideMenuItem.resetColor()

    def selectByIndex(self, index):        
        if(len(self.sideMenuItems) > index):
            self.sideMenuItems[index].selectWithCallback()

    def select(self, state):
        for sideMenuItem in self.sideMenuItems:
            if( sideMenuItem.contentState == state):
                sideMenuItem.select()

    def clearItems(self):
        self.boxView.clear_widgets()
        self.sideMenuItems = []

    def addSideMenuItem(self, sideMenuItem):
        self.boxView.add_widget(sideMenuItem)
        self.sideMenuItems.append(sideMenuItem)
        sideMenuItem.setSideMenu(self)

    def clearAndAddSideMenuItems(self, sideMenuItems):
        self.clearItems()
        for sideMenu in sideMenuItems:
            self.addSideMenuItem(sideMenu)
Exemplo n.º 13
0
class PageSelection(BoxLayout):
    """The "right" widget, that is used to select which page to plot"""

    cinfdata = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(PageSelection, self).__init__(**kwargs)
        self.mainbutton = Button(text='Select Setup', size_hint=(1, 0.2))
        self.pages_widget = BoxLayout(orientation='vertical', size_hint=(1, None))
        #self.pages_widget.bind(minimum_height=self.pages_widget.setter('height'))
        self.pages_widget.add_widget(Button(text='Pages', size_hint=(1, 1)))
        self.scroll_view = ScrollView(size_hint=(1, 0.8), do_scroll_x=False)
        self.scroll_view.add_widget(self.pages_widget)
        self.add_widget(self.mainbutton)
        self.add_widget(self.scroll_view)

    def on_cinfdata(self, instance, value):
        """Setup the setup selection page, when the cinfdata ObjectProperty is set
        (happens only on startup)"""

        dropdown = DropDown()

        for setup in self.cinfdata.get_setups():
            # Do not show setups that has no dateplots
            if len([l for l in setup['links']
                    if l['pagetype'] == 'dateplot']) == 0:
                continue
            btn = SetupButton(text='Setup: ' + setup['title'], size_hint_y=None,
                              height=44, setup=setup)
            btn.bind(on_release=lambda btn: dropdown.select(btn))
            dropdown.add_widget(btn)

        self.mainbutton.bind(on_release=lambda widget: dropdown.open(widget))
        dropdown.bind(on_select=self._select)

    def _select(self, dropdown, setup_button):
        """Set the selected plot"""
        Logger.debug('PageSelection._select: %s', setup_button.text)
        self.mainbutton.text = setup_button.text

        self.pages_widget.clear_widgets()
        setup = setup_button.data
        for link in setup_button.data['links']:
            # So far only dateplots are implemented
            if link['pagetype'] != 'dateplot':
                continue
            codename = setup['codename']
            button = ToggleButton(text=link['title'], group=codename,
                                  size_hint_y=None, height=50)
            button.bind(on_release=partial(self._select_page, setup, link))
            self.pages_widget.add_widget(button)
        self.pages_widget.height = len(setup_button.data['links']) * 50
        # Eventually set self.cinfdata.selected_plot with (setup, link)

    def _select_page(self, setup, link, widget):
        """  """
        Logger.debug('PageSelection._select_page: %s - %s', setup['title'], link['title'])
        self.cinfdata.selected_plot = (setup, link)
Exemplo n.º 14
0
class PreparationScreen(Screen):
    def __init__(self, **kwargs):
        Screen.__init__(self, name="Preparation", **kwargs)
        _layout = BoxLayout(orientation='vertical')
        self._question_grid = BoxLayout(orientation='vertical',
                                        size_hint=(1, 0.2))
        _layout.add_widget(self._question_grid)
        self._answer_grid = GridLayout(cols=3, size_hint=(1, 0.4))
        _layout.add_widget(self._answer_grid)
        self.send_btn = Button(text="Send", font_size=36, size_hint=(1, 0.2))
        self.send_btn.bind(on_release=self.on_send)
        _layout.add_widget(self.send_btn)
        self.add_widget(_layout)
        self._questions = []
        self._answers = []

    def init(self, num_questions, num_answers):
        self._question_grid.clear_widgets()
        self._answer_grid.clear_widgets()
        self._questions = [
            TextInput(multiline=False, font_size=36)
            for _ in range(num_questions)
        ]
        for widget in self._questions:
            self._question_grid.add_widget(widget)
        self._answers = [
            TextInput(multiline=False, font_size=28)
            for _ in range(num_answers)
        ]
        for widget in self._answers:
            self._answer_grid.add_widget(widget)

    def on_pre_enter(self, *args):
        client.add_listener(self.game_started_handler)

    def on_pre_leave(self, *args):
        client.remove_listener(self.game_started_handler)

    def on_leave(self, *args):
        self.send_btn.disabled = False
        self.send_btn.text = 'Send'

    def on_send(self, instance: Button):
        questions = [widget.text for widget in self._questions]
        answers = [widget.text for widget in self._answers]
        if all(questions) and all(answers):
            instance.disabled = True
            instance.text = "Waiting for others..."
            client.send({"op": "AddQuestions", "questions": questions})
            client.send({"op": "AddAnswers", "answers": answers})

    def game_started_handler(self, msg):
        if msg.get('op') == 'MainStarted':
            players = [(plr['id'], plr['name']) for plr in msg['players']
                       if plr['id'] != player_id]
            next_screen = GameScreen(players)
            self.manager.add_widget(next_screen)
            self.manager.current = next_screen.name
Exemplo n.º 15
0
class PageSelection(BoxLayout):
    """The "right" widget, that is used to select which page to plot"""

    cinfdata = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(PageSelection, self).__init__(**kwargs)
        self.mainbutton = Button(text='Select Setup', size_hint=(1, 0.2))
        self.pages_widget = BoxLayout(orientation='vertical',
                                      size_hint=(1, None))
        #self.pages_widget.bind(minimum_height=self.pages_widget.setter('height'))
        self.pages_widget.add_widget(Button(text='Pages', size_hint=(1, 1)))
        self.scroll_view = ScrollView(size_hint=(1, 0.8), do_scroll_x=False)
        self.scroll_view.add_widget(self.pages_widget)
        self.add_widget(self.mainbutton)
        self.add_widget(self.scroll_view)

    def on_cinfdata(self, instance, value):
        """Setup the setup selection page, when the cinfdata ObjectProperty is set
        (happens only on startup)"""

        dropdown = DropDown()

        for setup in self.cinfdata.get_setups():
            btn = SetupButton(text='Setup: ' + setup['title'],
                              size_hint_y=None,
                              height=44,
                              setup=setup)
            btn.bind(on_release=lambda btn: dropdown.select(btn))
            dropdown.add_widget(btn)

        self.mainbutton.bind(on_release=lambda widget: dropdown.open(widget))
        dropdown.bind(on_select=self._select)

    def _select(self, dropdown, setup_button):
        """Set the selected plot"""
        Logger.debug('PageSelection._select: %s', setup_button.text)
        self.mainbutton.text = setup_button.text

        self.pages_widget.clear_widgets()
        setup = setup_button.data
        for link in setup_button.data['links']:
            codename = setup['codename']
            button = ToggleButton(text=link['title'],
                                  group=codename,
                                  size_hint_y=None,
                                  height=50)
            button.bind(on_release=partial(self._select_page, setup, link))
            self.pages_widget.add_widget(button)
        self.pages_widget.height = len(setup_button.data['links']) * 50
        # Eventually set self.cinfdata.selected_plot with (setup, link)

    def _select_page(self, setup, link, widget):
        """  """
        Logger.debug('PageSelection._select_page: %s - %s', setup['title'],
                     link['title'])
        self.cinfdata.selected_plot = (setup, link)
Exemplo n.º 16
0
class RuleBox(BoxLayout):
    def __init__(self, app=None, **kwargs):
        self.types_container = BoxLayout(orientation="vertical")
        self.app = app
        super(RuleBox, self).__init__(**kwargs)
        self.add_widget(self.types_container)

    def load_rules(self, rules_widget):
        self.types_container.clear_widgets()
        self.types_container.add_widget(rules_widget)
Exemplo n.º 17
0
class AddIten(Popup):
    """Popup to add an iten to the order."""
    def close_btn_touch(self, btn, touch):
        """Close and cancel."""
        if is_left_click(btn, touch):
            self.dismiss()

    def new_iten_btn_touch(self, btn, touch):
        """Add a new iten."""
        if is_left_click(btn, touch):
            self.dismiss()
            NewIten().open()

    def __init__(self, **kwargs):
        """Initialization method with style information."""
        super().__init__(**kwargs)
        self.title = "Adicionar Item"
        self.title_size = 25
        self.title_align = 'center'
        self.size_hint = .7, .7
        self.content = BoxLayout(orientation='vertical')
        self.grid = BoxLayout(orientation="vertical", size_hint_y=None)
        self.grid.bind(minimum_height=self.grid.setter('height'))
        scroll = ScrollView()
        scroll.add_widget(self.grid)
        self.content.add_widget(scroll)
        buttons = BoxLayout(size_hint_y=None, height=60)

        buttons.add_widget(
            BorderedButton(background_color=(1, 0, 0, 1),
                           on_touch_down=self.close_btn_touch,
                           text="Fechar",
                           font_size=25,
                           size_hint_y=None,
                           height=60))

        buttons.add_widget(
            BorderedButton(background_color=(0, 1, 0, 1),
                           text="Novo Item",
                           on_touch_down=self.new_iten_btn_touch,
                           font_size=25,
                           size_hint_y=None,
                           height=60))

        self.content.add_widget(buttons)

    def on_open(self):
        """Get all the itens options."""
        app = App.get_running_app()
        for iten in app.session.query(Iten).all():
            self.grid.add_widget(ItenToAdd(iten))

    def on_dismiss(self):
        """Clear the current itens when closed."""
        self.grid.clear_widgets()
Exemplo n.º 18
0
class Rate(ModalView):
    prev_rating = 0
    star_id = {}

    def on_open(self):
        self.rate_stars = BoxLayout(orientation="horizontal")
        self.rate_stars.size_hint = [1, 0.075]
        self.rate_stars.padding = (0, -30)
        # Replace Tile image with Gray star img, and Tile_Down with yellow star img
        for i in range(5):
            button = Button(background_normal="../Art/NOSTAR.png",
                            background_down="../Art/GOLDSTAR.png")
            self.star_id[button] = (i + 1)
            button.bind(on_release=self.stars)
            self.rate_stars.add_widget(button, len(self.rate_stars.children))
        #self.rate_stars.pos = (50, 50)
        self.add_widget(self.rate_stars)

    def stars(self, instance):
        rating = 6 - self.star_id[instance]

        if rating > self.prev_rating:
            for i in range(5):
                self.rate_stars.children[
                    i].background_normal = "../Art/NOSTAR.png"
                self.rate_stars.children[
                    i].background_down = "../Art/GOLDSTAR.png"

        if rating > 0:
            self.rate_stars.children[
                4].background_normal = "../Art/GOLDSTAR.png"
            self.rate_stars.children[4].background_down = "../Art/NOSTAR.png"
        if rating > 1:
            self.rate_stars.children[
                3].background_normal = "../Art/GOLDSTAR.png"
            self.rate_stars.children[3].background_down = "../Art/NOSTAR.png"
        if rating > 2:
            self.rate_stars.children[
                2].background_normal = "../Art/GOLDSTAR.png"
            self.rate_stars.children[2].background_down = "../Art/NOSTAR.png"
        if rating > 3:
            self.rate_stars.children[
                1].background_normal = "../Art/GOLDSTAR.png"
            self.rate_stars.children[1].background_down = "../Art/NOSTAR.png"
        if rating > 4:
            self.rate_stars.children[
                0].background_normal = "../Art/GOLDSTAR.png"
            self.rate_stars.children[0].background_down = "../Art/NOSTAR.png"

    def clean(self):
        self.rate_stars.clear_widgets()
        self.remove_widget(self.rate_stars)
        self.prev_rating = 0
        self.dismiss()
Exemplo n.º 19
0
class crestChooser(Image):
    def __init__(self, position, **kwargs):
        super(crestChooser, self).__init__(**kwargs)
        self.source = './data/images/interface-choose-crest.png'
        self.size_hint = (None, None)
        self.size = (310, 90)
        self.pos = position

        self.scroller = ScrollView(do_scroll_y=False,
                                   bar_color=[.0, .0, .0, .0])
        self.scroller.size_hint = (None, None)
        self.scroller.size = (310, 90)
        self.scroller.pos = position

        self.crest_box = BoxLayout(orientation='horizontal')
        self.crest_box.size_hint = (None, None)

        self.available_crests = [
        ]  #A stub. Will be filled when the screen is called.

        self.scroller.add_widget(self.crest_box)
        self.add_widget(self.scroller)

    def get_selected(self):
        """Returns the selected crest object. It has a 'name' property."""
        selected = 'none'
        for button in self.available_crests:
            if button.state == 'down':
                selected = button
        if selected == 'none':
            return None
        else:
            return selected

    def fill_crests(self, list_of_crest_names):
        """Places the correct crests. Loaded when the screen is called."""
        #First we erase the crests that are there already
        self.crest_box.clear_widgets()
        self.available_crests = []
        ##We read the save in search of the new available crests
        #list_of_crest_names = g.save.crests
        #Then add them to the box and to a parallel list that guard the btn objects
        for name in list_of_crest_names:
            btn = ToggleButton(group='crests')
            btn.name = name
            btn.background_normal = './data/images/crest_' + name + '_no.png'
            btn.background_down = './data/images/crest_' + name + '.png'
            self.crest_box.add_widget(btn)
            self.available_crests.append(btn)
        #Then we align everything right
        self.crest_box.size = (len(list_of_crest_names) * 90, 90)
        if len(list_of_crest_names) == 3:
            self.scroller.pos = (45, self.pos[1])
Exemplo n.º 20
0
class GameAPP(App):
    _maze = ObjectProperty(None)
    _map = ObjectProperty(None,force_dispatch = True)
    engine = ObjectProperty(None)
    _lighting = DictProperty({})
    interface = ObjectProperty(None)
    console = ObjectProperty(None)
    def output(self,text):
        self.console.add(text)        
    def parse(self,keyboard,keycode,text,modifiers):
        if text not in "wasdf":
            return
        self.engine.parse(text)
        self.interface.update()
        #print keyboard,keycode,text,modifiers
    def build(self):
        self._maze = Maze()
        self.title = "can't think of one now"
        self.icon = "graphics/icon.png"
        #self.root = ScreenManager()
        self.root = BoxLayout(orientation = "horizontal")
        self.keyboard = Window.request_keyboard(None,self.root)
        self.keyboard.bind(on_key_down = self.parse)
        self.reset()
        #Clock.schedule_interval(self.update,0.5)
        return self.root
    def update(self,dt):
        self.engine.monaction()
        self.engine.cleanup()
        if not self.engine.player._alive:
            gameoversound.play()
            Clock.unschedule(self.update)
            popup = GameOver()
            popup.bind(on_dismiss = lambda x:self.reset())
            popup.open()
        self.interface.update()
    def reset(self):
        self.root.clear_widgets()
        #screen = Screen(name = "Game")
        shapep = int(mapsize)+((initlevel-1)*5)
        if shapep % 2 == 0:
            shapep += 1
        self._map = self._maze((shapep,shapep),0.75,0.75,new = True)
        self.engine = Engine(_maze = self._map,_level = initlevel,outputfunc = self.output)
        self.interface = LayeredMap(_shape = shapep,_map = self.engine._map)
        self.root.add_widget(self.interface)
        self.console = Console()
        self.root.add_widget(self.console)
        #screen.add_widget(self.interface) 
        #self.root.add_widget(screen)
        #self.root.current = "Game"
        Clock.schedule_interval(self.update,0.5)
Exemplo n.º 21
0
class TaskApp(App):
    detailsID = 0
    BiD = 0
    taskId = 0

    def build(self):
        self.layout = BoxLayout(orientation='vertical')
        self.menuBar = MenuBar()
        self.menuBar.app = self
        self.layout.add_widget(self.menuBar)
        self.sublayout = BoxLayout(orientation='horizontal')
        self.layout.add_widget(self.sublayout)
        self.tv = CustomTreeView(root_options=dict(text='Tree One'), hide_root=True, indent_level=4)
        self.tv.size_hint = 1, None
        self.tv.bind(minimum_height = self.tv.setter('height'))
        self.tv.app = self
        populate_tree_view(self.tv)
        self.sv = ScrollView()
        self.sv.add_widget(self.tv)
        self.sublayout.add_widget(self.sv)
        # subsublayout = GridLayout()
        if self.detailsID != 0:
            self.details = Details.giveDetailsObject(self.detailsID)
            self.sublayout.add_widget(self.details)
        else:
            self.details = BoxLayout(orientation="vertical")
            self.sublayout.add_widget(self.details)
        # sublayout.add_widget(subsublayout)
        # sublayout.add_widget(Button(text='Test'))

        return  self.layout

    def updateDetails(self, *args):
        children = self.sublayout.children[:1]

        self.sublayout.clear_widgets(children=children)
        self.details = Details.giveDetailsObject(self.detailsID)
        self.sublayout.add_widget(self.details)

    def getTaskScreen(self,*args):
        children = self.sublayout.children[:1]
        self.sublayout.clear_widgets(children=children)
        print(self.taskId, 'taskid')
        print(self.BiD, 'buildid')
        self.details = AddTaskScreen(task=AddTaskScreen.get_rigt_task_for_task_screen(self.taskId,self.BiD), app=self)
        print("after AddTaskScreen()")
        #self.details.buildID = self.BiD
        #self.details.task = Task.getTask(self.taskId)
        #self.details.app = self
        self.sublayout.add_widget(self.details)
        print('im here')
Exemplo n.º 22
0
class AskUserEventHandler(EventHandler):
    """Handles user input for actions which require special input."""

    menu: BoxLayout = None
    bg: Rectangle = None

    def __init__(self, engine, **kwargs):
        super(AskUserEventHandler, self).__init__(engine)
        # Create Framed Menu with Cursor or Highlight
        self.menu = BoxLayout(pos_hint={
            "top": 0.75,
            "center_x": 0.35
        },
                              orientation="vertical",
                              size_hint=(None, None))
        with self.menu.canvas:
            Color(0.5, 0.25, 0.1, 1)
            self.bg = Rectangle(pos=self.menu.pos, size=self.menu.size)

    def __on_exit__(self, root_widget: Widget) -> None:
        root_widget.remove_widget(self.menu)
        self.menu.clear_widgets()
        self.menu.canvas.clear()
        self.rect = None

    def ev_keydown(self,
                   event: tcod.event.KeyDown) -> Optional[ActionOrHandler]:
        """By default any key exits this input handler."""
        if event.sym in {  # Ignore modifier keys.
            tcod.event.K_LSHIFT,
            tcod.event.K_RSHIFT,
            tcod.event.K_LCTRL,
            tcod.event.K_RCTRL,
            tcod.event.K_LALT,
            tcod.event.K_RALT,
        }:
            return None
        return self.on_exit()

    def ev_mousebuttondown(
            self,
            event: tcod.event.MouseButtonDown) -> Optional[ActionOrHandler]:
        """By default any mouse click exits this input handler."""
        return self.on_exit()

    def on_exit(self) -> Optional[ActionOrHandler]:
        """Called when the user is trying to exit or cancel an action.

        By default this returns to the main event handler.
        """
        return MainGameEventHandler(self.engine)
Exemplo n.º 23
0
class MainWid(ScreenManager):
    def __init__(self, *args, **kwargs):
        super(MainWid, self).__init__()
        # Control de Path
        self.APP_PATH = os.getcwd()
        self.DB_PATH = self.APP_PATH + '/database.db'

        self.MenuWid = MenuWid(self)  #Screen: menu
        self.CreatureListWid = CreatureListWid(self)  #Screen: creaturelist
        self.CreatureCreateWid = BoxLayout()  #Screen: creaturecreate
        self.CreatureUpdateWid = BoxLayout()  #Screen: creatureupdate

        wid = Screen(name='menu')
        wid.add_widget(self.MenuWid)
        self.add_widget(wid)

        wid = Screen(name='creaturelist')
        wid.add_widget(self.CreatureListWid)
        self.add_widget(wid)

        wid = Screen(name='creaturecreate')
        wid.add_widget(self.CreatureCreateWid)
        self.add_widget(wid)

        wid = Screen(name='creatureupdate')
        wid.add_widget(self.CreatureUpdateWid)
        self.add_widget(wid)

        self.goto_menu()

    def goto_menu(self):
        self.current = 'menu'

    def goto_creturelist(self):
        self.CreatureListWid.check_memory()
        self.current = 'creaturelist'

    def goto_creaturecreate(self):
        self.CreatureCreateWid.clear_widgets()
        wid = CreatureCreateWid(self)
        self.CreatureCreateWid.add_widget(wid)
        self.current = 'creaturecreate'

    def goto_creatureupdate(self, data_id):
        self.CreatureUpdateWid.clear_widgets()
        wid = CreatureUpdateWid(self, data_id)
        self.CreatureUpdateWid.add_widget(wid)
        self.current = 'creatureupdate'
Exemplo n.º 24
0
class MainWid(ScreenManager):
    def __init__(self, **kwargs):  #recibe un diccionario de parametros
        super(MainWid, self).__init__()
        self.APP_PATH = os.getcwd()  #constante DB
        self.DB_PATH = self.APP_PATH + "/my_database.db"
        self.StartWid = StartWid(self)  #instancia de la clase StartWid
        self.DataBaseWid = DataBaseWid(self)
        self.InsertDataWid = BoxLayout(
        )  #Limpiar para inicar nuevo widget %%%%%
        self.UpdateDataWid = BoxLayout()  #Actualizar producto
        self.Popup = MessagePopup()

        wid = Screen(name="start")
        wid.add_widget(self.StartWid)
        self.add_widget(wid)
        wid = Screen(name="database")
        wid.add_widget(self.DataBaseWid)
        self.add_widget(wid)
        #%%%%%
        wid = Screen(name="insertdata")
        wid.add_widget(self.InsertDataWid)
        self.add_widget(wid)
        wid = Screen(name="updatedata")
        wid.add_widget(self.UpdateDataWid)
        self.add_widget(wid)

        #Función que ayuda a acomodar las pantallas en el momento que se invoquen.
        self.goto_start()

    def goto_start(self):
        self.current = "start"

    def goto_database(self):
        self.DataBaseWid.check_memory()
        self.current = "database"

    #%%%%%
    def goto_insertdata(self):
        self.InsertDataWid.clear_widgets()  #para limpiarlo
        wid = InsertDataWid(self)
        self.InsertDataWid.add_widget(wid)
        self.current = "insertdata"

    def goto_updatedata(self, data_id):
        self.UpdateDataWid.clear_widgets()  #para limpiarlo
        wid = UpdateDataWid(self, data_id)
        self.UpdateDataWid.add_widget(wid)
        self.current = "updatedata"
Exemplo n.º 25
0
class MainApp(App):
    def build(self):
        self.layout = BoxLayout(padding=30)
        button = Button(text='Try me',
                        size_hint=(.5, .5),
                        pos_hint={'center_x': .5, 'center_y': .5})
        button.bind(on_press=self.on_press_button)
        self.layout.add_widget(button)

        return self.layout

    def on_press_button(self, instance):
        self.layout.clear_widgets()
        to_birthday = ToBirthday()
        Clock.schedule_interval(to_birthday.update, 1)
        self.layout.add_widget(to_birthday)
Exemplo n.º 26
0
class LienzoApp(ScreenManager):
    def __init__(self):
        super(LienzoApp, self).__init__()
        self.APP_PATH = os.getcwd()
        self.DB_PATH = self.APP_PATH + "/testdb.db"
        self.InicioLienzo = InicioLienzo(self)
        self.DBWid = DBWid(self)
        self.InsertarDataWid = BoxLayout()
        self.ActualizaCajas = BoxLayout()
        self.popup = MensajePopUp()

        wid = Screen(name="inicio")
        wid.add_widget(self.InicioLienzo)
        self.add_widget(wid)

        wid = Screen(name="productos")
        wid.add_widget(self.DBWid)
        self.add_widget(wid)

        wid = Screen(name="insertardatos")
        wid.add_widget(self.InsertarDataWid)
        self.add_widget(wid)

        wid = Screen(name="actualizar")
        wid.add_widget(self.ActualizaCajas)
        self.add_widget(wid)

        self.goto_inicio()

    def goto_inicio(self):
        self.current = "inicio"

    def goto_soluciones(self):
        self.DBWid.check_memory()
        self.current = "productos"

    def goto_insertar(self):
        self.InsertarDataWid.clear_widgets()
        wid = InsertarDataWid(self)
        self.InsertarDataWid.add_widget(wid)
        self.current = "insertardatos"

    def goto_actualizar(self, data_id):
        self.ActualizaCajas.clear_widgets()
        wid = ActualizaCajas(self, data_id)
        self.ActualizaCajas.add_widget(wid)
        self.current = "actualizar"
Exemplo n.º 27
0
class MainWid(ScreenManager):
    def __init__(self, *args, **kwargs):
        super().__init__(**kwargs)
        self.APP_PATH = os.getcwd()
        self.DB_PATH = self.APP_PATH + '/db_sqlite3.db'
        self.startWid = StartWid(self)
        self.dataBaseWid = DataBaseWid(self)
        self.insertDataWid = InsertDataWid(self)  # BoxLayout()
        self.updateDataWid = BoxLayout()
        self.popup = MessagePopup()

        wid = Screen(name='start')
        wid.add_widget(self.startWid)
        self.add_widget(wid)

        wid = Screen(name='database')
        wid.add_widget(self.dataBaseWid)
        self.add_widget(wid)

        wid = Screen(name='insertdata')
        wid.add_widget(self.insertDataWid)
        self.add_widget(wid)

        wid = Screen(name='updatedata')
        wid.add_widget(self.updateDataWid)
        self.add_widget(wid)

        self.start()

    def start(self):
        self.current = 'start'

    def dataBase(self):
        self.dataBaseWid.check_mem()
        self.current = 'database'

    def insert_data(self):
        self.insertDataWid.clear_widgets()
        wid = InsertDataWid(self)
        self.insertDataWid.add_widget(wid)
        self.current = 'insertdata'

    def update_data(self, data_id):
        self.updateDataWid.clear_widgets()
        wid = UpdateDataWid(self, data_id)
        self.updateDataWid.add_widget(wid)
        self.current = 'updatedata'
Exemplo n.º 28
0
class MainWid(ScreenManager):
    def __init__(self, **kwarg):
        super(MainWid, self).__init__()
        self.app_path = os.getcwd()
        self.db_path = self.app_path + "/my_database.db"
        self.StartWid = StartWid(self)
        self.DataBaseWid = DataBaseWid(self)
        self.InsertDataWid = BoxLayout()
        self.UpdateDataWid = BoxLayout()
        self.Popup = MessagePopup()

        wid = Screen(name='start')
        wid.add_widget(self.StartWid)
        self.add_widget(wid)

        wid = Screen(name='database')
        wid.add_widget(self.DataBaseWid)
        self.add_widget(wid)

        wid = Screen(name='insertdata')
        wid.add_widget(self.InsertDataWid)
        self.add_widget(wid)

        wid = Screen(name='updatedata')
        wid.add_widget(self.UpdateDataWid)
        self.add_widget(wid)

        self.goto_start()

    def goto_start(self):
        self.current = 'start'

    def goto_database(self):
        self.DataBaseWid.check_memory()
        self.current = 'database'

    def goto_insertdata(self):
        self.InsertDataWid.clear_widgets()
        wid = InsertDataWid(self)
        self.InsertDataWid.add_widget(wid)
        self.current = 'insertdata'

    def goto_updatedata(self, data_id):
        self.UpdateDataWid.clear_widgets()
        wid = UpdateDataWid(self, data_id)
        self.UpdateDataWid.add_widget(wid)
        self.current = 'updatedata'
Exemplo n.º 29
0
class MainWindow(App):

    settings_popup = Settings()

    def add_widgets(self, root):
        self.settings_popup.ok.bind(on_press=self.re_build)
        page = PageLayout(border=30, swipe_threshold=0.2)
        p1 = BoxLayout(orientation='horizontal', background_color=[1, 1, 1, 1])
        p1.add_widget(self.settings_popup.specimen.eps_sig_wid)
        p1.add_widget(self.settings_popup.specimen.f_u_wid)
        page.add_widget(p1)

        p2 = BoxLayout(orientation='horizontal', background_color=[1, 1, 1, 1])
        p2.add_widget(self.settings_popup.specimen.disp_slip_wid)
        p2.add_widget(self.settings_popup.specimen.shear_flow_wid)
        page.add_widget(p2)

        upper = BoxLayout(orientation='horizontal', size_hint=(1, 0.7))
        upper.add_widget(page)
        root.add_widget(upper)

        btns = BoxLayout(orientation='horizontal', size_hint=(1, 0.1))
        settings = Button(text='Settings')
        settings.bind(on_press=self.settings_popup.open)

        reset = Button(text='Reset')
        reset.bind(on_press=self.settings_popup.reset)

        btns.add_widget(Label())
        btns.add_widget(Label())
        btns.add_widget(settings)
        btns.add_widget(reset)
        root.add_widget(self.settings_popup.specimen)
        root.add_widget(btns)

    def build(self):
        self.root = BoxLayout(orientation='vertical')
        self.add_widgets(self.root)
        return self.root

    def re_build(self, btn):
        self.settings_popup.confirm_settings(btn)
        self.root.clear_widgets()
        self.add_widgets(self.root)
        self.settings_popup.reset(None)
Exemplo n.º 30
0
    def disabled_menu(self):
        """
		Creates a disabled messaging menu should xmpp be disabled.
		"""
        self.clear_widgets()
        sub_layout = BoxLayout(size_hint=(1, 1))
        sub_layout.clear_widgets()
        lab = Label(text='XMPP messaging is disabled due to config errors!',
                    size_hint=(1, 1),
                    markup=True)
        lab.color = colorsys.hsv_to_rgb(0, 0, 1)

        with lab.canvas.before:
            Color(1, 1, 0, mode='hsv')
            lab.bg_rect = Rectangle(pos=self.pos, size=self.size)

        lab.bind(pos=self.redraw, size=self.redraw)
        sub_layout.add_widget(lab)
        self.add_widget(sub_layout)
Exemplo n.º 31
0
class MyApp(App):
    isConnected = False
    connect = object

    def build(self):
        global connect
        self.mainview = BoxLayout(orientation='horizontal')

        self.startscreen = SimMainScreen(self)
        self.mainview.add_widget(self.startscreen)

        return self.mainview

    def on_stop(self):
        return

    def showStartScreen(self):
        self.mainview.clear_widgets()
        self.mainview.add_widget(self.startscreen)

    def showResult(self, simobj):
        self.mainview.clear_widgets()
        resultpage = SimResultScreen(self, simobj)
        self.mainview.add_widget(resultpage)

    def showEditorNew(self):
        self.mainview.clear_widgets()
        editorpage = SimParamEditor(self)
        self.mainview.add_widget(editorpage)
Exemplo n.º 32
0
class CityChooser(BoxLayout):
    def __init__(self, main, caller, next_screen, returner, **kwargs):
        super().__init__(**kwargs, orientation='horizontal')
        self.next_screen = next_screen
        self.callnext = main.callnext
        self.caller = caller
        self.returner = returner
        self.moves = 0
        self.cdc = 1

        color_btns = BoxLayout(orientation='vertical')
        bluebtn = Button(text="Blue")
        yellowbtn = Button(text="Yellow")
        blackbtn = Button(text="Black")
        redbtn = Button(text="Red")
        bluebtn.bind(on_press=self.color_clicked)
        yellowbtn.bind(on_press=self.color_clicked)
        blackbtn.bind(on_press=self.color_clicked)
        redbtn.bind(on_press=self.color_clicked)
        color_btns.add_widget(bluebtn)
        color_btns.add_widget(yellowbtn)
        color_btns.add_widget(blackbtn)
        color_btns.add_widget(redbtn)
        self.citybtns = BoxLayout(orientation='vertical')
        self.add_widget(color_btns)
        self.add_widget(self.citybtns)

    def color_clicked(self, btn):
        self.citybtns.clear_widgets()
        cities = city_list[btn.text.lower()]
        for city in cities:
            btn = Button(text=city)
            btn.bind(on_press=self.city_choosen)
            self.citybtns.add_widget(btn)

    def city_choosen(self, btn):
        if self.returner(btn.text):
            self.callnext(self.next_screen)
        else:
            self.callnext(self.caller)
Exemplo n.º 33
0
class AddWord(ScreenManager):

    def __init__(self, **kwargs):
        super(AddWord, self).__init__(**kwargs)

        layout = BoxLayout(orientation='vertical')

        self.word_input = TextInput(multiline=False, size_hint=(1, .5))
        layout.add_widget(self.word_input)

        self.button = Button(
            on_press=self.send_word,
            on_error=self.on_error,
            text="Send", size_hint=(1, .5),
            pos_hint={'center_x': .5, 'center_y': .5})
        layout.add_widget(self.button)

        add = Screen(name='Add')
        add.add_widget(layout)
        self.add_widget(add)

        # --
        self.status_layout = BoxLayout(orientation='vertical')
        status = Screen(name='Status')
        status.add_widget(self.status_layout)
        self.add_widget(status)

    def send_word(self, *args):
        self.status_layout.clear_widgets()
        self.status_layout.add_widget(Label(text='Loading..'))
        self.current = 'Status'
        word = self.word_input.text
        headers = {'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'}

        UrlRequest(POST_WORD_URL, method="POST",
                   req_headers=headers,
                   req_body=urlencode({'word': word}),
                   on_success=self.show_response,
                   on_error=self.on_error,
                   on_failure=self.on_error)

    def show_response(self, _, data):
        if data['name']:
            text = "%s \n\n%s" % (data['name'], "\n".join(["-(%s) %s" % tuple(i) for i in data['meanings_list']]))
        else:
            text = "The word wasn't found"

        self.status_layout.clear_widgets()
        self.status_layout.add_widget(Label(text=text, text_size=(self.width, None), padding_x=10))
        self.status_layout.add_widget(Button(text='OK', on_press=self.reset))

    def on_error(self, *args):
        print('on_error', args)

    def reset(self, *args):
        self.word_input.text = ""
        self.current = 'Add'
        self.status_layout.clear_widgets()
Exemplo n.º 34
0
    def do_popup_file_select(self):
        """
		Prompts the user to navigate to the WAV file.
		"""
        self.filewidget = FileWidget()
        box = BoxLayout(orientation='vertical')
        box_int = BoxLayout(orientation='horizontal', size_hint=(1, .2))
        close_button = Button(text='Load')
        close_button.bind(on_release=lambda x: self.copy_sound())
        dismiss_button = Button(text='Cancel')
        dismiss_button.bind(
            on_release=lambda x: self.file_select_popup.dismiss())
        box.clear_widgets()
        box_int.add_widget(close_button)
        box_int.add_widget(dismiss_button)
        box.add_widget(self.filewidget)
        box.add_widget(box_int)
        self.file_select_popup = Popup(title='Choose File',
                                       content=box,
                                       size_hint=(None, None),
                                       size=(800, 1000),
                                       auto_dismiss=False)
        self.file_select_popup.open()
Exemplo n.º 35
0
class MusicApp(App):
    def __init__(self, **kwargs):

        super().__init__(**kwargs)
        self.window_x = Window.size[0]
        self.window_y = Window.size[1]
        self.all_window = BoxLayout(orientation='vertical', size_hint=[1, 1])
        if True:  # Make fast_menu
            self.fast_menu = BoxLayout(size_hint=[1, .0625])
            self.btn1 = Button(text='music',
                               size_hint=[1, 1],
                               on_press=self.press_chart)
            self.btn2 = Button(text='+',
                               size_hint=[1, 1],
                               on_press=self.press_add_music)
            self.btn3 = Button(text='profil',
                               size_hint=[1, 1],
                               on_press=self.press_profile)
            self.fast_menu.add_widget(self.btn1)
            self.fast_menu.add_widget(self.btn2)
            self.fast_menu.add_widget(self.btn3)
        if True:  # Make main_menu and variety of main menu
            self.profile_menu = BoxLayout()
            self.make_profile_menu()
            self.chart_menu = BoxLayout()
            self.make_chart_menu()
            self.add_music_menu = BoxLayout()
            self.make_add_music_menu()
            self.main_menu = BoxLayout(size_hint=[1, .9375])
            self.main_menu.add_widget(self.profile_menu)
        self.all_window.add_widget(self.main_menu)
        self.all_window.add_widget(self.fast_menu)

    def build(self):
        return self.all_window

    def press_chart(self, instance):  # at the moment it is finished
        self.main_menu.clear_widgets()
        self.main_menu.add_widget(self.chart_menu)

    def press_add_music(self, instance):  # at the moment it is finished
        self.main_menu.clear_widgets()
        self.main_menu.add_widget(self.add_music_menu)

    def press_profile(self, instance):  # at the moment it is finished
        self.main_menu.clear_widgets()
        self.main_menu.add_widget(self.profile_menu)

    def make_profile_menu(self):  # a lot of work
        self.profile_menu.add_widget(Button(text='profile', size_hint=[1, 1]))

    def make_add_music_menu(self):  # a lot of work
        self.add_music_menu.add_widget(
            Button(text='add music', size_hint=[1, 1]))

    def make_chart_menu(self):  # a lot of work
        self.chart_menu.add_widget(Button(text='chart', size_hint=[1, 1]))
Exemplo n.º 36
0
class SettingContainer(BoxLayout):
    def __init__(self, app, **kwargs):
        self.app = app
        self.settings = self.app.settings
        self.settings_container = BoxLayout(orientation="vertical")
        super(SettingContainer, self).__init__(**kwargs)
        self.create_button = Button(text="create", size_hint_x=None)
        self.create_button.bind(on_press=lambda widget: self.create_item())
        self.add_widget(self.settings_container)
        self.add_widget(self.create_button)
        self.update_widgets()

    def update_widgets(self):
        self.settings_container.clear_widgets()
        for widget in self.settings:
            self.settings_container.add_widget(widget)

    def create_item(self):
        w = SetItem(None)
        self.settings_container.add_widget(w)

    def remove_item(self, item):
        self.settings_container.remove_widget(item)
        del item
Exemplo n.º 37
0
class AdventureApp(App):
    def __init__(self, **kwargs):
        super(AdventureApp, self).__init__(**kwargs)
        Builder.load_file('mainMenu.kv')
        Builder.load_file('adventure.kv')
        Builder.load_file('movement.kv')
        self.WidgetSet = BoxLayout()
        self.Game = Main_Menu()
        self.b = None
        f = open("gamechoice.txt", "w")
        f.write('mainmenu')
        f.close()

    def build(self):
        Clock.schedule_interval(self.update, 1)
        return self.WidgetSet

    def update(self, dt):
        print 'update'
        f = open('gamechoice.txt', 'r')
        a = f.read()
        f.close()
        if self.b == a:
            print 'passed'
        else:
            self.b = a
            if a == "mainmenu":
                print 'MainMenu!!'
                self.WidgetSet.clear_widgets()
                self.Game = Main_Menu()
                self.WidgetSet.add_widget(self.Game)
            elif a == 'scratch':
                print 'Scratch!!'
                self.WidgetSet.clear_widgets()
                self.Game = map.Mechanics()
                self.WidgetSet.add_widget(self.Game)
            elif a == 'box':
                print 'BOX!!'
                self.WidgetSet.clear_widgets()
                self.Game = box.stuff_moving()
                self.WidgetSet.add_widget(self.Game)
            else:
                pass
Exemplo n.º 38
0
class InfoPopup(Scatter):
    """Widget that contains detailed information in a draggable popup."""

    def __init__(self, **kwargs):
        global popups

        popups.append(self)

        self._built = False
        self._window = None
        self._parent = None
        self._old_center = (0, 0)
        self.layout = None
        self.label = None
        self.container = None

        self.background = kwargs.get(
            'background',
            'atlas://data/images/defaulttheme/modalview-background'
        )
        self.border = kwargs.get('border', [16, 16, 16, 16])

        self._title = kwargs.get('title', 'No title')
        self._content = kwargs.get('content', None)

        self.register_event_type('on_show')
        self.register_event_type('on_dismiss')

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

    def build(self):
        """Render the popup."""
        with self.canvas:
            Color(1, 1, 1)
            BorderImage(
                source=self.background,
                border=self.border,
                pos=self.pos,
                size=self.size
            )

        self.layout = GridLayout(
            cols=1,
            padding=12,
            spacing=5,
            size_hint=(None, None),
            pos=self.pos,
            size=self.size
        )

        header = BoxLayout(size_hint_y=None, height=28)

        # Set the popup's title
        self.label = Label(
            text=self.title,
            size_hint_y=None,
            height=24,
            valign='middle',
            font_size=12,
            padding=(0, 6),
            text_size=(self.width - 124, 24)
        )
        header.add_widget(self.label)

        # Add a close button
        close_btn = Button(
            text='Close',
            size_hint=(None, None),
            size=(100, 28)
        )
        close_btn.bind(on_release=self.dismiss)
        header.add_widget(close_btn)

        self.layout.add_widget(header)

        separator = WRectangle(
            size_hint_y=None,
            height=2,
            color=[.2, .6, .9, 1.]
        )
        self.layout.add_widget(separator)

        # Add the popup's contents
        self.container = BoxLayout()
        if self._content:
            self.container.add_widget(self._content)
        self.layout.add_widget(self.container)

        self.add_widget(self.layout)

        self._built = True

    def update_textures(self, widget=None, *largs):
        """Update all labels inside the popup."""
        if not isinstance(widget, Widget):
            widget = self
        if isinstance(widget, Label):
            Logger.debug("InfoPopup: Update texture of %s" % widget.__class__)
            widget.texture_update()
        for child in widget.children:
            self.update_textures(child)

    def show(self, *largs):
        """Open the popup."""
        if self._window:
            # Bring to front
            self._window.remove_widget(self)
            self._window.add_widget(self)
            self._align_center()
            return self

        self._window = Window
        if not self._window:
            Logger.warning('InfoPopup: cannot open popup, no window found.')
            return self

        self._window.add_widget(self)
        self._window.bind(on_resize=self._align_center)

        if not self._built:
            # Render the popup when not done so yet
            self.build()
        self.center = self._window.mouse_pos
        self._align_center()

        Clock.schedule_once(self.update_textures, .5)
        self.dispatch('on_show')
        return self

    def dismiss(self, *largs):
        """Close the popup."""
        if self._window:
            self._window.remove_widget(self)
            self._window.unbind(on_resize=self._align_center)
            self._window = None

        self.dispatch('on_dismiss')
        return self

    def swerve(self, *largs):
        """Move the popup to the closest side of the screen."""
        if not self._window:
            return

        self._old_center = self.center

        dx = self._window.center[0] - self.center[0]
        dy = self._window.center[1] - self.center[1]

        # Window dimensions
        ww = self._window.width
        wh = self._window.height

        # Extended sizes
        eww = ww + (self.width - 40)
        ewh = wh + (self.height - 40)

        if abs(dx) / ww >= abs(dy) / wh:
            if dx > 0:
                tx = -(self.width / 2 - 20)
            else:
                tx = ww + (self.width / 2 - 20)

            if dy > 0:
                ty = self.center[1] - eww / 2 * abs(dy) / (abs(dx) + 1e-5) + dy
            else:
                ty = self.center[1] + eww / 2 * abs(dy) / (abs(dx) + 1e-5) + dy
        else:
            if dx > 0:
                tx = self.center[0] - ewh / 2 * abs(dx) / (abs(dy) + 1e-5) + dx
            else:
                tx = self.center[0] + ewh / 2 * abs(dx) / (abs(dy) + 1e-5) + dx

            if dy > 0:
                ty = -(self.height / 2 - 20)
            else:
                ty = wh + (self.height / 2 - 20)

        Animation(
            center=(tx, ty),
            t='in_out_expo',
            d=.3
        ).start(self)

    def swerve_back(self, *largs):
        """Move the popup back to where it came from."""
        if not self._window:
            return

        Animation(
            center=self._old_center,
            t='in_out_expo',
            d=.3
        ).start(self)

    def on_size(self, instance, value):
        """Handler when the popup is resized. Re-align the popup."""
        self._align_center()

    def _align_center(self, *largs):
        """Re-align the popup to the center of the screen."""
        if self._window:
            Animation(
                center=self._window.center,
                t='in_out_expo',
                d=.3
            ).start(self)

    def on_show(self):
        """Handler when the popup is opened. Does nothing."""
        pass

    def on_dismiss(self):
        """Handler when the popup is closed. Does nothing."""
        pass

    def get_title(self):
        """Getter for the popup's title."""
        return self._title

    def set_title(self, value):
        """Setter for the popup's title."""
        self._title = value
        if self.label:
            self.label.text = self._title

    def get_content(self):
        """Getter for the popup's content."""
        return self._content

    def set_content(self, value):
        """Setter for the popup's content."""
        self._content = value
        if self.container:
            self.container.clear_widgets()
            if self._content:
                self.container.add_widget(self._content)
            Clock.schedule_once(self.update_textures, .5)

    # Define getters and setters
    title = property(get_title, set_title)
    content = property(get_content, set_content)
Exemplo n.º 39
0
class SubstitutingScreen(Screen):
    def __init__(self, **kwargs):
        result = super(SubstitutingScreen, self).__init__(**kwargs)

        layout = BoxLayout(orientation='vertical')
        backButton = Button(text='<<<', size_hint=(1, 0.1))

        scroll = ScrollView(size_hint=(1,1))
        self._contentSpace = BoxLayout(orientation='vertical')
        scroll.add_widget(self._contentSpace)

        backButton.bind(on_press=self.goBack)

        layout.add_widget(backButton)
        layout.add_widget(scroll)

        self.add_widget(layout)

        self.bind(on_enter=self.displayContent)

        return result

    def goBack(self, invoker):
        self.manager.current="Menu"

    def downloadContent(self):
        date = datetime.date.today()
        # Tomorrow
        #date = datetime.date.today() + datetime.timedelta(days=1)
        dateText = str(date.year) + str(date.month).zfill(2) + str(date.day).zfill(2)
        url =  'http://www.glstn.sk/zastupo/zast_' + dateText + '.htm'
        htmlRequest = requests.get(url)
        htmlRequest.encoding = 'windows-1250'
        return htmlRequest.text.encode('utf-8')

    def parseContent(self, htmlText):
        # Cut the interesting portion
        htmlStart = re.search('zastupovanie', htmlText)
        htmlText = htmlText[htmlStart.regs[0][0]:]

        htmlStart = re.search('<table.*class="Pozadie".*>', htmlText)
        htmlText = htmlText[htmlStart.regs[0][1]:]

        htmlEnd = re.search('</table>', htmlText)
        htmlText = htmlText[:htmlEnd.regs[0][0]]

        htmlText = re.sub('nowrap|&nbsp;', '', htmlText)

        htmlText = '<body>' + htmlText + '</body>'

        # Parse the html
        htmlDom = xml.dom.minidom.parseString(htmlText)

        # Build dictionary where class is the key
        substitutionByClass = {}

        missingTeacher = None
        hour = None
        schoolClasses = None
        subject = None
        classroom = None
        substitutingTeacher = None
        substitutionType = None
        note = None

        for row in htmlDom.getElementsByTagName('tr'):
            correctRow = True

            for cell in row.getElementsByTagName('td'):
                atr = cell.getAttribute('class')
                if cell.firstChild:
                    data = cell.firstChild.data
                else:
                    data = ''

                if atr == 'C11':
                    if data != '':
                        missingTeacher = data
                elif atr == 'C12':
                    hour = int(data)
                elif atr == 'C13':
                    schoolClasses = data
                elif atr == 'C14':
                    subject = data
                elif atr == 'C15':
                    classroom = data
                elif atr == 'C16':
                    substitutingTeacher = data
                elif atr == 'C17':
                    substitutionType = data
                elif atr == 'C18':
                    note = data
                else:
                    correctRow = False
                    break

            if not correctRow:
                continue

            # The schoolClasses might contain a list of classes separated by comma
            for schoolClass in schoolClasses.split(', '):
                if not schoolClass in substitutionByClass:
                    substitutionByClass[schoolClass] = []
                substitutionByClass[schoolClass].append(SubstituteItem(hour, subject, substitutingTeacher, note, missingTeacher, classroom, substitutionType))

        return substitutionByClass

    def prepareContent(self):
        htmlText = self.downloadContent()
        return self.parseContent(htmlText)

    def displayContent(self, invoker):
        self._contentSpace.clear_widgets()
        self._contentSpace.size_hint=(1, 1)
        self._contentSpace.size=(0,0)
        try:
            content = self.prepareContent()
            if Settings.schoolClass in content:
                for x in content[Settings.schoolClass]:
                    self._contentSpace.add_widget(x.kivy_short(self.displayFull))
                self._contentSpace.add_widget(Spacer())
                self._contentSpace.size_hint=(1, None)
                self._contentSpace.size=(0,1000)
            else:
                self._contentSpace.add_widget(Label(text='No substituting today :('))
        except Exception, e:
            self._contentSpace.add_widget(Label(text='An error occured.'))
            MessagePopup('Error', traceback.format_exc(e))
Exemplo n.º 40
0
class DatePicker(BoxLayout):
    def __init__(self, *args, **kwargs):
        super(DatePicker, self).__init__(**kwargs)
        self.date = date.today()
        self.orientation = "vertical"
        self.month_names = ('January', 'February', 'March', 'April', 'May',
                            'June', 'July', 'August', 'September', 'October',
                            'November', 'December')
        if kwargs.has_key("month_names"):
            self.month_names = kwargs['month_names']
        self.header = BoxLayout(orientation='horizontal', size_hint=(1, 0.2))
        self.body = GridLayout(cols=7)
        self.add_widget(self.header)
        self.add_widget(self.body)

        self.populate_body()
        self.populate_header()

    def populate_header(self, *args, **kwargs):
        self.header.clear_widgets()
        previous_month = Button(text="<")
        previous_month.bind(on_press=partial(self.move_previous_month))
        next_month = Button(text=">", on_press=self.move_next_month)
        next_month.bind(on_press=partial(self.move_next_month))
        month_year_text = self.month_names[self.date.month - 1] + ' ' + str(
            self.date.year)
        current_month = Label(text=month_year_text, size_hint=(2, 1))

        self.header.add_widget(previous_month)
        self.header.add_widget(current_month)
        self.header.add_widget(next_month)

    def populate_body(self, *args, **kwargs):
        self.body.clear_widgets()
        date_cursor = date(self.date.year, self.date.month, 1)
        for filler in range(date_cursor.isoweekday() - 1):
            self.body.add_widget(Label(text=""))
        while date_cursor.month == self.date.month:
            date_label = Button(text=str(date_cursor.day))
            date_label.bind(
                on_press=partial(self.set_date, day=date_cursor.day))
            if self.date.day == date_cursor.day:
                date_label.background_normal, date_label.background_down = date_label.background_down, date_label.background_normal
            self.body.add_widget(date_label)
            date_cursor += timedelta(days=1)

    def set_date(self, *args, **kwargs):
        self.date = date(self.date.year, self.date.month, kwargs['day'])
        self.populate_body()
        self.populate_header()

    def move_next_month(self, *args, **kwargs):
        if self.date.month == 12:
            self.date = date(self.date.year + 1, 1, self.date.day)
        else:
            self.date = date(self.date.year, self.date.month + 1,
                             self.date.day)
        self.populate_header()
        self.populate_body()

    def move_previous_month(self, *args, **kwargs):
        if self.date.month == 1:
            self.date = date(self.date.year - 1, 12, self.date.day)
        else:
            self.date = date(self.date.year, self.date.month - 1,
                             self.date.day)
        self.populate_header()
        self.populate_body()
Exemplo n.º 41
0
class DatePicker(BoxLayout):

    def __init__(self, *args, **kwargs):
        super(DatePicker, self).__init__(**kwargs)
        self.date = date.today()
        self.orientation = "vertical"
        self.month_names = ('January',
                            'February', 
                            'March', 
                            'April', 
                            'May', 
                            'June', 
                            'July', 
                            'August', 
                            'September', 
                            'October',
                            'November',
                            'December')
        if kwargs.has_key("month_names"):
            self.month_names = kwargs['month_names']
        self.header = BoxLayout(orientation = 'horizontal', 
                                size_hint = (1, 0.2))
        self.body = GridLayout(cols = 7)
        self.add_widget(self.header)
        self.add_widget(self.body)

        self.populate_body()
        self.populate_header()

    def populate_header(self, *args, **kwargs):
        self.header.clear_widgets()
        previous_month = Button(text = "<")
        previous_month.bind(on_press=partial(self.move_previous_month))
        next_month = Button(text = ">", on_press = self.move_next_month)
        next_month.bind(on_press=partial(self.move_next_month))
        month_year_text = self.month_names[self.date.month -1] + ' ' + str(self.date.year)
        current_month = Label(text=month_year_text, size_hint = (2, 1))

        self.header.add_widget(previous_month)
        self.header.add_widget(current_month)
        self.header.add_widget(next_month)

    def populate_body(self, *args, **kwargs):
        self.body.clear_widgets()
        date_cursor = date(self.date.year, self.date.month, 1)
        for filler in range(date_cursor.isoweekday()-1):
            self.body.add_widget(Label(text=""))
        while date_cursor.month == self.date.month:
            date_label = Button(text = str(date_cursor.day))
            date_label.bind(on_press=partial(self.set_date, 
                                                  day=date_cursor.day))
            if self.date.day == date_cursor.day:
                date_label.background_normal, date_label.background_down = date_label.background_down, date_label.background_normal
            self.body.add_widget(date_label)
            date_cursor += timedelta(days = 1)

    def set_date(self, *args, **kwargs):
        self.date = date(self.date.year, self.date.month, kwargs['day'])
        self.populate_body()
        self.populate_header()

    def move_next_month(self, *args, **kwargs):
        if self.date.month == 12:
            self.date = date(self.date.year + 1, 1, self.date.day)
        else:
            self.date = date(self.date.year, self.date.month + 1, self.date.day)
        self.populate_header()
        self.populate_body()

    def move_previous_month(self, *args, **kwargs):
        if self.date.month == 1:
            self.date = date(self.date.year - 1, 12, self.date.day)
        else:
            self.date = date(self.date.year, self.date.month -1, self.date.day)
        self.populate_header()
        self.populate_body()
Exemplo n.º 42
0
class CancelLunchScreen(Screen):
    def __init__(self, **kwargs):
        result = super(CancelLunchScreen, self).__init__(**kwargs)

        layout = BoxLayout(orientation='vertical')
        backButton = Button(text='<<<', size_hint=(1, 0.1))

        scroll = ScrollView(size_hint=(1,1))
        self._contentSpace = BoxLayout(orientation='vertical')
        scroll.add_widget(self._contentSpace)

        backButton.bind(on_press=self.goBack)

        layout.add_widget(backButton)
        layout.add_widget(scroll)

        self.add_widget(layout)

        self.bind(on_enter=self.displayContent)
        self.dateField = None

        return result
    
    def goBack(self, invoker):
        self.dateField = None
        self.manager.current="Menu"

    def downloadContent(self):
        htmlRequest = requests.get('http://www.google.com/recaptcha/api/noscript?k=6Led_70SAAAAALznKUaJm-fIGI4FFzUvUymYq_6w')
        htmlRequest.encoding = 'utf-8'
        return htmlRequest.text

    def parseContent(self, htmlText):
        recaptchaChallengeRegex = re.compile('<input.*name="recaptcha_challenge_field".*value=["]([^"]+)["]>', re.UNICODE)
        imgRegex = re.compile('<img.*src=["](image[?]c=[^"]+)["]>', re.UNICODE)

        recaptchaChallengeResult = recaptchaChallengeRegex.search(htmlText)
        imgResult = imgRegex.search(htmlText)

        recaptchaChallengeId = recaptchaChallengeResult.group(1)
        imgUrl = 'http://www.google.com/recaptcha/api/' + imgResult.group(1)
        return (recaptchaChallengeId, imgUrl)

    def prepareContent(self):
        htmlText = self.downloadContent()
        parsedData = self.parseContent(htmlText)
        self.recaptchaChallengeId = parsedData[0]

        with open(Settings.captchaPath, 'wb') as imageFile:
            r = requests.get(parsedData[1])
            imageFile.write(r.content)

    def displayContent(self, invoker):
        self._contentSpace.clear_widgets()
        self._contentSpace.size_hint=(1, 1)
        self._contentSpace.size=(0,0)
        try:
            self.prepareContent()
            if not self.dateField:
                self.dateField = TextInput(multiline=False, size_hint=(1,None), size=(0,30))
            hlayoutSetDate = BoxLayout(orientation='horizontal', size_hint_y=0.2)
            hlayoutSetDate.add_widget(Button(text='Today', on_press=lambda x: self.setDate('today')))
            hlayoutSetDate.add_widget(Button(text='Tomorrow', on_press=lambda x: self.setDate('tomorrow')))
            self._contentSpace.add_widget(hlayoutSetDate)
            self._contentSpace.add_widget(self.dateField)
            self.captchaImage = Image(source=Settings.captchaPath, nocache=True)
            self._contentSpace.add_widget(Button(text='Reload', on_press=self.reloadCaptcha, size_hint_y = 0.2))
            self._contentSpace.add_widget(self.captchaImage)
            self.captchaResponse = TextInput(multiline=False, size_hint=(1,None), size=(0,30))
            self._contentSpace.add_widget(self.captchaResponse)
            self._contentSpace.add_widget(Button(text='Submit', on_press=self.postData, size_hint_y=0.3))
        except Exception, e:
            self._contentSpace.add_widget(Label(text='An error occured.'))
            MessagePopup('Error', traceback.format_exc(e))
Exemplo n.º 43
0
class DatePicker(BoxLayout,Form):
    date=ObjectProperty(date.today())
    __stereotype__ = StringProperty('widget')
    
    def on_date(self,sender,value):
        self.data['date']=self.transform_date_oerp(value)
        self.data['date_display']=self.transform_date_human(value)
        self.populate_header()
        self.populate_body()
    
    def __init__(self, *args, **kwargs):
        super(DatePicker, self).__init__(**kwargs)
        self.orientation = "vertical"
        self.month_names = (_('Enero'),
                            _('Febrero'), 
                            _('Marzo'), 
                            _('Abril'), 
                            _('Mayo'), 
                            _('Junio'), 
                            _('Julio'), 
                            _('Agosto'), 
                            _('Septiembre'), 
                            _('Octubre'),
                            _('Noviembre'),
                            _('Diciembre'))
        if kwargs.has_key("month_names"):
            self.month_names = kwargs['month_names']
        self.header = BoxLayout(orientation = 'horizontal', 
                                size_hint = (1, 0.2))
        self.body = GridLayout(cols = 7)
        self.add_widget(self.header)
        self.add_widget(self.body)

        self.populate_body()
        self.populate_header()
        if kwargs.has_key("init_vals"):
            if kwargs["init_vals"].has_key('date') and kwargs["init_vals"]['date']!='':
                self.date=datetime.strptime(kwargs["init_vals"]['date'],'%Y-%m-%d')
        self.data['date']=self.transform_date_oerp(self.date)
        self.data['date_display']=self.transform_date_human(self.date)

    def populate_header(self, *args, **kwargs):
        self.header.clear_widgets()
        previous_month = Button(text = "<")
        previous_month.bind(on_press=partial(self.move_previous_month))
        next_month = Button(text = ">")
        next_month.bind(on_press=partial(self.move_next_month))
        month_year_text = self.month_names[self.date.month -1] + ' ' + str(self.date.year)
        current_month = Label(text=month_year_text, size_hint = (2, 1))

        self.header.add_widget(previous_month)
        self.header.add_widget(current_month)
        self.header.add_widget(next_month)

    def populate_body(self, *args, **kwargs):
        self.body.clear_widgets()
        date_cursor = date(self.date.year, self.date.month, 1)
        for filler in range(date_cursor.isoweekday()-1):
            self.body.add_widget(Label(text=""))
        while date_cursor.month == self.date.month:
            date_label = Button(text = str(date_cursor.day))
            date_label.bind(on_press=partial(self.set_date,day=date_cursor.day))
            if self.date.day == date_cursor.day:
                date_label.background_normal, date_label.background_down = date_label.background_down, date_label.background_normal
            self.body.add_widget(date_label)
            date_cursor += timedelta(days = 1)

    def set_date(self, *args, **kwargs):
        self.date = date(self.date.year, self.date.month, kwargs['day'])
        self.populate_body()
        self.populate_header()

    def move_next_month(self, *args, **kwargs):
        if self.date.month == 12:
            self.date = date(self.date.year + 1, 1,min(self.date.day,calendar.monthrange(self.date.year,1)[1]) )
        else:
            self.date = date(self.date.year, self.date.month + 1,min(self.date.day,calendar.monthrange(self.date.year, self.date.month +1)[1]))
        self.populate_header()
        self.populate_body()

    def move_previous_month(self, *args, **kwargs):
        if self.date.month == 1:
            self.date = date(self.date.year - 1, 12, min(self.date.day,calendar.monthrange(self.date.year,12)[1]))
        else:
            self.date = date(self.date.year, self.date.month -1, min(self.date.day,calendar.monthrange(self.date.year, self.date.month -1)[1]))
        self.populate_header()
        self.populate_body()

    def transform_date_oerp(self, date):
        select_date = str(date.year)+'-'+str(date.month).zfill(2)+'-'+str(date.day).zfill(2)
        return select_date

    def transform_date_human(self, date):
        select_date = str(date.day).zfill(2)+'-'+str(date.month).zfill(2)+'-'+str(date.year)
        return select_date
Exemplo n.º 44
0
class LeafScreen(Screen):
  def on_pre_enter(self):
    self.clear_widgets()
    
    self.leafLayout = BoxLayout(orientation = 'vertical')
    
    self.readMode()
    #self.editMode()

    self.add_widget(self.leafLayout)

    self.win = Window
    self.win.bind(on_keyboard=self.keyboardHandler)

    self.leafLayout.bind(
          size=self._update_rect,
          pos=self._update_rect)
    with self.leafLayout.canvas.before:
      Color(0.5, 0.8, 1, 0.9) 
      self.rect = Rectangle(
                  size=self.leafLayout.size,
                  pos=self.leafLayout.pos)
  def _update_rect(self, instance, value):
    self.rect.pos = instance.pos
    self.rect.size = instance.size

  def on_pre_leave(self):
    self.win.unbind(on_keyboard=self.keyboardHandler)

  def keyboardHandler(self, window, keycode1, keycode2, text, modifiers):
    if keycode1 == systemBtnBack:
      self.back()
      return True
    return False

  def readMode(self, *args):
    self.leafLayout.clear_widgets()
    # top
    btnBack = Button(text='Back', size_hint_x=0.1)
    capture = Label(text=tree.curItem().name, size_hint_x=0.8, color = color['lblPath'])
    btnEdit = Button(text='Edit', size_hint_x=0.1)
    topLayout = BoxLayout(size_hint_y = 0.1)
    topLayout.add_widget(btnBack)
    topLayout.add_widget(capture)
    topLayout.add_widget(btnEdit)
    self.leafLayout.add_widget(topLayout) 
    btnBack.bind(on_press=self.back)

    # Content
    self.textField = TextInputForScroll(
        size_hint_y=None,
        text=tree.curItem().read(), 
        background_color = color['readLeaf'],
        readonly = True,
        focus = True)
    self.textField.on_text()
    textFieldScroll = ScrollView( bar_width = 10)
    textFieldScroll.add_widget(self.textField)

    self.leafLayout.add_widget(textFieldScroll) 

    btnEdit.bind(on_release=self.editMode)

  def editMode(self, *args):
    self.leafLayout.clear_widgets()
    # top
    btnBack = Button(text='Back', size_hint_x=0.1)
    capture = Label(text=tree.curItem().name, size_hint_x=0.8, color = color['lblPath'])
    btnSave = Button(text='Save', size_hint_x=0.1)
    topLayout = BoxLayout(size_hint_y = 0.1)
    topLayout.add_widget(btnBack)
    topLayout.add_widget(capture)
    topLayout.add_widget(btnSave)
    self.leafLayout.add_widget(topLayout) 
    btnBack.bind(on_press=self.back)

    # Content
    self.textField = TextInput(
        text=tree.curItem().read(), 
        background_color = color['editLeaf'],
        focus = True)
    self.leafLayout.add_widget(self.textField)

    btnSave.bind(on_release=self.readMode,
                on_press=self.save)

  def save(self, *args):  
    tree.curItem().write(self.textField.text)

  def back(self, *args):
    if sm.current == "leafScreen" :
      self.save()
      if not tree.reachRoot():
        tree.down()
        sm.transition = SlideTransition(direction='right')
        sm.current = 'mainScreen'
Exemplo n.º 45
0
class LunchScreen(Screen):
    def __init__(self, **kwargs):
        result = super(LunchScreen, self).__init__(**kwargs)

        layout = BoxLayout(orientation='vertical')
        backButton = Button(text='<<<', size_hint=(1, 0.1))

        scroll = ScrollView(size_hint=(1,1))
        self._contentSpace = BoxLayout(orientation='vertical')
        scroll.add_widget(self._contentSpace)

        backButton.bind(on_press=self.goBack)

        layout.add_widget(backButton)
        layout.add_widget(scroll)

        self.add_widget(layout)

        self.bind(on_enter=self.displayContent)

        return result

    def goBack(self, invoker):
        self.manager.current="Menu"

    def downloadContent(self):
        url =  'http://www.gymnaziumtrencin.sk/stravovanie/jedalny-listok.html?page_id=198'
        htmlRequest = requests.get(url)
        htmlRequest.encoding = 'utf-8'
        return htmlRequest.text

    def parseContent(self, htmlText):
        # Cut out only the data that are needed to improve performance later 
        dateRegex = re.compile('<h2>Od\s([\d]+)[.]([\d]+)[.](\d+)\sdo\s([\d]+)[.]([\d]+)[.](\d+)<\/h2>', re.UNICODE)
        cutLunchDataRegex = re.compile('<table\s+class=["]obed_menu["]\s*>(.*?)</table>', re.DOTALL | re.UNICODE)
        soupRegex = re.compile('<td\s+class=["]v_align["]\s*>(.*)<\/td>', re.UNICODE)
        mealRegex = re.compile('<td>(.*?)<\/td>', re.DOTALL | re.UNICODE)
        dateResult = dateRegex.search(htmlText)
        if not dateResult:
            #TODO: Error
            return None

        cutLunchDataResult = cutLunchDataRegex.search(htmlText, dateResult.end())
        if not cutLunchDataResult:
            #TODO: Error
            return None

        dateStart = datetime.date(day=int(dateResult.group(1)), month=int(dateResult.group(2)), year=int(dateResult.group(3)))
        dateEnd = datetime.date(day=int(dateResult.group(4)), month=int(dateResult.group(5)), year=int(dateResult.group(6)))
        cutLunchData = cutLunchDataResult.group(1)
        searchStart = 0
        lunches = []
        for i in range(5):
            soupResult = soupRegex.search(cutLunchData, searchStart)
            if not soupResult:
                #TODO: Error
                return None
            searchStart = soupResult.end()
            mealResult = mealRegex.search(cutLunchData, searchStart)
            if not mealResult:
                #TODO: Error
                return None
            searchStart = mealResult.end()

            soupText = soupResult.group(1).strip()
            mealText = mealResult.group(1).strip()
            lunches.append(Lunch(i, soupText, mealText))

        return LunchWeek(dateStart, dateEnd, lunches)
        
    def prepareContent(self):
        htmlText = self.downloadContent()
        return self.parseContent(htmlText)

    def displayContent(self, invoker):
        self._contentSpace.clear_widgets()
        self._contentSpace.size_hint=(1, 1)
        self._contentSpace.size=(0,0)
        try:
            self._contentSpace(self.prepareContent().kivy())
        except Exception, e:
            self._contentSpace.add_widget(Label(text='An error occured.'))
            MessagePopup('Error', traceback.format_exc(e))
Exemplo n.º 46
0
class ScrollBox(ScrollView):
    orientation = StringProperty("default")
    spacing = NumericProperty(10)
    padding = NumericProperty(10)
    
    def __init__(self, **kwargs):
        
        self.layout = BoxLayout() 
        
        super(ScrollBox, self).__init__(size_hint=(1,1), **kwargs)
        
          
        self.layout.height = 0 
        self.layout.width = 0
        super(ScrollBox, self).add_widget(self.layout)
        
        
    def on_orientation(self, w, val):
        if not hasattr(self, "layout"):
            return

        self.layout.orientation = val
        if val == 'vertical':
            self.layout.size_hint_y = None
            self.layout.width = self.width
        else:
            self.layout.size_hint_x = None
            self.layout.height = self.height
            
        self.update_layout_size()
        
    def on_spacing(self, w, val):
        self.layout.spacing = val
        
    def on_padding(self, w, val):
        self.layout.padding = val
        
    def add_widget(self, w, index=0):
                
        self.layout.add_widget(w, index)
        
        self.update_layout_size()
        
    def remove_widget(self, w):
                
        self.layout.remove_widget(w)
        
        self.update_layout_size()
    
    '''    
    def collide_point(self, x, y):
        print self.pos, x, y
        super(ScrollBox, self).collide_point(x, y+self.height)
    '''
    
    def update_layout_size(self):
        if self.layout.orientation == 'vertical':
            self.layout.width = self.width
            self.layout.height = self.layout.padding[0]
            self.layout.size_hint_y = None
        else:
            self.layout.height = self.height
            self.layout.width = self.layout.padding[0]
            self.layout.size_hint_x = None
        
        for i in self.layout.children:
            if self.layout.orientation == 'vertical':
                self.layout.height += i.height + self.layout.spacing
                
            else:
                self.layout.width += i.width + self.layout.spacing
                
    def on_size(self, w, val):
        self.update_layout_size()
                
    def clear(self):
        self.scroll_y = 1
        self.layout.clear_widgets()
        self.layout.width = 0
        self.layout.height = 0
Exemplo n.º 47
0
class MITMs1(Screen):
	def __init__(self,**kwargs):
		super(MITMs1,self).__init__(**kwargs)
		self.iface_name = self.ids['iface_name']
		self.device_lbl = self.ids['device_lbl']
		self.client_box = self.ids['client_box']
		self.nodes = self.ids['nodes']
		self.scan_arp_btn = self.ids['scan_arp_btn']
		self.save_results_btn = self.ids['save_results_btn']
		self.arps = [] #contain ARP's responses

	def run_ifconfig(self):
		try:
			self.scan_arp_btn.disabled = False
			self.ifconfig = check_output(['ifconfig', self.iface_name.text])
			self.iface, self.IP, self.MAC, self.Bcast, self.Nmask, self.IPv6 = \
			(self.ifconfig.split()[i] for i in (0,6,4,7,8,11))

			self.device_lbl.text = '[color=00ff00][i][b]My Device[/b][/i][/color] \n\n' +\
			'Interface: [color=00ff00][i]{0}[/i][/color] \n\n'.format(self.iface) +\
			'IP: [color=00ff00][i]{0}[/i][/color] \n\n'.format(self.IP[5:]) +\
			'IPv6: [color=00ff00][i]{0}[/i][/color] \n\n'.format(self.IPv6) +\
			'Bcast: [color=00ff00][i]{0}[/i][/color] \n\n'.format(self.Bcast[6:]) +\
			'Nmask: [color=00ff00][i]{0}[/i][/color] \n\n'.format(self.Nmask[5:]) +\
			'MAC: [color=00ff00][i]{0}[/i][/color] \n\n'.format(self.MAC)
		except:
			pass

	def ARP_scan(self):
		network_ip = '192.168.40.'
		self.nodes.clear_widgets()
		self.arps = []
		for i in range(1,255):
			scanNode = ArpScan(self.arps, self.nodes , network_ip + str(i) , self.iface)
			scanNode.start()
			print 'Thread %s'%i

	def now(self):
		now = time.localtime(time.time())
		return time.asctime(now)

	def save_results(self):
		self.box = BoxLayout(orientation = 'vertical')
		self.input_lb = TextInput(text = 'Untitled', multiline = False, on_text_validate = self.save_file)
		self.btn_lb = Button(text = 'Save Results', size_hint = (1, None), height = 50, on_release = self.save_file)

		self.box.add_widget(self.input_lb)
		self.box.add_widget(self.btn_lb)

		self.popup = Popup(content = self.box, title = 'Save Scan Results', size_hint = (.7, .7))
		self.popup.open()

	def save_file(self,obj):
		filename = self.input_lb.text
		if filename == None: return
		f = open(filename,'w')
		content = '[*] Lan Scan \n\n' + self.now() + '\n\n%s Hosts Up!'%len(self.arps) + '\n\n'
		for arp in self.arps:
			content += 'IP : %s\nMAC:%s\n\n'%(arp.psrc,arp.hwsrc)
		self.box.clear_widgets()
		try:
			f.write(content)
			self.box.add_widget(Label(text = 'File saved in : %s'%(os.getcwd() + '/' + filename)))
			self.box.add_widget(Button(text = 'Close', size_hint = (1, None), height = 50, on_release = self.popup.dismiss))
		except:
			self.box.add_widget(Label(text = 'Error while writting file : %s'%filename))
			self.box.add_widget(Button(text = 'Close', size_hint = (1, None), height = 50, on_release = self.popup.dismiss))
	@staticmethod
	def change_screen(obj):
		sm.current = 'MITMs2'
		MITMs1.itf_inform = obj.text
		MITMs1.logo = obj.background_normal
	@staticmethod
	def load_string(obj):
		obj.itf_box.clear_widgets()
		logo_3d_file = {'Image/Node/gatewayNode.png' : 'Image/3dLogo/gateSpin.zip',
				        'Image/Node/windowsNode.png' : 'Image/3dLogo/winSpin.zip',
				  		'Image/Node/appleNode.png'   : 'Image/3dLogo/appleSpin.zip',
				  		'Image/Node/androidNode.png' : 'Image/3dLogo/andSpin.zip',
				  		'Image/Node/linuxNode.png'   : 'Image/3dLogo/linuxSpin.zip',
				  		'Image/Node/unknownNode.png' : 'Image/3dLogo/unkSpin.zip'}
		logo_3d = logo_3d_file[MITMs1.logo]
		obj.itf_box.add_widget(Image(source = logo_3d, anim_delay = 1/80, pos_hint = {'x': -.4}, size_hint = (1, .2)))
		obj.itf_box.add_widget(Label(text = MITMs1.itf_inform, markup = True))
Exemplo n.º 48
0
class ScrollableButtonStack(BoxLayout):
    def __init__(self, *args, **kwargs):
        data = kwargs.get("data", [])
        if data: del(kwargs["data"])
        kwargs["orientation"] = "horizontal"
        super(ScrollableButtonStack, self).__init__(*args, **kwargs)
        self.sv = ScrollView(size_hint=(0.9,1))
        self.buttonstack = BoxLayout(orientation="vertical", size_hint=(1,None), spacing=2)
        self.sv.add_widget(self.buttonstack)
        self.add_widget(self.sv)

        self.alphaidx = {}
        self.alphabet = BoxLayout(orientation="vertical", size_hint=(0.1,1), spacing=0)
        for i in string.uppercase:
            btn = Button(text=i, size_hint=(1,1.0/len(string.uppercase)), background_color=(0,0,0,1))
            self.alphabet.add_widget(btn)
            btn.bind(on_touch_move=self.alphatouch)
            btn.bind(on_touch_down=self.alphatouch)
        self.add_widget(self.alphabet)

        self.UNIQUIFIER = 0
        self.set_data(data)

    def alphatouch(self, btn, pos):
        if btn.collide_point(*pos.pos):
            uni = self.alphaidx.get(btn.text)
            if uni:
                Clock.schedule_once(lambda x: self._scroll_to_uniquifier(uni), 0.01)

    def set_data(self, data):
        self.sv.remove_widget(self.buttonstack)
        self.buttonstack.clear_widgets()
        self.buttonstack.height = BUTTONHEIGHT * len(data)
        self.alphaidx = {}
        for i in data:
            nd = i.copy()
            nd["unique"] = self.UNIQUIFIER
            self.UNIQUIFIER += 1
            nd["open"] = False
            first = i["text"][0].upper()
            if first not in self.alphaidx:
                self.alphaidx[first] = nd["unique"]
            b = ButtonWithData(text=i["text"], size_hint_x=0.8, size_y=BUTTONHEIGHT, data=nd)
            self.buttonstack.add_widget(b)
            b.bind(on_press=self.toggle_open)
        self.sv.add_widget(self.buttonstack)

    def _get_button_at_top_uniquifier(self):
        print "gbatu"
        if not self.buttonstack.children: return None
        scrollable_height = self.buttonstack.height - self.height
        if scrollable_height < 0:
            return self.buttonstack.children[0].data["unique"]
        scrolled_px = scrollable_height * (1-self.sv.scroll_y)
        widget_idx_at_top = int(round(float(scrolled_px) / BUTTONHEIGHT))
        # but buttonstack.children is in reverse order, so
        widget_idx_at_top = len(self.buttonstack.children) - widget_idx_at_top - 1
        print "saving uniq", self.buttonstack.children[widget_idx_at_top].data["unique"]
        return self.buttonstack.children[widget_idx_at_top].data["unique"]

    def _scroll_to_uniquifier(self, uni):
        print "stu"
        if uni is None: return
        scrollable_height = self.buttonstack.height - self.height
        idx = None
        counter = 0
        for c in self.buttonstack.children:
            if c.data["unique"] == uni:
                idx = counter
                break
            counter += 1
        if idx is None:
            return
        # but buttonstack.children is in reverse order, so
        idx = len(self.buttonstack.children) - idx - 1
        scroll_position = (idx * BUTTONHEIGHT) / scrollable_height
        print "scroll to widget uni", uni, "which is idx", idx, " posn", scroll_position
        Clock.schedule_once(lambda x: self.scroll_now_to(scroll_position), 2)

    def scroll_now_to(self, scroll_position):
        print "scroll now to"
        self.sv.scroll_y = 1-scroll_position

    def toggle_open(self, button):
        print "toggling open", button, button.data
        uni = self._get_button_at_top_uniquifier()
        if button.data["open"]:
            # remove all children of this button
            print "Removing children"
            to_remove = [x for x in self.buttonstack.children 
                if x.owner_button 
                and x.owner_button.data["unique"] == button.data["unique"]]
            self.buttonstack.height -= len(to_remove) * BUTTONHEIGHT
            for w in to_remove:
                self.buttonstack.remove_widget(w)
            button.data["open"] = False
        else:
            print "Collapsing all others"
            to_remove = [x for x in self.buttonstack.children 
                if x.owner_button]
            self.buttonstack.height -= len(to_remove) * BUTTONHEIGHT
            for w in to_remove:
                self.buttonstack.remove_widget(w)
            print "Expanding"
            insert_idx = 0
            count = 0
            for w in self.buttonstack.children:
                if w.data["unique"] == button.data["unique"]:
                    insert_idx = count
                    break
                count += 1
            self.buttonstack.height += 1 * BUTTONHEIGHT
            nd = {
                "unique": "load tracks",
            }
            self.UNIQUIFIER += 1
            nbtn = ButtonWithData(text="loading...",
                size_hint_x=1, size_y=BUTTONHEIGHT, data=nd, owner_button=button)
            self.buttonstack.add_widget(nbtn, index=insert_idx)
            self.owner_app.mpc.send(("list_tracks", button.data["unique"]), 'find artist "%s"\n' % button.data["text"])
            button.data["open"] = True
        self._scroll_to_uniquifier(uni)

    def load_tracks(self, tracks):
        # remove the loading button, if present, and get its index
        loading_button = None
        counter = 0
        insert_idx = None
        for b in self.buttonstack.children:
            if b.data["unique"] == "load tracks":
                insert_idx = counter
                loading_button = b
                break
            counter += 1
        if not loading_button: return
        print "removing loading button at idx", insert_idx
        owner = loading_button.owner_button
        self.buttonstack.remove_widget(loading_button)
        for t in tracks:
            nd = {
                "unique": self.UNIQUIFIER,
            }
            nd.update(t)
            self.UNIQUIFIER += 1
            nbtn = ButtonWithData(text=t.get("Title", t.get("file")),
                size_hint_x=0.8, pos_hint={'right':1.0}, size_y=BUTTONHEIGHT, data=nd, owner_button=owner)
            nbtn.bind(on_press=self.queue_song)
            self.buttonstack.add_widget(nbtn, index=insert_idx)

    def queue_song(self, button):
        print "queueing song", button.data
        self.owner_app.mpc.send("add", 'add "%s"\n' % button.data["file"])
        self.owner_app.mpc.send("play", "play\n")
Exemplo n.º 49
0
class HexTap(App):
    def __init__(self, **kwargs):
        super(HexTap, self).__init__(**kwargs)
        self.difficulty = 1
        self.first_run = True
        self.current_state = 'mainMenu'
        self.content = BoxLayout()
        self.main_menu = MainMenu()
        self.help_menu = HelpMenu()
        self.game_map = None
        self.content.add_widget(self.main_menu)
        self.music = SoundLoader.load('assets/audio/music.ogg')
        self.soundsOption = True
        self.musicOption = False
        self.hardcoreOption = False

    def safe_options_loading(self):
        if type(self.soundsOption) == bool or type(self.soundsOption) == int:
            pass
        elif self.soundsOption == 'True' or '1' in self.soundsOption:
            self.soundsOption = True
        else:
            self.soundsOption = False
        if type(self.musicOption) == bool or type(self.musicOption) == int:
            pass
        elif self.musicOption == 'True' or '1' in self.musicOption:
            self.musicOption = True
        else:
            self.musicOption = False
        if type(self.hardcoreOption) == bool or type(self.hardcoreOption) == int:
            pass
        elif self.hardcoreOption == 'True' or '1' in self.hardcoreOption:
            self.hardcoreOption = True
        else:
            self.hardcoreOption = False

    def build(self):
        self.use_kivy_settings = False
        self.soundsOption = self.config.get('sound', 'soundsOption')
        self.musicOption = self.config.get('sound', 'musicOption')
        self.hardcoreOption = self.config.get('game', 'hardcoreOption')
        self.safe_options_loading()
        Clock.schedule_interval(self.update, 1. / 1.5)
        return self.content

    def show_help(self):
        self.content.clear_widgets()
        self.content.add_widget(self.help_menu)

    def generate_main_menu(self):
        self.content.clear_widgets()
        self.content.add_widget(self.main_menu)

    def new_game(self):
        if use_ads:
            revmob.show_popup()
        self.content.clear_widgets()
        self.content.add_widget(Image(source='assets/graphics/ui/loading.png', size=Window.size, allow_stretch=True))
        Clock.schedule_once(self.post_splash)

    def post_splash(self, dt):
        rows, cols = map_sizes[self.difficulty-1]
        self.game_map = MapCanvas(cols, rows, self.difficulty, self.hardcoreOption, self.soundsOption,
                                  self.musicOption)
        self.content.clear_widgets()
        self.content.add_widget(self.game_map)

    def update(self, dt):
        if self.main_menu.start_game:
            self.new_game()
            self.main_menu.start_game = False
        if self.main_menu.show_help:
            self.show_help()
            self.main_menu.show_help = False
        if self.help_menu.back_to_main:
            self.generate_main_menu()
            self.help_menu.back_to_main = False
        if self.game_map and self.game_map.return_to_menu:
            self.generate_main_menu()
            self.game_map.return_to_menu = False
        if self.musicOption and self.music.state == 'stop':
            self.music.play()
        elif not self.musicOption and self.music.state == 'play':
            self.music.stop()

    def build_config(self, config):
        try:
            config.setdefaults('sound', {
                'musicOption': '0',
                'soundsOption': '1'
            })
            config.setdefaults('game', {
                'hardcoreOption': '0'
            })
        except TypeError:
            config.setdefaults('sound', {
                'musicOption': False,
                'soundsOption': True
            })
            config.setdefaults('game', {
                'hardcoreOption': False
            })

    def build_settings(self, settings):
        settings.add_json_panel('hexTap options', self.config, data=settings_json)

    def on_config_change(self, config, section, key, value):
        if key == 'musicOption':
            if type(value) == bool or type(value) == int:
                self.musicOption = value
            elif value == 'True' or '1' in value:
                self.musicOption = True
            else:
                self.musicOption = False
        elif key == 'soundsOption':
            if type(value) == bool or type(value) == int:
                self.soundsOption = value
            elif value == 'True' or '1' in value:
                self.soundsOption = True
            else:
                self.soundsOption = False
        elif key == 'hardcoreOption':
            if type(value) == bool or type(value) == int:
                self.hardcoreOption = value
            elif value == 'True' or '1' in value:
                self.hardcoreOption = True
            else:
                self.hardcoreOption = False

    def on_pause(self):
        return True

    def on_resume(self):
        pass
Exemplo n.º 50
0
class RemoteControlUI(BoxLayout):
    """The main app layout
    """

    # Auth properties
    login = StringProperty(u'')
    password = StringProperty(u'')
    host = StringProperty('')

    # Represents the last command which was accepted
    last_accepted_command = StringProperty('')

    # Bound to the "Info" label
    info_text = StringProperty('')

    # Command execution confirmation flag
    need_confirm = BooleanProperty(True)

    def __init__(self, **kwargs):
        # ID of the command being executed
        self._cmd_id = None

        # List of the "completed" statuses.
        # The first status should be "Done"
        self._completed = []

        # If True - sends a request to retrieve a command status
        self._wait_completion = False

        # requested command
        self._command = (0, '')

        super(RemoteControlUI, self).__init__(
            orientation='vertical', spacing=2, padding=3, **kwargs)

        # Control buttons panel
        pnl_controls = BoxLayout(size_hint_y=None, height=metrics.dp(35))
        pnl_controls.add_widget(
            Button(text='Refresh', on_release=self._get_commands))
        pnl_controls.add_widget(
            Button(text='Close', on_release=App.get_running_app().stop))
        self.add_widget(pnl_controls)

        # Command buttons panel
        self._pnl_commands = BoxLayout(orientation='vertical')
        self.add_widget(self._pnl_commands)

        # Info panel
        lbl_info = Label(
            text=self.info_text, size_hint_y=None, height=metrics.dp(35))
        self.bind(info_text=lbl_info.setter('text'))
        self.add_widget(lbl_info)

    # ============= HTTP REQUEST ==============
    def _get_auth(self):
        # Encodes basic authorization data
        cred = ('%s:%s' % (self.login, self.password))
        return 'Basic %s' %\
               base64.b64encode(cred.encode('ascii')).decode('ascii')

    def _send_request(self, url, success=None, error=None, params=None):
        headers = {
            'User-Agent': 'Mozilla/5.0',
            'Content-type': 'application/json',
            'Authorization': self._get_auth()
        }

        UrlRequest(
            url=self.host + url, timeout=30, req_headers=headers,
            req_body=None if params is None else dumps(params),
            on_success=success, on_error=error, on_failure=error)

    # =========== GET COMMAND LIST ===========
    def _get_commands(self, instance=None):
        # Implements API-call "Get available command list"
        self._progress_start('Trying to get command list')
        self._send_request(
            'commands_available/', params=[],
            success=self._get_commands_result, error=self._get_commands_error)

    def _get_commands_result(self, request, response):
        # Parses API-call response
        try:
            self._pnl_commands.clear_widgets()

            # Create command buttons
            for code, command in sorted(
                    response['commands'].items(),
                    key=lambda x: int(x[0])):
                btn = Button(
                    id=code, text=command, on_release=self._btn_command_click)
                self._pnl_commands.add_widget(btn)

            self._completed = response['completed']

            # Save correct host and login in the app configuration
            App.get_running_app().config.set('auth', 'login', self.login)
            App.get_running_app().config.set('auth', 'host', self.host)

            self._progress_complete('Command list received successfully')
        except Exception as e:
            self._get_commands_error(request, str(e))

    def _get_commands_error(self, request, error):
        self._progress_complete()
        XError(text=str(error)[:256], buttons=['Retry', 'Re-enter', 'Exit'],
               on_dismiss=self._get_commands_error_dismiss)

    def _get_commands_error_dismiss(self, instance):
        if instance.button_pressed == 'Exit':
            App.get_running_app().stop()
        elif instance.button_pressed == 'Re-enter':
            self._login()
        elif instance.button_pressed == 'Retry':
            self._get_commands()

    # ============= SEND COMMAND =============
    def _btn_command_click(self, button):
        self._command = (button.id, button.text)
        if self.need_confirm:
            XConfirmation(
                text='Send command "%s" ?' % button.text,
                on_dismiss=self._send_command)
        else:
            self._send_command(None)

    def _send_command(self, instance):
        # Implements API-call "Create command"
        if instance and not instance.is_confirmed():
            return

        self._cmd_id = None
        self._wait_completion = True
        self._progress_start('Processing command "%s"' % self._command[1])
        self._send_request(
            'commands/', params={'code': self._command[0]},
            success=self._send_command_result, error=self._send_command_error)

    def _send_command_result(self, request, response):
        # Parses API-call response
        try:
            if response['status'] not in self._completed:
                # Executing in progress
                self._cmd_id = response['id']
                if self._wait_completion:
                    Clock.schedule_once(self._get_status, 1)
            else:
                # Command "completed"
                if response['status'] == self._completed[0]:
                    self.last_accepted_command = response['code_dsp']
                self._progress_complete(
                    'Command "%s" is %s' %
                    (response['code_dsp'], response['status_dsp']))
        except Exception as e:
            XError(text=str(e)[:256])

    def _send_command_error(self, request, error):
        self._progress_complete()
        XError(text=str(error)[:256])

    # ========== GET COMMAND STATUS ==========
    def _get_status(self, pdt=None):
        # Implements API-call "Get command status"
        if not self._cmd_id:
            return

        self._send_request(
            'commands/%s/' % self._cmd_id, success=self._send_command_result,
            error=self._send_command_error)

    # ============= LOGIN POPUP ==============
    def _login(self):
        AuthEx(login=self.login, password=self.password, host=self.host,
               autologin=None, pos_hint={'top': 0.99},
               on_dismiss=self._login_dismiss)

    def _login_dismiss(self, instance):
        if instance.is_canceled():
            App.get_running_app().stop()
            return

        self.login = instance.get_value('login')
        self.password = instance.get_value('password')
        self.host = instance.get_value('host')

        self._get_commands()

    # ============= PROGRESS BAR ==============
    def _progress_start(self, text):
        self.popup = XProgress(
            title='RemoteControl', text=text, buttons=['Close'],
            on_dismiss=self._progress_dismiss)
        self.popup.autoprogress()

    def _progress_dismiss(self, instance):
        self._wait_completion = False

    def _progress_complete(self, text=''):
        if self.popup is not None:
            self.popup.complete(text=text, show_time=0 if text is None else 1)

    # =========================================
    def on_last_accepted_command(self, instance, value):
        self.info_text = 'Last accepted command: %s' % value
        App.get_running_app().config.set(
            'common', 'last_accepted_command', value)

    def start(self):
        if not self.login or not self.password or not self.host:
            self._login()
        else:
            self._get_commands()
class KiPyKeyboard( BoxLayout ) :
    
    def __init__( self, handlerfoo, plotfoo ) :
        BoxLayout.__init__( self, orientation="vertical" )
        inp = BoxLayout( orientation="horizontal" )
        inp.padding = 1
        self.current = TextInput( text=u"" )
        self.current.font_name = FONT_NAME
        self.current.font_size = FONT_SIZE
        self.current.size_hint = 0.85, 1

        inp.add_widget( self.current )
        btnExec = Button( text="Exec()" )
        btnExec.font_name = FONT_NAME
        btnExec.font_size = FONT_SIZE
        btnExec.bind( on_press=handlerfoo )
        btnPlot = Button( text="Plot!" )
        btnPlot.font_name = FONT_NAME
        btnPlot.font_size = FONT_SIZE
        btnPlot.bind( on_press=plotfoo )
        b = BoxLayout( orientation="vertical" )
        b.add_widget( btnExec )
        b.add_widget( btnPlot )
        b.size_hint = 0.25, 1
        inp.add_widget( b )
        
        self.static_keys = BoxLayout( orientation="vertical" )
        self.loadStaticKeys()

        self.numpad = GridLayout( cols=4 )
        self.loadNumpad()
        self.numpad.size_hint = 0.6, 1

        self.symbols = GridLayout( cols=4 )
        self.loadSymbols()
        self.symbols.size_hint = 0.6, 1
         
        self.foo1 = GridLayout( cols=2 )
        self.loadFoo1()
        self.foo1.size_hint = 0.4, 1

        self.foo2 = GridLayout( cols=2 )
        self.loadFoo2()
        self.foo2.size_hint = 0.4, 1

        self.kb = BoxLayout( orientation="horizontal" )
        self.kb.size_hit = 1, 0.33
        self.static_keys.size_hit = 1, 0.33
        inp.size_hint = 1, 0.6
        self.add_widget( inp )
        self.add_widget( self.static_keys )
        self.add_widget( self.kb )
        self.shiftCount = -1
        self.onShift()

    def loadStaticKeys( self ) :
        k1 = "<- space tab \\n ->".split( " " )
        k2 = "{ [ ( , ) ] }".split( " " )
        k3 = "evalf ans print undo clear shift".split( " " )
        k4 = "+ - * / ** =".split( " " ) + [ u"√" ]
        default_keys = ( k1, k2, k3, k4 )

        for keySet in default_keys :
            k = BoxLayout( orientation="horizontal" )
            loadButtonsFromString( k, keySet, self.onBtnPress )
            self.static_keys.add_widget( k )

    def loadNumpad( self ) :
        keySet = "1 2 3 4 5 6 7 8 9 0 . I E".split( " " ) + [ u"π", "10**", "E**" ] 
        loadButtonsFromString( self.numpad, keySet, self.onBtnPress )

    def loadSymbols( self ) :
        keySet = "x y z t T w a b c d f g k . I E".split( " " ) 
        loadButtonsFromString( self.symbols, keySet, self.onBtnPress )

    def loadFoo1( self ) :
        keySet = "cos sin tan Ln Log diff".split( " " )
        loadButtonsFromString( self.foo1, keySet, self.onBtnPress )

    def loadFoo2( self ) :
        keySet = "aCos aSin aTan aTan2 Lim".split( " " ) + [ u"∫" ]
        loadButtonsFromString( self.foo2, keySet, self.onBtnPress )

    def onShift( self ) :
        self.shiftCount += 1
        if self.shiftCount == 2 : self.shiftCount = 0 
        self.kb.clear_widgets()

        if self.shiftCount == 0 : 
            self.kb.add_widget( self.foo1 )
            self.kb.add_widget( self.numpad )
        elif self.shiftCount == 1 : 
            self.kb.add_widget( self.foo2 )
            self.kb.add_widget( self.symbols )

    def onBtnPress( self, instance ) :
        command = instance.text
        toInsert = ""

        if   command == u"√" :    toInsert = "sqrt( ans )"
        elif command == u"∫" :    toInsert = "integrate( ans, x )"
        elif command == "diff" :  toInsert = "diff( ans, x )"
        elif command == "cos" :   toInsert = "cos( ans )"
        elif command == "aCos" :  toInsert = "acos( ans )"
        elif command == "sin" :   toInsert = "sin( ans )"
        elif command == "aSin" :  toInsert = "asin( ans )"
        elif command == "tan" :   toInsert = "tan( ans )"
        elif command == "aTan" :  toInsert = "atan( ans )"
        elif command == "aTan2" : toInsert = "atan2( ans )"
        elif command == "coTan" : toInsert = "cot( ans )"
        elif command == "Lim" : toInsert = "limit( ans, x, n )"
        elif command == "Log" :   toInsert = "log( ans )"
        elif command == "Ln" :   toInsert = "ln( ans )"
        elif command == "evalf" : toInsert = "evalf()"
        elif command == u"π" :    toInsert = "pi"
        elif command == "clear" : self.current.text = u""
        elif command == "space" : toInsert = " "
        elif command == "shift" : self.onShift()
        elif command == "\\n" :   toInsert = "\n"
        elif command == "tab" :   toInsert = "    "
        elif command == "\\t" :   toInsert = "    "
        elif command == "print" : toInsert = "pprint( ans )"
        elif command == "<-" :    self.current.do_cursor_movement( 'cursor_left' )
        elif command == "->" :    self.current.do_cursor_movement( 'cursor_right' )
        elif command == "undo" :  self.current.do_undo()
        #all the rest...
        else : 
            toInsert = command
        self.current.insert_text( toInsert )

    def flush( self ) : 
        self.current.text = ""
Exemplo n.º 52
0
class MakeTable(BoxLayout):
    def appeandtotable(self, output, server, table):
        for line in output.splitlines():
            # print(type(line))
            line = line.decode("utf-8")
            if line.startswith(' ica-cgp#'):
                for i in range(30, 1, -1):
                    line = line.replace(" " * i, "|")
                if line[-1:] == "|":
                    line = line + server
                else:
                    line = line + "|" + server
                cells = line.split("|")
                # print(line)
                table.append(cells)

    # Launches a dialog box for confirming you want to kill a session.
    def confirmkillsession(self, instance):
        data = instance.__name__

        ConfirmPopup(self.killsession,
                     text='Do You Want To Kill This Session?',
                     title="Kill Session?",
                     data=data)

    # Kills a windows user session based on the ID
    def killsession(self, session):
        data = session.split("|")
        command = ("LOGOFF {} /server:{}").format(data[0], data[1])
        # print(command)
        os.system(command)
        self.__init__()

    # Refreshes the list of users
    def refreshsession(self, instance):
        instance.text = "Refreshing"

        df = self.filldata(self.txtservers.text)

        self.databox.clear_widgets()

        for index, row in df.iterrows():
            if row['SERVER'] is not None:
                grid = GridLayout()
                grid.cols = 3
                btnkill = Button(text="Kill Session: {}".format(row['ID']))
                btnkill.__name__ = "{}|{}".format(row['ID'], row['SERVER'])
                btnkill.bind(on_press=self.confirmkillsession)
                grid.add_widget(btnkill)
                lbluser = Label(text=row['USERNAME'])
                grid.add_widget(lbluser)
                lblserver = Label(text=row['SERVER'])
                grid.add_widget(lblserver)
                self.databox.add_widget(grid)

        instance.text = "Refresh"
        print("Refresh")

    # Gets the data from a windows QWINSTA command
    def filldata(self, svrs):
        if len(svrs) > 0:
            print(svrs)
            servers = svrs.split(" ")
            table = []
            for server in servers:
                try:
                    output = subprocess.check_output(
                        "QWINSTA /server:{}".format(server), shell=False)
                    self.appeandtotable(output, server, table)
                except:
                    print("Server: {} - Does Not Exists".format(server))
            if len(table) > 0:
                df = pandas.DataFrame(table)
                new_header = [
                    "SESSIONAME", "USERNAME", "ID", "STATE", "TYPE", "SERVER"
                ]
                df.columns = new_header  # set the header row as the df header
                df = df.sort_values(['USERNAME', "ID", 'SERVER'])
                # print(df)
                return df
            else:
                df = pandas.DataFrame()
                return df
        else:
            df = pandas.DataFrame()
            return df

    # Application Init
    def __init__(self, **kwargs):
        super(MakeTable, self).__init__(**kwargs)

        self.clear_widgets()
        self.orientation = 'vertical'

        header = BoxLayout()
        header.orientation = 'vertical'

        servergrid = GridLayout()
        servergrid.cols = 3
        lblservers = Label(text="Servers: ")
        servergrid.add_widget(lblservers)
        self.txtservers = TextInput(text='', multiline=True)
        servergrid.add_widget(self.txtservers)
        header.add_widget(servergrid)

        # Loads server names from a file if it exists
        fname = "servers.txt"
        if os.path.isfile(fname):
            with open(fname) as f:
                content = f.readlines()
            content = [x.strip() for x in content]
            self.txtservers.text = " ".join(content)
        else:
            print("No Servers File Found")

        btnrefresh = Button(text="Refresh")
        btnrefresh.id = "btnRefresh"
        btnrefresh.bind(on_press=self.refreshsession)
        header.add_widget(btnrefresh)

        self.add_widget(header)

        self.databox = BoxLayout()
        self.databox.clear_widgets()
        self.databox.orientation = 'vertical'

        self.add_widget(self.databox)

        self.refreshsession(self)
Exemplo n.º 53
0
class GameScreenView( BoxLayout ):
    game = None
    startingButton = None
    leftPane = None
    rightPane = None

    def __init__(self, **kwargs):
        super().__init__(cols=2,**kwargs)
        self.leftPane = BoxLayout()
        self.rightPane = BoxLayout(orientation='vertical')
        self.add_widget(self.leftPane)
        self.add_widget(self.rightPane)

    def draw(self):
        self.game = self.parent.game
        self.size = self.parent.size
        self.drawShipPlacementArea()
        self.drawShipPort()

    def addWidgetToGameScreenViewLeft(self, widgetToAdd):
        self.leftPane.add_widget( widgetToAdd )

    def addWidgetToGameScreenViewRight(self, widgetToAdd):
        self.rightPane.add_widget( widgetToAdd )

    def removeWidgetFromGameScreenView(self, widgetToRemove):
        if widgetToRemove in self.rightPane.children:
            self.rightPane.remove_widget( widgetToRemove )
        if widgetToRemove in self.leftPane.children:
            self.leftPane.remove_widget( widgetToRemove )

    def drawShipPlacementArea(self):
        self.game.shipPlacementArea = GridArea()
        self.game.activeArea = self.game.shipPlacementArea
        self.addWidgetToGameScreenViewLeft( self.game.shipPlacementArea )
        self.game.shipPlacementArea.draw(1)

    def drawOwnShipGridArea(self):
        self.game.ownShipGridArea = GridArea()
        self.addWidgetToGameScreenViewRight( self.game.ownShipGridArea )
        self.game.ownShipGridArea.draw(2)

    def drawEnemyShipGridArea(self):
        self.game.enemyShipGridArea = GridArea()
        self.addWidgetToGameScreenViewLeft( self.game.enemyShipGridArea )
        self.game.enemyShipGridArea.draw(1)

    def drawShipPort(self):
        self.game.shipPort = ShipPort(game=self.game)
        self.addWidgetToGameScreenViewRight( self.game.shipPort )
        self.game.shipPort.draw()

    def drawStartingButton(self):
        self.startingButton = Button(text='ALUSTA MÄNGU!')
        self.startingButton.bind(on_press=self.game.startBattle)
        self.addWidgetToGameScreenViewRight( self.startingButton )

    def drawGameOverText(self, youWon):
        self.rightPane.clear_widgets()
        print(youWon)
        if youWon == True:
            text = 'MÄNG LÄBI !!! VÕITSID !'
        else:
            text = "MÄNG LÄBI !!! Kaotasid.... :'("
        self.addWidgetToGameScreenViewRight( Label(font_size='40sp',text=text) )

    def removeShipPort(self):
        self.removeWidgetFromGameScreenView( self.game.shipPort )
Exemplo n.º 54
0
class DatePicker(BoxLayout):
    def __init__(self, *args, **kwargs):
        super(DatePicker, self).__init__(**kwargs)
        self.date = date.today()
        self.orientation = "vertical"
        self.month_names = ('Январь',
                            'Февраль',
                            'Март',
                            'Апрель',
                            'Май',
                            'Июнь',
                            'Июль',
                            'Август',
                            'Сентябрь',
                            'Октябрь',
                            'Ноябрь',
                            'Декабрь')
        if"month_names" in kwargs:
            self.month_names = kwargs['month_names']
        self.header = BoxLayout(orientation='horizontal',
                                size_hint=(1, 0.2))
        self.body = GridLayout(cols=7)
        self.add_widget(self.header)
        self.add_widget(self.body)

        self.populate_body()
        self.populate_header()

    def populate_header(self, *args, **kwargs):
        self.header.clear_widgets()
        previous_month = Button(text="<")
        previous_month.bind(on_press=partial(self.move_previous_month))
        next_month = Button(text=">")
        next_month.bind(on_press=partial(self.move_next_month))
        month_year_text = self.month_names[self.date.month - 1] + ' ' + str(self.date.year)
        current_month = Label(text=month_year_text, size_hint=(2, 1))

        self.header.add_widget(previous_month)
        self.header.add_widget(current_month)
        self.header.add_widget(next_month)

    def populate_body(self, *args, **kwargs):
        self.body.clear_widgets()
        date_cursor = date(self.date.year, self.date.month, 1)
        for filler in range(date_cursor.isoweekday() - 1):
            self.body.add_widget(Label(text=""))
        while date_cursor.month == self.date.month:
            date_label = Button(text=str(date_cursor.day))
            date_label.bind(on_press=partial(self.set_date,
                                             day=date_cursor.day))
            if self.date.day == date_cursor.day:
                date_label.background_normal, \
                    date_label.background_down = date_label.background_down, date_label.background_normal
            self.body.add_widget(date_label)
            date_cursor += timedelta(days=1)

    def set_date(self, *args, **kwargs):
        self.date = date(self.date.year, self.date.month, kwargs['day'])
        self.populate_body()
        self.populate_header()

    def move_next_month(self, *args, **kwargs):
        if self.date.month == 12:
            self.date = date(self.date.year + 1, 1, self.date.day)
        else:
            self.date = date(self.date.year, self.date.month + 1,
                             min(self.date.day, calendar.monthrange(self.date.year, self.date.month + 1)[1]))
        self.populate_header()
        self.populate_body()

    def move_previous_month(self, *args, **kwargs):
        if self.date.month == 1:
            self.date = date(self.date.year - 1, 12, self.date.day)
        else:
            self.date = date(self.date.year, self.date.month - 1,
                             min(self.date.day, calendar.monthrange(self.date.year, self.date.month - 1)[1]))
        self.populate_header()
        self.populate_body()
Exemplo n.º 55
0
class Downloads(BoxLayout):
    def __init__(self, **kwargs):
        super(Downloads, self).__init__(**kwargs)
        user_interface.ui.ids.documentCounter.text = str(len(download_identifiers))
        del download_buttons[:]
        if len(download_identifiers) != 0:
            self.layout = BoxLayout(orientation='vertical')
            for i in range(0, len(download_identifiers)):
                layout1 = BoxLayout()
                label = Label(text=download_identifiers[i])
                button = Button(text="remove")
                button.bind(on_press=self.remove)
                download_buttons.append(button)
                layout1.add_widget(label)
                layout1.add_widget(button)
                self.layout.add_widget(layout1)

            download_btn = Button(text="download")
            download_btn.bind(on_press=self.download)
            self.layout.add_widget(download_btn)
            self.add_widget(self.layout)

    def download(self, instance):
        prs = Presentation('template.pptx')
        # Left, top, width, height
        for i in range(0, len(download_identifiers)):
            if i == 0 or i % 2 == 1:
                slide = prs.slides[-1]
            else:
                slide = prs.slides.add_slide(prs.slide_layouts[1])
            # Details
            if i % 2 == 1:
                tx_box1 = slide.shapes.add_textbox(Inches(5.2), Inches(5.5), Inches(4.5), Inches(2))
            else:
                tx_box1 = slide.shapes.add_textbox(Inches(0.5), Inches(5.5), Inches(4.5), Inches(2))
            tf1 = tx_box1.text_frame
            tf1.word_wrap = True
            run = tf1.paragraphs[0].add_run()
            run.text = download_details[i]
            run.font.size = Pt(14)
            # Stats
            if i % 2 == 1:
                tx_box2 = slide.shapes.add_textbox(Inches(5.2), Inches(4.2), Inches(4.5), Inches(2))
            else:
                tx_box2 = slide.shapes.add_textbox(Inches(0.5), Inches(4.2), Inches(4.5), Inches(2))
            tf2 = tx_box2.text_frame
            tf2.word_wrap = True
            run = tf2.paragraphs[0].add_run()
            run.text = download_stats[i]
            run.font.size = Pt(14)
            # Graph
            if i % 2 == 1:
                slide.shapes.add_picture(download_images[i], Inches(4.8), Inches(1.2), height=Inches(3.0), width=Inches(5.0))
            else:
                slide.shapes.add_picture(download_images[i], Inches(0.1), Inches(1.2), height=Inches(3.0), width=Inches(5.0))

        date = datetime.datetime.now().strftime("%m-%d-%Y")
        prs.save(PATH[:-8] + "\\output\\" + date + '.pptx')
        del download_identifiers[:]

        del download_images[:]
        del download_details[:]
        del download_stats[:]
        self.update()

    # update the downloads shown
    def update(self):
        self.layout.clear_widgets()
        user_interface.ui.ids.documentCounter.text = str(len(download_identifiers))
        if len(download_identifiers) != 0:
            for i in range(0, len(download_identifiers)):
                layout1 = BoxLayout()
                label = Label(text=download_identifiers[i])
                button = Button(text="remove")
                button.bind(on_press=self.remove)
                download_buttons.append(button)
                layout1.add_widget(label)
                layout1.add_widget(button)
                self.layout.add_widget(layout1)

            download_btn = Button(text="download")
            download_btn.bind(on_press=self.download)
            self.layout.add_widget(download_btn)

    # remove the specific download shown
    def remove(self, instance):
        for i in range(0, len(download_identifiers)):
            if download_buttons[i] == instance:
                del download_identifiers[i]
                del download_details[i]
                del download_stats[i]
                del download_images[i]
                del download_buttons[:]
                break
        self.update()
Exemplo n.º 56
0
class PongGame(Widget):
    ball = ObjectProperty(None)
    player1 = ObjectProperty(None)
    player2 = ObjectProperty(None)
    who_wins = StringProperty("")
    is_menu = StringProperty("No menu")
    #def __init__(self, **kwargs):
    #    super(PongGame, self).__init__(**kwargs)
    #    self.menu = None


    def serve_ball(self, vel = (4, 0)):
        self.ball.center = self.center
        self.ball.velocity = vel

    def the_menu(self):
        self.ball.velocity = 0, 0
        self.menu = BoxLayout(orientation = "vertical", center_x = self.center_x, center_y = self.center_y)
        lbl = Label(text = "menu")
        self.menu.add_widget(lbl)
        btn1 = Button(text = "Restart", on_press = self.the_resume)
        btn1.bind(on_press = self.the_resume)
        btn2 = Button(text = "Exit", on_press = self.get_out)
        self.menu.add_widget(btn1)
        self.menu.add_widget(btn2)
        self.add_widget(self.menu)

    def the_resume(self, instance):  
        self.who_wins = ""
        self.player2.score = 0
        self.player1.score = 0
        self.menu.clear_widgets() #this is not working 
        self.remove_widget(self.menu) #Neither is this
        self.is_menu = "No menu"
        if self.who_wins == "Player 2 wins":
            vel = (-4, 0)
        else:
            vel = (4, 0)
        self.serve_ball(vel)

    def get_out(self, instance):
        exit()
            

    def update(self, dt):
        self.ball.move()

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

        if (self.ball.y < 0) or (self.ball.top > self.height):
            self.ball.velocity_y *= -1
        
        if self.ball.x < self.x:
            self.player2.score += 1
            self.serve_ball(vel = (4, 0))
        if self.ball.x > self.width:
            self.player1.score += 1
            self.serve_ball(vel = (-4, 0))

        if self.who_wins == "":
            if self.player2.score >= 1:
                self.who_wins = "Player 2 wins"
            elif self.player1.score >= 10:
                self.who_wins = "Player 1 wins"
        elif  self.is_menu == "No menu":
            self.is_menu = "menu"
            self.the_menu()

    def on_touch_move(self, touch):
        if touch.x < self.width / 3:
            self.player1.center_y = touch.y
        if touch.x > self.width - self.width / 3:
            self.player2.center_y = touch.y
Exemplo n.º 57
0
class TimetableScreen(Screen):
    def __init__(self, **kwargs):
        result = super(TimetableScreen, self).__init__(**kwargs)

        layout = BoxLayout(orientation='vertical')
        backButton = Button(text='<<<', size_hint=(1, 0.1))

        scroll = ScrollView(size_hint=(1,1))
        self._contentSpace = BoxLayout(orientation='vertical')
        scroll.add_widget(self._contentSpace)

        backButton.bind(on_press=self.goBack)

        layout.add_widget(backButton)
        layout.add_widget(scroll)

        self.add_widget(layout)

        self.bind(on_enter=self.displayContent)

        return result

    def goBack(self, invoker):
        self.manager.current="Menu"

    def downloadContent(self):
        # First we need to find correct content according to settings
        url = 'http://www.glstn.sk/rozvrh/' + School.timetables[School.classes.index(Settings.schoolClass)]
        htmlRequest = requests.get(url)
        htmlRequest.encoding = 'windows-1250'
        return htmlRequest.text

    def parseContent(self, htmlText):
        findRegex = re.compile(ur'["][*].*[*](?:[\r\n]*[^"]*)*["]', re.UNICODE)

        # 1. part: Between stars [*]
        # Capture day and hour (optionaly range of hours in format digit-digit) that are separated by :
        # 2. part:
        # Resolve if this is one subject or list. This is done by searching for = sign
        # 3. part
        # Capture last name of teacher
        singleRegex = re.compile('[*]\s*(\w*)\s*:\s*(\d)-{0,1}(\d){0,1}\s*[*][\r\n]{1,2}.*=\s*(?:[\w.]+\s+)*(\w+)', re.UNICODE)
        # This is run after singleRegex matched, because the information doesn't contain subject
        # It should be run from last match position of singleRegex and search for first occurence
        # as that will be correct subject for that timetable item
        singleSubjectRegex = re.compile('class=["]Predmet["]\s*title=["]([^"=\s]*)[^"]*["]', re.UNICODE)
        # Same as above but searches for classroom
        singleClassRegex = re.compile('class=["]Ucebna["]\s*title=["]([^"=\s]*)[^"]*["]', re.UNICODE)
        # 1. part:
        # Same as before
        # 2. part:
        # Skip all empty lines before 3. part
        # 3. part:
        # Capture all non-empty lines
        listRegex = re.compile('[*]\s*(\w*)\s*:\s*(\d)-{0,1}(\d){0,1}\s*[*](?:[\r\n]{1,2}\s*)*((?:.+[\r\n]{0,2})+)', re.UNICODE)
        # 1. part:
        # Skip subject group and capture subject in 2nd column, teacher in 3rd column and clasroom in 4th column
        listLineRegex = re.compile('[^\s]*\s*([^\s]*)\s*([^\s]*)\s*([^\s]*)', re.UNICODE)

        # Now match each item with singleRegex. If failed, try listRegex. If failed, the timetable place is empty
        day = ''
        startHour = 0
        endHour = 0
        subject = ''
        classroom = ''
        teacher = ''
        content = []
        for item in findRegex.finditer(htmlText):
            # Remove quotes from result
            itemText = item.group()[1:-1].strip()
            singleResult = singleRegex.match(itemText)
            if singleResult:
                day = singleResult.group(1)
                startHour = int(singleResult.group(2))
                endHour = int(singleResult.group(3)) if singleResult.group(3) else None
                teacher = singleResult.group(4)
                subjectResult = singleSubjectRegex.search(htmlText, item.end())
                classResult = singleClassRegex.search(htmlText, subjectResult.end())
                subject = subjectResult.group(1)
                classroom = classResult.group(1)
                content.append(TimetableItem(day, startHour, endHour, subject, classroom, teacher))
            else:
                listResult = listRegex.match(itemText)
                if listResult:
                    day = listResult.group(1)
                    startHour = int(listResult.group(2))
                    endHour = int(listResult.group(3)) if listResult.group(3) else None
                    for line in listResult.group(4).splitlines():
                        lineResult = listLineRegex.match(line.strip())
                        subject = lineResult.group(1).strip()
                        teacher = lineResult.group(2)
                        classroom = lineResult.group(3)
                        content.append(TimetableItem(day, startHour, endHour, subject, classroom, teacher))

        return content

    def prepareContent(self):
        htmlText = self.downloadContent()
        return self.parseContent(htmlText)

    def filterBy(self, content, rule):
        filteredContent = []
        for item in content:
            if rule(item):
                filteredContent.append(item)

        return filteredContent

    def prepareHeader(self):
        hlayout = BoxLayout(orientation='horizontal', size_hint_y=0.1)
        for i in range(10):
            hlayout.add_widget(Button(text=unicode(i), background_color=(0.1,0.8,0.3,1), disabled=True))
        return hlayout

    def prepareHour(self, content, hour):
        vlayout = BoxLayout(orientation='vertical')
        itemsInHour = self.filterBy(content, lambda x: x.hourStart == hour)
        for x in itemsInHour:
            vlayout.add_widget(x.kivy_short(self.displayFull))
        return vlayout

    def prepareDay(self, content, day):
        hlayout = BoxLayout(orientation='horizontal')
        itemsInDay = self.filterBy(content, lambda x: x.day == day)
        for i in range(10):
            hlayout.add_widget(self.prepareHour(itemsInDay, i))
        return hlayout

    def displayContent(self, invoker):
        self._contentSpace.clear_widgets()
        self._contentSpace.size_hint=(1, 1)
        self._contentSpace.size=(0,0)
        try:
            content = self.prepareContent()
            self._contentSpace.add_widget(self.prepareHeader())
            for i in range(5):
                self._contentSpace.add_widget(self.prepareDay(content, School.days[i]))
            self._contentSpace.size_hint=(None, None)
            self._contentSpace.size=(500,1500)
        except Exception, e:
            self._contentSpace.add_widget(Label(text='An error occured.'))
            MessagePopup('Error', traceback.format_exc(e))
Exemplo n.º 58
0
class Level(Screen):

    def __init__(self,**kwargs):
        super(Level, self).__init__(**kwargs)
        self.register_event_type('on_pass')
        self.name="level"
        main_layout=BoxLayout(orientation='vertical')
        labels=BoxLayout(orientation="horizontal",size_hint=(1,.1))
        labels.add_widget(Label(text="Valid",background_color=(0,1,0,1)))
        labels.add_widget(Label(text="Invalid",background_color=(1,0,0,1)))
        history=BoxLayout(orientation="horizontal",spacing=100)
        self.enter_label=Label(text="Enter your sequence:",size_hint=(1,.2))
        self.valid_history=CaterpillarList()
        self.invalid_history=CaterpillarList()
        history.add_widget(self.valid_history)
        history.add_widget(self.invalid_history)
        self.buttons=BoxLayout(orientation="vertical")
        self.exam=Exam()
        self.exam.bind(on_answer=self.chain_entered)
        self.exam.bind(on_finish=self.finish)
        self.input_chain=InputCaterpillar()
        self.input_chain.bind(on_input=self.chain_entered)
        self.exam_button=Button(text="I know the rule and ready for test!")
        self.exam_button.bind(on_press=self.to_exam_mode)
        main_layout.add_widget(labels)
        main_layout.add_widget(history)
        self.to_game_mode()
        main_layout.add_widget(self.buttons)
        self.add_widget(main_layout)

    def start_game(self,func):
        self.func=func
        self.input_chain.func=self.func
        self.valids,self.invalids=get_valid_invalid(func)
        valids_sample=get_n(7,self.valids)
        invalids_sample=get_n(7,self.invalids)
        self.valid_history.reset()
        self.invalid_history.reset()
        for e in valids_sample:
            self.valid_history.add(e)
        for e in invalids_sample:
            self.invalid_history.add(e)
        self.to_game_mode()



    def chain_entered(self,instance,chain):
        if self.func(chain):
            self.valid_history.add(chain)
        else:
            self.invalid_history.add(chain)

    def finish(self,instance,passed):
        self.to_game_mode()
        if passed:
            self.dispatch('on_pass')


    def on_pass(self,*args):
        pass

    def to_exam_mode(self,*args):
        self.buttons.clear_widgets()
        self.exam.start_exam(self.valids,
                             self.invalids,
                             self.valid_history.caterpillars,
                             self.invalid_history.caterpillars)
        self.buttons.add_widget(self.exam)

    def to_game_mode(self,*args):
        self.buttons.clear_widgets()
        self.buttons.add_widget(self.enter_label)
        self.buttons.add_widget(self.input_chain)
        self.buttons.add_widget(self.exam_button)
Exemplo n.º 59
0
class XBase(XPopup):
    """XBase class. See module documentation for more information.
    """

    auto_open = BooleanProperty(True)
    '''This property determines if the pop-up is automatically
    opened when the instance was created. Otherwise use :meth:`XBase.open`

    :attr:`auto_open` is a :class:`~kivy.properties.BooleanProperty` and
    defaults to True.
    '''

    buttons = ListProperty()
    '''List of button names. Can be used when using custom button sets.

    :attr:`buttons` is a :class:`~kivy.properties.ListProperty` and defaults to
    [].
    '''

    button_pressed = StringProperty('')
    '''Name of button which has been pressed.

    :attr:`button_pressed` is a :class:`~kivy.properties.StringProperty` and
    defaults to '', read-only.
    '''

    size_hint_x = NumericProperty(.6, allownone=True)
    size_hint_y = NumericProperty(.3, allownone=True)
    auto_dismiss = BooleanProperty(False)
    '''Overrides properties from :class:`~kivy.uix.popup.Popup`
    '''

    min_width = NumericProperty(metrics.dp(300), allownone=True)
    min_height = NumericProperty(metrics.dp(150), allownone=True)
    fit_to_window = BooleanProperty(True)
    '''Overrides properties from :class:`XPopup`
    '''

    BUTTON_OK = 'OK'
    BUTTON_CANCEL = 'Cancel'
    BUTTON_YES = 'Yes'
    BUTTON_NO = 'No'
    BUTTON_CLOSE = 'Close'
    '''Basic button names
    '''

    def __init__(self, **kwargs):
        # preventing change content of the popup
        kwargs.pop('content', None)
        self._pnl_buttons = None
        super(XBase, self).__init__(**kwargs)

        layout = BoxLayout(orientation="vertical")
        layout.add_widget(self._get_body())
        self._pnl_buttons = BoxLayout(size_hint_y=None)
        layout.add_widget(self._pnl_buttons)
        self.add_widget(layout)

        # creating buttons panel
        self.property('buttons').dispatch(self)

        if self.auto_open:
            self.open()

    def _on_click(self, instance):
        self.button_pressed = instance.id
        self.dismiss()

    def _get_body(self):
        """Returns the content of the popup. You need to implement
        this in your subclass.
        """
        raise NotImplementedError

    def on_buttons(self, instance, buttons):
        if self._pnl_buttons is None:
            return

        self._pnl_buttons.clear_widgets()
        if len(buttons) == 0:
            self._pnl_buttons.height = 0
            return

        self._pnl_buttons.height = metrics.dp(30)
        for button in buttons:
            self._pnl_buttons.add_widget(
                ButtonEx(text=button, id=button, on_release=self._on_click))

    def is_canceled(self):
        """Check the `cancel` event

        :return: True, if the button 'Cancel' has been pressed
        """
        return self.button_pressed == self.BUTTON_CANCEL