<commit_before>/*
Copyright (c) 2015, Asratec Corp.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list 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 VSidoConnServer nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "debug.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <fcntl.h>
#include <unistd.h>

#include <iostream>
#include <list>
#include <fstream>
#include <streambuf>
using namespace std;

#include <string>
#include <iostream>
#include <sstream>
#include <cstdio>

static string exec(string cmd);
static void initEnv(void);

#include "VSidoConnectUartConnect.hpp"
#include "VSidoConnectUartSend.hpp"
#include "VSidoConnectUartRead.hpp"
#include "VSidoConnect.hpp"
using namespace VSido;

#include <memory>
#include <thread>
using namespace std;

#include "picojson.h"

static unique_ptr<UARTConnect> uartConn_;
static unique_ptr<UARTSend> uartSend_;
static unique_ptr<UARTRead> uartRead_;

VSido::SystemInfo VSido::gSysInfo;
void fillSystemInformation(void);

void IOConnect(const string &device,int baudrate) throw(string)
{
    fillSystemInformation();
	if(device.empty())
	{
		initEnv();
		uartConn_ = unique_ptr<UARTConnect>(new UARTConnect("/dev/tty.vsido.link"));
	}
	else
	{
		uartConn_ = unique_ptr<UARTConnect>(new UARTConnect(device,baudrate));
	}
	uartSend_ = unique_ptr<UARTSend>(new UARTSend);
	uartRead_ = unique_ptr<UARTRead>(new UARTRead);
	uartSend_->setFD(*uartConn_);
	uartRead_->setFD(*uartConn_);

	thread threadRead(std::ref(*uartRead_));
	threadRead.detach();

}

void IODisConnect(void ) throw(string)
{
	if(nullptr != uartConn_)
	{
		uartConn_->closeSPP();
		uartConn_.reset(nullptr);
	}
}

void IOSendUart(list<unsigned char> data)
{
	if(nullptr != uartSend_)
	{
		uartSend_->send(data);
	}
}

void IOSetRecieveCallback(function<void(list<unsigned char>)> fn)
{
	if(nullptr != uartRead_)
	{
		uartRead_->callback(fn);
	}
}

static string exec(string cmd)
{
    FILE* pipe = ::popen(cmd.c_str(), "r");
    if (!pipe)
	{
		return "ERROR";
	}
    char buffer[128];
    std::string result = "";
    while(!feof(pipe))
	{
    	if(fgets(buffer, 128, pipe) != NULL)
		{
    		result += buffer;
		}
    }
    pclose(pipe);
    return result;
}

/** 実行時必要なファイル領域を作る
* @param None
* @return None
*/
static void initEnv(void)
{
    string systemType("uname");
    auto uType = exec(systemType);
    FATAL_VAR(uType);
    if("Darwin\n"== uType)
    {
        /// using bluetooth
        {
            string shell("find  /dev/tty* | grep tty.SBDBT");
            auto result = exec(shell);
            FATAL_VAR(result);
            stringstream ss(result);
            std::string tty;
            getline(ss, tty);
            FATAL_VAR(tty);
            if(tty.size() > 5)
            {
                string link("rm -f /dev/tty.vsido.link;ln -sf ");
                link += tty;
                link += " /dev/tty.vsido.link";
                auto result = exec(link);
                FATAL_VAR(result);
            }
        }
    }
    else if("Linux\n"== uType)
    {
        /// add a action log folder
        {
            string shell("umount /mnt/vsido/log");
            int ret = ::system(shell.c_str());
        }
        {
            string shell("mkdir -p /mnt/vsido/log");
            int ret = ::system(shell.c_str());
        }
        {
            string shell("mount -t tmpfs -o size=2M tmpfs /mnt/vsido/log");
            int ret = ::system(shell.c_str());
        }
        {
            string shell("sync");
            int ret = ::system(shell.c_str());
        }
    }

	string systemInfo("uname -n");
    auto uname = exec(systemInfo);
	FATAL_VAR(uname);
	if("raspberrypi\n"== uname)
	{
		/// using AMA0
		{
			string shell("find  /dev/tty* | grep ttyAMA0");
	        auto result = exec(shell);
	    	FATAL_VAR(result);
			if(result.size() > 5)
			{
				string link("rm -f /dev/tty.vsido.link;ln -sf /dev/ttyAMA0 /dev/tty.vsido.link");
				auto result = exec(link);
				FATAL_VAR(result);
			}
		}
		/// check BT ,if has a HCI Mode dongle will using BLUE Tooth
		{
			/// wait 5 secend for usb dongle.
			{
				string shell("sleep 5;lsusb;hciconfig;");
		        auto result = exec(shell);
		    	FATAL_VAR(result);
			}
			string shell("hciconfig | grep \"BD Address:\"");
	        auto result = exec(shell);
	    	FATAL_VAR(result);
			if(result.size() > 5)
			{
		        string shellBT("/opt/vsido/usr/bin/btsetup");
				system(shellBT.c_str());
				/// blocked at read pipe us system. do not see result.
//		        auto result = exec(shellBT);
//		    	FATAL_VAR(result);
				{
					string link("ln -sf /dev/rfcomm75 /dev/tty.vsido.link");
					auto result = exec(link);
					FATAL_VAR(result);
				}
			}
		}
	}
	else if("edison\n"== uname)
	{
        string shellBT("/home/sysroot/usr/bin/btsetup");
        system(shellBT.c_str());

		{
			string link("rm -f /dev/tty.vsido.link;ln -sf /dev/rfcomm75 /dev/tty.vsido.link");
			auto result = exec(link);
			FATAL_VAR(result);
		}
    }
    else
    {

    }
}

#define BAURATE(x) {"B_"#x,B##x}

static map<string,int> baudrateTable =
{
    BAURATE(50),
    BAURATE(75),
    BAURATE(110),
    BAURATE(134),
    BAURATE(150),
    BAURATE(200),
    BAURATE(300),
    BAURATE(600),
    BAURATE(1200),
    BAURATE(1800),
    BAURATE(2400),
    BAURATE(4800),
    BAURATE(9600),
    BAURATE(19200),
    BAURATE(38400),
    BAURATE(57600),
    BAURATE(115200),
    BAURATE(230400),
    BAURATE(460800),
    BAURATE(500000),
    BAURATE(576000),
    BAURATE(921600),
    BAURATE(1000000),
    BAURATE(1152000),
    BAURATE(1500000),
    BAURATE(2000000),
    BAURATE(2500000),
    BAURATE(3000000),
    BAURATE(3500000),
    BAURATE(4000000)
};

void readConfig(string &port ,int &baudrate)
{
    string systemInfo("uname -n");
    auto uname = exec(systemInfo);
    FATAL_VAR(uname);

    string configPah;
    if("edison\n"== uname)
    {
        configPah = "/home/sysroot/usr/etc/serial";
    }
    else if("raspberrypi\n"== uname)
    {
        configPah = "/opt/vsido/usr/etc/serial";
    }
    else
    {

    }
    if(false==configPah.empty())
    {
        picojson::value conf;
        ifstream t(configPah);
        string err;
        picojson::parse(conf, istream_iterator<char>(t),istream_iterator<char>(),&err);

        if(err.empty())
        {
            auto& confObj = conf.get<picojson::object>();

            if(conf.contains("port"))
            {
                port = confObj["port"].get<string>();
            }
            if(conf.contains("baudrate"))
            {
                auto baudrateS = confObj["baudrate"].get<string>();
                auto it = baudrateTable.find(baudrateS);
                if(it != baudrateTable.end())
                {
                    baudrate = it->second;
                }
            }
        }
        else
        {
            FATAL_VAR(err);
        }
    }
}

