<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: view.hxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: vg $ $Date: 2006-11-22 10:40:27 $
 *
 *  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 VIEW_HXX
#define VIEW_HXX

#ifndef _SFXDOCKWIN_HXX //autogen
#include <sfx2/dockwin.hxx>
#endif
#ifndef _SFXVIEWSH_HXX //autogen
#include <sfx2/viewsh.hxx>
#endif
#ifndef _SCRWIN_HXX //autogen
#include <svtools/scrwin.hxx>
#endif
#ifndef _SFXCTRLITEM_HXX //autogen
#include <sfx2/ctrlitem.hxx>
#endif
#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif
#ifndef _VIEWFAC_HXX //autogen
#include <sfx2/viewfac.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_COLORCFG_HXX
#include <svtools/colorcfg.hxx>
#endif

#ifndef EDIT_HXX
#include "edit.hxx"
#endif
#ifndef NODE_HXX
#include "node.hxx"
#endif
#ifndef _ACCESSIBILITY_HXX_
#include "accessibility.hxx"
#endif

class Menu;
class DataChangedEvent;
class SmClipboardChangeListener;
class SmDocShell;
class SmViewShell;

/**************************************************************************/

class SmGraphicWindow : public ScrollableWindow
{
    Point           aFormulaDrawPos;
    Rectangle       aCursorRect;

    ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible >  xAccessible;
    SmGraphicAccessible *                                       pAccessible;

    SmViewShell    *pViewShell;
    USHORT          nZoom;
    short           nModifyCount;
    BOOL            bIsCursorVisible;

protected:
    void        SetFormulaDrawPos(const Point &rPos) { aFormulaDrawPos = rPos; }
    void        SetIsCursorVisible(BOOL bVis) { bIsCursorVisible = bVis; }
    void        SetCursor(const SmNode *pNode);
    void        SetCursor(const Rectangle &rRect);

    virtual void DataChanged( const DataChangedEvent& );
    virtual void Paint(const Rectangle&);
    virtual void KeyInput(const KeyEvent& rKEvt);
    virtual void Command(const CommandEvent& rCEvt);
    virtual void StateChanged( StateChangedType eChanged );
    DECL_LINK(MenuSelectHdl, Menu *);

public:
    SmGraphicWindow(SmViewShell* pShell);
    ~SmGraphicWindow();

    // Window
    virtual void    MouseButtonDown(const MouseEvent &rMEvt);
    virtual void    GetFocus();
    virtual void    LoseFocus();

    SmViewShell *   GetView()   { return pViewShell; }

    void   SetZoom(USHORT Factor);
    USHORT GetZoom() const { return nZoom; }

    const Point &   GetFormulaDrawPos() const { return aFormulaDrawPos; }

    void ZoomToFitInWindow();
    void SetTotalSize();

    BOOL IsCursorVisible() const { return bIsCursorVisible; }
    void ShowCursor(BOOL bShow);
    const SmNode * SetCursorPos(USHORT nRow, USHORT nCol);

    void ApplyColorConfigValues( const svtools::ColorConfig &rColorCfg );

    // for Accessibility
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();

    SmGraphicAccessible *   GetAccessible()  { return pAccessible; }
};

/**************************************************************************/

class SmGraphicController: public SfxControllerItem
{
protected:
    SmGraphicWindow &rGraphic;
public:
    SmGraphicController(SmGraphicWindow &, USHORT, SfxBindings & );
    virtual void StateChanged(USHORT             nSID,
                              SfxItemState       eState,
                              const SfxPoolItem* pState);
};

/**************************************************************************/

class SmEditController: public SfxControllerItem
{
protected:
    SmEditWindow &rEdit;

public:
    SmEditController(SmEditWindow &, USHORT, SfxBindings  & );
#if OSL_DEBUG_LEVEL > 1
    virtual ~SmEditController();
#endif

    virtual void StateChanged(USHORT             nSID,
                              SfxItemState       eState,
                              const SfxPoolItem* pState);
};

/**************************************************************************/

class SmCmdBoxWindow : public SfxDockingWindow
{
    SmEditWindow        aEdit;
    SmEditController    aController;
    BOOL                bExiting;

protected :

    // Window
    virtual void    GetFocus();
    virtual void Resize();
    virtual void Paint(const Rectangle& rRect);
    virtual void StateChanged( StateChangedType nStateChange );

    virtual Size CalcDockingSize(SfxChildAlignment eAlign);
    virtual SfxChildAlignment CheckAlignment(SfxChildAlignment eActual,
                                             SfxChildAlignment eWish);

    virtual void    ToggleFloatingMode();

public:
    SmCmdBoxWindow(SfxBindings    *pBindings,
                   SfxChildWindow *pChildWindow,
                   Window         *pParent);

    virtual ~SmCmdBoxWindow ();

    void AdjustPosition();

    SmEditWindow *GetEditWindow() { return (&aEdit); }
    SmViewShell  *GetView();
};

/**************************************************************************/

class SmCmdBoxWrapper : public SfxChildWindow
{
    SFX_DECL_CHILDWINDOW(SmCmdBoxWrapper);

protected:
    SmCmdBoxWrapper(Window          *pParentWindow,
                    USHORT           nId,
                    SfxBindings     *pBindings,
                    SfxChildWinInfo *pInfo);

#if OSL_DEBUG_LEVEL > 1
    virtual ~SmCmdBoxWrapper();
#endif

public:

    SmEditWindow *GetEditWindow()
    {
        return (((SmCmdBoxWindow *)pWindow)->GetEditWindow());
    }

};

/**************************************************************************/

namespace sfx2 { class FileDialogHelper; }
struct SmViewShell_Impl;

class SmViewShell: public SfxViewShell
{
    // for handling the PasteClipboardState
    friend class SmClipboardChangeListener;

    SmGraphicWindow     aGraphic;
    SmGraphicController aGraphicController;
    String              StatusText;

    ::com::sun::star::uno:: Reference <
            ::com::sun::star::lang:: XEventListener > xClipEvtLstnr;
    SmClipboardChangeListener*  pClipEvtLstnr;
    SmViewShell_Impl*   pImpl;
    BOOL                bPasteState;

    void AddRemoveClipboardListener( BOOL bAdd );

    DECL_LINK( DialogClosedHdl, sfx2::FileDialogHelper* );

protected:

    Size GetTextLineSize(OutputDevice& rDevice,
                         const String& rLine);
    Size GetTextSize(OutputDevice& rDevice,
                     const String& rText,
                     long          MaxWidth);
    void DrawTextLine(OutputDevice& rDevice,
                      const Point&  rPosition,
                      const String& rLine);
    void DrawText(OutputDevice& rDevice,
                  const Point&  rPosition,
                  const String& rText,
                  USHORT        MaxWidth);

    virtual USHORT Print(SfxProgress &rProgress,
                         PrintDialog *pPrintDialog = 0);
    virtual SfxPrinter *GetPrinter(BOOL bCreate = FALSE);
    virtual USHORT SetPrinter(SfxPrinter *pNewPrinter,
                              USHORT     nDiffFlags = SFX_PRINTER_ALL);

    BOOL        Insert( SfxMedium& rMedium );
    BOOL        InsertFrom(SfxMedium &rMedium);

    virtual SfxTabPage *CreatePrintOptionsPage(Window           *pParent,
                                               const SfxItemSet &rOptions);
    virtual void Deactivate(BOOL IsMDIActivate);
    virtual void Activate(BOOL IsMDIActivate);
    virtual Size GetOptimalSizePixel() const;
    virtual void AdjustPosSizePixel(const Point &rPos, const Size &rSize);
    virtual void InnerResizePixel(const Point &rOfs, const Size  &rSize);
    virtual void OuterResizePixel(const Point &rOfs, const Size  &rSize);
    virtual void QueryObjAreaPixel( Rectangle& rRect ) const;
    virtual void SetZoomFactor( const Fraction &rX, const Fraction &rY );

public:
    TYPEINFO();

    SmViewShell(SfxViewFrame *pFrame, SfxViewShell *pOldSh);
    ~SmViewShell();

    SmDocShell * GetDoc()
    {
        return (SmDocShell *) GetViewFrame()->GetObjectShell();
    }

    SmEditWindow * GetEditWindow();
          SmGraphicWindow & GetGraphicWindow()       { return aGraphic; }
    const SmGraphicWindow & GetGraphicWindow() const { return aGraphic; }

    void        SetStatusText(const String& Text);

    void        ShowError( const SmErrorDesc *pErrorDesc );
    void        NextError();
    void        PrevError();

    SFX_DECL_INTERFACE(SFX_INTERFACE_SMA_START+2);
    SFX_DECL_VIEWFACTORY(SmViewShell);

    virtual void Execute( SfxRequest& rReq );
    virtual void GetState(SfxItemSet &);

    void Impl_Print( OutputDevice &rOutDev, const SmPrintSize ePrintSize,
                     Rectangle aOutRect, Point aZeroPoint );
};

#endif

<commit_msg>INTEGRATION: CWS mbafixesfor22 (1.19.12); FILE MERGED 2007/01/16 11:27:23 mba 1.19.12.1: #i64552#: pass bIsAPI to every print call<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: view.hxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: obo $ $Date: 2007-01-25 11:35:16 $
 *
 *  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 VIEW_HXX
#define VIEW_HXX

#ifndef _SFXDOCKWIN_HXX //autogen
#include <sfx2/dockwin.hxx>
#endif
#ifndef _SFXVIEWSH_HXX //autogen
#include <sfx2/viewsh.hxx>
#endif
#ifndef _SCRWIN_HXX //autogen
#include <svtools/scrwin.hxx>
#endif
#ifndef _SFXCTRLITEM_HXX //autogen
#include <sfx2/ctrlitem.hxx>
#endif
#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif
#ifndef _VIEWFAC_HXX //autogen
#include <sfx2/viewfac.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_COLORCFG_HXX
#include <svtools/colorcfg.hxx>
#endif

#ifndef EDIT_HXX
#include "edit.hxx"
#endif
#ifndef NODE_HXX
#include "node.hxx"
#endif
#ifndef _ACCESSIBILITY_HXX_
#include "accessibility.hxx"
#endif

