<commit_before>/*
 * Copyright (C) 2013 Red Hat, Inc.
 *
 * Licensed under the GNU Lesser General Public License Version 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <Python.h>

// libsolv
#include <solv/util.h>

// hawkey
#include "hy-nevra.hpp"
#include "hy-query.h"
#include "dnf-sack.h"

// pyhawkey
#include "iutil-py.hpp"
#include "nevra-py.hpp"
#include "pycomp.hpp"
#include "query-py.hpp"
#include "sack-py.hpp"

typedef struct {
    PyObject_HEAD
    libdnf::Nevra *nevra;
} _NevraObject;

libdnf::Nevra *
nevraFromPyObject(PyObject *o)
{
    if (!PyObject_TypeCheck(o, &nevra_Type)) {
        PyErr_SetString(PyExc_TypeError, "Expected a _hawkey.NEVRA object.");
        return NULL;
    }
    return ((_NevraObject *)o)->nevra;
}

PyObject *
nevraToPyObject(libdnf::Nevra *nevra)
{
    _NevraObject *self = (_NevraObject *)nevra_Type.tp_alloc(&nevra_Type, 0);
    if (self)
        self->nevra = nevra;
    return (PyObject *)self;
}

// getsetters
static int
set_epoch(_NevraObject *self, PyObject *value, void *closure)
{
    if (value == NULL)
        self->nevra->setEpoch(-1);
    else if (PyInt_Check(value))
        self->nevra->setEpoch(PyLong_AsLong(value));
    else if (value == Py_None)
        self->nevra->setEpoch(-1);
    else
        return -1;
    return 0;
}

static PyObject *
get_epoch(_NevraObject *self, void *closure)
{
    if (self->nevra->getEpoch() == -1)
        Py_RETURN_NONE;
#if PY_MAJOR_VERSION >= 3
    return PyLong_FromLong(self->nevra->getEpoch());
#else
    return PyInt_FromLong(self->nevra->getEpoch());
#endif
}

template<const std::string & (libdnf::Nevra::*getMethod)() const>
static PyObject *
get_attr(_NevraObject *self, void *closure)
{
    auto str = (self->nevra->*getMethod)();
    if (str.empty())
        Py_RETURN_NONE;
    else
        return PyString_FromString(str.c_str());
}

template<void (libdnf::Nevra::*setMethod)(std::string &&)>
static int
set_attr(_NevraObject *self, PyObject *value, void *closure)
{
    PyObject *tmp_py_str = NULL;
    auto str_value = pycomp_get_string(value, &tmp_py_str);

    if (str_value == NULL) {
        Py_XDECREF(tmp_py_str);
        return -1;
    }

    (self->nevra->*setMethod)(str_value);

    Py_XDECREF(tmp_py_str);
    return 0;
}

static PyGetSetDef nevra_getsetters[] = {
    {(char*)"name", (getter)get_attr<&libdnf::Nevra::getName>,
        (setter)set_attr<&libdnf::Nevra::setName>, NULL, NULL},
    {(char*)"epoch", (getter)get_epoch, (setter)set_epoch,
        NULL, NULL},
    {(char*)"version", (getter)get_attr<&libdnf::Nevra::getVersion>,
        (setter)set_attr<&libdnf::Nevra::setVersion>, NULL, NULL},
    {(char*)"release", (getter)get_attr<&libdnf::Nevra::getRelease>,
        (setter)set_attr<&libdnf::Nevra::setRelease>, NULL, NULL},
    {(char*)"arch", (getter)get_attr<&libdnf::Nevra::getArch>,
        (setter)set_attr<&libdnf::Nevra::setArch>, NULL, NULL},
    {NULL}          /* sentinel */
};

static PyObject *
nevra_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    _NevraObject *self = (_NevraObject*)type->tp_alloc(type, 0);
    if (self)
        self->nevra = new libdnf::Nevra;
    return (PyObject*)self;
}

static void
nevra_dealloc(_NevraObject *self)
{
    delete self->nevra;
    Py_TYPE(self)->tp_free(self);
}

static int
nevra_init(_NevraObject *self, PyObject *args, PyObject *kwds)
{
    char *name = NULL, *version = NULL, *release = NULL, *arch = NULL;
    PyObject *epoch_o = NULL;
    libdnf::Nevra * cnevra = NULL;

    const char *kwlist[] = {"name", "epoch", "version", "release", "arch",
        "nevra", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|zOzzzO&", (char**) kwlist,
        &name, &epoch_o, &version, &release, &arch, nevra_converter, &cnevra))
        return -1;
    if (!name && !cnevra) {
        PyErr_SetString(PyExc_ValueError,
            "Name is required parameter.");
        return -1;
    }
    if (cnevra) {
        self->nevra = new libdnf::Nevra(*cnevra);
        return 0;
    }
    if (set_epoch(self, epoch_o, NULL) == -1) {
        PyErr_SetString(PyExc_TypeError,
            "An integer value or None expected for epoch.");
        return -1;
    }
    if (name)
        self->nevra->setName(name);
    if (version)
        self->nevra->setVersion(version);
    if (release)
        self->nevra->setRelease(release);
    if (arch)
        self->nevra->setArch(arch);
    return 0;
}

/* object methods */

static PyObject *
evr(_NevraObject *self, PyObject *unused)
{
    return PyString_FromString(self->nevra->getEvr().c_str());;
}

int
nevra_converter(PyObject *o, libdnf::Nevra **nevra_ptr)
{
    auto nevra = nevraFromPyObject(o);
    if (nevra == NULL)
        return 0;
    *nevra_ptr = nevra;
    return 1;
}

static PyObject *
evr_cmp(_NevraObject *self, PyObject *args)
{
    DnfSack *sack;
    libdnf::Nevra *nevra;
    if (!PyArg_ParseTuple(args, "O&O&", nevra_converter, &nevra, sack_converter, &sack)) {
        return NULL;
    }
    if (sack == NULL || nevra == NULL)
        return NULL;
    int cmp = self->nevra->compareEvr(*nevra, sack);
    return PyLong_FromLong(cmp);
}

static PyObject *
has_just_name(_NevraObject *self, PyObject *unused)
{
    return PyBool_FromLong(self->nevra->hasJustName());
}

static PyObject *
to_query(_NevraObject *self, PyObject *args, PyObject *kwds)
{
    PyObject *sack;
    DnfSack *csack;
    const char *kwlist[] = {"sack", "icase", NULL};
    PyObject *icase = NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|O!", (char**) kwlist, &sack_Type, &sack,
        &PyBool_Type, &icase)) {
        return NULL;
    }
    gboolean c_icase = icase!=NULL && PyObject_IsTrue(icase);
    csack = sackFromPyObject(sack);
    HyQuery query = hy_query_from_nevra(self->nevra, csack, c_icase);
    PyObject *q = queryToPyObject(query, sack, &query_Type);
    return q;
}

static struct PyMethodDef nevra_methods[] = {
    {"evr_cmp",     (PyCFunction) evr_cmp, METH_VARARGS, NULL},
    {"evr", (PyCFunction) evr, METH_NOARGS,   NULL},
    {"has_just_name",     (PyCFunction) has_just_name, METH_NOARGS, NULL},
    {"to_query",     (PyCFunction) to_query, METH_VARARGS | METH_KEYWORDS, NULL},

    {NULL}                      /* sentinel */
};

static PyObject *
nevra_richcompare(PyObject *self, PyObject *other, int op)
{
    PyObject *v;
    libdnf::Nevra *other_nevra, *self_nevra;
    other_nevra = nevraFromPyObject(other);
    self_nevra = nevraFromPyObject(self);

    if (!other_nevra) {
        if(PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_TypeError))
            PyErr_Clear();
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }

    long result = self_nevra->compare(*other_nevra);

    switch (op) {
    case Py_EQ:
        v = TEST_COND(result == 0);
        break;
    case Py_NE:
        v = TEST_COND(result != 0);
        break;
    case Py_LE:
        v = TEST_COND(result <= 0);
        break;
    case Py_GE:
        v = TEST_COND(result >= 0);
        break;
    case Py_LT:
        v = TEST_COND(result < 0);
        break;
    case Py_GT:
        v = TEST_COND(result > 0);
        break;
    default:
        PyErr_BadArgument();
        return NULL;
    }
    Py_INCREF(v);
    return v;
}

static PyObject *
iter(_NevraObject *self)
{
    PyObject *res;
    auto nevra = self->nevra;
    if (nevra->getEpoch() == -1) {
        Py_INCREF(Py_None);
        res = Py_BuildValue("zOzzz",
                            nevra->getName().c_str(),
                            Py_None,
                            nevra->getVersion().c_str(),
                            nevra->getRelease().c_str(),
                            nevra->getArch().c_str());
    } else
        res = Py_BuildValue("zizzz",
                            nevra->getName().c_str(),
                            nevra->getEpoch(),
                            nevra->getVersion().c_str(),
                            nevra->getRelease().c_str(),
                            nevra->getArch().c_str());
    PyObject *iter = PyObject_GetIter(res);
    Py_DECREF(res);
    return iter;
}

PyTypeObject nevra_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    "_hawkey.NEVRA",        /*tp_name*/
    sizeof(_NevraObject),   /*tp_basicsize*/
    0,              /*tp_itemsize*/
    (destructor) nevra_dealloc,  /*tp_dealloc*/
    0,              /*tp_print*/
    0,              /*tp_getattr*/
    0,              /*tp_setattr*/
    0,              /*tp_compare*/
    0,              /*tp_repr*/
    0,              /*tp_as_number*/
    0,              /*tp_as_sequence*/
    0,              /*tp_as_mapping*/
    0,              /*tp_hash */
    0,              /*tp_call*/
    0,              /*tp_str*/
    0,              /*tp_getattro*/
    0,              /*tp_setattro*/
    0,              /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,     /*tp_flags*/
    "NEVRA object",     /* tp_doc */
    0,              /* tp_traverse */
    0,              /* tp_clear */
    nevra_richcompare,              /* tp_richcompare */
    0,              /* tp_weaklistoffset */
    (getiterfunc) iter,/* tp_iter */
    0,                          /* tp_iternext */
    nevra_methods,      /* tp_methods */
    0,              /* tp_members */
    nevra_getsetters,       /* tp_getset */
    0,              /* tp_base */
    0,              /* tp_dict */
    0,              /* tp_descr_get */
    0,              /* tp_descr_set */
    0,              /* tp_dictoffset */
    (initproc)nevra_init,   /* tp_init */
    0,              /* tp_alloc */
    nevra_new,          /* tp_new */
    0,              /* tp_free */
    0,              /* tp_is_gc */
};
<commit_msg>Fix memory leak<commit_after>/*
 * Copyright (C) 2013 Red Hat, Inc.
 *
 * Licensed under the GNU Lesser General Public License Version 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <Python.h>

// libsolv
#include <solv/util.h>

// hawkey
#include "hy-nevra.hpp"
#include "hy-query.h"
#include "dnf-sack.h"

// pyhawkey
#include "iutil-py.hpp"
#include "nevra-py.hpp"
#include "pycomp.hpp"
#include "query-py.hpp"
#include "sack-py.hpp"

typedef struct {
    PyObject_HEAD
    libdnf::Nevra *nevra;
} _NevraObject;

libdnf::Nevra *
nevraFromPyObject(PyObject *o)
{
    if (!PyObject_TypeCheck(o, &nevra_Type)) {
        PyErr_SetString(PyExc_TypeError, "Expected a _hawkey.NEVRA object.");
        return NULL;
    }
    return ((_NevraObject *)o)->nevra;
}

PyObject *
nevraToPyObject(libdnf::Nevra *nevra)
{
    _NevraObject *self = (_NevraObject *)nevra_Type.tp_alloc(&nevra_Type, 0);
    if (self)
        self->nevra = nevra;
    return (PyObject *)self;
}

// getsetters
static int
set_epoch(_NevraObject *self, PyObject *value, void *closure)
{
    if (value == NULL)
        self->nevra->setEpoch(-1);
    else if (PyInt_Check(value))
        self->nevra->setEpoch(PyLong_AsLong(value));
    else if (value == Py_None)
        self->nevra->setEpoch(-1);
    else
        return -1;
    return 0;
}

static PyObject *
get_epoch(_NevraObject *self, void *closure)
{
    if (self->nevra->getEpoch() == -1)
        Py_RETURN_NONE;
#if PY_MAJOR_VERSION >= 3
    return PyLong_FromLong(self->nevra->getEpoch());
#else
    return PyInt_FromLong(self->nevra->getEpoch());
#endif
}

template<const std::string & (libdnf::Nevra::*getMethod)() const>
static PyObject *
get_attr(_NevraObject *self, void *closure)
{
    auto str = (self->nevra->*getMethod)();
    if (str.empty())
        Py_RETURN_NONE;
    else
        return PyString_FromString(str.c_str());
}

template<void (libdnf::Nevra::*setMethod)(std::string &&)>
static int
set_attr(_NevraObject *self, PyObject *value, void *closure)
{
    PyObject *tmp_py_str = NULL;
    auto str_value = pycomp_get_string(value, &tmp_py_str);

    if (str_value == NULL) {
        Py_XDECREF(tmp_py_str);
        return -1;
    }

    (self->nevra->*setMethod)(str_value);

    Py_XDECREF(tmp_py_str);
    return 0;
}

static PyGetSetDef nevra_getsetters[] = {
    {(char*)"name", (getter)get_attr<&libdnf::Nevra::getName>,
        (setter)set_attr<&libdnf::Nevra::setName>, NULL, NULL},
    {(char*)"epoch", (getter)get_epoch, (setter)set_epoch,
        NULL, NULL},
    {(char*)"version", (getter)get_attr<&libdnf::Nevra::getVersion>,
        (setter)set_attr<&libdnf::Nevra::setVersion>, NULL, NULL},
    {(char*)"release", (getter)get_attr<&libdnf::Nevra::getRelease>,
        (setter)set_attr<&libdnf::Nevra::setRelease>, NULL, NULL},
    {(char*)"arch", (getter)get_attr<&libdnf::Nevra::getArch>,
        (setter)set_attr<&libdnf::Nevra::setArch>, NULL, NULL},
    {NULL}          /* sentinel */
};

