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

#ifndef _CONNECTIVITY_ODBC_ODATABASEMETADATA_HXX_
#include "odbc/ODatabaseMetaData.hxx"
#endif

namespace connectivity
{
    namespace odbc
    {
        class OConnection;
    }
    namespace adabas
    {
        typedef odbc::ODatabaseMetaData OAdabasDatabaseMetaData_BASE;

        class OAdabasDatabaseMetaData : public OAdabasDatabaseMetaData_BASE
        {
        public:
            OAdabasDatabaseMetaData(const SQLHANDLE _pHandle,odbc::OConnection* _pCon)
                : ODatabaseMetaData(_pHandle,_pCon)
            {
            }

            // just to return our url
            virtual ::rtl::OUString SAL_CALL getURL(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL supportsIntegrityEnhancementFacility(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getTypeInfo(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        };
    }
}

<commit_msg>INTEGRATION: CWS dba24d (1.5.310); FILE MERGED 2007/11/21 12:39:23 oj 1.5.310.1: #i68854# impl TypeSettingInfo for Oracle and some clean up<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: BDatabaseMetaData.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2008-01-30 08:00:02 $
 *
 *  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 _CONNECTIVITY_ODBC_ODATABASEMETADATA_HXX_
#include "odbc/ODatabaseMetaData.hxx"
#endif

namespace connectivity
{
    namespace odbc
    {
        class OConnection;
    }
    namespace adabas
    {
        typedef odbc::ODatabaseMetaData OAdabasDatabaseMetaData_BASE;

        class OAdabasDatabaseMetaData : public OAdabasDatabaseMetaData_BASE
        {
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > impl_getTypeInfo_throw();
        public:
            OAdabasDatabaseMetaData(const SQLHANDLE _pHandle,odbc::OConnection* _pCon)
                : ODatabaseMetaData(_pHandle,_pCon)
            {
            }

            // just to return our url
            virtual ::rtl::OUString SAL_CALL getURL(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL supportsIntegrityEnhancementFacility(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        };
    }
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestGPURayCastAdditive.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// This test covers cropping on volume datasets.

#include <vtkSphere.h>
#include <vtkSampleFunction.h>

#include <vtkTestUtilities.h>

#include <vtkActor.h>
#include <vtkColorTransferFunction.h>
#include <vtkCommand.h>
#include <vtkFixedPointVolumeRayCastMapper.h>
#include <vtkGPUVolumeRayCastMapper.h>
#include <vtkImageData.h>
#include <vtkOutlineFilter.h>
#include <vtkPlane.h>
#include <vtkPlaneCollection.h>
#include <vtkPiecewiseFunction.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRegressionTestImage.h>
#include <vtkRTAnalyticSource.h>
#include <vtkNew.h>
#include <vtkSinglePassVolumeMapper.h>
#include <vtkSphereSource.h>
#include <vtkSmartPointer.h>
#include <vtkTimerLog.h>
#include <vtkPolyDataMapper.h>
#include <vtkVolumeProperty.h>
#include <vtkXMLImageDataReader.h>

#include <vtksys/SystemTools.hxx>

#include <cstdlib>

int TestGPURayCastClip(int argc, char *argv[])
{
  double scalarRange[2];

  vtkNew<vtkActor> outlineActor;
  vtkNew<vtkPolyDataMapper> outlineMapper;
  vtkNew<vtkSinglePassVolumeMapper> volumeMapper;
  volumeMapper->SetSampleDistance(0.05);

  vtkNew<vtkXMLImageDataReader> reader;
  const char* volumeFile = vtkTestUtilities::ExpandDataFileName(
                            argc, argv, "Data/vase_1comp.vti");
  reader->SetFileName(volumeFile);
  reader->Update();
  volumeMapper->SetInputConnection(reader->GetOutputPort());

  // Add outline filter
  vtkNew<vtkOutlineFilter> outlineFilter;
  outlineFilter->SetInputConnection(reader->GetOutputPort());
  outlineMapper->SetInputConnection(outlineFilter->GetOutputPort());
  outlineActor->SetMapper(outlineMapper.GetPointer());

  volumeMapper->GetInput()->GetScalarRange(scalarRange);
  volumeMapper->SetBlendModeToComposite();

  // Testing prefers image comparison with small images
  vtkNew<vtkRenderWindow> renWin;
  renWin->SetSize(400, 400);

  // Intentional odd and NPOT  width/height
  vtkNew<vtkRenderer> ren;
  renWin->AddRenderer(ren.GetPointer());

  vtkNew<vtkRenderWindowInteractor> iren;
  iren->SetRenderWindow(renWin.GetPointer());

  // Make sure we have an OpenGL context.
  renWin->Render();

  vtkNew<vtkPiecewiseFunction> scalarOpacity;
  scalarOpacity->AddPoint(scalarRange[0], 0.0);
  scalarOpacity->AddPoint(scalarRange[1], 1.0);

  vtkNew<vtkVolumeProperty> volumeProperty;
  volumeProperty->ShadeOff();
  volumeProperty->SetInterpolationType(VTK_LINEAR_INTERPOLATION);
  volumeProperty->SetScalarOpacity(scalarOpacity.GetPointer());

  vtkSmartPointer<vtkColorTransferFunction> colorTransferFunction =
    volumeProperty->GetRGBTransferFunction(0);
  colorTransferFunction->RemoveAllPoints();
  colorTransferFunction->AddRGBPoint(scalarRange[0], 0.0, 0.0, 0.0);
  colorTransferFunction->AddRGBPoint(scalarRange[1], 1.0, 1.0, 1.0);

  // Test cropping now

  double* bounds = reader->GetOutput()->GetBounds();
  vtkNew<vtkPlane> clipPlane1;
  clipPlane1->SetOrigin(0.45 * (bounds[0] + bounds[1]), 0.0, 0.0);
  clipPlane1->SetNormal(1.0, 0.0, 0.0);

  vtkNew<vtkPlane> clipPlane2;
  clipPlane2->SetOrigin(0.55 * (bounds[0] + bounds[1]), 0.0, 0.0);
  clipPlane2->SetNormal(-1.0, 0.0, 0.0);

  vtkNew<vtkPlaneCollection> clipPlaneCollection;
  clipPlaneCollection->AddItem(clipPlane1.GetPointer());
  clipPlaneCollection->AddItem(clipPlane2.GetPointer());
  volumeMapper->SetClippingPlanes(clipPlaneCollection.GetPointer());

  // Setup volume actor
  vtkNew<vtkVolume> volume;
  volume->SetMapper(volumeMapper.GetPointer());
  volume->SetProperty(volumeProperty.GetPointer());

  ren->AddViewProp(volume.GetPointer());
  ren->AddActor(outlineActor.GetPointer());
  ren->ResetCamera();

  renWin->Render();
  iren->Initialize();

  int retVal = vtkRegressionTestImage(renWin.GetPointer());
  if (retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }
  return !retVal;
}

<commit_msg>Removed hard-coded sample distance<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestGPURayCastAdditive.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// This test covers cropping on volume datasets.

#include <vtkSphere.h>
#include <vtkSampleFunction.h>

#include <vtkTestUtilities.h>

#include <vtkActor.h>
#include <vtkColorTransferFunction.h>
#include <vtkCommand.h>
#include <vtkFixedPointVolumeRayCastMapper.h>
#include <vtkGPUVolumeRayCastMapper.h>
#include <vtkImageData.h>
#include <vtkOutlineFilter.h>
#include <vtkPlane.h>
#include <vtkPlaneCollection.h>
#include <vtkPiecewiseFunction.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRegressionTestImage.h>
#include <vtkRTAnalyticSource.h>
#include <vtkNew.h>
#include <vtkSinglePassVolumeMapper.h>
#include <vtkSphereSource.h>
#include <vtkSmartPointer.h>
#include <vtkTimerLog.h>
#include <vtkPolyDataMapper.h>
#include <vtkVolumeProperty.h>
#include <vtkXMLImageDataReader.h>

#include <vtksys/SystemTools.hxx>

#include <cstdlib>

int TestGPURayCastClip(int argc, char *argv[])
{
  double scalarRange[2];

  vtkNew<vtkActor> outlineActor;
  vtkNew<vtkPolyDataMapper> outlineMapper;
  vtkNew<vtkSinglePassVolumeMapper> volumeMapper;

  vtkNew<vtkXMLImageDataReader> reader;
  const char* volumeFile = vtkTestUtilities::ExpandDataFileName(
                            argc, argv, "Data/vase_1comp.vti");
  reader->SetFileName(volumeFile);
  reader->Update();
  volumeMapper->SetInputConnection(reader->GetOutputPort());

  // Add outline filter
  vtkNew<vtkOutlineFilter> outlineFilter;
  outlineFilter->SetInputConnection(reader->GetOutputPort());
  outlineMapper->SetInputConnection(outlineFilter->GetOutputPort());
  outlineActor->SetMapper(outlineMapper.GetPointer());

  volumeMapper->GetInput()->GetScalarRange(scalarRange);
  volumeMapper->SetBlendModeToComposite();

  // Testing prefers image comparison with small images
  vtkNew<vtkRenderWindow> renWin;
  renWin->SetSize(400, 400);

  // Intentional odd and NPOT  width/height
  vtkNew<vtkRenderer> ren;
  renWin->AddRenderer(ren.GetPointer());

  vtkNew<vtkRenderWindowInteractor> iren;
  iren->SetRenderWindow(renWin.GetPointer());

  // Make sure we have an OpenGL context.
  renWin->Render();

  vtkNew<vtkPiecewiseFunction> scalarOpacity;
  scalarOpacity->AddPoint(scalarRange[0], 0.0);
  scalarOpacity->AddPoint(scalarRange[1], 1.0);

  vtkNew<vtkVolumeProperty> volumeProperty;
  volumeProperty->ShadeOff();
  volumeProperty->SetInterpolationType(VTK_LINEAR_INTERPOLATION);
  volumeProperty->SetScalarOpacity(scalarOpacity.GetPointer());

  vtkSmartPointer<vtkColorTransferFunction> colorTransferFunction =
    volumeProperty->GetRGBTransferFunction(0);
  colorTransferFunction->RemoveAllPoints();
  colorTransferFunction->AddRGBPoint(scalarRange[0], 0.0, 0.0, 0.0);
  colorTransferFunction->AddRGBPoint(scalarRange[1], 1.0, 1.0, 1.0);

  // Test cropping now

  double* bounds = reader->GetOutput()->GetBounds();
  vtkNew<vtkPlane> clipPlane1;
  clipPlane1->SetOrigin(0.45 * (bounds[0] + bounds[1]), 0.0, 0.0);
  clipPlane1->SetNormal(1.0, 0.0, 0.0);

  vtkNew<vtkPlane> clipPlane2;
  clipPlane2->SetOrigin(0.55 * (bounds[0] + bounds[1]), 0.0, 0.0);
  clipPlane2->SetNormal(-1.0, 0.0, 0.0);

  vtkNew<vtkPlaneCollection> clipPlaneCollection;
  clipPlaneCollection->AddItem(clipPlane1.GetPointer());
  clipPlaneCollection->AddItem(clipPlane2.GetPointer());
  volumeMapper->SetClippingPlanes(clipPlaneCollection.GetPointer());

  // Setup volume actor
  vtkNew<vtkVolume> volume;
  volume->SetMapper(volumeMapper.GetPointer());
  volume->SetProperty(volumeProperty.GetPointer());

  ren->AddViewProp(volume.GetPointer());
  ren->AddActor(outlineActor.GetPointer());
  ren->ResetCamera();

  renWin->Render();
  iren->Initialize();

  int retVal = vtkRegressionTestImage(renWin.GetPointer());
  if (retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }
  return !retVal;
}

<|endoftext|>


<commit_before>#include <QString>
#include <QtTest>

#include <libgpsbip/OptionTypes.h>
#include <libgpsbip/OptionsGroupBase.h>

class MockGroup : public gpsbip::OptionsGroupBase
{
    Q_OBJECT

public:
    MockGroup() {
        auto r = new gpsbip::BoolOption();
        root = addOption(r);
        opt = addOption<gpsbip::BoolOption>("label");
        strOpt = addOption<gpsbip::StringOption>(*r, "label");
    }

