<commit_before>/*
 * Copyright (C) 2007, 2008 Apple Inc. All Rights Reserved.
 * Copyright (C) 2007 Staikos Computing Services Inc. <info@staikos.net>
 * Copyright (C) 2007 Trolltech ASA
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "ScrollbarThemeQt.h"

#include "GraphicsContext.h"
#include "PlatformMouseEvent.h"
#include "ScrollBar.h"

#include <QApplication>
#include <QDebug>
#include <QPainter>
#include <QStyle>
#include <QStyleOptionSlider>
#include <QMenu>

namespace WebCore {

ScrollbarTheme* ScrollbarTheme::nativeTheme()
{
    static ScrollbarThemeQt theme;
    return &theme;
}

ScrollbarThemeQt::~ScrollbarThemeQt()
{
}

static QStyle::SubControl scPart(const ScrollbarPart& part)
{
    switch (part) {
        case NoPart:
            return QStyle::SC_None;
        case BackButtonPart:
            return QStyle::SC_ScrollBarSubLine;
        case BackTrackPart:
            return QStyle::SC_ScrollBarSubPage;
        case ThumbPart:
            return QStyle::SC_ScrollBarSlider;
        case ForwardTrackPart:
            return QStyle::SC_ScrollBarAddPage;
        case ForwardButtonPart:
            return QStyle::SC_ScrollBarAddLine;
    }

    return QStyle::SC_None;
}

static ScrollbarPart scrollbarPart(const QStyle::SubControl& sc)
{
    switch (sc) {
        case QStyle::SC_None:
            return NoPart;
        case QStyle::SC_ScrollBarSubLine:
            return BackButtonPart;
        case QStyle::SC_ScrollBarSubPage:
            return BackTrackPart;
        case QStyle::SC_ScrollBarSlider:
            return ThumbPart;
        case QStyle::SC_ScrollBarAddPage:
            return ForwardTrackPart;
        case QStyle::SC_ScrollBarAddLine:
            return ForwardButtonPart;
    }
    return NoPart;
}

static QStyleOptionSlider* styleOptionSlider(Scrollbar* scrollbar)
{
    static QStyleOptionSlider opt;
    opt.rect = scrollbar->frameGeometry();
    opt.state = 0;
    if (scrollbar->isEnabled())
        opt.state |= QStyle::State_Enabled;
    if (scrollbar->controlSize() != RegularScrollbar)
        opt.state |= QStyle::State_Mini;
    opt.orientation = (scrollbar->orientation() == VerticalScrollbar) ? Qt::Vertical : Qt::Horizontal;
    opt.sliderValue = scrollbar->value();
    opt.sliderPosition = opt.sliderValue;
    opt.pageStep = scrollbar->visibleSize();
    opt.singleStep = scrollbar->lineStep();
    opt.minimum = 0;
    opt.maximum = qMax(0, scrollbar->maximum());
    ScrollbarPart pressedPart = scrollbar->pressedPart();
    ScrollbarPart hoveredPart = scrollbar->hoveredPart();
    if (pressedPart != NoPart) {
        opt.activeSubControls = scPart(scrollbar->pressedPart());
        if (pressedPart == BackButtonPart || pressedPart == ForwardButtonPart ||
            pressedPart == ThumbPart)
            opt.state |= QStyle::State_Sunken;
    } else
        opt.activeSubControls = scPart(hoveredPart);
    if (hoveredPart != NoPart)
        opt.state |= QStyle::State_MouseOver;
    return &opt;
}

bool ScrollbarThemeQt::paint(Scrollbar* scrollbar, GraphicsContext* graphicsContext, const IntRect& damageRect)
{
    QStyleOptionSlider* opt = styleOptionSlider(scrollbar);
    QRect clip = opt->rect.intersected(damageRect);

    QPainter* p = graphicsContext->platformContext();
    p->save();
    p->setClipRect(clip);

    const QPoint topLeft = opt->rect.topLeft();
#ifdef Q_WS_MAC
    QApplication::style()->drawComplexControl(QStyle::CC_ScrollBar, opt, p, 0);
#else
    p->translate(topLeft);
    opt->rect.moveTo(QPoint(0, 0));

    // The QStyle expects the background to be already filled
    p->fillRect(opt->rect, opt->palette.background());

    QApplication::style()->drawComplexControl(QStyle::CC_ScrollBar, opt, p, 0);
    opt->rect.moveTo(topLeft);
#endif
    p->restore();

    return true;
}

ScrollbarPart ScrollbarThemeQt::hitTest(Scrollbar* scrollbar, const PlatformMouseEvent& evt)
{
    QStyleOptionSlider* opt = styleOptionSlider(scrollbar);
    const QPoint pos = convertFromContainingWindow(evt.pos());
    opt->rect.moveTo(QPoint(0, 0));
    QStyle::SubControl sc = QApplication::style()->hitTestComplexControl(QStyle::CC_ScrollBar, opt, pos, 0);
    return scrollbarPart(sc);
}

bool ScrollbarThemeQt::shouldCenterOnThumb(Scrollbar*, const PlatformMouseEvent&)
{
    // Middle click centers slider thumb (if supported)
    return QApplication::style()->styleHint(QStyle::SH_ScrollBar_MiddleClickAbsolutePosition) && evt.button() == MiddleButton;
}

void ScrollbarThemeQt::invalidatePart(Scrollbar* scrollbar, ScrollbarPart)
{
    // FIXME: Do more precise invalidation.
    scrollbar->invalidate();
}

int ScrollbarThemeQt::scrollbarThickness(ScrollbarControlSize controlSize)
{
    QStyle* s = QApplication::style();
    QStyleOptionSlider o;
    o.orientation = Qt::Vertical;
    o.state &= ~QStyle::State_Horizontal;
    if (controlSize != RegularScrollbar)
        o.state |= QStyle::State_Mini;
    return s->pixelMetric(QStyle::PM_ScrollBarExtent, &o, 0);
}

int ScrollbarThemeQt::thumbPosition(Scrollbar* scrollbar)
{
    if (scrollbar->isEnabled())
        return (int)((float)scrollbar->currentPos() * (trackLength(scrollbar) - thumbLength(scrollbar)) / scrollbar->maximum();
    return 0;
}

int ScrollbarThemeQt::thumbLength(Scrollbar* scrollbar)
{
    QStyleOptionSlider* opt = styleOptionSlider(scrollbar);
    IntRect thumb = QApplication::style()->subControlRect(QStyle::CC_ScrollBar, opt, QStyle::SC_ScrollBarSlider, 0);
    return scrollbar->orientation() == HorizontalScrollbar ? thumb.width() : thumb.height();
}

int ScrollbarThemeQt::trackPosition(Scrollbar* scrollbar)
{
    QStyleOptionSlider* opt = styleOptionSlider(scrollbar);
    IntRect track = QApplication::style()->subControlRect(QStyle::CC_ScrollBar, opt, QStyle::SC_ScrollBarGroove, 0);
    return scrollbar->orientation() == HorizontalScrollbar ? track.x() : track.y();
}

int ScrollbarThemeQt::trackLength(Scrollbar* scrollbar)
{
    QStyleOptionSlider* opt = styleOptionSlider(scrollbar);
    IntRect track = QApplication::style()->subControlRect(QStyle::CC_ScrollBar, opt, QStyle::SC_ScrollBarGroove, 0);
    return scrollbar->orientation() == HorizontalScrollbar ? track.width() : track.height();
}

}

<commit_msg>Fix Qt build bustage in ScrollbarThemeQt.cpp<commit_after>/*
 * Copyright (C) 2007, 2008 Apple Inc. All Rights Reserved.
 * Copyright (C) 2007 Staikos Computing Services Inc. <info@staikos.net>
 * Copyright (C) 2007 Trolltech ASA
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "ScrollbarThemeQt.h"

#include "GraphicsContext.h"
#include "PlatformMouseEvent.h"
#include "ScrollBar.h"

#include <QApplication>
#include <QDebug>
#include <QPainter>
#include <QStyle>
#include <QStyleOptionSlider>
#include <QMenu>

namespace WebCore {

ScrollbarTheme* ScrollbarTheme::nativeTheme()
{
    static ScrollbarThemeQt theme;
    return &theme;
}

ScrollbarThemeQt::~ScrollbarThemeQt()
{
}

static QStyle::SubControl scPart(const ScrollbarPart& part)
{
    switch (part) {
        case NoPart:
            return QStyle::SC_None;
        case BackButtonPart:
            return QStyle::SC_ScrollBarSubLine;
        case BackTrackPart:
            return QStyle::SC_ScrollBarSubPage;
        case ThumbPart:
            return QStyle::SC_ScrollBarSlider;
        case ForwardTrackPart:
            return QStyle::SC_ScrollBarAddPage;
        case ForwardButtonPart:
            return QStyle::SC_ScrollBarAddLine;
    }

    return QStyle::SC_None;
}

static ScrollbarPart scrollbarPart(const QStyle::SubControl& sc)
{
    switch (sc) {
        case QStyle::SC_None:
            return NoPart;
        case QStyle::SC_ScrollBarSubLine:
            return BackButtonPart;
        case QStyle::SC_ScrollBarSubPage:
            return BackTrackPart;
        case QStyle::SC_ScrollBarSlider:
            return ThumbPart;
        case QStyle::SC_ScrollBarAddPage:
            return ForwardTrackPart;
        case QStyle::SC_ScrollBarAddLine:
            return ForwardButtonPart;
    }
    return NoPart;
}

static QStyleOptionSlider* styleOptionSlider(Scrollbar* scrollbar)
{
    static QStyleOptionSlider opt;
    opt.rect = scrollbar->frameGeometry();
    opt.state = 0;
    if (scrollbar->isEnabled())
        opt.state |= QStyle::State_Enabled;
    if (scrollbar->controlSize() != RegularScrollbar)
        opt.state |= QStyle::State_Mini;
    opt.orientation = (scrollbar->orientation() == VerticalScrollbar) ? Qt::Vertical : Qt::Horizontal;
    opt.sliderValue = scrollbar->value();
    opt.sliderPosition = opt.sliderValue;
    opt.pageStep = scrollbar->visibleSize();
    opt.singleStep = scrollbar->lineStep();
    opt.minimum = 0;
    opt.maximum = qMax(0, scrollbar->maximum());
    ScrollbarPart pressedPart = scrollbar->pressedPart();
    ScrollbarPart hoveredPart = scrollbar->hoveredPart();
    if (pressedPart != NoPart) {
        opt.activeSubControls = scPart(scrollbar->pressedPart());
        if (pressedPart == BackButtonPart || pressedPart == ForwardButtonPart ||
            pressedPart == ThumbPart)
            opt.state |= QStyle::State_Sunken;
    } else
        opt.activeSubControls = scPart(hoveredPart);
    if (hoveredPart != NoPart)
        opt.state |= QStyle::State_MouseOver;
    return &opt;
}

bool ScrollbarThemeQt::paint(Scrollbar* scrollbar, GraphicsContext* graphicsContext, const IntRect& damageRect)
{
    QStyleOptionSlider* opt = styleOptionSlider(scrollbar);
    QRect clip = opt->rect.intersected(damageRect);

    QPainter* p = graphicsContext->platformContext();
    p->save();
    p->setClipRect(clip);

    const QPoint topLeft = opt->rect.topLeft();
#ifdef Q_WS_MAC
    QApplication::style()->drawComplexControl(QStyle::CC_ScrollBar, opt, p, 0);
#else
    p->translate(topLeft);
    opt->rect.moveTo(QPoint(0, 0));

    // The QStyle expects the background to be already filled
    p->fillRect(opt->rect, opt->palette.background());

    QApplication::style()->drawComplexControl(QStyle::CC_ScrollBar, opt, p, 0);
    opt->rect.moveTo(topLeft);
#endif
    p->restore();

    return true;
}

ScrollbarPart ScrollbarThemeQt::hitTest(Scrollbar* scrollbar, const PlatformMouseEvent& evt)
{
    QStyleOptionSlider* opt = styleOptionSlider(scrollbar);
    const QPoint pos = scrollbar->convertFromContainingWindow(evt.pos());
    opt->rect.moveTo(QPoint(0, 0));
    QStyle::SubControl sc = QApplication::style()->hitTestComplexControl(QStyle::CC_ScrollBar, opt, pos, 0);
    return scrollbarPart(sc);
}

bool ScrollbarThemeQt::shouldCenterOnThumb(Scrollbar*, const PlatformMouseEvent& evt)
{
    // Middle click centers slider thumb (if supported)
    return QApplication::style()->styleHint(QStyle::SH_ScrollBar_MiddleClickAbsolutePosition) && evt.button() == MiddleButton;
}

void ScrollbarThemeQt::invalidatePart(Scrollbar* scrollbar, ScrollbarPart)
{
    // FIXME: Do more precise invalidation.
    scrollbar->invalidate();
}

int ScrollbarThemeQt::scrollbarThickness(ScrollbarControlSize controlSize)
{
    QStyle* s = QApplication::style();
    QStyleOptionSlider o;
    o.orientation = Qt::Vertical;
    o.state &= ~QStyle::State_Horizontal;
    if (controlSize != RegularScrollbar)
        o.state |= QStyle::State_Mini;
    return s->pixelMetric(QStyle::PM_ScrollBarExtent, &o, 0);
}

int ScrollbarThemeQt::thumbPosition(Scrollbar* scrollbar)
{
    if (scrollbar->isEnabled())
        return (int)((float)scrollbar->currentPos() * (trackLength(scrollbar) - thumbLength(scrollbar)) / scrollbar->maximum());
    return 0;
}

int ScrollbarThemeQt::thumbLength(Scrollbar* scrollbar)
{
    QStyleOptionSlider* opt = styleOptionSlider(scrollbar);
    IntRect thumb = QApplication::style()->subControlRect(QStyle::CC_ScrollBar, opt, QStyle::SC_ScrollBarSlider, 0);
    return scrollbar->orientation() == HorizontalScrollbar ? thumb.width() : thumb.height();
}

int ScrollbarThemeQt::trackPosition(Scrollbar* scrollbar)
{
    QStyleOptionSlider* opt = styleOptionSlider(scrollbar);
    IntRect track = QApplication::style()->subControlRect(QStyle::CC_ScrollBar, opt, QStyle::SC_ScrollBarGroove, 0);
    return scrollbar->orientation() == HorizontalScrollbar ? track.x() : track.y();
}

int ScrollbarThemeQt::trackLength(Scrollbar* scrollbar)
{
    QStyleOptionSlider* opt = styleOptionSlider(scrollbar);
    IntRect track = QApplication::style()->subControlRect(QStyle::CC_ScrollBar, opt, QStyle::SC_ScrollBarGroove, 0);
    return scrollbar->orientation() == HorizontalScrollbar ? track.width() : track.height();
}

}

<|endoftext|>


<commit_before>#include <QtPlugin>
#include <QSqlQuery>

#include "kernel.h"
#include "angle.h"
#include "point.h"
#include "internalmodule.h"
#include "factory.h"
#include "ilwisdata.h"
#include "range.h"
#include "connectorinterface.h"
#include "abstractfactory.h"
#include "connectorfactory.h"
#include "ilwisobjectfactory.h"
#include "internalilwisobjectfactory.h"
#include "catalogconnector.h"
#include "catalogconnectorfactory.h"
#include "internalcatalogconnector.h"
#include "ilwisobjectconnector.h"
#include "internalgridcoverageconnector.h"
#include "internaltableconnector.h"
#include "projection.h"
#include "ProjectionImplementation.h"
#include "projectionfactory.h"
#include "internalprjmplfactory.h"

using namespace Ilwis;
using namespace Internal;

InternalModule::InternalModule(QObject *parent) :
    Module(parent, "InternalModule", "iv40","1.0")
{
}

QString InternalModule::getInterfaceVersion() const
{
    return "iv40";

}

void InternalModule::prepare()
{
    InternalIlwisObjectFactory *ifactory = new InternalIlwisObjectFactory();
    kernel()->addFactory(ifactory);

    ConnectorFactory *factory = kernel()->factory<ConnectorFactory>("ilwis::ConnectorFactory");
    if (!factory)
        return ;

    factory->addCreator(itRASTER,"internal", InternalRasterCoverageConnector::create);
    factory->addCreator(itTABLE,"internal", InternalTableConnector::create);

    FactoryInterface *projfactory = new ProjectionImplFactory();
    projfactory->prepare();
    kernel()->addFactory(projfactory );

    CatalogConnectorFactory *catfactory = kernel()->factory<CatalogConnectorFactory>("catalogconnectorfactory","ilwis");
    catfactory->add(InternalCatalogConnector::create);

}

QString InternalModule::name() const
{
    return "Internal Connector connector plugin";
}

QString InternalModule::version() const
{
    return "1.0";
}

<commit_msg>integrated containerConnector<commit_after>#include <QtPlugin>
#include <QSqlQuery>

#include "kernel.h"
#include "connectorinterface.h"
#include "containerconnector.h"
#include "angle.h"
#include "point.h"
#include "internalmodule.h"
#include "factory.h"
#include "ilwisdata.h"
#include "range.h"
#include "connectorinterface.h"
#include "abstractfactory.h"
#include "connectorfactory.h"
#include "ilwisobjectfactory.h"
#include "internalilwisobjectfactory.h"
#include "catalogconnector.h"
#include "catalogconnectorfactory.h"
#include "internalcatalogconnector.h"
#include "ilwisobjectconnector.h"
#include "internalgridcoverageconnector.h"
#include "internaltableconnector.h"
#include "projection.h"
#include "ProjectionImplementation.h"
#include "projectionfactory.h"
#include "internalprjmplfactory.h"

using namespace Ilwis;
using namespace Internal;

InternalModule::InternalModule(QObject *parent) :
    Module(parent, "InternalModule", "iv40","1.0")
{
}

QString InternalModule::getInterfaceVersion() const
{
    return "iv40";

}

void InternalModule::prepare()
{
    InternalIlwisObjectFactory *ifactory = new InternalIlwisObjectFactory();
    kernel()->addFactory(ifactory);

    ConnectorFactory *factory = kernel()->factory<ConnectorFactory>("ilwis::ConnectorFactory");
    if (!factory)
        return ;
    factory->addCreator(itCONTAINER,"internal",InternalCatalogConnector::create);

    factory->addCreator(itRASTER,"internal", InternalRasterCoverageConnector::create);
    factory->addCreator(itTABLE,"internal", InternalTableConnector::create);

    FactoryInterface *projfactory = new ProjectionImplFactory();
    projfactory->prepare();
    kernel()->addFactory(projfactory );

}

QString InternalModule::name() const
{
    return "Internal Connector connector plugin";
}

QString InternalModule::version() const
{
    return "1.0";
}

<|endoftext|>


<commit_before>// Copyright (c) 2016 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <stdio.h>
#include <chrono>
#include <thread>
#include "../TPlatform.h"
#include "../TTimestamp.h"
#include "../unexposed/TCurrentThreadUnexposed.h"
#include "../TCurrentThread.h"

namespace tyr { namespace basic {

namespace CurrentThread {
  __declspec(thread) const int tMainTid = kern_gettid();
  __declspec(thread) int tCachedTid = 0;
  __declspec(thread) char tTidString[32];
  __declspec(thread) int tTidStringLength = 6;
  __declspec(thread) const char* tThreadName = "unknown";
  static_assert(std::is_same<int, pid_t>::value, "pid_t should be int");

  namespace unexposed {
    void set_cached_tid(int cached_tid) {
      CurrentThread::tCachedTid = cached_tid;
    }

    void set_thread_name(const char* name) {
      CurrentThread::tThreadName = name;
    }
  }

  void cached_tid(void) {
    if (0 == tCachedTid) {
      tCachedTid = kern_gettid();
      tTidStringLength = snprintf(tTidString, sizeof(tTidString), "%5d ", tCachedTid);
    }
  }

  int tid(void) {
    if (__builtin_expect(tCachedTid == 0, 0))
      cached_tid();
    return tCachedTid;
  }

  const char* tid_string(void) {
    return tTidString;
  }

  int tid_string_length(void) {
    return tTidStringLength;
  }

  const char* name(void) {
    return tThreadName;
  }

  bool is_main_thread(void) {
    return tid() == tMainTid;
  }

  void sleep_usec(int64_t usec) {
    // use C++11 on Windows
    std::this_thread::sleep_for(std::chrono::microseconds(usec));
  }

}}}
<commit_msg>chore(thread): modify default tid length for windows (in theory it's equial to DWORD_MAX)<commit_after>// Copyright (c) 2016 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <stdio.h>
#include <chrono>
#include <thread>
#include "../TPlatform.h"
#include "../TTimestamp.h"
#include "../unexposed/TCurrentThreadUnexposed.h"
#include "../TCurrentThread.h"

namespace tyr { namespace basic {

namespace CurrentThread {
  __declspec(thread) const int tMainTid = kern_gettid();
  __declspec(thread) int tCachedTid = 0;
  __declspec(thread) char tTidString[32];
  __declspec(thread) int tTidStringLength = 12;
  __declspec(thread) const char* tThreadName = "unknown";
  static_assert(std::is_same<int, pid_t>::value, "pid_t should be int");

  namespace unexposed {
    void set_cached_tid(int cached_tid) {
      CurrentThread::tCachedTid = cached_tid;
    }

    void set_thread_name(const char* name) {
      CurrentThread::tThreadName = name;
    }
  }

  void cached_tid(void) {
    if (0 == tCachedTid) {
      tCachedTid = kern_gettid();
      tTidStringLength = snprintf(tTidString, sizeof(tTidString), "%11d ", tCachedTid);
    }
  }

  int tid(void) {
    if (__builtin_expect(tCachedTid == 0, 0))
      cached_tid();
    return tCachedTid;
  }

  const char* tid_string(void) {
    return tTidString;
  }

  int tid_string_length(void) {
    return tTidStringLength;
  }

  const char* name(void) {
    return tThreadName;
  }

  bool is_main_thread(void) {
    return tid() == tMainTid;
  }

  void sleep_usec(int64_t usec) {
    // use C++11 on Windows
    std::this_thread::sleep_for(std::chrono::microseconds(usec));
  }

}}}
<|endoftext|>


<commit_before><commit_msg>updated dfs<commit_after><|endoftext|>


<commit_before>/* libs/graphics/ports/SkTime_Unix.cpp
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/

#include "SkTime.h"

#include <sys/time.h>
#include <time.h>

void SkTime::GetDateTime(DateTime* dt)
{
    if (dt)
    {
        time_t m_time;
        time(&m_time);
        struct tm* tstruct;
        tstruct = localtime(&m_time);

        dt->fYear       = tstruct->tm_year;
        dt->fMonth      = SkToU8(tstruct->tm_mon + 1);
        dt->fDayOfWeek  = SkToU8(tstruct->tm_wday);
        dt->fDay        = SkToU8(tstruct->tm_mday);
        dt->fHour       = SkToU8(tstruct->tm_hour);
        dt->fMinute     = SkToU8(tstruct->tm_min);
        dt->fSecond     = SkToU8(tstruct->tm_sec);
    }
}

SkMSec SkTime::GetMSecs()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (SkMSec) (tv.tv_sec * 1000 + tv.tv_usec / 1000 ); // microseconds to milliseconds
}

#endif
<commit_msg>Deleted the #endif that's caused the compiler erro<commit_after>/* libs/graphics/ports/SkTime_Unix.cpp
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/

#include "SkTime.h"

#include <sys/time.h>
#include <time.h>

void SkTime::GetDateTime(DateTime* dt)
{
    if (dt)
    {
        time_t m_time;
        time(&m_time);
        struct tm* tstruct;
        tstruct = localtime(&m_time);

        dt->fYear       = tstruct->tm_year;
        dt->fMonth      = SkToU8(tstruct->tm_mon + 1);
        dt->fDayOfWeek  = SkToU8(tstruct->tm_wday);
        dt->fDay        = SkToU8(tstruct->tm_mday);
        dt->fHour       = SkToU8(tstruct->tm_hour);
        dt->fMinute     = SkToU8(tstruct->tm_min);
        dt->fSecond     = SkToU8(tstruct->tm_sec);
    }
}

SkMSec SkTime::GetMSecs()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (SkMSec) (tv.tv_sec * 1000 + tv.tv_usec / 1000 ); // microseconds to milliseconds
}<|endoftext|>


<commit_before>#include "platform_gl.h"

#include "gl.h"
#include "gl/error.h"

namespace Tangram {

GLenum GL::getError() {
    return glGetError();
}

const GLubyte* GL::getString(GLenum name) {
    auto result = glGetString(name);
    GL_CHECK();
    return result;
}

void GL::clear(GLbitfield mask) {
    GL_CHECK(glClear(mask));
}
void GL::lineWidth(GLfloat width) {
    GL_CHECK(glLineWidth(width));
}
void GL::viewport(GLint x, GLint y, GLsizei width, GLsizei height) {
    GL_CHECK(glViewport(x, y, width, height));
}

void GL::enable(GLenum id) {
    GL_CHECK(glEnable(id));
}
void GL::disable(GLenum id) {
    GL_CHECK(glDisable(id));
}
void GL::depthFunc(GLenum func) {
    GL_CHECK(glDepthFunc(func));
}
void GL::depthMask(GLboolean flag) {
    GL_CHECK(glDepthMask(flag));
}
void GL::depthRange(GLfloat n, GLfloat f) {
    GL_CHECK(glDepthRangef(n, f));
}
void GL::clearDepth(GLfloat d) {
    GL_CHECK(glClearDepthf(d));
}
void GL::blendFunc(GLenum sfactor, GLenum dfactor) {
    GL_CHECK(glBlendFunc(sfactor, dfactor));
}
void GL::stencilFunc(GLenum func, GLint ref, GLuint mask) {
    GL_CHECK(glStencilFunc(func, ref, mask));
}
void GL::stencilMask(GLuint mask) {
    GL_CHECK(glStencilMask(mask));
}
void GL::stencilOp(GLenum fail, GLenum zfail, GLenum zpass) {
    GL_CHECK(glStencilOp(fail, zfail, zpass));
}
void GL::clearStencil(GLint s) {
    GL_CHECK(glClearStencil(s));
}
void GL::colorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) {
    GL_CHECK(glColorMask(red, green, blue, alpha));
}
void GL::cullFace(GLenum mode) {
    GL_CHECK(glCullFace(mode));
}
void GL::frontFace(GLenum mode) {
    GL_CHECK(glFrontFace(mode));
}
void GL::clearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) {
    GL_CHECK(glClearColor(red, green, blue, alpha));
}
void GL::getIntegerv(GLenum pname, GLint *params ) {
    GL_CHECK(glGetIntegerv(pname, params ));
}

// Program
void GL::useProgram(GLuint program) {
    GL_CHECK(glUseProgram(program));
}
void GL::deleteProgram(GLuint program) {
    GL_CHECK(glDeleteProgram(program));
}
void GL::deleteShader(GLuint shader) {
    GL_CHECK(glDeleteShader(shader));
}
GLuint GL::createShader(GLenum type) {
    auto result = glCreateShader(type);
    GL_CHECK();
    return result;
}
GLuint GL::createProgram() {
    auto result = glCreateProgram();
    GL_CHECK();
    return result;
}

void GL::compileShader(GLuint shader) {
    GL_CHECK(glCompileShader(shader));
}
void GL::attachShader(GLuint program, GLuint shader) {
    GL_CHECK(glAttachShader(program,shader));
}
void GL::linkProgram(GLuint program) {
    GL_CHECK(glLinkProgram(program));
}

void GL::shaderSource(GLuint shader, GLsizei count, const GLchar **string, const GLint *length) {
        auto source = const_cast<const GLchar**>(string);
    GL_CHECK(glShaderSource(shader, count, source, length));
}
void GL::getShaderInfoLog(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog) {
    GL_CHECK(glGetShaderInfoLog(shader, bufSize, length, infoLog));
}
void GL::getProgramInfoLog(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog) {
    GL_CHECK(glGetProgramInfoLog(program, bufSize, length, infoLog));
}
GLint GL::getUniformLocation(GLuint program, const GLchar *name) {
    return GL_CHECK(glGetUniformLocation(program, name));
}
GLint GL::getAttribLocation(GLuint program, const GLchar *name) {
    return GL_CHECK(glGetAttribLocation(program, name));
}
void GL::getProgramiv(GLuint program, GLenum pname, GLint *params) {
    GL_CHECK(glGetProgramiv(program,pname,params));
}
void GL::getShaderiv(GLuint shader, GLenum pname, GLint *params) {
    GL_CHECK(glGetShaderiv(shader,pname, params));
}

// Buffers
void GL::bindBuffer(GLenum target, GLuint buffer) {
    GL_CHECK(glBindBuffer(target, buffer));
}
void GL::deleteBuffers(GLsizei n, const GLuint *buffers) {
    GL_CHECK(glDeleteBuffers(n, buffers));
}
void GL::genBuffers(GLsizei n, GLuint *buffers) {
    GL_CHECK(glGenBuffers(n, buffers));
}
void GL::bufferData(GLenum target, GLsizeiptr size, const void *data, GLenum usage) {
    GL_CHECK(glBufferData(target, size, data, usage));
}
void GL::bufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const void *data) {
    GL_CHECK(glBufferSubData(target, offset, size, data));
}
void GL::readPixels(GLint x, GLint y, GLsizei width, GLsizei height,
                    GLenum format, GLenum type, GLvoid* pixels) {
    GL_CHECK(glReadPixels(x, y, width, height, format, type, pixels));
}

// Texture
void GL::bindTexture(GLenum target, GLuint texture ) {
    GL_CHECK(glBindTexture(target, texture ));
}
void GL::activeTexture(GLenum texture) {
    GL_CHECK(glActiveTexture(texture));
}
void GL::genTextures(GLsizei n, GLuint *textures ) {
    GL_CHECK(glGenTextures(n, textures ));
}
void GL::deleteTextures(GLsizei n, const GLuint *textures) {
    GL_CHECK(glDeleteTextures(n, textures));
}
void GL::texParameteri(GLenum target, GLenum pname, GLint param ) {
    GL_CHECK(glTexParameteri(target, pname, param ));
}
void GL::texImage2D(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height,
                    GLint border, GLenum format, GLenum type, const GLvoid *pixels) {
    GL_CHECK(glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels)); }

void GL::texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
                       GLenum format, GLenum type, const GLvoid *pixels) {
    GL_CHECK(glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels)); }

void GL::generateMipmap(GLenum target) {
    GL_CHECK(glGenerateMipmap(target));
}

void GL::enableVertexAttribArray(GLuint index) {
    GL_CHECK(glEnableVertexAttribArray(index));
}
void GL::disableVertexAttribArray(GLuint index) {
    GL_CHECK(glDisableVertexAttribArray(index));
}
void GL::vertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized,
                             GLsizei stride, const void *pointer) {
    GL_CHECK(glVertexAttribPointer(index, size, type, normalized, stride, pointer));
}

void GL::drawArrays(GLenum mode, GLint first, GLsizei count ) {
    GL_CHECK(glDrawArrays(mode, first, count ));
}
void GL::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices ) {
    GL_CHECK(glDrawElements(mode, count, type, indices ));
}

void GL::uniform1f(GLint location, GLfloat v0) {
    GL_CHECK(glUniform1f(location, v0));
}
void GL::uniform2f(GLint location, GLfloat v0, GLfloat v1) {
    GL_CHECK(glUniform2f(location, v0, v1));
}
void GL::uniform3f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2) {
    GL_CHECK(glUniform3f(location, v0, v1, v2));
}
void GL::uniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) {
    GL_CHECK(glUniform4f(location, v0, v1, v2, v3));
}

void GL::uniform1i(GLint location, GLint v0) {
    GL_CHECK(glUniform1i(location, v0));
}
void GL::uniform2i(GLint location, GLint v0, GLint v1) {
    GL_CHECK(glUniform2i(location, v0, v1));
}
void GL::uniform3i(GLint location, GLint v0, GLint v1, GLint v2) {
    GL_CHECK(glUniform3i(location, v0, v1, v2));
}
void GL::uniform4i(GLint location, GLint v0, GLint v1, GLint v2, GLint v3) {
    GL_CHECK(glUniform4i(location, v0, v1, v2, v3));
}

void GL::uniform1fv(GLint location, GLsizei count, const GLfloat *value) {
    GL_CHECK(glUniform1fv(location, count, value));
}
void GL::uniform2fv(GLint location, GLsizei count, const GLfloat *value) {
    GL_CHECK(glUniform2fv(location, count, value));
}
void GL::uniform3fv(GLint location, GLsizei count, const GLfloat *value) {
    GL_CHECK(glUniform3fv(location, count, value));
}
void GL::uniform4fv(GLint location, GLsizei count, const GLfloat *value) {
    GL_CHECK(glUniform4fv(location, count, value));
}
void GL::uniform1iv(GLint location, GLsizei count, const GLint *value) {
    GL_CHECK(glUniform1iv(location, count, value));
}
void GL::uniform2iv(GLint location, GLsizei count, const GLint *value) {
    GL_CHECK(glUniform2iv(location, count, value));
}
void GL::uniform3iv(GLint location, GLsizei count, const GLint *value) {
    GL_CHECK(glUniform3iv(location, count, value));
}
void GL::uniform4iv(GLint location, GLsizei count, const GLint *value) {
    GL_CHECK(glUniform4iv(location, count, value));
}

void GL::uniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) {
    GL_CHECK(glUniformMatrix2fv(location, count, transpose, value));
}
void GL::uniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) {
    GL_CHECK(glUniformMatrix3fv(location, count, transpose, value));
}
void GL::uniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) {
    GL_CHECK(glUniformMatrix4fv(location, count, transpose, value));
}

// mapbuffer
void* GL::mapBuffer(GLenum target, GLenum access) {
    auto result =  glMapBuffer(target, access);
    GL_CHECK();
    return result;
}
GLboolean GL::unmapBuffer(GLenum target) {
    auto result = glUnmapBuffer(target);
    GL_CHECK();
    return result;
}

void GL::finish(void) {
    GL_CHECK(glFinish());
}

// VAO
void GL::bindVertexArray(GLuint array) {
    GL_CHECK(glBindVertexArray(array));
}
void GL::deleteVertexArrays(GLsizei n, const GLuint *arrays) {
    GL_CHECK(glDeleteVertexArrays(n, arrays));
}
void GL::genVertexArrays(GLsizei n, GLuint *arrays) {
    GL_CHECK(glGenVertexArrays(n, arrays));
}
}
<commit_msg>add Tangram::GL<commit_after>#include "platform_gl.h"

#include "gl.h"
#include "gl/error.h"
namespace Tangram {

GLenum GL::getError() {
    return glGetError();
}

const GLubyte* GL::getString(GLenum name) {
    auto result = glGetString(name);
    GL_CHECK();
    return result;
}

void GL::clear(GLbitfield mask) {
    GL_CHECK(glClear(mask));
}
void GL::lineWidth(GLfloat width) {
    GL_CHECK(glLineWidth(width));
}
void GL::viewport(GLint x, GLint y, GLsizei width, GLsizei height) {
    GL_CHECK(glViewport(x, y, width, height));
}

void GL::enable(GLenum id) {
    GL_CHECK(glEnable(id));
}
void GL::disable(GLenum id) {
    GL_CHECK(glDisable(id));
}
void GL::depthFunc(GLenum func) {
    GL_CHECK(glDepthFunc(func));
}
void GL::depthMask(GLboolean flag) {
    GL_CHECK(glDepthMask(flag));
}
void GL::depthRange(GLfloat n, GLfloat f) {
    GL_CHECK(glDepthRangef(n, f));
}
void GL::clearDepth(GLfloat d) {
    GL_CHECK(glClearDepthf(d));
}
void GL::blendFunc(GLenum sfactor, GLenum dfactor) {
    GL_CHECK(glBlendFunc(sfactor, dfactor));
}
void GL::stencilFunc(GLenum func, GLint ref, GLuint mask) {
    GL_CHECK(glStencilFunc(func, ref, mask));
}
void GL::stencilMask(GLuint mask) {
    GL_CHECK(glStencilMask(mask));
}
void GL::stencilOp(GLenum fail, GLenum zfail, GLenum zpass) {
    GL_CHECK(glStencilOp(fail, zfail, zpass));
}
void GL::clearStencil(GLint s) {
    GL_CHECK(glClearStencil(s));
}
void GL::colorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) {
    GL_CHECK(glColorMask(red, green, blue, alpha));
}
void GL::cullFace(GLenum mode) {
    GL_CHECK(glCullFace(mode));
}
void GL::frontFace(GLenum mode) {
    GL_CHECK(glFrontFace(mode));
}
void GL::clearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) {
    GL_CHECK(glClearColor(red, green, blue, alpha));
}
void GL::getIntegerv(GLenum pname, GLint *params ) {
    GL_CHECK(glGetIntegerv(pname, params ));
}

// Program
void GL::useProgram(GLuint program) {
    GL_CHECK(glUseProgram(program));
}
void GL::deleteProgram(GLuint program) {
    GL_CHECK(glDeleteProgram(program));
}
void GL::deleteShader(GLuint shader) {
    GL_CHECK(glDeleteShader(shader));
}
GLuint GL::createShader(GLenum type) {
    auto result = glCreateShader(type);
    GL_CHECK();
    return result;
}
GLuint GL::createProgram() {
    auto result = glCreateProgram();
    GL_CHECK();
    return result;
}

void GL::compileShader(GLuint shader) {
    GL_CHECK(glCompileShader(shader));
}
void GL::attachShader(GLuint program, GLuint shader) {
    GL_CHECK(glAttachShader(program,shader));
}
void GL::linkProgram(GLuint program) {
    GL_CHECK(glLinkProgram(program));
}

void GL::shaderSource(GLuint shader, GLsizei count, const GLchar **string, const GLint *length) {
        auto source = const_cast<const GLchar**>(string);
    GL_CHECK(glShaderSource(shader, count, source, length));
}
void GL::getShaderInfoLog(GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog) {
    GL_CHECK(glGetShaderInfoLog(shader, bufSize, length, infoLog));
}
void GL::getProgramInfoLog(GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog) {
    GL_CHECK(glGetProgramInfoLog(program, bufSize, length, infoLog));
}
GLint GL::getUniformLocation(GLuint program, const GLchar *name) {
    return GL_CHECK(glGetUniformLocation(program, name));
}
GLint GL::getAttribLocation(GLuint program, const GLchar *name) {
    return GL_CHECK(glGetAttribLocation(program, name));
}
void GL::getProgramiv(GLuint program, GLenum pname, GLint *params) {
    GL_CHECK(glGetProgramiv(program,pname,params));
}
void GL::getShaderiv(GLuint shader, GLenum pname, GLint *params) {
    GL_CHECK(glGetShaderiv(shader,pname, params));
}

// Buffers
void GL::bindBuffer(GLenum target, GLuint buffer) {
    GL_CHECK(glBindBuffer(target, buffer));
}
void GL::deleteBuffers(GLsizei n, const GLuint *buffers) {
    GL_CHECK(glDeleteBuffers(n, buffers));
}
void GL::genBuffers(GLsizei n, GLuint *buffers) {
    GL_CHECK(glGenBuffers(n, buffers));
}
void GL::bufferData(GLenum target, GLsizeiptr size, const void *data, GLenum usage) {
    GL_CHECK(glBufferData(target, size, data, usage));
}
void GL::bufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const void *data) {
    GL_CHECK(glBufferSubData(target, offset, size, data));
}
void GL::readPixels(GLint x, GLint y, GLsizei width, GLsizei height,
                    GLenum format, GLenum type, GLvoid* pixels) {
    GL_CHECK(glReadPixels(x, y, width, height, format, type, pixels));
}

// Texture
void GL::bindTexture(GLenum target, GLuint texture ) {
    GL_CHECK(glBindTexture(target, texture ));
}
void GL::activeTexture(GLenum texture) {
    GL_CHECK(glActiveTexture(texture));
}
void GL::genTextures(GLsizei n, GLuint *textures ) {
    GL_CHECK(glGenTextures(n, textures ));
}
void GL::deleteTextures(GLsizei n, const GLuint *textures) {
    GL_CHECK(glDeleteTextures(n, textures));
}
void GL::texParameteri(GLenum target, GLenum pname, GLint param ) {
    GL_CHECK(glTexParameteri(target, pname, param ));
}
void GL::texImage2D(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height,
                    GLint border, GLenum format, GLenum type, const GLvoid *pixels) {
    GL_CHECK(glTexImage2D(target, level, internalFormat, width, height, border, format, type, pixels)); }

void GL::texSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
                       GLenum format, GLenum type, const GLvoid *pixels) {
    GL_CHECK(glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels)); }

void GL::generateMipmap(GLenum target) {
    GL_CHECK(glGenerateMipmap(target));
}

void GL::enableVertexAttribArray(GLuint index) {
    GL_CHECK(glEnableVertexAttribArray(index));
}
void GL::disableVertexAttribArray(GLuint index) {
    GL_CHECK(glDisableVertexAttribArray(index));
}
void GL::vertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized,
                             GLsizei stride, const void *pointer) {
    GL_CHECK(glVertexAttribPointer(index, size, type, normalized, stride, pointer));
}

void GL::drawArrays(GLenum mode, GLint first, GLsizei count ) {
    GL_CHECK(glDrawArrays(mode, first, count ));
}
void GL::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices ) {
    GL_CHECK(glDrawElements(mode, count, type, indices ));
}

void GL::uniform1f(GLint location, GLfloat v0) {
    GL_CHECK(glUniform1f(location, v0));
}
void GL::uniform2f(GLint location, GLfloat v0, GLfloat v1) {
    GL_CHECK(glUniform2f(location, v0, v1));
}
void GL::uniform3f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2) {
    GL_CHECK(glUniform3f(location, v0, v1, v2));
}
void GL::uniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) {
    GL_CHECK(glUniform4f(location, v0, v1, v2, v3));
}

void GL::uniform1i(GLint location, GLint v0) {
    GL_CHECK(glUniform1i(location, v0));
}
void GL::uniform2i(GLint location, GLint v0, GLint v1) {
    GL_CHECK(glUniform2i(location, v0, v1));
}
void GL::uniform3i(GLint location, GLint v0, GLint v1, GLint v2) {
    GL_CHECK(glUniform3i(location, v0, v1, v2));
}
void GL::uniform4i(GLint location, GLint v0, GLint v1, GLint v2, GLint v3) {
    GL_CHECK(glUniform4i(location, v0, v1, v2, v3));
}

void GL::uniform1fv(GLint location, GLsizei count, const GLfloat *value) {
    GL_CHECK(glUniform1fv(location, count, value));
}
void GL::uniform2fv(GLint location, GLsizei count, const GLfloat *value) {
    GL_CHECK(glUniform2fv(location, count, value));
}
void GL::uniform3fv(GLint location, GLsizei count, const GLfloat *value) {
    GL_CHECK(glUniform3fv(location, count, value));
}
void GL::uniform4fv(GLint location, GLsizei count, const GLfloat *value) {
    GL_CHECK(glUniform4fv(location, count, value));
}
void GL::uniform1iv(GLint location, GLsizei count, const GLint *value) {
    GL_CHECK(glUniform1iv(location, count, value));
}
void GL::uniform2iv(GLint location, GLsizei count, const GLint *value) {
    GL_CHECK(glUniform2iv(location, count, value));
}
void GL::uniform3iv(GLint location, GLsizei count, const GLint *value) {
    GL_CHECK(glUniform3iv(location, count, value));
}
void GL::uniform4iv(GLint location, GLsizei count, const GLint *value) {
    GL_CHECK(glUniform4iv(location, count, value));
}

void GL::uniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) {
    GL_CHECK(glUniformMatrix2fv(location, count, transpose, value));
}
void GL::uniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) {
    GL_CHECK(glUniformMatrix3fv(location, count, transpose, value));
}
void GL::uniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) {
    GL_CHECK(glUniformMatrix4fv(location, count, transpose, value));
}

// mapbuffer
void* GL::mapBuffer(GLenum target, GLenum access) {
    auto result =  glMapBuffer(target, access);
    GL_CHECK();
    return result;
}
GLboolean GL::unmapBuffer(GLenum target) {
    auto result = glUnmapBuffer(target);
    GL_CHECK();
    return result;
}

void GL::finish(void) {
    GL_CHECK(glFinish());
}

// VAO
void GL::bindVertexArray(GLuint array) {
    GL_CHECK(glBindVertexArray(array));
}
void GL::deleteVertexArrays(GLsizei n, const GLuint *arrays) {
    GL_CHECK(glDeleteVertexArrays(n, arrays));
}
void GL::genVertexArrays(GLsizei n, GLuint *arrays) {
    GL_CHECK(glGenVertexArrays(n, arrays));
}
}
<|endoftext|>


<commit_before><commit_msg>An unnecessary assignment has been removed, since the data has already been stored in the correct vector.<commit_after><|endoftext|>


<commit_before>
#include "InteractiveFit.h"
#include "Strcpp.h"
#include "fit-engine.h"
#include "lmfit-simple.h"
#include "spectra-path.h"

// Map
FXDEFMAP(InteractiveFit) InteractiveFitMap[]={
  FXMAPFUNC(SEL_COMMAND, InteractiveFit::ID_PARAM_SELECT, InteractiveFit::onCmdParamSelect),
  FXMAPFUNC(SEL_COMMAND, InteractiveFit::ID_PARAM_VALUE,  InteractiveFit::onCmdParamChange),
  FXMAPFUNC(SEL_CHANGED, InteractiveFit::ID_PARAM_VALUE,  InteractiveFit::onCmdParamChange),
  FXMAPFUNC(SEL_PAINT,   InteractiveFit::ID_CANVAS,       InteractiveFit::onCmdPaint),
  FXMAPFUNC(SEL_UPDATE,  InteractiveFit::ID_CANVAS,       InteractiveFit::onUpdCanvas),
  FXMAPFUNC(SEL_COMMAND, InteractiveFit::ID_RUN_FIT,      InteractiveFit::onCmdRunFit),
};

// Object implementation
FXIMPLEMENT(InteractiveFit,FXMainWindow,InteractiveFitMap,ARRAYNUMBER(InteractiveFitMap));

InteractiveFit::InteractiveFit(EllissApp *app, struct fit_engine *_fit, struct spectrum *user_spectr)
  : FXMainWindow(app, "Interactive Fit", NULL, &app->appicon, DECOR_ALL, 0, 0, 640, 480),
    fit_engine(_fit), spectrum(user_spectr), m_canvas_is_dirty(true)
{
  // Menubar
  menubar = new FXMenuBar(this, LAYOUT_SIDE_TOP|LAYOUT_FILL_X);
  statusbar = new FXStatusBar(this, LAYOUT_SIDE_BOTTOM|LAYOUT_FILL_X|FRAME_RAISED|STATUSBAR_WITH_DRAGCORNER);

  // fit menu
  fitmenu = new FXMenuPane(this);
  new FXMenuCommand(fitmenu,"&Run",NULL,this,ID_RUN_FIT);
  new FXMenuTitle(menubar,"&Fit",NULL,fitmenu);

  FXHorizontalFrame *mf = new FXHorizontalFrame(this, LAYOUT_FILL_X|LAYOUT_FILL_Y);
  FXMatrix *matrix = new FXMatrix(mf, 2, LAYOUT_FILL_Y|MATRIX_BY_COLUMNS, 0, 0, 0, 0, DEFAULT_SPACING, DEFAULT_SPACING, DEFAULT_SPACING, DEFAULT_SPACING, 1, 1);

  fit_engine->config->subsampling = 0;

  fit_engine_prepare (fit_engine, spectrum, 0);

  struct fit_parameters *params = fit_engine_get_all_parameters (fit_engine);
  m_parameters.init(params);

  m_params_text_field.resize(m_parameters.number);

  for (int k = 0; k < m_parameters.number; k++)
    {
      fit_param_t *fp = params->values + k;
      double fpval = fit_engine_get_default_param_value (fit_engine, fp);
      gsl_vector_set (m_parameters.values, k, fpval);
    }

  Str pname;
  int current_layer = 0;
  for (int k = 0; k < m_parameters.number; k++)
    {
      fit_param_t *fp = params->values + k;

      if (fp->id == PID_LAYER_N && fp->layer_nb != current_layer)
	{
	  current_layer = fp->layer_nb;
	  FXString str;
	  str.format("Layer %i", current_layer);
	  new FXLabel(matrix, str);
	  new FXLabel(matrix, "");
	}

      get_param_name(fp, pname.str());
      FXString fxpname((const FXchar *) pname.cstr());
      FXCheckButton *bt = new FXCheckButton(matrix, fxpname, this, ID_PARAM_SELECT);
      FXTextField *tf = new FXTextField(matrix, 10, this, ID_PARAM_VALUE, FRAME_SUNKEN|FRAME_THICK|TEXTFIELD_REAL|LAYOUT_FILL_ROW);

      void *offset_ptr = (void *) (m_parameters.base_ptr + k);
      tf->setUserData(offset_ptr);
      bt->setUserData(offset_ptr);

      m_params_text_field[k] = tf;

      double fpval = gsl_vector_get (m_parameters.values, k);
      char fpvalbuf[16];
      int len = snprintf(fpvalbuf, 16, "%g", fpval);
      if (len >= 16)
	fpvalbuf[15] = 0;
      tf->setText(fpvalbuf, true);
    }

  canvas = new FXCanvas(mf, this, ID_CANVAS, LAYOUT_FILL_X|LAYOUT_FILL_Y);

  unsigned plot_mult = (fit_engine->system_kind == SYSTEM_REFLECTOMETER ? 1 : 2);
  m_plots.init(app, plot_mult);

  updatePlot(true);
}

InteractiveFit::~InteractiveFit() {
  fit_engine_disable(fit_engine);
  fit_engine_free(fit_engine);
  delete fitmenu;
}

long
InteractiveFit::onCmdParamSelect(FXObject* _cb, FXSelector, void*)
{
  FXCheckButton *cb = (FXCheckButton *) _cb;
  double * paddr = (double *) cb->getUserData();
  int k = (paddr - m_parameters.base_ptr);
  m_parameters.select[k] = cb->getCheck();
  return 1;
}

void
InteractiveFit::updatePlot(bool freeze_lmt)
{
  struct fit_parameters* ps = m_parameters.parameters;
  fit_engine_apply_parameters (fit_engine, ps, m_parameters.values);

  switch (fit_engine->system_kind)
    {
    case SYSTEM_REFLECTOMETER:
      {
	plot *p = m_plots[0];
	refl_spectra_plot (fit_engine, p);
	if (freeze_lmt)
	  p->auto_limits(false);
	break;
      }
    case SYSTEM_ELLISS_AB:
    case SYSTEM_ELLISS_PSIDEL:
      {
	plot *p1 = m_plots[0], *p2 = m_plots[1];
	elliss_spectra_plot (fit_engine, p1, p2);
	if (freeze_lmt)
	  {
	    p1->auto_limits(false);
	    p2->auto_limits(false);
	  }
	break;
      }
    default:
      /* */ ;
    }
}

