Exemplo n.º 1
0
    def __init__(self, container, rows=20):

        table = html.TABLE(style=styles["panel"])

        menu_td = html.TD(colspan=2, style=styles["menu"])
        self.menu = menu.Menu(menu_td)
        m1 = self.menu.add_menu("Edition")
        m1.add_item("Search", self.search_dialog)
        table <= html.TR(menu_td)

        self.linenums = html.TEXTAREA(rows=21,
                                      cols=5,
                                      autocomplete="off",
                                      disabled=True,
                                      style=styles["linenums"])
        self.editor = html.TEXTAREA(rows=20,
                                    cols=120,
                                    wrap="off",
                                    autocomplete="off",
                                    spellcheck="false",
                                    style=styles["editor"])
        table <= html.TR(
            html.TD(self.linenums, valign="top") +
            html.TD(self.editor, valign="top"))
        container <= table
        self.editor.bind("keydown", self.keydown)
        self.editor.bind("keyup", self.keyup)
        self.editor.bind("scroll", self.scroll)
        self.set_line_nums()
        self.stack = []
        self.store_undo()
Exemplo n.º 2
0
def share_code(ev):
    src = editor.getValue()
    if len(src) > 2048:
        d = dialog.InfoDialog("Copy url",
                              f"code length is {len(src)}, must be < 2048",
                              style={"zIndex": 10},
                              ok=True)
    else:
        href = window.location.href.rsplit("?", 1)[0]
        query = doc.query
        query["code"] = src
        url = f"{href}{query}"
        url = url.replace("(", "%28").replace(")", "%29")
        d = dialog.Dialog("Copy url")
        area = html.TEXTAREA(rows=0, cols=0)
        d.panel <= area
        area.value = url
        # copy to clipboard
        area.focus()
        area.select()
        doc.execCommand("copy")
        d.remove()
        d = dialog.Dialog("Copy url")
        d.panel <= html.DIV("url copied in the clipboard<br>Send it to share the code")
        buttons = html.DIV()
        ok = html.BUTTON("Ok")
        buttons <= html.DIV(ok, style={"text-align": "center"})
        d.panel <= html.BR() + buttons

        @bind(ok, "click")
        def click(evt):
            d.remove()
Exemplo n.º 3
0
    def __init__(self, elt_id=None, globals=None, locals=None):
        if elt_id is None:
            d = Dialog("REPL")
            self.zone = html.TEXTAREA(rows=30, cols=60)
            d.panel <= self.zone
        else:
            self.zone = document[elt_id]
        v = sys.implementation.version
        self.zone.value = "Brython %s.%s.%s on %s %s\n>>> " % (
            v[0], v[1], v[2], window.navigator.appName,
            window.navigator.appVersion)
        self.zone.focus()
        self.cursorToEnd()
        self._status = "main"
        self.current = 0
        self.history = []

        self.buffer = ''
        sys.stdout.write = sys.stderr.write = self.write
        sys.stdout.__len__ = sys.stderr.__len__ = lambda: len(self.buffer)

        self.globals = globals or {}
        self.globals.update(editor_ns)
        self.locals = locals or {}

        self.zone.bind('keypress', self.myKeyPress)
        self.zone.bind('keydown', self.myKeyDown)
        self.zone.bind('click', self.cursorToEnd)
Exemplo n.º 4
0
 def __init__(self):
     self.onde = self.cena = j.s.MANSÃO_HALL.leste
     print("implanta_livro_de_notas", self.cena.img)
     self.livro = Cena(PROP["LIVRO"])
     self.papel = Elemento(img=PROP["FAKEOB"],
                           tit="Um lavatorio",
                           vai=self.pega_papel,
                           style=dict(left=360,
                                      top=356,
                                      width=170,
                                      height="111px"))
     self.implanta_livro_de_notas()
     self.div = html.DIV(style=dict(position="absolute",
                                    left=45,
                                    top=70,
                                    width=450,
                                    background="transparent",
                                    border="none"))
     self.ta = html.TEXTAREA(CODE,
                             cols="70",
                             rows="20",
                             style=dict(position="absolute",
                                        left=50,
                                        top=50,
                                        background="transparent",
                                        border="none"))
     self.div <= self.ta
     self.livro.elt <= self.div
