Fix forward navigation control on Linux.
[dorian] / mainwindow.cpp
index 34d56b5..8694cd2 100755 (executable)
@@ -1,11 +1,14 @@
 #include <QtGui>
-#include <QtDebug>
-#include <QDir>
-#include <QCoreApplication>
-#include <QFileInfo>
+#include <QEvent>
+
 #ifdef Q_WS_MAEMO_5
-#   include <QtMaemo5/QMaemo5InformationBox>
-#endif
+#   include <QtDBus>
+#   include <QtGui/QX11Info>
+#   include <X11/Xlib.h>
+#   include <X11/Xatom.h>
+#   include <mce/mode-names.h>
+#   include <mce/dbus-names.h>
+#endif // Q_WS_MAEMO_5
 
 #include "bookview.h"
 #include "book.h"
 #include "librarydialog.h"
 #include "devtools.h"
 #include "mainwindow.h"
-#include "translucentbutton.h"
 #include "settingswindow.h"
 #include "bookmarksdialog.h"
 #include "settings.h"
+#include "chaptersdialog.h"
+#include "fullscreenwindow.h"
+#include "trace.h"
+#include "bookfinder.h"
+#include "progress.h"
+#include "dyalog.h"
+#include "translucentbutton.h"
+#include "platform.h"
+#include "progressdialog.h"
+#include "sortedlibrary.h"
 
 #ifdef DORIAN_TEST_MODEL
-#include "modeltest.h"
+#   include "modeltest.h"
 #endif
 
-#ifdef Q_WS_MAC
-#   define ICON_PREFIX ":/icons/mac/"
-#else
-#   define ICON_PREFIX ":/icons/"
-#endif
-
-const Qt::WindowFlags WIN_BIG_FLAGS =
-        Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint;
-const int WIN_BIG_TIMER = 3000;
-
 MainWindow::MainWindow(QWidget *parent):
-        QMainWindow(parent), view(0), isFullscreen(false)
+    AdopterWindow(parent), view(0), preventBlankingTimer(-1)
 {
+    TRACE;
 #ifdef Q_WS_MAEMO_5
     setAttribute(Qt::WA_Maemo5StackedWindow, true);
 #endif
-    setWindowTitle("Dorian");
+
+    // Central widget. Must be an intermediate, because the book view widget
+    // might be re-parented later
+    QFrame *central = new QFrame(this);
+    QVBoxLayout *layout = new QVBoxLayout(central);
+    layout->setMargin(0);
+    central->setLayout(layout);
+    setCentralWidget(central);
 
     // Book view
     view = new BookView(this);
-    setCentralWidget(view);
-
-    // Tool bar
-    setUnifiedTitleAndToolBarOnMac(true);
-    settings = new QDialog(this);
-    toolBar = addToolBar("controls");
-    toolBar->setMovable(false);
-    toolBar->setFloatable(false);
-    toolBar->toggleViewAction()->setVisible(false);
-#if defined(Q_WS_X11) && !defined(Q_WS_MAEMO_5)
-    toolBar->setIconSize(QSize(42, 42));
-#endif
-    previousAction = addToolBarAction(view, SLOT(goPrevious()), "previous");
-    nextAction = addToolBarAction(view, SLOT(goNext()), "next");
+
+    // Tool bar actions
+
+    chaptersAction = addToolBarAction(this, SLOT(showChapters()),
+                                      "chapters", tr("Chapters"), true);
     bookmarksAction = addToolBarAction(this, SLOT(showBookmarks()),
-                                       "bookmarks");
-#ifdef Q_WS_MAEMO_5
-    infoAction = new QAction(this);
-#else
-    infoAction = addToolBarAction(this, SLOT(showInfo()), "document-properties");
-#endif
+                                       "bookmarks", tr("Bookmarks"), true);
     libraryAction = addToolBarAction(this, SLOT(showLibrary()),
-                                     "system-file-manager");
-    settingsAction = addToolBarAction(this, SLOT(showSettings()),
-                                      "preferences-system");
+                                     "library", tr("Library"), false);
+
 #ifdef Q_WS_MAEMO_5
-    devToolsAction = new QAction(this);
+    settingsAction = menuBar()->addAction(tr("Settings"));
+    connect(settingsAction, SIGNAL(triggered()), this, SLOT(showSettings()));
+    devToolsAction = menuBar()->addAction(tr("Developer"));
+    connect(devToolsAction, SIGNAL(triggered()), this, SLOT(showDevTools()));
 #else
