示例#1
0
	def _get_document_parts_for_ref(self, module_name, ref, do_current_ref=True):
		t = default_timer()

		stylesheets = list(self.bible_stylesheets)
		scripts = self.standard_scripts + self.bible_scripts + ["highlight.js", "bpbible_html.js", "contrib/hyphenate.js", "columns.js"]

		book = biblemgr.get_module_book_wrapper(module_name)
		assert book, "Module wrapper not found for book " + module_name
		module = book.mod
		if book.chapter_view:
			scripts.append("bpbible_html_chapter_view.js")
			#stylesheets.append("bpbible_chapter_view.css")
			#stylesheets.append("bpbible://content/quotes_skin/")
		else:
			scripts.append("bpbible_html_page_view.js")
			stylesheets.append("bpbible_page_view.css")			
	
		if is_debugging():
			stylesheets.append("bpbible_html_debug.css")

		if book.is_verse_keyed:
			if book.chapter_view:
				if do_current_ref:
					c = book.GetChapter(ref, ref, config.current_verse_template)
				else:
					c = book.GetChapter(ref)

				ref_id = VK(ref).get_chapter_osis_ref()
				
			else:
				c = book.GetReference(ref, headings=True)
				ref_id = VK(ref).getOSISRef()


		elif book.is_dictionary:
			c = book.GetReference(ref)
			ref_id = ref

		elif book.is_genbook:
			c = book.GetReference(ref)
			ref_id = ref
		else:
			dprint(ERROR, "Book `%s' not found." % module_name)
			c = ''
		c = c.replace("<!P>", "</p><p>")

		clas = ""
		if not c:
			clas = " nocontent"

		lang = module.Lang() if module else "en",
		c = convert_language(c, lang)
		c = '<div class="segment%s" ref_id="%s">%s</div>' % (clas, urllib.quote(ref_id.encode("utf8")), c)

		return dict(
			module=module, content=c,
			bodyattrs=self._get_body_attrs(module),
			stylesheets=stylesheets,
			scripts=scripts,
			timer="<div class='timer'>Time taken: %.3f (ref_id %s)</div>" % (default_timer() - t, ref_id))
示例#2
0
def check_item(item):
	if not item:
		dprint(WARNING, "Called with invalid tree item")
		import traceback
		traceback.print_stack(file=sys.stdout)
			
	return bool(item)
示例#3
0
	def start_hi(self, xmltag):
		assert not xmltag.isEmpty(), "Hi cannot be empty"
		type = xmltag.getAttribute("type")
		types = {
			"acrostic": ("<i>", "</i>"),
			"bold": ("<b>", "</b>"),
			"b": ("<b>", "</b>"),
			"x-b": ("<b>", "</b>"),
			"emphasis": ("<em>", "</em>"),
			"illuminated": ("<i>", "</i>"),
			"italic": ("<i>", "</i>"),
			"line-through": ('<span class="line-through">', "</span>"),
			"normal": ("", ""),
			"ol": ('<span class="overline">', "</span>"),
			"small-caps": ('<span class="small-caps">', "</span>"),
			"sub": ("<sub>", "</sub>"),
			"super": ("<sup>", "</sup>"),
			"underline": ("<u>", "</u>"),
		}
		if type not in types:
			dprint(WARNING, "Unhandled hi type", type)
			type = "italic"
		
		start, end = types[type]
		self.buf += start
		self._end_hi_stack.append(end)
示例#4
0
def initialize():
    global langid, mytranslation, ngettext
    langid = locale_settings["language"]
    if langid not in languages:
        dprint(WARNING, "Didn't have language", langid)
        langid = "en"

    # Set up Python's gettext
    mytranslation = gettext.translation(domain,
                                        localedir, [langid],
                                        fallback=True)

    if type(mytranslation) == gettext.NullTranslations:
        dprint(WARNING, "Language not found for python", langid)

    mytranslation.install(unicode=True)
    ngettext = mytranslation.ngettext

    if langid in languages:
        desc, locale, abbrev, conf = languages[langid]
        b = locale_settings["language_book_names"].get(langid)
        bookname_languages = dict(get_bookname_languages())
        if b not in bookname_languages:
            if b: print "Language not found", b
            lang = langid
            #b = langid
        else:
            desc, locale, abbrev = bookname_languages[b]
            lang = b

        change_locale(lang, abbrev, additional=conf)
