<commit_before>/*
 * Copyright (c) 2010, Intel Corporation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Intel Corporation nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "chrome/browser/ui/meegotouch/back_forward_button_qt.h"
#include "chrome/browser/ui/meegotouch/browser_window_qt.h"
#include "chrome/browser/ui/meegotouch/browser_toolbar_qt.h"
#include "base/utf_string_conversions.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "base/string_number_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "content/browser/tab_contents/navigation_controller.h"
#include "content/browser/tab_contents/navigation_entry.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "net/base/registry_controlled_domain.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"

#include <QGraphicsItem>
#include <QGraphicsSceneMouseEvent>
#include <QVector>
#include <QList>
#include <QTimer>
#include <algorithm>
#include <QGraphicsSceneResizeEvent>
#include <QGraphicsWidget>
#include <QEvent>
#include <QDebug>
//#include <QTapAndHoldGesture>

#include <QDeclarativeEngine>
#include <QDeclarativeView>
#include <QDeclarativeContext>
#include <QDeclarativeItem>
#include <QDeclarativeImageProvider>
#include <QAbstractListModel>

// Image provider, managing to provide image to QML
// for history view
// Due to qml limitation, the id of image is suffixed with
// a static increaser, which forces using new image source
// each time
class HistoryImageProvider : public QDeclarativeImageProvider
{
public:
    HistoryImageProvider()
        : QDeclarativeImageProvider(QDeclarativeImageProvider::Image)
    {}

    // clear all images in image hashmap
    void clear()
    {
        imageList_.clear();
    }

    // overrided function, inherited from QDeclarativeImageProvider
    virtual QImage requestImage(const QString& id,
                                QSize* size,
                                const QSize& requestedSize)
    {
        DLOG(INFO) << "requesting image id: " << id.toStdString();
        int finded = id.indexOf("_");
        if (finded != -1) {
            QImage& image = imageList_[id.left(finded)];
            if (!image.isNull()) {
                //QImage scaled = image.scaled(requestedSize);
                *size = image.size();
                return image;
            }
        }
        *size = QSize(0, 0);
        return QImage();
    }

    // add a new image
    void addImage(const QString& id, const QImage &image)
    {
        imageList_.insert(id, image);
    }

private:
    QMap<QString, QImage> imageList_;
};

class HistoryStackModel;

// history entry to represent one history data
class HistoryEntry
{
public:

    // constructor
    // @param index the index in history stack
    // @param hiProvider image provider for history stack
    // @param entry representation of navigation entry in browser
    // @param controller current navigation controller in browser
    // @param model history stack model
    HistoryEntry(const int index,
                 HistoryImageProvider& hiProvider,
                 NavigationEntry* entry,
                 NavigationController* controller,
                 HistoryStackModel* model)
        : index_(index), hiProvider_(hiProvider), entry_(entry), model_(model)
    {
        // get image
        HistoryService* hs = controller->profile()->GetHistoryService(Profile::EXPLICIT_ACCESS);
        hs->GetPageThumbnail(entry->url(),
                             &consumer_,
                             NewCallback(static_cast<HistoryEntry*>(this),
                                         &HistoryEntry::onThumbnailDataAvailable));

        std::wstring title_str = UTF16ToWide(entry->title());
        title_ = QString::fromStdWString(title_str);
    }

    void imgURLGen()
    {
        static QString prefix("image://historystack/");
        imageSrc_ = prefix + QString::number(index_) + "_" + QString::number(reloadNumber_);
    }

    // callback to get the image data from browser
    void onThumbnailDataAvailable(HistoryService::Handle request_handle,
                                  scoped_refptr<RefCountedBytes> jpeg_data);

    NavigationEntry* entry() { return entry_; }
    QString image() { return imageSrc_; }
    QString title() { return title_; }

    static void incReloadNumber() { reloadNumber_++; }
    static unsigned long reloadNumber() { return reloadNumber_; }

private:
    // static increaser to generate unique image source
    static unsigned long reloadNumber_;

    int index_;
    HistoryImageProvider& hiProvider_;
    NavigationEntry* entry_;
    HistoryStackModel* model_;
    // image source
    QString imageSrc_;
    // history title
    QString title_;
    CancelableRequestConsumer consumer_;
};

unsigned long HistoryEntry::reloadNumber_ = 0;

// represent list model used in QML to store history data
class HistoryStackModel: public QAbstractListModel
{
    Q_OBJECT
    enum HistoryRole {
        IMAGE_ROLE = Qt::UserRole + 1,
        TITLE_ROLE
    };

public:
    HistoryStackModel(BackForwardButtonQtImpl* backForward)
        : back_forward_(backForward), returnedImages_(0)
    {
        QHash<int, QByteArray> roles;
        roles[IMAGE_ROLE] = "thumbSrc";
        roles[TITLE_ROLE] = "title";
        setRoleNames(roles);
    }

    ~HistoryStackModel()
    {
        clear();
    }

    // clear saved data
    void clear()
    {
        returnedImages_ = 0;
        beginResetModel();
        for(int i = 0; i < entryList_.count(); i++) {
            delete entryList_[i];
        }
        entryList_.clear();
        hiProvider_.clear();
        endResetModel();
    }

    // wrapper to check whether browser returns all images of history
    // so we can reset model to avoid resetting model many times
    void beginReset()
    {
        // begin reset if necessary
        returnedImages_++;
        if (returnedImages_ == rowCount()) {
            DLOG(INFO) << "begin reset history stack model";
            // generate new number to create new image url
            HistoryEntry::incReloadNumber();
            for(int i = 0; i < entryList_.count(); i++) {
                HistoryEntry* entry = entryList_[i];
                entry->imgURLGen();
            }
            beginResetModel();
        }
    }

    void endReset()
    {
        // end reset if necessary
        if (returnedImages_ == rowCount()) {
            DLOG(INFO) << "end reset history stack model";
            endResetModel();
        }
    }

    int rowCount(const QModelIndex& parent = QModelIndex()) const
    {
        return entryList_.count();
    }

    QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const
    {
        DLOG(INFO) << "read list model data: row = " << index.row() << ", column = " << index.column();
        if(index.row() < 0 || index.row() > entryList_.count())
            return QVariant();
        HistoryEntry* entry = entryList_[index.row()];
        switch(role) {
            case IMAGE_ROLE:
                return entry->image();
            case TITLE_ROLE:
                return entry->title();
            default:
                return QVariant();
        }
    }

    void appendEntry(NavigationController* controller, NavigationEntry *entry)
    {
        HistoryEntry* historyEntry
                                = new HistoryEntry(entryList_.count(),
                                                   hiProvider_,
                                                   entry,
                                                   controller,
                                                   this);
        beginInsertRows(QModelIndex(), rowCount(), rowCount());
        entryList_.push_back(historyEntry);
        endInsertRows();
    }

    // emit a showHistory signal to QML
    void show() { emit showHistory(); }

    // emit a hideHistory signal to QML
    void hide() { emit hideHistory(); }

    // emit a current selected(focused) history entry
    void setCurrent(int index) { emit current(index); }

    HistoryImageProvider* hiProvider() { return &hiProvider_; }

Q_SIGNALS:
    // three signals used to notify QML
    void showHistory();
    void hideHistory();
    void current(int index);

public Q_SLOTS:
    // open specific page, called by QML element
    // It's called by QML element when user clicks one history entry in QML view
    void openPage(const int index);

private:
    BackForwardButtonQtImpl* back_forward_;
    // list to hold entries
    QList<HistoryEntry*> entryList_;
    HistoryImageProvider hiProvider_;
    // count of returned images from browser
    int returnedImages_;
};

class BackForwardButtonQtImpl
{
public:
    enum NaviState {
        ONLY_BACK = 0,
        ONLY_FORWARD,
        BACK_FORWARD
    };

    // constructor
    BackForwardButtonQtImpl(BrowserToolbarQt* toolbar, Browser* browser, BrowserWindowQt* window)
        :toolbar_(toolbar), browser_(browser), model_(this),
        state_(ONLY_BACK), active_(false)
    {
        QDeclarativeView* view = window->DeclarativeView();
        QDeclarativeContext *context = view->rootContext();
        context->setContextProperty("historyStackModel", &model_);
        context->engine()->addImageProvider(QLatin1String("historystack"), model_.hiProvider());
    }

    NavigationController* currentController()
    {
        return &(browser_->GetSelectedTabContents()->controller());
    }

    void openPage(NavigationEntry *entry)
    {
        currentController()->GoToIndex(currentController()->GetIndexOfEntry(entry));
        updateStatus();
    }

    void updateStatus()
    {
        if(currentController()->GetCurrentEntryIndex() == currentController()->entry_count() - 1)
        {
            state_ = ONLY_BACK;
            if (currentController()->entry_count() > 1) {
                active_ = true;
            } else {
                active_ = false;
            }
        } else if (currentController()->GetCurrentEntryIndex() == 0
                   && currentController()->entry_count() > 0) {
            state_ = ONLY_FORWARD;
        } else if (currentController()->CanGoBack() && currentController()->CanGoForward()) {
            state_ = BACK_FORWARD;
        } else {
            state_ = ONLY_BACK;
            active_ = false;
        }
        // update button status in qml
        updateButton();
        DLOG(INFO) << "In C++, updateStatus is invoked\n";
    }

    // update back-forward button icon
    void updateButton() { toolbar_->updateBfButton((int)state_, active_); }

    void tap()
    {
        DLOG(INFO) << "In C++, tap is invoked";
        switch(state_) {
        case ONLY_BACK:
            if (currentController()->CanGoBack()) {
                currentController()->GoBack();
            }
            break;
        case ONLY_FORWARD:
            if (currentController()->entry_count() == 2) {
                if (currentController()->CanGoForward()) {
                    currentController()->GoForward();
                }
            } else {
                prepareAndShowHistory();
            }
            break;
        case BACK_FORWARD:
            prepareAndShowHistory();
            break;
        default:
            break;
        }
    }

    void tapAndHold()
    {
        switch(state_) {
        case ONLY_BACK:
            prepareAndShowHistory();
            break;
        case ONLY_FORWARD:
            if (currentController()->entry_count() == 2) {
                if (currentController()->CanGoForward()) {
                    currentController()->GoForward();
                }
            } else {
                prepareAndShowHistory();
            }
            break;
        case BACK_FORWARD:
                prepareAndShowHistory();
            break;
        default:
            break;
        }
        updateStatus();
    }

    //prepare c++ list model and emit signal to QML to show it
    void prepareAndShowHistory()
    {
        model_.clear();
        int count = currentController()->entry_count();
        int curr = -1;
        for(int i = count - 1; i >= 0; i--)
        {
            DLOG(INFO) << "page index: ---" << i << "---\n";
            NavigationEntry* navEntry = currentController()->GetEntryAtIndex(i);
            // don't skip 'newtab' now, if yes, we do not only skip newtab here
            // but also skip count calculation for 'updateStatus'
            /*
            if (navEntry->url().HostNoBrackets() == "newtab") {
                // skip 'newtab'
                continue;
            }*/
            model_.appendEntry(currentController(), navEntry);
            curr++;
            if(currentController()->GetCurrentEntryIndex() == i) {
                model_.setCurrent(curr);
            }
        }
        model_.show();
        toolbar_->showHistory();
    }

