<commit_before>#ifndef NANOCV_OPTIMIZE_LINESEARCH_WOLFE_HPP
#define NANOCV_OPTIMIZE_LINESEARCH_WOLFE_HPP

#include "descent.hpp"

namespace ncv
{
        namespace optimize
        {
                ///
                /// \brief helper function
                ///
                template
                <
                        typename tproblem,

                        // dependent types
                        typename tscalar = typename tproblem::tscalar,
                        typename tsize = typename tproblem::tsize,
                        typename tvector = typename tproblem::tvector,
                        typename tstate = typename tproblem::tstate,

                        typename twlog = typename tproblem::twlog,
                        typename telog = typename tproblem::telog,
                        typename tulog = typename tproblem::tulog
                >
                tscalar ls_zoom(const tproblem& problem, const tstate& st,
                        tscalar& ft, tvector& gt,
                        tscalar tlo, tscalar thi, tscalar ftlo, tscalar fthi,
                        tscalar c1, tscalar c2, tsize max_iters = 64)
                {
                        const tscalar dg = st.d.dot(st.g);

                        // (Nocedal & Wright (numerical optimization 2nd) @ p.60)
                        for (tsize i = 0; i < max_iters; i ++)
                        {
                                const tscalar t = (tlo + thi) / 2;

                                // check sufficient decrease
                                ft = problem(st.x + t * st.d, gt);
                                if (ft > st.f + c1 * t * dg || ft >= ftlo)
                                {
                                        thi = t;
                                        fthi = ft;
                                }

                                // check curvature
                                else
                                {
                                        const tscalar dg1 = gt.dot(st.d);
                                        if (std::fabs(dg1) <= -c2 * dg)
                                        {
                                                return t;
                                        }

                                        if (dg1 * (thi - tlo) >= 0)
                                        {
                                                thi = tlo;
                                                fthi = ftlo;
                                        }

                                        tlo = t;
                                        ftlo = ft;
                                }
                        }

                        return 0;
                }

                ///
                /// \brief line-search method to find the scalar that reduces
                /// the function value (the most) along the direction d: argmin(t) f(x + t * d),
                /// using the strong Wolfe (sufficient decrease and curvature) conditions
                ///
                template
                <
                        typename tproblem,

                        // dependent types
                        typename tscalar = typename tproblem::tscalar,
                        typename tsize = typename tproblem::tsize,
                        typename tvector = typename tproblem::tvector,
                        typename tstate = typename tproblem::tstate,

                        typename twlog = typename tproblem::twlog,
                        typename telog = typename tproblem::telog,
                        typename tulog = typename tproblem::tulog
                >
                tscalar ls_strong_wolfe(const tproblem& problem, tstate& st, const twlog& wlog,
                        tscalar& ft, tvector& gt,
                        tscalar c1 = 1e-4, tscalar c2 = 0.1, tsize max_iters = 64)
                {
                        const tscalar dg = descent(st, wlog);

                        const tscalar tmax = 1000;

                        tscalar t0 = 0, ft0 = std::numeric_limits<tscalar>::max();
                        tscalar t = 1;

                        // (Nocedal & Wright (numerical optimization 2nd) @ p.60)
                        for (tsize i = 0; i < max_iters; i ++)
                        {
                                // check sufficient decrease
                                ft = problem(st.x + t * st.d, gt);
                                if (ft > st.f + c1 * t * dg || ft >= ft0)
                                {
                                        return ls_zoom(problem, st, ft, gt, t0, t, ft0, ft, c1, c2, max_iters);
                                }

                                // check curvature
                                const tscalar dg1 = gt.dot(st.d);
                                if (std::fabs(dg1) <= -c2 * dg)
                                {
                                        return t;
                                }

                                if (dg1 >= 0)
                                {
                                        return ls_zoom(problem, st, ft, gt, t, t0, ft, ft0, c1, c2, max_iters);
                                }

                                t0 = t;
                                t = std::min(tmax, t * 3);
                                ft0 = ft;
                        }

                        return 0;
                }
        }
}

#endif // NANOCV_OPTIMIZE_LINESEARCH_WOLFE_HPP
<commit_msg>fix bug in the line-search<commit_after>#ifndef NANOCV_OPTIMIZE_LINESEARCH_WOLFE_HPP
#define NANOCV_OPTIMIZE_LINESEARCH_WOLFE_HPP

#include "descent.hpp"

namespace ncv
{
        namespace optimize
        {
                ///
                /// \brief helper function
                ///
                template
                <
                        typename tproblem,

                        // dependent types
                        typename tscalar = typename tproblem::tscalar,
                        typename tsize = typename tproblem::tsize,
                        typename tvector = typename tproblem::tvector,
                        typename tstate = typename tproblem::tstate,

                        typename twlog = typename tproblem::twlog,
                        typename telog = typename tproblem::telog,
                        typename tulog = typename tproblem::tulog
                >
                tscalar ls_zoom(const tproblem& problem, const tstate& st,
                        tscalar& ft, tvector& gt,
                        tscalar tlo, tscalar thi, tscalar ftlo, tscalar fthi,
                        tscalar c1, tscalar c2, tsize max_iters = 64)
                {
                        const tscalar dg = st.d.dot(st.g);

                        // (Nocedal & Wright (numerical optimization 2nd) @ p.60)
                        for (tsize i = 0; i < max_iters; i ++)
                        {
                                const tscalar t = (tlo + thi) / 2;

                                // check sufficient decrease
                                ft = problem(st.x + t * st.d, gt);
                                if (ft > st.f + c1 * t * dg || ft >= ftlo)
                                {
                                        thi = t;
                                        fthi = ft;
                                }

                                // check curvature
                                else
                                {
                                        const tscalar dg1 = gt.dot(st.d);
                                        if (std::fabs(dg1) <= -c2 * dg)
                                        {
                                                return t;
                                        }

                                        if (dg1 * (thi - tlo) >= 0)
                                        {
                                                thi = tlo;
                                                fthi = ftlo;
                                        }

                                        tlo = t;
                                        ftlo = ft;
                                }
                        }

                        return 0;
                }

                ///
                /// \brief line-search method to find the scalar that reduces
                /// the function value (the most) along the direction d: argmin(t) f(x + t * d),
                /// using the strong Wolfe (sufficient decrease and curvature) conditions
                ///
                template
                <
                        typename tproblem,

                        // dependent types
                        typename tscalar = typename tproblem::tscalar,
                        typename tsize = typename tproblem::tsize,
                        typename tvector = typename tproblem::tvector,
                        typename tstate = typename tproblem::tstate,

                        typename twlog = typename tproblem::twlog,
                        typename telog = typename tproblem::telog,
                        typename tulog = typename tproblem::tulog
                >
                tscalar ls_strong_wolfe(const tproblem& problem, tstate& st, const twlog& wlog,
                        tscalar& ft, tvector& gt,
                        tscalar c1 = 1e-4, tscalar c2 = 0.1, tsize max_iters = 64)
                {
                        const tscalar dg = descent(st, wlog);

                        const tscalar tmax = 1000;

                        tscalar t0 = 0, ft0 = std::numeric_limits<tscalar>::max();
                        tscalar t = 1;

                        // (Nocedal & Wright (numerical optimization 2nd) @ p.60)
                        for (tsize i = 0; i < max_iters; i ++)
                        {
                                // check sufficient decrease
                                ft = problem(st.x + t * st.d, gt);
                                if (ft > st.f + c1 * t * dg || (ft >= ft0 && i > 0))
                                {
                                        return ls_zoom(problem, st, ft, gt, t0, t, ft0, ft, c1, c2, max_iters);
                                }

                                // check curvature
                                const tscalar dg1 = gt.dot(st.d);
                                if (std::fabs(dg1) <= -c2 * dg)
                                {
                                        return t;
                                }

                                if (dg1 >= 0)
                                {
                                        return ls_zoom(problem, st, ft, gt, t, t0, ft, ft0, c1, c2, max_iters);
                                }

                                t0 = t;
                                t = std::min(tmax, t * 3);
                                ft0 = ft;
                        }

                        return 0;
                }
        }
}

#endif // NANOCV_OPTIMIZE_LINESEARCH_WOLFE_HPP
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "CameraNode.h"
#include "DisplayEngine.h"
#include "Player.h"
#include "ISurface.h"

#include "../base/TimeSource.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../base/ScopeTimer.h"
#include "../base/XMLHelper.h"

#include "../imaging/FWCamera.h"
#ifdef AVG_ENABLE_V4L2
#include "../imaging/V4LCamera.h"
#endif

#include <iostream>
#include <sstream>
#include <unistd.h>

using namespace std;