void fillSystemInformation(void)
{
    gSysInfo.linux =true;
    string systemInfo("uname -n");
    auto uname = exec(systemInfo);
    FATAL_VAR(uname);

    string configPah;
    if("edison\n"== uname)
    {
        gSysInfo.edison =true;
    	gSysInfo.name = "edison";
    }
    else if("raspberrypi\n"== uname)
    {
        gSysInfo.rasp =true;
    	gSysInfo.name = "rasp";
    }
    else
    {

    }

}<commit_msg>add name tag<commit_after>/*
Copyright (c) 2015, Asratec Corp.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list 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 VSidoConnServer nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "debug.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <fcntl.h>
#include <unistd.h>

#include <iostream>
#include <list>
#include <fstream>
#include <streambuf>
using namespace std;

#include <string>
#include <iostream>
#include <sstream>
#include <cstdio>

static string exec(string cmd);
static void initEnv(void);

#include "VSidoConnectUartConnect.hpp"
#include "VSidoConnectUartSend.hpp"
#include "VSidoConnectUartRead.hpp"
#include "VSidoConnect.hpp"
using namespace VSido;

#include <memory>
#include <thread>
using namespace std;

#include "picojson.h"

static unique_ptr<UARTConnect> uartConn_;
static unique_ptr<UARTSend> uartSend_;
static unique_ptr<UARTRead> uartRead_;

VSido::SystemInfo VSido::gSysInfo;
void fillSystemInformation(void);

void IOConnect(const string &device,int baudrate) throw(string)
{
    fillSystemInformation();
	if(device.empty())
	{
		initEnv();
		uartConn_ = unique_ptr<UARTConnect>(new UARTConnect("/dev/tty.vsido.link"));
	}
	else
	{
		uartConn_ = unique_ptr<UARTConnect>(new UARTConnect(device,baudrate));
	}
	uartSend_ = unique_ptr<UARTSend>(new UARTSend);
	uartRead_ = unique_ptr<UARTRead>(new UARTRead);
	uartSend_->setFD(*uartConn_);
	uartRead_->setFD(*uartConn_);

	thread threadRead(std::ref(*uartRead_));
	threadRead.detach();

}

void IODisConnect(void ) throw(string)
{
	if(nullptr != uartConn_)
	{
		uartConn_->closeSPP();
		uartConn_.reset(nullptr);
	}
}

void IOSendUart(list<unsigned char> data)
{
	if(nullptr != uartSend_)
	{
		uartSend_->send(data);
	}
}

void IOSetRecieveCallback(function<void(list<unsigned char>)> fn)
{
	if(nullptr != uartRead_)
	{
		uartRead_->callback(fn);
	}
}

static string exec(string cmd)
{
    FILE* pipe = ::popen(cmd.c_str(), "r");
    if (!pipe)
	{
		return "ERROR";
	}
    char buffer[128];
    std::string result = "";
    while(!feof(pipe))
	{
    	if(fgets(buffer, 128, pipe) != NULL)
		{
    		result += buffer;
		}
    }
    pclose(pipe);
    return result;
}

/** 実行時必要なファイル領域を作る
* @param None
* @return None
*/
static void initEnv(void)
{
    string systemType("uname");
    auto uType = exec(systemType);
    FATAL_VAR(uType);
    if("Darwin\n"== uType)
    {
        /// using bluetooth
        {
            string shell("find  /dev/tty* | grep tty.SBDBT");
            auto result = exec(shell);
            FATAL_VAR(result);
            stringstream ss(result);
            std::string tty;
            getline(ss, tty);
            FATAL_VAR(tty);
            if(tty.size() > 5)
            {
                string link("rm -f /dev/tty.vsido.link;ln -sf ");
                link += tty;
                link += " /dev/tty.vsido.link";
                auto result = exec(link);
                FATAL_VAR(result);
            }
        }
    }
    else if("Linux\n"== uType)
    {
        /// add a action log folder
        {
            string shell("umount /mnt/vsido/log");
            int ret = ::system(shell.c_str());
        }
        {
            string shell("mkdir -p /mnt/vsido/log");
            int ret = ::system(shell.c_str());
        }
        {
            string shell("mount -t tmpfs -o size=2M tmpfs /mnt/vsido/log");
            int ret = ::system(shell.c_str());
        }
        {
            string shell("sync");
            int ret = ::system(shell.c_str());
        }
    }

	string systemInfo("uname -n");
    auto uname = exec(systemInfo);
	FATAL_VAR(uname);
	if("raspberrypi\n"== uname)
	{
		/// using AMA0
		{
			string shell("find  /dev/tty* | grep ttyAMA0");
	        auto result = exec(shell);
	    	FATAL_VAR(result);
			if(result.size() > 5)
			{
				string link("rm -f /dev/tty.vsido.link;ln -sf /dev/ttyAMA0 /dev/tty.vsido.link");
				auto result = exec(link);
				FATAL_VAR(result);
			}
		}
		/// check BT ,if has a HCI Mode dongle will using BLUE Tooth
		{
			/// wait 5 secend for usb dongle.
			{
				string shell("sleep 5;lsusb;hciconfig;");
		        auto result = exec(shell);
		    	FATAL_VAR(result);
			}
			string shell("hciconfig | grep \"BD Address:\"");
	        auto result = exec(shell);
	    	FATAL_VAR(result);
			if(result.size() > 5)
			{
		        string shellBT("/opt/vsido/usr/bin/btsetup");
				system(shellBT.c_str());
				/// blocked at read pipe us system. do not see result.
//		        auto result = exec(shellBT);
//		    	FATAL_VAR(result);
				{
					string link("ln -sf /dev/rfcomm75 /dev/tty.vsido.link");
					auto result = exec(link);
					FATAL_VAR(result);
				}
			}
		}
	}
	else if("edison\n"== uname)
	{
        string shellBT("/home/sysroot/usr/bin/btsetup");
        system(shellBT.c_str());

		{
			string link("rm -f /dev/tty.vsido.link;ln -sf /dev/rfcomm75 /dev/tty.vsido.link");
			auto result = exec(link);
			FATAL_VAR(result);
		}
    }
    else
    {

    }
}

#define BAURATE(x) {"B_"#x,B##x}

static map<string,int> baudrateTable =
{
    BAURATE(50),
    BAURATE(75),
    BAURATE(110),
    BAURATE(134),
    BAURATE(150),
    BAURATE(200),
    BAURATE(300),
    BAURATE(600),
    BAURATE(1200),
    BAURATE(1800),
    BAURATE(2400),
    BAURATE(4800),
    BAURATE(9600),
    BAURATE(19200),
    BAURATE(38400),
    BAURATE(57600),
    BAURATE(115200),
    BAURATE(230400),
    BAURATE(460800),
    BAURATE(500000),
    BAURATE(576000),
    BAURATE(921600),
    BAURATE(1000000),
    BAURATE(1152000),
    BAURATE(1500000),
    BAURATE(2000000),
    BAURATE(2500000),
    BAURATE(3000000),
    BAURATE(3500000),
    BAURATE(4000000)
};

void readConfig(string &port ,int &baudrate)
{
    string systemInfo("uname -n");
    auto uname = exec(systemInfo);
    FATAL_VAR(uname);

    string configPah;
    if("edison\n"== uname)
    {
        configPah = "/home/sysroot/usr/etc/serial";
    }
    else if("raspberrypi\n"== uname)
    {
        configPah = "/opt/vsido/usr/etc/serial";
    }
    else
    {

    }
    if(false==configPah.empty())
    {
        picojson::value conf;
        ifstream t(configPah);
        string err;
        picojson::parse(conf, istream_iterator<char>(t),istream_iterator<char>(),&err);

        if(err.empty())
        {
            auto& confObj = conf.get<picojson::object>();

            if(conf.contains("port"))
            {
                port = confObj["port"].get<string>();
            }
            if(conf.contains("baudrate"))
            {
                auto baudrateS = confObj["baudrate"].get<string>();
                auto it = baudrateTable.find(baudrateS);
                if(it != baudrateTable.end())
                {
                    baudrate = it->second;
                }
            }
        }
        else
        {
            FATAL_VAR(err);
        }
    }
}

void fillSystemInformation(void)
{
    gSysInfo.linux =true;
    string systemInfo("cat /etc/vsido/name");
    auto uname = exec(systemInfo);
    FATAL_VAR(uname);

    string configPah;
    if("edison\n"== uname)
    {
        gSysInfo.edison =true;
    	gSysInfo.name = "edison";
    }
    else if("raspberrypi\n"== uname)
    {
        gSysInfo.rasp =true;
    	gSysInfo.name = "rasp";
    }
    else
    {

    }

}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: forbiddencharacterstable.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-11-08 09:09:58 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <forbiddencharacterstable.hxx>

#include <unotools/localedatawrapper.hxx>
#include <unolingu.hxx>

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

SvxForbiddenCharactersTable::SvxForbiddenCharactersTable( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xMSF, USHORT nISize, USHORT nGrow )
 : SvxForbiddenCharactersTableImpl( nISize, nGrow )
{
    mxMSF = xMSF;
}

SvxForbiddenCharactersTable::~SvxForbiddenCharactersTable()
{
    for ( ULONG n = Count(); n; )
        delete GetObject( --n );
}

const com::sun::star::i18n::ForbiddenCharacters* SvxForbiddenCharactersTable::GetForbiddenCharacters( USHORT nLanguage, BOOL bGetDefault ) const
{
    ForbiddenCharactersInfo* pInf = Get( nLanguage );
    if ( !pInf && bGetDefault && mxMSF.is() )
    {
        const SvxForbiddenCharactersTableImpl *pConstImpl = dynamic_cast<const SvxForbiddenCharactersTableImpl*>(this);
        SvxForbiddenCharactersTableImpl* pImpl = const_cast<SvxForbiddenCharactersTableImpl*>(pConstImpl);
         pInf = new ForbiddenCharactersInfo;
        pImpl->Insert( nLanguage, pInf );

        pInf->bTemporary = TRUE;
        LocaleDataWrapper aWrapper( mxMSF, SvxCreateLocale( nLanguage ) );
        pInf->aForbiddenChars = aWrapper.getForbiddenCharacters();
    }
    return pInf ? &pInf->aForbiddenChars : NULL;
}

void SvxForbiddenCharactersTable::SetForbiddenCharacters( USHORT nLanguage, const com::sun::star::i18n::ForbiddenCharacters& rForbiddenChars )
{
    ForbiddenCharactersInfo* pInf = Get( nLanguage );
    if ( !pInf )
    {
        pInf = new ForbiddenCharactersInfo;
        Insert( nLanguage, pInf );
    }
    pInf->bTemporary = FALSE;
    pInf->aForbiddenChars = rForbiddenChars;
}

void SvxForbiddenCharactersTable::ClearForbiddenCharacters( USHORT nLanguage )
{
    ForbiddenCharactersInfo* pInf = Get( nLanguage );
    if ( pInf )
    {
        Remove( nLanguage );
        delete pInf;
    }
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.432); FILE MERGED 2006/09/01 17:46:38 kaib 1.3.432.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: forbiddencharacterstable.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 04:51:44 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"

#include <forbiddencharacterstable.hxx>

#include <unotools/localedatawrapper.hxx>
#include <unolingu.hxx>

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

SvxForbiddenCharactersTable::SvxForbiddenCharactersTable( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xMSF, USHORT nISize, USHORT nGrow )
 : SvxForbiddenCharactersTableImpl( nISize, nGrow )
{
    mxMSF = xMSF;
}

SvxForbiddenCharactersTable::~SvxForbiddenCharactersTable()
{
    for ( ULONG n = Count(); n; )
        delete GetObject( --n );
}

const com::sun::star::i18n::ForbiddenCharacters* SvxForbiddenCharactersTable::GetForbiddenCharacters( USHORT nLanguage, BOOL bGetDefault ) const
{
    ForbiddenCharactersInfo* pInf = Get( nLanguage );
    if ( !pInf && bGetDefault && mxMSF.is() )
    {
        const SvxForbiddenCharactersTableImpl *pConstImpl = dynamic_cast<const SvxForbiddenCharactersTableImpl*>(this);
        SvxForbiddenCharactersTableImpl* pImpl = const_cast<SvxForbiddenCharactersTableImpl*>(pConstImpl);
         pInf = new ForbiddenCharactersInfo;
        pImpl->Insert( nLanguage, pInf );

        pInf->bTemporary = TRUE;
        LocaleDataWrapper aWrapper( mxMSF, SvxCreateLocale( nLanguage ) );
        pInf->aForbiddenChars = aWrapper.getForbiddenCharacters();
    }
    return pInf ? &pInf->aForbiddenChars : NULL;
}

