Esempio n. 1
0
def colorize(txt):
    res = ''
    i = 0
    name = ''
    while i < len(txt):
        car = txt[i]
        if car in ["'", '"']:
            k = i + 1
            while k < len(txt):
                if txt[k] == car:
                    res += html.SPAN(txt[i:k + 1], Class='string')
                    i = k
                    break
                k += 1
        elif car == '#':  # comment
            res += html.SPAN(txt[i:], Class='comment')
            break
        elif car in string.ascii_letters + '_':
            name += car
        elif car in string.digits and name:
            name += car
        else:
            if name:
                if re.search(kw_pattern, name):
                    res += html.SPAN(name, Class='keyword')
                elif re.search(bf_pattern, name):
                    res += html.SPAN(name, Class='keyword')
                else:
                    res += name
                name = ''
            res += car
        i += 1
    res += name
    return res
Esempio n. 2
0
    def __init__(self, title="", style={}, top=0, left=0, ok_cancel=False):
        for key in style:
            for item in styles:
                styles[item][key] = style[key]
        html.DIV.__init__(self, style=styles["dialog"])
        self.left = left
        self.top = top
        self._title = html.DIV(html.SPAN(title), style=styles["title"])
        self <= self._title
        btn = html.SPAN("&times;", style=styles["close"])
        self._title <= btn
        btn.bind("click", self.close)
        self.panel = html.DIV(style=styles["panel"])
        self <= self.panel

        if ok_cancel:
            ok_cancel_zone = html.DIV(style={"text-align": "center"})
            self.ok_button = html.BUTTON("Ok")
            self.cancel_button = html.BUTTON("Cancel")
            self.cancel_button.bind("click", self.close)
            ok_cancel_zone <= self.ok_button + self.cancel_button
            self <= ok_cancel_zone

        document <= self
        self._title.bind("mousedown", self.mousedown)
        document.bind("mousemove", self.mousemove)
        self._title.bind("mouseup", self.mouseup)
        self.bind("leave", self.mouseup)
        self.is_moving = False
Esempio n. 3
0
 def on_complete(self, req):
     # if req.status == 200:
     datas = js.JSON.parse(req.text)
     for data in datas:
         # print(data)
         # document[f"state-{data['camera_id']}"].text = data['state']
         i = html.I()
         data_id = data["camera_id"] + "/" + data["project_id"]
         if data["state"] in ["running", "start"]:
             i.class_name = "ui green circle icon big"
             s = html.SPAN(style={"color": "green"})
             self.disable_button(document.select(".startlpr"), data_id)
             self.enable_button(document.select(".stoplpr"), data_id)
         elif data["state"] in ["starting"]:
             i.class_name = "ui yellow circle icon big"
             s = html.SPAN(style={"color": "yellow"})
             self.disable_button(document.select(".stoplpr"), data_id)
             self.enable_button(document.select(".startlpr"), data_id)
         elif data["state"] in ["stop"]:
             i.class_name = "ui grey circle icon big"
             s = html.SPAN(style={"color": "grey"})
             self.disable_button(document.select(".stoplpr"), data_id)
             self.enable_button(document.select(".startlpr"), data_id)
         elif data["state"] in ["stopping"]:
             i.class_name = "ui red circle icon big"
             s = html.SPAN(style={"color": "red"})
             self.disable_button(document.select(".stoplpr"), data_id)
             self.enable_button(document.select(".startlpr"), data_id)
         s <= data["state"].capitalize()
         document[f"state-{data['camera_id']}"].text = ""
         document[f"state-{data['camera_id']}"] <= i + s
    def setup(self, container):
        def _make_handler(building):
            def _handle(e):
                self.game.buildings[building].on_buy()

            return _handle

        self.divs = {}
        self.buybuttons = {}
        for key, value in self.game.buildings.items():
            self.divs[key] = []
            self.buybuttons[key] = []
            for ele in container.get(selector=".building-holder-holder"):
                if value.in_world(ele.parent.parent.id.split("_")[1]):
                    parent = html.DIV(
                        html.SPAN(value.name),
                        Class="building-holder building-holder_" + key)
                    div = html.SPAN("Loading...", Class="building-count")
                    parent <= div
                    desc = html.DIV(value.desc + "\n" + value.buy_desc,
                                    Class="building-desc")
                    button = html.BUTTON("Buy!", disabled=True)
                    self.buybuttons[key].append(button)
                    button.bind("click", _make_handler(key))
                    desc <= html.BR()
                    desc <= button
                    parent <= desc
                    self.divs[key].append(div)
                    ele <= parent
