Example #1
0
def insert_security_info(page, *dummy):
    """Inserts security information on a page"""
    if not len(page.body):
        return

    create_security_menu_item(page)

    # Next, the hidden container for the full security information

    if not page.includes("security_included"):
        page.add_include("security_included")
        page.insert_js_file("/javascript/security.js")

        info_container = Element("div", id="security_info")

        # prompt user to approve sites as soon as the first page is loaded
        # if there are sites for which to confirm the security level.
        if ((page.url.startswith("/index") or page.url == "/")
                # will work with /index_fr.html ...
                and config[page.username]['site_security']
                # something to confirm
                and not config[page.username]['initial_security_set']):
            # only do it once per session
            confirm_at_start(page, info_container)
            config[page.username]['initial_security_set'] = True
        else:
            page.add_css_code(security_css % ('none', 'none'))
            format_report(page, info_container)

        page.body.append(info_container)
        info_container_x = Element("div",
                                   id="security_info_x",
                                   onclick="hide_security_info()")
        info_container_x.text = "X"
        page.body.append(info_container_x)
Example #2
0
def insert_security_info(page, *dummy):
    """Inserts security information on a page"""
    if not len(page.body):
        return

    create_security_menu_item(page)

    # Next, the hidden container for the full security information

    if not page.includes("security_included"):
        page.add_include("security_included")
        page.insert_js_file("/javascript/security.js")

        info_container = Element("div", id="security_info")

        # prompt user to approve sites as soon as the first page is loaded
        # if there are sites for which to confirm the security level.
        if ((page.url.startswith("/index") or page.url=="/")
                  # will work with /index_fr.html ...
              and config[page.username]['site_security']
                  # something to confirm
              and not config[page.username]['initial_security_set']):
                  # only do it once per session
            confirm_at_start(page, info_container)
            config[page.username]['initial_security_set'] = True
        else:
            page.add_css_code(security_css%('none','none'))
            format_report(page, info_container)

        page.body.append(info_container)
        info_container_x = Element("div", id="security_info_x",
                                        onclick="hide_security_info()")
        info_container_x.text = "X"
        page.body.append(info_container_x)
Example #3
0
def code_setup_process(page, elem, uid):
    """Style and saves a copy of the setup code. This code currently
    does not work because it depends on the obsoleted style_pycode
    service in the colourize plugin."""

    raise NotImplementedError()

    vlam = elem.attrib["title"]
    name = extract_name(vlam)
    # next, we style the code, also extracting it in a useful form
    setup_code, markup, error = plugin['services'].style_pycode(
        page, elem, css_class='test_setup')
    if error is not None:
        markup = copy.deepcopy(elem)
    # which we store
    code_setups[name] = setup_code
    # reset the original element to use it as a container.  For those
    # familiar with dealing with ElementTree Elements, in other context,
    # note that the style_pycode() method extracted all of the existing
    # text, removing any original markup (and other elements), so that we
    # do not need to save either the "text" attribute or the "tail" one
    # before resetting the element.
    elem.clear()
    elem.tag = "div"
    elem.attrib["id"] = "div_" + uid
    elem.attrib['class'] = "test_setup"
    # We insert the styled setup code inside this container element:
    elem.append(markup)
    # Create a title
    h4 = Element('h4')
    h4.text = "Setup code; name= %s" % name
    elem.insert(0, h4)
Example #4
0
def insert_code(page, elem, uid, lines, lineno):
    '''insert the code in the element and style it appropriately'''
    # Note: in developping this plugin, we observed that the code was styled
    # automatically - that is the "div/getsource" handler was called before the
    # "pre" handler was.  This could just be a coincidence on which we can not
    # rely.
    pre = Element("pre")
    if 'editor' in elem.attrib['title']:
        vlam = "editor"
    elif 'interpreter' in elem.attrib['title']:
        vlam = "interpreter"
    elif python_version < 3:
        vlam = "python"
    else:
        vlam = "python3"
    if "linenumber" in elem.attrib['title']:
        vlam += " linenumber=%s"%lineno
    pre.attrib['title'] = vlam
    pre.text ="".join(lines)
    if 'editor' in vlam:
        insert_editor(page, elem, uid, lines, lineno)
    elif 'interpreter' in vlam:
        insert_interpreter(page, elem, uid, lines, lineno)
    else:
        dummy, dummy = plugin['services'].style(page, pre, None, vlam)
        elem.append(pre)
    # prevent any further processing
    pre.attrib["title"] = "no_vlam"
    return