void SvxForbiddenCharactersTable::SetForbiddenCharacters( USHORT nLanguage, const com::sun::star::i18n::ForbiddenCharacters& rForbiddenChars )
{
    ForbiddenCharactersInfo* pInf = Get( nLanguage );
    if ( !pInf )
    {
        pInf = new ForbiddenCharactersInfo;
        Insert( nLanguage, pInf );
    }
    pInf->bTemporary = FALSE;
    pInf->aForbiddenChars = rForbiddenChars;
}

void SvxForbiddenCharactersTable::ClearForbiddenCharacters( USHORT nLanguage )
{
    ForbiddenCharactersInfo* pInf = Get( nLanguage );
    if ( pInf )
    {
        Remove( nLanguage );
        delete pInf;
    }
}
<|endoftext|>


<commit_before>// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

#include "sw/device/silicon_creator/lib/error.h"

#include <climits>
#include <cstdint>
#include <map>
#include <string>

#include "gtest/gtest.h"
#include "sw/device/lib/base/bitfield.h"

namespace error_unittest {
namespace {

// FIXME: what should this value be?
constexpr int kMinimumHammingDistance = 4;

const std::map<std::string, uint32_t> &GetErrorMap() {
#define STRINGIFY(x) #x
#define ERROR_MAP_INIT(name, value) \
  { STRINGIFY(name), value }
  static std::map<std::string, uint32_t> errors = {
      DEFINE_ERRORS(ERROR_MAP_INIT),
  };
  return errors;
}

rom_error_t ReturnIfError(rom_error_t value) {
  RETURN_IF_ERROR(value);

  // Return something other than kErrorOk just in case RETURN_IF_ERROR
  // was wrong.
  return static_cast<rom_error_t>(0);
}

int HammingDistance(uint32_t a, uint32_t b) {
  // The hamming distance is the number of bits different between the two words.
  return bitfield_popcount32(a ^ b);
}

// Checks that there are no duplicate values in the error definitions.
TEST(ErrorsTest, NoDuplicateValues) {
  const auto &errors = GetErrorMap();

  for (auto a = errors.begin(); a != errors.end(); ++a) {
    for (auto b = a; b != errors.end(); ++b) {
      if (a == b) {
        continue;
      }
      EXPECT_NE(a->second, b->second)
          << "Error codes '" << a->first << "' and '" << b->first
          << "' have the same value.";
    }
  }
}

// Checks that the RETURN_IF_ERROR macro works as expected.
TEST(ErrorsTest, CheckReturnIfError) {
  EXPECT_EQ(kErrorUartBadBaudRate, ReturnIfError(kErrorUartBadBaudRate));

  rom_error_t ok = ReturnIfError(kErrorOk);
  EXPECT_EQ(0, static_cast<int>(ok));
}

TEST(ErrorsTest, CheckHammingDistanceToOk) {
  const auto &errors = GetErrorMap();
  int max_distance = 0;
  int min_distance = INT_MAX;
  int distance;

  for (const auto &a : errors) {
    if (a.second == kErrorOk) {
      distance = HammingDistance(a.second, 0);
      std::cout << "Hamming distance between '" << a.first
                << "' and zero: " << distance << std::endl;
    } else {
      distance = HammingDistance(a.second, kErrorOk);
      std::cout << "Hamming distance between '" << a.first
                << "' and kErrorOk: " << distance << std::endl;
    }
    EXPECT_GE(distance, kMinimumHammingDistance);
    min_distance = std::min(min_distance, distance);
    max_distance = std::max(max_distance, distance);
  }
  std::cout << "Minimum hamming distance observed: " << min_distance
            << std::endl;
  std::cout << "Maximum hamming distance observed: " << max_distance
            << std::endl;
}

}  // namespace
}  // namespace error_unittest
<commit_msg>[sw/silicon_creator] Increase min HD in error_unittest.cc<commit_after>// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

#include "sw/device/silicon_creator/lib/error.h"

#include <climits>
#include <cstdint>
#include <map>
#include <string>

#include "gtest/gtest.h"
#include "sw/device/lib/base/bitfield.h"

namespace error_unittest {
namespace {

constexpr int kMinimumHammingDistance = 6;

const std::map<std::string, uint32_t> &GetErrorMap() {
#define STRINGIFY(x) #x
#define ERROR_MAP_INIT(name, value) \
  { STRINGIFY(name), value }
  static std::map<std::string, uint32_t> errors = {
      DEFINE_ERRORS(ERROR_MAP_INIT),
  };
  return errors;
}

rom_error_t ReturnIfError(rom_error_t value) {
  RETURN_IF_ERROR(value);

  // Return something other than kErrorOk just in case RETURN_IF_ERROR
  // was wrong.
  return static_cast<rom_error_t>(0);
}

int HammingDistance(uint32_t a, uint32_t b) {
  // The hamming distance is the number of bits different between the two words.
  return bitfield_popcount32(a ^ b);
}

// Checks that there are no duplicate values in the error definitions.
TEST(ErrorsTest, NoDuplicateValues) {
  const auto &errors = GetErrorMap();

  for (auto a = errors.begin(); a != errors.end(); ++a) {
    for (auto b = a; b != errors.end(); ++b) {
      if (a == b) {
        continue;
      }
      EXPECT_NE(a->second, b->second)
          << "Error codes '" << a->first << "' and '" << b->first
          << "' have the same value.";
    }
  }
}

// Checks that the RETURN_IF_ERROR macro works as expected.
TEST(ErrorsTest, CheckReturnIfError) {
  EXPECT_EQ(kErrorUartBadBaudRate, ReturnIfError(kErrorUartBadBaudRate));

  rom_error_t ok = ReturnIfError(kErrorOk);
  EXPECT_EQ(0, static_cast<int>(ok));
}

TEST(ErrorsTest, CheckHammingDistanceToOk) {
  const auto &errors = GetErrorMap();
  int max_distance = 0;
  int min_distance = INT_MAX;
  int distance;

  for (const auto &a : errors) {
    if (a.second == kErrorOk) {
      distance = HammingDistance(a.second, 0);
      std::cout << "Hamming distance between '" << a.first
                << "' and zero: " << distance << std::endl;
    } else {
      distance = HammingDistance(a.second, kErrorOk);
      std::cout << "Hamming distance between '" << a.first
                << "' and kErrorOk: " << distance << std::endl;
    }
    EXPECT_GE(distance, kMinimumHammingDistance);
    min_distance = std::min(min_distance, distance);
    max_distance = std::max(max_distance, distance);
  }
  std::cout << "Minimum hamming distance observed: " << min_distance
            << std::endl;
  std::cout << "Maximum hamming distance observed: " << max_distance
            << std::endl;
}

}  // namespace
}  // namespace error_unittest
<|endoftext|>


<commit_before>#include "stdafx.h"

class security_attributes
{
    SECURITY_ATTRIBUTES _securityAttributes;
    PSID pEveryoneSID;
    PACL pACL;
    PSECURITY_DESCRIPTOR pSD;
public:
    security_attributes(DWORD permissions) : pEveryoneSID(nullptr), pACL(nullptr), pSD(nullptr)
    {
        SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;

        // Create a well-known SID for the Everyone group.
        if (!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pEveryoneSID))
        {
            printf("AllocateAndInitializeSid Error %u\n", GetLastError());
            return;
        }

        EXPLICIT_ACCESS ea = { 0 };
        ea.grfAccessPermissions = permissions;
        ea.grfAccessMode = SET_ACCESS;
        ea.grfInheritance = NO_INHERITANCE;
        ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
        ea.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
        ea.Trustee.ptstrName = (LPTSTR)pEveryoneSID;

        // Create a new ACL that contains the new ACEs.
        DWORD dwRes = SetEntriesInAclW(1, &ea, NULL, &pACL);
        if (dwRes != ERROR_SUCCESS)
        {
            printf("SetEntriesInAcl Error %u\n", GetLastError());
            return;
        }

        // Initialize a security descriptor.
        pSD = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
        if (pSD == NULL)
        {
            printf("LocalAlloc Error %u\n", GetLastError());
            return;
        }

        if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION))
        {
            printf("InitializeSecurityDescriptor Error %u\n", GetLastError());
            return;
        }

        // Add the ACL to the security descriptor.
        if (!SetSecurityDescriptorDacl(pSD, TRUE, pACL, FALSE))
        {
            printf("SetSecurityDescriptorDacl Error %u\n", GetLastError());
            return;
        }

        // Initialize a security attributes structure.
        _securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
        _securityAttributes.lpSecurityDescriptor = pSD;
        _securityAttributes.bInheritHandle = FALSE;
    }

    ~security_attributes()
    {
        if (pEveryoneSID)
            FreeSid(pEveryoneSID);
        if (pACL)
            LocalFree(pACL);
        if (pSD)
            LocalFree(pSD);
    }

    LPSECURITY_ATTRIBUTES get_sa()
    {
        return &_securityAttributes;
    }
};

void init_security_attributes(LPSECURITY_ATTRIBUTES lpSecurityAttributes)
{
    DWORD dwRes;
    PSID pEveryoneSID = NULL;
    PACL pACL = NULL;
    PSECURITY_DESCRIPTOR pSD = NULL;
    EXPLICIT_ACCESS ea;
    SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;

    // Create a well-known SID for the Everyone group.
    if (!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pEveryoneSID))
    {
        printf("AllocateAndInitializeSid Error %u\n", GetLastError());
        goto Cleanup;
    }

    ZeroMemory(&ea, sizeof(EXPLICIT_ACCESS));
    ea.grfAccessPermissions = GENERIC_WRITE | GENERIC_READ;
    ea.grfAccessMode = SET_ACCESS;
    ea.grfInheritance = NO_INHERITANCE;
    ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
    ea.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
    ea.Trustee.ptstrName = (LPTSTR)pEveryoneSID;

    // Create a new ACL that contains the new ACEs.
    dwRes = SetEntriesInAclW(1, &ea, NULL, &pACL);
    if (ERROR_SUCCESS != dwRes)
    {
        printf("SetEntriesInAcl Error %u\n", GetLastError());
        goto Cleanup;
    }

    // Initialize a security descriptor.
    pSD = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
    if (NULL == pSD)
    {
        printf("LocalAlloc Error %u\n", GetLastError());
        goto Cleanup;
    }

    if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION))
    {
        printf("InitializeSecurityDescriptor Error %u\n", GetLastError());
        goto Cleanup;
    }

    // Add the ACL to the security descriptor.
    if (!SetSecurityDescriptorDacl(pSD, TRUE, pACL, FALSE))
    {
        printf("SetSecurityDescriptorDacl Error %u\n", GetLastError());
        goto Cleanup;
    }

    // Initialize a security attributes structure.
    lpSecurityAttributes->nLength = sizeof(SECURITY_ATTRIBUTES);
    lpSecurityAttributes->lpSecurityDescriptor = pSD;
    lpSecurityAttributes->bInheritHandle = FALSE;

