<commit_before>// -*- c-basic-offset: 2; related-file-name: "aggwrap.h" -*-
/*
 * @(#)$Id$
 *
 * This file is distributed under the terms in the attached INTEL-LICENSE file.
 * If you do not find these files, copies can be found by writing to:
 * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,
 * Berkeley, CA, 94704.  Attention:  Intel License Inquiry.
 *
 */

#include "aggwrap.h"
#include "trace.h"
#include "val_int32.h"
#include "val_str.h"

Aggwrap::Aggwrap(str aggfn, int aggfield, str outputTableName)
  : Element(strbuf() << "Aggwrap<" << aggfn << "," << aggfield
	    << ", " << outputTableName << ">", 2, 2),
    _aggfn(aggfn),
    _aggfield(aggfield),
    inner_accepting(true),
    ext_in_cb(cbv_null),
    ext_out_cb(cbv_null)
{
  numJoins = 0;
  _outputTableName = outputTableName;
  if (aggfn == "min") {
    log(LoggerI::INFO, 0, str(strbuf() << "min aggregation " << _aggfield));
  } else if (aggfn == "max") {
    log(LoggerI::INFO, 0, str(strbuf() << "max aggregation " << _aggfield));
  } else if (aggfn == "count") {
    log(LoggerI::INFO, 0, str(strbuf() << "count aggregation " << _aggfield));
  } else {
    log(LoggerI::INFO, 0, "HELP: Don't understand agg function '"
	<< aggfn << "'");
  }
}

//
// A new tuple is coming in from outside.
//
int Aggwrap::push(int port, TupleRef t, cbv cb)
{
  log(LoggerI::INFO, 0, str(strbuf() << " Push: " << port << "," << t->toString()));

  // if receive the next one when previous has not finished, then keep in queue?

  // Is this the right port?
  switch (port) {
  case 0:
    ext_in_cb = cb;
    switch(aggState) {
    case 0:  // Waiting
      log(LoggerI::INFO, 0,
	  str(strbuf() << " received a tuple from outside!"
	      << t->toString()));
      assert(inner_accepting);
      agg_init();
      _incomingTuple = t;
      inner_accepting = output(1)->push(t, wrap(this, &Aggwrap::int_push_cb));
      break;
    case 1:
      log(LoggerI::INFO, 0, "FAIL: pushed when processing!");
      // Discard tuple
      break;
    case 2:
      log(LoggerI::INFO, 0, "FAIL: pushed when done pending");
      break;
    default:
      log(LoggerI::INFO, 0, str(strbuf() << "FAIL: weird state "
				<< aggState));
    }
    log(LoggerI::INFO, 0, str(strbuf() << " Block downstream"));
    return 0;
  case 1:
    switch(aggState) {
    case 0:  // Waiting
      log(LoggerI::INFO, 0,
	  "OOPS: unexpected result tuple when in state waiting");
      break;
    case 1:
      agg_accum(t);
      break;
    case 2:
      log(LoggerI::INFO, 0, "FAIL: pushed when done pending");
      break;
    default:
      log(LoggerI::INFO, 0, str(strbuf() << "FAIL: weird state "
				<< aggState));
    }
    return 1;
  default:
    assert(port < 2);
    return  0;
  }

}

//
// Callback from the inner graph when we can push more tuples.
//
void Aggwrap::int_push_cb()
{
  TRC_FN;
  inner_accepting = true;
  log(LoggerI::INFO,
      0, str(strbuf()
	     << "Callback from inner graph on successful push" << aggState));
  if (aggState == 0 && ext_in_cb) {
    log(LoggerI::INFO, 0, str(strbuf() << "Invoke ext_in_cb"));
    ext_in_cb();
    ext_in_cb = cbv_null;
  }
}

//
// Completion callback
//
void Aggwrap::comp_cb(int jnum)
{
  TRC_FN;
  log(LoggerI::INFO, 0, str(strbuf() << "Join " << jnum << " completed."));
  if (curJoin < jnum) {
    curJoin = jnum;
  }

  if (curJoin >= numJoins - 1) {
    // Presumably, we're now done.
    agg_finalize();
  }
}

//
// Getting hold of a closure for the above
//
cbv Aggwrap::get_comp_cb()
{
  log(LoggerI::INFO, 0, str(strbuf() << "Joins so far: " << numJoins + 1));
  return wrap(this,&Aggwrap::comp_cb,numJoins++);
}

//
// Finally, the aggregation functions
//
void Aggwrap::agg_init() {
  TRC_FN;
  curJoin = -1;
  aggState = 1;
  if ( _aggfn == "count") {
    count = 0;
  } else {
    aggResult = NULL;
  }
}

void Aggwrap::agg_accum(TupleRef t) {
  TRC_FN;
  if ( _aggfn == "count") {
    count++;
    aggResult = t;
    log(LoggerI::INFO, 0, str(strbuf() << "After Agg accumulation: "
			      << aggResult->toString()));
    return;
  }

  if ( aggResult == NULL ) {
    aggResult = t;
    log(LoggerI::INFO, 0, str(strbuf() << "After Agg accumulation: "
			      << aggResult->toString()));
    return;
  }

  log(LoggerI::INFO, 0, str(strbuf() << "Before Agg accumulation: "
			    << aggResult->toString()));
  int cr = (*t)[_aggfield]->compareTo((*aggResult)[_aggfield]);
  if ((cr == -1 && _aggfn == "min") || (cr == 1 && _aggfn == "max")) {
    aggResult = t;
  }
  log(LoggerI::INFO, 0, str(strbuf() << "After Agg accumulation: "
			    << aggResult->toString() << cr
			    << " " << (*t)[_aggfield]->toString() << " "
			    << (*aggResult)[_aggfield]->toString()));
}

void Aggwrap::agg_finalize() {
  TRC_FN;
  if (_aggfn == "count") {
    if (_incomingTuple) {
      TupleRef aggResultToRet = Tuple::mk();
      aggResultToRet->append(Val_Str::mk(_outputTableName));
      for (uint k = 0; k < _groupByFields.size(); k++) {
	aggResultToRet->append((*_incomingTuple)[k+1]);
      }
      aggResultToRet->append(Val_Int32::mk(count));
      aggResultToRet->freeze();

      aggResult = Tuple::mk();
      aggResult->concat(aggResultToRet);
      aggResult->freeze();
    }
  }
  if (aggResult) {
    log(LoggerI::INFO, 0,
	str(strbuf() << " finalize: Pushing tuple" << aggResult->toString()));
    output(0)->push(aggResult, cbv_null);
  } else {
    log(LoggerI::INFO, 0, "Finalize: Alas, nothing to push");
  }
  if (ext_in_cb) {
    log(LoggerI::INFO, 0, "Invoke push callback for more tuples");
    // accept new tuples to be pushed in via outer regardless of any outputs
    ext_in_cb();
    ext_in_cb = cbv_null;
  }
  aggState = 0;
}

void Aggwrap::registerGroupbyField(int field)
{
  _groupByFields.push_back(field);
  warn << " Register group by" << field << "\n";
}
<commit_msg>aggwrap count bug<commit_after>// -*- c-basic-offset: 2; related-file-name: "aggwrap.h" -*-
/*
 * @(#)$Id$
 *
 * This file is distributed under the terms in the attached INTEL-LICENSE file.
 * If you do not find these files, copies can be found by writing to:
 * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300,
 * Berkeley, CA, 94704.  Attention:  Intel License Inquiry.
 *
 */

#include "aggwrap.h"
#include "trace.h"
#include "val_int32.h"
#include "val_str.h"

Aggwrap::Aggwrap(str aggfn, int aggfield, str outputTableName)
  : Element(strbuf() << "Aggwrap<" << aggfn << "," << aggfield
	    << ", " << outputTableName << ">", 2, 2),
    _aggfn(aggfn),
    _aggfield(aggfield),
    inner_accepting(true),
    ext_in_cb(cbv_null),
    ext_out_cb(cbv_null)
{
  numJoins = 0;
  _outputTableName = outputTableName;
  if (aggfn == "min") {
    log(LoggerI::INFO, 0, str(strbuf() << "min aggregation " << _aggfield));
  } else if (aggfn == "max") {
    log(LoggerI::INFO, 0, str(strbuf() << "max aggregation " << _aggfield));
  } else if (aggfn == "count") {
    log(LoggerI::INFO, 0, str(strbuf() << "count aggregation " << _aggfield));
  } else {
    log(LoggerI::INFO, 0, "HELP: Don't understand agg function '"
	<< aggfn << "'");
  }
}

//
// A new tuple is coming in from outside.
//
int Aggwrap::push(int port, TupleRef t, cbv cb)
{
  log(LoggerI::INFO, 0, str(strbuf() << " Push: " << port << "," << t->toString()));

  // if receive the next one when previous has not finished, then keep in queue?

  // Is this the right port?
  switch (port) {
  case 0:
    ext_in_cb = cb;
    switch(aggState) {
    case 0:  // Waiting
      log(LoggerI::INFO, 0,
	  str(strbuf() << " received a tuple from outside!"
	      << t->toString()));
      assert(inner_accepting);
      agg_init();
      _incomingTuple = t;
      inner_accepting = output(1)->push(t, wrap(this, &Aggwrap::int_push_cb));
      break;
    case 1:
      log(LoggerI::INFO, 0, "FAIL: pushed when processing!");
      // Discard tuple
      break;
    case 2:
      log(LoggerI::INFO, 0, "FAIL: pushed when done pending");
      break;
    default:
      log(LoggerI::INFO, 0, str(strbuf() << "FAIL: weird state "
				<< aggState));
    }
    log(LoggerI::INFO, 0, str(strbuf() << " Block downstream"));
    return 0;
  case 1:
    switch(aggState) {
    case 0:  // Waiting
      log(LoggerI::INFO, 0,
	  "OOPS: unexpected result tuple when in state waiting");
      break;
    case 1:
      agg_accum(t);
      break;
    case 2:
      log(LoggerI::INFO, 0, "FAIL: pushed when done pending");
      break;
    default:
      log(LoggerI::INFO, 0, str(strbuf() << "FAIL: weird state "
				<< aggState));
    }
    return 1;
  default:
    assert(port < 2);
    return  0;
  }

}

//
// Callback from the inner graph when we can push more tuples.
//
void Aggwrap::int_push_cb()
{
  TRC_FN;
  inner_accepting = true;
  log(LoggerI::INFO,
      0, str(strbuf()
	     << "Callback from inner graph on successful push" << aggState));
  if (aggState == 0 && ext_in_cb) {
    log(LoggerI::INFO, 0, str(strbuf() << "Invoke ext_in_cb"));
    ext_in_cb();
    ext_in_cb = cbv_null;
  }
}

//
// Completion callback
//
void Aggwrap::comp_cb(int jnum)
{
  TRC_FN;
  log(LoggerI::INFO, 0, str(strbuf() << "Join " << jnum << " completed."));
  if (curJoin < jnum) {
    curJoin = jnum;
  }

  if (curJoin >= numJoins - 1) {
    // Presumably, we're now done.
    agg_finalize();
  }
}

//
// Getting hold of a closure for the above
//
cbv Aggwrap::get_comp_cb()
{
  log(LoggerI::INFO, 0, str(strbuf() << "Joins so far: " << numJoins + 1));
  return wrap(this,&Aggwrap::comp_cb,numJoins++);
}

//
// Finally, the aggregation functions
//
void Aggwrap::agg_init() {
  TRC_FN;
  curJoin = -1;
  aggState = 1;
  if ( _aggfn == "count") {
    count = 0;
  } else {
    aggResult = NULL;
  }
}

void Aggwrap::agg_accum(TupleRef t) {
  TRC_FN;
  if ( _aggfn == "count") {
    count++;
    aggResult = t;
    log(LoggerI::INFO, 0, str(strbuf() << "After Agg accumulation: "
			      << aggResult->toString()));
    return;
  }

  if ( aggResult == NULL ) {
    aggResult = t;
    log(LoggerI::INFO, 0, str(strbuf() << "After Agg accumulation: "
			      << aggResult->toString()));
    return;
  }

  log(LoggerI::INFO, 0, str(strbuf() << "Before Agg accumulation: "
			    << aggResult->toString()));
  int cr = (*t)[_aggfield]->compareTo((*aggResult)[_aggfield]);
  if ((cr == -1 && _aggfn == "min") || (cr == 1 && _aggfn == "max")) {
    aggResult = t;
  }
  log(LoggerI::INFO, 0, str(strbuf() << "After Agg accumulation: "
			    << aggResult->toString() << cr
			    << " " << (*t)[_aggfield]->toString() << " "
			    << (*aggResult)[_aggfield]->toString()));
}