示例#5
0
    def __init__(self,
                 text,
                 action,
                 doc=None,
                 enabled=lambda: True,
                 update_text=lambda: None,
                 update_ui=None,
                 accelerator=None,
                 id=wx.ID_ANY,
                 font=None):
        self.text = text
        self.action = action

        if doc is None:
            self.doc = action.__doc__
            if self.doc is None:
                dprint(WARNING, "No description for menu item", text)
                self.doc = ""
        else:
            self.doc = doc

        self.enabled = enabled
        self.update_text = update_text
        self.update_ui = update_ui
        self.accelerator = accelerator
        self.id = id
        self.font = font
示例#6
0
	def start_reference(self, xmltag):
		self.ref = xmltag.getAttribute("osisRef")
		if not self.ref:
			self.ref = None
			self.success = SW.INHERITED
			dprint(WARNING, "No osisRef in reference", xmltag.toString())
			
			return
			

		#TODO check this
		#TODO check for Bible:Gen.3.5
		idx = self.ref.find(":")
		self.was_sword_ref = False
		
		if idx != -1:
			if not self.ref[:idx].startswith("Bible"):
				self.ref = "sword://%s/%s" % (
					self.ref[:idx], SW.URL.encode(self.ref[idx+1:]).c_str()
				)
				self.was_sword_ref = True
			else:
				self.ref = self.ref[idx+1:]

		self.u.suspendLevel += 1
		self.u.suspendTextPassThru = self.u.suspendLevel
示例#7
0
def initialize():
	global langid, mytranslation, ngettext
	langid = locale_settings["language"]
	if langid not in languages:
		dprint(WARNING, "Didn't have language", langid)
		langid = "en"
	
	# Set up Python's gettext
	mytranslation = gettext.translation(domain, localedir,
		[langid], fallback=True)
	
	if type(mytranslation) == gettext.NullTranslations:
		dprint(WARNING, "Language not found for python", langid)
	
	mytranslation.install(unicode=True)
	ngettext = mytranslation.ngettext

	if langid in languages:
		desc, locale, abbrev, conf = languages[langid]
		b = locale_settings["language_book_names"].get(langid)
		bookname_languages = dict(get_bookname_languages())
		if b not in bookname_languages:
			if b: print "Language not found", b
			lang = langid
			#b = langid
		else:
			desc, locale, abbrev = bookname_languages[b]
			lang = b

		change_locale(lang, abbrev, additional=conf)
示例#8
0
def find_zip_installer(filename):
    for zip_installer in zip_installers:
        dprint(INSTALL_ZIP, "Trying to load with", zip_installer)
        try:
            return zip_installer(filename)
        except InvalidModuleException, e:
            # it might not be this type of installer...
            dprint(INSTALL_ZIP, "Exception thrown", e)
示例#9
0
def find_zip_installer(filename):
    for zip_installer in zip_installers:
        dprint(INSTALL_ZIP, "Trying to load with", zip_installer)
        try:
            return zip_installer(filename)
        except InvalidModuleException, e:
            # it might not be this type of installer...
            dprint(INSTALL_ZIP, "Exception thrown", e)
示例#10
0
 def OnOpenURI(self, event):
     href = event.GetHref()
     dprint(WARNING, "Loading HREF", href)
     if self.allow_url_to_open(href) or self.force_next_uri_to_open:
         self.dom_loaded = False
         self.force_next_uri_to_open = False
     else:
         protocol_handler.on_link_opened(self, href)
         event.Veto()
示例#11
0
    def Encoding(self):
        mapping = {None: chr(SW.ENC_LATIN1), "UTF-8": chr(SW.ENC_UTF8), "Latin-1": chr(SW.ENC_LATIN1)}

        enc = self.getConfigEntry("Encoding")
        if enc in mapping:
            return mapping[enc]

        dprint(WARNING, "Invalid encoding '%s' in module %s" % (enc, self.name))
        return chr(SW.ENC_LATIN1)