Exemplo n.º 5
0
    def __init__(self, placeholderText="# Write some Python code here"):

        self.text = html.TEXTAREA(Class="textarea")
        self.text.value = placeholderText
        self.output = html.PRE()
        document <= self.text
        document <= self.output
        self.text.bind("keydown", self.onKeydown)
Exemplo n.º 6
0
 def __init__(self, pageindex, title, backgroundcolour):
     super().__init__(title, backgroundcolour)
     self.viewed = False
     self.chartbox =  ws.ColumnPanel(className="chartcontainer")
     self.description = html.DIV(Class="description")
     self.databox = html.TEXTAREA(Class="databox")
     self.codebox = html.TEXTAREA(Class="codebox")
     self.attach(ws.RowPanel([
         html.DIV([
             self.description,
             html.P("How the data is structured:", Class="boxlabel"),
             self.databox,
             html.P("Code to generate the charts:", Class="boxlabel"),
             self.codebox
             ], Class="leftpane"),
         self.chartbox
         ]))
 def __init__(self):
     self.shadow = self.attachShadow({'mode': 'open'})
     self.locals = {}
     self.globals = {}
     ta = html.TEXTAREA()
     self.shadow <= ta
     bind(ta, 'change')(self.onChange(ta))
     button = html.BUTTON('Evaluate')
     self.shadow <= button
     bind(button, 'click')(self.eval)
Exemplo n.º 8
0
def output_txt_data(e):
    if not document.select('#rt1'):
        link_txt = f'static/combs/{_name}.txt'

        def read(f):
            document['rt1'].value = f.read()

        div = html.DIV(html.P(), Class='form-group')
        div <= html.TEXTAREA(id="rt1",
                             rows="20",
                             cols="30",
                             autocomplete="off",
                             Class='form-control')
        document['output_txt'] <= div
        ajax.get(link_txt, oncomplete=read)
Exemplo n.º 9
0
 def __init__(self,
              cena=NADA,
              tit="",
              txt="",
              texto=None,
              foi=None,
              indo=None,
              **kwargs):
     super().__init__(cena=cena, tit=tit, txt=txt, foi=foi, **kwargs)
     # self.elt = Popup.POP.popup
     self.t = []
     self.cena, self.area = cena, html.DIV()
     if texto is not None:
         self.area = html.TEXTAREA(texto,
                                   Id="_TEXT_POPUP_",
                                   rows=4,
                                   style=dict(width='100%', resize=None))
         self.area.bind('keypress', self.indo)
     self._esconde = foi if foi else lambda: None
     self.indo = indo if indo else self.indo
Exemplo n.º 10
0
    def __init__(self, editor_id, console_id, container_id, storage_id):
        self.editor_id = editor_id
        self.console_id = console_id
        self.container_id = container_id
        self.storage_id = storage_id
        self.output = ''

        try:
            self.editor = window.ace.edit(self.editor_id)
            session = self.editor.getSession()
            session.setMode("ace/mode/python")

            self.editor.setOptions({
                'enableLiveAutocompletion': True,
                'enableSnippets': True,
                'highlightActiveLine': False,
                'highlightSelectedWord': True,
                'autoScrollEditorIntoView': True,
                # 'maxLines': session.getLength() 可以根據程式長度設定 editor 列數
                # 設定讓使用者最多可以在畫面中顯示 20 行程式碼
                'maxLines': 20,
                'fontSize': '12pt'
            })
        except:
            from browser import html
            self.editor = html.TEXTAREA(rows=20, cols=70)
            doc[self.editor_id] <= self.editor

            def get_value():
                return self.editor.value

            def set_value(x):
                self.editor.value = x

            self.editor.getValue = get_value
            self.editor.setValue = set_value