    gpsbip::BoolOption* getRootOption() { return &get<gpsbip::BoolOption>(root); }
    gpsbip::BoolOption* getOption() { return &get<gpsbip::BoolOption>(opt); }
    gpsbip::StringOption* getStrOption() { return &get<gpsbip::StringOption>(strOpt); }

private:
    int root, opt, strOpt;
};

class Tst_optionsGroups : public QObject
{
    Q_OBJECT

public:
    Tst_optionsGroups();

private Q_SLOTS:
    void testOptionGroupMechanic();
    void testOptionGroupMechanic_optionParenting();
};

Tst_optionsGroups::Tst_optionsGroups()
{
}

void Tst_optionsGroups::testOptionGroupMechanic()
{
    try {
        // Validates all 3 addOption variants (by definition, can't really assert that :/)
        MockGroup g;

        // Validates get<>
        gpsbip::BoolOption *root = g.getRootOption();
        QVERIFY(root != nullptr);
        gpsbip::BoolOption *opt = g.getOption();
        QVERIFY(opt != nullptr);
        gpsbip::StringOption *str = g.getStrOption();
        QVERIFY(str != nullptr);

        // Confirm that the string option is dependant on the root one and that the expected addOption was used
        QCOMPARE(str->isEnabled(), false);
        *root = true;
        QCOMPARE(str->isEnabled(), true);
    }
    catch (std::exception &e) {
        QFAIL(e.what());
    }
}

void Tst_optionsGroups::testOptionGroupMechanic_optionParenting()
{
    try {
        MockGroup g;

        gpsbip::BoolOption *root = g.getRootOption();
        gpsbip::BoolOption *opt = g.getOption();
        gpsbip::StringOption *str = g.getStrOption();

        QCOMPARE(root->parent(), &g);
        QCOMPARE(opt->parent(), &g);
        QCOMPARE(str->parent(), &g);
    }
    catch (std::exception &e) {
        QFAIL(e.what());
    }
}

QTEST_APPLESS_MAIN(Tst_optionsGroups)

#include "tst_optionsgroups.moc"
<commit_msg>Added validation of gps group definition<commit_after>#include <QString>
#include <QtTest>

#include <libgpsbip/OptionTypes.h>
#include <libgpsbip/OptionsGroupBase.h>
#include <libgpsbip/GpsOptionsGroup.h>

class MockGroup : public gpsbip::OptionsGroupBase
{
    Q_OBJECT

public:
    MockGroup() {
        auto r = new gpsbip::BoolOption();
        root = addOption(r);
        opt = addOption<gpsbip::BoolOption>("label");
        strOpt = addOption<gpsbip::StringOption>(*r, "label");
    }

    gpsbip::BoolOption* getRootOption() { return &get<gpsbip::BoolOption>(root); }
    gpsbip::BoolOption* getOption() { return &get<gpsbip::BoolOption>(opt); }
    gpsbip::StringOption* getStrOption() { return &get<gpsbip::StringOption>(strOpt); }

private:
    int root, opt, strOpt;
};

class Tst_optionsGroups : public QObject
{
    Q_OBJECT

public:
    Tst_optionsGroups();

private Q_SLOTS:
    // Base group validation
    void testOptionGroupMechanic();
    void testOptionGroupMechanic_optionParenting();