void Aggwrap::agg_finalize() {
  TRC_FN;
  if (_aggfn == "count") {
    if (_incomingTuple) {
      TupleRef aggResultToRet = Tuple::mk();
      aggResultToRet->append(Val_Str::mk(_outputTableName));
      for (uint k = 0; k < _groupByFields.size(); k++) {
	/*warn << _incomingTuple->toString() << " "
	  << _groupByFields.at(k) + 1 << "\n";     */
	aggResultToRet->append((*_incomingTuple)[_groupByFields.at(k)+1]);
      }
      aggResultToRet->append(Val_Int32::mk(count));
      aggResultToRet->freeze();

      aggResult = Tuple::mk();
      aggResult->concat(aggResultToRet);
      aggResult->freeze();
    }
  }
  if (aggResult) {
    log(LoggerI::INFO, 0,
	str(strbuf() << " finalize: Pushing tuple" << aggResult->toString()));
    output(0)->push(aggResult, cbv_null);
  } else {
    log(LoggerI::INFO, 0, "Finalize: Alas, nothing to push");
  }
  if (ext_in_cb) {
    log(LoggerI::INFO, 0, "Invoke push callback for more tuples");
    // accept new tuples to be pushed in via outer regardless of any outputs
    ext_in_cb();
    ext_in_cb = cbv_null;
  }
  aggState = 0;
}

void Aggwrap::registerGroupbyField(int field)
{
  _groupByFields.push_back(field);
  warn << " Register group by" << field << "\n";
}
<|endoftext|>


<commit_before><commit_msg>Reorder zeros<commit_after><|endoftext|>


<commit_before>/*  -*- Mode: C++ -*-
 *
 * contextkit-meego
 * Copyright © 2010, Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 */

#include "cellularprovider.h"
#include "ofono_interface.h"
#include "manager_interface.h"

#include <QDBusConnection>

#define SignalStrength "Cellular.SignalStrength"
#define DataTechnology "Cellular.DataTechnology"
#define RegistrationStatus "Cellular.RegistrationStatus"
IProviderPlugin* pluginFactory(const QString& constructionString)
{
	Q_UNUSED(constructionString)
	return new CellularProvider();
}

CellularProvider::CellularProvider()
{
	qDebug() << "CellularProvider" << "Initializing cellular provider";
        registerContextDataTypes();
	QMetaObject::invokeMethod(this,"ready",Qt::QueuedConnection);
}

CellularProvider::~CellularProvider()
{

}

void CellularProvider::subscribe(QSet<QString> keys)
{
	if(subscribedProps.isEmpty()) initProvider();

	subscribedProps.unite(keys);

	QMetaObject::invokeMethod(this, "emitSubscribeFinished", Qt::QueuedConnection);
}

void CellularProvider::unsubscribe(QSet<QString> keys)
{
	subscribedProps.subtract(keys);
	if(subscribedProps.isEmpty()) cleanProvider();
}

void CellularProvider::initProvider()
{
	qDebug() << "CellularProvider" << "First subscriber appeared, connecting to ofono";

        Manager managerProxy("org.ofono",
				  "/",
				QDBusConnection::systemBus());

        QDBusPendingReply<QArrayOfPathProperties> reply;
        QDBusPendingCallWatcher * watcher;

        reply = managerProxy.GetModems();
        watcher = new QDBusPendingCallWatcher(reply);
        watcher->waitForFinished();

        QList<QDBusObjectPath> paths = providerProcessGetModems(watcher);

        QString modemPath;
	foreach (QDBusObjectPath p, paths)
	{
		if (modemPath.isNull() || modemPath.isEmpty())
		{
			modemPath = QString(p.path());
			networkProps = new NetworkProperties("org.ofono",
					modemPath,
					QDBusConnection::systemBus());

			connect(networkProps,SIGNAL(PropertyChanged(const QString&, const QDBusVariant&)),this,SLOT(updateProperty(const QString&, const QDBusVariant&)));
			updateProperties();
			break;
		}
	}
	if (!networkProps)
	{
		qDebug() << "ProviderProvider" << "No NetworkRegistration interface found";
	}
}

QList<QDBusObjectPath> CellularProvider::providerProcessGetModems(QDBusPendingCallWatcher *call)
{
    QDBusPendingReply<QArrayOfPathProperties> reply = *call;
    QList<QDBusObjectPath> pathlist;
    if (reply.isError()) {
        // TODO: Handle this properly, by setting states, or disabling features
        qWarning() << "org.ofono.Manager.GetModems() failed: " <<
                      reply.error().message();
    } else {
        QArrayOfPathProperties modems = reply.value();
        qDebug() << QString("modem count:")<<modems.count();
        for (int i=0; i< modems.count();i++) {
            OfonoPathProperties p = modems[i];
            pathlist.append(QDBusObjectPath(p.path.path()));
        }
    }
    return pathlist;
}

void CellularProvider::cleanProvider()
{
	qDebug() << "CellularProvider" << "Last subscriber gone, destroying CellularProvider connections";
	delete networkProps;
	networkProps = NULL;
}

void CellularProvider::updateProperty(const QString &key, const QDBusVariant &val)
{
	qDebug() << "CellularProvider" << key<<" changed";
	if(key == "Status")
	{
		QString status = qdbus_cast<QString> (val.variant());
		if (status == "registered" || status == "roming")
		{
        		props[RegistrationStatus] = QVariant("online");
		} else if (status == "unknown")
		{
			props[RegistrationStatus] = QVariant("no-sim");
		} else if (status == "denied")
		{
			props[RegistrationStatus] = QVariant("forbidden");
		} else if (status == "unregister")
		{
			props[RegistrationStatus] = QVariant("offline");
		} else
		{
			props[RegistrationStatus] =QVariant("");
		}

	} else if (key == "Strength")
	{
        	props[SignalStrength] = QVariant((val.variant()).toInt());
	} else if (key == "Technologies")
	{
        	props[DataTechnology] = val.variant();
	}
	foreach(QString key, subscribedProps)
	{
		emit valueChanged(key, props[key]);
	}
}

void CellularProvider::updateProperties()
{
	if(!networkProps) return;

	QVariantMap newProps = networkProps->GetProperties();
	props[SignalStrength] = QVariant(newProps["Strength"].toInt());
	props[DataTechnology] = newProps["Technology"];

	QString status  = newProps["Status"].toString();
	if (status == "registered" || status == "roming")
	{
       		props[RegistrationStatus] = QVariant("online");
	} else if (status == "unknown")
	{
		props[RegistrationStatus] = QVariant("no-sim");
	} else if (status == "denied")
	{
		props[RegistrationStatus] = QVariant("forbidden");
	} else if (status == "unregister")
	{
		props[RegistrationStatus] = QVariant("offline");
	} else
	{
		props[RegistrationStatus] =QVariant("");
	}

	foreach(QString key, subscribedProps)
	{
		emit valueChanged(key, props[key]);
	}
}
void CellularProvider::emitSubscribeFinished()
{
	foreach(QString key, subscribedProps)
	{
		emit subscribeFinished(key, props[key]);
	}
}

<commit_msg>cellular: Source updated to match current oFono<commit_after>/*  -*- Mode: C++ -*-
 *
 * contextkit-meego
 * Copyright © 2010, Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 */

#include "cellularprovider.h"
#include "ofono_interface.h"
#include "sim_interface.h"

#include <QDBusConnection>

#define SignalStrength "Cellular.SignalStrength"
#define Technology "Cellular.Technology"
#define DataTechnology "Cellular.DataTechnology"
#define RegistrationStatus "Cellular.RegistrationStatus"
#define CellName "Cellular.CellName"
#define NetworkName "Cellular.NetworkName"
#define SignalBars "Cellular.SignalBars" // DUMMY
#define PacketData "Cellular.PacketData" // TODO
#define GSMBand "Cellular.GSMBand" // TODO
#define ExtendedNName "Cellular.ExtendedNetworkName" // TODO
#define CellNameEnabled "Cellular.CellNameDisplayEnabled" // TODO

IProviderPlugin* pluginFactory(const QString& constructionString)
{
	Q_UNUSED(constructionString)
	return new CellularProvider();
}

CellularProvider::CellularProvider(): activeModem(""), networkProperties(NULL), simProperties(NULL)
{
	qDebug() << "CellularProvider" << "Initializing cellular provider";
	registerContextDataTypes();
	QMetaObject::invokeMethod(this,"ready",Qt::QueuedConnection);
}

CellularProvider::~CellularProvider()
{
	cleanProvider();
}

void CellularProvider::subscribe(QSet<QString> keys)
{
	if(subscribedProperties.isEmpty()) initProvider();

	subscribedProperties.unite(keys);

	QMetaObject::invokeMethod(this, "emitSubscribeFinished", Qt::QueuedConnection);
}

void CellularProvider::unsubscribe(QSet<QString> keys)
{
	subscribedProperties.subtract(keys);
	if(subscribedProperties.isEmpty()) cleanProvider();
}

void CellularProvider::initProvider()
{
	QDBusPendingReply<QArrayOfPathProperties> reply;
	QList<QDBusObjectPath> paths;

	qDebug() << "CellularProvider" << "First subscriber appeared, connecting to ofono";

	 managerProxy = new Manager("org.ofono", "/", QDBusConnection::systemBus());

	reply = managerProxy->GetModems();
	QDBusPendingCallWatcher watcher(reply);
	watcher.waitForFinished();

	connect(managerProxy, SIGNAL(ModemAdded(const QDBusObjectPath &, const QVariantMap &)),
		this, SLOT(addModem(const QDBusObjectPath &, const QVariantMap &)));

	connect(managerProxy, SIGNAL(ModemRemoved(const QDBusObjectPath&)),
		this, SLOT(removeModem(const QDBusObjectPath&)));

	paths = providerProcessGetModems(&watcher);

	foreach (QDBusObjectPath modem, paths)
	{
		if (activateModem(modem.path())) {
			updateProperties();
			return;
		}
	}

	qDebug() << "ProviderProvider" << "No NetworkRegistration interface found";

}

QList<QDBusObjectPath> CellularProvider::providerProcessGetModems(QDBusPendingCallWatcher *call)
{
	QDBusPendingReply<QArrayOfPathProperties> reply = *call;
	QList<QDBusObjectPath> pathlist;

	if (reply.isError()) {
		// TODO: Handle this properly, by setting states, or disabling features
		qWarning() << "org.ofono.Manager.GetModems() failed: " <<
		reply.error().message();
	} else {
		QArrayOfPathProperties modems = reply.value();
		qDebug() << QString("modem count:")<<modems.count();

		for (int i=0; i< modems.count();i++) {
			OfonoPathProperties p = modems[i];
			pathlist.append(QDBusObjectPath(p.path.path()));
		}
	}
	return pathlist;
}

bool CellularProvider::activateModem(const QString& path) {

	qDebug() << "CellularProvider" << "activateModem" << path;

	networkProperties = new NetworkProperties("org.ofono",
				path,
				QDBusConnection::systemBus());
	simProperties = new SimProperties("org.ofono",
				path,
				QDBusConnection::systemBus());

	if (!networkProperties->isValid() || !simProperties->isValid()) {
		deleteProperties();
		return false;
	}

	connect(networkProperties,SIGNAL(PropertyChanged(const QString&, const QDBusVariant&)),
		this,SLOT(updateProperty(const QString&, const QDBusVariant&)));

	connect(simProperties,SIGNAL(PropertyChanged(const QString&, const QDBusVariant&)),
		this,SLOT(updateProperty(const QString&, const QDBusVariant&)));

	activeModem = path;

	return true;
}

void CellularProvider::addModem(const QDBusObjectPath& path, const QVariantMap& properties) {

	Q_UNUSED(properties)

	if(activeModem != "")
		return;

	QString modemPath = path.path();

	if (activateModem(modemPath) == false)
		return;

	updateProperties();

	qDebug() << "CellularProvider" << "Modem added: " << path.path();
}

