Beispiel #1
0
def on_genbook_click(frame, href, url):
	if frame != guiconfig.mainfrm.genbooktext:
		frame = guiconfig.mainfrm.genbooktext

	if url is None:
		url = SW.URL(href)
	
	host = to_unicode(
		url.getHostName(),
		frame.reference.module
	)

	if host == "previous":
		frame.chapter_back()

	elif host == "next":
		frame.chapter_forward()

	elif host.startswith("parent"):
		frame.go_to_parent(int(host[6:]))
	
	else:
		key = TK(frame.book.mod.getKey(), frame.book.mod)
		path = to_unicode(
			url.getPath(),
			frame.reference.module
		)
		ref = u"/%s" % host
		if path:
			ref += "/%s" % path
		key.text = ref
		
		frame.go_to_key(key)
Beispiel #2
0
def on_genbook_click(frame, href, url):
    if frame != guiconfig.mainfrm.genbooktext:
        frame = guiconfig.mainfrm.genbooktext

    if url is None:
        url = SW.URL(href)

    host = to_unicode(url.getHostName(), frame.reference.module)

    if host == "previous":
        frame.chapter_back()

    elif host == "next":
        frame.chapter_forward()

    elif host.startswith("parent"):
        frame.go_to_parent(int(host[6:]))

    else:
        key = TK(frame.book.mod.getKey(), frame.book.mod)
        path = to_unicode(url.getPath(), frame.reference.module)
        ref = u"/%s" % host
        if path:
            ref += "/%s" % path
        key.text = ref

        frame.go_to_key(key)
Beispiel #3
0
def on_sword_hover(frame, href, url, element, x, y):
	tooltip_config = TextTooltipConfig("", mod=None)

	module = url.getHostName()
	key = SW.URL.decode(url.getPath()).c_str()
	
	f = find_frame(module)
	if f:
		mod = biblemgr.get_module(module)
		mod.KeyText(key)
		
		ref = to_unicode(mod.getKeyText(), mod)
		ref = f.format_ref(mod, ref)
		text = to_unicode(mod.RenderText(), mod)

		tooltip_config.module = mod
		tooltip_config.text = (u"%s (%s)<br>%s" % (
			ref, mod.Name(), text
		))
	else:
		tooltip_config.text = (
			_("The book '%s' is not installed, "
				"so you cannot view "
				"details for this entry (%s)") % (module, key.decode("utf8")))

	frame.show_tooltip(tooltip_config)
Beispiel #4
0
    def __init__(self, parent, book, key):
        super(PopupList, self).__init__(parent)
        self.book = book
        self.modules = book.GetModules()
        self.set_data(
            list(u"%s - %s" % (to_unicode(mod.Name(), mod),
                               to_unicode(mod.Description(), mod))
                 for mod in self.modules))
        for idx, item in enumerate(self.modules):
            if item == book.mod:
                self.EnsureVisible(idx)

        self.key = key
Beispiel #5
0
	def __init__(self, parent, book, key):
		super(PopupList, self).__init__(parent)
		self.book = book
		self.modules = book.GetModules()
		self.set_data(list(
			u"%s - %s" % (to_unicode(mod.Name(), mod), to_unicode(mod.Description(), mod))
			for mod in self.modules
		))
		for idx, item in enumerate(self.modules):
			if item == book.mod:
				self.EnsureVisible(idx)
		
		self.key = key
Beispiel #6
0
    def GetReference(self,
                     ref,
                     context=None,
                     max_verses=500,
                     stripped=False,
                     raw=False,
                     end_ref=None):
        if not self.mod:
            return None

        assert not end_ref, "Dictionaries don't support ranges"

        raw = raw or display_options.options["raw"]

        render_text, render_start, render_end = self.get_rendertext()
        #TODO: use render_start and render_end?

        template = self.templatelist[-1]
        key = self.mod.getKey()
        key.setText(to_str(ref, self.mod))
        self.mod.setKey(key)

        # We have to get KeyText after RenderText, otherwise our
        # KeyText will be wrong

        if stripped:
            text = self.mod.StripText().decode("utf-8", "replace")
        else:
            text = render_text().decode("utf-8", "replace")

        d = dict(
            # render text so that we convert utf-8 into html
            range=to_unicode(self.mod.getKeyText(), self.mod),
            description=to_unicode(self.mod.Description(), self.mod),
            version=self.mod.Name(),
            reference_encoded=SW.URL.encode(self.mod.getKeyText()).c_str(),
        )
        d["reference"] = self.format_ref(self.mod, d["range"], snap=False)
        verses = template.header.safe_substitute(d)

        d1 = d
        if raw:
            d1["text"] = self.process_raw(self.mod.getRawEntry(), text,
                                          self.mod.getKey(), self.mod)
        else:
            d1["text"] = text

        verses += template.body.safe_substitute(d1)

        verses += template.footer.safe_substitute(d)  #dictionary name
        return verses
