kaccelmanager.cpp

00001 /*  This file is part of the KDE project
00002     Copyright (C) 2002 Matthias Hölzer-Klüpfel <mhk@kde.org>
00003 
00004     This library is free software; you can redistribute it and/or
00005     modify it under the terms of the GNU Library General Public
00006     License as published by the Free Software Foundation; either
00007     version 2 of the License, or (at your option) any later version.
00008 
00009     This library is distributed in the hope that it will be useful,
00010     but WITHOUT ANY WARRANTY; without even the implied warranty of
00011     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012     Library General Public License for more details.
00013 
00014     You should have received a copy of the GNU Library General Public License
00015     along with this library; see the file COPYING.LIB.  If not, write to
00016     the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
00017     Boston, MA 02110-1301, USA.
00018 */
00019 
00020 #include "kaccelmanager.h"
00021 
00022 #include <qapplication.h>
00023 #include <qcheckbox.h>
00024 #include <qcombobox.h>
00025 #include <qgroupbox.h>
00026 #include <qlabel.h>
00027 #include <qlineedit.h>
00028 #include <qmenubar.h>
00029 #include <qmemarray.h>
00030 #include <qmetaobject.h>
00031 #include <qmainwindow.h>
00032 #include <qobjectlist.h>
00033 #include <qpopupmenu.h>
00034 #include <qptrlist.h>
00035 #include <qpushbutton.h>
00036 #include <qradiobutton.h>
00037 #include <qspinbox.h>
00038 #include <qtabbar.h>
00039 #include <qtextview.h>
00040 #include <qwidget.h>
00041 #include <qwidgetstack.h>
00042 
00043 #include <kstdaction.h>
00044 #include <kstaticdeleter.h>
00045 #include <kdebug.h>
00046 
00047 
00048 #include "kaccelmanager_private.h"
00049 #include "../kdeui/kstdaction_p.h"
00050 
00051 
00052 /*********************************************************************
00053 
00054  class Item - helper class containing widget information
00055 
00056  This class stores information about the widgets the need accelerators,
00057  as well as about their relationship.
00058 
00059  *********************************************************************/
00060 
00061 
00062 
00063 /*********************************************************************
00064 
00065  class KAcceleratorManagerPrivate - internal helper class
00066 
00067  This class does all the work to find accelerators for a hierarchy of
00068  widgets.
00069 
00070  *********************************************************************/
00071 
00072 
00073 class KAcceleratorManagerPrivate
00074 {
00075 public:
00076 
00077     static void manage(QWidget *widget);
00078     static bool programmers_mode;
00079     static bool standardName(const QString &str);
00080 
00081     static bool checkChange(const KAccelString &as)  {
00082         QString t2 = as.accelerated();
00083         QString t1 = as.originalText();
00084         if (t1 != t2)
00085         {
00086             if (as.accel() == -1)  {
00087                 removed_string  += "<tr><td>" + QStyleSheet::escape(t1) + "</td></tr>";
00088             } else if (as.originalAccel() == -1) {
00089                 added_string += "<tr><td>" + QStyleSheet::escape(t2) + "</td></tr>";
00090             } else {
00091                 changed_string += "<tr><td>" + QStyleSheet::escape(t1) + "</td>";
00092                 changed_string += "<td>" + QStyleSheet::escape(t2) + "</td></tr>";
00093             }
00094             return true;
00095         }
00096         return false;
00097     }
00098     static QString changed_string;
00099     static QString added_string;
00100     static QString removed_string;
00101     static QMap<QWidget *, int> ignored_widgets;
00102 
00103 private:
00104   class Item;
00105 public:
00106   typedef QPtrList<Item> ItemList;
00107 
00108 private:
00109   static void traverseChildren(QWidget *widget, Item *item);
00110 
00111   static void manageWidget(QWidget *widget, Item *item);
00112   static void manageMenuBar(QMenuBar *mbar, Item *item);
00113   static void manageTabBar(QTabBar *bar, Item *item);
00114 
00115   static void calculateAccelerators(Item *item, QString &used);
00116 
00117   class Item
00118   {
00119   public:
00120 
00121     Item() : m_widget(0), m_children(0), m_index(-1) {};
00122     ~Item();
00123 
00124     void addChild(Item *item);
00125 
00126     QWidget       *m_widget;
00127     KAccelString  m_content;
00128     ItemList      *m_children;
00129     int           m_index;
00130 
00131   };
00132 };
00133 
00134 
00135 bool KAcceleratorManagerPrivate::programmers_mode = false;
00136 QString KAcceleratorManagerPrivate::changed_string;
00137 QString KAcceleratorManagerPrivate::added_string;
00138 QString KAcceleratorManagerPrivate::removed_string;
00139 static QStringList *kaccmp_sns = 0;
00140 static KStaticDeleter<QStringList> kaccmp_sns_d;
00141 QMap<QWidget*, int> KAcceleratorManagerPrivate::ignored_widgets;
00142 
00143 bool KAcceleratorManagerPrivate::standardName(const QString &str)
00144 {
00145     if (!kaccmp_sns)
00146         kaccmp_sns_d.setObject(kaccmp_sns, new QStringList(KStdAction::internal_stdNames()));
00147         return kaccmp_sns->contains(str);
00148 }
00149 
00150 KAcceleratorManagerPrivate::Item::~Item()
00151 {
00152     delete m_children;
00153 }
00154 
00155 
00156 void KAcceleratorManagerPrivate::Item::addChild(Item *item)
00157 {
00158     if (!m_children) {
00159         m_children = new ItemList;
00160     m_children->setAutoDelete(true);
00161     }
00162 
00163     m_children->append(item);
00164 }
00165 
00166 void KAcceleratorManagerPrivate::manage(QWidget *widget)
00167 {
00168     if (!widget)
00169     {
00170         kdDebug(125) << "null pointer given to manage" << endl;
00171         return;
00172     }
00173 
00174     if (dynamic_cast<QPopupMenu*>(widget))
00175     {
00176         // create a popup accel manager that can deal with dynamic menus
00177         KPopupAccelManager::manage(static_cast<QPopupMenu*>(widget));
00178         return;
00179     }
00180 
00181     Item *root = new Item;
00182 
00183     manageWidget(widget, root);
00184 
00185     QString used;
00186     calculateAccelerators(root, used);
00187     delete root;
00188 }
00189 
00190 
00191 void KAcceleratorManagerPrivate::calculateAccelerators(Item *item, QString &used)
00192 {
00193     if (!item->m_children)
00194         return;
00195 
00196     // collect the contents
00197     KAccelStringList contents;
00198     for (Item *it = item->m_children->first(); it != 0;
00199          it = item->m_children->next())
00200     {
00201         contents << it->m_content;
00202     }
00203 
00204     // find the right accelerators
00205     KAccelManagerAlgorithm::findAccelerators(contents, used);
00206 
00207     // write them back into the widgets
00208     int cnt = -1;
00209     for (Item *it = item->m_children->first(); it != 0;
00210          it = item->m_children->next())
00211     {
00212         cnt++;
00213 
00214         QTabBar *tabBar = dynamic_cast<QTabBar*>(it->m_widget);
00215         if (tabBar)
00216         {
00217             if (checkChange(contents[cnt]))
00218                 tabBar->tabAt(it->m_index)->setText(contents[cnt].accelerated());
00219             continue;
00220         }
00221         QMenuBar *menuBar = dynamic_cast<QMenuBar*>(it->m_widget);
00222         if (menuBar)
00223         {
00224             if (it->m_index >= 0)
00225             {
00226                 QMenuItem *mitem = menuBar->findItem(menuBar->idAt(it->m_index));
00227                 if (mitem)
00228                 {
00229                     checkChange(contents[cnt]);
00230                     mitem->setText(contents[cnt].accelerated());
00231                 }
00232                 continue;
00233             }
00234         }
00235         // we possibly reserved an accel, but we won't set it as it looks silly
00236         if ( dynamic_cast<QGroupBox*>( it->m_widget ) )
00237              continue;
00238         // links look weird with ampersands
00239         if ( dynamic_cast<QLabel*>( it->m_widget ) && it->m_widget->inherits("KURLLabel") )
00240              continue;
00241 
00242         kdDebug(125) << "write " << cnt << " " << it->m_widget->className() << " " <<contents[cnt].accelerated() << endl;
00243 
00244         int tprop = it->m_widget->metaObject()->findProperty("text", true);
00245         if (tprop != -1)  {
00246             if (checkChange(contents[cnt]))
00247                 it->m_widget->setProperty("text", contents[cnt].accelerated());
00248         } else {
00249             tprop = it->m_widget->metaObject()->findProperty("title", true);
00250             if (tprop != -1 && checkChange(contents[cnt]))
00251                 it->m_widget->setProperty("title", contents[cnt].accelerated());
00252         }
00253     }
00254 
00255     // calculate the accelerators for the children
00256     for (Item *it = item->m_children->first(); it != 0;
00257          it = item->m_children->next())
00258     {
00259         kdDebug(125) << "children " << it->m_widget->className() << endl;
00260         if (it->m_widget && it->m_widget->isVisibleTo( item->m_widget ) )
00261             calculateAccelerators(it, used);
00262     }
00263 }
00264 
00265 
00266 void KAcceleratorManagerPrivate::traverseChildren(QWidget *widget, Item *item)
00267 {
00268   QObjectList *childList = widget->queryList("QWidget", 0, false, false);
00269   for ( QObject *it = childList->first(); it; it = childList->next() )
00270   {
00271     QWidget *w = static_cast<QWidget*>(it);
00272 
00273     if ( !w->isVisibleTo( widget ) || w->isTopLevel() )
00274         continue;
00275 
00276     if ( KAcceleratorManagerPrivate::ignored_widgets.find( w ) != KAcceleratorManagerPrivate::ignored_widgets.end() )
00277         continue;
00278 
00279     manageWidget(w, item);
00280   }
00281   delete childList;
00282 }
00283 
00284 void KAcceleratorManagerPrivate::manageWidget(QWidget *w, Item *item)
00285 {
00286   // first treat the special cases
00287 
00288   QTabBar *tabBar = dynamic_cast<QTabBar*>(w);
00289   if (tabBar)
00290   {
00291       manageTabBar(tabBar, item);
00292       return;
00293   }
00294 
00295   QWidgetStack *wds = dynamic_cast<QWidgetStack*>( w );
00296   if ( wds )
00297   {
00298       QWidgetStackAccelManager::manage( wds );
00299       // return;
00300   }
00301 
00302   QPopupMenu *popupMenu = dynamic_cast<QPopupMenu*>(w);
00303   if (popupMenu)
00304   {
00305       // create a popup accel manager that can deal with dynamic menus
00306       KPopupAccelManager::manage(popupMenu);
00307       return;
00308   }
00309 
00310   QWidgetStack *wdst = dynamic_cast<QWidgetStack*>( w );
00311   if ( wdst )
00312   {
00313       QWidgetStackAccelManager::manage( wdst );
00314       // return;
00315   }
00316 
00317   QMenuBar *menuBar = dynamic_cast<QMenuBar*>(w);
00318   if (menuBar)
00319   {
00320       manageMenuBar(menuBar, item);
00321       return;
00322   }
00323 
00324   if (dynamic_cast<QComboBox*>(w) || dynamic_cast<QLineEdit*>(w) ||
00325       dynamic_cast<QTextEdit*>(w) || dynamic_cast<QTextView*>(w) ||
00326       dynamic_cast<QSpinBox*>(w) || w->qt_cast( "KMultiTabBar" ))
00327       return;
00328 
00329   // now treat 'ordinary' widgets
00330   QLabel *label =  dynamic_cast<QLabel*>(w);
00331   if ( label  ) {
00332       if ( !label->buddy() )
00333           label = 0;
00334       else {
00335           if ( label->textFormat() == Qt::RichText ||
00336                ( label->textFormat() == Qt::AutoText &&
00337                  QStyleSheet::mightBeRichText( label->text() ) ) )
00338               label = 0;
00339       }
00340   }
00341 
00342   if (w->isFocusEnabled() || label || dynamic_cast<QGroupBox*>(w) || dynamic_cast<QRadioButton*>( w ))
00343   {
00344     QString content;
00345     QVariant variant;
00346     int tprop = w->metaObject()->findProperty("text", true);
00347     if (tprop != -1)  {
00348         const QMetaProperty* p = w->metaObject()->property( tprop, true );
00349         if ( p && p->isValid() )
00350             w->qt_property( tprop, 1, &variant );
00351         else
00352             tprop = -1;
00353     }
00354 
00355     if (tprop == -1)  {
00356         tprop = w->metaObject()->findProperty("title", true);
00357         if (tprop != -1)  {
00358             const QMetaProperty* p = w->metaObject()->property( tprop, true );
00359             if ( p && p->isValid() )
00360                 w->qt_property( tprop, 1, &variant );
00361         }
00362     }
00363 
00364     if (variant.isValid())
00365         content = variant.toString();
00366 
00367     if (!content.isEmpty())
00368     {
00369         Item *i = new Item;
00370         i->m_widget = w;
00371 
00372         // put some more weight on the usual action elements
00373         int weight = KAccelManagerAlgorithm::DEFAULT_WEIGHT;
00374         if (dynamic_cast<QPushButton*>(w) || dynamic_cast<QCheckBox*>(w) || dynamic_cast<QRadioButton*>(w) || dynamic_cast<QLabel*>(w))
00375             weight = KAccelManagerAlgorithm::ACTION_ELEMENT_WEIGHT;
00376 
00377         // don't put weight on group boxes, as usually the contents are more important
00378         if (dynamic_cast<QGroupBox*>(w))
00379             weight = KAccelManagerAlgorithm::GROUP_BOX_WEIGHT;
00380 
00381         // put a lot of extra weight on the KDialogBaseButton's
00382         if (w->inherits("KDialogBaseButton"))
00383             weight += KAccelManagerAlgorithm::DIALOG_BUTTON_EXTRA_WEIGHT;
00384 
00385         i->m_content = KAccelString(content, weight);
00386         item->addChild(i);
00387     }
00388   }
00389   traverseChildren(w, item);
00390 }
00391 
00392 void KAcceleratorManagerPrivate::manageTabBar(QTabBar *bar, Item *item)
00393 {
00394   for (int i=0; i<bar->count(); i++)
00395   {
00396     QString content = bar->tabAt(i)->text();
00397     if (content.isEmpty())
00398       continue;
00399 
00400     Item *it = new Item;
00401     item->addChild(it);
00402     it->m_widget = bar;
00403     it->m_index = i;
00404     it->m_content = KAccelString(content);
00405   }
00406 }
00407 
00408 void KAcceleratorManagerPrivate::manageMenuBar(QMenuBar *mbar, Item *item)
00409 {
00410     QMenuItem *mitem;
00411     QString s;
00412 
00413     for (uint i=0; i<mbar->count(); ++i)
00414     {
00415         mitem = mbar->findItem(mbar->idAt(i));
00416         if (!mitem)
00417             continue;
00418 
00419         // nothing to do for separators
00420         if (mitem->isSeparator())
00421             continue;
00422 
00423         s = mitem->text();
00424         if (!s.isEmpty())
00425         {
00426             Item *it = new Item;
00427             item->addChild(it);
00428             it->m_content =
00429                 KAccelString(s,
00430                              // menu titles are important, so raise the weight
00431                              KAccelManagerAlgorithm::MENU_TITLE_WEIGHT);
00432 
00433             it->m_widget = mbar;
00434             it->m_index = i;
00435         }
00436 
00437         // have a look at the popup as well, if present
00438         if (mitem->popup())
00439             KPopupAccelManager::manage(mitem->popup());
00440     }
00441 }
00442 
00443 
00444 /*********************************************************************
00445 
00446  class KAcceleratorManager - main entry point
00447 
00448  This class is just here to provide a clean public API...
00449 
00450  *********************************************************************/
00451 
00452 void KAcceleratorManager::manage(QWidget *widget)
00453 {
00454     KAcceleratorManager::manage(widget, false);
00455 }
00456 
00457 void KAcceleratorManager::manage(QWidget *widget, bool programmers_mode)
00458 {
00459     kdDebug(125) << "KAcceleratorManager::manage\n";
00460     KAcceleratorManagerPrivate::changed_string = QString::null;
00461     KAcceleratorManagerPrivate::added_string = QString::null;
00462     KAcceleratorManagerPrivate::removed_string = QString::null;
00463     KAcceleratorManagerPrivate::programmers_mode = programmers_mode;
00464     KAcceleratorManagerPrivate::manage(widget);
00465 }
00466 
00467 void KAcceleratorManager::last_manage(QString &added,  QString &changed, QString &removed)
00468 {
00469     added = KAcceleratorManagerPrivate::added_string;
00470     changed = KAcceleratorManagerPrivate::changed_string;
00471     removed = KAcceleratorManagerPrivate::removed_string;
00472 }
00473 
00474 
00475 /*********************************************************************
00476 
00477  class KAccelString - a string with weighted characters
00478 
00479  *********************************************************************/
00480 
00481 KAccelString::KAccelString(const QString &input, int initialWeight)
00482   : m_pureText(input), m_weight()
00483 {
00484     m_orig_accel = m_pureText.find("(!)&");
00485     if (m_orig_accel != -1)
00486     m_pureText.remove(m_orig_accel, 4);
00487 
00488     m_orig_accel = m_pureText.find("(&&)");
00489     if (m_orig_accel != -1)
00490         m_pureText.replace(m_orig_accel, 4, "&");
00491 
00492     m_origText = m_pureText;
00493 
00494     if (m_pureText.contains('\t'))
00495         m_pureText = m_pureText.left(m_pureText.find('\t'));
00496 
00497     m_orig_accel = m_accel = stripAccelerator(m_pureText);
00498 
00499     kdDebug(125) << input << " " << m_orig_accel << " " << m_accel << " " << m_pureText << endl;
00500     if (initialWeight == -1)
00501         initialWeight = KAccelManagerAlgorithm::DEFAULT_WEIGHT;
00502 
00503     calculateWeights(initialWeight);
00504 
00505     // dump();
00506 }
00507 
00508 
00509 QString KAccelString::accelerated() const
00510 {
00511   QString result = m_origText;
00512   if (result.isEmpty())
00513       return result;
00514 
00515   if (KAcceleratorManagerPrivate::programmers_mode)
00516   {
00517     if (m_accel != m_orig_accel) {
00518       int oa = m_orig_accel;
00519 
00520       if (m_accel >= 0) {
00521               result.insert(m_accel, "(!)&");
00522               if (m_accel < m_orig_accel)
00523                   oa += 4;
00524       }
00525       if (m_orig_accel >= 0)
00526       result.replace(oa, 1, "(&&)");
00527     }
00528   } else {
00529       if (m_accel >= 0 && m_orig_accel != m_accel) {
00530           result.remove(m_orig_accel, 1);
00531           result.insert(m_accel, "&");
00532       }
00533   }
00534   return result;
00535 }
00536 
00537 
00538 QChar KAccelString::accelerator() const
00539 {
00540   if ((m_accel < 0) || (m_accel > (int)m_pureText.length()))
00541     return QChar();
00542 
00543   return m_pureText[m_accel].lower();
00544 }
00545 
00546 
00547 void KAccelString::calculateWeights(int initialWeight)
00548 {
00549   m_weight.resize(m_pureText.length());
00550 
00551   uint pos = 0;
00552   bool start_character = true;
00553 
00554   while (pos<m_pureText.length())
00555   {
00556     QChar c = m_pureText[pos];
00557 
00558     int weight = initialWeight+1;
00559 
00560     // add special weight to first character
00561     if (pos == 0)
00562       weight += KAccelManagerAlgorithm::FIRST_CHARACTER_EXTRA_WEIGHT;
00563 
00564     // add weight to word beginnings
00565     if (start_character)
00566     {
00567       weight += KAccelManagerAlgorithm::WORD_BEGINNING_EXTRA_WEIGHT;
00568       start_character = false;
00569     }
00570 
00571     // add decreasing weight to left characters
00572     if (pos < 50)
00573       weight += (50-pos);
00574 
00575     // try to preserve the wanted accelarators
00576     if ((int)pos == accel()) {
00577         weight += KAccelManagerAlgorithm::WANTED_ACCEL_EXTRA_WEIGHT;
00578         // kdDebug(125) << "wanted " << m_pureText << " " << KAcceleratorManagerPrivate::standardName(m_origText) << endl;
00579         if (KAcceleratorManagerPrivate::standardName(m_origText))  {
00580             weight += KAccelManagerAlgorithm::STANDARD_ACCEL;
00581         }
00582     }
00583 
00584     // skip non typeable characters
00585     if (!c.isLetterOrNumber())
00586     {
00587       weight = 0;
00588       start_character = true;
00589     }
00590 
00591     m_weight[pos] = weight;
00592 
00593     ++pos;
00594   }
00595 }
00596 
00597 
00598 int KAccelString::stripAccelerator(QString &text)
00599 {
00600   // Note: this code is derived from QAccel::shortcutKey
00601   int p = 0;
00602 
00603   while (p >= 0)
00604   {
00605     p = text.find('&', p)+1;
00606 
00607     if (p <= 0 || p >= (int)text.length())
00608       return -1;
00609 
00610     if (text[p] != '&')
00611     {
00612       QChar c = text[p];
00613       if (c.isPrint())
00614       {
00615         text.remove(p-1,1);
00616     return p-1;
00617       }
00618     }
00619 
00620     p++;
00621   }
00622 
00623   return -1;
00624 }
00625 
00626 
00627 int KAccelString::maxWeight(int &index, const QString &used)
00628 {
00629   int max = 0;
00630   index = -1;
00631 
00632   for (uint pos=0; pos<m_pureText.length(); ++pos)
00633     if (used.find(m_pureText[pos], 0, FALSE) == -1 && m_pureText[pos].latin1() != 0)
00634       if (m_weight[pos] > max)
00635       {
00636         max = m_weight[pos];
00637     index = pos;
00638       }
00639 
00640   return max;
00641 }
00642 
00643 
00644 void KAccelString::dump()
00645 {
00646   QString s;
00647   for (uint i=0; i<m_weight.count(); ++i)
00648     s += QString("%1(%2) ").arg(pure()[i]).arg(m_weight[i]);
00649   kdDebug() << "s " << s << endl;
00650 }
00651 
00652 
00653 /*********************************************************************
00654 
00655  findAccelerators - the algorithm determining the new accelerators
00656 
00657  The algorithm is very crude:
00658 
00659    * each character in each widget text is assigned a weight
00660    * the character with the highest weight over all is picked
00661    * that widget is removed from the list
00662    * the weights are recalculated
00663    * the process is repeated until no more accelerators can be found
00664 
00665  The algorithm has some advantages:
00666 
00667    * it favors 'nice' accelerators (first characters in a word, etc.)
00668    * it is quite fast, O(N²)
00669    * it is easy to understand :-)
00670 
00671  The disadvantages:
00672 
00673    * it does not try to find as many accelerators as possible
00674 
00675  TODO:
00676 
00677  * The result is always correct, but not neccesarily optimal. Perhaps
00678    it would be a good idea to add another algorithm with higher complexity
00679    that gets used when this one fails, i.e. leaves widgets without
00680    accelerators.
00681 
00682  * The weights probably need some tweaking so they make more sense.
00683 
00684  *********************************************************************/
00685 
00686 void KAccelManagerAlgorithm::findAccelerators(KAccelStringList &result, QString &used)
00687 {
00688     kdDebug(125) << "findAccelerators\n";
00689   KAccelStringList accel_strings = result;
00690 
00691   // initally remove all accelerators
00692   for (KAccelStringList::Iterator it = result.begin(); it != result.end(); ++it) {
00693       kdDebug(125) << "reset " << ( *it ).pure() << endl;
00694     (*it).setAccel(-1);
00695   }
00696 
00697   // pick the highest bids
00698   for (uint cnt=0; cnt<accel_strings.count(); ++cnt)
00699   {
00700       kdDebug(125) << "cnt " << accel_strings[cnt].pure() << endl;
00701     int max = 0, index = -1, accel = -1;
00702 
00703     // find maximum weight
00704     for (uint i=0; i<accel_strings.count(); ++i)
00705     {
00706       int a;
00707       int m = accel_strings[i].maxWeight(a, used);
00708       if (m>max)
00709       {
00710         max = m;
00711         index = i;
00712         accel = a;
00713       }
00714     }
00715 
00716     // stop if no more accelerators can be found
00717     if (index < 0)
00718       return;
00719 
00720     // insert the accelerator
00721     if (accel >= 0)
00722     {
00723       result[index].setAccel(accel);
00724       used.append(result[index].accelerator());
00725     }
00726 
00727     // make sure we don't visit this one again
00728     accel_strings[index] = KAccelString();
00729   }
00730 }
00731 
00732 
00733 /*********************************************************************
00734 
00735  class KPopupAccelManager - managing QPopupMenu widgets dynamically
00736 
00737  *********************************************************************/
00738 
00739 KPopupAccelManager::KPopupAccelManager(QPopupMenu *popup)
00740   : QObject(popup), m_popup(popup), m_count(-1)
00741 {
00742     aboutToShow(); // do one check and then connect to show
00743     connect(popup, SIGNAL(aboutToShow()), SLOT(aboutToShow()));
00744 }
00745 
00746 
00747 void KPopupAccelManager::aboutToShow()
00748 {
00749   // Note: we try to be smart and avoid recalculating the accelerators
00750   // whenever possible. Unfortunately, there is no way to know if an
00751  // item has been added or removed, so we can not do much more than
00752   // to compare the items each time the menu is shown :-(
00753 
00754   if (m_count != (int)m_popup->count())
00755   {
00756     findMenuEntries(m_entries);
00757     calculateAccelerators();
00758     m_count = m_popup->count();
00759   }
00760   else
00761   {
00762     KAccelStringList entries;
00763     findMenuEntries(entries);
00764     if (entries != m_entries)
00765     {
00766       m_entries = entries;
00767       calculateAccelerators();
00768     }
00769   }
00770 }
00771 
00772 
00773 void KPopupAccelManager::calculateAccelerators()
00774 {
00775   // find the new accelerators
00776   QString used;
00777   KAccelManagerAlgorithm::findAccelerators(m_entries, used);
00778 
00779   // change the menu entries
00780   setMenuEntries(m_entries);
00781 }
00782 
00783 
00784 void KPopupAccelManager::findMenuEntries(KAccelStringList &list)
00785 {
00786   QMenuItem *mitem;
00787   QString s;
00788 
00789   list.clear();
00790 
00791   // read out the menu entries
00792   for (uint i=0; i<m_popup->count(); i++)
00793   {
00794     mitem = m_popup->findItem(m_popup->idAt(i));
00795     if (mitem->isSeparator())
00796       continue;
00797 
00798     s = mitem->text();
00799 
00800     // in full menus, look at entries with global accelerators last
00801     int weight = 50;
00802     if (s.contains('\t'))
00803         weight = 0;
00804 
00805     list.append(KAccelString(s, weight));
00806 
00807     // have a look at the popup as well, if present
00808     if (mitem->popup())
00809         KPopupAccelManager::manage(mitem->popup());
00810   }
00811 }
00812 
00813 
00814 void KPopupAccelManager::setMenuEntries(const KAccelStringList &list)
00815 {
00816   QMenuItem *mitem;
00817 
00818   uint cnt = 0;
00819   for (uint i=0; i<m_popup->count(); i++)
00820   {
00821     mitem = m_popup->findItem(m_popup->idAt(i));
00822     if (mitem->isSeparator())
00823       continue;
00824 
00825     if (KAcceleratorManagerPrivate::checkChange(list[cnt]))
00826         mitem->setText(list[cnt].accelerated());
00827     cnt++;
00828   }
00829 }
00830 
00831 
00832 void KPopupAccelManager::manage(QPopupMenu *popup)
00833 {
00834   // don't add more than one manager to a popup
00835   if (popup->child(0, "KPopupAccelManager", false) == 0 )
00836     new KPopupAccelManager(popup);
00837 }
00838 
00839 void QWidgetStackAccelManager::manage( QWidgetStack *stack )
00840 {
00841     if ( stack->child( 0, "QWidgetStackAccelManager", false ) == 0 )
00842         new QWidgetStackAccelManager( stack );
00843 }
00844 
00845 QWidgetStackAccelManager::QWidgetStackAccelManager(QWidgetStack *stack)
00846   : QObject(stack), m_stack(stack)
00847 {
00848     aboutToShow(stack->visibleWidget()); // do one check and then connect to show
00849     connect(stack, SIGNAL(aboutToShow(QWidget *)), SLOT(aboutToShow(QWidget *)));
00850 }
00851 
00852 bool QWidgetStackAccelManager::eventFilter ( QObject * watched, QEvent * e )
00853 {
00854     if ( e->type() == QEvent::Show && qApp->activeWindow() ) {
00855         KAcceleratorManager::manage( qApp->activeWindow() );
00856         watched->removeEventFilter( this );
00857     }
00858     return false;
00859 }
00860 
00861 void QWidgetStackAccelManager::aboutToShow(QWidget *child)
00862 {
00863     if (!child)
00864     {
00865         kdDebug(125) << "null pointer given to aboutToShow" << endl;
00866         return;
00867     }
00868 
00869     child->installEventFilter( this );
00870 }
00871 
00872 void KAcceleratorManager::setNoAccel( QWidget *widget )
00873 {
00874     KAcceleratorManagerPrivate::ignored_widgets[widget] = 1;
00875 }
00876 
00877 #include "kaccelmanager_private.moc"
KDE Home | KDE Accessibility Home | Description of Access Keys