private:
    BrowserToolbarQt* toolbar_;
    Browser* browser_;
    HistoryStackModel model_;

    // current navigation state
    NaviState state_;
    // whether the backward/forward button is active
    bool active_;
};

BackForwardButtonQt::BackForwardButtonQt(BrowserToolbarQt* toolbar, Browser* browser, BrowserWindowQt* window)
{
  impl_ = new BackForwardButtonQtImpl(toolbar, browser, window);
}

BackForwardButtonQt::~BackForwardButtonQt()
{
  delete impl_;
}

void BackForwardButtonQt::tap()
{
  impl_->tap();
}

void BackForwardButtonQt::tapAndHold()
{
  impl_->tapAndHold();
}

void BackForwardButtonQt::updateStatus()
{
  impl_->updateStatus();
}

void HistoryEntry::onThumbnailDataAvailable(HistoryService::Handle request_handle,
                                            scoped_refptr<RefCountedBytes> jpeg_data)
{
    model_->beginReset();
    if (jpeg_data.get()) {
        DLOG(INFO) << "get image id: " << index_;
        std::vector<unsigned char> thumbnail_data;
        std::copy(jpeg_data->data.begin(), jpeg_data->data.end(),
                std::back_inserter(thumbnail_data));
        QImage image = QImage::fromData(thumbnail_data.data(), thumbnail_data.size());
        hiProvider_.addImage(QString::number(index_), image);
    }
    model_->endReset();
}

void HistoryStackModel::openPage(const int index)
{
    back_forward_->openPage(entryList_[index]->entry());
    hide();
}