    // Real groups validation
    void validateGpsOptionsGroup();
};

Tst_optionsGroups::Tst_optionsGroups()
{
}

void Tst_optionsGroups::testOptionGroupMechanic()
{
    try {
        // Validates all 3 addOption variants (by definition, can't really assert that :/)
        MockGroup g;

        // Validates get<>
        gpsbip::BoolOption *root = g.getRootOption();
        QVERIFY(root != nullptr);
        gpsbip::BoolOption *opt = g.getOption();
        QVERIFY(opt != nullptr);
        gpsbip::StringOption *str = g.getStrOption();
        QVERIFY(str != nullptr);

        // Confirm that the string option is dependant on the root one and that the expected addOption was used
        QCOMPARE(str->isEnabled(), false);
        *root = true;
        QCOMPARE(str->isEnabled(), true);
    }
    catch (std::exception &e) {
        QFAIL(e.what());
    }
}

void Tst_optionsGroups::testOptionGroupMechanic_optionParenting()
{
    try {
        MockGroup g;

        gpsbip::BoolOption *root = g.getRootOption();
        gpsbip::BoolOption *opt = g.getOption();
        gpsbip::StringOption *str = g.getStrOption();

        QCOMPARE(root->parent(), &g);
        QCOMPARE(opt->parent(), &g);
        QCOMPARE(str->parent(), &g);
    }
    catch (std::exception &e) {
        QFAIL(e.what());
    }
}

void Tst_optionsGroups::validateGpsOptionsGroup()
{
    // Since we validated base mechanics previously, we will only validates that the
    // properties are indeed available and the relationships between those is correct.

    try {
        gpsbip::GpsOptionsGroup gps;
        gpsbip::BoolOption * const root         = qvariant_cast<gpsbip::BoolOption*>(gps.property("gpsEnabled"));
        gpsbip::BoolOption * const toDetection  = qvariant_cast<gpsbip::BoolOption*>(gps.property("takeOffDetection"));

        QVERIFY(root != nullptr);
        QVERIFY(toDetection != nullptr);

        // Enablement checking
        QCOMPARE(toDetection->isEnabled(), false);

        *root = true;

        QCOMPARE(toDetection->isEnabled(), true);
    }
    catch (std::exception &e) {
        QFAIL(e.what());
    }
}

QTEST_APPLESS_MAIN(Tst_optionsGroups)

#include "tst_optionsgroups.moc"
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "filesystemstub.h"
#include "ut_wallpaperbusinesslogic.h"
//#include "wallpapergconf.h"

#include "wallpaperbusinesslogic.h"
#include "wallpaperitrans.h"
//#include "wallpapergconf.h"
#include "wallpaperutils.h"
#include "wallpaperconfiguration.h"

#include <MApplication>
#include <MGConfItem>

#define DEBUG
#include "../../src/debug.h"

static const QString PortraitKey =
    "/desktop/meego/background/portrait/picture_filename";
static const QString LandscapeKey =
    "/desktop/meego/background/landscape/picture_filename";

/******************************************************************************
 * GConf stub.
 */
#include <gconf/gconf-client.h>
#include <gconf/gconf-value.h>

static QHash<QString, QString> MyGConfDatabase;

GConfValue *
gconf_client_get (
        GConfClient* client,
        const gchar* key,
        GError** err)
{
    Q_UNUSED (client);
    Q_UNUSED (err);
    Q_ASSERT (qstrlen (key) >= 10);

    QString myKey = key;
    GConfValue *retval;

    SYS_WARNING ("*** key = %s", SYS_STR(myKey));
    if (MyGConfDatabase.contains(myKey)) {
        const char *r = strdup(MyGConfDatabase[myKey].toUtf8().constData());

        retval = gconf_value_new (GCONF_VALUE_STRING);
        gconf_value_set_string (retval, r);
        SYS_DEBUG ("returning '%s'", r);
    } else {
        SYS_DEBUG ("returning false");
        retval = gconf_value_new (GCONF_VALUE_BOOL);
    }

    return retval;
}

/******************************************************************************
 * QImage stub.
 */
#include <QImage>

bool
QImage::load (
        const QString  &fileName,
        const char     *format)
{
    Q_UNUSED (fileName);
    Q_UNUSED (format);
    SYS_DEBUG ("*** fileName = %s", SYS_STR(fileName));
    return true;
}

#include <QPixmap>
bool
QPixmap::load (
        const QString  &fileName,
        const char     *format,
        Qt::ImageConversionFlags flags)
{
    Q_UNUSED (fileName);
    Q_UNUSED (format);
    Q_UNUSED (flags);
    SYS_DEBUG ("*** fileName = %s", SYS_STR(fileName));
    return true;
}

/******************************************************************************
 * SignalSink implementation.
 */
SignalSink::SignalSink ()
{
    reset ();
}

void
SignalSink::reset ()
{
    m_WallpaperChangedCame = false;
}

void
SignalSink::wallpaperChanged ()
{
    SYS_DEBUG ("");
    m_WallpaperChangedCame = true;
}

/******************************************************************************
 * Ut_WallpaperBusinessLogic implementation.
 */
void
Ut_WallpaperBusinessLogic::init()
{
}

void
Ut_WallpaperBusinessLogic::cleanup()
{
}

static int argc = 1;
static char* app_name = (char*) "./ut_wallpaperbusinesslogic";

void
Ut_WallpaperBusinessLogic::initTestCase()
{
    bool connectSuccess;

    MyGConfDatabase["/meegotouch/theme/name"] = "MyThemeName";
    MyGConfDatabase[Wallpaper::CurrentPortraitKey] =
        "/ak/current.jpg";
    MyGConfDatabase[Wallpaper::OriginalPortraitKey] = "";

    m_App = new MApplication (argc, &app_name);

    m_Api = new WallpaperBusinessLogic;
    connectSuccess = connect (
            m_Api, SIGNAL (wallpaperChanged()),
            &m_SignalSink, SLOT (wallpaperChanged()));
    QVERIFY (connectSuccess);

    //QVERIFY (m_Api->m_EditedImage == 0);
}

void
Ut_WallpaperBusinessLogic::cleanupTestCase()
{
    delete m_Api;

    m_App->deleteLater ();
}

/*!
 * Checks the low level WallpaperITrans class, its tag methods and overloaded
 * operators.
 */
void
Ut_WallpaperBusinessLogic::testITrans ()
{
    WallpaperITrans trans1, trans2;

    SYS_DEBUG ("Checking default values of WallpaperITrans...");
    QVERIFY (trans1.x() == 0);
    QVERIFY (trans1.y() == 0);
    QVERIFY (trans1.scale() == 1.0);
    QVERIFY (trans1.orientation() == M::Landscape);

    SYS_DEBUG ("Checking the set functions...");
    trans2.setOffset (QPointF(10, 11));
    trans2.setScale (2.0);
    trans2.setOrientation (M::Portrait);
    trans2.setExpectedSize (QSize(864, 480));

    QVERIFY (trans2.x() == 10);
    QVERIFY (trans2.y() == 11);
    QVERIFY (trans2.scale() == 2.0);
    QVERIFY (trans2.orientation() == M::Portrait);
    QVERIFY (trans2.expectedWidth() == 864);
    QVERIFY (trans2.expectedHeight() == 480);

    SYS_DEBUG ("Testing the copy constructor.");
    WallpaperITrans trans3 (trans2);
    QVERIFY (trans3.x() == 10);
    QVERIFY (trans3.y() == 11);
    QVERIFY (trans3.scale() == 2.0);
    QVERIFY (trans3.orientation() == M::Portrait);
    QVERIFY (trans3.expectedWidth() == 864);
    QVERIFY (trans3.expectedHeight() == 480);

    SYS_DEBUG ("testing operator=...");
    trans1 = trans2;
    QVERIFY (trans1.x() == 10);
    QVERIFY (trans1.y() == 11);
    QVERIFY (trans1.scale() == 2.0);
    QVERIFY (trans1.orientation() == M::Portrait);
    QVERIFY (trans1.expectedWidth() == 864);
    QVERIFY (trans1.expectedHeight() == 480);

    SYS_DEBUG ("Testing operator*...");
    SYS_DEBUG ("*** trans1.scale() = %d", trans2 * 2);
    QVERIFY (trans2 * 2 == 4);
}

/*!
 * Checks if the GConfItem objects are created with the right keys.
 */
void
Ut_WallpaperBusinessLogic::testGConfItems ()
{
    QVERIFY (m_Api->m_PPItem != NULL);
    QVERIFY (m_Api->m_PPItem->key() == Wallpaper::CurrentPortraitKey);

    QVERIFY (m_Api->m_POItem != NULL);
    QVERIFY (m_Api->m_POItem->key() == Wallpaper::OriginalPortraitKey);

    QVERIFY (m_Api->m_PHItem != NULL);
    QVERIFY (m_Api->m_PHItem->key() == Wallpaper::PortraitHistoryKey);
}

/*!
 */
void
Ut_WallpaperBusinessLogic::testCurrentWallpaper ()
{
    QString currentFilePath;
    QString originalFilePath;

    m_Api->currentWallpaper (currentFilePath, originalFilePath);
    QVERIFY (currentFilePath == "/ak/current.jpg");
    QVERIFY (originalFilePath.isEmpty());

    SYS_DEBUG ("*** currentFilePath  = %s", SYS_STR(currentFilePath));
    SYS_DEBUG ("*** originalFilePath = %s", SYS_STR(originalFilePath));
}

void
Ut_WallpaperBusinessLogic::testSceneSize ()
{
    QSize size = m_Api->sceneSize ();
    QSize expected = QSize (480, 854);

    QVERIFY (size == expected);
}

void
Ut_WallpaperBusinessLogic::testEditedImage ()
{
    QVERIFY (!m_Api->hasEditedImage ());

    m_Api->endEdit ();
    QVERIFY (!m_Api->hasEditedImage ());

}

/******************************************************************************
 * Private functions.
 */
QTEST_APPLESS_MAIN(Ut_WallpaperBusinessLogic)

<commit_msg>New unit test.<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "filesystemstub.h"
#include "ut_wallpaperbusinesslogic.h"
//#include "wallpapergconf.h"

#include "wallpaperbusinesslogic.h"
#include "wallpaperitrans.h"
//#include "wallpapergconf.h"
#include "wallpaperutils.h"
#include "wallpaperconfiguration.h"

#include <MApplication>
#include <MGConfItem>

#define DEBUG
#include "../../src/debug.h"

static const QString PortraitKey =
    "/desktop/meego/background/portrait/picture_filename";
static const QString LandscapeKey =
    "/desktop/meego/background/landscape/picture_filename";

/******************************************************************************
 * GConf stub.
 */
#include <gconf/gconf-client.h>
#include <gconf/gconf-value.h>

static QHash<QString, QString> MyGConfDatabase;

GConfValue *
gconf_client_get (
        GConfClient* client,
        const gchar* key,
        GError** err)
{
    Q_UNUSED (client);
    Q_UNUSED (err);
    Q_ASSERT (qstrlen (key) >= 10);

    QString myKey = key;
    GConfValue *retval;

    SYS_WARNING ("*** key = %s", SYS_STR(myKey));
    if (MyGConfDatabase.contains(myKey)) {
        const char *r = strdup(MyGConfDatabase[myKey].toUtf8().constData());

        retval = gconf_value_new (GCONF_VALUE_STRING);
        gconf_value_set_string (retval, r);
        SYS_DEBUG ("returning '%s'", r);
    } else {
        SYS_DEBUG ("returning false");
        retval = gconf_value_new (GCONF_VALUE_BOOL);
    }

    return retval;
}

/******************************************************************************
 * QImage stub.
 */
#include <QImage>

bool
QImage::load (
        const QString  &fileName,
        const char     *format)
{
    Q_UNUSED (fileName);
    Q_UNUSED (format);
    SYS_DEBUG ("*** fileName = %s", SYS_STR(fileName));
    return true;
}

#include <QPixmap>
bool
QPixmap::load (
        const QString  &fileName,
        const char     *format,
        Qt::ImageConversionFlags flags)
{
    Q_UNUSED (fileName);
    Q_UNUSED (format);
    Q_UNUSED (flags);
    SYS_DEBUG ("*** fileName = %s", SYS_STR(fileName));
    return true;
}

/******************************************************************************
 * SignalSink implementation.
 */
SignalSink::SignalSink ()
{
    reset ();
}

void
SignalSink::reset ()
{
    m_WallpaperChangedCame = false;
}

void
SignalSink::wallpaperChanged ()
{
    SYS_DEBUG ("");
    m_WallpaperChangedCame = true;
}

/******************************************************************************
 * Ut_WallpaperBusinessLogic implementation.
 */
void
Ut_WallpaperBusinessLogic::init()
{
}

void
Ut_WallpaperBusinessLogic::cleanup()
{
}

static int argc = 1;
static char* app_name = (char*) "./ut_wallpaperbusinesslogic";

void
Ut_WallpaperBusinessLogic::initTestCase()
{
    bool connectSuccess;

    MyGConfDatabase["/meegotouch/theme/name"] = "MyThemeName";
    MyGConfDatabase[Wallpaper::CurrentPortraitKey] =
        "/ak/current.jpg";
    MyGConfDatabase[Wallpaper::OriginalPortraitKey] = "";

    m_App = new MApplication (argc, &app_name);

    m_Api = new WallpaperBusinessLogic;
    connectSuccess = connect (
            m_Api, SIGNAL (wallpaperChanged()),
            &m_SignalSink, SLOT (wallpaperChanged()));
    QVERIFY (connectSuccess);

    //QVERIFY (m_Api->m_EditedImage == 0);
}

void
Ut_WallpaperBusinessLogic::cleanupTestCase()
{
    delete m_Api;

    m_App->deleteLater ();
}

/*!
 * Checks the low level WallpaperITrans class, its tag methods and overloaded
 * operators.
 */
void
Ut_WallpaperBusinessLogic::testITrans ()
{
    WallpaperITrans trans1, trans2, trans4, trans5;

    SYS_DEBUG ("Checking default values of WallpaperITrans...");
    QVERIFY (trans1.x() == 0);
    QVERIFY (trans1.y() == 0);
    QVERIFY (trans1.scale() == 1.0);
    QVERIFY (trans1.orientation() == M::Landscape);

    SYS_DEBUG ("Checking the set functions...");
    trans2.setOffset (QPointF(10, 11));
    trans2.setScale (2.0);
    trans2.setOrientation (M::Portrait);
    trans2.setExpectedSize (QSize(864, 480));

    QVERIFY (trans2.x() == 10);
    QVERIFY (trans2.y() == 11);
    QVERIFY (trans2.offset() == QPointF(10, 11));
    QVERIFY (trans2.scale() == 2.0);
    QVERIFY (trans2.orientation() == M::Portrait);
    QVERIFY (trans2.expectedWidth() == 864);
    QVERIFY (trans2.expectedHeight() == 480);

    trans2 += QPointF(1.0, 1.0);
    QVERIFY (trans2.offset() == QPointF(11, 12));

    SYS_DEBUG ("Testing the copy constructor.");
    WallpaperITrans trans3 (trans2);
    QVERIFY (trans3.x() == 11);
    QVERIFY (trans3.y() == 12);
    QVERIFY (trans3.scale() == 2.0);
    QVERIFY (trans3.orientation() == M::Portrait);
    QVERIFY (trans3.expectedWidth() == 864);
    QVERIFY (trans3.expectedHeight() == 480);

    SYS_DEBUG ("testing operator=...");
    trans1 = trans2;
    QVERIFY (trans1.x() == 11);
    QVERIFY (trans1.y() == 12);
    QVERIFY (trans1.scale() == 2.0);
    QVERIFY (trans1.orientation() == M::Portrait);
    QVERIFY (trans1.expectedWidth() == 864);
    QVERIFY (trans1.expectedHeight() == 480);
    QVERIFY (trans1.expectedSize() == QSize(864, 480));

    SYS_DEBUG ("Testing operator*...");
    SYS_DEBUG ("*** trans1.scale() = %d", trans2 * 2);
    QVERIFY (trans2 * 2 == 4);

    QVERIFY (trans4.noTransformation ());
    QVERIFY (trans4.rotation() == 0.0);
    trans4.setRotation(90.0);
    QVERIFY (!trans4.noTransformation ());
    QVERIFY (trans4.rotation() == 90.0);
    trans4.modRotation(1200.0);
    QVERIFY (trans4.rotation() > 90.0);

    QVERIFY (trans5.noTransformation ());
    trans5.modScale(1200);
    QVERIFY (!trans5.noTransformation ());
    QVERIFY (trans5.scale() > 1.0);

    trans5.setScale (0.1);
    trans5.modScale (-1200);
    trans5.modScale (-1200);
    trans5.modScale (-1200);
    QVERIFY (trans5.scale() > 0.0);
}

/*!
 * Checks if the GConfItem objects are created with the right keys.
 */
void
Ut_WallpaperBusinessLogic::testGConfItems ()
{
    QVERIFY (m_Api->m_PPItem != NULL);
    QVERIFY (m_Api->m_PPItem->key() == Wallpaper::CurrentPortraitKey);

    QVERIFY (m_Api->m_POItem != NULL);
    QVERIFY (m_Api->m_POItem->key() == Wallpaper::OriginalPortraitKey);

    QVERIFY (m_Api->m_PHItem != NULL);
    QVERIFY (m_Api->m_PHItem->key() == Wallpaper::PortraitHistoryKey);
}

/*!
 */
void
Ut_WallpaperBusinessLogic::testCurrentWallpaper ()
{
    QString currentFilePath;
    QString originalFilePath;

    m_Api->currentWallpaper (currentFilePath, originalFilePath);
    QVERIFY (currentFilePath == "/ak/current.jpg");
    QVERIFY (originalFilePath.isEmpty());

    SYS_DEBUG ("*** currentFilePath  = %s", SYS_STR(currentFilePath));
    SYS_DEBUG ("*** originalFilePath = %s", SYS_STR(originalFilePath));
}

void
Ut_WallpaperBusinessLogic::testSceneSize ()
{
    QSize size = m_Api->sceneSize ();
    QSize expected = QSize (480, 854);

    QVERIFY (size == expected);
}

void
Ut_WallpaperBusinessLogic::testEditedImage ()
{
    QVERIFY (!m_Api->hasEditedImage ());

    m_Api->endEdit ();
    QVERIFY (!m_Api->hasEditedImage ());

}

/******************************************************************************
 * Private functions.
 */
QTEST_APPLESS_MAIN(Ut_WallpaperBusinessLogic)

<|endoftext|>


<commit_before>#include "stdafx.h"
#include "window-video.h"

static HWND         g_hVideo = NULL;

#define MAX_LOADSTRING 100

// Video_WndProc
LRESULT CALLBACK Video_WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{ int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	switch (message)
	{
		case WM_PAINT:
			hdc = BeginPaint(hWnd, &ps);
			EndPaint(hWnd, &ps);
			break;

    case WM_CLOSE:
      { ShowWindow( hWnd, FALSE );
      }
	    break;

    case WM_DESTROY:
      { PostQuitMessage(0);
      }
		  break;

		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
	}

	return 0;
}

ATOM Video_RegisterClass ( HINSTANCE hInstance )
{   //
    // Register class
    //
    WNDCLASSEX wcex;
    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style          = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = Video_WndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = LoadIcon(hInstance, (LPCTSTR)IDI_FETCH);
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName   = NULL;
    wcex.lpszClassName  = VIDEO_CLASS_NAME;
    wcex.hIconSm        = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_FETCH);
    if( !RegisterClassEx(&wcex) )
    return FALSE;
}

HWND Video_InitInstance ( HINSTANCE hInstance, int nCmdShow)
{ HWND hWnd;
  TCHAR        szTitle[MAX_LOADSTRING] = "Video:\0";  // The title bar text

  LoadString(hInstance, IDS_APP_TITLE, szTitle+6, MAX_LOADSTRING-6);
  //
  // Create window
  //
  RECT rc = { 0, 0, 640, 480 };
  AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE );
  g_hVideo = CreateWindow( VIDEO_CLASS_NAME,
                           "Direct3D 10 Tutorial 0: Setting Up Window",
                           WS_OVERLAPPEDWINDOW,
                           CW_USEDEFAULT,
                           CW_USEDEFAULT,
                           rc.right - rc.left,
                           rc.bottom - rc.top,
                           NULL,
                           NULL,
                           hInstance,
                           NULL);

