<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Denis Mingulov.
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "classviewnavigationwidget.h"
#include "ui_classviewnavigationwidget.h"
#include "classviewtreeitemmodel.h"
#include "classviewmanager.h"
#include "classviewsymbollocation.h"
#include "classviewsymbolinformation.h"
#include "classviewutils.h"
#include "classviewconstants.h"

#include <utils/qtcassert.h>

#include <QtCore/QDebug>
#include <QtCore/QPointer>

enum { debug = false };

namespace ClassView {
namespace Internal {

///////////////////////////////// NavigationWidgetPrivate //////////////////////////////////

/*!
   \struct NavigationWidgetPrivate
   \brief Internal data structures / methods for NavigationWidget
 */

class NavigationWidgetPrivate
{
public:
    NavigationWidgetPrivate() : ui(0) {}

    //! Ui generated by Designer
    Ui::NavigationWidget *ui;

    //! current tree model
    QPointer<TreeItemModel> treeModel;

    //! full projects mode
    QPointer<QToolButton> fullProjectsModeButton;
};

///////////////////////////////// NavigationWidget //////////////////////////////////

NavigationWidget::NavigationWidget(QWidget *parent) :
    QWidget(parent),
    d(new NavigationWidgetPrivate())
{
    d->ui = new Ui::NavigationWidget;
    d->ui->setupUi(this);

    // tree model
    d->treeModel = new TreeItemModel(this);
    d->ui->treeView->setModel(d->treeModel);

    // connect signal/slots
    // selected item
    connect(d->ui->treeView, SIGNAL(activated(QModelIndex)), SLOT(onItemActivated(QModelIndex)));

    // connections to the manager
    Manager *manager = Manager::instance();

    connect(this, SIGNAL(visibilityChanged(bool)),
            manager, SLOT(onWidgetVisibilityIsChanged(bool)));

    connect(this, SIGNAL(requestGotoLocation(QString,int,int)),
            manager, SLOT(gotoLocation(QString,int,int)));

    connect(this, SIGNAL(requestGotoLocations(QList<QVariant>)),
            manager, SLOT(gotoLocations(QList<QVariant>)));

    connect(manager, SIGNAL(treeDataUpdate(QSharedPointer<QStandardItem>)),
            this, SLOT(onDataUpdate(QSharedPointer<QStandardItem>)));

    connect(this, SIGNAL(requestTreeDataUpdate()),
            manager, SLOT(onRequestTreeDataUpdate()));
}

NavigationWidget::~NavigationWidget()
{
    delete d->fullProjectsModeButton;
    delete d->ui;
    delete d;
}

void NavigationWidget::hideEvent(QHideEvent *event)
{
    emit visibilityChanged(false);
    QWidget::hideEvent(event);
}

void NavigationWidget::showEvent(QShowEvent *event)
{
    emit visibilityChanged(true);

    // request to update to the current state - to be sure
    emit requestTreeDataUpdate();

    QWidget::showEvent(event);
}

QList<QToolButton *> NavigationWidget::createToolButtons()
{
    QList<QToolButton *> list;

    // full projects mode
    if (!d->fullProjectsModeButton) {
        // create a button
        d->fullProjectsModeButton = new QToolButton();
        d->fullProjectsModeButton->setIcon(
                QIcon(QLatin1String(":/classview/images/hierarchicalmode.png")));
        d->fullProjectsModeButton->setCheckable(true);
        d->fullProjectsModeButton->setToolTip(tr("Show Subprojects"));

        // by default - not a flat mode
        setFlatMode(false);

        // connections
        connect(d->fullProjectsModeButton, SIGNAL(toggled(bool)),
                this, SLOT(onFullProjectsModeToggled(bool)));
    }

    list << d->fullProjectsModeButton;

    return list;
}

bool NavigationWidget::flatMode() const
{
    QTC_ASSERT(d->fullProjectsModeButton, return false);

    // button is 'full projects mode' - so it has to be inverted
    return !d->fullProjectsModeButton->isChecked();
}

void NavigationWidget::setFlatMode(bool flatMode)
{
    QTC_ASSERT(d->fullProjectsModeButton, return);

    // button is 'full projects mode' - so it has to be inverted
    d->fullProjectsModeButton->setChecked(!flatMode);
}

void NavigationWidget::onFullProjectsModeToggled(bool state)
{
    // button is 'full projects mode' - so it has to be inverted
    Manager::instance()->setFlatMode(!state);
}

void NavigationWidget::onItemActivated(const QModelIndex &index)
{
    if (!index.isValid())
        return;

    QList<QVariant> list = d->treeModel->data(index, Constants::SymbolLocationsRole).toList();

    emit requestGotoLocations(list);
}

void NavigationWidget::onDataUpdate(QSharedPointer<QStandardItem> result)
{
    if (result.isNull())
        return;

    // if this is 1st call
    bool expandRootItems = false;
    if (d->treeModel->invisibleRootItem()->rowCount() == 0)
        expandRootItems = true;

    QTime timer;
    if (debug)
        timer.start();
    // update is received. root item must be updated - and received information
    // might be just a root - if a lazy data population is enabled.
    // so expanded items must be parsed and 'fetched'

    fetchExpandedItems(result.data(), d->treeModel->invisibleRootItem());

    d->treeModel->moveRootToTarget(result.data());

    // expand top level projects
    QModelIndex sessionIndex;

    for (int i = 0; i < d->treeModel->rowCount(sessionIndex); ++i)
        d->ui->treeView->expand(d->treeModel->index(i, 0, sessionIndex));

    if (debug)
        qDebug() << "Class View:" << QDateTime::currentDateTime().toString()
            << "TreeView is updated in" << timer.elapsed() << "msecs";
}

void NavigationWidget::fetchExpandedItems(QStandardItem *item, const QStandardItem *target) const
{
    if (!item || !target)
        return;

    const QModelIndex &parent = d->treeModel->indexFromItem(target);
    if (d->ui->treeView->isExpanded(parent))
        Manager::instance()->fetchMore(item, true);

    int itemIndex = 0;
    int targetIndex = 0;
    int itemRows = item->rowCount();
    int targetRows = target->rowCount();

    while (itemIndex < itemRows && targetIndex < targetRows) {
        QStandardItem *itemChild = item->child(itemIndex);
        const QStandardItem *targetChild = target->child(targetIndex);

        const SymbolInformation &itemInf = Utils::symbolInformationFromItem(itemChild);
        const SymbolInformation &targetInf = Utils::symbolInformationFromItem(targetChild);

        if (itemInf < targetInf) {
            ++itemIndex;
        } else if (itemInf == targetInf) {
            fetchExpandedItems(itemChild, targetChild);
            ++itemIndex;
            ++targetIndex;
        } else {
            ++targetIndex;
        }
    }
}

} // namespace Internal
} // namespace ClassView
<commit_msg>Classview: Remove dead code<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Denis Mingulov.
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "classviewnavigationwidget.h"
#include "ui_classviewnavigationwidget.h"
#include "classviewtreeitemmodel.h"
#include "classviewmanager.h"
#include "classviewsymbollocation.h"
#include "classviewsymbolinformation.h"
#include "classviewutils.h"
#include "classviewconstants.h"

#include <utils/qtcassert.h>

#include <QtCore/QDebug>
#include <QtCore/QPointer>

enum { debug = false };

namespace ClassView {
namespace Internal {

///////////////////////////////// NavigationWidgetPrivate //////////////////////////////////

/*!
   \struct NavigationWidgetPrivate
   \brief Internal data structures / methods for NavigationWidget
 */

class NavigationWidgetPrivate
{
public:
    NavigationWidgetPrivate() : ui(0) {}

