refactor: elimate makeScanPopup()

* Old code keep destory the scanpopup, then recreate it whenever the dict list or group list changed.
* New code keep a single instance of scanpopup, and only update necessary info.
This commit is contained in:
shenleban tongying 2023-02-22 19:44:29 -05:00
parent 67d5799708
commit b3aac01f41
4 changed files with 93 additions and 121 deletions

View file

@ -555,8 +555,6 @@ MainWindow::MainWindow( Config::Class & cfg_ ):
showDictBarNamesTriggered(); // Make update its state according to initial showDictBarNamesTriggered(); // Make update its state according to initial
// setting // setting
useSmallIconsInToolbarsTriggered();
connect( this, SIGNAL( clickOnDictPane( QString const & ) ), connect( this, SIGNAL( clickOnDictPane( QString const & ) ),
&dictionaryBar, SLOT( dictsPaneClicked( QString const & ) ) ); &dictionaryBar, SLOT( dictsPaneClicked( QString const & ) ) );
@ -726,8 +724,6 @@ MainWindow::MainWindow( Config::Class & cfg_ ):
restoreState( cfg.mainWindowState, 1 ); restoreState( cfg.mainWindowState, 1 );
} }
#endif #endif
updateSearchPaneAndBar( cfg.preferences.searchInDock );
ui.searchPane->setVisible( cfg.preferences.searchInDock );
applyProxySettings(); applyProxySettings();
@ -783,7 +779,33 @@ MainWindow::MainWindow( Config::Class & cfg_ ):
applyQtStyleSheet( cfg.preferences.addonStyle, cfg.preferences.displayStyle, cfg.preferences.darkMode ); applyQtStyleSheet( cfg.preferences.addonStyle, cfg.preferences.displayStyle, cfg.preferences.darkMode );
makeScanPopup(); // Scanpopup related
scanPopup = new ScanPopup(nullptr, cfg, articleNetMgr, audioPlayerFactory.player(),
dictionaries, groupInstances, history );
scanPopup->setStyleSheet(styleSheet());
connect( scanPopup,SIGNAL(editGroupRequested(unsigned)),
this, SLOT(editDictionaries(unsigned)),
Qt::QueuedConnection);
connect( scanPopup, &ScanPopup::sendPhraseToMainWindow,
this,&MainWindow::phraseReceived,
Qt::QueuedConnection);
connect( this, &MainWindow::setExpandOptionalParts, scanPopup, &ScanPopup::setViewExpandMode );
connect( scanPopup, &ScanPopup::setExpandMode, this, &MainWindow::setExpandMode );
connect( scanPopup, &ScanPopup::inspectSignal,this,&MainWindow::inspectElement );
connect( scanPopup, &ScanPopup::forceAddWordToHistory, this, &MainWindow::forceAddWordToHistory );
connect( scanPopup, &ScanPopup::showDictionaryInfo, this, &MainWindow::showDictionaryInfo );
connect ( scanPopup, &ScanPopup::openDictionaryFolder, this, &MainWindow::openDictionaryFolder );
connect( scanPopup, &ScanPopup::sendWordToHistory, this, &MainWindow::addWordToHistory );
connect( this, &MainWindow::setPopupGroupByName, scanPopup, &ScanPopup::setGroupByName );
connect( scanPopup, &ScanPopup::sendWordToFavorites, this, &MainWindow::addWordToFavorites );
connect( scanPopup, &ScanPopup::isWordPresentedInFavorites, this, &MainWindow::isWordPresentedInFavorites );
updateSearchPaneAndBar( cfg.preferences.searchInDock );
ui.searchPane->setVisible( cfg.preferences.searchInDock );
if ( trayIcon ) if ( trayIcon )
{ {
@ -891,12 +913,13 @@ MainWindow::MainWindow( Config::Class & cfg_ ):
QString("\"%1\"").arg( QDir::toNativeSeparators(QApplication::applicationFilePath())) + " \"%1\""); QString("\"%1\"").arg( QDir::toNativeSeparators(QApplication::applicationFilePath())) + " \"%1\"");
urlRegistry.endGroup(); urlRegistry.endGroup();
#endif #endif
useSmallIconsInToolbarsTriggered();
} }
void MainWindow::clipboardChange( QClipboard::Mode m) void MainWindow::clipboardChange( QClipboard::Mode m)
{ {
if( scanPopup )
{
#if defined(HAVE_X11) #if defined(HAVE_X11)
if(m == QClipboard::Clipboard){ if(m == QClipboard::Clipboard){
if(!cfg.preferences.trackClipboardScan) return; if(!cfg.preferences.trackClipboardScan) return;
@ -939,7 +962,7 @@ void MainWindow::clipboardChange( QClipboard::Mode m)
#else #else
scanPopup->translateWordFromClipboard(); scanPopup->translateWordFromClipboard();
#endif #endif
}
} }
void MainWindow::ctrlTabPressed() void MainWindow::ctrlTabPressed()
@ -1114,8 +1137,7 @@ void MainWindow::commitData()
// Save popup window state and geometry // Save popup window state and geometry
if( scanPopup.get() ) scanPopup->saveConfigData();
scanPopup->saveConfigData();
// Save any changes in last chosen groups etc // Save any changes in last chosen groups etc
try try
@ -1416,8 +1438,6 @@ void MainWindow::setupNetworkCache( int maxSize )
void MainWindow::makeDictionaries() void MainWindow::makeDictionaries()
{ {
Q_ASSERT( !scanPopup && "Scan popup must not exist while dictionaries are initialized. "
"It does not support dictionaries changes and must be constructed anew." );
wordFinder.clear(); wordFinder.clear();
@ -1548,50 +1568,6 @@ void MainWindow::updateDictionaryBar()
} }
} }
void MainWindow::makeScanPopup()
{
scanPopup.reset();
scanPopup = std::make_shared<ScanPopup>( nullptr, cfg, articleNetMgr, audioPlayerFactory.player(),
dictionaries, groupInstances, history );
scanPopup->setStyleSheet( styleSheet() );
connect( scanPopup.get(), SIGNAL(editGroupRequested( unsigned ) ),
this, SLOT(editDictionaries( unsigned )), Qt::QueuedConnection );
connect( scanPopup.get(),
&ScanPopup::sendPhraseToMainWindow,
this,
&MainWindow::phraseReceived,
Qt::QueuedConnection );
connect( this, &MainWindow::setExpandOptionalParts, scanPopup.get(), &ScanPopup::setViewExpandMode );
connect( scanPopup.get(), &ScanPopup::setExpandMode, this, &MainWindow::setExpandMode );
connect( scanPopup.get(), &ScanPopup::inspectSignal,this,&MainWindow::inspectElement );
connect( scanPopup.get(), &ScanPopup::forceAddWordToHistory, this, &MainWindow::forceAddWordToHistory );
connect( scanPopup.get(), &ScanPopup::showDictionaryInfo, this, &MainWindow::showDictionaryInfo );
connect( scanPopup.get(), &ScanPopup::openDictionaryFolder, this, &MainWindow::openDictionaryFolder );
connect( scanPopup.get(), &ScanPopup::sendWordToHistory, this, &MainWindow::addWordToHistory );
connect( this, &MainWindow::setPopupGroupByName, scanPopup.get(), &ScanPopup::setGroupByName );
connect( scanPopup.get(), &ScanPopup::sendWordToFavorites, this, &MainWindow::addWordToFavorites );
connect( scanPopup.get(), &ScanPopup::isWordPresentedInFavorites, this, &MainWindow::isWordPresentedInFavorites );
#ifdef Q_OS_WIN32
connect( scanPopup.get(), SIGNAL( isGoldenDictWindow( HWND ) ),
this, SLOT( isGoldenDictWindow( HWND ) ) );
#endif
}
vector< sptr< Dictionary::Class > > const & MainWindow::getActiveDicts() vector< sptr< Dictionary::Class > > const & MainWindow::getActiveDicts()
{ {
if ( groupInstances.empty() ) if ( groupInstances.empty() )
@ -2117,7 +2093,6 @@ void MainWindow::updatePronounceAvailability()
void MainWindow::editDictionaries( unsigned editDictionaryGroup ) void MainWindow::editDictionaries( unsigned editDictionaryGroup )
{ {
hotkeyWrapper.reset(); // No hotkeys while we're editing dictionaries hotkeyWrapper.reset(); // No hotkeys while we're editing dictionaries
scanPopup.reset(); // No scan popup either. No one should use dictionaries.
closeHeadwordsDialog(); closeHeadwordsDialog();
closeFullTextSearchDialog(); closeFullTextSearchDialog();
@ -2184,7 +2159,7 @@ void MainWindow::editDictionaries( unsigned editDictionaryGroup )
} }
makeScanPopup(); scanPopup->refresh();
installHotKeys(); installHotKeys();
@ -2198,7 +2173,6 @@ void MainWindow::editCurrentGroup()
void MainWindow::editPreferences() void MainWindow::editPreferences()
{ {
hotkeyWrapper.reset(); // So we could use the keys it hooks hotkeyWrapper.reset(); // So we could use the keys it hooks
scanPopup.reset(); // No scan popup either. No one should use dictionaries.
closeHeadwordsDialog(); closeHeadwordsDialog();
closeFullTextSearchDialog(); closeFullTextSearchDialog();
@ -2319,7 +2293,7 @@ void MainWindow::editPreferences()
Config::save( cfg ); Config::save( cfg );
} }
makeScanPopup(); scanPopup->refresh();
installHotKeys(); installHotKeys();
ftsIndexing.setDictionaries( dictionaries ); ftsIndexing.setDictionaries( dictionaries );
@ -3015,7 +2989,7 @@ void MainWindow::installHotKeys()
if ( cfg.preferences.enableMainWindowHotkey ) if ( cfg.preferences.enableMainWindowHotkey )
hotkeyWrapper->setGlobalKey( cfg.preferences.mainWindowHotkey,0 ); hotkeyWrapper->setGlobalKey( cfg.preferences.mainWindowHotkey,0 );
if ( cfg.preferences.enableClipboardHotkey && scanPopup.get() && !enableScanningAction->isChecked() ) if ( cfg.preferences.enableClipboardHotkey && !enableScanningAction->isChecked() )
{ {
hotkeyWrapper->setGlobalKey( cfg.preferences.clipboardHotkey,1 ); hotkeyWrapper->setGlobalKey( cfg.preferences.clipboardHotkey,1 );
} }
@ -3033,7 +3007,7 @@ void MainWindow::hotKeyActivated( int hk )
if ( !hk ) if ( !hk )
toggleMainWindow(); toggleMainWindow();
else else
if ( scanPopup.get() ) if ( scanPopup )
{ {
#ifdef HAVE_X11 #ifdef HAVE_X11
// When the user requests translation with the Ctrl+C+C hotkey in certain apps // When the user requests translation with the Ctrl+C+C hotkey in certain apps
@ -3042,7 +3016,7 @@ void MainWindow::hotKeyActivated( int hk )
// the clipboard empty, silently cancels the translation request, and users report // the clipboard empty, silently cancels the translation request, and users report
// that Ctrl+C+C is broken in these apps. Slightly delay handling the clipboard // that Ctrl+C+C is broken in these apps. Slightly delay handling the clipboard
// hotkey to give the active application more time and thus work around the issue. // hotkey to give the active application more time and thus work around the issue.
QTimer::singleShot( 10, scanPopup.get(), SLOT( translateWordFromClipboard() ) ); QTimer::singleShot( 10, scanPopup, SLOT( translateWordFromClipboard() ) );
#else #else
scanPopup->translateWordFromClipboard(); scanPopup->translateWordFromClipboard();
#endif #endif
@ -3195,9 +3169,7 @@ void MainWindow::trayIconActivated( QSystemTrayIcon::ActivationReason r )
case QSystemTrayIcon::MiddleClick: case QSystemTrayIcon::MiddleClick:
// Middle mouse click on Tray translates selection // Middle mouse click on Tray translates selection
// it is functional like as stardict // it is functional like as stardict
if ( scanPopup.get() ) {
scanPopup->translateWordFromSelection(); scanPopup->translateWordFromSelection();
}
break; break;
default: default:
break; break;
@ -3282,8 +3254,7 @@ void MainWindow::useSmallIconsInToolbarsTriggered()
cfg.usingSmallIconsInToolbars = useSmallIcons; cfg.usingSmallIconsInToolbars = useSmallIcons;
if( scanPopup.get() ) scanPopup->setDictionaryIconSize();
scanPopup->setDictionaryIconSize();
} }
void MainWindow::toggleMenuBarTriggered(bool announce) void MainWindow::toggleMenuBarTriggered(bool announce)
@ -3599,7 +3570,6 @@ void MainWindow::on_saveArticle_triggered()
void MainWindow::on_rescanFiles_triggered() void MainWindow::on_rescanFiles_triggered()
{ {
hotkeyWrapper.reset(); // No hotkeys while we're editing dictionaries hotkeyWrapper.reset(); // No hotkeys while we're editing dictionaries
scanPopup.reset(); // No scan popup either. No one should use dictionaries.
closeHeadwordsDialog(); closeHeadwordsDialog();
closeFullTextSearchDialog(); closeFullTextSearchDialog();
@ -3625,7 +3595,8 @@ void MainWindow::on_rescanFiles_triggered()
updateGroupList(); updateGroupList();
makeScanPopup();
scanPopup->refresh();
installHotKeys(); installHotKeys();
updateSuggestionList(); updateSuggestionList();
@ -3717,8 +3688,7 @@ void MainWindow::scaleArticlesByCurrentZoomFactor()
view.setZoomFactor( cfg.preferences.zoomFactor ); view.setZoomFactor( cfg.preferences.zoomFactor );
} }
if ( scanPopup.get() ) scanPopup->applyZoomFactor();
scanPopup->applyZoomFactor();
} }
void MainWindow::doWordsZoomIn() void MainWindow::doWordsZoomIn()
@ -3814,8 +3784,7 @@ void MainWindow::applyWordsZoomLevel()
navToolbar->layout()->invalidate(); navToolbar->layout()->invalidate();
} }
if ( scanPopup.get() ) scanPopup->applyWordsZoomLevel();
scanPopup->applyWordsZoomLevel();
} }
void MainWindow::messageFromAnotherInstanceReceived( QString const & message ) void MainWindow::messageFromAnotherInstanceReceived( QString const & message )
@ -3827,7 +3796,7 @@ void MainWindow::messageFromAnotherInstanceReceived( QString const & message )
} }
if( message.left( 15 ) == "translateWord: " ) if( message.left( 15 ) == "translateWord: " )
{ {
if( scanPopup.get() ) if( scanPopup )
scanPopup->translateWord( message.mid( 15 ) ); scanPopup->translateWord( message.mid( 15 ) );
else else
wordReceived( message.mid( 15 ) ); wordReceived( message.mid( 15 ) );
@ -4437,10 +4406,10 @@ void MainWindow::foundDictsContextMenuRequested( const QPoint &pos )
if( !pDict->isLocalDictionary() ) if( !pDict->isLocalDictionary() )
{ {
if ( scanPopup ) if ( scanPopup )
scanPopup.get()->blockSignals( true ); scanPopup->blockSignals( true );
showDictionaryInfo( id ); showDictionaryInfo( id );
if ( scanPopup ) if ( scanPopup )
scanPopup.get()->blockSignals( false ); scanPopup->blockSignals( false );
} }
else else
{ {
@ -4464,19 +4433,19 @@ void MainWindow::foundDictsContextMenuRequested( const QPoint &pos )
if( result && result == infoAction ) if( result && result == infoAction )
{ {
if ( scanPopup ) if ( scanPopup )
scanPopup.get()->blockSignals( true ); scanPopup->blockSignals( true );
showDictionaryInfo( id ); showDictionaryInfo( id );
if ( scanPopup ) if ( scanPopup )
scanPopup.get()->blockSignals( false ); scanPopup->blockSignals( false );
} }
else else
if( result && result == headwordsAction ) if( result && result == headwordsAction )
{ {
if ( scanPopup ) if ( scanPopup )
scanPopup.get()->blockSignals( true ); scanPopup->blockSignals( true );
showDictionaryHeadwords( this, pDict ); showDictionaryHeadwords( this, pDict );
if ( scanPopup ) if ( scanPopup )
scanPopup.get()->blockSignals( false ); scanPopup->blockSignals( false );
} }
else else
if( result && result == openDictFolderAction ) if( result && result == openDictFolderAction )
@ -4826,12 +4795,3 @@ void MainWindow::headwordFromFavorites( QString const & headword,
showTranslationFor( words[ 0 ] ); showTranslationFor( words[ 0 ] );
} }
#ifdef Q_OS_WIN32
bool MainWindow::isGoldenDictWindow( HWND hwnd )
{
return hwnd == (HWND)winId() || hwnd == (HWND)ui.centralWidget->winId();
}
#endif

View file

@ -154,7 +154,7 @@ private:
WordFinder wordFinder; WordFinder wordFinder;
sptr< ScanPopup > scanPopup; ScanPopup * scanPopup;
sptr< HotkeyWrapper > hotkeyWrapper; sptr< HotkeyWrapper > hotkeyWrapper;
@ -206,7 +206,6 @@ private:
void updateStatusLine(); void updateStatusLine();
void updateGroupList(); void updateGroupList();
void updateDictionaryBar(); void updateDictionaryBar();
void makeScanPopup();
void updatePronounceAvailability(); void updatePronounceAvailability();
@ -511,9 +510,6 @@ protected:
unsigned gdAskMessage; unsigned gdAskMessage;
public: public:
private slots:
/// Return true while scanning GoldenDict window
bool isGoldenDictWindow( HWND hwnd );
#endif #endif
}; };

View file

@ -299,6 +299,26 @@ ScanPopup::ScanPopup( QWidget * parent,
applyWordsZoomLevel(); applyWordsZoomLevel();
} }
void ScanPopup::refresh() {
// TODO: GroupCombox's update should be moved inside GroupCombox
// currentIndexChanged() signal is very trigger-happy. To avoid triggering
// it, we disconnect it while we're clearing and filling back groups.
disconnect( ui.groupList, &GroupComboBox::currentIndexChanged,
this, &ScanPopup::currentGroupChanged );
ui.groupList->clear();
ui.groupList->fill(groups);
ui.groupList->setCurrentGroup(0); // user edited group list, force reset to default
ui.groupList->setVisible(!cfg.groups.empty());
updateDictionaryBar();
connect( ui.groupList, &GroupComboBox::currentIndexChanged,
this, &ScanPopup::currentGroupChanged );
}
ScanPopup::~ScanPopup() ScanPopup::~ScanPopup()
{ {
saveConfigData(); saveConfigData();
@ -385,11 +405,7 @@ void ScanPopup::applyWordsZoomLevel()
Qt::WindowFlags ScanPopup::unpinnedWindowFlags() const Qt::WindowFlags ScanPopup::unpinnedWindowFlags() const
{ {
#if defined( HAVE_X11 )
return defaultUnpinnedWindowFlags | Qt::X11BypassWindowManagerHint;
#else
return defaultUnpinnedWindowFlags; return defaultUnpinnedWindowFlags;
#endif
} }
void ScanPopup::translateWordFromClipboard() void ScanPopup::translateWordFromClipboard()
@ -689,33 +705,30 @@ vector< sptr< Dictionary::Class > > const & ScanPopup::getActiveDicts()
{ {
int current = ui.groupList->currentIndex(); int current = ui.groupList->currentIndex();
if ( current < 0 || current >= (int) groups.size() ) Q_ASSERT(0 <= current || current <= groups.size());
{
// This shouldn't ever happen
return allDictionaries;
}
Config::MutedDictionaries const * mutedDictionaries = dictionaryBar.getMutedDictionaries(); Config::MutedDictionaries const * mutedDictionaries = dictionaryBar.getMutedDictionaries();
if ( !dictionaryBar.toggleViewAction()->isChecked() || mutedDictionaries == 0 )
return groups[ current ].dictionaries;
else
{
vector< sptr< Dictionary::Class > > const & activeDicts =
groups[ current ].dictionaries;
// Populate the special dictionariesUnmuted array with only unmuted if ( !dictionaryBar.toggleViewAction()->isChecked() || mutedDictionaries == 0 ){
// dictionaries return groups[current].dictionaries;
dictionariesUnmuted.clear();
dictionariesUnmuted.reserve( activeDicts.size() );
for( unsigned x = 0; x < activeDicts.size(); ++x )
if ( !mutedDictionaries->contains(
QString::fromStdString( activeDicts[ x ]->getId() ) ) )
dictionariesUnmuted.push_back( activeDicts[ x ] );
return dictionariesUnmuted;
} }
vector< sptr< Dictionary::Class > > const & activeDicts =
groups[current].dictionaries;
// Populate the special dictionariesUnmuted array with only unmuted
// dictionaries
dictionariesUnmuted.clear();
dictionariesUnmuted.reserve( activeDicts.size() );
for(const auto & activeDict : activeDicts){
if ( !mutedDictionaries->contains(QString::fromStdString( activeDict->getId() ) ) ){
dictionariesUnmuted.push_back( activeDict );
}
}
return dictionariesUnmuted;
} }
void ScanPopup::typingEvent( QString const & t ) void ScanPopup::typingEvent( QString const & t )

View file

@ -37,6 +37,9 @@ public:
~ScanPopup(); ~ScanPopup();
// update dictionary bar, group data and possibly other data
void refresh();
/// Applies current zoom factor to the popup's view. Should be called when /// Applies current zoom factor to the popup's view. Should be called when
/// it's changed. /// it's changed.
void applyZoomFactor(); void applyZoomFactor();