long
InteractiveFit::onCmdParamChange(FXObject *_txt, FXSelector, void*)
{
  FXTextField *txt = (FXTextField *) _txt;
  FXString vstr = txt->getText();
  double * paddr = (double *) txt->getUserData();
  double new_val = strtod (vstr.text(), NULL);

  if (new_val == *paddr)
    return 0;

  *paddr = new_val;
  m_canvas_is_dirty = true;
  return 1;
}

void
InteractiveFit::drawPlot()
{
  FXDCWindow dc(canvas);
  int ww = canvas->getWidth(), hh = canvas->getHeight();
  int n = m_plots.size();
  for (unsigned j = 0; j < n; j++)
    m_plots[j]->draw(&dc, ww, hh/n, 0, hh*j/n);

  m_canvas_is_dirty = false;
}

long
InteractiveFit::onCmdPaint(FXObject*, FXSelector, void* ptr)
{
  drawPlot();
  return 1;
}

long
InteractiveFit::onUpdCanvas(FXObject*, FXSelector, void* ptr)
{
  if (m_canvas_is_dirty)
    {
      updatePlot();
      drawPlot();
      return 1;
    }
  return 0;
}

long
InteractiveFit::onCmdRunFit(FXObject*, FXSelector, void* ptr)
{
  struct fit_parameters* fps = fit_parameters_new ();

  int fit_params_nb = 0;
  for (int j = 0; j < m_parameters.number; j++)
    {
      if (m_parameters.select[j])
	fit_params_nb++;
    }

  gsl_vector* seeds = gsl_vector_alloc(fit_params_nb);

  int k = 0;
  for (int j = 0; j < m_parameters.number; j++)
    {
      if (m_parameters.select[j])
	{
	  fit_parameters_add (fps, m_parameters.parameters->values + j);
	  gsl_vector_set (seeds, k, gsl_vector_get (m_parameters.values, j));
	  k ++;
	}
    }

  fit_engine_set_parameters (fit_engine, fps);

  double chisq;
  lmfit_simple (fit_engine, seeds, &chisq, 0, 0, 0, 0, 0);

  k = 0;
  FXString ns;
  for (int j = 0; j < m_parameters.number; j++)
    {
      if (m_parameters.select[j])
	{
	  double val = gsl_vector_get(fit_engine->results, k);
	  ns.format("%g", val);
	  m_params_text_field[j]->setText(ns);
	  gsl_vector_set(m_parameters.values, j, val);
	  k ++;
	}
    }

  m_canvas_is_dirty = true;

  return 1;
}
<commit_msg>Added scrollbar for fit parameters in interactive fit window<commit_after>
#include "InteractiveFit.h"
#include "Strcpp.h"
#include "fit-engine.h"
#include "lmfit-simple.h"
#include "spectra-path.h"

