opt: rewrite the logic of determine the existence of audio link (#1860)

* opt: rewrite the logic of determine the existence of audio link



---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
This commit is contained in:
xiaoyifang 2024-10-24 21:32:21 +08:00 committed by GitHub
parent e749a6077f
commit 01b9814760
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 53 additions and 95 deletions

View file

@ -11,40 +11,9 @@ std::string addAudioLink( std::string const & url, std::string const & dictionar
std::string addAudioLink( QString const & url, std::string const & dictionaryId ) std::string addAudioLink( QString const & url, std::string const & dictionaryId )
{ {
if ( url.isEmpty() || url.length() < 2 ) { if ( url.isEmpty() ) {
return {}; return {};
} }
GlobalBroadcaster::instance()->pronounce_engine.sendAudio( dictionaryId, url.mid( 1, url.length() - 2 ) ); GlobalBroadcaster::instance()->pronounce_engine.sendAudio( dictionaryId, url );
return "";
return std::string( "<script type=\"text/javascript\">" + makeAudioLinkScript( url.toStdString(), dictionaryId )
+ "</script>" );
}
std::string makeAudioLinkScript( std::string const & url, std::string const & dictionaryId )
{
/// Convert "'" to "\'" - this char broke autoplay of audiolinks
std::string ref;
bool escaped = false;
for ( const char ch : url ) {
if ( escaped ) {
ref += ch;
escaped = false;
continue;
}
if ( ch == '\'' ) {
ref += '\\';
}
ref += ch;
escaped = ( ch == '\\' );
}
const std::string audioLinkForDict = QString::fromStdString( R"(
if(!gdAudioMap.has('%1')){
gdAudioMap.set('%1',%2);
}
)" )
.arg( QString::fromStdString( dictionaryId ), QString::fromStdString( url ) )
.toStdString();
return "gdAudioLinks.first = gdAudioLinks.first || " + ref + ";" + audioLinkForDict;
} }

View file

@ -15,6 +15,5 @@
/// The dictionary id is used to make active dictionary feature work. /// The dictionary id is used to make active dictionary feature work.
std::string addAudioLink( std::string const & url, std::string const & dictionaryId ); std::string addAudioLink( std::string const & url, std::string const & dictionaryId );
std::string addAudioLink( QString const & url, std::string const & dictionaryId ); std::string addAudioLink( QString const & url, std::string const & dictionaryId );
std::string makeAudioLinkScript( std::string const & url, std::string const & dictionaryId );
#endif #endif

View file

@ -861,7 +861,7 @@ string DslDictionary::nodeToHtml( ArticleDom::Node const & node )
string ref = string( "\"" ) + url.toEncoded().data() + "\""; string ref = string( "\"" ) + url.toEncoded().data() + "\"";
result += addAudioLink( ref, getId() ); result += addAudioLink( url.toEncoded(), getId() );
result += "<span class=\"dsl_s_wav\"><a href=" + ref result += "<span class=\"dsl_s_wav\"><a href=" + ref
+ R"(><img src="qrc:///icons/playsound.png" border="0" align="absmiddle" alt="Play"/></a></span>)"; + R"(><img src="qrc:///icons/playsound.png" border="0" align="absmiddle" alt="Play"/></a></span>)";

View file

@ -1569,7 +1569,7 @@ QByteArray EpwingBook::handleWave( EB_Hook_Code code, const unsigned int * argv
url.setPath( Utils::Url::ensureLeadingSlash( name ) ); url.setPath( Utils::Url::ensureLeadingSlash( name ) );
string ref = string( "\"" ) + url.toEncoded().data() + "\""; string ref = string( "\"" ) + url.toEncoded().data() + "\"";
QByteArray result = addAudioLink( ref, dictID.toUtf8().data() ).c_str(); QByteArray result = addAudioLink( url.toEncoded(), dictID.toUtf8().data() ).c_str();
result += QByteArray( "<span class=\"epwing_wav\"><a href=" ) + ref.c_str() + ">"; result += QByteArray( "<span class=\"epwing_wav\"><a href=" ) + ref.c_str() + ">";

View file

@ -260,7 +260,7 @@ void ForvoArticleRequest::requestFinished( QNetworkReply * r )
string ref = string( "\"" ) + url.toEncoded().data() + "\""; string ref = string( "\"" ) + url.toEncoded().data() + "\"";
articleBody += addAudioLink( ref, dictionaryId ).c_str(); articleBody += addAudioLink( url.toEncoded(), dictionaryId ).c_str();
bool isMale = ( item.namedItem( "sex" ).toElement().text().toLower() != "f" ); bool isMale = ( item.namedItem( "sex" ).toElement().text().toLower() != "f" );

View file

@ -789,9 +789,11 @@ QString & GlsDictionary::filterResource( QString & article )
articleNewText += match.captured(); articleNewText += match.captured();
} }
else { else {
std::string href = "\"gdau://" + getId() + "/" + src.toUtf8().data() + "\""; std::string audioLink = "gdau://" + getId() + "/" + src.toUtf8().data();
std::string href = "\"" + audioLink + "\"";
QString newTag = QString::fromUtf8( QString newTag = QString::fromUtf8(
( addAudioLink( href, getId() ) + "<span class=\"gls_wav\"><a href=" + href + ">" ).c_str() ); ( addAudioLink( audioLink, getId() ) + "<span class=\"gls_wav\"><a href=" + href + ">" ).c_str() );
newTag += match.captured( 4 ); newTag += match.captured( 4 );
if ( match.captured( 4 ).indexOf( "<img " ) < 0 ) { if ( match.captured( 4 ).indexOf( "<img " ) < 0 ) {
newTag += R"( <img src="qrc:///icons/playsound.png" border="0" alt="Play">)"; newTag += R"( <img src="qrc:///icons/playsound.png" border="0" alt="Play">)";

View file

@ -357,7 +357,7 @@ void LinguaArticleRequest::requestFinished( QNetworkReply * r )
string title = pageJsonObj[ "title" ].toString().toHtmlEscaped().toStdString(); string title = pageJsonObj[ "title" ].toString().toHtmlEscaped().toStdString();
string audiolink = string audiolink =
pageJsonObj[ "imageinfo" ].toArray().at( 0 ).toObject()[ "url" ].toString().toHtmlEscaped().toStdString(); pageJsonObj[ "imageinfo" ].toArray().at( 0 ).toObject()[ "url" ].toString().toHtmlEscaped().toStdString();
articleBody += addAudioLink( "\"" + audiolink + "\"", dictionaryId ); articleBody += addAudioLink( audiolink, dictionaryId );
articleBody += R"(<a href=")"; articleBody += R"(<a href=")";
articleBody += audiolink; articleBody += audiolink;
articleBody += R"(">)"; articleBody += R"(">)";

View file

@ -277,7 +277,7 @@ sptr< Dictionary::DataRequest > LsaDictionary::getArticle( wstring const & word,
string ref = string( "\"" ) + url.toEncoded().data() + "\""; string ref = string( "\"" ) + url.toEncoded().data() + "\"";
result += addAudioLink( ref, getId() ); result += addAudioLink( url.toEncoded(), getId() );
result += "<td><a href=" + ref + R"(><img src="qrc:///icons/playsound.png" border="0" alt="Play"/></a></td>)"; result += "<td><a href=" + ref + R"(><img src="qrc:///icons/playsound.png" border="0" alt="Play"/></a></td>)";
result += "<td><a href=" + ref + ">" + i->second + "</a></td>"; result += "<td><a href=" + ref + ">" + i->second + "</a></td>";
@ -294,7 +294,7 @@ sptr< Dictionary::DataRequest > LsaDictionary::getArticle( wstring const & word,
string ref = string( "\"" ) + url.toEncoded().data() + "\""; string ref = string( "\"" ) + url.toEncoded().data() + "\"";
result += addAudioLink( ref, getId() ); result += addAudioLink( url.toEncoded(), getId() );
result += "<td><a href=" + ref + R"(><img src="qrc:///icons/playsound.png" border="0" alt="Play"/></a></td>)"; result += "<td><a href=" + ref + R"(><img src="qrc:///icons/playsound.png" border="0" alt="Play"/></a></td>)";
result += "<td><a href=" + ref + ">" + i->second + "</a></td>"; result += "<td><a href=" + ref + ">" + i->second + "</a></td>";

View file

@ -922,9 +922,8 @@ void MdxDictionary::replaceLinks( QString & id, QString & article )
// sounds and audio link script // sounds and audio link script
QString newTxt = match.captured( 1 ) + match.captured( 2 ) + "gdau://" + id + "/" + match.captured( 3 ) QString newTxt = match.captured( 1 ) + match.captured( 2 ) + "gdau://" + id + "/" + match.captured( 3 )
+ match.captured( 2 ) + R"( onclick="return false;" )"; + match.captured( 2 ) + R"( onclick="return false;" )";
newLink = newLink = QString::fromUtf8(
QString::fromUtf8( addAudioLink( "gdau://" + getId() + "/" + match.captured( 3 ).toUtf8().data(), getId() ).c_str() )
addAudioLink( "\"gdau://" + getId() + "/" + match.captured( 3 ).toUtf8().data() + "\"", getId() ).c_str() )
+ newLink.replace( match.capturedStart(), match.capturedLength(), newTxt ); + newLink.replace( match.capturedStart(), match.capturedLength(), newTxt );
} }

View file

@ -608,7 +608,7 @@ void MediaWikiArticleRequest::requestFinished( QNetworkReply * r )
if ( ref.startsWith( "//" ) ) { if ( ref.startsWith( "//" ) ) {
ref = wikiUrl.scheme() + ":" + ref; ref = wikiUrl.scheme() + ":" + ref;
} }
auto script = addAudioLink( "\"" + ref + "\"", this->dictPtr->getId() ); auto script = addAudioLink( ref, this->dictPtr->getId() );
QString audio_url = QString::fromStdString( script ) + "<a href=\"" + ref QString audio_url = QString::fromStdString( script ) + "<a href=\"" + ref
+ R"("><img src="qrc:///icons/playsound.png" border="0" align="absmiddle" alt="Play"/></a>)"; + R"("><img src="qrc:///icons/playsound.png" border="0" align="absmiddle" alt="Play"/></a>)";
articleNewString += audio_url; articleNewString += audio_url;

View file

@ -95,7 +95,7 @@ ProgramsDictionary::getArticle( wstring const & word, vector< wstring > const &,
string ref = string( "\"" ) + url.toEncoded().data() + "\""; string ref = string( "\"" ) + url.toEncoded().data() + "\"";
result += addAudioLink( ref, getId() ); result += addAudioLink( url.toEncoded(), getId() );
result += "<td><a href=" + ref + R"(><img src="qrc:///icons/playsound.png" border="0" alt="Play"/></a></td>)"; result += "<td><a href=" + ref + R"(><img src="qrc:///icons/playsound.png" border="0" alt="Play"/></a></td>)";
result += "<td><a href=" + ref + ">" + Html::escape( wordUtf8 ) + "</a></td>"; result += "<td><a href=" + ref + ">" + Html::escape( wordUtf8 ) + "</a></td>";

View file

@ -229,7 +229,7 @@ sptr< Dictionary::DataRequest > SoundDirDictionary::getArticle( wstring const &
string ref = string( "\"" ) + url.toEncoded().data() + "\""; string ref = string( "\"" ) + url.toEncoded().data() + "\"";
result += addAudioLink( ref, getId() ); result += addAudioLink( url.toEncoded(), getId() );
result += "<td><a href=" + ref + R"(><img src="qrc:///icons/playsound.png" border="0" alt="Play"/></a></td>)"; result += "<td><a href=" + ref + R"(><img src="qrc:///icons/playsound.png" border="0" alt="Play"/></a></td>)";
result += "<td><a href=" + ref + ">" + _displayName + "</a></td>"; result += "<td><a href=" + ref + ">" + _displayName + "</a></td>";
@ -277,7 +277,7 @@ sptr< Dictionary::DataRequest > SoundDirDictionary::getArticle( wstring const &
string ref = string( "\"" ) + url.toEncoded().data() + "\""; string ref = string( "\"" ) + url.toEncoded().data() + "\"";
result += addAudioLink( ref, getId() ); result += addAudioLink( url.toEncoded(), getId() );
result += "<td><a href=" + ref + R"(><img src="qrc:///icons/playsound.png" border="0" alt="Play"/></a></td>)"; result += "<td><a href=" + ref + R"(><img src="qrc:///icons/playsound.png" border="0" alt="Play"/></a></td>)";
result += "<td><a href=" + ref + ">" + _displayName + "</a></td>"; result += "<td><a href=" + ref + ">" + _displayName + "</a></td>";

View file

@ -543,8 +543,9 @@ string StardictDictionary::handleResource( char type, char const * resource, siz
articleNewText += match.captured(); articleNewText += match.captured();
} }
else { else {
std::string href = "\"gdau://" + getId() + "/" + src.toUtf8().data() + "\""; std::string audioLink = "gdau://" + getId() + "/" + src.toUtf8().data();
std::string newTag = addAudioLink( href, getId() ) + "<span class=\"sdict_h_wav\"><a href=" + href + ">"; std::string href = "\"" + audioLink + "\"";
std::string newTag = addAudioLink( audioLink, getId() ) + "<span class=\"sdict_h_wav\"><a href=" + href + ">";
newTag += match.captured( 4 ).toUtf8().constData(); newTag += match.captured( 4 ).toUtf8().constData();
if ( match.captured( 4 ).indexOf( "<img " ) < 0 ) { if ( match.captured( 4 ).indexOf( "<img " ) < 0 ) {
newTag += R"( <img src="qrc:///icons/playsound.png" border="0" alt="Play">)"; newTag += R"( <img src="qrc:///icons/playsound.png" border="0" alt="Play">)";

View file

@ -98,7 +98,7 @@ VoiceEnginesDictionary::getArticle( wstring const & word, vector< wstring > cons
string encodedUrl = url.toEncoded().data(); string encodedUrl = url.toEncoded().data();
string ref = string( "\"" ) + encodedUrl + "\""; string ref = string( "\"" ) + encodedUrl + "\"";
result += addAudioLink( ref, getId() ); result += addAudioLink( encodedUrl, getId() );
result += "<td><a href=" + ref + R"(><img src="qrc:///icons/playsound.png" border="0" alt="Play"/></a></td>)"; result += "<td><a href=" + ref + R"(><img src="qrc:///icons/playsound.png" border="0" alt="Play"/></a></td>)";
result += "<td><a href=" + ref + ">" + Html::escape( wordUtf8 ) + "</a></td>"; result += "<td><a href=" + ref + ">" + Html::escape( wordUtf8 ) + "</a></td>";

View file

@ -661,9 +661,7 @@ string convert( string const & in,
el_script.setAttribute( "type", "text/javascript" ); el_script.setAttribute( "type", "text/javascript" );
parent.replaceChild( el_script, el ); parent.replaceChild( el_script, el );
QDomText el_txt = dd.createTextNode( addAudioLink( string( "\"" ) + url.toEncoded().data() + "\"", dictPtr->getId() );
makeAudioLinkScript( string( "\"" ) + url.toEncoded().data() + "\"", dictPtr->getId() ).c_str() );
el_script.appendChild( el_txt );
QDomElement el_span = dd.createElement( "span" ); QDomElement el_span = dd.createElement( "span" );
el_span.setAttribute( "class", "xdxf_wav" ); el_span.setAttribute( "class", "xdxf_wav" );

View file

@ -263,7 +263,7 @@ sptr< Dictionary::DataRequest > ZipSoundsDictionary::getArticle( wstring const &
string ref = string( "\"" ) + url.toEncoded().data() + "\""; string ref = string( "\"" ) + url.toEncoded().data() + "\"";
result += addAudioLink( ref, getId() ); result += addAudioLink( url.toEncoded(), getId() );
result += "<td><a href=" + ref + R"(><img src="qrc:///icons/playsound.png" border="0" alt="Play"/></a></td>)"; result += "<td><a href=" + ref + R"(><img src="qrc:///icons/playsound.png" border="0" alt="Play"/></a></td>)";
result += "<td><a href=" + ref + ">" + Html::escape( displayedName ) + "</a></td>"; result += "<td><a href=" + ref + ">" + Html::escape( displayedName ) + "</a></td>";
@ -305,7 +305,7 @@ sptr< Dictionary::DataRequest > ZipSoundsDictionary::getArticle( wstring const &
string ref = string( "\"" ) + url.toEncoded().data() + "\""; string ref = string( "\"" ) + url.toEncoded().data() + "\"";
result += addAudioLink( ref, getId() ); result += addAudioLink( url.toEncoded(), getId() );
result += "<td><a href=" + ref + R"(><img src="qrc:///icons/playsound.png" border="0" alt="Play"/></a></td>)"; result += "<td><a href=" + ref + R"(><img src="qrc:///icons/playsound.png" border="0" alt="Play"/></a></td>)";
result += "<td><a href=" + ref + ">" + Html::escape( displayedName ) + "</a></td>"; result += "<td><a href=" + ref + ">" + Html::escape( displayedName ) + "</a></td>";

View file

@ -8,7 +8,6 @@ PronounceEngine::PronounceEngine( QObject * parent ):
{ {
} }
void PronounceEngine::reset() void PronounceEngine::reset()
{ {
QMutexLocker _( &mutex ); QMutexLocker _( &mutex );
@ -48,6 +47,7 @@ void PronounceEngine::finishDictionary( std::string dictId )
} }
state = PronounceState::OCCUPIED; state = PronounceState::OCCUPIED;
} }
emit emitAudio( dictAudioMap[ dictId ].first() ); auto link = dictAudioMap[ dictId ].first();
emit emitAudio( link );
} }
} }

View file

@ -1,12 +1,3 @@
// seperate from cpp code.
var gdAudioLinks = {
first: null,
current: null,
};
//store dictionary audio link.
var gdAudioMap = new Map();
function gdMakeArticleActive(newId, noEvent) { function gdMakeArticleActive(newId, noEvent) {
const gdCurrentArticle = const gdCurrentArticle =
document.querySelector(".gdactivearticle").attributes.id; document.querySelector(".gdactivearticle").attributes.id;
@ -16,7 +7,6 @@ function gdMakeArticleActive(newId, noEvent) {
.classList.remove("gdactivearticle"); .classList.remove("gdactivearticle");
const newFormId = "gdfrom-" + newId; const newFormId = "gdfrom-" + newId;
document.querySelector(`#${newFormId}`).classList.add("gdactivearticle"); document.querySelector(`#${newFormId}`).classList.add("gdactivearticle");
gdAudioLinks.current = newId;
if (!noEvent) articleview.onJsActiveArticleChanged("gdfrom-" + newId); if (!noEvent) articleview.onJsActiveArticleChanged("gdfrom-" + newId);
} }
} }

View file

@ -277,6 +277,16 @@ unsigned ArticleView::getCurrentGroupId()
return currentGroupId; return currentGroupId;
} }
void ArticleView::setAudioLink( QString audioLink )
{
audioLink_ = audioLink;
}
QString ArticleView::getAudioLink() const
{
return audioLink_;
}
ArticleView::~ArticleView() ArticleView::~ArticleView()
{ {
cleanupTemp(); cleanupTemp();
@ -302,6 +312,7 @@ void ArticleView::showDefinition( QString const & word,
currentActiveDictIds.clear(); currentActiveDictIds.clear();
// first, let's stop the player // first, let's stop the player
audioPlayer->stop(); audioPlayer->stop();
audioLink_.clear();
QUrl req; QUrl req;
Contexts contexts( contexts_ ); Contexts contexts( contexts_ );
@ -376,6 +387,7 @@ void ArticleView::showDefinition( QString const & word,
currentActiveDictIds.clear(); currentActiveDictIds.clear();
// first, let's stop the player // first, let's stop the player
audioPlayer->stop(); audioPlayer->stop();
audioLink_.clear();
QUrl req; QUrl req;
@ -1306,33 +1318,14 @@ void ArticleView::reload()
void ArticleView::hasSound( const std::function< void( bool ) > & callback ) void ArticleView::hasSound( const std::function< void( bool ) > & callback )
{ {
webview->page()->runJavaScript( R"(if(typeof(gdAudioLinks)!="undefined") gdAudioLinks.first)", callback( !audioLink_.isEmpty() );
[ callback ]( const QVariant & v ) {
bool has = false;
if ( v.type() == QVariant::String ) {
has = !v.toString().isEmpty();
}
callback( has );
} );
} }
//use webengine javascript to playsound
void ArticleView::playSound() void ArticleView::playSound()
{ {
QString variable = R"( (function(){ var link=gdAudioMap.get(gdAudioLinks.current); if ( !audioLink_.isEmpty() ) {
if(link==undefined){ playAudio( QUrl::fromEncoded( audioLink_.toUtf8() ) );
link=gdAudioLinks.first;
} }
return link;})(); )";
webview->page()->runJavaScript( variable, [ this ]( const QVariant & result ) {
if ( result.typeId() == qMetaTypeId< QString >() ) {
QString soundScript = result.toString();
if ( !soundScript.isEmpty() ) {
openLink( QUrl::fromEncoded( soundScript.toUtf8() ), webview->url() );
}
}
} );
} }
void ArticleView::stopSound() void ArticleView::stopSound()

View file

@ -71,6 +71,8 @@ class ArticleView: public QWidget
//current active dictionary id; //current active dictionary id;
QString activeDictId; QString activeDictId;
QString audioLink_;
/// Search in results of full-text search /// Search in results of full-text search
QString firstAvailableText; QString firstAvailableText;
QStringList uniqueMatches; QStringList uniqueMatches;
@ -99,6 +101,9 @@ public:
void setCurrentGroupId( unsigned currengGrgId ); void setCurrentGroupId( unsigned currengGrgId );
unsigned getCurrentGroupId(); unsigned getCurrentGroupId();
void setAudioLink( QString audioLink );
QString getAudioLink() const;
virtual QSize minimumSizeHint() const; virtual QSize minimumSizeHint() const;
void clearContent(); void clearContent();

View file

@ -717,10 +717,11 @@ MainWindow::MainWindow( Config::Class & cfg_ ):
&PronounceEngine::emitAudio, &PronounceEngine::emitAudio,
this, this,
[ this ]( auto audioUrl ) { [ this ]( auto audioUrl ) {
auto view = getCurrentArticleView();
view->setAudioLink( audioUrl );
if ( !isActiveWindow() ) { if ( !isActiveWindow() ) {
return; return;
} }
auto view = getCurrentArticleView();
if ( ( cfg.preferences.pronounceOnLoadMain ) && view != nullptr ) { if ( ( cfg.preferences.pronounceOnLoadMain ) && view != nullptr ) {
view->playAudio( QUrl::fromEncoded( audioUrl.toUtf8() ) ); view->playAudio( QUrl::fromEncoded( audioUrl.toUtf8() ) );

View file

@ -165,6 +165,7 @@ ScanPopup::ScanPopup( QWidget * parent,
&PronounceEngine::emitAudio, &PronounceEngine::emitAudio,
this, this,
[ this ]( auto audioUrl ) { [ this ]( auto audioUrl ) {
definition->setAudioLink( audioUrl );
if ( !isActiveWindow() ) { if ( !isActiveWindow() ) {
return; return;
} }