void CellularProvider::removeModem(const QDBusObjectPath& path) {

	qDebug() << "CellularProvider" << "removeModem" << path.path();

	if(path.path() == activeModem) {
		activeModem = "";

		deleteProperties();

		QArrayOfPathProperties modems = managerProxy->GetModems();
		foreach (OfonoPathProperties modem, modems) {

			if (activateModem(modem.path.path())) {
				updateProperties();
				return;
			}
		}

		qDebug() << "CellularProvider" << "No proper modem found";
	}
}

void CellularProvider::deleteProperties() {

	qDebug() << "CellularProvider" << "deleteProperties";

	delete networkProperties;
	delete simProperties;

	foreach (QString prop, subscribedProperties) {
		setUnknown(prop);
	}
	properties.empty();
	networkProperties = NULL;
	simProperties = NULL;
}

void CellularProvider::cleanProvider()
{
	qDebug() << "CellularProvider" << "Last subscriber gone, destroying CellularProvider connections";
	deleteProperties();

	delete managerProxy;
	managerProxy = NULL;
}

void CellularProvider::updateProperty(const QString &key, const QDBusVariant &val)
{
	qDebug() << "CellularProvider" << key<<" changed";

	if (key == "Present")
		updateSimPresent(val);

	else if (key == "Status")
		updateRegistrationStatus(val);

	else if (key == "BaseStation")
		updateCellName(val);

	else if (key == "Strength")
		updateSignalStrength(val);

	else if (key == "Technology")
		updateTechnology(val);

	else if (key == "Name")
		updateNetworkName(val);
}

void CellularProvider::updateProperties()
{
	if(!networkProperties || !simProperties) {
		qDebug() << "No Properties found";
		return;
	}

	QVariantMap np = networkProperties->GetProperties();
	QVariantMap sp = simProperties->GetProperties();

	QVariantMap::const_iterator iter = np.begin();
	while (iter != np.end()) {
		updateProperty(iter.key(), QDBusVariant(iter.value()));
		iter++;
	}

	iter = sp.begin();
	while (iter != sp.end()) {
		updateProperty(iter.key(), QDBusVariant(iter.value()));
		iter++;
	}
}

void CellularProvider::updateSimPresent(const QDBusVariant &val)
{
	bool simPresent = val.variant().toBool();
	if (simPresent == FALSE) {
		properties[RegistrationStatus] = QVariant("no-sim");
		emit valueChanged(RegistrationStatus, properties[RegistrationStatus]);

	}
}

void CellularProvider::updateRegistrationStatus(const QDBusVariant &val)
{
	QString status = qdbus_cast<QString> (val.variant());
	if (status == "registered") {
		properties[RegistrationStatus] = QVariant("home");
	}
	else if ( status =="roaming") {
		properties[RegistrationStatus] = QVariant("roam");
	}
	else if (status == "denied") {
		properties[RegistrationStatus] = QVariant("forbidden");
	}
	else {
		properties[RegistrationStatus] =QVariant("offline");
	}
	emit valueChanged(RegistrationStatus, properties[RegistrationStatus]);
}

void CellularProvider::updateCellName(const QDBusVariant &val)
{
	properties[CellName] = val.variant();
	emit valueChanged(CellName, properties[CellName]);
}

void CellularProvider::updateSignalStrength(const QDBusVariant &val)
{
	int strength = val.variant().toInt();

	if(strength >= 0 && strength <= 100) {
		properties[SignalStrength] = QVariant((val.variant()).toInt());
		properties[SignalBars] = QVariant((val.variant()).toInt() / 20); //DUMMY
	} else {
		properties[SignalStrength] = QVariant();
		properties[SignalBars] = QVariant();
	}

	emit valueChanged(SignalStrength, properties[SignalStrength]);
	emit valueChanged(SignalBars, properties[SignalBars]);
}

void CellularProvider::updateTechnology(const QDBusVariant &val)
{
	QString tech = qdbus_cast<QString> (val.variant());

	if (tech == "gprs") {
		properties[DataTechnology] = QVariant("gsm");
		properties[Technology] = QVariant("gsm");
	}
	else if (tech == "egprs") {
		properties[DataTechnology] = QVariant("edge");
		properties[Technology] = QVariant("gsm");
	}
	else if (tech == "umts") {
		properties[DataTechnology] = QVariant("umts");
		properties[Technology] = QVariant("umts");
	}
	else if (tech == "hspa") {
		properties[DataTechnology] = QVariant("hspa");
		properties[Technology] = QVariant("umts");
	}
	else if (tech == "lte") {
		properties[DataTechnology] = QVariant("lte");
		properties[Technology] = QVariant("lte");
	}
	else {
		properties[DataTechnology] = QVariant();
		properties[Technology] = QVariant();

	}
	emit valueChanged(DataTechnology, properties[DataTechnology]);
	emit valueChanged(Technology, properties[Technology]);
}

void CellularProvider::setUnknown(const QString& key) {
	emit valueChanged(key,QVariant());
}

void CellularProvider::updateNetworkName(const QDBusVariant &val)
{
	properties[NetworkName] = val.variant();
	emit valueChanged(NetworkName, properties[NetworkName]);
}

void CellularProvider::emitSubscribeFinished()
{
	foreach(QString key, subscribedProperties)
	{
		emit subscribeFinished(key, properties[key]);
	}
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TitleHelper.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2008-02-18 16:00:07 $
 *
 *  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 _CHART2_TOOLS_TITLEHELPER_HXX
#define _CHART2_TOOLS_TITLEHELPER_HXX

#include "ReferenceSizeProvider.hxx"

#ifndef _COM_SUN_STAR_CHART2_XTITLED_HPP_
#include <com/sun/star/chart2/XTitled.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_XDIAGRAM_HPP_
#include <com/sun/star/chart2/XDiagram.hpp>
#endif

//.............................................................................
namespace chart
{
//.............................................................................

class TitleHelper
{
public:
    enum eTitleType
    {
        TITLE_BEGIN = 0,
        MAIN_TITLE = 0,
        SUB_TITLE,
        X_AXIS_TITLE,
        Y_AXIS_TITLE,
        Z_AXIS_TITLE,
        SECONDARY_X_AXIS_TITLE,
        SECONDARY_Y_AXIS_TITLE,
        NORMAL_TITLE_END,

        //it is intended that this both types are after NORMAL_TITLE_END
        TITLE_AT_STANDARD_X_AXIS_POSITION, //equals the Y_AXIS_TITLE for barchart
        TITLE_AT_STANDARD_Y_AXIS_POSITION  //equals the X_AXIS_TITLE for barchart
    };

    static ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XTitle >
        getTitle( eTitleType nTitleIndex
                    , const ::com::sun::star::uno::Reference<
                    ::com::sun::star::frame::XModel >& xModel );

    static ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XTitle >
        createTitle(  eTitleType nTitleIndex
                    , const rtl::OUString& rTitleText
                    , const ::com::sun::star::uno::Reference<
                            ::com::sun::star::frame::XModel >& xModel
                    , const ::com::sun::star::uno::Reference<
                            ::com::sun::star::uno::XComponentContext > & xContext
                    , ReferenceSizeProvider * pRefSizeProvider = 0 );

    static void removeTitle( eTitleType nTitleIndex
                    , const ::com::sun::star::uno::Reference<
                            ::com::sun::star::frame::XModel >& xModel );

    static rtl::OUString getCompleteString( const ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::XTitle >& xTitle );
    static void setCompleteString( const rtl::OUString& rNewText
        , const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XTitle >& xTitle
        , const ::com::sun::star::uno::Reference<
            ::com::sun::star::uno::XComponentContext > & xContext
        , float * pDefaultCharHeight = 0 );

    static bool getTitleType( eTitleType& rType
                    , const ::com::sun::star::uno::Reference<
                        ::com::sun::star::chart2::XTitle >& xTitle
                    , const ::com::sun::star::uno::Reference<
                        ::com::sun::star::frame::XModel >& xModel );
};

//.............................................................................
} //namespace chart
//.............................................................................
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.6.34); FILE MERGED 2008/04/01 10:50:29 thb 1.6.34.2: #i85898# Stripping all external header guards 2008/03/28 16:43:57 rt 1.6.34.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: TitleHelper.hxx,v $
 * $Revision: 1.7 $
 *
 * 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 _CHART2_TOOLS_TITLEHELPER_HXX
#define _CHART2_TOOLS_TITLEHELPER_HXX

#include "ReferenceSizeProvider.hxx"
#include <com/sun/star/chart2/XTitled.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/chart2/XDiagram.hpp>

//.............................................................................
namespace chart
{
//.............................................................................

class TitleHelper
{
public:
    enum eTitleType
    {
        TITLE_BEGIN = 0,
        MAIN_TITLE = 0,
        SUB_TITLE,
        X_AXIS_TITLE,
        Y_AXIS_TITLE,
        Z_AXIS_TITLE,
        SECONDARY_X_AXIS_TITLE,
        SECONDARY_Y_AXIS_TITLE,
        NORMAL_TITLE_END,

        //it is intended that this both types are after NORMAL_TITLE_END
        TITLE_AT_STANDARD_X_AXIS_POSITION, //equals the Y_AXIS_TITLE for barchart
        TITLE_AT_STANDARD_Y_AXIS_POSITION  //equals the X_AXIS_TITLE for barchart
    };

    static ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XTitle >
        getTitle( eTitleType nTitleIndex
                    , const ::com::sun::star::uno::Reference<
                    ::com::sun::star::frame::XModel >& xModel );

    static ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XTitle >
        createTitle(  eTitleType nTitleIndex
                    , const rtl::OUString& rTitleText
                    , const ::com::sun::star::uno::Reference<
                            ::com::sun::star::frame::XModel >& xModel
                    , const ::com::sun::star::uno::Reference<
                            ::com::sun::star::uno::XComponentContext > & xContext
                    , ReferenceSizeProvider * pRefSizeProvider = 0 );

    static void removeTitle( eTitleType nTitleIndex
                    , const ::com::sun::star::uno::Reference<
                            ::com::sun::star::frame::XModel >& xModel );

    static rtl::OUString getCompleteString( const ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::XTitle >& xTitle );
    static void setCompleteString( const rtl::OUString& rNewText
        , const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XTitle >& xTitle
        , const ::com::sun::star::uno::Reference<
            ::com::sun::star::uno::XComponentContext > & xContext
        , float * pDefaultCharHeight = 0 );

    static bool getTitleType( eTitleType& rType
                    , const ::com::sun::star::uno::Reference<
                        ::com::sun::star::chart2::XTitle >& xTitle
                    , const ::com::sun::star::uno::Reference<
                        ::com::sun::star::frame::XModel >& xModel );
};

//.............................................................................
} //namespace chart
//.............................................................................
#endif
<|endoftext|>


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

#include "chrome/browser/page_info_model.h"

#include <string>

#include "app/l10n_util.h"
#include "base/callback.h"
#include "base/i18n/time_formatting.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/cert_store.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/ssl/ssl_manager.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "net/base/cert_status_flags.h"
#include "net/base/x509_certificate.h"

namespace {
  // Returns a name that can be used to represent the issuer.  It tries in this
  // order CN, O and OU and returns the first non-empty one found.
  std::string GetIssuerName(const net::X509Certificate::Principal& issuer) {
    if (!issuer.common_name.empty())
      return issuer.common_name;
    if (!issuer.organization_names.empty())
      return issuer.organization_names[0];
    if (!issuer.organization_unit_names.empty())
      return issuer.organization_unit_names[0];

    return std::string();
  }
}