def get_chapter_headings(chapter):
	"""Get chapter headings from the current Bible for a given chapter

	chapter must be a whole chapter reference, not a verse in the chapter
	Returns list of (VK, heading text)
	"""
	if biblemgr.bible.mod is None:
		return []

	version_headings = headings_cache.setdefault(biblemgr.bible.version, {})
	if chapter in version_headings:
		return version_headings[chapter]
		
	# put ourselves into a plain state
	biblemgr.temporary_state(biblemgr.plainstate)

	# and turn on headings
	biblemgr.set_option("Headings", True)

	vk = EncodedVK(("%s:0" % chapter, chapter), headings=True)

	mod = biblemgr.bible.mod
	headings = []
	for item in vk:	
		mod.setKey(item)
		content = to_unicode(mod.RenderText(), mod)

		# if it was in verse 0, link to verse 1 for now
		if item.Verse() == 0:
			item.Verse(1)
		
		hs = biblemgr.bible.get_headings(item.getText())

		# see comment in book.py for why we are checking if it starts with <
		# (short version - pre-verse div's)
		# try to handle pre-verse headings in div's
		content = '\n'.join(to_unicode(mod.RenderText(heading), mod)
			for heading, canonical in hs if heading.startswith("<")) + content
		
		# and non-div pre-verse headings
		headings += ((item, to_unicode(mod.RenderText(heading), mod))
			for heading, canonical in hs if not heading.startswith("<"))

		headings += ((item, text) for heading, text in re.findall(
			'(<h2 class="heading(?: canonical)?">(.*?)</h2>)', 
			content, re.U) if text)
		
	biblemgr.restore_state()
	version_headings[chapter] = headings
	return headings
Beispiel #8
0
	def find_index(self, mylist):
		"""Turn a sorted list of begin, end pairs into references using 
		the index"""
		if not mylist:
			return []
		
		module = self.load_module(self.version)		
		key = self.get_key(module)

		upto = 0
		begin, end = mylist[upto]
		ret = []
		for idx, (key_value, start, length) in enumerate(self.index):
			# find in index
			# mylist must be sorted
			while start + length >= begin:
				# loop here because search phrase may be
				# multiple times in one verse, so we get all
				n = 1

				# This loop tells us if we go over verse boundaries
				while (idx + n < len(self.index) and 
					self.index[idx + n][1] < begin + end):
					n += 1
	
				self.set_key(module, key, key_value)
				ref1 = to_unicode(key.getText(), module)

				if n > 1:
					self.set_key(module, key, self.index[idx+n-1][0])
					ref2 = to_unicode(key.getText(), module)
					ret.append("%s - %s" % (ref1, ref2))

				else:
					ret.append(ref1)
	
				upto += 1
				if upto >= len(mylist):
					return ret

				begin, end = mylist[upto]
		
		dprint(
			WARNING, 
			"Exceeded index length "
			"(this usually means 0 width match at the end of the text)", 
			mylist[upto]
		)
		return ret
	def _get_moduleinfo(self, module):
		rows = []
		name = u"%s - %s" % (module.Name(), to_unicode(module.Description(), module))
		default_items = (
			("Name", name),
			("Language", languages.get_language_description(module.Lang())),
			("License", self.get_formatted_config_entry(module, "DistributionLicense")),
			("Unlock", self.get_formatted_unlock_url(module)),
			("More", self.get_formatted_config_entry(module, "ShortPromo")),
			("About", self.get_formatted_config_entry(module, "About")),
		)
		for key, value in default_items:
			if value:
				rows.append('''
				<tr>
					<th class="module_information_key">%s</th>
					<td class="module_information_value">%s</td>
				</tr>''' % (key, value))

		html, javascript = self.add_additional_config_entries(module)
		rows.append(html)
		table = u"<table class='module_information'>%s</table>" % (''.join(rows))

		return self._get_html(module, table, stylesheets=["book_information_window.css"],
				scripts=PageProtocolHandler.standard_scripts, javascript_block=javascript)
    def _get_moduleinfo(self, module):
        rows = []
        name = u"%s - %s" % (module.Name(),
                             to_unicode(module.Description(), module))
        default_items = (
            ("Name", name),
            ("Language", languages.get_language_description(module.Lang())),
            ("License",
             self.get_formatted_config_entry(module, "DistributionLicense")),
            ("Unlock", self.get_formatted_unlock_url(module)),
            ("More", self.get_formatted_config_entry(module, "ShortPromo")),
            ("About", self.get_formatted_config_entry(module, "About")),
        )
        for key, value in default_items:
            if value:
                rows.append('''
				<tr>
					<th class="module_information_key">%s</th>
					<td class="module_information_value">%s</td>
				</tr>''' % (key, value))

        html, javascript = self.add_additional_config_entries(module)
        rows.append(html)
        table = u"<table class='module_information'>%s</table>" % (
            ''.join(rows))

        return self._get_html(module,
                              table,
                              stylesheets=["book_information_window.css"],
                              scripts=PageProtocolHandler.standard_scripts,
                              javascript_block=javascript)
Beispiel #11
0
    def process_raw(self,
                    text,
                    rendered_text,
                    key,
                    module,
                    headings=(),
                    option_filtered=""):
        kt = key.getOSISRefRangeText() or key.getText()
        kt = to_unicode(kt, module)
        if headings:
            headings = "<ul class='raw-headings'>%s</ul>" % ('\n'.join(
                "<li>%s</li>" % cgi.escape(heading) for heading in headings))
        else:
            headings = ""

        if option_filtered:
            option_filtered = "<pre class='raw-option-filtered'>%s</pre>" % cgi.escape(
                option_filtered.decode("utf-8", "replace"))
        return u"""
%s
<div class='debug-raw-details' key='%s'>
	<pre class='raw-rendered'>%s</pre>
	%s
	<pre class='raw'>%s</pre>
	%s
</div>""" % (rendered_text, cgi.escape(kt), cgi.escape(rendered_text),
             headings, cgi.escape(text.decode("utf-8",
                                              "replace")), option_filtered)