    //! Ui generated by Designer
    Ui::NavigationWidget *ui;

    //! current tree model
    QPointer<TreeItemModel> treeModel;

    //! full projects mode
    QPointer<QToolButton> fullProjectsModeButton;
};

///////////////////////////////// NavigationWidget //////////////////////////////////

NavigationWidget::NavigationWidget(QWidget *parent) :
    QWidget(parent),
    d(new NavigationWidgetPrivate())
{
    d->ui = new Ui::NavigationWidget;
    d->ui->setupUi(this);

    // tree model
    d->treeModel = new TreeItemModel(this);
    d->ui->treeView->setModel(d->treeModel);

    // connect signal/slots
    // selected item
    connect(d->ui->treeView, SIGNAL(activated(QModelIndex)), SLOT(onItemActivated(QModelIndex)));

    // connections to the manager
    Manager *manager = Manager::instance();

    connect(this, SIGNAL(visibilityChanged(bool)),
            manager, SLOT(onWidgetVisibilityIsChanged(bool)));

    connect(this, SIGNAL(requestGotoLocation(QString,int,int)),
            manager, SLOT(gotoLocation(QString,int,int)));

    connect(this, SIGNAL(requestGotoLocations(QList<QVariant>)),
            manager, SLOT(gotoLocations(QList<QVariant>)));

    connect(manager, SIGNAL(treeDataUpdate(QSharedPointer<QStandardItem>)),
            this, SLOT(onDataUpdate(QSharedPointer<QStandardItem>)));

    connect(this, SIGNAL(requestTreeDataUpdate()),
            manager, SLOT(onRequestTreeDataUpdate()));
}

NavigationWidget::~NavigationWidget()
{
    delete d->fullProjectsModeButton;
    delete d->ui;
    delete d;
}

void NavigationWidget::hideEvent(QHideEvent *event)
{
    emit visibilityChanged(false);
    QWidget::hideEvent(event);
}

void NavigationWidget::showEvent(QShowEvent *event)
{
    emit visibilityChanged(true);

    // request to update to the current state - to be sure
    emit requestTreeDataUpdate();

    QWidget::showEvent(event);
}

QList<QToolButton *> NavigationWidget::createToolButtons()
{
    QList<QToolButton *> list;

    // full projects mode
    if (!d->fullProjectsModeButton) {
        // create a button
        d->fullProjectsModeButton = new QToolButton();
        d->fullProjectsModeButton->setIcon(
                QIcon(QLatin1String(":/classview/images/hierarchicalmode.png")));
        d->fullProjectsModeButton->setCheckable(true);
        d->fullProjectsModeButton->setToolTip(tr("Show Subprojects"));

        // by default - not a flat mode
        setFlatMode(false);

        // connections
        connect(d->fullProjectsModeButton, SIGNAL(toggled(bool)),
                this, SLOT(onFullProjectsModeToggled(bool)));
    }

    list << d->fullProjectsModeButton;

    return list;
}

bool NavigationWidget::flatMode() const
{
    QTC_ASSERT(d->fullProjectsModeButton, return false);

    // button is 'full projects mode' - so it has to be inverted
    return !d->fullProjectsModeButton->isChecked();
}

void NavigationWidget::setFlatMode(bool flatMode)
{
    QTC_ASSERT(d->fullProjectsModeButton, return);

    // button is 'full projects mode' - so it has to be inverted
    d->fullProjectsModeButton->setChecked(!flatMode);
}

void NavigationWidget::onFullProjectsModeToggled(bool state)
{
    // button is 'full projects mode' - so it has to be inverted
    Manager::instance()->setFlatMode(!state);
}

void NavigationWidget::onItemActivated(const QModelIndex &index)
{
    if (!index.isValid())
        return;

    QList<QVariant> list = d->treeModel->data(index, Constants::SymbolLocationsRole).toList();

    emit requestGotoLocations(list);
}

void NavigationWidget::onDataUpdate(QSharedPointer<QStandardItem> result)
{
    if (result.isNull())
        return;

    QTime timer;
    if (debug)
        timer.start();
    // update is received. root item must be updated - and received information
    // might be just a root - if a lazy data population is enabled.
    // so expanded items must be parsed and 'fetched'

    fetchExpandedItems(result.data(), d->treeModel->invisibleRootItem());

    d->treeModel->moveRootToTarget(result.data());

    // expand top level projects
    QModelIndex sessionIndex;

    for (int i = 0; i < d->treeModel->rowCount(sessionIndex); ++i)
        d->ui->treeView->expand(d->treeModel->index(i, 0, sessionIndex));

    if (debug)
        qDebug() << "Class View:" << QDateTime::currentDateTime().toString()
            << "TreeView is updated in" << timer.elapsed() << "msecs";
}

void NavigationWidget::fetchExpandedItems(QStandardItem *item, const QStandardItem *target) const
{
    if (!item || !target)
        return;

    const QModelIndex &parent = d->treeModel->indexFromItem(target);
    if (d->ui->treeView->isExpanded(parent))
        Manager::instance()->fetchMore(item, true);

    int itemIndex = 0;
    int targetIndex = 0;
    int itemRows = item->rowCount();
    int targetRows = target->rowCount();

    while (itemIndex < itemRows && targetIndex < targetRows) {
        QStandardItem *itemChild = item->child(itemIndex);
        const QStandardItem *targetChild = target->child(targetIndex);

        const SymbolInformation &itemInf = Utils::symbolInformationFromItem(itemChild);
        const SymbolInformation &targetInf = Utils::symbolInformationFromItem(targetChild);

        if (itemInf < targetInf) {
            ++itemIndex;
        } else if (itemInf == targetInf) {
            fetchExpandedItems(itemChild, targetChild);
            ++itemIndex;
            ++targetIndex;
        } else {
            ++targetIndex;
        }
    }
}

} // namespace Internal
} // namespace ClassView
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: docsh.hxx,v $
 *
 *  $Revision: 1.27 $
 *
 *  last change: $Author: kz $ $Date: 2004-08-31 09:42:59 $
 *
 *  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 _SWDOCSH_HXX
#define _SWDOCSH_HXX

#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _SFX_OBJFAC_HXX //autogen
#include <sfx2/docfac.hxx>
#endif
#ifndef _SFX_INTERNO_HXX //autogen
#include <sfx2/interno.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
#ifndef SW_SWDLL_HXX
#include <swdll.hxx>
#endif
#ifndef _SHELLID_HXX
#include <shellid.hxx>
#endif

class   SwDoc;
class   Sw3Io;
class   SfxDocumentInfoDialog;
class   SfxStyleSheetBasePool;
class   FontList;
class   SwView;
class   SwWrtShell;
class   SwFEShell;
class   Reader;
class   SwReader;
class   SwCrsrShell;
class   SwSrcView;
class   PushButton;
class   FixedText;
class   SwPaM;
class   SwgReaderOption;