Exemplo n.º 11
0
Arquivo: repl.py Projeto: x00b/brython
    def __init__(self, elt_id=None, title="REPL", globals=None, locals=None):
        """
        Create the interpreter.
        - "elt_id" is the id of a textarea in the document. If not set, a new
          popup window is added with a textarea.
        - "globals" and "locals" are the namespaces the RPEL runs in
        """
        if elt_id is None:
            self.dialog = Dialog(title=title, top=10, left=10)
            self.zone = html.TEXTAREA(rows=30, cols=60)
            set_style(self.zone, "brython-console")
            self.dialog.panel <= self.zone
        else:
            self.zone = document[elt_id]
        v = sys.implementation.version
        self.zone.value = (f"Brython {v[0]}.{v[1]}.{v[2]} on " +
            f"{window.navigator.appName} {window.navigator.appVersion}\n>>> ")
        self.zone.focus()
        self.cursor_to_end()
        self._status = "main"
        self.current = 0
        self.history = []

        self.globals = {} if globals is None else globals
        self.globals.update(editor_ns)
        self.locals = {} if locals is None else locals

        self.buffer = ''
        sys.stdout.write = sys.stderr.write = self.write
        sys.stdout.__len__ = sys.stderr.__len__ = lambda: len(self.buffer)

        self.zone.bind('keypress', self.keypress)
        self.zone.bind('keydown', self.keydown)
        self.zone.bind('mouseup', self.mouseup)

        self.zone.focus()
Exemplo n.º 12
0
def draw_home_title_description():
    panel = document["main_panel"]

    table = html.TABLE()
    table.style.fontSize = "large"
    table.style.font = "16px verdana"

    tableBody = html.TBODY()
    row = html.TR()

    tableBody.style.verticalAlign = "center"
    row.style.verticalAlign = "center"

    table.style.background = "#F7F7F7"
    table.style.padding = "10px 10px 10px 10px"

    label = html.LABEL("Details for dataset:", id="label_details_for_dataset")
    label.style.verticalAlign = "center"
    label.style.marginRight = "10px"

    td1 = html.TD()
    td1 <= label
    td1.style.width = "200px"
    row <= td1

    div2 = html.DIV()
    div2.style.overflow = "scroll"
    div2.height = 100
    div2.width = 250

    title_text_area = html.TEXTAREA("Title:", id="dataset_title")
    title_text_area.readOnly = True
    #title_text_area.disabled = True
    title_text_area.style.font = "14px verdana"
    title_text_area.rows = 10
    title_text_area.cols = 26
    div2 <= title_text_area

    td2 = html.TD()
    td2 <= div2
    row <= td2

    div3 = html.DIV()
    div3.style.overflow = "scroll"
    div3.height = 100
    div3.width = 450

    description_text_area = html.TEXTAREA("Description:",
                                          id="dataset_description")
    description_text_area.readOnly = True
    #description_text_area.disabled = True
    description_text_area.style.font = "14px verdana"
    description_text_area.rows = 10
    description_text_area.cols = 51
    div3 <= description_text_area

    td3 = html.TD()
    td3 <= div3
    row <= td3

    tableBody <= row
    table <= tableBody
    panel <= table
    panel <= html.BR()
Exemplo n.º 13
0
from browser import document, html, window
#import time
#tt = time.time()
import brywidgets as ws
#print(time.time()-tt)

class DemoPage(ws.NotebookPage):
    def update(self):
        __import__(self.id)

pages = [ws.NotebookPage("Introduction", "powderblue", tabwidth="12%", id="intro")]
for i in range(1,8):
    rgb1, rgb2 = ws.hwbtorgb(60+i*180,0.5,0)[1], ws.hwbtorgb(60+i*180,0.4,0.1)[1]
    pages.append(DemoPage("Demo "+str(i), "rgb({},{},{})".format(*rgb1), tabwidth=None, id="demo"+str(i)))
    pages.append(ws.NotebookPage("Code "+str(i), "rgb({},{},{})".format(*rgb2), html.TEXTAREA(open("demo"+str(i)+".py").read()), tabwidth=None, id="code"+str(i)))
document.select("body")[0].innerHTML = ""
document <= (notebook := ws.Notebook(pages))
pageheight = f"calc(95vh - {notebook.tabrow.offsetHeight}px)"
for page in pages: page.style.height = pageheight