Example #5
0
def code_setup_process(page, elem, uid):
    """Style and saves a copy of the setup code. This code currently
    does not work because it depends on the obsoleted style_pycode
    service in the colourize plugin."""

    raise NotImplementedError()

    vlam = elem.attrib["title"]
    name = extract_name(vlam)
    # next, we style the code, also extracting it in a useful form
    setup_code, markup, error = plugin['services'].style_pycode(page,
                                                   elem, css_class='test_setup')
    if error is not None:
        markup = copy.deepcopy(elem)
    # which we store
    code_setups[name] = setup_code
    # reset the original element to use it as a container.  For those
    # familiar with dealing with ElementTree Elements, in other context,
    # note that the style_pycode() method extracted all of the existing
    # text, removing any original markup (and other elements), so that we
    # do not need to save either the "text" attribute or the "tail" one
    # before resetting the element.
    elem.clear()
    elem.tag = "div"
    elem.attrib["id"] = "div_" + uid
    elem.attrib['class'] = "test_setup"
    # We insert the styled setup code inside this container element:
    elem.append(markup)
    # Create a title
    h4 = Element('h4')
    h4.text = "Setup code; name= %s" % name
    elem.insert(0, h4)
Example #6
0
def create_empty_menu():  # tested
    '''creates the basic menu structure including only the title'''
    menu = Element('div')
    menu.attrib['class'] = "crunchy_menu"
    _ul = SubElement(menu, "ul")
    _li = SubElement(_ul, "li")
    _li.text = _("Crunchy Menu")
    menu_items = SubElement(_li, "ul")
    return menu, menu_items
Example #7
0
def create_empty_menu(): # tested
    '''creates the basic menu structure including only the title'''
    menu = Element('div')
    menu.attrib['class'] = "crunchy_menu"
    _ul = SubElement(menu, "ul")
    _li = SubElement(_ul, "li")
    _li.text = _("Crunchy Menu")
    menu_items = SubElement(_li, "ul")
    return menu, menu_items
Example #8
0
def code_sample_process(page, elem, uid):
    """Style and saves a copy of the sample code. This code currently
    does not work because it depends on the obsoleted style_pycode
    service in the colourize plugin."""

    raise NotImplementedError()

    vlam = elem.attrib["title"]
    name = extract_name(vlam)
    names[uid] = name
    # When a security mode is set to "display ...", we only parse the
    # page, but no Python execution from is allowed from that page.
    # If that is the case, we won't include javascript either, to make
    # thus making the source easier to read.
    if 'display' not in config[page.username]['page_security_level'](page.url):
        if not page.includes("code_test_included") :
            page.add_include("code_test_included")
            page.add_js_code(code_test_jscode)
            page.add_js_code(complete_test_jscode)
            page.add_css_code(css)
            insert_comprehensive_test_button(page)
    # next, we style the code, also extracting it in a useful form
    sample_code, markup, error = plugin['services'].style_pycode(page, elem)
    if error is not None:
        markup = copy.deepcopy(elem)    # which we store
    code_samples[name] = sample_code
    # reset the original element to use it as a container.  For those
    # familiar with dealing with ElementTree Elements, in other context,
    # note that the style_pycode() method extracted all of the existing
    # text, removing any original markup (and other elements), so that we
    # do not need to save either the "text" attribute or the "tail" one
    # before resetting the element.
    elem.clear()
    elem.tag = "div"
    elem.attrib["id"] = "div_" + uid
    elem.attrib['class'] = "crunchy"
    # We insert the styled sample code inside this container element:
    elem.append(markup)
    # Create a title
    h4 = Element('h4')
    h4.text = "Sample code; name= %s" % name
    elem.insert(0, h4)
    #some spacing:
    SubElement(elem, "br")
    # the actual button used for code execution:
    btn = SubElement(elem, "button")
    btn.text = "Run code check"
    btn.attrib["onclick"] = "exec_code_check('%s')" % uid
    SubElement(elem, "br")
    # finally, an output subwidget:
    plugin['services'].insert_io_subwidget(page, elem, uid)
    return