Esempio n. 5
0
    def slider(self, label, min, max, value, step=1, unit='', marks=False, on_change=None, id=None, *args, **kwargs):
        """"""
        form = MDCForm()
        label_ = MDCComponent(html.SPAN(f'{label}'))
        label_ .mdc.typography('subtitle1')
        form <= label_
        form <= MDCComponent(html.SPAN(
            f' {self._round(value)} {unit}', id=f'value_{id}')).mdc.typography('caption')
        slider_ = form.mdc.Slider(
            'Slider', min=min, max=max, value=value, step=step, marks=marks, *args, **kwargs)

        if on_change:
            slider_.mdc.listen('MDCSlider:change',
                               lambda evt: on_change(self.widgets[id]))

        if id:
            self.widgets[id] = self._fix_value(value)
            self.component[id] = slider_

            def set_value(id, value):
                self.widgets[id] = self._round(value)
                document.select_one(
                    f'#value_{id}').html = f' {self.get_value(id)} {unit}'

            slider_.mdc.listen('MDCSlider:input', lambda event: set_value(
                id, slider_.mdc.getValue()))

        return form
Esempio n. 6
0
    def range_slider(self, label, min, max, value_lower, value_upper, step, unit='', on_change=None, id=None, *args, **kwargs):
        """"""
        form = MDCForm()
        label_ = MDCComponent(html.SPAN(f'{label}'))
        label_ .mdc.typography('subtitle1')
        form <= label_
        form <= MDCComponent(html.SPAN(
            f' {self._round(value_lower)}-{self._round(value_upper)} {unit}', id=f'value_{id}')).mdc.typography('caption')
        slider_ = form.mdc.RangeSlider(
            'Slider', min, max, value_lower, value_upper, step, *args, **kwargs)

        if on_change:
            slider_.mdc.listen('MDCSlider:change',
                               lambda evt: on_change(self.widgets[id]))

        if id:
            self.widgets[id] = [self._fix_value(
                value_lower), self._fix_value(value_upper)]
            self.component[id] = slider_

            def set_value(id, value):
                self.widgets[id] = [self._round(
                    value[0]), self._round(value[1])]
                document.select_one(
                    f'#value_{id}').html = f' {self.get_value(id)[0]}-{self.get_value(id)[1]} {unit}'

            slider_.mdc.listen('MDCSlider:input', lambda event: set_value(
                id, [slider_.mdc.getValueStart(), slider_.mdc.getValue()]))

        return form
Esempio n. 7
0
def highlight(txt,
              string_color="blue",
              comment_color="green",
              keyword_color="purple",
              builtin_func_color="#963"):
    res = html.PRE()
    txt = escape(txt)
    i = 0
    name = ''
    while i < len(txt):
        car = txt[i]
        if car in ["'", '"']:
            found_match = False
            k = i + 1
            while k < len(txt):
                if txt[k] == car:
                    nb_as = 0
                    j = k - 1
                    while True:
                        if txt[j] == '\\':
                            nb_as += 1
                            j -= 1
                        else:
                            break
                    if nb_as % 2 == 0:
                        res <= name + html.SPAN(escape(txt[i:k + 1]),
                                                Class="python-string")
                        i = k
                        name = ''
                        found_match = True
                        break
                k += 1
            if not found_match:
                name += car
        elif car == '#':  # comment
            end = txt.find('\n', i)
            if end == -1:
                res <= html.SPAN(txt[i:], Class="python-comment")
                break
            else:
                res <= html.SPAN(txt[i:end], Class="python-comment")
                i = end - 1
        elif car in letters:
            name += car
        elif car in digits and name:
            name += car
        else:
            if name:
                if re.search(kw_pattern, name):
                    res <= html.SPAN(name, Class="python-keyword")
                elif re.search(bf_pattern, name):
                    res <= html.SPAN(name, Class="python-builtin")
                else:
                    res <= name
                name = ''
            res <= car
        i += 1
    res <= name
    return res
