class ExampleBlock(Block):
    """
    ExampleBlock can render and process ExampleIdevices as XHTML
    GenericBlock will replace it..... one day
    """
    def __init__(self, parent, idevice):
        Block.__init__(self, parent, idevice)
        self.contentElement = TextAreaElement(idevice.content)
        self.contentElement.height = 250


    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        Block.process(self, request)
        content = self.contentElement.process(request)
        if content:
            self.idevice.content = content


    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        html  = u"<div>\n"
        html += self.contentElement.renderEdit()
        html += self.renderEditButtons()
        html += u"</div>\n"
        return html


    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\" "
        html += u"ondblclick=\"submitLink('edit',"+self.id+", 0);\">\n"
        html += self.contentElement.renderView()
        html += self.renderViewButtons()
        html += "</div>\n"
        return html


    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\">\n"
        html += self.contentElement.renderView()
        html += u"</div>\n"
        return html
Beispiel #2
0
class ExampleBlock(Block):
    """
    ExampleBlock can render and process ExampleIdevices as XHTML
    GenericBlock will replace it..... one day
    """
    def __init__(self, parent, idevice):
        Block.__init__(self, parent, idevice)
        self.contentElement = TextAreaElement(idevice.content)
        self.contentElement.height = 250

    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        Block.process(self, request)
        content = self.contentElement.process(request)
        if content:
            self.idevice.content = content

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        html = u"<div>\n"
        html += self.contentElement.renderEdit()
        html += self.renderEditButtons()
        html += u"</div>\n"
        return html

    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        html = u"<div class=\"iDevice "
        html += u"emphasis" + unicode(self.idevice.emphasis) + "\" "
        html += u"ondblclick=\"submitLink('edit'," + self.id + ", 0);\">\n"
        html += self.contentElement.renderView()
        html += self.renderViewButtons()
        html += "</div>\n"
        return html

    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        html = u"<div class=\"iDevice "
        html += u"emphasis" + unicode(self.idevice.emphasis) + "\">\n"
        html += self.contentElement.renderView()
        html += u"</div>\n"
        return html
class GenericHTMLBlock(Block):
    
    def __init__(self, parent, idevice):
        Block.__init__(self, parent, idevice)
        self.content_element = TextAreaElement(idevice.content_field)
        self.content_element.idevice = idevice
        
    def process(self, request):
        if self.id + "_htmlcontent" in request.args:
            request.args[self.content_element.id] = request.args[self.id+"_htmlcontent"]
        
        Block.process(self, request)
        self.content_element.process(request)
    
    
    def renderEdit(self, style):
        idevice_dir_name = self.idevice.get_idevice_dirname()
        html = u"<div>"
        html += common.ideviceShowEditMessage(self)
        
        html  = u"<div class='idevice_authoring_container' " \
            + "data-idevicetype='%s' " % idevice_dir_name \
            + "data-ideviceid='%s'>\n" % self.idevice.id
        
        
        # the content without wrapping div etc.
        content_html = self.content_element.field.content_w_resourcePaths
        
        html += content_html
        
        html += "</div>"
        html += "<input type='hidden' name='%s_htmlcontent'/>\n" % self.id
        html += "<input type='hidden' name='%s_resources'/>\n" % self.id
        html += self.renderEditButtons()
        html += u"</div>\n"
        
        return html

    def renderPreview(self, style):
        html = common.ideviceHeader(self, style, "preview")
        html += self.content_element.renderView()
        html += common.ideviceFooter(self, style, "preview")
        
        return html
    
    def renderView(self, style):
        html = common.ideviceHeader(self, style, "view")
        html += self.content_element.renderPreview()
        html += common.ideviceFooter(self, style, "view")
        
        return html
class PlacableObjectElement(Element):
    
    #here field should be placeableobjectfield
    def __init__(self, field):
        Element.__init__(self, field)
        # there is then field.maincontent, field.width, field.height, field.correctx, field.correcty , etc.
        self.mainContentElement = TextAreaElement(field.mainContentField)
        self.targetXElement = TextElement(field.targetX)
        self.targetYElement = TextElement(field.targetY)
        self.widthElement = TextElement(field.width)
        self.heightElement = TextElement(field.height)
        self.toleranceElement = TextElement(field.tolerance)

    def process(self, request):
        self.mainContentElement.process(request)
        self.targetXElement.process(request)
        self.targetYElement.process(request)
        self.widthElement.process(request)
        self.heightElement.process(request)
        self.toleranceElement.process(request)
        field_engine_check_delete(self, request, self.field.idevice.objectsToPlace)

    def renderEdit(self):
        html = ""
        html += self.mainContentElement.renderEdit()
        html += self.targetXElement.renderEdit()
        html += self.targetYElement.renderEdit()
        html += self.widthElement.renderEdit()
        html += self.heightElement.renderEdit()
        html += self.toleranceElement.renderEdit()
        html += field_engine_make_delete_button(self)
        return html
   
    def renderView(self):
        html = ""
        html += self.mainContentElement.renderView()
        html += self.mainContentElement.renderView()
        html += self.targetXElement.renderView()
        html += self.targetYElement.renderView()
        html += self.widthElement.renderView()
        html += self.heightElement.renderView()
        html += self.toleranceElement.renderView()

        return html

    def renderPreview(self):
        html = ""
        html += self.renderView()
        return html
Beispiel #5
0
class ImageMagnifierBlock(Block):
    """
    ImageMagnifierBlock can render and process ImageMagnifierIdevices as XHTML
    """

    name = 'imageManifier'

    def __init__(self, parent, idevice):
        """
        Initialize
        """
        Block.__init__(self, parent, idevice)
        self.imageMagnifierElement = MagnifierElement(idevice.imageMagnifier)

        # to compensate for the strange unpickling timing when objects are
        # loaded from an elp, ensure that proper idevices are set:
        # (only applies to the image-embeddable ones, not MagnifierElement)
        if idevice.text.idevice is None:
            idevice.text.idevice = idevice
        self.textElement = TextAreaElement(idevice.text)

        if not hasattr(self.idevice, 'undo'):
            self.idevice.undo = True

    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        log.debug("process " + repr(request.args))
        Block.process(self, request)

        is_cancel = common.requestHasCancel(request)

        if (u"action" not in request.args or
            (request.args[u"action"][0] != u"delete" and not is_cancel)):
            self.imageMagnifierElement.process(request)
            self.textElement.process(request)

        if "action" in request.args and request.args["action"][0] == "done":
            # remove the undo flag in order to reenable it next time:
            if hasattr(self.idevice, 'undo'):
                del self.idevice.undo

        if "float"+self.id in request.args \
        and not is_cancel:
            self.idevice.float = request.args["float" + self.id][0]

        if "caption"+self.id in request.args \
        and not is_cancel:
            self.idevice.caption = request.args["caption" + self.id][0]

        if "glass"+self.id in request.args \
        and not is_cancel:
            self.idevice.imageMagnifier.glassSize = \
                request.args["glass"+self.id][0]

        if "initial"+self.id in request.args \
        and not is_cancel:
            self.idevice.imageMagnifier.initialZSize = \
                request.args["initial"+self.id][0]

        if "maxZoom"+self.id in request.args \
        and not is_cancel:
            self.idevice.imageMagnifier.maxZSize = \
                request.args["maxZoom"+self.id][0]

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form elements for editing this block
        """
        log.debug("renderEdit")
        floatArr = [[_(u'Left'), 'left'], [_(u'Right'), 'right'],
                    [_(u'None'), 'none']]
        html = u"<div class=\"iDevice\">\n"

        # Caption
        html += '<div class="block">'
        html += u"<strong>%s</strong>" % _(u"Caption:")
        html += common.elementInstruc(self.idevice.captionInstruc)
        html += '</div>'
        html += '<div class="block">'
        html += common.textInput("caption" + self.id, self.idevice.caption)
        html += '</div>'

        # Text
        html += '<div class="block">'
        html += self.textElement.renderEdit()
        html += '</div>'

        # Image
        html += self.imageMagnifierElement.renderEdit()

        this_package = None
        if self.idevice is not None and self.idevice.parentNode is not None:
            this_package = self.idevice.parentNode.package

        # Align
        html += common.formField('select', this_package, _("Align:"),
                                 "float" + self.id, '',
                                 self.idevice.alignInstruc, floatArr,
                                 self.idevice.float)

        # Initial and Max Zoom opts
        zoomOpts = []
        for i in range(100, 201, 10):
            zoomOpts.append(('%d%%' % (i), str(i)))

        # Initial Zoom Size
        selection = self.idevice.imageMagnifier.initialZSize
        html += common.formField('select', this_package, _(u"Initial Zoom"),
                                 "initial" + self.id, '',
                                 self.idevice.initialZoomInstruc, zoomOpts,
                                 selection)

        # Maximum Zoom
        selection = self.idevice.imageMagnifier.maxZSize
        html += common.formField('select', this_package, _(u"Maximum zoom"),
                                 "maxZoom" + self.id, '',
                                 self.idevice.maxZoomInstruc, zoomOpts,
                                 selection)

        # Size of Magnifying Glass
        glassSizeArr = [
            [_(u'Small'), '1'],
            [_(u'Medium'), '2'],
            [_(u'Large'), '3'],
            [_(u'Extra large'), '4'],
        ]
        html += common.formField('select', this_package,
                                 _(u"Size of magnifying glass: "),
                                 "glass" + self.id, '',
                                 self.idevice.glassSizeInstruc, glassSizeArr,
                                 self.idevice.imageMagnifier.glassSize)

        html += self.renderEditButtons(undo=self.idevice.undo)
        html += u"</div>\n"
        return html

    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        log.debug("renderPreview")
        html = u"\n<!-- image with text iDevice -->\n"
        html += u"<div class=\"iDevice "
        html += u"emphasis" + unicode(self.idevice.emphasis) + "\" "
        html += "ondblclick=\"submitLink('edit'," + self.id + ", 0);\">\n"
        html += u"  <div class=\"image_text\" style=\""
        html += u"width:" + str(self.idevice.imageMagnifier.width) + "px; "
        html += u"float:%s;\">\n" % self.idevice.float
        html += u"    <div class=\"image\">\n"
        html += self.imageMagnifierElement.renderPreview()
        html += u"" + self.idevice.caption
        html += u"    </div> <!-- class=\"image\" -->\n"
        html += u"  </div> <!-- class=\"image_text\" -->\n"
        text = self.textElement.renderPreview()
        if text:
            html += text
        else:
            html += '&nbsp;'
        html += u'\n<div style="clear:both;height:1px;overflow:hidden;"></div>\n'
        html += self.renderViewButtons()
        html += u"</div> <!-- class=\"iDevice emphasisX\" -->\n"
        return html

    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        log.debug("renderView")
        html = u"\n<!-- image with text iDevice -->\n"
        html += u"<div class=\"iDevice "
        html += u"emphasis" + unicode(self.idevice.emphasis) + "\">\n"
        html += u"  <div class=\"image_text\" style=\""
        html += u"width:" + str(self.idevice.imageMagnifier.width) + "px; "
        html += u"float:%s;\">\n" % self.idevice.float
        html += u"    <div class=\"image\">\n"
        html += self.imageMagnifierElement.renderView()
        html += u"    <br/>" + self.idevice.caption
        html += u"    </div> <!-- class=\"image\" -->\n"
        html += u"  </div> <!-- class=\"image_text\" -->\n"
        text = self.textElement.renderView()
        if text:
            html += text
        else:
            html += '&nbsp;'
        html += u'\n<div style="clear:both;height:1px;overflow:hidden;"></div>\n'
        html += u"</div> <!-- class=\"iDevice emphasisX\" -->\n"
        return html
class ImageMagnifierBlock(Block):
    """
    ImageMagnifierBlock can render and process ImageMagnifierIdevices as XHTML
    """

    name = 'imageManifier'

    def __init__(self, parent, idevice):
        """
        Initialize
        """
        Block.__init__(self, parent, idevice)
        self.imageMagnifierElement = MagnifierElement(idevice.imageMagnifier)

        # to compensate for the strange unpickling timing when objects are
        # loaded from an elp, ensure that proper idevices are set:
        # (only applies to the image-embeddable ones, not MagnifierElement)
        if idevice.text.idevice is None:
            idevice.text.idevice = idevice
        self.textElement = TextAreaElement(idevice.text)

        if not hasattr(self.idevice, 'undo'):
            self.idevice.undo = True

    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        log.debug("process " + repr(request.args))
        Block.process(self, request)

        is_cancel = common.requestHasCancel(request)

        if (u"action" not in request.args or
            (request.args[u"action"][0] != u"delete" and not is_cancel)):
            self.imageMagnifierElement.process(request)
            self.textElement.process(request)

        if "action" in request.args and request.args["action"][0] == "done":
            # remove the undo flag in order to reenable it next time:
            if hasattr(self.idevice, 'undo'):
                del self.idevice.undo

        if "float"+self.id in request.args \
        and not is_cancel:
            self.idevice.float = request.args["float" + self.id][0]

        if "caption"+self.id in request.args \
        and not is_cancel:
            self.idevice.caption = request.args["caption" + self.id][0]

        if "glass"+self.id in request.args \
        and not is_cancel:
            self.idevice.imageMagnifier.glassSize = \
                request.args["glass"+self.id][0]

        if "initial"+self.id in request.args \
        and not is_cancel:
            self.idevice.imageMagnifier.initialZSize = \
                request.args["initial"+self.id][0]

        if "maxZoom"+self.id in request.args \
        and not is_cancel:
            self.idevice.imageMagnifier.maxZSize = \
                request.args["maxZoom"+self.id][0]

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form elements for editing this block
        """
        log.debug("renderEdit")
        floatArr = [[_(u'Left'), 'left'], [_(u'Right'), 'right'],
                    [_(u'None'), 'none']]
        html = u"<div class=\"iDevice\">\n"

        # Caption
        html += '<div class="block">'
        html += u"<strong>%s</strong>" % _(u"Caption:")
        html += common.elementInstruc(self.idevice.captionInstruc)
        html += '</div>'
        html += '<div class="block">'
        html += common.textInput("caption" + self.id, self.idevice.caption)
        html += '</div>'

        # Text
        html += '<div class="block">'
        html += self.textElement.renderEdit()
        html += '</div>'

        # Image
        html += self.imageMagnifierElement.renderEdit()

        this_package = None
        if self.idevice is not None and self.idevice.parentNode is not None:
            this_package = self.idevice.parentNode.package

        # Align
        html += common.formField('select', this_package, _("Align:"),
                                 "float" + self.id, '',
                                 self.idevice.alignInstruc, floatArr,
                                 self.idevice.float)

        # Initial and Max Zoom opts
        zoomOpts = []
        for i in range(100, 201, 10):
            zoomOpts.append(('%d%%' % (i), str(i)))

        # Initial Zoom Size
        selection = self.idevice.imageMagnifier.initialZSize
        html += common.formField('select', this_package, _(u"Initial Zoom"),
                                 "initial" + self.id, '',
                                 self.idevice.initialZoomInstruc, zoomOpts,
                                 selection)

        # Maximum Zoom
        selection = self.idevice.imageMagnifier.maxZSize
        html += common.formField('select', this_package, _(u"Maximum zoom"),
                                 "maxZoom" + self.id, '',
                                 self.idevice.maxZoomInstruc, zoomOpts,
                                 selection)

        # Size of Magnifying Glass
        glassSizeArr = [
            [_(u'Small'), '1'],
            [_(u'Medium'), '2'],
            [_(u'Large'), '3'],
            [_(u'Extra large'), '4'],
        ]
        html += common.formField('select', this_package,
                                 _(u"Size of magnifying glass: "),
                                 "glass" + self.id, '',
                                 self.idevice.glassSizeInstruc, glassSizeArr,
                                 self.idevice.imageMagnifier.glassSize)

        html += self.renderEditButtons(undo=self.idevice.undo)
        html += u"</div>\n"
        return html

    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """

        lb = "\n"  #Line breaks
        dT = common.getExportDocType()
        figureTag = "div"
        if dT == "HTML5":
            figureTag = "figure"

        html = common.ideviceHeader(self, style, "preview")

        html += '<div class="iDevice_content">' + lb
        html += '<' + figureTag + ' class="image_text" style="width:' + str(
            self.idevice.imageMagnifier.width
        ) + 'px;float:' + self.idevice.float + ';'
        if self.idevice.float == 'left':
            html += 'margin:0 20px 20px 0'
        if self.idevice.float == 'right':
            html += 'margin:0 0 20px 20px'
        html += '">' + lb
        html += self.imageMagnifierElement.renderPreview()
        if self.idevice.caption != '':
            html = html.replace(
                ' alt="" ',
                ' alt="' + self.idevice.caption.replace('"', '&quot;') + '" ',
                1)
            if dT == "HTML5":
                html += '<figcaption style="font-weight:bold">' + self.idevice.caption + '</figcaption>' + lb
            else:
                html += '<strong>' + self.idevice.caption + '</strong>' + lb
        html += '</' + figureTag + '>' + lb
        text = self.textElement.renderPreview()
        if text:
            text = text.replace('"block iDevice_content"', '"iDevice_text"', 1)
            html += text
        else:
            html += '&nbsp;'
        html += '</div>' + lb  # /.iDevice_content

        html += common.ideviceFooter(self, style, "preview")

        return html

    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """

        lb = "\n"  #Line breaks
        dT = common.getExportDocType()
        figureTag = "div"
        if dT == "HTML5":
            figureTag = "figure"

        html = common.ideviceHeader(self, style, "view")

        html += '<div class="iDevice_content">' + lb
        html += '<' + figureTag + ' class="image_text" style="width:' + str(
            self.idevice.imageMagnifier.width
        ) + 'px;float:' + self.idevice.float + ';'
        if self.idevice.float == 'left':
            html += 'margin:0 20px 20px 0'
        if self.idevice.float == 'right':
            html += 'margin:0 0 20px 20px'
        html += '">'
        html += lb
        html += self.imageMagnifierElement.renderView()
        if self.idevice.caption != '':
            html = html.replace(
                ' alt="" ',
                ' alt="' + self.idevice.caption.replace('"', '&quot;') + '" ',
                1)
            if dT == "HTML5":
                html += '<figcaption style="font-weight:bold">' + self.idevice.caption + '</figcaption>' + lb
            else:
                html += '<strong>' + self.idevice.caption + '</strong>' + lb
        html += '</' + figureTag + '>' + lb
        text = self.textElement.renderView()
        if text:
            text = text.replace('"block iDevice_content"', '"iDevice_text"', 1)
            html += text
        else:
            html += '&nbsp;'
        html += '</div>' + lb  # /.iDevice_content

        html += common.ideviceFooter(self, style, "view")

        return html
class QuestionElement(object):
    """
    QuestionElement is responsible for a block of question. 
    Used by MultichoiceBlock CasestudyBlock.
    """

    def __init__(self, index, idevice, question):
        """
        Initialize
        'index' is our number in the list of questions
        'idevice' is a case study idevice
        'question' is a exe.engine.casestudyidevice.Question instance
        """
        self.index        = index
        self.id           = "q" + unicode(index) + "b" + idevice.id        
        self.idevice      = idevice


        self.quesId       = "quesQuestion" + unicode(index) + "b" + idevice.id
        self.feedbackId   = "quesFeedback" + unicode(index) + "b" + idevice.id

        self.question     = question
        # also split out each part for a separate TextAreaElement:

        # but first....  
        # to compensate for the strange unpickling timing when objects are 
        # loaded from an elp, ensure that proper idevices are set: 
        if question.questionTextArea.idevice is None: 
            question.questionTextArea.idevice = idevice 
        if question.feedbackTextArea.idevice is None: 
            question.feedbackTextArea.idevice = idevice

        self.question_question = TextAreaElement(question.questionTextArea)
        self.question_question.id = self.quesId 
        self.question_feedback = TextAreaElement(question.feedbackTextArea)
        self.question_feedback.id = self.feedbackId 

    def process(self, request):
        """
        Process arguments from the web server.  Return any which apply to this
        element.
        """
        log.debug("process " + repr(request.args))
        
        if self.quesId in request.args:
            self.question_question.process(request)
                        
        if self.feedbackId in request.args:
            self.question_feedback.process(request)

        if "action" in request.args and request.args["action"][0] == self.id:
            # before deleting the question object, remove any internal anchors:
            for q_field in self.question.getRichTextFields():
                 q_field.ReplaceAllInternalAnchorsLinks()  
                 q_field.RemoveAllInternalLinks()  
            self.idevice.questions.remove(self.question)
            # disable Undo once an activity has been deleted:
            self.idevice.undo = False


    def renderEdit(self):
        """
        Returns an XHTML string for editing this question element
        """

        html  = "<tr><td><b>%s</b>\n" % _("Activity")
        html += common.elementInstruc(self.idevice.questionInstruc)
        html += self.question_question.renderEdit()

        html += "<b>%s</b>\n" % _("Feedback")
        html += common.elementInstruc(self.idevice.feedbackInstruc)
        html += self.question_feedback.renderEdit()

        html += "</td><td>\n"
        html += common.submitImage(self.id, self.idevice.id, 
                                   "/images/stock-cancel.png",
                                   _("Delete question"))
        html += "</td></tr>\n"
        return html

    def doRender(self, preview=False):
        """
        Returns an XHTML string for viewing and previewing this question element
        depending on the value of 'preview'.
        """
        log.debug("renderView called")
              
        if preview: 
            html  = self.question_question.renderPreview()
        else:
            html  = self.question_question.renderView()

        if  self.question_feedback.field.content.strip() != "" :            
            html += '<div id="view%s" style="display:block;">' % self.id
            html += common.feedbackButton('btnshow' + self.id,
                        _(u"Show Feedback"),
                        onclick = "showAnswer('%s',1)" % self.id)
            html += '</div>'
            html += '<div id="hide%s" style="display:none;">' % self.id
            html += common.feedbackButton('btnhide' + self.id,
                        _(u"Hide Feedback"),
                        onclick = "showAnswer('%s',0)" % self.id)
            html += '<p>'

            html += '</p>'
            html += '</div>'
            html += '<div id="s%s" class="feedback" style=" ' % self.id
            html += 'display: none;">'

            if preview: 
                html  += self.question_feedback.renderPreview() 
            else: 
                html  += self.question_feedback.renderView()

            html += "</div>\n"
# JR: Generamos el contenido que ira dentro de la etiqueta noscript
	    html += '<noscript><div class="feedback">\n'
	    html += "<p><strong>" + _("Solucion") + ": </strong></p>\n"
            if preview: 
            	html  += self.question_feedback.field.content_w_resourcePaths
            else: 
            	html  += self.question_feedback.field.content_wo_resourcePaths
	    html += "</div></noscript>\n"
        else:
            html += "\n"
        
        return html

    def renderView(self):
        """
        Returns an XHTML string for viewing this question element
        """
        html = "<div class=\"question\">\n"
        html += self.doRender(preview=False)
        html += "</div>\n"
        return html
    
    def renderPreview(self):
        """
        Returns an XHTML string for previewing this question element
        """
        return self.doRender(preview=True)
class FreeTextBlock(Block):
    """
    FreeTextBlock can render and process FreeTextIdevices as XHTML
    GenericBlock will replace it..... one day
    """
    def __init__(self, parent, idevice):
        Block.__init__(self, parent, idevice)
        if idevice.content.idevice is None:
            # due to the loading process's timing, idevice wasn't yet set;
            # set it here for the TextAreaElement's tinyMCE editor
            idevice.content.idevice = idevice

        self.contentElement = TextAreaElement(idevice.content)
        self.contentElement.height = 250
        if not hasattr(self.idevice, 'undo'):
            self.idevice.undo = True

    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        is_cancel = common.requestHasCancel(request)

        if is_cancel:
            self.idevice.edit = False
            # but double-check for first-edits, and ensure proper attributes:
            if not hasattr(self.idevice.content, 'content_w_resourcePaths'):
                self.idevice.content.content_w_resourcePaths = ""
            if not hasattr(self.idevice.content, 'content_wo_resourcePaths'):
                self.idevice.content.content_wo_resourcePaths = ""
            return

        Block.process(self, request)

        if (u"action" not in request.args
                or request.args[u"action"][0] != u"delete"):
            content = self.contentElement.process(request)
            if content:
                self.idevice.content = content

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        html = u"<div style=\"position: relative\">\n"
        html += self.contentElement.renderEdit()
        html += self.renderEditButtons()
        html += u"</div>\n"
        return html

    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        if hasattr(self.idevice, 'parent'
                   ) and self.idevice.parent and not self.idevice.parent.edit:
            return u""
        html = common.ideviceHeader(self, style, "preview")
        html += self.contentElement.renderPreview()
        html += common.ideviceFooter(self, style, "preview")
        return html

    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        html = u"<div class=\"iDevice "
        html += u"emphasis" + unicode(self.idevice.emphasis) + "\">\n"
        html += self.contentElement.renderView()
        html += u"</div>\n"
        return html

    def renderXML(self, style):
        xml = u""
        """
        If we are effectively just one large image then make just an img tag and sound
        tag if appropriate.  If not output all the html 
        """

        xmlStr = self.contentElement.renderXML(None, "idevice",
                                               self.idevice.id)
        return xmlStr
Beispiel #9
0
class TrueFalseBlock(Block):
    """
    TrueFalseBlock can render and process TrueFalseIdevices as XHTML
    """
    def __init__(self, parent, idevice):
        """
        Initialize a new Block object
        """
        Block.__init__(self, parent, idevice)
        self.idevice = idevice
        self.questionElements = []
        self.questionInstruc = idevice.questionInstruc
        self.keyInstruc = idevice.keyInstruc
        self.feedbackInstruc = idevice.feedbackInstruc
        self.hintInstruc = idevice.hintInstruc

        # to compensate for the strange unpickling timing when objects are
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.instructionsForLearners.idevice is None:
            idevice.instructionsForLearners.idevice = idevice
        self.instructionElement = \
            TextAreaElement(idevice.instructionsForLearners)

        if not hasattr(self.idevice, 'undo'):
            self.idevice.undo = True

        i = 0
        for question in idevice.questions:
            self.questionElements.append(TrueFalseElement(
                i, idevice, question))
            i += 1

    def process(self, request):
        """
        Process the request arguments from the web server
        """
        Block.process(self, request)

        is_cancel = common.requestHasCancel(request)

        self.instructionElement.process(request)

        if ("addQuestion" + unicode(self.id)) in request.args:
            self.idevice.addQuestion()
            self.idevice.edit = True
            # disable Undo once a question has been added:
            self.idevice.undo = False

        if "title"+self.id in request.args \
        and not is_cancel:
            self.idevice.title = request.args["title" + self.id][0]

        for element in self.questionElements:
            element.process(request)

        if ("action" in request.args and request.args["action"][0] == "done"
                or not self.idevice.edit):
            # remove the undo flag in order to reenable it next time:
            if hasattr(self.idevice, 'undo'):
                del self.idevice.undo

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """

        html = u"<div class=\"iDevice\"><br/>\n"
        html += common.textInput("title" + self.id, self.idevice.title)
        html += u"<br/><br/>\n"
        html += self.instructionElement.renderEdit()

        for element in self.questionElements:
            html += element.renderEdit()

        value = _(u"Add another question")
        html += common.submitButton("addQuestion" + unicode(self.id), value)
        html += u"<br /><br />" + self.renderEditButtons(
            undo=self.idevice.undo)
        html += u"</div>\n"

        return html

    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        html = u"<div class=\"iDevice "
        html += u"emphasis" + unicode(self.idevice.emphasis) + "\" "
        html += u"ondblclick=\"submitLink('edit'," + self.id + ", 0);\">\n"
        html += u'<img alt="" class="iDevice_icon" '
        html += u"src=\"/style/" + style + "/icon_" + self.idevice.icon + ".gif\" />\n"
        html += u"<span class=\"iDeviceTitle\"><strong>"
        html += self.idevice.title + "</strong></span>\n"
        html += u"<div class=\"iDevice_inner\">\n"
        html += self.instructionElement.renderPreview()

        for element in self.questionElements:
            html += element.renderQuestionPreview()
            html += element.renderFeedbackPreview()

        html += "</div>\n"
        html += self.renderViewButtons()
        html += "</div>\n"

        return html

    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        html = u'<script type="text/javascript" src="common.js"></script>\n'
        html += u'<script type="text/javascript" src="libot_drag.js"></script>'
        html += u"\n<div class=\"iDevice "
        html += u"emphasis" + unicode(self.idevice.emphasis) + "\">\n"
        html += u'<img alt="" class="iDevice_icon" '
        html += u"src=\"icon_" + self.idevice.icon + ".gif\" />\n"
        html += u"<span class=\"iDeviceTitle\"><strong>"
        html += self.idevice.title + "</strong></span>\n"
        html += u"<div class=\"iDevice_inner\">\n"
        html += self.instructionElement.renderView()

        for element in self.questionElements:
            html += "<div class=\"question\">\n"
            html += element.renderQuestionView()
            html += element.renderFeedbackView()
            html += "</div>\n"

        html += u"</div>\n"
        html += u"</div>\n"

        return html
class FreeTextfpdBlock(Block):
    """
    FreeTextBlock can render and process FreeTextIdevices as XHTML
    GenericBlock will replace it..... one day
    """
    def __init__(self, parent, idevice):
        Block.__init__(self, parent, idevice)
        if idevice.content.idevice is None:
            # due to the loading process's timing, idevice wasn't yet set;
            # set it here for the TextAreaElement's tinyMCE editor
            idevice.content.idevice = idevice

        self.contentElement = TextAreaElement(idevice.content)
        self.contentElement.height = 250
        if not hasattr(self.idevice, 'undo'):
            self.idevice.undo = True

    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        is_cancel = common.requestHasCancel(request)

        if is_cancel:
            self.idevice.edit = False
            # but double-check for first-edits, and ensure proper attributes:
            if not hasattr(self.idevice.content, 'content_w_resourcePaths'):
                self.idevice.content.content_w_resourcePaths = ""
            if not hasattr(self.idevice.content, 'content_wo_resourcePaths'):
                self.idevice.content.content_wo_resourcePaths = ""
            return

        Block.process(self, request)

        if (u"action" not in request.args
                or request.args[u"action"][0] != u"delete"):
            content = self.contentElement.process(request)
            if content:
                self.idevice.content = content

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        html = u"<div>\n"
        html += self.contentElement.renderEdit()
        html += self.renderEditButtons()
        html += u"</div>\n"
        return html

    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        html = u"<div class=\"iDevice "
        html += u"emphasis" + unicode(self.idevice.emphasis) + "\" "
        html += u"ondblclick=\"submitLink('edit'," + self.id + ", 0);\">\n"
        html += self.contentElement.renderPreview()
        html += self.renderViewButtons()
        html += "</div>\n"
        return html

    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        html = u"<div class=\"iDevice "
        html += u"emphasis" + unicode(self.idevice.emphasis) + "\">\n"
        html += self.contentElement.renderView()
        html += u"</div>\n"
        return html
Beispiel #11
0
class WikipediaBlock(Block):
    """
    WikipediaBlock can render and process WikipediaIdevices as XHTML
    """
    def __init__(self, parent, idevice):
        """
        Initialize
        """
        Block.__init__(self, parent, idevice)

        # to compensate for the strange unpickling timing when objects are
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.article.idevice is None:
            idevice.article.idevice = idevice
        self.articleElement = TextAreaElement(idevice.article)
        self.articleElement.height = 300
        if not hasattr(self.idevice, 'undo'):
            self.idevice.undo = True

    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        log.debug("process " + repr(request.args))

        is_cancel = common.requestHasCancel(request)

        if 'emphasis'+self.id in request.args \
        and not is_cancel:
            self.idevice.emphasis = int(request.args['emphasis' + self.id][0])
            # disable Undo once an emphasis has changed:
            self.idevice.undo = False

        if 'ssite'+self.id in request.args \
        and not is_cancel:
            self.idevice.site = request.args['ssite' + self.id][0]

        if 'ownUrl'+self.id in request.args \
        and not is_cancel:
            self.idevice.ownUrl = request.args['ownUrl' + self.id][0]

        if 'title'+self.id in request.args \
        and not is_cancel:
            self.idevice.title = request.args['title' + self.id][0]

        if ("object" in request.args
                and request.args["object"][0] == "site" + self.id):
            pass
        elif 'loadWikipedia' + self.id in request.args:
            # If they've hit "load" instead of "the tick"
            self.idevice.loadArticle(request.args['article'][0])
            # disable Undo once an article has been loaded:
            self.idevice.undo = False
        else:
            # If they hit "the tick" instead of "load"
            Block.process(self, request)
            if (u"action" not in request.args \
            or request.args[u"action"][0] != u"delete"):
                # If the text has been changed
                self.articleElement.process(request)
            if "action" in request.args \
            and request.args["action"][0] == "done":
                # remove the undo flag in order to reenable it next time:
                if hasattr(self.idevice, 'undo'):
                    del self.idevice.undo

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form elements for editing this block
        """
        log.debug("renderEdit")

        html = u"<div class=\"iDevice\"><br/>\n"
        html += common.textInput("title" + self.id,
                                 self.idevice.title) + "<br/><br/>"

        sites = [
            (_(u"English Wikipedia Article"), "http://en.wikipedia.org/wiki/"),
            (_(u"Basque Wikipedia Article"), "http://eu.wikipedia.org/wiki/"),
            (_(u"Catalan Wikipedia Article"), "http://ca.wikipedia.org/wiki/"),
            (_(u"Chinese Wikipedia Article"), "http://zh.wikipedia.org/wiki/"),
            (_(u"Dutch Wikipedia Article"), "http://nl.wikipedia.org/wiki/"),
            (_(u"French Wikipedia Article"), "http://fr.wikipedia.org/wiki/"),
            (_(u"German Wikipedia Article"), "http://de.wikipedia.org/wiki/"),
            (_(u"Galician Wikipedia Article"),
             "http://gl.wikipedia.org/wiki/"),
            (_(u"Greek Wikipedia Article"), "http://el.wikipedia.org/wiki/"),
            (_(u"Italian Wikipedia Article"), "http://it.wikipedia.org/wiki/"),
            (_(u"Japanese Wikipedia Article"),
             "http://ja.wikipedia.org/wiki/"),
            (_(u"Magyar Wikipedia Article"), "http://hu.wikipedia.org/wiki/"),
            (_(u"Polish Wikipedia Article"), "http://pl.wikipedia.org/wiki/"),
            (_(u"Portugese Wikipedia Article"),
             "http://pt.wikipedia.org/wiki/"),
            (_(u"Slovenian Wikipedia Article"),
             "http://sl.wikipedia.org/wiki/"),
            (_(u"Spanish Wikipedia Article"), "http://es.wikipedia.org/wiki/"),
            (_(u"Swedish Wikipedia Article"), "http://sv.wikipedia.org/wiki/"),
            (_(u"Wikibooks Article"), "http://en.wikibooks.org/wiki/"),
            (_(u"Wikiversity"), "http://en.wikiversity.org/wiki/"),
            (_(u"Wiktionary"), "http://en.wiktionary.org/wiki/"),
            (_(u"Wikieducator Content"), "http://wikieducator.org/"),
            (_(u"Other"), "")
        ]

        this_package = None
        if self.idevice is not None and self.idevice.parentNode is not None:
            this_package = self.idevice.parentNode.package
        html += common.formField('select', this_package, _('Site'), 's',
                                 'site' + self.id, self.idevice.langInstruc,
                                 sites, self.idevice.site)

        url = "none"
        if self.idevice.site == "":
            url = "block"
        html += '<div style="display:%s"> %s: <br/>' % (url, _("Own site"))
        html += common.textInput("ownUrl" + self.id,
                                 self.idevice.ownUrl) + '<br/></div>'
        html += "<br/>"
        html += common.textInput("article", self.idevice.articleName)
        html += common.elementInstruc(self.idevice.searchInstruc)
        html += common.submitButton(u"loadWikipedia" + self.id, _(u"Load"))

        html += u"<br/>\n"
        html += self.articleElement.renderEdit()
        emphasisValues = [(_(u"No emphasis"), Idevice.NoEmphasis),
                          (_(u"Some emphasis"), Idevice.SomeEmphasis)]

        html += common.formField(
            'select',
            this_package,
            _('Emphasis'),
            'emphasis',
            self.id,
            '',  # TODO: Instructions
            emphasisValues,
            self.idevice.emphasis)

        html += self.renderEditButtons(undo=self.idevice.undo)
        html += u"</div>\n"
        return html

    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        log.debug("renderPreview")
        html = common.ideviceHeader(self, style, "preview")
        html += self.articleElement.renderPreview()
        html += common.ideviceFooter(self, style, "preview")
        return html

    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        log.debug("renderView")
        content = self.articleElement.renderView()
        # content = re.sub(r'src="resources/', 'src="', content)
        content = re.sub(r'src="http://127.0.0.1:\d+/newPackage.*/resources/',
                         'src="', content)
        content = re.sub(r'src="/newPackage.*/resources/', 'src="', content)
        content = re.sub(r'src=\'/newPackage.*/resources/', 'src="', content)
        content = re.sub(r'src=\"/newPackage.*/resources/', 'src="', content)
        html = common.ideviceHeader(self, style, "view")
        html += content
        html += common.ideviceFooter(self, style, "view")
        return html