Example #9
0
def code_sample_process(page, elem, uid):
    """Style and saves a copy of the sample code. This code currently
    does not work because it depends on the obsoleted style_pycode
    service in the colourize plugin."""

    raise NotImplementedError()

    vlam = elem.attrib["title"]
    name = extract_name(vlam)
    names[uid] = name
    # When a security mode is set to "display ...", we only parse the
    # page, but no Python execution from is allowed from that page.
    # If that is the case, we won't include javascript either, to make
    # thus making the source easier to read.
    if 'display' not in config[page.username]['page_security_level'](page.url):
        if not page.includes("code_test_included"):
            page.add_include("code_test_included")
            page.add_js_code(code_test_jscode)
            page.add_js_code(complete_test_jscode)
            page.add_css_code(css)
            insert_comprehensive_test_button(page)
    # next, we style the code, also extracting it in a useful form
    sample_code, markup, error = plugin['services'].style_pycode(page, elem)
    if error is not None:
        markup = copy.deepcopy(elem)  # which we store
    code_samples[name] = sample_code
    # reset the original element to use it as a container.  For those
    # familiar with dealing with ElementTree Elements, in other context,
    # note that the style_pycode() method extracted all of the existing
    # text, removing any original markup (and other elements), so that we
    # do not need to save either the "text" attribute or the "tail" one
    # before resetting the element.
    elem.clear()
    elem.tag = "div"
    elem.attrib["id"] = "div_" + uid
    elem.attrib['class'] = "crunchy"
    # We insert the styled sample code inside this container element:
    elem.append(markup)
    # Create a title
    h4 = Element('h4')
    h4.text = "Sample code; name= %s" % name
    elem.insert(0, h4)
    #some spacing:
    SubElement(elem, "br")
    # the actual button used for code execution:
    btn = SubElement(elem, "button")
    btn.text = "Run code check"
    btn.attrib["onclick"] = "exec_code_check('%s')" % uid
    SubElement(elem, "br")
    # finally, an output subwidget:
    plugin['services'].insert_io_subwidget(page, elem, uid)
    return
Example #10
0
def insert_browser(page, *dummy):  # tested
    '''Inserts a default file/url browser at the bottom of a page'''
    div = Element("div")
    div.text = ' '

    browser = plugin.get(config[page.username]['power_browser'])
    if not browser:
        return

    try:
        browser(page, div, 'dummy')
        page.body.append(div)
    except:
        print(traceback.format_exc())
        return
Example #11
0
def insert_comprehensive_test_button(page):
    '''inserts a button to enable all tests on a page be executed with
       a single click'''
    style = "margin-left: 400px; font-size: 40pt"
    text = "Run all tests"
    action = "check_all_code_samples('%s')" % page.pageid

    label = 'btn1_' + page.pageid
    btn1 = Element("button", style=style, onclick=action, id=label, label=label)
    btn1.text = text
    page.body.insert(0, btn1)  # insert at the top

    label = 'btn2_' + page.pageid
    btn2 = Element("button", style=style, onclick=action, id=label, label=label)
    btn2.text = text
    page.body.append(btn2)  # append at the bottom
    return
Example #12
0
def add_configuration_to_menu(page):
    '''adds a menu item allowing the user to choose the preferences'''
    menu_item = Element("li")
    link = SubElement(menu_item,
                      'a',
                      href="/docs/basic_tutorial/preferences.html")
    link.text = _("Preferences")
    additional_menu_items['preferences'] = menu_item
Example #13
0
def add_browsing_to_menu(dummy):
    '''adds a menu item allowing the user to go the the browsers page'''
    menu_item = Element("li")
    link = SubElement(menu_item,
                      'a',
                      href="/docs/basic_tutorial/browsing.html")
    link.text = _("Browsing")
    additional_menu_items['browsing'] = menu_item
