<commit_before>/*
 * Copyright  2016 Cask Data, Inc.
 *
 * 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 "stdafx.h"
#include "spi.h"
#include "Driver.h"
#include "ConnectionInfo.h"
#include "CdapException.h"
#include "InvalidHandleException.h"
#include "Argument.h"

using namespace Cask::CdapOdbc;

SQLRETURN SQL_SPI SQLCleanupConnectionPoolID(
  SQLHENV environmentHandle,
  POOLID poolID) {
  return SQL_ERROR;
}

SQLRETURN SQL_SPI SQLGetPoolID(
  SQLHDBC_INFO_TOKEN hDbcInfoToken,
  _Out_ POOLID* pPoolID) {
  return SQL_ERROR;
}

SQLRETURN SQL_SPI SQLPoolConnectW(
  SQLHDBC hdbc,
  SQLHDBC_INFO_TOKEN hDbcInfoToken,
  _Out_writes_opt_(cchConnStrOutMax) SQLWCHAR* szConnStrOut,
  SQLSMALLINT cchConnStrOutMax,
  _Out_opt_ SQLSMALLINT* pcchConnStrOut) {
  return SQL_ERROR;
}

SQLRETURN SQL_SPI SQLRateConnection(
  SQLHDBC_INFO_TOKEN hRequest,
  SQLHDBC hCandidateConnection,
  BOOL fRequiresTransactionEnlistment,
  TRANSID transId,
  _Out_ SQLConnPoolRating* pRating) {
  TRACE(L"SQLRateConnection(hRequest = %X, hCandidateConnection = %X)\n", hRequest, hCandidateConnection);
  try {
    auto& info = Driver::getInstance().getConnectionInfo(hRequest);
    auto& connection = Driver::getInstance().getConnection(hCandidateConnection);
    try {
      info.getSqlStatus().clear();
      *pRating = static_cast<SQLConnPoolRating>(info.rateConnection(connection));
      TRACE(L"SQLRateConnection returns SQL_SUCCESS\n");
      return SQL_SUCCESS;
    } catch (CdapException& cex) {
      TRACE(L"SQLRateConnection returns SQL_ERROR\n");
      info.getSqlStatus().addError(cex);
      return cex.getErrorCode();
    } catch (std::exception& ex) {
      TRACE(L"SQLRateConnection returns SQL_ERROR\n");
      info.getSqlStatus().addError(ex);
      return SQL_ERROR;
    }
  } catch (InvalidHandleException&) {
    TRACE(L"SQLRateConnection returns SQL_INVALID_HANDLE\n");
    return SQL_INVALID_HANDLE;
  } catch (std::exception&) {
    TRACE(L"SQLRateConnection returns SQL_ERROR\n");
    return SQL_ERROR;
  }
}

SQLRETURN SQL_SPI SQLSetConnectAttrForDbcInfoW(
  SQLHDBC_INFO_TOKEN hDbcInfoToken,
  SQLINTEGER Attribute,
  _In_reads_bytes_opt_(StringLength) SQLPOINTER Value,
  SQLINTEGER StringLength) {
  TRACE(L"SQLSetConnectAttrForDbcInfoW(hDbcInfoToken = %X, Attribute = %d)\n", hDbcInfoToken, Attribute);
  try {
    auto& info = Driver::getInstance().getConnectionInfo(hDbcInfoToken);
    try {
      info.getSqlStatus().clear();
      SQLULEN value = 0;
      switch (Attribute) {
        case SQL_ATTR_ASYNC_ENABLE:
          value = reinterpret_cast<SQLULEN>(Value);
          info.setAsync(value == SQL_ASYNC_ENABLE_ON);
          TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_SUCCESS\n");
          return SQL_SUCCESS;
        case SQL_ATTR_ASYNC_DBC_FUNCTIONS_ENABLE:
          value = reinterpret_cast<SQLULEN>(Value);
          info.setFunctionsAsync(value == SQL_ASYNC_DBC_ENABLE_ON);
          TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_SUCCESS\n");
          return SQL_SUCCESS;
        default:
          TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_SUCCESS\n");
          return SQL_SUCCESS;
      }
    } catch (CdapException& cex) {
      TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_ERROR\n");
      info.getSqlStatus().addError(cex);
      return cex.getErrorCode();
    } catch (std::exception& ex) {
      TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_ERROR\n");
      info.getSqlStatus().addError(ex);
      return SQL_ERROR;
    }
  } catch (InvalidHandleException&) {
    TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_INVALID_HANDLE\n");
    return SQL_INVALID_HANDLE;
  } catch (std::exception&) {
    TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_ERROR\n");
    return SQL_ERROR;
  }
}

SQLRETURN SQL_SPI SQLSetConnectInfoW(
  SQLHDBC_INFO_TOKEN hDbcInfoToken,
  _In_reads_(cchDSN) SQLWCHAR* szDSN,
  SQLSMALLINT cchDSN,
  _In_reads_(cchUID) SQLWCHAR* szUID,
  SQLSMALLINT cchUID,
  _In_reads_(cchAuthStr) SQLWCHAR* szAuthStr,
  SQLSMALLINT cchAuthStr) {
  // Used for SQLConnect call
  // Not supported
  TRACE(L"SQLSetConnectInfoW\n");
  TRACE(L"SQLSetConnectInfoW returns SQL_ERROR\n");
  return SQL_ERROR;
}

SQLRETURN SQL_SPI SQLSetDriverConnectInfoW(
  SQLHDBC_INFO_TOKEN hDbcInfoToken,
  _In_reads_(cchConnStrIn) SQLWCHAR* szConnStrIn,
  SQLSMALLINT cchConnStrIn) {
  TRACE(L"SQLSetDriverConnectInfoW(hDbcInfoToken = %X, szConnStrIn = %s)\n", hDbcInfoToken, szConnStrIn);
  try {
    auto& info = Driver::getInstance().getConnectionInfo(hDbcInfoToken);
    try {
      info.getSqlStatus().clear();
      auto connectionString = Argument::toStdString(szConnStrIn, cchConnStrIn);
      if (connectionString) {
        info.setConnectionString(*connectionString);
        TRACE(L"SQLSetDriverConnectInfoW returns SQL_SUCCESS\n");
        return SQL_SUCCESS;
      } else {
        throw CdapException(L"Connection string cannot be empty.");
      }
    } catch (CdapException& cex) {
      TRACE(L"SQLSetDriverConnectInfoW returns SQL_ERROR\n");
      info.getSqlStatus().addError(cex);
      return cex.getErrorCode();
    } catch (std::exception& ex) {
      TRACE(L"SQLSetDriverConnectInfoW returns SQL_ERROR\n");
      info.getSqlStatus().addError(ex);
      return SQL_ERROR;
    }
  } catch (InvalidHandleException&) {
    TRACE(L"SQLSetDriverConnectInfoW returns SQL_INVALID_HANDLE\n");
    return SQL_INVALID_HANDLE;
  } catch (std::exception&) {
    TRACE(L"SQLSetDriverConnectInfoW returns SQL_ERROR\n");
    return SQL_ERROR;
  }
}<commit_msg>SQLPoolConnect function.<commit_after>/*
 * Copyright  2016 Cask Data, Inc.
 *
 * 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 "stdafx.h"
#include "spi.h"
#include "Driver.h"
#include "ConnectionInfo.h"
#include "CdapException.h"
#include "InvalidHandleException.h"
#include "Argument.h"
#include "Connection.h"

using namespace Cask::CdapOdbc;

SQLRETURN SQL_SPI SQLCleanupConnectionPoolID(
  SQLHENV environmentHandle,
  POOLID poolID) {
  return SQL_ERROR;
}

SQLRETURN SQL_SPI SQLGetPoolID(
  SQLHDBC_INFO_TOKEN hDbcInfoToken,
  _Out_ POOLID* pPoolID) {
  return SQL_ERROR;
}

SQLRETURN SQL_SPI SQLPoolConnectW(
  SQLHDBC hdbc,
  SQLHDBC_INFO_TOKEN hDbcInfoToken,
  _Out_writes_opt_(cchConnStrOutMax) SQLWCHAR* szConnStrOut,
  SQLSMALLINT cchConnStrOutMax,
  _Out_opt_ SQLSMALLINT* pcchConnStrOut) {
  TRACE(L"SQLPoolConnectW(hdbc = %X, hDbcInfoToken = %X)\n", hdbc, hDbcInfoToken);
  try {
    auto& connection = Driver::getInstance().getConnection(hdbc);
    auto& info = Driver::getInstance().getConnectionInfo(hDbcInfoToken);
    try {
      auto connectionString = connection.getParams().getFullConnectionString();
      if (connection.getIsFunctionsAsync()) {
        if (!connection.openAsync(connectionString)) {
          TRACE(L"SQLPoolConnectW returns SQL_STILL_EXECUTING, szConnStrOut = %s\n", szConnStrOut);
          return SQL_STILL_EXECUTING;
        }
      } else {
        connection.open(connectionString);
      }

      Argument::fromStdString(connectionString, szConnStrOut, cchConnStrOutMax, pcchConnStrOut);
      TRACE(L"SQLPoolConnectW returns SQL_SUCCESS, szConnStrOut = %s\n", szConnStrOut);
      return SQL_SUCCESS;
    } catch (CdapException& cex) {
      TRACE(L"SQLPoolConnectW returns SQL_ERROR\n");
      info.getSqlStatus().addError(cex);
      return cex.getErrorCode();
    } catch (std::exception& ex) {
      TRACE(L"SQLPoolConnectW returns SQL_ERROR\n");
      info.getSqlStatus().addError(ex);
      return SQL_ERROR;
    }
  } catch (InvalidHandleException&) {
    TRACE(L"SQLPoolConnectW returns SQL_INVALID_HANDLE\n");
    return SQL_INVALID_HANDLE;
  } catch (std::exception&) {
    TRACE(L"SQLPoolConnectW returns SQL_ERROR\n");
    return SQL_ERROR;
  }
}

SQLRETURN SQL_SPI SQLRateConnection(
  SQLHDBC_INFO_TOKEN hRequest,
  SQLHDBC hCandidateConnection,
  BOOL fRequiresTransactionEnlistment,
  TRANSID transId,
  _Out_ SQLConnPoolRating* pRating) {
  TRACE(L"SQLRateConnection(hRequest = %X, hCandidateConnection = %X)\n", hRequest, hCandidateConnection);
  try {
    auto& info = Driver::getInstance().getConnectionInfo(hRequest);
    auto& connection = Driver::getInstance().getConnection(hCandidateConnection);
    try {
      info.getSqlStatus().clear();
      *pRating = static_cast<SQLConnPoolRating>(info.rateConnection(connection));
      TRACE(L"SQLRateConnection returns SQL_SUCCESS\n");
      return SQL_SUCCESS;
    } catch (CdapException& cex) {
      TRACE(L"SQLRateConnection returns SQL_ERROR\n");
      info.getSqlStatus().addError(cex);
      return cex.getErrorCode();
    } catch (std::exception& ex) {
      TRACE(L"SQLRateConnection returns SQL_ERROR\n");
      info.getSqlStatus().addError(ex);
      return SQL_ERROR;
    }
  } catch (InvalidHandleException&) {
    TRACE(L"SQLRateConnection returns SQL_INVALID_HANDLE\n");
    return SQL_INVALID_HANDLE;
  } catch (std::exception&) {
    TRACE(L"SQLRateConnection returns SQL_ERROR\n");
    return SQL_ERROR;
  }
}

SQLRETURN SQL_SPI SQLSetConnectAttrForDbcInfoW(
  SQLHDBC_INFO_TOKEN hDbcInfoToken,
  SQLINTEGER Attribute,
  _In_reads_bytes_opt_(StringLength) SQLPOINTER Value,
  SQLINTEGER StringLength) {
  TRACE(L"SQLSetConnectAttrForDbcInfoW(hDbcInfoToken = %X, Attribute = %d)\n", hDbcInfoToken, Attribute);
  try {
    auto& info = Driver::getInstance().getConnectionInfo(hDbcInfoToken);
    try {
      info.getSqlStatus().clear();
      SQLULEN value = 0;
      switch (Attribute) {
        case SQL_ATTR_ASYNC_ENABLE:
          value = reinterpret_cast<SQLULEN>(Value);
          info.setAsync(value == SQL_ASYNC_ENABLE_ON);
          TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_SUCCESS\n");
          return SQL_SUCCESS;
        case SQL_ATTR_ASYNC_DBC_FUNCTIONS_ENABLE:
          value = reinterpret_cast<SQLULEN>(Value);
          info.setFunctionsAsync(value == SQL_ASYNC_DBC_ENABLE_ON);
          TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_SUCCESS\n");
          return SQL_SUCCESS;
        default:
          TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_SUCCESS\n");
          return SQL_SUCCESS;
      }
    } catch (CdapException& cex) {
      TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_ERROR\n");
      info.getSqlStatus().addError(cex);
      return cex.getErrorCode();
    } catch (std::exception& ex) {
      TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_ERROR\n");
      info.getSqlStatus().addError(ex);
      return SQL_ERROR;
    }
  } catch (InvalidHandleException&) {
    TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_INVALID_HANDLE\n");
    return SQL_INVALID_HANDLE;
  } catch (std::exception&) {
    TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_ERROR\n");
    return SQL_ERROR;
  }
}

SQLRETURN SQL_SPI SQLSetConnectInfoW(
  SQLHDBC_INFO_TOKEN hDbcInfoToken,
  _In_reads_(cchDSN) SQLWCHAR* szDSN,
  SQLSMALLINT cchDSN,
  _In_reads_(cchUID) SQLWCHAR* szUID,
  SQLSMALLINT cchUID,
  _In_reads_(cchAuthStr) SQLWCHAR* szAuthStr,
  SQLSMALLINT cchAuthStr) {
  // Used for SQLConnect call
  // Not supported
  TRACE(L"SQLSetConnectInfoW\n");
  TRACE(L"SQLSetConnectInfoW returns SQL_ERROR\n");
  return SQL_ERROR;
}

SQLRETURN SQL_SPI SQLSetDriverConnectInfoW(
  SQLHDBC_INFO_TOKEN hDbcInfoToken,
  _In_reads_(cchConnStrIn) SQLWCHAR* szConnStrIn,
  SQLSMALLINT cchConnStrIn) {
  TRACE(L"SQLSetDriverConnectInfoW(hDbcInfoToken = %X, szConnStrIn = %s)\n", hDbcInfoToken, szConnStrIn);
  try {
    auto& info = Driver::getInstance().getConnectionInfo(hDbcInfoToken);
    try {
      info.getSqlStatus().clear();
      auto connectionString = Argument::toStdString(szConnStrIn, cchConnStrIn);
      if (connectionString) {
        info.setConnectionString(*connectionString);
        TRACE(L"SQLSetDriverConnectInfoW returns SQL_SUCCESS\n");
        return SQL_SUCCESS;
      } else {
        throw CdapException(L"Connection string cannot be empty.");
      }
    } catch (CdapException& cex) {
      TRACE(L"SQLSetDriverConnectInfoW returns SQL_ERROR\n");
      info.getSqlStatus().addError(cex);
      return cex.getErrorCode();
    } catch (std::exception& ex) {
      TRACE(L"SQLSetDriverConnectInfoW returns SQL_ERROR\n");
      info.getSqlStatus().addError(ex);
      return SQL_ERROR;
    }
  } catch (InvalidHandleException&) {
    TRACE(L"SQLSetDriverConnectInfoW returns SQL_INVALID_HANDLE\n");
    return SQL_INVALID_HANDLE;
  } catch (std::exception&) {
    TRACE(L"SQLSetDriverConnectInfoW returns SQL_ERROR\n");
    return SQL_ERROR;
  }
}<|endoftext|>


<commit_before>/*
 * Ultrasonic.cpp - Library for HC-SR04 Ultrasonic Sensing Module.
 *
 * With ideas from:
 *   Created by ITead studio. Apr 20, 2010.
 *   iteadstudio.com
 *
 * SVN Keywords
 * ----------------------------------
 * $Author$
 * $Date$
 * $Revision$
 * ----------------------------------
 */