// Map
FXDEFMAP(InteractiveFit) InteractiveFitMap[]={
  FXMAPFUNC(SEL_COMMAND, InteractiveFit::ID_PARAM_SELECT, InteractiveFit::onCmdParamSelect),
  FXMAPFUNC(SEL_COMMAND, InteractiveFit::ID_PARAM_VALUE,  InteractiveFit::onCmdParamChange),
  FXMAPFUNC(SEL_CHANGED, InteractiveFit::ID_PARAM_VALUE,  InteractiveFit::onCmdParamChange),
  FXMAPFUNC(SEL_PAINT,   InteractiveFit::ID_CANVAS,       InteractiveFit::onCmdPaint),
  FXMAPFUNC(SEL_UPDATE,  InteractiveFit::ID_CANVAS,       InteractiveFit::onUpdCanvas),
  FXMAPFUNC(SEL_COMMAND, InteractiveFit::ID_RUN_FIT,      InteractiveFit::onCmdRunFit),
};

// Object implementation
FXIMPLEMENT(InteractiveFit,FXMainWindow,InteractiveFitMap,ARRAYNUMBER(InteractiveFitMap));

InteractiveFit::InteractiveFit(EllissApp *app, struct fit_engine *_fit, struct spectrum *user_spectr)
  : FXMainWindow(app, "Interactive Fit", NULL, &app->appicon, DECOR_ALL, 0, 0, 640, 480),
    fit_engine(_fit), spectrum(user_spectr), m_canvas_is_dirty(true)
{
  // Menubar
  menubar = new FXMenuBar(this, LAYOUT_SIDE_TOP|LAYOUT_FILL_X);
  statusbar = new FXStatusBar(this, LAYOUT_SIDE_BOTTOM|LAYOUT_FILL_X|FRAME_RAISED|STATUSBAR_WITH_DRAGCORNER);

  // fit menu
  fitmenu = new FXMenuPane(this);
  new FXMenuCommand(fitmenu,"&Run",NULL,this,ID_RUN_FIT);
  new FXMenuTitle(menubar,"&Fit",NULL,fitmenu);

  FXHorizontalFrame *mf = new FXHorizontalFrame(this, LAYOUT_FILL_X|LAYOUT_FILL_Y);
  FXScrollWindow *iw = new FXScrollWindow(mf, VSCROLLER_ALWAYS | HSCROLLING_OFF | LAYOUT_FILL_Y);
  FXMatrix *matrix = new FXMatrix(iw, 2, LAYOUT_FILL_Y|MATRIX_BY_COLUMNS, 0, 0, 0, 0, DEFAULT_SPACING, DEFAULT_SPACING, DEFAULT_SPACING, DEFAULT_SPACING, 1, 1);

  fit_engine->config->subsampling = 0;

  fit_engine_prepare (fit_engine, spectrum, 0);

  struct fit_parameters *params = fit_engine_get_all_parameters (fit_engine);
  m_parameters.init(params);

  m_params_text_field.resize(m_parameters.number);

  for (int k = 0; k < m_parameters.number; k++)
    {
      fit_param_t *fp = params->values + k;
      double fpval = fit_engine_get_default_param_value (fit_engine, fp);
      gsl_vector_set (m_parameters.values, k, fpval);
    }

  Str pname;
  int current_layer = 0;
  for (int k = 0; k < m_parameters.number; k++)
    {
      fit_param_t *fp = params->values + k;

      if (fp->id == PID_LAYER_N && fp->layer_nb != current_layer)
	{
	  current_layer = fp->layer_nb;
	  FXString str;
	  str.format("Layer %i", current_layer);
	  new FXLabel(matrix, str);
	  new FXLabel(matrix, "");
	}

      get_param_name(fp, pname.str());
      FXString fxpname((const FXchar *) pname.cstr());
      FXCheckButton *bt = new FXCheckButton(matrix, fxpname, this, ID_PARAM_SELECT);
      FXTextField *tf = new FXTextField(matrix, 10, this, ID_PARAM_VALUE, FRAME_SUNKEN|FRAME_THICK|TEXTFIELD_REAL|LAYOUT_FILL_ROW);

      void *offset_ptr = (void *) (m_parameters.base_ptr + k);
      tf->setUserData(offset_ptr);
      bt->setUserData(offset_ptr);

      m_params_text_field[k] = tf;

      double fpval = gsl_vector_get (m_parameters.values, k);
      char fpvalbuf[16];
      int len = snprintf(fpvalbuf, 16, "%g", fpval);
      if (len >= 16)
	fpvalbuf[15] = 0;
      tf->setText(fpvalbuf, true);
    }

  canvas = new FXCanvas(mf, this, ID_CANVAS, LAYOUT_FILL_X|LAYOUT_FILL_Y);

  unsigned plot_mult = (fit_engine->system_kind == SYSTEM_REFLECTOMETER ? 1 : 2);
  m_plots.init(app, plot_mult);

  updatePlot(true);
}