  if( !g_hVideo )
      return FALSE;

  ShowWindow( g_hVideo, nCmdShow );
}

DWORD WINAPI Video_Main_Thread( LPVOID lparam )
{	MSG msg = {0};

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	return 0;
}<commit_msg>WIP: Going through DirectX tutorial<commit_after>#include "stdafx.h"
#include <d3d10.h>
#include <d3dx10.h>

#include "window-video.h"

static HWND         g_hVideo = NULL;

D3D10_DRIVER_TYPE       g_driverType = D3D10_DRIVER_TYPE_NULL;
ID3D10Device*           g_pd3dDevice = NULL;
IDXGISwapChain*         g_pSwapChain = NULL;
ID3D10RenderTargetView* g_pRenderTargetView = NULL;

#define MAX_LOADSTRING 100

// Video_WndProc
LRESULT CALLBACK Video_WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{ int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	switch (message)
	{
		case WM_PAINT:
			hdc = BeginPaint(hWnd, &ps);
			EndPaint(hWnd, &ps);
			break;

    case WM_CLOSE:
      { ShowWindow( hWnd, FALSE );
      }
	    break;

    case WM_DESTROY:
      { PostQuitMessage(0);
      }
		  break;

		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
	}

	return 0;
}

ATOM Video_RegisterClass ( HINSTANCE hInstance )
{   //
    // Register class
    //
    WNDCLASSEX wcex;
    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style          = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = Video_WndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = LoadIcon(hInstance, (LPCTSTR)IDI_FETCH);
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName   = NULL;
    wcex.lpszClassName  = VIDEO_CLASS_NAME;
    wcex.hIconSm        = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_FETCH);
    if( !RegisterClassEx(&wcex) )
      return E_FAIL;
    return S_OK;
}

HWND Video_InitWindow ( HINSTANCE hInstance, int nCmdShow)
{ HWND hWnd;
  TCHAR        szTitle[MAX_LOADSTRING] = "Video:\0";  // The title bar text

  LoadString(hInstance, IDS_APP_TITLE, szTitle+6, MAX_LOADSTRING-6);

  if( FAILED( Video_RegisterClass(hInistance) ) )
    return E_FAIL;

  //
  // Create window
  //
  RECT rc = { 0, 0, 640, 480 };
  AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE );
  g_hVideo = CreateWindow( VIDEO_CLASS_NAME,
                           "Direct3D 10 Tutorial 0: Setting Up Window",
                           WS_OVERLAPPEDWINDOW,
                           CW_USEDEFAULT,
                           CW_USEDEFAULT,
                           rc.right - rc.left,
                           rc.bottom - rc.top,
                           NULL,
                           NULL,
                           hInstance,
                           NULL);

  if( !g_hVideo )
      return FALSE;

  ShowWindow( g_hVideo, nCmdShow );
}

//--------------------------------------------------------------------------------------
// Create Direct3D device and swap chain
//--------------------------------------------------------------------------------------
HRESULT InitDevice()
{
    HRESULT hr = S_OK;;

    RECT rc;
    GetClientRect( g_hVideo, &rc );
    UINT width = rc.right - rc.left;
    UINT height = rc.bottom - rc.top;

    UINT createDeviceFlags = 0;
#ifdef _DEBUG
    createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG;
#endif

    D3D10_DRIVER_TYPE driverTypes[] =
    {
        D3D10_DRIVER_TYPE_HARDWARE,
        D3D10_DRIVER_TYPE_REFERENCE,
    };
    UINT numDriverTypes = sizeof( driverTypes ) / sizeof( driverTypes[0] );

    DXGI_SWAP_CHAIN_DESC sd;
    ZeroMemory( &sd, sizeof( sd ) );
    sd.BufferCount = 1;
    sd.BufferDesc.Width = width;
    sd.BufferDesc.Height = height;
    sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    sd.BufferDesc.RefreshRate.Numerator = 60;
    sd.BufferDesc.RefreshRate.Denominator = 1;
    sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    sd.OutputWindow = g_hVideo;
    sd.SampleDesc.Count = 1;
    sd.SampleDesc.Quality = 0;
    sd.Windowed = TRUE;

    for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ )
    {
        g_driverType = driverTypes[driverTypeIndex];
        hr = D3D10CreateDeviceAndSwapChain( NULL,             //adapter
                                            g_driverType,     //driver type
                                            NULL,             //software module
                                            createDeviceFlags,//flags   -  optionally set debug mode
                                            D3D10_SDK_VERSION,//version
                                            &sd,              //swap chain desciption
                                            &g_pSwapChain,    //swap chain
                                            &g_pd3dDevice );  //device
        if( SUCCEEDED( hr ) )
            break;
    }
    if( FAILED( hr ) )
        return hr;

    // Create a render target view
    ID3D10Texture2D* pBackBuffer;
    hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D10Texture2D ), ( LPVOID* )&pBackBuffer );
    if( FAILED( hr ) )
        return hr;

    hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRenderTargetView );
    pBackBuffer->Release();
    if( FAILED( hr ) )
        return hr;

    g_pd3dDevice->OMSetRenderTargets( 1, &g_pRenderTargetView, NULL );

    // Setup the viewport
    D3D10_VIEWPORT vp;
    vp.Width = width;
    vp.Height = height;
    vp.MinDepth = 0.0f;
    vp.MaxDepth = 1.0f;
    vp.TopLeftX = 0;
    vp.TopLeftY = 0;
    g_pd3dDevice->RSSetViewports( 1, &vp );

    return S_OK;
}