Beispiel #12
0
class LazyTopicList(object):
    # these are the sizes of entries in SWORD dictionaries. Dividing total
    # index length by entry size gives number of entries.
    entry_sizes = {SW.RawLD: 6, SW.RawLD4: 8, SW.zLD: 8}

    # how many items do we grab around the one we are asked for?
    # TODO: tune this value
    GRAB_AROUND = 10
    """Implement a lazy topic list. This precomputes its length, and caches
	any topics found"""
    def __init__(self, module):
        self.mod = module

        self.cardinality = 0
        self.entry_size = 0

        success = False
        try:
            success = self.read_entry_count()
        except Exception, e:
            dprint(WARNING, "Exception trying to read entry count", e)

        if not success:
            # Work this out the slow way
            topics = []
            self.mod.setPosition(TOP)

            while not ord(self.mod.Error()):
                try:
                    topics.append(to_unicode(self.mod.getKeyText(), self.mod))
                except UnicodeDecodeError, e:
                    dprint(WARNING, "Error on ", e)
                self.mod.increment(1)

            self.topics = topics
Beispiel #13
0
	def GetReference(self, ref, context = None, max_verses = 500,
			stripped=False, raw=False, end_ref=None):
		if not self.mod:
			return None

		assert not end_ref, "Dictionaries don't support ranges"

		raw = raw or display_options.options["raw"]

		render_text, render_start, render_end = self.get_rendertext()
		#TODO: use render_start and render_end?
		
		template = self.templatelist[-1]
		key = self.mod.getKey()
		key.setText(to_str(ref, self.mod))
		self.mod.setKey(key)
		
		# We have to get KeyText after RenderText, otherwise our
		# KeyText will be wrong
		
		if stripped:
			text = self.mod.StripText().decode("utf-8", "replace")
		else:
			text = render_text().decode("utf-8", "replace")
		
		d = dict(
			# render text so that we convert utf-8 into html
			range=to_unicode(self.mod.getKeyText(), self.mod),
			description=to_unicode(self.mod.Description(), self.mod),
			version=self.mod.Name(),
			reference_encoded=SW.URL.encode(self.mod.getKeyText()).c_str(),
			
		)
		d["reference"] = self.format_ref(self.mod, d["range"], snap=False)
		verses = template.header.safe_substitute(d)

		d1 = d
		if raw:
			d1["text"] = self.process_raw(self.mod.getRawEntry(), text,
											self.mod.getKey(), self.mod)
		else:
			d1["text"] = text

		verses += template.body.safe_substitute(d1)

		verses += template.footer.safe_substitute(d) #dictionary name
		return verses
Beispiel #14
0
    def find_index(self, mylist):
        """Turn a sorted list of begin, end pairs into references using 
		the index"""
        if not mylist:
            return []

        module = self.load_module(self.version)
        key = self.get_key(module)

        upto = 0
        begin, end = mylist[upto]
        ret = []
        for idx, (key_value, start, length) in enumerate(self.index):
            # find in index
            # mylist must be sorted
            while start + length >= begin:
                # loop here because search phrase may be
                # multiple times in one verse, so we get all
                n = 1

                # This loop tells us if we go over verse boundaries
                while (idx + n < len(self.index)
                       and self.index[idx + n][1] < begin + end):
                    n += 1

                self.set_key(module, key, key_value)
                ref1 = to_unicode(key.getText(), module)

                if n > 1:
                    self.set_key(module, key, self.index[idx + n - 1][0])
                    ref2 = to_unicode(key.getText(), module)
                    ret.append("%s - %s" % (ref1, ref2))

                else:
                    ret.append(ref1)

                upto += 1
                if upto >= len(mylist):
                    return ret

                begin, end = mylist[upto]

        dprint(
            WARNING, "Exceeded index length "
            "(this usually means 0 width match at the end of the text)",
            mylist[upto])
        return ret
Beispiel #15
0
    def add_module(self, tree_item, module, inactive_description=""):
        if self.hide_module(module):
            return

        text = "%s - %s" % (module.Name(), to_unicode(module.Description(), module))

        if biblemgr.all_modules[module.Name()] != module:
            text += inactive_description

        tree_item.add_child(text, data=module)
Beispiel #16
0
	def snap_text(self, text, module=None):
		mod = module or self.mod
		if mod is None:
			return text
		k = mod.getKey()
		k.setText(to_str(text, mod))
		mod.setKey(k)
		
		# snap to entry
		mod.getRawEntryBuf()
		return to_unicode(mod.getKeyText(), mod)
Beispiel #17
0
    def add_module(self, tree_item, module, inactive_description=""):
        if self.hide_module(module):
            return

        text = "%s - %s" % (module.Name(),
                            to_unicode(module.Description(), module))

        if biblemgr.all_modules[module.Name()] != module:
            text += inactive_description

        tree_item.add_child(text, data=module)