InteractiveFit::~InteractiveFit() {
  fit_engine_disable(fit_engine);
  fit_engine_free(fit_engine);
  delete fitmenu;
}

long
InteractiveFit::onCmdParamSelect(FXObject* _cb, FXSelector, void*)
{
  FXCheckButton *cb = (FXCheckButton *) _cb;
  double * paddr = (double *) cb->getUserData();
  int k = (paddr - m_parameters.base_ptr);
  m_parameters.select[k] = cb->getCheck();
  return 1;
}

void
InteractiveFit::updatePlot(bool freeze_lmt)
{
  struct fit_parameters* ps = m_parameters.parameters;
  fit_engine_apply_parameters (fit_engine, ps, m_parameters.values);

  switch (fit_engine->system_kind)
    {
    case SYSTEM_REFLECTOMETER:
      {
	plot *p = m_plots[0];
	refl_spectra_plot (fit_engine, p);
	if (freeze_lmt)
	  p->auto_limits(false);
	break;
      }
    case SYSTEM_ELLISS_AB:
    case SYSTEM_ELLISS_PSIDEL:
      {
	plot *p1 = m_plots[0], *p2 = m_plots[1];
	elliss_spectra_plot (fit_engine, p1, p2);
	if (freeze_lmt)
	  {
	    p1->auto_limits(false);
	    p2->auto_limits(false);
	  }
	break;
      }
    default:
      /* */ ;
    }
}