PageInfoModel::PageInfoModel(Profile* profile,
                             const GURL& url,
                             const NavigationEntry::SSLStatus& ssl,
                             bool show_history,
                             PageInfoModelObserver* observer)
    : observer_(observer) {
  bool state = true;
  string16 head_line;
  string16 description;
  scoped_refptr<net::X509Certificate> cert;

  // Identity section.
  string16 subject_name(UTF8ToUTF16(url.host()));
  bool empty_subject_name = false;
  if (subject_name.empty()) {
    subject_name.assign(
        l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
    empty_subject_name = true;
  }
  if (ssl.cert_id() &&
      CertStore::GetSharedInstance()->RetrieveCert(ssl.cert_id(), &cert) &&
      !net::IsCertStatusError(ssl.cert_status())) {
    // OK HTTPS page.
    if ((ssl.cert_status() & net::CERT_STATUS_IS_EV) != 0) {
      DCHECK(!cert->subject().organization_names.empty());
      head_line =
          l10n_util::GetStringFUTF16(IDS_PAGE_INFO_EV_IDENTITY_TITLE,
              UTF8ToUTF16(cert->subject().organization_names[0]),
              UTF8ToUTF16(url.host()));
      // An EV Cert is required to have a city (localityName) and country but
      // state is "if any".
      DCHECK(!cert->subject().locality_name.empty());
      DCHECK(!cert->subject().country_name.empty());
      string16 locality;
      if (!cert->subject().state_or_province_name.empty()) {
        locality = l10n_util::GetStringFUTF16(
            IDS_PAGEINFO_ADDRESS,
            UTF8ToUTF16(cert->subject().locality_name),
            UTF8ToUTF16(cert->subject().state_or_province_name),
            UTF8ToUTF16(cert->subject().country_name));
      } else {
        locality = l10n_util::GetStringFUTF16(
            IDS_PAGEINFO_PARTIAL_ADDRESS,
            UTF8ToUTF16(cert->subject().locality_name),
            UTF8ToUTF16(cert->subject().country_name));
      }
      DCHECK(!cert->subject().organization_names.empty());
      description.assign(l10n_util::GetStringFUTF16(
          IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV,
          UTF8ToUTF16(cert->subject().organization_names[0]),
          locality,
          UTF8ToUTF16(GetIssuerName(cert->issuer()))));
    } else {
      // Non EV OK HTTPS.
      if (empty_subject_name)
        head_line.clear();  // Don't display any title.
      else
        head_line.assign(subject_name);
      string16 issuer_name(UTF8ToUTF16(GetIssuerName(cert->issuer())));
      if (issuer_name.empty()) {
        issuer_name.assign(l10n_util::GetStringUTF16(
            IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
      } else {
        description.assign(l10n_util::GetStringFUTF16(
            IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, issuer_name));
      }
    }
  } else {
    // Bad HTTPS.
    description.assign(l10n_util::GetStringUTF16(
        IDS_PAGE_INFO_SECURITY_TAB_INSECURE_IDENTITY));
    state = false;
  }
  sections_.push_back(SectionInfo(
      state,
      l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_IDENTITY_TITLE),
      head_line,
      description));

  // Connection section.
  // We consider anything less than 80 bits encryption to be weak encryption.
  // TODO(wtc): Bug 1198735: report mixed/unsafe content for unencrypted and
  // weakly encrypted connections.
  state = true;
  head_line.clear();
  description.clear();
  if (ssl.security_bits() <= 0) {
    state = false;
    description.assign(l10n_util::GetStringFUTF16(
        IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT,
        subject_name));
  } else if (ssl.security_bits() < 80) {
    state = false;
    description.assign(l10n_util::GetStringFUTF16(
        IDS_PAGE_INFO_SECURITY_TAB_WEAK_ENCRYPTION_CONNECTION_TEXT,
        subject_name));
  } else {
    description.assign(l10n_util::GetStringFUTF16(
        IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_CONNECTION_TEXT,
        subject_name,
        IntToString16(ssl.security_bits())));
    if (ssl.displayed_insecure_content() || ssl.ran_insecure_content()) {
      state = false;
      description.assign(l10n_util::GetStringFUTF16(
          IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_SENTENCE_LINK,
          description,
          l10n_util::GetStringUTF16(ssl.ran_insecure_content() ?
              IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_ERROR :
              IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_WARNING)));
    }
  }
  sections_.push_back(SectionInfo(
      state,
      l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_CONNECTION_TITLE),
      head_line,
      description));

  // Request the number of visits.
  HistoryService* history = profile->GetHistoryService(
      Profile::EXPLICIT_ACCESS);
  if (show_history && history) {
    history->GetVisitCountToHost(
        url,
        &request_consumer_,
        NewCallback(this, &PageInfoModel::OnGotVisitCountToHost));
  }
}

int PageInfoModel::GetSectionCount() {
  return sections_.size();
}

PageInfoModel::SectionInfo PageInfoModel::GetSectionInfo(int index) {
  DCHECK(index < static_cast<int>(sections_.size()));
  return sections_[index];
}

void PageInfoModel::OnGotVisitCountToHost(HistoryService::Handle handle,
                                          bool found_visits,
                                          int count,
                                          base::Time first_visit) {
  if (!found_visits) {
    // This indicates an error, such as the page wasn't http/https; do nothing.
    return;
  }

  bool visited_before_today = false;
  if (count) {
    base::Time today = base::Time::Now().LocalMidnight();
    base::Time first_visit_midnight = first_visit.LocalMidnight();
    visited_before_today = (first_visit_midnight < today);
  }

  if (!visited_before_today) {
    sections_.push_back(SectionInfo(
        false,
        l10n_util::GetStringUTF16(
            IDS_PAGE_INFO_SECURITY_TAB_PERSONAL_HISTORY_TITLE),
        string16(),
        l10n_util::GetStringUTF16(
            IDS_PAGE_INFO_SECURITY_TAB_FIRST_VISITED_TODAY)));
  } else {
    sections_.push_back(SectionInfo(
        true,
        l10n_util::GetStringUTF16(
            IDS_PAGE_INFO_SECURITY_TAB_PERSONAL_HISTORY_TITLE),
        string16(),
        l10n_util::GetStringFUTF16(
            IDS_PAGE_INFO_SECURITY_TAB_VISITED_BEFORE_TODAY,
            WideToUTF16(base::TimeFormatShortDate(first_visit)))));
  }
  observer_->ModelChanged();
}

// static
void PageInfoModel::RegisterPrefs(PrefService* prefs) {
  prefs->RegisterDictionaryPref(prefs::kPageInfoWindowPlacement);
}
<commit_msg>Trivial change: update a comment.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/page_info_model.h"

#include <string>

#include "app/l10n_util.h"
#include "base/callback.h"
#include "base/i18n/time_formatting.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/cert_store.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/ssl/ssl_manager.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "net/base/cert_status_flags.h"
#include "net/base/x509_certificate.h"

namespace {
  // Returns a name that can be used to represent the issuer.  It tries in this
  // order CN, O and OU and returns the first non-empty one found.
  std::string GetIssuerName(const net::X509Certificate::Principal& issuer) {
    if (!issuer.common_name.empty())
      return issuer.common_name;
    if (!issuer.organization_names.empty())
      return issuer.organization_names[0];
    if (!issuer.organization_unit_names.empty())
      return issuer.organization_unit_names[0];

    return std::string();
  }
}

PageInfoModel::PageInfoModel(Profile* profile,
                             const GURL& url,
                             const NavigationEntry::SSLStatus& ssl,
                             bool show_history,
                             PageInfoModelObserver* observer)
    : observer_(observer) {
  bool state = true;
  string16 head_line;
  string16 description;
  scoped_refptr<net::X509Certificate> cert;

  // Identity section.
  string16 subject_name(UTF8ToUTF16(url.host()));
  bool empty_subject_name = false;
  if (subject_name.empty()) {
    subject_name.assign(
        l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
    empty_subject_name = true;
  }
  if (ssl.cert_id() &&
      CertStore::GetSharedInstance()->RetrieveCert(ssl.cert_id(), &cert) &&
      !net::IsCertStatusError(ssl.cert_status())) {
    // OK HTTPS page.
    if ((ssl.cert_status() & net::CERT_STATUS_IS_EV) != 0) {
      DCHECK(!cert->subject().organization_names.empty());
      head_line =
          l10n_util::GetStringFUTF16(IDS_PAGE_INFO_EV_IDENTITY_TITLE,
              UTF8ToUTF16(cert->subject().organization_names[0]),
              UTF8ToUTF16(url.host()));
      // An EV Cert is required to have a city (localityName) and country but
      // state is "if any".
      DCHECK(!cert->subject().locality_name.empty());
      DCHECK(!cert->subject().country_name.empty());
      string16 locality;
      if (!cert->subject().state_or_province_name.empty()) {
        locality = l10n_util::GetStringFUTF16(
            IDS_PAGEINFO_ADDRESS,
            UTF8ToUTF16(cert->subject().locality_name),
            UTF8ToUTF16(cert->subject().state_or_province_name),
            UTF8ToUTF16(cert->subject().country_name));
      } else {
        locality = l10n_util::GetStringFUTF16(
            IDS_PAGEINFO_PARTIAL_ADDRESS,
            UTF8ToUTF16(cert->subject().locality_name),
            UTF8ToUTF16(cert->subject().country_name));
      }
      DCHECK(!cert->subject().organization_names.empty());
      description.assign(l10n_util::GetStringFUTF16(
          IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV,
          UTF8ToUTF16(cert->subject().organization_names[0]),
          locality,
          UTF8ToUTF16(GetIssuerName(cert->issuer()))));
    } else {
      // Non EV OK HTTPS.
      if (empty_subject_name)
        head_line.clear();  // Don't display any title.
      else
        head_line.assign(subject_name);
      string16 issuer_name(UTF8ToUTF16(GetIssuerName(cert->issuer())));
      if (issuer_name.empty()) {
        issuer_name.assign(l10n_util::GetStringUTF16(
            IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
      } else {
        description.assign(l10n_util::GetStringFUTF16(
            IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY, issuer_name));
      }
    }
  } else {
    // HTTP or bad HTTPS.
    description.assign(l10n_util::GetStringUTF16(
        IDS_PAGE_INFO_SECURITY_TAB_INSECURE_IDENTITY));
    state = false;
  }
  sections_.push_back(SectionInfo(
      state,
      l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_IDENTITY_TITLE),
      head_line,
      description));

  // Connection section.
  // We consider anything less than 80 bits encryption to be weak encryption.
  // TODO(wtc): Bug 1198735: report mixed/unsafe content for unencrypted and
  // weakly encrypted connections.
  state = true;
  head_line.clear();
  description.clear();
  if (ssl.security_bits() <= 0) {
    state = false;
    description.assign(l10n_util::GetStringFUTF16(
        IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT,
        subject_name));
  } else if (ssl.security_bits() < 80) {
    state = false;
    description.assign(l10n_util::GetStringFUTF16(
        IDS_PAGE_INFO_SECURITY_TAB_WEAK_ENCRYPTION_CONNECTION_TEXT,
        subject_name));
  } else {
    description.assign(l10n_util::GetStringFUTF16(
        IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_CONNECTION_TEXT,
        subject_name,
        IntToString16(ssl.security_bits())));
    if (ssl.displayed_insecure_content() || ssl.ran_insecure_content()) {
      state = false;
      description.assign(l10n_util::GetStringFUTF16(
          IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_SENTENCE_LINK,
          description,
          l10n_util::GetStringUTF16(ssl.ran_insecure_content() ?
              IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_ERROR :
              IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_INSECURE_CONTENT_WARNING)));
    }
  }
  sections_.push_back(SectionInfo(
      state,
      l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_CONNECTION_TITLE),
      head_line,
      description));

  // Request the number of visits.
  HistoryService* history = profile->GetHistoryService(
      Profile::EXPLICIT_ACCESS);
  if (show_history && history) {
    history->GetVisitCountToHost(
        url,
        &request_consumer_,
        NewCallback(this, &PageInfoModel::OnGotVisitCountToHost));
  }
}

int PageInfoModel::GetSectionCount() {
  return sections_.size();
}

PageInfoModel::SectionInfo PageInfoModel::GetSectionInfo(int index) {
  DCHECK(index < static_cast<int>(sections_.size()));
  return sections_[index];
}

void PageInfoModel::OnGotVisitCountToHost(HistoryService::Handle handle,
                                          bool found_visits,
                                          int count,
                                          base::Time first_visit) {
  if (!found_visits) {
    // This indicates an error, such as the page wasn't http/https; do nothing.
    return;
  }

  bool visited_before_today = false;
  if (count) {
    base::Time today = base::Time::Now().LocalMidnight();
    base::Time first_visit_midnight = first_visit.LocalMidnight();
    visited_before_today = (first_visit_midnight < today);
  }

  if (!visited_before_today) {
    sections_.push_back(SectionInfo(
        false,
        l10n_util::GetStringUTF16(
            IDS_PAGE_INFO_SECURITY_TAB_PERSONAL_HISTORY_TITLE),
        string16(),
        l10n_util::GetStringUTF16(
            IDS_PAGE_INFO_SECURITY_TAB_FIRST_VISITED_TODAY)));
  } else {
    sections_.push_back(SectionInfo(
        true,
        l10n_util::GetStringUTF16(
            IDS_PAGE_INFO_SECURITY_TAB_PERSONAL_HISTORY_TITLE),
        string16(),
        l10n_util::GetStringFUTF16(
            IDS_PAGE_INFO_SECURITY_TAB_VISITED_BEFORE_TODAY,
            WideToUTF16(base::TimeFormatShortDate(first_visit)))));
  }
  observer_->ModelChanged();
}

// static
void PageInfoModel::RegisterPrefs(PrefService* prefs) {
  prefs->RegisterDictionaryPref(prefs::kPageInfoWindowPlacement);
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "EndingScene.h"
#include "ConstVars.h"
#include "FileStuff.h"
#include "StageScene.h"
#include "SimpleAudioEngine.h"

Scene* EndingScene::createScene()
{
	Scene* scene = Scene::create();

	Layer* layer = EndingScene::create();
	scene->addChild(layer);

	return scene;
}

bool EndingScene::init()
{

	if (!Layer::init())
	{
		return false;
	}

	Sequence* seq = Sequence::create(
	DelayTime::create(2.0f),

 	CallFuncN::create(CC_CALLBACK_0(EndingScene::ShowCrashingScene, this)),
 	DelayTime::create(9.0f),

 	CallFuncN::create(CC_CALLBACK_0(EndingScene::ShowAfterCrash, this)),
 	DelayTime::create(4.5f),

	CallFuncN::create(CC_CALLBACK_0(EndingScene::ShowWhiteScene, this)),
	DelayTime::create(3.0f),

	CallFuncN::create(CC_CALLBACK_0(EndingScene::ShowHospital, this)),

	nullptr);

	runAction(seq);
	return true;
}

void EndingScene::ShowCrashingScene()
{
	removeAllChildrenWithCleanup(true);

	CallFunc* nodding1 = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BEFORE_CRASHING_0));
	CallFunc* nodding2 = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BEFORE_CRASHING_1));
	CallFunc* crashingSound = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeSoundEffect, this, FileStuff::SOUND_CRASH));
	CallFunc* crashing1 = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BEFORE_CRASHING_2));
	CallFunc* crashing2 = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BEFORE_CRASHING_3));