namespace avg {

CameraNode::CameraNode(const xmlNodePtr xmlNode, Player * pPlayer)
    : VideoBase(xmlNode, pPlayer),
      m_FrameNum(0)
{
    string sDevice = getDefaultedStringAttr (xmlNode, "device", "");
    double FrameRate = getDefaultedDoubleAttr (xmlNode, "framerate", 15);
    string sSource = getDefaultedStringAttr (xmlNode, "source", "firewire");
    int Width = getDefaultedIntAttr (xmlNode, "capturewidth", 640);
    int Height = getDefaultedIntAttr (xmlNode, "captureheight", 480);
    string sPF = getDefaultedStringAttr (xmlNode, "pixelformat", "RGB");

    if (sSource == "firewire") {
#if defined(AVG_ENABLE_1394)\
    || defined(AVG_ENABLE_1394_2)
    m_pCamera = CameraPtr(new FWCamera(sDevice, IntPoint(Width, Height), sPF,
            FrameRate, true));
#else
        AVG_TRACE(Logger::ERROR, "Firewire camera specified, but firewire "
                "support not compiled in.");
#endif
    } else if (sSource == "v4l") {
#if defined(AVG_ENABLE_V4L2)
        int Channel = getDefaultedIntAttr (xmlNode, "channel", 0);

        m_pCamera = CameraPtr(new V4LCamera(sDevice, Channel,
            IntPoint(Width, Height), sPF, true));
#else
        AVG_TRACE(Logger::ERROR, "Video4Linux camera specified, but "
                "Video4Linux support not compiled in.");
#endif
    } else {
        AVG_TRACE(Logger::ERROR,
            "Unable to set up camera. Camera source '"+sSource+"' unknown.");
    }

    if (m_pCamera) {
        m_pCamera->setFeature ("brightness",
            getDefaultedIntAttr(xmlNode, "brightness", -1));
        m_pCamera->setFeature ("exposure",
            getDefaultedIntAttr(xmlNode, "exposure", -1));
        m_pCamera->setFeature ("sharpness",
            getDefaultedIntAttr(xmlNode, "sharpness", -1));
        m_pCamera->setFeature ("saturation",
            getDefaultedIntAttr(xmlNode, "saturation", -1));
        m_pCamera->setFeature ("gamma",
            getDefaultedIntAttr(xmlNode, "gamma", -1));
        m_pCamera->setFeature ("shutter",
            getDefaultedIntAttr(xmlNode, "shutter", -1));
        m_pCamera->setFeature ("gain",
            getDefaultedIntAttr(xmlNode, "gain", -1));
        m_pCamera->setFeature ("whitebalance",
            getDefaultedIntAttr(xmlNode, "whitebalance", -1));
    }
}

CameraNode::~CameraNode()
{
    close();
}

void CameraNode::setDisplayEngine(DisplayEngine * pEngine)
{
    VideoBase::setDisplayEngine(pEngine);
}

string CameraNode::getTypeStr()
{
    return "Camera";
}

IntPoint CameraNode::getMediaSize()
{
    if (m_pCamera) {
        return m_pCamera->getImgSize();
    } else {
        return IntPoint(640,480);
    }
}

double CameraNode::getFPS()
{
    if (m_pCamera) {
        return m_pCamera->getFrameRate();
    } else {
        return 0;
    }
}

void CameraNode::open(YCbCrMode ycbcrMode)
{
    if (m_pCamera) {
        m_pCamera->open();
    }
}

void CameraNode::close()
{
    if (m_pCamera) {
        m_pCamera->close();
    }
}

unsigned int CameraNode::getFeature (const std::string& sFeature) const
{
    if (m_pCamera) {
        return m_pCamera->getFeature(sFeature);
    } else {
        return 0;
    }
}

void CameraNode::setFeature (const std::string& sFeature, int Value)
{
    if (m_pCamera) {
        m_pCamera->setFeature(sFeature, Value);
    }
}

int CameraNode::getFrameNum() const
{
    return m_FrameNum;
}

static ProfilingZone CameraProfilingZone("Camera::render");
static ProfilingZone CameraUploadProfilingZone("Camera tex download");

bool CameraNode::renderToSurface(ISurface * pSurface)
{
    if (m_pCamera) {
        ScopeTimer Timer(CameraProfilingZone);
        BitmapPtr pCurBmp = m_pCamera->getImage(false);
        if (pCurBmp) {
            BitmapPtr pTempBmp;
            while (pTempBmp = m_pCamera->getImage(false)) {
                pCurBmp = pTempBmp;
            }
            m_FrameNum++;
            BitmapPtr pBmp = pSurface->lockBmp();
            assert(pBmp->getPixelFormat() == pCurBmp->getPixelFormat());
            pBmp->copyPixels(*pCurBmp);
            pSurface->unlockBmps();
            {
                ScopeTimer Timer(CameraUploadProfilingZone);
                getEngine()->surfaceChanged(pSurface);
            }
        }
    }
    return true;
}

PixelFormat CameraNode::getPixelFormat()
{
    return B8G8R8X8;
}

}
<commit_msg>DS camera support.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2006 Ulrich von Zadow
//
//  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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "CameraNode.h"
#include "DisplayEngine.h"
#include "Player.h"
#include "ISurface.h"

#include "../base/TimeSource.h"
#include "../base/Logger.h"
#include "../base/Exception.h"
#include "../base/ScopeTimer.h"
#include "../base/XMLHelper.h"

#include "../imaging/FWCamera.h"
#ifdef AVG_ENABLE_V4L2
#include "../imaging/V4LCamera.h"
#endif
#ifdef _WIN32
#include "../imaging/DSCamera.h"
#endif

#include <iostream>
#include <sstream>
#include <unistd.h>

using namespace std;

namespace avg {

CameraNode::CameraNode(const xmlNodePtr xmlNode, Player * pPlayer)
    : VideoBase(xmlNode, pPlayer),
      m_FrameNum(0)
{
    string sDevice = getDefaultedStringAttr (xmlNode, "device", "");
    double FrameRate = getDefaultedDoubleAttr (xmlNode, "framerate", 15);
    string sSource = getDefaultedStringAttr (xmlNode, "source", "firewire");
    int Width = getDefaultedIntAttr (xmlNode, "capturewidth", 640);
    int Height = getDefaultedIntAttr (xmlNode, "captureheight", 480);
    string sPF = getDefaultedStringAttr (xmlNode, "pixelformat", "RGB");

    if (sSource == "firewire") {
#if defined(AVG_ENABLE_1394)\
    || defined(AVG_ENABLE_1394_2)
    m_pCamera = CameraPtr(new FWCamera(sDevice, IntPoint(Width, Height), sPF,
            FrameRate, true));
#else
        AVG_TRACE(Logger::ERROR, "Firewire camera specified, but firewire "
                "support not compiled in.");
#endif
    } else if (sSource == "v4l") {
#if defined(AVG_ENABLE_V4L2)
        int Channel = getDefaultedIntAttr (xmlNode, "channel", 0);

        m_pCamera = CameraPtr(new V4LCamera(sDevice, Channel,
            IntPoint(Width, Height), sPF, true));
#else
        AVG_TRACE(Logger::ERROR, "Video4Linux camera specified, but "
                "Video4Linux support not compiled in.");
#endif
    } else if (sSource == "directshow") {
#if defined(_WIN32)
        m_pCamera = CameraPtr(new DSCamera(sDevice, IntPoint(Width, Height), sPF,
            FrameRate, true));
#else
        AVG_TRACE(Logger::ERROR, "DirectShow camera specified, but "
                "DirectShow is only available under windows.");
#endif
    } else {
        AVG_TRACE(Logger::ERROR,
            "Unable to set up camera. Camera source '"+sSource+"' unknown.");
    }

    if (m_pCamera) {
        m_pCamera->setFeature ("brightness",
            getDefaultedIntAttr(xmlNode, "brightness", -1));
        m_pCamera->setFeature ("exposure",
            getDefaultedIntAttr(xmlNode, "exposure", -1));
        m_pCamera->setFeature ("sharpness",
            getDefaultedIntAttr(xmlNode, "sharpness", -1));
        m_pCamera->setFeature ("saturation",
            getDefaultedIntAttr(xmlNode, "saturation", -1));
        m_pCamera->setFeature ("gamma",
            getDefaultedIntAttr(xmlNode, "gamma", -1));
        m_pCamera->setFeature ("shutter",
            getDefaultedIntAttr(xmlNode, "shutter", -1));
        m_pCamera->setFeature ("gain",
            getDefaultedIntAttr(xmlNode, "gain", -1));
        m_pCamera->setFeature ("whitebalance",
            getDefaultedIntAttr(xmlNode, "whitebalance", -1));
    }
}

CameraNode::~CameraNode()
{
    close();
}

void CameraNode::setDisplayEngine(DisplayEngine * pEngine)
{
    VideoBase::setDisplayEngine(pEngine);
}

string CameraNode::getTypeStr()
{
    return "Camera";
}

IntPoint CameraNode::getMediaSize()
{
    if (m_pCamera) {
        return m_pCamera->getImgSize();
    } else {
        return IntPoint(640,480);
    }
}

double CameraNode::getFPS()
{
    if (m_pCamera) {
        return m_pCamera->getFrameRate();
    } else {
        return 0;
    }
}

void CameraNode::open(YCbCrMode ycbcrMode)
{
    if (m_pCamera) {
        m_pCamera->open();
    }
}

void CameraNode::close()
{
    if (m_pCamera) {
        m_pCamera->close();
    }
}

unsigned int CameraNode::getFeature (const std::string& sFeature) const
{
    if (m_pCamera) {
        return m_pCamera->getFeature(sFeature);
    } else {
        return 0;
    }
}

void CameraNode::setFeature (const std::string& sFeature, int Value)
{
    if (m_pCamera) {
        m_pCamera->setFeature(sFeature, Value);
    }
}

int CameraNode::getFrameNum() const
{
    return m_FrameNum;
}

static ProfilingZone CameraProfilingZone("Camera::render");
static ProfilingZone CameraUploadProfilingZone("Camera tex download");

bool CameraNode::renderToSurface(ISurface * pSurface)
{
    if (m_pCamera) {
        ScopeTimer Timer(CameraProfilingZone);
        BitmapPtr pCurBmp = m_pCamera->getImage(false);
        if (pCurBmp) {
            BitmapPtr pTempBmp;
            while (pTempBmp = m_pCamera->getImage(false)) {
                pCurBmp = pTempBmp;
            }
            m_FrameNum++;
            BitmapPtr pBmp = pSurface->lockBmp();
            assert(pBmp->getPixelFormat() == pCurBmp->getPixelFormat());
            pBmp->copyPixels(*pCurBmp);
            pSurface->unlockBmps();
            {
                ScopeTimer Timer(CameraUploadProfilingZone);
                getEngine()->surfaceChanged(pSurface);
            }
        }
    }
    return true;
}

PixelFormat CameraNode::getPixelFormat()
{
    return B8G8R8X8;
}

}
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#include "PoolObjectSQL.h"
#include "PoolObjectAuth.h"
#include "SSLTools.h"

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