class Menu;
class DataChangedEvent;
class SmClipboardChangeListener;
class SmDocShell;
class SmViewShell;

/**************************************************************************/

class SmGraphicWindow : public ScrollableWindow
{
    Point           aFormulaDrawPos;
    Rectangle       aCursorRect;

    ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible >  xAccessible;
    SmGraphicAccessible *                                       pAccessible;

    SmViewShell    *pViewShell;
    USHORT          nZoom;
    short           nModifyCount;
    BOOL            bIsCursorVisible;

protected:
    void        SetFormulaDrawPos(const Point &rPos) { aFormulaDrawPos = rPos; }
    void        SetIsCursorVisible(BOOL bVis) { bIsCursorVisible = bVis; }
    void        SetCursor(const SmNode *pNode);
    void        SetCursor(const Rectangle &rRect);

    virtual void DataChanged( const DataChangedEvent& );
    virtual void Paint(const Rectangle&);
    virtual void KeyInput(const KeyEvent& rKEvt);
    virtual void Command(const CommandEvent& rCEvt);
    virtual void StateChanged( StateChangedType eChanged );
    DECL_LINK(MenuSelectHdl, Menu *);

public:
    SmGraphicWindow(SmViewShell* pShell);
    ~SmGraphicWindow();

    // Window
    virtual void    MouseButtonDown(const MouseEvent &rMEvt);
    virtual void    GetFocus();
    virtual void    LoseFocus();

    SmViewShell *   GetView()   { return pViewShell; }

    void   SetZoom(USHORT Factor);
    USHORT GetZoom() const { return nZoom; }

    const Point &   GetFormulaDrawPos() const { return aFormulaDrawPos; }

    void ZoomToFitInWindow();
    void SetTotalSize();

    BOOL IsCursorVisible() const { return bIsCursorVisible; }
    void ShowCursor(BOOL bShow);
    const SmNode * SetCursorPos(USHORT nRow, USHORT nCol);

    void ApplyColorConfigValues( const svtools::ColorConfig &rColorCfg );

    // for Accessibility
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();

    SmGraphicAccessible *   GetAccessible()  { return pAccessible; }
};

/**************************************************************************/

class SmGraphicController: public SfxControllerItem
{
protected:
    SmGraphicWindow &rGraphic;
public:
    SmGraphicController(SmGraphicWindow &, USHORT, SfxBindings & );
    virtual void StateChanged(USHORT             nSID,
                              SfxItemState       eState,
                              const SfxPoolItem* pState);
};

/**************************************************************************/

class SmEditController: public SfxControllerItem
{
protected:
    SmEditWindow &rEdit;

public:
    SmEditController(SmEditWindow &, USHORT, SfxBindings  & );
#if OSL_DEBUG_LEVEL > 1
    virtual ~SmEditController();
#endif

    virtual void StateChanged(USHORT             nSID,
                              SfxItemState       eState,
                              const SfxPoolItem* pState);
};

/**************************************************************************/

class SmCmdBoxWindow : public SfxDockingWindow
{
    SmEditWindow        aEdit;
    SmEditController    aController;
    BOOL                bExiting;

protected :

    // Window
    virtual void    GetFocus();
    virtual void Resize();
    virtual void Paint(const Rectangle& rRect);
    virtual void StateChanged( StateChangedType nStateChange );

    virtual Size CalcDockingSize(SfxChildAlignment eAlign);
    virtual SfxChildAlignment CheckAlignment(SfxChildAlignment eActual,
                                             SfxChildAlignment eWish);

    virtual void    ToggleFloatingMode();

public:
    SmCmdBoxWindow(SfxBindings    *pBindings,
                   SfxChildWindow *pChildWindow,
                   Window         *pParent);

    virtual ~SmCmdBoxWindow ();

    void AdjustPosition();

    SmEditWindow *GetEditWindow() { return (&aEdit); }
    SmViewShell  *GetView();
};

/**************************************************************************/

class SmCmdBoxWrapper : public SfxChildWindow
{
    SFX_DECL_CHILDWINDOW(SmCmdBoxWrapper);

protected:
    SmCmdBoxWrapper(Window          *pParentWindow,
                    USHORT           nId,
                    SfxBindings     *pBindings,
                    SfxChildWinInfo *pInfo);

#if OSL_DEBUG_LEVEL > 1
    virtual ~SmCmdBoxWrapper();
#endif

public:

    SmEditWindow *GetEditWindow()
    {
        return (((SmCmdBoxWindow *)pWindow)->GetEditWindow());
    }

};

/**************************************************************************/

namespace sfx2 { class FileDialogHelper; }
struct SmViewShell_Impl;

class SmViewShell: public SfxViewShell
{
    // for handling the PasteClipboardState
    friend class SmClipboardChangeListener;

    SmGraphicWindow     aGraphic;
    SmGraphicController aGraphicController;
    String              StatusText;

    ::com::sun::star::uno:: Reference <
            ::com::sun::star::lang:: XEventListener > xClipEvtLstnr;
    SmClipboardChangeListener*  pClipEvtLstnr;
    SmViewShell_Impl*   pImpl;
    BOOL                bPasteState;

    void AddRemoveClipboardListener( BOOL bAdd );

    DECL_LINK( DialogClosedHdl, sfx2::FileDialogHelper* );

protected:

    Size GetTextLineSize(OutputDevice& rDevice,
                         const String& rLine);
    Size GetTextSize(OutputDevice& rDevice,
                     const String& rText,
                     long          MaxWidth);
    void DrawTextLine(OutputDevice& rDevice,
                      const Point&  rPosition,
                      const String& rLine);
    void DrawText(OutputDevice& rDevice,
                  const Point&  rPosition,
                  const String& rText,
                  USHORT        MaxWidth);

    virtual USHORT Print(SfxProgress &rProgress, BOOL bIsAPI, PrintDialog *pPrintDialog = 0);
    virtual SfxPrinter *GetPrinter(BOOL bCreate = FALSE);
    virtual USHORT SetPrinter(SfxPrinter *pNewPrinter,
                              USHORT     nDiffFlags = SFX_PRINTER_ALL);

    BOOL        Insert( SfxMedium& rMedium );
    BOOL        InsertFrom(SfxMedium &rMedium);

    virtual SfxTabPage *CreatePrintOptionsPage(Window           *pParent,
                                               const SfxItemSet &rOptions);
    virtual void Deactivate(BOOL IsMDIActivate);
    virtual void Activate(BOOL IsMDIActivate);
    virtual Size GetOptimalSizePixel() const;
    virtual void AdjustPosSizePixel(const Point &rPos, const Size &rSize);
    virtual void InnerResizePixel(const Point &rOfs, const Size  &rSize);
    virtual void OuterResizePixel(const Point &rOfs, const Size  &rSize);
    virtual void QueryObjAreaPixel( Rectangle& rRect ) const;
    virtual void SetZoomFactor( const Fraction &rX, const Fraction &rY );

public:
    TYPEINFO();

    SmViewShell(SfxViewFrame *pFrame, SfxViewShell *pOldSh);
    ~SmViewShell();

    SmDocShell * GetDoc()
    {
        return (SmDocShell *) GetViewFrame()->GetObjectShell();
    }

    SmEditWindow * GetEditWindow();
          SmGraphicWindow & GetGraphicWindow()       { return aGraphic; }
    const SmGraphicWindow & GetGraphicWindow() const { return aGraphic; }

    void        SetStatusText(const String& Text);

    void        ShowError( const SmErrorDesc *pErrorDesc );
    void        NextError();
    void        PrevError();

    SFX_DECL_INTERFACE(SFX_INTERFACE_SMA_START+2);
    SFX_DECL_VIEWFACTORY(SmViewShell);

    virtual void Execute( SfxRequest& rReq );
    virtual void GetState(SfxItemSet &);

    void Impl_Print( OutputDevice &rOutDev, const SmPrintSize ePrintSize,
                     Rectangle aOutRect, Point aZeroPoint );
};

#endif

<|endoftext|>