-    devToolsAction = addToolBarAction(this, SLOT(showDevTools()), "developer");
-    QFrame *frame = new QFrame(toolBar);
-    frame->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
-    toolBar->addWidget(frame);
+    settingsAction = addToolBarAction(this, SLOT(showSettings()),
+                                      "preferences-system", tr("Settings"));
+    devToolsAction = addToolBarAction(this, SLOT(showDevTools()),
+                                      "developer", tr("Developer"));
 #endif
-    fullScreenAction = addToolBarAction(this, SLOT(showFullScreen()),
-                                        "view-fullscreen");
+
+    rotateAction = addToolBarAction(this, SLOT(rotate()),
+                                    "rotate", tr("Rotate"), true);
+    addToolBarSpace();
+    fullScreenAction = addToolBarAction(this, SLOT(showBig()),
+        "view-fullscreen", tr("Full screen"), true);
+
+#if defined(Q_WS_MAEMO_5)
+    QAction *aboutAction = menuBar()->addAction(tr("About"));
+    connect(aboutAction, SIGNAL(triggered()), this, SLOT(about()));
+#else
+    addToolBarAction(this, SLOT(about()), "about", tr("About"));
+#endif // defined(Q_WS_MAEMO_5)
+
+#if defined(Q_OS_SYMBIAN)
+    (void)addToolBarAction(this, SLOT(close()), "", tr("Exit"), false);
+#endif // defined(Q_OS_SYMBIAN)
+
+    // Decorations
+    prev = new TranslucentButton("back", this);
+    next = new TranslucentButton("forward", this);
+    prog = new Progress(this);
 
     // Handle model changes
     connect(Library::instance(), SIGNAL(nowReadingChanged()),
             this, SLOT(onCurrentBookChanged()));
 
-    normalFlags = windowFlags();
-    restoreButton = new TranslucentButton("view-fullscreen", this);
+    // Load library, upgrade it if needed
+    libraryProgress = new ProgressDialog(tr("Upgrading library"), this);
+    Library *library = Library::instance();
+    connect(library, SIGNAL(beginUpgrade(int)),
+            this, SLOT(onBeginUpgrade(int)));
+    connect(library, SIGNAL(upgrading(const QString &)),
+            this, SLOT(onUpgrading(const QString &)));
+    connect(library, SIGNAL(endUpgrade()), this, SLOT(onEndUpgrade()));
+
+    // Handle loading book parts
+    connect(view, SIGNAL(partLoadStart(int)), this, SLOT(onPartLoadStart()));
+    connect(view, SIGNAL(partLoadEnd(int)), this, SLOT(onPartLoadEnd(int)));
 
-    // Load book on command line, or load last read book, or load default book
+    // Handle progress
+    connect(view, SIGNAL(progress(qreal)), prog, SLOT(setProgress(qreal)));
+
+    // Shadow window for full screen reading
+    fullScreenWindow = new FullScreenWindow();
+    connect(fullScreenWindow, SIGNAL(restore()), this, SLOT(showRegular()));
+
+    // Handle settings changes
+    connect(Settings::instance(), SIGNAL(valueChanged(const QString &)),
+            this, SLOT(onSettingsChanged(const QString &)));
+
+    // Handle book view buttons
+    connect(next, SIGNAL(triggered()), this, SLOT(goToNextPage()));
+    connect(prev, SIGNAL(triggered()), this, SLOT(goToPreviousPage()));
+
+#ifdef DORIAN_TEST_MODEL
+    (void)new ModelTest(Library::instance(), this);
+#endif
+}
+
+MainWindow::~MainWindow()
+{
+    delete fullScreenWindow;
+}
+
+void MainWindow::initialize()
+{
+    TRACE;
     Library *library = Library::instance();
+
+    // Show in regular (non full-screen) mode
+    showRegular();
+
+    // Upgrade library if needed, then load it
+    library->upgrade();
+    library->load();
+
+    // Load book on command line, or load last read book, or load default book
     if (QCoreApplication::arguments().size() == 2) {
         QString path = QCoreApplication::arguments()[1];
         library->add(path);
@@ -95,60 +159,54 @@ MainWindow::MainWindow(QWidget *parent):
         if (index.isValid()) {
             library->setNowReading(index);
         }
-    }
-    else {
+    } else {
         QModelIndex index = library->nowReading();
         if (index.isValid()) {
             library->setNowReading(index);
-        }
-        else {
+        } else {
             if (!library->rowCount()) {
-                library->add(":/books/2 B R 0 2 B.epub");
+                library->add(":/books/2BR02B.epub");
             }
-            library->setNowReading(library->index(0));
+            SortedLibrary sorted;
+            library->setNowReading(sorted.mapToSource(sorted.index(0, 0)));
         }
     }
-
-    // Handle settings changes
-    connect(Settings::instance(), SIGNAL(valueChanged(const QString &)),
-            this, SLOT(onSettingsChanged(const QString &)));
-    Settings::instance()->setValue("orientation",
-                                   Settings::instance()->value("orientation"));
-
-    // Handle loading chapters
-    connect(view, SIGNAL(chapterLoaded(int)), this, SLOT(onChapterLoaded(int)));
-
-#ifdef DORIAN_TEST_MODEL
-    (void)new ModelTest(Library::instance(), this);
-#endif
 }
 
 void MainWindow::onCurrentBookChanged()
 {
+    TRACE;
     setCurrentBook(Library::instance()->nowReading());
 }
 