示例#12
0
def get_screen_rect(point):
	"""Get the size of the screen the given window is on"""
	screen = wx.Display.GetFromPoint(point)
	if screen == wx.NOT_FOUND:
		debug.dprint(debug.WARNING, "Couldn't find screen for point", point)
		return wx.Rect()
	
	display = wx.Display(screen)
	return display.GetClientArea()
示例#13
0
	def OnOpenURI(self, event):
		href = event.GetHref()
		dprint(WARNING, "Loading HREF", href)
		if self.allow_url_to_open(href) or self.force_next_uri_to_open:
			self.dom_loaded = False
			self.force_next_uri_to_open = False
		else:
			protocol_handler.on_link_opened(self, href)
			event.Veto()
示例#14
0
 def add_children(self, tree_item):
     for path, mgr, modules in reversed(biblemgr.mgrs):
         if mgr == tree_item.data:
             for modname, mod in sorted(modules, key=lambda x: x[0].lower()):
                 self.add_module(
                     tree_item, mod, "\nThis book is not active as it " "is shadowed by a book in a different path"
                 )
             break
     else:
         dprint(ERROR, "Did not find mgr in list", mgr)
示例#15
0
	def start_seg(self, xmltag):
		type = xmltag.getAttribute("type")
		if type in ("morph", "x-morph"):
			self.buf += '<span class="morphSegmentation">'
			if self.in_morph_seg:
				dprint(WARNING, "Nested morph segs", self.u.key.getText())

			self.in_morph_seg = True
		else:
			self.success = SW.INHERITED
	def GetContent(self, url):
		try:
			dprint(MESSAGE, "GetContent called for url:", url)
			protocol, path = self._breakup_url(url)
			return unicode(protocol_handlers.handlers[protocol].get_document(path))
		except Exception, e:
			dprint(ERROR, "EXCEPTION in GetContent")
			import traceback
			traceback.print_exc()
			raise
示例#17
0
	def InitXULRunner(self):
		dprint(MESSAGE, "Initialising XULRunner engine")
		self.InitProfile()
		wx.wc.WebControl.InitEngine(xulrunner_path)

		# NOTE: DO NOT move this import into the main import section.
		# Doing so causes InitEngine() above to fail when loading xul.dll.
		import gui.webconnect_protocol_handler
		wx.wc.RegisterProtocol("bpbible", gui.webconnect_protocol_handler.MasterProtocolHandler())
		dprint(MESSAGE, "XULRunner engine initialised")
示例#18
0
	def get_document(self, path):
		module_name = path

		book = biblemgr.get_module_book_wrapper(module_name)
		if not book:
			dprint(ERROR, "Book `%s' not found." % module_name)
			return "Error: Book `%s' not found." % module_name

		module = book.mod
		return self._get_moduleinfo(module)
示例#19
0
    def get_document(self, path):
        module_name = path

        book = biblemgr.get_module_book_wrapper(module_name)
        if not book:
            dprint(ERROR, "Book `%s' not found." % module_name)
            return "Error: Book `%s' not found." % module_name

        module = book.mod
        return self._get_moduleinfo(module)
示例#20
0
 def add_children(self, tree_item):
     for path, mgr, modules in reversed(biblemgr.mgrs):
         if mgr == tree_item.data:
             for modname, mod in sorted(modules,
                                        key=lambda x: x[0].lower()):
                 self.add_module(
                     tree_item, mod, "\nThis book is not active as it "
                     "is shadowed by a book in a different path")
             break
     else:
         dprint(ERROR, "Did not find mgr in list", mgr)
示例#21
0
 def GetContent(self, url):
     try:
         dprint(MESSAGE, "GetContent called for url:", url)
         protocol, path = self._breakup_url(url)
         return unicode(
             protocol_handlers.handlers[protocol].get_document(path))
     except Exception, e:
         dprint(ERROR, "EXCEPTION in GetContent")
         import traceback
         traceback.print_exc()
         raise