#include <stdlib.h>
#include <string.h>
#include <Ultrasonic.h>

Ultrasonic::Ultrasonic(int tp, int ep)
    {
    pinMode(tp, OUTPUT);
    pinMode(ep, INPUT);
    _trigPin = tp;
    _echoPin = ep;
    _multiplier = MULTIPLIER_DEFAULT;
    /* Don't allow a maximum distance longer than the sensor supports. */
    _maxDistance = _MAX_CM_DISTANCE;
    _pingTimeout = _maxDistance * _PING_OVERHEAD;
    _temp = _TEMP_CELSIUS_DEFAULT;
    }

long Ultrasonic::timing(void)
    {
    digitalWrite(_trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(_trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(_trigPin, LOW);
    return pulseIn(_echoPin, HIGH, _pingTimeout);
    }

float Ultrasonic::convert(long microsec, int metric)
    {
    // 0.5 * 331.29 * (1 + _temp/273)^0.5 * (microsec * 0.0001) * _multiplier
    float dist = min(0.0165645 * pow(1 + _temp/273, 0.5)
                     * microsec * _multiplier, _maxDistance);

    if(metric) return dist;
    else return dist * 0.3937;
    }

void Ultrasonic::setMultiplier(float value)
    {
    _multiplier = value;
    }

void Ultrasonic::setTemperature(float value)
    {
    _temp = value;
    }

void Ultrasonic::setMaxDistance(int value)
    {
    _maxDistance = min(value, _MAX_CM_DISTANCE);
    _pingTimeout = _maxDistance * _PING_OVERHEAD;
    }

#ifdef COMPILE_STD_DEV
bool Ultrasonic::sampleCreate(size_t numBufs, ...)
    {
    bool result = false;
    va_list ap;
    _numBufs = numBufs;

    if((_pBuffers = (BufCtl *) calloc(numBufs, sizeof(BufCtl))) != NULL)
        {
        va_start(ap, numBufs);
        BufCtl *buf;
        size_t smpSize;

        for(size_t i = 0; i < _numBufs; i++)
            {
            buf = &_pBuffers[i];
            smpSize = va_arg(ap, size_t);

            if((buf->pBegin = (float *) calloc(smpSize, sizeof(float))) != NULL)
                {
                buf->pIndex = buf->pBegin;
                buf->length = smpSize;
                buf->filled = false;
                result = true;
                }
            else
                {
                result = false;
                break;
                }
            }

        va_end(ap);
        }

    if(!result) _freeBuffers();
    return result;
    }

void Ultrasonic::sampleClear()
    {
    if(_pBuffers)
        {
        BufCtl *buf;

        for(size_t i = 0; i < _numBufs; i++)
            {
            buf = &_pBuffers[i];
            memset(buf, '\0', sizeof(float) * buf->length);
            buf->pIndex = buf->pBegin;
            buf->filled = false;
            }
        }
    }

float Ultrasonic::unbiasedStdDev(float value, size_t bufNum)
    {
    float result = 0.0;

    if(_pBuffers)
        {
        BufCtl *buf = &_pBuffers[bufNum];

        if(buf->length > 1)
            {
            _sampleUpdate(buf, float(value));

            if(buf->filled)
                {
                float sum = 0.0, mean, tmp;

                for(size_t i = 0; i < buf->length; i++)
                    sum += buf->pBegin[i];

                mean = sum / buf->length;
                sum = 0.0;

                for(size_t i = 0; i < buf->length; i++)
                    {
                    tmp = buf->pBegin[i] - mean;
                    sum += (tmp * tmp);
                    }

                result = sqrt(sum / (buf->length - 1));
                //Serial.print(bufNum);
                //Serial.print(" : ");
                //Serial.println(result);
                }
            }
        }

    return result;
    }

void Ultrasonic::_sampleUpdate(BufCtl *buf, float msec)
    {
    if(buf->pIndex >= (buf->pBegin + buf->length))
        {
        buf->pIndex = buf->pBegin;
        buf->filled = true;
        }

    *(buf->pIndex++) = msec;
    }

void Ultrasonic::_freeBuffers()
    {
    if(_pBuffers)
        {
        BufCtl *buf;

        for(size_t i = 0; i < _numBufs; i++)
            {
            buf = &_pBuffers[i];
            free(buf->pBegin);
            }

        free(_pBuffers);
        }
    }
#endif // COMPILE_STD_DEV
<commit_msg>Updated header name.<commit_after>/*
 * Ultrasonic.cpp - Library for HC-SR04 Ultrasonic Sensing Module.
 *
 * With ideas from:
 *   Created by ITead studio. Apr 20, 2010.
 *   iteadstudio.com
 *
 * SVN Keywords
 * ----------------------------------
 * $Author$
 * $Date$
 * $Revision$
 * ----------------------------------
 */

#include <stdlib.h>
#include <string.h>
#include <HCSR04Ultrasonic.h>

Ultrasonic::Ultrasonic(int tp, int ep)
    {
    pinMode(tp, OUTPUT);
    pinMode(ep, INPUT);
    _trigPin = tp;
    _echoPin = ep;
    _multiplier = MULTIPLIER_DEFAULT;
    /* Don't allow a maximum distance farther than the sensor supports. */
    _maxDistance = _MAX_CM_DISTANCE;
    _pingTimeout = _maxDistance * _PING_OVERHEAD;
    _temp = _TEMP_CELSIUS_DEFAULT;
    }

long Ultrasonic::timing(void)
    {
    digitalWrite(_trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(_trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(_trigPin, LOW);
    return pulseIn(_echoPin, HIGH, _pingTimeout);
    }

float Ultrasonic::convert(long microsec, int metric)
    {
    // 0.5 * 331.29 * (1 + _temp/273)^0.5 * (microsec * 0.0001) * _multiplier
    float dist = min(0.0165645 * pow(1 + _temp/273, 0.5)
                     * microsec * _multiplier, _maxDistance);

    if(metric) return dist;
    else return dist * 0.3937;
    }

void Ultrasonic::setMultiplier(float value)
    {
    _multiplier = value;
    }

void Ultrasonic::setTemperature(float value)
    {
    _temp = value;
    }

void Ultrasonic::setMaxDistance(int value)
    {
    _maxDistance = min(value, _MAX_CM_DISTANCE);
    _pingTimeout = _maxDistance * _PING_OVERHEAD;
    }

#ifdef COMPILE_STD_DEV
bool Ultrasonic::sampleCreate(size_t numBufs, ...)
    {
    bool result = false;
    va_list ap;
    _numBufs = numBufs;

    if((_pBuffers = (BufCtl *) calloc(numBufs, sizeof(BufCtl))) != NULL)
        {
        va_start(ap, numBufs);
        BufCtl *buf;
        size_t smpSize;

        for(size_t i = 0; i < _numBufs; i++)
            {
            buf = &_pBuffers[i];
            smpSize = va_arg(ap, size_t);

            if((buf->pBegin = (float *) calloc(smpSize, sizeof(float))) != NULL)
                {
                buf->pIndex = buf->pBegin;
                buf->length = smpSize;
                buf->filled = false;
                result = true;
                }
            else
                {
                result = false;
                break;
                }
            }

        va_end(ap);
        }

    if(!result) _freeBuffers();
    return result;
    }

void Ultrasonic::sampleClear()
    {
    if(_pBuffers)
        {
        BufCtl *buf;

        for(size_t i = 0; i < _numBufs; i++)
            {
            buf = &_pBuffers[i];
            memset(buf, '\0', sizeof(float) * buf->length);
            buf->pIndex = buf->pBegin;
            buf->filled = false;
            }
        }
    }

float Ultrasonic::unbiasedStdDev(float value, size_t bufNum)
    {
    float result = 0.0;

    if(_pBuffers)
        {
        BufCtl *buf = &_pBuffers[bufNum];

        if(buf->length > 1)
            {
            _sampleUpdate(buf, float(value));

            if(buf->filled)
                {
                float sum = 0.0, mean, tmp;

                for(size_t i = 0; i < buf->length; i++)
                    sum += buf->pBegin[i];

                mean = sum / buf->length;
                sum = 0.0;

                for(size_t i = 0; i < buf->length; i++)
                    {
                    tmp = buf->pBegin[i] - mean;
                    sum += (tmp * tmp);
                    }

                result = sqrt(sum / (buf->length - 1));
                //Serial.print(bufNum);
                //Serial.print(" : ");
                //Serial.println(result);
                }
            }
        }

    return result;
    }

void Ultrasonic::_sampleUpdate(BufCtl *buf, float msec)
    {
    if(buf->pIndex >= (buf->pBegin + buf->length))
        {
        buf->pIndex = buf->pBegin;
        buf->filled = true;
        }

    *(buf->pIndex++) = msec;
    }

void Ultrasonic::_freeBuffers()
    {
    if(_pBuffers)
        {
        BufCtl *buf;

        for(size_t i = 0; i < _numBufs; i++)
            {
            buf = &_pBuffers[i];
            free(buf->pBegin);
            }

        free(_pBuffers);
        }
    }
#endif // COMPILE_STD_DEV
<|endoftext|>


<commit_before>#include "manageescrowdialog.h"
#include "ui_manageescrowdialog.h"

#include "guiutil.h"
#include "syscoingui.h"
#include "ui_interface.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
#include "rpcserver.h"
using namespace std;

extern const CRPCTable tableRPC;
ManageEscrowDialog::ManageEscrowDialog(const QString &escrow, const QString &buyer, const QString &seller, const QString &arbiter, const QString &status, const QString &offertitle, const QString &total,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ManageEscrowDialog), escrow(escrow), buyer(buyer), seller(seller), arbiter(arbiter), status(status),offertitle(offertitle), total(total)
{
    ui->setupUi(this);
	EscrowType escrowType = findYourEscrowRoleFromAliases(buyer, seller, arbiter);
	ui->manageInfo->setText(tr("You are managing escrow ID: %1 of an offer for %2 totalling %3SYS. The buyer is %4, seller is %5 and arbiter is %6").arg(escrow).arg(offertitle).arg(total).arg(buyer).arg(seller).arg(arbiter));
	if(escrowType == None)
	{
		ui->manageInfo2->setText(tr("You cannot manage this escrow because you do not own one of either the buyer, seller or arbiter aliases."));
		ui->releaseButton->setEnabled(false);
		ui->refundButton->setEnabled(false);
	}
	else if(status == "in-escrow")
	{
		if(escrowType == Buyer)
		{
			ui->manageInfo2->setText(tr("You are the buyer of the offer held in escrow, you may release the coins to the seller once you have confirmed that you have recieved the item as per the description of the offer."));
			ui->refundButton->setEnabled(false);
		}
		else if(escrowType == Seller)
		{
			ui->manageInfo2->setText(tr("You are the seller of the offer held in escrow, you may refund the coins back to the buyer."));
			ui->releaseButton->setEnabled(false);
		}
		else if(escrowType == Arbiter)
		{
			ui->manageInfo2->setText(tr("You are the arbiter of the offer held in escrow, you may refund the coins back to the buyer if you have evidence that the seller did not honour the agreement to ship the offer item. You may also release the coins to the seller if the buyer has not released. You may use Syscoin messages to communicate with the buyer and seller to ensure you have adequeate proof for your decision."));
		}

	}
	else if(status == "escrow released")
	{
		if(escrowType == Buyer)
		{
			ui->manageInfo2->setText(tr("The escrow has already been released to the seller. You may communicate with your arbiter or seller via Syscoin messages."));
			ui->refundButton->setEnabled(false);
			ui->releaseButton->setEnabled(false);
		}
		else if(escrowType == Seller)
		{
			ui->manageInfo2->setText(tr("You are the seller of the offer held in escrow. The payment of coins have been released to you, you may claim them now."));
			ui->refundButton->setEnabled(false);
			ui->releaseButton->setText(tr("Claim Payment"));
		}
		else if(escrowType == Arbiter)
		{
			ui->manageInfo2->setText(tr("The escrow has already been released to the seller. You're job is done, if you were the one to release the coins you will recieve a commission as soon as the seller claims his payment."));
			ui->refundButton->setEnabled(false);
			ui->releaseButton->setEnabled(false);
		}
	}
	else if(status == "escrow refunded")
	{
		if(escrowType == Buyer)
		{
			ui->manageInfo2->setText(tr("You are the buyer of the offer held in escrow. The coins have been refunded back to you, you may claim them now."));
			ui->refundButton->setText(tr("Claim Refund"));
			ui->releaseButton->setEnabled(false);
		}
		else if(escrowType == Seller)
		{
			ui->manageInfo2->setText(tr("The escrow has already been refunded back to the buyer."));
			ui->refundButton->setEnabled(false);
			ui->releaseButton->setEnabled(false);
		}
		else if(escrowType == Arbiter)
		{
			ui->manageInfo2->setText(tr("The escrow has already been refunded back to the buyer. You're job is done, if you were the one to refund the coins you will recieve a commission as soon as the buyer claims his refund."));
			ui->refundButton->setEnabled(false);
			ui->releaseButton->setEnabled(false);
		}
	}
	else if(status == "complete")
	{
		ui->manageInfo2->setText(tr("The escrow has been successfully claimed by the seller. The escrow is complete."));
		ui->refundButton->setEnabled(false);
		ui->releaseButton->setEnabled(false);
	}
	else
	{
		ui->manageInfo2->setText(tr("The escrow status was not recognized. Please contact the Syscoin team."));
		ui->refundButton->setEnabled(false);
		ui->releaseButton->setEnabled(false);
	}
}
void ManageEscrowDialog::on_cancelButton_clicked()
{
    reject();
}
ManageEscrowDialog::~ManageEscrowDialog()
{
    delete ui;
}
void ManageEscrowDialog::on_releaseButton_clicked()
{
	UniValue params(UniValue::VARR);
	string strMethod = string("escrowrelease");
	params.push_back(escrow.toStdString());
	try {
		UniValue result = tableRPC.execute(strMethod, params);
		QMessageBox::information(this, windowTitle(),
		tr("Escrow released successfully!"),
			QMessageBox::Ok, QMessageBox::Ok);
		ManageEscrowDialog::accept();
	}
	catch (UniValue& objError)
	{
		string strError = find_value(objError, "message").get_str();
		QMessageBox::critical(this, windowTitle(),
        tr("Error releasing escrow: \"%1\"").arg(QString::fromStdString(strError)),
			QMessageBox::Ok, QMessageBox::Ok);
	}
	catch(std::exception& e)
	{
		QMessageBox::critical(this, windowTitle(),
            tr("General exception releasing escrow"),
			QMessageBox::Ok, QMessageBox::Ok);
	}
}
void ManageEscrowDialog::on_refundButton_clicked()
{
	UniValue params(UniValue::VARR);
	string strMethod = string("escrowrefund");
	params.push_back(escrow.toStdString());
	try {
		UniValue result = tableRPC.execute(strMethod, params);
		QMessageBox::information(this, windowTitle(),
		tr("Escrow refunded successfully!"),
			QMessageBox::Ok, QMessageBox::Ok);
		ManageEscrowDialog::accept();
	}
	catch (UniValue& objError)
	{
		string strError = find_value(objError, "message").get_str();
		QMessageBox::critical(this, windowTitle(),
        tr("Error refunding escrow: \"%1\"").arg(QString::fromStdString(strError)),
			QMessageBox::Ok, QMessageBox::Ok);
	}
	catch(std::exception& e)
	{
		QMessageBox::critical(this, windowTitle(),
            tr("General exception refunding escrow"),
			QMessageBox::Ok, QMessageBox::Ok);
	}
}
ManageEscrowDialog::EscrowType ManageEscrowDialog::findYourEscrowRoleFromAliases(const QString &buyer, const QString &seller, const QString &arbiter)
{
	if(isYourAlias(buyer))
		return EscrowType::Buyer;
	else if(isYourAlias(seller))
		return EscrowType::Seller;
	else if(isYourArbiter(arbiter))
		return EscrowType::Arbiter;
	else
		return EscrowType::None;

}
bool ManageEscrowDialog::isYourAlias(const QString &alias)
{
	string strMethod = string("aliasinfo");
    UniValue params(UniValue::VARR);
	UniValue result ;
	string name_str;
	int expired = 0;
	params.push_back(alias.toStdString());
	try {
		result = tableRPC.execute(strMethod, params);

		if (result.type() == UniValue::VOBJ)
		{
			const UniValue& o = result.get_obj();
			const UniValue& mine_value = find_value(o, "ismine");
			if (mine_value.type() == UniValue::VBOOL)
				return mine_value.get_bool();

		}
	}
	catch (UniValue& objError)
	{
		string strError = find_value(objError, "message").get_str();
		QMessageBox::critical(this, windowTitle(),
			tr("Could not refresh cert list: %1").arg(QString::fromStdString(strError)),
				QMessageBox::Ok, QMessageBox::Ok);
	}
	catch(std::exception& e)
	{
		QMessageBox::critical(this, windowTitle(),
			tr("There was an exception trying to refresh the cert list: ") + QString::fromStdString(e.what()),
				QMessageBox::Ok, QMessageBox::Ok);
	}
	return false;
}
<commit_msg>typo<commit_after>#include "manageescrowdialog.h"
#include "ui_manageescrowdialog.h"

#include "guiutil.h"
#include "syscoingui.h"
#include "ui_interface.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
#include "rpcserver.h"
using namespace std;

extern const CRPCTable tableRPC;
ManageEscrowDialog::ManageEscrowDialog(const QString &escrow, const QString &buyer, const QString &seller, const QString &arbiter, const QString &status, const QString &offertitle, const QString &total,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ManageEscrowDialog), escrow(escrow), buyer(buyer), seller(seller), arbiter(arbiter), status(status),offertitle(offertitle), total(total)
{
    ui->setupUi(this);
	EscrowType escrowType = findYourEscrowRoleFromAliases(buyer, seller, arbiter);
	ui->manageInfo->setText(tr("You are managing escrow ID: %1 of an offer for %2 totalling %3SYS. The buyer is %4, seller is %5 and arbiter is %6").arg(escrow).arg(offertitle).arg(total).arg(buyer).arg(seller).arg(arbiter));
	if(escrowType == None)
	{
		ui->manageInfo2->setText(tr("You cannot manage this escrow because you do not own one of either the buyer, seller or arbiter aliases."));
		ui->releaseButton->setEnabled(false);
		ui->refundButton->setEnabled(false);
	}
	else if(status == "in-escrow")
	{
		if(escrowType == Buyer)
		{
			ui->manageInfo2->setText(tr("You are the buyer of the offer held in escrow, you may release the coins to the seller once you have confirmed that you have recieved the item as per the description of the offer."));
			ui->refundButton->setEnabled(false);
		}
		else if(escrowType == Seller)
		{
			ui->manageInfo2->setText(tr("You are the seller of the offer held in escrow, you may refund the coins back to the buyer."));
			ui->releaseButton->setEnabled(false);
		}
		else if(escrowType == Arbiter)
		{
			ui->manageInfo2->setText(tr("You are the arbiter of the offer held in escrow, you may refund the coins back to the buyer if you have evidence that the seller did not honour the agreement to ship the offer item. You may also release the coins to the seller if the buyer has not released. You may use Syscoin messages to communicate with the buyer and seller to ensure you have adequeate proof for your decision."));
		}

	}
	else if(status == "escrow released")
	{
		if(escrowType == Buyer)
		{
			ui->manageInfo2->setText(tr("The escrow has already been released to the seller. You may communicate with your arbiter or seller via Syscoin messages."));
			ui->refundButton->setEnabled(false);
			ui->releaseButton->setEnabled(false);
		}
		else if(escrowType == Seller)
		{
			ui->manageInfo2->setText(tr("You are the seller of the offer held in escrow. The payment of coins have been released to you, you may claim them now."));
			ui->refundButton->setEnabled(false);
			ui->releaseButton->setText(tr("Claim Payment"));
		}
		else if(escrowType == Arbiter)
		{
			ui->manageInfo2->setText(tr("The escrow has already been released to the seller. You're job is done, if you were the one to release the coins you will recieve a commission as soon as the seller claims his payment."));
			ui->refundButton->setEnabled(false);
			ui->releaseButton->setEnabled(false);
		}
	}
	else if(status == "escrow refunded")
	{
		if(escrowType == Buyer)
		{
			ui->manageInfo2->setText(tr("You are the buyer of the offer held in escrow. The coins have been refunded back to you, you may claim them now."));
			ui->refundButton->setText(tr("Claim Refund"));
			ui->releaseButton->setEnabled(false);
		}
		else if(escrowType == Seller)
		{
			ui->manageInfo2->setText(tr("The escrow has already been refunded back to the buyer."));
			ui->refundButton->setEnabled(false);
			ui->releaseButton->setEnabled(false);
		}
		else if(escrowType == Arbiter)
		{
			ui->manageInfo2->setText(tr("The escrow has already been refunded back to the buyer. You're job is done, if you were the one to refund the coins you will recieve a commission as soon as the buyer claims his refund."));
			ui->refundButton->setEnabled(false);
			ui->releaseButton->setEnabled(false);
		}
	}
	else if(status == "complete")
	{
		ui->manageInfo2->setText(tr("The escrow has been successfully claimed by the seller. The escrow is complete."));
		ui->refundButton->setEnabled(false);
		ui->releaseButton->setEnabled(false);
	}
	else
	{
		ui->manageInfo2->setText(tr("The escrow status was not recognized. Please contact the Syscoin team."));
		ui->refundButton->setEnabled(false);
		ui->releaseButton->setEnabled(false);
	}
}
void ManageEscrowDialog::on_cancelButton_clicked()
{
    reject();
}
ManageEscrowDialog::~ManageEscrowDialog()
{
    delete ui;
}
void ManageEscrowDialog::on_releaseButton_clicked()
{
	UniValue params(UniValue::VARR);
	string strMethod = string("escrowrelease");
	params.push_back(escrow.toStdString());
	try {
		UniValue result = tableRPC.execute(strMethod, params);
		QMessageBox::information(this, windowTitle(),
		tr("Escrow released successfully!"),
			QMessageBox::Ok, QMessageBox::Ok);
		ManageEscrowDialog::accept();
	}
	catch (UniValue& objError)
	{
		string strError = find_value(objError, "message").get_str();
		QMessageBox::critical(this, windowTitle(),
        tr("Error releasing escrow: \"%1\"").arg(QString::fromStdString(strError)),
			QMessageBox::Ok, QMessageBox::Ok);
	}
	catch(std::exception& e)
	{
		QMessageBox::critical(this, windowTitle(),
            tr("General exception releasing escrow"),
			QMessageBox::Ok, QMessageBox::Ok);
	}
}
void ManageEscrowDialog::on_refundButton_clicked()
{
	UniValue params(UniValue::VARR);
	string strMethod = string("escrowrefund");
	params.push_back(escrow.toStdString());
	try {
		UniValue result = tableRPC.execute(strMethod, params);
		QMessageBox::information(this, windowTitle(),
		tr("Escrow refunded successfully!"),
			QMessageBox::Ok, QMessageBox::Ok);
		ManageEscrowDialog::accept();
	}
	catch (UniValue& objError)
	{
		string strError = find_value(objError, "message").get_str();
		QMessageBox::critical(this, windowTitle(),
        tr("Error refunding escrow: \"%1\"").arg(QString::fromStdString(strError)),
			QMessageBox::Ok, QMessageBox::Ok);
	}
	catch(std::exception& e)
	{
		QMessageBox::critical(this, windowTitle(),
            tr("General exception refunding escrow"),
			QMessageBox::Ok, QMessageBox::Ok);
	}
}
ManageEscrowDialog::EscrowType ManageEscrowDialog::findYourEscrowRoleFromAliases(const QString &buyer, const QString &seller, const QString &arbiter)
{
	if(isYourAlias(buyer))
		return Buyer;
	else if(isYourAlias(seller))
		return Seller;
	else if(isYourArbiter(arbiter))
		return Arbiter;
	else
		return None;

}
bool ManageEscrowDialog::isYourAlias(const QString &alias)
{
	string strMethod = string("aliasinfo");
    UniValue params(UniValue::VARR);
	UniValue result ;
	string name_str;
	int expired = 0;
	params.push_back(alias.toStdString());
	try {
		result = tableRPC.execute(strMethod, params);

		if (result.type() == UniValue::VOBJ)
		{
			const UniValue& o = result.get_obj();
			const UniValue& mine_value = find_value(o, "ismine");
			if (mine_value.type() == UniValue::VBOOL)
				return mine_value.get_bool();

		}
	}
	catch (UniValue& objError)
	{
		string strError = find_value(objError, "message").get_str();
		QMessageBox::critical(this, windowTitle(),
			tr("Could not refresh cert list: %1").arg(QString::fromStdString(strError)),
				QMessageBox::Ok, QMessageBox::Ok);
	}
	catch(std::exception& e)
	{
		QMessageBox::critical(this, windowTitle(),
			tr("There was an exception trying to refresh the cert list: ") + QString::fromStdString(e.what()),
				QMessageBox::Ok, QMessageBox::Ok);
	}
	return false;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: inputhdl.hxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:33:37 $
 *
 *  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 SC_INPUTHDL_HXX
#define SC_INPUTHDL_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

#ifndef _FRACT_HXX //autogen
#include <tools/fract.hxx>
#endif

#ifndef _GEN_HXX //autogen
#include <tools/gen.hxx>
#endif

class ScDocument;
class ScTabView;
class ScTabViewShell;
class ScInputWindow;
class ScPatternAttr;
class EditEngine;
class ScEditEngineDefaulter;
class EditView;
class EditTextObject;
class ScInputHdlState;
class TypedStrCollection;
class ScRangeFindList;
class Timer;
class KeyEvent;
class CommandEvent;

struct ESelection;

//========================================================================
//  ScInputHandler
//========================================================================

class ScInputHandler
{
private:
    ScInputWindow*          pInputWin;

    ScEditEngineDefaulter*  pEngine;                // editierte Daten in der Tabelle
    EditView*               pTableView;                 // aktive EditView dazu
    EditView*               pTopView;                   // EditView in der Eingabezeile

    TypedStrCollection*     pColumnData;
    TypedStrCollection*     pFormulaData;
    ULONG                   nTipVisible;
    String                  aManualTip;
    String                  aAutoSearch;
    USHORT                  nAutoPos;
    BOOL                    bUseTab;                    // Blaettern moeglich

    BOOL                    bTextValid;                 // Text noch nicht in Edit-Engine
    String                  aCurrentText;

    String                  aFormText;                  // fuer Funktions-Autopilot
    xub_StrLen              nFormSelStart;              // Selektion fuer Funktions-Autopilot
    xub_StrLen              nFormSelEnd;

    USHORT                  nAutoPar;                   // autom.parentheses than can be overwritten

    ScAddress               aCursorPos;
    ScInputMode             eMode;
    BOOL                    bModified;
    BOOL                    bSelIsRef;
    BOOL                    bFormulaMode;
    BOOL                    bInRangeUpdate;
    BOOL                    bParenthesisShown;
    BOOL                    bCreatingFuncView;
    BOOL                    bInEnterHandler;
    BOOL                    bCommandErrorShown;
    BOOL                    bInOwnChange;

    BOOL                    bProtected;
    BOOL                    bCellHasPercentFormat;
    ULONG                   nValidation;
    USHORT                  nAttrAdjust;                // enum SvxCellHorJustify

    Fraction                aScaleX;                    // fuer Ref-MapMode
    Fraction                aScaleY;

    ScTabViewShell*         pRefViewSh;
    ScTabViewShell*         pActiveViewSh;

    const ScPatternAttr*    pLastPattern;
    SfxItemSet*             pEditDefaults;
    BOOL                    bLastIsSymbol;

    ScInputHdlState*        pLastState;
    Timer*                  pDelayTimer;

    ScRangeFindList*        pRangeFindList;

    static BOOL             bAutoComplete;              // aus App-Optionen
    static BOOL             bOptLoaded;

#ifdef _INPUTHDL_CXX
private:
    void            UpdateActiveView();
    void            SetAllUpdateMode( BOOL bUpdate );
    void            SyncViews( EditView* pSourceView = NULL );
    BOOL            StartTable( sal_Unicode cTyped, BOOL bFromCommand );
    void            RemoveSelection();
    void            UpdateFormulaMode();
    void            InvalidateAttribs();
    void            ImplCreateEditEngine();
    DECL_LINK(      DelayTimer, Timer* );
    void            GetColData();
    void            UseColData();
    void            NextAutoEntry( BOOL bBack );
    void            UpdateAdjust( sal_Unicode cTyped );
    void            GetFormulaData();
    void            UseFormulaData();
    void            NextFormulaEntry( BOOL bBack );
    void            PasteFunctionData();
    void            PasteManualTip();
    EditView*       GetFuncEditView();
    void            RemoveAdjust();
    void            RemoveRangeFinder();
    void            DeleteRangeFinder();
    void            UpdateParenthesis();
    void            UpdateAutoCorrFlag();
    void            ResetAutoPar();
    void            AutoParAdded();
    BOOL            CursorAtClosingPar();
    void            SkipClosingPar();
    void            StopInputWinEngine( BOOL bAll );
    DECL_LINK( ModifyHdl, void* );
#endif

public:
                    ScInputHandler();
    virtual         ~ScInputHandler();

    void            SetMode( ScInputMode eNewMode );
    BOOL            IsInputMode() const { return (eMode != SC_INPUT_NONE); }
    BOOL            IsEditMode() const  { return (eMode != SC_INPUT_NONE &&
                                                  eMode != SC_INPUT_TYPE); }
    BOOL            IsTopMode() const   { return (eMode == SC_INPUT_TOP);  }

    const String&   GetEditString();
    const String&   GetFormString() const   { return aFormText; }

    BOOL            GetTextAndFields( ScEditEngineDefaulter& rDestEngine );

    BOOL            KeyInput( const KeyEvent& rKEvt, BOOL bStartEdit = FALSE );
    void            EnterHandler( BYTE nBlockMode = 0 );
    void            CancelHandler();
    void            SetReference( const ScRange& rRef, ScDocument* pDoc );
    void            AddRefEntry();

    BOOL            InputCommand( const CommandEvent& rCEvt, BOOL bForce );

    void            InsertFunction( const String& rFuncName, BOOL bAddPar = TRUE );
    void            ClearText();

    void            InputSelection( EditView* pView );
    void            InputChanged( EditView* pView, BOOL bFromNotify = FALSE );

    void            ViewShellGone(ScTabViewShell* pViewSh);
    void            SetRefViewShell(ScTabViewShell* pRefVsh) {pRefViewSh=pRefVsh;}

    void            NotifyChange( const ScInputHdlState* pState, BOOL bForce = FALSE,
                                    ScTabViewShell* pSourceSh = NULL,
                                    BOOL bStopEditing = TRUE);

    void            ResetDelayTimer(); //BugId 54702

    void            HideTip();
    void            ShowTip( const String& rText );     // am Cursor

    void            SetRefScale( const Fraction& rX, const Fraction& rY );
    void            UpdateRefDevice();

    EditView*       GetActiveView();
    EditView*       GetTableView()      { return pTableView; }
    EditView*       GetTopView()        { return pTopView; }

    BOOL            DataChanging( sal_Unicode cTyped = 0, BOOL bFromCommand = FALSE );
    void            DataChanged( BOOL bFromTopNotify = FALSE );

    BOOL            TakesReturn() const     { return ( nTipVisible != 0 ); }

    void            SetModified()       { bModified = TRUE; }

    BOOL            GetSelIsRef() const     { return bSelIsRef; }
    void            SetSelIsRef(BOOL bSet)  { bSelIsRef = bSet; }

    void            ShowRefFrame();

    ScRangeFindList* GetRangeFindList()     { return pRangeFindList; }

    void            UpdateRange( USHORT nIndex, const ScRange& rNew );

    // Kommunikation mit Funktionsautopilot
    void            InputGetSelection       ( xub_StrLen& rStart, xub_StrLen& rEnd );
    void            InputSetSelection       ( xub_StrLen nStart, xub_StrLen nEnd );
    void            InputReplaceSelection   ( const String& rStr );
    String          InputGetFormulaStr      ();

    BOOL            IsFormulaMode() const                   { return bFormulaMode; }
    ScInputWindow*  GetInputWindow()                        { return pInputWin; }
    void            SetInputWindow( ScInputWindow* pNew )   { pInputWin = pNew; }

    BOOL            IsInEnterHandler() const                { return bInEnterHandler; }
    BOOL            IsInOwnChange() const                   { return bInOwnChange; }

    BOOL            IsModalMode( SfxObjectShell* pDocSh );

    void            ActivateInputWindow( const String&     rText,
                                         const ESelection& rSel );

    void            ForgetLastPattern();

    void            UpdateSpellSettings( BOOL bFromStartTab = FALSE );

    void            FormulaPreview();

    Size            GetTextSize();      // in 1/100mm

                    // eigentlich private, fuer SID_INPUT_SUM public
    void            InitRangeFinder( const String& rFormula );

    static void     SetAutoComplete(BOOL bSet)  { bAutoComplete = bSet; }
};

//========================================================================
//  ScInputHdlState
//========================================================================
class ScInputHdlState
{
    friend class ScInputHandler;

public:
        ScInputHdlState( const ScAddress& rCurPos,
                         const ScAddress& rStartPos,
                         const ScAddress& rEndPos,
                         const String& rString,
                         const EditTextObject* pData );
        ScInputHdlState( const ScInputHdlState& rCpy );
        ~ScInputHdlState();

    ScInputHdlState&    operator= ( const ScInputHdlState& r );
    int                 operator==( const ScInputHdlState& r ) const;
    int                 operator!=( const ScInputHdlState& r ) const
                            { return !operator==( r ); }

    const ScAddress&        GetPos() const          { return aCursorPos; }
    const ScAddress&        GetStartPos() const     { return aStartPos; }
    const ScAddress&        GetEndPos() const       { return aEndPos; }
    const String&           GetString() const       { return aString; }
    const EditTextObject*   GetEditData() const     { return pEditData; }

private:
    ScAddress       aCursorPos;
    ScAddress       aStartPos;
    ScAddress       aEndPos;
    String          aString;
    EditTextObject* pEditData;
};

#endif

<commit_msg>INTEGRATION: CWS dr43 (1.13.42); FILE MERGED 2005/11/23 13:09:27 nn 1.13.42.1: #125841# StopInputWinEngine public<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: inputhdl.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: rt $ $Date: 2006-01-13 17:04:03 $
 *
 *  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 SC_INPUTHDL_HXX
#define SC_INPUTHDL_HXX

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

#ifndef _FRACT_HXX //autogen
#include <tools/fract.hxx>
#endif

#ifndef _GEN_HXX //autogen
#include <tools/gen.hxx>
#endif

class ScDocument;
class ScTabView;
class ScTabViewShell;
class ScInputWindow;
class ScPatternAttr;
class EditEngine;
class ScEditEngineDefaulter;
class EditView;
class EditTextObject;
class ScInputHdlState;
class TypedStrCollection;
class ScRangeFindList;
class Timer;
class KeyEvent;
class CommandEvent;

struct ESelection;

//========================================================================
//  ScInputHandler
//========================================================================

class ScInputHandler
{
private:
    ScInputWindow*          pInputWin;

    ScEditEngineDefaulter*  pEngine;                // editierte Daten in der Tabelle
    EditView*               pTableView;                 // aktive EditView dazu
    EditView*               pTopView;                   // EditView in der Eingabezeile

    TypedStrCollection*     pColumnData;
    TypedStrCollection*     pFormulaData;
    ULONG                   nTipVisible;
    String                  aManualTip;
    String                  aAutoSearch;
    USHORT                  nAutoPos;
    BOOL                    bUseTab;                    // Blaettern moeglich

    BOOL                    bTextValid;                 // Text noch nicht in Edit-Engine
    String                  aCurrentText;

    String                  aFormText;                  // fuer Funktions-Autopilot
    xub_StrLen              nFormSelStart;              // Selektion fuer Funktions-Autopilot
    xub_StrLen              nFormSelEnd;

    USHORT                  nAutoPar;                   // autom.parentheses than can be overwritten

    ScAddress               aCursorPos;
    ScInputMode             eMode;
    BOOL                    bModified;
    BOOL                    bSelIsRef;
    BOOL                    bFormulaMode;
    BOOL                    bInRangeUpdate;
    BOOL                    bParenthesisShown;
    BOOL                    bCreatingFuncView;
    BOOL                    bInEnterHandler;
    BOOL                    bCommandErrorShown;
    BOOL                    bInOwnChange;

    BOOL                    bProtected;
    BOOL                    bCellHasPercentFormat;
    ULONG                   nValidation;
    USHORT                  nAttrAdjust;                // enum SvxCellHorJustify

    Fraction                aScaleX;                    // fuer Ref-MapMode
    Fraction                aScaleY;

    ScTabViewShell*         pRefViewSh;
    ScTabViewShell*         pActiveViewSh;

    const ScPatternAttr*    pLastPattern;
    SfxItemSet*             pEditDefaults;
    BOOL                    bLastIsSymbol;

    ScInputHdlState*        pLastState;
    Timer*                  pDelayTimer;

    ScRangeFindList*        pRangeFindList;

    static BOOL             bAutoComplete;              // aus App-Optionen
    static BOOL             bOptLoaded;

#ifdef _INPUTHDL_CXX
private:
    void            UpdateActiveView();
    void            SetAllUpdateMode( BOOL bUpdate );
    void            SyncViews( EditView* pSourceView = NULL );
    BOOL            StartTable( sal_Unicode cTyped, BOOL bFromCommand );
    void            RemoveSelection();
    void            UpdateFormulaMode();
    void            InvalidateAttribs();
    void            ImplCreateEditEngine();
    DECL_LINK(      DelayTimer, Timer* );
    void            GetColData();
    void            UseColData();
    void            NextAutoEntry( BOOL bBack );
    void            UpdateAdjust( sal_Unicode cTyped );
    void            GetFormulaData();
    void            UseFormulaData();
    void            NextFormulaEntry( BOOL bBack );
    void            PasteFunctionData();
    void            PasteManualTip();
    EditView*       GetFuncEditView();
    void            RemoveAdjust();
    void            RemoveRangeFinder();
    void            DeleteRangeFinder();
    void            UpdateParenthesis();
    void            UpdateAutoCorrFlag();
    void            ResetAutoPar();
    void            AutoParAdded();
    BOOL            CursorAtClosingPar();
    void            SkipClosingPar();
    DECL_LINK( ModifyHdl, void* );
#endif

public:
                    ScInputHandler();
    virtual         ~ScInputHandler();

    void            SetMode( ScInputMode eNewMode );
    BOOL            IsInputMode() const { return (eMode != SC_INPUT_NONE); }
    BOOL            IsEditMode() const  { return (eMode != SC_INPUT_NONE &&
                                                  eMode != SC_INPUT_TYPE); }
    BOOL            IsTopMode() const   { return (eMode == SC_INPUT_TOP);  }

    const String&   GetEditString();
    const String&   GetFormString() const   { return aFormText; }

    BOOL            GetTextAndFields( ScEditEngineDefaulter& rDestEngine );

    BOOL            KeyInput( const KeyEvent& rKEvt, BOOL bStartEdit = FALSE );
    void            EnterHandler( BYTE nBlockMode = 0 );
    void            CancelHandler();
    void            SetReference( const ScRange& rRef, ScDocument* pDoc );
    void            AddRefEntry();

    BOOL            InputCommand( const CommandEvent& rCEvt, BOOL bForce );

    void            InsertFunction( const String& rFuncName, BOOL bAddPar = TRUE );
    void            ClearText();

    void            InputSelection( EditView* pView );
    void            InputChanged( EditView* pView, BOOL bFromNotify = FALSE );

    void            ViewShellGone(ScTabViewShell* pViewSh);
    void            SetRefViewShell(ScTabViewShell* pRefVsh) {pRefViewSh=pRefVsh;}

    void            NotifyChange( const ScInputHdlState* pState, BOOL bForce = FALSE,
                                    ScTabViewShell* pSourceSh = NULL,
                                    BOOL bStopEditing = TRUE);

    void            ResetDelayTimer(); //BugId 54702

    void            HideTip();
    void            ShowTip( const String& rText );     // am Cursor

    void            SetRefScale( const Fraction& rX, const Fraction& rY );
    void            UpdateRefDevice();

    EditView*       GetActiveView();
    EditView*       GetTableView()      { return pTableView; }
    EditView*       GetTopView()        { return pTopView; }

    BOOL            DataChanging( sal_Unicode cTyped = 0, BOOL bFromCommand = FALSE );
    void            DataChanged( BOOL bFromTopNotify = FALSE );

    BOOL            TakesReturn() const     { return ( nTipVisible != 0 ); }

    void            SetModified()       { bModified = TRUE; }

    BOOL            GetSelIsRef() const     { return bSelIsRef; }
    void            SetSelIsRef(BOOL bSet)  { bSelIsRef = bSet; }

    void            ShowRefFrame();

    ScRangeFindList* GetRangeFindList()     { return pRangeFindList; }

    void            UpdateRange( USHORT nIndex, const ScRange& rNew );

    // Kommunikation mit Funktionsautopilot
    void            InputGetSelection       ( xub_StrLen& rStart, xub_StrLen& rEnd );
    void            InputSetSelection       ( xub_StrLen nStart, xub_StrLen nEnd );
    void            InputReplaceSelection   ( const String& rStr );
    String          InputGetFormulaStr      ();

    BOOL            IsFormulaMode() const                   { return bFormulaMode; }
    ScInputWindow*  GetInputWindow()                        { return pInputWin; }
    void            SetInputWindow( ScInputWindow* pNew )   { pInputWin = pNew; }
    void            StopInputWinEngine( BOOL bAll );

    BOOL            IsInEnterHandler() const                { return bInEnterHandler; }
    BOOL            IsInOwnChange() const                   { return bInOwnChange; }

    BOOL            IsModalMode( SfxObjectShell* pDocSh );

    void            ActivateInputWindow( const String&     rText,
                                         const ESelection& rSel );

    void            ForgetLastPattern();

    void            UpdateSpellSettings( BOOL bFromStartTab = FALSE );

    void            FormulaPreview();

    Size            GetTextSize();      // in 1/100mm

                    // eigentlich private, fuer SID_INPUT_SUM public
    void            InitRangeFinder( const String& rFormula );

    static void     SetAutoComplete(BOOL bSet)  { bAutoComplete = bSet; }
};

//========================================================================
//  ScInputHdlState
//========================================================================
class ScInputHdlState
{
    friend class ScInputHandler;

public:
        ScInputHdlState( const ScAddress& rCurPos,
                         const ScAddress& rStartPos,
                         const ScAddress& rEndPos,
                         const String& rString,
                         const EditTextObject* pData );
        ScInputHdlState( const ScInputHdlState& rCpy );
        ~ScInputHdlState();

    ScInputHdlState&    operator= ( const ScInputHdlState& r );
    int                 operator==( const ScInputHdlState& r ) const;
    int                 operator!=( const ScInputHdlState& r ) const
                            { return !operator==( r ); }

    const ScAddress&        GetPos() const          { return aCursorPos; }
    const ScAddress&        GetStartPos() const     { return aStartPos; }
    const ScAddress&        GetEndPos() const       { return aEndPos; }
    const String&           GetString() const       { return aString; }
    const EditTextObject*   GetEditData() const     { return pEditData; }

private:
    ScAddress       aCursorPos;
    ScAddress       aStartPos;
    ScAddress       aEndPos;
    String          aString;
    EditTextObject* pEditData;
};

#endif

<|endoftext|>


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

#ifndef SC_NAVCITEM_HXX
#define SC_NAVCITEM_HXX

#ifndef _SFXCTRLITEM_HXX //autogen
#include <sfx2/ctrlitem.hxx>
#endif

//==================================================================

class ScNavigatorDlg;

class ScNavigatorControllerItem : public SfxControllerItem
{
public:
    ScNavigatorControllerItem( USHORT nId,
                               ScNavigatorDlg& rDlg,
                               SfxBindings& rBindings );
protected:
    virtual void    StateChanged( USHORT nSID, SfxItemState eState,
                                      const SfxPoolItem* pItem );

private:
    ScNavigatorDlg& rNavigatorDlg;
};

#endif // SC_NAVCITEM_HXX

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

#ifndef SC_NAVCITEM_HXX
#define SC_NAVCITEM_HXX

#ifndef _SFXCTRLITEM_HXX //autogen
#include <sfx2/ctrlitem.hxx>
#endif

//==================================================================

class ScNavigatorDlg;

class ScNavigatorControllerItem : public SfxControllerItem
{
public:
    ScNavigatorControllerItem( USHORT nId,
                               ScNavigatorDlg& rDlg,
                               SfxBindings& rBindings );
protected:
    virtual void    StateChanged( USHORT nSID, SfxItemState eState,
                                      const SfxPoolItem* pItem );

private:
    ScNavigatorDlg& rNavigatorDlg;
};

#endif // SC_NAVCITEM_HXX

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: irendermodule.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-13 14:37:00 $
 *
 *  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 INCLUDED_CANVAS_IRENDERMODULE_HXX
#define INCLUDED_CANVAS_IRENDERMODULE_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#include <boost/shared_ptr.hpp>
#include <boost/utility.hpp>

namespace basegfx
{
    class B2DRange;
    class B2IRange;
    class B2IVector;
    class B2IPoint;
}

namespace canvas
{
    struct ISurface;

    struct Vertex
    {
        float r,g,b,a;
        float u,v;
        float x,y,z;
    };

    /** Output module interface for backend render implementations.

        Implement this interface for each operating system- or
        library-specific rendering backend, which needs coupling with
        the canvas rendering framework (which can be shared between
        all backend implementations).
     */
    struct IRenderModule
    {
        /** Type of primitive passed to the render module via
            pushVertex()
         */
        enum PrimitiveType
        {
            PRIMITIVE_TYPE_UNKNOWN,
            PRIMITIVE_TYPE_TRIANGLE,
            PRIMITIVE_TYPE_QUAD
        };

        virtual ~IRenderModule() {}

        /// Lock rendermodule against concurrent access
        virtual void lock() const = 0;

        /// Unlock rendermodule for concurrent access
        virtual void unlock() const = 0;

        /** Maximal size of VRAM pages available

            This is typically the maximum texture size of the
            hardware, or some arbitrary limit if the backend is
            software.
         */
        virtual ::basegfx::B2IVector getPageSize() = 0;

        /** Create a (possibly hardware-accelerated) surface

            @return a pointer to a surface, which is an abstraction of
            a piece of (possibly hardware-accelerated) texture memory.
         */
        virtual ::boost::shared_ptr<ISurface> createSurface( const ::basegfx::B2IVector& surfaceSize ) = 0;

        /** Begin rendering the given primitive.

            Each beginPrimitive() call must be matched with an
            endPrimitive() call.
         */
        virtual void      beginPrimitive( PrimitiveType eType ) = 0;

        /** Finish rendering a primitive.

            Each beginPrimitive() call must be matched with an
            endPrimitive() call.
         */
        virtual void      endPrimitive() = 0;

        /** Add given vertex to current primitive

            After issuing a beginPrimitive(), each pushVertex() adds a
            vertex to the active primitive.
         */
        virtual void      pushVertex( const Vertex& vertex ) = 0;

        /** Query error status

            @returns true, if an error occured during primitive
            construction.
         */
        virtual bool      isError() = 0;
    };

    typedef ::boost::shared_ptr< IRenderModule > IRenderModuleSharedPtr;

    /// Little RAII wrapper for guarding access to IRenderModule interface
    class RenderModuleGuard : private ::boost::noncopyable
    {
    public:
        explicit RenderModuleGuard( const IRenderModuleSharedPtr& rRenderModule ) :
            mpRenderModule( rRenderModule )
        {
            mpRenderModule->lock();
        }

        ~RenderModuleGuard()
        {
            mpRenderModule->unlock();
        }

    private:
        const IRenderModuleSharedPtr mpRenderModule;
    };
}

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

#ifndef INCLUDED_CANVAS_IRENDERMODULE_HXX
#define INCLUDED_CANVAS_IRENDERMODULE_HXX

#include <sal/types.h>

#include <boost/shared_ptr.hpp>
#include <boost/utility.hpp>

namespace basegfx
{
    class B2DRange;
    class B2IRange;
    class B2IVector;
    class B2IPoint;
}

namespace canvas
{
    struct ISurface;

    struct Vertex
    {
        float r,g,b,a;
        float u,v;
        float x,y,z;
    };

    /** Output module interface for backend render implementations.

        Implement this interface for each operating system- or
        library-specific rendering backend, which needs coupling with
        the canvas rendering framework (which can be shared between
        all backend implementations).
     */
    struct IRenderModule
    {
        /** Type of primitive passed to the render module via
            pushVertex()
         */
        enum PrimitiveType
        {
            PRIMITIVE_TYPE_UNKNOWN,
            PRIMITIVE_TYPE_TRIANGLE,
            PRIMITIVE_TYPE_QUAD
        };

        virtual ~IRenderModule() {}

        /// Lock rendermodule against concurrent access
        virtual void lock() const = 0;

        /// Unlock rendermodule for concurrent access
        virtual void unlock() const = 0;

        /** Maximal size of VRAM pages available

            This is typically the maximum texture size of the
            hardware, or some arbitrary limit if the backend is
            software.
         */
        virtual ::basegfx::B2IVector getPageSize() = 0;

        /** Create a (possibly hardware-accelerated) surface

            @return a pointer to a surface, which is an abstraction of
            a piece of (possibly hardware-accelerated) texture memory.
         */
        virtual ::boost::shared_ptr<ISurface> createSurface( const ::basegfx::B2IVector& surfaceSize ) = 0;

        /** Begin rendering the given primitive.

            Each beginPrimitive() call must be matched with an
            endPrimitive() call.
         */
        virtual void      beginPrimitive( PrimitiveType eType ) = 0;

        /** Finish rendering a primitive.

            Each beginPrimitive() call must be matched with an
            endPrimitive() call.
         */
        virtual void      endPrimitive() = 0;

        /** Add given vertex to current primitive

            After issuing a beginPrimitive(), each pushVertex() adds a
            vertex to the active primitive.
         */
        virtual void      pushVertex( const Vertex& vertex ) = 0;

        /** Query error status

            @returns true, if an error occured during primitive
            construction.
         */
        virtual bool      isError() = 0;
    };

    typedef ::boost::shared_ptr< IRenderModule > IRenderModuleSharedPtr;

    /// Little RAII wrapper for guarding access to IRenderModule interface
    class RenderModuleGuard : private ::boost::noncopyable
    {
    public:
        explicit RenderModuleGuard( const IRenderModuleSharedPtr& rRenderModule ) :
            mpRenderModule( rRenderModule )
        {
            mpRenderModule->lock();
        }

        ~RenderModuleGuard()
        {
            mpRenderModule->unlock();
        }

    private:
        const IRenderModuleSharedPtr mpRenderModule;
    };
}

#endif /* INCLUDED_CANVAS_IRENDERMODULE_HXX */
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <ctime>
#include <cstdio>
#include <boost/filesystem.hpp>

#include "gflags/gflags.h"
#include "jsoncons/json.hpp"
#include "utils/protocol.h"
#include "utils/connection.h"
#include "bots/bot_interface.h"
#include "bots/raw_bot.h"
#include "bots/basic/bot.h"
#include "bots/tomek/bot.h"
#include "bots/piotr/bot.h"
#include "bots/greedy/bot.h"
#include "bots/stepping/bot.h"
#include "bots/constant/bot.h"
#include "bots/kamikaze/bot.h"
#include "game/simulator.h"

DECLARE_string(race_id);
DECLARE_string(throttle_scheduler);
DECLARE_string(switch_scheduler);
DEFINE_string(track, "keimola", "The track to run simulator on.");
DEFINE_int32(physics, 0, "The physics to use");

std::string random_race_id() {
  char buffer[80];
  sprintf (buffer, "%d", rand());
  return std::string(buffer);
}

int main(int argc, char** argv) {
  std::vector<std::pair<std::vector<double>, std::vector<double> > > physics;
  physics = {
    {{0.98, 0.2     }, {1.9, -0.9, -0.00125, 0.00125 * sqrt(180000), 0.3}},
    {{0.98, 0.168896}, {1.9, -0.9, -0.00118604, 0.483757, 0.284649}},
    {{0.98, 0.233986}, {1.9, -0.9, -0.00120513, 0.497467, 0.289232}},
    {{0.98, 0.214027}, {1.9, -0.9, -0.00127153, 0.546417, 0.305167}},
    {{0.98, 0.17629 }, {1.9, -0.9, -0.00130643, 0.572936, 0.313544}},
    {{0.98, 0.198433}, {1.9, -0.9, -0.00129546, 0.56454 , 0.31091 }},
    {{0.98, 0.210197}, {1.9, -0.9, -0.00121806, 0.506844, 0.292334}},
  };

  // FLAGS_throttle_scheduler = "BinaryThrottleScheduler";
  // FLAGS_switch_scheduler = "NeverSwitchScheduler";

  gflags::ParseCommandLineFlags(&argc, &argv, true);
  srand (time(NULL));

  if (FLAGS_race_id.empty()) {
    FLAGS_race_id = random_race_id();
  }
  boost::filesystem::create_directories("bin/" + FLAGS_race_id);

  game::Simulator::Result result;
  {
    std::unique_ptr<bots::RawBot> bot(new bots::RawBot(new bots::stepping::Bot()));
    std::unique_ptr<game::Simulator> simulator(new game::Simulator());

    game::Simulator::Options options;
    options.physics_params = game::PhysicsParams::Load();
    options.physics_params.velocity_model_params.model = physics[FLAGS_physics].first;
    options.physics_params.drift_model_params.model = physics[FLAGS_physics].second;

    options.track_name = FLAGS_track;
    result = simulator->Run(bot.get(), options);
  }

  std::cout << "BEST LAP: " << result.best_lap_time_in_ticks << std::endl;
  std::cout << "TOTAL TICKS: " << result.total_ticks << std::endl;
  std::cout << "TOTAL DISTANCE: " << result.total_distance << std::endl;
  std::cout << "MAX TICK TIME: " << result.max_tick_time_ms << " ms" << std::endl;
  std::cout << "AVG TICK TIME: " << result.avg_tick_time_ms << " ms" << std::endl;
  if (result.crashed) {
    std::cout << "CRASHED !!!!!!!!!!!!!" << std::endl;
  }

  return 0;
}
<commit_msg>Add 100 physics<commit_after>#include <iostream>
#include <string>
#include <ctime>
#include <cstdio>
#include <boost/filesystem.hpp>

#include "gflags/gflags.h"
#include "jsoncons/json.hpp"
#include "utils/protocol.h"
#include "utils/connection.h"
#include "bots/bot_interface.h"
#include "bots/raw_bot.h"
#include "bots/basic/bot.h"
#include "bots/tomek/bot.h"
#include "bots/piotr/bot.h"
#include "bots/greedy/bot.h"
#include "bots/stepping/bot.h"
#include "bots/constant/bot.h"
#include "bots/kamikaze/bot.h"
#include "game/simulator.h"

DECLARE_string(race_id);
DECLARE_string(throttle_scheduler);
DECLARE_string(switch_scheduler);
DEFINE_string(track, "keimola", "The track to run simulator on.");
DEFINE_int32(physics, 0, "The physics to use");

std::string random_race_id() {
  char buffer[80];
  sprintf (buffer, "%d", rand());
  return std::string(buffer);
}

namespace {

double range(double a, double b) {
  double r = double(rand() % 1000000) / 1000000.0;
  return a + r * (b-a);
}

}  // anonymous namespace

int main(int argc, char** argv) {
  std::vector<std::pair<std::vector<double>, std::vector<double> > > physics;
  physics = {
    {{0.98, 0.2     }, {1.9, -0.9, -0.00125, 0.00125 * sqrt(180000), 0.3}},
    {{0.98, 0.168896}, {1.9, -0.9, -0.00118604, 0.483757, 0.284649}},
    {{0.98, 0.233986}, {1.9, -0.9, -0.00120513, 0.497467, 0.289232}},
    {{0.98, 0.214027}, {1.9, -0.9, -0.00127153, 0.546417, 0.305167}},
    {{0.98, 0.17629 }, {1.9, -0.9, -0.00130643, 0.572936, 0.313544}},
    {{0.98, 0.198433}, {1.9, -0.9, -0.00129546, 0.56454 , 0.31091 }},
    {{0.98, 0.210197}, {1.9, -0.9, -0.00121806, 0.506844, 0.292334}},
  };

  srand(123456789);
  while (physics.size() < 100) {
    //                  speed_decay       acceleration       angle_decay angle_change_speed     target_angle_fac target_angle_treshold
    physics.push_back({{range(0.9, 0.99), range(0.1, 0.5)}, {1.9, -0.9, range(-0.001, -0.002), range(0.3, 0.7), range(0.25, 0.35)}});

    /*printf("{%lf %lf}{%lf %lf %lf %lf}\n",
        physics.back().first[0],
        physics.back().first[1],
        physics.back().second[0],
        physics.back().second[1],
        physics.back().second[2],
        physics.back().second[3]
        );*/
  }

  // FLAGS_throttle_scheduler = "BinaryThrottleScheduler";
  // FLAGS_switch_scheduler = "NeverSwitchScheduler";

  gflags::ParseCommandLineFlags(&argc, &argv, true);
  srand (time(NULL));

  if (FLAGS_race_id.empty()) {
    FLAGS_race_id = random_race_id();
  }
  boost::filesystem::create_directories("bin/" + FLAGS_race_id);

  game::Simulator::Result result;
  {
    std::unique_ptr<bots::RawBot> bot(new bots::RawBot(new bots::stepping::Bot()));
    std::unique_ptr<game::Simulator> simulator(new game::Simulator());

    game::Simulator::Options options;
    options.physics_params = game::PhysicsParams::Load();
    options.physics_params.velocity_model_params.model = physics[FLAGS_physics].first;
    options.physics_params.drift_model_params.model = physics[FLAGS_physics].second;

    options.track_name = FLAGS_track;
    result = simulator->Run(bot.get(), options);
  }

  std::cout << "BEST LAP: " << result.best_lap_time_in_ticks << std::endl;
  std::cout << "TOTAL TICKS: " << result.total_ticks << std::endl;
  std::cout << "TOTAL DISTANCE: " << result.total_distance << std::endl;
  std::cout << "MAX TICK TIME: " << result.max_tick_time_ms << " ms" << std::endl;
  std::cout << "AVG TICK TIME: " << result.avg_tick_time_ms << " ms" << std::endl;
  if (result.crashed) {
    std::cout << "CRASHED !!!!!!!!!!!!!" << std::endl;
  }

  return 0;
}
<|endoftext|>


<commit_before>#include "xchainer/op_node.h"

#include <algorithm>
#include <cassert>
#include <functional>
#include <memory>
#include <tuple>
#include <utility>
#include <vector>

#include "xchainer/array_node.h"
#include "xchainer/backward.h"
#include "xchainer/graph.h"

namespace xchainer {
namespace internal {

OpNodeBackwardEntry::OpNodeBackwardEntry(
        OpNode& op_node, std::vector<nonstd::optional<size_t>> next_array_node_indices, BackwardFunction backward_func)
    : op_node_{op_node}, next_array_node_indices_{std::move(next_array_node_indices)}, backward_func_{std::move(backward_func)} {}

std::vector<std::shared_ptr<ArrayNode>> OpNodeBackwardEntry::GetNextArrayNodes() const {
    std::vector<std::shared_ptr<ArrayNode>> array_nodes;
    array_nodes.reserve(next_array_node_indices_.size());
    for (nonstd::optional<size_t> index : next_array_node_indices_) {
        if (index.has_value()) {
            array_nodes.emplace_back(gsl::at(op_node_.next_array_nodes(), *index));
        } else {
            array_nodes.emplace_back(nullptr);
        }
    }
    return array_nodes;
}

void OpNodeBackwardEntry::AddExoticNextArrayNode(std::tuple<GraphId, std::vector<std::shared_ptr<ArrayNode>>> next_array_nodes) {
    assert(std::get<0>(next_array_nodes) != op_node_.graph_id());
    exotic_next_array_nodes_.emplace_back(std::move(next_array_nodes));
}

}  // namespace internal

OpNode::OpNode(
        std::string name,
        GraphId graph_id,
        std::vector<std::weak_ptr<ArrayNode>> prev_array_nodes,
        std::vector<internal::ArrayProps> prev_array_props)
    : name_{std::move(name)},
      graph_id_{graph_id},
      prev_array_nodes_{std::move(prev_array_nodes)},
      prev_array_props_{std::move(prev_array_props)} {
    assert(prev_array_props_.size() == prev_array_nodes_.size());
    AssertConsistency();
}

void OpNode::AssertConsistency() const {
#ifndef NDEBUG
    // No pair of entries may have the same graph ID.
    assert(std::all_of(outer_graphs_prev_array_nodes_.begin(), outer_graphs_prev_array_nodes_.end(), [this](const auto& tup1) {
        return std::all_of(outer_graphs_prev_array_nodes_.begin(), outer_graphs_prev_array_nodes_.end(), [&tup1](const auto& tup2) {
            return &tup1 == &tup2 || std::get<0>(tup1) != std::get<0>(tup2);
        });
    }));

    // Corresponding previous array nodes across graphs (corresponding to the same output array) should have the same array body, if it's
    // alive.
    for (size_t i_prev = 0; i_prev < prev_node_count(); ++i_prev) {
        nonstd::optional<internal::ArrayBody*> prev_array_body{};
        for (const auto& tup : outer_graphs_prev_array_nodes_) {
            const std::vector<std::shared_ptr<ArrayNode>>& vec = std::get<1>(tup);
            const std::shared_ptr<ArrayNode>& prev_array_node = vec[i_prev];
            std::shared_ptr<internal::ArrayBody> body = prev_array_node->GetBody();
            if (!prev_array_body.has_value()) {
                prev_array_body = body.get();
            } else {
                assert(*prev_array_body == body.get());
            }
        }
    }
#endif  // NDEBUG
}

std::vector<std::shared_ptr<ArrayNode>>& OpNode::next_array_nodes() {
    assert(std::all_of(next_array_nodes_.begin(), next_array_nodes_.end(), [this](const std::shared_ptr<ArrayNode>& arr_node) {
        return arr_node != nullptr;
    }));
    assert(std::all_of(next_array_nodes_.begin(), next_array_nodes_.end(), [this](const std::shared_ptr<ArrayNode>& arr_node) {
        return arr_node->graph_id() == graph_id_;
    }));
    return next_array_nodes_;
}

const std::vector<std::shared_ptr<ArrayNode>>& OpNode::next_array_nodes() const {
    assert(std::all_of(next_array_nodes_.begin(), next_array_nodes_.end(), [this](const std::shared_ptr<ArrayNode>& arr_node) {
        return arr_node != nullptr;
    }));
    assert(std::all_of(next_array_nodes_.begin(), next_array_nodes_.end(), [this](const std::shared_ptr<ArrayNode>& arr_node) {
        return arr_node->graph_id() == graph_id_;
    }));
    return next_array_nodes_;
}

internal::OpNodeBackwardEntry& OpNode::RegisterBackwardFunction(
        std::vector<std::shared_ptr<ArrayNode>> next_array_nodes, BackwardFunction backward_func) {
    AssertConsistency();
    assert(!next_array_nodes.empty());
    assert(std::all_of(next_array_nodes.begin(), next_array_nodes.end(), [this](const std::shared_ptr<ArrayNode>& next_array_node) {
        // next_array_node could be nullptr, if the corresponding input array does not require grad.
        return next_array_node == nullptr || next_array_node->graph_id() == graph_id_;
    }));

    // Update the rank of op node
    for (const std::shared_ptr<ArrayNode>& next_array_node : next_array_nodes) {
        if (next_array_node != nullptr) {
            rank_ = std::max(rank_, next_array_node->rank() + 1);
        }
    }

    // Store next nodes and record indices of them
    std::vector<nonstd::optional<size_t>> next_array_node_indices;
    next_array_node_indices.reserve(next_array_nodes.size());
    for (std::shared_ptr<ArrayNode>& next_array_node : next_array_nodes) {
        if (next_array_node != nullptr) {
            next_array_node_indices.emplace_back(next_array_nodes_.size());
            next_array_nodes_.emplace_back(std::move(next_array_node));
        } else {
            next_array_node_indices.emplace_back(nonstd::nullopt);
        }
    }

    // Add backward entry
    backward_entries_.emplace_back(*this, std::move(next_array_node_indices), std::move(backward_func));

    AssertConsistency();
    return backward_entries_.back();
}

void OpNode::RegisterOuterGraphsPreviousArrayNodes(
        const GraphId& other_graph_id, std::vector<std::shared_ptr<ArrayNode>> outer_graphs_prev_array_nodes) {
    AssertConsistency();
    assert(other_graph_id != graph_id_);
    assert(outer_graphs_prev_array_nodes.size() == prev_array_props_.size());

    outer_graphs_prev_array_nodes_.emplace_back(other_graph_id, std::move(outer_graphs_prev_array_nodes));

    AssertConsistency();
}

namespace internal {

std::shared_ptr<ArrayNode> CreatePrevArrayNode(std::shared_ptr<OpNode> op_node, size_t prev_array_node_index) {
    assert(prev_array_node_index < op_node->prev_node_count());
    assert(op_node->prev_array_nodes()[prev_array_node_index].expired());

    const internal::ArrayProps& props = op_node->GetPrevArrayProps(prev_array_node_index);
    auto prev_array_node = std::make_shared<ArrayNode>(props.shape, props.dtype, props.device, op_node->graph_id());
    prev_array_node->set_next_op_node(std::move(op_node));
    op_node->prev_array_nodes()[prev_array_node_index] = prev_array_node;

    return prev_array_node;
}

}  // namespace internal
}  // namespace xchainer
<commit_msg>Fix for segfault<commit_after>#include "xchainer/op_node.h"

#include <algorithm>
#include <cassert>
#include <functional>
#include <memory>
#include <tuple>
#include <utility>
#include <vector>

#include "xchainer/array_node.h"
#include "xchainer/backward.h"
#include "xchainer/graph.h"

namespace xchainer {
namespace internal {

OpNodeBackwardEntry::OpNodeBackwardEntry(
        OpNode& op_node, std::vector<nonstd::optional<size_t>> next_array_node_indices, BackwardFunction backward_func)
    : op_node_{op_node}, next_array_node_indices_{std::move(next_array_node_indices)}, backward_func_{std::move(backward_func)} {}

std::vector<std::shared_ptr<ArrayNode>> OpNodeBackwardEntry::GetNextArrayNodes() const {
    std::vector<std::shared_ptr<ArrayNode>> array_nodes;
    array_nodes.reserve(next_array_node_indices_.size());
    for (nonstd::optional<size_t> index : next_array_node_indices_) {
        if (index.has_value()) {
            array_nodes.emplace_back(gsl::at(op_node_.next_array_nodes(), *index));
        } else {
            array_nodes.emplace_back(nullptr);
        }
    }
    return array_nodes;
}

void OpNodeBackwardEntry::AddExoticNextArrayNode(std::tuple<GraphId, std::vector<std::shared_ptr<ArrayNode>>> next_array_nodes) {
    assert(std::get<0>(next_array_nodes) != op_node_.graph_id());
    exotic_next_array_nodes_.emplace_back(std::move(next_array_nodes));
}

}  // namespace internal

OpNode::OpNode(
        std::string name,
        GraphId graph_id,
        std::vector<std::weak_ptr<ArrayNode>> prev_array_nodes,
        std::vector<internal::ArrayProps> prev_array_props)
    : name_{std::move(name)},
      graph_id_{graph_id},
      prev_array_nodes_{std::move(prev_array_nodes)},
      prev_array_props_{std::move(prev_array_props)} {
    assert(prev_array_props_.size() == prev_array_nodes_.size());
    AssertConsistency();
}

void OpNode::AssertConsistency() const {
#ifndef NDEBUG
    // No pair of entries may have the same graph ID.
    assert(std::all_of(outer_graphs_prev_array_nodes_.begin(), outer_graphs_prev_array_nodes_.end(), [this](const auto& tup1) {
        return std::all_of(outer_graphs_prev_array_nodes_.begin(), outer_graphs_prev_array_nodes_.end(), [&tup1](const auto& tup2) {
            return &tup1 == &tup2 || std::get<0>(tup1) != std::get<0>(tup2);
        });
    }));

    // Corresponding previous array nodes across graphs (corresponding to the same output array) should have the same array body, if it's
    // alive.
    for (size_t i_prev = 0; i_prev < prev_node_count(); ++i_prev) {
        nonstd::optional<internal::ArrayBody*> prev_array_body{};
        for (const auto& tup : outer_graphs_prev_array_nodes_) {
            const std::vector<std::shared_ptr<ArrayNode>>& vec = std::get<1>(tup);
            const std::shared_ptr<ArrayNode>& prev_array_node = vec[i_prev];
            std::shared_ptr<internal::ArrayBody> body = prev_array_node->GetBody();
            if (!prev_array_body.has_value()) {
                prev_array_body = body.get();
            } else {
                assert(*prev_array_body == body.get());
            }
        }
    }
#endif  // NDEBUG
}

std::vector<std::shared_ptr<ArrayNode>>& OpNode::next_array_nodes() {
    assert(std::all_of(next_array_nodes_.begin(), next_array_nodes_.end(), [this](const std::shared_ptr<ArrayNode>& arr_node) {
        return arr_node != nullptr;
    }));
    assert(std::all_of(next_array_nodes_.begin(), next_array_nodes_.end(), [this](const std::shared_ptr<ArrayNode>& arr_node) {
        return arr_node->graph_id() == graph_id_;
    }));
    return next_array_nodes_;
}

const std::vector<std::shared_ptr<ArrayNode>>& OpNode::next_array_nodes() const {
    assert(std::all_of(next_array_nodes_.begin(), next_array_nodes_.end(), [this](const std::shared_ptr<ArrayNode>& arr_node) {
        return arr_node != nullptr;
    }));
    assert(std::all_of(next_array_nodes_.begin(), next_array_nodes_.end(), [this](const std::shared_ptr<ArrayNode>& arr_node) {
        return arr_node->graph_id() == graph_id_;
    }));
    return next_array_nodes_;
}

internal::OpNodeBackwardEntry& OpNode::RegisterBackwardFunction(
        std::vector<std::shared_ptr<ArrayNode>> next_array_nodes, BackwardFunction backward_func) {
    AssertConsistency();
    assert(!next_array_nodes.empty());
    assert(std::all_of(next_array_nodes.begin(), next_array_nodes.end(), [this](const std::shared_ptr<ArrayNode>& next_array_node) {
        // next_array_node could be nullptr, if the corresponding input array does not require grad.
        return next_array_node == nullptr || next_array_node->graph_id() == graph_id_;
    }));

    // Update the rank of op node
    for (const std::shared_ptr<ArrayNode>& next_array_node : next_array_nodes) {
        if (next_array_node != nullptr) {
            rank_ = std::max(rank_, next_array_node->rank() + 1);
        }
    }

    // Store next nodes and record indices of them
    std::vector<nonstd::optional<size_t>> next_array_node_indices;
    next_array_node_indices.reserve(next_array_nodes.size());
    for (std::shared_ptr<ArrayNode>& next_array_node : next_array_nodes) {
        if (next_array_node != nullptr) {
            next_array_node_indices.emplace_back(next_array_nodes_.size());
            next_array_nodes_.emplace_back(std::move(next_array_node));
        } else {
            next_array_node_indices.emplace_back(nonstd::nullopt);
        }
    }

    // Add backward entry
    backward_entries_.emplace_back(*this, std::move(next_array_node_indices), std::move(backward_func));

    AssertConsistency();
    return backward_entries_.back();
}

void OpNode::RegisterOuterGraphsPreviousArrayNodes(
        const GraphId& other_graph_id, std::vector<std::shared_ptr<ArrayNode>> outer_graphs_prev_array_nodes) {
    AssertConsistency();
    assert(other_graph_id != graph_id_);
    assert(outer_graphs_prev_array_nodes.size() == prev_array_props_.size());

    outer_graphs_prev_array_nodes_.emplace_back(other_graph_id, std::move(outer_graphs_prev_array_nodes));

    AssertConsistency();
}

namespace internal {

std::shared_ptr<ArrayNode> CreatePrevArrayNode(std::shared_ptr<OpNode> op_node, size_t prev_array_node_index) {
    assert(prev_array_node_index < op_node->prev_node_count());
    assert(op_node->prev_array_nodes()[prev_array_node_index].expired());

    const internal::ArrayProps& props = op_node->GetPrevArrayProps(prev_array_node_index);
    auto prev_array_node = std::make_shared<ArrayNode>(props.shape, props.dtype, props.device, op_node->graph_id());
    op_node->prev_array_nodes()[prev_array_node_index] = prev_array_node;
    prev_array_node->set_next_op_node(std::move(op_node));

    return prev_array_node;
}

}  // namespace internal
}  // namespace xchainer
<|endoftext|>