Cleanup:

    if (pEveryoneSID)
        FreeSid(pEveryoneSID);
    if (pACL)
        LocalFree(pACL);
    if (pSD)
        LocalFree(pSD);

    return;
}

// This gives all access to anyone, allows client impersonation
void init_security_attributes2(LPSECURITY_ATTRIBUTES lpSecurityAttributes)
{
    auto pSD = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);

    if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION))
    {
        printf("InitializeSecurityDescriptor Error %d\n", GetLastError());
        return;
    }

    if (!SetSecurityDescriptorDacl(pSD, TRUE, NULL, FALSE))
    {
        printf("SetSecurityDescriptorDacl Error %d\n", GetLastError());
        return;
    }

    lpSecurityAttributes->nLength = sizeof(SECURITY_ATTRIBUTES);
    lpSecurityAttributes->lpSecurityDescriptor = pSD;
    lpSecurityAttributes->bInheritHandle = FALSE;
}

int main()
{
    HANDLE hPipe;
    char buffer[1024];
    DWORD dwRead;

    SECURITY_ATTRIBUTES securityAttributes;
    init_security_attributes(&securityAttributes);

    security_attributes sa(GENERIC_WRITE | GENERIC_READ);

    hPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\ztp-client-pipe"),
        PIPE_ACCESS_DUPLEX | PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,   // FILE_FLAG_FIRST_PIPE_INSTANCE is not needed but forces CreateNamedPipe(..) to fail if the pipe already exists...
        PIPE_WAIT,
        1,
        1024 * 16,
        1024 * 16,
        NMPWAIT_USE_DEFAULT_WAIT,
        sa.get_sa());
    if (hPipe != INVALID_HANDLE_VALUE)
    {
        printf("Waiting for someone to connect...\n");
        if (ConnectNamedPipe(hPipe, NULL) != FALSE)   // wait for someone to connect to the pipe
        {
            printf("Reading data...\n");
            while (ReadFile(hPipe, buffer, sizeof(buffer) - 1, &dwRead, NULL) != FALSE)
            {
                /* add terminating zero */
                buffer[dwRead] = '\0';

                /* do something with data in buffer */
                printf("%s", buffer);
            }
        }
        else
        {
            printf("ConnectNamedPipe Error %d\n", GetLastError());
        }

        DisconnectNamedPipe(hPipe);
    }
    else
    {
        printf("CreateNamedPipe Error %d\n", GetLastError());
    }

    return 0;
}

<commit_msg>Remove init_security_attributes function<commit_after>#include "stdafx.h"

class security_attributes
{
    SECURITY_ATTRIBUTES _securityAttributes;
    PSID pEveryoneSID;
    PACL pACL;
    PSECURITY_DESCRIPTOR pSD;
public:
    security_attributes(DWORD permissions) : pEveryoneSID(nullptr), pACL(nullptr), pSD(nullptr)
    {
        SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;

        // Create a well-known SID for the Everyone group.
        if (!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pEveryoneSID))
        {
            printf("AllocateAndInitializeSid Error %u\n", GetLastError());
            return;
        }

        EXPLICIT_ACCESS ea = { 0 };
        ea.grfAccessPermissions = permissions;
        ea.grfAccessMode = SET_ACCESS;
        ea.grfInheritance = NO_INHERITANCE;
        ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
        ea.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
        ea.Trustee.ptstrName = (LPTSTR)pEveryoneSID;

        // Create a new ACL that contains the new ACEs.
        DWORD dwRes = SetEntriesInAclW(1, &ea, NULL, &pACL);
        if (dwRes != ERROR_SUCCESS)
        {
            printf("SetEntriesInAcl Error %u\n", GetLastError());
            return;
        }

        // Initialize a security descriptor.
        pSD = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);
        if (pSD == NULL)
        {
            printf("LocalAlloc Error %u\n", GetLastError());
            return;
        }

        if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION))
        {
            printf("InitializeSecurityDescriptor Error %u\n", GetLastError());
            return;
        }

        // Add the ACL to the security descriptor.
        if (!SetSecurityDescriptorDacl(pSD, TRUE, pACL, FALSE))
        {
            printf("SetSecurityDescriptorDacl Error %u\n", GetLastError());
            return;
        }

        // Initialize a security attributes structure.
        _securityAttributes.nLength = sizeof(SECURITY_ATTRIBUTES);
        _securityAttributes.lpSecurityDescriptor = pSD;
        _securityAttributes.bInheritHandle = FALSE;
    }

    ~security_attributes()
    {
        if (pEveryoneSID)
            FreeSid(pEveryoneSID);
        if (pACL)
            LocalFree(pACL);
        if (pSD)
            LocalFree(pSD);
    }

    LPSECURITY_ATTRIBUTES get_sa()
    {
        return &_securityAttributes;
    }
};

// HACK: this gives all access to anyone, allows client impersonation
void init_security_attributes2(LPSECURITY_ATTRIBUTES lpSecurityAttributes)
{
    auto pSD = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH);

    if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION))
    {
        printf("InitializeSecurityDescriptor Error %d\n", GetLastError());
        return;
    }

    if (!SetSecurityDescriptorDacl(pSD, TRUE, NULL, FALSE))
    {
        printf("SetSecurityDescriptorDacl Error %d\n", GetLastError());
        return;
    }

    lpSecurityAttributes->nLength = sizeof(SECURITY_ATTRIBUTES);
    lpSecurityAttributes->lpSecurityDescriptor = pSD;
    lpSecurityAttributes->bInheritHandle = FALSE;
}

int main()
{
    HANDLE hPipe;
    char buffer[1024];
    DWORD dwRead;

    security_attributes sa(GENERIC_WRITE | GENERIC_READ);

    hPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\ztp-client-pipe"),
        PIPE_ACCESS_DUPLEX | PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,   // FILE_FLAG_FIRST_PIPE_INSTANCE is not needed but forces CreateNamedPipe(..) to fail if the pipe already exists...
        PIPE_WAIT,
        1,
        1024 * 16,
        1024 * 16,
        NMPWAIT_USE_DEFAULT_WAIT,
        sa.get_sa());
    if (hPipe != INVALID_HANDLE_VALUE)
    {
        printf("Waiting for someone to connect...\n");
        if (ConnectNamedPipe(hPipe, NULL) != FALSE)   // wait for someone to connect to the pipe
        {
            printf("Reading data...\n");
            while (ReadFile(hPipe, buffer, sizeof(buffer) - 1, &dwRead, NULL) != FALSE)
            {
                /* add terminating zero */
                buffer[dwRead] = '\0';

                /* do something with data in buffer */
                printf("%s", buffer);
            }
        }
        else
        {
            printf("ConnectNamedPipe Error %d\n", GetLastError());
        }

        DisconnectNamedPipe(hPipe);
    }
    else
    {
        printf("CreateNamedPipe Error %d\n", GetLastError());
    }

    return 0;
}

<|endoftext|>


<commit_before>// Copyright Hugh Perkins 2016

// 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 "cocl/cocl_memory.h"

#include "cocl/hostside_opencl_funcs.h"

#include <iostream>
#include <memory>
#include <vector>
#include <map>
#include <set>

#include "EasyCL.h"

#include "CL/cl.h"

using namespace std;
using namespace cocl;
using namespace easycl;

#undef COCL_PRINT
#define COCL_PRINT(stuff) \
   stuff

namespace cocl {
    // we should index these, but a set is ok-ish for now. maybe
    set<Memory *>memories;
    long long nextAllocPos = 1;
    map< long long, Memory *>memoryByAllocPos;

    Memory::Memory(cl_mem clmem, size_t bytes) :
            clmem(clmem), bytes(bytes) {
        fakePos = nextAllocPos;
        nextAllocPos += bytes;
        memoryByAllocPos[fakePos] = this;
        memories.insert(this);
    }

    Memory *Memory::newDeviceAlloc(size_t bytes) {
        cl_int err;
        cl_mem clmem = clCreateBuffer(*ctx, CL_MEM_READ_WRITE, bytes,
                                               NULL, &err);
        cl->checkError(err);
        Memory *memory = new Memory(clmem, bytes);
        COCL_PRINT(cout << "Memory::newDeviceAlloc bytes=" << bytes << " memory=" << (void *)memory << " clmem=" << (void*)memory->clmem << endl);
        return memory;
    }

    Memory::~Memory() {
        COCL_PRINT(cout << "~Memory releasing mem object memory=" << (void *)this << endl);
        cl_int err = clReleaseMemObject(clmem);
        cl->checkError(err);
        // TODO: should remove from map and set too
    }

    Memory *findMemory(char *passedInAsCharStar) {
        // char *passedInAsCharStar = (char *)passedInPointer;
        long long pos = (long long )passedInAsCharStar;
        for(auto it=memories.begin(), e=memories.end(); it != e; it++) {
            Memory *memory = *it;
            if(pos >= memory->fakePos && pos < memory->fakePos + memory->bytes) {
                COCL_PRINT(cout << "found memory: " << (void *)memory);
                return memory;
            }
        }
        cout << "could not find memory for " << (void *)passedInAsCharStar << endl;
        throw runtime_error("could not find memory");
    }
    size_t Memory::getOffset(char *passedInAsCharStar) {
        return (long long)passedInAsCharStar - fakePos;
    }
}

size_t cuMemHostAlloc(void **pHostPointer, unsigned int bytes, int CU_MEMHOSTALLOC_PORTABLE) {
    COCL_PRINT(cout << "cuMemHostAlloc redirected bytes=" << bytes << endl);
    *pHostPointer = malloc(bytes);
    return 0;
}

size_t cuMemFreeHost(void *hostPointer) {
    COCL_PRINT(cout << "cuMemFreeHost redirected" << endl);
    free(hostPointer);
    return 0;
}