示例#22
0
    def open_zipfile(self, zip_path):
        zip_file = self.read_zipfile(zip_path)
        file_list = zip_file.filelist
        module_name = None

        for zip_info in file_list:
            dprint(INSTALL_ZIP, "Has file %s" % zip_info.filename)
            if self.is_conf(zip_info):
                return zip_file, zip_info.filename

        raise InvalidModuleException("File does not appear to be a valid book")
示例#23
0
    def InitXULRunner(self):
        dprint(MESSAGE, "Initialising XULRunner engine")
        self.InitProfile()
        wx.wc.WebControl.InitEngine(xulrunner_path)

        # NOTE: DO NOT move this import into the main import section.
        # Doing so causes InitEngine() above to fail when loading xul.dll.
        import gui.webconnect_protocol_handler
        wx.wc.RegisterProtocol(
            "bpbible", gui.webconnect_protocol_handler.MasterProtocolHandler())
        dprint(MESSAGE, "XULRunner engine initialised")
示例#24
0
    def open_zipfile(self, zip_path):
        zip_file = self.read_zipfile(zip_path)
        file_list = zip_file.filelist
        module_name = None

        for zip_info in file_list:
            dprint(INSTALL_ZIP, "Has file %s" % zip_info.filename)
            if self.is_conf(zip_info):
                return zip_file, zip_info.filename

        raise InvalidModuleException("File does not appear to be a valid book")
示例#25
0
    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)
示例#26
0
	def frozen_internal(self, *args, **kwargs):
		self.Freeze()
		try:
			function(self, *args, **kwargs)
		finally:
			try:
				if self.IsFrozen():	
					self.Thaw()
				# even with checking it is frozen, it will sometimes throw an
				# assertion on 
			except AssertionError, e:
				debug.dprint(debug.WARNING, "Ignoring assertion with thaw", e)
示例#27
0
def enable_faulthandler():
    try:
        # Faulthandler helps us to find the stack trace when BPBible segmentation faults.
        import faulthandler
        faulthandler.enable()
    except ImportError:
        dprint(WARNING, "Faulthandler not installed")
    except AttributeError, e:
        # Faulthandler encounters an AttributeError when built with Py2exe,
        # because py2exe is missing the fileno method on standard input and output.
        # We catch this to prevent a crash.
        dprint(WARNING, "AttributeError encountered enabling faulthandler.", e)
示例#28
0
	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)
示例#29
0
def enable_faulthandler():
	try:
		# Faulthandler helps us to find the stack trace when BPBible segmentation faults.
		import faulthandler
		faulthandler.enable()
	except ImportError:
		dprint(WARNING, "Faulthandler not installed")
	except AttributeError, e:
		# Faulthandler encounters an AttributeError when built with Py2exe,
		# because py2exe is missing the fileno method on standard input and output.
		# We catch this to prevent a crash.
		dprint(WARNING, "AttributeError encountered enabling faulthandler.", e)
示例#30
0
    def GetChapter(self,
                   ref,
                   specialref="",
                   specialtemplate=None,
                   context="",
                   raw=False):
        self.vk.setText(to_str(ref, self.mod))

        #get first ref
        text = self.vk.getText()

        match = re.match("([\w\s]+) (\d+):(\d+)", text)
        if match:
            book, chapter, verse = match.group(1, 2, 3)

            # include introductions - book introduction if necessary
            ref = "%s %s" % (book, chapter)
            text = "%s %s:0-%s %s" % (book, chapter, book, chapter)
            vk = SW.VerseKey()
            vk.Headings(1)
            list = vk.ParseVerseList(text, "", True)
            if chapter == "1":
                vk.setText("%s 0:0" % book)
                list.add(vk)
                #text = "%s 0:0-%s %s" % (book, book, chapter)

                if book == "Genesis":
                    vk.Testament(0)
                    list.add(vk)
                    vk.Testament(1)
                    list.add(vk)

                elif book == "Matthew":
                    # set it to 0 first so that we come back to the testament
                    # heading
                    vk.Testament(0)
                    vk.Testament(2)
                    list.add(vk)

                list.sort()

        else:
            dprint(ERROR, "Couldn't parse verse text", text)
            return ""

        return self.GetReference(ref,
                                 specialref,
                                 specialtemplate,
                                 context,
                                 raw=raw,
                                 headings=True,
                                 verselist=list)