Example #14
0
def unittest_widget_callback(page, elem, uid):
    """Handles embedding suitable code into the page in order to display and
    run unittests"""
    vlam = elem.attrib["title"]
    log_id = extract_log_id(vlam)
    if log_id:
        t = 'unittest'
        config[page.username]['logging_uids'][uid] = (log_id, t)

    # When a security mode is set to "display ...", we only parse the
    # page, but no Python execution from is allowed from that page.
    # If that is the case, we won't include javascript either, to make
    # thus making the source easier to read.
    if 'display' not in config[page.username]['page_security_level'](page.url):
        if not page.includes("unittest_included"):
            page.add_include("unittest_included")
            page.add_js_code(unittest_jscode)

    elem.attrib['title'] = "python"
    unittestcode, show_vlam = plugin['services'].style(page, elem, None, vlam)
    elem.attrib['title'] = vlam

    if log_id:
        config['log'][log_id] = [tostring(markup)]
    # which we store
    unittests[uid] = unittestcode

    wrap_in_div(elem, uid, vlam, "doctest", show_vlam)
    if config[page.username]['popups']:
        # insert popup helper
        img = Element("img",
                      src="/images/help.png",
                      style="height:32px;",
                      title="cluetip Hello %s! " % page.username +
                      "This is a unittest.; click for more.",
                      rel="/docs/popups/unittest.html")
        elem.append(img)
        plugin['services'].insert_cluetip(page, img, uid)

    #insert_markup(elem, uid, vlam, markup, "unittest")

    # call the insert_editor_subwidget service to insert an editor:
    plugin['services'].insert_editor_subwidget(page, elem, uid)
    #some spacing:
    SubElement(elem, "br")
    # the actual button used for code execution:
    btn = SubElement(elem, "button")
    btn.text = "Run Unittest"
    btn.attrib["onclick"] = "exec_unittest('%s')" % uid
    if "analyzer_score" in vlam:
        plugin['services'].add_scoring(page, btn, uid)
    if "analyzer_report" in vlam:
        plugin['services'].insert_analyzer_button(page, elem, uid)
    SubElement(elem, "br")
    # finally, an output subwidget:
    plugin['services'].insert_io_subwidget(page, elem, uid)
Example #15
0
def transform_rst(page):
    """transforms the elements in an rst page so that they can
    be merged into a template.  It is assumed that the
    entire body content is to be used as the content inside the template."""
    for div in page.tree.findall(".//div"):
        if "class" in div.attrib:
            if div.attrib["class"] == "document" or div.attrib["class"] == "section":
                div.tag = "span"
    new_body = copy.deepcopy(page.body)
    new_body.tag = "div"
    new_body.attrib["id"] = "content"
    page.body.clear()
    page.body.text = ""
    page.body.append(new_body)
    for title in page.tree.findall(".//title"):  # there should be only one:
        div = Element("div")
        div.attrib["id"] = "main_title"
        div.text = title.text
        page.body.insert(0, div)
        break
Example #16
0
def create_show_vlam(page, elem, vlam):
    '''Creates a <code> element showing the complete vlam options
    used, as well as the element type.'''
    if 'show_vlam' not in vlam:
        return None
    cssclass = config[page.username]['style']
    attributes = ' title="%s"' % vlam
    for attr in elem.attrib:
        if attr != 'title':
            attributes += ' %s="%s"' % (attr, elem.attrib[attr])
    elem_info = '<%s%s> ... </%s>' % (elem.tag, attributes, elem.tag)
    styled_elem_info = _style(elem_info, 'html', cssclass)
    show_vlam = fromstring(styled_elem_info)
    show_vlam.tag = 'code'
    show_vlam.attrib['class'] = CRUNCHY_PYGMENTS
    display = Element('h3')
    display.attrib['class'] = "show_vlam"
    display.text = "VLAM = "
    display.append(show_vlam)
    return display
Example #17
0
def transform_rst(page):
    '''transforms the elements in an rst page so that they can
    be merged into a template.  It is assumed that the
    entire body content is to be used as the content inside the template.'''
    for div in page.tree.findall(".//div"):
        if 'class' in div.attrib:
            if (div.attrib['class'] == 'document'
                    or div.attrib['class'] == 'section'):
                div.tag = 'span'
    new_body = copy.deepcopy(page.body)
    new_body.tag = "div"
    new_body.attrib["id"] = "content"
    page.body.clear()
    page.body.text = ''
    page.body.append(new_body)
    for title in page.tree.findall(".//title"):  # there should be only one:
        div = Element("div")
        div.attrib["id"] = "main_title"
        div.text = title.text
        page.body.insert(0, div)
        break
Example #18
0
def insert_comprehensive_test_button(page):
    '''inserts a button to enable all tests on a page be executed with
       a single click'''
    style = "margin-left: 400px; font-size: 40pt"
    text = "Run all tests"
    action = "check_all_code_samples('%s')" % page.pageid

    label = 'btn1_' + page.pageid
    btn1 = Element("button",
                   style=style,
                   onclick=action,
                   id=label,
                   label=label)
    btn1.text = text
    page.body.insert(0, btn1)  # insert at the top

    label = 'btn2_' + page.pageid
    btn2 = Element("button",
                   style=style,
                   onclick=action,
                   id=label,
                   label=label)
    btn2.text = text
    page.body.append(btn2)  # append at the bottom
    return