static PyObject *
nevra_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    _NevraObject *self = (_NevraObject*)type->tp_alloc(type, 0);
    if (self)
        self->nevra = new libdnf::Nevra;
    return (PyObject*)self;
}

static void
nevra_dealloc(_NevraObject *self)
{
    delete self->nevra;
    Py_TYPE(self)->tp_free(self);
}

static int
nevra_init(_NevraObject *self, PyObject *args, PyObject *kwds)
{
    char *name = NULL, *version = NULL, *release = NULL, *arch = NULL;
    PyObject *epoch_o = NULL;
    libdnf::Nevra * cnevra = NULL;

    const char *kwlist[] = {"name", "epoch", "version", "release", "arch",
        "nevra", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|zOzzzO&", (char**) kwlist,
        &name, &epoch_o, &version, &release, &arch, nevra_converter, &cnevra))
        return -1;
    if (!name && !cnevra) {
        PyErr_SetString(PyExc_ValueError,
            "Name is required parameter.");
        return -1;
    }
    if (cnevra) {
        *self->nevra = *cnevra;
        return 0;
    }
    if (set_epoch(self, epoch_o, NULL) == -1) {
        PyErr_SetString(PyExc_TypeError,
            "An integer value or None expected for epoch.");
        return -1;
    }
    if (name)
        self->nevra->setName(name);
    if (version)
        self->nevra->setVersion(version);
    if (release)
        self->nevra->setRelease(release);
    if (arch)
        self->nevra->setArch(arch);
    return 0;
}

/* object methods */

static PyObject *
evr(_NevraObject *self, PyObject *unused)
{
    return PyString_FromString(self->nevra->getEvr().c_str());;
}

int
nevra_converter(PyObject *o, libdnf::Nevra **nevra_ptr)
{
    auto nevra = nevraFromPyObject(o);
    if (nevra == NULL)
        return 0;
    *nevra_ptr = nevra;
    return 1;
}

static PyObject *
evr_cmp(_NevraObject *self, PyObject *args)
{
    DnfSack *sack;
    libdnf::Nevra *nevra;
    if (!PyArg_ParseTuple(args, "O&O&", nevra_converter, &nevra, sack_converter, &sack)) {
        return NULL;
    }
    if (sack == NULL || nevra == NULL)
        return NULL;
    int cmp = self->nevra->compareEvr(*nevra, sack);
    return PyLong_FromLong(cmp);
}

static PyObject *
has_just_name(_NevraObject *self, PyObject *unused)
{
    return PyBool_FromLong(self->nevra->hasJustName());
}

static PyObject *
to_query(_NevraObject *self, PyObject *args, PyObject *kwds)
{
    PyObject *sack;
    DnfSack *csack;
    const char *kwlist[] = {"sack", "icase", NULL};
    PyObject *icase = NULL;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|O!", (char**) kwlist, &sack_Type, &sack,
        &PyBool_Type, &icase)) {
        return NULL;
    }
    gboolean c_icase = icase!=NULL && PyObject_IsTrue(icase);
    csack = sackFromPyObject(sack);
    HyQuery query = hy_query_from_nevra(self->nevra, csack, c_icase);
    PyObject *q = queryToPyObject(query, sack, &query_Type);
    return q;
}

static struct PyMethodDef nevra_methods[] = {
    {"evr_cmp",     (PyCFunction) evr_cmp, METH_VARARGS, NULL},
    {"evr", (PyCFunction) evr, METH_NOARGS,   NULL},
    {"has_just_name",     (PyCFunction) has_just_name, METH_NOARGS, NULL},
    {"to_query",     (PyCFunction) to_query, METH_VARARGS | METH_KEYWORDS, NULL},

    {NULL}                      /* sentinel */
};

static PyObject *
nevra_richcompare(PyObject *self, PyObject *other, int op)
{
    PyObject *v;
    libdnf::Nevra *other_nevra, *self_nevra;
    other_nevra = nevraFromPyObject(other);
    self_nevra = nevraFromPyObject(self);

    if (!other_nevra) {
        if(PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_TypeError))
            PyErr_Clear();
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }

    long result = self_nevra->compare(*other_nevra);

    switch (op) {
    case Py_EQ:
        v = TEST_COND(result == 0);
        break;
    case Py_NE:
        v = TEST_COND(result != 0);
        break;
    case Py_LE:
        v = TEST_COND(result <= 0);
        break;
    case Py_GE:
        v = TEST_COND(result >= 0);
        break;
    case Py_LT:
        v = TEST_COND(result < 0);
        break;
    case Py_GT:
        v = TEST_COND(result > 0);
        break;
    default:
        PyErr_BadArgument();
        return NULL;
    }
    Py_INCREF(v);
    return v;
}

static PyObject *
iter(_NevraObject *self)
{
    PyObject *res;
    auto nevra = self->nevra;
    if (nevra->getEpoch() == -1) {
        Py_INCREF(Py_None);
        res = Py_BuildValue("zOzzz",
                            nevra->getName().c_str(),
                            Py_None,
                            nevra->getVersion().c_str(),
                            nevra->getRelease().c_str(),
                            nevra->getArch().c_str());
    } else
        res = Py_BuildValue("zizzz",
                            nevra->getName().c_str(),
                            nevra->getEpoch(),
                            nevra->getVersion().c_str(),
                            nevra->getRelease().c_str(),
                            nevra->getArch().c_str());
    PyObject *iter = PyObject_GetIter(res);
    Py_DECREF(res);
    return iter;
}

PyTypeObject nevra_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    "_hawkey.NEVRA",        /*tp_name*/
    sizeof(_NevraObject),   /*tp_basicsize*/
    0,              /*tp_itemsize*/
    (destructor) nevra_dealloc,  /*tp_dealloc*/
    0,              /*tp_print*/
    0,              /*tp_getattr*/
    0,              /*tp_setattr*/
    0,              /*tp_compare*/
    0,              /*tp_repr*/
    0,              /*tp_as_number*/
    0,              /*tp_as_sequence*/
    0,              /*tp_as_mapping*/
    0,              /*tp_hash */
    0,              /*tp_call*/
    0,              /*tp_str*/
    0,              /*tp_getattro*/
    0,              /*tp_setattro*/
    0,              /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,     /*tp_flags*/
    "NEVRA object",     /* tp_doc */
    0,              /* tp_traverse */
    0,              /* tp_clear */
    nevra_richcompare,              /* tp_richcompare */
    0,              /* tp_weaklistoffset */
    (getiterfunc) iter,/* tp_iter */
    0,                          /* tp_iternext */
    nevra_methods,      /* tp_methods */
    0,              /* tp_members */
    nevra_getsetters,       /* tp_getset */
    0,              /* tp_base */
    0,              /* tp_dict */
    0,              /* tp_descr_get */
    0,              /* tp_descr_set */
    0,              /* tp_dictoffset */
    (initproc)nevra_init,   /* tp_init */
    0,              /* tp_alloc */
    nevra_new,          /* tp_new */
    0,              /* tp_free */
    0,              /* tp_is_gc */
};
<|endoftext|>


<commit_before>/*
 * Copyright 2000-2008, François Revol, <revol@free.fr>. All rights reserved.
 * Distributed under the terms of the MIT License.
 */

/*
 * deskbar ThemesAddon class
 */

#include <Alert.h>
#include <Application.h>
#include <Directory.h>
#include <Message.h>
#include <Messenger.h>
#include <Roster.h>
#include <be_apps/Deskbar/Deskbar.h>

#include <string.h>

#include "ThemesAddon.h"
#include "UITheme.h"

#ifdef SINGLE_BINARY
#define instantiate_themes_addon instantiate_themes_addon_deskbar
#endif

#define A_NAME "Deskbar"
#define A_MSGNAME Z_THEME_DESKBAR_SETTINGS
#define A_DESCRIPTION "Deskbar on-screen position"

class DeskbarThemesAddon : public ThemesAddon {
public:
	DeskbarThemesAddon();
	~DeskbarThemesAddon();

const char *Description();

status_t	RunPreferencesPanel();

status_t	AddNames(BMessage &names);

status_t	ApplyTheme(BMessage &theme, uint32 flags=0L);
status_t	MakeTheme(BMessage &theme, uint32 flags=0L);

status_t	ApplyDefaultTheme(uint32 flags=0L);
};

DeskbarThemesAddon::DeskbarThemesAddon()
	: ThemesAddon(A_NAME, A_MSGNAME)
{
}

DeskbarThemesAddon::~DeskbarThemesAddon()
{
}

const char *
DeskbarThemesAddon::Description()
{
	return A_DESCRIPTION;
}

status_t
DeskbarThemesAddon::RunPreferencesPanel()
{
	status_t err;
	entry_ref ref;
	BEntry ent;
	err = ent.SetTo("/boot/beos/preferences/Deskbar");
	if (!err) {
		err = ent.GetRef(&ref);
		if (!err) {
			err = be_roster->Launch(&ref);
		}
	}
	if (!err)
		return B_OK;
	err = ent.SetTo("/system/add-ons/Preferences/Deskbar");
	if (!err) {
		err = ent.GetRef(&ref);
		if (!err) {
			err = be_roster->Launch(&ref);
			if (err) {
				BMessage msg(B_REFS_RECEIVED);
				msg.AddRef("refs", &ref);
				be_app_messenger.SendMessage(&msg);
			}
		}
	}
	return err;
}

status_t
DeskbarThemesAddon::AddNames(BMessage &names)
{
	names.AddString(Z_THEME_DESKBAR_SETTINGS, "Deskbar position");
	names.AddString("db:location", "Deskbar on-screen position");
	names.AddString("db:expanded", "Deskbar is expanded");
	return B_OK;
}

status_t
DeskbarThemesAddon::ApplyTheme(BMessage &theme, uint32 flags)
{
	BMessage deskbar;
	status_t err;
	int32 loc = 5;
	bool expanded = true;
	BDeskbar db;

	if (!(flags & UI_THEME_SETTINGS_SET_ALL) || !(AddonFlags() & Z_THEME_ADDON_DO_SET_ALL))
		return B_OK;

	err = MyMessage(theme, deskbar);
	if (err)
		return err;

	if (deskbar.FindInt32("db:location", &loc) != B_OK)
		return ENOENT;
	deskbar.FindBool("db:expanded", &expanded);
	return db.SetLocation((deskbar_location)loc, expanded);
}