示例#31
0
	def __init__(self, *args, **kwargs):
		super(MultiChoiceDialog, self).__init__(*args, **kwargs)
		for item in self.Children:
			if isinstance(item, wx.CheckListBox):
				self.Bind(wx.EVT_KEY_UP,  self.on_char)
				item.Bind(wx.EVT_KEY_UP,  self.on_char)
				
				break
		else:
			dprint(WARNING, "ListBox not found in MultiChoiceDialog")
			item = None
		
		self.list_box = item
示例#32
0
    def __init__(self, *args, **kwargs):
        super(MultiChoiceDialog, self).__init__(*args, **kwargs)
        for item in self.Children:
            if isinstance(item, wx.CheckListBox):
                self.Bind(wx.EVT_KEY_UP, self.on_char)
                item.Bind(wx.EVT_KEY_UP, self.on_char)

                break
        else:
            dprint(WARNING, "ListBox not found in MultiChoiceDialog")
            item = None

        self.list_box = item
示例#33
0
    def Encoding(self):
        mapping = {
            None: chr(SW.ENC_LATIN1),
            "UTF-8": chr(SW.ENC_UTF8),
            "Latin-1": chr(SW.ENC_LATIN1)
        }

        enc = self.getConfigEntry("Encoding")
        if enc in mapping:
            return mapping[enc]

        dprint(WARNING,
               "Invalid encoding '%s' in module %s" % (enc, self.name))
        return chr(SW.ENC_LATIN1)
示例#34
0
	def start_lg(self, xmltag):
		if xmltag and xmltag.getAttribute("eID"):
			return self.end_lg(xmltag)

		if self.in_lg:
			dprint(WARNING, "Nested lg's? (or l outside lg, then lg?)")

		self.in_lg = True
		clas = ""
		if not xmltag:
			clas = " forced_lg"

		if not self.in_copy_verses_mode:
			self.buf += '<blockquote class="lg" width="0">'
示例#35
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
示例#36
0
	def run(self, module):
		try:
			markup = self.get_filter(module)
			if markup is not None:
				module.AddRenderFilter(markup)
				return True
			return False

		except Exception, e:
			import traceback
			dprint(ERROR, "EXCEPTION: ", e)
			try:
				traceback.print_exc(file=sys.stdout)
			except Exception, e2:
				dprint(ERROR, "Couldn't print exception - exception raised", e2)
示例#37
0
    def OnInit(self):
        self.InitXULRunner()
        self.FindXULRunnerVersion()
        self.ShowSplashScreen()

        self.starting = True
        self.restarting = False
        self.reload_restarting = False

        dprint(MESSAGE, "App Init")
        guiconfig.load_icons()

        from wx import xrc
        self.res = xrc.XmlResource(config.xrc_path + "auifrm.xrc")
        return True
示例#38
0
		def get_caption(match):
			n = match.group(2)
			for frame, caption, name, dummy, dummy in aui_items:
				if name == n:
					break
			else:
				for item in self.toolbars:
					if item[1] == n:
						caption = _(item[1])
						break
				else:
					dprint(WARNING, "Couldn't find caption by name", n)
					return match.group(0)

			return match.group(1) + caption + ";"
示例#39
0
	def stay_on_top(self, evt):
		new = PermanentTooltip(guiconfig.mainfrm,
			tooltip_config=self.tooltip_config.another(),)

		if not hasattr(self.html, "reference"):
			dprint(WARNING, "Tooltip html didn't have reference", self.html)
			self.html.reference = ""
		
		# the context of the note
		new.html.reference = self.html.reference

		new.ShowTooltip(self.get_permanent_tooltip_position())
		
		dprint(TOOLTIP, "Stop on permanent popup")
		self.Stop()
示例#40
0
        def get_caption(match):
            n = match.group(2)
            for frame, caption, name, dummy, dummy in aui_items:
                if name == n:
                    break
            else:
                for item in self.toolbars:
                    if item[1] == n:
                        caption = _(item[1])
                        break
                else:
                    dprint(WARNING, "Couldn't find caption by name", n)
                    return match.group(0)

            return match.group(1) + caption + ";"