Example #19
0
def insert_markup(elem, uid, vlam, markup, interactive_type):
    '''clears an element and inserts the new markup inside it'''
    elem.clear()
    elem.tag = "div"
    elem.attrib["id"] = "div_"+uid
    elem.attrib['class'] = interactive_type # 'editor', 'doctest', 'interpreter'
    if not "no_pre" in vlam:
        try:
            new_div = Element("div")
            new_div.append(markup)
            new_div.attrib['class'] = 'sample_python_code'
            elem.insert(0, new_div)
        except AssertionError:  # this should never happen
            elem.insert(0, Element("br"))
            bold = Element("b")
            span = Element("span")
            span.text = "AssertionError from ElementTree"
            bold.append(span)
            elem.insert(1, bold)
Example #20
0
def wrap_in_div(elem, uid, vlam, element_type, show_vlam):
    '''wraps a styled code inside a div'''
    elem_copy = copy.deepcopy(elem)
    elem.clear()
    elem.text = ''
    elem.tag = "div"
    elem.attrib["id"] = "div_"+uid
    username = names[uid.split("_")[0]]
    # element_type = 'editor', 'doctest', etc.
    elem.attrib['class'] = element_type + " " + config[username]['style']
    if not "no_pre" in vlam:
        try:
            elem.append(elem_copy)
        except AssertionError:  # this should never happen
            elem.insert(0, Element("br"))
            bold = Element("b")
            span = Element("span")
            span.text = "AssertionError from ElementTree"
            bold.append(span)
            elem.insert(1, bold)
            return
    if show_vlam is not None:
        elem.insert(0, show_vlam)
Example #21
0
def insert_interactive_objects(page):
    '''inserts the interactive objects required in a slideshow'''
    if not page.includes("slideshow_included"):
        return
    for div in page.tree.getiterator("div"):
        if 'class' in div.attrib:
            if div.attrib['class'] == "presentation":
                # add slide with interpreter
                new_div = Element("div")
                new_div.attrib['class'] = "slide"
                # new_div is not processed by set_overflow above which is why
                # we must set this property explictly.
                new_div.attrib['style'] = "height: 70%; overflow: auto;"
                new_div.attrib['id'] = "crunchy_interpreter"
                pre = SubElement(new_div, "pre", title="interpreter")
                # the following text is at least 50 characters
                # with a non-space character at the end.  This is to allow
                # the creation of a list with "short" titles to select
                # a given slide.
                # see slides.js line 100
                pre.text = "# Crunchy Interpreter                             #"
                uid = page.pageid + "_" + uidgen(page.username)
                plugin['services'].insert_interpreter(page, pre, uid)
                div.append(new_div)
                # add slide with editor
                new_div2 = Element("div")
                new_div2.attrib['class'] = "slide"
                # new_div2 is not processed by set_overflow above ...
                new_div2.attrib['style'] = "height: 70%; overflow: auto;"
                new_div2.attrib['id'] = "crunchy_editor"
                pre2 = SubElement(new_div2, "pre", title="editor")
                # same as above.
                pre2.text = "# Crunchy editor                                 #"
                uid = page.pageid + "_" + uidgen(page.username)
                plugin['services'].insert_editor(page, pre2, uid)
                div.append(new_div2)
                return
Example #22
0
def insert_bare_editor(page, elem, uid):
    """inserts a 'bare' editor, python code, but no execution buttons.

    Common code to both insert_editor() and insert_alternate_python().
    """
    vlam = elem.attrib["title"]
    log_id = util.extract_log_id(vlam)
    if log_id:
        t = 'editor'
        config[page.username]['logging_uids'][uid] = (log_id, t)

    # When a security mode is set to "display ...", we only parse the
    # page, but no Python execution from is allowed from that page.
    # If that is the case, we won't include javascript either,
    # thus making the source easier to read.
    if 'display' not in config[page.username]['page_security_level'](page.url):
        if not page.includes("exec_included"):
            page.add_include("exec_included")
            page.add_js_code(exec_jscode)
    # then we can go ahead and add html markup, extracting the Python
    # code to be executed in the process
    python_code = util.extract_code(elem)
    if util.is_interpreter_session(python_code):
        elem.attrib['title'] = "pycon"
        python_code = util.extract_code_from_interpreter(python_code)
    else:
        elem.attrib['title'] = "python"
    dummy, show_vlam = plugin['services'].style(page, elem, None, vlam)
    elem.attrib['title'] = vlam
    if log_id:
        config[page.username]['log'][log_id] = [tostring(elem)]
    util.wrap_in_div(elem, uid, vlam, "editor", show_vlam)
    if config[page.username]['popups']:
        # insert popup helper
        img = Element("img",
                      src="/images/help.png",
                      style="height:32px;",
                      title="cluetip Hello %s! " % page.username +
                      "This is an Editor; click for more",
                      rel="/docs/popups/editor.html")
        elem.append(img)
        plugin['services'].insert_cluetip(page, img, uid)

    if (("no_copy" in vlam) and not ("no_pre" in vlam)) or (not python_code):
        python_code = "\n"
    plugin['services'].insert_editor_subwidget(page, elem, uid, python_code)
    return vlam