DWORD WINAPI Video_Main_Thread( LPVOID lparam )
{	MSG msg = {0};

  if( FAILED( InitWindow( hInstance, nCmdShow ) ) )
      return 0;

  if( FAILED( InitDevice() ) )
  {
      CleanupDevice();
      return 0;
  }

  // Main message loop
  MSG msg = {0};
  while( WM_QUIT != msg.message )
  {
      if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
      {
          TranslateMessage( &msg );
          DispatchMessage( &msg );
      }
      else
      {
          Render();
      }
  }

  CleanupDevice();

  return ( int )msg.wParam;
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: stgio.cxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:56:52 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include "stg.hxx"
#include "stgelem.hxx"
#include "stgcache.hxx"
#include "stgstrms.hxx"
#include "stgdir.hxx"
#include "stgio.hxx"
#pragma hdrstop

///////////////////////////// class StgIo //////////////////////////////

// This class holds the storage header and all internal streams.

StgIo::StgIo() : StgCache()
{
    pTOC      = NULL;
    pDataFAT  = NULL;
    pDataStrm = NULL;
    pFAT      = NULL;
    bCopied   = FALSE;
}

StgIo::~StgIo()
{
    delete pTOC;
    delete pDataFAT;
    delete pDataStrm;
    delete pFAT;
}

// Load the header. Do not set an error code if the header is invalid.

BOOL StgIo::Load()
{
    if( pStrm )
    {
        if( aHdr.Load( *this ) )
            if( aHdr.Check() )
                SetupStreams();
            else
                return FALSE;
    }
    return Good();
}

// Set up an initial, empty storage

BOOL StgIo::Init()
{
    aHdr.Init();
    SetupStreams();
    return CommitAll();
}

void StgIo::SetupStreams()
{
    delete pTOC;
    delete pDataFAT;
    delete pDataStrm;
    delete pFAT;
    pTOC      = NULL;
    pDataFAT  = NULL;
    pDataStrm = NULL;
    pFAT      = NULL;
    ResetError();
    SetPhysPageSize( 1 << aHdr.GetPageSize() );
    pFAT = new StgFATStrm( *this );
    pTOC = new StgDirStrm( *this );
    if( !GetError() )
    {
        StgDirEntry* pRoot = pTOC->GetRoot();
        if( pRoot )
        {
            pDataFAT = new StgDataStrm( *this, aHdr.GetDataFATStart(), -1 );
            pDataStrm = new StgDataStrm( *this, pRoot );
            pDataFAT->SetIncrement( 1 << aHdr.GetPageSize() );
            pDataStrm->SetIncrement( GetDataPageSize() );
            pDataStrm->SetEntry( *pRoot );
        }
        else
            SetError( SVSTREAM_FILEFORMAT_ERROR );
    }
}

// get the logical data page size

short StgIo::GetDataPageSize()
{
    return 1 << aHdr.GetDataPageSize();
}

// Commit everything

BOOL StgIo::CommitAll()
{
    // Store the data (all streams and the TOC)
    if( pTOC->Store() )
    {
        if( Commit( NULL ) )
        {
            aHdr.SetDataFATStart( pDataFAT->GetStart() );
            aHdr.SetDataFATSize( pDataFAT->GetPages() );
            aHdr.SetTOCStart( pTOC->GetStart() );
            if( aHdr.Store( *this ) )
            {
                pStrm->Flush();
                ULONG n = pStrm->GetError();
                SetError( n );
#ifdef DBG_UTIL
                if( n==0 ) ValidateFATs();
#endif
                return BOOL( n == 0 );
            }
        }
    }
    SetError( SVSTREAM_WRITE_ERROR );
    return FALSE;
}

class EasyFat
{
    INT32 *pFat;
    BOOL  *pFree;
    INT32 nPages;
    INT32 nPageSize;

public:
    EasyFat( StgIo & rIo, StgStrm *pFatStream, INT32 nPSize );
    ~EasyFat() { delete pFat; delete pFree; }
    INT32 GetPageSize() { return nPageSize; }
    INT32 Count() { return nPages; }
    INT32 operator[]( INT32 nOffset ) { return pFat[ nOffset ]; }

    ULONG Mark( INT32 nPage, INT32 nCount, INT32 nExpect );
    BOOL HasUnrefChains();
};

EasyFat::EasyFat( StgIo& rIo, StgStrm* pFatStream, INT32 nPSize )
{
    nPages = pFatStream->GetSize() >> 2;
    nPageSize = nPSize;
    pFat = new INT32[ nPages ];
    pFree = new BOOL[ nPages ];

    StgPage *pPage;
    INT32 nFatPageSize = 1 << rIo.aHdr.GetPageSize() - 2;

    for( INT32 nPage = 0; nPage < nPages; nPage++ )
    {
        if( ! (nPage % nFatPageSize) )
        {
            pFatStream->Pos2Page( nPage << 2 );
            INT32 nPhysPage = pFatStream->GetPage();
            pPage = rIo.Get( nPhysPage, TRUE );
        }

        pFat[ nPage ] = pPage->GetPage( ( nPage % nFatPageSize ) );
        pFree[ nPage ] = TRUE;
    }
}

BOOL EasyFat::HasUnrefChains()
{
    for( INT32 nPage = 0; nPage < nPages; nPage++ )
    {
        if( pFree[ nPage ] && pFat[ nPage ] != -1 )
            return TRUE;
    }
    return FALSE;
}

ULONG EasyFat::Mark( INT32 nPage, INT32 nCount, INT32 nExpect )
{
    if( nCount > 0 )
        --nCount /= GetPageSize(), nCount++;

    INT32 nCurPage = nPage;
    while( nCount != 0 )
    {
        pFree[ nCurPage ] = FALSE;
        nCurPage = pFat[ nCurPage ];
        //Stream zu lang
        if( nCurPage != nExpect && nCount == 1 )
            return FAT_WRONGLENGTH;
        //Stream zu kurz
        if( nCurPage == nExpect && nCount != 1 && nCount != -1 )
            return FAT_WRONGLENGTH;
        // letzter Block bei Stream ohne Laenge
        if( nCurPage == nExpect && nCount == -1 )
            nCount = 1;
        if( nCount != -1 )
            nCount--;
        // Naechster Block nicht in der FAT
        if( nCount && ( nCurPage < 0 || nCurPage >= nPages ) )
            return FAT_OUTOFBOUNDS;
    }
    return FAT_OK;
}

class Validator
{
    ULONG nError;

    EasyFat aSmallFat;
    EasyFat aFat;

    StgIo &rIo;

    ULONG ValidateMasterFATs();
    ULONG ValidateDirectoryEntries();
    ULONG FindUnrefedChains();
    ULONG MarkAll( StgDirEntry *pEntry );

public:

    Validator( StgIo &rIo );
    BOOL IsError() { return nError != 0; }
};

Validator::Validator( StgIo &rIoP )
    : aSmallFat( rIoP, rIoP.pDataFAT, 1 << rIoP.aHdr.GetDataPageSize() ),
      aFat( rIoP, rIoP.pFAT, 1 << rIoP.aHdr.GetPageSize() ),
      rIo( rIoP )
{
    ULONG nErr = nError = FAT_OK;

    if( ( nErr = ValidateMasterFATs() ) != FAT_OK )
        nError = nErr;
    else if(    ( nErr = ValidateDirectoryEntries() ) != FAT_OK )
        nError = nErr;
    else if(    ( nErr = FindUnrefedChains()) != FAT_OK )
        nError = nErr;
}

ULONG Validator::ValidateMasterFATs()
{
    INT32 nCount = rIo.aHdr.GetFATSize();
    ULONG nErr;
    for( INT32 i = 0; i < nCount; i++ )
    {
        if( ( nErr = aFat.Mark(
            rIo.pFAT->GetPage( i, FALSE ), aFat.GetPageSize(), -3 ))
            != FAT_OK )
            return nErr;
    }
    if( rIo.aHdr.GetMasters() )
        if( ( nErr = aFat.Mark(
            rIo.aHdr.GetFATChain( ), aFat.GetPageSize(), -4 )) != FAT_OK )
            return nErr;
    return FAT_OK;
}

ULONG Validator::MarkAll( StgDirEntry *pEntry )
{
    StgIterator aIter( *pEntry );
    ULONG nErr = FAT_OK;
    for( StgDirEntry* p = aIter.First(); p ; p = aIter.Next() )
    {
        if( p->aEntry.GetType() == STG_STORAGE )
        {
            nErr = MarkAll( p );
            if( nErr != FAT_OK )
                return nErr;
        }
        else
        {
            INT32 nSize = p->aEntry.GetSize();
            if( nSize < rIo.aHdr.GetThreshold()  )
                nErr = aSmallFat.Mark( p->aEntry.GetStartPage(),nSize, -2 );
            else
                nErr = aFat.Mark( p->aEntry.GetStartPage(),nSize, -2 );
            if( nErr != FAT_OK )
                return nErr;
        }
    }
    return FAT_OK;
}

ULONG Validator::ValidateDirectoryEntries()
{
    // Normale DirEntries
    ULONG nErr = MarkAll( rIo.pTOC->GetRoot() );
    if( nErr != FAT_OK )
        return nErr;
    // Small Data
    nErr = aFat.Mark( rIo.pTOC->GetRoot()->aEntry.GetStartPage(),
                 rIo.pTOC->GetRoot()->aEntry.GetSize(), -2 );
    if( nErr != FAT_OK )
        return nErr;
    // Small Data FAT
    nErr = aFat.Mark(
        rIo.aHdr.GetDataFATStart(),
        rIo.aHdr.GetDataFATSize() * aFat.GetPageSize(), -2 );
    if( nErr != FAT_OK )
        return nErr;
    // TOC
    nErr = aFat.Mark(
        rIo.aHdr.GetTOCStart(), -1, -2 );
    return nErr;
}

ULONG Validator::FindUnrefedChains()
{
    if( aSmallFat.HasUnrefChains() ||
        aFat.HasUnrefChains() )
        return FAT_UNREFCHAIN;
    else
        return FAT_OK;
}

Link StgIo::aErrorLink;

void StgIo::SetErrorLink( const Link& rLink )
{
    aErrorLink = rLink;
}

ULONG StgIo::ValidateFATs()
{
    if( bFile )
    {
        Validator *pV = new Validator( *this );
        BOOL bRet1 = !pV->IsError(), bRet2 = TRUE ;
        delete pV;
        SvFileStream *pFileStrm = ( SvFileStream *) GetStrm();
        StgIo aIo;
        if( aIo.Open( pFileStrm->GetFileName(),
                      STREAM_READ  | STREAM_SHARE_DENYNONE) &&
            aIo.Load() )
        {
            pV = new Validator( aIo );
            bRet2 = !pV->IsError();
            delete pV;
        }

        ULONG nErr;
        if( bRet1 != bRet2 )
            nErr = bRet1 ? FAT_ONFILEERROR : FAT_INMEMORYERROR;
        else nErr = bRet1 ? FAT_OK : FAT_BOTHERROR;
        if( nErr != FAT_OK && !bCopied )
        {
            StgLinkArg aArg;
            aArg.aFile = pFileStrm->GetFileName();
            aArg.nErr = nErr;
            aErrorLink.Call( &aArg );
            bCopied = TRUE;
        }
//      DBG_ASSERT( nErr == FAT_OK ,"Storage kaputt");
        return nErr;
    }
//  DBG_ERROR("Validiere nicht (kein FileStorage)");
    return FAT_OK;
}

<commit_msg>INTEGRATION: CWS ooo20031216 (1.1.1.1.146); FILE MERGED 2003/12/24 11:39:09 waratah 1.1.1.1.146.1: #i1858# work around a warning issued by gcc<commit_after>/*************************************************************************
 *
 *  $RCSfile: stgio.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2004-02-04 12:31:21 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include "stg.hxx"
#include "stgelem.hxx"
#include "stgcache.hxx"
#include "stgstrms.hxx"
#include "stgdir.hxx"
#include "stgio.hxx"
#pragma hdrstop

///////////////////////////// class StgIo //////////////////////////////

// This class holds the storage header and all internal streams.

StgIo::StgIo() : StgCache()
{
    pTOC      = NULL;
    pDataFAT  = NULL;
    pDataStrm = NULL;
    pFAT      = NULL;
    bCopied   = FALSE;
}

StgIo::~StgIo()
{
    delete pTOC;
    delete pDataFAT;
    delete pDataStrm;
    delete pFAT;
}

// Load the header. Do not set an error code if the header is invalid.

BOOL StgIo::Load()
{
    if( pStrm )
    {
        if( aHdr.Load( *this ) )
            if( aHdr.Check() )
                SetupStreams();
            else
                return FALSE;
    }
    return Good();
}

// Set up an initial, empty storage

BOOL StgIo::Init()
{
    aHdr.Init();
    SetupStreams();
    return CommitAll();
}

void StgIo::SetupStreams()
{
    delete pTOC;
    delete pDataFAT;
    delete pDataStrm;
    delete pFAT;
    pTOC      = NULL;
    pDataFAT  = NULL;
    pDataStrm = NULL;
    pFAT      = NULL;
    ResetError();
    SetPhysPageSize( 1 << aHdr.GetPageSize() );
    pFAT = new StgFATStrm( *this );
    pTOC = new StgDirStrm( *this );
    if( !GetError() )
    {
        StgDirEntry* pRoot = pTOC->GetRoot();
        if( pRoot )
        {
            pDataFAT = new StgDataStrm( *this, aHdr.GetDataFATStart(), -1 );
            pDataStrm = new StgDataStrm( *this, pRoot );
            pDataFAT->SetIncrement( 1 << aHdr.GetPageSize() );
            pDataStrm->SetIncrement( GetDataPageSize() );
            pDataStrm->SetEntry( *pRoot );
        }
        else
            SetError( SVSTREAM_FILEFORMAT_ERROR );
    }
}

// get the logical data page size

short StgIo::GetDataPageSize()
{
    return 1 << aHdr.GetDataPageSize();
}

// Commit everything

BOOL StgIo::CommitAll()
{
    // Store the data (all streams and the TOC)
    if( pTOC->Store() )
    {
        if( Commit( NULL ) )
        {
            aHdr.SetDataFATStart( pDataFAT->GetStart() );
            aHdr.SetDataFATSize( pDataFAT->GetPages() );
            aHdr.SetTOCStart( pTOC->GetStart() );
            if( aHdr.Store( *this ) )
            {
                pStrm->Flush();
                ULONG n = pStrm->GetError();
                SetError( n );
#ifdef DBG_UTIL
                if( n==0 ) ValidateFATs();
#endif
                return BOOL( n == 0 );
            }
        }
    }
    SetError( SVSTREAM_WRITE_ERROR );
    return FALSE;
}

class EasyFat
{
    INT32 *pFat;
    BOOL  *pFree;
    INT32 nPages;
    INT32 nPageSize;

public:
    EasyFat( StgIo & rIo, StgStrm *pFatStream, INT32 nPSize );
    ~EasyFat() { delete pFat; delete pFree; }
    INT32 GetPageSize() { return nPageSize; }
    INT32 Count() { return nPages; }
    INT32 operator[]( INT32 nOffset ) { return pFat[ nOffset ]; }

    ULONG Mark( INT32 nPage, INT32 nCount, INT32 nExpect );
    BOOL HasUnrefChains();
};

EasyFat::EasyFat( StgIo& rIo, StgStrm* pFatStream, INT32 nPSize )
{
    nPages = pFatStream->GetSize() >> 2;
    nPageSize = nPSize;
    pFat = new INT32[ nPages ];
    pFree = new BOOL[ nPages ];

    StgPage *pPage = NULL;
    INT32 nFatPageSize = 1 << rIo.aHdr.GetPageSize() - 2;

    for( INT32 nPage = 0; nPage < nPages; nPage++ )
    {
        if( ! (nPage % nFatPageSize) )
        {
            pFatStream->Pos2Page( nPage << 2 );
            INT32 nPhysPage = pFatStream->GetPage();
            pPage = rIo.Get( nPhysPage, TRUE );
        }

        pFat[ nPage ] = pPage->GetPage( ( nPage % nFatPageSize ) );
        pFree[ nPage ] = TRUE;
    }
}

BOOL EasyFat::HasUnrefChains()
{
    for( INT32 nPage = 0; nPage < nPages; nPage++ )
    {
        if( pFree[ nPage ] && pFat[ nPage ] != -1 )
            return TRUE;
    }
    return FALSE;
}

ULONG EasyFat::Mark( INT32 nPage, INT32 nCount, INT32 nExpect )
{
    if( nCount > 0 )
        --nCount /= GetPageSize(), nCount++;

    INT32 nCurPage = nPage;
    while( nCount != 0 )
    {
        pFree[ nCurPage ] = FALSE;
        nCurPage = pFat[ nCurPage ];
        //Stream zu lang
        if( nCurPage != nExpect && nCount == 1 )
            return FAT_WRONGLENGTH;
        //Stream zu kurz
        if( nCurPage == nExpect && nCount != 1 && nCount != -1 )
            return FAT_WRONGLENGTH;
        // letzter Block bei Stream ohne Laenge
        if( nCurPage == nExpect && nCount == -1 )
            nCount = 1;
        if( nCount != -1 )
            nCount--;
        // Naechster Block nicht in der FAT
        if( nCount && ( nCurPage < 0 || nCurPage >= nPages ) )
            return FAT_OUTOFBOUNDS;
    }
    return FAT_OK;
}

class Validator
{
    ULONG nError;

    EasyFat aSmallFat;
    EasyFat aFat;

    StgIo &rIo;

    ULONG ValidateMasterFATs();
    ULONG ValidateDirectoryEntries();
    ULONG FindUnrefedChains();
    ULONG MarkAll( StgDirEntry *pEntry );

public:

    Validator( StgIo &rIo );
    BOOL IsError() { return nError != 0; }
};

Validator::Validator( StgIo &rIoP )
    : aSmallFat( rIoP, rIoP.pDataFAT, 1 << rIoP.aHdr.GetDataPageSize() ),
      aFat( rIoP, rIoP.pFAT, 1 << rIoP.aHdr.GetPageSize() ),
      rIo( rIoP )
{
    ULONG nErr = nError = FAT_OK;

    if( ( nErr = ValidateMasterFATs() ) != FAT_OK )
        nError = nErr;
    else if(    ( nErr = ValidateDirectoryEntries() ) != FAT_OK )
        nError = nErr;
    else if(    ( nErr = FindUnrefedChains()) != FAT_OK )
        nError = nErr;
}

ULONG Validator::ValidateMasterFATs()
{
    INT32 nCount = rIo.aHdr.GetFATSize();
    ULONG nErr;
    for( INT32 i = 0; i < nCount; i++ )
    {
        if( ( nErr = aFat.Mark(
            rIo.pFAT->GetPage( i, FALSE ), aFat.GetPageSize(), -3 ))
            != FAT_OK )
            return nErr;
    }
    if( rIo.aHdr.GetMasters() )
        if( ( nErr = aFat.Mark(
            rIo.aHdr.GetFATChain( ), aFat.GetPageSize(), -4 )) != FAT_OK )
            return nErr;
    return FAT_OK;
}

ULONG Validator::MarkAll( StgDirEntry *pEntry )
{
    StgIterator aIter( *pEntry );
    ULONG nErr = FAT_OK;
    for( StgDirEntry* p = aIter.First(); p ; p = aIter.Next() )
    {
        if( p->aEntry.GetType() == STG_STORAGE )
        {
            nErr = MarkAll( p );
            if( nErr != FAT_OK )
                return nErr;
        }
        else
        {
            INT32 nSize = p->aEntry.GetSize();
            if( nSize < rIo.aHdr.GetThreshold()  )
                nErr = aSmallFat.Mark( p->aEntry.GetStartPage(),nSize, -2 );
            else
                nErr = aFat.Mark( p->aEntry.GetStartPage(),nSize, -2 );
            if( nErr != FAT_OK )
                return nErr;
        }
    }
    return FAT_OK;
}

ULONG Validator::ValidateDirectoryEntries()
{
    // Normale DirEntries
    ULONG nErr = MarkAll( rIo.pTOC->GetRoot() );
    if( nErr != FAT_OK )
        return nErr;
    // Small Data
    nErr = aFat.Mark( rIo.pTOC->GetRoot()->aEntry.GetStartPage(),
                 rIo.pTOC->GetRoot()->aEntry.GetSize(), -2 );
    if( nErr != FAT_OK )
        return nErr;
    // Small Data FAT
    nErr = aFat.Mark(
        rIo.aHdr.GetDataFATStart(),
        rIo.aHdr.GetDataFATSize() * aFat.GetPageSize(), -2 );
    if( nErr != FAT_OK )
        return nErr;
    // TOC
    nErr = aFat.Mark(
        rIo.aHdr.GetTOCStart(), -1, -2 );
    return nErr;
}

ULONG Validator::FindUnrefedChains()
{
    if( aSmallFat.HasUnrefChains() ||
        aFat.HasUnrefChains() )
        return FAT_UNREFCHAIN;
    else
        return FAT_OK;
}

Link StgIo::aErrorLink;

void StgIo::SetErrorLink( const Link& rLink )
{
    aErrorLink = rLink;
}

ULONG StgIo::ValidateFATs()
{
    if( bFile )
    {
        Validator *pV = new Validator( *this );
        BOOL bRet1 = !pV->IsError(), bRet2 = TRUE ;
        delete pV;
        SvFileStream *pFileStrm = ( SvFileStream *) GetStrm();
        StgIo aIo;
        if( aIo.Open( pFileStrm->GetFileName(),
                      STREAM_READ  | STREAM_SHARE_DENYNONE) &&
            aIo.Load() )
        {
            pV = new Validator( aIo );
            bRet2 = !pV->IsError();
            delete pV;
        }

        ULONG nErr;
        if( bRet1 != bRet2 )
            nErr = bRet1 ? FAT_ONFILEERROR : FAT_INMEMORYERROR;
        else nErr = bRet1 ? FAT_OK : FAT_BOTHERROR;
        if( nErr != FAT_OK && !bCopied )
        {
            StgLinkArg aArg;
            aArg.aFile = pFileStrm->GetFileName();
            aArg.nErr = nErr;
            aErrorLink.Call( &aArg );
            bCopied = TRUE;
        }
//      DBG_ASSERT( nErr == FAT_OK ,"Storage kaputt");
        return nErr;
    }
//  DBG_ERROR("Validiere nicht (kein FileStorage)");
    return FAT_OK;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: appedit.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: gh $ $Date: 2002-04-11 08:38:47 $
 *
 *  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 _APPEDIT_HXX
#define _APPEDIT_HXX

#ifndef _SCRBAR_HXX //autogen
#include <vcl/scrbar.hxx>
#endif

#include "appwin.hxx"
#include "textedit.hxx"

class BasicFrame;

class AppEdit : public AppWin    {  // Editor-Window:
public:
    ScrollBar *pVScroll;
    ScrollBar *pHScroll;
    void SetScrollBarRanges();
    ULONG nCurTextWidth;
private:
    void InitScrollBars();
protected:
    DECL_LINK( Scroll, ScrollBar* );
public:
    TYPEINFO();
    AppEdit( BasicFrame* );
    ~AppEdit();
    USHORT GetLineNr();             // Aktuelle Zeilennummer
    FileType GetFileType();         // Liefert den Filetype
    virtual long InitMenu( Menu* );         // Initialisierung des Menues
    virtual long DeInitMenu( Menu* );   // rcksetzen, so da wieder alle Shortcuts enabled sind
    virtual void Command( const CommandEvent& rCEvt );  // Kommando-Handler
    void Resize();
    void PostLoad();                // Nachbearbeiten des geladenen (Source am Modul setzen)
    void PostSaveAs();              // Nachbearbeiten des Modils ...
    void Mark( short, short, short );// Text markieren
    void Highlight( USHORT nLine, USHORT nCol1, USHORT nCol2 );
    virtual BOOL ReloadAllowed(){ return !StarBASIC::IsRunning(); }
    virtual void LoadIniFile();     // (re)load ini file after change
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.336); FILE MERGED 2005/09/05 14:35:49 rt 1.3.336.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: appedit.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 21:11:06 $
 *
 *  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 _APPEDIT_HXX
#define _APPEDIT_HXX

#ifndef _SCRBAR_HXX //autogen
#include <vcl/scrbar.hxx>
#endif

#include "appwin.hxx"
#include "textedit.hxx"

class BasicFrame;

class AppEdit : public AppWin    {  // Editor-Window:
public:
    ScrollBar *pVScroll;
    ScrollBar *pHScroll;
    void SetScrollBarRanges();
    ULONG nCurTextWidth;
private:
    void InitScrollBars();
protected:
    DECL_LINK( Scroll, ScrollBar* );
public:
    TYPEINFO();
    AppEdit( BasicFrame* );
    ~AppEdit();
    USHORT GetLineNr();             // Aktuelle Zeilennummer
    FileType GetFileType();         // Liefert den Filetype
    virtual long InitMenu( Menu* );         // Initialisierung des Menues
    virtual long DeInitMenu( Menu* );   // rcksetzen, so da wieder alle Shortcuts enabled sind
    virtual void Command( const CommandEvent& rCEvt );  // Kommando-Handler
    void Resize();
    void PostLoad();                // Nachbearbeiten des geladenen (Source am Modul setzen)
    void PostSaveAs();              // Nachbearbeiten des Modils ...
    void Mark( short, short, short );// Text markieren
    void Highlight( USHORT nLine, USHORT nCol1, USHORT nCol2 );
    virtual BOOL ReloadAllowed(){ return !StarBASIC::IsRunning(); }
    virtual void LoadIniFile();     // (re)load ini file after change
};

#endif
<|endoftext|>


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

#include "content/browser/renderer_host/ime_adapter_android.h"

#include <android/input.h>

#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_android.h"
#include "content/common/view_messages.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "jni/ImeAdapter_jni.h"
#include "third_party/WebKit/public/web/WebCompositionUnderline.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"

using base::android::AttachCurrentThread;
using base::android::ConvertJavaStringToUTF16;

namespace content {
namespace {

// Maps a java KeyEvent into a NativeWebKeyboardEvent.
// |java_key_event| is used to maintain a globalref for KeyEvent.
// |action| will help determine the WebInputEvent type.
// type, |modifiers|, |time_ms|, |key_code|, |unicode_char| is used to create
// WebKeyboardEvent. |key_code| is also needed ad need to treat the enter key
// as a key press of character \r.
NativeWebKeyboardEvent NativeWebKeyboardEventFromKeyEvent(
    JNIEnv* env,
    jobject java_key_event,
    int action,
    int modifiers,
    long time_ms,
    int key_code,
    bool is_system_key,
    int unicode_char) {
  WebKit::WebInputEvent::Type type = WebKit::WebInputEvent::Undefined;
  if (action == AKEY_EVENT_ACTION_DOWN)
    type = WebKit::WebInputEvent::RawKeyDown;
  else if (action == AKEY_EVENT_ACTION_UP)
    type = WebKit::WebInputEvent::KeyUp;
  return NativeWebKeyboardEvent(java_key_event, type, modifiers,
      time_ms, key_code, unicode_char, is_system_key);
}

}  // anonymous namespace

bool RegisterImeAdapter(JNIEnv* env) {
  if (!RegisterNativesImpl(env))
    return false;

  Java_ImeAdapter_initializeWebInputEvents(env,
                                           WebKit::WebInputEvent::RawKeyDown,
                                           WebKit::WebInputEvent::KeyUp,
                                           WebKit::WebInputEvent::Char,
                                           WebKit::WebInputEvent::ShiftKey,
                                           WebKit::WebInputEvent::AltKey,
                                           WebKit::WebInputEvent::ControlKey,
                                           WebKit::WebInputEvent::CapsLockOn,
                                           WebKit::WebInputEvent::NumLockOn);
  // TODO(miguelg): remove date time related enums after
  // https://bugs.webkit.org/show_bug.cgi?id=100935.
  Java_ImeAdapter_initializeTextInputTypes(
      env,
      ui::TEXT_INPUT_TYPE_NONE,
      ui::TEXT_INPUT_TYPE_TEXT,
      ui::TEXT_INPUT_TYPE_TEXT_AREA,
      ui::TEXT_INPUT_TYPE_PASSWORD,
      ui::TEXT_INPUT_TYPE_SEARCH,
      ui::TEXT_INPUT_TYPE_URL,
      ui::TEXT_INPUT_TYPE_EMAIL,
      ui::TEXT_INPUT_TYPE_TELEPHONE,
      ui::TEXT_INPUT_TYPE_NUMBER,
      ui::TEXT_INPUT_TYPE_DATE,
      ui::TEXT_INPUT_TYPE_DATE_TIME,
      ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL,
      ui::TEXT_INPUT_TYPE_MONTH,
      ui::TEXT_INPUT_TYPE_TIME,
      ui::TEXT_INPUT_TYPE_WEEK,
      ui::TEXT_INPUT_TYPE_CONTENT_EDITABLE);
  return true;
}

ImeAdapterAndroid::ImeAdapterAndroid(RenderWidgetHostViewAndroid* rwhva)
    : rwhva_(rwhva) {
}

ImeAdapterAndroid::~ImeAdapterAndroid() {
  JNIEnv* env = AttachCurrentThread();
  base::android::ScopedJavaLocalRef<jobject> obj = java_ime_adapter_.get(env);
  if (!obj.is_null())
    Java_ImeAdapter_detach(env, obj.obj());
}

bool ImeAdapterAndroid::SendSyntheticKeyEvent(JNIEnv*,
                                              jobject,
                                              int type,
                                              long time_ms,
                                              int key_code,
                                              int text) {
  NativeWebKeyboardEvent event(static_cast<WebKit::WebInputEvent::Type>(type),
                               0 /* modifiers */, time_ms / 1000.0, key_code,
                               text, false /* is_system_key */);
  rwhva_->SendKeyEvent(event);
  return true;
}

bool ImeAdapterAndroid::SendKeyEvent(JNIEnv* env, jobject,
                                     jobject original_key_event,
                                     int action, int modifiers,
                                     long time_ms, int key_code,
                                     bool is_system_key, int unicode_char) {
  NativeWebKeyboardEvent event = NativeWebKeyboardEventFromKeyEvent(
          env, original_key_event, action, modifiers,
          time_ms, key_code, is_system_key, unicode_char);
  bool key_down_text_insertion =
      event.type == WebKit::WebInputEvent::RawKeyDown && event.text[0];
  // If we are going to follow up with a synthetic Char event, then that's the
  // one we expect to test if it's handled or unhandled, so skip handling the
  // "real" event in the browser.
  event.skip_in_browser = key_down_text_insertion;
  rwhva_->SendKeyEvent(event);
  if (key_down_text_insertion) {
    // Send a Char event, but without an os_event since we don't want to
    // roundtrip back to java such synthetic event.
    NativeWebKeyboardEvent char_event(event);
    char_event.os_event = NULL;
    char_event.type = WebKit::WebInputEvent::Char;
    rwhva_->SendKeyEvent(char_event);
  }
  return true;
}

void ImeAdapterAndroid::SetComposingText(JNIEnv* env, jobject, jstring text,
                                         int new_cursor_pos) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  string16 text16 = ConvertJavaStringToUTF16(env, text);
  std::vector<WebKit::WebCompositionUnderline> underlines;
  underlines.push_back(
      WebKit::WebCompositionUnderline(0, text16.length(), SK_ColorBLACK,
                                      false));
  // new_cursor_position is as described in the Android API for
  // InputConnection#setComposingText, whereas the parameters for
  // ImeSetComposition are relative to the start of the composition.
  if (new_cursor_pos > 0)
    new_cursor_pos = text16.length() + new_cursor_pos - 1;

  rwhi->ImeSetComposition(text16, underlines, new_cursor_pos, new_cursor_pos);
}

void ImeAdapterAndroid::ImeBatchStateChanged(JNIEnv* env,
                                             jobject,
                                             jboolean is_begin) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->Send(new ViewMsg_ImeBatchStateChanged(rwhi->GetRoutingID(), is_begin));
}

void ImeAdapterAndroid::CommitText(JNIEnv* env, jobject, jstring text) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  string16 text16 = ConvertJavaStringToUTF16(env, text);
  rwhi->ImeConfirmComposition(text16, ui::Range::InvalidRange(), false);
}