Esempio n. 8
0
    def __init__(self, title="", *,
            top=None, left=None, ok_cancel=False, default_css=True):
        if default_css:
            for stylesheet in document.styleSheets:
                if stylesheet.ownerNode.id == "brython-dialog":
                    break
            else:
                document <= html.STYLE(style_sheet, id="brython-dialog")

        html.DIV.__init__(self, style=dict(position="absolute"),
            Class="brython-dialog-main")
        #set_style(self, "dialog-main")
        self.title_bar = html.DIV(html.SPAN(title), Class="brython-dialog-title")
        self <= self.title_bar
        self.close_button = html.SPAN("&times;", Class="brython-dialog-close")
        self.title_bar <= self.close_button
        self.close_button.bind("click", self.close)
        self.panel = html.DIV(Class="brython-dialog-panel")
        self <= self.panel

        if ok_cancel:
            ok_cancel_zone = html.DIV(style={"text-align": "center"})
            ok, cancel = "Ok", "Cancel"
            if isinstance(ok_cancel, (list, tuple)):
                if not len(ok_cancel) == 2:
                    raise ValueError(
                        f"ok_cancel expects 2 elements, got {len(ok_cancel)}")
                ok, cancel = ok_cancel
            self.ok_button = html.BUTTON(ok, Class="brython-dialog-button")
            self.cancel_button = html.BUTTON(cancel,
                Class="brython-dialog-button")
            self.cancel_button.bind("click", self.close)
            ok_cancel_zone <= self.ok_button + self.cancel_button
            self <= ok_cancel_zone

        document <= self
        cstyle = window.getComputedStyle(self)

        # Center horizontally and vertically
        if left is None:
            width = round(float(cstyle.width[:-2]) + 0.5)
            left = int((window.innerWidth - width) / 2)
        self.left = left
        self.style.left = f'{left}px'
        if top is None:
            height = round(float(cstyle.height[:-2]) + 0.5)
            top = int((window.innerHeight - height) / 2)
        # top is relative to document scrollTop
        top += document.scrollingElement.scrollTop
        self.top = top
        self.style.top = f'{top}px'

        self.title_bar.bind("mousedown", self.mousedown)
        self.title_bar.bind("touchstart", self.mousedown)
        self.title_bar.bind("mouseup", self.mouseup)
        self.title_bar.bind("touchend", self.mouseup)
        self.bind("leave", self.mouseup)
        self.is_moving = False
Esempio n. 9
0
def highlight(txt,
              string_color="blue",
              comment_color="green",
              keyword_color="purple"):
    res = html.PRE()
    i = 0
    name = ''
    while i < len(txt):
        car = txt[i]
        if car in ["'", '"']:
            found_match = False
            k = i + 1
            while k < len(txt):
                if txt[k] == car:
                    nb_as = 0
                    j = k - 1
                    while True:
                        if txt[j] == '\\':
                            nb_as += 1
                            j -= 1
                        else:
                            break
                    if nb_as % 2 == 0:
                        res <= name + html.SPAN(txt[i:k + 1],
                                                style=dict(color=string_color))
                        i = k
                        name = ''
                        found_match = True
                        break
                k += 1
            if not found_match:
                name += car
        elif car == '#':  # comment
            end = txt.find('\n', i)
            if end == -1:
                res <= html.SPAN(txt[i:], style=dict(color=comment_color))
                break
            else:
                res <= html.SPAN(txt[i:end], style=dict(color=comment_color))
                i = end - 1
        elif car in letters:
            name += car
        elif car in digits and name:
            name += car
        else:
            if name:
                if re.search(kw_pattern, name):
                    res <= html.SPAN(name, style=dict(color=keyword_color))
                elif re.search(bf_pattern, name):
                    res <= html.SPAN(name, style=dict(color=keyword_color))
                else:
                    res <= name
                name = ''
            res <= car
        i += 1
    res <= name
    return res