status_t
DeskbarThemesAddon::MakeTheme(BMessage &theme, uint32 flags)
{
	BMessage deskbar;
	status_t err;

	(void)flags;
	err = MyMessage(theme, deskbar);
	if (err)
		deskbar.MakeEmpty();

	deskbar_location loc;
	bool expanded;
	BDeskbar db;

	deskbar.RemoveName("db:location");
	deskbar.RemoveName("db:expanded");

	loc = db.Location(&expanded);
	deskbar.AddInt32("db:location", (int32)loc);
	deskbar.AddBool("db:expanded", expanded);

	err = SetMyMessage(theme, deskbar);
	return err;
}

status_t
DeskbarThemesAddon::ApplyDefaultTheme(uint32 flags)
{
	BMessage theme;
	BMessage deskbar;
	deskbar_location loc = B_DESKBAR_RIGHT_TOP;
	bool expanded = true;
	deskbar.AddInt32("db:location", (int32)loc);
	deskbar.AddBool("db:expanded", expanded);
	theme.AddMessage(A_MSGNAME, &deskbar);
	return ApplyTheme(theme, flags);
}

ThemesAddon *
instantiate_themes_addon()
{
	return (ThemesAddon *) new DeskbarThemesAddon;
}

<commit_msg>Add defaults for icon size and hide label in Deskbar<commit_after>/*
 * Copyright 2000-2008, François Revol, <revol@free.fr>. All rights reserved.
 * Distributed under the terms of the MIT License.
 */

/*
 * deskbar ThemesAddon class
 */

#include <Alert.h>
#include <Application.h>
#include <Directory.h>
#include <Message.h>
#include <Messenger.h>
#include <Roster.h>
#include <be_apps/Deskbar/Deskbar.h>

#include <string.h>

#include "ThemesAddon.h"
#include "UITheme.h"

#ifdef SINGLE_BINARY
#define instantiate_themes_addon instantiate_themes_addon_deskbar
#endif

#define A_NAME "Deskbar"
#define A_MSGNAME Z_THEME_DESKBAR_SETTINGS
#define A_DESCRIPTION "Deskbar on-screen position"

class DeskbarThemesAddon : public ThemesAddon {
public:
	DeskbarThemesAddon();
	~DeskbarThemesAddon();

const char *Description();

status_t	RunPreferencesPanel();

status_t	AddNames(BMessage &names);

status_t	ApplyTheme(BMessage &theme, uint32 flags=0L);
status_t	MakeTheme(BMessage &theme, uint32 flags=0L);

status_t	ApplyDefaultTheme(uint32 flags=0L);
};

DeskbarThemesAddon::DeskbarThemesAddon()
	: ThemesAddon(A_NAME, A_MSGNAME)
{
}

DeskbarThemesAddon::~DeskbarThemesAddon()
{
}

const char *
DeskbarThemesAddon::Description()
{
	return A_DESCRIPTION;
}

status_t
DeskbarThemesAddon::RunPreferencesPanel()
{
	status_t err;
	entry_ref ref;
	BEntry ent;
	err = ent.SetTo("/boot/beos/preferences/Deskbar");
	if (!err) {
		err = ent.GetRef(&ref);
		if (!err) {
			err = be_roster->Launch(&ref);
		}
	}
	if (!err)
		return B_OK;
	err = ent.SetTo("/system/add-ons/Preferences/Deskbar");
	if (!err) {
		err = ent.GetRef(&ref);
		if (!err) {
			err = be_roster->Launch(&ref);
			if (err) {
				BMessage msg(B_REFS_RECEIVED);
				msg.AddRef("refs", &ref);
				be_app_messenger.SendMessage(&msg);
			}
		}
	}
	return err;
}

status_t
DeskbarThemesAddon::AddNames(BMessage &names)
{
	names.AddString(Z_THEME_DESKBAR_SETTINGS, "Deskbar position");
	names.AddString("db:location", "Deskbar on-screen position");
	names.AddString("db:expanded", "Deskbar is expanded");
	names.AddString("db:iconSize", "Deskbar icons size");
	names.AddString("db:hideLabels", "Deskbar hide labels");
	return B_OK;
}

status_t
DeskbarThemesAddon::ApplyTheme(BMessage &theme, uint32 flags)
{
	BMessage deskbar;
	status_t err;
	int32 loc = 5;
	bool expanded = true;
	BDeskbar db;

	if (!(flags & UI_THEME_SETTINGS_SET_ALL) || !(AddonFlags() & Z_THEME_ADDON_DO_SET_ALL))
		return B_OK;

	err = MyMessage(theme, deskbar);
	if (err)
		return err;

	if (deskbar.FindInt32("db:location", &loc) != B_OK)
		return ENOENT;
	deskbar.FindBool("db:expanded", &expanded);
	return db.SetLocation((deskbar_location)loc, expanded);
}

status_t
DeskbarThemesAddon::MakeTheme(BMessage &theme, uint32 flags)
{
	BMessage deskbar;
	status_t err;

	(void)flags;
	err = MyMessage(theme, deskbar);
	if (err)
		deskbar.MakeEmpty();

	deskbar_location loc;
	bool expanded;
	BDeskbar db;

	deskbar.RemoveName("db:location");
	deskbar.RemoveName("db:expanded");

	loc = db.Location(&expanded);
	deskbar.AddInt32("db:location", (int32)loc);
	deskbar.AddBool("db:expanded", expanded);

	err = SetMyMessage(theme, deskbar);
	return err;
}

status_t
DeskbarThemesAddon::ApplyDefaultTheme(uint32 flags)
{
	BMessage theme;
	BMessage deskbar;
	deskbar_location loc = B_DESKBAR_RIGHT_TOP;
	bool expanded = true;
	int32 iconSize = 16;
	bool hideLabels = false;
	deskbar.AddInt32("db:location", (int32)loc);
	deskbar.AddBool("db:expanded", expanded);
	deskbar.AddInt32("db:iconSize", iconSize);
	deskbar.AddBool("db:hideLabels", hideLabels);
	theme.AddMessage(A_MSGNAME, &deskbar);
	return ApplyTheme(theme, flags);
}

ThemesAddon *
instantiate_themes_addon()
{
	return (ThemesAddon *) new DeskbarThemesAddon;
}

<|endoftext|>


<commit_before>#include <stdint.h>

#ifndef __APPLE__
#ifdef _LP64
typedef uint64_t size_t;
#else
typedef uint32_t size_t;
#endif
#endif
#define WEAK __attribute__((weak))

extern "C" {

#ifndef __SIZEOF_PTHREAD_ATTR_T

typedef struct {
    uint32_t flags;
    void * stack_base;
    size_t stack_size;
    size_t guard_size;
    int32_t sched_policy;
    int32_t sched_priority;
} pthread_attr_t;
typedef long pthread_t;
typedef struct {
    // 48 bytes is enough for a cond on 64-bit and 32-bit systems
    unsigned char _private[48];
} pthread_cond_t;
typedef long pthread_condattr_t;
typedef struct {
    // 40 bytes is enough for a mutex on 64-bit and 32-bit systems
    unsigned char _private[40];
} pthread_mutex_t;
typedef long pthread_mutexattr_t;
extern int pthread_create(pthread_t *thread, pthread_attr_t const * attr,
                          void *(*start_routine)(void *), void * arg);
extern int pthread_join(pthread_t thread, void **retval);
extern int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr);
extern int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
extern int pthread_cond_broadcast(pthread_cond_t *cond);
extern int pthread_cond_destroy(pthread_cond_t *cond);
extern int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);
extern int pthread_mutex_lock(pthread_mutex_t *mutex);
extern int pthread_mutex_unlock(pthread_mutex_t *mutex);
extern int pthread_mutex_destroy(pthread_mutex_t *mutex);
#else

// We've already included some of pthreads, may as well include it
// all. This is forced by the OpenCL backend, where CL.h includes some
// of pthreads.
#include <pthread.h>

#endif

extern char *getenv(const char *);
extern int atoi(const char *);

extern int halide_printf(const char *, ...);

#ifndef NULL
#define NULL 0
#endif

struct work {
    work *next_job;
    void (*f)(int, uint8_t *);
    int next, max;
    uint8_t *closure;
    int active_workers;

    bool running() { return next < max || active_workers > 0; }
};

// The work queue and thread pool is weak, so one big work queue is shared by all halide functions
#define MAX_THREADS 64
WEAK struct {
    // all fields are protected by this mutex.
    pthread_mutex_t mutex;

    // Singly linked list for job stack
    work *jobs;

    // Broadcast whenever items are added to the queue or a job completes.
    pthread_cond_t state_change;
    // Keep track of threads so they can be joined at shutdown
    pthread_t threads[MAX_THREADS];

    // Global flag indicating
    bool shutdown;

    bool running() {
        return !shutdown;
    }

} halide_work_queue;

WEAK int halide_threads;
WEAK bool halide_thread_pool_initialized = false;

WEAK void halide_shutdown_thread_pool() {
    if (!halide_thread_pool_initialized) return;

    // Wake everyone up and tell them the party's over and it's time
    // to go home
    pthread_mutex_lock(&halide_work_queue.mutex);
    halide_work_queue.shutdown = true;
    pthread_cond_broadcast(&halide_work_queue.state_change);
    pthread_mutex_unlock(&halide_work_queue.mutex);

    // Wait until they leave
    for (int i = 0; i < halide_threads-1; i++) {
        //fprintf(stderr, "Waiting for thread %d to exit\n", i);
        void *retval;
        pthread_join(halide_work_queue.threads[i], &retval);
    }

    //fprintf(stderr, "All threads have quit. Destroying mutex and condition variable.\n");
    // Tidy up
    pthread_mutex_destroy(&halide_work_queue.mutex);
    pthread_cond_destroy(&halide_work_queue.state_change);
    halide_thread_pool_initialized = false;
}

WEAK void (*halide_custom_do_task)(void (*)(int, uint8_t *), int, uint8_t *);
WEAK void halide_set_custom_do_task(void (*f)(void (*)(int, uint8_t *), int, uint8_t *)) {
    halide_custom_do_task = f;
}

WEAK void (*halide_custom_do_par_for)(void (*)(int, uint8_t *), int, int, uint8_t *);
WEAK void halide_set_custom_do_par_for(void (*f)(void (*)(int, uint8_t *), int, int, uint8_t *)) {
    halide_custom_do_par_for = f;
}

WEAK void halide_do_task(void (*f)(int, uint8_t *), int idx, uint8_t *closure) {
    if (halide_custom_do_task) {
        (*halide_custom_do_task)(f, idx, closure);
    } else {
        f(idx, closure);
    }
}

WEAK void *halide_worker_thread(void *void_arg) {
    work *owned_job = (work *)void_arg;

    // Grab the lock
    pthread_mutex_lock(&halide_work_queue.mutex);

    // If I'm a job owner, then I was the thread that called
    // do_par_for, and I should only stay in this function until my
    // job is complete. If I'm a lowly worker thread, I should stay in
    // this function as long as the work queue is running.
    while (owned_job != NULL ? owned_job->running()
           : halide_work_queue.running()) {

        if (halide_work_queue.jobs == NULL) {
            // There are no jobs pending, though some tasks may still
            // be in flight from the last job. Release the lock and
            // wait for something new to happen.
            pthread_cond_wait(&halide_work_queue.state_change, &halide_work_queue.mutex);
        } else {
            // There are jobs still to do. Grab the next one.
            work *job = halide_work_queue.jobs;

            // Claim a task from it.
            work myjob = *job;
            job->next++;

            // If there were no more tasks pending for this job,
            // remove it from the stack.
            if (job->next == job->max) {
                halide_work_queue.jobs = job->next_job;
            }

            // Increment the active_worker count so that other threads
            // are aware that this job is still in progress even
            // though there are no outstanding tasks for it.
            job->active_workers++;

            // Release the lock and do the task.
            pthread_mutex_unlock(&halide_work_queue.mutex);
            halide_do_task(myjob.f, myjob.next, myjob.closure);
            pthread_mutex_lock(&halide_work_queue.mutex);

            // We are no longer active on this job
            job->active_workers--;

            // If the job is done and I'm not the owner of it, wake up
            // the owner.
            if (!job->running() && job != owned_job) {
                pthread_cond_broadcast(&halide_work_queue.state_change);
            }
        }
    }
    pthread_mutex_unlock(&halide_work_queue.mutex);
    return NULL;
}