<commit_before>/*
 * This file is part of telepathy-accounts-kcm
 *
 * Copyright (C) 2012 Daniele E. Domenichelli <daniele.domenichelli@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "edit-display-name-button.h"

#include <QtGui/QVBoxLayout>
#include <QtGui/QLabel>

#include <KDE/KDialog>
#include <KDE/KLineEdit>
#include <KDE/KLocalizedString>
#include <KDE/KDebug>

#include <TelepathyQt/Account>
#include <TelepathyQt/PendingOperation>

class EditDisplayNameDialog : public KDialog
{
    Q_OBJECT
    Q_DISABLE_COPY(EditDisplayNameDialog)

public:
    EditDisplayNameDialog(Tp::AccountPtr account,
                          QWidget* parent = 0,
                          Qt::WFlags flags = 0);
    virtual ~EditDisplayNameDialog();

    QString displayName() const;

private Q_SLOTS:
    void onTextChanged(const QString &text);

private:
    Tp::AccountPtr m_account;
    KLineEdit *m_displayNameLineEdit;
};

EditDisplayNameDialog::EditDisplayNameDialog(Tp::AccountPtr account,
                                             QWidget* parent,
                                             Qt::WFlags flags)
    : KDialog(parent, flags),
      m_account(account)
{
    setCaption(i18n("Edit display name"));
    setButtons( KDialog::Ok | KDialog::Cancel );
    setWindowIcon(KIcon(QLatin1String("telepathy-kde")));
    setFixedSize(400, 150);
    enableButtonOk(false);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    QHBoxLayout *topLayout = new QHBoxLayout(this);

    QLabel *topLabel = new QLabel(i18n("Choose a new display name for your account"), this);
    QFont font = topLabel->font();
    font.setBold(true);
    topLabel->setFont(font);
    topLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);

    QLabel *icon = new QLabel;
    icon->setPixmap(KIcon(account->iconName()).pixmap(KIconLoader::SizeMedium));
    icon->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);

    topLayout->addWidget(topLabel);
    topLayout->addWidget(icon);

    mainLayout->addLayout(topLayout);

    m_displayNameLineEdit = new KLineEdit(account->displayName(), this);
    mainLayout->addWidget(m_displayNameLineEdit);

    QLabel *bottomLabel = new QLabel(i18n("A display name is your local alias for the account, only you will see it."), this);
    mainLayout->addWidget(bottomLabel);

    QWidget * mainWidget = new QWidget(this);
    mainWidget->setLayout(mainLayout);
    setMainWidget(mainWidget);

    connect(m_displayNameLineEdit, SIGNAL(textChanged(QString)), SLOT(onTextChanged(QString)));
}

EditDisplayNameDialog::~EditDisplayNameDialog()
{
}

void EditDisplayNameDialog::onTextChanged(const QString& text)
{
    enableButtonOk(text != m_account->displayName());
}

QString EditDisplayNameDialog::displayName() const
{
    return m_displayNameLineEdit->text();
}

EditDisplayNameButton::EditDisplayNameButton(QWidget* parent) :
    KPushButton(parent)
{
    connect(this,
            SIGNAL(clicked(bool)),
            SLOT(onClicked()));
}

EditDisplayNameButton::~EditDisplayNameButton()
{
}

void EditDisplayNameButton::setAccount(Tp::AccountPtr account)
{
    m_account = account;
}

Tp::AccountPtr EditDisplayNameButton::account() const
{
    return m_account;
}

void EditDisplayNameButton::onClicked()
{
    if (!m_account.isNull() && m_account->isValid()) {
        EditDisplayNameDialog *dialog = new EditDisplayNameDialog(m_account, this);
        dialog->exec();
        if (dialog->result() == KDialog::Accepted) {
            kDebug() << "Setting display name" << dialog->displayName() << "for account" << account()->uniqueIdentifier();
            Tp::PendingOperation *op = m_account->setDisplayName(dialog->displayName());
            connect(op, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onFinished(Tp::PendingOperation*)));
        }
    }
}

void EditDisplayNameButton::onFinished(Tp::PendingOperation* op)
{
    if (op->isError()) {
        kWarning() << "Cannot set display name" << op->errorName() << op->errorMessage();
    }
}

#include "edit-display-name-button.moc"
#include "moc_edit-display-name-button.cpp"
<commit_msg>Capitalize window title<commit_after>/*
 * This file is part of telepathy-accounts-kcm
 *
 * Copyright (C) 2012 Daniele E. Domenichelli <daniele.domenichelli@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "edit-display-name-button.h"

#include <QtGui/QVBoxLayout>
#include <QtGui/QLabel>

#include <KDE/KDialog>
#include <KDE/KLineEdit>
#include <KDE/KLocalizedString>
#include <KDE/KDebug>

#include <TelepathyQt/Account>
#include <TelepathyQt/PendingOperation>

class EditDisplayNameDialog : public KDialog
{
    Q_OBJECT
    Q_DISABLE_COPY(EditDisplayNameDialog)

public:
    EditDisplayNameDialog(Tp::AccountPtr account,
                          QWidget* parent = 0,
                          Qt::WFlags flags = 0);
    virtual ~EditDisplayNameDialog();

    QString displayName() const;

private Q_SLOTS:
    void onTextChanged(const QString &text);

private:
    Tp::AccountPtr m_account;
    KLineEdit *m_displayNameLineEdit;
};

EditDisplayNameDialog::EditDisplayNameDialog(Tp::AccountPtr account,
                                             QWidget* parent,
                                             Qt::WFlags flags)
    : KDialog(parent, flags),
      m_account(account)
{
    setCaption(i18n("Edit Display Name"));
    setButtons( KDialog::Ok | KDialog::Cancel );
    setWindowIcon(KIcon(QLatin1String("telepathy-kde")));
    setFixedSize(400, 150);
    enableButtonOk(false);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    QHBoxLayout *topLayout = new QHBoxLayout(this);

    QLabel *topLabel = new QLabel(i18n("Choose a new display name for your account"), this);
    QFont font = topLabel->font();
    font.setBold(true);
    topLabel->setFont(font);
    topLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);

    QLabel *icon = new QLabel;
    icon->setPixmap(KIcon(account->iconName()).pixmap(KIconLoader::SizeMedium));
    icon->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);

    topLayout->addWidget(topLabel);
    topLayout->addWidget(icon);

    mainLayout->addLayout(topLayout);

    m_displayNameLineEdit = new KLineEdit(account->displayName(), this);
    mainLayout->addWidget(m_displayNameLineEdit);

    QLabel *bottomLabel = new QLabel(i18n("A display name is your local alias for the account, only you will see it."), this);
    mainLayout->addWidget(bottomLabel);

    QWidget * mainWidget = new QWidget(this);
    mainWidget->setLayout(mainLayout);
    setMainWidget(mainWidget);

    connect(m_displayNameLineEdit, SIGNAL(textChanged(QString)), SLOT(onTextChanged(QString)));
}

EditDisplayNameDialog::~EditDisplayNameDialog()
{
}

void EditDisplayNameDialog::onTextChanged(const QString& text)
{
    enableButtonOk(text != m_account->displayName());
}

QString EditDisplayNameDialog::displayName() const
{
    return m_displayNameLineEdit->text();
}

EditDisplayNameButton::EditDisplayNameButton(QWidget* parent) :
    KPushButton(parent)
{
    connect(this,
            SIGNAL(clicked(bool)),
            SLOT(onClicked()));
}

EditDisplayNameButton::~EditDisplayNameButton()
{
}

void EditDisplayNameButton::setAccount(Tp::AccountPtr account)
{
    m_account = account;
}

Tp::AccountPtr EditDisplayNameButton::account() const
{
    return m_account;
}

void EditDisplayNameButton::onClicked()
{
    if (!m_account.isNull() && m_account->isValid()) {
        EditDisplayNameDialog *dialog = new EditDisplayNameDialog(m_account, this);
        dialog->exec();
        if (dialog->result() == KDialog::Accepted) {
            kDebug() << "Setting display name" << dialog->displayName() << "for account" << account()->uniqueIdentifier();
            Tp::PendingOperation *op = m_account->setDisplayName(dialog->displayName());
            connect(op, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onFinished(Tp::PendingOperation*)));
        }
    }
}

void EditDisplayNameButton::onFinished(Tp::PendingOperation* op)
{
    if (op->isError()) {
        kWarning() << "Cannot set display name" << op->errorName() << op->errorMessage();
    }
}

#include "edit-display-name-button.moc"
#include "moc_edit-display-name-button.cpp"
<|endoftext|>


<commit_before>
/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBlurMaskFilter.h"
#include "SkBlurMask.h"
#include "SkFlattenableBuffers.h"
#include "SkMaskFilter.h"

class SkBlurMaskFilterImpl : public SkMaskFilter {
public:
    SkBlurMaskFilterImpl(SkScalar radius, SkBlurMaskFilter::BlurStyle,
                         uint32_t flags);

    // overrides from SkMaskFilter
    virtual SkMask::Format getFormat() SK_OVERRIDE;
    virtual bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&,
                            SkIPoint* margin) SK_OVERRIDE;
    virtual BlurType asABlur(BlurInfo*) const SK_OVERRIDE;
    virtual void setAsABlur(const BlurInfo&) SK_OVERRIDE;
    virtual void computeFastBounds(const SkRect& src, SkRect* dst) SK_OVERRIDE;

    SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkBlurMaskFilterImpl)

protected:
    virtual FilterReturn filterRectsToNine(const SkRect[], int count, const SkMatrix&,
                                           const SkIRect& clipBounds,
                                           NinePatch*) SK_OVERRIDE;

private:
    SkScalar                    fRadius;
    SkBlurMaskFilter::BlurStyle fBlurStyle;
    uint32_t                    fBlurFlags;

    SkBlurMaskFilterImpl(SkFlattenableReadBuffer&);
    virtual void flatten(SkFlattenableWriteBuffer&) const SK_OVERRIDE;

    typedef SkMaskFilter INHERITED;
};

SkMaskFilter* SkBlurMaskFilter::Create(SkScalar radius,
                                       SkBlurMaskFilter::BlurStyle style,
                                       uint32_t flags) {
    // use !(radius > 0) instead of radius <= 0 to reject NaN values
    if (!(radius > 0) || (unsigned)style >= SkBlurMaskFilter::kBlurStyleCount
        || flags > SkBlurMaskFilter::kAll_BlurFlag) {
        return NULL;
    }

    return SkNEW_ARGS(SkBlurMaskFilterImpl, (radius, style, flags));
}

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

SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkScalar radius,
                                           SkBlurMaskFilter::BlurStyle style,
                                           uint32_t flags)
    : fRadius(radius), fBlurStyle(style), fBlurFlags(flags) {
#if 0
    fGamma = NULL;
    if (gammaScale) {
        fGamma = new U8[256];
        if (gammaScale > 0)
            SkBlurMask::BuildSqrGamma(fGamma, gammaScale);
        else
            SkBlurMask::BuildSqrtGamma(fGamma, -gammaScale);
    }
#endif
    SkASSERT(radius >= 0);
    SkASSERT((unsigned)style < SkBlurMaskFilter::kBlurStyleCount);
    SkASSERT(flags <= SkBlurMaskFilter::kAll_BlurFlag);
}

SkMask::Format SkBlurMaskFilterImpl::getFormat() {
    return SkMask::kA8_Format;
}

bool SkBlurMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src,
                                      const SkMatrix& matrix, SkIPoint* margin) {
    SkScalar radius;
    if (fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag) {
        radius = fRadius;
    } else {
        radius = matrix.mapRadius(fRadius);
    }

    // To avoid unseemly allocation requests (esp. for finite platforms like
    // handset) we limit the radius so something manageable. (as opposed to
    // a request like 10,000)
    static const SkScalar MAX_RADIUS = SkIntToScalar(128);
    radius = SkMinScalar(radius, MAX_RADIUS);
    SkBlurMask::Quality blurQuality =
        (fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag) ?
            SkBlurMask::kHigh_Quality : SkBlurMask::kLow_Quality;

    if (fBlurFlags & SkBlurMaskFilter::kCoarseRadius_BlurFlag) {
        return SkBlurMask::BlurSeparable(dst, src, radius, (SkBlurMask::Style)fBlurStyle,
                                blurQuality, margin);
    } else {
        return SkBlurMask::Blur(dst, src, radius, (SkBlurMask::Style)fBlurStyle,
                                blurQuality, margin);
    }
}

#include "SkCanvas.h"

static bool drawRectsIntoMask(const SkRect rects[], int count, SkMask* mask) {
    rects[0].roundOut(&mask->fBounds);
    mask->fRowBytes = SkAlign4(mask->fBounds.width());
    mask->fFormat = SkMask::kA8_Format;
    size_t size = mask->computeImageSize();
    mask->fImage = SkMask::AllocImage(size);
    if (NULL == mask->fImage) {
        return false;
    }
    sk_bzero(mask->fImage, size);

    SkBitmap bitmap;
    bitmap.setConfig(SkBitmap::kA8_Config,
                     mask->fBounds.width(), mask->fBounds.height(),
                     mask->fRowBytes);
    bitmap.setPixels(mask->fImage);

    SkCanvas canvas(bitmap);
    canvas.translate(-SkIntToScalar(mask->fBounds.left()),
                     -SkIntToScalar(mask->fBounds.top()));

    SkPaint paint;
    paint.setAntiAlias(true);

    if (1 == count) {
        canvas.drawRect(rects[0], paint);
    } else {
        // todo: do I need a fast way to do this?
        SkPath path;
        path.addRect(rects[0]);
        path.addRect(rects[1]);
        path.setFillType(SkPath::kEvenOdd_FillType);
        canvas.drawPath(path, paint);
    }
    return true;
}

static bool rect_exceeds(const SkRect& r, SkScalar v) {
    return r.fLeft < -v || r.fTop < -v || r.fRight > v || r.fBottom > v ||
           r.width() > v || r.height() > v;
}

SkMaskFilter::FilterReturn
SkBlurMaskFilterImpl::filterRectsToNine(const SkRect rects[], int count,
                                        const SkMatrix& matrix,
                                        const SkIRect& clipBounds,
                                        NinePatch* patch) {
    if (count < 1 || count > 2) {
        return kUnimplemented_FilterReturn;
    }

    // TODO: take clipBounds into account to limit our coordinates up front
    // for now, just skip too-large src rects (to take the old code path).
    if (rect_exceeds(rects[0], SkIntToScalar(32767))) {
        return kUnimplemented_FilterReturn;
    }

    SkIPoint margin;
    SkMask  srcM, dstM;
    rects[0].roundOut(&srcM.fBounds);
    srcM.fImage = NULL;
    srcM.fFormat = SkMask::kA8_Format;
    srcM.fRowBytes = 0;
    if (!this->filterMask(&dstM, srcM, matrix, &margin)) {
        return kFalse_FilterReturn;
    }

    /*
     *  smallR is the smallest version of 'rect' that will still guarantee that
     *  we get the same blur results on all edges, plus 1 center row/col that is
     *  representative of the extendible/stretchable edges of the ninepatch.
     *  Since our actual edge may be fractional we inset 1 more to be sure we
     *  don't miss any interior blur.
     *  x is an added pixel of blur, and { and } are the (fractional) edge
     *  pixels from the original rect.
     *
     *   x x { x x .... x x } x x
     *
     *  Thus, in this case, we inset by a total of 5 (on each side) beginning
     *  with our outer-rect (dstM.fBounds)
     */
    SkRect smallR[2];
    SkIPoint center;

    // +2 is from +1 for each edge (to account for possible fractional edges
    int smallW = dstM.fBounds.width() - srcM.fBounds.width() + 2;
    int smallH = dstM.fBounds.height() - srcM.fBounds.height() + 2;
    SkIRect innerIR;

    if (1 == count) {
        innerIR = srcM.fBounds;
        center.set(smallW, smallH);
    } else {
        SkASSERT(2 == count);
        rects[1].roundIn(&innerIR);
        center.set(smallW + (innerIR.left() - srcM.fBounds.left()),
                   smallH + (innerIR.top() - srcM.fBounds.top()));
    }

    // +1 so we get a clean, stretchable, center row/col
    smallW += 1;
    smallH += 1;

    // we want the inset amounts to be integral, so we don't change any
    // fractional phase on the fRight or fBottom of our smallR.
    const SkScalar dx = SkIntToScalar(innerIR.width() - smallW);
    const SkScalar dy = SkIntToScalar(innerIR.height() - smallH);
    if (dx < 0 || dy < 0) {
        // we're too small, relative to our blur, to break into nine-patch,
        // so we ask to have our normal filterMask() be called.
        return kUnimplemented_FilterReturn;
    }

    smallR[0].set(rects[0].left(), rects[0].top(), rects[0].right() - dx, rects[0].bottom() - dy);
    SkASSERT(!smallR[0].isEmpty());
    if (2 == count) {
        smallR[1].set(rects[1].left(), rects[1].top(),
                      rects[1].right() - dx, rects[1].bottom() - dy);
        SkASSERT(!smallR[1].isEmpty());
    }

    if (!drawRectsIntoMask(smallR, count, &srcM)) {
        return kFalse_FilterReturn;
    }

    if (!this->filterMask(&patch->fMask, srcM, matrix, &margin)) {
        return kFalse_FilterReturn;
    }
    patch->fMask.fBounds.offsetTo(0, 0);
    patch->fOuterRect = dstM.fBounds;
    patch->fCenter = center;
    return kTrue_FilterReturn;
}