class SW_DLLPUBLIC SwDocShell: public SfxObjectShell, public SfxInPlaceObject,
                  public SfxListener
{
    SwDoc*                  pDoc;           // Document
    Sw3Io*                  pIo;            // Reader / Writer
    SfxStyleSheetBasePool*  pBasePool;      // Durchreiche fuer Formate
    FontList*               pFontList;      // aktuelle FontListe

    // Nix geht ohne die WrtShell (historische Gruende)
    // RuekwaertsPointer auf die View (historische Gruende)
    // Dieser gilt solange bis im Activate ein neuer gesetzt wird
    // oder dieser im Dtor der View geloescht wird
    //
    SwView*                 pView;
    SwWrtShell*             pWrtShell;

    Timer                   aFinishedTimer; // Timer fuers ueberpriefen der
                                            // Grafik-Links. Sind alle da,
                                            // dann ist Doc voll. geladen

    SvPersistRef            xOLEChildList;  // fuers RemoveOLEObjects
    sal_Int16               nUpdateDocMode; // contains the com::sun::star::document::UpdateDocMode
    bool                    bInUpdateFontList; //prevent nested calls of UpdateFontList
    // Methoden fuer den Zugriff aufs Doc
    SW_DLLPRIVATE void                  AddLink();
    SW_DLLPRIVATE void                  RemoveLink();

    // Hint abfangen fuer DocInfo
    SW_DLLPRIVATE virtual void          Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    // FileIO
    SW_DLLPRIVATE virtual BOOL          InitNew(SvStorage* pNewStor);
    SW_DLLPRIVATE virtual BOOL          Load(SvStorage* pStor);
    SW_DLLPRIVATE virtual BOOL          LoadFrom(SvStorage* pStor);
    SW_DLLPRIVATE virtual BOOL          ConvertFrom( SfxMedium &rMedium );
    SW_DLLPRIVATE virtual void          HandsOff();
    SW_DLLPRIVATE virtual BOOL          SaveAs(SvStorage * pNewStor );
    SW_DLLPRIVATE virtual BOOL          ConvertTo(SfxMedium &rMedium );
    SW_DLLPRIVATE virtual BOOL          SaveCompleted(SvStorage * pNewStor );
    SW_DLLPRIVATE virtual USHORT            PrepareClose( BOOL bUI = TRUE, BOOL bForBrowsing = FALSE );

    // DocInfo dem Doc melden
    //
    SW_DLLPRIVATE virtual SfxDocumentInfoDialog* CreateDocumentInfoDialog(
                                    Window *pParent, const SfxItemSet &);
    // OLE-Geraffel
    SW_DLLPRIVATE virtual void          Draw( OutputDevice*, const JobSetup&, USHORT);

    // Methoden fuer StyleSheets
    SW_DLLPRIVATE USHORT                    Edit( const String &rName, const String& rParent, USHORT nFamily,
                                    USHORT nMask, BOOL bNew,
                                    BOOL bColumn = FALSE,
                                    SwWrtShell* pActShell = 0,
                                    BOOL bBasic = FALSE );
    SW_DLLPRIVATE USHORT                    Delete(const String &rName, USHORT nFamily);
    SW_DLLPRIVATE USHORT                    ApplyStyles(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0,
                                        USHORT nMode = 0 );
    SW_DLLPRIVATE USHORT                    DoWaterCan( const String &rName, USHORT nFamily);
    SW_DLLPRIVATE USHORT                    UpdateStyle(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0);
    SW_DLLPRIVATE USHORT                    MakeByExample(const String &rName,
                                            USHORT nFamily, USHORT nMask, SwWrtShell* pShell = 0);

    SW_DLLPRIVATE void                  InitDraw();
    SW_DLLPRIVATE void                  SubInitNew();   // fuer InitNew und HtmlSourceModus
    inline void             SetWrtShell(SwWrtShell* pShell)
                                { pWrtShell = pShell; }

    SW_DLLPRIVATE void                  RemoveOLEObjects();
    SW_DLLPRIVATE void                  CalcLayoutForOLEObjects();

    SW_DLLPRIVATE void                    Init_Impl();
    SW_DLLPRIVATE DECL_STATIC_LINK( SwDocShell, IsLoadFinished, void* );

public:

    // aber selbst implementieren
    SFX_DECL_INTERFACE(SW_DOCSHELL);
    SFX_DECL_OBJECTFACTORY(SwDocShell);
    TYPEINFO();

    static SfxInterface *_GetInterface() { return _GetInterfaceImpl(); }

    //Das Doc wird fuer SO-Datenaustausch benoetigt!
    SwDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
    SwDocShell( SwDoc *pDoc, SfxObjectCreateMode eMode = SFX_CREATE_MODE_STANDARD );
    ~SwDocShell();

    // OLE 2.0-Benachrichtigung
    DECL_LINK( Ole2ModifiedHdl, void * );

    // OLE-Geraffel
    virtual void      SetVisArea( const Rectangle &rRect );
    virtual Rectangle GetVisArea( USHORT nAspect ) const;
    virtual Printer  *GetDocumentPrinter();
    virtual OutputDevice* GetDocumentRefDev();
    virtual void      OnDocumentPrinterChanged( Printer * pNewPrinter );
    virtual ULONG     GetMiscStatus() const;

    virtual void            PrepareReload();
    virtual void            SetModified( BOOL = TRUE );

    // Dispatcher
    void                    Execute(SfxRequest &);
    void                    ExecStyleSheet(SfxRequest&);
    void                    ExecDB(SfxRequest&);

    void                    GetState(SfxItemSet &);
    void                    StateAlways(SfxItemSet &);
    void                    StateStyleSheet(SfxItemSet&, SwWrtShell* pSh = 0 );

    // Doc rausreichen aber VORSICHT
    inline SwDoc*           GetDoc() { return pDoc; }
    void                    UpdateFontList();
    void                    UpdateChildWindows();

    // DocumentInfo neu setzen
    BOOL                    SetDocumentInfo(const SfxDocumentInfo& rInfo);

    // globaler IO
    virtual BOOL            Save();
    inline BOOL                 SaveAsChilds( SvStorage *pStor );
    inline BOOL                 SaveCompletedChilds( SvStorage *pStor );

    // fuer VorlagenPI
    virtual SfxStyleSheetBasePool*  GetStyleSheetPool();

    // Fuer Organizer
    virtual BOOL Insert(SfxObjectShell &rSource,
                        USHORT  nSourceIdx1,
                        USHORT  nSourceIdx2,
                        USHORT  nSourceIdx3,
                        USHORT& nIdx1,
                        USHORT& nIdx2,
                        USHORT& nIdx3,
                        USHORT& nRemovedIdx);

    virtual BOOL Remove(USHORT nIdx1,
                        USHORT nIdx2 = INDEX_IGNORE,
                        USHORT nIdx3 = INDEX_IGNORE);

    virtual Bitmap      GetStyleFamilyBitmap( SfxStyleFamily eFamily, BmpColorMode eColorMode );

    // View setzen fuer Aktionen ueber Shell
    void          SetView(SwView* pVw);
    const SwView *GetView() const { return pView; }
    SwView       *GetView()       { return pView; }

    // Zugriff auf die zur SwView gehoerige SwWrtShell
          SwWrtShell *GetWrtShell()       { return pWrtShell; }
    const SwWrtShell *GetWrtShell() const { return pWrtShell; }

    // fuer die Core - die kennt die DocShell aber keine WrtShell!
          SwFEShell *GetFEShell();
    const SwFEShell *GetFEShell() const
                { return ((SwDocShell*)this)->GetFEShell(); }

    // Fuer Einfuegen Dokument
    Reader* StartConvertFrom(SfxMedium& rMedium, SwReader** ppRdr,
                            SwCrsrShell* pCrsrSh = 0, SwPaM* pPaM = 0);

    // Anforderung der pIo-Struktur fuer den Zugriff auf Substorages
    // und Streams
    Sw3Io* GetIoSystem() { return pIo; }

    virtual long DdeGetData( const String& rItem, const String& rMimeType,
                             ::com::sun::star::uno::Any & rValue );
    virtual long DdeSetData( const String& rItem, const String& rMimeType,
                                const ::com::sun::star::uno::Any & rValue );
    virtual ::so3::SvLinkSource* DdeCreateLinkSource( const String& rItem );
    virtual void FillClass( SvGlobalName * pClassName,
                                   ULONG * pClipFormat,
                                   String * pAppName,
                                   String * pLongUserName,
                                   String * pUserName,
                                   long nVersion = SOFFICE_FILEFORMAT_CURRENT ) const;

    virtual void LoadStyles( SfxObjectShell& rSource );

    void _LoadStyles( SfxObjectShell& rSource, BOOL bPreserveCurrentDocument );

    // Seitenvorlagedialog anzeigen, ggf. auf Spaltenpage
    void FormatPage( const String& rPage,
                        BOOL bColumn = FALSE,
                        SwWrtShell*     pActShell = 0 );

    // Timer starten fuers ueberpruefen der Grafik-Links. Sind alle
    // vollstaendig geladen, dann ist das Doc fertig
    void StartLoadFinishedTimer();

    // eine Uebertragung wird abgebrochen (wird aus dem SFX gerufen)
    virtual void CancelTransfers();

    // Doc aus Html-Source neu laden
    void    ReloadFromHtml( const String& rStreamName, SwSrcView* pSrcView );

    sal_Int16   GetUpdateDocMode() const {return nUpdateDocMode;}

    //Activate wait cursor for all windows of this document
    //Optionally all dispatcher could be Locked
    //Usually locking should be done using the class: SwWaitObject!
    void EnterWait( BOOL bLockDispatcher );
    void LeaveWait( BOOL bLockDispatcher );

    void ToggleBrowserMode(BOOL bOn, SwView* pView = 0);

    ULONG LoadStylesFromFile( const String& rURL, SwgReaderOption& rOpt,
                                BOOL bUnoCall );
    void InvalidateModel();
    void ReactivateModel();

#if SUPD>620
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >  GetEventNames();
#endif

    // --> FME 2004-08-05 #i20883# Digital Signatures and Encryption
    virtual sal_uInt16 GetHiddenInformationState( sal_uInt16 nStates );
    // <--
};