WEAK void halide_do_par_for(void (*f)(int, uint8_t *), int min, int size, uint8_t *closure) {
    if (halide_custom_do_par_for) {
        (*halide_custom_do_par_for)(f, min, size, closure);
        return;
    }
    if (!halide_thread_pool_initialized) {
        halide_work_queue.shutdown = false;
        pthread_mutex_init(&halide_work_queue.mutex, NULL);
        pthread_cond_init(&halide_work_queue.state_change, NULL);
        halide_work_queue.jobs = NULL;

        char *threadStr = getenv("HL_NUMTHREADS");
        #ifdef _LP64
        // On 64-bit systems we use 8 threads by default
        halide_threads = 8;
        #else
        // On 32-bit systems we use 2 threads by default
        halide_threads = 2;
        #endif
        if (threadStr) {
            halide_threads = atoi(threadStr);
        } else {
            halide_printf("HL_NUMTHREADS not defined. Defaulting to %d threads.\n", halide_threads);
        }
        if (halide_threads > MAX_THREADS) {
            halide_threads = MAX_THREADS;
        }
        for (int i = 0; i < halide_threads-1; i++) {
            //fprintf(stderr, "Creating thread %d\n", i);
            pthread_create(halide_work_queue.threads + i, NULL, halide_worker_thread, NULL);
        }

        halide_thread_pool_initialized = true;
    }

    // Make the job.
    work job;
    job.f = f;               // The job should call this function. It takes an index and a closure.
    job.next = min;          // Start at this index.
    job.max  = min + size;   // Keep going until one less than this index.
    job.closure = closure;   // Use this closure.
    job.active_workers = 0;

    // Push the job onto the stack.
    pthread_mutex_lock(&halide_work_queue.mutex);
    job.next_job = halide_work_queue.jobs;
    halide_work_queue.jobs = &job;
    pthread_mutex_unlock(&halide_work_queue.mutex);

    // Wake up any idle worker threads.
    pthread_cond_broadcast(&halide_work_queue.state_change);

    // Do some work myself.
    halide_worker_thread((void *)(&job));
}

}
<commit_msg>Choose number of worker threads based on # of CPUs present if HL_NUMTHREADS isn't defined.<commit_after>#include <stdint.h>
#include <unistd.h>

#ifndef __APPLE__
#ifdef _LP64
typedef uint64_t size_t;
#else
typedef uint32_t size_t;
#endif
#endif
#define WEAK __attribute__((weak))

extern "C" {

#ifndef __SIZEOF_PTHREAD_ATTR_T

typedef struct {
    uint32_t flags;
    void * stack_base;
    size_t stack_size;
    size_t guard_size;
    int32_t sched_policy;
    int32_t sched_priority;
} pthread_attr_t;
typedef long pthread_t;
typedef struct {
    // 48 bytes is enough for a cond on 64-bit and 32-bit systems
    unsigned char _private[48];
} pthread_cond_t;
typedef long pthread_condattr_t;
typedef struct {
    // 40 bytes is enough for a mutex on 64-bit and 32-bit systems
    unsigned char _private[40];
} pthread_mutex_t;
typedef long pthread_mutexattr_t;
extern int pthread_create(pthread_t *thread, pthread_attr_t const * attr,
                          void *(*start_routine)(void *), void * arg);
extern int pthread_join(pthread_t thread, void **retval);
extern int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr);
extern int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
extern int pthread_cond_broadcast(pthread_cond_t *cond);
extern int pthread_cond_destroy(pthread_cond_t *cond);
extern int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);
extern int pthread_mutex_lock(pthread_mutex_t *mutex);
extern int pthread_mutex_unlock(pthread_mutex_t *mutex);
extern int pthread_mutex_destroy(pthread_mutex_t *mutex);
#else

// We've already included some of pthreads, may as well include it
// all. This is forced by the OpenCL backend, where CL.h includes some
// of pthreads.
#include <pthread.h>

#endif

extern char *getenv(const char *);
extern int atoi(const char *);

extern int halide_printf(const char *, ...);

#ifndef NULL
#define NULL 0
#endif

struct work {
    work *next_job;
    void (*f)(int, uint8_t *);
    int next, max;
    uint8_t *closure;
    int active_workers;

    bool running() { return next < max || active_workers > 0; }
};

// The work queue and thread pool is weak, so one big work queue is shared by all halide functions
#define MAX_THREADS 64
WEAK struct {
    // all fields are protected by this mutex.
    pthread_mutex_t mutex;

    // Singly linked list for job stack
    work *jobs;

    // Broadcast whenever items are added to the queue or a job completes.
    pthread_cond_t state_change;
    // Keep track of threads so they can be joined at shutdown
    pthread_t threads[MAX_THREADS];

    // Global flag indicating
    bool shutdown;

    bool running() {
        return !shutdown;
    }

} halide_work_queue;

WEAK int halide_threads;
WEAK bool halide_thread_pool_initialized = false;

WEAK void halide_shutdown_thread_pool() {
    if (!halide_thread_pool_initialized) return;

    // Wake everyone up and tell them the party's over and it's time
    // to go home
    pthread_mutex_lock(&halide_work_queue.mutex);
    halide_work_queue.shutdown = true;
    pthread_cond_broadcast(&halide_work_queue.state_change);
    pthread_mutex_unlock(&halide_work_queue.mutex);

    // Wait until they leave
    for (int i = 0; i < halide_threads-1; i++) {
        //fprintf(stderr, "Waiting for thread %d to exit\n", i);
        void *retval;
        pthread_join(halide_work_queue.threads[i], &retval);
    }

    //fprintf(stderr, "All threads have quit. Destroying mutex and condition variable.\n");
    // Tidy up
    pthread_mutex_destroy(&halide_work_queue.mutex);
    pthread_cond_destroy(&halide_work_queue.state_change);
    halide_thread_pool_initialized = false;
}

WEAK void (*halide_custom_do_task)(void (*)(int, uint8_t *), int, uint8_t *);
WEAK void halide_set_custom_do_task(void (*f)(void (*)(int, uint8_t *), int, uint8_t *)) {
    halide_custom_do_task = f;
}

WEAK void (*halide_custom_do_par_for)(void (*)(int, uint8_t *), int, int, uint8_t *);
WEAK void halide_set_custom_do_par_for(void (*f)(void (*)(int, uint8_t *), int, int, uint8_t *)) {
    halide_custom_do_par_for = f;
}

WEAK void halide_do_task(void (*f)(int, uint8_t *), int idx, uint8_t *closure) {
    if (halide_custom_do_task) {
        (*halide_custom_do_task)(f, idx, closure);
    } else {
        f(idx, closure);
    }
}

WEAK void *halide_worker_thread(void *void_arg) {
    work *owned_job = (work *)void_arg;

    // Grab the lock
    pthread_mutex_lock(&halide_work_queue.mutex);

    // If I'm a job owner, then I was the thread that called
    // do_par_for, and I should only stay in this function until my
    // job is complete. If I'm a lowly worker thread, I should stay in
    // this function as long as the work queue is running.
    while (owned_job != NULL ? owned_job->running()
           : halide_work_queue.running()) {

        if (halide_work_queue.jobs == NULL) {
            // There are no jobs pending, though some tasks may still
            // be in flight from the last job. Release the lock and
            // wait for something new to happen.
            pthread_cond_wait(&halide_work_queue.state_change, &halide_work_queue.mutex);
        } else {
            // There are jobs still to do. Grab the next one.
            work *job = halide_work_queue.jobs;

            // Claim a task from it.
            work myjob = *job;
            job->next++;

            // If there were no more tasks pending for this job,
            // remove it from the stack.
            if (job->next == job->max) {
                halide_work_queue.jobs = job->next_job;
            }

            // Increment the active_worker count so that other threads
            // are aware that this job is still in progress even
            // though there are no outstanding tasks for it.
            job->active_workers++;

            // Release the lock and do the task.
            pthread_mutex_unlock(&halide_work_queue.mutex);
            halide_do_task(myjob.f, myjob.next, myjob.closure);
            pthread_mutex_lock(&halide_work_queue.mutex);

            // We are no longer active on this job
            job->active_workers--;

            // If the job is done and I'm not the owner of it, wake up
            // the owner.
            if (!job->running() && job != owned_job) {
                pthread_cond_broadcast(&halide_work_queue.state_change);
            }
        }
    }
    pthread_mutex_unlock(&halide_work_queue.mutex);
    return NULL;
}

WEAK int halide_host_cpu_count() {
    return sysconf(_SC_NPROCESSORS_ONLN);
}

WEAK void halide_do_par_for(void (*f)(int, uint8_t *), int min, int size, uint8_t *closure) {
    if (halide_custom_do_par_for) {
        (*halide_custom_do_par_for)(f, min, size, closure);
        return;
    }
    if (!halide_thread_pool_initialized) {
        halide_work_queue.shutdown = false;
        pthread_mutex_init(&halide_work_queue.mutex, NULL);
        pthread_cond_init(&halide_work_queue.state_change, NULL);
        halide_work_queue.jobs = NULL;

        char *threadStr = getenv("HL_NUMTHREADS");
        if (threadStr) {
            halide_threads = atoi(threadStr);
        } else {
            halide_threads = halide_host_cpu_count();
            halide_printf("HL_NUMTHREADS not defined. Defaulting to %d threads.\n", halide_threads);
        }
        if (halide_threads > MAX_THREADS) {
            halide_threads = MAX_THREADS;
        } else if (halide_threads < 1) {
            halide_threads = 1;
        }
        for (int i = 0; i < halide_threads-1; i++) {
            //fprintf(stderr, "Creating thread %d\n", i);
            pthread_create(halide_work_queue.threads + i, NULL, halide_worker_thread, NULL);
        }

        halide_thread_pool_initialized = true;
    }

    // Make the job.
    work job;
    job.f = f;               // The job should call this function. It takes an index and a closure.
    job.next = min;          // Start at this index.
    job.max  = min + size;   // Keep going until one less than this index.
    job.closure = closure;   // Use this closure.
    job.active_workers = 0;

    // Push the job onto the stack.
    pthread_mutex_lock(&halide_work_queue.mutex);
    job.next_job = halide_work_queue.jobs;
    halide_work_queue.jobs = &job;
    pthread_mutex_unlock(&halide_work_queue.mutex);

    // Wake up any idle worker threads.
    pthread_cond_broadcast(&halide_work_queue.state_change);

    // Do some work myself.
    halide_worker_thread((void *)(&job));
}

}
<|endoftext|>


<commit_before>/**
   @file alsadaptor.cpp
   @brief ALSAdaptor

   Copyright (C) 2009-2010 Nokia Corporation

   @author Timo Rongas <ext-timo.2.rongas@nokia.com>
   @author Ustun Ergenoglu <ext-ustun.ergenoglu@nokia.com>
   @author Matias Muhonen <ext-matias.muhonen@nokia.com>
   @author Tapio Rantala <ext-tapio.rantala@nokia.com>
   @author Lihan Guo <lihan.guo@digia.com>
   @author Antti Virtanen <antti.i.virtanen@nokia.com>
   @author Shenghua <ext-shenghua.1.liu@nokia.com>
   @author Antti Virtanen <antti.i.virtanen@nokia.com>

   This file is part of Sensord.

   Sensord 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.

   Sensord 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 Sensord.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "logging.h"
#include "config.h"
#include "alsadaptor.h"
#include <errno.h>
#include "datatypes/utils.h"
#include <linux/types.h>
#include <QFile>

/* Device name: /dev/apds990x0 */
struct apds990x_data {
    __u32 lux; /* 10x scale */
    __u32 lux_raw; /* 10x scale */
    __u16 ps;
    __u16 ps_raw;
    __u16 status;
} __attribute__((packed));

struct bh1770glc_als {
    __u16 lux;
} __attribute__((packed));