introtext = html.DIV([
html.H1("BrySVG DEMO"),
html.P("""The other tabs on this page provide a series of short demos showing the capabilities of the BrySVG module.
For each demo there is also a tab showing the code needed to create it.  A brief description of each demo follows:"""),
html.P(html.B("Demo 1")+""" - This illustrates MouseMode.PAN: drag the canvas to move the viewport."""+html.BR()+
"""It also shows how to create most of the SVG objects:
CanvasObject, PolylineObject, PolygonObject, RectangleObject, EllipseObject, CircleObject, BezierObject,
ClosedBezierObject, SmoothBezierObject, SmoothClosedBezierObject, TextObject, WrappingTextObject"""+html.BR()+
"""and the use of the CanvasObject methods rotateElement and translateElement.
(The same set of objects is also used in Demo2 and Demo 6.)"""),
html.P(html.B("Demo 2")+""" - This is the famous Tangram puzzle, which demonstrates MouseMode.DRAG and canvas.vertexSnap.
Exemplo n.º 14
0

@draw_button.bind("click")
def draw_a_circle(event):
    global x
    ctx.beginPath()
    ctx.arc(x, 100, 50, 0, math.pi * 2)
    x += 25
    ctx.stroke()


main <= canvas
main <= draw_button

# Text input
text_area = html.TEXTAREA()


@text_area.bind("keydown")
def print_keystrokes(event):
    print(text_area.value)


main <= text_area

# query selector all
buttons = document.querySelectorAll('button')
print(len(buttons))

# ajax
main <= html.H2("BACON")
Exemplo n.º 15
0
def gettext():
    return document["usertext"].value


def setrowcount(n):
    listbox.size = n


#################################################
#    Code for building the page starts here.    #
#################################################

page1 = ws.NotebookPage("Demo", "powderblue", id="page1")
page2 = ws.NotebookPage("Brython code",
                        "khaki",
                        html.TEXTAREA(open("demo.py").read()),
                        id="page2")
page3 = ws.NotebookPage("CSS",
                        "lightgreen",
                        html.TEXTAREA(open("demo.css").read()),
                        id="page3")
page4 = ws.NotebookPage("HTML",
                        "lightpink",
                        html.TEXTAREA(open("demo.html").read()),
                        id="page4")
document <= ws.Notebook([page1, page2, page3, page4])

page1 <= (
    html.H1("Brywidgets Demo"),
    html.P(
        """This page is a demo of most of the widgets in the brywidgets module.
Exemplo n.º 16
0
    def __init__(self,
                 elt_id=None,
                 title="Interactive Interpreter",
                 globals=None,
                 locals=None,
                 history=None,
                 rows=30,
                 cols=84,
                 default_css=True,
                 clear_zone=True,
                 banner=True):
        """
        Create the interpreter.
        - "elt_id" is the id of a textarea in the document. If not set, a new
          popup window is added with a textarea.
        - "globals" and "locals" are the namespaces the RPEL runs in
        - "history", if set, must be a list of strings
        """
        if default_css:
            # Insert default CSS stylesheet if not already loaded
            for stylesheet in document.styleSheets:
                if stylesheet.ownerNode.id == "brython-interpreter":
                    break
            else:
                document <= html.STYLE(style_sheet, id="brython-interpreter")

        if elt_id is None:
            self.dialog = Dialog(title=title,
                                 top=10,
                                 left=10,
                                 default_css=default_css)
            self.zone = html.TEXTAREA(rows=rows,
                                      cols=cols,
                                      Class="brython-interpreter")
            self.dialog.panel <= self.zone
        else:
            if isinstance(elt_id, str):
                try:
                    elt = document[elt_id]
                    if elt.tagName != "TEXTAREA":
                        raise ValueError(
                            f"element {elt_id} is a {elt.tagName}, " +
                            "not a TEXTAREA")
                    self.zone = elt
                except KeyError:
                    raise KeyError(f"no element with id '{elt_id}'")
            elif isinstance(elt_id, DOMNode):
                if elt_id.tagName == "TEXTAREA":
                    self.zone = elt_id
                else:
                    raise ValueError("element is not a TEXTAREA")
            else:
                raise ValueError(
                    "element should be a string or " +
                    f"a TEXTAREA, got '{elt_id.__class__.__name__}'")
        v = sys.implementation.version
        if clear_zone:
            self.zone.value = ''
        if banner:
            self.zone.value += (
                f"Brython {v[0]}.{v[1]}.{v[2]} on "
                f"{window.navigator.appName} {window.navigator.appVersion}"
                "\n")
        self.zone.value += ">>> "
        self.cursor_to_end()
        self._status = "main"
        self.history = history or []
        self.current = len(self.history)

        self.globals = {} if globals is None else globals
        self.globals.update(editor_ns)
        self.locals = self.globals if locals is None else locals

        self.buffer = ''
        sys.stdout.write = sys.stderr.write = self.write
        sys.stdout.__len__ = sys.stderr.__len__ = lambda: len(self.buffer)

        self.zone.bind('keypress', self.keypress)
        self.zone.bind('keydown', self.keydown)
        self.zone.bind('mouseup', self.mouseup)

        self.zone.focus()
Exemplo n.º 17
0
has_ace = True
try:
    editor = window.ace.edit("editor")
    session = editor.getSession()
    session.setMode("ace/mode/python")

    editor.setOptions({
        'enableLiveAutocompletion': True,
        'enableSnippets': True,
        'highlightActiveLine': False,
        'highlightSelectedWord': True
    })
except:
    from browser import html
    editor = html.TEXTAREA(rows=20, cols=70)
    doc["editor"] <= editor

    def get_value():
        return editor.value

    def set_value(x):
        editor.value = x

    editor.getValue = get_value
    editor.setValue = set_value
    has_ace = False

if hasattr(window, 'localStorage'):
    from browser.local_storage import storage
else:
def show_contact(evt):
    """
  Show the contact form
  """
    if len(document['contact_container'].text) > 0:
        document['contact_container'].html = ""
        return

    form = html.FORM(id="contact_form", method='post', action='/contact_form')

    div = html.DIV()
    div <= html.BR() + html.BR()

    label = html.LABEL()
    span = html.SPAN()
    span.text = "Name (required): "
    widget = html.INPUT(id="name",
                        placeholder="Name",
                        type="text",
                        tabindex="1",
                        required=True,
                        autofocus=True)
    label <= span + html.BR() + widget
    div <= label
    form <= div

    div = html.DIV()
    label = html.LABEL()
    span = html.SPAN()
    span.text = "Email (required): "
    widget = html.INPUT(id="email",
                        placeholder="Email address",
                        type="email",
                        tabindex="2",
                        size="30",
                        required=True)
    label <= span + html.BR() + widget
    div <= label
    form <= div

    div = html.DIV()
    label = html.LABEL()
    span = html.SPAN()
    span.text = "Other (if you type anything in this box your message will be trashed): "
    widget = html.INPUT(id="other",
                        placeholder="Don't do it.",
                        type="text",
                        tabindex="3",
                        required=True)
    label <= span + html.BR() + widget
    div <= label
    form <= div

    div = html.DIV()
    label = html.LABEL()
    span = html.SPAN()
    span.text = "Are you a human? If so, how many legs does a dog have? "
    widget = html.INPUT(id="magic",
                        placeholder="How many?",
                        type="text",
                        tabindex="4",
                        size="9",
                        required=True)
    label <= span + html.BR() + widget
    div <= label
    form <= div

    div = html.DIV()
    label = html.LABEL()
    span = html.SPAN()
    span.text = "Message: "
    widget = html.TEXTAREA(id="message",
                           placeholder="Type your message",
                           tabindex="5",
                           cols="60",
                           required=True)
    label <= span + html.BR() + widget
    div <= label
    form <= div

    div = html.DIV()
    button = html.BUTTON(type="button", id="contact_submit")
    button.text = "Submit Message"
    div <= button
    form <= div

    document['contact_container'] <= form
    document['contact_submit'].bind('click', submit_contact)
    window.scrollBy(0, 50)