Beispiel #18
0
    def snap_text(self, text, module=None):
        mod = module or self.mod
        if mod is None:
            return text
        k = mod.getKey()
        k.setText(to_str(text, mod))
        mod.setKey(k)

        # snap to entry
        mod.getRawEntryBuf()
        return to_unicode(mod.getKeyText(), mod)
Beispiel #19
0
	def chapter_move(self, amount):
		mod = self.book.mod
		if not mod:
			return

		key = mod.getKey()
		key.Persist(1)
		key.setText(to_str(self.reference, mod))
		mod.setKey(key)
		mod.increment(amount);
		ref = to_unicode(mod.getKeyText(), mod)
		self.notify(ref, source=events.CHAPTER_MOVE)
Beispiel #20
0
    def chapter_move(self, amount):
        mod = self.book.mod
        if not mod:
            return

        key = mod.getKey()
        key.Persist(1)
        key.setText(to_str(self.reference, mod))
        mod.setKey(key)
        mod.increment(amount)
        ref = to_unicode(mod.getKeyText(), mod)
        self.notify(ref, source=events.CHAPTER_MOVE)
Beispiel #21
0
def on_sword_opened(frame, href, url):
    module = url.getHostName()
    key = SW.URL.decode(url.getPath()).c_str()
    frame = find_frame(module)
    if not frame:
        return

    guiconfig.mainfrm.set_module(module, frame.book)

    frame.SetReference_from_string(to_unicode(
        key,
        frame.book.mod,
    ))
Beispiel #22
0
	def update_preview(self):
		if self.mod is None:
			self.preview.SetPage(config.MODULE_MISSING_STRING())
			return

		try:
			for frame in guiconfig.mainfrm.frames:
				book = frame.book
				if self.mod.Name() not in book.GetModuleList():
					continue

				# if we are already set to that book, use it
				### should we get a better key here?
				if self.mod == frame.mod or True:
					if isinstance(frame.reference, basestring):
						ref = frame.reference
					else:
						ref = frame.reference.text
						
				self.mod.KeyText(to_str(ref, self.mod))
				
				text = self.mod.RenderText()
				# if there is no text here, look back and forth for text
				if not text:
					old = self.mod.getSkipConsecutiveLinks()
					self.mod.setSkipConsecutiveLinks(True)
					
					for direction in 1, -1:
						self.mod.increment(direction)
						text = self.mod.RenderText()
						if text:
							break
					
					self.mod.setSkipConsecutiveLinks(old)

				ref = to_unicode(self.mod.getKeyText(), self.mod)
				ref = frame.format_ref(self.mod, ref)
				preview_text = u'%s (%s)<br>%s' % (
					ref, self.mod.Name().decode("utf8"), text.decode("utf8")
				)
				preview_text = u'<span style="font-family: %s; font-size: %spt;">%s</span>' % \
						(self.font_face.StringSelection, self.font_size.Value, preview_text)
				item_to_focus_on = wx.Window.FindFocus()
				self.preview.SetPage(preview_text)
				#self.preview.ForceKillFocus()
				self.preview.SetFocus()
				item_to_focus_on.SetFocus()
				
		finally:
			pass
Beispiel #23
0
    def update_preview(self):
        if self.mod is None:
            self.preview.SetPage(config.MODULE_MISSING_STRING())
            return

        try:
            for frame in guiconfig.mainfrm.frames:
                book = frame.book
                if self.mod.Name() not in book.GetModuleList():
                    continue

                # if we are already set to that book, use it
                ### should we get a better key here?
                if self.mod == frame.mod or True:
                    if isinstance(frame.reference, basestring):
                        ref = frame.reference
                    else:
                        ref = frame.reference.text

                self.mod.KeyText(to_str(ref, self.mod))

                text = self.mod.RenderText()
                # if there is no text here, look back and forth for text
                if not text:
                    old = self.mod.getSkipConsecutiveLinks()
                    self.mod.setSkipConsecutiveLinks(True)

                    for direction in 1, -1:
                        self.mod.increment(direction)
                        text = self.mod.RenderText()
                        if text:
                            break

                    self.mod.setSkipConsecutiveLinks(old)

                ref = to_unicode(self.mod.getKeyText(), self.mod)
                ref = frame.format_ref(self.mod, ref)
                preview_text = u'%s (%s)<br>%s' % (
                    ref, self.mod.Name().decode("utf8"), text.decode("utf8"))
                preview_text = u'<span style="font-family: %s; font-size: %spt;">%s</span>' % \
                  (self.font_face.StringSelection, self.font_size.Value, preview_text)
                item_to_focus_on = wx.Window.FindFocus()
                self.preview.SetPage(preview_text)
                #self.preview.ForceKillFocus()
                self.preview.SetFocus()
                item_to_focus_on.SetFocus()

        finally:
            pass
Beispiel #24
0
def on_sword_hover(frame, href, url, element, x, y):
    tooltip_config = TextTooltipConfig("", mod=None)

    module = url.getHostName()
    key = SW.URL.decode(url.getPath()).c_str()

    f = find_frame(module)
    if f:
        mod = biblemgr.get_module(module)
        mod.KeyText(key)

        ref = to_unicode(mod.getKeyText(), mod)
        ref = f.format_ref(mod, ref)
        text = to_unicode(mod.RenderText(), mod)

        tooltip_config.module = mod
        tooltip_config.text = (u"%s (%s)<br>%s" % (ref, mod.Name(), text))
    else:
        tooltip_config.text = (_("The book '%s' is not installed, "
                                 "so you cannot view "
                                 "details for this entry (%s)") %
                               (module, key.decode("utf8")))

    frame.show_tooltip(tooltip_config)