ALSAdaptor::ALSAdaptor(const QString& id):
    SysfsAdaptor(id, SysfsAdaptor::SelectMode, false),
#ifdef SENSORFW_MCE_WATCHER
    alsEnabled(false),
#endif
    deviceType_(DeviceUnknown)
{
    alsBuffer_ = new DeviceAdaptorRingBuffer<TimedUnsigned>(1);
    setAdaptedSensor("als", "Internal ambient light sensor lux values", alsBuffer_);
    setDescription("Ambient light");
    deviceType_ = (DeviceType)Config::configuration()->value<int>("als/driver_type", DeviceUnknown);
    powerStatePath_ = Config::configuration()->value("als/powerstate_path").toByteArray();

#ifdef SENSORFW_MCE_WATCHER
    dbusIfc = new QDBusInterface(MCE_SERVICE, MCE_REQUEST_PATH, MCE_REQUEST_IF,
                                 QDBusConnection::systemBus(), this);
#endif
}

ALSAdaptor::~ALSAdaptor()
{
#ifdef SENSORFW_MCE_WATCHER
    delete dbusIfc;
#endif
    delete alsBuffer_;
}

#ifdef SENSORFW_MCE_WATCHER
void ALSAdaptor::enableALS()
{
    if(!alsEnabled)
    {
        sensordLogT() << "Requesting MCE to enable ALS";
        dbusIfc->call(QDBus::NoBlock, "req_als_enable");
        alsEnabled = true;
    }
}

void ALSAdaptor::disableALS()
{
    if(alsEnabled)
    {
        sensordLogT() << "Requesting MCE to disable ALS";
        dbusIfc->call(QDBus::NoBlock, "req_als_disable");
        alsEnabled = false;
    }
}
#endif

bool ALSAdaptor::startSensor()
{
    if(deviceType_ == NCDK && !powerStatePath_.isEmpty())
    {
        writeToFile(powerStatePath_, "1");
    }
    if (SysfsAdaptor::startSensor())
    {
#ifdef SENSORFW_MCE_WATCHER
        enableALS();
#endif
        return true;
    }
    return false;
}

void ALSAdaptor::stopSensor()
{
    if(deviceType_ == NCDK && !powerStatePath_.isEmpty())
    {
        writeToFile(powerStatePath_, "0");
    }
#ifdef SENSORFW_MCE_WATCHER
    disableALS();
#endif
    SysfsAdaptor::stopSensor();
}

bool ALSAdaptor::standby()
{
    if(SysfsAdaptor::standby())
    {
#ifdef SENSORFW_MCE_WATCHER
        disableALS();
#endif
        return true;
    }
    return false;
}

bool ALSAdaptor::resume()
{
    if(SysfsAdaptor::resume())
    {
#ifdef SENSORFW_MCE_WATCHER
        enableALS();
#endif
        return true;
    }
    return false;
}

void ALSAdaptor::processSample(int pathId, int fd)
{
    Q_UNUSED(pathId);

    if(deviceType_ == RM680)
    {
        struct bh1770glc_als als_data;
        als_data.lux = 0;

        int bytesRead = read(fd, &als_data, sizeof(als_data));

        if (bytesRead <= 0) {
            sensordLogW() << "read(): " << strerror(errno);
            return;
        }
        sensordLogW() << "Ambient light value: " << als_data.lux;

        TimedUnsigned* lux = alsBuffer_->nextSlot();
        lux->value_ = als_data.lux;
        lux->timestamp_ = Utils::getTimeStamp();
    }
    else if (deviceType_ == RM696)
    {
        struct apds990x_data als_data;
        als_data.lux = 0;

        int bytesRead = read(fd, &als_data, sizeof(als_data));

        if (bytesRead <= 0) {
            sensordLogW() << "read(): " << strerror(errno);
            return;
        }
        sensordLogT() << "Ambient light value: " << als_data.lux;

        TimedUnsigned* lux = alsBuffer_->nextSlot();
        lux->value_ = als_data.lux;
        lux->timestamp_ = Utils::getTimeStamp();
    }
    else if (deviceType_ == NCDK)
    {
        char buffer[32];
        memset(buffer, 0, sizeof(buffer));
        int bytesRead = read(fd, &buffer, sizeof(buffer));
        if (bytesRead <= 0) {
            sensordLogW() << "read(): " << strerror(errno);
            return;
        }
        QVariant value(buffer);
        bool ok;
        double fValue(value.toDouble(&ok));
        if(!ok) {
            sensordLogT() << "read(): failed to parse float from: " << buffer;
            return;
        }
        TimedUnsigned* lux = alsBuffer_->nextSlot();
        lux->value_ = fValue * 10;
        lux->timestamp_ = Utils::getTimeStamp();
        sensordLogT() << "Ambient light value: " << lux->value_;
    }
    else
    {
        sensordLogW() << "Not known device type: " << deviceType_;
        return;
    }
    alsBuffer_->commit();
    alsBuffer_->wakeUpReaders();
}
<commit_msg>[sensorfw] Fix in ALSAdaptor, logging and power.<commit_after>/**
   @file alsadaptor.cpp
   @brief ALSAdaptor

   Copyright (C) 2009-2010 Nokia Corporation

   @author Timo Rongas <ext-timo.2.rongas@nokia.com>
   @author Ustun Ergenoglu <ext-ustun.ergenoglu@nokia.com>
   @author Matias Muhonen <ext-matias.muhonen@nokia.com>
   @author Tapio Rantala <ext-tapio.rantala@nokia.com>
   @author Lihan Guo <lihan.guo@digia.com>
   @author Antti Virtanen <antti.i.virtanen@nokia.com>
   @author Shenghua <ext-shenghua.1.liu@nokia.com>
   @author Antti Virtanen <antti.i.virtanen@nokia.com>

   This file is part of Sensord.

   Sensord 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.

   Sensord 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 Sensord.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "logging.h"
#include "config.h"
#include "alsadaptor.h"
#include <errno.h>
#include "datatypes/utils.h"
#include <linux/types.h>
#include <QFile>

/* Device name: /dev/apds990x0 */
struct apds990x_data {
    __u32 lux; /* 10x scale */
    __u32 lux_raw; /* 10x scale */
    __u16 ps;
    __u16 ps_raw;
    __u16 status;
} __attribute__((packed));

struct bh1770glc_als {
    __u16 lux;
} __attribute__((packed));

ALSAdaptor::ALSAdaptor(const QString& id):
    SysfsAdaptor(id, SysfsAdaptor::SelectMode, false),
#ifdef SENSORFW_MCE_WATCHER
    alsEnabled(false),
#endif
    deviceType_(DeviceUnknown)
{
    alsBuffer_ = new DeviceAdaptorRingBuffer<TimedUnsigned>(1);
    setAdaptedSensor("als", "Internal ambient light sensor lux values", alsBuffer_);
    setDescription("Ambient light");
    deviceType_ = (DeviceType)Config::configuration()->value<int>("als/driver_type", DeviceUnknown);
    powerStatePath_ = Config::configuration()->value("als/powerstate_path").toByteArray();

#ifdef SENSORFW_MCE_WATCHER
    dbusIfc = new QDBusInterface(MCE_SERVICE, MCE_REQUEST_PATH, MCE_REQUEST_IF,
                                 QDBusConnection::systemBus(), this);
#endif
}

ALSAdaptor::~ALSAdaptor()
{
#ifdef SENSORFW_MCE_WATCHER
    delete dbusIfc;
#endif
    delete alsBuffer_;
}

#ifdef SENSORFW_MCE_WATCHER
void ALSAdaptor::enableALS()
{
    if(!alsEnabled)
    {
        sensordLogT() << "Requesting MCE to enable ALS";
        dbusIfc->call(QDBus::NoBlock, "req_als_enable");
        alsEnabled = true;
    }
}

void ALSAdaptor::disableALS()
{
    if(alsEnabled)
    {
        sensordLogT() << "Requesting MCE to disable ALS";
        dbusIfc->call(QDBus::NoBlock, "req_als_disable");
        alsEnabled = false;
    }
}
#endif

bool ALSAdaptor::startSensor()
{
    if(!powerStatePath_.isEmpty())
    {
        writeToFile(powerStatePath_, "1");
    }
    if (SysfsAdaptor::startSensor())
    {
#ifdef SENSORFW_MCE_WATCHER
        enableALS();
#endif
        return true;
    }
    return false;
}

void ALSAdaptor::stopSensor()
{
    if(!powerStatePath_.isEmpty())
    {
        writeToFile(powerStatePath_, "0");
    }
#ifdef SENSORFW_MCE_WATCHER
    disableALS();
#endif
    SysfsAdaptor::stopSensor();
}

bool ALSAdaptor::standby()
{
    if(SysfsAdaptor::standby())
    {
#ifdef SENSORFW_MCE_WATCHER
        disableALS();
#endif
        return true;
    }
    return false;
}

bool ALSAdaptor::resume()
{
    if(SysfsAdaptor::resume())
    {
#ifdef SENSORFW_MCE_WATCHER
        enableALS();
#endif
        return true;
    }
    return false;
}

void ALSAdaptor::processSample(int pathId, int fd)
{
    Q_UNUSED(pathId);

    if(deviceType_ == RM680)
    {
        struct bh1770glc_als als_data;
        als_data.lux = 0;

        int bytesRead = read(fd, &als_data, sizeof(als_data));

        if (bytesRead <= 0) {
            sensordLogW() << "read(): " << strerror(errno);
            return;
        }
        sensordLogT() << "Ambient light value: " << als_data.lux;

        TimedUnsigned* lux = alsBuffer_->nextSlot();
        lux->value_ = als_data.lux;
        lux->timestamp_ = Utils::getTimeStamp();
    }
    else if (deviceType_ == RM696)
    {
        struct apds990x_data als_data;
        als_data.lux = 0;

        int bytesRead = read(fd, &als_data, sizeof(als_data));

        if (bytesRead <= 0) {
            sensordLogW() << "read(): " << strerror(errno);
            return;
        }
        sensordLogT() << "Ambient light value: " << als_data.lux;

        TimedUnsigned* lux = alsBuffer_->nextSlot();
        lux->value_ = als_data.lux;
        lux->timestamp_ = Utils::getTimeStamp();
    }
    else if (deviceType_ == NCDK)
    {
        char buffer[32];
        memset(buffer, 0, sizeof(buffer));
        int bytesRead = read(fd, &buffer, sizeof(buffer));
        if (bytesRead <= 0) {
            sensordLogW() << "read(): " << strerror(errno);
            return;
        }
        QVariant value(buffer);
        bool ok;
        double fValue(value.toDouble(&ok));
        if(!ok) {
            sensordLogT() << "read(): failed to parse float from: " << buffer;
            return;
        }
        TimedUnsigned* lux = alsBuffer_->nextSlot();
        lux->value_ = fValue * 10;
        lux->timestamp_ = Utils::getTimeStamp();
        sensordLogT() << "Ambient light value: " << lux->value_;
    }
    else
    {
        sensordLogW() << "Not known device type: " << deviceType_;
        return;
    }
    alsBuffer_->commit();
    alsBuffer_->wakeUpReaders();
}
<|endoftext|>


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

#include "TextButton.hh"
#include "TextUtils.hh"
#include "Font.hh"
#include "GContext.hh"
#include <cstdio>