#include "moc_back_forward_button_qt.cc"
<commit_msg>History: get thumbnails from TopSites<commit_after>/*
 * Copyright (c) 2010, Intel Corporation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Intel Corporation nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "chrome/browser/ui/meegotouch/back_forward_button_qt.h"
#include "chrome/browser/ui/meegotouch/browser_window_qt.h"
#include "chrome/browser/ui/meegotouch/browser_toolbar_qt.h"
#include "base/utf_string_conversions.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "base/string_number_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "content/browser/tab_contents/navigation_controller.h"
#include "content/browser/tab_contents/navigation_entry.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "net/base/registry_controlled_domain.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"

#include <QGraphicsItem>
#include <QGraphicsSceneMouseEvent>
#include <QVector>
#include <QList>
#include <QTimer>
#include <algorithm>
#include <QGraphicsSceneResizeEvent>
#include <QGraphicsWidget>
#include <QEvent>
#include <QDebug>
//#include <QTapAndHoldGesture>

#include <QDeclarativeEngine>
#include <QDeclarativeView>
#include <QDeclarativeContext>
#include <QDeclarativeItem>
#include <QDeclarativeImageProvider>
#include <QAbstractListModel>

// Image provider, managing to provide image to QML
// for history view
// Due to qml limitation, the id of image is suffixed with
// a static increaser, which forces using new image source
// each time
class HistoryImageProvider : public QDeclarativeImageProvider
{
public:
    HistoryImageProvider()
        : QDeclarativeImageProvider(QDeclarativeImageProvider::Image)
    {}

    // clear all images in image hashmap
    void clear()
    {
        imageList_.clear();
    }

    // overrided function, inherited from QDeclarativeImageProvider
    virtual QImage requestImage(const QString& id,
                                QSize* size,
                                const QSize& requestedSize)
    {
        DLOG(INFO) << "requesting image id: " << id.toStdString();
        int finded = id.indexOf("_");
        if (finded != -1) {
            QImage& image = imageList_[id.left(finded)];
            if (!image.isNull()) {
                //QImage scaled = image.scaled(requestedSize);
                *size = image.size();
                return image;
            }
        }
        *size = QSize(0, 0);
        return QImage();
    }

    // add a new image
    void addImage(const QString& id, const QImage &image)
    {
        imageList_.insert(id, image);
    }

private:
    QMap<QString, QImage> imageList_;
};

class HistoryStackModel;

// history entry to represent one history data
class HistoryEntry
{
public:

    // constructor
    // @param index the index in history stack
    // @param hiProvider image provider for history stack
    // @param entry representation of navigation entry in browser
    // @param controller current navigation controller in browser
    // @param model history stack model
    HistoryEntry(const int index,
                 HistoryImageProvider& hiProvider,
                 NavigationEntry* entry,
                 NavigationController* controller,
                 HistoryStackModel* model)
        : index_(index), hiProvider_(hiProvider), entry_(entry), model_(model)
    {
        // get image
        getThumbnailData(controller);
        std::wstring title_str = UTF16ToWide(entry->title());
        title_ = QString::fromStdWString(title_str);
    }

    void imgURLGen()
    {
        static QString prefix("image://historystack/");
        imageSrc_ = prefix + QString::number(index_) + "_" + QString::number(reloadNumber_);
    }

    void getThumbnailData(NavigationController *controller);

    NavigationEntry* entry() { return entry_; }
    QString image() { return imageSrc_; }
    QString title() { return title_; }

    static void incReloadNumber() { reloadNumber_++; }
    static unsigned long reloadNumber() { return reloadNumber_; }

private:
    // static increaser to generate unique image source
    static unsigned long reloadNumber_;

    int index_;
    HistoryImageProvider& hiProvider_;
    NavigationEntry* entry_;
    HistoryStackModel* model_;
    // image source
    QString imageSrc_;
    // history title
    QString title_;
    CancelableRequestConsumer consumer_;
};

unsigned long HistoryEntry::reloadNumber_ = 0;

// represent list model used in QML to store history data
class HistoryStackModel: public QAbstractListModel
{
    Q_OBJECT
    enum HistoryRole {
        IMAGE_ROLE = Qt::UserRole + 1,
        TITLE_ROLE
    };

public:
    HistoryStackModel(BackForwardButtonQtImpl* backForward)
        : back_forward_(backForward), returnedImages_(0)
    {
        QHash<int, QByteArray> roles;
        roles[IMAGE_ROLE] = "thumbSrc";
        roles[TITLE_ROLE] = "title";
        setRoleNames(roles);
    }

    ~HistoryStackModel()
    {
        clear();
    }

    // clear saved data
    void clear()
    {
        returnedImages_ = 0;
        beginResetModel();
        for(int i = 0; i < entryList_.count(); i++) {
            delete entryList_[i];
        }
        entryList_.clear();
        hiProvider_.clear();
        endResetModel();
    }

    int rowCount(const QModelIndex& parent = QModelIndex()) const
    {
        return entryList_.count();
    }

    QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const
    {
        DLOG(INFO) << "read list model data: row = " << index.row() << ", column = " << index.column();
        if(index.row() < 0 || index.row() > entryList_.count())
            return QVariant();
        HistoryEntry* entry = entryList_[index.row()];
        switch(role) {
            case IMAGE_ROLE:
                return entry->image();
            case TITLE_ROLE:
                return entry->title();
            default:
                return QVariant();
        }
    }

    void appendEntry(NavigationController* controller, NavigationEntry *entry)
    {
        HistoryEntry* historyEntry
                                = new HistoryEntry(entryList_.count(),
                                                   hiProvider_,
                                                   entry,
                                                   controller,
                                                   this);
        historyEntry->imgURLGen();
        beginInsertRows(QModelIndex(), rowCount(), rowCount());
        entryList_.push_back(historyEntry);
        endInsertRows();
    }

    // emit a showHistory signal to QML
    void show() { emit showHistory(); }

    // emit a hideHistory signal to QML
    void hide() { emit hideHistory(); }

    // emit a current selected(focused) history entry
    void setCurrent(int index) { emit current(index); }

    HistoryImageProvider* hiProvider() { return &hiProvider_; }

Q_SIGNALS:
    // three signals used to notify QML
    void showHistory();
    void hideHistory();
    void current(int index);

public Q_SLOTS:
    // open specific page, called by QML element
    // It's called by QML element when user clicks one history entry in QML view
    void openPage(const int index);

private:
    BackForwardButtonQtImpl* back_forward_;
    // list to hold entries
    QList<HistoryEntry*> entryList_;
    HistoryImageProvider hiProvider_;
    // count of returned images from browser
    int returnedImages_;
};

class BackForwardButtonQtImpl
{
public:
    enum NaviState {
        ONLY_BACK = 0,
        ONLY_FORWARD,
        BACK_FORWARD
    };

    // constructor
    BackForwardButtonQtImpl(BrowserToolbarQt* toolbar, Browser* browser, BrowserWindowQt* window)
        :toolbar_(toolbar), browser_(browser), model_(this),
        state_(ONLY_BACK), active_(false)
    {
        QDeclarativeView* view = window->DeclarativeView();
        QDeclarativeContext *context = view->rootContext();
        context->setContextProperty("historyStackModel", &model_);
        context->engine()->addImageProvider(QLatin1String("historystack"), model_.hiProvider());
    }

    NavigationController* currentController()
    {
        return &(browser_->GetSelectedTabContents()->controller());
    }

    void openPage(NavigationEntry *entry)
    {
        currentController()->GoToIndex(currentController()->GetIndexOfEntry(entry));
        updateStatus();
    }

    void updateStatus()
    {
        if(currentController()->GetCurrentEntryIndex() == currentController()->entry_count() - 1)
        {
            state_ = ONLY_BACK;
            if (currentController()->entry_count() > 1) {
                active_ = true;
            } else {
                active_ = false;
            }
        } else if (currentController()->GetCurrentEntryIndex() == 0
                   && currentController()->entry_count() > 0) {
            state_ = ONLY_FORWARD;
        } else if (currentController()->CanGoBack() && currentController()->CanGoForward()) {
            state_ = BACK_FORWARD;
        } else {
            state_ = ONLY_BACK;
            active_ = false;
        }
        // update button status in qml
        updateButton();
        DLOG(INFO) << "In C++, updateStatus is invoked\n";
    }

    // update back-forward button icon
    void updateButton() { toolbar_->updateBfButton((int)state_, active_); }

    void tap()
    {
        DLOG(INFO) << "In C++, tap is invoked";
        switch(state_) {
        case ONLY_BACK:
            if (currentController()->CanGoBack()) {
                currentController()->GoBack();
            }
            break;
        case ONLY_FORWARD:
            if (currentController()->entry_count() == 2) {
                if (currentController()->CanGoForward()) {
                    currentController()->GoForward();
                }
            } else {
                prepareAndShowHistory();
            }
            break;
        case BACK_FORWARD:
            prepareAndShowHistory();
            break;
        default:
            break;
        }
    }

    void tapAndHold()
    {
        switch(state_) {
        case ONLY_BACK:
            prepareAndShowHistory();
            break;
        case ONLY_FORWARD:
            if (currentController()->entry_count() == 2) {
                if (currentController()->CanGoForward()) {
                    currentController()->GoForward();
                }
            } else {
                prepareAndShowHistory();
            }
            break;
        case BACK_FORWARD:
                prepareAndShowHistory();
            break;
        default:
            break;
        }
        updateStatus();
    }

    //prepare c++ list model and emit signal to QML to show it
    void prepareAndShowHistory()
    {
        model_.clear();
        int count = currentController()->entry_count();
        int curr = -1;
        HistoryEntry::incReloadNumber();
        for(int i = count - 1; i >= 0; i--)
        {
            DLOG(INFO) << "page index: ---" << i << "---\n";
            NavigationEntry* navEntry = currentController()->GetEntryAtIndex(i);
            // don't skip 'newtab' now, if yes, we do not only skip newtab here
            // but also skip count calculation for 'updateStatus'
            /*
            if (navEntry->url().HostNoBrackets() == "newtab") {
                // skip 'newtab'
                continue;
            }*/
            model_.appendEntry(currentController(), navEntry);
            curr++;
            if(currentController()->GetCurrentEntryIndex() == i) {
                model_.setCurrent(curr);
            }
        }
        model_.show();
        toolbar_->showHistory();
    }

private:
    BrowserToolbarQt* toolbar_;
    Browser* browser_;
    HistoryStackModel model_;

    // current navigation state
    NaviState state_;
    // whether the backward/forward button is active
    bool active_;
};

BackForwardButtonQt::BackForwardButtonQt(BrowserToolbarQt* toolbar, Browser* browser, BrowserWindowQt* window)
{
  impl_ = new BackForwardButtonQtImpl(toolbar, browser, window);
}

BackForwardButtonQt::~BackForwardButtonQt()
{
  delete impl_;
}

void BackForwardButtonQt::tap()
{
  impl_->tap();
}

void BackForwardButtonQt::tapAndHold()
{
  impl_->tapAndHold();
}

void BackForwardButtonQt::updateStatus()
{
  impl_->updateStatus();
}

void HistoryEntry::getThumbnailData(NavigationController *controller)
{
  history::TopSites* ts = controller->profile()->GetTopSites();
  if (ts) {
    scoped_refptr<RefCountedBytes> thumbnail_data;
    ts->GetPageThumbnail(entry_->url(), &thumbnail_data);
    if (thumbnail_data.get()) {
      std::vector <unsigned char> jpeg;
      std::copy(thumbnail_data->data.begin(),
                thumbnail_data->data.end(),
                std::back_inserter(jpeg));
      QImage image = QImage::fromData(jpeg.data(), jpeg.size());
      DLOG(INFO) << "image size ===== " << jpeg.size();
      hiProvider_.addImage(QString::number(index_), image);
    }
  }
}

void HistoryStackModel::openPage(const int index)
{
    back_forward_->openPage(entryList_[index]->entry());
    hide();
}

#include "moc_back_forward_button_qt.cc"
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: asiancfg.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:16:39 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SVX_ASIANCFG_HXX
#define _SVX_ASIANCFG_HXX

#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

namespace com{namespace sun{namespace star{
namespace lang{
    struct Locale;
}}}}
//-----------------------------------------------------------------------------
struct SvxAsianConfig_Impl;
class SVX_DLLPUBLIC SvxAsianConfig : public utl::ConfigItem
{
    SvxAsianConfig_Impl* pImpl;

public:
    SvxAsianConfig(sal_Bool bEnableNotify = sal_True);
    virtual ~SvxAsianConfig();

    void            Load();
    virtual void    Commit();
    virtual void    Notify( const com::sun::star::uno::Sequence<rtl::OUString>& aPropertyNames);

    sal_Bool    IsKerningWesternTextOnly() const;
    void        SetKerningWesternTextOnly(sal_Bool bSet);

    sal_Int16   GetCharDistanceCompression() const;
    void        SetCharDistanceCompression(sal_Int16 nSet);

    com::sun::star::uno::Sequence<com::sun::star::lang::Locale>
                GetStartEndCharLocales();