void SkBlurMaskFilterImpl::computeFastBounds(const SkRect& src, SkRect* dst) {
    dst->set(src.fLeft - fRadius, src.fTop - fRadius,
             src.fRight + fRadius, src.fBottom + fRadius);
}

SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkFlattenableReadBuffer& buffer)
        : SkMaskFilter(buffer) {
    fRadius = buffer.readScalar();
    fBlurStyle = (SkBlurMaskFilter::BlurStyle)buffer.readInt();
    fBlurFlags = buffer.readUInt() & SkBlurMaskFilter::kAll_BlurFlag;
    SkASSERT(fRadius >= 0);
    SkASSERT((unsigned)fBlurStyle < SkBlurMaskFilter::kBlurStyleCount);
}

void SkBlurMaskFilterImpl::flatten(SkFlattenableWriteBuffer& buffer) const {
    this->INHERITED::flatten(buffer);
    buffer.writeScalar(fRadius);
    buffer.writeInt(fBlurStyle);
    buffer.writeUInt(fBlurFlags);
}

static const SkMaskFilter::BlurType gBlurStyle2BlurType[] = {
    SkMaskFilter::kNormal_BlurType,
    SkMaskFilter::kSolid_BlurType,
    SkMaskFilter::kOuter_BlurType,
    SkMaskFilter::kInner_BlurType,
};

SkMaskFilter::BlurType SkBlurMaskFilterImpl::asABlur(BlurInfo* info) const {
    if (info) {
        info->fRadius = fRadius;
        info->fIgnoreTransform = SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag);
        info->fHighQuality = SkToBool(fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag);
    }
    return gBlurStyle2BlurType[fBlurStyle];
}

void SkBlurMaskFilterImpl::setAsABlur(const BlurInfo& info) {
    fRadius = info.fRadius;
    fBlurFlags = (fBlurFlags & ~(SkBlurMaskFilter::kIgnoreTransform_BlurFlag
                                 | SkBlurMaskFilter::kHighQuality_BlurFlag))
            | (info.fIgnoreTransform ? SkBlurMaskFilter::kIgnoreTransform_BlurFlag : 0)
            | (info.fHighQuality ? SkBlurMaskFilter::kHighQuality_BlurFlag : 0);
}

SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkBlurMaskFilter)
    SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkBlurMaskFilterImpl)
SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
<commit_msg>don't leak *every* src mask in the ninepatch case. doh.<commit_after>
/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBlurMaskFilter.h"
#include "SkBlurMask.h"
#include "SkFlattenableBuffers.h"
#include "SkMaskFilter.h"

class SkBlurMaskFilterImpl : public SkMaskFilter {
public:
    SkBlurMaskFilterImpl(SkScalar radius, SkBlurMaskFilter::BlurStyle,
                         uint32_t flags);

    // overrides from SkMaskFilter
    virtual SkMask::Format getFormat() SK_OVERRIDE;
    virtual bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&,
                            SkIPoint* margin) SK_OVERRIDE;
    virtual BlurType asABlur(BlurInfo*) const SK_OVERRIDE;
    virtual void setAsABlur(const BlurInfo&) SK_OVERRIDE;
    virtual void computeFastBounds(const SkRect& src, SkRect* dst) SK_OVERRIDE;

    SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkBlurMaskFilterImpl)

protected:
    virtual FilterReturn filterRectsToNine(const SkRect[], int count, const SkMatrix&,
                                           const SkIRect& clipBounds,
                                           NinePatch*) SK_OVERRIDE;

private:
    SkScalar                    fRadius;
    SkBlurMaskFilter::BlurStyle fBlurStyle;
    uint32_t                    fBlurFlags;

    SkBlurMaskFilterImpl(SkFlattenableReadBuffer&);
    virtual void flatten(SkFlattenableWriteBuffer&) const SK_OVERRIDE;

    typedef SkMaskFilter INHERITED;
};

SkMaskFilter* SkBlurMaskFilter::Create(SkScalar radius,
                                       SkBlurMaskFilter::BlurStyle style,
                                       uint32_t flags) {
    // use !(radius > 0) instead of radius <= 0 to reject NaN values
    if (!(radius > 0) || (unsigned)style >= SkBlurMaskFilter::kBlurStyleCount
        || flags > SkBlurMaskFilter::kAll_BlurFlag) {
        return NULL;
    }

    return SkNEW_ARGS(SkBlurMaskFilterImpl, (radius, style, flags));
}

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

SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkScalar radius,
                                           SkBlurMaskFilter::BlurStyle style,
                                           uint32_t flags)
    : fRadius(radius), fBlurStyle(style), fBlurFlags(flags) {
#if 0
    fGamma = NULL;
    if (gammaScale) {
        fGamma = new U8[256];
        if (gammaScale > 0)
            SkBlurMask::BuildSqrGamma(fGamma, gammaScale);
        else
            SkBlurMask::BuildSqrtGamma(fGamma, -gammaScale);
    }
#endif
    SkASSERT(radius >= 0);
    SkASSERT((unsigned)style < SkBlurMaskFilter::kBlurStyleCount);
    SkASSERT(flags <= SkBlurMaskFilter::kAll_BlurFlag);
}