string& PoolObjectSQL::to_xml64(string &xml64)
{
    string *str64;

    to_xml(xml64);

    str64 = SSLTools::base64_encode(xml64);

    xml64 = *str64;

    delete str64;

    return xml64;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::select(SqlDB *db)
{
    ostringstream   oss;
    int             rc;
    int             boid;

    set_callback(
            static_cast<Callbackable::Callback>(&PoolObjectSQL::select_cb));

    oss << "SELECT body FROM " << table << " WHERE oid = " << oid;

    boid = oid;
    oid  = -1;

    rc = db->exec(oss, this);

    unset_callback();

    if ((rc != 0) || (oid != boid ))
    {
        return -1;
    }

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::select(SqlDB *db, const string& _name, int _uid)
{
    ostringstream oss;

    int rc;
    char * sql_name;

    sql_name = db->escape_str(_name.c_str());

    if ( sql_name == 0 )
    {
        return -1;
    }

    set_callback(
            static_cast<Callbackable::Callback>(&PoolObjectSQL::select_cb));

    oss << "SELECT body FROM " << table << " WHERE name = '" << sql_name << "'";

    if ( _uid != -1 )
    {
        oss << " AND uid = " << _uid;
    }

    name  = "";
    uid   = -1;

    rc = db->exec(oss, this);

    unset_callback();

    db->free_str(sql_name);

    if ((rc != 0) || (_name != name) || (_uid != -1 && _uid != uid))
    {
        return -1;
    }

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::drop(SqlDB *db)
{
    ostringstream oss;
    int rc;

    oss << "DELETE FROM " << table << " WHERE oid=" << oid;

    rc = db->exec(oss);

    if ( rc == 0 )
    {
        set_valid(false);
    }

    return rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

const char * PoolObjectSQL::error_attribute_name = "ERROR";

void PoolObjectSQL::set_template_error_message(const string& message)
{
    VectorAttribute *  attr;
    map<string,string> error_value;

    char   str[26];
    time_t the_time;

    the_time = time(NULL);

#ifdef SOLARIS
    ctime_r(&(the_time),str,sizeof(char)*26);
#else
    ctime_r(&(the_time),str);
#endif

    str[24] = '\0'; // Get rid of final enter character

    error_value.insert(make_pair("TIMESTAMP",str));
    error_value.insert(make_pair("MESSAGE",message));

    attr = new VectorAttribute(error_attribute_name,error_value);

    obj_template->set(attr);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::replace_template(const string& tmpl_str, string& error)
{
    Template * new_tmpl  = get_new_template();
    char *     error_msg = 0;

    if ( new_tmpl == 0 )
    {
        error = "Can not allocate a new template";
        return -1;
    }

    if ( new_tmpl->parse(tmpl_str, &error_msg) != 0 )
    {
        ostringstream oss;

        oss << "Parse error";

        if (error_msg != 0)
        {
            oss << ": " << error_msg;
        }

        error = oss.str();

        return -1;
    }

    delete obj_template;

    obj_template = new_tmpl;

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

string& PoolObjectSQL::perms_to_xml(string& xml) const
{
    ostringstream   oss;

    oss <<
        "<PERMISSIONS>" <<
            "<OWNER_U>" << owner_u << "</OWNER_U>"  <<
            "<OWNER_M>" << owner_m << "</OWNER_M>"  <<
            "<OWNER_A>" << owner_a << "</OWNER_A>"  <<
            "<GROUP_U>" << group_u << "</GROUP_U>"  <<
            "<GROUP_M>" << group_m << "</GROUP_M>"  <<
            "<GROUP_A>" << group_a << "</GROUP_A>"  <<
            "<OTHER_U>" << other_u << "</OTHER_U>"  <<
            "<OTHER_M>" << other_m << "</OTHER_M>"  <<
            "<OTHER_A>" << other_a << "</OTHER_A>"  <<
        "</PERMISSIONS>";

    xml = oss.str();
    return xml;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::perms_from_xml()
{
    int rc = 0;

    rc += xpath(owner_u, "/*/PERMISSIONS/OWNER_U", 0);
    rc += xpath(owner_m, "/*/PERMISSIONS/OWNER_M", 0);
    rc += xpath(owner_a, "/*/PERMISSIONS/OWNER_A", 0);

    rc += xpath(group_u, "/*/PERMISSIONS/GROUP_U", 0);
    rc += xpath(group_m, "/*/PERMISSIONS/GROUP_M", 0);
    rc += xpath(group_a, "/*/PERMISSIONS/GROUP_A", 0);

    rc += xpath(other_u, "/*/PERMISSIONS/OTHER_U", 0);
    rc += xpath(other_m, "/*/PERMISSIONS/OTHER_M", 0);
    rc += xpath(other_a, "/*/PERMISSIONS/OTHER_A", 0);

    return rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void PoolObjectSQL::get_permissions(PoolObjectAuth& auth)
{
    auth.obj_type = obj_type;

    auth.oid = oid;
    auth.uid = uid;
    auth.gid = gid;

    auth.owner_u = owner_u;
    auth.owner_m = owner_m;
    auth.owner_a = owner_a;

    group_u = auth.group_u;
    group_m = auth.group_m;
    group_a = auth.group_a;

    other_u = auth.other_u;
    other_m = auth.other_m;
    other_a = auth.other_a;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
<commit_msg>Feature #862: Fix bug in PoolObjectSQL::get_permissions<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#include "PoolObjectSQL.h"
#include "PoolObjectAuth.h"
#include "SSLTools.h"

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

string& PoolObjectSQL::to_xml64(string &xml64)
{
    string *str64;

    to_xml(xml64);

    str64 = SSLTools::base64_encode(xml64);

    xml64 = *str64;

    delete str64;

    return xml64;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::select(SqlDB *db)
{
    ostringstream   oss;
    int             rc;
    int             boid;

    set_callback(
            static_cast<Callbackable::Callback>(&PoolObjectSQL::select_cb));

    oss << "SELECT body FROM " << table << " WHERE oid = " << oid;

    boid = oid;
    oid  = -1;

    rc = db->exec(oss, this);

    unset_callback();

    if ((rc != 0) || (oid != boid ))
    {
        return -1;
    }

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::select(SqlDB *db, const string& _name, int _uid)
{
    ostringstream oss;

    int rc;
    char * sql_name;

    sql_name = db->escape_str(_name.c_str());

    if ( sql_name == 0 )
    {
        return -1;
    }

    set_callback(
            static_cast<Callbackable::Callback>(&PoolObjectSQL::select_cb));

    oss << "SELECT body FROM " << table << " WHERE name = '" << sql_name << "'";

    if ( _uid != -1 )
    {
        oss << " AND uid = " << _uid;
    }

    name  = "";
    uid   = -1;

    rc = db->exec(oss, this);

    unset_callback();

    db->free_str(sql_name);

    if ((rc != 0) || (_name != name) || (_uid != -1 && _uid != uid))
    {
        return -1;
    }

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::drop(SqlDB *db)
{
    ostringstream oss;
    int rc;

    oss << "DELETE FROM " << table << " WHERE oid=" << oid;

    rc = db->exec(oss);

    if ( rc == 0 )
    {
        set_valid(false);
    }

    return rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

const char * PoolObjectSQL::error_attribute_name = "ERROR";

void PoolObjectSQL::set_template_error_message(const string& message)
{
    VectorAttribute *  attr;
    map<string,string> error_value;

    char   str[26];
    time_t the_time;

    the_time = time(NULL);

#ifdef SOLARIS
    ctime_r(&(the_time),str,sizeof(char)*26);
#else
    ctime_r(&(the_time),str);
#endif

    str[24] = '\0'; // Get rid of final enter character

    error_value.insert(make_pair("TIMESTAMP",str));
    error_value.insert(make_pair("MESSAGE",message));

    attr = new VectorAttribute(error_attribute_name,error_value);

    obj_template->set(attr);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::replace_template(const string& tmpl_str, string& error)
{
    Template * new_tmpl  = get_new_template();
    char *     error_msg = 0;

    if ( new_tmpl == 0 )
    {
        error = "Can not allocate a new template";
        return -1;
    }

    if ( new_tmpl->parse(tmpl_str, &error_msg) != 0 )
    {
        ostringstream oss;

        oss << "Parse error";

        if (error_msg != 0)
        {
            oss << ": " << error_msg;
        }

        error = oss.str();

        return -1;
    }

    delete obj_template;

    obj_template = new_tmpl;

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

string& PoolObjectSQL::perms_to_xml(string& xml) const
{
    ostringstream   oss;

    oss <<
        "<PERMISSIONS>" <<
            "<OWNER_U>" << owner_u << "</OWNER_U>"  <<
            "<OWNER_M>" << owner_m << "</OWNER_M>"  <<
            "<OWNER_A>" << owner_a << "</OWNER_A>"  <<
            "<GROUP_U>" << group_u << "</GROUP_U>"  <<
            "<GROUP_M>" << group_m << "</GROUP_M>"  <<
            "<GROUP_A>" << group_a << "</GROUP_A>"  <<
            "<OTHER_U>" << other_u << "</OTHER_U>"  <<
            "<OTHER_M>" << other_m << "</OTHER_M>"  <<
            "<OTHER_A>" << other_a << "</OTHER_A>"  <<
        "</PERMISSIONS>";

    xml = oss.str();
    return xml;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int PoolObjectSQL::perms_from_xml()
{
    int rc = 0;

    rc += xpath(owner_u, "/*/PERMISSIONS/OWNER_U", 0);
    rc += xpath(owner_m, "/*/PERMISSIONS/OWNER_M", 0);
    rc += xpath(owner_a, "/*/PERMISSIONS/OWNER_A", 0);

    rc += xpath(group_u, "/*/PERMISSIONS/GROUP_U", 0);
    rc += xpath(group_m, "/*/PERMISSIONS/GROUP_M", 0);
    rc += xpath(group_a, "/*/PERMISSIONS/GROUP_A", 0);

    rc += xpath(other_u, "/*/PERMISSIONS/OTHER_U", 0);
    rc += xpath(other_m, "/*/PERMISSIONS/OTHER_M", 0);
    rc += xpath(other_a, "/*/PERMISSIONS/OTHER_A", 0);

    return rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void PoolObjectSQL::get_permissions(PoolObjectAuth& auth)
{
    auth.obj_type = obj_type;

    auth.oid = oid;
    auth.uid = uid;
    auth.gid = gid;

    auth.owner_u = owner_u;
    auth.owner_m = owner_m;
    auth.owner_a = owner_a;

    auth.group_u = group_u;
    auth.group_m = group_m;
    auth.group_a = group_a;

    auth.other_u = other_u;
    auth.other_m = other_m;
    auth.other_a = other_a;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2018.  All rights reserved
 */
#include "../StroikaPreComp.h"

#include "../Characters/Format.h"
#include "../Characters/String_Constant.h"
#include "../Characters/ToString.h"
#include "../Containers/Bijection.h"
#include "../DataExchange/Variant/CharacterDelimitedLines/Reader.h"
#include "../Debug/Trace.h"
#if qPlatform_Windows
#include "../Execution/Platform/Windows/Exception.h"
#endif
#include "../IO/FileSystem/FileInputStream.h"
#include "../IO/FileSystem/PathName.h"

#include "InternetMediaTypeRegistry.h"

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::DataExchange;
using namespace Stroika::Foundation::Execution;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

using FileSuffixType = InternetMediaTypeRegistry::FileSuffixType;

#if qPlatform_Windows
using Stroika::Foundation::Execution::Platform::Windows::ThrowIfNotERROR_SUCCESS;
#endif

#if qPlatform_Linux
// not sure what platforms have this
namespace {
    Mapping<FileSuffixType, InternetMediaType> GetGlobsFile_ ()
    {
        auto readGlobsFile = []() -> Mapping<FileSuffixType, InternetMediaType> {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
            Debug::TraceContextBumper ctx{L"{}readGlobsFile"};
#endif
            Mapping<FileSuffixType, InternetMediaType> results{};
            for (Sequence<String> line : DataExchange::Variant::CharacterDelimitedLines::Reader{{':'}}.ReadMatrix (IO::FileSystem::FileInputStream::New (L"/usr/share/mime/globs"))) {
                if (line.length () == 2) {
                    String glob = line[1];
                    if (glob.StartsWith ('*')) {
                        glob = glob.SubString (1);
                    }
                    results.Add (glob, InternetMediaType{line[0]});
                }
            }
#if USE_NOISY_TRACE_IN_THIS_MODULE_
            DbgTrace (L"returning %s", Characters::ToString (results).c_str ());
#endif
            return results;
		};
		static const Mapping<FileSuffixType, InternetMediaType> kData_ = readGlobsFile ();
        return kData_;
    }
}
#endif

#if qPlatform_Windows
namespace {
    // Based on code from HealthFrame. MAYBE someday do more generic version of this - as helper
    // @see https://stroika.atlassian.net/browse/STK-575
    struct OptionsFileHelper_ {
        OptionsFileHelper_ (HKEY hkey)
            : fKey (hkey)
        {
            Assert (nullptr != INVALID_HANDLE_VALUE);
            if (hkey == INVALID_HANDLE_VALUE or hkey == nullptr) {
                Execution::Throw (Execution::Platform::Windows::Exception (ERROR_INVALID_HANDLE), "OptionsFileHelper::CTOR - bad handle");
            }
        }
        OptionsFileHelper_ (HKEY parentKey, const String& path, REGSAM samDesired = KEY_READ | KEY_WRITE)
            : fKey (OpenWithCreateAlongPath (parentKey, path, samDesired))
        {
            if (parentKey == INVALID_HANDLE_VALUE or parentKey == nullptr) {
                Execution::Throw (Execution::Platform::Windows::Exception (ERROR_INVALID_HANDLE), "OptionsFileHelper::CTOR - bad handle");
            }
        }
        OptionsFileHelper_ ()                          = delete;
        OptionsFileHelper_ (const OptionsFileHelper_&) = delete;
        const OptionsFileHelper_& operator= (const OptionsFileHelper_&) const = delete;
        ~OptionsFileHelper_ ()
        {
            Assert (nullptr != INVALID_HANDLE_VALUE);
            Assert (fKey != nullptr);
            Assert (fKey != INVALID_HANDLE_VALUE);
            ::RegCloseKey (fKey);
        }
        /*
         * Walk the given path (in segments) - and make sure each exists, and create each segment if it doesn't
         * exist.Finally - do a regular registry open with access permissions 'samDesired'.< / p>
         */
        static HKEY OpenWithCreateAlongPath (HKEY parentKey, const String& path, REGSAM samDesired = KEY_READ | KEY_WRITE)
        {
            Debug::TraceContextBumper trcCtx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"OptionsFileHelper::OpenWithCreateAlongPath", L"parentKey=%p, path='%s'", parentKey, path.c_str ())};
            Require (parentKey != nullptr);
            size_t prevPos = 0;
            HKEY   curPar  = parentKey;
            for (;;) {
                size_t    endPos    = path.find ('\\', prevPos);
                SDKString segName   = path.AsSDKString ().substr (prevPos, endPos == SDKString::npos ? endPos : (endPos - prevPos));
                REGSAM    createSAM = (endPos == SDKString::npos) ? samDesired : KEY_READ;
                HKEY      newKey    = static_cast<HKEY> (INVALID_HANDLE_VALUE);

                ThrowIfNotERROR_SUCCESS (::RegCreateKeyEx (curPar, segName.c_str (), 0, REG_NONE, REG_OPTION_NON_VOLATILE, createSAM, nullptr, &newKey, nullptr));
                if (curPar != parentKey) {
                    ::RegCloseKey (curPar);
                }
                curPar = newKey;
                if (endPos == SDKString::npos) {
                    return newKey;
                }
                prevPos = endPos + 1;
            }
        }

        nonvirtual bool LookupPref (const String& prefName, string* value, DWORD* regStrType = nullptr) const
        {
            RequireNotNull (value);
            Assert (fKey != INVALID_HANDLE_VALUE);
            string strValue;
            DWORD  dwType  = 0;
            DWORD  dwCount = 0;
            LONG   lResult = ::RegQueryValueExA (fKey, prefName.AsNarrowSDKString ().c_str (), nullptr, &dwType, nullptr, &dwCount);
            if (lResult == ERROR_SUCCESS) {
                if (dwType == REG_SZ or dwType == REG_EXPAND_SZ) {
                    if (dwCount != 0) {
                        strValue.resize (dwCount);
                        lResult = ::RegQueryValueExA (fKey, prefName.AsNarrowSDKString ().c_str (), nullptr, &dwType, (LPBYTE) & (*strValue.begin ()), &dwCount);
                    }
                }
                else {
                    lResult = !ERROR_SUCCESS;
                }
            }
            if (lResult == ERROR_SUCCESS) {
                if (dwType == REG_SZ or dwType == REG_EXPAND_SZ) {
                    *value = strValue.c_str (); // copying like this loses xtra NUL-byte if there is one from read...
                    if (regStrType != nullptr) {
                        *regStrType = dwType;
                    }
                    return true;
                }
            }
            return false;
        }
        nonvirtual bool LookupPref (const String& prefName, wstring* value, DWORD* regStrType = nullptr) const
        {
            RequireNotNull (value);
            Assert (fKey != INVALID_HANDLE_VALUE);
            wstring strValue;
            DWORD   dwType  = 0;
            DWORD   dwCount = 0;
            LONG    lResult = ::RegQueryValueExW (fKey, prefName.c_str (), nullptr, &dwType, nullptr, &dwCount);
            if (lResult == ERROR_SUCCESS) {
                if (dwType == REG_SZ or dwType == REG_EXPAND_SZ) {
                    if (dwCount != 0) {
                        strValue.resize (dwCount);
                        lResult = ::RegQueryValueExW (fKey, prefName.c_str (), nullptr, &dwType, (LPBYTE) & (*strValue.begin ()), &dwCount);
                    }
                }
                else {
                    lResult = !ERROR_SUCCESS;
                }
            }
            if (lResult == ERROR_SUCCESS) {
                if (dwType == REG_SZ or dwType == REG_EXPAND_SZ) {
                    *value = strValue.c_str (); // copying like this loses xtra NUL-byte if there is one from read...
                    if (regStrType != nullptr) {
                        *regStrType = dwType;
                    }
                    return true;
                }
            }
            // If not success - then maybe cuz non-UNICODE functions not available - so try to read a non-UNICODE string
            {
                string tmp;
                if (LookupPref (prefName, &tmp, regStrType)) {
                    *value = NarrowSDKStringToWide (tmp);
                    return true;
                }
            }
            return false;
        }

    private:
        HKEY fKey;
    };
    Optional<String> GrabRegistryStringValue_ (HKEY parentKey, const String& path)
    {
        try {
            String eltPath = path;
            String parentPath;
            {
                size_t i = path.rfind ('\\');
                if (i != SDKString::npos) {
                    parentPath = path.substr (0, i);
                    eltPath    = path.substr (i + 1);
                }
            }
            OptionsFileHelper_ ofh (parentKey, parentPath, KEY_READ);
            wstring            result;
            if (ofh.LookupPref (eltPath, &result)) {
                return result;
            }
        }
        catch (...) {
            // ignore
        }
        return {};
    }
}
#endif
/*
 ********************************************************************************
 *************************** MimeTypes::Private::INIT ***************************
 ********************************************************************************
 */

Optional<FileSuffixType> InternetMediaTypeRegistry::GetPreferredAssociatedFileSuffix (const InternetMediaType& ct) const
{
#if qPlatform_Windows
    return GrabRegistryStringValue_ (HKEY_CLASSES_ROOT, Characters::Format (L"MIME\\Database\\Content Type\\%s\\Extension"));
#else
    AssertNotImplemented ();
    return {};
#endif
}

Sequence<String> InternetMediaTypeRegistry::GetAssociatedFileSuffixes (const InternetMediaType& ct, bool includeMoreGeneralTypes) const
{
#if qPlatform_Windows
    Sequence<String> tmp;
    // @todo - hack - inadequate, but good enough to start
    if (auto i = GetPreferredAssociatedFileSuffix (ct)) {
        tmp += *i;
    }
    return tmp;
#else
    AssertNotImplemented ();
    return {};
#endif
}

Optional<String> InternetMediaTypeRegistry::GetAssociatedPrettyName (const InternetMediaType& ct) const
{
#if qPlatform_Windows
    if (Optional<FileSuffixType> fileSuffix = GetPreferredAssociatedFileSuffix (ct)) {
        if (Optional<String> fileTypeID = GrabRegistryStringValue_ (HKEY_CLASSES_ROOT, *fileSuffix)) {
            return GrabRegistryStringValue_ (HKEY_CLASSES_ROOT, *fileTypeID);
        }
    }
#else
    AssertNotImplemented ();
#endif
    return {};
}

Optional<InternetMediaType> InternetMediaTypeRegistry::GetAssociatedContentType (const FileSuffixType& fileNameOrSuffix) const
{
    FileSuffixType suffix = IO::FileSystem::GetFileSuffix (fileNameOrSuffix);
#if qPlatform_Linux
    return GetGlobsFile_ ().Lookup (suffix);
#elif qPlatform_Windows
    if (Optional<String> oct = GrabRegistryStringValue_ (HKEY_CLASSES_ROOT, Characters::Format (L"%s\\Content Type", suffix.c_str ()))) {
        return InternetMediaType{*oct};
    }
#else
    AssertNotImplemented ();
#endif
    return {};
}<commit_msg>cosmetic<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2018.  All rights reserved
 */
#include "../StroikaPreComp.h"

#include "../Characters/Format.h"
#include "../Characters/String_Constant.h"
#include "../Characters/ToString.h"
#include "../Containers/Bijection.h"
#include "../DataExchange/Variant/CharacterDelimitedLines/Reader.h"
#include "../Debug/Trace.h"
#if qPlatform_Windows
#include "../Execution/Platform/Windows/Exception.h"
#endif
#include "../IO/FileSystem/FileInputStream.h"
#include "../IO/FileSystem/PathName.h"

#include "InternetMediaTypeRegistry.h"

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::DataExchange;
using namespace Stroika::Foundation::Execution;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

using FileSuffixType = InternetMediaTypeRegistry::FileSuffixType;

#if qPlatform_Windows
using Stroika::Foundation::Execution::Platform::Windows::ThrowIfNotERROR_SUCCESS;
#endif

#if qPlatform_Linux
// not sure what platforms have this
namespace {
    Mapping<FileSuffixType, InternetMediaType> GetGlobsFile_ ()
    {
        auto readGlobsFile = []() -> Mapping<FileSuffixType, InternetMediaType> {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
            Debug::TraceContextBumper ctx{L"{}readGlobsFile"};
#endif
            Mapping<FileSuffixType, InternetMediaType> results{};
            for (Sequence<String> line : DataExchange::Variant::CharacterDelimitedLines::Reader{{':'}}.ReadMatrix (IO::FileSystem::FileInputStream::New (L"/usr/share/mime/globs"))) {
                if (line.length () == 2) {
                    String glob = line[1];
                    if (glob.StartsWith ('*')) {
                        glob = glob.SubString (1);
                    }
                    results.Add (glob, InternetMediaType{line[0]});
                }
            }
#if USE_NOISY_TRACE_IN_THIS_MODULE_
            DbgTrace (L"returning %s", Characters::ToString (results).c_str ());
#endif
            return results;
        };
        static const Mapping<FileSuffixType, InternetMediaType> kData_ = readGlobsFile ();
        return kData_;
    }
}
#endif

#if qPlatform_Windows
namespace {
    // Based on code from HealthFrame. MAYBE someday do more generic version of this - as helper
    // @see https://stroika.atlassian.net/browse/STK-575
    struct OptionsFileHelper_ {
        OptionsFileHelper_ (HKEY hkey)
            : fKey (hkey)
        {
            Assert (nullptr != INVALID_HANDLE_VALUE);
            if (hkey == INVALID_HANDLE_VALUE or hkey == nullptr) {
                Execution::Throw (Execution::Platform::Windows::Exception (ERROR_INVALID_HANDLE), "OptionsFileHelper::CTOR - bad handle");
            }
        }
        OptionsFileHelper_ (HKEY parentKey, const String& path, REGSAM samDesired = KEY_READ | KEY_WRITE)
            : fKey (OpenWithCreateAlongPath (parentKey, path, samDesired))
        {
            if (parentKey == INVALID_HANDLE_VALUE or parentKey == nullptr) {
                Execution::Throw (Execution::Platform::Windows::Exception (ERROR_INVALID_HANDLE), "OptionsFileHelper::CTOR - bad handle");
            }
        }
        OptionsFileHelper_ ()                          = delete;
        OptionsFileHelper_ (const OptionsFileHelper_&) = delete;
        const OptionsFileHelper_& operator= (const OptionsFileHelper_&) const = delete;
        ~OptionsFileHelper_ ()
        {
            Assert (nullptr != INVALID_HANDLE_VALUE);
            Assert (fKey != nullptr);
            Assert (fKey != INVALID_HANDLE_VALUE);
            ::RegCloseKey (fKey);
        }
        /*
         * Walk the given path (in segments) - and make sure each exists, and create each segment if it doesn't
         * exist.Finally - do a regular registry open with access permissions 'samDesired'.< / p>
         */
        static HKEY OpenWithCreateAlongPath (HKEY parentKey, const String& path, REGSAM samDesired = KEY_READ | KEY_WRITE)
        {
            Debug::TraceContextBumper trcCtx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"OptionsFileHelper::OpenWithCreateAlongPath", L"parentKey=%p, path='%s'", parentKey, path.c_str ())};
            Require (parentKey != nullptr);
            size_t prevPos = 0;
            HKEY   curPar  = parentKey;
            for (;;) {
                size_t    endPos    = path.find ('\\', prevPos);
                SDKString segName   = path.AsSDKString ().substr (prevPos, endPos == SDKString::npos ? endPos : (endPos - prevPos));
                REGSAM    createSAM = (endPos == SDKString::npos) ? samDesired : KEY_READ;
                HKEY      newKey    = static_cast<HKEY> (INVALID_HANDLE_VALUE);

                ThrowIfNotERROR_SUCCESS (::RegCreateKeyEx (curPar, segName.c_str (), 0, REG_NONE, REG_OPTION_NON_VOLATILE, createSAM, nullptr, &newKey, nullptr));
                if (curPar != parentKey) {
                    ::RegCloseKey (curPar);
                }
                curPar = newKey;
                if (endPos == SDKString::npos) {
                    return newKey;
                }
                prevPos = endPos + 1;
            }
        }

        nonvirtual bool LookupPref (const String& prefName, string* value, DWORD* regStrType = nullptr) const
        {
            RequireNotNull (value);
            Assert (fKey != INVALID_HANDLE_VALUE);
            string strValue;
            DWORD  dwType  = 0;
            DWORD  dwCount = 0;
            LONG   lResult = ::RegQueryValueExA (fKey, prefName.AsNarrowSDKString ().c_str (), nullptr, &dwType, nullptr, &dwCount);
            if (lResult == ERROR_SUCCESS) {
                if (dwType == REG_SZ or dwType == REG_EXPAND_SZ) {
                    if (dwCount != 0) {
                        strValue.resize (dwCount);
                        lResult = ::RegQueryValueExA (fKey, prefName.AsNarrowSDKString ().c_str (), nullptr, &dwType, (LPBYTE) & (*strValue.begin ()), &dwCount);
                    }
                }
                else {
                    lResult = !ERROR_SUCCESS;
                }
            }
            if (lResult == ERROR_SUCCESS) {
                if (dwType == REG_SZ or dwType == REG_EXPAND_SZ) {
                    *value = strValue.c_str (); // copying like this loses xtra NUL-byte if there is one from read...
                    if (regStrType != nullptr) {
                        *regStrType = dwType;
                    }
                    return true;
                }
            }
            return false;
        }
        nonvirtual bool LookupPref (const String& prefName, wstring* value, DWORD* regStrType = nullptr) const
        {
            RequireNotNull (value);
            Assert (fKey != INVALID_HANDLE_VALUE);
            wstring strValue;
            DWORD   dwType  = 0;
            DWORD   dwCount = 0;
            LONG    lResult = ::RegQueryValueExW (fKey, prefName.c_str (), nullptr, &dwType, nullptr, &dwCount);
            if (lResult == ERROR_SUCCESS) {
                if (dwType == REG_SZ or dwType == REG_EXPAND_SZ) {
                    if (dwCount != 0) {
                        strValue.resize (dwCount);
                        lResult = ::RegQueryValueExW (fKey, prefName.c_str (), nullptr, &dwType, (LPBYTE) & (*strValue.begin ()), &dwCount);
                    }
                }
                else {
                    lResult = !ERROR_SUCCESS;
                }
            }
            if (lResult == ERROR_SUCCESS) {
                if (dwType == REG_SZ or dwType == REG_EXPAND_SZ) {
                    *value = strValue.c_str (); // copying like this loses xtra NUL-byte if there is one from read...
                    if (regStrType != nullptr) {
                        *regStrType = dwType;
                    }
                    return true;
                }
            }
            // If not success - then maybe cuz non-UNICODE functions not available - so try to read a non-UNICODE string
            {
                string tmp;
                if (LookupPref (prefName, &tmp, regStrType)) {
                    *value = NarrowSDKStringToWide (tmp);
                    return true;
                }
            }
            return false;
        }

    private:
        HKEY fKey;
    };
    Optional<String> GrabRegistryStringValue_ (HKEY parentKey, const String& path)
    {
        try {
            String eltPath = path;
            String parentPath;
            {
                size_t i = path.rfind ('\\');
                if (i != SDKString::npos) {
                    parentPath = path.substr (0, i);
                    eltPath    = path.substr (i + 1);
                }
            }
            OptionsFileHelper_ ofh (parentKey, parentPath, KEY_READ);
            wstring            result;
            if (ofh.LookupPref (eltPath, &result)) {
                return result;
            }
        }
        catch (...) {
            // ignore
        }
        return {};
    }
}
#endif
/*
 ********************************************************************************
 *************************** MimeTypes::Private::INIT ***************************
 ********************************************************************************
 */

Optional<FileSuffixType> InternetMediaTypeRegistry::GetPreferredAssociatedFileSuffix (const InternetMediaType& ct) const
{
#if qPlatform_Windows
    return GrabRegistryStringValue_ (HKEY_CLASSES_ROOT, Characters::Format (L"MIME\\Database\\Content Type\\%s\\Extension"));
#else
    AssertNotImplemented ();
    return {};
#endif
}

Sequence<String> InternetMediaTypeRegistry::GetAssociatedFileSuffixes (const InternetMediaType& ct, bool includeMoreGeneralTypes) const
{
#if qPlatform_Windows
    Sequence<String> tmp;
    // @todo - hack - inadequate, but good enough to start
    if (auto i = GetPreferredAssociatedFileSuffix (ct)) {
        tmp += *i;
    }
    return tmp;
#else
    AssertNotImplemented ();
    return {};
#endif
}

Optional<String> InternetMediaTypeRegistry::GetAssociatedPrettyName (const InternetMediaType& ct) const
{
#if qPlatform_Windows
    if (Optional<FileSuffixType> fileSuffix = GetPreferredAssociatedFileSuffix (ct)) {
        if (Optional<String> fileTypeID = GrabRegistryStringValue_ (HKEY_CLASSES_ROOT, *fileSuffix)) {
            return GrabRegistryStringValue_ (HKEY_CLASSES_ROOT, *fileTypeID);
        }
    }
#else
    AssertNotImplemented ();
#endif
    return {};
}

Optional<InternetMediaType> InternetMediaTypeRegistry::GetAssociatedContentType (const FileSuffixType& fileNameOrSuffix) const
{
    FileSuffixType suffix = IO::FileSystem::GetFileSuffix (fileNameOrSuffix);
#if qPlatform_Linux
    return GetGlobsFile_ ().Lookup (suffix);
#elif qPlatform_Windows
    if (Optional<String> oct = GrabRegistryStringValue_ (HKEY_CLASSES_ROOT, Characters::Format (L"%s\\Content Type", suffix.c_str ()))) {
        return InternetMediaType{*oct};
    }
#else
    AssertNotImplemented ();
#endif
    return {};
}<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2016.  All rights reserved
 */
#ifndef _Stroika_Foundation_Debug_AssertExternallySynchronizedLock_inl_
#define _Stroika_Foundation_Debug_AssertExternallySynchronizedLock_inl_    1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */

namespace   Stroika {
    namespace   Foundation {
        namespace   Debug {

            /*
             ********************************************************************************
             *************** Debug::AssertExternallySynchronizedLock ************************
             ********************************************************************************
             */
            inline  AssertExternallySynchronizedLock::AssertExternallySynchronizedLock (const AssertExternallySynchronizedLock& src)
                : AssertExternallySynchronizedLock ()
            {
                lock_guard<const AssertExternallySynchronizedLock> critSec1 { src };    // to copy, the src can have shared_locks, but no (write) locks
            }
            inline  AssertExternallySynchronizedLock::AssertExternallySynchronizedLock (AssertExternallySynchronizedLock&& src)
                : AssertExternallySynchronizedLock ()
            {
#if     qDebug
                lock_guard<mutex> sharedLockProtect { fSharedLockThreadsMutex_.Get () };
                Require (src.fLocks_ == 0 and src.fSharedLockThreads_.empty ());  // to move, the src can have no locks of any kind (since we change src)
#endif
            }
            inline  AssertExternallySynchronizedLock&   AssertExternallySynchronizedLock::operator= (const AssertExternallySynchronizedLock& rhs)
            {
                lock_guard<const AssertExternallySynchronizedLock> critSec1 { rhs };    // to copy, the src can have shared_locks, but no (write) locks
#if     qDebug
                lock_guard<mutex> sharedLockProtect { fSharedLockThreadsMutex_.Get () };
                Require (rhs.fLocks_ == 0 and rhs.fSharedLockThreads_.empty ());        // We must not have any locks going to replace this
#endif
                return *this;
            }
            inline  AssertExternallySynchronizedLock&   AssertExternallySynchronizedLock::operator= (AssertExternallySynchronizedLock&& rhs)
            {
#if     qDebug
                lock_guard<mutex> sharedLockProtect { fSharedLockThreadsMutex_.Get () };
                Require (rhs.fLocks_ == 0 and rhs.fSharedLockThreads_.empty ());    // to move, the rhs can have no locks of any kind (since we change rhs)
                Require (fLocks_ == 0 and fSharedLockThreads_.empty ());            // ditto for thing being assigned to
#endif
                return *this;
            }
            inline  void    AssertExternallySynchronizedLock::lock () const
            {
#if     qDebug
                if (fLocks_++ == 0) {
                    // If first time in, save thread-id
                    fCurLockThread_ = this_thread::get_id ();
                    lock_guard<mutex> sharedLockProtect { fSharedLockThreadsMutex_.Get () };
                    if (not fSharedLockThreads_.empty ()) {
                        // If first already shared locks - OK - so long as same thread
                        Require (fSharedLockThreads_.count (fCurLockThread_) == fSharedLockThreads_.size ());
                    }
                }
                else {
                    // If first already locked - OK - so long as same thread
                    Require (fCurLockThread_ == this_thread::get_id ());
                }
#endif
            }
            inline  void    AssertExternallySynchronizedLock::unlock () const
            {
#if     qDebug
                Require (fCurLockThread_ == this_thread::get_id ());
                Require (fLocks_ > 0);  // else unbalanced
                --fLocks_;
#endif
            }
            inline  void    AssertExternallySynchronizedLock::lock_shared () const
            {
#if     qDebug
                // OK to shared lock from various threads
                // But if already locked, NOT OK (would have blocked in real impl) - if you try to shared lock from another thread while locked
                if (fLocks_ != 0) {
                    // If first already locks - OK - so long as same thread
                    Require (fCurLockThread_ == this_thread::get_id ());
                }
                lock_guard<mutex> sharedLockProtect { fSharedLockThreadsMutex_.Get () };
                fSharedLockThreads_.insert (this_thread::get_id ());
#endif
            }
            inline  void    AssertExternallySynchronizedLock::unlock_shared () const
            {
#if     qDebug
                lock_guard<mutex> sharedLockProtect { fSharedLockThreadsMutex_.Get () };
                Require (fSharedLockThreads_.find (this_thread::get_id ()) != fSharedLockThreads_.end ());  // else unbalanced
                fSharedLockThreads_.erase (fSharedLockThreads_.find (this_thread::get_id ()));
#endif
            }

        }
    }
}
#endif  /*_Stroika_Foundation_Debug_AssertExternallySynchronizedLock_inl_*/
<commit_msg>speed tweak on AssertExternallySynchronizedLock::unlock_shared ()<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2016.  All rights reserved
 */
#ifndef _Stroika_Foundation_Debug_AssertExternallySynchronizedLock_inl_
#define _Stroika_Foundation_Debug_AssertExternallySynchronizedLock_inl_    1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */

namespace   Stroika {
    namespace   Foundation {
        namespace   Debug {

            /*
             ********************************************************************************
             *************** Debug::AssertExternallySynchronizedLock ************************
             ********************************************************************************
             */
            inline  AssertExternallySynchronizedLock::AssertExternallySynchronizedLock (const AssertExternallySynchronizedLock& src)
                : AssertExternallySynchronizedLock ()
            {
                lock_guard<const AssertExternallySynchronizedLock> critSec1 { src };    // to copy, the src can have shared_locks, but no (write) locks
            }
            inline  AssertExternallySynchronizedLock::AssertExternallySynchronizedLock (AssertExternallySynchronizedLock&& src)
                : AssertExternallySynchronizedLock ()
            {
#if     qDebug
                lock_guard<mutex> sharedLockProtect { fSharedLockThreadsMutex_.Get () };
                Require (src.fLocks_ == 0 and src.fSharedLockThreads_.empty ());  // to move, the src can have no locks of any kind (since we change src)
#endif
            }
            inline  AssertExternallySynchronizedLock&   AssertExternallySynchronizedLock::operator= (const AssertExternallySynchronizedLock& rhs)
            {
                lock_guard<const AssertExternallySynchronizedLock> critSec1 { rhs };    // to copy, the src can have shared_locks, but no (write) locks
#if     qDebug
                lock_guard<mutex> sharedLockProtect { fSharedLockThreadsMutex_.Get () };
                Require (rhs.fLocks_ == 0 and rhs.fSharedLockThreads_.empty ());        // We must not have any locks going to replace this
#endif
                return *this;
            }
            inline  AssertExternallySynchronizedLock&   AssertExternallySynchronizedLock::operator= (AssertExternallySynchronizedLock&& rhs)
            {
#if     qDebug
                lock_guard<mutex> sharedLockProtect { fSharedLockThreadsMutex_.Get () };
                Require (rhs.fLocks_ == 0 and rhs.fSharedLockThreads_.empty ());    // to move, the rhs can have no locks of any kind (since we change rhs)
                Require (fLocks_ == 0 and fSharedLockThreads_.empty ());            // ditto for thing being assigned to
#endif
                return *this;
            }
            inline  void    AssertExternallySynchronizedLock::lock () const
            {
#if     qDebug
                if (fLocks_++ == 0) {
                    // If first time in, save thread-id
                    fCurLockThread_ = this_thread::get_id ();
                    lock_guard<mutex> sharedLockProtect { fSharedLockThreadsMutex_.Get () };
                    if (not fSharedLockThreads_.empty ()) {
                        // If first already shared locks - OK - so long as same thread
                        Require (fSharedLockThreads_.count (fCurLockThread_) == fSharedLockThreads_.size ());
                    }
                }
                else {
                    // If first already locked - OK - so long as same thread
                    Require (fCurLockThread_ == this_thread::get_id ());
                }
#endif
            }
            inline  void    AssertExternallySynchronizedLock::unlock () const
            {
#if     qDebug
                Require (fCurLockThread_ == this_thread::get_id ());
                Require (fLocks_ > 0);  // else unbalanced
                --fLocks_;
#endif
            }
            inline  void    AssertExternallySynchronizedLock::lock_shared () const
            {
#if     qDebug
                // OK to shared lock from various threads
                // But if already locked, NOT OK (would have blocked in real impl) - if you try to shared lock from another thread while locked
                if (fLocks_ != 0) {
                    // If first already locks - OK - so long as same thread
                    Require (fCurLockThread_ == this_thread::get_id ());
                }
                lock_guard<mutex> sharedLockProtect { fSharedLockThreadsMutex_.Get () };
                fSharedLockThreads_.insert (this_thread::get_id ());
#endif
            }
            inline  void    AssertExternallySynchronizedLock::unlock_shared () const
            {
#if     qDebug
                lock_guard<mutex> sharedLockProtect { fSharedLockThreadsMutex_.Get () };
                multiset<std::thread::id>::iterator tti = fSharedLockThreads_.find (this_thread::get_id ());
                Require (tti != fSharedLockThreads_.end ());  // else unbalanced
                fSharedLockThreads_.erase (tti);
#endif
            }

        }
    }
}
#endif  /*_Stroika_Foundation_Debug_AssertExternallySynchronizedLock_inl_*/
<|endoftext|>


<commit_before><commit_msg>Cleanup. Remove superfluous header. Style changes.<commit_after><|endoftext|>


<commit_before><commit_msg>remove pragma that was causing crashes in safari<commit_after><|endoftext|>


<commit_before>// Example of TTasks.
// Create a hierachy of objects derived from TTask in library Mytasks
// Show the tasks in a browser.
// To execute a Task, use the context context menu and select
// the item "ExecuteTask"
// see also other functions in the TTask context menu, such as
//   -setting a breakpoint in one or more tasks
//   -enabling/disabling one task, etc

void tasks()
{
   gROOT->ProcessLine(".L MyTasks.cxx+");

   TTask *run      = new MyRun("run","Process one run");
   TTask *event    = new MyEvent("event","Process one event");
   TTask *geomInit = new MyGeomInit("geomInit","Geometry Initialisation");
   TTask *matInit  = new MyMaterialInit("matInit","Materials Initialisation");
   TTask *tracker  = new MyTracker("tracker","Tracker manager");
   TTask *tpc      = new MyRecTPC("tpc","TPC Reconstruction");
   TTask *its      = new MyRecITS("its","ITS Reconstruction");
   TTask *muon     = new MyRecMUON("muon","MUON Reconstruction");
   TTask *phos     = new MyRecPHOS("phos","PHOS Reconstruction");
   TTask *rich     = new MyRecRICH("rich","RICH Reconstruction");
   TTask *trd      = new MyRecTRD("trd","TRD Reconstruction");
   TTask *global   = new MyRecGlobal("global","Global Reconstruction");

   run->Add(geomInit);
   run->Add(matInit);
   run->Add(event);
   event->Add(tracker);
   event->Add(global);
   tracker->Add(tpc);
   tracker->Add(its);
   tracker->Add(muon);
   tracker->Add(phos);
   tracker->Add(rich);
   tracker->Add(trd);

   gROOT->GetListOfTasks()->Add(run);
   gROOT->GetListOfBrowsables()->Add(run);
   new TBrowser;
}
<commit_msg>Correct typo in a comment.<commit_after>// Example of TTasks.
// Create a hierarchy of objects derived from TTask in library Mytasks
// Show the tasks in a browser.
// To execute a Task, use the context context menu and select
// the item "ExecuteTask"
// see also other functions in the TTask context menu, such as
//   -setting a breakpoint in one or more tasks
//   -enabling/disabling one task, etc

void tasks()
{
   gROOT->ProcessLine(".L MyTasks.cxx+");

   TTask *run      = new MyRun("run","Process one run");
   TTask *event    = new MyEvent("event","Process one event");
   TTask *geomInit = new MyGeomInit("geomInit","Geometry Initialisation");
   TTask *matInit  = new MyMaterialInit("matInit","Materials Initialisation");
   TTask *tracker  = new MyTracker("tracker","Tracker manager");
   TTask *tpc      = new MyRecTPC("tpc","TPC Reconstruction");
   TTask *its      = new MyRecITS("its","ITS Reconstruction");
   TTask *muon     = new MyRecMUON("muon","MUON Reconstruction");
   TTask *phos     = new MyRecPHOS("phos","PHOS Reconstruction");
   TTask *rich     = new MyRecRICH("rich","RICH Reconstruction");
   TTask *trd      = new MyRecTRD("trd","TRD Reconstruction");
   TTask *global   = new MyRecGlobal("global","Global Reconstruction");

   run->Add(geomInit);
   run->Add(matInit);
   run->Add(event);
   event->Add(tracker);
   event->Add(global);
   tracker->Add(tpc);
   tracker->Add(its);
   tracker->Add(muon);
   tracker->Add(phos);
   tracker->Add(rich);
   tracker->Add(trd);

   gROOT->GetListOfTasks()->Add(run);
   gROOT->GetListOfBrowsables()->Add(run);
   new TBrowser;
}
<|endoftext|>


<commit_before>#include "tweettextedit.h"
#include "twittertextsplitter.h"

TweetTextEdit::TweetTextEdit(QWidget *parent)
    : QTextEdit(parent)
{
    connect(this, &QTextEdit::textChanged, this, &TweetTextEdit::on_textChanged);

}

void TweetTextEdit::updateHighlight()
{
    TwitterTextSplitter splitter;

    splitter.setPrefix( m_prefix);
    splitter.setText( toPlainText() );
    splitter.setPostfix( m_postfix );

    QList<SplittedItem> tweet = splitter.split();
    if (tweet.isEmpty()) {
        return;
    }

    blockSignals(true);

    QTextCursor cursor = textCursor();
    cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);

    QTextCharFormat formatOdd, formatEven;
    formatOdd.setForeground (QColor(0,0,0));
    formatOdd.setBackground (QColor(255,255,255));
    formatEven.setForeground(QColor(0,0,0));
    formatEven.setBackground(QColor(225,225,225));
    bool odd = false;

    for (QList<SplittedItem>::iterator
            ite = tweet.begin(),
            last= tweet.end();
         ite != last; ++ite, odd = !odd) {
        cursor.setPosition(cursor.position() + ite->text().size(), QTextCursor::KeepAnchor);
        cursor.mergeCharFormat(odd ? formatOdd : formatEven);
        cursor.setPosition(cursor.position(), QTextCursor::MoveAnchor);
    }

    blockSignals(false);

}

void TweetTextEdit::on_textChanged()
{
    updateHighlight();
}

void TweetTextEdit::setPrefix(const QString &prefix)
{
    m_prefix = prefix;
    updateHighlight();
}

void TweetTextEdit::setPostfix(const QString &postfix)
{
    m_postfix = postfix;
    updateHighlight();
}
<commit_msg>ツイート内容のカラーリングを変更<commit_after>#include "tweettextedit.h"
#include "twittertextsplitter.h"

TweetTextEdit::TweetTextEdit(QWidget *parent)
    : QTextEdit(parent)
{
    connect(this, &QTextEdit::textChanged, this, &TweetTextEdit::on_textChanged);

}

void TweetTextEdit::updateHighlight()
{
    TwitterTextSplitter splitter;

    splitter.setPrefix( m_prefix);
    splitter.setText( toPlainText() );
    splitter.setPostfix( m_postfix );

    QList<SplittedItem> tweet = splitter.split();
    if (tweet.isEmpty()) {
        return;
    }

    blockSignals(true);

    QTextCursor cursor = textCursor();
    cursor.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);

    QTextCharFormat formatOdd, formatEven;
    formatOdd.setForeground (QColor(0,0,0));
    formatOdd.setBackground (QColor(255,255,255));
    formatEven.setForeground(QColor(0,0,0));
    formatEven.setBackground(QColor(220,236,246));
    bool odd = false;

    for (QList<SplittedItem>::iterator
            ite = tweet.begin(),
            last= tweet.end();
         ite != last; ++ite, odd = !odd) {
        cursor.setPosition(cursor.position() + ite->text().size(), QTextCursor::KeepAnchor);
        cursor.mergeCharFormat(odd ? formatOdd : formatEven);
        cursor.setPosition(cursor.position(), QTextCursor::MoveAnchor);
    }

    blockSignals(false);

}

void TweetTextEdit::on_textChanged()
{
    updateHighlight();
}

void TweetTextEdit::setPrefix(const QString &prefix)
{
    m_prefix = prefix;
    updateHighlight();
}

void TweetTextEdit::setPostfix(const QString &postfix)
{
    m_postfix = postfix;
    updateHighlight();
}
<|endoftext|>


<commit_before>#include <jni.h>
#include "Device.h"

namespace crown
{

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT void JNICALL Java_crown_android_CrownLib_init(JNIEnv* env, jobject obj)
{
	device()->init(0, NULL);
}

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT void JNICALL Java_crown_android_CrownLib_shutdown(JNIEnv* env, jobject obj)
{
	device()->shutdown();
}

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT void JNICALL Java_crown_android_CrownLib_frame(JNIEnv* env, jobject obj)
{
	device()->frame();
}

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT bool JNICALL Java_crown_android_CrownLib_isInit(JNIEnv* env, jobject obj)
{
	return device()->is_init();
}

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT bool JNICALL Java_crown_android_CrownLib_isRunning(JNIEnv* env, jobject obj)
{
	return device()->is_running();
}

} // namespace crown
<commit_msg>Add some CL options for android<commit_after>#include <jni.h>
#include "Device.h"

namespace crown
{

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT void JNICALL Java_crown_android_CrownLib_init(JNIEnv* env, jobject obj)
{
	const char* argv[] = { "crown-android", "--root-path", "", "--dev" };

	device()->init(4, (char**)argv);
}

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT void JNICALL Java_crown_android_CrownLib_shutdown(JNIEnv* env, jobject obj)
{
	device()->shutdown();
}

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT void JNICALL Java_crown_android_CrownLib_frame(JNIEnv* env, jobject obj)
{
	device()->frame();
}

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT bool JNICALL Java_crown_android_CrownLib_isInit(JNIEnv* env, jobject obj)
{
	return device()->is_init();
}

//-----------------------------------------------------------------------------
extern "C" JNIEXPORT bool JNICALL Java_crown_android_CrownLib_isRunning(JNIEnv* env, jobject obj)
{
	return device()->is_running();
}

} // namespace crown
<|endoftext|>