namespace FbTk {

TextButton::TextButton(const FbTk::FbWindow &parent,
                       FbTk::Font &font,
                       const FbTk::BiDiString &text):
    FbTk::Button(parent, 0, 0, 10, 10),
    m_font(&font),
    m_text(text),
    m_justify(FbTk::LEFT),
    m_orientation(FbTk::ROT0),
    m_bevel(1),
    m_left_padding(0),
    m_right_padding(0) {

    setRenderer(*this);
}

void TextButton::setJustify(FbTk::Justify just) {
    m_justify = just;
}

bool TextButton::setOrientation(FbTk::Orientation orient) {

    if (orient == m_orientation
        || !m_font->validOrientation(orient))
        return false;

    invalidateBackground();

    if (((m_orientation == FbTk::ROT0 || m_orientation == FbTk::ROT180) &&
         (orient == FbTk::ROT90 || orient == FbTk::ROT270)) ||
        ((m_orientation == FbTk::ROT90 || m_orientation == FbTk::ROT270) &&
         (orient == FbTk::ROT0 || orient == FbTk::ROT180))) {

        m_orientation = orient;
        resize(height(), width());
    } else {
        m_orientation = orient;
    }

    return true;
}

void TextButton::setText(const FbTk::BiDiString &text) {
    if (m_text.logical() != text.logical()) {
        m_text = text;
        updateBackground(false);
        clear();
    }
}

void TextButton::setFont(FbTk::Font &font) {
    // no need to set new font if it's the same
    if (&font == m_font)
        return;
    m_font = &font;
    font.validOrientation(m_orientation); // load the orientation!
}

void TextButton::setTextPaddingLeft(unsigned int leftpadding) {
    m_left_padding = leftpadding;
}

void TextButton::setTextPaddingRight(unsigned int rightpadding) {
    m_right_padding = rightpadding;
}

void TextButton::setTextPadding(unsigned int padding) {
    setTextPaddingLeft(padding/2);
    setTextPaddingRight(padding/2);
}

/// clear window and redraw text
void TextButton::clear() {
    TextButton::clearArea(0, 0, width(), height());
}

void TextButton::clearArea(int x, int y,
                           unsigned int width, unsigned int height,
                           bool exposure) {
    Button::clearArea(x, y, width, height, exposure);
}

unsigned int TextButton::textWidth() const {
    return font().textWidth(text());
}

void TextButton::renderForeground(FbWindow &win, FbDrawable &drawable) {
    // (win should always be *this, no need to check)
    drawText(0, 0, &drawable);
}

void TextButton::drawText(int x_offset, int y_offset, FbDrawable *drawable) {

    if (drawable == 0)
        drawable = this;

    const FbString& visual = text().visual();
    unsigned int textlen = visual.size();
    unsigned int button_width = width();
    unsigned int button_height = height();
    const int max_width = static_cast<int>(button_width) - x_offset -
        m_left_padding - m_right_padding;

    if (max_width <= bevel()) {
        return;
    }

    translateSize(m_orientation, button_width, button_height);

    // horizontal alignment, cut off text if needed
    int align_x = FbTk::doAlignment(max_width,
                                    bevel(), justify(), font(),
                                    visual.data(), visual.size(),
                                    textlen); // return new text len

    //
    //  we center the text vertically. to do this we have to nudge the
    //  baseline a little bit down so the "middle" of the glyph is placed
    //  on the middle of the button. we "assume", that ascent/2 is roughly
    //  the middle of the glyph. example:
    //
    //   +== ascent <--------->==                       +=====================
    //   |          |         |                         |
    //   |          |  ggggg  |                         |   ascent <--------->
    //   |          |  g  gg  |                         |          |         |
    //   | baseline <  glyph  |                         |          |  ggggg  |
    //   |          |      g  |  -- middle of button -- |          |  g  gg  |
    //   |  descent <  ggggg  |                         | baseline <  glyph  |
    //   |  height  |_________|                         |          |      g  |
    //   |                                              |  descent <  ggggg  |
    //   |                                              |   height |_________|
    //   |                                              |
    //   +=======================                       +=====================
    //
    //    ascent = 4
    //    button_height = 11
    //    baseline = (11 + 4) / 2 - 1 = 6
    //

    int baseline_x = align_x + x_offset + m_left_padding;
    int baseline_y = ((button_height + font().ascent()) / 2) - 1 + y_offset;

    // TODO: remove debug output fprintf(stderr, "%d | %d %d %d\n", height(), font().height(), font().ascent(), font().descent());

    // give it ROT0 style coords
    translateCoords(m_orientation, baseline_x, baseline_y, button_width, button_height);

    font().drawText(*drawable, screenNumber(), gc(),
                    visual.c_str(), textlen,
                    baseline_x, baseline_y, m_orientation);
}

bool TextButton::textExceeds(int x_offset) {

    const FbString& visual = text().visual();
    unsigned int textlen = visual.size();
    unsigned int button_width = width();
    unsigned int button_height = height();
    translateSize(m_orientation, button_width, button_height);

    FbTk::doAlignment(button_width - x_offset - m_left_padding - m_right_padding,
                      bevel(), justify(), font(), visual.data(), visual.size(),
                      textlen); // return new text len

    return visual.size() > textlen;
}

void TextButton::exposeEvent(XExposeEvent &event) {
    clearArea(event.x, event.y, event.width, event.height, false);
}

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

#include "TextButton.hh"
#include "TextUtils.hh"
#include "Font.hh"
#include "GContext.hh"

namespace FbTk {

TextButton::TextButton(const FbTk::FbWindow &parent,
                       FbTk::Font &font,
                       const FbTk::BiDiString &text):
    FbTk::Button(parent, 0, 0, 10, 10),
    m_font(&font),
    m_text(text),
    m_justify(FbTk::LEFT),
    m_orientation(FbTk::ROT0),
    m_bevel(1),
    m_left_padding(0),
    m_right_padding(0) {

    setRenderer(*this);
}

void TextButton::setJustify(FbTk::Justify just) {
    m_justify = just;
}

bool TextButton::setOrientation(FbTk::Orientation orient) {

    if (orient == m_orientation
        || !m_font->validOrientation(orient))
        return false;

    invalidateBackground();

    if (((m_orientation == FbTk::ROT0 || m_orientation == FbTk::ROT180) &&
         (orient == FbTk::ROT90 || orient == FbTk::ROT270)) ||
        ((m_orientation == FbTk::ROT90 || m_orientation == FbTk::ROT270) &&
         (orient == FbTk::ROT0 || orient == FbTk::ROT180))) {

        m_orientation = orient;
        resize(height(), width());
    } else {
        m_orientation = orient;
    }

    return true;
}

void TextButton::setText(const FbTk::BiDiString &text) {
    if (m_text.logical() != text.logical()) {
        m_text = text;
        updateBackground(false);
        clear();
    }
}

void TextButton::setFont(FbTk::Font &font) {
    // no need to set new font if it's the same
    if (&font == m_font)
        return;
    m_font = &font;
    font.validOrientation(m_orientation); // load the orientation!
}

void TextButton::setTextPaddingLeft(unsigned int leftpadding) {
    m_left_padding = leftpadding;
}

void TextButton::setTextPaddingRight(unsigned int rightpadding) {
    m_right_padding = rightpadding;
}

void TextButton::setTextPadding(unsigned int padding) {
    setTextPaddingLeft(padding/2);
    setTextPaddingRight(padding/2);
}

/// clear window and redraw text
void TextButton::clear() {
    TextButton::clearArea(0, 0, width(), height());
}

void TextButton::clearArea(int x, int y,
                           unsigned int width, unsigned int height,
                           bool exposure) {
    Button::clearArea(x, y, width, height, exposure);
}

unsigned int TextButton::textWidth() const {
    return font().textWidth(text());
}

void TextButton::renderForeground(FbWindow &win, FbDrawable &drawable) {
    // (win should always be *this, no need to check)
    drawText(0, 0, &drawable);
}

void TextButton::drawText(int x_offset, int y_offset, FbDrawable *drawable) {

    if (drawable == 0)
        drawable = this;

    const FbString& visual = text().visual();
    unsigned int textlen = visual.size();
    unsigned int button_width = width();
    unsigned int button_height = height();
    int padding = m_left_padding + m_right_padding;

    int n_pixels = static_cast<int>(button_width) - x_offset;
    if (m_orientation == ROT90 || m_orientation == ROT270) {
        n_pixels = static_cast<int>(button_height) - y_offset;
    }
    n_pixels -= padding;

    // text is to small to render
    if (n_pixels <= bevel()) {
        return;
    }

    translateSize(m_orientation, button_width, button_height);

    // horizontal alignment, cut off text if needed
    int align_x = FbTk::doAlignment(n_pixels,
                                    bevel(), justify(), font(),
                                    visual.data(), visual.size(),
                                    textlen); // return new text len

    //
    //  we center the text vertically. to do this we have to nudge the
    //  baseline a little bit down so the "middle" of the glyph is placed
    //  on the middle of the button. we "assume", that ascent/2 is roughly
    //  the middle of the glyph. example:
    //
    //   +== ascent <--------->==                       +=====================
    //   |          |         |                         |
    //   |          |  ggggg  |                         |   ascent <--------->
    //   |          |  g  gg  |                         |          |         |
    //   | baseline <  glyph  |                         |          |  ggggg  |
    //   |          |      g  |  -- middle of button -- |          |  g  gg  |
    //   |  descent <  ggggg  |                         | baseline <  glyph  |
    //   |  height  |_________|                         |          |      g  |
    //   |                                              |  descent <  ggggg  |
    //   |                                              |   height |_________|
    //   |                                              |
    //   +=======================                       +=====================
    //
    //    ascent = 4
    //    button_height = 11
    //    baseline = (11 + 4) / 2 - 1 = 6
    //

    int baseline_x = align_x + x_offset + m_left_padding;
    int baseline_y = ((button_height + font().ascent()) / 2) - 1 + y_offset;

    // TODO: remove debug output fprintf(stderr, "%d | %d %d %d\n", height(), font().height(), font().ascent(), font().descent());

    // give it ROT0 style coords
    translateCoords(m_orientation, baseline_x, baseline_y, button_width, button_height);

    font().drawText(*drawable, screenNumber(), gc(),
                    visual.c_str(), textlen,
                    baseline_x, baseline_y, m_orientation);
}

bool TextButton::textExceeds(int x_offset) {

    const FbString& visual = text().visual();
    unsigned int textlen = visual.size();
    unsigned int button_width = width();
    unsigned int button_height = height();
    translateSize(m_orientation, button_width, button_height);

    FbTk::doAlignment(button_width - x_offset - m_left_padding - m_right_padding,
                      bevel(), justify(), font(), visual.data(), visual.size(),
                      textlen); // return new text len

    return visual.size() > textlen;
}

void TextButton::exposeEvent(XExposeEvent &event) {
    clearArea(event.x, event.y, event.width, event.height, false);
}

} // end namespace FbTk
<|endoftext|>


<commit_before>//
// HTTPTimeServer.cpp
//
// $Id: //poco/1.4/Net/samples/HTTPTimeServer/src/HTTPTimeServer.cpp#1 $
//
// This sample demonstrates the HTTPServer and related classes.
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier:	BSL-1.0
//

#include "Poco/Net/HTTPServer.h"
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/ServerSocket.h"
#include "Poco/Timestamp.h"
#include "Poco/DateTimeFormatter.h"
#include "Poco/DateTimeFormat.h"
#include "Poco/Exception.h"
#include "Poco/ThreadPool.h"
#include "Poco/Util/ServerApplication.h"
#include "Poco/Util/Option.h"
#include "Poco/Util/OptionSet.h"
#include "Poco/Util/HelpFormatter.h"
#include <iostream>

using Poco::Net::ServerSocket;
using Poco::Net::HTTPRequestHandler;
using Poco::Net::HTTPRequestHandlerFactory;
using Poco::Net::HTTPServer;
using Poco::Net::HTTPServerRequest;
using Poco::Net::HTTPServerResponse;
using Poco::Net::HTTPServerParams;
using Poco::Timestamp;
using Poco::DateTimeFormatter;
using Poco::DateTimeFormat;
using Poco::ThreadPool;
using Poco::Util::ServerApplication;
using Poco::Util::Application;
using Poco::Util::Option;
using Poco::Util::OptionSet;
using Poco::Util::HelpFormatter;

class TimeRequestHandler: public HTTPRequestHandler
	/// Return a HTML document with the current date and time.
{
public:
	TimeRequestHandler(const std::string& format):
		_format(format)
	{
	}

	void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response)
	{
		Application& app = Application::instance();
		app.logger().information("Request from " + request.clientAddress().toString());

		Timestamp now;
		std::string dt(DateTimeFormatter::format(now, _format));

		response.setChunkedTransferEncoding(true);
		response.setContentType("text/html");

		std::ostream& ostr = response.send();
		ostr << "<title>HTTPTimeServer powered by POCO C++ Libraries</title>";
		ostr << "<meta http-equiv=\"refresh\" content=\"1\">";
		ostr << "
";
		ostr << dt;
		ostr << "
";
	}

private:
	std::string _format;
};