SkMask::Format SkBlurMaskFilterImpl::getFormat() {
    return SkMask::kA8_Format;
}

bool SkBlurMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src,
                                      const SkMatrix& matrix, SkIPoint* margin) {
    SkScalar radius;
    if (fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag) {
        radius = fRadius;
    } else {
        radius = matrix.mapRadius(fRadius);
    }

    // To avoid unseemly allocation requests (esp. for finite platforms like
    // handset) we limit the radius so something manageable. (as opposed to
    // a request like 10,000)
    static const SkScalar MAX_RADIUS = SkIntToScalar(128);
    radius = SkMinScalar(radius, MAX_RADIUS);
    SkBlurMask::Quality blurQuality =
        (fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag) ?
            SkBlurMask::kHigh_Quality : SkBlurMask::kLow_Quality;

    if (fBlurFlags & SkBlurMaskFilter::kCoarseRadius_BlurFlag) {
        return SkBlurMask::BlurSeparable(dst, src, radius, (SkBlurMask::Style)fBlurStyle,
                                blurQuality, margin);
    } else {
        return SkBlurMask::Blur(dst, src, radius, (SkBlurMask::Style)fBlurStyle,
                                blurQuality, margin);
    }
}

#include "SkCanvas.h"

static bool drawRectsIntoMask(const SkRect rects[], int count, SkMask* mask) {
    rects[0].roundOut(&mask->fBounds);
    mask->fRowBytes = SkAlign4(mask->fBounds.width());
    mask->fFormat = SkMask::kA8_Format;
    size_t size = mask->computeImageSize();
    mask->fImage = SkMask::AllocImage(size);
    if (NULL == mask->fImage) {
        return false;
    }
    sk_bzero(mask->fImage, size);

    SkBitmap bitmap;
    bitmap.setConfig(SkBitmap::kA8_Config,
                     mask->fBounds.width(), mask->fBounds.height(),
                     mask->fRowBytes);
    bitmap.setPixels(mask->fImage);

    SkCanvas canvas(bitmap);
    canvas.translate(-SkIntToScalar(mask->fBounds.left()),
                     -SkIntToScalar(mask->fBounds.top()));

    SkPaint paint;
    paint.setAntiAlias(true);

    if (1 == count) {
        canvas.drawRect(rects[0], paint);
    } else {
        // todo: do I need a fast way to do this?
        SkPath path;
        path.addRect(rects[0]);
        path.addRect(rects[1]);
        path.setFillType(SkPath::kEvenOdd_FillType);
        canvas.drawPath(path, paint);
    }
    return true;
}

static bool rect_exceeds(const SkRect& r, SkScalar v) {
    return r.fLeft < -v || r.fTop < -v || r.fRight > v || r.fBottom > v ||
           r.width() > v || r.height() > v;
}

SkMaskFilter::FilterReturn
SkBlurMaskFilterImpl::filterRectsToNine(const SkRect rects[], int count,
                                        const SkMatrix& matrix,
                                        const SkIRect& clipBounds,
                                        NinePatch* patch) {
    if (count < 1 || count > 2) {
        return kUnimplemented_FilterReturn;
    }

    // TODO: take clipBounds into account to limit our coordinates up front
    // for now, just skip too-large src rects (to take the old code path).
    if (rect_exceeds(rects[0], SkIntToScalar(32767))) {
        return kUnimplemented_FilterReturn;
    }

    SkIPoint margin;
    SkMask  srcM, dstM;
    rects[0].roundOut(&srcM.fBounds);
    srcM.fImage = NULL;
    srcM.fFormat = SkMask::kA8_Format;
    srcM.fRowBytes = 0;
    if (!this->filterMask(&dstM, srcM, matrix, &margin)) {
        return kFalse_FilterReturn;
    }

    /*
     *  smallR is the smallest version of 'rect' that will still guarantee that
     *  we get the same blur results on all edges, plus 1 center row/col that is
     *  representative of the extendible/stretchable edges of the ninepatch.
     *  Since our actual edge may be fractional we inset 1 more to be sure we
     *  don't miss any interior blur.
     *  x is an added pixel of blur, and { and } are the (fractional) edge
     *  pixels from the original rect.
     *
     *   x x { x x .... x x } x x
     *
     *  Thus, in this case, we inset by a total of 5 (on each side) beginning
     *  with our outer-rect (dstM.fBounds)
     */
    SkRect smallR[2];
    SkIPoint center;

    // +2 is from +1 for each edge (to account for possible fractional edges
    int smallW = dstM.fBounds.width() - srcM.fBounds.width() + 2;
    int smallH = dstM.fBounds.height() - srcM.fBounds.height() + 2;
    SkIRect innerIR;

    if (1 == count) {
        innerIR = srcM.fBounds;
        center.set(smallW, smallH);
    } else {
        SkASSERT(2 == count);
        rects[1].roundIn(&innerIR);
        center.set(smallW + (innerIR.left() - srcM.fBounds.left()),
                   smallH + (innerIR.top() - srcM.fBounds.top()));
    }

    // +1 so we get a clean, stretchable, center row/col
    smallW += 1;
    smallH += 1;

    // we want the inset amounts to be integral, so we don't change any
    // fractional phase on the fRight or fBottom of our smallR.
    const SkScalar dx = SkIntToScalar(innerIR.width() - smallW);
    const SkScalar dy = SkIntToScalar(innerIR.height() - smallH);
    if (dx < 0 || dy < 0) {
        // we're too small, relative to our blur, to break into nine-patch,
        // so we ask to have our normal filterMask() be called.
        return kUnimplemented_FilterReturn;
    }

    smallR[0].set(rects[0].left(), rects[0].top(), rects[0].right() - dx, rects[0].bottom() - dy);
    SkASSERT(!smallR[0].isEmpty());
    if (2 == count) {
        smallR[1].set(rects[1].left(), rects[1].top(),
                      rects[1].right() - dx, rects[1].bottom() - dy);
        SkASSERT(!smallR[1].isEmpty());
    }

    if (!drawRectsIntoMask(smallR, count, &srcM)) {
        return kFalse_FilterReturn;
    }

    SkAutoMaskFreeImage amf(srcM.fImage);

    if (!this->filterMask(&patch->fMask, srcM, matrix, &margin)) {
        return kFalse_FilterReturn;
    }
    patch->fMask.fBounds.offsetTo(0, 0);
    patch->fOuterRect = dstM.fBounds;
    patch->fCenter = center;
    return kTrue_FilterReturn;
}

void SkBlurMaskFilterImpl::computeFastBounds(const SkRect& src, SkRect* dst) {
    dst->set(src.fLeft - fRadius, src.fTop - fRadius,
             src.fRight + fRadius, src.fBottom + fRadius);
}

SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkFlattenableReadBuffer& buffer)
        : SkMaskFilter(buffer) {
    fRadius = buffer.readScalar();
    fBlurStyle = (SkBlurMaskFilter::BlurStyle)buffer.readInt();
    fBlurFlags = buffer.readUInt() & SkBlurMaskFilter::kAll_BlurFlag;
    SkASSERT(fRadius >= 0);
    SkASSERT((unsigned)fBlurStyle < SkBlurMaskFilter::kBlurStyleCount);
}

void SkBlurMaskFilterImpl::flatten(SkFlattenableWriteBuffer& buffer) const {
    this->INHERITED::flatten(buffer);
    buffer.writeScalar(fRadius);
    buffer.writeInt(fBlurStyle);
    buffer.writeUInt(fBlurFlags);
}

static const SkMaskFilter::BlurType gBlurStyle2BlurType[] = {
    SkMaskFilter::kNormal_BlurType,
    SkMaskFilter::kSolid_BlurType,
    SkMaskFilter::kOuter_BlurType,
    SkMaskFilter::kInner_BlurType,
};

SkMaskFilter::BlurType SkBlurMaskFilterImpl::asABlur(BlurInfo* info) const {
    if (info) {
        info->fRadius = fRadius;
        info->fIgnoreTransform = SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag);
        info->fHighQuality = SkToBool(fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag);
    }
    return gBlurStyle2BlurType[fBlurStyle];
}

void SkBlurMaskFilterImpl::setAsABlur(const BlurInfo& info) {
    fRadius = info.fRadius;
    fBlurFlags = (fBlurFlags & ~(SkBlurMaskFilter::kIgnoreTransform_BlurFlag
                                 | SkBlurMaskFilter::kHighQuality_BlurFlag))
            | (info.fIgnoreTransform ? SkBlurMaskFilter::kIgnoreTransform_BlurFlag : 0)
            | (info.fHighQuality ? SkBlurMaskFilter::kHighQuality_BlurFlag : 0);
}

SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkBlurMaskFilter)
    SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkBlurMaskFilterImpl)
SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
<|endoftext|>


<commit_before>
#ifndef __ARRAY_NODE_HPP__
#define __ARRAY_NODE_HPP__

#include <algorithm>
#include <stdio.h>

struct array_leaf_node_t;
struct array_internal_node_t;

// TODO: this shouldn't be a compile time option
#define NODE_ORDER    16

struct array_node_t {
    array_node_t(bool _leaf) : leaf(_leaf), nkeys(0) {}

    bool leaf;
    bool is_leaf() {
        return leaf;
    }
    bool is_internal() {
        return !leaf;
    }

    bool is_full() {
        return nkeys == NODE_ORDER;
    }

    typedef array_leaf_node_t leaf_node_t;
    typedef array_internal_node_t internal_node_t;

protected:
    int lookup(int key) {
        int *_value = std::lower_bound(keys, keys + nkeys, key);
        return _value - keys;
    }

protected:
    int nkeys;
    int keys[NODE_ORDER];
};

struct array_leaf_node_t : public array_node_t {
    array_leaf_node_t() : array_node_t(true) {}

#ifndef NDEBUG
    void print() {
        for(int i = 0; i < nkeys; i++) {
            printf("%d : %d, ", keys[i], values[i]);
        }
        printf("\n");
    }
#endif