示例#41
0
    def __init__(self,
                 biblename="ESV",
                 commentaryname="TSK",
                 dictionaryname="ISBE",
                 genbook="Josephus",
                 daily_devotional_name="",
                 harmonyname="CompositeGospel"):

        self.on_before_reload = ObserverList()
        self.on_after_reload = ObserverList()
        self.reloading = False

        self.mgrs = []
        self.paths = []

        dprint(MESSAGE, "Creating manager")

        self.make_managers()

        # call on after reload in case
        self.on_after_reload(self)

        dprint(MESSAGE, "/Creating manager")

        self.bible = Bible(self, biblename)
        self.commentary = Commentary(self, commentaryname)
        self.dictionary = Dictionary(self, dictionaryname)
        self.genbook = GenBook(self, genbook)
        self.daily_devotional = DailyDevotional(self, daily_devotional_name)
        self.harmony = Harmony(self, harmonyname)

        self.state = []
        self.options = {}
        self.init_options()

        self.book_type_map = {
            self.bible.type: self.bible,
            self.commentary.type: self.commentary,
            self.dictionary.type: self.dictionary,
            self.genbook.type: self.genbook,
        }

        self.book_category_map = {
            self.daily_devotional.category: self.daily_devotional,
            self.harmony.category: self.harmony,
        }

        self.parser_mode = NORMAL_PARSER_MODE
示例#42
0
    def compose_regex(self, stemming_data, word):
        if self.do_stemming():
            words_to_search_for = stemming_data.get(self.stemWord(word.lower()), None)

            if words_to_search_for is None:
                dprint(WARNING, "Stemmed word not found", word, word.lower())
                words_to_search_for = [word]
        else:
            # don't try using the stemming data, as it might lead to
            # inconsistencies
            words_to_search_for = [word]

            # if there are too many options, factorizing these will be a worthwile
            # option. With around 10, it seems ~10% slower than a simple
            # factorization.
        return "(?:" + "|".join(words_to_search_for) + ")"
示例#43
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
示例#44
0
    def run(self, module):
        try:
            markup = self.get_filter(module)
            if markup is not None:
                module.AddRenderFilter(markup)
                return True
            return False

        except Exception, e:
            import traceback
            dprint(ERROR, "EXCEPTION: ", e)
            try:
                traceback.print_exc(file=sys.stdout)
            except Exception, e2:
                dprint(ERROR, "Couldn't print exception - exception raised",
                       e2)
示例#45
0
	def OnInit(self):
		self.InitXULRunner()
		self.FindXULRunnerVersion()
		self.ShowSplashScreen()
		
		self.starting = True
		self.restarting = False
		self.reload_restarting = False
	
		dprint(MESSAGE, "App Init")
		guiconfig.load_icons()
		

		from wx import xrc
		self.res = xrc.XmlResource(config.xrc_path+"auifrm.xrc" )
		return True
示例#46
0
	def on_link_clicked(frame, href, url):
		host = url.getHostName()
		if host != "passagestudy.jsp":
			return
		action = url.getParameterValue("action")
		if action == "showStrongs":
			type = url.getParameterValue("type") #Hebrew or greek
			value = url.getParameterValue("value") #strongs number
			if not type or not value: 
				return
			#do lookup
			type = "Strongs"+type #as module is StrongsHebrew or StrongsGreek
			if biblemgr.dictionary.ModuleExists(type):
				guiconfig.mainfrm.set_module(type, biblemgr.dictionary)
				wx.CallAfter(guiconfig.mainfrm.dictionarytext.UpdateUI, value)
			return
		if action=="showMorph":
			type = url.getParameterValue("type") #Hebrew or greek
			value = url.getParameterValue("value") #strongs number
			if not type or not value: 
				return
			
			if type.split(":")[0] not in ("robinson", "Greek"):
				return

			#do lookup
			type = "Robinson"
			if biblemgr.dictionary.ModuleExists(type):
				guiconfig.mainfrm.set_module(type, biblemgr.dictionary)
				wx.CallAfter(guiconfig.mainfrm.dictionarytext.UpdateUI, value)


		if action=="showImage":
			value = url.getParameterValue("value") # path to image
			if not value:
				dprint(WARNING, "No URL value?", href)
				return
			else:
				assert value.startswith("file:")
				filepath = value[5:]
				dprint(MESSAGE, "Opening image", filepath)
				osutils.system_open_file(filepath)

		if action == "showRef":
			if url.getParameterValue("type") == "scripRef":
				ref = url.getParameterValue("value")
				guiconfig.mainfrm.set_bible_ref(ref, events.LINK_CLICKED)