Example #23
0
def create_security_menu_item(page):
    '''creates the security report menu item'''

    if 'display' in page.security_info['level']:
        security_result_image = '/images/display.png'
    elif page.security_info['number removed'] == 0:
        security_result_image = '/images/ok.png'
    else:
        security_result_image = '/images/warning.png'

    security_item = Element("li")
    a = SubElement(security_item,
                   "a",
                   id="security_info_link",
                   href="#",
                   onclick="show_security_info();",
                   title="security_link")
    a.text = "Security: "
    SubElement(a, "img", src=security_result_image)
    additional_menu_items['security_report'] = security_item
    return
Example #24
0
def wrap_in_div(elem, uid, vlam, element_type, show_vlam):
    '''wraps a styled code inside a div'''
    elem_copy = copy.deepcopy(elem)
    elem.clear()
    elem.text = ''
    elem.tag = "div"
    elem.attrib["id"] = "div_" + uid
    username = names[uid.split("_")[0]]
    # element_type = 'editor', 'doctest', etc.
    elem.attrib['class'] = element_type + " " + config[username]['style']
    if not "no_pre" in vlam:
        try:
            elem.append(elem_copy)
        except AssertionError:  # this should never happen
            elem.insert(0, Element("br"))
            bold = Element("b")
            span = Element("span")
            span.text = "AssertionError from ElementTree"
            bold.append(span)
            elem.insert(1, bold)
            return
    if show_vlam is not None:
        elem.insert(0, show_vlam)
Example #25
0
def insert_interactive_objects(page):
    '''inserts the interactive objects required in a slideshow'''
    if not page.includes("slideshow_included"):
        return
    for div in page.tree.getiterator("div"):
        if 'class' in div.attrib:
            if div.attrib['class'] == "presentation":
                # add slide with interpreter
                new_div = Element("div")
                new_div.attrib['class'] = "slide"
                # new_div is not processed by set_overflow above which is why
                # we must set this property explictly.
                new_div.attrib['style'] = "height: 70%; overflow: auto;"
                new_div.attrib['id'] = "crunchy_interpreter"
                pre = SubElement(new_div, "pre", title="interpreter")
                # the following text is at least 50 characters
                # with a non-space character at the end.  This is to allow
                # the creation of a list with "short" titles to select
                # a given slide.
                # see slides.js line 100
                pre.text = "# Crunchy Interpreter                             #"
                uid = page.pageid + "_" + uidgen(page.username)
                plugin['services'].insert_interpreter(page, pre, uid)
                div.append(new_div)
                # add slide with editor
                new_div2 = Element("div")
                new_div2.attrib['class'] = "slide"
                # new_div2 is not processed by set_overflow above ...
                new_div2.attrib['style'] = "height: 70%; overflow: auto;"
                new_div2.attrib['id'] = "crunchy_editor"
                pre2 = SubElement(new_div2, "pre", title="editor")
                # same as above.
                pre2.text = "# Crunchy editor                                 #"
                uid = page.pageid + "_" + uidgen(page.username)
                plugin['services'].insert_editor(page, pre2, uid)
                div.append(new_div2)
                return
Example #26
0
def create_show_vlam(page, elem, vlam):
    '''Creates a <code> element showing the complete vlam options
    used, as well as the element type.'''
    if 'show_vlam' not in vlam:
        return None
    cssclass = config[page.username]['style']
    attributes = ' title="%s"' % vlam
    for attr in elem.attrib:
        if attr != 'title':
            attributes += ' %s="%s"' % (attr, elem.attrib[attr])
    elem_info = '<%s%s> ... </%s>' % (elem.tag, attributes, elem.tag)
    styled_elem_info = _style(elem_info, 'html', cssclass)
    show_vlam = fromstring(styled_elem_info)
    show_vlam.tag = 'code'
    show_vlam.attrib['class'] = CRUNCHY_PYGMENTS
    display = Element('h3')
    display.attrib['class'] = "show_vlam"
    display.text = "VLAM = "
    display.append(show_vlam)
    return display