Beispiel #25
0
def on_sword_opened(frame, href, url):
	module = url.getHostName()
	key = SW.URL.decode(url.getPath()).c_str()
	frame = find_frame(module)
	if not frame:
		return
	
	guiconfig.mainfrm.set_module(module, frame.book)
	
	frame.SetReference_from_string(
		to_unicode(
			key,
			frame.book.mod,
		)
	)
Beispiel #26
0
    def end_scripRef(self, xmltag):
        if not filterutils.filter_settings["expand_thml_refs"]:

            self.success = SW.INHERITED
            return

        refList = self.scripRef_passage
        if self.u.module.Type() == "Biblical Texts":
            if refList:
                dprint(MESSAGE, "FOUND ThML reflist in Bible", refList)
                self.success = SW.INHERITED
                return

            else:
                refs = self.u.lastTextNode.c_str().split(";")
                self.buf += filterutils.ellipsize(refs, self.u.key.getText())

            self.u.suspendTextPassThru = False

            return

        # if we have a ref list, then we need to display the text and just
        # pop up usual thing
        if refList:
            self.buf += (
                "<a href=\"newbible://content/passagestudy.jsp?action=showRef&type=scripRef&value=%s&module=%s\">"
            ) % (SW.URL.encode(refList).c_str(), "")
            self.buf += self.u.lastTextNode.c_str()
            self.buf += "</a>"
        else:
            # break it up into its constituent parts and display each as a
            # separate link
            refList = self.u.lastTextNode.c_str()

            items = []
            last = GetVerseStr(self.u.key.getText())
            for item in refList.split(";"):
                vref = item
                vref = GetBestRange(to_unicode(vref),
                                    context=last,
                                    use_bpbible_locale=True)
                items.append('<a href="bible:%s">%s</a>' % (vref, item))
                last = vref
            self.buf += "; ".join(items)

        # let text resume to output again
        self.u.suspendTextPassThru = False
Beispiel #27
0
	def end_scripRef(self, xmltag):
		if not filterutils.filter_settings["expand_thml_refs"]:
		
			self.success = SW.INHERITED
			return

		refList = self.scripRef_passage
		if self.u.module.Type() == "Biblical Texts":
			if refList:
				dprint(MESSAGE, "FOUND ThML reflist in Bible", refList)
				self.success = SW.INHERITED
				return
				
			else:
				refs = self.u.lastTextNode.c_str().split(";")
				self.buf += filterutils.ellipsize(refs, self.u.key.getText())

			self.u.suspendTextPassThru = False
			
			return

		# if we have a ref list, then we need to display the text and just
		# pop up usual thing
		if refList:
			self.buf += ("<a href=\"newbible://content/passagestudy.jsp?action=showRef&type=scripRef&value=%s&module=%s\">") % (
				SW.URL.encode(refList).c_str(), ""
			)
			self.buf += self.u.lastTextNode.c_str()
			self.buf += "</a>"
		else:
			# break it up into its constituent parts and display each as a
			# separate link
			refList = self.u.lastTextNode.c_str()
		
			items = []
			last = GetVerseStr(self.u.key.getText())
			for item in refList.split(";"):
				vref = item
				vref = GetBestRange(to_unicode(vref), context=last, use_bpbible_locale=True)
				items.append('<a href="bible:%s">%s</a>' %(vref, item))
				last = vref
			self.buf += "; ".join(items)

		# let text resume to output again
		self.u.suspendTextPassThru = False
Beispiel #28
0
	def process_raw(self, text, rendered_text, key, module, 
		headings=(), option_filtered=""):
		kt = key.getOSISRefRangeText() or key.getText()
		kt = to_unicode(kt, module)
		if headings:
			headings = "<ul class='raw-headings'>%s</ul>" % (
				'\n'.join("<li>%s</li>" % cgi.escape(heading) for heading in headings))
		else:
			headings = ""

		if option_filtered:
			option_filtered = "<pre class='raw-option-filtered'>%s</pre>" % cgi.escape(option_filtered.decode("utf-8", "replace"))
		return u"""
%s
<div class='debug-raw-details' key='%s'>
	<pre class='raw-rendered'>%s</pre>
	%s
	<pre class='raw'>%s</pre>
	%s
</div>""" % (rendered_text, cgi.escape(kt), cgi.escape(rendered_text), headings, cgi.escape(text.decode("utf-8", "replace")), option_filtered)
	def install_modules(modules, dest_dir):
		def callback(progress, text):
			continuing, skip = p.Update(progress, text)
			wx.GetApp().Yield()
	
		for module in modules:
			p = wx.ProgressDialog(
				_("Extracting %s") % to_unicode(module.Description(), module),
				_("Preparing"), style=wx.PD_APP_MODAL)

			# make it nice and long so that the status text will fit in
			p.Size = (640, -1)

			p.Show()

			try:
				module.extract_zipfile(dest_dir, callback)
				
			finally:
				p.Hide()
				p.Destroy()			
		
		biblemgr.set_new_paths(path_changed=to_str(dest_dir))