-void MainWindow::showNormal()
+void MainWindow::showRegular()
 {
-    qDebug() << "MainWindow::showNormal";
-    isFullscreen = false;
-    setWindowFlags(normalFlags);
-    hide();
-    setGeometry(normalGeometry);
-    toolBar->show();
-    restoreButton->hide();
+    TRACE;
+
+    view->setLastBookmark();
+    fullScreenWindow->leaveBookView();
+    takeBookView(view, prog, prev, next);
+
+    fullScreenWindow->hide();
     show();
+    view->scheduleRestoreLastBookmark();
 }
 
-void MainWindow::showFullScreen()
+void MainWindow::showBig()
 {
-    qDebug() << "MainWindow::showFullscreen";
-    normalGeometry = geometry();
-    isFullscreen = true;
-    toolBar->hide();
-    setWindowFlags(normalFlags | WIN_BIG_FLAGS);
-    showMaximized();
-    restoreButton->flash();
+    TRACE;
+
+    view->setLastBookmark();
+    leaveBookView();
+    fullScreenWindow->takeBookView(view, prog, prev, next);
+
+#if defined(Q_WS_MAEMO_5)
+    fullScreenWindow->raise();
+#else
+    hide();
+#endif
+    fullScreenWindow->showFullScreen();
+    view->scheduleRestoreLastBookmark();
 }
 
 void MainWindow::setCurrentBook(const QModelIndex &current)
@@ -156,42 +214,31 @@ void MainWindow::setCurrentBook(const QModelIndex &current)
     mCurrent = current;
     Book *book = Library::instance()->book(current);
     view->setBook(book);
-    setWindowTitle(book? book->name(): tr("Dorian"));
-}
-
-QAction *MainWindow::addToolBarAction(const QObject *receiver,
-                                      const char *member,
-                                      const QString &name)
-{
-    return toolBar->
-        addAction(QIcon(ICON_PREFIX + name + ".png"), "", receiver, member);
+    setWindowTitle(book? book->shortName(): tr("Dorian"));
 }
 
 void MainWindow::showLibrary()
 {
-    LibraryDialog *dialog = new LibraryDialog();
-    dialog->exec();
+    (new LibraryDialog(this))->show();
 }
 
 void MainWindow::showSettings()
 {
-    SettingsWindow *settings = new SettingsWindow(this);
-    settings->show();
+    (new SettingsWindow(this))->show();
 }
 
-void MainWindow::showInfo()
+void MainWindow::rotate()
 {
-    if (mCurrent.isValid()) {
-        InfoDialog *info =
-            new InfoDialog(Library::instance()->book(mCurrent), this);
-        info->exec();
-    }
+    QString current = Settings::instance()->value("orientation",
+        Platform::instance()->defaultOrientation()).toString();
+    QString target = (current == "landscape")? "portrait": "landscape";
+    view->setLastBookmark();
+    Settings::instance()->setValue("orientation", target);
 }
 
 void MainWindow::showDevTools()
 {
-    DevTools *devTools = new DevTools();
-    devTools->exec();
+    (new DevTools(this))->exec();
 }
 
 void MainWindow::showBookmarks()