Example #27
0
def insert_markup(elem, uid, vlam, markup, interactive_type):
    '''clears an element and inserts the new markup inside it'''
    elem.clear()
    elem.tag = "div"
    elem.attrib["id"] = "div_" + uid
    elem.attrib[
        'class'] = interactive_type  # 'editor', 'doctest', 'interpreter'
    if not "no_pre" in vlam:
        try:
            new_div = Element("div")
            new_div.append(markup)
            new_div.attrib['class'] = 'sample_python_code'
            elem.insert(0, new_div)
        except AssertionError:  # this should never happen
            elem.insert(0, Element("br"))
            bold = Element("b")
            span = Element("span")
            span.text = "AssertionError from ElementTree"
            bold.append(span)
            elem.insert(1, bold)
Example #28
0
def insert_tooltip(page, *dummy):
    '''inserts a (hidden) tooltip object in a page'''
    if not page.includes("tooltip_included") and len(page.body):
        borg_console[page.pageid] = interpreter.BorgConsole(group=page.pageid)

        page.add_include("tooltip_included")
        page.insert_js_file("/javascript/tooltip.js")
        page.add_js_code(tooltip_js)

        tooltip = Element("div")
        tooltip.attrib["id"] = "interp_tooltip"
        tooltip.text = " "
        page.body.append(tooltip)

        help_menu = Element("div")
        help_menu.attrib["id"] = "help_menu"
        help_menu.text = " "
        page.body.append(help_menu)

        help_menu_x = Element("div")
        help_menu_x.attrib["id"] = "help_menu_x"
        help_menu_x.attrib["onclick"] = "hide_help();"
        help_menu_x.text = "X"
        page.body.append(help_menu_x)
Example #29
0
def insert_interpreter(page, elem, uid):
    """inserts an interpreter (and the js code to initialise an interpreter)"""

    vlam = elem.attrib["title"]
    interp_kind = select_type(
        vlam, config[page.username]['override_default_interpreter'], elem)

    # When a security mode is set to "display ...", we only parse the
    # page, but no Python execution from is allowed from that page.
    # If that is the case, we won't include javascript either, to make
    # thus making the source easier to read.
    show = True
    if not ('display' in config[page.username]['page_security_level'](page.url)
            or interp_kind == None):
        include_interpreter(interp_kind, page, uid)
        log_id = util.extract_log_id(vlam)
        if log_id:
            t = 'interpreter'
            config[page.username]['logging_uids'][uid] = (log_id, t)
    else:
        log_id = False
        show = False

    # then we can go ahead and add html markup, extracting the Python
    # code to be executed in the process - we will not need this code;
    # this could change in a future version where we could add a button to
    # have the code automatically "injected" and executed by the
    # interpreter, thus saving some typing by the user.

    python_code = util.extract_code(elem)
    if util.is_interpreter_session(python_code):
        elem.attrib['title'] = "pycon"
        python_code = util.extract_code_from_interpreter(python_code)
    else:
        elem.attrib['title'] = "python"
    dummy, show_vlam = plugin['services'].style(page, elem, None, vlam)
    elem.attrib['title'] = vlam
    if log_id:
        config[page.username]['log'][log_id] = [tostring(elem)]
    util.wrap_in_div(elem, uid, vlam, "interpreter", show_vlam)

    if config[page.username][
            'popups'] and interp_kind is not None and not page.includes(
                "interpreter_helper"):
        page.add_include("interpreter_helper")
        # insert popup helper
        img = Element("img",
                      src="/images/help.png",
                      style="height:32px;",
                      title="cluetip Hello %s! " % page.username +
                      titles[interp_kind],
                      rel=help_files[interp_kind])
        elem.append(img)
        plugin['services'].insert_cluetip(page, img, uid)
    plugin['services'].insert_io_subwidget(page,
                                           elem,
                                           uid,
                                           interp_kind=interp_kind,
                                           sample_code=python_code,
                                           show=show)
    plugin['services'].insert_tooltip(page, elem, uid)
    return