Beispiel #30
0
	def GetReference(self, ref, context = None, max_verses = 500,
			stripped=False, end_ref=None):
		"""Get a reference from a genbook.

		ref should be either a TK or a string. If it is a TK, it is guaranteed
		not to change its position."""
		if not self.mod:
			return None
		
		template = self.templatelist[-1]
		render_text, render_start, render_end = self.get_rendertext()
		#TODO: use render_start and render_end?
		
		module = self.mod
		
		if isinstance(ref, TK) and end_ref:
			# we will move, so take a copy to move
			ref = TK(ref)
		
		if isinstance(ref, basestring):
			key = TK(module.getKey(), module)
			key.setText(to_str(ref, module))
			ref = key
		
		if isinstance(end_ref, basestring):
			key = TK(module.getKey(), module)
			key.setText(to_str(end_ref, module))
			end_ref = key

		old_key = module.getKey()
		if not ord(old_key.Persist()):
			# if it wasn't a persistent key, the module owns it
			# so take a copy of it, and say we own it
			old_key = old_key.clone()
			old_key.thisown = True
		
		ref.Persist(1)
		module.setKey(ref)
		
		# snap to it
		entry = module.getRawEntry()
		
		# We have to get KeyText after getRawEntry, otherwise our
		# KeyText will be wrong
		d = dict(range = module.KeyText(), version = module.Name())
		verses = template.header.substitute(d)
		
		d1 = d.copy()
		
		raw = display_options.options["raw"]
	
		while True:
			if stripped:
				text = module.StripText(entry).decode("utf-8", "replace")
			else:
				# we can't specify entry here for the same reasons as in
				# book.py
				text = render_text(#entry
				).decode("utf-8", "replace")

			if raw:
				text = self.process_raw(entry, text, ref, module)

			d1["reference"] = to_unicode(module.getKeyText(), module)
			d1["reference_encoded"] = \
				SW.URL.encode(module.getKeyText()).c_str()
			
			d1["text"] = text
			d1["breadcrumbed_reference"] = ref.breadcrumb(delimiter=" > ")		
			d1["level"] = ref.getLevel()
			
			verses += template.body.substitute(d1)
			if not end_ref or end_ref == ref:
				break
			
			ref.increment(1)
			entry = module.getRawEntry()

		verses += template.footer.substitute(d)
		module.setKey(old_key)
		
		return verses
Beispiel #31
0
	def GetReference(self, ref, specialref="",
			specialtemplate=None, context="", max_verses=177, raw=False,
			stripped=False, template=None, display_tags=None,
			exclude_topic_tag=None, end_ref=None, headings=False,
			verselist=None, remove_extra_whitespace=False):
		"""GetReference gets a reference from a Book.
		
		specialref is a ref (string) which will be specially formatted 
		according to specialtemplate.

		exclude_topic_tag: If this is not None, then it is a topic that
		should not have a tag generated, because it is obvious from the
		context (for example, the topic window for that topic).
		"""
		#only for bible keyed books
		if not self.mod:
			return None

		raw = raw or display_options.options["raw"]
		
		if template is None and self.templatelist:
			template = self.templatelist[-1]
		if context:
			lastverse = context
		else:
			lastverse = ""

		if display_tags is None:
			# if we don't have tags in, don't calculate them as it can be
			# expensive
			if "$tags" not in template.body.template:
				display_tags = False
			else:
				display_tags = passage_list.settings.display_tags
	
		assert not (verselist and end_ref), \
			"No end ref with a listkey!!!"

		if end_ref:
			ref += " - " + end_ref

		old_headings = self.vk.Headings(headings)

		if not verselist:
			verselist = self.vk.ParseVerseList(to_str(ref), to_str(lastverse), True)

		# if they pass in a verselist, they can also pass in the ref they
		# would like to go along with it. This can be useful if it also
		# includes headings that shouldn't be seen
		rangetext = GetBestRange(ref, context=context,
			userInput=False, userOutput=True, headings=headings)

		internal_rangetext = GetBestRange(ref, context=context, headings=headings)
			
		if rangetext == "":
			self.vk.Headings(old_headings)
			#if invalid reference, return empty string
			return u""
			
		
		if specialref:
			specialref = GetVerseStr(specialref)
		
		description = to_unicode(self.mod.Description(), self.mod)
		d = dict(range=rangetext, 
				 internal_range=internal_rangetext,
				 version=self.mod.Name(), 
				 description=description)

		text = template.header.safe_substitute(d)
		verses = []
		
		
		for body_dict, headings in self.GetReference_yield(
			verselist, max_verses, raw, stripped,
			exclude_topic_tag=exclude_topic_tag,
			display_tags=display_tags,
		):
			# if we have exceeded the verse limit, body_dict will be None
			if body_dict is None:
				verses.append(config.MAX_VERSES_EXCEEDED() % max_verses)
				break

			body_dict.update(d)
			
			t = template

			if specialref == body_dict["internal_reference"]:
				t = specialtemplate

			verse = t.preverse.safe_substitute(body_dict)

			for heading_dict in headings:
				verse += t.headings.safe_substitute(heading_dict)
			
			verse += t.body.safe_substitute(body_dict)

			verses.append(verse)
		
		self.vk.Headings(old_headings)

		text += template.finalize(u''.join(verses))
		text += self.end_of_render
		text += template.footer.safe_substitute(d)
		return text