//	CallFunc* blackout = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BLACKOUT));

	Sequence* seq = Sequence::create(
		crashingSound,
		nodding1,
		DelayTime::create(2.0f),
		nodding2,
		DelayTime::create(1.0f),
		nodding1,
		DelayTime::create(2.0f),
		nodding2,
		DelayTime::create(1.5f),
		crashing1,
		DelayTime::create(0.2f),
		crashing2,
		DelayTime::create(1.2f),
//		blackout,
		nullptr
		);

	runAction(seq);
}

void EndingScene::ChangeSoundEffect(const char* sound)
{
	CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(sound, false);
}

void EndingScene::ShowAfterCrash()
{
	m_background = Sprite::create(FileStuff::AFTER_CRASHED);
	float scale = (Director::getInstance()->getVisibleSize().width) / (m_background->getContentSize().width);
	m_background->setAnchorPoint(Point::ZERO);
	m_background->setScale(scale);
	addChild(m_background);
}

void EndingScene::ChangeBackgroundImg(string bgImg)
{
	removeAllChildren();
	m_background = Sprite::create(bgImg);

	float scale = (Director::getInstance()->getVisibleSize().width) / (m_background->getContentSize().width);
	m_background->setAnchorPoint(Point::ZERO);
	m_background->setScale(scale);
	m_background->setName("background");
	addChild(m_background);

}

void EndingScene::AddMonitor()
{
	Sprite* monitor = Sprite::create(FileStuff::MONITOR);

	monitor->setPosition(Vec2(130, 335));
	monitor->setScale(2.0f);

	monitor->setName("monitor");
	addChild(monitor);
}

void EndingScene::FadeOut()
{
	removeAllChildren();

	m_background = Sprite::create(FileStuff::HOSPITAL_WAKED);

	float scale = (Director::getInstance()->getVisibleSize().width) / (m_background->getContentSize().width);
	m_background->setAnchorPoint(Point::ZERO);
	m_background->setScale(scale);
	addChild(m_background);

	Sprite* monitor = Sprite::create(FileStuff::MONITOR);
	addChild(monitor);

	monitor->setScale(2.0f);
	monitor->setPosition(Vec2(130, 335));

	m_background->runAction(
		Sequence::create(
		FadeOut::create(12.0f),
		nullptr
		)
	);

	monitor->runAction(
		Sequence::create(
		FadeOut::create(5.0f),
		nullptr)
		);
}

void EndingScene::ShowHospital()
{
	CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(FileStuff::SOUND_EAR_RINGING, false, 3.0f);

	m_background = Sprite::create(FileStuff::HOSPITAL_CLOSED_EYE);
	float scale = (Director::getInstance()->getVisibleSize().width) / (m_background->getContentSize().width);
	m_background->setAnchorPoint(Point::ZERO);
	m_background->setScale(scale);
	addChild(m_background);
	m_background->setOpacity(0);

	m_background->runAction(
		Sequence::create(
		DelayTime::create(5.0f),
		FadeIn::create(5.0f),
		nullptr)
		);

	Sequence* standing = Sequence::create(
		DelayTime::create(12.0f),
		CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::HOSPITAL_OPEN_EYE)),
		CallFunc::create(CC_CALLBACK_0(EndingScene::AddMonitor, this)),
		DelayTime::create(1.0f),
		CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::HOSPITAL_WAKING)),
		CallFunc::create(CC_CALLBACK_0(EndingScene::AddMonitor, this)),
		DelayTime::create(0.5f),
		CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::HOSPITAL_WAKED)),
		CallFunc::create(CC_CALLBACK_0(EndingScene::AddMonitor, this)),
		DelayTime::create(3.0f),
		CallFunc::create(CC_CALLBACK_0(EndingScene::FadeOut, this)),
		nullptr
		);

	runAction(standing);

	Sprite* monitor = Sprite::create(FileStuff::MONITOR);
	addChild(monitor);

	monitor->setScale(2.0f);
	monitor->setPosition(Vec2(130, 335));
	monitor->setOpacity(0);

	monitor->runAction(
		FadeIn::create(2.0f)
		);
}

void EndingScene::ShowWhiteScene()
{
	removeAllChildrenWithCleanup(true);
	Sprite* white = Sprite::create(FileStuff::WHITE);
	float scale = (Director::getInstance()->getVisibleSize().width) / (white->getContentSize().width);
	white->setAnchorPoint(Point::ZERO);
	white->setScale(scale);
	white->runAction(FadeOut::create(1.5f));
	addChild(white);
}

void EndingScene::RemoveAllChildren()
{
	removeAllChildren();
}
<commit_msg>Add one second between dead body and crashing<commit_after>#include "stdafx.h"
#include "EndingScene.h"
#include "ConstVars.h"
#include "FileStuff.h"
#include "StageScene.h"
#include "SimpleAudioEngine.h"

Scene* EndingScene::createScene()
{
	Scene* scene = Scene::create();

	Layer* layer = EndingScene::create();
	scene->addChild(layer);

	return scene;
}

bool EndingScene::init()
{

	if (!Layer::init())
	{
		return false;
	}

	Sequence* seq = Sequence::create(
	DelayTime::create(2.0f),

 	CallFuncN::create(CC_CALLBACK_0(EndingScene::ShowCrashingScene, this)),
 	DelayTime::create(9.0f),

 	CallFuncN::create(CC_CALLBACK_0(EndingScene::ShowAfterCrash, this)),
 	DelayTime::create(7.0f),

	CallFuncN::create(CC_CALLBACK_0(EndingScene::ShowWhiteScene, this)),
	DelayTime::create(3.0f),

	CallFuncN::create(CC_CALLBACK_0(EndingScene::ShowHospital, this)),

	nullptr);

	runAction(seq);
	return true;
}

void EndingScene::ShowCrashingScene()
{
	removeAllChildrenWithCleanup(true);

	CallFunc* nodding1 = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BEFORE_CRASHING_0));
	CallFunc* nodding2 = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BEFORE_CRASHING_1));
	CallFunc* crashingSound = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeSoundEffect, this, FileStuff::SOUND_CRASH));
	CallFunc* crashing1 = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BEFORE_CRASHING_2));
	CallFunc* crashing2 = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BEFORE_CRASHING_3));
//	CallFunc* blackout = CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::BLACKOUT));

	Sequence* seq = Sequence::create(
		crashingSound,
		nodding1,
		DelayTime::create(2.0f),
		nodding2,
		DelayTime::create(1.0f),
		nodding1,
		DelayTime::create(2.0f),
		nodding2,
		DelayTime::create(1.5f),
		crashing1,
		DelayTime::create(0.2f),
		crashing2,
		DelayTime::create(1.2f),
//		blackout,
		nullptr
		);

	runAction(seq);
}

void EndingScene::ChangeSoundEffect(const char* sound)
{
	CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(sound, false);
}

void EndingScene::ShowAfterCrash()
{
	m_background = Sprite::create(FileStuff::AFTER_CRASHED);
	float scale = (Director::getInstance()->getVisibleSize().width) / (m_background->getContentSize().width);
	m_background->setAnchorPoint(Point::ZERO);
	m_background->setScale(scale);
	addChild(m_background);
}

void EndingScene::ChangeBackgroundImg(string bgImg)
{
	removeAllChildren();
	m_background = Sprite::create(bgImg);

	float scale = (Director::getInstance()->getVisibleSize().width) / (m_background->getContentSize().width);
	m_background->setAnchorPoint(Point::ZERO);
	m_background->setScale(scale);
	m_background->setName("background");
	addChild(m_background);

}

void EndingScene::AddMonitor()
{
	Sprite* monitor = Sprite::create(FileStuff::MONITOR);

	monitor->setPosition(Vec2(130, 335));
	monitor->setScale(2.0f);

	monitor->setName("monitor");
	addChild(monitor);
}

void EndingScene::FadeOut()
{
	removeAllChildren();

	m_background = Sprite::create(FileStuff::HOSPITAL_WAKED);

	float scale = (Director::getInstance()->getVisibleSize().width) / (m_background->getContentSize().width);
	m_background->setAnchorPoint(Point::ZERO);
	m_background->setScale(scale);
	addChild(m_background);

	Sprite* monitor = Sprite::create(FileStuff::MONITOR);
	addChild(monitor);

	monitor->setScale(2.0f);
	monitor->setPosition(Vec2(130, 335));

	m_background->runAction(
		Sequence::create(
		FadeOut::create(12.0f),
		nullptr
		)
	);

	monitor->runAction(
		Sequence::create(
		FadeOut::create(5.0f),
		nullptr)
		);
}

void EndingScene::ShowHospital()
{
	CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(FileStuff::SOUND_EAR_RINGING, false, 3.0f);

	m_background = Sprite::create(FileStuff::HOSPITAL_CLOSED_EYE);
	float scale = (Director::getInstance()->getVisibleSize().width) / (m_background->getContentSize().width);
	m_background->setAnchorPoint(Point::ZERO);
	m_background->setScale(scale);
	addChild(m_background);
	m_background->setOpacity(0);

	m_background->runAction(
		Sequence::create(
		DelayTime::create(5.0f),
		FadeIn::create(5.0f),
		nullptr)
		);

	Sequence* standing = Sequence::create(
		DelayTime::create(12.0f),
		CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::HOSPITAL_OPEN_EYE)),
		CallFunc::create(CC_CALLBACK_0(EndingScene::AddMonitor, this)),
		DelayTime::create(1.0f),
		CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::HOSPITAL_WAKING)),
		CallFunc::create(CC_CALLBACK_0(EndingScene::AddMonitor, this)),
		DelayTime::create(0.5f),
		CallFunc::create(CC_CALLBACK_0(EndingScene::ChangeBackgroundImg, this, FileStuff::HOSPITAL_WAKED)),
		CallFunc::create(CC_CALLBACK_0(EndingScene::AddMonitor, this)),
		DelayTime::create(3.0f),
		CallFunc::create(CC_CALLBACK_0(EndingScene::FadeOut, this)),
		nullptr
		);

	runAction(standing);

	Sprite* monitor = Sprite::create(FileStuff::MONITOR);
	addChild(monitor);

	monitor->setScale(2.0f);
	monitor->setPosition(Vec2(130, 335));
	monitor->setOpacity(0);

	monitor->runAction(
		FadeIn::create(2.0f)
		);
}