    sal_Bool    GetStartEndChars( const com::sun::star::lang::Locale& rLocale,
                                    rtl::OUString& rStartChars,
                                    rtl::OUString& rEndChars );
    void        SetStartEndChars( const com::sun::star::lang::Locale& rLocale,
                                    const rtl::OUString* pStartChars,
                                    const rtl::OUString* pEndChars );
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.3.1256); FILE MERGED 2008/04/01 15:49:10 thb 1.3.1256.3: #i85898# Stripping all external header guards 2008/04/01 12:46:17 thb 1.3.1256.2: #i85898# Stripping all external header guards 2008/03/31 14:17:53 rt 1.3.1256.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: asiancfg.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SVX_ASIANCFG_HXX
#define _SVX_ASIANCFG_HXX

#include <unotools/configitem.hxx>
#include <com/sun/star/uno/Sequence.h>
#include "svx/svxdllapi.h"

namespace com{namespace sun{namespace star{
namespace lang{
    struct Locale;
}}}}
//-----------------------------------------------------------------------------
struct SvxAsianConfig_Impl;
class SVX_DLLPUBLIC SvxAsianConfig : public utl::ConfigItem
{
    SvxAsianConfig_Impl* pImpl;

public:
    SvxAsianConfig(sal_Bool bEnableNotify = sal_True);
    virtual ~SvxAsianConfig();

    void            Load();
    virtual void    Commit();
    virtual void    Notify( const com::sun::star::uno::Sequence<rtl::OUString>& aPropertyNames);

    sal_Bool    IsKerningWesternTextOnly() const;
    void        SetKerningWesternTextOnly(sal_Bool bSet);

    sal_Int16   GetCharDistanceCompression() const;
    void        SetCharDistanceCompression(sal_Int16 nSet);

    com::sun::star::uno::Sequence<com::sun::star::lang::Locale>
                GetStartEndCharLocales();

    sal_Bool    GetStartEndChars( const com::sun::star::lang::Locale& rLocale,
                                    rtl::OUString& rStartChars,
                                    rtl::OUString& rEndChars );
    void        SetStartEndChars( const com::sun::star::lang::Locale& rLocale,
                                    const rtl::OUString* pStartChars,
                                    const rtl::OUString* pEndChars );
};

#endif

<|endoftext|>


<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stdio.h>
#include <locale>
#include <string>
#include <vector>

#include "base/at_exit.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/thread.h"
#include "base/threading/thread_local.h"
#include "chrome/test/chromedriver/logging.h"
#include "chrome/test/chromedriver/net/port_server.h"
#include "chrome/test/chromedriver/server/http_handler.h"
#include "chrome/test/chromedriver/version.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/server/http_server.h"
#include "net/server/http_server_request_info.h"
#include "net/server/http_server_response_info.h"
#include "net/socket/tcp_listen_socket.h"

namespace {

typedef base::Callback<
    void(const net::HttpServerRequestInfo&, const HttpResponseSenderFunc&)>
    HttpRequestHandlerFunc;

class HttpServer : public net::HttpServer::Delegate {
 public:
  explicit HttpServer(const HttpRequestHandlerFunc& handle_request_func)
      : handle_request_func_(handle_request_func),
        weak_factory_(this) {}

  virtual ~HttpServer() {}

  bool Start(int port) {
    server_ = new net::HttpServer(
        net::TCPListenSocketFactory("0.0.0.0", port), this);
    net::IPEndPoint address;
    return server_->GetLocalAddress(&address) == net::OK;
  }

  // Overridden from net::HttpServer::Delegate:
  virtual void OnHttpRequest(int connection_id,
                             const net::HttpServerRequestInfo& info) OVERRIDE {
    handle_request_func_.Run(
        info,
        base::Bind(&HttpServer::OnResponse,
                   weak_factory_.GetWeakPtr(),
                   connection_id));
  }
  virtual void OnWebSocketRequest(
      int connection_id,
      const net::HttpServerRequestInfo& info) OVERRIDE {}
  virtual void OnWebSocketMessage(int connection_id,
                                  const std::string& data) OVERRIDE {}
  virtual void OnClose(int connection_id) OVERRIDE {}

 private:
  void OnResponse(int connection_id,
                  scoped_ptr<net::HttpServerResponseInfo> response) {
    // Don't support keep-alive, since there's no way to detect if the
    // client is HTTP/1.0. In such cases, the client may hang waiting for
    // the connection to close (e.g., python 2.7 urllib).
    response->AddHeader("Connection", "close");
    server_->SendResponse(connection_id, *response);
    server_->Close(connection_id);
  }

  HttpRequestHandlerFunc handle_request_func_;
  scoped_refptr<net::HttpServer> server_;
  base::WeakPtrFactory<HttpServer> weak_factory_;  // Should be last.
};

void SendResponseOnCmdThread(
    const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner,
    const HttpResponseSenderFunc& send_response_on_io_func,
    scoped_ptr<net::HttpServerResponseInfo> response) {
  io_task_runner->PostTask(
      FROM_HERE, base::Bind(send_response_on_io_func, base::Passed(&response)));
}

void HandleRequestOnCmdThread(
    HttpHandler* handler,
    const net::HttpServerRequestInfo& request,
    const HttpResponseSenderFunc& send_response_func) {
  handler->Handle(request, send_response_func);
}

void HandleRequestOnIOThread(
    const scoped_refptr<base::SingleThreadTaskRunner>& cmd_task_runner,
    const HttpRequestHandlerFunc& handle_request_on_cmd_func,
    const net::HttpServerRequestInfo& request,
    const HttpResponseSenderFunc& send_response_func) {
  cmd_task_runner->PostTask(
      FROM_HERE,
      base::Bind(handle_request_on_cmd_func,
                 request,
                 base::Bind(&SendResponseOnCmdThread,
                            base::MessageLoopProxy::current(),
                            send_response_func)));
}

base::LazyInstance<base::ThreadLocalPointer<HttpServer> >
    lazy_tls_server = LAZY_INSTANCE_INITIALIZER;

void StopServerOnIOThread() {
  // Note, |server| may be NULL.
  HttpServer* server = lazy_tls_server.Pointer()->Get();
  lazy_tls_server.Pointer()->Set(NULL);
  delete server;
}

void StartServerOnIOThread(int port,
                           const HttpRequestHandlerFunc& handle_request_func) {
  scoped_ptr<HttpServer> temp_server(new HttpServer(handle_request_func));
  if (!temp_server->Start(port)) {
    printf("Port not available. Exiting...\n");
    exit(1);
  }
  lazy_tls_server.Pointer()->Set(temp_server.release());
}

void RunServer(int port,
               const std::string& url_base,
               int adb_port,
               scoped_ptr<PortServer> port_server) {
  base::Thread io_thread("ChromeDriver IO");
  CHECK(io_thread.StartWithOptions(
      base::Thread::Options(base::MessageLoop::TYPE_IO, 0)));

  base::MessageLoop cmd_loop;
  base::RunLoop cmd_run_loop;
  HttpHandler handler(cmd_run_loop.QuitClosure(),
                      io_thread.message_loop_proxy(),
                      url_base,
                      adb_port,
                      port_server.Pass());
  HttpRequestHandlerFunc handle_request_func =
      base::Bind(&HandleRequestOnCmdThread, &handler);

  io_thread.message_loop()
      ->PostTask(FROM_HERE,
                 base::Bind(&StartServerOnIOThread,
                            port,
                            base::Bind(&HandleRequestOnIOThread,
                                       cmd_loop.message_loop_proxy(),
                                       handle_request_func)));
  // Run the command loop. This loop is quit after the response for a shutdown
  // request is posted to the IO loop. After the command loop quits, a task
  // is posted to the IO loop to stop the server. Lastly, the IO thread is
  // destroyed, which waits until all pending tasks have been completed.
  // This assumes the response is sent synchronously as part of the IO task.
  cmd_run_loop.Run();
  io_thread.message_loop()
      ->PostTask(FROM_HERE, base::Bind(&StopServerOnIOThread));
}

}  // namespace