size_t cuMemGetInfo(size_t *free, size_t *total) {
    COCL_PRINT(cout << "cuMemGetInfo redirected" << endl);
    *free = 1024 * 1024;
    *total = 1024 * 1024;
    return 0;
}

size_t cudaMemcpyAsync (void *dst, const void *src, size_t count, size_t cudaMemcpyKind, char *_queue) {
    CLQueue *queue = (CLQueue *)_queue;
    COCL_PRINT(cout << "cudaMemcpyAsync count=" << count << " cudaMemcpyKind=" << cudaMemcpyKind << " queue=" << queue << endl);

    if(queue == 0) {
        queue = cl->default_queue;
        COCL_PRINT(cout << "using default queue" << endl);
    }
    cl_int err;
    if(cudaMemcpyKind == cudaMemcpyDeviceToHost) {
        // device => host
        // Memory *srcMemory = (Memory *)src;
        Memory *srcMemory = findMemory((char *)src);
        size_t src_offset = srcMemory->getOffset((char *)src);
        err = clEnqueueReadBuffer(queue->queue, srcMemory->clmem, CL_FALSE, src_offset,
                                         count, dst, 0, NULL, NULL);
        cl->checkError(err);
        // cl->finish();
    } else if(cudaMemcpyKind == cudaMemcpyHostToDevice) {
        // host => device
        // Memory *dstMemory = (Memory*)dst;
        Memory *dstMemory = findMemory((char *)dst);
        size_t dst_offset = dstMemory->getOffset((char *)dst);
        err = clEnqueueWriteBuffer(queue->queue, dstMemory->clmem, CL_FALSE, dst_offset,
                                          count, src, 0, NULL, NULL);
        cl->checkError(err);
    } else {
        cout << "cudaMemcpyKind using opencl " << cudaMemcpyKind << endl;
        throw runtime_error("unhandled cudaMemcpyKind");
    }

    return 0;
}

size_t cudaMemsetAsync(void *devPtr, int value, size_t count, char *_queue) {
    CLQueue *queue = (CLQueue *)_queue;
    COCL_PRINT(cout << "cudaMemsetAsync stub value=" << value << " count=" << count << " queue=" << queue << endl);
    // assert(stream == 0);
    throw runtime_error("cudaMemsetAsync not implemented");

    return 0;
}

size_t cuMemsetD8(CUdeviceptr location, unsigned char value, uint32_t count) {
    COCL_PRINT(cout << "cuMemsetD8 redirected value " << value << " count=" << count << endl);
    // Memory *memory = (Memory *)location;
    // use default queue??
    Memory *memory = findMemory((char *)location);
    size_t offset = memory->getOffset((char *)location);
    cl_int err = clEnqueueFillBuffer(cl->default_queue->queue, memory->clmem, &value, sizeof(unsigned char), offset, count * sizeof(unsigned char), 0, 0, 0);
    cl->checkError(err);
    return 0;
}

size_t cuMemsetD32(CUdeviceptr location, unsigned int value, uint32_t count) {
    // Memory *memory = (Memory *)location;
    Memory *memory = findMemory((char *)location);
    size_t offset = memory->getOffset((char *)location);
    COCL_PRINT(cout << "cuMemsetD32 redirected value " << value << " count=" << count << " location=" << location << " memory=" << (void *)memory << endl);
    cl_int err = clEnqueueFillBuffer(cl->default_queue->queue, memory->clmem, &value, sizeof(int), offset, count * sizeof(int), 0, 0, 0);
    cl->checkError(err);
    return 0;
}

size_t cuDeviceTotalMem(uint64_t *value, CUdeviceptr device) {
    COCL_PRINT(cout << "cuDeviceTotalMem redirected" << endl);
    *value = 1024 * 1024;
    return 0;
}

size_t cudaMemcpy(void *dst, const void *src, size_t bytes, size_t cudaMemcpyKind) {
    COCL_PRINT(cout << "cudamempcy using opencl cudaMemcpyKind " << cudaMemcpyKind << " count=" << bytes << endl);
    cl_int err;
    if(cudaMemcpyKind == cudaMemcpyDeviceToHost) {
        // device => host
        cout << "cudamemcpy device to host" << endl;
        Memory *srcMemory = findMemory((char *)src);
        size_t offset = srcMemory->getOffset((char *)src);
        err = clEnqueueReadBuffer(cl->default_queue->queue, srcMemory->clmem, CL_TRUE, offset,
                                         bytes, dst, 0, NULL, NULL);
        cl->checkError(err);
        // cl->finish();
    } else if(cudaMemcpyKind == cudaMemcpyHostToDevice) {
        // host => device
        cout << "cudamemcpy host to device" << endl;
        Memory *dstMemory = findMemory((char *)dst);
        size_t offset = dstMemory->getOffset((char *)dst);
        err = clEnqueueWriteBuffer(cl->default_queue->queue, dstMemory->clmem, CL_TRUE, offset,
                                          bytes, src, 0, NULL, NULL);
        cl->checkError(err);
    } else if(cudaMemcpyKind == cudaMemcpyDeviceToDevice) {
        // device => device
        Memory *srcMemory = findMemory((char *)src);
        size_t src_offset = srcMemory->getOffset((char *)src);
        Memory *dstMemory = findMemory((char *)dst);
        size_t dst_offset = dstMemory->getOffset((char *)dst);
        err = clEnqueueCopyBuffer(
            cl->default_queue->queue,
            srcMemory->clmem,
            dstMemory->clmem,
            src_offset,
            dst_offset,
            bytes,
            0,
            0,
            0);
        cl->checkError(err);
    } else {
        cout << "cudaMemcpyKind using opencl " << cudaMemcpyKind << endl;
        throw runtime_error("unhandled cudaMemcpyKind");
    }
    return 0;
}

size_t cuMemcpyHtoDAsync(CUdeviceptr dst, const void *src, size_t bytes, char *_queue) {
    CLQueue *queue = (CLQueue*)_queue;
    // host => device
    COCL_PRINT(cout << "cuMemcpyHtoDAsync dst=" << dst << " src=" << src << " bytes=" << bytes << endl);
    Memory *dstMemory = findMemory((char *)dst);
    size_t offset = dstMemory->getOffset((char *)dst);
    COCL_PRINT(cout << "memory " << (void *)dstMemory << " offset=" << offset << endl);
    cl_int err = clEnqueueWriteBuffer(queue->queue, dstMemory->clmem, CL_FALSE, offset,
                                      bytes, src, 0, NULL, NULL);
    cl->checkError(err);
    return 0;
}

size_t  cuMemcpyDtoHAsync(void *dst, CUdeviceptr src, size_t bytes, char *_queue) {
    CLQueue *queue = (CLQueue*)_queue;
    COCL_PRINT(cout << "cuMemcpyDtoHAsync dst=" << dst << " src=" << src << " bytes=" << bytes << endl);
    Memory *srcMemory = findMemory((char *)src);
    size_t offset = srcMemory->getOffset((char *)src);
    COCL_PRINT(cout << "memory " << (void *)srcMemory << " offset=" << offset << endl);
    cl_int err = clEnqueueReadBuffer(queue->queue, srcMemory->clmem, CL_FALSE, offset,
                                     bytes, dst, 0, NULL, NULL);
    cl->checkError(err);
    return 0;
}

// => synchronous <=
size_t cuMemcpyHtoD(CUdeviceptr gpu_dst, const void *host_src, size_t size) {
    cudaMemcpy((void *)gpu_dst, host_src, size, cudaMemcpyHostToDevice);
    cl->finish();
    return 0;
}

// => synchronous <=
size_t  cuMemcpyDtoH(void *host_dst, CUdeviceptr gpu_src, size_t size) {
    cout << "cumemcpyDtoH" << endl;
    cudaMemcpy(host_dst, (void *)gpu_src, size, cudaMemcpyDeviceToHost);
    cl->finish();
    return 0;
}

size_t cudaMalloc(void **_pMemory, size_t N) {
    hostside_opencl_funcs_assure_initialized();
    Memory *memory = Memory::newDeviceAlloc(N);
    COCL_PRINT(cout << "cudaMalloc using cl, size " << N << " memory=" << (void *)memory << " fakePos=" << memory->fakePos << endl);
    *_pMemory = (void *)memory->fakePos;
    return 0;
}

size_t cuMemAlloc(CUdeviceptr*_pMemory, size_t bytes) {
    return cudaMalloc((void **)_pMemory, bytes);
}

size_t cudaFree(void *_memory) {
    Memory *memory = findMemory((char *)_memory);
    COCL_PRINT(cout << "cudafree using opencl memory=" << memory << endl);
    delete memory;
    return 0;
}

size_t cuMemFree(CUdeviceptr memory) {
    return cudaFree((void *)memory);
}
<commit_msg>"memory" is 128-aligned now<commit_after>// Copyright Hugh Perkins 2016

// 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 "cocl/cocl_memory.h"

#include "cocl/hostside_opencl_funcs.h"

#include <iostream>
#include <memory>
#include <vector>
#include <map>
#include <set>

#include "EasyCL.h"

#include "CL/cl.h"

using namespace std;
using namespace cocl;
using namespace easycl;

#undef COCL_PRINT
#define COCL_PRINT(stuff) \
   stuff

namespace cocl {
    // we should index these, but a set is ok-ish for now. maybe
    set<Memory *>memories;
    long long nextAllocPos = 1;
    map< long long, Memory *>memoryByAllocPos;

    Memory::Memory(cl_mem clmem, size_t bytes) :
            clmem(clmem), bytes(bytes) {
        fakePos = nextAllocPos;
        // we should align it actually.  on 128-bytes?
        fakePos = ((fakePos + 127) / 128) * 128;
        nextAllocPos = fakePos + bytes;
        memoryByAllocPos[fakePos] = this;
        memories.insert(this);
    }

    Memory *Memory::newDeviceAlloc(size_t bytes) {
        cl_int err;
        cl_mem clmem = clCreateBuffer(*ctx, CL_MEM_READ_WRITE, bytes,
                                               NULL, &err);
        cl->checkError(err);
        Memory *memory = new Memory(clmem, bytes);
        COCL_PRINT(cout << "Memory::newDeviceAlloc bytes=" << bytes << " memory=" << (void *)memory << " clmem=" << (void*)memory->clmem << endl);
        return memory;
    }