void EndingScene::ShowWhiteScene()
{
	removeAllChildrenWithCleanup(true);
	Sprite* white = Sprite::create(FileStuff::WHITE);
	float scale = (Director::getInstance()->getVisibleSize().width) / (white->getContentSize().width);
	white->setAnchorPoint(Point::ZERO);
	white->setScale(scale);
	white->runAction(FadeOut::create(1.5f));
	addChild(white);
}

void EndingScene::RemoveAllChildren()
{
	removeAllChildren();
}
<|endoftext|>


<commit_before>#pragma once

namespace kitrokopter {

class API {

	public:

		API();

		/* Quadcopter mutation */
		APIQuadcopter getQuadcopter(int id);
		void removeQuadcopter(int id);

		/* Formation */
		void setFormation(APIFormation formation);
		APIFormation getFormation();

		/* Cameras */
		APICameraSystem getCameraSystem();
		APICamera[] getCameras();
		APICamera[] getCalibratedCameras();
		APICamera[] getUncalibratedCameras();
		int getCameraAmount();
		int getCalibratedCameraAmount();
		int getUncalibratedCameraAmount();

		/* Quadcopter getters */
		APIQuadcopter[] getQuadcopters();
		APIQuadcopter[] getQuadcoptersFlying();
		APIQuadcopter[] getQuadcoptersOnGround();
		APIQuadcopter[] getQuadcoptersTracked();
		APIQuadcopter[] getQuadcoptersUntracked();
		APIQuadcopter[] getQuadcoptersInFormation();
		APIQuadcopter[] getQuadcoptersNotInFormation();

		/* Quadcopter amount */
		int getQuadcopterAmount();
		int getQuadcoptersFlyingAmount();
		int getQuadcoptersOnGroundAmount();
		int getQuadcoptersTrackedAmount();
		int getQuadcoptersUntrackedAmount();
		int getQuadcoptersInFormationAmount();
		int getQuadcoptersNotInFormationAmount();

		/* message listeners */
		void addMessageListener(APIMessageListener);
		void removeMessageListener(APIMessageListener);

		/* Launch / Land */
		void launchQuadcopters(int height);
		double getLaunchProgress();
		bool quadcoptersLaunched();
		void landQuadcopters();

		void shutdownSystem();

		/* Settings */
		Cuboid getMaximumOperatingArea();
		bool setOperatingArea(Cuboid);
		int getMaximumHorizontalSpeed();
		int getMaximumVerticalSpeed();
		int getMaximumHorizontalAcceleration();
		int getMaximumVerticalAcceleration();
		void setReceiveTargetMovementData(bool);
		void setReceiveActualMovementData(bool);
		void setReceiveQuadcopterState(bool);

		/* Movement */
		void moveFormation(Vector);
		void rotateFormation(Vector);

};

}
<commit_msg>Use std::vector instead of C arrays<commit_after>#pragma once

#include <vector>

namespace kitrokopter {

class API {

	public:

		API();

		/* Quadcopter mutation */
		APIQuadcopter getQuadcopter(int id);
		void removeQuadcopter(int id);

		/* Formation */
		void setFormation(APIFormation formation);
		APIFormation getFormation();

		/* Cameras */
		APICameraSystem getCameraSystem();
		std::vector<APICamera> getCameras();
		std::vector<APICamera> getCalibratedCameras();
		std::vector<APICamera> getUncalibratedCameras();
		int getCameraAmount();
		int getCalibratedCameraAmount();
		int getUncalibratedCameraAmount();

		/* Quadcopter getters */
		std::vector<APIQuadcopter> getQuadcopters();
		std::vector<APIQuadcopter> getQuadcoptersFlying();
		std::vector<APIQuadcopter> getQuadcoptersOnGround();
		std::vector<APIQuadcopter> getQuadcoptersTracked();
		std::vector<APIQuadcopter> getQuadcoptersUntracked();
		std::vector<APIQuadcopter> getQuadcoptersInFormation();
		std::vector<APIQuadcopter> getQuadcoptersNotInFormation();

		/* Quadcopter amount */
		int getQuadcopterAmount();
		int getQuadcoptersFlyingAmount();
		int getQuadcoptersOnGroundAmount();
		int getQuadcoptersTrackedAmount();
		int getQuadcoptersUntrackedAmount();
		int getQuadcoptersInFormationAmount();
		int getQuadcoptersNotInFormationAmount();

		/* message listeners */
		void addMessageListener(APIMessageListener);
		void removeMessageListener(APIMessageListener);

		/* Launch / Land */
		void launchQuadcopters(int height);
		double getLaunchProgress();
		bool quadcoptersLaunched();
		void landQuadcopters();

		void shutdownSystem();

		/* Settings */
		Cuboid getMaximumOperatingArea();
		bool setOperatingArea(Cuboid);
		int getMaximumHorizontalSpeed();
		int getMaximumVerticalSpeed();
		int getMaximumHorizontalAcceleration();
		int getMaximumVerticalAcceleration();
		void setReceiveTargetMovementData(bool);
		void setReceiveActualMovementData(bool);
		void setReceiveQuadcopterState(bool);

		/* Movement */
		void moveFormation(Vector);
		void rotateFormation(Vector);

};

}
<|endoftext|>


<commit_before>#include <exodus/program.h>
programinit()

var verbose;
var dictfilename;
var dictfile;
var dictrec;

function main() {

	// Syntax:
	// dict2sql {filename {dictid}} {V}

	// 1. Creates pgsql functions to calculate columns given data and key
	//
	// functions like "dict_filename_DICT_ID(key,data)" returns text
	// /df
	// List of functions
	// Schema | Name | Result data type | Argument data types | Type
	// -------+---------------------------+--------------------+---------------------+--------
	// public | dict_ads_brand_and_date | text | key text, data text | normal
	// ...

	// NOTE: Multivalued pgsql dictionary functions currently should be written to calculate
	// and return ALL multivalues (as if MV=0) since currently exodus never requests postgres
	// to call a dict functions to get a specific mv.
	// If in future MV is required, then dict function arguments will probably become (key,data,mv)

	// 2. Creates dict_all file which represents all dictionary files and their items in one file
	//
	// only performed when filename is omitted
	//
	// see "listdict all"

	// 3. Creates various exodus pgsql utility functions
	//
	// only performed when filename is omitted
	//
	// /df
	// List of functions
	// Schema | Name | Result data type | Argument data types | Type
	// -------+---------------------------+--------------------+---------------------+--------
	// public | exodus_count | integer | text, text | normal
	// public | exodus_trim | text | data text
	// ...

	//TODO work on more than the default db connection

	var filenames=COMMAND.a(2).lcase();
	var dictid=COMMAND.a(3);
	verbose=index(OPTIONS,'V');
	var doall = true;

	if (filenames)
	{
		doall = false;
		if (filenames.substr(1,5) ne "dict_")
			filenames.splicer(1,0,"dict_");
	}
	else
		filenames=var().listfiles();

	//create global view of all dicts in "dict_all"
	var viewsql="";
	if (doall)
		viewsql ^= "CREATE MATERIALIZED VIEW dict_all AS\n";

	//do one or many/all files
	int nfiles=dcount(filenames,FM);
	for (int filen=1;filen<=nfiles;++filen)
		onefile(filenames.a(filen),dictid,viewsql);

	//quit if not doing all files
	/////////////////////////////
	if (!doall)
		return 0;

	//create dict_all file

	//ignore error if doesnt exist
	if (not var().sqlexec("DROP MATERIALIZED VIEW dict_all"))
		var().sqlexec("DROP VIEW dict_all");

	viewsql.splicer(-6,6,"");//remove trailing "UNION" word
	var errmsg;
	if (verbose)
		viewsql.output("SQL:");
	if (var().sqlexec(viewsql,errmsg))
		printl("dict_all file created");
	else {
		if (not verbose)
			viewsql.outputl("SQL:");
		errmsg.outputl("Error:");
	}

	//create exodus pgsql functions

	var sqltemplate=
R"V0G0N(
CREATE OR REPLACE FUNCTION
$functionname_and_args
RETURNS text
AS
$$
BEGIN
$sqlcode
END;
$$
LANGUAGE 'plpgsql'
IMMUTABLE
SECURITY
DEFINER
COST 10;
)V0G0N";

	//exodus_trim
	var trimsql=R"(return regexp_replace(regexp_replace(data, '^\s+|\s+$', '', 'g'),'\s{2,}',' ','g');)";
	do_sql("exodus_trim(data text)",trimsql,sqltemplate);

	//exodus_field_remove
	var removesql=
R"V0G0N(
DECLARE
 charn int;
 nchars int;
 currfieldn int;
 ans text;

BEGIN

 if fieldno<=0 then
  if fieldno=0 then
   return '';
  end if;
  return data;
 end if;

 ans := '';
 currfieldn :=1;
 nchars := length(data);
 for charn in 1..nchars loop

  if substr(data,charn,1) = sep then

   currfieldn=currfieldn+1;

   if currfieldn=fieldno then
    ans := substr(data,1,charn-1);

   elseif currfieldn>fieldno then
    if ans<>'' then
     ans := ans || sep || substr(data,charn+1);
    else
     ans := substr(data,charn+1);
    end if;
    return ans;
   end if;

  end if;

 end loop;

 -- deleting beyond the number of existing fields
 if currfieldn<fieldno then
  return data;
  end if;

 return ans;

END;
)V0G0N";

	do_sql("exodus_field_remove(data text, sep text, fieldno int)",removesql,sqltemplate);

	return 0;
}

subroutine do_sql(in functionname_and_args, in sql, in sqltemplate) {

	functionname_and_args.outputl();

	var functionsql=sqltemplate;

	functionsql.swapper("$functionname_and_args",functionname_and_args);

	functionsql.swapper("$sqlcode",sql);

	if (verbose)
		functionsql.outputl();

	var errmsg;
	var().sqlexec(functionsql,errmsg);

	if (errmsg) {
		if (not verbose) {
			//functionsql.outputl();
			int nlines=count(functionsql,"\n");
			for (int linen=1;linen<=nlines;++linen) {
				printl(linen-2+2,". ", field(functionsql,"\n",linen) );
			}
			outputl();
		}
		errmsg.outputl();
	}
	return;
}

subroutine onefile(in dictfilename, in reqdictid, io viewsql) {

	if (dictfilename.substr(1,5) ne "dict_")
		return;

	if (!open(dictfilename,dictfile)) {
		call fsmsg();
		abort();
	}

	if (reqdictid)
		makelist("",reqdictid);
	else
		select(dictfilename);

	var dictid;
	while (readnext(dictid)) {
		onedictid(dictfilename, dictid, reqdictid);
	}

	if (viewsql) {
		viewsql ^= "SELECT '" ^ dictfilename.substr(6).ucase() ^ "'||'*'||key as key, data\n";
		viewsql ^= "FROM " ^ dictfilename ^ "\n";
		viewsql ^= "UNION\n";
	}

	return;
}

subroutine onedictid(in dictfilename, io dictid, in reqdictid) {

	//get the dict source code
	var dictrec;
	if (not dictrec.read(dictfile,dictid)) {
		dictid.ucaser();
		if (!dictrec.read(dictfile,dictid))
			stop(quote(dictid)^" cannot be read in "^quote(dictfilename));
	}
	var sourcecode=dictrec.a(8);
	var ismv=dictrec.a(4)[1]=="M";

	//remove anything before sql code
	var pos=index(sourcecode,"/" "*pgsql");
	if (!pos) {
		if (reqdictid)
			stop(quote(dictfilename)^" "^quote(dictid)^" does not have any pgsql section");
		return;
	}
	var sql=sourcecode.substr(pos+8);

	//printl(dictfilename, " ",dictid, " > sql");

	//should take everything up to the end ??
	//so pgsql comments like /* */ are respected ??
	//remove anything after sql code
	//find the LAST * /  pair and remove everything after it
	var lastpos=0;
	for (int ii=1;;++ii) {
		//find the ii'th * / terminator
		pos=index(sql,"*" "/",ii);
		if (!pos)
			break;
		lastpos=pos;
	}
	if (lastpos)
		sql.splicer(lastpos-1,"");

	var xlatetemplate;
	if (ismv)
		xlatetemplate=
R"V0G0N(
$RETVAR := array_to_string
(
 array
 (
  SELECT
    $TARGET_EXPR
   FROM
    unnest
    (
     string_to_array($SOURCEKEY_EXPR,chr(29))
    )
   LEFT JOIN
    $TARGETFILE on $TARGETFILE.key = unnest
 ),
 chr(29),
 ''
);
)V0G0N";
		else
			xlatetemplate=