long
InteractiveFit::onCmdParamChange(FXObject *_txt, FXSelector, void*)
{
  FXTextField *txt = (FXTextField *) _txt;
  FXString vstr = txt->getText();
  double * paddr = (double *) txt->getUserData();
  double new_val = strtod (vstr.text(), NULL);

  if (new_val == *paddr)
    return 0;

  *paddr = new_val;
  m_canvas_is_dirty = true;
  return 1;
}

void
InteractiveFit::drawPlot()
{
  FXDCWindow dc(canvas);
  int ww = canvas->getWidth(), hh = canvas->getHeight();
  int n = m_plots.size();
  for (unsigned j = 0; j < n; j++)
    m_plots[j]->draw(&dc, ww, hh/n, 0, hh*j/n);

  m_canvas_is_dirty = false;
}

long
InteractiveFit::onCmdPaint(FXObject*, FXSelector, void* ptr)
{
  drawPlot();
  return 1;
}

long
InteractiveFit::onUpdCanvas(FXObject*, FXSelector, void* ptr)
{
  if (m_canvas_is_dirty)
    {
      updatePlot();
      drawPlot();
      return 1;
    }
  return 0;
}

long
InteractiveFit::onCmdRunFit(FXObject*, FXSelector, void* ptr)
{
  struct fit_parameters* fps = fit_parameters_new ();

  int fit_params_nb = 0;
  for (int j = 0; j < m_parameters.number; j++)
    {
      if (m_parameters.select[j])
	fit_params_nb++;
    }

  gsl_vector* seeds = gsl_vector_alloc(fit_params_nb);

  int k = 0;
  for (int j = 0; j < m_parameters.number; j++)
    {
      if (m_parameters.select[j])
	{
	  fit_parameters_add (fps, m_parameters.parameters->values + j);
	  gsl_vector_set (seeds, k, gsl_vector_get (m_parameters.values, j));
	  k ++;
	}
    }

  fit_engine_set_parameters (fit_engine, fps);

  double chisq;
  lmfit_simple (fit_engine, seeds, &chisq, 0, 0, 0, 0, 0);

  k = 0;
  FXString ns;
  for (int j = 0; j < m_parameters.number; j++)
    {
      if (m_parameters.select[j])
	{
	  double val = gsl_vector_get(fit_engine->results, k);
	  ns.format("%g", val);
	  m_params_text_field[j]->setText(ns);
	  gsl_vector_set(m_parameters.values, j, val);
	  k ++;
	}
    }

  m_canvas_is_dirty = true;

  return 1;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2005-2022 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbWrapperElevationParametersHandler.h"
#include "otbDEMHandler.h"

namespace otb
{
namespace Wrapper
{

void ElevationParametersHandler::AddElevationParameters(Application::Pointer app, const std::string& key)
{
  app->AddParameter(ParameterType_Group, key, "Elevation management");
  app->SetParameterDescription(key,
                               "This group of parameters allows managing elevation values.");

  // DEM directory
  std::ostringstream oss;
  oss << key << ".dem";
  app->AddParameter(ParameterType_Directory, oss.str(), "DEM directory");
  app->SetParameterDescription(oss.str(),
                               "This parameter allows selecting a directory containing Digital Elevation Model files. Note that this directory should contain "
                               "only DEM files. Unexpected behaviour might occurs if other images are found in this directory. Input DEM tiles should be in a raster format supported by GDAL.");
  app->MandatoryOff(oss.str());

  std::string demDirFromConfig = otb::ConfigurationManager::GetDEMDirectory();

  if (demDirFromConfig != "")
  {
    app->SetParameterString(oss.str(), demDirFromConfig);
    app->EnableParameter(oss.str());
  }
  else
  {
    app->DisableParameter(oss.str());
  }

  // Geoid file
  oss.str("");
  oss << key << ".geoid";
  app->AddParameter(ParameterType_InputFilename, oss.str(), "Geoid File");
  app->SetParameterDescription(oss.str(),
                               "Use a geoid grid to get the height "
                               "above the ellipsoid in case there is no DEM available, no coverage for "
                               "some points or pixels with no_data in the DEM tiles. A version of the "
                               "geoid can be found on the OTB website"
                               "(https://gitlab.orfeo-toolbox.org/orfeotoolbox/otb-data/blob/master/Input/DEM/egm96.grd).");
  app->MandatoryOff(oss.str());

  std::string geoidFromConfig = otb::ConfigurationManager::GetGeoidFile();

  if (geoidFromConfig != "")
  {
    app->SetParameterString(oss.str(), geoidFromConfig);
    app->EnableParameter(oss.str());
  }
  else
  {
    app->DisableParameter(oss.str());
  }

  // Average elevation
  oss.str("");
  oss << key << ".default";
  app->AddParameter(ParameterType_Float, oss.str(), "Default elevation");
  app->SetParameterDescription(oss.str(),
                               "This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points "
                               "or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average "
                               "elevation value.");
  app->SetDefaultParameterFloat(oss.str(), 0.);

  // TODO : not implemented yet
  //   // Tiff image
  //   oss << ".tiff";
  //   app->AddChoice(oss.str(), "Tiff file");
  //   app->AddParameter(ParameterType_InputImage, oss.str(), "Tiff file");
  //   app->SetParameterDescription(oss.str(),"Tiff file used to get elevation for each location in the image");
}

void ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(const Application::Pointer app, const std::string& key)
{
  auto & demHandler = otb::DEMHandler::GetInstance();

  // Set default elevation
  demHandler.SetDefaultHeightAboveEllipsoid(GetDefaultElevation(app, key));

  std::ostringstream oss;
  oss << "Elevation management: setting default height above ellipsoid to " << GetDefaultElevation(app, key) << " meters" << std::endl;

  app->GetLogger()->Info(oss.str());

  // Set geoid if available
  if (IsGeoidUsed(app, key))
  {
    oss.str("");
    oss << "Elevation management: using geoid file (" << GetGeoidFile(app, key) << ")" << std::endl;
    demHandler.OpenGeoidFile(GetGeoidFile(app, key));

    app->GetLogger()->Info(oss.str());
  }

  // Set DEM directory if available
  if (IsDEMUsed(app, key))
  {
    std::string demDirectory = GetDEMDirectory(app, key);
    if (demHandler.IsValidDEMDirectory(demDirectory.c_str()))
    {
      oss.str("");
      oss << "Elevation management: using DEM directory (" << demDirectory << ")" << std::endl;
      demHandler.OpenDEMDirectory(demDirectory);
      app->GetLogger()->Info(oss.str());
    }
    else
    {
      oss.str("");
      oss << "DEM directory : " << demDirectory << " is not a valid DEM directory";
      app->GetLogger()->Warning(oss.str());
    }
  }
}

/**
 *
 * Get the Average elevation value
 */
float ElevationParametersHandler::GetDefaultElevation(const Application::Pointer app, const std::string& key)
{
  std::ostringstream oss;
  oss << key << ".default";
  return app->GetParameterFloat(oss.str());
}

/**
 * Get the Geoid file
 */
const std::string ElevationParametersHandler::GetGeoidFile(const Application::Pointer app, const std::string& key)
{
  std::ostringstream oss;
  oss << key << ".geoid";
  if (IsGeoidUsed(app, key))
  {
    return app->GetParameterString(oss.str());
  }

  return "";
}

/**
 * Is Geoid used
 */
bool ElevationParametersHandler::IsGeoidUsed(const Application::Pointer app, const std::string& key)
{
  std::ostringstream geoidKey;
  geoidKey << key << ".geoid";

  return app->IsParameterEnabled(geoidKey.str()) && app->HasValue(geoidKey.str());
}

/**
 *
 * Is Geoid used
 */
bool ElevationParametersHandler::IsDEMUsed(const Application::Pointer app, const std::string& key)
{
  std::ostringstream demKey;
  demKey << key << ".dem";

  return app->IsParameterEnabled(demKey.str()) && app->HasValue(demKey.str());
}

const std::string ElevationParametersHandler::GetDEMDirectory(const Application::Pointer app, const std::string& key)
{
  std::ostringstream oss;
  oss << key << ".dem";
  if (IsDEMUsed(app, key))
  {
    return app->GetParameterString(oss.str());
  }

  return "";
}

} // End namespace Wrapper
} // End namespace otb
<commit_msg>DOC: New link to the geoid files<commit_after>/*
 * Copyright (C) 2005-2022 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "otbWrapperElevationParametersHandler.h"
#include "otbDEMHandler.h"

namespace otb
{
namespace Wrapper
{

void ElevationParametersHandler::AddElevationParameters(Application::Pointer app, const std::string& key)
{
  app->AddParameter(ParameterType_Group, key, "Elevation management");
  app->SetParameterDescription(key,
                               "This group of parameters allows managing elevation values.");

  // DEM directory
  std::ostringstream oss;
  oss << key << ".dem";
  app->AddParameter(ParameterType_Directory, oss.str(), "DEM directory");
  app->SetParameterDescription(oss.str(),
                               "This parameter allows selecting a directory containing Digital Elevation Model files. Note that this directory should contain "
                               "only DEM files. Unexpected behaviour might occurs if other images are found in this directory. Input DEM tiles should be in a raster format supported by GDAL.");
  app->MandatoryOff(oss.str());

  std::string demDirFromConfig = otb::ConfigurationManager::GetDEMDirectory();

  if (demDirFromConfig != "")
  {
    app->SetParameterString(oss.str(), demDirFromConfig);
    app->EnableParameter(oss.str());
  }
  else
  {
    app->DisableParameter(oss.str());
  }

  // Geoid file
  oss.str("");
  oss << key << ".geoid";
  app->AddParameter(ParameterType_InputFilename, oss.str(), "Geoid File");
  app->SetParameterDescription(oss.str(),
                               "Use a geoid grid to get the height "
                               "above the ellipsoid in case there is no DEM available, no coverage for "
                               "some points or pixels with no_data in the DEM tiles. A version of the "
                               "geoid can be found on the OTB website (egm96.grd and egm96.grd.hdr at "
                               "https://gitlab.orfeo-toolbox.org/orfeotoolbox/otb/-/tree/master/Data/Input/DEM).");
  app->MandatoryOff(oss.str());

  std::string geoidFromConfig = otb::ConfigurationManager::GetGeoidFile();

  if (geoidFromConfig != "")
  {
    app->SetParameterString(oss.str(), geoidFromConfig);
    app->EnableParameter(oss.str());
  }
  else
  {
    app->DisableParameter(oss.str());
  }

  // Average elevation
  oss.str("");
  oss << key << ".default";
  app->AddParameter(ParameterType_Float, oss.str(), "Default elevation");
  app->SetParameterDescription(oss.str(),
                               "This parameter allows setting the default height above ellipsoid when there is no DEM available, no coverage for some points "
                               "or pixels with no_data in the DEM tiles, and no geoid file has been set. This is also used by some application as an average "
                               "elevation value.");
  app->SetDefaultParameterFloat(oss.str(), 0.);

  // TODO : not implemented yet
  //   // Tiff image
  //   oss << ".tiff";
  //   app->AddChoice(oss.str(), "Tiff file");
  //   app->AddParameter(ParameterType_InputImage, oss.str(), "Tiff file");
  //   app->SetParameterDescription(oss.str(),"Tiff file used to get elevation for each location in the image");
}

void ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(const Application::Pointer app, const std::string& key)
{
  auto & demHandler = otb::DEMHandler::GetInstance();

  // Set default elevation
  demHandler.SetDefaultHeightAboveEllipsoid(GetDefaultElevation(app, key));

  std::ostringstream oss;
  oss << "Elevation management: setting default height above ellipsoid to " << GetDefaultElevation(app, key) << " meters" << std::endl;

  app->GetLogger()->Info(oss.str());

  // Set geoid if available
  if (IsGeoidUsed(app, key))
  {
    oss.str("");
    oss << "Elevation management: using geoid file (" << GetGeoidFile(app, key) << ")" << std::endl;
    demHandler.OpenGeoidFile(GetGeoidFile(app, key));

    app->GetLogger()->Info(oss.str());
  }

  // Set DEM directory if available
  if (IsDEMUsed(app, key))
  {
    std::string demDirectory = GetDEMDirectory(app, key);
    if (demHandler.IsValidDEMDirectory(demDirectory.c_str()))
    {
      oss.str("");
      oss << "Elevation management: using DEM directory (" << demDirectory << ")" << std::endl;
      demHandler.OpenDEMDirectory(demDirectory);
      app->GetLogger()->Info(oss.str());
    }
    else
    {
      oss.str("");
      oss << "DEM directory : " << demDirectory << " is not a valid DEM directory";
      app->GetLogger()->Warning(oss.str());
    }
  }
}

/**
 *
 * Get the Average elevation value
 */
float ElevationParametersHandler::GetDefaultElevation(const Application::Pointer app, const std::string& key)
{
  std::ostringstream oss;
  oss << key << ".default";
  return app->GetParameterFloat(oss.str());
}

/**
 * Get the Geoid file
 */
const std::string ElevationParametersHandler::GetGeoidFile(const Application::Pointer app, const std::string& key)
{
  std::ostringstream oss;
  oss << key << ".geoid";
  if (IsGeoidUsed(app, key))
  {
    return app->GetParameterString(oss.str());
  }

  return "";
}

/**
 * Is Geoid used
 */
bool ElevationParametersHandler::IsGeoidUsed(const Application::Pointer app, const std::string& key)
{
  std::ostringstream geoidKey;
  geoidKey << key << ".geoid";

  return app->IsParameterEnabled(geoidKey.str()) && app->HasValue(geoidKey.str());
}

/**
 *
 * Is Geoid used
 */
bool ElevationParametersHandler::IsDEMUsed(const Application::Pointer app, const std::string& key)
{
  std::ostringstream demKey;
  demKey << key << ".dem";

  return app->IsParameterEnabled(demKey.str()) && app->HasValue(demKey.str());
}

const std::string ElevationParametersHandler::GetDEMDirectory(const Application::Pointer app, const std::string& key)
{
  std::ostringstream oss;
  oss << key << ".dem";
  if (IsDEMUsed(app, key))
  {
    return app->GetParameterString(oss.str());
  }

  return "";
}

} // End namespace Wrapper
} // End namespace otb
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlHierarchyCollection.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 14:07:17 $
 *
 *  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 DBA_XMLHIERARCHYCOLLECTION_HXX