Esempio n. 10
0
def highlight(txt):
    res = html.PRE()
    i = 0
    name = ''
    while i < len(txt):
        car = txt[i]
        if car in ["'", '"']:
            mul_car = txt[i:i + 3]
            if mul_car in ["'''", '"""']:
                car = mul_car
            found_match = False
            k = i + len(car)
            while k < len(txt):
                k = txt.find(car, k)
                if k != -1:
                    nb_as, j = 0, k - 1
                    while txt[j] == '\\':
                        nb_as += 1
                        j -= 1
                    if nb_as % 2 == 0:
                        res <= name + html.SPAN(escape(txt[i:k + len(car)]),
                                                Class="python-string")
                        i = k + len(car) - 1
                        name = ''
                        found_match = True
                        break
                else:
                    break
                k += len(car)
            if not found_match:
                name += car
        elif car == '#':  # comment
            end = txt.find('\n', i)
            if end == -1:
                res <= html.SPAN(escape(txt[i:]), Class="python-comment")
                break
            else:
                res <= html.SPAN(escape(txt[i:end]), Class="python-comment")
                i = end - 1
        elif car in letters:
            name += car
        elif car in digits and name:
            name += car
        else:
            if name:
                if re.search(kw_pattern, name):
                    res <= html.SPAN(name, Class="python-keyword")
                elif re.search(bf_pattern, name):
                    res <= html.SPAN(name, Class="python-builtin")
                else:
                    res <= name
                name = ''
            res <= car
        i += 1
    res <= name
    return res
Esempio n. 11
0
    def rebuildBatch(self):
        for c in [x for x in self.construction.children][:-1]:
            self.construction.removeChild(c)

        self.reset(False)

        for token in [x for x in self.editorRow.children][:-1]:
            self.extend(token.result)

        lastRow = self.constructionRow

        res = self.commit()
        for entry in res:
            row = html.TR()
            row.activity = entry

            if isinstance(entry, airbatch.Activity):
                for txt in [
                        #entry.takeoff.strftime("%d.%m.%Y"),
                        str(entry.aircraft),
                        str(entry.pilot),
                        str(entry.copilot) if entry.copilot else "-",
                        entry.takeoff.strftime("%H:%M"),
                        str(entry.ltakeoff),
                        entry.touchdown.strftime("%H:%M"),
                        str(entry.ltouchdown),
                        str(entry.duration)
                ]:

                    col = row.insertCell()
                    col.innerHTML = txt

                row.commit = html.SPAN("✓", Class="commit")
                row.commit.bind("click", self.commitRow)

                row.close = html.SPAN("⨉", Class="close")
                row.close.bind("click", self.removeRow)

                col = row.insertCell()
                col.appendChild(row.commit)
                col.appendChild(row.close)

            else:
                row.classList.add("error")

                col = row.insertCell()
                col.colSpan = "10"
                col.innerHTML = str(entry)

            self.construction.insertBefore(row, lastRow)