    int insert(int key, int value) {
        if(nkeys == NODE_ORDER) {
            return 0;
        }
        int index = array_node_t::lookup(key);
        // TODO: handle duplicates
        // TODO: this is likely suboptimal, we might want two for
        // loops (one for keys, one for values)
        for(int i = nkeys - 1; i >= index; i--) {
            keys[i + 1] = keys[i];
            values[i + 1] = values[i];
        }
        keys[index] = key;
        values[index] = value;
        nkeys++;
        return 1;
    }

    int lookup(int key, int *value) {
        int index = array_node_t::lookup(key);
        if(index == nkeys || keys[index] != key) {
            return 0;
        } else {
            *value = values[index];
            return 1;
        }
    }

    void split(array_leaf_node_t **lnode, array_leaf_node_t **rnode, int *median) {
        *median = keys[nkeys / 2];

        // TODO: we need a good allocator here
        array_leaf_node_t *_rnode = new array_leaf_node_t();
        int rkeys = nkeys - nkeys / 2;
        memcpy(_rnode->keys, keys + nkeys / 2, rkeys * sizeof(*keys));
        memcpy(_rnode->values, values + nkeys / 2, rkeys * sizeof(*values));
        _rnode->nkeys = rkeys;

        nkeys /= 2;

        *lnode = this;
        *rnode = _rnode;
    }

private:
    int values[NODE_ORDER];
};

struct array_internal_node_t : public array_node_t  {
    array_internal_node_t() : array_node_t(false) {}

#ifndef NDEBUG
    void print() {
        printf("  ");
        for(int i = 0; i < nkeys; i++) {
            printf("%d, ", keys[i]);
        }
        printf("\n");
        for(int i = 0; i < nkeys + 1; i++) {
            printf("%d, ", (int)(long)values[i]);
        }
        printf("\n\n");
    }
#endif

    int insert(int key, array_node_t *lnode, array_node_t *rnode) {
        if(nkeys == NODE_ORDER) {
            return 0;
        }
        int index = array_node_t::lookup(key);
        // TODO: handle duplicates
        // TODO: this is likely suboptimal, we might want two for
        // loops (one for keys, one for values)
        values[nkeys + 1] = values[nkeys];
        for(int i = nkeys - 1; i >= index; i--) {
            keys[i + 1] = keys[i];
            values[i + 1] = values[i];
        }
        keys[index] = key;
        values[index] = lnode;
        values[index + 1] = rnode;
        nkeys++;
        return 1;
    }

    array_node_t* lookup(int key) {
        int index = array_node_t::lookup(key);
        if(index == nkeys) {
            return values[nkeys];
        } else {
            if(key < keys[index]) {
                return values[index];
            } else {
                return values[index + 1];
            }
        }
    }

    void split(array_internal_node_t **lnode, array_internal_node_t **rnode, int *median) {
        *median = keys[nkeys / 2];

        // TODO: we need a good allocator here
        array_internal_node_t *_rnode = new array_internal_node_t();
        int rkeys = nkeys - nkeys / 2 - 1;
        memcpy(_rnode->keys, keys + (nkeys / 2 + 1), rkeys * sizeof(*keys));
        memcpy(_rnode->values, values + (nkeys / 2 + 1), (rkeys + 1) * sizeof(*values));
        _rnode->nkeys = rkeys;

        nkeys /= 2;
        *lnode = this;
        *rnode = _rnode;
    }

private:
    array_node_t* values[NODE_ORDER + 1];
};

#endif // __ARRAY_NODE_HPP__

<commit_msg>More todo<commit_after>
#ifndef __ARRAY_NODE_HPP__
#define __ARRAY_NODE_HPP__

#include <algorithm>
#include <stdio.h>

struct array_leaf_node_t;
struct array_internal_node_t;

// TODO: this shouldn't be a compile time option (or perhaps it should
// in this case)
#define NODE_ORDER    16

// TODO: optimize for cache alignment/cache misses/etc.
struct array_node_t {
    array_node_t(bool _leaf) : leaf(_leaf), nkeys(0) {}

    bool leaf;
    bool is_leaf() {
        return leaf;
    }
    bool is_internal() {
        return !leaf;
    }

    bool is_full() {
        return nkeys == NODE_ORDER;
    }

    typedef array_leaf_node_t leaf_node_t;
    typedef array_internal_node_t internal_node_t;

protected:
    int lookup(int key) {
        int *_value = std::lower_bound(keys, keys + nkeys, key);
        return _value - keys;
    }

protected:
    int nkeys;
    int keys[NODE_ORDER];
};

struct array_leaf_node_t : public array_node_t {
    array_leaf_node_t() : array_node_t(true) {}

#ifndef NDEBUG
    void print() {
        for(int i = 0; i < nkeys; i++) {
            printf("%d : %d, ", keys[i], values[i]);
        }
        printf("\n");
    }
#endif

    int insert(int key, int value) {
        if(nkeys == NODE_ORDER) {
            return 0;
        }
        int index = array_node_t::lookup(key);
        // TODO: handle duplicates
        // TODO: this is likely suboptimal, we might want two for
        // loops (one for keys, one for values)
        for(int i = nkeys - 1; i >= index; i--) {
            keys[i + 1] = keys[i];
            values[i + 1] = values[i];
        }
        keys[index] = key;
        values[index] = value;
        nkeys++;
        return 1;
    }

    int lookup(int key, int *value) {
        int index = array_node_t::lookup(key);
        if(index == nkeys || keys[index] != key) {
            return 0;
        } else {
            *value = values[index];
            return 1;
        }
    }

    void split(array_leaf_node_t **lnode, array_leaf_node_t **rnode, int *median) {
        *median = keys[nkeys / 2];

        // TODO: we need a good allocator here
        array_leaf_node_t *_rnode = new array_leaf_node_t();
        int rkeys = nkeys - nkeys / 2;
        memcpy(_rnode->keys, keys + nkeys / 2, rkeys * sizeof(*keys));
        memcpy(_rnode->values, values + nkeys / 2, rkeys * sizeof(*values));
        _rnode->nkeys = rkeys;

        nkeys /= 2;

        *lnode = this;
        *rnode = _rnode;
    }

private:
    int values[NODE_ORDER];
};

struct array_internal_node_t : public array_node_t  {
    array_internal_node_t() : array_node_t(false) {}

#ifndef NDEBUG
    void print() {
        printf("  ");
        for(int i = 0; i < nkeys; i++) {
            printf("%d, ", keys[i]);
        }
        printf("\n");
        for(int i = 0; i < nkeys + 1; i++) {
            printf("%d, ", (int)(long)values[i]);
        }
        printf("\n\n");
    }
#endif

    int insert(int key, array_node_t *lnode, array_node_t *rnode) {
        if(nkeys == NODE_ORDER) {
            return 0;
        }
        int index = array_node_t::lookup(key);
        // TODO: handle duplicates
        // TODO: this is likely suboptimal, we might want two for
        // loops (one for keys, one for values)
        values[nkeys + 1] = values[nkeys];
        for(int i = nkeys - 1; i >= index; i--) {
            keys[i + 1] = keys[i];
            values[i + 1] = values[i];
        }
        keys[index] = key;
        values[index] = lnode;
        values[index + 1] = rnode;
        nkeys++;
        return 1;
    }

    array_node_t* lookup(int key) {
        int index = array_node_t::lookup(key);
        if(index == nkeys) {
            return values[nkeys];
        } else {
            if(key < keys[index]) {
                return values[index];
            } else {
                return values[index + 1];
            }
        }
    }

    void split(array_internal_node_t **lnode, array_internal_node_t **rnode, int *median) {
        *median = keys[nkeys / 2];

        // TODO: we need a good allocator here
        array_internal_node_t *_rnode = new array_internal_node_t();
        int rkeys = nkeys - nkeys / 2 - 1;
        memcpy(_rnode->keys, keys + (nkeys / 2 + 1), rkeys * sizeof(*keys));
        memcpy(_rnode->values, values + (nkeys / 2 + 1), (rkeys + 1) * sizeof(*values));
        _rnode->nkeys = rkeys;

        nkeys /= 2;
        *lnode = this;
        *rnode = _rnode;
    }

private:
    array_node_t* values[NODE_ORDER + 1];
};

#endif // __ARRAY_NODE_HPP__

<|endoftext|>


<commit_before>/** \file
 *
 *  Copyright (c) 2012 by Travis Gockel. All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
 *  as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
 *  version.
 *
 *  \author Travis Gockel (travis@gockelhut.com)
**/
#include "test.hpp"

#include <jsonv/array.hpp>
#include <jsonv/object.hpp>
#include <jsonv/parse.hpp>

#include <string>
#include <utility>

TEST(object)
{
    jsonv::value obj = jsonv::object();
    obj["hi"] = false;
    ensure(obj["hi"].as_boolean() == false);
    obj["yay"] = jsonv::array({ "Hello", "to", "the", "world" });
    ensure(obj["hi"].as_boolean() == false);
    ensure(obj["yay"].size() == 4);
    ensure(obj.size() == 2);
}

TEST(object_view_iter_assign)
{
    using namespace jsonv;

    value obj = object({ { "foo", 5 }, { "bar", "wat" } });
    value found = object({ { "foo", false }, { "bar", false } });
    ensure(obj.size() == 2);

    for (auto iter = obj.begin_object(); iter != obj.end_object(); ++iter)
    {
        value::object_iterator fiter;
        fiter = found.find(iter->first);
        ensure(!fiter->second.as_boolean());
        fiter->second = true;
    }

    for (auto iter = found.begin_object(); iter != found.end_object(); ++iter)
        ensure(iter->second.as_boolean());
}

TEST(object_view_reverse_iter)
{
    using namespace jsonv;

    value obj = object({ { "a", 1 }, { "b", 2 }, { "c", 3 } });
    auto riter = obj.as_object().rbegin();
    ensure_eq(riter->first, "c");
    ++riter;
    ensure_eq(riter->first, "b");
    ++riter;
    ensure_eq(riter->first, "a");
    ++riter;
    ensure(riter == obj.as_object().rend());
}