class TimeRequestHandlerFactory: public HTTPRequestHandlerFactory
{
public:
	TimeRequestHandlerFactory(const std::string& format):
		_format(format)
	{
	}

	HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request)
	{
		if (request.getURI() == "/")
			return new TimeRequestHandler(_format);
		else
			return 0;
	}

private:
	std::string _format;
};

class HTTPTimeServer: public Poco::Util::ServerApplication
	/// The main application class.
	///
	/// This class handles command-line arguments and
	/// configuration files.
	/// Start the HTTPTimeServer executable with the help
	/// option (/help on Windows, --help on Unix) for
	/// the available command line options.
	///
	/// To use the sample configuration file (HTTPTimeServer.properties),
	/// copy the file to the directory where the HTTPTimeServer executable
	/// resides. If you start the debug version of the HTTPTimeServer
	/// (HTTPTimeServerd[.exe]), you must also create a copy of the configuration
	/// file named HTTPTimeServerd.properties. In the configuration file, you
	/// can specify the port on which the server is listening (default
	/// 9980) and the format of the date/time string sent back to the client.
	///
	/// To test the TimeServer you can use any web browser (http://localhost:9980/).
{
public:
	HTTPTimeServer(): _helpRequested(false)
	{
	}

	~HTTPTimeServer()
	{
	}

protected:
	void initialize(Application& self)
	{
		loadConfiguration(); // load default configuration files, if present
		ServerApplication::initialize(self);
	}

	void uninitialize()
	{
		ServerApplication::uninitialize();
	}

	void defineOptions(OptionSet& options)
	{
		ServerApplication::defineOptions(options);

		options.addOption(
			Option("help", "h", "display help information on command line arguments")
				.required(false)
				.repeatable(false));
	}

	void handleOption(const std::string& name, const std::string& value)
	{
		ServerApplication::handleOption(name, value);

		if (name == "help")
			_helpRequested = true;
	}

	void displayHelp()
	{
		HelpFormatter helpFormatter(options());
		helpFormatter.setCommand(commandName());
		helpFormatter.setUsage("OPTIONS");
		helpFormatter.setHeader("A web server that serves the current date and time.");
		helpFormatter.format(std::cout);
	}

	int main(const std::vector<std::string>& args)
	{
		if (_helpRequested)
		{
			displayHelp();
		}
		else
		{
			// get parameters from configuration file
			unsigned short port = (unsigned short) config().getInt("HTTPTimeServer.port", 9980);
			std::string format(config().getString("HTTPTimeServer.format", DateTimeFormat::SORTABLE_FORMAT));
			int maxQueued  = config().getInt("HTTPTimeServer.maxQueued", 100);
			int maxThreads = config().getInt("HTTPTimeServer.maxThreads", 16);
			ThreadPool::defaultPool().addCapacity(maxThreads);

			HTTPServerParams* pParams = new HTTPServerParams;
			pParams->setMaxQueued(maxQueued);
			pParams->setMaxThreads(maxThreads);

			// set-up a server socket
			ServerSocket svs(port);
			// set-up a HTTPServer instance
			HTTPServer srv(new TimeRequestHandlerFactory(format), svs, pParams);
			// start the HTTPServer
			srv.start();
			// wait for CTRL-C or kill
			waitForTerminationRequest();
			// Stop the HTTPServer
			srv.stop();
		}
		return Application::EXIT_OK;
	}

private:
	bool _helpRequested;
};

int main(int argc, char** argv)
{
	HTTPTimeServer app;
	return app.run(argc, argv);
}
<commit_msg>remove extra files<commit_after><|endoftext|>


<commit_before>#include "TString.h"
#include "TCint.h"
#include <fstream>
#include "TH1.h"
#include "TGraphSmooth.h"
#include "TCanvas.h"
#include "TSystem.h"

TCanvas *vC1;
TGraph *grin, *grout;

void DrawSmooth(Int_t pad, const char *title, const char *xt, const char *yt)
{
   vC1->cd(pad);
   TH1F *vFrame = vC1->DrawFrame(0,-130,60,70);
   vFrame->SetTitle(title);
   vFrame->SetTitleSize(0.2);
   vFrame->SetXTitle(xt);
   vFrame->SetYTitle(yt);
   grin->Draw("P");
//   grout->SetMarkerColor(kRed);
//   grout->SetMarkerStyle(21);
//   grout->SetMarkerSize(0.5);
//   grout->DrawClone("P");
   grout->DrawClone("LPX");
}

void motorcycle()
{
/******************************************************************************
* Author: Christian Stratowa, Vienna, Austria.                                *
* Created: 26 Aug 2001                            Last modified: 29 Sep 2001  *
******************************************************************************/

// Macro to test scatterplot smoothers: ksmooth, lowess, supsmu
// as described in:
//    Modern Applied Statistics with S-Plus, 3rd Edition
//    W.N. Venables and B.D. Ripley
//    Chapter 9: Smooth Regression, Figure 9.1
//
// Example is a set of data on 133 observations of acceleration against time
// for a simulated motorcycle accident, taken from Silverman (1985).

// data taken from R library MASS: mcycle.txt
   TString dir = gSystem->UnixPathName(TCint::GetCurrentMacroName());
   dir.ReplaceAll("motorcycle.C","");
   dir.ReplaceAll("/./","/");

// read file and add to fit object
   Double_t *x = new Double_t[133];
   Double_t *y = new Double_t[133];
   Double_t vX, vY;
   Int_t vNData = 0;
   ifstream vInput;
   vInput.open(Form("%smotorcycle.dat",dir.Data()));
   while (1) {
      vInput >> vX >> vY;
      if (!vInput.good()) break;
      x[vNData] = vX;
      y[vNData] = vY;
      vNData++;
   }//while
   vInput.close();
   grin = new TGraph(vNData,x,y);

// draw graph
   vC1 = new TCanvas("vC1","Smooth Regression",200,10,900,700);
   vC1->Divide(2,3);

// Kernel Smoother
// create new kernel smoother and smooth data with bandwidth = 2.0
   TGraphSmooth *gs = new TGraphSmooth("normal");
   grout = gs->SmoothKern(grin,"normal",2.0);
   DrawSmooth(1,"Kernel Smoother: bandwidth = 2.0","times","accel");

// redraw ksmooth with bandwidth = 5.0
   grout = gs->SmoothKern(grin,"normal",5.0);
   DrawSmooth(2,"Kernel Smoother: bandwidth = 5.0","","");

// Lowess Smoother
// create new lowess smoother and smooth data with fraction f = 2/3
   grout = gs->SmoothLowess(grin,"",0.67);
   DrawSmooth(3,"Lowess: f = 2/3","","");

// redraw lowess with fraction f = 0.2
   grout = gs->SmoothLowess(grin,"",0.2);
   DrawSmooth(4,"Lowess: f = 0.2","","");

// Super Smoother
// create new super smoother and smooth data with default bass = 0 and span = 0
   grout = gs->SmoothSuper(grin,"",0,0);
   DrawSmooth(5,"Super Smoother: bass = 0","","");

// redraw supsmu with bass = 3 (smoother curve)
   grout = gs->SmoothSuper(grin,"",3);
   DrawSmooth(6,"Super Smoother: bass = 3","","");

// cleanup
   delete [] x;
   delete [] y;
   delete gs;
}

<commit_msg>When calling TPad::DrawFrame, one must use the current pad (gPad)<commit_after>#include "TString.h"
#include "TCint.h"
#include <fstream>
#include "TH1.h"
#include "TGraphSmooth.h"
#include "TCanvas.h"
#include "TSystem.h"

TCanvas *vC1;
TGraph *grin, *grout;

void DrawSmooth(Int_t pad, const char *title, const char *xt, const char *yt)
{
   vC1->cd(pad);
   TH1F *vFrame = gPad->DrawFrame(0,-130,60,70);
   vFrame->SetTitle(title);
   vFrame->SetTitleSize(0.2);
   vFrame->SetXTitle(xt);
   vFrame->SetYTitle(yt);
   grin->Draw("P");
//   grout->SetMarkerColor(kRed);
//   grout->SetMarkerStyle(21);
//   grout->SetMarkerSize(0.5);
//   grout->DrawClone("P");
   grout->DrawClone("LPX");
}

void motorcycle()
{
/******************************************************************************
* Author: Christian Stratowa, Vienna, Austria.                                *
* Created: 26 Aug 2001                            Last modified: 29 Sep 2001  *
******************************************************************************/

// Macro to test scatterplot smoothers: ksmooth, lowess, supsmu
// as described in:
//    Modern Applied Statistics with S-Plus, 3rd Edition
//    W.N. Venables and B.D. Ripley
//    Chapter 9: Smooth Regression, Figure 9.1
//
// Example is a set of data on 133 observations of acceleration against time
// for a simulated motorcycle accident, taken from Silverman (1985).

// data taken from R library MASS: mcycle.txt
   TString dir = gSystem->UnixPathName(TCint::GetCurrentMacroName());
   dir.ReplaceAll("motorcycle.C","");
   dir.ReplaceAll("/./","/");

// read file and add to fit object
   Double_t *x = new Double_t[133];
   Double_t *y = new Double_t[133];
   Double_t vX, vY;
   Int_t vNData = 0;
   ifstream vInput;
   vInput.open(Form("%smotorcycle.dat",dir.Data()));
   while (1) {
      vInput >> vX >> vY;
      if (!vInput.good()) break;
      x[vNData] = vX;
      y[vNData] = vY;
      vNData++;
   }//while
   vInput.close();
   grin = new TGraph(vNData,x,y);

// draw graph
   vC1 = new TCanvas("vC1","Smooth Regression",200,10,900,700);
   vC1->Divide(2,3);

// Kernel Smoother
// create new kernel smoother and smooth data with bandwidth = 2.0
   TGraphSmooth *gs = new TGraphSmooth("normal");
   grout = gs->SmoothKern(grin,"normal",2.0);
   DrawSmooth(1,"Kernel Smoother: bandwidth = 2.0","times","accel");

// redraw ksmooth with bandwidth = 5.0
   grout = gs->SmoothKern(grin,"normal",5.0);
   DrawSmooth(2,"Kernel Smoother: bandwidth = 5.0","","");

// Lowess Smoother
// create new lowess smoother and smooth data with fraction f = 2/3
   grout = gs->SmoothLowess(grin,"",0.67);
   DrawSmooth(3,"Lowess: f = 2/3","","");

// redraw lowess with fraction f = 0.2
   grout = gs->SmoothLowess(grin,"",0.2);
   DrawSmooth(4,"Lowess: f = 0.2","","");

// Super Smoother
// create new super smoother and smooth data with default bass = 0 and span = 0
   grout = gs->SmoothSuper(grin,"",0,0);
   DrawSmooth(5,"Super Smoother: bass = 0","","");

// redraw supsmu with bass = 3 (smoother curve)
   grout = gs->SmoothSuper(grin,"",3);
   DrawSmooth(6,"Super Smoother: bass = 3","","");

// cleanup
   delete [] x;
   delete [] y;
   delete gs;
}

<|endoftext|>


<commit_before>#define CATCH_CONFIG_MAIN  // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "Vec.h"

TEST_CASE( "vector", "[vec]" ) {

  Vec a = Vec(5);
  Vec b = Vec(4);

  for( int i = 0; i < 4; i++ ){
    a._vec[i] = i; //0 to 3
    b._vec[i] = i + 10; //10 to 13
  }
  a._vec[4] = 4;

  SECTION( "resizing dimension" ) {
    a.SetDim(4);
    REQUIRE( a._dim == 4 );
    for( int i = 0; i < 4; i++ ){
      REQUIRE( a._vec[i] == i );
    }
  }

  a.SetDim(4);
  Vec copied = a;
  SECTION( "copy"){
    for( int i = 0; i < 4; i++ ){
      REQUIRE( copied._vec[i] == a._vec[i] );
    }
  }

  SECTION( "adddition" ) {
    Vec c = copied+b;

    REQUIRE( c._vec[0] == 10 );
    REQUIRE( c._vec[1] == 12 );
    REQUIRE( c._vec[2] == 14 );
    REQUIRE( c._vec[3] == 16 );
  }

  SECTION( "subtraction" ) {
    Vec c = b-copied;

    REQUIRE( c._vec[0] == 10 );
    REQUIRE( c._vec[1] == 10 );
    REQUIRE( c._vec[2] == 10 );
    REQUIRE( c._vec[3] == 10 );
  }

  SECTION( "dot product" ) {
    float c = b.Dot(copied);

    REQUIRE( c == 74 );
  }

  SECTION( "cross product" ) {
    copied.SetDim(3);
    b.SetDim(3);
    Vec c = b.Cross(copied);

    REQUIRE( c._vec[0] == 10 );
    REQUIRE( c._vec[1] == -20 );
    REQUIRE( c._vec[2] == 10 );
  }

}
<commit_msg>added more tets<commit_after>#define CATCH_CONFIG_MAIN  // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
#include "Vec.h"
#include <math.h>