Esempio n. 12
0
    def doParse(self, event):
        self.reset()
        res = self.parse(self.batchEditor.value)

        lastRow = self.constructionRow

        if self.batchErrorRow:
            self.batchErrorRow.parent.removeChild(self.batchErrorRow)
            self.batchErrorRow = None

        for entry in res:
            row = html.TR()
            row.activity = entry

            if isinstance(entry, airbatch.Activity):
                for txt in [
                        #str(entry.row),
                        #entry.takeoff.strftime("%d.%m.%Y"),
                        str(entry.aircraft),
                        str(entry.pilot),
                        str(entry.copilot) if entry.copilot else "-",
                        entry.takeoff.strftime("%H:%M"),
                        str(entry.ltakeoff),
                        entry.touchdown.strftime("%H:%M"),
                        str(entry.ltouchdown),
                        str(entry.duration)
                ]:

                    col = row.insertCell()
                    col.innerHTML = txt

                row.commit = html.SPAN("✓", Class="commit")
                row.commit.bind("click", self.commitRow)

                row.close = html.SPAN("⨉", Class="close")
                row.close.bind("click", self.removeRow)

                col = row.insertCell()
                col.appendChild(row.commit)
                col.appendChild(row.close)

            else:
                self.batchErrorRow = row
                row.classList.add("error")

                col = row.insertCell()
                col.colSpan = "10"
                col.innerHTML = str(entry)

            self.construction.insertBefore(row, lastRow)
Esempio n. 13
0
def arrow(thing):
    try:
        v = doc["v"]
        v.contentEditable = 'false'
        v.id = "n"
        v.unbind("keydown")
    except:
        pass
    doc["c"] <= html.DIV()
    doc["c"] <= html.SPAN(serial(thing[:3]), Class="con")
    doc["c"] <= html.SPAN(
        thing[3:].replace(" ", "\u200b \u200b"), Class="edt", Id="v")
    v = doc["v"]
    v.bind("keydown", keys)
    v.contentEditable = 'true'
    def PassageToDiv(self, passage: Passage) -> DivPassage:
        output = html.DIV()
        allow_back = False
        for element in passage:
            is_allow_back = (type(element) is type) and element.__name__ == "Allow_Back"
            if is_allow_back:
                allow_back = True
                continue

            if isinstance(element, str):
                output <= html.SPAN(md_to_html(element))
                continue
            if isinstance(element, TP):
                alink = html.A(f" {element.Text} ")
                output <= self.makeLink(element.Text, element.PassageFactory)
                continue
            if callable(element):
                function_name = element.__name__
                text_link = f"{function_name.replace('_',' ')}"
                if text_link.startswith(" "):
                    text_link = text_link[1:]
                output <= self.makeLink(text_link, element)
                continue
            else:
                print(element)
                raise Exception(f"Unknown element type {type(element)}")

        return DivPassage(output, allow_back)
Esempio n. 15
0
def delete(evt, elt):
    dialog_window.style.display = "block"
    dialog.clear()

    dialog_title = dialog_window.select_one(".dialog_title")
    dialog_title.clear()
    dialog_title <= html.SPAN("Remove script")

    dialog <= f"Do you really want to delete script {current} ?"
    dialog <= html.P()
    dialog <= html.BUTTON("Ok") + html.BUTTON("Cancel")

    @dialog.select("button")[0].bind("click")
    def confirm_delete(evt):
        db = request.result
        tx = db.transaction("scripts", "readwrite")
        store = tx.objectStore("scripts")
        cursor = store.delete(current)
        dialog_window.style.display = "none"

        # when record is added, show message
        def ok(evt):
            open_scripts.remove(current)
            editor.text = ""
            print_line_nums()
            draw_file_browser()

        cursor.bind('success', ok)

    @dialog.select("button")[1].bind("click")
    def cancel_delete(evt):
        dialog_window.style.display = "none"
Esempio n. 16
0
    def __init__(self, todos, filter):
        count = len([todo for todo in todos if not todo.completed])
        item_text = 'item' if count == 1 else 'items'

        super().__init__(
            [
                H.SPAN(
                    [
                        H.STRONG(count),
                        ' {} left'.format(item_text),
                    ],
                    Class='todo-count',
                ),
                H.UL(
                    [
                        H.LI(
                            FilterLink('All',
                                       filter=ALL_FILTER,
                                       current_filter=filter), ),
                        H.LI(
                            FilterLink('Active',
                                       filter=ACTIVE_FILTER,
                                       current_filter=filter), ),
                        H.LI(
                            FilterLink('Completed',
                                       filter=COMPLETED_FILTER,
                                       current_filter=filter), ),
                    ],
                    Class='filters',
                ),
                ClearCompletedButton(todos),
            ],
            Class='footer',
            style={'display': 'block' if len(todos) else 'none'},
        )