    Memory::~Memory() {
        COCL_PRINT(cout << "~Memory releasing mem object memory=" << (void *)this << endl);
        cl_int err = clReleaseMemObject(clmem);
        cl->checkError(err);
        // TODO: should remove from map and set too
    }

    Memory *findMemory(char *passedInAsCharStar) {
        // char *passedInAsCharStar = (char *)passedInPointer;
        long long pos = (long long )passedInAsCharStar;
        for(auto it=memories.begin(), e=memories.end(); it != e; it++) {
            Memory *memory = *it;
            if(pos >= memory->fakePos && pos < memory->fakePos + memory->bytes) {
                COCL_PRINT(cout << "found memory: " << (void *)memory);
                return memory;
            }
        }
        cout << "could not find memory for " << (void *)passedInAsCharStar << endl;
        throw runtime_error("could not find memory");
    }
    size_t Memory::getOffset(char *passedInAsCharStar) {
        return (long long)passedInAsCharStar - fakePos;
    }
}

size_t cuMemHostAlloc(void **pHostPointer, unsigned int bytes, int CU_MEMHOSTALLOC_PORTABLE) {
    COCL_PRINT(cout << "cuMemHostAlloc redirected bytes=" << bytes << endl);
    *pHostPointer = malloc(bytes);
    return 0;
}

size_t cuMemFreeHost(void *hostPointer) {
    COCL_PRINT(cout << "cuMemFreeHost redirected" << endl);
    free(hostPointer);
    return 0;
}

size_t cuMemGetInfo(size_t *free, size_t *total) {
    COCL_PRINT(cout << "cuMemGetInfo redirected" << endl);
    *free = 1024 * 1024;
    *total = 1024 * 1024;
    return 0;
}

size_t cudaMemcpyAsync (void *dst, const void *src, size_t count, size_t cudaMemcpyKind, char *_queue) {
    CLQueue *queue = (CLQueue *)_queue;
    COCL_PRINT(cout << "cudaMemcpyAsync count=" << count << " cudaMemcpyKind=" << cudaMemcpyKind << " queue=" << queue << endl);

    if(queue == 0) {
        queue = cl->default_queue;
        COCL_PRINT(cout << "using default queue" << endl);
    }
    cl_int err;
    if(cudaMemcpyKind == cudaMemcpyDeviceToHost) {
        // device => host
        // Memory *srcMemory = (Memory *)src;
        Memory *srcMemory = findMemory((char *)src);
        size_t src_offset = srcMemory->getOffset((char *)src);
        err = clEnqueueReadBuffer(queue->queue, srcMemory->clmem, CL_FALSE, src_offset,
                                         count, dst, 0, NULL, NULL);
        cl->checkError(err);
        // cl->finish();
    } else if(cudaMemcpyKind == cudaMemcpyHostToDevice) {
        // host => device
        // Memory *dstMemory = (Memory*)dst;
        Memory *dstMemory = findMemory((char *)dst);
        size_t dst_offset = dstMemory->getOffset((char *)dst);
        err = clEnqueueWriteBuffer(queue->queue, dstMemory->clmem, CL_FALSE, dst_offset,
                                          count, src, 0, NULL, NULL);
        cl->checkError(err);
    } else {
        cout << "cudaMemcpyKind using opencl " << cudaMemcpyKind << endl;
        throw runtime_error("unhandled cudaMemcpyKind");
    }

    return 0;
}

size_t cudaMemsetAsync(void *devPtr, int value, size_t count, char *_queue) {
    CLQueue *queue = (CLQueue *)_queue;
    COCL_PRINT(cout << "cudaMemsetAsync stub value=" << value << " count=" << count << " queue=" << queue << endl);
    // assert(stream == 0);
    throw runtime_error("cudaMemsetAsync not implemented");

    return 0;
}

size_t cuMemsetD8(CUdeviceptr location, unsigned char value, uint32_t count) {
    COCL_PRINT(cout << "cuMemsetD8 redirected value " << value << " count=" << count << endl);
    // Memory *memory = (Memory *)location;
    // use default queue??
    Memory *memory = findMemory((char *)location);
    size_t offset = memory->getOffset((char *)location);
    cl_int err = clEnqueueFillBuffer(cl->default_queue->queue, memory->clmem, &value, sizeof(unsigned char), offset, count * sizeof(unsigned char), 0, 0, 0);
    cl->checkError(err);
    return 0;
}

size_t cuMemsetD32(CUdeviceptr location, unsigned int value, uint32_t count) {
    // Memory *memory = (Memory *)location;
    Memory *memory = findMemory((char *)location);
    size_t offset = memory->getOffset((char *)location);
    COCL_PRINT(cout << "cuMemsetD32 redirected value " << value << " count=" << count << " location=" << location << " memory=" << (void *)memory << endl);
    cl_int err = clEnqueueFillBuffer(cl->default_queue->queue, memory->clmem, &value, sizeof(int), offset, count * sizeof(int), 0, 0, 0);
    cl->checkError(err);
    return 0;
}

size_t cuDeviceTotalMem(uint64_t *value, CUdeviceptr device) {
    COCL_PRINT(cout << "cuDeviceTotalMem redirected" << endl);
    *value = 1024 * 1024;
    return 0;
}

size_t cudaMemcpy(void *dst, const void *src, size_t bytes, size_t cudaMemcpyKind) {
    COCL_PRINT(cout << "cudamempcy using opencl cudaMemcpyKind " << cudaMemcpyKind << " count=" << bytes << endl);
    cl_int err;
    if(cudaMemcpyKind == cudaMemcpyDeviceToHost) {
        // device => host
        cout << "cudamemcpy device to host" << endl;
        Memory *srcMemory = findMemory((char *)src);
        size_t offset = srcMemory->getOffset((char *)src);
        err = clEnqueueReadBuffer(cl->default_queue->queue, srcMemory->clmem, CL_TRUE, offset,
                                         bytes, dst, 0, NULL, NULL);
        cl->checkError(err);
        // cl->finish();
    } else if(cudaMemcpyKind == cudaMemcpyHostToDevice) {
        // host => device
        cout << "cudamemcpy host to device" << endl;
        Memory *dstMemory = findMemory((char *)dst);
        size_t offset = dstMemory->getOffset((char *)dst);
        err = clEnqueueWriteBuffer(cl->default_queue->queue, dstMemory->clmem, CL_TRUE, offset,
                                          bytes, src, 0, NULL, NULL);
        cl->checkError(err);
    } else if(cudaMemcpyKind == cudaMemcpyDeviceToDevice) {
        // device => device
        Memory *srcMemory = findMemory((char *)src);
        size_t src_offset = srcMemory->getOffset((char *)src);
        Memory *dstMemory = findMemory((char *)dst);
        size_t dst_offset = dstMemory->getOffset((char *)dst);
        err = clEnqueueCopyBuffer(
            cl->default_queue->queue,
            srcMemory->clmem,
            dstMemory->clmem,
            src_offset,
            dst_offset,
            bytes,
            0,
            0,
            0);
        cl->checkError(err);
    } else {
        cout << "cudaMemcpyKind using opencl " << cudaMemcpyKind << endl;
        throw runtime_error("unhandled cudaMemcpyKind");
    }
    return 0;
}

size_t cuMemcpyHtoDAsync(CUdeviceptr dst, const void *src, size_t bytes, char *_queue) {
    CLQueue *queue = (CLQueue*)_queue;
    // host => device
    COCL_PRINT(cout << "cuMemcpyHtoDAsync dst=" << dst << " src=" << src << " bytes=" << bytes << endl);
    Memory *dstMemory = findMemory((char *)dst);
    size_t offset = dstMemory->getOffset((char *)dst);
    COCL_PRINT(cout << "memory " << (void *)dstMemory << " offset=" << offset << endl);
    cl_int err = clEnqueueWriteBuffer(queue->queue, dstMemory->clmem, CL_FALSE, offset,
                                      bytes, src, 0, NULL, NULL);
    cl->checkError(err);
    return 0;
}

size_t  cuMemcpyDtoHAsync(void *dst, CUdeviceptr src, size_t bytes, char *_queue) {
    CLQueue *queue = (CLQueue*)_queue;
    COCL_PRINT(cout << "cuMemcpyDtoHAsync dst=" << dst << " src=" << src << " bytes=" << bytes << endl);
    Memory *srcMemory = findMemory((char *)src);
    size_t offset = srcMemory->getOffset((char *)src);
    COCL_PRINT(cout << "memory " << (void *)srcMemory << " offset=" << offset << endl);
    cl_int err = clEnqueueReadBuffer(queue->queue, srcMemory->clmem, CL_FALSE, offset,
                                     bytes, dst, 0, NULL, NULL);
    cl->checkError(err);
    return 0;
}

// => synchronous <=
size_t cuMemcpyHtoD(CUdeviceptr gpu_dst, const void *host_src, size_t size) {
    cudaMemcpy((void *)gpu_dst, host_src, size, cudaMemcpyHostToDevice);
    cl->finish();
    return 0;
}

// => synchronous <=
size_t  cuMemcpyDtoH(void *host_dst, CUdeviceptr gpu_src, size_t size) {
    cout << "cumemcpyDtoH" << endl;
    cudaMemcpy(host_dst, (void *)gpu_src, size, cudaMemcpyDeviceToHost);
    cl->finish();
    return 0;
}

size_t cudaMalloc(void **_pMemory, size_t N) {
    hostside_opencl_funcs_assure_initialized();
    Memory *memory = Memory::newDeviceAlloc(N);
    COCL_PRINT(cout << "cudaMalloc using cl, size " << N << " memory=" << (void *)memory << " fakePos=" << memory->fakePos << endl);
    *_pMemory = (void *)memory->fakePos;
    return 0;
}

size_t cuMemAlloc(CUdeviceptr*_pMemory, size_t bytes) {
    return cudaMalloc((void **)_pMemory, bytes);
}

size_t cudaFree(void *_memory) {
    Memory *memory = findMemory((char *)_memory);
    COCL_PRINT(cout << "cudafree using opencl memory=" << memory << endl);
    delete memory;
    return 0;
}

size_t cuMemFree(CUdeviceptr memory) {
    return cudaFree((void *)memory);
}
<|endoftext|>