int main(int argc, char *argv[]) {
  CommandLine::Init(argc, argv);

  base::AtExitManager at_exit;
  CommandLine* cmd_line = CommandLine::ForCurrentProcess();

#if defined(OS_LINUX)
  // Select the locale from the environment by passing an empty string instead
  // of the default "C" locale. This is particularly needed for the keycode
  // conversion code to work.
  std::setlocale(LC_ALL, "");
#endif

  // Parse command line flags.
  int port = 9515;
  int adb_port = 5037;
  std::string url_base;
  scoped_ptr<PortServer> port_server;
  if (cmd_line->HasSwitch("h") || cmd_line->HasSwitch("help")) {
    std::string options;
    const char* kOptionAndDescriptions[] = {
        "port=PORT", "port to listen on",
        "adb-port=PORT", "adb server port",
        "log-path=FILE", "write server log to file instead of stderr, "
            "increases log level to INFO",
        "verbose", "log verbosely",
        "silent", "log nothing",
        "url-base", "base URL path prefix for commands, e.g. wd/url",
        "port-server", "address of server to contact for reserving a port",
    };
    for (size_t i = 0; i < arraysize(kOptionAndDescriptions) - 1; i += 2) {
      options += base::StringPrintf(
          "  --%-30s%s\n",
          kOptionAndDescriptions[i], kOptionAndDescriptions[i + 1]);
    }
    printf("Usage: %s [OPTIONS]\n\nOptions\n%s", argv[0], options.c_str());
    return 0;
  }
  if (cmd_line->HasSwitch("port")) {
    if (!base::StringToInt(cmd_line->GetSwitchValueASCII("port"), &port)) {
      printf("Invalid port. Exiting...\n");
      return 1;
    }
  }
  if (cmd_line->HasSwitch("adb-port")) {
    if (!base::StringToInt(cmd_line->GetSwitchValueASCII("adb-port"),
                           &adb_port)) {
      printf("Invalid adb-port. Exiting...\n");
      return 1;
    }
  }
  if (cmd_line->HasSwitch("port-server")) {
#if defined(OS_LINUX)
    std::string address = cmd_line->GetSwitchValueASCII("port-server");
    if (address.empty() || address[0] != '@') {
      printf("Invalid port-server. Exiting...\n");
      return 1;
    }
    std::string path;
    // First character of path is \0 to use Linux's abstract namespace.
    path.push_back(0);
    path += address.substr(1);
    port_server.reset(new PortServer(path));
#else
    printf("Warning: port-server not implemented for this platform.\n");
#endif
  }
  if (cmd_line->HasSwitch("url-base"))
    url_base = cmd_line->GetSwitchValueASCII("url-base");
  if (url_base.empty() || url_base[0] != '/')
    url_base = "/" + url_base;
  if (url_base[url_base.length() - 1] != '/')
    url_base = url_base + "/";
  if (!cmd_line->HasSwitch("silent")) {
    printf(
        "Starting ChromeDriver (v%s) on port %d\n", kChromeDriverVersion, port);
    fflush(stdout);
  }

  if (!InitLogging()) {
    printf("Unable to initialize logging. Exiting...\n");
    return 1;
  }
  RunServer(port, url_base, adb_port, port_server.Pass());
  return 0;
}
<commit_msg>Add a switch to print the version and exit<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stdio.h>
#include <locale>
#include <string>
#include <vector>

#include "base/at_exit.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/thread.h"
#include "base/threading/thread_local.h"
#include "chrome/test/chromedriver/logging.h"
#include "chrome/test/chromedriver/net/port_server.h"
#include "chrome/test/chromedriver/server/http_handler.h"
#include "chrome/test/chromedriver/version.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/server/http_server.h"
#include "net/server/http_server_request_info.h"
#include "net/server/http_server_response_info.h"
#include "net/socket/tcp_listen_socket.h"

namespace {

typedef base::Callback<
    void(const net::HttpServerRequestInfo&, const HttpResponseSenderFunc&)>
    HttpRequestHandlerFunc;

class HttpServer : public net::HttpServer::Delegate {
 public:
  explicit HttpServer(const HttpRequestHandlerFunc& handle_request_func)
      : handle_request_func_(handle_request_func),
        weak_factory_(this) {}

  virtual ~HttpServer() {}

  bool Start(int port) {
    server_ = new net::HttpServer(
        net::TCPListenSocketFactory("0.0.0.0", port), this);
    net::IPEndPoint address;
    return server_->GetLocalAddress(&address) == net::OK;
  }

  // Overridden from net::HttpServer::Delegate:
  virtual void OnHttpRequest(int connection_id,
                             const net::HttpServerRequestInfo& info) OVERRIDE {
    handle_request_func_.Run(
        info,
        base::Bind(&HttpServer::OnResponse,
                   weak_factory_.GetWeakPtr(),
                   connection_id));
  }
  virtual void OnWebSocketRequest(
      int connection_id,
      const net::HttpServerRequestInfo& info) OVERRIDE {}
  virtual void OnWebSocketMessage(int connection_id,
                                  const std::string& data) OVERRIDE {}
  virtual void OnClose(int connection_id) OVERRIDE {}

 private:
  void OnResponse(int connection_id,
                  scoped_ptr<net::HttpServerResponseInfo> response) {
    // Don't support keep-alive, since there's no way to detect if the
    // client is HTTP/1.0. In such cases, the client may hang waiting for
    // the connection to close (e.g., python 2.7 urllib).
    response->AddHeader("Connection", "close");
    server_->SendResponse(connection_id, *response);
    server_->Close(connection_id);
  }

  HttpRequestHandlerFunc handle_request_func_;
  scoped_refptr<net::HttpServer> server_;
  base::WeakPtrFactory<HttpServer> weak_factory_;  // Should be last.
};

void SendResponseOnCmdThread(
    const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner,
    const HttpResponseSenderFunc& send_response_on_io_func,
    scoped_ptr<net::HttpServerResponseInfo> response) {
  io_task_runner->PostTask(
      FROM_HERE, base::Bind(send_response_on_io_func, base::Passed(&response)));
}

void HandleRequestOnCmdThread(
    HttpHandler* handler,
    const net::HttpServerRequestInfo& request,
    const HttpResponseSenderFunc& send_response_func) {
  handler->Handle(request, send_response_func);
}

void HandleRequestOnIOThread(
    const scoped_refptr<base::SingleThreadTaskRunner>& cmd_task_runner,
    const HttpRequestHandlerFunc& handle_request_on_cmd_func,
    const net::HttpServerRequestInfo& request,
    const HttpResponseSenderFunc& send_response_func) {
  cmd_task_runner->PostTask(
      FROM_HERE,
      base::Bind(handle_request_on_cmd_func,
                 request,
                 base::Bind(&SendResponseOnCmdThread,
                            base::MessageLoopProxy::current(),
                            send_response_func)));
}

base::LazyInstance<base::ThreadLocalPointer<HttpServer> >
    lazy_tls_server = LAZY_INSTANCE_INITIALIZER;

void StopServerOnIOThread() {
  // Note, |server| may be NULL.
  HttpServer* server = lazy_tls_server.Pointer()->Get();
  lazy_tls_server.Pointer()->Set(NULL);
  delete server;
}

void StartServerOnIOThread(int port,
                           const HttpRequestHandlerFunc& handle_request_func) {
  scoped_ptr<HttpServer> temp_server(new HttpServer(handle_request_func));
  if (!temp_server->Start(port)) {
    printf("Port not available. Exiting...\n");
    exit(1);
  }
  lazy_tls_server.Pointer()->Set(temp_server.release());
}

void RunServer(int port,
               const std::string& url_base,
               int adb_port,
               scoped_ptr<PortServer> port_server) {
  base::Thread io_thread("ChromeDriver IO");
  CHECK(io_thread.StartWithOptions(
      base::Thread::Options(base::MessageLoop::TYPE_IO, 0)));

  base::MessageLoop cmd_loop;
  base::RunLoop cmd_run_loop;
  HttpHandler handler(cmd_run_loop.QuitClosure(),
                      io_thread.message_loop_proxy(),
                      url_base,
                      adb_port,
                      port_server.Pass());
  HttpRequestHandlerFunc handle_request_func =
      base::Bind(&HandleRequestOnCmdThread, &handler);

  io_thread.message_loop()
      ->PostTask(FROM_HERE,
                 base::Bind(&StartServerOnIOThread,
                            port,
                            base::Bind(&HandleRequestOnIOThread,
                                       cmd_loop.message_loop_proxy(),
                                       handle_request_func)));
  // Run the command loop. This loop is quit after the response for a shutdown
  // request is posted to the IO loop. After the command loop quits, a task
  // is posted to the IO loop to stop the server. Lastly, the IO thread is
  // destroyed, which waits until all pending tasks have been completed.
  // This assumes the response is sent synchronously as part of the IO task.
  cmd_run_loop.Run();
  io_thread.message_loop()
      ->PostTask(FROM_HERE, base::Bind(&StopServerOnIOThread));
}

}  // namespace