@@ -199,84 +246,190 @@ void MainWindow::showBookmarks()
     Book *book = Library::instance()->book(mCurrent);
     if (book) {
         BookmarksDialog *bookmarks = new BookmarksDialog(book, this);
-        int ret = bookmarks->exec();
-        if (ret > 0) {
-            int index = ret - 1;
-            view->goToBookmark(book->bookmarks()[index]);
-        }
-        else if (ret < 0) {
-            view->addBookmark();
-        }
+        connect(bookmarks, SIGNAL(addBookmark(const QString &)),
+                this, SLOT(onAddBookmark(const QString &)));
+        connect(bookmarks, SIGNAL(goToBookmark(int)),
+                this, SLOT(onGoToBookmark(int)));
+        bookmarks->show();
     }
 }
 
-void MainWindow::MOUSE_ACTIVATE_EVENT(QMouseEvent *event)
+void MainWindow::onSettingsChanged(const QString &key)
 {
-    qDebug() << "MainWindow::mousePress/ReleaseEvent at" << event->pos()
-            << "against" << fullScreenZone();
-    if (isFullscreen && fullScreenZone().contains(event->x(), event->y())) {
-        qDebug() << " In fullScreenZone";
-        showNormal();
+    TRACE;
+    qDebug() << "Key" << key;
+
+    if (key == "orientation") {
+        QString value = Settings::instance()->value(key,
+            Platform::instance()->defaultOrientation()).toString();
+        qDebug() << "Value: orientation" << value;
+        Platform::instance()->setOrientation(this, value);
+        Platform::instance()->setOrientation(fullScreenWindow, value);
+    }
+
+#if defined(Q_WS_MAEMO_5)
+    else if (key == "lightson") {
+        bool enable = Settings::instance()->value(key, false).toBool();
+        killTimer(preventBlankingTimer);
+        if (enable) {
+            preventBlankingTimer = startTimer(29 * 1000);
+        }
     }
-    QMainWindow::MOUSE_ACTIVATE_EVENT(event);
+#endif // defined(Q_WS_MAEMO_5)
 }
 
-QRect MainWindow::fullScreenZone() const
+void MainWindow::onPartLoadStart()
 {
-    return QRect(width() / 2 - 45, height() - 104, 95, 95);
+    TRACE;
+    Platform::instance()->showBusy(this, true);
+}
+
+void MainWindow::onPartLoadEnd(int index)
+{
+    TRACE;
+    bool enablePrevious = false;
+    bool enableNext = false;
+    Book *book = Library::instance()->book(mCurrent);
+    if (book) {
+        if (index > 0) {
+            enablePrevious = true;
+        }
+        if (index < (book->parts.size() - 1)) {
+            enableNext = true;
+        }
+    }
+    Platform::instance()->showBusy(this, false);
 }
 
-void MainWindow::resizeEvent(QResizeEvent *event)
+void MainWindow::onAddBookmark(const QString &note)
 {
-    (void)event;
-    restoreButton->setGeometry(fullScreenZone());
+    TRACE;
+    view->addBookmark(note);
+    Platform::instance()->information(tr("Bookmarked current position"), this);
 }
 
-void MainWindow::closeEvent(QCloseEvent *event)
+void MainWindow::onGoToBookmark(int index)
 {
-    qDebug() << "MainWindow::closeEvent";
-    view->setLastBookmark();
-    event->accept();
+    TRACE;
+    Book *book = Library::instance()->book(mCurrent);
+    view->goToBookmark(book->bookmarks()[index]);
 }
 
-void MainWindow::onSettingsChanged(const QString &key)
+void MainWindow::showChapters()
 {
-#ifdef Q_WS_MAEMO_5
-    if (key == "orientation") {
-        QString value = Settings::instance()->value(key).toString();
-        if (value == "portrait") {
-            setAttribute(Qt::WA_Maemo5PortraitOrientation, true);
-            setAttribute(Qt::WA_Maemo5LandscapeOrientation, false);
-        }
-        else {
-            setAttribute(Qt::WA_Maemo5PortraitOrientation, false);
-            setAttribute(Qt::WA_Maemo5LandscapeOrientation, true);
-        }
+    Book *book = Library::instance()->book(mCurrent);
+    if (book) {
+        ChaptersDialog *chapters = new ChaptersDialog(book, this);
+        connect(chapters, SIGNAL(goToChapter(int)),
+                this, SLOT(onGoToChapter(int)));
+        chapters->show();
     }
-#else
-    Q_UNUSED(key);
-#endif // Q_WS_MAEMO_5
 }
 
-void MainWindow::onChapterLoaded(int index)
+void MainWindow::onGoToChapter(int index)
 {
-    bool enablePrevious = false;
-    bool enableNext = false;
+    TRACE;
+
     Book *book = Library::instance()->book(mCurrent);
     if (book) {
-        if (index > 0) {
-            enablePrevious = true;
-        }
-        if (index < (book->toc.size() - 1)) {
-            enableNext = true;
+        QString fragment;
+        int partIndex = book->partFromChapter(index, fragment);
+        if (partIndex != -1) {
+            view->goToPart(partIndex, fragment);
         }
     }
+}
+
+void MainWindow::timerEvent(QTimerEvent *event)
+{
+    if (event->timerId() == preventBlankingTimer) {
 #ifdef Q_WS_MAEMO_5
-    previousAction->setIcon(QIcon(enablePrevious?
-        ":/icons/previous.png" : ":/icons/previous-disabled.png"));
-    nextAction->setIcon(QIcon(enableNext?
-        ":/icons/next.png": ":/icons/next-disabled.png"));
+        QDBusInterface mce(MCE_SERVICE, MCE_REQUEST_PATH,
+                           MCE_REQUEST_IF, QDBusConnection::systemBus());
+        mce.call(MCE_PREVENT_BLANK_REQ);
 #endif // Q_WS_MAEMO_5
-    previousAction->setEnabled(enablePrevious);
-    nextAction->setEnabled(enableNext);
+        qDebug() << "MainWindow::timerEvent: Prevent display blanking";
+    }
+    AdopterWindow::timerEvent(event);
+}
+
+void MainWindow::about()
+{
+    Dyalog *aboutDialog = new Dyalog(this, false);
+    aboutDialog->setWindowTitle(tr("About Dorian"));
+    QString version = Platform::instance()->version();
+#if !defined(Q_WS_MAEMO_5) && !defined(Q_OS_SYMBIAN)
+    QLabel *icon = new QLabel(aboutDialog);
+    QPixmap pixmap(Platform::instance()->icon("dorian"));
+    icon->setPixmap(pixmap);
+    aboutDialog->addWidget(icon);
+#endif
+    QLabel *label = new QLabel(aboutDialog);
+    label->setTextFormat(Qt::RichText);
+    label->setOpenExternalLinks(true);
+    label->setWordWrap(true);
+    label->setText(tr("<b>Dorian %1</b><br><br>"
+        "Copyright &copy; 2010-2011 by "
+        "Akos Polster &lt;akos@pipacs.com&gt;<br><br>"
+        "Licensed under GNU General Public License, Version 3<br><br>"
+        "<a href='http://dorian.garage.maemo.org/'>"
+        "dorian.garage.maemo.org</a><br><br>"
+        ).arg(version));
+    aboutDialog->addWidget(label);
+    aboutDialog->addStretch();
+    aboutDialog->show();
+}
+
+void MainWindow::goToNextPage()
+{
+    next->flash();
+    prev->flash();
+    view->goNextPage();
+}
+
+void MainWindow::goToPreviousPage()
+{
+    next->flash();
+    prev->flash();
+    view->goPreviousPage();
+}
+
+void MainWindow::onBeginUpgrade(int total)
+{
+    libraryProgress->setVisible(total > 0);
+    libraryProgress->setWindowTitle(tr("Upgrading library"));
+    libraryProgress->setMaximum(total);
+}
+
+void MainWindow::onUpgrading(const QString &path)
+{
+    libraryProgress->setLabelText(tr("Upgrading %1").
+                                  arg(QFileInfo(path).fileName()));
+    libraryProgress->setValue(libraryProgress->value() + 1);
+}
+
+void MainWindow::onEndUpgrade()
+{
+    libraryProgress->hide();
+    libraryProgress->reset();
+}
+
+void MainWindow::onBeginLoad(int total)
+{
+    libraryProgress->setVisible(total > 0);
+    libraryProgress->setWindowTitle(tr("Loading library"));
+    libraryProgress->setMaximum(total);
+}
+
+void MainWindow::onLoading(const QString &path)
+{
+    libraryProgress->setLabelText(tr("Loading %1").
+                                  arg(QFileInfo(path).fileName()));
+    libraryProgress->setValue(libraryProgress->value() + 1);
+}
+
+void MainWindow::onEndLoad()
+{
+    libraryProgress->hide();
+    libraryProgress->reset();
 }