#include "xmlHierarchyCollection.hxx"
#endif
#ifndef DBA_XMLCOMPONENT_HXX
#include "xmlComponent.hxx"
#endif
#ifndef DBA_XMLQUERY_HXX
#include "xmlQuery.hxx"
#endif
#ifndef DBA_XMLCOLUMN_HXX
#include "xmlColumn.hxx"
#endif
#ifndef DBA_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef DBA_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef DBACCESS_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif

namespace dbaxml
{
    using namespace ::rtl;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::xml::sax;

OXMLHierarchyCollection::OXMLHierarchyCollection( ODBFilter& rImport
                ,sal_uInt16 nPrfx
                ,const OUString& _sLocalName
                ,const Reference< XAttributeList > & _xAttrList
                ,const Reference< XNameAccess >& _xParentContainer
                ,const ::rtl::OUString& _sCollectionServiceName
                ,const ::rtl::OUString& _sComponentServiceName) :
    SvXMLImportContext( rImport, nPrfx, _sLocalName )
    ,m_xParentContainer(_xParentContainer)
    ,m_sCollectionServiceName(_sCollectionServiceName)
    ,m_sComponentServiceName(_sComponentServiceName)
{
    const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
    const SvXMLTokenMap& rTokenMap = rImport.GetComponentElemTokenMap();

    sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0;
    sal_Bool bAutoEnabled = sal_False;
    for(sal_Int16 i = 0; i < nLength; ++i)
    {
        OUString sLocalName;
        rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
        sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
        rtl::OUString sValue = _xAttrList->getValueByIndex( i );

        switch( rTokenMap.Get( nPrefix, sLocalName ) )
        {
            case XML_TOK_COMPONENT_NAME:
                m_sName = sValue;
                break;
        }
    }
    if ( m_sName.getLength() && _xParentContainer.is() )
    {
        try
        {
            Sequence< Any > aArguments(2);
            PropertyValue aValue;
            // set as folder
            aValue.Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Name"));
            aValue.Value <<= m_sName;
            aArguments[0] <<= aValue;
            //parent
            aValue.Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Parent"));
            aValue.Value <<= _xParentContainer;
            aArguments[1] <<= aValue;

            Reference<XMultiServiceFactory> xORB(_xParentContainer,UNO_QUERY);
            if ( xORB.is() )
            {
                m_xContainer.set(xORB->createInstanceWithArguments(_sCollectionServiceName,aArguments),UNO_QUERY);
                Reference<XNameContainer> xNameContainer(_xParentContainer,UNO_QUERY);
                if ( xNameContainer.is() )
                    xNameContainer->insertByName(m_sName,makeAny(m_xContainer));
            }
        }
        catch(Exception&)
        {
            OSL_ENSURE(0,"OXMLHierarchyCollection::OXMLHierarchyCollection -> exception catched");
        }
    }
}
// -----------------------------------------------------------------------------
OXMLHierarchyCollection::OXMLHierarchyCollection( ODBFilter& rImport
                ,sal_uInt16 nPrfx
                ,const OUString& _sLocalName
                ,const Reference< XNameAccess >& _xContainer
            ) :
    SvXMLImportContext( rImport, nPrfx, _sLocalName )
    ,m_xContainer(_xContainer)
{
}
// -----------------------------------------------------------------------------

OXMLHierarchyCollection::~OXMLHierarchyCollection()
{
}
// -----------------------------------------------------------------------------
SvXMLImportContext* OXMLHierarchyCollection::CreateChildContext(
        sal_uInt16 nPrefix,
        const OUString& rLocalName,
        const Reference< XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    const SvXMLTokenMap&    rTokenMap   = GetOwnImport().GetDocumentsElemTokenMap();

    switch( rTokenMap.Get( nPrefix, rLocalName ) )
    {
//      case XML_TOK_QUERY:
//          pContext = new OXMLQuery( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer );
//          break;
        case XML_TOK_COMPONENT:
            GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLComponent( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer,m_sComponentServiceName );
            break;
        case XML_TOK_COLUMN:
            GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLColumn( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer);
            break;
        //  case XML_TOK_QUERY_COLLECTION:
        case XML_TOK_COMPONENT_COLLECTION:
            GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLHierarchyCollection( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer,m_sCollectionServiceName,m_sComponentServiceName);
            break;
    }

    if( !pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );

    return pContext;
}
// -----------------------------------------------------------------------------
ODBFilter& OXMLHierarchyCollection::GetOwnImport()
{
    return static_cast<ODBFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
//----------------------------------------------------------------------------
} // namespace dbaxml
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba201b (1.2.146); FILE MERGED 2005/09/21 07:30:41 oj 1.2.146.2: RESYNC: (1.2-1.3); FILE MERGED 2005/07/11 13:37:06 fs 1.2.146.1: merging CWS dba201 into CWS dba201b<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlHierarchyCollection.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2005-09-23 12:11:34 $
 *
 *  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 DBA_XMLHIERARCHYCOLLECTION_HXX
#include "xmlHierarchyCollection.hxx"
#endif
#ifndef DBA_XMLCOMPONENT_HXX
#include "xmlComponent.hxx"
#endif
#ifndef DBA_XMLQUERY_HXX
#include "xmlQuery.hxx"
#endif
#ifndef DBA_XMLCOLUMN_HXX
#include "xmlColumn.hxx"
#endif
#ifndef DBA_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef DBA_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef DBACCESS_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

namespace dbaxml
{
    using namespace ::rtl;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::xml::sax;
DBG_NAME(OXMLHierarchyCollection)

OXMLHierarchyCollection::OXMLHierarchyCollection( ODBFilter& rImport
                ,sal_uInt16 nPrfx
                ,const OUString& _sLocalName
                ,const Reference< XAttributeList > & _xAttrList
                ,const Reference< XNameAccess >& _xParentContainer
                ,const ::rtl::OUString& _sCollectionServiceName
                ,const ::rtl::OUString& _sComponentServiceName) :
    SvXMLImportContext( rImport, nPrfx, _sLocalName )
    ,m_xParentContainer(_xParentContainer)
    ,m_sCollectionServiceName(_sCollectionServiceName)
    ,m_sComponentServiceName(_sComponentServiceName)
{
    DBG_CTOR(OXMLHierarchyCollection,NULL);

    const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
    const SvXMLTokenMap& rTokenMap = rImport.GetComponentElemTokenMap();

    sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0;
    sal_Bool bAutoEnabled = sal_False;
    for(sal_Int16 i = 0; i < nLength; ++i)
    {
        OUString sLocalName;
        rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
        sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
        rtl::OUString sValue = _xAttrList->getValueByIndex( i );

        switch( rTokenMap.Get( nPrefix, sLocalName ) )
        {
            case XML_TOK_COMPONENT_NAME:
                m_sName = sValue;
                break;
        }
    }
    if ( m_sName.getLength() && _xParentContainer.is() )
    {
        try
        {
            Sequence< Any > aArguments(2);
            PropertyValue aValue;
            // set as folder
            aValue.Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Name"));
            aValue.Value <<= m_sName;
            aArguments[0] <<= aValue;
            //parent
            aValue.Name = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Parent"));
            aValue.Value <<= _xParentContainer;
            aArguments[1] <<= aValue;

            Reference<XMultiServiceFactory> xORB(_xParentContainer,UNO_QUERY);
            if ( xORB.is() )
            {
                m_xContainer.set(xORB->createInstanceWithArguments(_sCollectionServiceName,aArguments),UNO_QUERY);
                Reference<XNameContainer> xNameContainer(_xParentContainer,UNO_QUERY);
                if ( xNameContainer.is() )
                    xNameContainer->insertByName(m_sName,makeAny(m_xContainer));
            }
        }
        catch(Exception&)
        {
            OSL_ENSURE(0,"OXMLHierarchyCollection::OXMLHierarchyCollection -> exception catched");
        }
    }
}
// -----------------------------------------------------------------------------
OXMLHierarchyCollection::OXMLHierarchyCollection( ODBFilter& rImport
                ,sal_uInt16 nPrfx
                ,const OUString& _sLocalName
                ,const Reference< XNameAccess >& _xContainer
            ) :
    SvXMLImportContext( rImport, nPrfx, _sLocalName )
    ,m_xContainer(_xContainer)
{
    DBG_CTOR(OXMLHierarchyCollection,NULL);
}
// -----------------------------------------------------------------------------

OXMLHierarchyCollection::~OXMLHierarchyCollection()
{

    DBG_DTOR(OXMLHierarchyCollection,NULL);
}
// -----------------------------------------------------------------------------
SvXMLImportContext* OXMLHierarchyCollection::CreateChildContext(
        sal_uInt16 nPrefix,
        const OUString& rLocalName,
        const Reference< XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    const SvXMLTokenMap&    rTokenMap   = GetOwnImport().GetDocumentsElemTokenMap();

    switch( rTokenMap.Get( nPrefix, rLocalName ) )
    {
//      case XML_TOK_QUERY:
//          pContext = new OXMLQuery( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer );
//          break;
        case XML_TOK_COMPONENT:
            GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLComponent( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer,m_sComponentServiceName );
            break;
        case XML_TOK_COLUMN:
            GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLColumn( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer);
            break;
        //  case XML_TOK_QUERY_COLLECTION:
        case XML_TOK_COMPONENT_COLLECTION:
            GetOwnImport().GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLHierarchyCollection( GetOwnImport(), nPrefix, rLocalName,xAttrList,m_xContainer,m_sCollectionServiceName,m_sComponentServiceName);
            break;
    }

    if( !pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );

    return pContext;
}
// -----------------------------------------------------------------------------
ODBFilter& OXMLHierarchyCollection::GetOwnImport()
{
    return static_cast<ODBFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
//----------------------------------------------------------------------------
} // namespace dbaxml
// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before><commit_msg>Simplify CheckValidR function PR feedback<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2006-2008 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.

#define STRSAFE_NO_DEPRECATE
#include "webkit/glue/plugins/test/plugin_execute_script_delete_test.h"
#include "webkit/glue/plugins/test/plugin_client.h"

namespace NPAPIClient {

ExecuteScriptDeleteTest::ExecuteScriptDeleteTest(
    NPP id, NPNetscapeFuncs *host_functions, const std::string& test_name)
  : PluginTest(id, host_functions),
    test_name_(test_name) {
}

int16 ExecuteScriptDeleteTest::HandleEvent(void* event) {

  NPNetscapeFuncs* browser = NPAPIClient::PluginClient::HostFunctions();

  NPBool supports_windowless = 0;
  NPError result = browser->getvalue(id(), NPNVSupportsWindowless,
                                     &supports_windowless);
  if ((result != NPERR_NO_ERROR) || (supports_windowless != TRUE)) {
    SetError("Failed to read NPNVSupportsWindowless value");
    SignalTestCompleted();
    return PluginTest::HandleEvent(event);
  }

  NPEvent* np_event = reinterpret_cast<NPEvent*>(event);
  if (WM_PAINT == np_event->event &&
      base::strcasecmp(test_name_.c_str(),
                       "execute_script_delete_in_paint") == 0) {
    NPString script_string;
    script_string.UTF8Characters = "javascript:alert(\"hi\")";
    script_string.UTF8Length =
        static_cast<unsigned int>(strlen("javascript:alert(\"hi\")"));

    NPObject *window_obj = NULL;
    browser->getvalue(id(), NPNVWindowNPObject, &window_obj);
    NPVariant result_var;
    NPError result = browser->evaluate(id(), window_obj,
                                       &script_string, &result_var);

    NPUTF8* urlString = "javascript:DeletePluginWithinScript()";
    NPUTF8* targetString = NULL;
    browser->geturl(id(), urlString, targetString);
    SignalTestCompleted();
  } else if (WM_MOUSEMOVE == np_event->event &&
             base::strcasecmp(test_name_.c_str(),
                              "execute_script_delete_in_mouse_move") == 0) {
    std::string script = "javascript:DeletePluginWithinScript()";
    NPString script_string;
    script_string.UTF8Characters = script.c_str();
    script_string.UTF8Length =
        static_cast<unsigned int>(script.length());

    NPObject *window_obj = NULL;
    browser->getvalue(id(), NPNVWindowNPObject, &window_obj);
    NPVariant result_var;
    NPError result = browser->evaluate(id(), window_obj,
                                       &script_string, &result_var);
    SignalTestCompleted();
  }
  // If this test failed, then we'd have crashed by now.
  return PluginTest::HandleEvent(event);
}

} // namespace NPAPIClient

<commit_msg>Revert this file submitted by accident Review URL: http://codereview.chromium.org/13222<commit_after>// Copyright (c) 2006-2008 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.

#define STRSAFE_NO_DEPRECATE
#include "webkit/glue/plugins/test/plugin_execute_script_delete_test.h"
#include "webkit/glue/plugins/test/plugin_client.h"

namespace NPAPIClient {

ExecuteScriptDeleteTest::ExecuteScriptDeleteTest(
    NPP id, NPNetscapeFuncs *host_functions, const std::string& test_name)
  : PluginTest(id, host_functions),
    test_name_(test_name) {
}

int16 ExecuteScriptDeleteTest::HandleEvent(void* event) {

  NPNetscapeFuncs* browser = NPAPIClient::PluginClient::HostFunctions();

  NPBool supports_windowless = 0;
  NPError result = browser->getvalue(id(), NPNVSupportsWindowless,
                                     &supports_windowless);
  if ((result != NPERR_NO_ERROR) || (supports_windowless != TRUE)) {
    SetError("Failed to read NPNVSupportsWindowless value");
    SignalTestCompleted();
    return PluginTest::HandleEvent(event);
  }

  NPEvent* np_event = reinterpret_cast<NPEvent*>(event);
  if (WM_PAINT == np_event->event &&
      base::strcasecmp(test_name_.c_str(),
                       "execute_script_delete_in_paint") == 0) {
    NPUTF8* urlString = "javascript:DeletePluginWithinScript()";
    NPUTF8* targetString = NULL;
    browser->geturl(id(), urlString, targetString);
    SignalTestCompleted();
  } else if (WM_MOUSEMOVE == np_event->event &&
             base::strcasecmp(test_name_.c_str(),
                              "execute_script_delete_in_mouse_move") == 0) {
    std::string script = "javascript:DeletePluginWithinScript()";
    NPString script_string;
    script_string.UTF8Characters = script.c_str();
    script_string.UTF8Length =
        static_cast<unsigned int>(script.length());

    NPObject *window_obj = NULL;
    browser->getvalue(id(), NPNVWindowNPObject, &window_obj);
    NPVariant result_var;
    NPError result = browser->evaluate(id(), window_obj,
                                       &script_string, &result_var);
    SignalTestCompleted();
  }
  // If this test failed, then we'd have crashed by now.
  return PluginTest::HandleEvent(event);
}

} // namespace NPAPIClient

<|endoftext|>