helpbrowser.cpp

Go to the documentation of this file.
00001 /****************************************************************
00002  *  Vidalia is distributed under the following license:
00003  *
00004  *  Copyright (C) 2006,  Matt Edman, Justin Hipple
00005  *
00006  *  This program is free software; you can redistribute it and/or
00007  *  modify it under the terms of the GNU General Public License
00008  *  as published by the Free Software Foundation; either version 2
00009  *  of the License, or (at your option) any later version.
00010  *
00011  *  This program is distributed in the hope that it will be useful,
00012  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014  *  GNU General Public License for more details.
00015  *
00016  *  You should have received a copy of the GNU General Public License
00017  *  along with this program; if not, write to the Free Software
00018  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, 
00019  *  Boston, MA  02110-1301, USA.
00020  ****************************************************************/
00021 
00022 /** 
00023  * \file helpbrowser.cpp
00024  * \version $Id: helpbrowser.cpp 1808 2007-07-21 17:02:31Z edmanm $
00025  * \brief Displays a list of help topics and content
00026  */
00027 
00028 #include <QDomDocument>
00029 #include <QDir>
00030 #include <vidalia.h>
00031 #include <gui/mainwindow.h>
00032 
00033 #include "helpbrowser.h"
00034 
00035 
00036 #define LEFT_PANE_INDEX     0
00037 #define NO_STRETCH          0
00038 #define MINIMUM_PANE_SIZE   1
00039 
00040 /* Names of elements and attributes in the XML file */
00041 #define ELEMENT_CONTENTS        "Contents"
00042 #define ELEMENT_TOPIC           "Topic"
00043 #define ATTRIBUTE_TOPIC_ID      "id"
00044 #define ATTRIBUTE_TOPIC_HTML    "html"
00045 #define ATTRIBUTE_TOPIC_NAME    "name"
00046 #define ATTRIBUTE_TOPIC_SECTION "section"
00047 
00048 /* Define two roles used to store data associated with a topic item */
00049 #define ROLE_TOPIC_ID        Qt::UserRole
00050 #define ROLE_TOPIC_QRC_PATH (Qt::UserRole+1)
00051 
00052 
00053 /** Constuctor. This will probably do more later */
00054 HelpBrowser::HelpBrowser(QWidget *parent)
00055  : VidaliaWindow("HelpBrowser", parent)
00056 {
00057   VidaliaSettings settings;
00058 
00059   /* Invoke Qt Designer generated QObject setup routine */
00060   ui.setupUi(this);
00061 #if defined(Q_WS_MAC)
00062   ui.actionHome->setShortcut(QString("Shift+Ctrl+H"));
00063 #endif
00064 #if !defined(Q_WS_WIN)
00065   ui.actionClose->setShortcut(QString("Ctrl+W"));
00066 #endif
00067 
00068   /* Hide Search frame */
00069   ui.frmFind->setHidden(true);
00070  
00071   /* Set the splitter pane sizes so that only the txtBrowser pane expands
00072    * and set to arbitrary sizes (the minimum sizes will take effect */
00073   QList<int> sizes;
00074   sizes.append(MINIMUM_PANE_SIZE); 
00075   sizes.append(MINIMUM_PANE_SIZE);
00076   ui.splitter->setSizes(sizes);
00077   ui.splitter->setStretchFactor(LEFT_PANE_INDEX, NO_STRETCH);
00078 
00079   connect(ui.treeContents,
00080           SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
00081           this, SLOT(contentsItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)));
00082 
00083   connect(ui.treeSearch,
00084           SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
00085           this, SLOT(searchItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)));
00086 
00087   /* Connect the navigation actions to their slots */
00088   connect(ui.actionHome, SIGNAL(triggered()), ui.txtBrowser, SLOT(home()));
00089   connect(ui.actionBack, SIGNAL(triggered()), ui.txtBrowser, SLOT(backward()));
00090   connect(ui.actionForward, SIGNAL(triggered()), ui.txtBrowser, SLOT(forward()));
00091   connect(ui.txtBrowser, SIGNAL(backwardAvailable(bool)), 
00092           ui.actionBack, SLOT(setEnabled(bool)));
00093   connect(ui.txtBrowser, SIGNAL(forwardAvailable(bool)),
00094           ui.actionForward, SLOT(setEnabled(bool)));
00095   connect(ui.btnFindNext, SIGNAL(clicked()), this, SLOT(findNext()));
00096   connect(ui.btnFindPrev, SIGNAL(clicked()), this, SLOT(findPrev()));
00097   connect(ui.btnSearch, SIGNAL(clicked()), this, SLOT(search()));
00098   
00099   /* Load the help topics from XML */
00100   loadContentsFromXml(":/help/" + language() + "/contents.xml");
00101 
00102   /* Show the first help topic in the tree */
00103   ui.treeContents->setCurrentItem(ui.treeContents->topLevelItem(0));
00104   ui.treeContents->setItemExpanded(ui.treeContents->topLevelItem(0), true);
00105 }
00106 
00107 /** Returns the language in which help topics should appear, or English
00108  * ("en") if no translated help files exist for the current GUI language. */
00109 QString
00110 HelpBrowser::language()
00111 {
00112   QString lang = Vidalia::language();
00113   if (!QDir(":/help/" + lang).exists())
00114     lang = "en";
00115   return lang;
00116 }
00117 
00118 /** Load the contents of the help topics tree from the specified XML file. */
00119 void
00120 HelpBrowser::loadContentsFromXml(QString xmlFile)
00121 {
00122   QString errorString;
00123   QFile file(xmlFile);
00124   QDomDocument document;
00125   
00126   /* Load the XML contents into the DOM document */
00127   if (!document.setContent(&file, true, &errorString)) {
00128     ui.txtBrowser->setPlainText(tr("Error Loading Help Contents: ")+errorString);
00129     return;
00130   }
00131   /* Load the DOM document contents into the tree view */
00132   if (!loadContents(&document, errorString)) {
00133     ui.txtBrowser->setPlainText(tr("Error Loading Help Contents: ")+errorString);
00134     return;
00135   }
00136 }
00137 
00138 /** Load the contents of the help topics tree from the given DOM document. */
00139 bool
00140 HelpBrowser::loadContents(const QDomDocument *document, QString &errorString)
00141 {
00142   /* Grab the root document element and make sure it's the right one */
00143   QDomElement root = document->documentElement();
00144   if (root.tagName() != ELEMENT_CONTENTS) {
00145     errorString = tr("Supplied XML file is not a valid Contents document.");
00146     return false;
00147   }
00148   _elementList << root;
00149 
00150   /* Create the home item */
00151   QTreeWidgetItem *home = createTopicTreeItem(root, 0);
00152   ui.treeContents->addTopLevelItem(home);
00153   
00154   /* Process all top-level help topics */
00155   QDomElement child = root.firstChildElement(ELEMENT_TOPIC);
00156   while (!child.isNull()) {
00157     parseHelpTopic(child, home);
00158     child = child.nextSiblingElement(ELEMENT_TOPIC);
00159   }
00160   return true;
00161 }
00162 
00163 /** Parse a Topic element and handle all its children recursively. */
00164 void
00165 HelpBrowser::parseHelpTopic(const QDomElement &topicElement, 
00166                             QTreeWidgetItem *parent)
00167 {
00168   /* Check that we have a valid help topic */
00169   if (isValidTopicElement(topicElement)) {
00170     /* Save this element for later (used for searching) */
00171     _elementList << topicElement;
00172 
00173     /* Create and populate the new topic item in the tree */
00174     QTreeWidgetItem *topic = createTopicTreeItem(topicElement, parent);
00175 
00176     /* Process all its child elements */
00177     QDomElement child = topicElement.firstChildElement(ELEMENT_TOPIC);
00178     while (!child.isNull()) {
00179       parseHelpTopic(child, topic);
00180       child = child.nextSiblingElement(ELEMENT_TOPIC);
00181     }
00182   }
00183 }
00184 
00185 /** Returns true if the given Topic element has the necessary attributes. */
00186 bool
00187 HelpBrowser::isValidTopicElement(const QDomElement &topicElement)
00188 {
00189   return (topicElement.hasAttribute(ATTRIBUTE_TOPIC_ID) &&
00190           topicElement.hasAttribute(ATTRIBUTE_TOPIC_NAME) &&
00191           topicElement.hasAttribute(ATTRIBUTE_TOPIC_HTML));
00192 }
00193 
00194 /** Builds a resource path to an html file associated with the given help
00195  * topic. If the help topic needs an achor, the anchor will be formatted and
00196  * appended. */
00197 QString
00198 HelpBrowser::getResourcePath(const QDomElement &topicElement)
00199 {
00200   QString link = language() + "/" + topicElement.attribute(ATTRIBUTE_TOPIC_HTML);
00201   if (topicElement.hasAttribute(ATTRIBUTE_TOPIC_SECTION)) {
00202     link += "#" + topicElement.attribute(ATTRIBUTE_TOPIC_SECTION);
00203   }
00204   return link;
00205 }
00206 
00207 /** Creates a new element to be inserted into the topic tree. */
00208 QTreeWidgetItem*
00209 HelpBrowser::createTopicTreeItem(const QDomElement &topicElement, 
00210                                  QTreeWidgetItem *parent)
00211 {
00212   QTreeWidgetItem *topic = new QTreeWidgetItem(parent);
00213   topic->setText(0, topicElement.attribute(ATTRIBUTE_TOPIC_NAME));
00214   topic->setData(0, ROLE_TOPIC_ID, topicElement.attribute(ATTRIBUTE_TOPIC_ID));
00215   topic->setData(0, ROLE_TOPIC_QRC_PATH, getResourcePath(topicElement));
00216   return topic;
00217 }
00218 
00219 /** Called when the user selects a different item in the content topic tree */
00220 void
00221 HelpBrowser::contentsItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *prev)
00222 {
00223   QList<QTreeWidgetItem *> selected = ui.treeSearch->selectedItems();
00224   /* Deselect the selection in the search tree */
00225   if (!selected.isEmpty()) {
00226     ui.treeSearch->setItemSelected(selected[0], false);
00227   }
00228   currentItemChanged(current, prev);
00229 }
00230 
00231 /** Called when the user selects a different item in the content topic tree */
00232 void
00233 HelpBrowser::searchItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *prev)
00234 {
00235   QList<QTreeWidgetItem *> selected = ui.treeContents->selectedItems();
00236   /* Deselect the selection in the contents tree */
00237   if (!selected.isEmpty()) {
00238     ui.treeContents->setItemSelected(selected[0], false);
00239   }
00240 
00241   /* Change to selected page */
00242   currentItemChanged(current, prev);
00243 
00244   /* Highlight search phrase */
00245   QTextCursor found;
00246   QTextDocument::FindFlags flags = QTextDocument::FindWholeWords;
00247   found = ui.txtBrowser->document()->find(_lastSearch, 0, flags);
00248   if (!found.isNull()) {
00249     ui.txtBrowser->setTextCursor(found);
00250   }
00251 }
00252 
00253 /** Called when the user selects a different item in the tree. */
00254 void
00255 HelpBrowser::currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *prev)
00256 {
00257   Q_UNUSED(prev);
00258   if (current) {
00259     ui.txtBrowser->setSource(QUrl(current->data(0, 
00260                                               ROLE_TOPIC_QRC_PATH).toString()));
00261   }
00262   _foundBefore = false;
00263 }
00264 
00265 /** Searches for a topic in the topic tree. Returns a pointer to that topics
00266  * item in the topic tree if it is found, 0 otherwise. */
00267 QTreeWidgetItem*
00268 HelpBrowser::findTopicItem(QTreeWidgetItem *startItem, QString topic)
00269 {
00270   /* Parse the first subtopic in the topic id. */
00271   QString subtopic = topic.mid(0, topic.indexOf(".")).toLower();
00272 
00273   /* Search through all children of startItem and look for a subtopic match */
00274   for (int i = 0; i < startItem->childCount(); i++) {
00275     QTreeWidgetItem *item = startItem->child(i);
00276     
00277     if (subtopic == item->data(0, ROLE_TOPIC_ID).toString().toLower()) {
00278       /* Found a subtopic match, so expand this item */
00279       ui.treeContents->setItemExpanded(item, true);
00280       if (!topic.contains(".")) {
00281         /* Found the exact topic */
00282         return item;
00283       }
00284       /* Search recursively for the next subtopic */
00285       return findTopicItem(item, topic.mid(topic.indexOf(".")+1));
00286     }
00287   }
00288   return 0;
00289 }
00290 
00291 /** Shows the help browser. If a sepcified topic was given, the search for
00292  * that topic's ID (e.g., "log.basic") and display the appropriate page. */
00293 void
00294 HelpBrowser::showTopic(QString topic)
00295 {
00296   /* Search for the topic in the contents tree */
00297   QTreeWidgetItem *item =
00298     findTopicItem(ui.treeContents->topLevelItem(0), topic);
00299   
00300   if (item) {
00301     /* Item was found, so show its location in the hierarchy and select its
00302      * tree item. */
00303     QTreeWidgetItem* selected = ui.treeContents->selectedItems()[0];
00304     if (selected) {
00305       ui.treeContents->setItemSelected(selected, false);
00306     }
00307     ui.treeContents->setItemExpanded(ui.treeContents->topLevelItem(0), true);
00308     ui.treeContents->setItemSelected(item, true);
00309     currentItemChanged(item, selected);
00310   }
00311 }
00312 
00313 /** Called when the user clicks "Find Next". */
00314 void
00315 HelpBrowser::findNext()
00316 {
00317   find(true);
00318 }
00319 
00320 /** Called when the user clicks "Find Previous". */
00321 void
00322 HelpBrowser::findPrev()
00323 {
00324   find(false);
00325 }
00326 
00327 /** Searches the current page for the phrase in the Find box.
00328  *  Highlights the first instance found in the document
00329  *  \param forward true search forward if true, backward if false
00330  **/
00331 void
00332 HelpBrowser::find(bool forward)
00333 {
00334   /* Don't bother searching if there is no search phrase */
00335   if (ui.lineFind->text().isEmpty()) {
00336     return;
00337   }
00338   
00339   QTextDocument::FindFlags flags = 0;
00340   QTextCursor cursor = ui.txtBrowser->textCursor();
00341   QString searchPhrase = ui.lineFind->text();
00342   
00343   /* Clear status bar */
00344   this->statusBar()->clearMessage();
00345   
00346   /* Set search direction and other flags */
00347   if (!forward) {
00348     flags |= QTextDocument::FindBackward;
00349   }
00350   if (ui.chkbxMatchCase->isChecked()) {
00351     flags |= QTextDocument::FindCaseSensitively;
00352   }
00353   if (ui.chkbxWholePhrase->isChecked()) {
00354     flags |= QTextDocument::FindWholeWords;
00355   }
00356   
00357   /* Check if search phrase is the same as the previous */
00358   if (searchPhrase != _lastFind) {
00359     _foundBefore = false;
00360   }
00361   _lastFind = searchPhrase;
00362   
00363   /* Set the cursor to the appropriate start location if necessary */
00364   if (!cursor.hasSelection()) {
00365     if (forward) {
00366       cursor.movePosition(QTextCursor::Start);
00367     } else {
00368       cursor.movePosition(QTextCursor::End);
00369     }
00370     ui.txtBrowser->setTextCursor(cursor);
00371   }
00372 
00373   /* Search the page */
00374   QTextCursor found;
00375   found = ui.txtBrowser->document()->find(searchPhrase, cursor, flags);
00376   
00377   /* If found, move the cursor to the location */
00378   if (!found.isNull()) {
00379     ui.txtBrowser->setTextCursor(found);
00380   /* If not found, display appropriate error message */
00381   } else {
00382     if (_foundBefore) {
00383       if (forward) 
00384         this->statusBar()->showMessage(tr("Search reached end of document"));
00385       else 
00386         this->statusBar()->showMessage(tr("Search reached start of document"));
00387     } else {
00388       this->statusBar()->showMessage(tr("Text not found in document"));
00389     }
00390   }
00391   
00392   /* Even if not found this time, may have been found previously */
00393   _foundBefore |= !found.isNull();
00394 }
00395  
00396 /** Searches all help pages for the phrase the Search box.
00397  *  Fills treeSearch with documents containing matches and sets the
00398  *  status bar text appropriately.
00399  */
00400 void
00401 HelpBrowser::search()
00402 {
00403   /* Clear the list */
00404   ui.treeSearch->clear();
00405   
00406   /* Don't search if invalid document or blank search phrase */
00407   if (ui.lineSearch->text().isEmpty()) {
00408     return;
00409   }
00410     
00411   HelpTextBrowser browser;
00412   QTextCursor found;
00413   QTextDocument::FindFlags flags = QTextDocument::FindWholeWords;
00414 
00415   _lastSearch = ui.lineSearch->text();
00416 
00417   /* Search through all the pages looking for the phrase */
00418   for (int i=0; i < _elementList.size(); ++i) {
00419     /* Load page data into browser */
00420     browser.setSource(QUrl(getResourcePath(_elementList[i])));
00421       
00422     /* Search current document */
00423     found = browser.document()->find(ui.lineSearch->text(), 0, flags);
00424 
00425     /* If found, add page to tree */
00426     if (!found.isNull()) {
00427       ui.treeSearch->addTopLevelItem(createTopicTreeItem(_elementList[i], 0));
00428     }
00429   }
00430 
00431   /* Set the status bar text */
00432   this->statusBar()->showMessage(tr("Found %1 results")
00433                                 .arg(ui.treeSearch->topLevelItemCount()));
00434 }
00435 
00436 /** Overrides the default show method */
00437 void
00438 HelpBrowser::showWindow(QString topic)
00439 {
00440   
00441   /* Bring the window to the top */
00442   VidaliaWindow::showWindow();
00443 
00444   /* If a topic was specified, then go ahead and display it. */
00445   if (!topic.isEmpty()) {
00446     showTopic(topic);
00447   }
00448 }
00449 

Generated on Wed Sep 5 15:49:27 2007 for Vidalia by  doxygen 1.5.3