void ImeAdapterAndroid::FinishComposingText(JNIEnv* env, jobject) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->ImeConfirmComposition(string16(), ui::Range::InvalidRange(), true);
}

void ImeAdapterAndroid::AttachImeAdapter(JNIEnv* env, jobject java_object) {
  java_ime_adapter_ = JavaObjectWeakGlobalRef(env, java_object);
}

void ImeAdapterAndroid::CancelComposition() {
  base::android::ScopedJavaLocalRef<jobject> obj =
      java_ime_adapter_.get(AttachCurrentThread());
  if (!obj.is_null())
    Java_ImeAdapter_cancelComposition(AttachCurrentThread(), obj.obj());
}

void ImeAdapterAndroid::SetEditableSelectionOffsets(JNIEnv*, jobject,
                                                    int start, int end) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->Send(new ViewMsg_SetEditableSelectionOffsets(rwhi->GetRoutingID(),
                                                     start, end));
}

void ImeAdapterAndroid::SetComposingRegion(JNIEnv*, jobject,
                                           int start, int end) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  std::vector<WebKit::WebCompositionUnderline> underlines;
  underlines.push_back(
      WebKit::WebCompositionUnderline(0, end - start, SK_ColorBLACK, false));

  rwhi->Send(new ViewMsg_SetCompositionFromExistingText(
      rwhi->GetRoutingID(), start, end, underlines));
}