int main(int argc, char *argv[]) {
  CommandLine::Init(argc, argv);

  base::AtExitManager at_exit;
  CommandLine* cmd_line = CommandLine::ForCurrentProcess();

#if defined(OS_LINUX)
  // Select the locale from the environment by passing an empty string instead
  // of the default "C" locale. This is particularly needed for the keycode
  // conversion code to work.
  std::setlocale(LC_ALL, "");
#endif

  // Parse command line flags.
  int port = 9515;
  int adb_port = 5037;
  std::string url_base;
  scoped_ptr<PortServer> port_server;
  if (cmd_line->HasSwitch("h") || cmd_line->HasSwitch("help")) {
    std::string options;
    const char* kOptionAndDescriptions[] = {
        "port=PORT", "port to listen on",
        "adb-port=PORT", "adb server port",
        "log-path=FILE", "write server log to file instead of stderr, "
            "increases log level to INFO",
        "verbose", "log verbosely",
        "version", "print the version number and exit",
        "silent", "log nothing",
        "url-base", "base URL path prefix for commands, e.g. wd/url",
        "port-server", "address of server to contact for reserving a port",
    };
    for (size_t i = 0; i < arraysize(kOptionAndDescriptions) - 1; i += 2) {
      options += base::StringPrintf(
          "  --%-30s%s\n",
          kOptionAndDescriptions[i], kOptionAndDescriptions[i + 1]);
    }
    printf("Usage: %s [OPTIONS]\n\nOptions\n%s", argv[0], options.c_str());
    return 0;
  }
  if (cmd_line->HasSwitch("v") || cmd_line->HasSwitch("version")) {
    printf("ChromeDriver %s\n", kChromeDriverVersion);
    return 0;
  }
  if (cmd_line->HasSwitch("port")) {
    if (!base::StringToInt(cmd_line->GetSwitchValueASCII("port"), &port)) {
      printf("Invalid port. Exiting...\n");
      return 1;
    }
  }
  if (cmd_line->HasSwitch("adb-port")) {
    if (!base::StringToInt(cmd_line->GetSwitchValueASCII("adb-port"),
                           &adb_port)) {
      printf("Invalid adb-port. Exiting...\n");
      return 1;
    }
  }
  if (cmd_line->HasSwitch("port-server")) {
#if defined(OS_LINUX)
    std::string address = cmd_line->GetSwitchValueASCII("port-server");
    if (address.empty() || address[0] != '@') {
      printf("Invalid port-server. Exiting...\n");
      return 1;
    }
    std::string path;
    // First character of path is \0 to use Linux's abstract namespace.
    path.push_back(0);
    path += address.substr(1);
    port_server.reset(new PortServer(path));
#else
    printf("Warning: port-server not implemented for this platform.\n");
#endif
  }
  if (cmd_line->HasSwitch("url-base"))
    url_base = cmd_line->GetSwitchValueASCII("url-base");
  if (url_base.empty() || url_base[0] != '/')
    url_base = "/" + url_base;
  if (url_base[url_base.length() - 1] != '/')
    url_base = url_base + "/";
  if (!cmd_line->HasSwitch("silent")) {
    printf(
        "Starting ChromeDriver (v%s) on port %d\n", kChromeDriverVersion, port);
    fflush(stdout);
  }

  if (!InitLogging()) {
    printf("Unable to initialize logging. Exiting...\n");
    return 1;
  }
  RunServer(port, url_base, adb_port, port_server.Pass());
  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pfiledlg.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 18:17:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SVX_PFILEDLG_HXX
#define _SVX_PFILEDLG_HXX

// include ---------------------------------------------------------------

#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

/*************************************************************************
|*
|* Filedialog to insert Plugin-Fileformats
|*
\************************************************************************/

class SVX_DLLPUBLIC SvxPluginFileDlg
{
private:
    sfx2::FileDialogHelper          maFileDlg;

public:
    // with nKind = SID_INSERT_SOUND    or
    //      nKind = SID_INSERT_VIDEO
    SvxPluginFileDlg (Window *pParent, USHORT nKind );
    ~SvxPluginFileDlg ();

    ErrCode                  Execute();
    String                   GetPath() const;

    static BOOL IsAvailable (USHORT nKind);

    // setting HelpId and/or context of FileDialogHelper
    void                    SetDialogHelpId( const sal_Int32 nHelpId );
    void                    SetContext( sfx2::FileDialogHelper::Context eNewContext );
};

#endif // _SVX_PFILEDLG_HXX

<commit_msg>INTEGRATION: CWS sb59 (1.5.486); FILE MERGED 2006/08/18 12:02:42 sb 1.5.486.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: pfiledlg.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 11:47:45 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SVX_PFILEDLG_HXX
#define _SVX_PFILEDLG_HXX

// include ---------------------------------------------------------------

#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

/*************************************************************************
|*
|* Filedialog to insert Plugin-Fileformats
|*
\************************************************************************/

class SVX_DLLPUBLIC SvxPluginFileDlg
{
private:
    sfx2::FileDialogHelper          maFileDlg;

public:
    // with nKind = SID_INSERT_SOUND    or
    //      nKind = SID_INSERT_VIDEO
    SvxPluginFileDlg (Window *pParent, USHORT nKind );
    ~SvxPluginFileDlg ();

    ErrCode                  Execute();
    String                   GetPath() const;

    static bool IsAvailable (USHORT nKind);

    // setting HelpId and/or context of FileDialogHelper
    void                    SetDialogHelpId( const sal_Int32 nHelpId );
    void                    SetContext( sfx2::FileDialogHelper::Context eNewContext );
};

#endif // _SVX_PFILEDLG_HXX

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: svdshort.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-12 14:28:26 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#error svdshort wird nicht mehr verwendet!

#ifndef _SVDSHORT_HXX
#define _SVDSHORT_HXX

////////////////////////////////////////////////////////////////////////////////////////////////////

#ifdef Weg_Mit_Den_Doofen_Abkuerzungen
                                           // Statistik - Stand 02-03-1995
                                           //   Haeufigkeit  Ersparnis
#define SdrObjSurrogate              SdrSU
#define SdrHelpLineKind              SdrFLK /* HL ist schon besetzt */
#define SdrHelpLineList              SdrFLL /* HL ist schon besetzt */
#define SdrHelpLine                  SdrFL  /* HL ist schon besetzt */
//#define SdrMasterPageDescriptorList  SdrMPL
//#define SdrMasterPageDescriptor      SdrMP
#define SdrObjTransformInfoRec       SdrTI
#define SdrDragCrook                 SdrDC
#define SdrDragMirror                SdrDI
#define SdrDragMovHdl                SdrDH
#define SdrDragResize                SdrDZ
#define SdrDragRotate                SdrDR
#define SdrDragShear                 SdrDE
#define SdrDragMove                  SdrDM
#define SdrCreateCmd                 SdrCC
#define SdrUndoAttrObj               SdrAU
#define SdrObjKind                   SdrOK
#define SdrUndoGroup                 SdrUG
#define SdrUndoAction                SdrUA
#define SdrAttrObj                   SdrAO
#define SdrGrafObj                   SdrGO
#define SdrMarkList                  SdrML
#define SdrHdlList                   SdrHL
#define SdrLayerAdmin                SdrLA
//#define SdrObjEditRec                SdrER
#define SdrObjIOHeader               SdrOH
#define SdrObjUserCall               SdrUC
#define SdrObjUnknown                SdrUO
#define SdrExchangeView              SdrXV
#define SdrCreateView                SdrCV
#define SdrOle2Obj                   SdrOO
#define SdrObjGeoData                SdrGD
#define SdrDragView                  SdrDV
#define SdrSnapView                  SdrSV
#define SdrObjList                   SdrOL
#define SdrEdgeObj                   SdrEO
#define SdrCircObj                   SdrCO
#define SdrObjGroup                  SdrOG
#define SdrPage                      SdrPg
#define SdrObjEditView               SdrOV
#define SdrModel                     SdrMD
#define ExtOutputDevice              SdrXO
#define SdrEditView                  SdrEV
#define SdrPaintView                 SdrNV
#define SdrPolyObj                   SdrPO
#define SdrRectObj                   SdrRO
#define SdrTextObj                   SdrTO
#define SdrMarkView                  SdrMV
#define SdrPathObj                   SdrBO
#define SdrPageView                  SdrPV
#define SdrDragStat                  SdrDS
#define SdrVirtObj                   SdrVO
#define SdrObject                    SdrO

#endif

////////////////////////////////////////////////////////////////////////////////////////////////////

#endif //_SVDSHORT_HXX

<commit_msg>INTEGRATION: CWS aw019 (1.2.138); FILE MERGED 2004/10/06 16:17:50 aw 1.2.138.2: #i34831# 2004/09/28 15:52:17 aw 1.2.138.1: #i11190#<commit_after>/*************************************************************************
 *
 *  $RCSfile: svdshort.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: pjunck $ $Date: 2004-11-03 10:23:46 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#error svdshort wird nicht mehr verwendet!

#ifndef _SVDSHORT_HXX
#define _SVDSHORT_HXX

////////////////////////////////////////////////////////////////////////////////////////////////////

#ifdef Weg_Mit_Den_Doofen_Abkuerzungen
                                           // Statistik - Stand 02-03-1995
                                           //   Haeufigkeit  Ersparnis
//BFS01#define SdrObjSurrogate              SdrSU
#define SdrHelpLineKind              SdrFLK /* HL ist schon besetzt */
#define SdrHelpLineList              SdrFLL /* HL ist schon besetzt */
#define SdrHelpLine                  SdrFL  /* HL ist schon besetzt */
//#define SdrMasterPageDescriptorList  SdrMPL
//#define SdrMasterPageDescriptor      SdrMP
#define SdrObjTransformInfoRec       SdrTI
#define SdrDragCrook                 SdrDC
#define SdrDragMirror                SdrDI
#define SdrDragMovHdl                SdrDH
#define SdrDragResize                SdrDZ
#define SdrDragRotate                SdrDR
#define SdrDragShear                 SdrDE
#define SdrDragMove                  SdrDM
#define SdrCreateCmd                 SdrCC
#define SdrUndoAttrObj               SdrAU
#define SdrObjKind                   SdrOK
#define SdrUndoGroup                 SdrUG
#define SdrUndoAction                SdrUA
#define SdrAttrObj                   SdrAO
#define SdrGrafObj                   SdrGO
#define SdrMarkList                  SdrML
#define SdrHdlList                   SdrHL
#define SdrLayerAdmin                SdrLA
//#define SdrObjEditRec                SdrER
//BFS01#define SdrObjIOHeader               SdrOH
#define SdrObjUserCall               SdrUC
#define SdrObjUnknown                SdrUO
#define SdrExchangeView              SdrXV
#define SdrCreateView                SdrCV
#define SdrOle2Obj                   SdrOO
#define SdrObjGeoData                SdrGD
#define SdrDragView                  SdrDV
#define SdrSnapView                  SdrSV
#define SdrObjList                   SdrOL
#define SdrEdgeObj                   SdrEO
#define SdrCircObj                   SdrCO
#define SdrObjGroup                  SdrOG
#define SdrPage                      SdrPg
#define SdrObjEditView               SdrOV
#define SdrModel                     SdrMD
#define XOutputDevice              SdrXO
#define SdrEditView                  SdrEV
#define SdrPaintView                 SdrNV
#define SdrPolyObj                   SdrPO
#define SdrRectObj                   SdrRO
#define SdrTextObj                   SdrTO
#define SdrMarkView                  SdrMV
#define SdrPathObj                   SdrBO
#define SdrPageView                  SdrPV
#define SdrDragStat                  SdrDS
#define SdrVirtObj                   SdrVO
#define SdrObject                    SdrO

#endif

////////////////////////////////////////////////////////////////////////////////////////////////////

#endif //_SVDSHORT_HXX

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xmleohlp.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLEOHLP_HXX
#define _XMLEOHLP_HXX

#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase2.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#include <sot/storage.hxx>
#include <map>

#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEMBEDDEDOBJECTRESOLVER_HPP_
#include <com/sun/star/document/XEmbeddedObjectResolver.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

// -----------------------------
// - SvXMLEmbeddedObjectHelper -
// -----------------------------

enum SvXMLEmbeddedObjectHelperMode
{
    EMBEDDEDOBJECTHELPER_MODE_READ = 0,
    EMBEDDEDOBJECTHELPER_MODE_WRITE = 1
};

// -----------------------------
// - SvXMLEmbeddedObjectHelper -
// -----------------------------

class SfxObjectShell;
class SvGlobalName;
struct OUStringLess;
class OutputStorageWrapper_Impl;

class SVX_DLLPUBLIC SvXMLEmbeddedObjectHelper : public ::cppu::WeakComponentImplHelper2<
    ::com::sun::star::document::XEmbeddedObjectResolver,
    ::com::sun::star::container::XNameAccess >
{
    typedef ::std::map< ::rtl::OUString, OutputStorageWrapper_Impl*,
                         OUStringLess > SvXMLEmbeddedObjectHelper_Impl;
private:

    ::osl::Mutex                maMutex;

    const ::rtl::OUString       maReplacementGraphicsContainerStorageName;
    const ::rtl::OUString       maReplacementGraphicsContainerStorageName60;
    ::rtl::OUString             maCurContainerStorageName;

    com::sun::star::uno::Reference < com::sun::star::embed::XStorage > mxRootStorage;  // package
    SfxObjectShell*             mpDocPersist;
    com::sun::star::uno::Reference < com::sun::star::embed::XStorage > mxContainerStorage; // container sub package for
    com::sun::star::uno::Reference < com::sun::star::embed::XStorage > mxTempStorage;  // package
                                                // objects
    SvXMLEmbeddedObjectHelperMode       meCreateMode;
    SvXMLEmbeddedObjectHelper_Impl      *mpStreamMap;

    SVX_DLLPRIVATE sal_Bool                 ImplGetStorageNames(
                                    const ::rtl::OUString& rURLStr,
                                    ::rtl::OUString& rContainerStorageName,
                                    ::rtl::OUString& rObjectStorageName,
                                    sal_Bool bInternalToExternal,
                                       sal_Bool *pGraphicRepl=0 ) const;

    SVX_DLLPRIVATE com::sun::star::uno::Reference < com::sun::star::embed::XStorage > ImplGetContainerStorage(
                                    const ::rtl::OUString& rStorageName );

    SVX_DLLPRIVATE String                      ImplGetUniqueName( SfxObjectShell*, const sal_Char* p ) const;
    SVX_DLLPRIVATE sal_Bool                 ImplReadObject(
                                    const ::rtl::OUString& rContainerStorageName,
                                    ::rtl::OUString& rObjName,
                                    const SvGlobalName *pClassId,
                                    SvStream* pTemp );

    SVX_DLLPRIVATE ::rtl::OUString              ImplInsertEmbeddedObjectURL(
                                    const ::rtl::OUString& rURLStr );

protected:

                                SvXMLEmbeddedObjectHelper();
                                ~SvXMLEmbeddedObjectHelper();
    void                        Init( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >&,
                                      SfxObjectShell& rDocPersist,
                                      SvXMLEmbeddedObjectHelperMode eCreateMode );

    virtual void SAL_CALL       disposing();

public:
                                SvXMLEmbeddedObjectHelper(
                                    SfxObjectShell& rDocPersist,
                                    SvXMLEmbeddedObjectHelperMode eCreateMode );

    static SvXMLEmbeddedObjectHelper*   Create(
                                    const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >&,
                                    SfxObjectShell& rDocPersist,
                                    SvXMLEmbeddedObjectHelperMode eCreateMode,
                                    sal_Bool bDirect = sal_True );
    static SvXMLEmbeddedObjectHelper*   Create(
                                    SfxObjectShell& rDocPersist,
                                    SvXMLEmbeddedObjectHelperMode eCreateMode );
    static void                 Destroy( SvXMLEmbeddedObjectHelper* pSvXMLEmbeddedObjectHelper );

    void                        Flush();

    // XEmbeddedObjectResolver
    virtual ::rtl::OUString SAL_CALL resolveEmbeddedObjectURL( const ::rtl::OUString& aURL ) throw(::com::sun::star::uno::RuntimeException);

    // XNameAccess
    virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException);

    // XNameAccess
    virtual ::com::sun::star::uno::Type SAL_CALL getElementType(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasElements(  ) throw (::com::sun::star::uno::RuntimeException);
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.10.420); FILE MERGED 2005/09/05 14:17:18 rt 1.10.420.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmleohlp.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 19:49:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _XMLEOHLP_HXX
#define _XMLEOHLP_HXX

#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase2.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#include <sot/storage.hxx>
#include <map>

#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEMBEDDEDOBJECTRESOLVER_HPP_
#include <com/sun/star/document/XEmbeddedObjectResolver.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

// -----------------------------
// - SvXMLEmbeddedObjectHelper -
// -----------------------------

enum SvXMLEmbeddedObjectHelperMode
{
    EMBEDDEDOBJECTHELPER_MODE_READ = 0,
    EMBEDDEDOBJECTHELPER_MODE_WRITE = 1
};

// -----------------------------
// - SvXMLEmbeddedObjectHelper -
// -----------------------------

class SfxObjectShell;
class SvGlobalName;
struct OUStringLess;
class OutputStorageWrapper_Impl;

class SVX_DLLPUBLIC SvXMLEmbeddedObjectHelper : public ::cppu::WeakComponentImplHelper2<
    ::com::sun::star::document::XEmbeddedObjectResolver,
    ::com::sun::star::container::XNameAccess >
{
    typedef ::std::map< ::rtl::OUString, OutputStorageWrapper_Impl*,
                         OUStringLess > SvXMLEmbeddedObjectHelper_Impl;
private:

    ::osl::Mutex                maMutex;

    const ::rtl::OUString       maReplacementGraphicsContainerStorageName;
    const ::rtl::OUString       maReplacementGraphicsContainerStorageName60;
    ::rtl::OUString             maCurContainerStorageName;

    com::sun::star::uno::Reference < com::sun::star::embed::XStorage > mxRootStorage;  // package
    SfxObjectShell*             mpDocPersist;
    com::sun::star::uno::Reference < com::sun::star::embed::XStorage > mxContainerStorage; // container sub package for
    com::sun::star::uno::Reference < com::sun::star::embed::XStorage > mxTempStorage;  // package
                                                // objects
    SvXMLEmbeddedObjectHelperMode       meCreateMode;
    SvXMLEmbeddedObjectHelper_Impl      *mpStreamMap;

    SVX_DLLPRIVATE sal_Bool                 ImplGetStorageNames(
                                    const ::rtl::OUString& rURLStr,
                                    ::rtl::OUString& rContainerStorageName,
                                    ::rtl::OUString& rObjectStorageName,
                                    sal_Bool bInternalToExternal,
                                       sal_Bool *pGraphicRepl=0 ) const;

    SVX_DLLPRIVATE com::sun::star::uno::Reference < com::sun::star::embed::XStorage > ImplGetContainerStorage(
                                    const ::rtl::OUString& rStorageName );

    SVX_DLLPRIVATE String                      ImplGetUniqueName( SfxObjectShell*, const sal_Char* p ) const;
    SVX_DLLPRIVATE sal_Bool                 ImplReadObject(
                                    const ::rtl::OUString& rContainerStorageName,
                                    ::rtl::OUString& rObjName,
                                    const SvGlobalName *pClassId,
                                    SvStream* pTemp );

    SVX_DLLPRIVATE ::rtl::OUString              ImplInsertEmbeddedObjectURL(
                                    const ::rtl::OUString& rURLStr );

protected:

                                SvXMLEmbeddedObjectHelper();
                                ~SvXMLEmbeddedObjectHelper();
    void                        Init( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >&,
                                      SfxObjectShell& rDocPersist,
                                      SvXMLEmbeddedObjectHelperMode eCreateMode );

    virtual void SAL_CALL       disposing();

public:
                                SvXMLEmbeddedObjectHelper(
                                    SfxObjectShell& rDocPersist,
                                    SvXMLEmbeddedObjectHelperMode eCreateMode );

    static SvXMLEmbeddedObjectHelper*   Create(
                                    const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >&,
                                    SfxObjectShell& rDocPersist,
                                    SvXMLEmbeddedObjectHelperMode eCreateMode,
                                    sal_Bool bDirect = sal_True );
    static SvXMLEmbeddedObjectHelper*   Create(
                                    SfxObjectShell& rDocPersist,
                                    SvXMLEmbeddedObjectHelperMode eCreateMode );
    static void                 Destroy( SvXMLEmbeddedObjectHelper* pSvXMLEmbeddedObjectHelper );

    void                        Flush();

    // XEmbeddedObjectResolver
    virtual ::rtl::OUString SAL_CALL resolveEmbeddedObjectURL( const ::rtl::OUString& aURL ) throw(::com::sun::star::uno::RuntimeException);

    // XNameAccess
    virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException);

    // XNameAccess
    virtual ::com::sun::star::uno::Type SAL_CALL getElementType(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasElements(  ) throw (::com::sun::star::uno::RuntimeException);
};

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SwNodeNum.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2006-05-05 09:12:46 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SW_NODE_NUM_HXX
#define _SW_NODE_NUM_HXX

#include <SwNumberTree.hxx>

class SwTxtNode;
struct SwPosition;
class SwNumRule;
class SwNumFmt;

class SW_DLLPUBLIC SwNodeNum : public SwNumberTreeNode
{
    SwTxtNode * mpTxtNode;
    SwNumRule * mpNumRule;

    tSwNumTreeNumber mnStart;
    bool mbRestart;

    // --> OD 2006-03-07 #131436#
    static void _UnregisterMeAndChildrenDueToRootDelete( SwNodeNum& rNodeNum );
    // <--
protected:
    void SetTxtNode(SwTxtNode * pTxtNode);
    SwTxtNode * GetTxtNode() const;

    void SetNumRule(SwNumRule * pRule);
    SwNumRule * GetNumRule() const;

    // --> OD 2006-04-26 #i64010#
    virtual bool HasCountedChildren() const;
    virtual bool IsCountedForNumbering() const;
    // <--

public:
    SwNodeNum();
    SwNodeNum(const SwNodeNum & rNodeNum);
    virtual ~SwNodeNum();

    virtual SwNumberTreeNode * Create() const;

    virtual SwNumberTreeNode * Copy() const;

    virtual void RemoveChild(SwNumberTreeNode * pChild);

    virtual bool IsNotifiable() const;

    virtual bool IsContinuous() const;

    virtual bool IsCounted() const;

    virtual bool IsCountPhantoms() const;

    virtual void NotifyNode();

    virtual bool LessThan(const SwNumberTreeNode & rNode) const;

    void SetRestart(bool bRestart);

    virtual bool IsRestart() const;

    void SetStart(tSwNumTreeNumber nStart);

    virtual tSwNumTreeNumber GetStart() const;

    String ToString() const;

    void SetLevel(unsigned int nLevel);

    SwPosition GetPosition() const;

    const SwNumFmt * GetNumFmt() const;

    friend class SwTxtNode;
    friend class SwNumRule;

    // --> OD 2005-11-16 #i57919# - direct access on <mnStart>, needed for HTML export
    inline const tSwNumTreeNumber GetStartValue() const
    {
        return mnStart;
    }
    // <--

    // --> OD 2006-03-07 #131436#
    // The number tree root node is deleted, when the corresponding numbering
    // rule is deleted. In this situation the number tree should be empty -
    // still registered text nodes aren't allowed. But it is possible, that
    // text nodes of the undo nodes array are still registered. These will be
    // unregistered.
    // Text nodes of the document nodes array aren't allowed to be registered
    // in this situation - this will be asserted.
    static void HandleNumberTreeRootNodeDelete( SwNodeNum& rNodeNum );
    // <--
};

#endif // _SW_NODE_NUM_HXX
<commit_msg>INTEGRATION: CWS swautomatic01 (1.5.84); FILE MERGED 2006/09/11 12:04:46 ama 1.5.84.1: #i65476#: Automatic Styles, numbering<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SwNodeNum.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2006-12-01 15:31:08 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SW_NODE_NUM_HXX
#define _SW_NODE_NUM_HXX

#include <SwNumberTree.hxx>

class SwTxtNode;
struct SwPosition;
class SwNumRule;
class SwNumFmt;

class SW_DLLPUBLIC SwNodeNum : public SwNumberTreeNode
{
    SwTxtNode * mpTxtNode;
    SwNumRule * mpNumRule;

    tSwNumTreeNumber mnStart;
    bool mbRestart;

    // --> OD 2006-03-07 #131436#
    static void _UnregisterMeAndChildrenDueToRootDelete( SwNodeNum& rNodeNum );
    // <--
protected:
    void SetTxtNode(SwTxtNode * pTxtNode);
    SwTxtNode * GetTxtNode() const;

    void SetNumRule(SwNumRule * pRule);
    SwNumRule * GetNumRule() const;

    // --> OD 2006-04-26 #i64010#
    virtual bool HasCountedChildren() const;
    virtual bool IsCountedForNumbering() const;
    // <--

public:
    SwNodeNum();
    SwNodeNum(const SwNodeNum & rNodeNum);
    virtual ~SwNodeNum();

    virtual SwNumberTreeNode * Create() const;

    virtual SwNumberTreeNode * Copy() const;

    virtual void RemoveChild(SwNumberTreeNode * pChild);

    virtual bool IsNotifiable() const;

    virtual bool IsNotificationEnabled() const;

    virtual bool IsContinuous() const;

    virtual bool IsCounted() const;

    virtual bool IsCountPhantoms() const;

    virtual void NotifyNode();

    virtual bool LessThan(const SwNumberTreeNode & rNode) const;

    void SetRestart(bool bRestart);

    virtual bool IsRestart() const;

    void SetStart(tSwNumTreeNumber nStart);

    virtual tSwNumTreeNumber GetStart() const;

    String ToString() const;

    void SetLevel(unsigned int nLevel);

    SwPosition GetPosition() const;

    const SwNumFmt * GetNumFmt() const;

    friend class SwTxtNode;
    friend class SwNumRule;

    // --> OD 2005-11-16 #i57919# - direct access on <mnStart>, needed for HTML export
    inline const tSwNumTreeNumber GetStartValue() const
    {
        return mnStart;
    }
    // <--

    // --> OD 2006-03-07 #131436#
    // The number tree root node is deleted, when the corresponding numbering
    // rule is deleted. In this situation the number tree should be empty -
    // still registered text nodes aren't allowed. But it is possible, that
    // text nodes of the undo nodes array are still registered. These will be
    // unregistered.
    // Text nodes of the document nodes array aren't allowed to be registered
    // in this situation - this will be asserted.
    static void HandleNumberTreeRootNodeDelete( SwNodeNum& rNodeNum );
    // <--
};

#endif // _SW_NODE_NUM_HXX
<|endoftext|>