TEST_CASE( "vector", "[vec]" ) {

  Vec a = Vec(5);
  Vec b = Vec(4);

  for( int i = 0; i < 4; i++ ){
    a._vec[i] = i; //0 to 3
    b._vec[i] = i + 10; //10 to 13
  }
  a._vec[4] = 4;

  SECTION( "resizing dimension" ) {
    a.SetDim(4);
    REQUIRE( a._dim == 4 );
    for( int i = 0; i < 4; i++ ){
      REQUIRE( a._vec[i] == i );
    }
  }

  a.SetDim(4);
  Vec copied = a;
  SECTION( "copy"){
    for( int i = 0; i < 4; i++ ){
      REQUIRE( copied._vec[i] == a._vec[i] );
    }
  }

  SECTION( "adddition" ) {
    Vec c = copied+b;

    REQUIRE( c._vec[0] == 10 );
    REQUIRE( c._vec[1] == 12 );
    REQUIRE( c._vec[2] == 14 );
    REQUIRE( c._vec[3] == 16 );
  }

  SECTION( "subtraction" ) {
    Vec c = b-copied;

    REQUIRE( c._vec[0] == 10 );
    REQUIRE( c._vec[1] == 10 );
    REQUIRE( c._vec[2] == 10 );
    REQUIRE( c._vec[3] == 10 );
  }

  SECTION( "dot product" ) {
    float c = b.Dot(copied);

    REQUIRE( c == 74 );
  }

  SECTION( "cross product" ) {
    copied.SetDim(3);
    b.SetDim(3);
    Vec c = b.Cross(copied);

    REQUIRE( c._vec[0] == 10 );
    REQUIRE( c._vec[1] == -20 );
    REQUIRE( c._vec[2] == 10 );
  }

  SECTION( "magnitude" ) {
    float expected = sqrt(1+4+9);
    REQUIRE( a.Magnitude() >= expected - expected * 0.001 );
    REQUIRE( a.Magnitude() <= expected + expected * 0.001 );
  }

  SECTION( "normalize" ) {
    a.Normalize();
    Vec c = a;

    float val = 0;

    for(int i = 0; i < 4; i++){
      val += c._vec[i]*c._vec[i];
    }

    val = sqrt(val);

    REQUIRE( val >= 0.9999 );
    REQUIRE( val <= 1.0001 );
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.  Redistributions
 * in binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.  Neither the name of
 * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#ifndef __ARCH_X86_LINUX_LINUX_HH__
#define __ARCH_X86_LINUX_LINUX_HH__

#include "kern/linux/linux.hh"

class X86Linux64 : public Linux
{
  public:

    typedef struct {
        uint64_t st_dev;
        uint64_t st_ino;
        uint64_t st_nlink;
        uint32_t st_mode;
        uint32_t st_uid;
        uint32_t st_gid;
        uint32_t __pad0[4];
        uint64_t st_rdev;
        int64_t st_size;
        int64_t st_blksize;
        int64_t st_blocks;
        uint64_t st_atimeX;
        uint64_t st_atime_nsec;
        uint64_t st_mtimeX;
        uint64_t st_mtime_nsec;
        uint64_t st_ctimeX;
        uint64_t st_ctime_nsec;
        int64_t __unused[3];
    } tgt_stat64;

    static OpenFlagTransTable openFlagTable[];

    static const int TGT_O_RDONLY	= 0x00000000;	//!< O_RDONLY
    static const int TGT_O_WRONLY	= 0x00000001;	//!< O_WRONLY
    static const int TGT_O_RDWR	        = 0x00000002;	//!< O_RDWR
    static const int TGT_O_NONBLOCK     = 0x00004000;	//!< O_NONBLOCK
    static const int TGT_O_APPEND	= 0x00000008;	//!< O_APPEND
    static const int TGT_O_CREAT	= 0x00000200;	//!< O_CREAT
    static const int TGT_O_TRUNC	= 0x00000400;	//!< O_TRUNC
    static const int TGT_O_EXCL	        = 0x00000800;	//!< O_EXCL
    static const int TGT_O_NOCTTY	= 0x00008000;	//!< O_NOCTTY
    static const int TGT_O_SYNC	        = 0x00002000;	//!< O_SYNC
//    static const int TGT_O_DRD	        = 0x00010000;	//!< O_DRD
//    static const int TGT_O_DIRECTIO     = 0x00020000;	//!< O_DIRECTIO
//    static const int TGT_O_CACHE	= 0x00002000;	//!< O_CACHE
//    static const int TGT_O_DSYNC	= 0x00008000;	//!< O_DSYNC
//    static const int TGT_O_RSYNC	= 0x00040000;	//!< O_RSYNC

    static const int NUM_OPEN_FLAGS;

    static const unsigned TGT_MAP_ANONYMOUS = 0x20;

    typedef struct {
        uint64_t iov_base; // void *
        uint64_t iov_len;  // size_t
    } tgt_iovec;
};

#endif
<commit_msg>X86: __pad0 should be a 4 byte pad, not a 4 long array of 4 byte pads.<commit_after>/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.  Redistributions
 * in binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.  Neither the name of
 * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Gabe Black
 */

#ifndef __ARCH_X86_LINUX_LINUX_HH__
#define __ARCH_X86_LINUX_LINUX_HH__

#include "kern/linux/linux.hh"

class X86Linux64 : public Linux
{
  public:

    typedef struct {
        uint64_t st_dev;
        uint64_t st_ino;
        uint64_t st_nlink;
        uint32_t st_mode;
        uint32_t st_uid;
        uint32_t st_gid;
        uint32_t __pad0;
        uint64_t st_rdev;
        int64_t st_size;
        int64_t st_blksize;
        int64_t st_blocks;
        uint64_t st_atimeX;
        uint64_t st_atime_nsec;
        uint64_t st_mtimeX;
        uint64_t st_mtime_nsec;
        uint64_t st_ctimeX;
        uint64_t st_ctime_nsec;
        int64_t __unused[3];
    } tgt_stat64;

    static OpenFlagTransTable openFlagTable[];

    static const int TGT_O_RDONLY	= 0x00000000;	//!< O_RDONLY
    static const int TGT_O_WRONLY	= 0x00000001;	//!< O_WRONLY
    static const int TGT_O_RDWR	        = 0x00000002;	//!< O_RDWR
    static const int TGT_O_NONBLOCK     = 0x00004000;	//!< O_NONBLOCK
    static const int TGT_O_APPEND	= 0x00000008;	//!< O_APPEND
    static const int TGT_O_CREAT	= 0x00000200;	//!< O_CREAT
    static const int TGT_O_TRUNC	= 0x00000400;	//!< O_TRUNC
    static const int TGT_O_EXCL	        = 0x00000800;	//!< O_EXCL
    static const int TGT_O_NOCTTY	= 0x00008000;	//!< O_NOCTTY
    static const int TGT_O_SYNC	        = 0x00002000;	//!< O_SYNC
//    static const int TGT_O_DRD	        = 0x00010000;	//!< O_DRD
//    static const int TGT_O_DIRECTIO     = 0x00020000;	//!< O_DIRECTIO
//    static const int TGT_O_CACHE	= 0x00002000;	//!< O_CACHE
//    static const int TGT_O_DSYNC	= 0x00008000;	//!< O_DSYNC
//    static const int TGT_O_RSYNC	= 0x00040000;	//!< O_RSYNC

    static const int NUM_OPEN_FLAGS;

    static const unsigned TGT_MAP_ANONYMOUS = 0x20;

    typedef struct {
        uint64_t iov_base; // void *
        uint64_t iov_len;  // size_t
    } tgt_iovec;
};

#endif
<|endoftext|>


<commit_before>//..............................................................................
//
//  This file is part of the Jancy toolkit.
//
//  Jancy is distributed under the MIT license.
//  For details see accompanying license.txt file,
//  the public copy of which is also available at:
//  http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................

#include "pch.h"
#include "jnc_ct_CapabilityMgr.h"

namespace jnc {
namespace ct {

//..............................................................................

size_t
CapabilityMgr::readCapabilityParam(
	const char* param,
	void* value,
	size_t size
	)
{
	sl::StringHashTableIterator<sl::Array<char> > it = m_paramSet.find(param);
	if (!it)
		return 0;

	size_t copySize = it->m_value.getCount();
	if (!size)
		return copySize;

	if (copySize > size)
		copySize = size;

	memcpy(value, it->m_value, copySize);
	return copySize;
}

size_t
CapabilityMgr::writeCapabilityParam(
	const char* param,
	const void* value,
	size_t size
	)
{
	sl::StringHashTableIterator<sl::Array<char> > it = m_paramSet.visit(param);
	it->m_value.copy((char*)value, size);
	return size;
}

void
CapabilityMgr::initializeCapabilities(const sl::StringRef& initializer)
{
	sl::StringRef delimiters(" \t\r\n");

	m_capabilitySet.clear();
	m_isEverythingEnabled = false;

	for (size_t i = 0;;)
	{
		i = initializer.findNotOneOf(delimiters, i);
		if (i == -1)
			break;

		size_t end = initializer.findOneOf(delimiters, i);
		if (end == -1)
			end = initializer.getLength();

		sl::StringRef capability = initializer.getSubString(i, end - i);
		if (capability == "*")
		{
			m_isEverythingEnabled = true;
			break;
		}

		m_capabilitySet[capability] = true;
		i = end;
	}
}

//..............................................................................

} // namespace ct
} // namespace jnc
<commit_msg>[jnc_ct] add ,;/ to the list of capability delimiters<commit_after>//..............................................................................
//
//  This file is part of the Jancy toolkit.
//
//  Jancy is distributed under the MIT license.
//  For details see accompanying license.txt file,
//  the public copy of which is also available at:
//  http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................

#include "pch.h"
#include "jnc_ct_CapabilityMgr.h"

namespace jnc {
namespace ct {

//..............................................................................

size_t
CapabilityMgr::readCapabilityParam(
	const char* param,
	void* value,
	size_t size
	)
{
	sl::StringHashTableIterator<sl::Array<char> > it = m_paramSet.find(param);
	if (!it)
		return 0;

	size_t copySize = it->m_value.getCount();
	if (!size)
		return copySize;

	if (copySize > size)
		copySize = size;

	memcpy(value, it->m_value, copySize);
	return copySize;
}

size_t
CapabilityMgr::writeCapabilityParam(
	const char* param,
	const void* value,
	size_t size
	)
{
	sl::StringHashTableIterator<sl::Array<char> > it = m_paramSet.visit(param);
	it->m_value.copy((char*)value, size);
	return size;
}

void
CapabilityMgr::initializeCapabilities(const sl::StringRef& initializer)
{
	sl::StringRef delimiters(",;/ \t\r\n");

	m_capabilitySet.clear();
	m_isEverythingEnabled = false;

	for (size_t i = 0;;)
	{
		i = initializer.findNotOneOf(delimiters, i);
		if (i == -1)
			break;

		size_t end = initializer.findOneOf(delimiters, i);
		if (end == -1)
			end = initializer.getLength();

		sl::StringRef capability = initializer.getSubString(i, end - i);
		if (capability == "*")
		{
			m_isEverythingEnabled = true;
			break;
		}

		m_capabilitySet[capability] = true;
		i = end;
	}
}

//..............................................................................

} // namespace ct
} // namespace jnc
<|endoftext|>