示例#47
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
示例#48
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
示例#49
0
	def FindXULRunnerVersion(self):
		"""Find the XULRunner version from the XULRunner platform.ini config file.

		This should be provided by XULRunner (and then wxWebConnect) through
		the nsIXULAppInfo API, but it seems this is only possible when xulrunner
		has been run from the command line and has an application.ini and
		XRE_Main() has been called.

		Since XRE_Main() is just looking up the value in the INI file,
		I figure it can't hurt too much to do the same here.
		"""
		xulrunner_ini_file = os.path.join(xulrunner_path, "platform.ini")
		config_parser = confparser.config()
		config_parser.read(xulrunner_ini_file)
		if config_parser.has_option("Build", "Milestone"):
			config.xulrunner_version = config_parser.get("Build", "Milestone")[0]
			dprint(MESSAGE,"XULRunner version is %s." % config.xulrunner_version)
示例#50
0
	def get_module_book_wrapper(self, module_name):
		mod = self.modules_with_lowercase_name.get(module_name.lower())
		if mod is None:
			dprint(ERROR, "Mod is none", module_name)
			return None

		category = mod.getConfigEntry("Category")
		if category and (category in self.book_category_map):
			book = self.book_category_map[category]
		else:
			book = self.book_type_map.get(mod.Type())
			if book is None:
				dprint(ERROR, "book is none", module_name, mod.Type())
				return None

		book.SetModule(mod)
		return book
示例#51
0
    def get_module_book_wrapper(self, module_name):
        mod = self.modules_with_lowercase_name.get(module_name.lower())
        if mod is None:
            dprint(ERROR, "Mod is none", module_name)
            return None

        category = mod.getConfigEntry("Category")
        if category and (category in self.book_category_map):
            book = self.book_category_map[category]
        else:
            book = self.book_type_map.get(mod.Type())
            if book is None:
                dprint(ERROR, "book is none", module_name, mod.Type())
                return None

        book.SetModule(mod)
        return book
示例#52
0
	def start_l(self, xmltag):
		if xmltag.getAttribute("eID"):
			return self.end_l(xmltag)

		if xmltag.isEmpty() and not xmltag.getAttribute("sID"):
			print "<l />?!?", xmltag.toString()
			self.success = SW.INHERITED
			return

		if not self.in_lg:
			dprint(WARNING, "l outside lg??? (or block doesn't contain lg)")
			self.start_lg(None)
		
		mapping = {
			# usual poetry indent in ESV
			"x-indent": 2,

			# extra indent - 1 Tim 3:16 (ESV) for example
			"x-indent-2": 4,

			# declares lines - Declares the Lord, Says the Lord, etc.
			"x-declares": 6,
			
			# doxology - Amen and Amen - Psalms 41:13, 72:19, 89:52 in ESV 
			"x-psalm-doxology": 6,

			# usual poetry indent in WEB
			"x-secondary": 2,
		}

		level = xmltag.getAttribute("level")
		if level:
			# the level defaults to 1 - i.e. no indent
			indent = 2 * (int(level) - 1)
		else:
			indent = mapping.get(xmltag.getAttribute("type"), 0)

		#if indent:
		if self.in_indent:
			dprint(WARNING, "Nested indented l's", self.u.key.getText())

		self.in_indent = True
		if not self.in_copy_verses_mode:
			self.buf += '<div class="indentedline width-%d" source="l">' % indent
		self.blocklevel_start()