Wikipedia: revamp languages handling

Replace the cumbersome implementation of language rotation
with a more natural language selection:
- replace the "en > fr" button with a "Language" button,
  which on tap shows a popup with the user languages allowing
  direct selection (instead of having to rotate through
  all the intermediate languages and wait for each result)
- we don't touch anymore the user-set wikipedia_languages
  array when switching language
- the newly selected language is stored in doc_settings, and
  will be used for next queries on this book. It is also
  stored in G_reader_settings as the language to be used
  for next newly opened books and for lookups done when
  in FileBrowser

Also:
On Wikipedia full articles, the top left hamburger menu
shows a popup with the other Wikipedia languages the
current article is available for, and allows reading
them.
Wikipedia article ToC: the 'sections' properties
of the Wikipedia API is now deprecated: use its
replacement 'tocdata'.
This commit is contained in:
poire-z committed 2026-01-08 21:11:30 +01:00
1 parent 43d52a1c08
commit e1c5f35d37
3 files changed
+153 -95

No files matched your search

@@ -31,6 +31,9 @@ local ReaderWikipedia = ReaderDictionary:extend{
function ReaderWikipedia:init()
self:registerKeyEvents()
self.wiki_languages = {}
-- Read this from G_reader_settings for when used in FileBrowser
-- (:onReadSettings() may replace it from the one saved in doc_settings)
self.wiki_last_language = G_reader_settings:readSetting("wikipedia_last_language")
self.ui.menu:registerToMainMenu(self)
if not wikipedia_history then
wikipedia_history = LuaData:open(DataStorage:getSettingsDir() .. "/wikipedia_history.lua", "WikipediaHistory")
@@ -92,6 +95,7 @@ function ReaderWikipedia:addToMainMenu(menu_items)
local kv_pairs = {}
local previous_title
self:initLanguages() -- so current lang is set
local main_lang = self.wiki_languages[1]:lower()
for i = #wikipedia_history_table, 1, -1 do
local value = wikipedia_history_table[i]
if value.book_title ~= previous_title then
@@ -103,8 +107,8 @@ function ReaderWikipedia:addToMainMenu(menu_items)
type_s = "▤ " -- full page: large square with lines
end
local lang_s = ""
if value.lang ~= self.wiki_languages[1]:lower() then
-- We show item's lang only when different from current lang
if value.lang ~= main_lang then
-- We show item's language only when different from first user-set wiki language
lang_s = " ["..value.lang:upper().."]"
end
local text = type_s .. value.word .. lang_s
@@ -384,12 +388,13 @@ function ReaderWikipedia:lookupWikipedia(word, is_sane, box, get_fullpage, force
self:initLanguages(word)
local lang
if forced_lang then
-- use provided lang (from readerlink when noticing that an external link is a wikipedia url,
-- use provided language (from readerlink when noticing that an external link is a wikipedia url,
-- of from Wikipedia lookup history, or when switching to next language in DictQuickLookup)
lang = forced_lang
else
-- use first lang from self.wiki_languages
lang = self.wiki_languages[1]
-- use last language selected, or first language from self.wiki_languages
lang = self.wiki_last_language or self.wiki_languages[1]
self.wiki_last_language_used = true
end
logger.dbg("lookup word:", word, box, get_fullpage)
-- no need to clean word if get_fullpage, as it is the exact wikipetia page title
@@ -415,7 +420,7 @@ function ReaderWikipedia:lookupWikipedia(word, is_sane, box, get_fullpage, force
})
end
-- Fix lookup message to include lang and set appropriate error texts
-- Fix lookup message to include language and set appropriate error texts
local no_result_text, req_failure_text
if get_fullpage then
self.lookup_msg = T(_("Retrieving Wikipedia %2 article:\n%1"), "%1", lang:upper())
@@ -477,6 +482,7 @@ function ReaderWikipedia:lookupWikipedia(word, is_sane, box, get_fullpage, force
lang = lang,
rtl_lang = Wikipedia:isWikipediaLanguageRTL(lang),
images = page.images,
lang_links = page.langlinks, -- available when get_fullpage
}
table.insert(results, result)
end
@@ -501,67 +507,45 @@ function ReaderWikipedia:lookupWikipedia(word, is_sane, box, get_fullpage, force
lang = lang,
}
}
-- Also put this as a k/v into the results array: if we end up with this
-- after lang rotation, DictQuickLookup will not update this lang rotation.
results.no_result = true
logger.dbg("dummy result table:", word, results)
end
self:showDict(word, results, box, nil, dict_close_callback)
end
function ReaderWikipedia:getWikiLanguages(first_lang)
-- Always return a copy of ours
local wiki_languages = {unpack(self.wiki_languages)}
local is_first_lang = first_lang == wiki_languages[1]
if not is_first_lang then
-- return a wiki_languages with requested lang at first
if util.arrayContains(wiki_languages, first_lang) then
-- first_lang in the list: rotate until it is first
while wiki_languages[1] ~= first_lang do
table.insert(wiki_languages, table.remove(wiki_languages, 1))
end
else
-- first_lang not in the list: add it first
table.insert(wiki_languages, 1, first_lang)
end
function ReaderWikipedia:getWikiLanguages()
local wiki_languages = self.wiki_languages
-- If for some reason (wiki languages array changed) the last language is no longer
-- in the array, add it at the end (so we at least get 2 languages so the menu
-- is enabled and the user can switch)
if self.wiki_last_language and not util.arrayContains(wiki_languages, self.wiki_last_language) then
wiki_languages = {unpack(self.wiki_languages)} -- copy
table.insert(wiki_languages, self.wiki_last_language)
end
local update_wiki_languages_on_close = false
if DictQuickLookup.rotated_update_wiki_languages_on_close ~= nil then
-- Flag set by DictQuickLookup when rotating, forwarding the flag
-- of the rotated out DictQuickLookup instance: trust it
update_wiki_languages_on_close = DictQuickLookup.rotated_update_wiki_languages_on_close
DictQuickLookup.rotated_update_wiki_languages_on_close = nil
else
-- Not a rotation. Only if it's the first request with the current
-- first language, we will have it (and any lang rotation from it)
-- update the main ReaderWikipedia.wiki_languages. That is, queries
-- from Wikipedia url links for another language, or from Wikipedia
-- lookup history with other languages (and any lang rotation made
-- from them) won't update it.
if is_first_lang then
update_wiki_languages_on_close = true
for i = #DictQuickLookup.window_list-1, 1, -1 do -- (ignore the last one, which is the one calling this)
if DictQuickLookup.window_list[i].is_wiki then
-- Another upper Wikipedia result: only this one may update it
update_wiki_languages_on_close = false
break
end
end
end
end
return wiki_languages, update_wiki_languages_on_close
return wiki_languages, self.wiki_last_language or self.wiki_languages[1]
end
function ReaderWikipedia:onUpdateWikiLanguages(wiki_languages)
-- Update our self.wiki_languages in-place
while table.remove(self.wiki_languages) do end
for _, lang in ipairs(wiki_languages) do
table.insert(self.wiki_languages, lang)
end
function ReaderWikipedia:setLastSelectedLanguage(lang)
self.wiki_last_language = lang
self.wiki_last_language_updated = true
end
function ReaderWikipedia:onReadSettings(config)
self.wiki_last_language = config:readSetting("wikipedia_language")
or G_reader_settings:readSetting("wikipedia_last_language")
end
-- override onSaveSettings in ReaderDictionary
function ReaderWikipedia:onSaveSettings()
if self.ui.doc_settings and self.wiki_last_language_used then
-- Only save it if it has really been used (which, if it came from G_reader_settings,
-- means the user is fine with this language, otherwise he will have changed it;
-- if not, on a next opening we will get to use the actual global setting)
self.ui.doc_settings:saveSetting("wikipedia_language", self.wiki_last_language)
end
if self.wiki_last_language_updated then
-- Only save it if it has been changed (so a different wikipedia_language coming
-- from the book previous docsetting don't get to be the new global)
G_reader_settings:saveSetting("wikipedia_last_language", self.wiki_last_language)
end
end
function ReaderWikipedia:onShowWikipediaLookup()
+103 -31
View File
@@ -66,8 +66,6 @@ local DictQuickLookup = InputContainer:extend{
-- Static class member, holds a ref to the currently opened widgets (in instantiation order).
window_list = {},
-- Static class member, used by ReaderWiktionary to communicate state from a closed widget to the next opened one.
rotated_update_wiki_languages_on_close = nil,
_is_temporary_large_window = false,
}
@@ -85,7 +83,8 @@ end
function DictQuickLookup:canSearch()
if self.is_wiki then
-- In the Wiki variant of this widget, the Search button is coopted to cycle between enabled languages.
-- In the Wiki variant of this widget, the Search button is coopted to show and select
-- between user-defined (or UI+book) languages.
if #self.wiki_languages > 1 then
return true
end
@@ -226,9 +225,7 @@ function DictQuickLookup:init()
-- And here comes the initial widget layout...
if self.is_wiki then
-- Get a copy of ReaderWikipedia.wiki_languages, with the current result
-- lang first (rotated, or added)
self.wiki_languages, self.update_wiki_languages_on_close = self.ui.wikipedia:getWikiLanguages(self.lang)
self.wiki_languages, self.wiki_last_language = self.ui.wikipedia:getWikiLanguages()
end
-- Bigger window if fullpage Wikipedia article being shown,
@@ -259,7 +256,11 @@ function DictQuickLookup:init()
left_icon = "appbar.menu",
left_icon_tap_callback = function()
if self.is_wiki then
self:showWikiResultsMenu()
if self.is_wiki_fullpage then
self:showWikiFullOtherLangsMenu()
else
self:showWikiResultsMenu()
end
else
self:onShowResultsMenu()
end
@@ -375,8 +376,7 @@ function DictQuickLookup:init()
callback = function()
local InfoMessage = require("ui/widget/infomessage")
local ConfirmBox = require("ui/widget/confirmbox")
-- if forced_lang was specified, it may not be in our wiki_languages,
-- but ReaderWikipedia will have put it in result.lang
-- We should have a self.lang set, but let's have a fallback
local lang = self.lang or self.wiki_languages[1]
-- Find a directory to save file into
local dir
@@ -498,7 +498,7 @@ function DictQuickLookup:init()
text_func = function()
if self.is_wiki then
-- @translators Full Wikipedia article.
return C_("Button", "Wikipedia full")
return C_("Wikipedia", "Full article")
else
return _("Wikipedia")
end
@@ -509,23 +509,49 @@ function DictQuickLookup:init()
end)
end,
},
-- Rotate thru available wikipedia languages, or Search in book if dict window
-- Allow selecting a different wikipedia language, or Search in book if dict window
{
id = "search",
-- if more than one language, enable it and display "current lang > next lang"
-- otherwise, just display current lang
text = self.is_wiki
and ( #self.wiki_languages > 1 and BD.wrap(self.wiki_languages[1]).." > "..BD.wrap(self.wiki_languages[2])
or self.wiki_languages[1] ) -- (this " > " will be auro-mirrored by bidi)
or _("Search"),
text = self.is_wiki and C_("Wikipedia", "Language").." \u{2261}" or _("Search"),
enabled = self:canSearch(),
callback = function()
if self.is_wiki then
-- We're rotating: forward this flag from the one we're closing so
-- that ReaderWikipedia can give it to the one we'll be showing
DictQuickLookup.rotated_update_wiki_languages_on_close = self.update_wiki_languages_on_close
self:lookupWikipedia(false, nil, nil, self.wiki_languages[2])
self:onClose(true)
local button_dialog
local lang_buttons = {}
for idx, lang in ipairs(self.wiki_languages) do
local bold = lang == self.lang -- bold the language currently shown
local row = {
{
text = lang,
font_bold = bold,
align = "left",
callback = function()
self.ui.wikipedia:setLastSelectedLanguage(lang)
self:lookupWikipedia(false, nil, nil, lang)
self:onClose(true)
end,
},
}
-- Show them in reverse, so first/prefered ones are at the bottom near the button where the user tap'ed
table.insert(lang_buttons, 1, row)
end
local search_btn = self.button_table:getButtonById("search")
button_dialog = ButtonDialog:new{
buttons = lang_buttons,
width = search_btn.dimen.w,
anchor = function()
return Geom:new{
x = search_btn.dimen.x,
-- We want its bottom border overlapping the whole DictQuickLookup window bottom border
y = self.dict_frame.dimen.y + self.dict_frame.dimen.h,
}
end,
tap_close_callback = function()
self.menu_opened[button_dialog] = nil
end
}
self.menu_opened[button_dialog] = true
UIManager:show(button_dialog)
else
self.ui:handleEvent(Event:new("HighlightSearch"))
self:onClose(true) -- don't unhighlight (or we might erase a search hit)
@@ -1286,13 +1312,6 @@ function DictQuickLookup:onClose(no_clear)
DictQuickLookup.temp_large_window_request = nil
end
if self.update_wiki_languages_on_close then
-- except if we got no result for current language
if not self.results.no_result then
self.ui:handleEvent(Event:new("UpdateWikiLanguages", self.wiki_languages))
end
end
if self.save_highlight then
self.highlight:saveHighlight()
self.highlight:clear()
@@ -1508,8 +1527,8 @@ end
function DictQuickLookup:lookupWikipedia(get_fullpage, word, is_sane, lang, dict_close_callback)
if not lang then
-- Use the lang of the current or nearest is_wiki DictQuickLookup.
-- Otherwise, first lang in ReaderWikipedia.wiki_languages will be used.
-- Use the language of the current or nearest is_wiki DictQuickLookup.
-- Otherwise, LookupWikipedia will use wiki_last_language
for i = #DictQuickLookup.window_list, 1, -1 do
local window = DictQuickLookup.window_list[i]
if window.is_wiki and window.lang then
@@ -1778,6 +1797,59 @@ function DictQuickLookup:showWikiResultsMenu()
UIManager:show(button_dialog)
end
function DictQuickLookup:showWikiFullOtherLangsMenu()
-- Show one row for each article available in other languages
local max_width = math.floor(self.width * 0.75)
local font_size = 18
local button_dialog
local buttons = {}
local lang_links = self.results[1].lang_links
-- We'll show the articles in the wikipedia languages set by the user first (and in bold)
local user_wiki_languages = {}
for _, lang in ipairs(self.wiki_languages) do
user_wiki_languages[lang] = true
end
local nb_user_lang_links = 0
for i=1, #lang_links do
if user_wiki_languages[lang_links[i].lang] then
nb_user_lang_links = nb_user_lang_links + 1
table.insert(lang_links, nb_user_lang_links, table.remove(lang_links, i))
end
end
for idx, lang_link in ipairs(lang_links) do
local lang, page = lang_link.lang, lang_link["*"]
local bold = idx <= nb_user_lang_links
local row = {{
text = T("%1: %2", lang_link.lang, lang_link["*"]),
lang = lang,
font_size = font_size,
font_bold = bold,
align = "left",
callback = function()
-- As the new article will be displayed in a new window, keep the
-- popup menu opened so we get to it when done to try another lang
self:lookupWikipedia(true, page, true, lang)
end,
}}
table.insert(buttons, row)
end
button_dialog = ButtonDialog:new{
width = max_width,
shrink_unneeded_width = true,
buttons = buttons,
anchor = function()
return self.dict_title.left_button.image.dimen, true -- pop down
end,
tap_close_callback = function()
self.menu_scrolled_offsets["wikifull"] = button_dialog:getScrolledOffset()
self.menu_opened[button_dialog] = nil
end
}
button_dialog:setScrolledOffset(self.menu_scrolled_offsets["wikifull"])
self.menu_opened[button_dialog] = true
UIManager:show(button_dialog)
end
function DictQuickLookup:clearDictionaryHighlight()
if self.shw_widget then
self.shw_widget.htmlbox_widget:scheduleClearHighlightAndRedraw()
+10 -8
View File
@@ -15,8 +15,8 @@ local T = ffiutil.template
-- https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=jsonfm&explaintext=&redirects=&titles=E-reader
--
-- To get parsed HTML :
-- https://en.wikipedia.org/w/api.php?action=parse&page=E-book
-- https://en.wikipedia.org/w/api.php?action=parse&page=E-book&prop=text|sections|displaytitle|revid&disablelimitreport=&disableeditsection
-- https://en.wikipedia.org/w/api.php?action=parse&page=Ebook
-- https://en.wikipedia.org/w/api.php?action=parse&page=Ebook&prop=text|tocdata|displaytitle|revid&disablelimitreport=&disableeditsection
-- https://www.mediawiki.org/wiki/API:Parsing_wikitext#parse
--]]
@@ -44,19 +44,20 @@ local Wikipedia = {
-- Full article, parsed to output text (+ main thumbnail image)
wiki_full_params = {
action = "query",
prop = "extracts|pageimages",
prop = "extracts|pageimages|langlinks",
format = "json",
-- exintro = nil, -- get more than only the intro
explaintext = "",
redirects = "",
-- title = nil, -- text to lookup, will be added below
lllimit = 500, -- (default nb of langlinks returned is 10)
},
-- Full article, parsed to output HTML, for Save as EPUB
wiki_phtml_params = {
action = "parse",
format = "json",
-- we only need the following pieces of information
prop = "text|sections|displaytitle|revid",
prop = "text|tocdata|displaytitle|revid",
-- page = nil, -- text to lookup, will be added below
-- disabletoc = "", -- if we want to remove toc IN html
-- 20230722: there is no longer the TOC in the html no matter this param
@@ -715,7 +716,7 @@ function Wikipedia:createEpub(epub_path, page, lang, with_images)
local wiki_base_url = self:getWikiServer(lang)
-- Get infos from wikipedia result
-- (see example at https://en.wikipedia.org/w/api.php?action=parse&page=E-book&prop=text|sections|displaytitle|revid&disablelimitreport=&disableeditsection)
-- (see example at https://en.wikipedia.org/w/api.php?action=parse&page=Ebook&prop=text|tocdata|displaytitle|revid&disablelimitreport=&disableeditsection)
local cancelled = false
local html = phtml.text["*"] -- html content
local page_cleaned = page:gsub("_", " ") -- page title
@@ -726,7 +727,8 @@ function Wikipedia:createEpub(epub_path, page, lang, with_images)
-- encodes. (We don't escape < or > as these JSON strings may contain HTML tags)
page_cleaned = util.htmlEntitiesToUtf8(page_cleaned):gsub("&", "&#38;")
page_htmltitle = util.htmlEntitiesToUtf8(page_htmltitle):gsub("&", "&#38;")
local sections = phtml.sections -- Wikipedia provided TOC
-- Wikipedia provided TOC (might be "null", that JSON.decode() converts to a function)
local sections = type(phtml.tocdata) == "table" and phtml.tocdata.sections or {}
local bookid = string.format("wikipedia_%s_%s_%s", lang, phtml.pageid, phtml.revid)
-- Not sure if this bookid may ever be used by indexing software/calibre, but if it is,
-- should it changes if content is updated (as now, including the wikipedia revisionId),
@@ -1343,7 +1345,7 @@ abbr.abbr {
-- We need to do as for page_htmltitle above. But headings can contain
-- html entities for < and > that we need to put back as html entities
s_title = util.htmlEntitiesToUtf8(s_title):gsub("&", "&#38;"):gsub(">", "&gt;"):gsub("<", "&lt;")
local s_level = s.toclevel
local s_level = s.tocLevel
if s_level > depth then
depth = s_level -- max depth required in toc.ncx
end
@@ -1415,7 +1417,7 @@ abbr.abbr {
-- for the links to be valid.
local s_anchor = s.anchor:gsub("&", "&amp;"):gsub('"', "&quot;"):gsub(">", "&gt;"):gsub("<", "&lt;")
local s_title = string.format("%s %s", s.number, s.line)
local s_level = s.toclevel
local s_level = s.tocLevel
if s_level == cur_level then
table.insert(toc_html_parts, "</li>")
elseif s_level < cur_level then