TEST(object_compare)
{
    using namespace jsonv;

    value obj = object();
    value i = 5;

    // really just a test to see if this compiles:
    ensure(obj != i);
}

TEST(object_erase_key)
{
    jsonv::value obj = jsonv::object({ { "foo", 5 }, { "bar", "wat" } });
    ensure_eq(obj.size(), 2);
    ensure_eq(obj.count("bar"), 1);
    ensure_eq(obj.count("foo"), 1);
    ensure_eq(obj.erase("foo"), 1);
    ensure_eq(obj.count("bar"), 1);
    ensure_eq(obj.count("foo"), 0);
    ensure_eq(obj.erase("foo"), 0);
}

TEST(object_erase_iter)
{
    jsonv::value obj = jsonv::object({ { "foo", 5 }, { "bar", "wat" } });
    ensure_eq(obj.size(), 2);
    ensure_eq(obj.count("bar"), 1);
    ensure_eq(obj.count("foo"), 1);
    auto iter = obj.find("bar");
    ensure_eq(iter->first, "bar");
    iter = obj.erase(iter);
    ensure_eq(obj.count("bar"), 0);
    ensure_eq(obj.count("foo"), 1);
    ensure_eq(obj.erase("bar"), 0);
    ensure_eq(iter->first, "foo");
}

TEST(object_erase_whole)
{
    jsonv::value obj = jsonv::object({ { "foo", 5 }, { "bar", "wat" } });
    ensure_eq(obj.size(), 2);
    ensure_eq(obj.count("bar"), 1);
    ensure_eq(obj.count("foo"), 1);
    auto iter = obj.begin_object();
    ensure_eq(iter->first, "bar");
    iter = obj.erase(iter, obj.end_object());
    ensure_eq(obj.size(), 0);
    ensure_eq(obj.count("bar"), 0);
    ensure_eq(obj.count("foo"), 0);
    ensure_eq(obj.erase("bar"), 0);
    ensure(iter == obj.end_object());
    ensure(iter == obj.begin_object());
}

TEST(object_view)
{
    const jsonv::value obj1 = jsonv::object({ { "foo", 5 }, { "bar", "wat" } });
    jsonv::value obj2 = jsonv::object();
    for (const std::pair<const std::string, const jsonv::value>& entry : obj1.as_object())
        obj2.insert(entry);
    ensure_eq(obj1, obj2);
}

TEST(object_nested_access)
{
    jsonv::value v = jsonv::object({ { "x", 0 } });
    jsonv::value* p = &v;
    int depth = 1;
    for (std::string name : { "a", "b", "c", "d" })
    {
        (*p)[name] = jsonv::object({ { "x", depth } });
        p = &(*p)[name];
        ++depth;
    }

    ensure_eq(v["x"],                     0);
    ensure_eq(v["a"]["x"],                1);
    ensure_eq(v["a"]["b"]["x"],           2);
    ensure_eq(v["a"]["b"]["c"]["x"],      3);
    ensure_eq(v["a"]["b"]["c"]["d"]["x"], 4);
}

TEST(owning_object_view)
{
    auto view = jsonv::object({ { "a", 1 }, { "b", 2 } }).as_object();
    auto iter = view.begin();
    ensure_eq("a", iter->first);
    ++iter;
    ensure_eq("b", iter->first);
    ++iter;
    ensure(iter == view.end());
}

TEST(parse_empty_object)
{
    auto obj = jsonv::parse("{}");

    ensure(obj.size() == 0);
}

TEST(parse_keyless_object)
{
    try
    {
        jsonv::parse("{a : 3}", jsonv::parse_options().failure_mode(jsonv::parse_options::on_error::collect_all));
    }
    catch (const jsonv::parse_error& err)
    {
        ensure_eq(jsonv::object({ { "a", 3 } }), err.partial_result());
    }
}