void ImeAdapterAndroid::DeleteSurroundingText(JNIEnv*, jobject,
                                              int before, int after) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->Send(new ViewMsg_ExtendSelectionAndDelete(rwhi->GetRoutingID(),
                                                  before, after));
}

void ImeAdapterAndroid::Unselect(JNIEnv* env, jobject) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->Unselect();
}

void ImeAdapterAndroid::SelectAll(JNIEnv* env, jobject) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->SelectAll();
}

void ImeAdapterAndroid::Cut(JNIEnv* env, jobject) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->Cut();
}

void ImeAdapterAndroid::Copy(JNIEnv* env, jobject) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->Copy();
}

void ImeAdapterAndroid::Paste(JNIEnv* env, jobject) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->Paste();
}

void ImeAdapterAndroid::ResetImeAdapter(JNIEnv* env, jobject) {
  java_ime_adapter_.reset();
}

}  // namespace content
<commit_msg>Do not alter NativeWebKeybardEvent::os_event<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/renderer_host/ime_adapter_android.h"

#include <android/input.h>

#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "content/browser/renderer_host/render_widget_host_impl.h"
#include "content/browser/renderer_host/render_widget_host_view_android.h"
#include "content/common/view_messages.h"
#include "content/public/browser/native_web_keyboard_event.h"
#include "jni/ImeAdapter_jni.h"
#include "third_party/WebKit/public/web/WebCompositionUnderline.h"
#include "third_party/WebKit/public/web/WebInputEvent.h"