inline BOOL SwDocShell::SaveAsChilds( SvStorage *pStor )
{
    return SfxInPlaceObject::SaveAsChilds( pStor );
}

inline BOOL SwDocShell::SaveCompletedChilds( SvStorage *pStor )
{
    return SfxInPlaceObject::SaveCompletedChilds( pStor );
}
#endif
<commit_msg>INTEGRATION: CWS mav09 (1.24.78); FILE MERGED 2004/09/16 19:05:43 mav 1.24.78.3: RESYNC: (1.24-1.27); FILE MERGED 2004/08/12 17:11:45 mav 1.24.78.2: #i27773# introduce version back 2004/05/18 16:43:02 mba 1.24.78.1: RESYNC to m39<commit_after>/*************************************************************************
 *
 *  $RCSfile: docsh.hxx,v $
 *
 *  $Revision: 1.28 $
 *
 *  last change: $Author: kz $ $Date: 2004-10-04 18:58:00 $
 *
 *  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 _SWDOCSH_HXX
#define _SWDOCSH_HXX

#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _SFX_OBJFAC_HXX //autogen
#include <sfx2/docfac.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
#ifndef SW_SWDLL_HXX
#include <swdll.hxx>
#endif
#ifndef _SHELLID_HXX
#include <shellid.hxx>
#endif

#include <svtools/lstner.hxx>

class   SwDoc;
class   SfxDocumentInfoDialog;
class   SfxStyleSheetBasePool;
class   FontList;
class   SwView;
class   SwWrtShell;
class   SwFEShell;
class   Reader;
class   SwReader;
class   SwCrsrShell;
class   SwSrcView;
class   PushButton;
class   FixedText;
class   SwPaM;
class   SwgReaderOption;

class SW_DLLPUBLIC SwDocShell: public SfxObjectShell, public SfxListener
{
    SwDoc*                  pDoc;           // Document
    SfxStyleSheetBasePool*  pBasePool;      // Durchreiche fuer Formate
    FontList*               pFontList;      // aktuelle FontListe

    // Nix geht ohne die WrtShell (historische Gruende)
    // RuekwaertsPointer auf die View (historische Gruende)
    // Dieser gilt solange bis im Activate ein neuer gesetzt wird
    // oder dieser im Dtor der View geloescht wird
    //
    SwView*                 pView;
    SwWrtShell*             pWrtShell;

    Timer                   aFinishedTimer; // Timer fuers ueberpriefen der
                                            // Grafik-Links. Sind alle da,
                                            // dann ist Doc voll. geladen

    //SvPersistRef            xOLEChildList;  // fuers RemoveOLEObjects
    comphelper::EmbeddedObjectContainer*    pOLEChildList;
    sal_Int16               nUpdateDocMode; // contains the com::sun::star::document::UpdateDocMode
    bool                    bInUpdateFontList; //prevent nested calls of UpdateFontList
    // Methoden fuer den Zugriff aufs Doc
    SW_DLLPRIVATE void                  AddLink();
    SW_DLLPRIVATE void                  RemoveLink();