Beispiel #32
0
 def version_tree_tooltip(self, event):
     item = event.GetItem()
     data = self.tree.GetPyData(item)
     if isinstance(data.data, SW.Module):
         event.SetToolTip(to_unicode(data.data.Description(), data.data))
Beispiel #33
0
 def version_tree_tooltip(self, event):
     item = event.GetItem()
     data = self.tree.GetPyData(item)
     if isinstance(data.data, SW.Module):
         event.SetToolTip(to_unicode(data.data.Description(), data.data))
Beispiel #34
0
	def __repr__(self): return "%s('%s')" % (self.__class__.__name__, to_unicode(self.getRangeText()))

	def __iadd__(self, amount): 
	def get_document(self, path):
		module_name, rest = path.split("/", 1)
		ref, direction = rest.rsplit("/", 1)
		assert direction in ("next", "previous")

		dir = {"next": 1, "previous": -1}[direction]
		book = biblemgr.get_module_book_wrapper(module_name)
		mod = book.mod		
		no_more = False
		if book.is_verse_keyed:
			vk = VK(ref, headings=not book.chapter_view)
			if book.chapter_view:
				vk.chapter += dir
				if vk.Error():
					print "No more in that direction", dir
					no_more = True
				else:
				
					# go back just a little, so that when we go forward on the module
					# we won't overshoot... (at least, that is our plan - we hope it
					# won't be baffled...)
					vk.Verse(vk.Verse() - dir)
					if vk.Error():
						print "VK had an error taking away a verse", dir
	
			if not no_more:
				old_mod_skiplinks = mod.getSkipConsecutiveLinks()
				mod.setSkipConsecutiveLinks(True)
				try:
					vk.Persist(1)
					mod.setKey(vk)
					#print repr(mod.Error())
					mod.increment(dir)

					if mod.Error() != '\x00':
						print "Mod had an error"
						no_more = True
					else:
						if book.chapter_view:
							new_ref = vk.get_chapter_osis_ref()
						else:
							new_ref = vk.getOSISRef()
				finally:
					mod.setKey(SW.Key())
					mod.setSkipConsecutiveLinks(old_mod_skiplinks)
		
		elif book.is_dictionary:
			# XXX: Would using an index rather than a reference (as the XUL code did) be more efficient?
			book.snap_text(ref)
			book.mod.increment(dir)
			if mod.Error() == '\x00' and book.mod.getKey().getText():
				new_ref = to_unicode(mod.getKey().getText(), mod)
			else:
				no_more = True
			
		elif book.is_genbook:
			ref = "/" + ref
			tk = book.GetKey()
			tk.Persist(1)
			assert tk.thisown
			newtk = book.GetKey()
			newtk.thisown = True
			mod.setKey(tk)
			print "Getting next for", ref
			tk.set_text(ref)
			print tk.getText()
			if mod.Error() != '\x00':
				print "Error on initial set?"
			mod.increment(dir)
			if mod.Error() == '\x00' and tk.getText():
				new_ref = to_unicode(tk.getText(), mod)[1:] # trim off the leading /
			else:
				no_more = True
			
			mod.setKey(newtk)
		else:
			print "Book type not handled", module_name
		
		if no_more:
			message = (_("You are at the start of this book.") if dir == -1
				else _("You are at the end of this book."))
			class_name = "book-%s" % ("start" if dir == -1 else "end")
			return '''
			<div class="page_segment" empty="true">
				<div class='no_more_text %(class_name)s'>
					%(message)s
				</div>
			</div>''' % locals()
		
		return '<div class="page_segment">%(content)s%(timer)s</div>' % self._get_document_parts_for_ref(module_name, new_ref, do_current_ref=False)