R"V0G0N(
$RETVAR :=
  $TARGET_EXPR
  FROM $TARGETFILE
  WHERE $TARGETFILE.key=$SOURCEKEY_EXPR;
  $RETVAR := coalesce($RETVAR,'');
)V0G0N";

	// expand lines like the following to sql
	// (all spaces are MANDATORY)
	// ans := xlate filename fromfn tofn
	// e.g.
	// xlate=xlate jobs 2 14
	// ->
	// ans:=split_part(jobs.data,chr(30),14)
	// FROM jobs
	// WHERE jobs.key=split_part($2,chr(30),2);
	//
	// fromfn and tofn can be functions
	// "from" expression has access to source file data in variable $2 (argument 2)
	// "to" expression has access to target file data eg invoices.data
	int nlines=dcount(sql,VM);
	for (int ln=1;ln<=nlines;++ln) {
		var line=sql.a(1,ln).trim();
		if (line.substr(1,2)!="--" && field(line," ",2,2) eq ":= xlate") {

			//line.outputl("xlate=");

			//eg ans
			var targetvariablename=line.field(" ",1);

			//target file name eg jobs
			var target_filename=line.field(" ",4);

			//source file field number or expression for key to target file
			var source_key_expr=line.field(" ",5);
			//if key field numeric then extract from source file date
			if (source_key_expr.isnum())
				source_key_expr="split_part($2,chr(30),"^source_key_expr^")";

			//target file field number or expression
			var target_expr=line.field(" ",6);
			if (target_expr.isnum())
				target_expr="split_part("^target_filename^".data,chr(30),"^target_expr^")";

			//line=targetvariablename^" := ";
			//if (ismv) {
			//	line^="array_to_string"
			//	"("
			//	" array"
			// " ("
			// " select ";
			//}
			//line^=target_expression;
			//line^="\n FROM "^target_filename;
			//line^="\n WHERE "^target_filename^".key="^source_key_expression^";";
			line=xlatetemplate;
			line.swapper("$RETVAR",targetvariablename);
			line.swapper("$TARGETFILE",target_filename);
			line.swapper("$SOURCEKEY_EXPR",source_key_expr);
			line.swapper("$TARGET_EXPR",target_expr);
			//line.outputl("sql=");

			sql.r(1,ln,line);
		}
	}

	//convert to text
	sql.trimmerf(VM).trimmerb(VM);
	sql.converter(VM,"\n");

	var sqltemplate=
R"V0G0N(CREATE OR REPLACE FUNCTION
 $functionname_and_args
 RETURNS text
 AS
 $$
  DECLARE
   ans text;
  BEGIN
$sqlcode
  RETURN ans;
  END;
 $$
 LANGUAGE 'plpgsql'
 IMMUTABLE
 SECURITY
 DEFINER
 COST 10;
 )V0G0N";

	//set the function name
	do_sql(dictfilename^"_"^dictid^"(key text, data text)",sql,sqltemplate);

}

programexit()
<commit_msg>exodus_field_replace(text sep fieldn), exodus_split(amountpluscurrcode)<commit_after>#include <exodus/program.h>
programinit()

var verbose;
var dictfilename;
var dictfile;
var dictrec;

function main() {

	// Syntax:
	// dict2sql {filename {dictid}} {V}

	// 1. Creates pgsql functions to calculate columns given data and key
	//
	// functions like "dict_filename_DICT_ID(key,data)" returns text
	// /df
	// List of functions
	// Schema | Name | Result data type | Argument data types | Type
	// -------+---------------------------+--------------------+---------------------+--------
	// public | dict_ads_brand_and_date | text | key text, data text | normal
	// ...

	// NOTE: Multivalued pgsql dictionary functions currently should be written to calculate
	// and return ALL multivalues (as if MV=0) since currently exodus never requests postgres
	// to call a dict functions to get a specific mv.
	// If in future MV is required, then dict function arguments will probably become (key,data,mv)

	// 2. Creates dict_all file which represents all dictionary files and their items in one file
	//
	// only performed when filename is omitted
	//
	// see "listdict all"

	// 3. Creates various exodus pgsql utility functions
	//
	// only performed when filename is omitted
	//
	// /df
	// List of functions
	// Schema | Name | Result data type | Argument data types | Type
	// -------+---------------------------+--------------------+---------------------+--------
	// public | exodus_count | integer | text, text | normal
	// public | exodus_trim | text | data text
	// ...

	//TODO work on more than the default db connection

	var filenames=COMMAND.a(2).lcase();
	var dictid=COMMAND.a(3);
	verbose=index(OPTIONS,'V');
	var doall = true;

	if (filenames)
	{
		doall = false;
		if (filenames.substr(1,5) ne "dict_")
			filenames.splicer(1,0,"dict_");
	}
	else
		filenames=var().listfiles();

	//create global view of all dicts in "dict_all"
	var viewsql="";
	if (doall)
		viewsql ^= "CREATE MATERIALIZED VIEW dict_all AS\n";

	//do one or many/all files
	int nfiles=dcount(filenames,FM);
	for (int filen=1;filen<=nfiles;++filen)
		onefile(filenames.a(filen),dictid,viewsql);

	//quit if not doing all files
	/////////////////////////////
	if (!doall)
		return 0;

	//create dict_all file

	//ignore error if doesnt exist
	if (not var().sqlexec("DROP MATERIALIZED VIEW dict_all"))
		var().sqlexec("DROP VIEW dict_all");

	viewsql.splicer(-6,6,"");//remove trailing "UNION" word
	var errmsg;
	if (verbose)
		viewsql.output("SQL:");
	if (var().sqlexec(viewsql,errmsg))
		printl("dict_all file created");
	else {
		if (not verbose)
			viewsql.outputl("SQL:");
		errmsg.outputl("Error:");
	}

	//create exodus pgsql functions

	var sqltemplate=
R"V0G0N(
CREATE OR REPLACE FUNCTION
$functionname_and_args
RETURNS text
AS
$$
BEGIN
$sqlcode
END;
$$
LANGUAGE 'plpgsql'
IMMUTABLE
SECURITY
DEFINER
COST 10;
)V0G0N";

	//exodus_trim
	var trimsql=R"(return regexp_replace(regexp_replace(data, '^\s+|\s+$', '', 'g'),'\s{2,}',' ','g');)";
	do_sql("exodus_trim(data text)",trimsql,sqltemplate);

	//exodus_field_replace
	do_sql("exodus_field_replace(data text, sep text, fieldno int, replacement text)",field_replace_sql,sqltemplate);

	//exodus_field_remove
	do_sql("exodus_field_remove(data text, sep text, fieldno int)",field_remove_sql,sqltemplate);

	//exodus_split
	do_sql("exodus_split(data text)",split_sql,sqltemplate);

	return 0;
}

subroutine do_sql(in functionname_and_args, in sql, in sqltemplate) {

	functionname_and_args.outputl();

	var functionsql=sqltemplate;

	functionsql.swapper("$functionname_and_args",functionname_and_args);

	functionsql.swapper("$sqlcode",sql);

	if (verbose)
		functionsql.outputl();

	var errmsg;
	var().sqlexec(functionsql,errmsg);

	if (errmsg) {
		if (not verbose) {
			//functionsql.outputl();
			int nlines=count(functionsql,"\n");
			for (int linen=1;linen<=nlines;++linen) {
				printl(linen-2+2,". ", field(functionsql,"\n",linen) );
			}
			outputl();
		}
		errmsg.outputl();
	}
	return;
}

subroutine onefile(in dictfilename, in reqdictid, io viewsql) {

	if (dictfilename.substr(1,5) ne "dict_")
		return;

	if (!open(dictfilename,dictfile)) {
		call fsmsg();
		abort();
	}

	if (reqdictid)
		makelist("",reqdictid);
	else
		select(dictfilename);

	var dictid;
	while (readnext(dictid)) {
		onedictid(dictfilename, dictid, reqdictid);
	}

	if (viewsql) {
		viewsql ^= "SELECT '" ^ dictfilename.substr(6).ucase() ^ "'||'*'||key as key, data\n";
		viewsql ^= "FROM " ^ dictfilename ^ "\n";
		viewsql ^= "UNION\n";
	}

	return;
}

subroutine onedictid(in dictfilename, io dictid, in reqdictid) {

	//get the dict source code
	var dictrec;
	if (not dictrec.read(dictfile,dictid)) {
		dictid.ucaser();
		if (!dictrec.read(dictfile,dictid))
			stop(quote(dictid)^" cannot be read in "^quote(dictfilename));
	}
	var sourcecode=dictrec.a(8);
	var ismv=dictrec.a(4)[1]=="M";

	//remove anything before sql code
	var pos=index(sourcecode,"/" "*pgsql");
	if (!pos) {
		if (reqdictid)
			stop(quote(dictfilename)^" "^quote(dictid)^" does not have any pgsql section");
		return;
	}
	var sql=sourcecode.substr(pos+8);

	//printl(dictfilename, " ",dictid, " > sql");

	//should take everything up to the end ??
	//so pgsql comments like /* */ are respected ??
	//remove anything after sql code
	//find the LAST * /  pair and remove everything after it
	var lastpos=0;
	for (int ii=1;;++ii) {
		//find the ii'th * / terminator
		pos=index(sql,"*" "/",ii);
		if (!pos)
			break;
		lastpos=pos;
	}
	if (lastpos)
		sql.splicer(lastpos-1,"");

	var xlatetemplate;
	if (ismv)
		xlatetemplate=
R"V0G0N(
$RETVAR := array_to_string
(
 array
 (
  SELECT
    $TARGET_EXPR
   FROM
    unnest
    (
     string_to_array($SOURCEKEY_EXPR,chr(29))
    )
   LEFT JOIN
    $TARGETFILE on $TARGETFILE.key = unnest
 ),
 chr(29),
 ''
);
)V0G0N";
		else
			xlatetemplate=
R"V0G0N(
$RETVAR :=
  $TARGET_EXPR
  FROM $TARGETFILE
  WHERE $TARGETFILE.key=$SOURCEKEY_EXPR;
  $RETVAR := coalesce($RETVAR,'');
)V0G0N";

	// expand lines like the following to sql
	// (all spaces are MANDATORY)
	// ans := xlate filename fromfn tofn
	// e.g.
	// xlate=xlate jobs 2 14
	// ->
	// ans:=split_part(jobs.data,chr(30),14)
	// FROM jobs
	// WHERE jobs.key=split_part($2,chr(30),2);
	//
	// fromfn and tofn can be functions
	// "from" expression has access to source file data in variable $2 (argument 2)
	// "to" expression has access to target file data eg invoices.data
	int nlines=dcount(sql,VM);
	for (int ln=1;ln<=nlines;++ln) {
		var line=sql.a(1,ln).trim();
		if (line.substr(1,2)!="--" && field(line," ",2,2) eq ":= xlate") {

			//line.outputl("xlate=");

			//eg ans
			var targetvariablename=line.field(" ",1);

			//target file name eg jobs
			var target_filename=line.field(" ",4);

			//source file field number or expression for key to target file
			var source_key_expr=line.field(" ",5);
			//if key field numeric then extract from source file date
			if (source_key_expr.isnum())
				source_key_expr="split_part($2,chr(30),"^source_key_expr^")";

			//target file field number or expression
			var target_expr=line.field(" ",6);
			if (target_expr.isnum())
				target_expr="split_part("^target_filename^".data,chr(30),"^target_expr^")";

			//line=targetvariablename^" := ";
			//if (ismv) {
			//	line^="array_to_string"
			//	"("
			//	" array"
			// " ("
			// " select ";
			//}
			//line^=target_expression;
			//line^="\n FROM "^target_filename;
			//line^="\n WHERE "^target_filename^".key="^source_key_expression^";";
			line=xlatetemplate;
			line.swapper("$RETVAR",targetvariablename);
			line.swapper("$TARGETFILE",target_filename);
			line.swapper("$SOURCEKEY_EXPR",source_key_expr);
			line.swapper("$TARGET_EXPR",target_expr);
			//line.outputl("sql=");

			sql.r(1,ln,line);
		}
	}

	//convert to text
	sql.trimmerf(VM).trimmerb(VM);
	sql.converter(VM,"\n");

	var sqltemplate=