Example #30
0
def create_quit():  # tested
    '''creates the quit element for the menu'''
    Quit = Element("li")
    a = SubElement(Quit, "a", href=server['exit'])
    a.text = _("Quit Crunchy")
    return Quit
Example #31
0
def create_home():  # tested
    '''creates the home element for the menu'''
    home = Element("li")
    a = SubElement(home, "a", href="/index.html")
    a.text = _("Crunchy Home")
    return home
Example #32
0
def insert_io_subwidget(page, elem, uid, interp_kind=None,
                        sample_code='', show=False):  # partially tested
    """insert an output widget into elem, usable for editors and interpreters,
    and includes a canvas.
    """
    # embed the io widget inside a div so that it could be floated left
    # or right ... or whatever.
    # insert another div below, that can have it style set to "clear:both;"
    # so that it can work together with the floated io widget
    # (and python code sample) to have a two-column display if desired.
    new_div = SubElement(elem, "div")
    new_div.attrib['class'] = "io_div " + interface.crunchy_pygments
    clear_div = SubElement(elem, "div")
    clear_div.attrib['class'] = "end_io_widget"

    # When a security mode is set to "display ...", we only parse the
    # page, but no Python execution from is allowed from that page.
    # If that is the case, we won't include javascript either, to make
    # thus making the source easier to read.
    if 'display' not in config[page.username]['page_security_level'](page.url):
        if config['ctypes_available']:
            kill_link = Element("a")
            elem.insert(-2, kill_link)
            kill_link.attrib["id"] = "kill_%s" % uid
            kill_link.attrib["onclick"] = "kill_thread('%s')" % uid
            kill_image = SubElement(kill_link, 'img')
            kill_image.attrib["src"] = "/images/stop.png"
            kill_image.attrib["alt"] = _("Interrupt thread")
            kill_image.attrib["class"] = "kill_thread_image"
            _id = "kill_image_%s" % uid
            kill_image.attrib["id"] = _id
            if config[page.username]['popups']:
                # insert popup helper
                kill_image.attrib["title"] = "cluetip KeyboardInterrupt"
                kill_image.attrib["rel"] = "/docs/popups/keyboard_interrupt.html"
                plugin['services'].insert_cluetip(page, kill_image, _id)

            # hide them initially
            kill_image.attrib['style'] = 'display: none;'
            kill_link.attrib['style'] = 'display: none;'

        if not page.includes("io_included"):
            page.add_include("io_included")
            page.add_js_code(io_js)

        if interp_kind is not None:
            if not page.includes("push_input_included"):
                page.add_include("push_input_included")
                page.add_js_code(push_input)
            # needed for switching to edit area; not currently working
            if not page.includes("editarea_included"):
                page.add_include("editarea_included")
                page.add_js_code(editArea_load_and_save)
                page.insert_js_file("/edit_area/edit_area_crunchy.js")
        elif config['ctypes_available']:
            kill_image.attrib['style'] = 'display:none;'  # revealed by Execute button
    else:
        return

    output = SubElement(new_div, "span")
    output.attrib["class"] = "output"
    output.attrib["id"] = "out_" + uid
    output.text = "\n"
    span_input = SubElement(new_div, "span")
    inp = SubElement(span_input, "input")
    inp.attrib["id"] = "in_" + uid
    inp.attrib["onkeydown"] = 'return push_keys(event, "%s")' % uid
    if interp_kind is not None:
        editor_link = SubElement(span_input, "a")
        editor_link.attrib["onclick"] = "return convertToEditor(this,'%s')" \
                                      % _("Execute")
        editor_link.attrib["id"] = "ed_link_" + uid
        image = SubElement(editor_link, 'img')
        image.attrib["src"] = "/images/editor.png"
        image.attrib["alt"] = _("copy existing code")
        image.attrib["class"] = "interpreter_image"

        code_sample = SubElement(new_div, "textarea")
        code_sample.attrib["id"] = "code_sample_" + uid
        code_sample.attrib["style"] = 'visibility:hidden;overflow:hidden;z-index:-1;position:fixed;top:0;'
        code_sample.text = sample_code + '\n'
    if interp_kind == 'borg':
        inp.attrib["onkeypress"] = 'return tooltip_display(event, "%s")' % uid
    inp.attrib["type"] = "text"
    if show:
        inp.attrib["class"] = "input"
    else:
        inp.attrib["class"] = "input hidden"