Beispiel #12
0
class ClozelangfpdBlock(Block):
    """
    Renders a paragraph where the content creator can choose which words the
    student must fill in.
    """
    def __init__(self, parent, idevice):
        """
        Pre-create our field ids
        """
        Block.__init__(self, parent, idevice)

        # to compensate for the strange unpickling timing when objects are
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.instructionsForLearners.idevice is None:
            idevice.instructionsForLearners.idevice = idevice
        if idevice.content.idevice is None:
            idevice.content.idevice = idevice
        if idevice.feedback.idevice is None:
            idevice.feedback.idevice = idevice

        dT = common.getExportDocType()
        sectionTag = "div"
        if dT == "HTML5":
            sectionTag = "section"

        idevice.instructionsForLearners.htmlTag = sectionTag
        idevice.instructionsForLearners.class_ = "block instructions"
        idevice.feedback.htmlTag = sectionTag

        self.instructionElement = \
            TextAreaElement(idevice.instructionsForLearners)
        self.clozelangElement = ClozelangElement(idevice.content)
        self.feedbackElement = \
            TextAreaElement(idevice.feedback)
        self.previewing = False  # In view or preview render
        if not hasattr(self.idevice, 'undo'):
            self.idevice.undo = True

    def process(self, request):
        """
        Handles changes in the paragraph text from editing
        """
        is_cancel = common.requestHasCancel(request)

        if "title"+self.id in request.args \
        and not is_cancel:
            self.idevice.title = request.args["title" + self.id][0]
        object = request.args.get('object', [''])[0]
        action = request.args.get('action', [''])[0]
        self.instructionElement.process(request)
        self.clozelangElement.process(request)
        self.feedbackElement.process(request)
        Block.process(self, request)

    def renderEdit(self, style):
        """
        Renders a screen that allows the user to enter paragraph text and choose
        which words are hidden.
        """
        """
        html = [
            u'<div class="iDevice">',
            u'<div class="block">',
#            common.textInput("title"+self.id, self.idevice.title),
            common.textInput("title"+self.id, x_(u"Now it's your turn")),
            u'</div>',
            self.instructionElement.renderEdit(),
            self.clozelangElement.renderEdit(),
            self.feedbackElement.renderEdit(),
            self.renderEditButtons(),
            u'</div>'
            ]
        return u'\n    '.join(html)
	"""
        html = "<div class=\"iDevice\"><br/>\n"
        html = "<div class=\"block\">"

        # JRJ
        # Quitamos el prefijo "FPD -"
        # (let's remove the "FPD -" prefix)
        if self.idevice.title.find("FPD - ") == 0:
            self.idevice.title = x_(u"Now It's Your Turn")
        html += common.textInput("title" + self.id, self.idevice.title)

        html += "</div>"
        html += self.instructionElement.renderEdit()
        html += self.clozelangElement.renderEdit()
        html += self.feedbackElement.renderEdit()
        html += self.renderEditButtons()
        html += "</div>"
        return html

    def renderPreview(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """
        self.previewing = True
        return Block.renderPreview(self, style)

    def renderView(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """
        self.previewing = False
        return Block.renderView(self, style)

    def renderViewContent(self):
        """
        Returns an XHTML string for this block
        """
        # Only show feedback button if feedback is present
        if self.feedbackElement.field.content.strip():
            # Cloze Idevice needs id of div for feedback content
            feedbackID = self.feedbackElement.id
            if self.previewing:
                clozeContent = self.clozelangElement.renderPreview(feedbackID)
            else:
                clozeContent = self.clozelangElement.renderView(feedbackID)
        else:
            if self.previewing:
                clozeContent = self.clozelangElement.renderPreview()
            else:
                clozeContent = self.clozelangElement.renderView()
        instruction_html = ""
        if self.previewing:
            instruction_html = self.instructionElement.renderPreview()
        else:
            instruction_html = self.instructionElement.renderView()
        # html = u'<div class="iDevice_inner">\n'

        dT = common.getExportDocType()
        sectionTag = "div"
        if dT == "HTML5":
            sectionTag = "section"

        html = instruction_html
        html += '<' + sectionTag + ' class="activity" id="activity-' + self.id + '">\n'
        if not self.previewing:
            html += '<form name="cloze-form-' + self.id + '" action="#" onsubmit="return false" class="activity-form">\n'
        html += clozeContent
        if not self.previewing:
            html += '</form>\n'
        html += '</' + sectionTag + '>\n'
        if self.feedbackElement.field.content:
            if self.previewing:
                html += self.feedbackElement.renderPreview(False,
                                                           class_="feedback")
            else:
                html += self.feedbackElement.renderView(False,
                                                        class_="feedback")
        # html += u'</div>\n'

#JR: Anadimos la etiqueta noscript
# 2014 - JavaScript is required
        '''
	if self.previewing:
		cloze = self.clozelangElement.field.content_w_resourcePaths
		feedback = self.feedbackElement.field.content_w_resourcePaths
	else:
		cloze = self.clozelangElement.field.content_wo_resourcePaths
		feedback = self.feedbackElement.field.content_wo_resourcePaths
	html += u'<noscript><div class="feedback">\n'
	html += u"<strong>" + c_("Solution") + u": </strong><br/>\n"
	html += cloze
	if self.feedbackElement.field.content:
		html += u"<br/><br/><strong>" + c_("Feedback") + ": </strong><br/>\n"
		html += feedback
	html += u"</div></noscript>"
	'''

        return html

    def renderText(self):
        """
        Returns an XHTML string for text file export.
        """

        if self.previewing:
            html = '<p>' + self.instructionElement.renderPreview() + '</p>'
        else:
            html = '<p>' + self.instructionElement.renderView() + '</p>'
        html += '<p>' + self.clozeElement.renderText() + '</p>'
        if self.feedbackElement.field.content:
            html += '<p>%s:</P>' % c_(u"Feedback")
            if self.previewing:
                html += '<p>' + self.feedbackElement.renderPreview(
                    False, class_="feedback")
                html += '</p>'
            else:
                html += '<p>' + self.feedbackElement.renderView(
                    False, class_="feedback")
                html += '</p>'
        html += self.clozelangElement.renderAnswers()
        return html
Beispiel #13
0
class FileAttachBlockInc(Block):
    """
    ExampleBlock can render and process ExampleIdevices as XHTML
    GenericBlock will replace it..... one day
    """
    def __init__(self, parent, idevice):
        Block.__init__(self, parent, idevice)
        self.fileAttachmentElements = []
        for fileField in self.idevice.fileAttachmentFields:
            fileElement = FileElement(fileField, False)
            self.fileAttachmentElements.append(fileElement)
        
        self.showDescBlock = ChoiceElement(idevice.showDesc)
        self.introHTMLElement = TextAreaElement(idevice.introHTML)
        

    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        Block.process(self, request)
        is_cancel = common.requestHasCancel(request)
        
        self.showDescBlock.process(request)
        self.introHTMLElement.process(request)
        
        showDesc = False
        if self.showDescBlock.renderView() == "yes":
            showDesc = True
        
        if showDesc == True:
            self.idevice.emphasis = Idevice.SomeEmphasis
        else:
            self.idevice.emphasis = Idevice.NoEmphasis
        
        for fileElement in self.fileAttachmentElements:
            fileElement.process(request)
            if field_engine_is_delete(fileElement, request, self.idevice.fileAttachmentFields):
                #fileElement.field.deleteFile()
                field_engine_check_delete(fileElement, request, self.idevice.fileAttachmentFields)
            
        if "addFileAttachment" + unicode(self.id) in request.args:
            self.idevice.addFileAttachmentField()            
            self.idevice.edit = True
            self.idevice.undo = False
            
        #check the title - lifted from genericblock
        if "title"+self.id in request.args \
        and not is_cancel:
            self.idevice.title = request.args["title"+self.id][0]

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        html  = _(u"<div>\n")
        html += _("<h2>File Attachment</h2>")
        html += _("<p>Here you can attach arbitary files to the package that will be included with the export</p>")
        html += _("<p>You can choose to display links or not below</p>")
        
        html += _("<strong>Title:</strong><br/>")
        html += common.textInput("title"+self.id, self.idevice.title)
        html += "<br/>"
        html += self.showDescBlock.renderEdit()
        html += self.introHTMLElement.renderEdit()
        
        
        for fileElement in self.fileAttachmentElements:
            html += fileElement.renderEdit()
            html += "<hr/>"
        
        html += "<br/>"    
        html += common.submitButton("addFileAttachment"+unicode(self.id), _("Add Another File Attachment"))
        html += "<br/>"
        html += self.renderEditButtons()
        html += u"</div>\n"
        return html


    def _renderMain(self, style, previewMode = False):
        """Decoration """
        showDesc = False
        if self.showDescBlock.renderView() == "yes":
            showDesc = True
        
        html = u""
        viewMode = "view"
        if previewMode == True:
            viewMode = "preview"
        
        
        if showDesc == True:
            html = common.ideviceHeader(self, style, viewMode)
            if previewMode == True:
                html += self.introHTMLElement.renderPreview()
            else:
                html += self.introHTMLElement.renderView()
            
            html += "<ul class='exeFileList'>"    
        
        prefix = ""
        if previewMode == True:
            prefix = "resources/" 
        

        if showDesc == False and previewMode == True:
            html += "<strong> " + _("File List (this list shows only in preview mode):") + "</strong><br/>"
        
                    
        for fileElement in self.fileAttachmentElements:
            if showDesc == False:
                if previewMode == True:
                    html += fileElement.renderPreview()
                else:
                    html += fileElement.renderView()
                
                html += "<br/>"
            else:
                html += "<li><a href='%(prefix)s%(filename)s' target='_blank'>%(desc)s" % \
                    {"filename" : fileElement.getFileName(), "desc" : fileElement.getDescription(),\
                     "prefix" : prefix}
                html += "<span> (" + c_('New Window')+")</span></a></li>\n"
                
        if showDesc == True:
            html += "</ul>"
        
        
        if showDesc == True:
            """End decoration"""
            html += common.ideviceFooter(self, style, viewMode)
        elif showDesc == False and previewMode == True:
            html += self.renderViewButtons()
        
        return html

    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        
        html = self._renderMain(style, True)
        
        #end of idevice
        
        
        
        
        return html


    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        html = self._renderMain(style, False)
        
        
        return html
Beispiel #14
0
class ScormClozeBlock(Block):
    """
    Renders a paragraph where the content creator can choose which words the
    student must fill in.
    """
    def __init__(self, parent, idevice):
        """
        Pre-create our field ids
        """
        Block.__init__(self, parent, idevice)

        # to compensate for the strange unpickling timing when objects are
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.instructionsForLearners.idevice is None:
            idevice.instructionsForLearners.idevice = idevice
        if idevice.content.idevice is None:
            idevice.content.idevice = idevice
        if idevice.feedback.idevice is None:
            idevice.feedback.idevice = idevice

        self.instructionElement = \
            TextAreaElement(idevice.instructionsForLearners)
        self.ScormClozeElement = ScormClozeElement(idevice.content)
        self.feedbackElement = \
            TextAreaElement(idevice.feedback)
        self.previewing = False  # In view or preview render
        if not hasattr(self.idevice, 'undo'):
            self.idevice.undo = True

    def process(self, request):
        """
        Handles changes in the paragraph text from editing
        """
        is_cancel = common.requestHasCancel(request)

        if "title"+self.id in request.args \
        and not is_cancel:
            self.idevice.title = request.args["title" + self.id][0]
        object = request.args.get('object', [''])[0]
        action = request.args.get('action', [''])[0]
        self.instructionElement.process(request)
        self.ScormClozeElement.process(request)
        #self.feedbackElement.process(request)
        Block.process(self, request)

    def renderEdit(self, style):
        """
        Renders a screen that allows the user to enter paragraph text and choose
        which words are hidden.
        """
        html = [
            u'<div class="iDevice">',
            u'<div class="block">',
            common.textInput("title" + self.id, self.idevice.title),
            u'</div>',
            self.instructionElement.renderEdit(),
            self.ScormClozeElement.renderEdit(),
            #self.feedbackElement.renderEdit(),
            self.renderEditButtons(),
            u'</div>'
        ]
        return u'\n    '.join(html)

    def renderPreview(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """
        self.previewing = True
        return Block.renderPreview(self, style)

    def renderView(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """
        self.previewing = False
        return Block.renderView(self, style)

    def renderViewContent(self):
        """
        Returns an XHTML string for this block
        """
        # Only show feedback button if feedback is present
        #        if self.feedbackElement.field.content.strip():
        #            # Cloze Idevice needs id of div for feedback content
        #            feedbackID = self.feedbackElement.id
        #            if self.previewing:
        #                clozeContent = self.ScormClozeElement.renderPreview(feedbackID)
        #            else:
        #                clozeContent = self.ScormClozeElement.renderView(feedbackID)
        #        else:
        if self.previewing:
            clozeContent = self.ScormClozeElement.renderPreview()
        else:
            clozeContent = self.ScormClozeElement.renderView()
        instruction_html = ""
        if self.previewing:
            instruction_html = self.instructionElement.renderPreview()
        else:
            instruction_html = self.instructionElement.renderView()
        html = [
            u'<script type="text/javascript" src="common.js"></script>\n',
            u'<div class="iDevice_inner">\n', instruction_html, clozeContent
        ]
        #        if self.feedbackElement.field.content:
        #            if self.previewing:
        #                html.append(self.feedbackElement.renderPreview(False,
        #                                                     class_="feedback"))
        #            else:
        #                html.append(self.feedbackElement.renderView(False,
        #                                                     class_="feedback"))
        html += [
            u'</div>\n',
        ]
        return u'\n    '.join(html)

    def renderText(self):
        """
        Returns an XHTML string for text file export.
        """

        if self.previewing:
            html = '<p>' + self.instructionElement.renderPreview() + '</p>'
        else:
            html = '<p>' + self.instructionElement.renderView() + '</p>'
        html += '<p>' + self.ScormClozeElement.renderText() + '</p>'
        #        if self.feedbackElement.field.content:
        #            html += '<p>%s:</P>' % _(u"Feedback")
        #            if self.previewing:
        #                html += '<p>' +self.feedbackElement.renderPreview(False,
        #                                                        class_="feedback")
        #                html += '</p>'
        #            else:
        #                html += '<p>' +self.feedbackElement.renderView(False,
        #                                                        class_="feedback")
        #                html += '</p>'
        html += self.ScormClozeElement.renderAnswers()
        return html
Beispiel #15
0
class WikipediaBlock(Block):
    """
    WikipediaBlock can render and process WikipediaIdevices as XHTML
    """
    def __init__(self, parent, idevice):
        """
        Initialize
        """
        Block.__init__(self, parent, idevice)
        if idevice.article.idevice is None: 
            idevice.article.idevice = idevice
        self.articleElement = TextAreaElement(idevice.article)
        self.articleElement.height = 300
        if not hasattr(self.idevice,'undo'): 
            self.idevice.undo = True
    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        log.debug("process " + repr(request.args))
        is_cancel = common.requestHasCancel(request)
        if 'emphasis'+self.id in request.args \
        and not is_cancel:
            self.idevice.emphasis = int(request.args['emphasis'+self.id][0])
            self.idevice.undo = False
        if 'ssite'+self.id in request.args \
        and not is_cancel:
            self.idevice.site = request.args['ssite'+self.id][0]
        if 'ownUrl'+self.id in request.args \
        and not is_cancel:
            self.idevice.ownUrl = request.args['ownUrl'+self.id][0]
        if 'title'+self.id in request.args \
        and not is_cancel:
            self.idevice.title = request.args['title'+self.id][0]
        if ("object" in request.args and request.args["object"][0] == "site" + self.id):
            pass
        elif 'loadWikipedia'+self.id in request.args:
            self.idevice.loadArticle(request.args['article'][0])
            self.idevice.undo = False
        else:
            Block.process(self, request)
            if (u"action" not in request.args \
            or request.args[u"action"][0] != u"delete"):
                self.articleElement.process(request)
            if "action" in request.args \
            and request.args["action"][0] == "done":
                if hasattr(self.idevice,'undo'): 
                    del self.idevice.undo
    def renderEdit(self, style):
        """
        Returns an XHTML string with the form elements for editing this block
        """
        log.debug("renderEdit")
        html  = u"<div class=\"iDevice\"><br/>\n"
        html += common.textInput("title" + self.id, self.idevice.title) + "<br/><br/>"
        sites = [(_(u"English Wikipedia Article"), "http://en.wikipedia.org/wiki/"),
                 (_(u"Catalan Wikipedia Article"), "http://ca.wikipedia.org/wiki/"),
                 (_(u"Chinese Wikipedia Article"), "http://zh.wikipedia.org/wiki/"),
                 (_(u"Dutch Wikipedia Article"),   "http://nl.wikipedia.org/wiki/"),
                 (_(u"French Wikipedia Article"),  "http://fr.wikipedia.org/wiki/"),
                 (_(u"German Wikipedia Article"),  "http://de.wikipedia.org/wiki/"),
                 (_(u"Greek Wikipedia Article"), "http://el.wikipedia.org/wiki/"),
                 (_(u"Italian Wikipedia Article"), "http://it.wikipedia.org/wiki/"),
                 (_(u"Japanese Wikipedia Article"),"http://ja.wikipedia.org/wiki/"),
                 (_(u"Magyar Wikipedia Article"),"http://hu.wikipedia.org/wiki/"),
                 (_(u"Polish Wikipedia Article"),  "http://pl.wikipedia.org/wiki/"),
                 (_(u"Portugese Wikipedia Article"), "http://pt.wikipedia.org/wiki/"),
                 (_(u"Slovenian Wikipedia Article"), "http://sl.wikipedia.org/wiki/"),
                 (_(u"Spanish Wikipedia Article"), "http://es.wikipedia.org/wiki/"),
                 (_(u"Swedish Wikipedia Article"), "http://sv.wikipedia.org/wiki/"),
                 (_(u"Wikibooks Article"),         "http://en.wikibooks.org/wiki/"),
                 (_(u"Wikiversity"),         "http://en.wikiversity.org/wiki/"),
                 (_(u"Wiktionary"),         "http://en.wiktionary.org/wiki/"),
                 (_(u"Wikieducator Content"),      "http://wikieducator.org/"),
                 (_(u"Other"),                     "")]          
        this_package = None
        if self.idevice is not None and self.idevice.parentNode is not None:
            this_package = self.idevice.parentNode.package
        html += common.formField('select', this_package, _('Site'),'s',
                                 'site'+self.id,
                                 self.idevice.langInstruc,
                                 sites,
                                 self.idevice.site)
        url = "none"
        if self.idevice.site == "":
            url = "block"
        html += '<div style="display:%s"> %s: <br/>' % (url, _("Own site"))
        html += common.textInput("ownUrl"+self.id, self.idevice.ownUrl) + '<br/></div>'
        html += "<br/>"
        html += common.textInput("article", self.idevice.articleName)
        html += common.elementInstruc(self.idevice.searchInstruc)
        html += common.submitButton(u"loadWikipedia"+self.id, _(u"Load"))
        html += u"<br/>\n"
        html += self.articleElement.renderEdit()
        emphasisValues = [(_(u"No emphasis"),     Idevice.NoEmphasis),
                          (_(u"Some emphasis"),   Idevice.SomeEmphasis)]
        html += common.formField('select', this_package, _('Emphasis'),
                                 'emphasis', self.id, 
                                 '', # TODO: Instructions
                                 emphasisValues,
                                 self.idevice.emphasis)
        html += self.renderEditButtons(undo=self.idevice.undo)
        html += u"</div>\n"
        return html
    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        log.debug("renderPreview")
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\" "
        html += u"ondblclick=\"submitLink('edit',"+self.id+", 0);\">\n"
        if self.idevice.emphasis != Idevice.NoEmphasis:
            if self.idevice.icon:
                html += u'<img alt="idevice icon" class="iDevice_icon" '
                html += u" src=\"/style/"+style
                html += "/icon_"+self.idevice.icon+".gif\"/>\n"
            html += u"<span class=\"iDeviceTitle\">"
            html += self.idevice.title
            html += u"</span>\n"
            html += u"<div class=\"iDevice_inner\">\n"
        html += self.articleElement.renderPreview()
        html += u"<br/>\n"
        html += u"This article is licensed under the "
        html += u'<span style="text-decoration: underline;">'
        html += u"GNU Free Documentation License</span>. It uses material "
        html += u'from the <span style="text-decoration: underline;">article '
        html += u'"%s"</span>.<br/>\n' % self.idevice.articleName
        html += self.renderViewButtons()
        if self.idevice.emphasis != Idevice.NoEmphasis:
            html += u"</div></div>\n"
        else:
            html += u"</div>\n"
        return html
    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """        
        log.debug("renderView")
        content = self.articleElement.renderView()
        content = re.sub(r'src="resources/', 'src="', content)
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\">\n"
        if self.idevice.emphasis != Idevice.NoEmphasis:
            if self.idevice.icon:
                html += u'<img alt="iDevice icon" class="iDevice_icon" '
                html += u" src=\"icon_"+self.idevice.icon+".gif\"/>\n"
            html += u"<span class=\"iDeviceTitle\">"
            html += self.idevice.title
            html += u"</span>\n"
            html += u"<div class=\"iDevice_inner\">\n"
        html += content
        html += u"<br/>\n"
        html += _(u"This article is licensed under the ")
        html += u"<a "
        html += u"href=\"javascript:window.open('fdl.html')\">"
        html += u"%s</a>. " % _(u"GNU Free Documentation License")
        html += _(u"It uses material from the ")
        if self.idevice.site == u"http://wikieducator.org/":
            html += u"<a href=\""+self.idevice.site
        else:
            html += u"<a href=\""+self.idevice.site+u"wiki/"
        html += self.idevice.articleName+u"\">"
        html += _(u"article ") 
        html += u"\""+self.idevice.articleName+u"\"</a>.<br/>\n"
        if self.idevice.emphasis != Idevice.NoEmphasis:
            html += u"</div></div>\n"
        else:
            html += u"</div>\n"
        return html
Beispiel #16
0
class TrueFalseElement(object):
    """
    TrueFalseElement is responsible for a block of question. 
    Used by TrueFalseBlock.
    """
    def __init__(self, index, idevice, question):
        """
        Initialize
        """
        self.index = index
        self.id = unicode(index) + "b" + idevice.id
        self.idevice = idevice

        self.question = question
        # also split out each part for a separate TextAreaElement:
        # but first...
        # to compensate for the strange unpickling timing when objects are
        # loaded from an elp, ensure that proper idevices are set:
        if question.questionTextArea.idevice is None:
            question.questionTextArea.idevice = idevice
        if question.feedbackTextArea.idevice is None:
            question.feedbackTextArea.idevice = idevice
        if question.hintTextArea.idevice is None:
            question.hintTextArea.idevice = idevice
        #
        self.question_question = TextAreaElement(question.questionTextArea)
        self.question_feedback = TextAreaElement(question.feedbackTextArea)
        self.question_hint = TextAreaElement(question.hintTextArea)

        # note, question.isCorrect is left as it was, and not split out.
        # because there are low-level mechanisms in place somewhere
        # with the radio buttons or ??? expecting that as such.

        self.questionId = "question" + unicode(index) + "b" + idevice.id
        self.question_question.id = self.questionId
        self.feedbackId = "feedback" + unicode(index) + "b" + idevice.id
        self.question_feedback.id = self.feedbackId
        self.hintId = "hint" + unicode(index) + "b" + idevice.id
        self.question_hint.id = self.hintId
        self.keyId = "Key" + unicode(index) + "b" + idevice.id

    def process(self, request):
        """
        Process arguments from the web server.  Return any which apply to this 
        element.
        """
        log.debug("process " + repr(request.args))

        is_cancel = common.requestHasCancel(request)

        if self.questionId in request.args \
        and not is_cancel:
            self.question_question.process(request)

        if self.hintId in request.args \
        and not is_cancel:
            self.question_hint.process(request)

        if self.keyId in request.args \
        and not is_cancel:
            if request.args[self.keyId][0] == "true":
                self.question.isCorrect = True
                log.debug("question " + repr(self.question.isCorrect))
            else:
                self.question.isCorrect = False

        if self.feedbackId in request.args \
        and not is_cancel:
            self.question_feedback.process(request)

        if "action" in request.args and request.args["action"][0] == self.id:
            # before deleting the question object, remove any internal anchors:
            for q_field in self.question.getRichTextFields():
                q_field.ReplaceAllInternalAnchorsLinks()
                q_field.RemoveAllInternalLinks()
            self.idevice.questions.remove(self.question)
            # disable Undo once a question has been deleted:
            self.idevice.undo = False

    def renderEdit(self):
        """
        Returns an XHTML string for editing this option element
        """

        html = self.question_question.renderEdit()

        html += _("True") + " "
        html += common.option(self.keyId, self.question.isCorrect, "true")
        html += _("False") + " "
        html += common.option(self.keyId, not self.question.isCorrect, "false")

        html += "<br/><br/>\n"

        html += common.elementInstruc(self.idevice.keyInstruc)

        html += self.question_feedback.renderEdit()
        html += self.question_hint.renderEdit()

        html += common.submitImage(self.id, self.idevice.id,
                                   "/images/stock-cancel.png",
                                   _("Delete question"))
        html += "<br/><br/>\n"
        return html

    def renderQuestionView(self):
        """
        Returns an XHTML string for viewing this question element
        """
        is_preview = 0
        html = self.renderQuestion(is_preview)
        return html

    """
    Will render this for XML - is actually designed to change this into
    an MCQ (because I'm lazy at the moment to make more J2ME)
    """

    def renderQuestionXML(self):
        questionFormatted = self.question_question.renderView()
        questionFormatted = questionFormatted.replace("align=\"right\"", "")
        xml = u"<question><![CDATA["
        xml += questionFormatted
        xml += "]]>"

        options = [True, False]

        for currentOption in options:
            answerCorrectStr = "false"
            if currentOption == self.question.isCorrect:
                answerCorrectStr = "true"

            xml += "<answer iscorrect='%s'><![CDATA[\n" % answerCorrectStr
            xml += "<span class='exe_tfmob'>" + str(currentOption) + "</span>"
            xml += "]]><feedback>\n<![CDATA["
            if currentOption == self.question.isCorrect:
                #this is a correct answer
                xml += "<img src='icon_mobile_stockcorrect.png'/>"
            else:
                xml += "<img src='icon_mobile_stockwrong.png'/>"

            xml += "]]></feedback>\n"
            xml += "</answer>\n"

        xml += "</question>\n"

        return xml

    def renderQuestionPreview(self):
        #TODO merge renderQuestionView and renderQuestionPreview
        """
        Returns an XHTML string for previewing this question element
        """
        is_preview = 1
        html = self.renderQuestion(is_preview)
        return html

    def renderQuestion(self, is_preview):
        """
        Returns an XHTML string for viewing and previewing this question element
        """
        log.debug("renderPreview called in the form of renderQuestion")

        lb = "\n"  #Line breaks
        dT = common.getExportDocType()
        titleTag = "h3"
        if dT == "HTML5":
            titleTag = "h1"

        if is_preview:
            html = '<' + titleTag + ' class="js-sr-av">' + c_(
                "Question") + ' ' + str(self.index +
                                        1) + '</' + titleTag + '>' + lb
            html += self.question_question.renderPreview()
            if self.question_hint.field.content:
                html += common.ideviceHint(self.question_hint.field.content,
                                           "preview", "h4")
        else:
            html = '<form name="true-false-form-' + self.id + '" action="#" class="activity-form">' + lb
            html += '<' + titleTag + ' class="js-sr-av">' + c_(
                "Question") + ' ' + str(self.index +
                                        1) + '</' + titleTag + '>' + lb
            html += self.question_question.renderView()
            if self.question_hint.field.content:
                html += common.ideviceHint(self.question_hint.field.content,
                                           "view", "h4")

        html += '<p class="iDevice_answer js-required">' + lb
        html += '<label for="true' + self.id + '">'
        html += self.__option(0, 2, "true") + ' '
        html += c_("True")
        html += '</label> ' + lb
        html += '<label for="false' + self.id + '">'
        html += self.__option(1, 2, "false") + ' '
        html += c_("False")
        html += '</label>' + lb
        html += '</p>' + lb

        if not is_preview:
            html += '</form>' + lb

        return html

    def __option(self, index, length, true):
        """Add a option input"""
        html = '<input type="radio" name="option%s" ' % self.id
        html += 'id="%s%s" ' % (true, self.id)
        html += 'class="exe-radio-option exe-radio-option-%d-%d-%s-truefalse" />' % (
            index, length, self.id)
        return html

    def renderFeedbackPreview(self):
        """
        Merely a front-end to renderFeedbackView(), setting preview mode.
        Note: this won't really matter all that much, since these won't yet
        show up in exported printouts, BUT the image paths will be correct.
        """
        return self.renderFeedbackView(is_preview=True)

    def renderFeedbackView(self, is_preview=False):
        """
        return xhtml string for display this option's feedback
        """
        lb = "\n"  #Line breaks
        dT = common.getExportDocType()
        sectionTag = "div"
        titleTag = "h4"
        if dT == "HTML5":
            sectionTag = "section"
            titleTag = "h1"

        if is_preview:
            content = self.question_feedback.field.content_w_resourcePaths
        else:
            content = self.question_feedback.field.content_wo_resourcePaths

        html = '<' + sectionTag + ' id="s' + self.id + '" class="feedback js-feedback js-hidden">' + lb
        html += '<' + titleTag + ' class="js-sr-av">' + c_(
            "Feedback") + '</' + titleTag + '>' + lb
        if self.question.isCorrect:
            html += '<p><strong id="s' + self.id + '-result" class="right">' + c_(
                "True") + '</strong></p>' + lb
        else:
            html += '<p><strong id="s' + self.id + '-result" class="wrong">' + c_(
                "False") + '</strong></p>' + lb
        html += content + lb
        html += '</' + sectionTag + '>' + lb

        return html
Beispiel #17
0
class HangmanBlockInc(Block):
    """
    ExampleBlock can render and process ExampleIdevices as XHTML
    GenericBlock will replace it..... one day
    """
    def __init__(self, parent, idevice):
        Block.__init__(self, parent, idevice)
        self.titleElement = TextElement(idevice.titleField)
        self.contentElement = TextAreaElement(idevice.content)
        self.contentElement.height = 250
        self.chanceImageElements = []

        #go through all image fields in the list and create an image element linked to that field
        for chanceImageField in idevice.chanceImageFields:
            newImgElement = ImageElement(chanceImageField)
            self.chanceImageElements.append(newImgElement)

        self.wordElements = []
        self.hintElements = []
        #go through all of the word fields and hint fields and create an 
        for wordIndex, word in enumerate(idevice.wordTextFields):
            newWordElement = TextElement(word)
            self.wordElements.append(newWordElement)
            newHintElement = TextElement(idevice.hintTextFields[wordIndex])
            self.hintElements.append(newHintElement)

        #make an element for the alphabet
        self.alphabetElement = TextElement(idevice.alphabet)

        #element for the messages that are shown to the player
        self.wrongGuessTextElement = TextAreaElement(self.idevice.wrongGuessMessageField)
        self.lostLevelTextElement = TextAreaElement(self.idevice.lostLevelMessageField)
        self.levelPassedTextElement = TextAreaElement(self.idevice.levelPasssedMessageField)
        self.gameWonTextElement = TextAreaElement(self.idevice.gameWonMessageField)
        
        self.letterButtonStyleElement = TextElement(self.idevice.letterButtonStyle)
        self.wrongLetterButtonStyleElement = TextElement(self.idevice.wrongLetterButtonStyle)
        self.rightLetterButtonStyleElement = TextElement(self.idevice.rightLetterButtonStyle)

        self.hintFieldStyleElement = TextElement(self.idevice.hintFieldStyle)
        self.wordAreaStyleElement = TextElement(self.idevice.wordAreaStyle)

        self.resetButtonTextElement = TextElement(self.idevice.resetButtonText)
        self.resetButtonStyleElement = TextElement(self.idevice.resetButtonStyle)
            

    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        
        #Make sure that we don't do anything when it's time to die...
        Block.process(self, request)
        self.idevice.message = ""
        
        if field_engine_is_delete_request(request):
            return
        
        self.idevice.addGameScript()

        self.titleElement.process(request)
        self.idevice.title = self.titleElement.renderView()
        self.alphabetElement.process(request)
        self.wrongGuessTextElement.process(request)
        self.lostLevelTextElement.process(request)
        self.levelPassedTextElement.process(request)
        self.gameWonTextElement.process(request)

        self.letterButtonStyleElement.process(request)
        self.wrongLetterButtonStyleElement.process(request)
        self.rightLetterButtonStyleElement.process(request)
        self.hintFieldStyleElement.process(request)
        self.wordAreaStyleElement.process(request)

        self.resetButtonTextElement.process(request)
        self.resetButtonStyleElement.process(request)
        
        #see if we need to delete a word
        blankWords = False
        for wordIndex in range(0, len(self.wordElements)):
            if self.wordElements[wordIndex].renderView() == "":
                blankWords = True
            elif self.hintElements[wordIndex].renderView() == "":
                blankWords = True
        
        if blankWords is True:
            self.idevice.message = _("One or more words or hints are blank.  Please do not have any blank hints or words - you can delete unused ones.")
            self.idevice.edit = True
        
        
        #see if we need to add another chance
        if ("addChance"+unicode(self.id)) in request.args: 
            self.idevice.addChance()
            self.idevice.edit = True
            # disable Undo once a question has been added:
            self.idevice.undo = False
        
        if("addWord"+unicode(self.id)) in request.args:
            self.idevice.addWord()
            self.idevice.edit = True
            self.idevice.undo = False

        content = self.contentElement.process(request)
        for imgElement in self.chanceImageElements:
            imgElement.process(request)
            if "action" in request.args and request.args["action"][0] == imgElement.id:
                self.idevice.chanceImageFields.remove(imgElement.field)
                imgElement.field.idevice.undo = False
                imgElement.field.idevice.edit = True
            

        for wordElement in self.wordElements:
            wordElement.process(request)
            if "action" in request.args and request.args["action"][0] == wordElement.id:
                wordIdx = self.wordElements.index(wordElement)
                self.idevice.wordTextFields.remove(wordElement.field)
                self.idevice.hintTextFields.remove(self.hintElements[wordIdx].field)
                wordElement.field.idevice.undo = False
                wordElement.field.idevice.edit = True
        
        for hintElement in self.hintElements:
            hintElement.process(request)

        if content:
            self.idevice.content = content

    #
    # Get an TextArea render back according to mode
    def _renderHTMLElement(self, mode, element, containerId = None):
        retVal = ""
        idStr = ""
        if containerId is not None:
            idStr = " id='%s' " % containerId
        retVal += "<div %s >" % idStr
        if mode == "preview":
            retVal += element.renderPreview()
        else:
            retVal += element.renderView()
        
        retVal += "</div>"
        return retVal
    #
    # This will generate the HTML elements and javascript that will be required
    # for this to be shown as a Javascript game in the web browser
    # 
    def _renderGame(self, style, mode = "view"):
        hangmanGameId = "hangman" + self.id
        
        resPath = ""
        if mode ==  "preview":
            resPath = "/templates/"       
        
        html = u"<script src='" + resPath + "hangman.js' type='text/javascript'></script>\n"
        html += common.ideviceHeader(self, style, mode)
        html += "<div id='hangman%(gameId)smessageStore' style='display: none'>" % {"gameId" : hangmanGameId}
        html += self._renderHTMLElement(mode, self.wrongGuessTextElement, "hmwrong" + hangmanGameId)
        html += self._renderHTMLElement(mode, self.lostLevelTextElement, "hmlost" + hangmanGameId)
        html += self._renderHTMLElement(mode, self.levelPassedTextElement, "hmpassed" + hangmanGameId)
        html += self._renderHTMLElement(mode, self.gameWonTextElement, "hmwon" + hangmanGameId)
        
        html += "</div>"
        html += u"<script type='text/javascript'>\n"

        #Go through the images and find out the max height and maxwidth
        imgMaxHeight = 0
        imgMaxWidth = 0

        for imgElement in self.chanceImageElements:
            if imgElement.field.imageResource and imgElement.field.imageResource is not None:
                if(int(imgElement.field.width) > imgMaxWidth):
                    imgMaxWidth = int(imgElement.field.width)

                if(imgElement.field.height > imgMaxHeight):
                    imgMaxHeight = int(imgElement.field.height)
        

        #Makes a javascript array of the list of words that the user has given
        html += "hangman_words['%s'] = new Array();\n" % hangmanGameId
        html += "hangman_buttonStyles['%s'] = new Array();\n" % hangmanGameId
        for wordIndex, word in enumerate(self.wordElements):
            html += u"hangman_words['%(gameId)s'][%(index)d] = new Array('%(word)s', '%(hint)s');\n" % \
                {"index" : wordIndex, "word" : word.renderView(), \
                "hint" : self.hintElements[wordIndex].renderView(), \
                "gameId" : hangmanGameId }
        
        #make the style for the buttons
        html += "hangman_buttonStyles['%(gameId)s'][HANGMAN_BEFORE_GUESS] = \"%(style)s\";\n" \
                % {"gameId" : hangmanGameId, "style" : self.letterButtonStyleElement.renderView()}
        html += "hangman_buttonStyles['%(gameId)s'][HANGMAN_CORRECT_GUESS] = \"%(style)s\";\n" \
                % {"gameId" : hangmanGameId, "style" : self.rightLetterButtonStyleElement.renderView()}
        html += "hangman_buttonStyles['%(gameId)s'][HANGMAN_WRONG_GUESS] = \"%(style)s\";\n" \
                % {"gameId" : hangmanGameId, "style" : self.wrongLetterButtonStyleElement.renderView()}

        #Makes a javscript string of the alphabet that the user can guess from
        html += u"hangman_alphabet['%(gameId)s'] = '%(alphabet)s';\n" % \
        {"alphabet" : self.alphabetElement.renderView(), \
        "gameId" : hangmanGameId }

        #Makes an array of the ids of the divs that hold the chance images
        html += u"hangman_chanceimgids['%s'] = new Array();\n" % hangmanGameId
        for imgIndex, imgElement in enumerate(self.chanceImageElements):
            html += "hangman_chanceimgids['%(gameId)s'][%(index)d] = '%(imgdivid)s';\n" % \
                {"index" : imgIndex, "imgdivid" : "hangman" + self.id + "img" + imgElement.id, \
                "gameId" : hangmanGameId }

        #Make the messages for this game
        html += u"playerMessages['%s'] = new Array();\n" % hangmanGameId
        
        
        
        messagesStr = """
        
        playerMessages['%(gameid)s']['wrongguess'] = 
            document.getElementById('hmwrong%(gameid)s').innerHTML;
        playerMessages['%(gameid)s']['lostlevel'] =
            document.getElementById('hmlost%(gameid)s').innerHTML;
        playerMessages['%(gameid)s']['levelpassed'] = 
            document.getElementById('hmpassed%(gameid)s').innerHTML;
        playerMessages['%(gameid)s']['gamewon'] = 
            document.getElementById('hmwon%(gameid)s').innerHTML;
        </script>
        """ % {"gameid" : hangmanGameId }
        
        html += messagesStr
        

        html += "<div id='hangman" + self.id + "_img'>"
        #render view of these images
        for imgElement in self.chanceImageElements:
            if imgElement.field.imageResource and imgElement.field.imageResource is not None:
                html += "<div id='hangman" + self.id + "img" + imgElement.id + "' style='display: none'>"
            
                if mode == "view":
                    html += imgElement.renderView()
                else:       
                    html += imgElement.renderPreview()
                html += "</div>"
       
        html += "</div>"

        messageTopMargin = (imgMaxHeight - 30) / 2
        gameWidth = max(600, imgMaxWidth)
        gameAreaHTML = """
<div id="%(gameId)s_gamearea" style='width: %(width)dpx;' class='exehangman_gamearea'>
        <div class='exehangman_alertarea' id="%(gameId)s_alertarea" style='position: absolute; z-index: 10; text-align: center; border: 1px; background-color: white; width: %(width)dpx; margin-top: %(messagetopmargin)dpx; visibility: hidden'>
        &#160;
        </div>
        <div id="%(gameId)s_imgarea" style='height: %(height)dpx; z-index: 1;' class='exehangman_imgarea'>
        </div>

        <input type='text' style='%(hintStyle)s' id='%(gameId)s_hintarea' style='width: %(width)dpx' class='exehangman_hintarea'/>
        <input type='text' style='%(wordStyle)s' id='%(gameId)s_wordarea' style='width: %(width)dpx' class='exehangman_wordarea'/>
        <div id="%(gameId)s_letterarea" class='exehangman_letterarea'>
        </div>
        <input class='exehangman_resetbutton' type='button' value='%(resetText)s' style='%(resetStyle)s' onclick='restartLevel("%(gameId)s")'/>
</div>

        """ % { "gameId" : hangmanGameId, "width" : gameWidth, "height": imgMaxHeight, \
                "messagetopmargin" : messageTopMargin, 'hintStyle' : self.hintFieldStyleElement.renderView(), \
                'wordStyle' : self.wordAreaStyleElement.renderView(), 'resetText' : self.resetButtonTextElement.renderView(), \
                'resetStyle' : self.resetButtonStyleElement.renderView() }
        html += gameAreaHTML
        html += "<script type='text/javascript'>setupGame('%s');</script>" % hangmanGameId

        return html



    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        html  = u"<div>\n"
        html += common.ideviceShowEditMessage(self)
        
        
        html += self.titleElement.renderEdit()
        html += self.contentElement.renderEdit()
        html += self.alphabetElement.renderEdit()

        #messages to show the user for different events
        html += self.wrongGuessTextElement.renderEdit()
        html += self.lostLevelTextElement.renderEdit()
        html += self.levelPassedTextElement.renderEdit()
        html += self.gameWonTextElement.renderEdit()
        html += self.resetButtonTextElement.renderEdit()

        divId = "fieldtype_advanced"  + self.id
        html += "<input name='showbox" + divId + "' type='checkbox' onchange='$(\"#" + divId + "\").toggle()'/>"
        
        html += _("Show Advanced Options") + "<br/>"
        html += "<div id='" + divId + "' style='display: none' "
        html += ">"
        
        #styles for buttons
        html += self.letterButtonStyleElement.renderEdit()
        html += self.wrongLetterButtonStyleElement.renderEdit()
        html += self.rightLetterButtonStyleElement.renderEdit()

        #style of the text fields
        html += self.hintFieldStyleElement.renderEdit()
        html += self.wordAreaStyleElement.renderEdit()

        html += self.resetButtonStyleElement.renderEdit()
        html += "</div>"
        
        #render edit of these images
        for imgElement in self.chanceImageElements:
            html += imgElement.renderEdit()
            html += common.submitImage(imgElement.id, imgElement.field.idevice.id, 
                                   "/images/stock-cancel.png",
                                   _("Remove This Life")) + "<br/>"

        addChanceButtonLabel = _("Add Chance")
        html += common.submitButton("addChance"+unicode(self.id), addChanceButtonLabel)
        html += "<br/>"

        #show words to be guessed
        html += _("<h2>Words to Guess</h2>")
        for wordIndex in range(0, len(self.wordElements)):
            word = self.wordElements[wordIndex]
            html += word.renderEdit()
            html += self.hintElements[wordIndex].renderEdit()
            html += "<br/>"
            if wordIndex > 0:
                html += common.submitImage(word.id, word.field.idevice.id, 
                                   "/images/stock-cancel.png",
                                   _("Remove This Word")) + "<br/>"
        
        html += common.submitButton("addWord"+unicode(self.id), _("Add Word"))        
        html += "<br/>"
        html += self.renderEditButtons()
        html += u"</div>\n"
        return html


    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\" "
        html += u"ondblclick=\"submitLink('edit',"+self.id+", 0);\">\n"
        html += self.contentElement.renderView()
        html += self._renderGame(style, mode = "preview")

        html += self.renderViewButtons()
        html += "</div>\n"
        return html

    def renderXML(self, style):
        xml = u""
        
        mediaConverter = ExportMediaConverter.getInstance()
        width = mediaConverter.getProfileWidth()
        height = mediaConverter.getProfileHeight()
        
        if mediaConverter is not None:
            for imgElement in  self.chanceImageElements:
                if imgElement.field.imageResource is not None:
                    mediaConverter.resizeImg(XMLPage.currentOutputDir/imgElement.field.imageResource.storageName, \
                         width, height, {}, {"resizemethod" : "stretch"})
        
        xml += "<idevice type='hangman' id='%s'>\n" % self.idevice.id
        xml += "<chanceimages>\n"
        for imgElement in  self.chanceImageElements:
            if imgElement.field.imageResource is not None:
                xml += "<img src='%s'/>\n" % imgElement.field.imageResource.storageName
            
        xml += "</chanceimages>\n"
        
        xml += "<alphabet>%s</alphabet>\n" % self.alphabetElement.renderView()
        xml += "<wrongguessmessage><![CDATA[ %s ]]></wrongguessmessage>\n" % self.wrongGuessTextElement.renderView()
        xml += "<lostlevelmessage><![CDATA[ %s ]]></lostlevelmessage>\n" % self.lostLevelTextElement.renderView()
        xml += "<levelpassedmessage><![CDATA[ %s ]]></levelpassedmessage>\n" % self.levelPassedTextElement.renderView()
        xml += "<gamewonmessage><![CDATA[ %s ]]></gamewonmessage>\n" % self.gameWonTextElement.renderView()
        
        xml += "<words>"
        for wordIndex in range(0, len(self.wordElements)):
            word = self.wordElements[wordIndex]
            if word != "":
                xml += "<word>\n<hint>%(hint)s</hint>\n<answer>%(answer)s</answer>\n</word>\n" \
                    % {"answer" : word.renderView() , "hint" : self.hintElements[wordIndex].renderView()}
            
        xml += "</words>\n"
        
        xml += "</idevice>\n"
        return xml


    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\">\n"
        html += self.contentElement.renderView()
        html += self._renderGame(style, mode = "view")
        html += u"</div>\n"
        return html
Beispiel #18
0
class FreeTextBlock(Block):
    """
    FreeTextBlock can render and process FreeTextIdevices as XHTML
    GenericBlock will replace it..... one day
    """
    def __init__(self, parent, idevice):
        Block.__init__(self, parent, idevice)
        if idevice.content.idevice is None: 
            # due to the loading process's timing, idevice wasn't yet set; 
            # set it here for the TextAreaElement's tinyMCE editor 
            idevice.content.idevice = idevice

        self.contentElement = TextAreaElement(idevice.content)
        self.contentElement.height = 250
        if not hasattr(self.idevice,'undo'): 
            self.idevice.undo = True


    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        is_cancel = common.requestHasCancel(request)

        if is_cancel:
            self.idevice.edit = False
            # but double-check for first-edits, and ensure proper attributes:
            if not hasattr(self.idevice.content, 'content_w_resourcePaths'):
                self.idevice.content.content_w_resourcePaths = ""
            if not hasattr(self.idevice.content, 'content_wo_resourcePaths'):
                self.idevice.content.content_wo_resourcePaths = ""
            return

        Block.process(self, request)

        if (u"action" not in request.args or 
            request.args[u"action"][0] != u"delete"): 
            content = self.contentElement.process(request) 
            if content: 
                self.idevice.content = content


    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        html  = u"<div style=\"position: relative\">\n"
        html += self.contentElement.renderEdit()
        html += self.renderEditButtons()
        html += u"</div>\n"
        return html


    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        if hasattr(self.idevice, 'parent') and self.idevice.parent and not self.idevice.parent.edit:
            return u""
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\" "
        html += u"style=\"position: relative\" "
        html += u"ondblclick=\"submitLink('edit',"+self.id+", 0);\">\n"
        html += self.contentElement.renderPreview()
        html += self.renderViewButtons()
        html += "</div>\n"
        return html


    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\">\n"
        html += self.contentElement.renderView()
        html += u"</div>\n"
        return html
Beispiel #19
0
class WikipediaBlock(Block):
    """
    WikipediaBlock can render and process WikipediaIdevices as XHTML
    """
    def __init__(self, parent, idevice):
        """
        Initialize
        """
        Block.__init__(self, parent, idevice)

        # to compensate for the strange unpickling timing when objects are
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.article.idevice is None:
            idevice.article.idevice = idevice
        self.articleElement = TextAreaElement(idevice.article)
        self.articleElement.height = 300
        if not hasattr(self.idevice, 'undo'):
            self.idevice.undo = True

    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        log.debug("process " + repr(request.args))

        is_cancel = common.requestHasCancel(request)

        if 'emphasis'+self.id in request.args \
        and not is_cancel:
            self.idevice.emphasis = int(request.args['emphasis' + self.id][0])
            # disable Undo once an emphasis has changed:
            self.idevice.undo = False

        if 'ssite'+self.id in request.args \
        and not is_cancel:
            self.idevice.site = request.args['ssite' + self.id][0]

        if 'ownUrl'+self.id in request.args \
        and not is_cancel:
            self.idevice.ownUrl = request.args['ownUrl' + self.id][0]

        if 'title'+self.id in request.args \
        and not is_cancel:
            self.idevice.title = request.args['title' + self.id][0]

        if ("object" in request.args
                and request.args["object"][0] == "site" + self.id):
            pass
        elif 'loadWikipedia' + self.id in request.args:
            # If they've hit "load" instead of "the tick"
            self.idevice.loadArticle(request.args['article'][0])
            # disable Undo once an article has been loaded:
            self.idevice.undo = False
        else:
            # If they hit "the tick" instead of "load"
            Block.process(self, request)
            if (u"action" not in request.args \
            or request.args[u"action"][0] != u"delete"):
                # If the text has been changed
                self.articleElement.process(request)
            if "action" in request.args \
            and request.args["action"][0] == "done":
                # remove the undo flag in order to reenable it next time:
                if hasattr(self.idevice, 'undo'):
                    del self.idevice.undo

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form elements for editing this block
        """
        log.debug("renderEdit")

        html = u"<div class=\"iDevice\"><br/>\n"
        html += common.textInput("title" + self.id,
                                 self.idevice.title) + "<br/><br/>"

        sites = [
            (_(u"English Wikipedia Article"), "http://en.wikipedia.org/wiki/"),
            (_(u"Catalan Wikipedia Article"), "http://ca.wikipedia.org/wiki/"),
            (_(u"Chinese Wikipedia Article"), "http://zh.wikipedia.org/wiki/"),
            (_(u"Dutch Wikipedia Article"), "http://nl.wikipedia.org/wiki/"),
            (_(u"French Wikipedia Article"), "http://fr.wikipedia.org/wiki/"),
            (_(u"German Wikipedia Article"), "http://de.wikipedia.org/wiki/"),
            (_(u"Greek Wikipedia Article"), "http://el.wikipedia.org/wiki/"),
            (_(u"Italian Wikipedia Article"), "http://it.wikipedia.org/wiki/"),
            (_(u"Japanese Wikipedia Article"),
             "http://ja.wikipedia.org/wiki/"),
            (_(u"Magyar Wikipedia Article"), "http://hu.wikipedia.org/wiki/"),
            (_(u"Polish Wikipedia Article"), "http://pl.wikipedia.org/wiki/"),
            (_(u"Portugese Wikipedia Article"),
             "http://pt.wikipedia.org/wiki/"),
            (_(u"Slovenian Wikipedia Article"),
             "http://sl.wikipedia.org/wiki/"),
            (_(u"Spanish Wikipedia Article"), "http://es.wikipedia.org/wiki/"),
            (_(u"Swedish Wikipedia Article"), "http://sv.wikipedia.org/wiki/"),
            (_(u"Wikibooks Article"), "http://en.wikibooks.org/wiki/"),
            (_(u"Wikiversity"), "http://en.wikiversity.org/wiki/"),
            (_(u"Wiktionary"), "http://en.wiktionary.org/wiki/"),
            (_(u"Wikieducator Content"), "http://wikieducator.org/"),
            (_(u"Other"), "")
        ]

        this_package = None
        if self.idevice is not None and self.idevice.parentNode is not None:
            this_package = self.idevice.parentNode.package
        html += common.formField('select', this_package, _('Site'), 's',
                                 'site' + self.id, self.idevice.langInstruc,
                                 sites, self.idevice.site)

        url = "none"
        if self.idevice.site == "":
            url = "block"
        html += '<div style="display:%s"> %s: <br/>' % (url, _("Own site"))
        html += common.textInput("ownUrl" + self.id,
                                 self.idevice.ownUrl) + '<br/></div>'
        html += "<br/>"
        html += common.textInput("article", self.idevice.articleName)
        html += common.elementInstruc(self.idevice.searchInstruc)
        html += common.submitButton(u"loadWikipedia" + self.id, _(u"Load"))

        html += u"<br/>\n"
        html += self.articleElement.renderEdit()
        emphasisValues = [(_(u"No emphasis"), Idevice.NoEmphasis),
                          (_(u"Some emphasis"), Idevice.SomeEmphasis)]

        html += common.formField(
            'select',
            this_package,
            _('Emphasis'),
            'emphasis',
            self.id,
            '',  # TODO: Instructions
            emphasisValues,
            self.idevice.emphasis)

        html += self.renderEditButtons(undo=self.idevice.undo)
        html += u"</div>\n"
        return html

    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        log.debug("renderPreview")
        html = u"<div class=\"iDevice "
        html += u"emphasis" + unicode(self.idevice.emphasis) + "\" "
        html += u"ondblclick=\"submitLink('edit'," + self.id + ", 0);\">\n"
        if self.idevice.emphasis != Idevice.NoEmphasis:
            if self.idevice.icon:
                html += u'<img alt="idevice icon" class="iDevice_icon" '
                html += u" src=\"/style/" + style
                html += "/icon_" + self.idevice.icon + ".gif\"/>\n"
            html += u"<span class=\"iDeviceTitle\">"
            html += self.idevice.title
            html += u"</span>\n"
            html += u"<div class=\"iDevice_inner\">\n"
        html += self.articleElement.renderPreview()
        html += u"<br/>\n"
        html += u"This article is licensed under the "
        html += u'<span style="text-decoration: underline;">'
        html += u"GNU Free Documentation License</span>. It uses material "
        html += u'from the <span style="text-decoration: underline;">article '
        html += u'"%s"</span>.<br/>\n' % self.idevice.articleName
        html += self.renderViewButtons()
        if self.idevice.emphasis != Idevice.NoEmphasis:
            html += u"</div></div>\n"
        else:
            html += u"</div>\n"
        return html

    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        log.debug("renderView")
        content = self.articleElement.renderView()
        content = re.sub(r'src="resources/', 'src="', content)
        html = u"<div class=\"iDevice "
        html += u"emphasis" + unicode(self.idevice.emphasis) + "\">\n"

        html += u"<div class=\"wiki_site\" value=\"" + self.idevice.site \
                + "\"></div>"
        html += u"<div class=\"article_name\" value=\"" + self.idevice.articleName \
                + "\"></div>"
        html += u"<div class=\"own_url\" value=\"" + self.idevice.ownUrl \
                + "\"></div>\n"

        if self.idevice.emphasis != Idevice.NoEmphasis:
            if self.idevice.icon:
                html += u'<img alt="iDevice icon" class="iDevice_icon" '
                html += u" src=\"icon_" + self.idevice.icon + ".gif\"/>\n"
            html += u"<span class=\"iDeviceTitle\">"
            html += self.idevice.title
            html += u"</span>\n"
            html += u"<div class=\"iDevice_inner\">\n"
        html += content
        html += u"<br/>\n"
        html += _(u"This article is licensed under the ")
        html += u"<a "
        html += u"href=\"javascript:window.open('fdl.html')\">"
        html += u"%s</a>. " % _(u"GNU Free Documentation License")
        html += _(u"It uses material from the ")
        # UGLY UGLY UGLY KLUDGE for Wayne
        # "BIG please - Will you check that the Wikieducator url is changed for
        # the next release - not sure if we'll get the image thing sorted, but
        # this is pretty important strategically re the international growth of
        # eXe.  Not a new feature <smile> just a small change to a string."
        if self.idevice.site == u"http://wikieducator.org/":
            html += u"<a href=\"" + self.idevice.site
        else:
            html += u"<a href=\"" + self.idevice.site + u"wiki/"
        html += self.idevice.articleName + u"\">"
        html += _(u"article ")
        html += u"\"" + self.idevice.articleName + u"\"</a>.<br/>\n"
        if self.idevice.emphasis != Idevice.NoEmphasis:
            html += u"</div></div>\n"
        else:
            html += u"</div>\n"
        return html
Beispiel #20
0
class RssBlock(Block):
    """
    RssBlock can render and process RssIdevices as XHTML
    """
    def __init__(self, parent, idevice):
        """
        Initialize
        """
        Block.__init__(self, parent, idevice)
        if idevice.rss.idevice is None: 
            idevice.rss.idevice = idevice
        self.rssElement = TextAreaElement(idevice.rss)
        self.rssElement.height = 300
        if not hasattr(self.idevice,'undo'): 
            self.idevice.undo = True
    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        log.debug("process " + repr(request.args))
        is_cancel = common.requestHasCancel(request)
        if 'emphasis'+self.id in request.args \
        and not is_cancel:
            self.idevice.emphasis = int(request.args['emphasis'+self.id][0])
        if 'site'+self.id in request.args \
        and not is_cancel:
            self.idevice.site = request.args['site'+self.id][0]
        if 'title'+self.id in request.args \
        and not is_cancel:
            self.idevice.title = request.args['title'+self.id][0]
        if "url" + self.id in request.args \
        and not is_cancel:
            self.idevice.url = request.args['url'+ self.id][0]
        if 'loadRss'+self.id in request.args \
        and not is_cancel:
            self.idevice.undo = False
            self.idevice.loadRss(request.args['url'+ self.id][0])
        else:
            Block.process(self, request)
            if (u"action" not in request.args or
                request.args[u"action"][0] != u"delete"):
                self.rssElement.process(request)
            if "action" in request.args \
            and request.args["action"][0] == "done":
                if hasattr(self.idevice,'undo'): 
                    del self.idevice.undo
    def renderEdit(self, style):
        """
        Returns an XHTML string with the form elements for editing this block
        """
        log.debug("renderEdit")
        html  = u"<div class=\"iDevice\"><br/>\n"
        html += common.textInput("title" + self.id, self.idevice.title)
        html += '<br/><br/>RSS URL ' + common.textInput("url" + self.id,
                                                        self.idevice.url)
        html += common.submitButton(u"loadRss"+self.id, _(u"Load"))
        html += common.elementInstruc(self.idevice.urlInstruc)
        html += u"<br/>\n"
        html += self.rssElement.renderEdit()
        emphasisValues = [(_(u"No emphasis"),     Idevice.NoEmphasis),
                          (_(u"Some emphasis"),   Idevice.SomeEmphasis)]
        this_package = None
        if self.idevice is not None and self.idevice.parentNode is not None:
            this_package = self.idevice.parentNode.package
        html += common.formField('select', this_package, _('Emphasis'),
                                 'emphasis', self.id, 
                                 '', # TODO: Instructions
                                 emphasisValues,
                                 self.idevice.emphasis)
        html += self.renderEditButtons(undo=self.idevice.undo)
        html += u"</div>\n"
        return html
    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        log.debug("renderPreview")
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\" "
        html += u"ondblclick=\"submitLink('edit',"+self.id+", 0);\">\n"
        if self.idevice.emphasis != Idevice.NoEmphasis:
            if self.idevice.icon:
                html += u'<img alt="idevice icon" class="iDevice_icon" '
                html += u" src=\"/style/"+style
                html += "/icon_"+self.idevice.icon+".gif\"/>\n"
            html += u"<span class=\"iDeviceTitle\">"
            html += self.idevice.title
            html += u"</span>\n"
            html += u"<div class=\"iDevice_inner\">\n"
        html += self.rssElement.renderPreview()
        html += self.renderViewButtons()
        if self.idevice.emphasis != Idevice.NoEmphasis:
            html += u"</div></div>\n"
        else:
            html += u"</div>\n"
        return html
    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """        
        log.debug("renderView")
        content = self.rssElement.renderView()
        content = re.sub(r'src="/.*?/resources/', 'src="', content)
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\">\n"
        html += u"<div class=\"rss_url\" value=\"" + self.idevice.url \
                + "\"></div>"
        if self.idevice.emphasis != Idevice.NoEmphasis:
            if self.idevice.icon:
                html += u'<img alt="iDevice icon" class="iDevice_icon" '
                html += u" src=\"icon_"+self.idevice.icon+".gif\"/>\n"
            html += u"<span class=\"iDeviceTitle\">"
            html += self.idevice.title
            html += u"</span>\n"
            html += u"<div class=\"iDevice_inner\">\n"
        html += content
        if self.idevice.emphasis != Idevice.NoEmphasis:
            html += u"</div></div>\n"
        else:
            html += u"</div>\n"
        return html
class PlaceTheObjectsBlockInc(Block):
    """
    ExampleBlock can render and process ExampleIdevices as XHTML
    GenericBlock will replace it..... one day
    """
    def __init__(self, parent, idevice):
        Block.__init__(self, parent, idevice)
        self.contentElement = TextAreaElement(idevice.content)
        self.contentElement.height = 250
        self.titleElement = TextElement(idevice.titleField)

        self.mainAreaElement = TextAreaElement(idevice.mainArea)
        self.mainAreaElement.height = 200
        
        self.placableObjectElements = []
        for placableObjectField in idevice.objectsToPlace:
            newPlacableElement = PlacableObjectElement(placableObjectField)
            self.placableObjectElements.append(newPlacableElement)

        self.positiveResponseElement = TextAreaElement(idevice.positiveResponseArea)
        self.negativeResponseElement = TextAreaElement(idevice.negativeResponseArea)
        self.clickToStartElement = TextAreaElement(idevice.clickToStartGameArea)
        self.gameTimeLimit = TextElement(idevice.gameTimeLimit)
        self.gameTimerShown = TextElement(idevice.gameTimerShown)
        self.partbinNumCols = TextElement(idevice.partbinNumCols)


    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        Block.process(self, request)

        self.idevice.uploadNeededScripts()

        if "addPlacableObject" + unicode(self.id) in request.args:
            self.idevice.addPlacableObject()
            self.idevice.edit = True
            self.idevice.undo = False
        if "checktimer" + unicode(self.id) in request.args:
            if "enabletimer" + unicode(self.id) in request.args:
                self.idevice.gameTimerShown.content = True
            else:
                self.idevice.gameTimerShown.content = False

        self.titleElement.process(request)
        self.idevice.title = self.titleElement.renderView()
        self.contentElement.process(request)
        self.mainAreaElement.process(request)
        self.positiveResponseElement.process(request)
        self.negativeResponseElement.process(request)
        self.clickToStartElement.process(request)
        self.gameTimeLimit.process(request)
        self.partbinNumCols.process(request)

        for placableObjectElement in self.placableObjectElements:
            placableObjectElement.process(request)
        

    def _makeObjectDivId(self, elementTypeName, placeableObjectElement):
        """
        Makes an id for a div that is the drag or drop element 
        as specified by elementTypeName = draggable | droppable
        for placeableObjectElement
        """

        objectdivid = "placetheobjects" + self.id + "_" + elementTypeName + placeableObjectElement.id
        return objectdivid

    def _renderForGame(self, style, previewMode = False):
        """
        Renders the block as the script and XHTML elements that will be needed in order
        to make this run as a game
        """
        viewModeStr = "view"
        scriptPrefix = ""
        if previewMode == True:
            scriptPrefix = "resources/"
            viewModeStr = "preview"

        html = "<script src='%sjquery-ui-1.10.3.custom.min.js' type='text/javascript'></script>\n" % scriptPrefix
        html += "<script src='%splacetheobjects.js' type='text/javascript'></script>\n" % scriptPrefix
        
        html += common.ideviceHeader(self, style, viewModeStr)
        
        #this shows the instructions
        html += self.contentElement.renderView()

        """
        Here we make the droppable target divs
        """
        for placeableObjectElement in self.placableObjectElements:
            borderStr = ""
            if previewMode == True:
                borderStr = "border: 1px solid red;"
            tolerance = int(placeableObjectElement.toleranceElement.renderView())

            html += """<div id='%(droppableid)s' class='placeTheObjectTargetClass%(gameId)s' style='position: absolute; 
                        margin-left: %(marginleft)dpx; margin-top: %(margintop)dpx;
                        width: %(width)dpx; height: %(height)dpx; %(borderstr)s '>
                        </div>
                """ % { "droppableid" : self._makeObjectDivId("droppable", placeableObjectElement), \
                        "marginleft" : int(placeableObjectElement.targetXElement.renderView()) - tolerance, \
                        "margintop" : int(placeableObjectElement.targetYElement.renderView()) - tolerance, \
                        "width": int(placeableObjectElement.widthElement.renderView()) + (tolerance * 2), \
                        "height": int(placeableObjectElement.heightElement.renderView()) + (tolerance * 2), \
                        "borderstr": borderStr, "gameId" : str(self.id) }

        """+ve/-ve feedback areas"""
        html += "<div id='placetheobjects_" + self.id +"_positivefeedback'" \
                +" style='position: absolute; z-index: 1; '>"
        if previewMode == True:
            html += self.positiveResponseElement.renderPreview()
        else:
            html += self.positiveResponseElement.renderView()
        html += "</div>"

        
        html += "<div id='placetheobjects_" + self.id + "_negativefeedback' " \
                + "style='position: absolute; z-index: 1;'>" 
        if previewMode == True:
            html += self.negativeResponseElement.renderPreview()
        else:
            html += self.negativeResponseElement.renderView()
        html += "</div>"

        """What to click to start the game"""
        html += "<div id='placetheobjects_" + self.id + "_clicktostart' style='position: " \
                + "absolute; cursor: pointer; z-index: 3' onclick='startPlaceGame(\"" + self.id + "\")'>"
        if previewMode == True:
            html += self.clickToStartElement.renderPreview()
        else:
            html += self.clickToStartElement.renderView()
        html += "</div>"



        """
        This is the main area background where the elements are going to be dropped...
        """
        html += "<div style='z-index: -4;' id='placetheobjects_" + self.id + "_main'>"
        if previewMode == True:
            html += self.mainAreaElement.renderPreview()
        else:
            html += self.mainAreaElement.renderView()

        html += "</div>"
        """
        Here we make the part bin that will contain the elements that will be dragged 
        and dropped in place
        """

        html += "<div id='placetheobjects" + self.id + "_partbin'>\n"
        html += "<table cellpadding='2' cellspacing='2'>"
        numCols = int(self.partbinNumCols.renderView())
        html += "<!-- num cols = " + str(numCols) + "-->"
        colCount = 0
        elementCount = 0

        for placeableObjectElement in self.placableObjectElements:
            if elementCount % numCols == 0:
                #we need to make a new row...
                if elementCount > 0:
                    html += "</tr>"
                html += "<tr>"
                
            idname = self._makeObjectDivId("draggable", placeableObjectElement)
            elementDimensions = {"width" : int(placeableObjectElement.widthElement.renderView()), \
                "height" : int(placeableObjectElement.heightElement.renderView()) }
            html += "<td style='width: %(width)dpx; height: $(height)spx;'>"
            html += "<div id='" + idname + "' onclick=\"objectPlacePickupElement('%(gameid)s', '%(draggableid)s')\" style='cursor: pointer;  " \
                % {"gameid" : str(self.id), "draggableid" : idname}
            html += "width: %(width)dpx; height: %(height)dpx; overflow: hidden; z-index: 1;'>\n" \
                % elementDimensions
            html += placeableObjectElement.mainContentElement.renderView()
            html += "</div>\n"
            html += "</td>"
            elementCount += 1

        html += "</tr></table>"        
        html += "</div>\n"

        html += "<!-- Javascript Code Generated by placetheobjectsblock.py - DO NOT MODIFY -->\n"
        html += "<script type='text/javascript'>\n"
        html +="initPlaceTheObjectsGameData('" + self.id + "');\n"
        html += "placeTheObjectsGameData['" + self.id + "']['showtimer'] = '" + str(self.gameTimerShown.field.content) + "';\n"
        html += "placeTheObjectsGameData['" + self.id + "']['timelimit'] = '" + str(self.gameTimeLimit.field.content) + "';\n"

        for placeableObjectElement in self.placableObjectElements:
            draggable_id = self._makeObjectDivId("draggable", placeableObjectElement)
            droppable_id = self._makeObjectDivId("droppable", placeableObjectElement)

            perItemCode = """
                if(exe_isTouchScreenDev == false) {
                    $(function() {
                    $("#%(draggableid)s").draggable({ 
                            revert : 'invalid',
                            start: function(event, ui) {
                                    placeObjectReadyTarget("%(droppableid)s");
                            },
                            stop: function (event, ui) {
                                    placeObjectHideTarget("%(droppableid)s");
                                    setTimeout('checkObjectPlaceOK("%(gameId)s", "%(draggableid)s")', 300);
                            }
                            }
                    );
                    $("#%(droppableid)s").droppable({
                    accept: "#%(draggableid)s",
                    activeClass: "ui-state-hover",
                    hoverClass: "ui-state-active",
                            drop: function(event, ui) {
                                    $("#%(draggableid)s").effect("pulsate", {}, "fast");
                                    objectPlaceOK("%(gameId)s", "%(draggableid)s");
                            }
                            });
                    });
                    document.getElementById("%(draggableid)s").onclick = null;   
                }
                
                placeTheObjectsGameData['%(gameId)s']['elements']['%(draggableid)s'] = new Array();
                placeTheObjectsGameData['%(gameId)s']['elements']['%(draggableid)s']['status'] = 'notplaced';
                placeTheObjectsGameData['%(gameId)s']['elements']['%(draggableid)s']['bounds'] = new Array(%(targetx)s, %(targety)s, %(width)s, %(height)s ); 
                               
                """ % { "draggableid" : draggable_id, "droppableid" : droppable_id, "gameId" : str(self.id), \
                "targetx": placeableObjectElement.targetXElement.renderView() , "targety" : placeableObjectElement.targetYElement.renderView(),\
                "width" : placeableObjectElement.widthElement.renderView(),  "height" : placeableObjectElement.heightElement.renderView() }
            html += perItemCode

        html += "</script>\n"
        html += common.ideviceFooter(self, style, viewModeStr)
        return html


    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        html  = u"<div>\n"
        html += self.titleElement.renderEdit()
        html += self.contentElement.renderEdit()
        html += self.mainAreaElement.renderEdit()

        html +=u"<strong>"+_("Game Options") +"</strong>"
        
        html += self.clickToStartElement.renderEdit()
        html += self.positiveResponseElement.renderEdit()
        html += self.negativeResponseElement.renderEdit()
        html += self.partbinNumCols.renderEdit()
        """
        Timer Options
        """
        html += "<input type='hidden' name='checktimer%s' value='true'/>" % self.id
        html += common.checkbox("enabletimer%s" % self.id, self.idevice.gameTimerShown.content, \
                title=_("Enable Timer"), instruction=_("Enable showing the timer in the game"))
        html += self.gameTimeLimit.renderEdit()

        for placableObjectElement in self.placableObjectElements:
            html += placableObjectElement.renderEdit()
        
        html += "<br/>"
        html += common.submitButton("addPlacableObject"+unicode(self.id), _("Add Placable Object"))
        html += "<br/>"
        
        
        html += self.renderEditButtons()
        html += u"</div>\n"
        return html


    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        
        html = self._renderForGame(style, True)

        return html


    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        
        html = self._renderForGame(style, previewMode=False)

        return html
Beispiel #22
0
class FlashMovieBlock(Block):
    """
    FlashMovieBlock can render and process FlashMovieIdevices as XHTML
    """
    name = 'flashMovie'
    def __init__(self, parent, idevice):
        """
        Initialize
        """
        Block.__init__(self, parent, idevice)
        self.flashMovieElement = FlashMovieElement(idevice.flash)
        self.textElement  = TextAreaElement(idevice.text)
    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        log.debug("process " + repr(request.args))
        Block.process(self, request)
        if (u"action" not in request.args or
            request.args[u"action"][0] != u"delete"):
            self.flashMovieElement.process(request)
            self.textElement.process(request)
        if "float"+self.id in request.args:
            self.idevice.float = request.args["float"+self.id][0]
        if "caption"+self.id in request.args:
            self.idevice.caption = request.args["caption"+self.id][0]
    def renderEdit(self, style):
        """
        Returns an XHTML string with the form elements for editing this block
        """
        log.debug("renderEdit")
        html  = u"<div class=\"iDevice\">\n"
        html += self.flashMovieElement.renderEdit()       
        floatArr    = [[_(u'Left'), 'left'],
                      [_(u'Right'), 'right'],
                      [_(u'None'),  'none']]
        html += common.formField('select', _("Align:"),
                                 "float" + self.id,
                                 options = floatArr,
                                 selection = self.idevice.float)
        html += u'<div class="block">'
        html += u"<b>%s </b>" % _(u"Caption:")
        html += common.elementInstruc(self.idevice.captionInstruc)
        html += u'</div>\n'
        html += u'<div class="block">'
        html += common.textInput("caption" + self.id, self.idevice.caption)
        html += u'</div>\n'
        html += u'<div class="block">'
        html += self.textElement.renderEdit()
        html += self.renderEditButtons()
        html += u'</div>\n'
        html += u"</div>\n"
        return html
    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        log.debug("renderPreview")
        html  = u"\n<!-- flash with text iDevice -->\n"
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\" "
        html += "ondblclick=\"submitLink('edit',"+self.id+", 0);\">\n"
        html += u"<div class=\"flash_text\" style=\""
        html += u"width:" + str(self.idevice.flash.width) + "px; "
        html += u"float:%s;\">\n" % self.idevice.float
        html += u"<div class=\"flash\">\n"
        html += self.flashMovieElement.renderPreview()
        html += u"" + self.idevice.caption + "</div>"
        html += u"</div>\n"
        html += self.textElement.renderPreview()
        html += u"<br/>\n"        
        html += u"<div style=\"clear:both;\">"
        html += u"</div>\n"
        html += self.renderViewButtons()
        html += u"</div>\n"
        return html
    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """        
        log.debug("renderView")
        html  = u"\n<!-- Flash with text iDevice -->\n"
        html += u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\">\n"
        html += u"<div class=\"flash_text\" style=\""
        html += u"width:" + str(self.idevice.flash.width) + "px; "
        html += u"float:%s;\">\n" % self.idevice.float
        html += u"<div class=\"flash\">\n"
        html += self.flashMovieElement.renderView()
        html += u"<br/>" + self.idevice.caption + "</div>"
        html += u"</div>\n"
        html += self.textElement.renderView()
        html += u"<div style=\"clear:both;\">"
        html += u"</div>\n"
        html += u"</div><br/>\n"
        return html
Beispiel #23
0
class NotaBlock(Block):
    def __init__(self, parent, idevice):
        """
        Initialize a new Block object
        """
        Block.__init__(self, parent, idevice)
        self.commentInstruc = idevice.commentInstruc

        if idevice.commentTextArea.idevice is None:
            idevice.commentTextArea.idevice = idevice

        self.commentElement = TextAreaElement(idevice.commentTextArea)

        self.previewing = False  # In view or preview render

        if not hasattr(self.idevice, 'undo'):
            self.idevice.undo = True

    def process(self, request):
        """
        Process the request arguments from the web server
        """
        Block.process(self, request)

        is_cancel = common.requestHasCancel(request)

        if not is_cancel:
            self.commentElement.process(request)
            if "title" + self.id in request.args:
                self.idevice.title = request.args["title" + self.id][0]

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        html = "<div class=\"iDevice\"><br/>\n"
        html += common.textInput("title" + self.id, self.idevice.title)
        html += self.commentElement.renderEdit()
        html += "<br/>" + self.renderEditButtons()
        html += "</div>\n"
        return html

    def renderPreview(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """

        self.previewing = True
        return self.renderNote()

    def renderView(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """
        self.previewing = False
        return self.renderNote()

    def renderNote(self):
        """
        Returns an XHTML string for this block
        """
        html = u'<div class="classnote">\n'
        if self.commentElement.field.content:
            html += '<div class="notetitleex" onclick="jQuery(\'#fb%s\').toggle()" title="%s">' % (
                self.id, _(u"Show/Hide"))
        else:
            html += '<div class="notetitle">'
        html += '%s</div>' % self.idevice.title
        if self.commentElement.field.content:
            html += '<div id="fb%s" class="notearea">' % self.id

            if self.previewing:
                html += self.commentElement.renderPreview()
            else:
                html += self.commentElement.renderView()

            html += "</div>\n"
        if self.previewing:
            html += Block.renderViewButtons(self)
            html += "<a title=\"" + _(
                u"Delete all notes"
            ) + "\" href=\"#\" onclick=\"confirmThenSubmitLink('" + _(
                u"Would you delete all notes?"
            ) + "', '" + u'deleteallnotes' + "', '" + self.id + "', 1);\" style=\"float:right;margin-top:-20px;\"><img alt=\"" + _(
                u"Delete all notes"
            ) + "\" width=\"16\" height=\"16\" class=\"submit\" src=\"/images/stock-delete.png\"></a>"
        html += "</div>\n"

        return html
class DestacadofpdBlock(Block):
    def __init__(self, parent, idevice):
        """
        Initialize a new Block object
        """
        Block.__init__(self, parent, idevice)
        self.activityInstruc = idevice.activityInstruc

        # to compensate for the strange unpickling timing when objects are
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.activityTextArea.idevice is None:
            idevice.activityTextArea.idevice = idevice

        self.activityElement = TextAreaElement(idevice.activityTextArea)

        self.previewing = False  # In view or preview render

        if not hasattr(self.idevice, 'undo'):
            self.idevice.undo = True

    def process(self, request):
        """
        Process the request arguments from the web server
        """
        Block.process(self, request)

        is_cancel = common.requestHasCancel(request)

        if not is_cancel:
            self.activityElement.process(request)
            if "title" + self.id in request.args:
                self.idevice.title = request.args["title" + self.id][0]

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        html = "<div class=\"iDevice\"><br/>\n"
        #        html += common.textInput("title"+self.id, "Destacado")
        html += self.activityElement.renderEdit()
        html += "<br/>" + self.renderEditButtons()
        html += "</div>\n"
        return html

    def renderPreview(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """
        self.previewing = True
        return Block.renderPreview(self, style)

    def renderView(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """
        self.previewing = False
        return Block.renderView(self, style)

    def renderViewContent(self):
        """
        Returns an XHTML string for this block
        """
        #        html  = u'<script type="text/javascript" src="common.js"></script>\n'
        #        html += u'<div class="iDevice_destacadofpd">\n'
        html = u'<div class="iDevice_destacadofpd">\n'

        if self.previewing:
            html += self.activityElement.renderPreview()
        else:
            html += self.activityElement.renderView()

        html += "</div>\n"
        return html
Beispiel #25
0
class QuestionElement(object):
    """
    QuestionElement is responsible for a block of question. 
    Used by MultichoiceBlock CasestudyBlock.
    """

    def __init__(self, index, idevice, question):
        """
        Initialize
        'index' is our number in the list of questions
        'idevice' is a case study idevice
        'question' is a exe.engine.casestudyidevice.Question instance
        """
        self.index        = index
        self.id           = "q" + unicode(index) + "b" + idevice.id        
        self.idevice      = idevice


        self.quesId       = "quesQuestion" + unicode(index) + "b" + idevice.id
        self.feedbackId   = "quesFeedback" + unicode(index) + "b" + idevice.id

        self.question     = question
        # also split out each part for a separate TextAreaElement:

        # but first....  
        # to compensate for the strange unpickling timing when objects are 
        # loaded from an elp, ensure that proper idevices are set: 
        if question.questionTextArea.idevice is None: 
            question.questionTextArea.idevice = idevice 
        if question.feedbackTextArea.idevice is None: 
            question.feedbackTextArea.idevice = idevice

        self.question_question = TextAreaElement(question.questionTextArea)
        self.question_question.id = self.quesId 
        self.question_feedback = TextAreaElement(question.feedbackTextArea)
        self.question_feedback.id = self.feedbackId 

    def process(self, request):
        """
        Process arguments from the web server.  Return any which apply to this
        element.
        """
        log.debug("process " + repr(request.args))
        
        if self.quesId in request.args:
            self.question_question.process(request)
                        
        if self.feedbackId in request.args:
            self.question_feedback.process(request)

        if "action" in request.args and request.args["action"][0] == self.id:
            # before deleting the question object, remove any internal anchors:
            for q_field in self.question.getRichTextFields():
                 q_field.ReplaceAllInternalAnchorsLinks()  
                 q_field.RemoveAllInternalLinks()  
            self.idevice.questions.remove(self.question)
            # disable Undo once an activity has been deleted:
            self.idevice.undo = False


    def renderEdit(self):
        """
        Returns an XHTML string for editing this question element
        """

        html  = "<tr><td><b>%s</b>\n" % _("Activity")
        html += common.elementInstruc(self.idevice.questionInstruc)
        html += self.question_question.renderEdit()

        html += "<b>%s</b>\n" % _("Feedback")
        html += common.elementInstruc(self.idevice.feedbackInstruc)
        html += self.question_feedback.renderEdit()

        html += "</td><td>\n"
        html += common.submitImage(self.id, self.idevice.id, 
                                   "/images/stock-cancel.png",
                                   _("Delete question"))
        html += "</td></tr>\n"
        return html

    def doRender(self, preview=False):
        """
        Returns an XHTML string for viewing and previewing this question element
        depending on the value of 'preview'.
        """
        if preview: 
            html  = self.question_question.renderPreview()
        else:
            html  = self.question_question.renderView()

        if  self.question_feedback.field.content.strip() != "" :
            if preview: 
                feedback = self.question_feedback.renderPreview() 
            else: 
                feedback = self.question_feedback.renderView()
            html += common.feedbackBlock(self.id,feedback)
        
        return html

    def renderView(self):
        """
        Returns an XHTML string for viewing this question element
        """
        html = "<div class=\"question\">\n"
        html += self.doRender(preview=False)
        html += "</div>\n"
        return html
    
    def renderPreview(self):
        """
        Returns an XHTML string for previewing this question element
        """
        return self.doRender(preview=True)
Beispiel #26
0
class DebesconocerfpdBlock(Block):
    def __init__(self, parent, idevice):
        """
        Initialize a new Block object
        """
        Block.__init__(self, parent, idevice)
        self.activityInstruc = idevice.activityInstruc

        # to compensate for the strange unpickling timing when objects are
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.activityTextArea.idevice is None:
            idevice.activityTextArea.idevice = idevice

        self.activityElement = TextAreaElement(idevice.activityTextArea)

        self.previewing = False  # In view or preview render

        if not hasattr(self.idevice, 'undo'):
            self.idevice.undo = True

    def process(self, request):
        """
        Process the request arguments from the web server
        """
        Block.process(self, request)

        is_cancel = common.requestHasCancel(request)

        if not is_cancel:
            self.activityElement.process(request)
            if "title" + self.id in request.args:
                self.idevice.title = request.args["title" + self.id][0]

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        html = "<div class=\"iDevice\"><br/>\n"

        # JRJ
        # Quitamos el prefijo "FPD -"
        # (let's remove the "FPD -" prefix)
        if self.idevice.title.find("FPD - ") == 0:
            self.idevice.title = x_(u"You Should Know")

        html += common.textInput("title" + self.id, self.idevice.title)
        html += self.activityElement.renderEdit()
        html += "<br/>" + self.renderEditButtons()
        html += "</div>\n"
        return html

    def renderPreview(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """
        self.previewing = True
        return Block.renderPreview(self, style)

    def renderView(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """
        self.previewing = False
        return Block.renderView(self, style)

    def renderViewContent(self):
        """
        Returns an XHTML string for this block
        """

        if self.previewing:
            html = self.activityElement.renderPreview()
        else:
            html = self.activityElement.renderView()

        return html
Beispiel #27
0
class ClozeBlock(Block):
    """
    Renders a paragraph where the content creator can choose which words the
    student must fill in.
    """
    def __init__(self, parent, idevice):
        """
        Pre-create our field ids
        """
        Block.__init__(self, parent, idevice)
        self.instructionElement = \
            TextAreaElement(idevice.instructionsForLearners)
        self.clozeElement = ClozeElement(idevice.content)
        self.feedbackElement = \
            TextAreaElement(idevice.feedback)
    def process(self, request):
        """
        Handles changes in the paragraph text from editing
        """
        if "title"+self.id in request.args:
            self.idevice.title = request.args["title"+self.id][0]
        object = request.args.get('object', [''])[0]
        action = request.args.get('action', [''])[0]
        self.instructionElement.process(request)
        if object == self.id:
            self.clozeElement.process(request)
        self.feedbackElement.process(request)
        Block.process(self, request)
    def renderEdit(self, style):
        """
        Renders a screen that allows the user to enter paragraph text and choose
        which words are hidden.
        """
        html = [
            u'<div class="iDevice">',
            u'<div class="block">',
            common.textInput("title"+self.id, self.idevice.title),
            u'</div>',
            self.instructionElement.renderEdit(),
            self.clozeElement.renderEdit(),
            self.feedbackElement.renderEdit(),
            self.renderEditButtons(),
            u'</div>'
            ]
        return u'\n    '.join(html)
    def renderViewContent(self):
        """
        Returns an XHTML string for this block
        """
        if self.feedbackElement.field.content:
            clozeContent = self.clozeElement.renderView(self.feedbackElement.id)
        else:
            clozeContent = self.clozeElement.renderView()
        html = [
            u'<script type="text/javascript" src="common.js"></script>\n',
            u'<div class="iDevice_inner">\n',
            self.instructionElement.renderView(),
            clozeContent]
        if self.feedbackElement.field.content:
            html.append(self.feedbackElement.renderView(False, class_="feedback"))
        html += [
            u'</div>\n',
            ]
        return u'\n    '.join(html)
class WikipediaBlock(Block):
    """
    WikipediaBlock can render and process WikipediaIdevices as XHTML
    """

    def __init__(self, parent, idevice):
        """
        Initialize
        """
        Block.__init__(self, parent, idevice)

        # to compensate for the strange unpickling timing when objects are
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.article.idevice is None:
            idevice.article.idevice = idevice
        self.articleElement = TextAreaElement(idevice.article)
        self.articleElement.height = 300
        if not hasattr(self.idevice, "undo"):
            self.idevice.undo = True

    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        log.debug("process " + repr(request.args))

        is_cancel = common.requestHasCancel(request)

        if "emphasis" + self.id in request.args and not is_cancel:
            self.idevice.emphasis = int(request.args["emphasis" + self.id][0])
            # disable Undo once an emphasis has changed:
            self.idevice.undo = False

        if "ssite" + self.id in request.args and not is_cancel:
            self.idevice.site = request.args["ssite" + self.id][0]

        if "ownUrl" + self.id in request.args and not is_cancel:
            self.idevice.ownUrl = request.args["ownUrl" + self.id][0]

        if "title" + self.id in request.args and not is_cancel:
            self.idevice.title = request.args["title" + self.id][0]

        if "object" in request.args and request.args["object"][0] == "site" + self.id:
            pass
        elif "loadWikipedia" + self.id in request.args:
            # If they've hit "load" instead of "the tick"
            self.idevice.loadArticle(request.args["article"][0])
            # disable Undo once an article has been loaded:
            self.idevice.undo = False
        else:
            # If they hit "the tick" instead of "load"
            Block.process(self, request)
            if u"action" not in request.args or request.args[u"action"][0] != u"delete":
                # If the text has been changed
                self.articleElement.process(request)
            if "action" in request.args and request.args["action"][0] == "done":
                # remove the undo flag in order to reenable it next time:
                if hasattr(self.idevice, "undo"):
                    del self.idevice.undo

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form elements for editing this block
        """
        log.debug("renderEdit")

        html = u'<div class="iDevice"><br/>\n'
        html += common.textInput("title" + self.id, self.idevice.title) + "<br/><br/>"

        sites = [
            (_(u"English Wikipedia Article"), "http://en.wikipedia.org/wiki/"),
            (_(u"Catalan Wikipedia Article"), "http://ca.wikipedia.org/wiki/"),
            (_(u"Chinese Wikipedia Article"), "http://zh.wikipedia.org/wiki/"),
            (_(u"Dutch Wikipedia Article"), "http://nl.wikipedia.org/wiki/"),
            (_(u"French Wikipedia Article"), "http://fr.wikipedia.org/wiki/"),
            (_(u"German Wikipedia Article"), "http://de.wikipedia.org/wiki/"),
            (_(u"Greek Wikipedia Article"), "http://el.wikipedia.org/wiki/"),
            (_(u"Italian Wikipedia Article"), "http://it.wikipedia.org/wiki/"),
            (_(u"Japanese Wikipedia Article"), "http://ja.wikipedia.org/wiki/"),
            (_(u"Magyar Wikipedia Article"), "http://hu.wikipedia.org/wiki/"),
            (_(u"Polish Wikipedia Article"), "http://pl.wikipedia.org/wiki/"),
            (_(u"Portugese Wikipedia Article"), "http://pt.wikipedia.org/wiki/"),
            (_(u"Slovenian Wikipedia Article"), "http://sl.wikipedia.org/wiki/"),
            (_(u"Spanish Wikipedia Article"), "http://es.wikipedia.org/wiki/"),
            (_(u"Swedish Wikipedia Article"), "http://sv.wikipedia.org/wiki/"),
            (_(u"Wikibooks Article"), "http://en.wikibooks.org/wiki/"),
            (_(u"Wikiversity"), "http://en.wikiversity.org/wiki/"),
            (_(u"Wiktionary"), "http://en.wiktionary.org/wiki/"),
            (_(u"Wikieducator Content"), "http://wikieducator.org/"),
            (_(u"Other"), ""),
        ]

        this_package = None
        if self.idevice is not None and self.idevice.parentNode is not None:
            this_package = self.idevice.parentNode.package
        html += common.formField(
            "select", this_package, _("Site"), "s", "site" + self.id, self.idevice.langInstruc, sites, self.idevice.site
        )

        url = "none"
        if self.idevice.site == "":
            url = "block"
        html += '<div style="display:%s"> %s: <br/>' % (url, _("Own site"))
        html += common.textInput("ownUrl" + self.id, self.idevice.ownUrl) + "<br/></div>"
        html += "<br/>"
        html += common.textInput("article", self.idevice.articleName)
        html += common.elementInstruc(self.idevice.searchInstruc)
        html += common.submitButton(u"loadWikipedia" + self.id, _(u"Load"))

        html += u"<br/>\n"
        html += self.articleElement.renderEdit()
        emphasisValues = [(_(u"No emphasis"), Idevice.NoEmphasis), (_(u"Some emphasis"), Idevice.SomeEmphasis)]

        html += common.formField(
            "select",
            this_package,
            _("Emphasis"),
            "emphasis",
            self.id,
            "",  # TODO: Instructions
            emphasisValues,
            self.idevice.emphasis,
        )

        html += self.renderEditButtons(undo=self.idevice.undo)
        html += u"</div>\n"
        return html

    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        log.debug("renderPreview")
        html = u'<div class="iDevice '
        html += u"emphasis" + unicode(self.idevice.emphasis) + '" '
        html += u"ondblclick=\"submitLink('edit'," + self.id + ', 0);">\n'
        if self.idevice.emphasis != Idevice.NoEmphasis:
            if self.idevice.icon:
                html += u'<img alt="idevice icon" class="iDevice_icon" '
                html += u' src="/style/' + style
                html += "/icon_" + self.idevice.icon + '.gif"/>\n'
            html += u'<span class="iDeviceTitle">'
            html += self.idevice.title
            html += u"</span>\n"
            html += u'<div class="iDevice_inner">\n'
        html += self.articleElement.renderPreview()
        html += u"<br/>\n"
        html += u"This article is licensed under the "
        html += u'<span style="text-decoration: underline;">'
        html += u"GNU Free Documentation License</span>. It uses material "
        html += u'from the <span style="text-decoration: underline;">article '
        html += u'"%s"</span>.<br/>\n' % self.idevice.articleName
        html += self.renderViewButtons()
        if self.idevice.emphasis != Idevice.NoEmphasis:
            html += u"</div></div>\n"
        else:
            html += u"</div>\n"
        return html

    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        log.debug("renderView")
        content = self.articleElement.renderView()
        content = re.sub(r'src="resources/', 'src="', content)
        html = u'<div class="iDevice '
        html += u"emphasis" + unicode(self.idevice.emphasis) + '">\n'

        html += u'<div class="wiki_site" value="' + self.idevice.site + '"></div>'
        html += u'<div class="article_name" value="' + self.idevice.articleName + '"></div>'
        html += u'<div class="own_url" value="' + self.idevice.ownUrl + '"></div>\n'

        if self.idevice.emphasis != Idevice.NoEmphasis:
            if self.idevice.icon:
                html += u'<img alt="iDevice icon" class="iDevice_icon" '
                html += u' src="icon_' + self.idevice.icon + '.gif"/>\n'
            html += u'<span class="iDeviceTitle">'
            html += self.idevice.title
            html += u"</span>\n"
            html += u'<div class="iDevice_inner">\n'
        html += content
        html += u"<br/>\n"
        html += _(u"This article is licensed under the ")
        html += u"<a "
        html += u"href=\"javascript:window.open('fdl.html')\">"
        html += u"%s</a>. " % _(u"GNU Free Documentation License")
        html += _(u"It uses material from the ")
        # UGLY UGLY UGLY KLUDGE for Wayne
        # "BIG please - Will you check that the Wikieducator url is changed for
        # the next release - not sure if we'll get the image thing sorted, but
        # this is pretty important strategically re the international growth of
        # eXe.  Not a new feature <smile> just a small change to a string."
        if self.idevice.site == u"http://wikieducator.org/":
            html += u'<a href="' + self.idevice.site
        else:
            html += u'<a href="' + self.idevice.site + u"wiki/"
        html += self.idevice.articleName + u'">'
        html += _(u"article ")
        html += u'"' + self.idevice.articleName + u'"</a>.<br/>\n'
        if self.idevice.emphasis != Idevice.NoEmphasis:
            html += u"</div></div>\n"
        else:
            html += u"</div>\n"
        return html
Beispiel #29
0
class AttachmentBlock(Block):
    """
    AttachmentBlock can render and process AttachmentIdevices as XHTML
    """
    def __init__(self, parent, idevice):
        """
        Initialize
        """

        Block.__init__(self, parent, idevice)

        # to compensate for the strange unpickling timing when objects are
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.descriptionTextArea.idevice is None:
            idevice.descriptionTextArea.idevice = idevice

        self.descriptionElement = TextAreaElement(idevice.descriptionTextArea)

    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        log.debug("process " + repr(request.args))
        Block.process(self, request)

        if (u"action" not in request.args
                or request.args[u"action"][0] != u"delete"):
            if u"label" + self.id in request.args:
                self.idevice.label = request.args[u"label" + self.id][0]

            self.descriptionElement.process(request)

            if "path" + self.id in request.args:
                attachmentPath = request.args["path" + self.id][0]

                if attachmentPath:
                    self.idevice.setAttachment(attachmentPath)

                if self.idevice.label == "":
                    self.idevice.label = os.path.basename(attachmentPath)

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form elements for editing this block
        """
        log.debug("renderEdit")
        html = u'<div class="iDevice">\n'
        html += u'<div class="block">\n'

        label = _(u'Filename:')
        if self.idevice.userResources:
            label += u': '
            label += u'<span style="text-decoration:underline">'
            label += self.idevice.userResources[0].storageName
            label += u'</span>\n'
        html += u'<div>'
        this_package = None
        if self.idevice is not None and self.idevice.parentNode is not None:
            this_package = self.idevice.parentNode.package
        html += common.formField('textInput',
                                 this_package,
                                 label,
                                 'path' + self.id,
                                 '',
                                 self.idevice.filenameInstruc,
                                 size=40)
        html += u'<input type="button" onclick="addFile(\'%s\')"' % self.id
        html += u' value="%s" />\n' % _(u"Select a file")
        html += u'</div><br style="clear:both;" />'
        html += u'</div>\n'
        html += u'<div class="block">\n'
        html += u'\n<b>%s</b>\n' % _(u'Label:')
        html += common.elementInstruc(self.idevice.labelInstruc)
        html += u'</div>\n'
        html += common.textInput(u'label' + self.id, self.idevice.label)
        html += self.descriptionElement.renderEdit()
        html += u'<div class="block">\n'
        html += self.renderEditButtons()
        html += u'</div>\n'
        html += u'\n</div>\n'

        return html

    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        log.debug("renderPreview")
        html = u"<div class=\"iDevice "
        html += u"emphasis" + unicode(self.idevice.emphasis) + "\" "
        html += u"ondblclick=\"submitLink('edit'," + self.id + ", 0);\">\n"

        if self.idevice.userResources:
            html += u"<img src='/images/stock-attach.png'> <a style=\"cursor: pointer;\" "
            html += u" onclick=\"browseURL('"
            html += u"%s/" % (G.application.exeAppUri)
            html += self.package.name
            html += u"/resources/"
            html += self.idevice.userResources[0].storageName
            html += u"');\" >"
            html += self.idevice.label
            html += u"</a>\n"

        html += u'<div class="block">\n'
        html += self.descriptionElement.renderPreview()
        html += u"</div>\n"
        html += self.renderViewButtons()
        html += u"</div>\n"

        return html

    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        log.debug("renderView")
        html = u"<!-- attachment iDevice -->\n"
        html += u"<div class=\"iDevice "
        html += u"emphasis" + unicode(self.idevice.emphasis) + "\">\n"

        if self.idevice.userResources:
            html += u"<img src='stock-attach.png'> "
            html += u"<a href=\"#\" onclick=\"window.open('"
            html += self.idevice.userResources[0].storageName
            html += u"', '_blank');\" >"
            html += self.idevice.label
            html += u"</a> \n"

        html += u'<div class="block">\n'
        html += self.descriptionElement.renderView()
        html += u"</div>"
        html += u"</div>\n"

        return html
Beispiel #30
0
class FlashWithTextBlock(Block):
    """
    FlashWithTextBlock can render and process FlashWithTextIdevices as XHTML
    """

    name = 'flashWithText'

    def __init__(self, parent, idevice):
        """
        Initialize
        """
        Block.__init__(self, parent, idevice)
        self.flashElement = FlashElement(idevice.flash)

        # to compensate for the strange unpickling timing when objects are
        # loaded from an elp, ensure that proper idevices are set:
        # (only applies to the image-embeddable ones, not FlashElement)
        if idevice.text.idevice is None:
            idevice.text.idevice = idevice
        self.textElement = TextAreaElement(idevice.text)

    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        log.debug("process " + repr(request.args))
        Block.process(self, request)

        if (u"action" not in request.args
                or request.args[u"action"][0] != u"delete"):
            self.flashElement.process(request)
            self.textElement.process(request)

        if "float" + self.id in request.args:
            self.idevice.float = request.args["float" + self.id][0]

        if "caption" + self.id in request.args:
            self.idevice.caption = request.args["caption" + self.id][0]

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form elements for editing this block
        """
        log.debug("renderEdit")
        html = u"<div class=\"iDevice\">\n"
        html += self.flashElement.renderEdit()
        floatArr = [[_(u'Left'), 'left'], [_(u'Right'), 'right'],
                    [_(u'None'), 'none']]

        this_package = None
        if self.idevice is not None and self.idevice.parentNode is not None:
            this_package = self.idevice.parentNode.package
        html += common.formField('select',
                                 this_package,
                                 _("Align:"),
                                 "float" + self.id,
                                 options=floatArr,
                                 selection=self.idevice.float)
        html += u"\n"
        html += u"<b>%s </b>" % _(u"Caption:")
        html += common.textInput("caption" + self.id, self.idevice.caption)
        html += common.elementInstruc(self.idevice.captionInstruc)
        html += "<br/>" + self.textElement.renderEdit()
        html += self.renderEditButtons()
        html += u"</div>\n"
        return html

    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        log.debug("renderPreview")
        html = u"\n<!-- flash with text iDevice -->\n"
        html = u"<div class=\"iDevice "
        html += u"emphasis" + unicode(self.idevice.emphasis) + "\" "
        html += "ondblclick=\"submitLink('edit'," + self.id + ", 0);\">\n"
        html += u"<div class=\"flash_text\" style=\""
        html += u"width:" + str(self.idevice.flash.width) + "px; "
        html += u"float:%s;\">\n" % self.idevice.float
        html += u"<div class=\"flash\">\n"
        html += self.flashElement.renderPreview()
        html += u"" + self.idevice.caption + "</div>"
        html += u"</div>\n"
        html += self.textElement.renderPreview()
        html += u"<br/>\n"
        html += u"<div style=\"clear:both;\">"
        html += u"</div>\n"
        html += self.renderViewButtons()
        html += u"</div>\n"
        return html

    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        log.debug("renderView")
        html = u"\n<!-- Flash with text iDevice -->\n"
        html += u"<div class=\"iDevice "
        html += u"emphasis" + unicode(self.idevice.emphasis) + "\">\n"
        html += u"<div class=\"flash_text\" style=\""
        html += u"width:" + str(self.idevice.flash.width) + "px; "
        html += u"float:%s;\">\n" % self.idevice.float
        html += u"<div class=\"flash\">\n"
        html += self.flashElement.renderView()
        html += u"<br/>" + self.idevice.caption + "</div>"
        html += u"</div>\n"
        html += self.textElement.renderView()
        html += u"<div style=\"clear:both;\">"
        html += u"</div>\n"
        html += u"</div><br/>\n"
        return html
Beispiel #31
0
class ListaBlock(Block):
    """

    """
    def __init__(self, parent, idevice):
        """
        Pre-create our field ids
        """
        Block.__init__(self, parent, idevice)
        
       
        # to compensate for the strange unpickling timing when objects are 
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.instructionsForLearners.idevice is None: 
            idevice.instructionsForLearners.idevice = idevice
        if idevice.content.idevice is None: 
            idevice.content.idevice = idevice
        if idevice.feedback.idevice is None: 
            idevice.feedback.idevice = idevice
            
        dT = common.getExportDocType()
        sectionTag = "div"
        if dT == "HTML5":
            sectionTag = "section"
            
        idevice.instructionsForLearners.htmlTag = sectionTag
        idevice.instructionsForLearners.class_ = "block instructions"
        idevice.feedback.htmlTag = sectionTag            

        self.instructionElement = TextAreaElement(idevice.instructionsForLearners)
        self.instructionElement.field.content_w_resourcePaths = c_(self.instructionElement.field.content_w_resourcePaths)
        self.listaElement = ListaElement(idevice.content)
        self.feedbackElement = \
            TextAreaElement(idevice.feedback)
        self.previewing        = False # In view or preview render
        if not hasattr(self.idevice,'undo'): 
            self.idevice.undo = True

    def process(self, request):
        """
        Handles changes in the paragraph text from editing
        """
        is_cancel = common.requestHasCancel(request)

        if "title"+self.id in request.args \
        and not is_cancel:
            self.idevice.title = request.args["title"+self.id][0]
        object = request.args.get('object', [''])[0]
        action = request.args.get('action', [''])[0]
        self.instructionElement.process(request)
        self.listaElement.process(request)
        self.feedbackElement.process(request)
        Block.process(self, request)

    def renderEdit(self, style):
        """
        Renders a screen that allows the user to enter paragraph text and choose
        which words are hidden.
        """
        html = [
            u'<div class="iDevice">',
            u'<div class="block">',
            common.textInput("title"+self.id, self.idevice.title),
            u'</div>',
            self.instructionElement.renderEdit(),
            self.listaElement.renderEdit(),
            self.feedbackElement.renderEdit(),
            self.renderEditButtons(),
            u'</div>'
            ]
        return u'\n    '.join(html)
    
    def renderPreview(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """ 
        self.previewing = True 
        return Block.renderPreview(self, style)

    def renderView(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """ 
        self.previewing = False 
        return Block.renderView(self, style)

    def renderViewContent(self):
        """
        Returns an XHTML string for this block
        """
        # Only show feedback button if feedback is present
        if self.feedbackElement.field.content.strip():
            # Lista Idevice needs id of div for feedback content
            feedbackID = self.feedbackElement.id
            if self.previewing: 
                clozeContent = self.listaElement.renderPreview(feedbackID)
            else: 
                clozeContent = self.listaElement.renderView(feedbackID)
        else:
            if self.previewing: 
                clozeContent = self.listaElement.renderPreview()
            else:
                clozeContent = self.listaElement.renderView()
        instruction_html = ""
        if self.previewing: 
            instruction_html = self.instructionElement.renderPreview()
        else:
            instruction_html = self.instructionElement.renderView()
        html = [       
            instruction_html,
            clozeContent]
        if self.feedbackElement.field.content: 
            if self.previewing: 
                html.append(self.feedbackElement.renderPreview(False, 
                                                     class_="feedback"))
            else:
                html.append(self.feedbackElement.renderView(False, 
                                                     class_="feedback"))
        return u'\n'.join(html)

    def renderText(self): 
        
        """
        Returns an XHTML string for text file export.
        """
        
        if self.previewing: 
            html = '<p>' +  self.instructionElement.renderPreview() +'</p>'
        else:
            html = '<p>' +  self.instructionElement.renderView() +'</p>'
        html += '<p>' + self.listaElement.renderText() + '</p>'
        if self.feedbackElement.field.content:
            html += '<p>%s:</P>' % c_(u"Feedback") 
            if self.previewing: 
                html += '<p>' +self.feedbackElement.renderPreview(False, 
                                                        class_="feedback") 
                html += '</p>'
            else:
                html += '<p>' +self.feedbackElement.renderView(False, 
                                                        class_="feedback") 
                html += '</p>'
        html += self.listaElement.renderAnswers()
        return html
class EjercicioresueltofpdBlock(Block):
    """
    FPD - CasestudyBlock can render and process CasestudyIdevices as XHTML
    """
    def __init__(self, parent, idevice):
        """
        Initialize a new Block object
        """
        Block.__init__(self, parent, idevice)
        self.idevice           = idevice
        self.questionElements  = []

        # to compensate for the strange unpickling timing when objects are 
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.storyTextArea.idevice is None: 
            idevice.storyTextArea.idevice = idevice
            
        dT = common.getExportDocType()
        sectionTag = "div"
        if dT == "HTML5":
            sectionTag = "section"
            
        idevice.storyTextArea.htmlTag = sectionTag
        idevice.storyTextArea.class_ = "block story"

        self.storyElement      = TextAreaElement(idevice.storyTextArea)

        self.questionInstruc   = idevice.questionInstruc
        self.storyInstruc      = idevice.storyInstruc
        self.feedbackInstruc   = idevice.feedbackInstruc
        self.previewing        = False # In view or preview render 

        if not hasattr(self.idevice,'undo'): 
            self.idevice.undo = True

        i = 0
        
        for question in idevice.questions:
            self.questionElements.append(QuestionElement(i, idevice, question))
            i += 1


    def process(self, request):
        """
        Process the request arguments from the web server
        """
        Block.process(self, request)

        is_cancel = common.requestHasCancel(request)

        self.storyElement.process(request)
            
        if (u"addQuestion"+unicode(self.id)) in request.args: 
            self.idevice.addQuestion()
            self.idevice.edit = True
            # disable Undo once another activity has been added:
            self.idevice.undo = False

            
        if "title"+self.id in request.args \
        and not is_cancel:
            self.idevice.title = request.args["title"+self.id][0]
            
        if "action" in request.args and request.args[u"action"][0] != u"delete":
            for element in self.questionElements:
                element.process(request)
            if request.args[u"action"][0] == u'done':
                # remove the undo flag in order to reenable it next time:
                if hasattr(self.idevice,'undo'): 
                    del self.idevice.undo


    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        self.previewing = True

        html  = u'<div class="iDevice"><br/>\n'

   # JRJ
	# Quitamos el prefijo "FPD -"
	# (let's remove the "FPD -" prefix)
	if self.idevice.title.find("FPD - ") == 0:
		self.idevice.title = x_(u"Translation")
        html += common.textInput("title"+self.id, self.idevice.title)
        html += self.storyElement.renderEdit()

        for element in self.questionElements:
            html += element.renderEdit() 
         
        html += u"</table>\n"
        value = _(u"Add another activity")    
        html += common.submitButton(u"addQuestion"+unicode(self.id), value)
        html += u"<br /><br />" + self.renderEditButtons(undo=self.idevice.undo)
        html += u"</div>\n"
        return html

    def renderView(self, style):
        """
        Remembers if we're previewing or not,
        then implicitly calls self.renderViewContent (via Block.renderView)
        """
        self.previewing = False
        return Block.renderView(self, style)
    
    def renderPreview(self, style):
        """
        Remembers if we're previewing or not,
        then implicitly calls self.renderViewContent (via Block.renderPreview)
        """
        self.previewing = True
        return Block.renderPreview(self, style)
    
    def renderViewContent(self):
        """
        Returns an XHTML string for this block
        """
        log.debug("renderViewContent called with previewing mode = " + str(self.previewing))

        html  = u""

        if self.previewing:
            html += self.storyElement.renderPreview()
            html + u"<br />\n"
            for element in self.questionElements:
                html += element.renderPreview()
        else:
            html += self.storyElement.renderView()
            html + u"<br />\n"
            for element in self.questionElements:
                html += element.renderView()

        return html
class FileAttachBlockInc(Block):
    """
    ExampleBlock can render and process ExampleIdevices as XHTML
    GenericBlock will replace it..... one day
    """
    def __init__(self, parent, idevice):
        Block.__init__(self, parent, idevice)
        self.fileAttachmentElements = []
        for fileField in self.idevice.fileAttachmentFields:
            fileElement = FileElement(fileField, False)
            self.fileAttachmentElements.append(fileElement)
        
        self.showDescBlock = ChoiceElement(idevice.showDesc)
        self.introHTMLElement = TextAreaElement(idevice.introHTML)
        

    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        Block.process(self, request)
        is_cancel = common.requestHasCancel(request)
        
        self.showDescBlock.process(request)
        self.introHTMLElement.process(request)
        
        showDesc = False
        if self.showDescBlock.renderView() == "yes":
            showDesc = True
        
        if showDesc == True:
            self.idevice.emphasis = Idevice.SomeEmphasis
        else:
            self.idevice.emphasis = Idevice.NoEmphasis
        
        for fileElement in self.fileAttachmentElements:
            fileElement.process(request)
            if field_engine_is_delete(fileElement, request, self.idevice.fileAttachmentFields):
                #fileElement.field.deleteFile()
                field_engine_check_delete(fileElement, request, self.idevice.fileAttachmentFields)
            
        if "addFileAttachment" + unicode(self.id) in request.args:
            self.idevice.addFileAttachmentField()            
            self.idevice.edit = True
            self.idevice.undo = False
            
        #check the title - lifted from genericblock
        if "title"+self.id in request.args \
        and not is_cancel:
            self.idevice.title = request.args["title"+self.id][0]

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        html  = _(u"<div>\n")
        html += _("<h2>File Attachment</h2>")
        html += _("<p>Here you can attach arbitary files to the package that will be included with the export</p>")
        html += _("<p>You can choose to display links or not below</p>")
        
        html += _("<strong>Title:</strong><br/>")
        html += common.textInput("title"+self.id, self.idevice.title)
        html += "<br/>"
        html += self.showDescBlock.renderEdit()
        html += self.introHTMLElement.renderEdit()
        
        
        for fileElement in self.fileAttachmentElements:
            html += fileElement.renderEdit()
            html += "<hr/>"
        
        html += "<br/>"    
        html += common.submitButton("addFileAttachment"+unicode(self.id), _("Add Another File Attachment"))
        html += "<br/>"
        html += self.renderEditButtons()
        html += u"</div>\n"
        return html


    def _renderMain(self, style, previewMode = False):
        """Decoration """
        showDesc = False
        if self.showDescBlock.renderView() == "yes":
            showDesc = True
        
        html = u""
        viewMode = "view"
        if previewMode == True:
            viewMode = "preview"
        
        
        if showDesc == True:
            html = common.ideviceHeader(self, style, viewMode)
            if previewMode == True:
                html += self.introHTMLElement.renderPreview()
            else:
                html += self.introHTMLElement.renderView()
            
            html += "<ul class='exeFileList'>"    
        
        prefix = ""
        if previewMode == True:
            prefix = "resources/" 
        

        if showDesc == False and previewMode == True:
            html += "<strong> " + _("File List (this list shows only in preview mode):") + "</strong><br/>"
        
                    
        for fileElement in self.fileAttachmentElements:
            if showDesc == False:
                if previewMode == True:
                    html += fileElement.renderPreview()
                else:
                    html += fileElement.renderView()
                
                html += "<br/>"
            else:
                link_filename = urllib2.quote(fileElement.getFileName())
                html += "<li><a href='%(prefix)s%(filename)s' target='_blank'>%(desc)s" % \
                    {"filename" : link_filename, "desc" : fileElement.getDescription(),\
                     "prefix" : prefix}
                html += "<span> (" + c_('New Window')+")</span></a></li>\n"
                
        if showDesc == True:
            html += "</ul>"
        
        
        if showDesc == True:
            """End decoration"""
            html += common.ideviceFooter(self, style, viewMode)
        elif showDesc == False and previewMode == True:
            html += self.renderViewButtons()
        
        return html

    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        
        html = self._renderMain(style, True)
        
        #end of idevice
        
        
        
        
        return html


    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        html = self._renderMain(style, False)
        
        
        return html
Beispiel #34
0
class TestoptionElement(object):
    """
    TestOptionElement is responsible for a block of option.  Used by
    TestquestionElement.  
    == SCORM Quiz Testoption, 
    pretty much the same as MultiSelect's SelectoptionElement,
    but with enough subtle variations that you'd better pay attention :-)
    """
    def __init__(self, index, question, questionId, option, idevice):
        """
        Initialize
        """
        self.index = index
        self.id = unicode(index) + "q" + questionId
        self.question = question
        self.questionId = questionId
        self.option = option
        self.answerId = "optionAnswer" + unicode(index) + "q" + questionId
        self.keyId = "key" + questionId
        self.idevice = idevice
        self.checked = False

        # to compensate for the strange unpickling timing when objects are
        # loaded from an elp, ensure that proper idevices are set:
        # (only applies to the image-embeddable ones, not FlashElement)
        if option.answerTextArea.idevice is None:
            option.answerTextArea.idevice = idevice
        self.answerElement = TextAreaElement(option.answerTextArea)
        self.answerElement.id = self.answerId

        if not hasattr(self.idevice, 'undo'):
            self.idevice.undo = True

    def process(self, request):
        """
        Process arguments from the web server.  Return any which apply to this 
        element.
        """
        log.debug("process " + repr(request.args))

        is_cancel = common.requestHasCancel(request)

        if self.answerId in request.args \
        and not is_cancel:
            self.answerElement.process(request)

        if "c"+self.keyId in request.args \
        and not is_cancel:
            if request.args["c" + self.keyId][0] == self.id:
                self.option.isCorrect = True
                self.question.correctAns = self.index
                log.debug("option " + repr(self.option.isCorrect))
            else:
                self.option.isCorrect = False

        if self.keyId in request.args \
        and not is_cancel:
            if request.args[self.keyId][0] == unicode(self.index):
                self.question.userAns = self.index

        if "action" in request.args and request.args["action"][0] == self.id:
            # before deleting the option object, remove any internal anchors:
            for o_field in self.option.getRichTextFields():
                o_field.ReplaceAllInternalAnchorsLinks()
                o_field.RemoveAllInternalLinks()
            self.question.options.remove(self.option)
            # disable Undo once an option has been deleted:
            self.idevice.undo = False

    def renderEdit(self):
        """
        Returns an XHTML string for editing this option element
        """
        html = u"<tr><td align=\"left\"><b>%s</b>" % _("Option")
        html += common.elementInstruc(self.question.optionInstruc)

        header = ""
        if self.index == 0:
            header = _("Correct Option")

        html += u"</td><td align=\"right\"><b>%s</b>\n" % header
        html += u"</td><td>\n"
        if self.index == 0:
            html += common.elementInstruc(self.question.correctAnswerInstruc)
        html += "</td></tr><tr><td colspan=2>\n"

        # rather than using answerElement.renderEdit(),
        # access the appropriate content_w_resourcePaths attribute directly,
        # since this is in a customised output format
        # (in a table, with an extra delete-option X to the right)

        this_package = None
        if self.answerElement.field_idevice is not None \
        and self.answerElement.field_idevice.parentNode is not None:
            this_package = self.answerElement.field_idevice.parentNode.package

        html += common.richTextArea(
            self.answerId,
            self.answerElement.field.content_w_resourcePaths,
            package=this_package)

        html += "</td><td align=\"center\">\n"
        html += common.option("c" + self.keyId, self.option.isCorrect, self.id)
        html += "<br><br><br><br>\n"
        html += common.submitImage(self.id, self.idevice.id,
                                   "/images/stock-cancel.png",
                                   _(u"Delete option"))
        html += "</td></tr>\n"

        return html

    def renderPreview(self):
        """
        Returns an XHTML string for previewing this option element
        """
        return self.renderView(preview=True)

    def renderView(self, preview=False):
        """
        Returns an XHTML string for viewing this option element
        """
        log.debug("renderView called")

        lb = "\n"  #Line breaks
        dT = common.getExportDocType()
        sectionTag = "div"
        if dT == "HTML5":
            sectionTag = "section"

        html = '<' + sectionTag + ' class="iDevice_answer">' + lb

        # Checkbox
        fieldId = self.keyId + unicode((self.index + 1))
        html += '<p class="iDevice_answer-field js-required">' + lb
        html += '<label for="' + fieldId + '" class="sr-av"><a href="#answer-' + fieldId + '">' + c_(
            "Option") + ' ' + unicode((self.index + 1)) + '</a></label>'
        html += '<input type="radio" name="' + self.keyId + '" id="' + fieldId + '" value="' + unicode(
            self.index) + '" />'
        html += lb
        html += '</p>' + lb

        # Answer content
        html += '<div class="iDevice_answer-content" id="answer-' + fieldId + '">'
        if dT != "HTML5":
            html += '<a name="answer-' + fieldId + '"></a>'
        html += lb
        if preview:
            html += self.answerElement.renderPreview()
        else:
            html += self.answerElement.renderView()
        html += '</div>' + lb

        html += "</" + sectionTag + ">" + lb

        return html
Beispiel #35
0
class ClozefpdBlock(Block):
    """
    Renders a paragraph where the content creator can choose which words the
    student must fill in.
    """
    def __init__(self, parent, idevice):
        """
        Pre-create our field ids
        """
        Block.__init__(self, parent, idevice)

        # to compensate for the strange unpickling timing when objects are 
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.instructionsForLearners.idevice is None: 
            idevice.instructionsForLearners.idevice = idevice
        if idevice.content.idevice is None: 
            idevice.content.idevice = idevice
        if idevice.feedback.idevice is None: 
            idevice.feedback.idevice = idevice

        self.instructionElement = \
            TextAreaElement(idevice.instructionsForLearners)
        self.clozeElement = ClozeElement(idevice.content)
        self.feedbackElement = \
            TextAreaElement(idevice.feedback)
        self.previewing        = False # In view or preview render
        if not hasattr(self.idevice,'undo'): 
            self.idevice.undo = True

    def process(self, request):
        """
        Handles changes in the paragraph text from editing
        """
        is_cancel = common.requestHasCancel(request)

        if "title"+self.id in request.args \
        and not is_cancel:
            self.idevice.title = request.args["title"+self.id][0]
        object = request.args.get('object', [''])[0]
        action = request.args.get('action', [''])[0]
        self.instructionElement.process(request)
        self.clozeElement.process(request)
        self.feedbackElement.process(request)
        Block.process(self, request)

    def renderEdit(self, style):
        """
        Renders a screen that allows the user to enter paragraph text and choose
        which words are hidden.
        """
	"""        
	html = [
            u'<div class="iDevice">',
            u'<div class="block">',
#            common.textInput("title"+self.id, self.idevice.title),
            common.textInput("title"+self.id, "Autoevaluaci&oacute;n"),
            u'</div>',
            self.instructionElement.renderEdit(),
            self.clozeElement.renderEdit(),
            self.feedbackElement.renderEdit(),
            self.renderEditButtons(),
            u'</div>'
            ]
        return u'\n    '.join(html)"""
	html  = "<div class=\"iDevice\"><br/>\n"
	html  = "<div class=\"block\">"
	
	# JR
	# Quitamos el prefijo "FPD -"
	if self.idevice.title.find("FPD - ") == 0:
		self.idevice.title = x_(u"Autoevaluacion")

        html += common.textInput("title"+self.id, self.idevice.title)
	html += "</div>"
	html += self.instructionElement.renderEdit()
	html += self.clozeElement.renderEdit()
	html += self.feedbackElement.renderEdit()
	html += self.renderEditButtons()
	html += "</div>"
        return html
    
    def renderPreview(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """ 
        self.previewing = True 
        return Block.renderPreview(self, style)

    def renderView(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """ 
        self.previewing = False 
        return Block.renderView(self, style)

    def renderViewContent(self):
        """
        Returns an XHTML string for this block
        """
        # Only show feedback button if feedback is present
        if self.feedbackElement.field.content.strip():
            # Cloze Idevice needs id of div for feedback content
            feedbackID = self.feedbackElement.id
            if self.previewing: 
                clozeContent = self.clozeElement.renderPreview(feedbackID)
            else: 
                clozeContent = self.clozeElement.renderView(feedbackID)
        else:
            if self.previewing: 
                clozeContent = self.clozeElement.renderPreview()
            else:
                clozeContent = self.clozeElement.renderView()
        instruction_html = ""
        if self.previewing: 
            instruction_html = self.instructionElement.renderPreview()
        else:
            instruction_html = self.instructionElement.renderView()
        html = u'<script type="text/javascript" src="common.js"></script>\n'
        html += u'<div class="iDevice_inner">\n'
        html += instruction_html
        html += clozeContent
        if self.feedbackElement.field.content: 
            if self.previewing: 
                html += self.feedbackElement.renderPreview(False, class_="feedback")
            else:
                html += self.feedbackElement.renderView(False, class_="feedback")
        html += u'</div>\n'

#JR: Anadimos la etiqueta noscript
	if self.previewing:
		cloze = self.clozeElement.field.content_w_resourcePaths
		feedback = self.feedbackElement.field.content_w_resourcePaths
	else:
		cloze = self.clozeElement.field.content_w_resourcePaths
		feedback = self.feedbackElement.field.content_wo_resourcePaths
	html += u'<noscript><div class="feedback">\n'
	html += u"<strong>" + _("Solucion") + u": </strong><br/>\n"
	html += cloze
	if self.feedbackElement.field.content:
		html += u"<br/><br/><strong>" + _("Retroalimentacion") + ": </strong><br/>\n"
		html += feedback
	html += u"</div></noscript>"

	return html

    def renderText(self): 
        
        """
        Returns an XHTML string for text file export.
        """
        
        if self.previewing: 
            html = '<p>' +  self.instructionElement.renderPreview() +'</p>'
        else:
            html = '<p>' +  self.instructionElement.renderView() +'</p>'
        html += '<p>' + self.clozeElement.renderText() + '</p>'
        if self.feedbackElement.field.content:
            html += '<p>%s:</P>' % _(u"Feedback") 
            if self.previewing: 
                html += '<p>' +self.feedbackElement.renderPreview(False, 
                                                        class_="feedback") 
                html += '</p>'
            else:
                html += '<p>' +self.feedbackElement.renderView(False, 
                                                        class_="feedback") 
                html += '</p>'
        html += self.clozeElement.renderAnswers()
        return html
Beispiel #36
0
class CasestudyBlock(Block):
    """
    CasestudyBlock can render and process CasestudyIdevices as XHTML
    """
    def __init__(self, parent, idevice):
        """
        Initialize a new Block object
        """
        Block.__init__(self, parent, idevice)
        self.idevice           = idevice
        self.questionElements  = []
        if idevice.storyTextArea.idevice is None: 
            idevice.storyTextArea.idevice = idevice
        self.storyElement      = TextAreaElement(idevice.storyTextArea)
        self.questionInstruc   = idevice.questionInstruc
        self.storyInstruc      = idevice.storyInstruc
        self.feedbackInstruc   = idevice.feedbackInstruc
        self.previewing        = False # In view or preview render 
        if not hasattr(self.idevice,'undo'): 
            self.idevice.undo = True
        i = 0
        for question in idevice.questions:
            self.questionElements.append(QuestionElement(i, idevice, question))
            i += 1
    def process(self, request):
        """
        Process the request arguments from the web server
        """
        Block.process(self, request)
        is_cancel = common.requestHasCancel(request)
        self.storyElement.process(request)
        if (u"addQuestion"+unicode(self.id)) in request.args: 
            self.idevice.addQuestion()
            self.idevice.edit = True
            self.idevice.undo = False
        if "title"+self.id in request.args \
        and not is_cancel:
            self.idevice.title = request.args["title"+self.id][0]
        if "action" in request.args and request.args[u"action"][0] != u"delete":
            for element in self.questionElements:
                element.process(request)
            if request.args[u"action"][0] == u'done':
                if hasattr(self.idevice,'undo'): 
                    del self.idevice.undo
    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        self.previewing = True
        html  = u'<div class="iDevice"><br/>\n'
        html += common.textInput("title"+self.id, self.idevice.title)
        html += self.storyElement.renderEdit()
        for element in self.questionElements:
            html += element.renderEdit() 
        html += u"</table>\n"
        value = _(u"Add another activity")    
        html += common.submitButton(u"addQuestion"+unicode(self.id), value)
        html += u"<br /><br />" + self.renderEditButtons(undo=self.idevice.undo)
        html += u"</div>\n"
        return html
    def renderView(self, style):
        """
        Remembers if we're previewing or not,
        then implicitly calls self.renderViewContent (via Block.renderView)
        """
        self.previewing = False
        return Block.renderView(self, style)
    def renderPreview(self, style):
        """
        Remembers if we're previewing or not,
        then implicitly calls self.renderViewContent (via Block.renderPreview)
        """
        self.previewing = True
        return Block.renderPreview(self, style)
    def renderViewContent(self):
        """
        Returns an XHTML string for this block
        """
        log.debug("renderViewContent called with previewing mode = " + str(self.previewing))
        html  = u"<div class=\"iDevice_inner\">\n"
        if self.previewing:
            html += self.storyElement.renderPreview()
            html + u"<br/>\n"
            for element in self.questionElements:
                html += element.renderPreview()
        else:
            html += self.storyElement.renderView()
            html + u"<br/>\n"
            for element in self.questionElements:
                html += element.renderView()
        html += u"</div>\n"
        return html
class ListaBlock(Block):
    """

    """
    def __init__(self, parent, idevice):
        """
        Pre-create our field ids
        """
        Block.__init__(self, parent, idevice)
        
       
        # to compensate for the strange unpickling timing when objects are 
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.instructionsForLearners.idevice is None: 
            idevice.instructionsForLearners.idevice = idevice
        if idevice.content.idevice is None: 
            idevice.content.idevice = idevice
        if idevice.feedback.idevice is None: 
            idevice.feedback.idevice = idevice
            
        dT = common.getExportDocType()
        sectionTag = "div"
        if dT == "HTML5":
            sectionTag = "section"
            
        idevice.instructionsForLearners.htmlTag = sectionTag
        idevice.instructionsForLearners.class_ = "block instructions"
        idevice.feedback.htmlTag = sectionTag            

        self.instructionElement = TextAreaElement(idevice.instructionsForLearners)
        self.instructionElement.field.content_w_resourcePaths = c_(self.instructionElement.field.content_w_resourcePaths)
        self.listaElement = ListaElement(idevice.content)
        self.feedbackElement = \
            TextAreaElement(idevice.feedback)
        self.previewing        = False # In view or preview render
        if not hasattr(self.idevice,'undo'): 
            self.idevice.undo = True

    def process(self, request):
        """
        Handles changes in the paragraph text from editing
        """
        is_cancel = common.requestHasCancel(request)

        if "title"+self.id in request.args \
        and not is_cancel:
            self.idevice.title = request.args["title"+self.id][0]
        object = request.args.get('object', [''])[0]
        action = request.args.get('action', [''])[0]
        self.instructionElement.process(request)
        self.listaElement.process(request)
        self.feedbackElement.process(request)
        Block.process(self, request)

    def renderEdit(self, style):
        """
        Renders a screen that allows the user to enter paragraph text and choose
        which words are hidden.
        """
        title_text = self.idevice.title
        if title_text == _("DropDown Activity"):
            title_text = ""
        
        html = [
            u'<div class="iDevice">',
            u'<div class="block">',
            common.textInput("title"+self.id, title_text,
                             default_prompt = "Type your title here"),
            u'</div>',
            self.instructionElement.renderEdit(),
            self.listaElement.renderEdit(),
            self.feedbackElement.renderEdit(),
            self.renderEditButtons(),
            u'</div>'
            ]
        return u'\n    '.join(html)
    
    def renderPreview(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """ 
        self.previewing = True 
        return Block.renderPreview(self, style)

    def renderView(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """ 
        self.previewing = False 
        return Block.renderView(self, style)

    def renderViewContent(self):
        """
        Returns an XHTML string for this block
        """
        # Only show feedback button if feedback is present
        if self.feedbackElement.field.content.strip():
            # Lista Idevice needs id of div for feedback content
            feedbackID = self.feedbackElement.id
            if self.previewing: 
                clozeContent = self.listaElement.renderPreview(feedbackID)
            else: 
                clozeContent = self.listaElement.renderView(feedbackID)
        else:
            if self.previewing: 
                clozeContent = self.listaElement.renderPreview()
            else:
                clozeContent = self.listaElement.renderView()
        instruction_html = ""
        if self.previewing: 
            instruction_html = self.instructionElement.renderPreview()
        else:
            instruction_html = self.instructionElement.renderView()
        html = [       
            instruction_html,
            clozeContent]
        if self.feedbackElement.field.content: 
            if self.previewing: 
                html.append(self.feedbackElement.renderPreview(False, 
                                                     class_="feedback"))
            else:
                html.append(self.feedbackElement.renderView(False, 
                                                     class_="feedback"))
        return u'\n'.join(html)

    def renderText(self): 
        
        """
        Returns an XHTML string for text file export.
        """
        
        if self.previewing: 
            html = '<p>' +  self.instructionElement.renderPreview() +'</p>'
        else:
            html = '<p>' +  self.instructionElement.renderView() +'</p>'
        html += '<p>' + self.listaElement.renderText() + '</p>'
        if self.feedbackElement.field.content:
            html += '<p>%s:</P>' % c_(u"Feedback") 
            if self.previewing: 
                html += '<p>' +self.feedbackElement.renderPreview(False, 
                                                        class_="feedback") 
                html += '</p>'
            else:
                html += '<p>' +self.feedbackElement.renderView(False, 
                                                        class_="feedback") 
                html += '</p>'
        html += self.listaElement.renderAnswers()
        return html
Beispiel #38
0
class TestquestionElement(object):
    """
    TestQuestionElement is responsible for a block of question.  
    Used by QuizTestBlock
    == SCORM Quiz Testquestion, 
    pretty much the same as MultiSelect's SelectquestionElement
    """
    def __init__(self, index, idevice, question):
        """
        Initialize
        """
        self.index      = index
        self.id         = unicode(index) + "b" + idevice.id        
        self.idevice    = idevice

        # to compensate for the strange unpickling timing when objects are 
        # loaded from an elp, ensure that proper idevices are set:
        if question.questionTextArea.idevice is None: 
            question.questionTextArea.idevice = idevice
        self.questionElement = TextAreaElement(question.questionTextArea)
        self.question   = question

        self.questionId = "question"+self.id
        self.questionElement.id = self.questionId

        self.options    = []
        self.keyId      = "key" + self.id
        i = 0
        for option in question.options:
            self.options.append(TestoptionElement(i,
                                                  question, 
                                                  self.id, 
                                                  option,
                                                  idevice))
            i += 1

    def process(self, request):
        """
        Process the request arguments from the web server
        """
        log.info("process " + repr(request.args))
        if self.questionId in request.args: 
            self.questionElement.process(request)
            
        if ("addOption"+unicode(self.id)) in request.args: 
            self.question.addOption()
            self.idevice.edit = True
            # disable Undo once an option has been added: 
            self.idevice.undo = False
            
        if "action" in request.args and request.args["action"][0] == self.id:
            # before deleting the question object, remove any internal anchors:
            for q_field in self.question.getRichTextFields():
                 q_field.ReplaceAllInternalAnchorsLinks()  
                 q_field.RemoveAllInternalLinks()  
            self.idevice.questions.remove(self.question)
            # disable Undo once a question has been deleted: 
            self.idevice.undo = False

        for element in self.options:
            element.process(request)


    def renderEdit(self):
        """
        Returns an XHTML string with the form element for editing this element
        """
        html  = u"<div class=\"iDevice\">\n"
        html += common.submitImage(self.id, self.idevice.id,  
                "/images/stock-cancel.png", 
                _("Delete question")) 
        html += self.questionElement.renderEdit()

        html += u"<table width =\"100%%\">"
        html += u"<thead>"
        html += u"<tr>"
        html += u"<th>%s " % _("Options")
        html += common.elementInstruc(self.question.optionInstruc)
        html += u"</th>"
        html += u"</tr>"
        html += u"</thead>"
        html += u"<tbody>"

        for element in self.options:
            html += element.renderEdit() 
            
        html += u"</tbody>"
        html += u"</table>\n"
        value = _(u"Add another Option")    
        html += common.submitButton("addOption"+unicode(self.id), value)
        html += u"<br />"
        html += u"</div>\n"

        return html

    
    def renderPreview(self):
        """
        Returns an XHTML string for previewing this element
        """
        return self.renderView(preview=True)

    def renderView(self, preview=False):
        """
        Returns an XHTML string for viewing this element
        """
        html  = u""

        html += "<div class=\"question\">\n"
        if preview: 
            html += self.questionElement.renderPreview()
        else:
            html += self.questionElement.renderView()
        html += "<br/>\n"

        html += "<table>"
        for element in self.options:
            if preview: 
                html += element.renderPreview()      
            else:
                html += element.renderView()      
        html += "</table>"   
        html += "</div>\n"
        
        return html
    
    
    def getCorrectAns(self):
        """
        return the correct answer for the question
        """
        return self.question.correctAns

    
    def getNumOption(self):
        """
        return the number of options
        """
        return len(self.question.options)
Beispiel #39
0
class TrueFalseElement(object):
    """
    TrueFalseElement is responsible for a block of question. 
    Used by TrueFalseBlock.
    """
    def __init__(self, index, idevice, question):
        """
        Initialize
        """
        self.index      = index
        self.id         = unicode(index) + "b" + idevice.id        
        self.idevice    = idevice
        self.question   = question
        if question.questionTextArea.idevice is None: 
            question.questionTextArea.idevice = idevice
        if question.feedbackTextArea.idevice is None: 
            question.feedbackTextArea.idevice = idevice
        if question.hintTextArea.idevice is None: 
            question.hintTextArea.idevice = idevice
        self.question_question = TextAreaElement(question.questionTextArea)
        self.question_feedback = TextAreaElement(question.feedbackTextArea)
        self.question_hint = TextAreaElement(question.hintTextArea)
        self.questionId = "question"+ unicode(index) + "b" + idevice.id
        self.question_question.id = self.questionId
        self.feedbackId = "feedback" + unicode(index) + "b" + idevice.id 
        self.question_feedback.id = self.feedbackId
        self.hintId     = "hint" + unicode(index) + "b" + idevice.id 
        self.question_hint.id = self.hintId
        self.keyId      = "Key" + unicode(index) + "b" + idevice.id       
    def process(self, request):
        """
        Process arguments from the web server.  Return any which apply to this 
        element.
        """
        log.debug("process " + repr(request.args))
        if self.questionId in request.args:
            self.question_question.process(request)
        if self.hintId in request.args:
            self.question_hint.process(request)
        if self.keyId in request.args:
            if request.args[self.keyId][0] == "true":
                self.question.isCorrect = True 
                log.debug("question " + repr(self.question.isCorrect))
            else:
                self.question.isCorrect = False        
        if self.feedbackId in request.args:
            self.question_feedback.process(request)
        if "action" in request.args and request.args["action"][0] == self.id:
            for q_field in self.question.getRichTextFields():
                 q_field.ReplaceAllInternalAnchorsLinks()  
                 q_field.RemoveAllInternalLinks()  
            self.idevice.questions.remove(self.question)
    def renderEdit(self):
        """
        Returns an XHTML string for editing this option element
        """
        html = self.question_question.renderEdit()
        html += _("True") + " " 
        html += common.option(self.keyId, self.question.isCorrect, "true") 
        html += _("False") + " " 
        html += common.option(self.keyId, not self.question.isCorrect, "false") 
        html += "<br/><br/>\n"
        html += common.elementInstruc(self.idevice.keyInstruc)
        html += self.question_feedback.renderEdit()
        html += self.question_hint.renderEdit()
        html += common.submitImage(self.id, self.idevice.id, 
                                   "/images/stock-cancel.png",
                                   _("Delete question"))
        html += "<br/><br/>\n"
        return html
    def renderQuestionView(self):
        """
        Returns an XHTML string for viewing this question element
        """
        is_preview = 0
        html  = self.renderQuestion(is_preview)
        if self.question.hintTextArea.content<>"":
            html += u'<span '
            html += u'style="background-image:url(\'panel-amusements.png\');">'
            html += u'\n<a onmousedown="Javascript:updateCoords(event);'
            html += u'showMe(\'%s\', 350, 100);" ' % self.hintId
            html += u'style="cursor:help;align:center;vertical-align:middle;" '
            html += u'title="%s" \n' % _(u"Hint")
            html += u'href="javascript:void(0);">&nbsp;&nbsp;&nbsp;&nbsp;</a>'
            html += u'</span>'
            html += u'<div id="'+self.hintId+'" '
            html += u'style="display:none; z-index:99;">'
            html += u'<div style="float:right;" >'
            html += u'<img alt="%s" ' % _('Close')
            html += u'src="stock-stop.png" title="%s"' % _('Close')
            html += u" onmousedown=\"Javascript:hideMe();\"/></div>"
            html += u'<div class="popupDivLabel">'
            html += _(u"Hint")
            html += u'</div>\n'
            html += self.question_hint.renderView()
            html += u"</div>\n"
        return html
    def renderQuestionPreview(self):
        """
        Returns an XHTML string for previewing this question element
        """
        is_preview = 1
        html  = self.renderQuestion(is_preview)
        html += " &nbsp;&nbsp;\n"
        html += common.elementInstruc(self.question_hint.field.content, 
                                      "panel-amusements.png", "Hint")
        return html
    def renderQuestion(self, is_preview):
        """
        Returns an XHTML string for viewing and previewing this question element
        """
        log.debug("renderPreview called in the form of renderQuestion")
        html  = u"<br/><br/>"
        if is_preview:
            html += self.question_question.renderPreview() + "<br/>" 
        else: 
            html += self.question_question.renderView() + "<br/>"
        html += _("True") + " " 
        html += self.__option(0, 2, "true") + " \n"
        html += _("False") + " " 
        html += self.__option(1, 2, "false") + "\n"
        return html
    def __option(self, index, length, true):
        """Add a option input"""
        html  = u'<input type="radio" name="option%s" ' % self.id
        html += u'id="%s%s" ' % (true, self.id)
        html += u'onclick="getFeedback(%d,%d,\'%s\',\'truefalse\')"/>' % (
                index, length, self.id)
        return html
    def renderFeedbackPreview(self):
        """
        Merely a front-end to renderFeedbackView(), setting preview mode.
        Note: this won't really matter all that much, since these won't yet
        show up in exported printouts, BUT the image paths will be correct.
        """
        return self.renderFeedbackView(is_preview=True)
    def renderFeedbackView(self, is_preview=False):
        """
        return xhtml string for display this option's feedback
        """
        feedbackStr1 = _(u"Correct!") + " "
        feedbackStr2 = _(u"Incorrect!") + " "
        if not self.question.isCorrect:
            feedbackStr1, feedbackStr2 = feedbackStr2, feedbackStr1 
        feedbackId1 = "0" + "b" + self.id
        feedbackId2 = "1" + "b" + self.id
        html  = u'<div id="s%s" style="color: rgb(0, 51, 204);' % feedbackId1
        html += u'display: none;">' 
        html += feedbackStr1 + '</div>\n'
        html += u'<div id="s%s" style="color: rgb(0, 51, 204);' % feedbackId2
        html += u'display: none;">' 
        html += feedbackStr2 + '</div>\n'
        html += u'<div id="sfbk%s" style="color: rgb(0, 51, 204);' % self.id
        html += u'display: none;">' 
        if is_preview:
            html += self.question_feedback.renderPreview()
        else:
            html += self.question_feedback.renderView()
        html += u'</div>\n'
        return html
class ReflectionBlock(Block):
    """
    ReflectionBlock can render and process ReflectionIdevices as XHTML
    """
    def __init__(self, parent, idevice):
        """
        Initialize a new Block object
        """
        Block.__init__(self, parent, idevice)
        self.activityInstruc = idevice.activityInstruc
        self.answerInstruc   = idevice.answerInstruc

        # to compensate for the strange unpickling timing when objects are 
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.activityTextArea.idevice is None: 
            idevice.activityTextArea.idevice = idevice
        if idevice.answerTextArea.idevice is None: 
            idevice.answerTextArea.idevice = idevice

        self.activityElement  = TextAreaElement(idevice.activityTextArea)
        self.answerElement    = TextAreaElement(idevice.answerTextArea)

        self.previewing        = False # In view or preview render

        if not hasattr(self.idevice,'undo'): 
            self.idevice.undo = True


    def process(self, request):
        """
        Process the request arguments from the web server
        """
        Block.process(self, request)

        is_cancel = common.requestHasCancel(request)

        if not is_cancel:
            self.activityElement.process(request)
            self.answerElement.process(request)
            if "title"+self.id in request.args:
                self.idevice.title = request.args["title"+self.id][0]
        

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        html  = "<div class=\"iDevice\"><br/>\n"
        html += common.textInput("title"+self.id, self.idevice.title)
        html += self.activityElement.renderEdit()
        html += self.answerElement.renderEdit()
        html += "<br/>" + self.renderEditButtons()
        html += "</div>\n"
        return html

    def renderPreview(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """ 
        self.previewing = True 
        return Block.renderPreview(self, style)

    def renderView(self, style): 
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """ 
        self.previewing = False 
        return Block.renderView(self, style)


    def renderViewContent(self):
        """
        Returns an XHTML string for this block
        """
        html  = u'<script type="text/javascript" src="common.js"></script>\n'
        html += u'<div class="iDevice_inner">\n'
    
        if self.previewing: 
            html += self.activityElement.renderPreview()
        else:
            html += self.activityElement.renderView()

        html += '<div id="view%s" style="display:block;">' % self.id
        html += common.feedbackButton("btnshow"+self.id, _(u"Click here"),
                    onclick="showAnswer('%s',1)" % self.id)
        html += '</div>\n' 
        html += '<div id="hide%s" style="display:none;">' % self.id
        html += common.feedbackButton("btnshow"+self.id, _(u"Hide"),
                    onclick="showAnswer('%s',0)" % self.id)
        html += '</div>\n'
        html += '<div id="s%s" class="feedback" style=" ' % self.id
        html += 'display: none;">'

        if self.previewing: 
            html += self.answerElement.renderPreview()
        else:
            html += self.answerElement.renderView()

        html += "</div>\n"
        html += "</div>\n"
        return html
Beispiel #41
0
class ClozeBlock(Block):
    """
    Renders a paragraph where the content creator can choose which words the
    student must fill in.
    """
    def __init__(self, parent, idevice):
        """
        Pre-create our field ids
        """
        Block.__init__(self, parent, idevice)
        if idevice.instructionsForLearners.idevice is None: 
            idevice.instructionsForLearners.idevice = idevice
        if idevice.content.idevice is None: 
            idevice.content.idevice = idevice
        if idevice.feedback.idevice is None: 
            idevice.feedback.idevice = idevice
        self.instructionElement = \
            TextAreaElement(idevice.instructionsForLearners)
        self.clozeElement = ClozeElement(idevice.content)
        self.feedbackElement = \
            TextAreaElement(idevice.feedback)
        self.previewing        = False # In view or preview render
    def process(self, request):
        """
        Handles changes in the paragraph text from editing
        """
        if "title"+self.id in request.args:
            self.idevice.title = request.args["title"+self.id][0]
        object = request.args.get('object', [''])[0]
        action = request.args.get('action', [''])[0]
        self.instructionElement.process(request)
        self.clozeElement.process(request)
        self.feedbackElement.process(request)
        Block.process(self, request)
    def renderEdit(self, style):
        """
        Renders a screen that allows the user to enter paragraph text and choose
        which words are hidden.
        """
        html = [
            u'<div class="iDevice">',
            u'<div class="block">',
            common.textInput("title"+self.id, self.idevice.title),
            u'</div>',
            self.instructionElement.renderEdit(),
            self.clozeElement.renderEdit(),
            self.feedbackElement.renderEdit(),
            self.renderEditButtons(),
            u'</div>'
            ]
        return u'\n    '.join(html)
    def renderPreview(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """ 
        self.previewing = True 
        return Block.renderPreview(self, style)
    def renderView(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """ 
        self.previewing = False 
        return Block.renderView(self, style)
    def renderViewContent(self):
        """
        Returns an XHTML string for this block
        """
        if self.feedbackElement.field.content:
            feedbackID = self.feedbackElement.id
            if self.previewing: 
                clozeContent = self.clozeElement.renderPreview(feedbackID)
            else: 
                clozeContent = self.clozeElement.renderView(feedbackID)
        else:
            if self.previewing: 
                clozeContent = self.clozeElement.renderPreview()
            else:
                clozeContent = self.clozeElement.renderView()
        instruction_html = ""
        if self.previewing: 
            instruction_html = self.instructionElement.renderPreview()
        else:
            instruction_html = self.instructionElement.renderView()
        html = [
            u'<script type="text/javascript" src="common.js"></script>\n',
            u'<div class="iDevice_inner">\n',
            instruction_html,
            clozeContent]
        if self.feedbackElement.field.content: 
            if self.previewing: 
                html.append(self.feedbackElement.renderPreview(False, 
                                                     class_="feedback"))
            else:
                html.append(self.feedbackElement.renderView(False, 
                                                     class_="feedback"))
        html += [
            u'</div>\n',
            ]
        return u'\n    '.join(html)
    def renderText(self): 
        """
        Returns an XHTML string for text file export.
        """
        if self.previewing: 
            html = '<p>' +  self.instructionElement.renderPreview() +'</p>'
        else:
            html = '<p>' +  self.instructionElement.renderView() +'</p>'
        html += '<p>' + self.clozeElement.renderText() + '</p>'
        if self.feedbackElement.field.content:
            html += '<p>%s:</P>' % _(u"Feedback") 
            if self.previewing: 
                html += '<p>' +self.feedbackElement.renderPreview(False, 
                                                        class_="feedback") 
                html += '</p>'
            else:
                html += '<p>' +self.feedbackElement.renderView(False, 
                                                        class_="feedback") 
                html += '</p>'
        html += self.clozeElement.renderAnswers()
        return html
Beispiel #42
0
class ImageMagnifierBlock(Block):
    """
    ImageMagnifierBlock can render and process ImageMagnifierIdevices as XHTML
    """
    name = 'imageManifier'
    def __init__(self, parent, idevice):
        """
        Initialize
        """
        Block.__init__(self, parent, idevice)
        self.imageMagnifierElement = MagnifierElement(idevice.imageMagnifier)
        self.textElement  = TextAreaElement(idevice.text)
    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        log.debug("process " + repr(request.args))
        Block.process(self, request)
        if (u"action" not in request.args or
            request.args[u"action"][0] != u"delete"):
            self.imageMagnifierElement.process(request)
            self.textElement.process(request)
        if "float"+self.id in request.args:
            self.idevice.float = request.args["float"+self.id][0]
        if "caption"+self.id in request.args:
            self.idevice.caption = request.args["caption"+self.id][0]
        if "glass"+self.id in request.args:
            self.idevice.imageMagnifier.glassSize = \
                request.args["glass"+self.id][0]
        if "initial"+self.id in request.args:
            self.idevice.imageMagnifier.initialZSize = \
                request.args["initial"+self.id][0]
        if "maxZoom"+self.id in request.args:
            self.idevice.imageMagnifier.maxZSize = \
                request.args["maxZoom"+self.id][0]
    def renderEdit(self, style):
        """
        Returns an XHTML string with the form elements for editing this block
        """
        log.debug("renderEdit")
        floatArr        = [[_(u'Left'), 'left'],
                          [_(u'Right'), 'right'],
                          [_(u'None'),  'none']]
        html  = u"<div class=\"iDevice\">\n"
        html += '<div class="block">'
        html += u"<strong>%s</strong>" % _(u"Caption:")
        html += common.elementInstruc(self.idevice.captionInstruc)
        html += '</div>'
        html += '<div class="block">'
        html += common.textInput("caption" + self.id, self.idevice.caption)
        html += '</div>'
        html += '<div class="block">'
        html += self.textElement.renderEdit()
        html += '</div>'
        html += self.imageMagnifierElement.renderEdit()       
        html += common.formField('select', _("Align:"),
                                 "float" + self.id, '',
                                 self.idevice.alignInstruc,
                                 floatArr, self.idevice.float)
        zoomOpts = []
        for i in range(100, 201, 10):
            zoomOpts.append(('%d%%' % (i), str(i)))
        selection = self.idevice.imageMagnifier.initialZSize
        html += common.formField('select', _(u"Initial Zoom"),
                                 "initial" + self.id, '',
                                 self.idevice.initialZoomInstruc,
                                 zoomOpts, selection)
        selection = self.idevice.imageMagnifier.maxZSize
        html += common.formField('select', _(u"Maximum zoom"),
                                 "maxZoom" + self.id, '',
                                 self.idevice.maxZoomInstruc,
                                 zoomOpts, selection)
        glassSizeArr    = [[_(u'Small'), '1'],
                          [_(u'Medium'),'2'],
                          [_(u'Large'),'3'],
                          [_(u'Extra large'),'4'],]
        html += common.formField('select', _(u"Size of magnifying glass: "),
                                 "glass" + self.id, '',
                                 self.idevice.glassSizeInstruc,
                                 glassSizeArr, 
                                 self.idevice.imageMagnifier.glassSize)
        html += self.renderEditButtons()
        html += u"</div>\n"
        return html
    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        log.debug("renderPreview")
        html  = u"\n<!-- image with text iDevice -->\n"
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\" "
        html += "ondblclick=\"submitLink('edit',"+self.id+", 0);\">\n"
        html += u"  <div class=\"image_text\" style=\""
        html += u"width:" + str(self.idevice.imageMagnifier.width) + "px; "
        html += u"float:%s;\">\n" % self.idevice.float
        html += u"    <div class=\"image\">\n"
        html += self.imageMagnifierElement.renderPreview()
        html += u"" + self.idevice.caption
        html += u"    </div> <!-- class=\"image\" -->\n" 
        html += u"  </div> <!-- class=\"image_text\" -->\n" 
        text = self.textElement.renderPreview()
        if text:
            html += text
        else:
            html += '&nbsp;'
        html += u'\n<div style="clear:both;height:1px;overflow:hidden;"></div>\n'
        html += self.renderViewButtons()
        html += u"</div> <!-- class=\"iDevice emphasisX\" -->\n" 
        return html
    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """        
        log.debug("renderView")
        html  = u"\n<!-- image with text iDevice -->\n"
        html += u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\">\n"
        html += u"  <div class=\"image_text\" style=\""
        html += u"width:" + str(self.idevice.imageMagnifier.width) + "px; "
        html += u"float:%s;\">\n" % self.idevice.float
        html += u"    <div class=\"image\">\n"
        html += self.imageMagnifierElement.renderView()
        html += u"    <br/>" + self.idevice.caption
        html += u"    </div> <!-- class=\"image\" -->\n" 
        html += u"  </div> <!-- class=\"image_text\" -->\n" 
        text = self.textElement.renderView()
        if text:
            html += text
        else:
            html += '&nbsp;'
        html += u'\n<div style="clear:both;height:1px;overflow:hidden;"></div>\n'
        html += u'\n<div style="clear:both;"></div>\n'
        html += u"</div> <!-- class=\"iDevice emphasisX\" -->\n" 
        return html
class TrueFalseElement(object):
    """
    TrueFalseElement is responsible for a block of question. 
    Used by TrueFalseBlock.
    """
    def __init__(self, index, idevice, question):
        """
        Initialize
        """
        self.index      = index
        self.id         = unicode(index) + "b" + idevice.id        
        self.idevice    = idevice

        self.question   = question
        # also split out each part for a separate TextAreaElement:
        # but first...
        # to compensate for the strange unpickling timing when objects are 
        # loaded from an elp, ensure that proper idevices are set:
        if question.questionTextArea.idevice is None: 
            question.questionTextArea.idevice = idevice
        if question.feedbackTextArea.idevice is None: 
            question.feedbackTextArea.idevice = idevice
        if question.hintTextArea.idevice is None: 
            question.hintTextArea.idevice = idevice
        #
        self.question_question = TextAreaElement(question.questionTextArea)
        self.question_feedback = TextAreaElement(question.feedbackTextArea)
        self.question_hint = TextAreaElement(question.hintTextArea)

        # note, question.isCorrect is left as it was, and not split out.
        # because there are low-level mechanisms in place somewhere 
        # with the radio buttons or ??? expecting that as such.
        
        self.questionId = "question"+ unicode(index) + "b" + idevice.id
        self.question_question.id = self.questionId
        self.feedbackId = "feedback" + unicode(index) + "b" + idevice.id 
        self.question_feedback.id = self.feedbackId
        self.hintId     = "hint" + unicode(index) + "b" + idevice.id 
        self.question_hint.id = self.hintId
        self.keyId      = "Key" + unicode(index) + "b" + idevice.id       

    def process(self, request):
        """
        Process arguments from the web server.  Return any which apply to this 
        element.
        """
        log.debug("process " + repr(request.args))

        is_cancel = common.requestHasCancel(request)

        if self.questionId in request.args \
        and not is_cancel:
            self.question_question.process(request)
            
        if self.hintId in request.args \
        and not is_cancel:
            self.question_hint.process(request)
                        
        if self.keyId in request.args \
        and not is_cancel:
            if request.args[self.keyId][0] == "true":
                self.question.isCorrect = True 
                log.debug("question " + repr(self.question.isCorrect))
            else:
                self.question.isCorrect = False        
        
        if self.feedbackId in request.args \
        and not is_cancel:
            self.question_feedback.process(request)
            
        if "action" in request.args and request.args["action"][0] == self.id:
            # before deleting the question object, remove any internal anchors:
            for q_field in self.question.getRichTextFields():
                 q_field.ReplaceAllInternalAnchorsLinks()  
                 q_field.RemoveAllInternalLinks()  
            self.idevice.questions.remove(self.question)
            # disable Undo once a question has been deleted: 
            self.idevice.undo = False

    def renderEdit(self):
        """
        Returns an XHTML string for editing this option element
        """
        
        html = self.question_question.renderEdit()

        html += _("True") + " " 
        html += common.option(self.keyId, self.question.isCorrect, "true") 
        html += _("False") + " " 
        html += common.option(self.keyId, not self.question.isCorrect, "false") 

        html += "<br/><br/>\n"

        html += common.elementInstruc(self.idevice.keyInstruc)
        
        html += self.question_feedback.renderEdit()
        html += self.question_hint.renderEdit()
        
        html += common.submitImage(self.id, self.idevice.id, 
                                   "/images/stock-cancel.png",
                                   _("Delete question"))
        html += "<br/><br/>\n"
        return html
    
    def renderQuestionView(self):
        """
        Returns an XHTML string for viewing this question element
        """
        is_preview = 0
        html  = self.renderQuestion(is_preview)
        if self.question.hintTextArea.content.strip() != "":
            html += u'<span '
            html += u'style="background-image:url(\'panel-amusements.png\');">'
            html += u'\n<a onmousedown="Javascript:updateCoords(event);'
            html += u'showMe(\'%s\', 350, 100);" ' % self.hintId
            html += u'style="cursor:help;align:center;vertical-align:middle;" '
            html += u'title="%s" \n' % _(u"Hint")
            html += u'href="javascript:void(0);">&nbsp;&nbsp;&nbsp;&nbsp;</a>'
            html += u'</span>'
            html += u'<div id="'+self.hintId+'" '
            html += u'style="display:none; z-index:99;">'
            html += u'<div style="float:right;" >'
            html += u'<img alt="%s" ' % _('Close')
            html += u'src="stock-stop.png" title="%s"' % _('Close')
            html += u" onmousedown=\"Javascript:hideMe();\"/></div>"
            html += u'<div class="popupDivLabel">'
            html += _(u"Hint")
            html += u'</div>\n'
            html += self.question_hint.renderView()
            html += u"</div>\n"
        
        return html
    
    def renderQuestionPreview(self):
        #TODO merge renderQuestionView and renderQuestionPreview
        """
        Returns an XHTML string for previewing this question element
        """
        is_preview = 1
        html  = self.renderQuestion(is_preview)
        html += " &nbsp;&nbsp;\n"

        html += common.elementInstruc(self.question_hint.field.content, 
                                      "panel-amusements.png", "Hint")
        return html

    def renderQuestion(self, is_preview):
        """
        Returns an XHTML string for viewing and previewing this question element
        """
        log.debug("renderPreview called in the form of renderQuestion")
    
        html  = u"<br/><br/>"

        if is_preview:
            html += self.question_question.renderPreview() + "<br/>" 
        else: 
            html += self.question_question.renderView() + "<br/>"

        html += _("True") + " " 
        html += self.__option(0, 2, "true") + " \n"
        html += _("False") + " " 
        html += self.__option(1, 2, "false") + "\n"
       
        return html
    
    def __option(self, index, length, true):
        """Add a option input"""
        html  = u'<input type="radio" name="option%s" ' % self.id
        html += u'id="%s%s" ' % (true, self.id)
        html += u'onclick="getFeedback(%d,%d,\'%s\',\'truefalse\')"/>' % (
                index, length, self.id)
        return html
    
    def renderFeedbackPreview(self):
        """
        Merely a front-end to renderFeedbackView(), setting preview mode.
        Note: this won't really matter all that much, since these won't yet
        show up in exported printouts, BUT the image paths will be correct.
        """
        return self.renderFeedbackView(is_preview=True)

    def renderFeedbackView(self, is_preview=False):
        """
        return xhtml string for display this option's feedback
        """
        feedbackStr1 = _(u"Correct!") + " "
        feedbackStr2 = _(u"Incorrect!") + " "

        # embed a score_representation as well, even==true,
        # so that Correct/Incorrect doesn't need to be un-translated
        # upon bursting from a CC export.
        # start off with a sorta random looking number:
        to_even1 = int(self.idevice.id)+5
        if to_even1 % 2:
            # ensure that to_even1 is indeed even, correct:
            to_even1 += 1
        # and ensure that to_even2 is odd, incorrect:
        to_even2 = to_even1 + 1


        if not self.question.isCorrect:
            feedbackStr1, feedbackStr2 = feedbackStr2, feedbackStr1 
            to_even1, to_even2 = to_even2, to_even1

        feedbackId1 = "0" + "b" + self.id
        feedbackId2 = "1" + "b" + self.id
        html  = u'<div id="s%s" style="color: rgb(0, 51, 204);' % feedbackId1
        html += u'display: none;" even_steven="%s">' % (str(to_even1))
        html += feedbackStr1 + '</div>\n'
        html += u'<div id="s%s" style="color: rgb(0, 51, 204);' % feedbackId2
        html += u'display: none;" even_steven="%s">' % (str(to_even2))
        html += feedbackStr2 + '</div>\n'
        html += u'<div id="sfbk%s" style="color: rgb(0, 51, 204);' % self.id
        html += u'display: none;">' 
        if is_preview:
            html += self.question_feedback.renderPreview()
        else:
            html += self.question_feedback.renderView()
        html += u'</div>\n'
        
        return html
Beispiel #44
0
class TestoptionElement(object):
    """
    TestOptionElement is responsible for a block of option.  Used by
    TestquestionElement.  
    == SCORM Quiz Testoption, 
    pretty much the same as MultiSelect's SelectoptionElement,
    but with enough subtle variations that you'd better pay attention :-)
    """
    def __init__(self, index, question, questionId, option, idevice):
        """
        Initialize
        """
        self.index      = index
        self.id         = unicode(index) + "q" + questionId       
        self.question   = question
        self.questionId = questionId
        self.option     = option
        self.answerId   = "optionAnswer"+ unicode(index) + "q" + questionId
        self.keyId      = "key" + questionId   
        self.idevice    = idevice
        self.checked    = False
        if option.answerTextArea.idevice is None: 
            option.answerTextArea.idevice = idevice
        self.answerElement = TextAreaElement(option.answerTextArea)
        self.answerElement.id = self.answerId
        if not hasattr(self.idevice,'undo'): 
            self.idevice.undo = True
    def process(self, request):
        """
        Process arguments from the web server.  Return any which apply to this 
        element.
        """
        log.debug("process " + repr(request.args))
        is_cancel = common.requestHasCancel(request)
        if self.answerId in request.args \
        and not is_cancel:
            self.answerElement.process(request)
        if "c"+self.keyId in request.args \
        and not is_cancel:
            if request.args["c"+self.keyId][0] == self.id:
                self.option.isCorrect = True 
                self.question.correctAns = self.index
                log.debug("option " + repr(self.option.isCorrect))
            else:
                self.option.isCorrect = False
        if self.keyId in request.args \
        and not is_cancel:
            if request.args[self.keyId][0] == unicode(self.index):
                self.question.userAns = self.index
        if "action" in request.args and request.args["action"][0] == self.id:
            for o_field in self.option.getRichTextFields():
                 o_field.ReplaceAllInternalAnchorsLinks()  
                 o_field.RemoveAllInternalLinks()  
            self.question.options.remove(self.option)
            self.idevice.undo = False
    def renderEdit(self):
        """
        Returns an XHTML string for editing this option element
        """
        html  = u"<tr><td align=\"left\"><b>%s</b>" % _("Option")
        html += common.elementInstruc(self.question.optionInstruc)
        header = ""
        if self.index == 0: 
            header = _("Correct Option")
        html += u"</td><td align=\"right\"><b>%s</b>\n" % header
        html += u"</td><td>\n"
        if self.index == 0: 
             html += common.elementInstruc(self.question.correctAnswerInstruc)
        html += "</td></tr><tr><td colspan=2>\n"
        this_package = None 
        if self.answerElement.field_idevice is not None \
        and self.answerElement.field_idevice.parentNode is not None: 
            this_package = self.answerElement.field_idevice.parentNode.package
        html += common.richTextArea(self.answerId,
                self.answerElement.field.content_w_resourcePaths,
                package=this_package)
        html += "</td><td align=\"center\">\n"
        html += common.option("c"+self.keyId, 
                self.option.isCorrect, self.id)
        html += "<br><br><br><br>\n"
        html += common.submitImage(self.id, self.idevice.id, 
                                   "/images/stock-cancel.png",
                                   _(u"Delete option"))
        html += "</td></tr>\n"
        return html
    def renderPreview(self):
        """
        Returns an XHTML string for previewing this option element
        """
        return self.renderView(preview=True)
    def renderView(self, preview=False):
        """
        Returns an XHTML string for viewing this option element
        """
        log.debug("renderView called")
        html  = '<tr><td>'
        html += common.option(self.keyId, 0, unicode(self.index))
        html += '</td><td>\n'
        if preview: 
            html += self.answerElement.renderPreview()
        else:            
            html += self.answerElement.renderView()
        html += "</td></tr>\n"
        return html
Beispiel #45
0
class ClozefpdBlock(Block):
    """
    Renders a paragraph where the content creator can choose which words the
    student must fill in.
    """
    def __init__(self, parent, idevice):
        """
        Pre-create our field ids
        """
        Block.__init__(self, parent, idevice)

        # to compensate for the strange unpickling timing when objects are
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.instructionsForLearners.idevice is None:
            idevice.instructionsForLearners.idevice = idevice
        if idevice.content.idevice is None:
            idevice.content.idevice = idevice
        if idevice.feedback.idevice is None:
            idevice.feedback.idevice = idevice

        self.instructionElement = \
            TextAreaElement(idevice.instructionsForLearners)
        self.clozeElement = ClozeElement(idevice.content)
        self.feedbackElement = \
            TextAreaElement(idevice.feedback)
        self.previewing = False  # In view or preview render
        if not hasattr(self.idevice, 'undo'):
            self.idevice.undo = True

    def process(self, request):
        """
        Handles changes in the paragraph text from editing
        """
        is_cancel = common.requestHasCancel(request)

        if "title"+self.id in request.args \
        and not is_cancel:
            self.idevice.title = request.args["title" + self.id][0]
        object = request.args.get('object', [''])[0]
        action = request.args.get('action', [''])[0]
        self.instructionElement.process(request)
        self.clozeElement.process(request)
        self.feedbackElement.process(request)
        Block.process(self, request)

    def renderEdit(self, style):
        """
        Renders a screen that allows the user to enter paragraph text and choose
        which words are hidden.
        """
        """        
	html = [
            u'<div class="iDevice">',
            u'<div class="block">',
#            common.textInput("title"+self.id, self.idevice.title),
            common.textInput("title"+self.id, "Autoevaluaci&oacute;n"),
            u'</div>',
            self.instructionElement.renderEdit(),
            self.clozeElement.renderEdit(),
            self.feedbackElement.renderEdit(),
            self.renderEditButtons(),
            u'</div>'
            ]
        return u'\n    '.join(html)"""
        html = "<div class=\"iDevice\"><br/>\n"
        html = "<div class=\"block\">"

        # JR
        # Quitamos el prefijo "FPD -"
        if self.idevice.title.find("FPD - ") == 0:
            self.idevice.title = x_(u"Autoevaluacion")

        html += common.textInput("title" + self.id, self.idevice.title)
        html += "</div>"
        html += self.instructionElement.renderEdit()
        html += self.clozeElement.renderEdit()
        html += self.feedbackElement.renderEdit()
        html += self.renderEditButtons()
        html += "</div>"
        return html

    def renderPreview(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """
        self.previewing = True
        return Block.renderPreview(self, style)

    def renderView(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """
        self.previewing = False
        return Block.renderView(self, style)

    def renderViewContent(self):
        """
        Returns an XHTML string for this block
        """
        # Only show feedback button if feedback is present
        if self.feedbackElement.field.content.strip():
            # Cloze Idevice needs id of div for feedback content
            feedbackID = self.feedbackElement.id
            if self.previewing:
                clozeContent = self.clozeElement.renderPreview(feedbackID)
            else:
                clozeContent = self.clozeElement.renderView(feedbackID)
        else:
            if self.previewing:
                clozeContent = self.clozeElement.renderPreview()
            else:
                clozeContent = self.clozeElement.renderView()
        instruction_html = ""
        if self.previewing:
            instruction_html = self.instructionElement.renderPreview()
        else:
            instruction_html = self.instructionElement.renderView()
        html = u'<script type="text/javascript" src="common.js"></script>\n'
        html += u'<div class="iDevice_inner">\n'
        html += instruction_html
        html += clozeContent
        if self.feedbackElement.field.content:
            if self.previewing:
                html += self.feedbackElement.renderPreview(False,
                                                           class_="feedback")
            else:
                html += self.feedbackElement.renderView(False,
                                                        class_="feedback")
        html += u'</div>\n'

        #JR: Anadimos la etiqueta noscript
        if self.previewing:
            cloze = self.clozeElement.field.content_w_resourcePaths
            feedback = self.feedbackElement.field.content_w_resourcePaths
        else:
            cloze = self.clozeElement.field.content_w_resourcePaths
            feedback = self.feedbackElement.field.content_wo_resourcePaths
        html += u'<noscript><div class="feedback">\n'
        html += u"<strong>" + _("Solucion") + u": </strong><br/>\n"
        html += cloze
        if self.feedbackElement.field.content:
            html += u"<br/><br/><strong>" + _(
                "Retroalimentacion") + ": </strong><br/>\n"
            html += feedback
        html += u"</div></noscript>"

        return html

    def renderText(self):
        """
        Returns an XHTML string for text file export.
        """

        if self.previewing:
            html = '<p>' + self.instructionElement.renderPreview() + '</p>'
        else:
            html = '<p>' + self.instructionElement.renderView() + '</p>'
        html += '<p>' + self.clozeElement.renderText() + '</p>'
        if self.feedbackElement.field.content:
            html += '<p>%s:</P>' % _(u"Feedback")
            if self.previewing:
                html += '<p>' + self.feedbackElement.renderPreview(
                    False, class_="feedback")
                html += '</p>'
            else:
                html += '<p>' + self.feedbackElement.renderView(
                    False, class_="feedback")
                html += '</p>'
        html += self.clozeElement.renderAnswers()
        return html
Beispiel #46
0
class OpinionElement(object):
    """
    TrueFalseElement is responsible for a block of question. 
    Used by TrueFalseBlock.
    """
    def __init__(self, index, idevice, question):
        """
        Initialize
        """
        self.index = index
        self.id = unicode(index) + "b" + idevice.id
        self.idevice = idevice

        self.question = question
        # also split out each part for a separate TextAreaElement:
        # but first...
        # to compensate for the strange unpickling timing when objects are
        # loaded from an elp, ensure that proper idevices are set:
        if question.questionTextArea.idevice is None:
            question.questionTextArea.idevice = idevice
        if question.feedbackTextArea.idevice is None:
            question.feedbackTextArea.idevice = idevice
        if question.hintTextArea.idevice is None:
            question.hintTextArea.idevice = idevice
        #
        self.question_question = TextAreaElement(question.questionTextArea)
        self.question_feedback = TextAreaElement(question.feedbackTextArea)
        self.question_hint = TextAreaElement(question.hintTextArea)

        # note, question.isCorrect is left as it was, and not split out.
        # because there are low-level mechanisms in place somewhere
        # with the radio buttons or ??? expecting that as such.

        self.questionId = "question" + unicode(index) + "b" + idevice.id
        self.question_question.id = self.questionId
        self.feedbackId = "feedback" + unicode(index) + "b" + idevice.id
        self.question_feedback.id = self.feedbackId
        self.hintId = "hint" + unicode(index) + "b" + idevice.id
        self.question_hint.id = self.hintId
        self.keyId = "Key" + unicode(index) + "b" + idevice.id

    def process(self, request):
        """
        Process arguments from the web server.  Return any which apply to this 
        element.
        """
        log.debug("process " + repr(request.args))

        is_cancel = common.requestHasCancel(request)

        if self.questionId in request.args \
        and not is_cancel:
            self.question_question.process(request)

        if self.hintId in request.args \
        and not is_cancel:
            self.question_hint.process(request)

        if self.keyId in request.args \
        and not is_cancel:
            if request.args[self.keyId][0] == "true":
                self.question.isCorrect = True
                log.debug("question " + repr(self.question.isCorrect))
            else:
                self.question.isCorrect = False

        if self.feedbackId in request.args \
        and not is_cancel:
            self.question_feedback.process(request)

        if "action" in request.args and request.args["action"][0] == self.id:
            # before deleting the question object, remove any internal anchors:
            for q_field in self.question.getRichTextFields():
                q_field.ReplaceAllInternalAnchorsLinks()
                q_field.RemoveAllInternalLinks()
            self.idevice.questions.remove(self.question)
            # disable Undo once a question has been deleted:
            self.idevice.undo = False

    def renderEdit(self):
        """
        Returns an XHTML string for editing this option element
        """

        html = self.question_question.renderEdit()

        #removed unnecessary elements kthamm 111028
        #html += _("True") + " "
        #html += common.option(self.keyId, self.question.isCorrect, "true")
        #html += _("False") + " "
        #html += common.option(self.keyId, not self.question.isCorrect, "false")

        #html += "<br/><br/>\n"

        #html += common.elementInstruc(self.idevice.keyInstruc)

        #html += self.question_hint.renderEdit()
        #end removed

        html += self.question_feedback.renderEdit()
        html += common.submitImage(self.id, self.idevice.id,
                                   "/images/stock-cancel.png",
                                   _("Delete question"))
        html += "<br/><br/>\n"
        return html

    def renderQuestionView(self):
        """
        Returns an XHTML string for viewing this question element
        """
        is_preview = 0
        html = self.renderQuestion(is_preview)

        #removed kthamm 111028
        #if self.question.hintTextArea.content.strip() != "":
        #html += u'<span '
        #html += u'style="background-image:url(\'panel-amusements.png\');">'
        #html += u'\n<a onmousedown="Javascript:updateCoords(event);'
        #html += u'showMe(\'%s\', 350, 100);" ' % self.hintId
        #html += u'style="cursor:help;align:center;vertical-align:middle;" '
        #html += u'title="%s" \n' % _(u"Hint")
        #html += u'href="javascript:void(0);">&nbsp;&nbsp;&nbsp;&nbsp;</a>'
        #html += u'</span>'
        ##html += u'<div id="'+self.hintId+'" ' //removed kthamm 111028
        ##html += u'style="display:none; z-index:99;">' //removed kthamm 111028
        #html += u'<div style="float:right;" >'
        #html += u'<img alt="%s" ' % _('Close')
        #html += u'src="stock-stop.png" title="%s"' % _('Close')
        #html += u" onmousedown=\"Javascript:hideMe();\"/></div>"
        #html += u'<div class="popupDivLabel">'
        #html += _(u"Hint")
        #html += u'</div>\n'
        #html += self.question_hint.renderView()
        #html += u"</div>\n"
        #end removed
        return html

    def renderQuestionPreview(self):
        #TODO merge renderQuestionView and renderQuestionPreview
        """
        Returns an XHTML string for previewing this question element
        """
        is_preview = 1
        html = self.renderQuestion(is_preview)
        html += " &nbsp;&nbsp;\n"

        #html += common.elementInstruc(self.question_hint.field.content,"panel-amusements.png", "Hint") //removed kthamm 111028
        return html

    def renderQuestion(self, is_preview):
        """
        Returns an XHTML string for viewing and previewing this question element
        """
        log.debug("renderPreview called in the form of renderQuestion")

        html = u"<br/><br/>"

        if is_preview:
            html += self.question_question.renderPreview() + "<br/>"
        else:
            html += self.question_question.renderView() + "<br/>"

        html += _("I agree") + " "
        html += self.__option(0, 2, "true") + " \n"
        html += _("I disagree") + " "
        html += self.__option(1, 2, "false") + "\n"

        return html

    def __option(self, index, length, true):
        """Add a option input"""
        html = u'<input type="radio" name="option%s" ' % self.id
        html += u'id="%s%s" ' % (true, self.id)
        html += u'onclick="getOptionFeedback(%d,%d,\'%s\',\'truefalse\')"/>' % (
            index, length, self.id)
        return html

    def renderFeedbackPreview(self):
        """
        Merely a front-end to renderFeedbackView(), setting preview mode.
        Note: this won't really matter all that much, since these won't yet
        show up in exported printouts, BUT the image paths will be correct.
        """
        return self.renderFeedbackView(is_preview=True)

    def renderFeedbackView(self, is_preview=False):
        """
        return xhtml string for display this option's feedback
        """
        feedbackStr1 = _(u"Correct!") + " "
        feedbackStr2 = _(u"Incorrect!") + " "

        # embed a score_representation as well, even==true,
        # so that Correct/Incorrect doesn't need to be un-translated
        # upon bursting from a CC export.
        # start off with a sorta random looking number:
        to_even1 = int(self.idevice.id) + 5
        if to_even1 % 2:
            # ensure that to_even1 is indeed even, correct:
            to_even1 += 1
        # and ensure that to_even2 is odd, incorrect:
        to_even2 = to_even1 + 1

        if not self.question.isCorrect:
            feedbackStr1, feedbackStr2 = feedbackStr2, feedbackStr1
            to_even1, to_even2 = to_even2, to_even1

        feedbackId1 = "0" + "b" + self.id
        feedbackId2 = "1" + "b" + self.id
        html = u''
        #html  = u'<div id="s%s" style="color: rgb(0, 51, 204);' % feedbackId1
        #html += u'display: none;" even_steven="%s">' % (str(to_even1))
        #html += feedbackStr1 + '</div>\n'
        #html += u'<div id="s%s" style="color: rgb(0, 51, 204);' % feedbackId2
        #html += u'display: none;" even_steven="%s">' % (str(to_even2))
        #html += feedbackStr2 + '</div>\n'
        html += u'<div id="sfbk%s" style="color: rgb(0, 51, 204);' % self.id
        html += u'display: none;">'
        if is_preview:
            html += self.question_feedback.renderPreview()
        else:
            html += self.question_feedback.renderView()
        html += u'</div>\n'

        return html
Beispiel #47
0
class NotaBlock(Block):

    def __init__(self, parent, idevice):
        """
        Initialize a new Block object
        """
        Block.__init__(self, parent, idevice)
        self.commentInstruc   = idevice.commentInstruc



        if idevice.commentTextArea.idevice is None: 
            idevice.commentTextArea.idevice = idevice


        self.commentElement    = TextAreaElement(idevice.commentTextArea)

        self.previewing        = False # In view or preview render

        if not hasattr(self.idevice,'undo'): 
            self.idevice.undo = True


    def process(self, request):
        """
        Process the request arguments from the web server
        """
        Block.process(self, request)

        is_cancel = common.requestHasCancel(request)

        if not is_cancel:
            self.commentElement.process(request)
            if "title"+self.id in request.args:
                self.idevice.title = request.args["title"+self.id][0]
        

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        html  = "<div class=\"iDevice\"><br/>\n"
        html += common.textInput("title"+self.id, self.idevice.title)
        html += self.commentElement.renderEdit()
        html += "<br/>" + self.renderEditButtons()
        html += "</div>\n"
        return html

    def renderPreview(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """ 

        self.previewing = True
        return self.renderNote()

    def renderView(self, style): 
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """ 
        self.previewing = False
        return self.renderNote()
        


    
    
    def renderNote(self):
        """
        Returns an XHTML string for this block
        """
        html = u'<div class="classnote">\n'
        if  self.commentElement.field.content:
            html += '<div class="notetitleex" onclick="jQuery(\'#fb%s\').toggle()" title="%s">' % (self.id , _(u"Show/Hide"))
        else:
            html += '<div class="notetitle">'
        html +='%s</div>' % self.idevice.title
        if  self.commentElement.field.content:
            html += '<div id="fb%s" class="notearea">' % self.id        
            
            if self.previewing: 
                html += self.commentElement.renderPreview()            
            else:
                html += self.commentElement.renderView()

            html += "</div>\n"
        if self.previewing:
            html +=Block.renderViewButtons(self)
            html +="<a title=\""+_(u"Delete all notes")+"\" href=\"#\" onclick=\"confirmThenSubmitLink('"+_(u"Would you delete all notes?")+"', '"+u'deleteallnotes'+"', '"+self.id+"', 1);\" style=\"float:right;margin-top:-20px;\"><img alt=\""+_(u"Delete all notes")+"\" width=\"16\" height=\"16\" class=\"submit\" src=\"/images/stock-delete.png\"></a>"
        html += "</div>\n"

        
        return html
class WikipediaBlock(Block):
    """
    WikipediaBlock can render and process WikipediaIdevices as XHTML
    """
    def __init__(self, parent, idevice):
        """
        Initialize
        """
        Block.__init__(self, parent, idevice)

        # to compensate for the strange unpickling timing when objects are 
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.article.idevice is None: 
            idevice.article.idevice = idevice
        self.articleElement = TextAreaElement(idevice.article)
        self.articleElement.height = 300
        if not hasattr(self.idevice,'undo'): 
            self.idevice.undo = True


    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        log.debug("process " + repr(request.args))

        is_cancel = common.requestHasCancel(request)
        
        if 'emphasis'+self.id in request.args \
        and not is_cancel:
            self.idevice.emphasis = int(request.args['emphasis'+self.id][0])
            # disable Undo once an emphasis has changed: 
            self.idevice.undo = False
            
        if 'ssite'+self.id in request.args \
        and not is_cancel:
            self.idevice.site = request.args['ssite'+self.id][0]
            
        if 'ownUrl'+self.id in request.args \
        and not is_cancel:
            self.idevice.ownUrl = request.args['ownUrl'+self.id][0]

        if 'title'+self.id in request.args \
        and not is_cancel:
            self.idevice.title = request.args['title'+self.id][0]
            
        if ("object" in request.args and request.args["object"][0] == "site" + self.id):
            pass
        elif 'loadWikipedia'+self.id in request.args:
            # If they've hit "load" instead of "the tick"
            self.idevice.loadArticle(request.args['article'][0])
            # disable Undo once an article has been loaded: 
            self.idevice.undo = False
        else:
            # If they hit "the tick" instead of "load"
            Block.process(self, request)
            if (u"action" not in request.args \
            or request.args[u"action"][0] != u"delete"):
                # If the text has been changed
                self.articleElement.process(request)
            if "action" in request.args \
            and request.args["action"][0] == "done":
                # remove the undo flag in order to reenable it next time:
                if hasattr(self.idevice,'undo'): 
                    del self.idevice.undo
        
            
    def renderEdit(self, style):
        """
        Returns an XHTML string with the form elements for editing this block
        """
        log.debug("renderEdit")
        

        html  = u"<div class=\"iDevice\"><br/>\n"
        html += common.textInput("title" + self.id, self.idevice.title) + "<br/><br/>"

        sites = [(_(u"English Wikipedia Article"), "http://en.wikipedia.org/wiki/"),
                 (_(u"Basque Wikipedia Article"), "http://eu.wikipedia.org/wiki/"),
                 (_(u"Catalan Wikipedia Article"), "http://ca.wikipedia.org/wiki/"),
                 (_(u"Chinese Wikipedia Article"), "http://zh.wikipedia.org/wiki/"),
                 (_(u"Dutch Wikipedia Article"),   "http://nl.wikipedia.org/wiki/"),
                 (_(u"French Wikipedia Article"),  "http://fr.wikipedia.org/wiki/"),
                 (_(u"German Wikipedia Article"),  "http://de.wikipedia.org/wiki/"),
                 (_(u"Galician Wikipedia Article"),  "http://gl.wikipedia.org/wiki/"),    
                 (_(u"Greek Wikipedia Article"), "http://el.wikipedia.org/wiki/"),
                 (_(u"Italian Wikipedia Article"), "http://it.wikipedia.org/wiki/"),
                 (_(u"Japanese Wikipedia Article"),"http://ja.wikipedia.org/wiki/"),
                 (_(u"Magyar Wikipedia Article"),"http://hu.wikipedia.org/wiki/"),
                 (_(u"Polish Wikipedia Article"),  "http://pl.wikipedia.org/wiki/"),
                 (_(u"Portugese Wikipedia Article"), "http://pt.wikipedia.org/wiki/"),
                 (_(u"Slovenian Wikipedia Article"), "http://sl.wikipedia.org/wiki/"),
                 (_(u"Spanish Wikipedia Article"), "http://es.wikipedia.org/wiki/"),
                 (_(u"Swedish Wikipedia Article"), "http://sv.wikipedia.org/wiki/"),
                 (_(u"Wikibooks Article"),         "http://en.wikibooks.org/wiki/"),
                 (_(u"Wikiversity"),         "http://en.wikiversity.org/wiki/"),
                 (_(u"Wiktionary"),         "http://en.wiktionary.org/wiki/"),
                 (_(u"Wikieducator Content"),      "http://wikieducator.org/"),
                 (_(u"Other"),                     "")]          

        this_package = None
        if self.idevice is not None and self.idevice.parentNode is not None:
            this_package = self.idevice.parentNode.package
        html += common.formField('select', this_package, _('Site'),'s',
                                 'site'+self.id,
                                 self.idevice.langInstruc,
                                 sites,
                                 self.idevice.site)

        
        url = "none"
        if self.idevice.site == "":
            url = "block"
        html += '<div style="display:%s"> %s: <br/>' % (url, _("Own site"))
        html += common.textInput("ownUrl"+self.id, self.idevice.ownUrl) + '<br/></div>'
        html += "<br/>"
        html += common.textInput("article", self.idevice.articleName)
        html += common.elementInstruc(self.idevice.searchInstruc)
        html += common.submitButton(u"loadWikipedia"+self.id, _(u"Load"))
        
        html += u"<br/>\n"
        html += self.articleElement.renderEdit()
        emphasisValues = [(_(u"No emphasis"),     Idevice.NoEmphasis),
                          (_(u"Some emphasis"),   Idevice.SomeEmphasis)]

        html += common.formField('select', this_package, _('Emphasis'),
                                 'emphasis', self.id, 
                                 '', # TODO: Instructions
                                 emphasisValues,
                                 self.idevice.emphasis)

        html += self.renderEditButtons(undo=self.idevice.undo)
        html += u"</div>\n"
        return html


    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        log.debug("renderPreview")    
        html = common.ideviceHeader(self, style, "preview")
        html += self.articleElement.renderPreview() 
        html += common.ideviceFooter(self, style, "preview")
        return html
    

    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """        
        log.debug("renderView")
        content = self.articleElement.renderView()
        # content = re.sub(r'src="resources/', 'src="', content)
        content = re.sub(r'src="http://127.0.0.1:\d+/newPackage.*/resources/', 'src="', content)
        content = re.sub(r'src="/newPackage.*/resources/', 'src="', content)
        content = re.sub(r'src=\'/newPackage.*/resources/', 'src="', content)
        content = re.sub(r'src=\"/newPackage.*/resources/', 'src="', content)
        html = common.ideviceHeader(self, style, "view")
        html += content        
        html += common.ideviceFooter(self, style, "view")
        return html
Beispiel #49
0
class QuestionElement(object):
    """
    QuestionElement is responsible for a block of question. 
    Used by MultichoiceBlock CasestudyBlock.
    """
    def __init__(self, index, idevice, question):
        """
        Initialize
        'index' is our number in the list of questions
        'idevice' is a case study idevice
        'question' is a exe.engine.casestudyidevice.Question instance
        """
        self.index        = index
        self.id           = "q" + unicode(index) + "b" + idevice.id        
        self.idevice      = idevice
        self.quesId       = "quesQuestion" + unicode(index) + "b" + idevice.id
        self.feedbackId   = "quesFeedback" + unicode(index) + "b" + idevice.id
        self.question     = question
        if question.questionTextArea.idevice is None: 
            question.questionTextArea.idevice = idevice 
        if question.feedbackTextArea.idevice is None: 
            question.feedbackTextArea.idevice = idevice
        self.question_question = TextAreaElement(question.questionTextArea)
        self.question_question.id = self.quesId 
        self.question_feedback = TextAreaElement(question.feedbackTextArea)
        self.question_feedback.id = self.feedbackId 
    def process(self, request):
        """
        Process arguments from the web server.  Return any which apply to this
        element.
        """
        log.debug("process " + repr(request.args))
        if self.quesId in request.args:
            self.question_question.process(request)
        if self.feedbackId in request.args:
            self.question_feedback.process(request)
        if "action" in request.args and request.args["action"][0] == self.id:
            for q_field in self.question.getRichTextFields():
                 q_field.ReplaceAllInternalAnchorsLinks()  
                 q_field.RemoveAllInternalLinks()  
            self.idevice.questions.remove(self.question)
            self.idevice.undo = False
    def renderEdit(self):
        """
        Returns an XHTML string for editing this question element
        """
        html  = "<tr><td><b>%s</b>\n" % _("Activity")
        html += common.elementInstruc(self.idevice.questionInstruc)
        html += self.question_question.renderEdit()
        html += "<b>%s</b>\n" % _("Feedback")
        html += common.elementInstruc(self.idevice.feedbackInstruc)
        html += self.question_feedback.renderEdit()
        html += "</td><td>\n"
        html += common.submitImage(self.id, self.idevice.id, 
                                   "/images/stock-cancel.png",
                                   _("Delete question"))
        html += "</td></tr>\n"
        return html
    def doRender(self, preview=False):
        """
        Returns an XHTML string for viewing and previewing this question element
        depending on the value of 'preview'.
        """
        log.debug("renderView called")
        if preview: 
            html  = self.question_question.renderPreview()
        else:
            html  = self.question_question.renderView()
        if  self.question_feedback.field.content != "" :            
            html += '<div id="view%s" style="display:block;">' % self.id
            html += common.feedbackButton('btnshow' + self.id,
                        _(u"Show Feedback"),
                        onclick = "showAnswer('%s',1)" % self.id)
            html += '</div>'
            html += '<div id="hide%s" style="display:none;">' % self.id
            html += common.feedbackButton('btnhide' + self.id,
                        _(u"Hide Feedback"),
                        onclick = "showAnswer('%s',0)" % self.id)
            html += '<p>'
            html += '</p>'
            html += '</div>'
            html += '<div id="s%s" class="feedback" style=" ' % self.id
            html += 'display: none;">'
            if preview: 
                html  += self.question_feedback.renderPreview() 
            else: 
                html  += self.question_feedback.renderView()
            html += "</div><br/>\n"
        else:
            html += "<br/>\n"
        return html
    def renderView(self):
        """
        Returns an XHTML string for viewing this question element
        """
        return self.doRender(preview=False)
    def renderPreview(self):
        """
        Returns an XHTML string for previewing this question element
        """
        return self.doRender(preview=True)
Beispiel #50
0
class WikipediaBlock(Block):
    """
    WikipediaBlock can render and process WikipediaIdevices as XHTML
    """
    def __init__(self, parent, idevice):
        """
        Initialize
        """
        Block.__init__(self, parent, idevice)
        self.articleElement = TextAreaElement(idevice.article)
        self.articleElement.height = 300
    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        log.debug("process " + repr(request.args))
        fieldNames = ['emphasis', 'site']
        fieldMap = [(field, field + self.id) for field in fieldNames]
        for attr, fieldName in fieldMap:
            if fieldName in request.args:
                setattr(self.idevice, attr, request.args[fieldName][0])
        if 'loadWikipedia'+self.id in request.args:
            self.idevice.loadArticle(request.args['article'][0])
        else:
            Block.process(self, request)
            if (u"action" not in request.args or
                request.args[u"action"][0] != u"delete"):
                self.articleElement.process(request)
    def renderEdit(self, style):
        """
        Returns an XHTML string with the form elements for editing this block
        """
        log.debug("renderEdit")
        html  = u"<div class=\"iDevice\"><br/>\n"
        html += common.textInput("title" + self.id, self.idevice.title)
        sites = [(_(u"English Wikipedia Article"), "http://en.wikipedia.org/"),
                 (_(u"Chinese Wikipedia Article"), "http://zh.wikipedia.org/"),
                 (_(u"German Wikipedia Article"),  "http://de.wikipedia.org/"),
                 (_(u"French Wikipedia Article"),  "http://fr.wikipedia.org/"),
                 (_(u"Japanese Wikipedia Article"),"http://ja.wikipedia.org/"),
                 (_(u"Italian Wikipedia Article"), "http://il.wikipedia.org/"),
                 (_(u"Polish Wikipedia Article"),  "http://pl.wikipedia.org/"),
                 (_(u"Dutch Wikipedia Article"),   "http://nl.wikipedia.org/"),
                 (_(u"Portugese Wikipedia Article"),
                                                   "http://pt.wikipedia.org/"),
                 (_(u"Spanish Wikipedia Article"), "http://es.wikipedia.org/"),
                 (_(u"Swedish Wikipedia Article"), "http://sv.wikipedia.org/"),
                 (_(u"Wikibooks Article"),         "http://en.wikibooks.org/"),
                 (_(u"Wikieducator Content"),      "http://wikieducator.org/")]
        html += common.formField('select', _('Site'),
                                 'site'+self.id, '',
                                 self.idevice.langInstruc,
                                 sites,
                                 self.idevice.site)
        html += common.textInput("article", self.idevice.articleName)
        html += common.elementInstruc(self.idevice.searchInstruc)
        html += common.submitButton(u"loadWikipedia"+self.id, _(u"Load"))
        html += u"<br/>\n"
        html += self.articleElement.renderEdit()
        emphasisValues = [(_(u"No emphasis"),     Idevice.NoEmphasis),
                          (_(u"Some emphasis"),   Idevice.SomeEmphasis),
                          (_(u"Strong emphasis"), Idevice.StrongEmphasis)]
        html += common.formField('select', _('Emphasis'),
                                 'emphasis'+self.id, '',
                                 '', # TODO: Instructions
                                 emphasisValues,
                                 self.idevice.emphasis)
        html += self.renderEditButtons()
        html += u"</div>\n"
        return html
    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        log.debug("renderPreview")
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\" "
        html += u"ondblclick=\"submitLink('edit',"+self.id+", 0);\">\n"
        if self.idevice.emphasis != Idevice.NoEmphasis:
            if self.idevice.icon:
                html += u'<img alt="idevice icon" class="iDevice_icon" '
                html += u" src=\"/style/"+style
                html += "/icon_"+self.idevice.icon+".gif\"/>\n"
            html += u"<span class=\"iDeviceTitle\">"
            html += self.idevice.title
            html += u"</span>\n"
            html += u"<div class=\"iDevice_inner\">\n"
        html += self.articleElement.renderPreview()
        html += u"<br/>\n"
        html += u"This article is licensed under the "
        html += u'<span style="text-decoration: underline;">GNU Free Documentation License</span>. It uses material '
        html += u'from the <span style="text-decoration: underline;">article '
        html += u'"%s"</span>.<br/>\n' % self.idevice.articleName
        html += self.renderViewButtons()
        if self.idevice.emphasis != Idevice.NoEmphasis:
            html += u"</div></div>\n"
        else:
            html += u"</div>\n"
        return html
    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """        
        log.debug("renderView")
        content = self.articleElement.renderView()
        content = re.sub(r'src="/.*?/resources/', 'src="', content)
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\">\n"
        if self.idevice.emphasis != Idevice.NoEmphasis:
            if self.idevice.icon:
                html += u'<img alt="iDevice icon" class="iDevice_icon" '
                html += u" src=\"icon_"+self.idevice.icon+".gif\"/>\n"
            html += u"<span class=\"iDeviceTitle\">"
            html += self.idevice.title
            html += u"</span>\n"
            html += u"<div class=\"iDevice_inner\">\n"
        html += content
        html += u"<br/>\n"
        html += _(u"This article is licensed under the ")
        html += u"<a "
        html += u"href=\"javascript:window.open('fdl.html')\">"
        html += u"%s</a>. " % _(u"GNU Free Documentation License")
        html += _(u"It uses material from the ")
        html += u"<a href=\""+self.idevice.site+u"wiki/"
        html += self.idevice.articleName+u"\">"
        html += _(u"article ") + u"\""+self.idevice.articleName+u"\"</a>.<br/>\n"
        if self.idevice.emphasis != Idevice.NoEmphasis:
            html += u"</div></div>\n"
        else:
            html += u"</div>\n"
        return html
class MultimediaBlock(Block):
    """
    ImageWithTextBlock can render and process ImageWithTextIdevices as XHTML
    """

    name = 'MultimediaWithText'

    def __init__(self, parent, idevice):
        """
        Initialize
        """
        Block.__init__(self, parent, idevice)
        self.mediaElement = MultimediaElement(idevice.media)

        # to compensate for the strange unpickling timing when objects are
        # loaded from an elp, ensure that proper idevices are set:
        # (only applies to the image-embeddable ones, not MultimediaElement)
        if idevice.text.idevice is None:
            idevice.text.idevice = idevice
        self.textElement = TextAreaElement(idevice.text)

    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        log.debug("process " + repr(request.args))
        Block.process(self, request)

        if (u"action" not in request.args
                or request.args[u"action"][0] != u"delete"):
            self.mediaElement.process(request)
            self.textElement.process(request)

        if 'emphasis' + self.id in request.args:
            self.idevice.emphasis = int(request.args['emphasis' + self.id][0])

        if "float" + self.id in request.args:
            self.idevice.float = request.args["float" + self.id][0]

        if "title" + self.id in request.args:
            self.idevice.title = request.args["title" + self.id][0]

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form elements for editing this block
        """
        log.debug("renderEdit")
        html = u"<div class=\"iDevice\">\n"
        html += common.textInput("title" + self.id,
                                 self.idevice.title) + '<br/><br/>'
        html += self.mediaElement.renderEdit()
        floatArr = [[_(u'Left'), 'left'], [_(u'Right'), 'right'],
                    [_(u'None'), 'none']]

        this_package = None
        if self.idevice is not None and self.idevice.parentNode is not None:
            this_package = self.idevice.parentNode.package
        html += common.formField('select', this_package, _("Align:"),
                                 "float" + self.id, '',
                                 self.idevice.alignInstruc, floatArr,
                                 self.idevice.float)
        #html += u'<div class="block">' #<b>%s</b></div>' % _(u"Caption:")
        #html += common.textInput("caption" + self.id, self.idevice.media.caption)
        #html += common.elementInstruc(self.idevice.media.captionInstruc)
        html += "<br/>" + self.textElement.renderEdit()
        emphasisValues = [(_(u"No emphasis"), Idevice.NoEmphasis),
                          (_(u"Some emphasis"), Idevice.SomeEmphasis)]

        html += common.formField(
            'select',
            this_package,
            _('Emphasis'),
            'emphasis',
            self.id,
            '',  # TODO: Instructions
            emphasisValues,
            self.idevice.emphasis)
        html += self.renderEditButtons()
        html += u"</div>\n"
        return html

    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        log.debug("renderPreview")
        html = u"\n<!-- MP3 iDevice -->\n"
        html += u"<div class=\"iDevice "
        html += u"emphasis" + unicode(self.idevice.emphasis) + "\" "
        html += "ondblclick=\"submitLink('edit'," + self.id + ", 0);\">\n"
        if self.idevice.emphasis != Idevice.NoEmphasis:
            if self.idevice.icon:
                html += u'<img alt="idevice icon" class="iDevice_icon" '
                html += u" src=\"/style/" + style
                html += "/icon_" + self.idevice.icon + ".gif\"/>\n"
            html += u"<span class=\"iDeviceTitle\">"
            html += self.idevice.title
            html += u"</span>\n"
        html += u"<div class=\"iDevice_inner\"> "
        html += u"<div class=\"media\">\n"
        html += self.mediaElement.renderPreview() + "</div>\n"
        # html += u"<br />" + self.idevice.media.caption + "</div>\n"
        html += self.textElement.renderPreview()
        html += u"<br/>\n"
        html += u"<div style=\"clear:both;\">"
        html += u"</div></div>\n"
        html += self.renderViewButtons()
        html += u"</div>\n"
        return html

    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        log.debug("renderView")
        html = u"\n<!-- MP3 iDevice -->\n"
        html += u"<div class=\"iDevice "
        html += u"emphasis" + unicode(self.idevice.emphasis) + "\">\n"
        if self.idevice.emphasis != Idevice.NoEmphasis:
            if self.idevice.icon:
                html += u'<img alt="idevice icon" class="iDevice_icon" '
                html += u' src="icon_' + self.idevice.icon + '.gif"/>\n'
            html += u"<span class=\"iDeviceTitle\">"
            html += self.idevice.title
            html += u"</span>\n"
        html += u"<div class=\"iDevice_inner\"> "
        html += u"<div class=\"media\">\n" + "</div>"
        html += self.mediaElement.renderView()
        # html += u"<br/>" + self.idevice.media.caption + "</div>"
        html += self.textElement.renderView()
        html += u"<div style=\"clear:both;\">"
        html += u"</div></div>\n"
        html += u"</div>\n"
        return html
class OrientacionesalumnadofpdBlock(Block):

    def __init__(self, parent, idevice):
        """
        Initialize a new Block object
        """
        Block.__init__(self, parent, idevice)
        self.activityInstruc = idevice.activityInstruc

        # to compensate for the strange unpickling timing when objects are 
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.activityTextArea.idevice is None: 
            idevice.activityTextArea.idevice = idevice

        self.activityElement  = TextAreaElement(idevice.activityTextArea)

        self.previewing        = False # In view or preview render

        if not hasattr(self.idevice,'undo'): 
            self.idevice.undo = True

    def process(self, request):
        """
        Process the request arguments from the web server
        """
        Block.process(self, request)

        is_cancel = common.requestHasCancel(request)

        if not is_cancel:
            self.activityElement.process(request)
            if "title"+self.id in request.args:
                self.idevice.title = request.args["title"+self.id][0]
        

    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        html  = "<div class=\"iDevice\"><br/>\n"

        # JR
	# Quitamos el prefijo "FPD -"
	if self.idevice.title.find("FPD - ") == 0:
		self.idevice.title = x_(u"Orientaciones para el alumnado")

        html += common.textInput("title"+self.id, self.idevice.title)
        html += self.activityElement.renderEdit()
        html += "<br/>" + self.renderEditButtons()
        html += "</div>\n"
        return html

    def renderPreview(self, style):
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """ 
        self.previewing = True 
        return Block.renderPreview(self, style)

    def renderView(self, style): 
        """ 
        Remembers if we're previewing or not, 
        then implicitly calls self.renderViewContent (via Block.renderPreview) 
        """ 
        self.previewing = False 
        return Block.renderView(self, style)

    def renderViewContent(self):
        """
        Returns an XHTML string for this block
        """
#        html = u'<script type="text/javascript" src="common.js"></script>\n'
#        html += u'<div class="iDevice_inner">\n'
	html = u'<div class="iDevice_inner">\n'
    
        if self.previewing: 
            html += self.activityElement.renderPreview()
        else:
            html += self.activityElement.renderView()

        html += "</div>\n"
        return html
Beispiel #53
0
class HangmanBlockInc(Block):
    """
    ExampleBlock can render and process ExampleIdevices as XHTML
    GenericBlock will replace it..... one day
    """
    def __init__(self, parent, idevice):
        Block.__init__(self, parent, idevice)
        self.titleElement = TextElement(idevice.titleField)
        self.contentElement = TextAreaElement(idevice.content)
        self.contentElement.height = 250
        self.chanceImageElements = []

        #go through all image fields in the list and create an image element linked to that field
        for chanceImageField in idevice.chanceImageFields:
            newImgElement = ImageElement(chanceImageField)
            self.chanceImageElements.append(newImgElement)

        self.wordElements = []
        self.hintElements = []
        #go through all of the word fields and hint fields and create an 
        for wordIndex, word in enumerate(idevice.wordTextFields):
            newWordElement = TextElement(word)
            self.wordElements.append(newWordElement)
            newHintElement = TextElement(idevice.hintTextFields[wordIndex])
            self.hintElements.append(newHintElement)

        #make an element for the alphabet
        self.alphabetElement = TextElement(idevice.alphabet)

        #element for the messages that are shown to the player
        self.wrongGuessTextElement = TextAreaElement(self.idevice.wrongGuessMessageField)
        self.lostLevelTextElement = TextAreaElement(self.idevice.lostLevelMessageField)
        self.levelPassedTextElement = TextAreaElement(self.idevice.levelPasssedMessageField)
        self.gameWonTextElement = TextAreaElement(self.idevice.gameWonMessageField)
        
        self.letterButtonStyleElement = TextElement(self.idevice.letterButtonStyle)
        self.wrongLetterButtonStyleElement = TextElement(self.idevice.wrongLetterButtonStyle)
        self.rightLetterButtonStyleElement = TextElement(self.idevice.rightLetterButtonStyle)

        self.hintFieldStyleElement = TextElement(self.idevice.hintFieldStyle)
        self.wordAreaStyleElement = TextElement(self.idevice.wordAreaStyle)

        self.resetButtonTextElement = TextElement(self.idevice.resetButtonText)
        self.resetButtonStyleElement = TextElement(self.idevice.resetButtonStyle)
            

    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        
        #Make sure that we don't do anything when it's time to die...
        Block.process(self, request)
        self.idevice.message = ""
        
        if field_engine_is_delete_request(request):
            return
        
        self.idevice.addGameScript()

        self.titleElement.process(request)
        self.idevice.title = self.titleElement.renderView()
        self.alphabetElement.process(request)
        self.wrongGuessTextElement.process(request)
        self.lostLevelTextElement.process(request)
        self.levelPassedTextElement.process(request)
        self.gameWonTextElement.process(request)

        self.letterButtonStyleElement.process(request)
        self.wrongLetterButtonStyleElement.process(request)
        self.rightLetterButtonStyleElement.process(request)
        self.hintFieldStyleElement.process(request)
        self.wordAreaStyleElement.process(request)

        self.resetButtonTextElement.process(request)
        self.resetButtonStyleElement.process(request)
        
        #see if we need to delete a word
        blankWords = False
        for wordIndex in range(0, len(self.wordElements)):
            if self.wordElements[wordIndex].renderView() == "":
                blankWords = True
            elif self.hintElements[wordIndex].renderView() == "":
                blankWords = True
        
        if blankWords is True:
            self.idevice.message = _("One or more words or hints are blank.  Please do not have any blank hints or words - you can delete unused ones.")
            self.idevice.edit = True
        
        
        #see if we need to add another chance
        if ("addChance"+unicode(self.id)) in request.args: 
            self.idevice.addChance()
            self.idevice.edit = True
            # disable Undo once a question has been added:
            self.idevice.undo = False
        
        if("addWord"+unicode(self.id)) in request.args:
            self.idevice.addWord()
            self.idevice.edit = True
            self.idevice.undo = False

        content = self.contentElement.process(request)
        for imgElement in self.chanceImageElements:
            imgElement.process(request)
            if "action" in request.args and request.args["action"][0] == imgElement.id:
                self.idevice.chanceImageFields.remove(imgElement.field)
                imgElement.field.idevice.undo = False
                imgElement.field.idevice.edit = True
            

        for wordElement in self.wordElements:
            wordElement.process(request)
            if "action" in request.args and request.args["action"][0] == wordElement.id:
                wordIdx = self.wordElements.index(wordElement)
                self.idevice.wordTextFields.remove(wordElement.field)
                self.idevice.hintTextFields.remove(self.hintElements[wordIdx].field)
                wordElement.field.idevice.undo = False
                wordElement.field.idevice.edit = True
        
        for hintElement in self.hintElements:
            hintElement.process(request)

        if content:
            self.idevice.content = content

    #
    # Get an TextArea render back according to mode
    def _renderHTMLElement(self, mode, element, containerId = None):
        retVal = ""
        idStr = ""
        if containerId is not None:
            idStr = " id='%s' " % containerId
        retVal += "<div %s >" % idStr
        if mode == "preview":
            retVal += element.renderPreview()
        else:
            retVal += element.renderView()
        
        retVal += "</div>"
        return retVal
    #
    # This will generate the HTML elements and javascript that will be required
    # for this to be shown as a Javascript game in the web browser
    # 
    def _renderGame(self, style, mode = "view"):
        hangmanGameId = "hangman" + self.id
        
        resPath = ""
        if mode ==  "preview":
            resPath = "resources/"       
        
        html = u"<script src='" + resPath + "hangman.js' type='text/javascript'></script>\n"
        html += common.ideviceHeader(self, style, mode)
        html += "<div id='hangman%(gameId)smessageStore' style='display: none'>" % {"gameId" : hangmanGameId}
        html += self._renderHTMLElement(mode, self.wrongGuessTextElement, "hmwrong" + hangmanGameId)
        html += self._renderHTMLElement(mode, self.lostLevelTextElement, "hmlost" + hangmanGameId)
        html += self._renderHTMLElement(mode, self.levelPassedTextElement, "hmpassed" + hangmanGameId)
        html += self._renderHTMLElement(mode, self.gameWonTextElement, "hmwon" + hangmanGameId)
        
        html += "</div>"
        html += u"<script type='text/javascript'>\n"

        #Go through the images and find out the max height and maxwidth
        imgMaxHeight = 0
        imgMaxWidth = 0

        for imgElement in self.chanceImageElements:
            if imgElement.field.imageResource and imgElement.field.imageResource is not None:
                if(int(imgElement.field.width) > imgMaxWidth):
                    imgMaxWidth = int(imgElement.field.width)

                if(imgElement.field.height > imgMaxHeight):
                    imgMaxHeight = int(imgElement.field.height)
        

        #Makes a javascript array of the list of words that the user has given
        html += "hangman_words['%s'] = new Array();\n" % hangmanGameId
        html += "hangman_buttonStyles['%s'] = new Array();\n" % hangmanGameId
        for wordIndex, word in enumerate(self.wordElements):
            html += u"hangman_words['%(gameId)s'][%(index)d] = new Array('%(word)s', '%(hint)s');\n" % \
                {"index" : wordIndex, "word" : word.renderView(), \
                "hint" : self.hintElements[wordIndex].renderView(), \
                "gameId" : hangmanGameId }
        
        #make the style for the buttons
        html += "hangman_buttonStyles['%(gameId)s'][HANGMAN_BEFORE_GUESS] = \"%(style)s\";\n" \
                % {"gameId" : hangmanGameId, "style" : self.letterButtonStyleElement.renderView()}
        html += "hangman_buttonStyles['%(gameId)s'][HANGMAN_CORRECT_GUESS] = \"%(style)s\";\n" \
                % {"gameId" : hangmanGameId, "style" : self.rightLetterButtonStyleElement.renderView()}
        html += "hangman_buttonStyles['%(gameId)s'][HANGMAN_WRONG_GUESS] = \"%(style)s\";\n" \
                % {"gameId" : hangmanGameId, "style" : self.wrongLetterButtonStyleElement.renderView()}

        #Makes a javscript string of the alphabet that the user can guess from
        html += u"hangman_alphabet['%(gameId)s'] = '%(alphabet)s';\n" % \
        {"alphabet" : self.alphabetElement.renderView(), \
        "gameId" : hangmanGameId }

        #Makes an array of the ids of the divs that hold the chance images
        html += u"hangman_chanceimgids['%s'] = new Array();\n" % hangmanGameId
        for imgIndex, imgElement in enumerate(self.chanceImageElements):
            html += "hangman_chanceimgids['%(gameId)s'][%(index)d] = '%(imgdivid)s';\n" % \
                {"index" : imgIndex, "imgdivid" : "hangman" + self.id + "img" + imgElement.id, \
                "gameId" : hangmanGameId }

        #Make the messages for this game
        html += u"playerMessages['%s'] = new Array();\n" % hangmanGameId
        
        
        
        messagesStr = """
        
        playerMessages['%(gameid)s']['wrongguess'] = 
            document.getElementById('hmwrong%(gameid)s').innerHTML;
        playerMessages['%(gameid)s']['lostlevel'] =
            document.getElementById('hmlost%(gameid)s').innerHTML;
        playerMessages['%(gameid)s']['levelpassed'] = 
            document.getElementById('hmpassed%(gameid)s').innerHTML;
        playerMessages['%(gameid)s']['gamewon'] = 
            document.getElementById('hmwon%(gameid)s').innerHTML;
        </script>
        """ % {"gameid" : hangmanGameId }
        
        html += messagesStr
        

        html += "<div id='hangman" + self.id + "_img'>"
        #render view of these images
        for imgElement in self.chanceImageElements:
            if imgElement.field.imageResource and imgElement.field.imageResource is not None:
                html += "<div id='hangman" + self.id + "img" + imgElement.id + "' style='display: none'>"
            
                if mode == "view":
                    html += imgElement.renderView()
                else:       
                    html += imgElement.renderPreview()
                html += "</div>"
       
        html += "</div>"

        messageTopMargin = (imgMaxHeight - 30) / 2
        gameWidth = max(600, imgMaxWidth)
        gameAreaHTML = """
<div id="%(gameId)s_gamearea" style='width: %(width)dpx;' class='exehangman_gamearea'>
        <div class='exehangman_alertarea' id="%(gameId)s_alertarea" style='position: absolute; z-index: 10; text-align: center; border: 1px; background-color: white; width: %(width)dpx; margin-top: %(messagetopmargin)dpx; visibility: hidden'>
        &#160;
        </div>
        <div id="%(gameId)s_imgarea" style='height: %(height)dpx; z-index: 1;' class='exehangman_imgarea'>
        </div>

        <input type='text' style='%(hintStyle)s' id='%(gameId)s_hintarea' style='width: %(width)dpx' class='exehangman_hintarea'/>
        <input type='text' style='%(wordStyle)s' id='%(gameId)s_wordarea' style='width: %(width)dpx' class='exehangman_wordarea'/>
        <div id="%(gameId)s_letterarea" class='exehangman_letterarea'>
        </div>
        <input class='exehangman_resetbutton' type='button' value='%(resetText)s' style='%(resetStyle)s' onclick='restartLevel("%(gameId)s")'/>
</div>

        """ % { "gameId" : hangmanGameId, "width" : gameWidth, "height": imgMaxHeight, \
                "messagetopmargin" : messageTopMargin, 'hintStyle' : self.hintFieldStyleElement.renderView(), \
                'wordStyle' : self.wordAreaStyleElement.renderView(), 'resetText' : self.resetButtonTextElement.renderView(), \
                'resetStyle' : self.resetButtonStyleElement.renderView() }
        html += gameAreaHTML
        html += "<script type='text/javascript'>setupGame('%s');</script>" % hangmanGameId

        return html



    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        html  = u"<div>\n"
        html += common.ideviceShowEditMessage(self)
        
        
        html += self.titleElement.renderEdit()
        html += self.contentElement.renderEdit()
        html += self.alphabetElement.renderEdit()

        #messages to show the user for different events
        html += self.wrongGuessTextElement.renderEdit()
        html += self.lostLevelTextElement.renderEdit()
        html += self.levelPassedTextElement.renderEdit()
        html += self.gameWonTextElement.renderEdit()
        html += self.resetButtonTextElement.renderEdit()

        divId = "fieldtype_advanced"  + self.id
        html += "<input name='showbox" + divId + "' type='checkbox' onchange='$(\"#" + divId + "\").toggle()'/>"
        
        html += _("Show Advanced Options") + "<br/>"
        html += "<div id='" + divId + "' style='display: none' "
        html += ">"
        
        #styles for buttons
        html += self.letterButtonStyleElement.renderEdit()
        html += self.wrongLetterButtonStyleElement.renderEdit()
        html += self.rightLetterButtonStyleElement.renderEdit()

        #style of the text fields
        html += self.hintFieldStyleElement.renderEdit()
        html += self.wordAreaStyleElement.renderEdit()

        html += self.resetButtonStyleElement.renderEdit()
        html += "</div>"
        
        #render edit of these images
        for imgElement in self.chanceImageElements:
            html += imgElement.renderEdit()
            html += common.submitImage(imgElement.id, imgElement.field.idevice.id, 
                                   "/images/stock-cancel.png",
                                   _("Remove This Life")) + "<br/>"

        addChanceButtonLabel = _("Add Chance")
        html += common.submitButton("addChance"+unicode(self.id), addChanceButtonLabel)
        html += "<br/>"

        #show words to be guessed
        html += _("<h2>Words to Guess</h2>")
        for wordIndex in range(0, len(self.wordElements)):
            word = self.wordElements[wordIndex]
            html += word.renderEdit()
            html += self.hintElements[wordIndex].renderEdit()
            html += "<br/>"
            if wordIndex > 0:
                html += common.submitImage(word.id, word.field.idevice.id, 
                                   "/images/stock-cancel.png",
                                   _("Remove This Word")) + "<br/>"
        
        html += common.submitButton("addWord"+unicode(self.id), _("Add Word"))        
        html += "<br/>"
        html += self.renderEditButtons()
        html += u"</div>\n"
        return html


    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\" "
        html += u"ondblclick=\"submitLink('edit',"+self.id+", 0);\">\n"
        html += self.contentElement.renderView()
        html += self._renderGame(style, mode = "preview")

        html += self.renderViewButtons()
        html += "</div>\n"
        return html

    def renderXML(self, style):
        xml = u""
        
        mediaConverter = ExportMediaConverter.getInstance()
        width = mediaConverter.getProfileWidth()
        height = mediaConverter.getProfileHeight()
        
        if mediaConverter is not None:
            for imgElement in  self.chanceImageElements:
                if imgElement.field.imageResource is not None:
                    mediaConverter.resizeImg(XMLPage.currentOutputDir/imgElement.field.imageResource.storageName, \
                         width, height, {}, {"resizemethod" : "stretch"})
        
        xml += "<idevice type='hangman' id='%s'>\n" % self.idevice.id
        xml += "<chanceimages>\n"
        for imgElement in  self.chanceImageElements:
            if imgElement.field.imageResource is not None:
                xml += "<img src='%s'/>\n" % imgElement.field.imageResource.storageName
            
        xml += "</chanceimages>\n"
        
        xml += "<alphabet>%s</alphabet>\n" % self.alphabetElement.renderView()
        xml += "<wrongguessmessage><![CDATA[ %s ]]></wrongguessmessage>\n" % self.wrongGuessTextElement.renderView()
        xml += "<lostlevelmessage><![CDATA[ %s ]]></lostlevelmessage>\n" % self.lostLevelTextElement.renderView()
        xml += "<levelpassedmessage><![CDATA[ %s ]]></levelpassedmessage>\n" % self.levelPassedTextElement.renderView()
        xml += "<gamewonmessage><![CDATA[ %s ]]></gamewonmessage>\n" % self.gameWonTextElement.renderView()
        
        xml += "<words>"
        for wordIndex in range(0, len(self.wordElements)):
            word = self.wordElements[wordIndex]
            if word != "":
                xml += "<word>\n<hint>%(hint)s</hint>\n<answer>%(answer)s</answer>\n</word>\n" \
                    % {"answer" : word.renderView() , "hint" : self.hintElements[wordIndex].renderView()}
            
        xml += "</words>\n"
        
        xml += "</idevice>\n"
        return xml


    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\">\n"
        html += self.contentElement.renderView()
        html += self._renderGame(style, mode = "view")
        html += u"</div>\n"
        return html
Beispiel #54
0
class TrueFalseBlock(Block):
    """
    TrueFalseBlock can render and process TrueFalseIdevices as XHTML
    """
    def __init__(self, parent, idevice):
        """
        Initialize a new Block object
        """
        Block.__init__(self, parent, idevice)
        self.idevice         = idevice
        self.questionElements  = []
        self.questionInstruc = idevice.questionInstruc
        self.keyInstruc      = idevice.keyInstruc
        self.feedbackInstruc = idevice.feedbackInstruc
        self.hintInstruc     = idevice.hintInstruc 
        if idevice.instructionsForLearners.idevice is None: 
            idevice.instructionsForLearners.idevice = idevice
        self.instructionElement = \
            TextAreaElement(idevice.instructionsForLearners)
        if not hasattr(self.idevice,'undo'):
            self.idevice.undo = True
        i = 0
        for question in idevice.questions:
            self.questionElements.append(TrueFalseElement(i, idevice, 
                                                           question))
            i += 1
    def process(self, request):
        """
        Process the request arguments from the web server
        """
        Block.process(self, request)
        is_cancel = common.requestHasCancel(request)
        self.instructionElement.process(request)
        if ("addQuestion"+unicode(self.id)) in request.args: 
            self.idevice.addQuestion()
            self.idevice.edit = True
            self.idevice.undo = False
        if "title"+self.id in request.args \
        and not is_cancel:
            self.idevice.title = request.args["title"+self.id][0]
        for element in self.questionElements:
            element.process(request)
        if ("action" in request.args and request.args["action"][0] == "done" 
        or not self.idevice.edit): 
            if hasattr(self.idevice,'undo'): 
                del self.idevice.undo
    def renderEdit(self, style):
        """
        Returns an XHTML string with the form element for editing this block
        """
        html  = u"<div class=\"iDevice\"><br/>\n"
        html += common.textInput("title"+self.id, self.idevice.title)
        html += u"<br/><br/>\n"
        html += self.instructionElement.renderEdit()
        for element in self.questionElements:
            html += element.renderEdit() 
        value = _(u"Add another question")    
        html += common.submitButton("addQuestion"+unicode(self.id), value)
        html += u"<br /><br />" + self.renderEditButtons(undo=self.idevice.undo)
        html += u"</div>\n"
        return html
    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\" "
        html += u"ondblclick=\"submitLink('edit',"+self.id+", 0);\">\n"
        html += u'<img alt="" class="iDevice_icon" '
        html += u"src=\"/style/"+style+"/icon_"+self.idevice.icon+".gif\" />\n"
        html += u"<span class=\"iDeviceTitle\">"       
        html += self.idevice.title+"</span><br/>\n"     
        html += u"<div class=\"iDevice_inner\">\n"
        html += self.instructionElement.renderPreview()
        for element in self.questionElements:
            html += element.renderQuestionPreview()
            html += element.renderFeedbackPreview()
        html += "</div>\n"    
        html += self.renderViewButtons()
        html += "</div>\n"
        return html
    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """
        html  = u'<script type="text/javascript" src="common.js"></script>\n'
        html += u'<script type="text/javascript" src="libot_drag.js"></script>'
        html += u"\n<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\">\n"
        html += u'<img alt="" class="iDevice_icon" '
        html += u"src=\"icon_"+self.idevice.icon+".gif\" />\n"
        html += u"<span class=\"iDeviceTitle\">"       
        html += self.idevice.title+"</span><br/>\n"
        html += u"<div class=\"iDevice_inner\">\n"
        html += self.instructionElement.renderView()
        for element in self.questionElements:
            html += "<div class=\"question\">\n"
            html += element.renderQuestionView()
            html += element.renderFeedbackView()
            html += "</div>\n"
        html += u"</div>\n"    
        html += u"</div>\n"
        return html
Beispiel #55
0
class TOCBlock(Block):
    """
    WikipediaBlock can render and process WikipediaIdevices as XHTML
    """
    def __init__(self, parent, idevice):
        """
        Initialize
        """
        Block.__init__(self, parent, idevice)

        # to compensate for the strange unpickling timing when objects are 
        # loaded from an elp, ensure that proper idevices are set:
        if idevice.article.idevice is None: 
            idevice.article.idevice = idevice
        self.articleElement = TextAreaElement(idevice.article)
        self.articleElement.height = 300
        if not hasattr(self.idevice,'undo'): 
            self.idevice.undo = True
        self.idevice.generateTOC()


    def process(self, request):
        """
        Process the request arguments from the web server to see if any
        apply to this block
        """
        log.debug("process " + repr(request.args))

        is_cancel = common.requestHasCancel(request)
        
        # If they hit "the tick" instead of "load"
        Block.process(self, request)
        if (u"action" not in request.args \
        or request.args[u"action"][0] != u"delete"):
            # If the text has been changed
            self.articleElement.process(request)
        if ("action" in request.args and request.args["action"][0] == "done" or not self.idevice.edit):
            if hasattr(self.idevice, 'undo'):
                del self.idevice.undo



           
    def renderEdit(self, style):
        """
        Returns an XHTML string with the form elements for editing this block
        """

        html = self.articleElement.renderEdit()
        html += self.renderEditButtons(undo=self.idevice.undo)
        html += u"</div>\n"
        return html


    def renderPreview(self, style):
        """
        Returns an XHTML string for previewing this block
        """
        log.debug("renderPreview")
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\" "
        html += u"ondblclick=\"submitLink('edit',"+self.id+", 0);\">\n"
        if self.idevice.emphasis != Idevice.NoEmphasis:
            if self.idevice.icon:
                html += u'<img alt="idevice icon" class="iDevice_icon" '
                html += u" src=\"/style/"+style
                html += "/icon_"+self.idevice.icon+".gif\"/>\n"
            html += u"<span class=\"iDeviceTitle\">"
            html += self.idevice.title
            html += u"</span>\n"
            html += u"<div class=\"iDevice_inner\">\n"
        html += self.articleElement.renderPreview()
        html += u"<br/>\n"
        html += self.renderViewButtons()
        if self.idevice.emphasis != Idevice.NoEmphasis:
            html += u"</div></div>\n"
        else:
            html += u"</div>\n"
        return html
    

    def renderView(self, style):
        """
        Returns an XHTML string for viewing this block
        """        
        log.debug("renderView")
        content = self.articleElement.renderView()
        content = re.sub(r'src="resources/', 'src="', content)
        html  = u"<div class=\"iDevice "
        html += u"emphasis"+unicode(self.idevice.emphasis)+"\">\n"

        if self.idevice.emphasis != Idevice.NoEmphasis:
            if self.idevice.icon:
                html += u'<img alt="iDevice icon" class="iDevice_icon" '
                html += u" src=\"icon_"+self.idevice.icon+".gif\"/>\n"
            html += u"<span class=\"iDeviceTitle\">"
            html += self.idevice.title
            html += u"</span>\n"
            html += u"<div class=\"iDevice_inner\">\n"
        html += content
        html += u"<br/>\n"
        if self.idevice.emphasis != Idevice.NoEmphasis:
            html += u"</div></div>\n"
        else:
            html += u"</div>\n"
        return html