R"V0G0N(CREATE OR REPLACE FUNCTION
 $functionname_and_args
 RETURNS text
 AS
 $$
  DECLARE
   ans text;
  BEGIN
$sqlcode
  RETURN ans;
  END;
 $$
 LANGUAGE 'plpgsql'
 IMMUTABLE
 SECURITY
 DEFINER
 COST 10;
 )V0G0N";

	//set the function name
	do_sql(dictfilename^"_"^dictid^"(key text, data text)",sql,sqltemplate);

}//onedictid

//exodus_field_remove
var field_remove_sql=
R"V0G0N(
DECLARE
 charn int;
 nchars int;
 currfieldn int;
 ans text;

BEGIN

 -- SIMILAR CODE IN FIELD_REMOVE AND FIELD_REPLACE

 if fieldno<=0 then
  if fieldno=0 then
   return '';
  end if;
  return data;
 end if;

 ans := '';
 currfieldn :=1;
 nchars := length(data);
 for charn in 1..nchars loop

  continue when substr(data,charn,1) <> sep;

  --if substr(data,charn,1) = sep then

   currfieldn=currfieldn+1;

  if currfieldn=fieldno then
   ans := substr(data,1,charn-1);

  elseif currfieldn>fieldno then
   if ans<>'' then
    ans := ans || sep || substr(data,charn+1);
   else
    ans := substr(data,charn+1);
   end if;
   return ans;
  end if;

  --end if;

 end loop;

 -- deleting beyond the number of existing fields
 if currfieldn<fieldno then
  return data;
  end if;

 return ans;

END;
)V0G0N";

//exodus_field_replace
var field_replace_sql=
R"V0G0N(
DECLARE
 charn int;
 nchars int;
 currfieldn int;
 ans text;

BEGIN

 -- SIMILAR CODE IN FIELD_REMOVE AND FIELD_REPLACE

 if fieldno<=0 then
  if fieldno=0 then
   return replacement;
  end if;
  if data='' then
   return replacement;
  else
   return data || sep || replacement;
  end if;

 end if;

 ans := '';
 currfieldn :=1;
 nchars := length(data);
 for charn in 1..nchars loop

  continue when substr(data,charn,1) <> sep;
  --if substr(data,charn,1) = sep then

  currfieldn=currfieldn+1;

  if currfieldn=fieldno then
   ans := substr(data,1,charn-1);

  elseif currfieldn>fieldno then
   if ans<>'' then
    ans := ans || sep || replacement || sep || substr(data,charn+1);
   else
    ans := replacement || sep || substr(data,charn+1);
   end if;
   return ans;
  end if;

  --end if;

 end loop;

 -- deleting beyond the number of existing fields
 if currfieldn<fieldno then
   if replacement<>'' then
    data := data || repeat(sep,fieldno-currfieldn)|| replacement;
   end if;
  return data;
  end if;

 if replacement<>'' then
  ans := ans || sep || replacement;
  end if;

 return ans;

END;
)V0G0N";

//exodus_split
var split_sql=
R"V0G0N(
DECLARE
 inputx text;
 temp text;
 numlen int;
 numx text;
 unitx text;
 nn int;
 tt int;
 char1 char(1);
BEGIN
   inputx:=data;
   inputx:=translate(inputx,' ','');
   temp:=inputx;
   char1:=substring(temp,1,1);
   if char1='-' then
    temp=substring(temp,2);
   end if;
   temp:=translate(temp,'123456789.,','           ');

   numlen=length(temp)-length(trim(leading from temp));
   if char1='-' then
    numlen := numlen+1;
    end if;
   numx:=substring(inputx,1,numlen);

   if numx='-' then
    numx:='';
   end if;

   -- unused (function arg output var)
   unitx=substring(inputx,numlen+1,99);

   -- convert to decimal format
   -- remove all , '.' besides last
   numx=translate(numx, ',' , '.');
   nn=exodus_count(numx,'.');
   for ii in 1..nn-1 loop
    tt=strpos(numx,'.');
    if tt<>0 then
     numx:=substring(numx,1,tt-1) || substring(numx,tt+1);
    end if;
   end loop;

   return numx || ' ' || unitx;

END;

)V0G0N";

programexit()
<|endoftext|>


<commit_before>#include <cstdint>

#include "BBox.h"

using namespace charto;

template <typename Unit>
double BBox<Unit> :: sqDistTo(Unit x, Unit y) const {
	double dx = 0, dy = 0;

	if(x < sw.x) dx = x - sw.x;
	else if(x > ne.x) dx = x - ne.x;

	if(y < sw.y) dy = y - sw.y;
	else if(y >= ne.y) dy = y - ne.y;

	return(dx * dx + dy * dy);
}

/*
	The extended edges of the bounding box partition the coordinate system
	into 9 regions like this:

	ul / sw

	v               v
	1100 | 0100 | 0110
	-----+------+-----
	1000 | 0000 | 0010
	-----+------+-----
	1001 | 0001 | 0011<   lr / ne

	Result is a 4-bit code where each bit represents being on the outside of a
	particular edge. Points on edges are considered to belong to the region
	below or on the right side of them in this diagram.
*/

template <typename Unit>
unsigned int BBox<Unit> :: getRegion(Unit x, Unit y) const {
	return((
		((x < ul.x) << 3) |
		((y < ul.y) << 2) |
		((x < lr.x) << 1) |
		 (y < lr.y)
	) ^ 3);
}

// Integer version uses more bit twiddles to ensure it's branchless.

template <>
unsigned int BBox<uint32_t> :: getRegion(uint32_t x, uint32_t y) const {
	return((
		(((x - ul.x) >> 28) & 8) |
		(((y - ul.y) >> 29) & 4) |
		(((x - lr.x) >> 30) & 2) |
		 ((y - lr.y) >> 31)
	) ^ 3);
}

// Box edges or corners touching each other are considered not to intersect,
// because only the SW corner and edges touching it belong to each box.

template <typename Unit>
bool BBox<Unit> :: intersects(const BBox &other) const {
	return(
		   other.sw.x < ne.x
		&& other.sw.y < ne.y
		&& other.ne.x > sw.x
		&& other.ne.y > sw.y
	);
}

// Both bounding boxes must have nonzero width!
// Otherwise this may erroneously return true.

template <typename Unit>
bool BBox<Unit> :: containsX(const BBox &other) const {
	return(other.sw.x >= sw.x && other.ne.x <= ne.x);
}

// Both bounding boxes must have nonzero height!
// Otherwise this may erroneously return true.

template <typename Unit>
bool BBox<Unit> :: containsY(const BBox &other) const {
	return(other.sw.y >= sw.y && other.ne.y <= ne.y);
}

// Both bounding boxes must have nonzero width and height!
// Otherwise this may erroneously return true.

template <typename Unit>
bool BBox<Unit> :: contains(const BBox &other) const {
	return(containsX(other) && containsY(other));
}

template <typename Unit>
void BBox<Unit> :: extend(Unit x, Unit y) {
	if(x < sw.x) sw.x = x;
	if(y < sw.y) sw.y = y;
	if(x > ne.x) ne.x = x;
	if(y > ne.y) ne.y = y;
}

template class charto::BBox<double>;
template class charto::BBox<uint32_t>;

#include "nbind/nbind.h"

using namespace nbind;

NBIND_CLASS(BBox<double>, BBox) {
	construct<double, double, double, double>();

	getter(getSW);
	getter(getNE);

//	method(sqDistTo);
	method(getRegion, Overloaded<unsigned int (double, double) const>());

	method(intersects);
	method(contains, Overloaded<bool (const BBox<double> &) const>());

	method(extend, Overloaded<void (double, double)>());
}

NBIND_CLASS(BBox<uint32_t>, BBoxInt) {
	construct<uint32_t, uint32_t, uint32_t, uint32_t>();

	getter(getSW);
	getter(getNE);

//	method(sqDistTo);
	method(getRegion, Overloaded<unsigned int (uint32_t, uint32_t) const>());

	method(intersects);

	method(extend, Overloaded<void (uint32_t, uint32_t)>());
}
<commit_msg>Update to latest nbind dev branch.<commit_after>#include <cstdint>

#include "BBox.h"

using namespace charto;

template <typename Unit>
double BBox<Unit> :: sqDistTo(Unit x, Unit y) const {
	double dx = 0, dy = 0;

	if(x < sw.x) dx = x - sw.x;
	else if(x > ne.x) dx = x - ne.x;

	if(y < sw.y) dy = y - sw.y;
	else if(y >= ne.y) dy = y - ne.y;

	return(dx * dx + dy * dy);
}

/*
	The extended edges of the bounding box partition the coordinate system
	into 9 regions like this:

	ul / sw

	v               v
	1100 | 0100 | 0110
	-----+------+-----
	1000 | 0000 | 0010
	-----+------+-----
	1001 | 0001 | 0011<   lr / ne

	Result is a 4-bit code where each bit represents being on the outside of a
	particular edge. Points on edges are considered to belong to the region
	below or on the right side of them in this diagram.
*/

template <typename Unit>
unsigned int BBox<Unit> :: getRegion(Unit x, Unit y) const {
	return((
		((x < ul.x) << 3) |
		((y < ul.y) << 2) |
		((x < lr.x) << 1) |
		 (y < lr.y)
	) ^ 3);
}

// Integer version uses more bit twiddles to ensure it's branchless.

template <>
unsigned int BBox<uint32_t> :: getRegion(uint32_t x, uint32_t y) const {
	return((
		(((x - ul.x) >> 28) & 8) |
		(((y - ul.y) >> 29) & 4) |
		(((x - lr.x) >> 30) & 2) |
		 ((y - lr.y) >> 31)
	) ^ 3);
}

// Box edges or corners touching each other are considered not to intersect,
// because only the SW corner and edges touching it belong to each box.

template <typename Unit>
bool BBox<Unit> :: intersects(const BBox &other) const {
	return(
		   other.sw.x < ne.x
		&& other.sw.y < ne.y
		&& other.ne.x > sw.x
		&& other.ne.y > sw.y
	);
}

// Both bounding boxes must have nonzero width!
// Otherwise this may erroneously return true.

template <typename Unit>
bool BBox<Unit> :: containsX(const BBox &other) const {
	return(other.sw.x >= sw.x && other.ne.x <= ne.x);
}

// Both bounding boxes must have nonzero height!
// Otherwise this may erroneously return true.

template <typename Unit>
bool BBox<Unit> :: containsY(const BBox &other) const {
	return(other.sw.y >= sw.y && other.ne.y <= ne.y);
}

// Both bounding boxes must have nonzero width and height!
// Otherwise this may erroneously return true.

template <typename Unit>
bool BBox<Unit> :: contains(const BBox &other) const {
	return(containsX(other) && containsY(other));
}

template <typename Unit>
void BBox<Unit> :: extend(Unit x, Unit y) {
	if(x < sw.x) sw.x = x;
	if(y < sw.y) sw.y = y;
	if(x > ne.x) ne.x = x;
	if(y > ne.y) ne.y = y;
}

template class charto::BBox<double>;
template class charto::BBox<uint32_t>;

#include "nbind/nbind.h"

using namespace nbind;

NBIND_CLASS(BBox<double>, BBox) {
	construct<double, double, double, double>();

	getter(getSW);
	getter(getNE);

//	method(sqDistTo);
	multimethod(getRegion, args(double, double));

	method(intersects);
	multimethod(contains, args(const BBox<double> &));

	multimethod(extend, args(double, double));
}

NBIND_CLASS(BBox<uint32_t>, BBoxInt) {
	construct<uint32_t, uint32_t, uint32_t, uint32_t>();

	getter(getSW);
	getter(getNE);

//	method(sqDistTo);
	multimethod(getRegion, args(uint32_t, uint32_t));

	method(intersects);

	multimethod(extend, args(uint32_t, uint32_t));
}
<|endoftext|>