    // Hint abfangen fuer DocInfo
    SW_DLLPRIVATE virtual void          Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    // FileIO
    SW_DLLPRIVATE virtual sal_Bool InitNew( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
    SW_DLLPRIVATE virtual sal_Bool Load( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
    SW_DLLPRIVATE virtual sal_Bool LoadFrom( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
    SW_DLLPRIVATE virtual sal_Bool            ConvertFrom( SfxMedium &rMedium );
    SW_DLLPRIVATE virtual sal_Bool            ConvertTo( SfxMedium &rMedium );
    SW_DLLPRIVATE virtual sal_Bool SaveAs( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xNewStg );
    SW_DLLPRIVATE virtual sal_Bool SaveCompleted( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );

    SW_DLLPRIVATE virtual USHORT            PrepareClose( BOOL bUI = TRUE, BOOL bForBrowsing = FALSE );

    // DocInfo dem Doc melden
    //
    SW_DLLPRIVATE virtual SfxDocumentInfoDialog* CreateDocumentInfoDialog(
                                    Window *pParent, const SfxItemSet &);
    // OLE-Geraffel
    SW_DLLPRIVATE virtual void          Draw( OutputDevice*, const JobSetup&, USHORT);

    // Methoden fuer StyleSheets
    SW_DLLPRIVATE USHORT                    Edit( const String &rName, const String& rParent, USHORT nFamily,
                                    USHORT nMask, BOOL bNew,
                                    BOOL bColumn = FALSE,
                                    SwWrtShell* pActShell = 0,
                                    BOOL bBasic = FALSE );
    SW_DLLPRIVATE USHORT                    Delete(const String &rName, USHORT nFamily);
    SW_DLLPRIVATE USHORT                    ApplyStyles(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0,
                                        USHORT nMode = 0 );
    SW_DLLPRIVATE USHORT                    DoWaterCan( const String &rName, USHORT nFamily);
    SW_DLLPRIVATE USHORT                    UpdateStyle(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0);
    SW_DLLPRIVATE USHORT                    MakeByExample(const String &rName,
                                            USHORT nFamily, USHORT nMask, SwWrtShell* pShell = 0);

    SW_DLLPRIVATE void                  InitDraw();
    SW_DLLPRIVATE void                  SubInitNew();   // fuer InitNew und HtmlSourceModus
    inline void             SetWrtShell(SwWrtShell* pShell)
                                { pWrtShell = pShell; }

    SW_DLLPRIVATE void                  RemoveOLEObjects();
    SW_DLLPRIVATE void                  CalcLayoutForOLEObjects();

    SW_DLLPRIVATE void                    Init_Impl();
    SW_DLLPRIVATE DECL_STATIC_LINK( SwDocShell, IsLoadFinished, void* );

public:

    // aber selbst implementieren
    SFX_DECL_INTERFACE(SW_DOCSHELL);
    SFX_DECL_OBJECTFACTORY();
    TYPEINFO();

    static SfxInterface *_GetInterface() { return _GetInterfaceImpl(); }

    //Das Doc wird fuer SO-Datenaustausch benoetigt!
    SwDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
    SwDocShell( SwDoc *pDoc, SfxObjectCreateMode eMode = SFX_CREATE_MODE_STANDARD );
    ~SwDocShell();

    // OLE 2.0-Benachrichtigung
    DECL_LINK( Ole2ModifiedHdl, void * );

    // OLE-Geraffel
    virtual void      SetVisArea( const Rectangle &rRect );
    virtual Rectangle GetVisArea( USHORT nAspect ) const;
    virtual Printer  *GetDocumentPrinter();
    virtual OutputDevice* GetDocumentRefDev();
    virtual void      OnDocumentPrinterChanged( Printer * pNewPrinter );
    virtual ULONG     GetMiscStatus() const;

    virtual void            PrepareReload();
    virtual void            SetModified( BOOL = TRUE );

    // Dispatcher
    void                    Execute(SfxRequest &);
    void                    ExecStyleSheet(SfxRequest&);
    void                    ExecDB(SfxRequest&);

    void                    GetState(SfxItemSet &);
    void                    StateAlways(SfxItemSet &);
    void                    StateStyleSheet(SfxItemSet&, SwWrtShell* pSh = 0 );

    // Doc rausreichen aber VORSICHT
    inline SwDoc*           GetDoc() { return pDoc; }
    void                    UpdateFontList();
    void                    UpdateChildWindows();

    // DocumentInfo neu setzen
    BOOL                    SetDocumentInfo(const SfxDocumentInfo& rInfo);

    // globaler IO
    virtual BOOL            Save();

    // fuer VorlagenPI
    virtual SfxStyleSheetBasePool*  GetStyleSheetPool();

    // Fuer Organizer
    virtual BOOL Insert(SfxObjectShell &rSource,
                        USHORT  nSourceIdx1,
                        USHORT  nSourceIdx2,
                        USHORT  nSourceIdx3,
                        USHORT& nIdx1,
                        USHORT& nIdx2,
                        USHORT& nIdx3,
                        USHORT& nRemovedIdx);

    virtual BOOL Remove(USHORT nIdx1,
                        USHORT nIdx2 = INDEX_IGNORE,
                        USHORT nIdx3 = INDEX_IGNORE);

    virtual Bitmap      GetStyleFamilyBitmap( SfxStyleFamily eFamily, BmpColorMode eColorMode );

    // View setzen fuer Aktionen ueber Shell
    void          SetView(SwView* pVw);
    const SwView *GetView() const { return pView; }
    SwView       *GetView()       { return pView; }

    // Zugriff auf die zur SwView gehoerige SwWrtShell
          SwWrtShell *GetWrtShell()       { return pWrtShell; }
    const SwWrtShell *GetWrtShell() const { return pWrtShell; }

    // fuer die Core - die kennt die DocShell aber keine WrtShell!
          SwFEShell *GetFEShell();
    const SwFEShell *GetFEShell() const
                { return ((SwDocShell*)this)->GetFEShell(); }

    // Fuer Einfuegen Dokument
    Reader* StartConvertFrom(SfxMedium& rMedium, SwReader** ppRdr,
                            SwCrsrShell* pCrsrSh = 0, SwPaM* pPaM = 0);

    virtual long DdeGetData( const String& rItem, const String& rMimeType,
                             ::com::sun::star::uno::Any & rValue );
    virtual long DdeSetData( const String& rItem, const String& rMimeType,
                                const ::com::sun::star::uno::Any & rValue );
    virtual ::sfx2::SvLinkSource* DdeCreateLinkSource( const String& rItem );
    virtual void FillClass( SvGlobalName * pClassName,
                                   ULONG * pClipFormat,
                                   String * pAppName,
                                   String * pLongUserName,
                                   String * pUserName,
                                   sal_Int32 nFileFormat ) const;

    virtual void LoadStyles( SfxObjectShell& rSource );

    void _LoadStyles( SfxObjectShell& rSource, BOOL bPreserveCurrentDocument );

    // Seitenvorlagedialog anzeigen, ggf. auf Spaltenpage
    void FormatPage( const String& rPage,
                        BOOL bColumn = FALSE,
                        SwWrtShell*     pActShell = 0 );

    // Timer starten fuers ueberpruefen der Grafik-Links. Sind alle
    // vollstaendig geladen, dann ist das Doc fertig
    void StartLoadFinishedTimer();

    // eine Uebertragung wird abgebrochen (wird aus dem SFX gerufen)
    virtual void CancelTransfers();

    // Doc aus Html-Source neu laden
    void    ReloadFromHtml( const String& rStreamName, SwSrcView* pSrcView );

    sal_Int16   GetUpdateDocMode() const {return nUpdateDocMode;}

    //Activate wait cursor for all windows of this document
    //Optionally all dispatcher could be Locked
    //Usually locking should be done using the class: SwWaitObject!
    void EnterWait( BOOL bLockDispatcher );
    void LeaveWait( BOOL bLockDispatcher );

    void ToggleBrowserMode(BOOL bOn, SwView* pView = 0);

    ULONG LoadStylesFromFile( const String& rURL, SwgReaderOption& rOpt,
                                BOOL bUnoCall );
    void InvalidateModel();
    void ReactivateModel();

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString >  GetEventNames();

    // --> FME 2004-08-05 #i20883# Digital Signatures and Encryption
    virtual sal_uInt16 GetHiddenInformationState( sal_uInt16 nStates );
    // <--
};

#endif
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "qbsprojectmanager.h"

#include "defaultpropertyprovider.h"
#include "qbslogsink.h"
#include "qbsproject.h"
#include "qbsprojectmanagerconstants.h"
#include "qbsprojectmanagerplugin.h"

#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/projectexplorer.h>
#include <qmljstools/qmljstoolsconstants.h>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>

#include <QVariantMap>

#include <qbs.h>
#include <qtprofilesetup.h>

const QChar sep = QLatin1Char('.');

static QString qtcProfileGroup() { return QLatin1String("preferences.qtcreator.kit"); }
static QString qtcProfilePrefix() { return qtcProfileGroup() + sep; }

namespace QbsProjectManager {
namespace Internal {

qbs::Settings *QbsManager::m_settings = 0;
Internal::QbsLogSink *QbsManager::m_logSink = 0;
QbsManager *QbsManager::m_instance = 0;

QbsManager::QbsManager() :
    m_defaultPropertyProvider(new DefaultPropertyProvider)
{
    m_settings = new qbs::Settings(Core::ICore::userResourcePath());
    m_instance = this;

    setObjectName(QLatin1String("QbsProjectManager"));
    connect(ProjectExplorer::KitManager::instance(), &ProjectExplorer::KitManager::kitsLoaded, this,
            [this]() { m_kitsToBeSetupForQbs = ProjectExplorer::KitManager::kits(); } );
    connect(ProjectExplorer::KitManager::instance(), &ProjectExplorer::KitManager::kitAdded, this,
            &QbsManager::addProfileFromKit);
    connect(ProjectExplorer::KitManager::instance(), &ProjectExplorer::KitManager::kitUpdated, this,
            &QbsManager::handleKitUpdate);
    connect(ProjectExplorer::KitManager::instance(), &ProjectExplorer::KitManager::kitRemoved, this,
            &QbsManager::handleKitRemoval);

    m_logSink = new QbsLogSink(this);
    int level = qbs::LoggerWarning;
    const QString levelEnv = QString::fromLocal8Bit(qgetenv("QBS_LOG_LEVEL"));
    if (!levelEnv.isEmpty()) {
        bool ok = false;
        int tmp = levelEnv.toInt(&ok);
        if (ok) {
            if (tmp < static_cast<int>(qbs::LoggerMinLevel))
                tmp = static_cast<int>(qbs::LoggerMinLevel);
            if (tmp > static_cast<int>(qbs::LoggerMaxLevel))
                tmp = static_cast<int>(qbs::LoggerMaxLevel);
            level = tmp;
        }
    }
    m_logSink->setLogLevel(static_cast<qbs::LoggerLevel>(level));
}

QbsManager::~QbsManager()
{
    delete m_defaultPropertyProvider;
    delete m_settings;
    m_instance = 0;
}

QString QbsManager::mimeType() const
{
    return QLatin1String(QmlJSTools::Constants::QBS_MIMETYPE);
}

ProjectExplorer::Project *QbsManager::openProject(const QString &fileName, QString *errorString)
{
    if (!QFileInfo(fileName).isFile()) {
        if (errorString)
            *errorString = tr("Failed opening project \"%1\": Project is not a file.")
                .arg(fileName);
        return 0;
    }

    return new QbsProject(this, fileName);
}

QString QbsManager::profileForKit(const ProjectExplorer::Kit *k)
{
    if (!k)
        return QString();
    updateProfileIfNecessary(k);
    return m_settings->value(qtcProfilePrefix() + k->id().toString()).toString();
}

void QbsManager::setProfileForKit(const QString &name, const ProjectExplorer::Kit *k)
{
    m_settings->setValue(qtcProfilePrefix() + k->id().toString(), name);
}

void QbsManager::updateProfileIfNecessary(const ProjectExplorer::Kit *kit)
{
    // kit in list <=> profile update is necessary
    // Note that the const_cast is safe, as we do not call any non-const methods on the object.
    if (m_kitsToBeSetupForQbs.removeOne(const_cast<ProjectExplorer::Kit *>(kit)))
        addProfileFromKit(kit);
}

void QbsManager::addProfile(const QString &name, const QVariantMap &data)
{
    qbs::Profile profile(name, settings());
    const QVariantMap::ConstIterator cend = data.constEnd();
    for (QVariantMap::ConstIterator it = data.constBegin(); it != cend; ++it)
        profile.setValue(it.key(), it.value());
}

void QbsManager::addQtProfileFromKit(const QString &profileName, const ProjectExplorer::Kit *k)
{
    const QtSupport::BaseQtVersion * const qt = QtSupport::QtKitInformation::qtVersion(k);
    if (!qt)
        return;

    qbs::QtEnvironment qtEnv;
    const QList<ProjectExplorer::Abi> abi = qt->qtAbis();
    if (!abi.empty()) {
        qtEnv.architecture = ProjectExplorer::Abi::toString(abi.first().architecture());
        if (abi.first().wordWidth() == 64)
            qtEnv.architecture.append(QLatin1String("_64"));
    }
    qtEnv.binaryPath = qt->binPath().toString();
    qtEnv.documentationPath = qt->docsPath().toString();
    qtEnv.includePath = qt->headerPath().toString();
    qtEnv.libraryPath = qt->libraryPath().toString();
    qtEnv.pluginPath = qt->pluginPath().toString();
    qtEnv.mkspecBasePath = qt->mkspecsPath().toString();
    qtEnv.mkspecName = qt->mkspec().toString();
    qtEnv.mkspecPath = qt->mkspecPath().toString();
    qtEnv.qtNameSpace = qt->qtNamespace();
    qtEnv.qtLibInfix = qt->qtLibInfix();
    qtEnv.qtVersion = qt->qtVersionString();
    qtEnv.qtMajorVersion = qt->qtVersion().majorVersion;
    qtEnv.qtMinorVersion = qt->qtVersion().minorVersion;
    qtEnv.qtPatchVersion = qt->qtVersion().patchVersion;
    qtEnv.frameworkBuild = qt->isFrameworkBuild();
    qtEnv.configItems = qt->configValues();
    qtEnv.qtConfigItems = qt->qtConfigValues();
    foreach (const QString &buildVariant,
            QStringList() << QLatin1String("debug") << QLatin1String("release")) {
        if (qtEnv.qtConfigItems.contains(buildVariant))
            qtEnv.buildVariant << buildVariant;
    }
    const qbs::ErrorInfo errorInfo = qbs::setupQtProfile(profileName, settings(), qtEnv);
    if (errorInfo.hasError()) {
        Core::MessageManager::write(tr("Failed to set up kit for Qbs: %1")
                .arg(errorInfo.toString()), Core::MessageManager::ModeSwitch);
    }
}

void QbsManager::addProfileFromKit(const ProjectExplorer::Kit *k)
{
    const QString name = QString::fromLatin1("qtc_%1_%2").arg(k->fileSystemFriendlyName().left(8),
            QString::number(k->id().uniqueIdentifier(), 16));
    qbs::Profile(name, settings()).removeProfile();
    setProfileForKit(name, k);
    addQtProfileFromKit(name, k);

    // set up properties:
    QVariantMap data = m_defaultPropertyProvider->properties(k, QVariantMap());
    QList<PropertyProvider *> providerList = ExtensionSystem::PluginManager::getObjects<PropertyProvider>();
    foreach (PropertyProvider *provider, providerList) {
        if (provider->canHandle(k))
            data = provider->properties(k, data);
    }

    addProfile(name, data);
}

void QbsManager::handleKitUpdate(ProjectExplorer::Kit *kit)
{
    m_kitsToBeSetupForQbs.removeOne(kit);
    addProfileFromKit(kit);
}

void QbsManager::handleKitRemoval(ProjectExplorer::Kit *kit)
{
    m_kitsToBeSetupForQbs.removeOne(kit);
    const QString key = qtcProfilePrefix() + kit->id().toString();
    const QString profileName = m_settings->value(key).toString();
    m_settings->remove(key);
    qbs::Profile(profileName, m_settings).removeProfile();
}

} // namespace Internal
} // namespace QbsProjectManager
<commit_msg>QbsProjectManager: Fix deriving qbs profile names from kit attributes.<commit_after>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "qbsprojectmanager.h"

#include "defaultpropertyprovider.h"
#include "qbslogsink.h"
#include "qbsproject.h"
#include "qbsprojectmanagerconstants.h"
#include "qbsprojectmanagerplugin.h"

#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/projectexplorer.h>
#include <qmljstools/qmljstoolsconstants.h>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>

#include <QCryptographicHash>
#include <QVariantMap>

#include <qbs.h>
#include <qtprofilesetup.h>

const QChar sep = QLatin1Char('.');

static QString qtcProfileGroup() { return QLatin1String("preferences.qtcreator.kit"); }
static QString qtcProfilePrefix() { return qtcProfileGroup() + sep; }

namespace QbsProjectManager {
namespace Internal {

qbs::Settings *QbsManager::m_settings = 0;
Internal::QbsLogSink *QbsManager::m_logSink = 0;
QbsManager *QbsManager::m_instance = 0;

QbsManager::QbsManager() :
    m_defaultPropertyProvider(new DefaultPropertyProvider)
{
    m_settings = new qbs::Settings(Core::ICore::userResourcePath());
    m_instance = this;

    setObjectName(QLatin1String("QbsProjectManager"));
    connect(ProjectExplorer::KitManager::instance(), &ProjectExplorer::KitManager::kitsLoaded, this,
            [this]() { m_kitsToBeSetupForQbs = ProjectExplorer::KitManager::kits(); } );
    connect(ProjectExplorer::KitManager::instance(), &ProjectExplorer::KitManager::kitAdded, this,
            &QbsManager::addProfileFromKit);
    connect(ProjectExplorer::KitManager::instance(), &ProjectExplorer::KitManager::kitUpdated, this,
            &QbsManager::handleKitUpdate);
    connect(ProjectExplorer::KitManager::instance(), &ProjectExplorer::KitManager::kitRemoved, this,
            &QbsManager::handleKitRemoval);

    m_logSink = new QbsLogSink(this);
    int level = qbs::LoggerWarning;
    const QString levelEnv = QString::fromLocal8Bit(qgetenv("QBS_LOG_LEVEL"));
    if (!levelEnv.isEmpty()) {
        bool ok = false;
        int tmp = levelEnv.toInt(&ok);
        if (ok) {
            if (tmp < static_cast<int>(qbs::LoggerMinLevel))
                tmp = static_cast<int>(qbs::LoggerMinLevel);
            if (tmp > static_cast<int>(qbs::LoggerMaxLevel))
                tmp = static_cast<int>(qbs::LoggerMaxLevel);
            level = tmp;
        }
    }
    m_logSink->setLogLevel(static_cast<qbs::LoggerLevel>(level));
}

QbsManager::~QbsManager()
{
    delete m_defaultPropertyProvider;
    delete m_settings;
    m_instance = 0;
}

QString QbsManager::mimeType() const
{
    return QLatin1String(QmlJSTools::Constants::QBS_MIMETYPE);
}

ProjectExplorer::Project *QbsManager::openProject(const QString &fileName, QString *errorString)
{
    if (!QFileInfo(fileName).isFile()) {
        if (errorString)
            *errorString = tr("Failed opening project \"%1\": Project is not a file.")
                .arg(fileName);
        return 0;
    }

    return new QbsProject(this, fileName);
}

QString QbsManager::profileForKit(const ProjectExplorer::Kit *k)
{
    if (!k)
        return QString();
    updateProfileIfNecessary(k);
    return m_settings->value(qtcProfilePrefix() + k->id().toString()).toString();
}

void QbsManager::setProfileForKit(const QString &name, const ProjectExplorer::Kit *k)
{
    m_settings->setValue(qtcProfilePrefix() + k->id().toString(), name);
}

void QbsManager::updateProfileIfNecessary(const ProjectExplorer::Kit *kit)
{
    // kit in list <=> profile update is necessary
    // Note that the const_cast is safe, as we do not call any non-const methods on the object.
    if (m_kitsToBeSetupForQbs.removeOne(const_cast<ProjectExplorer::Kit *>(kit)))
        addProfileFromKit(kit);
}

void QbsManager::addProfile(const QString &name, const QVariantMap &data)
{
    qbs::Profile profile(name, settings());
    const QVariantMap::ConstIterator cend = data.constEnd();
    for (QVariantMap::ConstIterator it = data.constBegin(); it != cend; ++it)
        profile.setValue(it.key(), it.value());
}

void QbsManager::addQtProfileFromKit(const QString &profileName, const ProjectExplorer::Kit *k)
{
    const QtSupport::BaseQtVersion * const qt = QtSupport::QtKitInformation::qtVersion(k);
    if (!qt)
        return;

    qbs::QtEnvironment qtEnv;
    const QList<ProjectExplorer::Abi> abi = qt->qtAbis();
    if (!abi.empty()) {
        qtEnv.architecture = ProjectExplorer::Abi::toString(abi.first().architecture());
        if (abi.first().wordWidth() == 64)
            qtEnv.architecture.append(QLatin1String("_64"));
    }
    qtEnv.binaryPath = qt->binPath().toString();
    qtEnv.documentationPath = qt->docsPath().toString();
    qtEnv.includePath = qt->headerPath().toString();
    qtEnv.libraryPath = qt->libraryPath().toString();
    qtEnv.pluginPath = qt->pluginPath().toString();
    qtEnv.mkspecBasePath = qt->mkspecsPath().toString();
    qtEnv.mkspecName = qt->mkspec().toString();
    qtEnv.mkspecPath = qt->mkspecPath().toString();
    qtEnv.qtNameSpace = qt->qtNamespace();
    qtEnv.qtLibInfix = qt->qtLibInfix();
    qtEnv.qtVersion = qt->qtVersionString();
    qtEnv.qtMajorVersion = qt->qtVersion().majorVersion;
    qtEnv.qtMinorVersion = qt->qtVersion().minorVersion;
    qtEnv.qtPatchVersion = qt->qtVersion().patchVersion;
    qtEnv.frameworkBuild = qt->isFrameworkBuild();
    qtEnv.configItems = qt->configValues();
    qtEnv.qtConfigItems = qt->qtConfigValues();
    foreach (const QString &buildVariant,
            QStringList() << QLatin1String("debug") << QLatin1String("release")) {
        if (qtEnv.qtConfigItems.contains(buildVariant))
            qtEnv.buildVariant << buildVariant;
    }
    const qbs::ErrorInfo errorInfo = qbs::setupQtProfile(profileName, settings(), qtEnv);
    if (errorInfo.hasError()) {
        Core::MessageManager::write(tr("Failed to set up kit for Qbs: %1")
                .arg(errorInfo.toString()), Core::MessageManager::ModeSwitch);
    }
}

void QbsManager::addProfileFromKit(const ProjectExplorer::Kit *k)
{
    const QString name = QString::fromLatin1("qtc_%1_%2").arg(k->fileSystemFriendlyName().left(8),
            QString::fromLatin1(QCryptographicHash::hash(k->id().name(),
                                                         QCryptographicHash::Sha1).toHex().left(8)));
    qbs::Profile(name, settings()).removeProfile();
    setProfileForKit(name, k);
    addQtProfileFromKit(name, k);

    // set up properties:
    QVariantMap data = m_defaultPropertyProvider->properties(k, QVariantMap());
    QList<PropertyProvider *> providerList = ExtensionSystem::PluginManager::getObjects<PropertyProvider>();
    foreach (PropertyProvider *provider, providerList) {
        if (provider->canHandle(k))
            data = provider->properties(k, data);
    }

    addProfile(name, data);
}

void QbsManager::handleKitUpdate(ProjectExplorer::Kit *kit)
{
    m_kitsToBeSetupForQbs.removeOne(kit);
    addProfileFromKit(kit);
}

void QbsManager::handleKitRemoval(ProjectExplorer::Kit *kit)
{
    m_kitsToBeSetupForQbs.removeOne(kit);
    const QString key = qtcProfilePrefix() + kit->id().toString();
    const QString profileName = m_settings->value(key).toString();
    m_settings->remove(key);
    qbs::Profile(profileName, m_settings).removeProfile();
}

} // namespace Internal
} // namespace QbsProjectManager
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "mobileapp.h"

#include <coreplugin/icore.h>

#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QRegExp>
#include <QtCore/QTextStream>

namespace Qt4ProjectManager {
namespace Internal {

const QString mainWindowBaseName(QLatin1String("mainwindow"));

const QString mainWindowCppFileName(mainWindowBaseName + QLatin1String(".cpp"));
const QString mainWindowHFileName(mainWindowBaseName + QLatin1String(".h"));
const QString mainWindowUiFileName(mainWindowBaseName + QLatin1String(".ui"));

bool MobileAppGeneratedFileInfo::isOutdated() const
{
    return version < AbstractMobileApp::makeStubVersion(MobileApp::StubVersion);
}

MobileApp::MobileApp() : AbstractMobileApp()
{
}

MobileApp::~MobileApp()
{
}

QString MobileApp::pathExtended(int fileType) const
{
    const QString pathBase = outputPathBase();
    switch (fileType) {
        case MainWindowCpp:       return pathBase + mainWindowCppFileName;
        case MainWindowCppOrigin: return originsRoot() + mainWindowCppFileName;
        case MainWindowH:         return pathBase + mainWindowHFileName;
        case MainWindowHOrigin:   return originsRoot() + mainWindowHFileName;
        case MainWindowUi:        return pathBase + mainWindowUiFileName;
        case MainWindowUiOrigin:  return originsRoot() + mainWindowUiFileName;
        default:                  qFatal("MobileApp::path() needs more work");
    }
    return QString();
}

bool MobileApp::adaptCurrentMainCppTemplateLine(QString &line) const
{
    Q_UNUSED(line);
    return true;
}

void MobileApp::handleCurrentProFileTemplateLine(const QString &line,
    QTextStream &proFileTemplate, QTextStream &proFile,
    bool &commentOutNextLine) const
{
    Q_UNUSED(line);
    Q_UNUSED(proFileTemplate);
    Q_UNUSED(proFile);
    Q_UNUSED(commentOutNextLine);
}

Core::GeneratedFiles MobileApp::generateFiles(QString *errorMessage) const
{
    Core::GeneratedFiles files = AbstractMobileApp::generateFiles(errorMessage);

    files.append(file(generateFile(AbstractGeneratedFileInfo::DeploymentPriFile, errorMessage), path(DeploymentPri)));
    files.append(file(generateFile(MobileAppGeneratedFileInfo::MainWindowCppFile, errorMessage), path(MainWindowCpp)));
    files.append(file(generateFile(MobileAppGeneratedFileInfo::MainWindowHFile, errorMessage), path(MainWindowH)));
    files.append(file(generateFile(MobileAppGeneratedFileInfo::MainWindowUiFile, errorMessage), path(MainWindowUi)));
    files.last().setAttributes(Core::GeneratedFile::OpenEditorAttribute);

    return files;
}

QByteArray MobileApp::generateFileExtended(int fileType,
    bool *versionAndCheckSum, QString *comment, QString *errorMessage) const
{
    Q_UNUSED(comment);
    QByteArray data;
    versionAndCheckSum = false;
    switch (fileType) {
        case MobileAppGeneratedFileInfo::MainWindowCppFile:
            data = readBlob(path(MainWindowCppOrigin), errorMessage);
            break;
        case MobileAppGeneratedFileInfo::MainWindowHFile:
            data = readBlob(path(MainWindowHOrigin), errorMessage);
            break;
        case MobileAppGeneratedFileInfo::MainWindowUiFile:
            data = readBlob(path(MainWindowUiOrigin), errorMessage);
            break;
        default:
            Q_ASSERT_X(false, Q_FUNC_INFO, "Whoops, case missing!");
    }
    return data;
}

QString MobileApp::originsRoot() const
{
    return templatesRoot() + QLatin1String("mobileapp/");
}

QString MobileApp::mainWindowClassName() const
{
    return QLatin1String("MainWindow");
}

int MobileApp::stubVersionMinor() const { return StubVersion; }

QList<AbstractGeneratedFileInfo> MobileApp::updateableFiles(const QString &mainProFile) const
{
    Q_UNUSED(mainProFile)
    return QList<AbstractGeneratedFileInfo>(); // Nothing to update, here
}

QList<DeploymentFolder> MobileApp::deploymentFolders() const
{
    QList<DeploymentFolder> result;
    return result;
}

const int MobileApp::StubVersion = 2;

} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>Fix: Do not assign false to a bool*<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "mobileapp.h"

#include <coreplugin/icore.h>

#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QRegExp>
#include <QtCore/QTextStream>

namespace Qt4ProjectManager {
namespace Internal {

const QString mainWindowBaseName(QLatin1String("mainwindow"));

const QString mainWindowCppFileName(mainWindowBaseName + QLatin1String(".cpp"));
const QString mainWindowHFileName(mainWindowBaseName + QLatin1String(".h"));
const QString mainWindowUiFileName(mainWindowBaseName + QLatin1String(".ui"));

bool MobileAppGeneratedFileInfo::isOutdated() const
{
    return version < AbstractMobileApp::makeStubVersion(MobileApp::StubVersion);
}

MobileApp::MobileApp() : AbstractMobileApp()
{
}

MobileApp::~MobileApp()
{
}

QString MobileApp::pathExtended(int fileType) const
{
    const QString pathBase = outputPathBase();
    switch (fileType) {
        case MainWindowCpp:       return pathBase + mainWindowCppFileName;
        case MainWindowCppOrigin: return originsRoot() + mainWindowCppFileName;
        case MainWindowH:         return pathBase + mainWindowHFileName;
        case MainWindowHOrigin:   return originsRoot() + mainWindowHFileName;
        case MainWindowUi:        return pathBase + mainWindowUiFileName;
        case MainWindowUiOrigin:  return originsRoot() + mainWindowUiFileName;
        default:                  qFatal("MobileApp::path() needs more work");
    }
    return QString();
}

bool MobileApp::adaptCurrentMainCppTemplateLine(QString &line) const
{
    Q_UNUSED(line);
    return true;
}

void MobileApp::handleCurrentProFileTemplateLine(const QString &line,
    QTextStream &proFileTemplate, QTextStream &proFile,
    bool &commentOutNextLine) const
{
    Q_UNUSED(line);
    Q_UNUSED(proFileTemplate);
    Q_UNUSED(proFile);
    Q_UNUSED(commentOutNextLine);
}

Core::GeneratedFiles MobileApp::generateFiles(QString *errorMessage) const
{
    Core::GeneratedFiles files = AbstractMobileApp::generateFiles(errorMessage);

    files.append(file(generateFile(AbstractGeneratedFileInfo::DeploymentPriFile, errorMessage), path(DeploymentPri)));
    files.append(file(generateFile(MobileAppGeneratedFileInfo::MainWindowCppFile, errorMessage), path(MainWindowCpp)));
    files.append(file(generateFile(MobileAppGeneratedFileInfo::MainWindowHFile, errorMessage), path(MainWindowH)));
    files.append(file(generateFile(MobileAppGeneratedFileInfo::MainWindowUiFile, errorMessage), path(MainWindowUi)));
    files.last().setAttributes(Core::GeneratedFile::OpenEditorAttribute);

    return files;
}

QByteArray MobileApp::generateFileExtended(int fileType,
    bool *versionAndCheckSum, QString *comment, QString *errorMessage) const
{
    Q_UNUSED(comment);
    QByteArray data;
    *versionAndCheckSum = false;
    switch (fileType) {
        case MobileAppGeneratedFileInfo::MainWindowCppFile:
            data = readBlob(path(MainWindowCppOrigin), errorMessage);
            break;
        case MobileAppGeneratedFileInfo::MainWindowHFile:
            data = readBlob(path(MainWindowHOrigin), errorMessage);
            break;
        case MobileAppGeneratedFileInfo::MainWindowUiFile:
            data = readBlob(path(MainWindowUiOrigin), errorMessage);
            break;
        default:
            Q_ASSERT_X(false, Q_FUNC_INFO, "Whoops, case missing!");
    }
    return data;
}

QString MobileApp::originsRoot() const
{
    return templatesRoot() + QLatin1String("mobileapp/");
}

QString MobileApp::mainWindowClassName() const
{
    return QLatin1String("MainWindow");
}

int MobileApp::stubVersionMinor() const { return StubVersion; }

QList<AbstractGeneratedFileInfo> MobileApp::updateableFiles(const QString &mainProFile) const
{
    Q_UNUSED(mainProFile)
    return QList<AbstractGeneratedFileInfo>(); // Nothing to update, here
}

QList<DeploymentFolder> MobileApp::deploymentFolders() const
{
    QList<DeploymentFolder> result;
    return result;
}

const int MobileApp::StubVersion = 2;

} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|>