Esempio n. 17
0
def load(evt, elt):
    global scripts
    db = request.result
    tx = db.transaction("scripts", "readonly")
    store = tx.objectStore("scripts")
    cursor = store.openCursor()

    dialog_window.style.display = "block"
    dialog.clear()

    dialog_title = dialog_window.select_one(".dialog_title")
    dialog_title.clear()
    dialog_title <= html.SPAN("Open file...")

    scripts = []
    def get_scripts(evt):
        res = evt.target.result
        if res:
            scripts.append(res.value.name)
            getattr(res, "continue")()
        else:
            scripts.sort()
            for script in scripts:
                dialog <= html.SPAN(script) + html.BR()
            for elt in dialog.childNodes:
                elt.bind("click", open_script)

    cursor.bind('success', get_scripts)
Esempio n. 18
0
    def select(self, label, options, value=None, on_change=None, id=None):
        """"""
        label_ = MDCComponent(html.SPAN(f'{label}'))
        label_ .mdc.typography('subtitle1')
        form = MDCForm(formfield_style={
                       'width': '100px', 'min-height': '90px', 'margin-left': '15px'})
        form <= label_
        select_ = form.mdc.Select('', options=options, selected=value)

        if id:
            self.widgets[id] = value
            self.component[id] = select_

            def set_value():
                def wrap(evt):
                    self.widgets[id] = select_.mdc.value
                return wrap

            select_.mdc.listen('MDCSelect:change', set_value())

        if on_change:
            select_.mdc.listen('MDCSelect:change',
                               lambda evt: on_change(select_.mdc.value))

        return form
Esempio n. 19
0
 def _fence(self, node):
     # FIXME: Make it return a proper comment node in both testing and production
     # pylint: disable=bare-except; this is invalid code which needs to be changed anyway
     try:
         return html.COMMENT(str(node))
     except:
         return html.SPAN()
Esempio n. 20
0
    def setup(self, container):
        self.divs = {}

        currency_holders = container.get(selector=".currency-holder-holder")
        for key, value in list(self.game.currencies.items()):
            self.divs[key] = []
            for container in currency_holders:
                if value.in_world(container.parent.parent.id.split("_")[1]):
                    parent = html.DIV(
                        html.SPAN(value.format_name()),
                        Class="currency-holder currency-holder_" + key)
                    div = html.SPAN("Loading...", Class="currency-value")
                    parent <= div
                    self.divs[key].append(div)
                    container <= parent
        print(self.divs)
Esempio n. 21
0
    def radios(self, label, options, on_change=None, id=None):
        """"""
        label = MDCComponent(html.SPAN(f'{label}'))
        label.mdc.typography('subtitle1')
        radios_ = []
        form = MDCForm(formfield_style={'width': '100px'})
        form <= label

        for i, (radio, value) in enumerate(options):
            radios_.append(
                [form.mdc.Radio(radio, name=id, checked=(i == 0)), value])

        if id:
            self.widgets[id] = options[0][1]
            self.component[id] = radios_

            def set_value(value):
                def wrap(evt):
                    self.widgets[id] = value
                return wrap

            for radio, value in radios_:
                radio.bind('change', set_value(value))

        if on_change:
            for radio, _ in radios_:
                radio.bind('change', lambda evt: on_change())

        return form