TEST(parse_object_wrong_kind_keys)
{
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({1: "blah")"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({null: "blah")"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({true: "blah")"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({1.3: "blah")"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({["hi"]: "blah")"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({{}: "blah")"));
}

TEST(parse_object_stops)
{
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({"a")"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({"a" )"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({"a":)"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({"a": "blah")"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({"a": "blah",)"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({"a": "blah", )"));
}

TEST(parse_object_value_stops)
{
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({"a": "blah)"));
}

TEST(parse_object_duplicate_keys)
{
    std::string source = R"({ "a": 1, "a": 2 })";
    ensure_throws(jsonv::parse_error, jsonv::parse(source));
    ensure_eq(jsonv::object({ { "a", 2 } }),
              jsonv::parse(source, jsonv::parse_options().failure_mode(jsonv::parse_options::on_error::ignore))
             );
}
<commit_msg>Adds basic testing for objects with wide-string keys.<commit_after>/** \file
 *
 *  Copyright (c) 2012 by Travis Gockel. All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
 *  as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
 *  version.
 *
 *  \author Travis Gockel (travis@gockelhut.com)
**/
#include "test.hpp"

#include <jsonv/array.hpp>
#include <jsonv/object.hpp>
#include <jsonv/parse.hpp>

#include <string>
#include <utility>

TEST(object)
{
    jsonv::value obj = jsonv::object();
    obj["hi"] = false;
    ensure(obj["hi"].as_boolean() == false);
    obj["yay"] = jsonv::array({ "Hello", "to", "the", "world" });
    ensure(obj["hi"].as_boolean() == false);
    ensure(obj["yay"].size() == 4);
    ensure(obj.size() == 2);
}

TEST(object_view_iter_assign)
{
    using namespace jsonv;

    value obj = object({ { "foo", 5 }, { "bar", "wat" } });
    value found = object({ { "foo", false }, { "bar", false } });
    ensure(obj.size() == 2);

    for (auto iter = obj.begin_object(); iter != obj.end_object(); ++iter)
    {
        value::object_iterator fiter;
        fiter = found.find(iter->first);
        ensure(!fiter->second.as_boolean());
        fiter->second = true;
    }

    for (auto iter = found.begin_object(); iter != found.end_object(); ++iter)
        ensure(iter->second.as_boolean());
}

TEST(object_view_reverse_iter)
{
    using namespace jsonv;

    value obj = object({ { "a", 1 }, { "b", 2 }, { "c", 3 } });
    auto riter = obj.as_object().rbegin();
    ensure_eq(riter->first, "c");
    ++riter;
    ensure_eq(riter->first, "b");
    ++riter;
    ensure_eq(riter->first, "a");
    ++riter;
    ensure(riter == obj.as_object().rend());
}

TEST(object_compare)
{
    using namespace jsonv;

    value obj = object();
    value i = 5;

    // really just a test to see if this compiles:
    ensure(obj != i);
}

TEST(object_erase_key)
{
    jsonv::value obj = jsonv::object({ { "foo", 5 }, { "bar", "wat" } });
    ensure_eq(obj.size(), 2);
    ensure_eq(obj.count("bar"), 1);
    ensure_eq(obj.count("foo"), 1);
    ensure_eq(obj.erase("foo"), 1);
    ensure_eq(obj.count("bar"), 1);
    ensure_eq(obj.count("foo"), 0);
    ensure_eq(obj.erase("foo"), 0);
}

TEST(object_erase_iter)
{
    jsonv::value obj = jsonv::object({ { "foo", 5 }, { "bar", "wat" } });
    ensure_eq(obj.size(), 2);
    ensure_eq(obj.count("bar"), 1);
    ensure_eq(obj.count("foo"), 1);
    auto iter = obj.find("bar");
    ensure_eq(iter->first, "bar");
    iter = obj.erase(iter);
    ensure_eq(obj.count("bar"), 0);
    ensure_eq(obj.count("foo"), 1);
    ensure_eq(obj.erase("bar"), 0);
    ensure_eq(iter->first, "foo");
}

TEST(object_erase_whole)
{
    jsonv::value obj = jsonv::object({ { "foo", 5 }, { "bar", "wat" } });
    ensure_eq(obj.size(), 2);
    ensure_eq(obj.count("bar"), 1);
    ensure_eq(obj.count("foo"), 1);
    auto iter = obj.begin_object();
    ensure_eq(iter->first, "bar");
    iter = obj.erase(iter, obj.end_object());
    ensure_eq(obj.size(), 0);
    ensure_eq(obj.count("bar"), 0);
    ensure_eq(obj.count("foo"), 0);
    ensure_eq(obj.erase("bar"), 0);
    ensure(iter == obj.end_object());
    ensure(iter == obj.begin_object());
}

TEST(object_view)
{
    const jsonv::value obj1 = jsonv::object({ { "foo", 5 }, { "bar", "wat" } });
    jsonv::value obj2 = jsonv::object();
    for (const std::pair<const std::string, const jsonv::value>& entry : obj1.as_object())
        obj2.insert(entry);
    ensure_eq(obj1, obj2);
}

TEST(object_nested_access)
{
    jsonv::value v = jsonv::object({ { "x", 0 } });
    jsonv::value* p = &v;
    int depth = 1;
    for (std::string name : { "a", "b", "c", "d" })
    {
        (*p)[name] = jsonv::object({ { "x", depth } });
        p = &(*p)[name];
        ++depth;
    }

    ensure_eq(v["x"],                     0);
    ensure_eq(v["a"]["x"],                1);
    ensure_eq(v["a"]["b"]["x"],           2);
    ensure_eq(v["a"]["b"]["c"]["x"],      3);
    ensure_eq(v["a"]["b"]["c"]["d"]["x"], 4);
}

TEST(object_wide_nested_access)
{
    jsonv::value v = jsonv::object({ { "x", 0 } });
    jsonv::value* p = &v;
    int depth = 1;
    for (std::string name : { "a", "b", "c", "d" })
    {
        (*p)[name] = jsonv::object({ { "x", depth } });
        p = &(*p)[name];
        ++depth;
    }

    ensure_eq(v.at(L"x"),                      0);
    ensure_eq(v[L"a"][L"x"],                   1);
    ensure_eq(v[L"a"][L"b"][L"x"],             2);
    ensure_eq(v[L"a"][L"b"][L"c"][L"x"],       3);
    ensure_eq(v[L"a"][L"b"][L"c"][L"d"][L"x"], 4);
}

TEST(owning_object_view)
{
    auto view = jsonv::object({ { "a", 1 }, { "b", 2 } }).as_object();
    auto iter = view.begin();
    ensure_eq("a", iter->first);
    ++iter;
    ensure_eq("b", iter->first);
    ++iter;
    ensure(iter == view.end());
}

// An object constructed with wide strings should be the same as one constructed with narrow ones
TEST(object_wide_keys)
{
    auto wobj = jsonv::object({ { L"a", 1 }, { L"b", 2 } });
    auto nobj = jsonv::object({ {  "a", 1 }, {  "b", 2 } });
    ensure_eq(nobj, wobj);
}

TEST(parse_empty_object)
{
    auto obj = jsonv::parse("{}");

    ensure(obj.size() == 0);
}

TEST(parse_keyless_object)
{
    try
    {
        jsonv::parse("{a : 3}", jsonv::parse_options().failure_mode(jsonv::parse_options::on_error::collect_all));
    }
    catch (const jsonv::parse_error& err)
    {
        ensure_eq(jsonv::object({ { "a", 3 } }), err.partial_result());
    }
}

TEST(parse_object_wrong_kind_keys)
{
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({1: "blah")"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({null: "blah")"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({true: "blah")"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({1.3: "blah")"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({["hi"]: "blah")"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({{}: "blah")"));
}

TEST(parse_object_stops)
{
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({"a")"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({"a" )"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({"a":)"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({"a": "blah")"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({"a": "blah",)"));
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({"a": "blah", )"));
}

TEST(parse_object_value_stops)
{
    ensure_throws(jsonv::parse_error, jsonv::parse(R"({"a": "blah)"));
}

TEST(parse_object_duplicate_keys)
{
    std::string source = R"({ "a": 1, "a": 2 })";
    ensure_throws(jsonv::parse_error, jsonv::parse(source));
    ensure_eq(jsonv::object({ { "a", 2 } }),
              jsonv::parse(source, jsonv::parse_options().failure_mode(jsonv::parse_options::on_error::ignore))
             );
}
<|endoftext|>


<commit_before>// menutest.cc a test app for Menus
// Copyright (c) 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

#include "App.hh"
#include "FbWindow.hh"
#include "Font.hh"
#include "EventHandler.hh"
#include "EventManager.hh"
#include "GContext.hh"
#include "Color.hh"
#include "Menu.hh"
#include "MenuItem.hh"
#include "MenuSeparator.hh"
#include "StringUtil.hh"
#include "ImageControl.hh"

#include "../FbMenuParser.hh"

#include <X11/Xutil.h>
#include <X11/keysym.h>

#include <string>
#include <iostream>
using namespace std;

void doSubmenu(Parser &parser, FbTk::Menu &menu,
               FbTk::MenuTheme &theme,
               FbTk::ImageControl &image_ctrl,
               const std::string labelstr) {

    Parser::Item key, label, cmd, icon;

    FbTk::Menu *submenu = new FbTk::Menu(theme, image_ctrl);
    submenu->setLabel(labelstr.c_str());
    menu.insert(labelstr.c_str(), submenu);
    // skip submenu items
    if (key.second == "begin") {
        while (key.second != "end") {
            parser>>key>>label>>cmd>>icon;
            if (key.second == "begin")
                doSubmenu(parser, *submenu,
                          theme, image_ctrl,
                          label.second);
        }
    }
}

class App:public FbTk::App, public FbTk::EventHandler {
public:
    App(const char *displayname, const std::string &stylefile, const std::string &menufile):
        FbTk::App(displayname),
        m_image_ctrl(DefaultScreen(display())),
        m_menu_theme(DefaultScreen(display())),
        m_menu(m_menu_theme, m_image_ctrl) {

        //m_menu_theme.frameFont().setAntialias(true);
        //m_menu_theme.titleFont().setAntialias(true);

        cerr<<"Loading menu: "<<menufile<<endl;
        FbMenuParser parser(menufile);
        if (parser.isLoaded()) {
            // get start of file
            Parser::Item key, label, cmd, icon;
            while (!parser.eof()) {
                // get first begin line
                parser>>key>>label>>cmd>>icon;
                if (key.second == "begin")
                    break;

            }

            m_menu.setLabel(label.second.c_str());

            while (!parser.eof()) {
                parser>>key>>label>>cmd>>icon;
                if (key.second == "end")
                    break;

                string iconfile = icon.second;
                if (key.second == "separator")
                    m_menu.insert(new FbTk::MenuSeparator());
                else if (key.second == "begin") { // new submenu
                    doSubmenu(parser, m_menu,
                              m_menu_theme,
                              m_image_ctrl,
                              label.second);
                } else if (key.second != "styles" &&
                           key.second != "stylesdir")
                    m_menu.insert(label.second.c_str());

                // set icon on items
                if (!iconfile.empty()) {
                    FbTk::MenuItem *item = m_menu.find(m_menu.numberOfItems() - 1);
                    item->setIcon(iconfile, m_menu.screenNumber());
                }
            }

        }

        cerr<<"Loading style: "<<stylefile<<endl;
        FbTk::ThemeManager::instance().load(stylefile);

        m_menu.show();

    }

    ~App() {
    }

private:
    FbTk::ImageControl m_image_ctrl;
    FbTk::MenuTheme m_menu_theme;
    FbTk::Menu m_menu;
};

int main(int argc, char **argv) {
    string displayname("");
    string stylefile, menufile="~/.fluxbox/menu";
    for (int a=1; a<argc; ++a) {
        if (strcmp("-display", argv[a]) == 0 && a + 1 < argc) {
            displayname = argv[++a];
        } else if (strcmp("-style", argv[a]) == 0 && a + 1 < argc) {
            stylefile = argv[++a];
        } else if (strcmp("-menu", argv[a]) == 0 && a + 1 < argc) {
            menufile = argv[++a];
        }
    }
    menufile = FbTk::StringUtil::expandFilename(menufile);
    App app(displayname.c_str(), stylefile, menufile);

    app.eventLoop();

}
<commit_msg>doSubmenu function in menutest.cc avoids copying labelstr by using a const reference.<commit_after>// menutest.cc a test app for Menus
// Copyright (c) 2006 Henrik Kinnunen (fluxgen at fluxbox dot org)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

#include "App.hh"
#include "FbWindow.hh"
#include "Font.hh"
#include "EventHandler.hh"
#include "EventManager.hh"
#include "GContext.hh"
#include "Color.hh"
#include "Menu.hh"
#include "MenuItem.hh"
#include "MenuSeparator.hh"
#include "StringUtil.hh"
#include "ImageControl.hh"

#include "../FbMenuParser.hh"

#include <X11/Xutil.h>
#include <X11/keysym.h>

#include <string>
#include <iostream>
using namespace std;

void doSubmenu(Parser &parser, FbTk::Menu &menu,
               FbTk::MenuTheme &theme,
               FbTk::ImageControl &image_ctrl,
               const std::string &labelstr) {

    Parser::Item key, label, cmd, icon;

    FbTk::Menu *submenu = new FbTk::Menu(theme, image_ctrl);
    submenu->setLabel(labelstr.c_str());
    menu.insert(labelstr.c_str(), submenu);
    // skip submenu items
    if (key.second == "begin") {
        while (key.second != "end") {
            parser>>key>>label>>cmd>>icon;
            if (key.second == "begin")
                doSubmenu(parser, *submenu,
                          theme, image_ctrl,
                          label.second);
        }
    }
}

class App:public FbTk::App, public FbTk::EventHandler {
public:
    App(const char *displayname, const std::string &stylefile, const std::string &menufile):
        FbTk::App(displayname),
        m_image_ctrl(DefaultScreen(display())),
        m_menu_theme(DefaultScreen(display())),
        m_menu(m_menu_theme, m_image_ctrl) {

        //m_menu_theme.frameFont().setAntialias(true);
        //m_menu_theme.titleFont().setAntialias(true);

        cerr<<"Loading menu: "<<menufile<<endl;
        FbMenuParser parser(menufile);
        if (parser.isLoaded()) {
            // get start of file
            Parser::Item key, label, cmd, icon;
            while (!parser.eof()) {
                // get first begin line
                parser>>key>>label>>cmd>>icon;
                if (key.second == "begin")
                    break;

            }

            m_menu.setLabel(label.second.c_str());

            while (!parser.eof()) {
                parser>>key>>label>>cmd>>icon;
                if (key.second == "end")
                    break;

                string iconfile = icon.second;
                if (key.second == "separator")
                    m_menu.insert(new FbTk::MenuSeparator());
                else if (key.second == "begin") { // new submenu
                    doSubmenu(parser, m_menu,
                              m_menu_theme,
                              m_image_ctrl,
                              label.second);
                } else if (key.second != "styles" &&
                           key.second != "stylesdir")
                    m_menu.insert(label.second.c_str());

                // set icon on items
                if (!iconfile.empty()) {
                    FbTk::MenuItem *item = m_menu.find(m_menu.numberOfItems() - 1);
                    item->setIcon(iconfile, m_menu.screenNumber());
                }
            }

        }

        cerr<<"Loading style: "<<stylefile<<endl;
        FbTk::ThemeManager::instance().load(stylefile);

        m_menu.show();

    }

    ~App() {
    }

private:
    FbTk::ImageControl m_image_ctrl;
    FbTk::MenuTheme m_menu_theme;
    FbTk::Menu m_menu;
};

int main(int argc, char **argv) {
    string displayname("");
    string stylefile, menufile="~/.fluxbox/menu";
    for (int a=1; a<argc; ++a) {
        if (strcmp("-display", argv[a]) == 0 && a + 1 < argc) {
            displayname = argv[++a];
        } else if (strcmp("-style", argv[a]) == 0 && a + 1 < argc) {
            stylefile = argv[++a];
        } else if (strcmp("-menu", argv[a]) == 0 && a + 1 < argc) {
            menufile = argv[++a];
        }
    }
    menufile = FbTk::StringUtil::expandFilename(menufile);
    App app(displayname.c_str(), stylefile, menufile);

    app.eventLoop();

}
<|endoftext|>