Beispiel #36
0
    def GetReference(self,
                     ref,
                     specialref="",
                     specialtemplate=None,
                     context="",
                     max_verses=177,
                     raw=False,
                     stripped=False,
                     template=None,
                     display_tags=None,
                     exclude_topic_tag=None,
                     end_ref=None,
                     headings=False,
                     verselist=None,
                     remove_extra_whitespace=False):
        """GetReference gets a reference from a Book.
		
		specialref is a ref (string) which will be specially formatted 
		according to specialtemplate.

		exclude_topic_tag: If this is not None, then it is a topic that
		should not have a tag generated, because it is obvious from the
		context (for example, the topic window for that topic).
		"""
        #only for bible keyed books
        if not self.mod:
            return None

        raw = raw or display_options.options["raw"]

        if template is None and self.templatelist:
            template = self.templatelist[-1]
        if context:
            lastverse = context
        else:
            lastverse = ""

        if display_tags is None:
            # if we don't have tags in, don't calculate them as it can be
            # expensive
            if "$tags" not in template.body.template:
                display_tags = False
            else:
                display_tags = passage_list.settings.display_tags

        assert not (verselist and end_ref), \
         "No end ref with a listkey!!!"

        if end_ref:
            ref += " - " + end_ref

        old_headings = self.vk.Headings(headings)

        if not verselist:
            verselist = self.vk.ParseVerseList(to_str(ref), to_str(lastverse),
                                               True)

        # if they pass in a verselist, they can also pass in the ref they
        # would like to go along with it. This can be useful if it also
        # includes headings that shouldn't be seen
        rangetext = GetBestRange(ref,
                                 context=context,
                                 userInput=False,
                                 userOutput=True,
                                 headings=headings)

        internal_rangetext = GetBestRange(ref,
                                          context=context,
                                          headings=headings)

        if rangetext == "":
            self.vk.Headings(old_headings)
            #if invalid reference, return empty string
            return u""

        if specialref:
            specialref = GetVerseStr(specialref)

        description = to_unicode(self.mod.Description(), self.mod)
        d = dict(range=rangetext,
                 internal_range=internal_rangetext,
                 version=self.mod.Name(),
                 description=description)

        text = template.header.safe_substitute(d)
        verses = []

        for body_dict, headings in self.GetReference_yield(
                verselist,
                max_verses,
                raw,
                stripped,
                exclude_topic_tag=exclude_topic_tag,
                display_tags=display_tags,
        ):
            # if we have exceeded the verse limit, body_dict will be None
            if body_dict is None:
                verses.append(config.MAX_VERSES_EXCEEDED() % max_verses)
                break

            body_dict.update(d)

            t = template

            if specialref == body_dict["internal_reference"]:
                t = specialtemplate

            verse = t.preverse.safe_substitute(body_dict)

            for heading_dict in headings:
                verse += t.headings.safe_substitute(heading_dict)

            verse += t.body.safe_substitute(body_dict)

            verses.append(verse)

        self.vk.Headings(old_headings)

        text += template.finalize(u''.join(verses))
        text += self.end_of_render
        text += template.footer.safe_substitute(d)
        return text
Beispiel #37
0
 def __getitem__(self, item):
     return to_unicode(self.mod.getKeyForEntry(item), self.mod)
Beispiel #38
0
	def __repr__(self):
		self.check_changed()
	
		return "<%s(%s)>" % (type(self).__name__, 
			to_unicode(self.getText(), self.module))
Beispiel #39
0
	def __str__(self):
		self.check_changed()
	
		return to_unicode(self.getLocalName(), self.module)
Beispiel #40
0
	def __getitem__(self, item):
		return to_unicode(self.mod.getKeyForEntry(item), self.mod)
    def get_document(self, path):
        module_name, rest = path.split("/", 1)
        ref, direction = rest.rsplit("/", 1)
        assert direction in ("next", "previous")

        dir = {"next": 1, "previous": -1}[direction]
        book = biblemgr.get_module_book_wrapper(module_name)
        mod = book.mod
        no_more = False
        if book.is_verse_keyed:
            vk = VK(ref, headings=not book.chapter_view)
            if book.chapter_view:
                vk.chapter += dir
                if vk.Error():
                    print "No more in that direction", dir
                    no_more = True
                else:

                    # go back just a little, so that when we go forward on the module
                    # we won't overshoot... (at least, that is our plan - we hope it
                    # won't be baffled...)
                    vk.Verse(vk.Verse() - dir)
                    if vk.Error():
                        print "VK had an error taking away a verse", dir

            if not no_more:
                old_mod_skiplinks = mod.getSkipConsecutiveLinks()
                mod.setSkipConsecutiveLinks(True)
                try:
                    vk.Persist(1)
                    mod.setKey(vk)
                    #print repr(mod.Error())
                    mod.increment(dir)

                    if mod.Error() != '\x00':
                        print "Mod had an error"
                        no_more = True
                    else:
                        if book.chapter_view:
                            new_ref = vk.get_chapter_osis_ref()
                        else:
                            new_ref = vk.getOSISRef()
                finally:
                    mod.setKey(SW.Key())
                    mod.setSkipConsecutiveLinks(old_mod_skiplinks)

        elif book.is_dictionary:
            # XXX: Would using an index rather than a reference (as the XUL code did) be more efficient?
            book.snap_text(ref)
            book.mod.increment(dir)
            if mod.Error() == '\x00' and book.mod.getKey().getText():
                new_ref = to_unicode(mod.getKey().getText(), mod)
            else:
                no_more = True

        elif book.is_genbook:
            ref = "/" + ref
            tk = book.GetKey()
            tk.Persist(1)
            assert tk.thisown
            newtk = book.GetKey()
            newtk.thisown = True
            mod.setKey(tk)
            print "Getting next for", ref
            tk.set_text(ref)
            print tk.getText()
            if mod.Error() != '\x00':
                print "Error on initial set?"
            mod.increment(dir)
            if mod.Error() == '\x00' and tk.getText():
                new_ref = to_unicode(tk.getText(),
                                     mod)[1:]  # trim off the leading /
            else:
                no_more = True

            mod.setKey(newtk)
        else:
            print "Book type not handled", module_name

        if no_more:
            message = (_("You are at the start of this book.")
                       if dir == -1 else _("You are at the end of this book."))
            class_name = "book-%s" % ("start" if dir == -1 else "end")
            return '''
			<div class="page_segment" empty="true">
				<div class='no_more_text %(class_name)s'>
					%(message)s
				</div>
			</div>''' % locals()

        return '<div class="page_segment">%(content)s%(timer)s</div>' % self._get_document_parts_for_ref(
            module_name, new_ref, do_current_ref=False)
Beispiel #42
0
	def get_text(self):
		self.check_changed()
	
		return to_unicode(self.getText(), self.module)