Esempio n. 22
0
def show_task(event, element):
    global data
    global idcheck
    global bind_list
    cla = "w3-tag w3-large w3-red"
    if len(data) != 0:
        doc['app-3'].style.display = "block"
        for x, q in data.items():
            if x not in idcheck:
                idcheck.append(x)
                span = html.SPAN("&times",
                                 id="id" + str(x),
                                 Class=cla,
                                 style={'margin-top': '4px'})

                inputcheckbox = html.INPUT(Class="w3-check w3-left",
                                           id="c" + str(x),
                                           type="checkbox")
                container = html.DIV(Class="w3-container", id="k" + str(x))
                input = html.INPUT(id="m" + str(x),
                                   Class="w3-left",
                                   value=q[0],
                                   readonly="true",
                                   style=styleinput)
                div1 = html.DIV(id=x)
                div1 <= inputcheckbox + input + span
                container <= div1
                doc['app-3'] <= container
    for x in idcheck:
        if x not in bind_list:
            bind_list.append(x)
            doc["id" + str(x)].bind("click", remove_item)
            doc["c" + str(x)].bind("change", line)
            doc["m" + str(x)].bind("click", editing)
            doc["m" + str(x)].bind("blur", editing_focus)
Esempio n. 23
0
  def __init__(self, id=None):
      self._div_shell=html.DIV(
         Class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front ui-draggable ui-resizable",
         style={'position': 'absolute', 'height': 'auto', 'width': '300px',
                'top': '98px', 'left': '140px', 'display': 'block'})

      widget.DraggableWidget.__init__(self, self._div_shell, 'dialog', id)

      _div_titlebar=html.DIV(Id="titlebar",
           Class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix")
      self._div_shell <= _div_titlebar

      self._div_title=html.SPAN(Id="title", Class="ui-dialog-title")
        
      _div_titlebar <= self._div_title

      self._title_button=html.BUTTON(Title="close",
            Class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only ui-dialog-titlebar-close")

      def dialog_close(e):
          #del document[self._div_shell.id]
          del document[self._div_shell.id]

      self._title_button.bind('click', dialog_close)
      _span=html.SPAN(Class="ui-button-icon-primary ui-icon ui-icon-closethick")
      self._title_button <= _span

      _span=html.SPAN('close', Class="ui-button-text")
      self._title_button <= _span

      _div_titlebar <= self._title_button

      self._div_dialog=html.DIV(Class="ui-dialog-content ui-widget-content",
           style={'width': 'auto', 'min-height': '105px', 
                  'max-height': 'none', 'height': 'auto'})

      self._div_shell <= self._div_dialog

      for _i in ['n', 'e', 's', 'w', 'se', 'sw', 'ne', 'nw']:
          if _i == 'se':
             _class="ui-resizable-handle ui-resizable-%s ui-icon ui-icon-gripsmall-diagonal-%s" % (_i, _i)
          else:
             _class="ui-resizable-handle ui-resizable-%s" % _i

          self._div_shell <= html.DIV(Class=_class, style={'z-index': '90'})

      document <= self._div_shell
Esempio n. 24
0
def save_as(ev):
    d = ui.Dialog("Save sheet as...")
    d.add_ok_cancel(ok=save_sheet, cancel=cancel_save_as)
    d.body <= html.SPAN('File name', style=dict(marginRight='10px'))
    d.body <= html.INPUT()
    document.unbind('keydown')

    document <= d
Esempio n. 25
0
 def opta(letra, texto):
         div = html.DIV(Class="content")
         optou = html.A(chr(ABOXED + ord(letra) - ord("A")), Class="option", href="#")
         optou.onclick = lambda *_: opcao(letra) or self._close()
         texto_opcao = html.SPAN(texto)
         div <= optou
         div <= texto_opcao
         return div
Esempio n. 26
0
def draw_file_browser():
    filebrowser.clear()
    open_scripts.sort()
    filebrowser <= (html.SPAN(s) + html.BR() for s in open_scripts)
    for span in filebrowser.select("span"):
        span.bind("click", open_script)
        if span.text.strip() == current:
            span.style.backgroundColor = "#888"
Esempio n. 27
0
    def __init__(self,
                 title="",
                 style={},
                 top=None,
                 left=None,
                 ok_cancel=False):
        for key in style:
            for item in styles:
                styles[item][key] = style[key]
        html.DIV.__init__(self, style=styles["dialog"])
        self._title = html.DIV(html.SPAN(title), style=styles["title"])
        self <= self._title
        btn = html.SPAN("&times;", style=styles["close"])
        self._title <= btn
        btn.bind("click", self.close)
        self.panel = html.DIV(style=styles["panel"])
        self <= self.panel

        if ok_cancel:
            ok_cancel_zone = html.DIV(style={"text-align": "center"})
            self.ok_button = html.BUTTON("Ok")
            self.cancel_button = html.BUTTON("Cancel")
            self.cancel_button.bind("click", self.close)
            ok_cancel_zone <= self.ok_button + self.cancel_button
            self <= ok_cancel_zone

        document <= self
        cstyle = window.getComputedStyle(self)

        # Center horizontally and vertically
        if left is None:
            width = round(float(cstyle.width[:-2]) + 0.5)
            left = int((window.innerWidth - width) / 2)
        self.left = left
        self.style.left = f'{left}px'
        if top is None:
            height = round(float(cstyle.height[:-2]) + 0.5)
            top = int((window.innerHeight - height) / 2)
        self.top = top
        self.style.top = f'{top}px'

        self._title.bind("mousedown", self.mousedown)
        document.bind("mousemove", self.mousemove)
        self._title.bind("mouseup", self.mouseup)
        self.bind("leave", self.mouseup)
        self.is_moving = False
Esempio n. 28
0
def load(sheet_name=None):
    global current_cell_info, menu_file

    if sheet_name is None:
        sheet_name = 'New document'

    panel = document['panel']

    title = html.DIV(style=dict(width='auto'))
    title <= html.H2(sheet_name, id="sheet_name")

    panel <= title

    menu = ui.Menu()

    menu_file = menu.add('File')
    menu_file.add('New', None)
    menu_file.add('Open...', select_sheet)
    menu_file.add('Save as...', save_as)

    panel <= html.SPAN(menu)

    panel <= html.BR()
    cell_editor = html.INPUT(style=dict(width="200px"), Id="current")
    cell_editor.bind('click', enter_editor)
    cell_editor.bind('keydown', editor_keydown)
    cell_editor.bind('keyup', update_from_editor)
    panel <= cell_editor

    t = html.TABLE(Id="sheet_table")
    srow = -1
    rows, cols = 20, 20
    col_widths = [100 for i in range(rows)]

    line = html.TR()
    line <= html.TH()
    for i in range(cols):
        col_name = chr(65 + i)
        line <= html.TH(col_name, style={'min-width': '%spx' % col_widths[i]})
    t <= line

    for i in range(rows * cols):
        row, column = divmod(i, cols)
        if row > srow:
            line = html.TR()
            line <= html.TH(row + 1)
            t <= line
            srow = row
        cell = html.TD('',
                       id='c%s_%s' % (row, column),
                       style=dict(padding='2px'))
        cell.bind('click', select)
        cell.bind('dblclick', entry)
        cell.info = {'entry': ''}
        line <= cell

    panel <= html.DIV(t, style=dict(float='left'))
    mark_selected(t.get(selector='TD')[0])
Esempio n. 29
0
    def label(self, text, typo='body1', style={}, id=None, *args, **kwargs):
        """"""
        label = MDCComponent(html.SPAN(f'{text}'), style={
                             **style, **{'width': '100%', 'display': 'flex'}}, *args, **kwargs)
        label.mdc.typography(typo)

        if id:
            self.component[id] = label

        return label
Esempio n. 30
0
	def loadHighScores(self):
		# storing up to 5 high scores.
		self._score = [0] * 5
		try:   # there may be less than 5 values stored so far.
			for i in range(5):
				self._score[i] = int(self._storage[f'highScore{i}'])
		except:
			pass
		self._scores_span = html.SPAN()
		self._game_info2_elem <= self._scores_span

		header = html.SPAN('High Scores: ')
		self._scores_span <= header

		for i in range(5):
			span = html.SPAN("{score}")
			self._score_val.append(template.Template(span))
			self._scores_span <= span
			self._score_val[i].render(score=self._score[i])