<commit_before>/*
 *  This file is part of Poedit (https://poedit.net)
 *
 *  Copyright (C) 2016 Vaclav Slavik
 *
 *  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 "colorscheme.h"

#include <wx/settings.h>

#ifdef __WXGTK__
    #include <pango/pango-utils.h>
    #if PANGO_VERSION_CHECK(1,38,0)
        #define SUPPORTS_BGALPHA
    #endif
#else
    #define SUPPORTS_BGALPHA
#endif

namespace
{

#ifdef __WXOSX__

inline wxColour sRGB(int r, int g, int b, double a = 1.0)
{
    return wxColour([NSColor colorWithSRGBRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]);
}

#else

inline wxColour sRGB(int r, int g, int b, double a = 1.0)
{
    return wxColour(r, g, b, int(a * wxALPHA_OPAQUE));
}

#endif

} // anonymous namespace

std::unique_ptr<ColorScheme::Data> ColorScheme::s_data;

wxColour ColorScheme::DoGet(Color color, Type type)
{
    switch (color)
    {
        // Labels:

        case Color::SecondaryLabel:
            #ifdef __WXOSX__
            return wxColour([NSColor secondaryLabelColor]);
            #elif defined(__WXGTK__)
            return wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
            #else
            return wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT);
            #endif

        // List items:

        case Color::ItemID:
            return type == Light ? "#a1a1a1" : wxNullColour;
        case Color::ItemFuzzy:
            return type == Light ? sRGB(218, 123, 0) : "#a9861b";
        case Color::ItemError:
            return sRGB(242, 84, 77);
        case Color::ItemContextFg:
            return sRGB(0, 103, 37);
        case Color::ItemContextBg:
            #ifdef SUPPORTS_BGALPHA
            return sRGB(207, 243, 220, 0.75);
            #else
            return sRGB(219, 246, 229);
            #endif

        // Separators:

        case Color::ToolbarSeparator:
            return "#cdcdcd";
        case Color::SidebarSeparator:
            return "#cbcbcb";
        case Color::EditingSeparator:
            return "#c1c1c1";

        // Backgrounds:

        case Color::SidebarBackground:
            return "#edf0f4";
        case Color::EditingBackground:
            return *wxWHITE;

        // Syntax highlighting:

        case Color::SyntaxLeadingWhitespaceBg:
            return sRGB(255, 233, 204);
        case Color::SyntaxEscapeFg:
            return sRGB(162, 0, 20);
        case Color::SyntaxEscapeBg:
            return sRGB(254, 234, 236);
        case Color::SyntaxMarkup:
            return sRGB(0, 121, 215);
        case Color::SyntaxFormat:
            return sRGB(178, 52, 197);

        // Attention bar:

#ifdef __WXGTK__
        case Color::AttentionWarningBackground:
            return sRGB(250, 173, 61);
        case Color::AttentionQuestionBackground:
            return sRGB(138, 173, 212);
        case Color::AttentionErrorBackground:
            return sRGB(237, 54, 54);
#else
        case Color::AttentionWarningBackground:
            return sRGB(255, 222, 91);
        case Color::AttentionQuestionBackground:
            return sRGB(150, 233, 109);
        case Color::AttentionErrorBackground:
            return sRGB(255, 125, 125);
#endif

        case Color::Max:
            return wxColour();
    }

    return wxColour(); // Visual C++ being silly
}

ColorScheme::Type ColorScheme::GetSchemeTypeFromWindow(const wxVisualAttributes& win)
{
    // Use dark scheme for very dark backgrounds:
    if (win.colBg.Red() < 0x60 &&
        win.colBg.Green() < 0x60 &&
        win.colBg.Blue() < 0x60)
    {
        return Dark;
    }
    else
    {
        return Light;
    }
}

void ColorScheme::CleanUp()
{
    s_data.reset();
}
<commit_msg>Tweak context string foreground color a bit<commit_after>/*
 *  This file is part of Poedit (https://poedit.net)
 *
 *  Copyright (C) 2016 Vaclav Slavik
 *
 *  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 "colorscheme.h"

#include <wx/settings.h>

#ifdef __WXGTK__
    #include <pango/pango-utils.h>
    #if PANGO_VERSION_CHECK(1,38,0)
        #define SUPPORTS_BGALPHA
    #endif
#else
    #define SUPPORTS_BGALPHA
#endif

namespace
{

#ifdef __WXOSX__

inline wxColour sRGB(int r, int g, int b, double a = 1.0)
{
    return wxColour([NSColor colorWithSRGBRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]);
}

#else

inline wxColour sRGB(int r, int g, int b, double a = 1.0)
{
    return wxColour(r, g, b, int(a * wxALPHA_OPAQUE));
}

#endif

} // anonymous namespace

std::unique_ptr<ColorScheme::Data> ColorScheme::s_data;

wxColour ColorScheme::DoGet(Color color, Type type)
{
    switch (color)
    {
        // Labels:

        case Color::SecondaryLabel:
            #ifdef __WXOSX__
            return wxColour([NSColor secondaryLabelColor]);
            #elif defined(__WXGTK__)
            return wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT);
            #else
            return wxSystemSettings::GetColour(wxSYS_COLOUR_GRAYTEXT);
            #endif

        // List items:

        case Color::ItemID:
            return type == Light ? "#a1a1a1" : wxNullColour;
        case Color::ItemFuzzy:
            return type == Light ? sRGB(218, 123, 0) : "#a9861b";
        case Color::ItemError:
            return sRGB(242, 84, 77);
        case Color::ItemContextFg:
            return sRGB(22, 150, 67);
        case Color::ItemContextBg:
            #ifdef SUPPORTS_BGALPHA
            return sRGB(207, 243, 220, 0.75);
            #else
            return sRGB(219, 246, 229);
            #endif

        // Separators:

        case Color::ToolbarSeparator:
            return "#cdcdcd";
        case Color::SidebarSeparator:
            return "#cbcbcb";
        case Color::EditingSeparator:
            return "#c1c1c1";

        // Backgrounds:

        case Color::SidebarBackground:
            return "#edf0f4";
        case Color::EditingBackground:
            return *wxWHITE;

        // Syntax highlighting:

        case Color::SyntaxLeadingWhitespaceBg:
            return sRGB(255, 233, 204);
        case Color::SyntaxEscapeFg:
            return sRGB(162, 0, 20);
        case Color::SyntaxEscapeBg:
            return sRGB(254, 234, 236);
        case Color::SyntaxMarkup:
            return sRGB(0, 121, 215);
        case Color::SyntaxFormat:
            return sRGB(178, 52, 197);

        // Attention bar:

#ifdef __WXGTK__
        case Color::AttentionWarningBackground:
            return sRGB(250, 173, 61);
        case Color::AttentionQuestionBackground:
            return sRGB(138, 173, 212);
        case Color::AttentionErrorBackground:
            return sRGB(237, 54, 54);
#else
        case Color::AttentionWarningBackground:
            return sRGB(255, 222, 91);
        case Color::AttentionQuestionBackground:
            return sRGB(150, 233, 109);
        case Color::AttentionErrorBackground:
            return sRGB(255, 125, 125);
#endif

        case Color::Max:
            return wxColour();
    }

    return wxColour(); // Visual C++ being silly
}

ColorScheme::Type ColorScheme::GetSchemeTypeFromWindow(const wxVisualAttributes& win)
{
    // Use dark scheme for very dark backgrounds:
    if (win.colBg.Red() < 0x60 &&
        win.colBg.Green() < 0x60 &&
        win.colBg.Blue() < 0x60)
    {
        return Dark;
    }
    else
    {
        return Light;
    }
}

void ColorScheme::CleanUp()
{
    s_data.reset();
}
<|endoftext|>


<commit_before>#include "Args.hpp"

#include <QApplication>
#include <QCommandLineParser>
#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QStringList>

namespace chatterino {

Args::Args(const QApplication &app)
{
    QCommandLineParser parser;
    parser.setApplicationDescription("Chatterino 2 Client for Twitch Chat");
    parser.addHelpOption();

    // Used internally by app to restart after unexpected crashes
    QCommandLineOption crashRecoveryOption("crash-recovery");
    crashRecoveryOption.setHidden(true);

    parser.addOptions({
        {{"v", "version"}, "Displays version information."},
        crashRecoveryOption,
    });
    parser.addOption(QCommandLineOption(
        {"c", "channels"},
        "Joins only supplied channels on startup. Use letters with colons to "
        "specify platform. Only twitch channels are supported at the moment.\n"
        "If platform isn't specified, default is Twitch.",
        "t:channel1;t:channel2;..."));

    if (!parser.parse(app.arguments()))
    {
        qDebug() << "Warning: Unhandled options:"
                 << parser.unknownOptionNames();
    }

    if (parser.isSet("help"))
    {
        qDebug().noquote() << parser.helpText();
        ::exit(EXIT_SUCCESS);
    }

    const QStringList args = parser.positionalArguments();
    this->shouldRunBrowserExtensionHost =
        (args.size() > 0 && (args[0].startsWith("chrome-extension://") ||
                             args[0].endsWith(".json")));

    if (parser.isSet("c"))
    {
        QJsonArray channelArray;
        QStringList channelArgList = parser.value("c").split(";");
        for (QString channelArg : channelArgList)
        {
            // Twitch is default platform
            QString platform = "t";
            QString channelName = channelArg;

            const QRegExp regExp("(.):(.*)");
            if (regExp.indexIn(channelArg) != -1)
            {
                platform = regExp.cap(1);
                channelName = regExp.cap(2);
            }

            // Twitch (default)
            if (platform == "t")
            {
                // TODO: try not to parse JSON
                QString channelObjectString =
                    "{\"splits2\": { \"data\": { \"name\": \"" + channelName +
                    "\", \"type\": \"twitch\" }, \"type\": \"split\" }}";
                channelArray.push_back(
                    QJsonDocument::fromJson(channelObjectString.toUtf8())
                        .object());
            }
        }
        if (channelArray.size() > 0)
        {
            this->dontSaveSettings = true;
            this->channelsToJoin = channelArray;
        }
    }

    this->printVersion = parser.isSet("v");
    this->crashRecovery = parser.isSet("crash-recovery");
}

static Args *instance = nullptr;

void initArgs(const QApplication &app)
{
    instance = new Args(app);
}

const Args &getArgs()
{
    assert(instance);

    return *instance;
}

}  // namespace chatterino
<commit_msg>Add parent-window option (#2089)<commit_after>#include "Args.hpp"

#include <QApplication>
#include <QCommandLineParser>
#include <QDebug>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QStringList>

namespace chatterino {

Args::Args(const QApplication &app)
{
    QCommandLineParser parser;
    parser.setApplicationDescription("Chatterino 2 Client for Twitch Chat");
    parser.addHelpOption();

    // Used internally by app to restart after unexpected crashes
    QCommandLineOption crashRecoveryOption("crash-recovery");
    crashRecoveryOption.setFlags(QCommandLineOption::HiddenFromHelp);

    // Added to ignore the parent-window option passed during native messaging
    QCommandLineOption parentWindowOption("parent-window");
    parentWindowOption.setFlags(QCommandLineOption::HiddenFromHelp);

    parser.addOptions({
        {{"v", "version"}, "Displays version information."},
        crashRecoveryOption,
        parentWindowOption,
    });
    parser.addOption(QCommandLineOption(
        {"c", "channels"},
        "Joins only supplied channels on startup. Use letters with colons to "
        "specify platform. Only twitch channels are supported at the moment.\n"
        "If platform isn't specified, default is Twitch.",
        "t:channel1;t:channel2;..."));

    if (!parser.parse(app.arguments()))
    {
        qDebug() << "Warning: Unhandled options:"
                 << parser.unknownOptionNames();
    }

    if (parser.isSet("help"))
    {
        qDebug().noquote() << parser.helpText();
        ::exit(EXIT_SUCCESS);
    }

    const QStringList args = parser.positionalArguments();
    this->shouldRunBrowserExtensionHost =
        (args.size() > 0 && (args[0].startsWith("chrome-extension://") ||
                             args[0].endsWith(".json")));

    if (parser.isSet("c"))
    {
        QJsonArray channelArray;
        QStringList channelArgList = parser.value("c").split(";");
        for (QString channelArg : channelArgList)
        {
            // Twitch is default platform
            QString platform = "t";
            QString channelName = channelArg;

            const QRegExp regExp("(.):(.*)");
            if (regExp.indexIn(channelArg) != -1)
            {
                platform = regExp.cap(1);
                channelName = regExp.cap(2);
            }

            // Twitch (default)
            if (platform == "t")
            {
                // TODO: try not to parse JSON
                QString channelObjectString =
                    "{\"splits2\": { \"data\": { \"name\": \"" + channelName +
                    "\", \"type\": \"twitch\" }, \"type\": \"split\" }}";
                channelArray.push_back(
                    QJsonDocument::fromJson(channelObjectString.toUtf8())
                        .object());
            }
        }
        if (channelArray.size() > 0)
        {
            this->dontSaveSettings = true;
            this->channelsToJoin = channelArray;
        }
    }

    this->printVersion = parser.isSet("v");
    this->crashRecovery = parser.isSet("crash-recovery");
}

static Args *instance = nullptr;

void initArgs(const QApplication &app)
{
    instance = new Args(app);
}

const Args &getArgs()
{
    assert(instance);

    return *instance;
}

}  // namespace chatterino
<|endoftext|>


<commit_before>/** \file    Elasticsearch.cc
 *  \brief   Implementation of the Elasticsearch class.
 *  \author  Dr. Johannes Ruscheinski
 *  \author  Mario Trojan
 *
 *  \copyright 2018 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program 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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "Elasticsearch.h"
#include "FileUtil.h"
#include "IniFile.h"
#include "REST.h"
#include "UBTools.h"
#include "UrlUtil.h"

const std::string DEFAULT_CONFIG_FILE_PATH(UBTools::GetTuelibPath() + "Elasticsearch.conf");

static void LoadIniParameters(const std::string &config_file_path, std::string * const host, std::string * const index,
                              std::string * const type, std::string * const username, std::string * const password,
                              bool * const ignore_ssl_certificates)
{
    if (not FileUtil::Exists(config_file_path))
        LOG_ERROR("Elasticsearch config file missing: " + config_file_path);

    const IniFile ini_file(config_file_path);

    *host                    = ini_file.getString("Elasticsearch", "host");
    *index                   = ini_file.getString("Elasticsearch", "index");
    *type                    = ini_file.getString("Elasticsearch", "type");
    *username                = ini_file.getString("Elasticsearch", "username", "");
    *password                = ini_file.getString("Elasticsearch", "password", "");
    *ignore_ssl_certificates = ini_file.getBool("Elasticsearch", "ignore_ssl_certificates", false);
}

Elasticsearch::Elasticsearch(const std::string &ini_file_path) {
    LoadIniParameters(ini_file_path.empty() ? DEFAULT_CONFIG_FILE_PATH : ini_file_path, &host_, &index_, &type_, &username_,
                      &password_, &ignore_ssl_certificates_);
}

// A general comment as to the strategy we use in this function:
//
//    We know that there is an _update API endpoint, but as we insert a bunch of chunks, the number of which can change,
//    we have to use a "wildcard" strategy to first delete possibly existing chunks as the number of new chunks may be greater or
//    fewer than what may already be stored.
void Elasticsearch::insertDocument(const std::string &document_id, const std::vector<std::string> &document_chunks) {
    Downloader::Params downloader_params;
    downloader_params.authentication_username_ = username_;
    downloader_params.authentication_password_ = password_;
    downloader_params.ignore_ssl_certificates_ = ignore_ssl_certificates_;
    downloader_params.additional_headers_.push_back("Content-Type: application/json");

    const Url delete_url(host_ + "/" + index_ + "/" + type_ + "/_delete_by_query");
    const JSON::ObjectNode match_node("{ \"query\": { \"match\": { \"document_id\": \"" + JSON::EscapeString(document_id) + "\" } } }");

    std::shared_ptr<JSON::JSONNode> result(REST::QueryJSON(delete_url, REST::POST, &match_node, downloader_params));
    std::shared_ptr<JSON::ObjectNode> result_object(JSON::JSONNode::CastToObjectNodeOrDie("Elasticsearch result", result));
    if (result_object->hasNode("error"))
        LOG_ERROR("Elasticsearch delete_by_query failed: " + result_object->getNode("error")->toString());

    const Url insert_url(host_ + "/" + index_ + "/" + type_ + "/_insert");
    for (const auto &document_chunk : document_chunks) {
        const JSON::ObjectNode payload(
            JSON::ObjectNode(std::unordered_map<std::string, std::string>{
                    { "document_id",    document_id    },
                    { "document_chunk", document_chunk }
                }));
        result = REST::QueryJSON(insert_url, REST::PUT, &payload, downloader_params);
    }
}
<commit_msg>Fix for _id always being "_insert"<commit_after>/** \file    Elasticsearch.cc
 *  \brief   Implementation of the Elasticsearch class.
 *  \author  Dr. Johannes Ruscheinski
 *  \author  Mario Trojan
 *
 *  \copyright 2018 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program 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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "Elasticsearch.h"
#include "FileUtil.h"
#include "IniFile.h"
#include "REST.h"
#include "UBTools.h"
#include "UrlUtil.h"

const std::string DEFAULT_CONFIG_FILE_PATH(UBTools::GetTuelibPath() + "Elasticsearch.conf");

static void LoadIniParameters(const std::string &config_file_path, std::string * const host, std::string * const index,
                              std::string * const type, std::string * const username, std::string * const password,
                              bool * const ignore_ssl_certificates)
{
    if (not FileUtil::Exists(config_file_path))
        LOG_ERROR("Elasticsearch config file missing: " + config_file_path);

    const IniFile ini_file(config_file_path);

    *host                    = ini_file.getString("Elasticsearch", "host");
    *index                   = ini_file.getString("Elasticsearch", "index");
    *type                    = ini_file.getString("Elasticsearch", "type");
    *username                = ini_file.getString("Elasticsearch", "username", "");
    *password                = ini_file.getString("Elasticsearch", "password", "");
    *ignore_ssl_certificates = ini_file.getBool("Elasticsearch", "ignore_ssl_certificates", false);
}

Elasticsearch::Elasticsearch(const std::string &ini_file_path) {
    LoadIniParameters(ini_file_path.empty() ? DEFAULT_CONFIG_FILE_PATH : ini_file_path, &host_, &index_, &type_, &username_,
                      &password_, &ignore_ssl_certificates_);
}

// A general comment as to the strategy we use in this function:
//
//    We know that there is an _update API endpoint, but as we insert a bunch of chunks, the number of which can change,
//    we have to use a "wildcard" strategy to first delete possibly existing chunks as the number of new chunks may be greater or
//    fewer than what may already be stored.
void Elasticsearch::insertDocument(const std::string &document_id, const std::vector<std::string> &document_chunks) {
    Downloader::Params downloader_params;
    downloader_params.authentication_username_ = username_;
    downloader_params.authentication_password_ = password_;
    downloader_params.ignore_ssl_certificates_ = ignore_ssl_certificates_;
    downloader_params.additional_headers_.push_back("Content-Type: application/json");

    const Url delete_url(host_ + "/" + index_ + "/" + type_ + "/_delete_by_query");
    const JSON::ObjectNode match_node("{ \"query\": { \"match\": { \"document_id\": \"" + JSON::EscapeString(document_id) + "\" } } }");

    std::shared_ptr<JSON::JSONNode> result(REST::QueryJSON(delete_url, REST::POST, &match_node, downloader_params));
    std::shared_ptr<JSON::ObjectNode> result_object(JSON::JSONNode::CastToObjectNodeOrDie("Elasticsearch result", result));
    if (result_object->hasNode("error"))
        LOG_ERROR("Elasticsearch delete_by_query failed: " + result_object->getNode("error")->toString());

    const Url insert_url(host_ + "/" + index_ + "/" + type_);
    for (const auto &document_chunk : document_chunks) {
        const JSON::ObjectNode payload(
            JSON::ObjectNode(std::unordered_map<std::string, std::string>{
                    { "document_id",    document_id    },
                    { "document_chunk", document_chunk }
                }));
        result = REST::QueryJSON(insert_url, REST::POST, &payload, downloader_params);
    }
}
<|endoftext|>