using base::android::AttachCurrentThread;
using base::android::ConvertJavaStringToUTF16;

namespace content {
namespace {

// Maps a java KeyEvent into a NativeWebKeyboardEvent.
// |java_key_event| is used to maintain a globalref for KeyEvent.
// |action| will help determine the WebInputEvent type.
// type, |modifiers|, |time_ms|, |key_code|, |unicode_char| is used to create
// WebKeyboardEvent. |key_code| is also needed ad need to treat the enter key
// as a key press of character \r.
NativeWebKeyboardEvent NativeWebKeyboardEventFromKeyEvent(
    JNIEnv* env,
    jobject java_key_event,
    int action,
    int modifiers,
    long time_ms,
    int key_code,
    bool is_system_key,
    int unicode_char) {
  WebKit::WebInputEvent::Type type = WebKit::WebInputEvent::Undefined;
  if (action == AKEY_EVENT_ACTION_DOWN)
    type = WebKit::WebInputEvent::RawKeyDown;
  else if (action == AKEY_EVENT_ACTION_UP)
    type = WebKit::WebInputEvent::KeyUp;
  return NativeWebKeyboardEvent(java_key_event, type, modifiers,
      time_ms, key_code, unicode_char, is_system_key);
}

}  // anonymous namespace

bool RegisterImeAdapter(JNIEnv* env) {
  if (!RegisterNativesImpl(env))
    return false;

  Java_ImeAdapter_initializeWebInputEvents(env,
                                           WebKit::WebInputEvent::RawKeyDown,
                                           WebKit::WebInputEvent::KeyUp,
                                           WebKit::WebInputEvent::Char,
                                           WebKit::WebInputEvent::ShiftKey,
                                           WebKit::WebInputEvent::AltKey,
                                           WebKit::WebInputEvent::ControlKey,
                                           WebKit::WebInputEvent::CapsLockOn,
                                           WebKit::WebInputEvent::NumLockOn);
  // TODO(miguelg): remove date time related enums after
  // https://bugs.webkit.org/show_bug.cgi?id=100935.
  Java_ImeAdapter_initializeTextInputTypes(
      env,
      ui::TEXT_INPUT_TYPE_NONE,
      ui::TEXT_INPUT_TYPE_TEXT,
      ui::TEXT_INPUT_TYPE_TEXT_AREA,
      ui::TEXT_INPUT_TYPE_PASSWORD,
      ui::TEXT_INPUT_TYPE_SEARCH,
      ui::TEXT_INPUT_TYPE_URL,
      ui::TEXT_INPUT_TYPE_EMAIL,
      ui::TEXT_INPUT_TYPE_TELEPHONE,
      ui::TEXT_INPUT_TYPE_NUMBER,
      ui::TEXT_INPUT_TYPE_DATE,
      ui::TEXT_INPUT_TYPE_DATE_TIME,
      ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL,
      ui::TEXT_INPUT_TYPE_MONTH,
      ui::TEXT_INPUT_TYPE_TIME,
      ui::TEXT_INPUT_TYPE_WEEK,
      ui::TEXT_INPUT_TYPE_CONTENT_EDITABLE);
  return true;
}

ImeAdapterAndroid::ImeAdapterAndroid(RenderWidgetHostViewAndroid* rwhva)
    : rwhva_(rwhva) {
}

ImeAdapterAndroid::~ImeAdapterAndroid() {
  JNIEnv* env = AttachCurrentThread();
  base::android::ScopedJavaLocalRef<jobject> obj = java_ime_adapter_.get(env);
  if (!obj.is_null())
    Java_ImeAdapter_detach(env, obj.obj());
}

bool ImeAdapterAndroid::SendSyntheticKeyEvent(JNIEnv*,
                                              jobject,
                                              int type,
                                              long time_ms,
                                              int key_code,
                                              int text) {
  NativeWebKeyboardEvent event(static_cast<WebKit::WebInputEvent::Type>(type),
                               0 /* modifiers */, time_ms / 1000.0, key_code,
                               text, false /* is_system_key */);
  rwhva_->SendKeyEvent(event);
  return true;
}

bool ImeAdapterAndroid::SendKeyEvent(JNIEnv* env, jobject,
                                     jobject original_key_event,
                                     int action, int modifiers,
                                     long time_ms, int key_code,
                                     bool is_system_key, int unicode_char) {
  NativeWebKeyboardEvent event = NativeWebKeyboardEventFromKeyEvent(
          env, original_key_event, action, modifiers,
          time_ms, key_code, is_system_key, unicode_char);
  bool key_down_text_insertion =
      event.type == WebKit::WebInputEvent::RawKeyDown && event.text[0];
  // If we are going to follow up with a synthetic Char event, then that's the
  // one we expect to test if it's handled or unhandled, so skip handling the
  // "real" event in the browser.
  event.skip_in_browser = key_down_text_insertion;
  rwhva_->SendKeyEvent(event);
  if (key_down_text_insertion) {
    // Send a Char event, but without an os_event since we don't want to
    // roundtrip back to java such synthetic event.
    NativeWebKeyboardEvent char_event(WebKit::WebInputEvent::Char, modifiers,
                                      time_ms, key_code, unicode_char,
                                      is_system_key);
    char_event.skip_in_browser = key_down_text_insertion;
    rwhva_->SendKeyEvent(char_event);
  }
  return true;
}

void ImeAdapterAndroid::SetComposingText(JNIEnv* env, jobject, jstring text,
                                         int new_cursor_pos) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  string16 text16 = ConvertJavaStringToUTF16(env, text);
  std::vector<WebKit::WebCompositionUnderline> underlines;
  underlines.push_back(
      WebKit::WebCompositionUnderline(0, text16.length(), SK_ColorBLACK,
                                      false));
  // new_cursor_position is as described in the Android API for
  // InputConnection#setComposingText, whereas the parameters for
  // ImeSetComposition are relative to the start of the composition.
  if (new_cursor_pos > 0)
    new_cursor_pos = text16.length() + new_cursor_pos - 1;

  rwhi->ImeSetComposition(text16, underlines, new_cursor_pos, new_cursor_pos);
}

void ImeAdapterAndroid::ImeBatchStateChanged(JNIEnv* env,
                                             jobject,
                                             jboolean is_begin) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->Send(new ViewMsg_ImeBatchStateChanged(rwhi->GetRoutingID(), is_begin));
}

void ImeAdapterAndroid::CommitText(JNIEnv* env, jobject, jstring text) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  string16 text16 = ConvertJavaStringToUTF16(env, text);
  rwhi->ImeConfirmComposition(text16, ui::Range::InvalidRange(), false);
}

void ImeAdapterAndroid::FinishComposingText(JNIEnv* env, jobject) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->ImeConfirmComposition(string16(), ui::Range::InvalidRange(), true);
}

void ImeAdapterAndroid::AttachImeAdapter(JNIEnv* env, jobject java_object) {
  java_ime_adapter_ = JavaObjectWeakGlobalRef(env, java_object);
}

void ImeAdapterAndroid::CancelComposition() {
  base::android::ScopedJavaLocalRef<jobject> obj =
      java_ime_adapter_.get(AttachCurrentThread());
  if (!obj.is_null())
    Java_ImeAdapter_cancelComposition(AttachCurrentThread(), obj.obj());
}

void ImeAdapterAndroid::SetEditableSelectionOffsets(JNIEnv*, jobject,
                                                    int start, int end) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->Send(new ViewMsg_SetEditableSelectionOffsets(rwhi->GetRoutingID(),
                                                     start, end));
}

void ImeAdapterAndroid::SetComposingRegion(JNIEnv*, jobject,
                                           int start, int end) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  std::vector<WebKit::WebCompositionUnderline> underlines;
  underlines.push_back(
      WebKit::WebCompositionUnderline(0, end - start, SK_ColorBLACK, false));

  rwhi->Send(new ViewMsg_SetCompositionFromExistingText(
      rwhi->GetRoutingID(), start, end, underlines));
}

void ImeAdapterAndroid::DeleteSurroundingText(JNIEnv*, jobject,
                                              int before, int after) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->Send(new ViewMsg_ExtendSelectionAndDelete(rwhi->GetRoutingID(),
                                                  before, after));
}

void ImeAdapterAndroid::Unselect(JNIEnv* env, jobject) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->Unselect();
}

void ImeAdapterAndroid::SelectAll(JNIEnv* env, jobject) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->SelectAll();
}

void ImeAdapterAndroid::Cut(JNIEnv* env, jobject) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->Cut();
}

void ImeAdapterAndroid::Copy(JNIEnv* env, jobject) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->Copy();
}

void ImeAdapterAndroid::Paste(JNIEnv* env, jobject) {
  RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From(
      rwhva_->GetRenderWidgetHost());
  if (!rwhi)
    return;

  rwhi->Paste();
}

void ImeAdapterAndroid::ResetImeAdapter(JNIEnv* env, jobject) {
  java_ime_adapter_.reset();
}

}  // namespace content
<|endoftext|>