<commit_before>/*
 * GaborConn.cpp
 *
 *  Created on: Jan 12, 2009
 *      Author: rasmussn
 */

#include "GaborConn.hpp"
#include "../io/io.h"
#include <assert.h>
#include <string.h>

namespace PV {

GaborConn::GaborConn(const char * name,
                     HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, int channel)
{
   initialize_base();
   initialize(name, hc, pre, post, channel, NULL);
}

int GaborConn::initializeWeights(const char * filename)
{
   float aspect = 4.0;
   float sigma  = 2.0;
   float rMax   = 8.0;
   float lambda = sigma/0.8;    // gabor wavelength
   float strength = 1.0;

   PVParams * params = parent->parameters();

   aspect = params->value(name, "aspect");
   sigma  = params->value(name, "sigma");
   rMax   = params->value(name, "rMax");
   lambda = params->value(name, "lambda");

   if (params->present(name, "strength")) {
      strength = params->value(name, "strength");
   }

   float r2Max = rMax * rMax;

   const int arbor = 0;
   const int numPatches = numWeightPatches(arbor);
   for (int i = 0; i < numPatches; i++) {
      int xScale = post->clayer->xScale - pre->clayer->xScale;
      int yScale = post->clayer->xScale - pre->clayer->yScale;
      gaborWeights(wPatches[arbor][i], xScale, yScale, aspect, sigma, r2Max, lambda, strength);
   }

   return 0;
}

int GaborConn::gaborWeights(PVPatch * wp, int xScale, int yScale,
                            float aspect, float sigma, float r2Max, float lambda, float strength)
{
   PVParams * params = parent->parameters();

   float rotate = 1.0;
   float invert = 0.0;
   if (params->present(name, "rotate")) rotate = params->value(name, "rotate");
   if (params->present(name, "invert")) invert = params->value(name, "invert");

   pvdata_t * w = wp->data;

   const float phi = 0.0;  // phase

   const int nx = wp->nx;
   const int ny = wp->ny;
   const int nf = wp->nf;

   const int sx = wp->sx;  assert(sx == nf);
   const int sy = wp->sy;  assert(sy == nf*nx);
   const int sf = wp->sf;  assert(sf == 1);

   const float dx = powf(2, xScale);
   const float dy = powf(2, yScale);

   // pre-synaptic neuron is at the center of the patch (0,0)
   // (x0,y0) is at upper left corner of patch (i=0,j=0)
   const float x0 = -(nx/2.0 - 0.5) * dx;
   const float y0 = +(ny/2.0 - 0.5) * dy;

   const float dth = PI/nf;
   const float th0 = rotate*dth/2.0;

   for (int f = 0; f < nf; f++) {
      float th = th0 + f * dth;
      for (int j = 0; j < ny; j++) {
         float yp = y0 - j * dy;    // pixel coordinate
         for (int i = 0; i < nx; i++) {
            float xp  = x0 + i*dx;  // pixel coordinate

            // rotate the reference frame by th ((x,y) is center of patch (0,0))
            float u1 = + (0.0 - xp) * cos(th) + (0.0 - yp) * sin(th);
            float u2 = - (0.0 - xp) * sin(th) + (0.0 - yp) * cos(th);

            float factor = cos(2.0*PI*u2/lambda + phi);
            if (fabs(u2/lambda) > 3.0/4.0) factor = 0.0;  // phase < 3*PI/2 (no second positive band)
            float d2 = u1 * u1 + (aspect*u2 * aspect*u2);
            float wt = factor * expf(-d2 / (2.0*sigma*sigma));

#ifdef DEBUG_OUTPUT
            if (j == 0) printf("x=%f fac=%f w=%f\n", xp, factor, wt);
#endif
            if (xp*xp + yp*yp > r2Max) {
               w[i*sx + j*sy + f*sf] = 0.0;
            }
            else {
               if (invert) wt *= -1.0;
               if (wt < 0.0) wt = 0.0;       // clip negative values
               w[i*sx + j*sy + f*sf] = wt;
            }
         }
      }
   }

   // normalize
   for (int f = 0; f < nf; f++) {
      float sum = 0;
      for (int i = 0; i < nx*ny; i++) {
         if (w[f + i*nf] > 0.0) sum += w[f + i*nf];
      }

      if (sum == 0.0) continue;  // all weights == zero is ok

      float factor = strength/sum;
      for (int i = 0; i < nx*ny; i++) w[f + i*nf] *= factor;
   }

   return 0;
}

} // Namespace PV
<commit_msg>Changed inheritance to KernelConn and modernized initialization.<commit_after>/*
 * GaborConn.cpp
 *
 *  Created on: Jan 12, 2009
 *      Author: rasmussn
 */

#include "GaborConn.hpp"
#include "../io/io.h"
#include <assert.h>
#include <string.h>

namespace PV {

GaborConn::GaborConn(const char * name,
                     HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, int channel)
{
   initialize_base();
   initialize(name, hc, pre, post, channel, NULL);
}

PVPatch ** GaborConn::initializeDefaultWeights(PVPatch ** patches, int numPatches)
{
   return initializeGaborWeights(patches, numPatches);
}

PVPatch ** GaborConn::initializeGaborWeights(PVPatch ** patches, int numPatches)
{
#ifdef TESTING
	   PVPatch * wp = kernelPatches[0];
	   pvdata_t * w = wp->data;

	   const int nxp = wp->nx;
	   const int nyp = wp->ny;
	   const int nfp = wp->nf;
	   if (nxp * nyp * nfp == 0) {
	      return 0; // reduced patch size is zero
	   }

	   for (int k = 0; k < nxp*nyp*nfp; k++) {
		   w[k] = 1.0f;
	   }
#else

   const int xScale = post->clayer->xScale - pre->clayer->xScale;
   const int yScale = post->clayer->xScale - pre->clayer->yScale;

   PVParams * params = parent->parameters();

   float aspect = 4.0;
   float sigma  = 2.0;
   float rMax   = 8.0;
   float lambda = sigma/0.8;    // gabor wavelength
   float strength = 1.0;

   aspect   = params->value(name, "aspect", aspect);
   sigma    = params->value(name, "sigma", sigma);
   rMax     = params->value(name, "rMax", rMax);
   lambda   = params->value(name, "lambda", lambda);
   strength = params->value(name, "strength", strength);

   float r2Max = rMax * rMax;

   for (int kernelIndex = 0; kernelIndex < numPatches; kernelIndex++) {
      // TODO - change parameters based on kernelIndex (i.e., change orientation)
      gaborWeights(patches[kernelIndex], xScale, yScale, aspect, sigma, r2Max, lambda, strength);
   }
#endif
   return patches;
}

int GaborConn::gaborWeights(PVPatch * wp, int xScale, int yScale,
                            float aspect, float sigma, float r2Max, float lambda, float strength)
{
   PVParams * params = parent->parameters();

   float rotate = 1.0;
   float invert = 0.0;
   if (params->present(name, "rotate")) rotate = params->value(name, "rotate");
   if (params->present(name, "invert")) invert = params->value(name, "invert");

   pvdata_t * w = wp->data;

   const float phi = 0.0;  // phase

   const int nx = wp->nx;
   const int ny = wp->ny;
   const int nf = wp->nf;

   const int sx = wp->sx;  assert(sx == nf);
   const int sy = wp->sy;  assert(sy == nf*nx);
   const int sf = wp->sf;  assert(sf == 1);

   const float dx = powf(2, xScale);
   const float dy = powf(2, yScale);

   // pre-synaptic neuron is at the center of the patch (0,0)
   // (x0,y0) is at upper left corner of patch (i=0,j=0)
   const float x0 = -(nx/2.0 - 0.5) * dx;
   const float y0 = +(ny/2.0 - 0.5) * dy;

   const float dth = PI/nf;
   const float th0 = rotate*dth/2.0;

   for (int f = 0; f < nf; f++) {
      float th = th0 + f * dth;
      for (int j = 0; j < ny; j++) {
         float yp = y0 - j * dy;    // pixel coordinate
         for (int i = 0; i < nx; i++) {
            float xp  = x0 + i*dx;  // pixel coordinate

            // rotate the reference frame by th ((x,y) is center of patch (0,0))
            float u1 = + (0.0 - xp) * cos(th) + (0.0 - yp) * sin(th);
            float u2 = - (0.0 - xp) * sin(th) + (0.0 - yp) * cos(th);

            float factor = cos(2.0*PI*u2/lambda + phi);
            if (fabs(u2/lambda) > 3.0/4.0) factor = 0.0;  // phase < 3*PI/2 (no second positive band)
            float d2 = u1 * u1 + (aspect*u2 * aspect*u2);
            float wt = factor * expf(-d2 / (2.0*sigma*sigma));

#ifdef DEBUG_OUTPUT
            if (j == 0) printf("x=%f fac=%f w=%f\n", xp, factor, wt);
#endif
            if (xp*xp + yp*yp > r2Max) {
               w[i*sx + j*sy + f*sf] = 0.0;
            }
            else {
               if (invert) wt *= -1.0;
               if (wt < 0.0) wt = 0.0;       // clip negative values
               w[i*sx + j*sy + f*sf] = wt;
            }
         }
      }
   }

   // normalize
   for (int f = 0; f < nf; f++) {
      float sum = 0;
      for (int i = 0; i < nx*ny; i++) {
         if (w[f + i*nf] > 0.0) sum += w[f + i*nf];
      }

      if (sum == 0.0) continue;  // all weights == zero is ok

      float factor = strength/sum;
      for (int i = 0; i < nx*ny; i++) w[f + i*nf] *= factor;
   }

   return 0;
}

} // Namespace PV
<|endoftext|>


<commit_before><commit_msg>Disable coalescing call stmts<commit_after><|endoftext|>


<commit_before>#include "gridmap.hpp"
#include "../utils/utils.hpp"
#include <cstdio>
#include <cstddef>
#include <cerrno>
#include <cstring>
#include <string>

GridMap::GridMap(std::string &fname) : map(NULL), flags(NULL), file(fname) {
	FILE *f = fopen(file.c_str(), "r");
	if (!f)
		fatalx(errno, "Unable to open %s for reading\n", file.c_str());
	load(f);
	fclose(f);
}

GridMap::~GridMap(void) {
	if (map)
		delete[] map;
	if (flags)
		delete[] flags;
}

void GridMap::output(FILE *out) const {
	fprintf(out, "type %s\n", typ);
	fprintf(out, "height %u\n", h);
	fprintf(out, "width %u\n", w);
	fprintf(out, "map\n");
	for (unsigned int y = 0; y < h; y++) {
		for (unsigned int x = 0; x < w; x++)
			fputc(map[loc(x, y)], out);
		fputc('\n', out);
	}
}

void GridMap::load(FILE *in) {
	if (fscanf(in, "type ") != 0)
		fatal("%s: Failed to read the map type", file.c_str());

	if (!fgets(typ, Bufsz, in))
		fatal("%s: Failed to read the map type", file.c_str());
	if (typ[strlen(typ)-1] == '\n')
		typ[strlen(typ)-1] = '\0';
	if (strcmp(typ, "octile") != 0)
		fatal("%s: Unsupported map type [%s]", file.c_str(), typ);

	if (fscanf(in, "height %u\nwidth %u\nmap\n", &h, &w) != 2)
		fatal("%s: Failed to read the map header [%s]", file.c_str(), file.c_str());

	map = new unsigned char[w * h];
	for (unsigned int y = 0; y < h; y++) {
		if (fread((void*) (map + y * w), sizeof(*map), w, in) != w)
			fatal("%s: Failed to read map line %u", y, file.c_str());
		int c = fgetc(in);
		if (c != '\n' && y < h - 1)
			fatal("%s:%d Expected newline, got [%c]", file.c_str(), y+5, c);
	}

	flags = new unsigned char[w * h];
	for (unsigned int i = 0; i < w * h; i++)
		flags[i] = terrain.flags[(int) map[i]];
}<commit_msg>Don't print line number on map errors.  This was a bit of a hack.<commit_after>#include "gridmap.hpp"
#include "../utils/utils.hpp"
#include <cstdio>
#include <cstddef>
#include <cerrno>
#include <cstring>
#include <string>

GridMap::GridMap(std::string &fname) : map(NULL), flags(NULL), file(fname) {
	FILE *f = fopen(file.c_str(), "r");
	if (!f)
		fatalx(errno, "Unable to open %s for reading\n", file.c_str());
	load(f);
	fclose(f);
}

GridMap::~GridMap(void) {
	if (map)
		delete[] map;
	if (flags)
		delete[] flags;
}

void GridMap::output(FILE *out) const {
	fprintf(out, "type %s\n", typ);
	fprintf(out, "height %u\n", h);
	fprintf(out, "width %u\n", w);
	fprintf(out, "map\n");
	for (unsigned int y = 0; y < h; y++) {
		for (unsigned int x = 0; x < w; x++)
			fputc(map[loc(x, y)], out);
		fputc('\n', out);
	}
}

void GridMap::load(FILE *in) {
	if (fscanf(in, "type ") != 0)
		fatal("%s: Failed to read the map type", file.c_str());

	if (!fgets(typ, Bufsz, in))
		fatal("%s: Failed to read the map type", file.c_str());
	if (typ[strlen(typ)-1] == '\n')
		typ[strlen(typ)-1] = '\0';
	if (strcmp(typ, "octile") != 0)
		fatal("%s: Unsupported map type [%s]", file.c_str(), typ);

	if (fscanf(in, "height %u\nwidth %u\nmap\n", &h, &w) != 2)
		fatal("%s: Failed to read the map header [%s]", file.c_str(), file.c_str());

	map = new unsigned char[w * h];
	for (unsigned int y = 0; y < h; y++) {
		if (fread((void*) (map + y * w), sizeof(*map), w, in) != w)
			fatal("%s: Failed to read map line %u", y, file.c_str());
		int c = fgetc(in);
		if (c != '\n' && y < h - 1)
			fatal("%s: Expected newline, got [%c]", file.c_str(), c);
	}

	flags = new unsigned char[w * h];
	for (unsigned int i = 0; i < w * h; i++)
		flags[i] = terrain.flags[(int) map[i]];
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dlgattr.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 07:09:05 $
 *
 *  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_dbaccess.hxx"

#ifdef MAC
#ifdef ITEMID_NUMBERINFO
#undef ITEMID_NUMBERINFO
#endif
#endif

#define ITEMID_NUMBERINFO 0

#ifndef DBAUI_SBATTRDLG_HXX
#include "dlgattr.hxx"
#endif

#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif

#ifndef _SVX_NUMINF_HXX //autogen
#include <svx/numinf.hxx>
#endif

//CHINA001 #ifndef _SVX_CHARDLG_HXX //autogen
//CHINA001 #include <svx/chardlg.hxx>
//CHINA001 #endif

//CHINA001 #ifndef _SVX_NUMFMT_HXX //autogen
//CHINA001 #include <svx/numfmt.hxx>
//CHINA001 #endif
#ifndef _SVX_NUMINF_HXX
#include <svx/numinf.hxx>
#endif

//CHINA001 #ifndef _SVX_ALIGN_HXX //autogen
//CHINA001 #include <svx/align.hxx>
//CHINA001 #endif

#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif

#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
#define _ZFORLIST_DECLARE_TABLE
#ifndef _ZFORLIST_HXX
#include <svtools/zforlist.hxx>
#endif
#include <svx/svxids.hrc> //CHINA001
#include <svx/flagsdef.hxx> //CHINA001
#ifndef _SFXINTITEM_HXX //CHINA001
#include <svtools/intitem.hxx> //CHINA001
#endif //CHINA001

using namespace dbaui;

DBG_NAME(SbaSbAttrDlg)
//==================================================================
SbaSbAttrDlg::SbaSbAttrDlg(Window* pParent, const SfxItemSet* pCellAttrs, SvNumberFormatter* pFormatter, USHORT nFlags, BOOL bRow)
             : SfxTabDialog(pParent, ModuleRes( DLG_ATTR ), pCellAttrs )
             ,aTitle(ResId(ST_ROW))
{
    DBG_CTOR(SbaSbAttrDlg,NULL);

    pNumberInfoItem = new SvxNumberInfoItem( pFormatter );

    if (bRow)
        SetText(aTitle);
    if( nFlags & TP_ATTR_CHAR )
//        AddTabPage( RID_SVXPAGE_CHAR_STD,String(ResId(TP_ATTR_CHAR)),SvxCharStdPage::Create,            0 );
        DBG_ERROR( "found flag TP_ATTR_CHAR" );
    if( nFlags & TP_ATTR_NUMBER )
        AddTabPage( RID_SVXPAGE_NUMBERFORMAT,String(ResId(TP_ATTR_NUMBER)) ); //CHINA001 AddTabPage( RID_SVXPAGE_NUMBERFORMAT,String(ResId(TP_ATTR_NUMBER)),SvxNumberFormatTabPage::Create, 0 );
    if( nFlags & TP_ATTR_ALIGN )
        AddTabPage( RID_SVXPAGE_ALIGNMENT,String(ResId(TP_ATTR_ALIGN)) );//CHINA001 AddTabPage( RID_SVXPAGE_ALIGNMENT,String(ResId(TP_ATTR_ALIGN)),SvxAlignmentTabPage::Create, 0 );
    FreeResource();
}

// -----------------------------------------------------------------------
SbaSbAttrDlg::~SbaSbAttrDlg()
{
    delete pNumberInfoItem;

    DBG_DTOR(SbaSbAttrDlg,NULL);
}

// -----------------------------------------------------------------------
void SbaSbAttrDlg::PageCreated( sal_uInt16 nPageId, SfxTabPage& rTabPage )
{
    SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));
    switch ( nPageId )
    {
        case RID_SVXPAGE_NUMBERFORMAT:
        {
            //CHINA001 ((SvxNumberFormatTabPage&)rTabPage).
                //CHINA001 SetNumberFormatList( *pNumberInfoItem );
            aSet.Put (SvxNumberInfoItem( pNumberInfoItem->GetNumberFormatter(), (const USHORT)SID_ATTR_NUMBERFORMAT_INFO));
            rTabPage.PageCreated(aSet);
        }
        break;

        case RID_SVXPAGE_CHAR_STD:
        {
            //  ((SvxCharStdPage&)rTabPage).SetFontList(SBA_MOD_EXT()->FontListItem());
        }
        break;

        case RID_SVXPAGE_ALIGNMENT:
        {
            //CHINA001 ((SvxAlignmentTabPage&)rTabPage).SetFlags(WBA_NO_ORIENTATION|WBA_NO_LINEBREAK|WBA_NO_GRIDLINES|WBA_NO_VERTICAL|WBA_NO_LEFTINDENT);
//           aSet.Put (SfxUInt32Item(SID_FLAG_TYPE, WBA_NO_ORIENTATION|WBA_NO_LINEBREAK|WBA_NO_GRIDLINES|WBA_NO_VERTICAL|WBA_NO_LEFTINDENT));
//           rTabPage.PageCreated(aSet);
        }
        break;

        default:
        break;
    }
}

<commit_msg>INTEGRATION: CWS sb59 (1.7.156); FILE MERGED 2006/08/29 11:44:28 sb 1.7.156.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dlgattr.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 13:37:28 $
 *
 *  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_dbaccess.hxx"

#ifdef MAC
#ifdef ITEMID_NUMBERINFO
#undef ITEMID_NUMBERINFO
#endif
#endif

#define ITEMID_NUMBERINFO 0

#ifndef DBAUI_SBATTRDLG_HXX
#include "dlgattr.hxx"
#endif

#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif

#ifndef _SVX_NUMINF_HXX //autogen
#include <svx/numinf.hxx>
#endif

//CHINA001 #ifndef _SVX_CHARDLG_HXX //autogen
//CHINA001 #include <svx/chardlg.hxx>
//CHINA001 #endif

//CHINA001 #ifndef _SVX_NUMFMT_HXX //autogen
//CHINA001 #include <svx/numfmt.hxx>
//CHINA001 #endif
#ifndef _SVX_NUMINF_HXX
#include <svx/numinf.hxx>
#endif

//CHINA001 #ifndef _SVX_ALIGN_HXX //autogen
//CHINA001 #include <svx/align.hxx>
//CHINA001 #endif

#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif

#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
#define _ZFORLIST_DECLARE_TABLE
#ifndef _ZFORLIST_HXX
#include <svtools/zforlist.hxx>
#endif
#include <svx/svxids.hrc> //CHINA001
#include <svx/flagsdef.hxx> //CHINA001
#ifndef _SFXINTITEM_HXX //CHINA001
#include <svtools/intitem.hxx> //CHINA001
#endif //CHINA001

using namespace dbaui;

DBG_NAME(SbaSbAttrDlg)
//==================================================================
SbaSbAttrDlg::SbaSbAttrDlg(Window* pParent, const SfxItemSet* pCellAttrs, SvNumberFormatter* pFormatter, USHORT nFlags, BOOL bRow)
             : SfxTabDialog(pParent, ModuleRes( DLG_ATTR ), pCellAttrs )
             ,aTitle(ResId(ST_ROW))
{
    DBG_CTOR(SbaSbAttrDlg,NULL);

    pNumberInfoItem = new SvxNumberInfoItem( pFormatter );

    if (bRow)
        SetText(aTitle);
    if( nFlags & TP_ATTR_CHAR )
    {
//        AddTabPage( RID_SVXPAGE_CHAR_STD,String(ResId(TP_ATTR_CHAR)),SvxCharStdPage::Create,            0 );
        DBG_ERROR( "found flag TP_ATTR_CHAR" );
    }
    if( nFlags & TP_ATTR_NUMBER )
        AddTabPage( RID_SVXPAGE_NUMBERFORMAT,String(ResId(TP_ATTR_NUMBER)) ); //CHINA001 AddTabPage( RID_SVXPAGE_NUMBERFORMAT,String(ResId(TP_ATTR_NUMBER)),SvxNumberFormatTabPage::Create, 0 );
    if( nFlags & TP_ATTR_ALIGN )
        AddTabPage( RID_SVXPAGE_ALIGNMENT,String(ResId(TP_ATTR_ALIGN)) );//CHINA001 AddTabPage( RID_SVXPAGE_ALIGNMENT,String(ResId(TP_ATTR_ALIGN)),SvxAlignmentTabPage::Create, 0 );
    FreeResource();
}

// -----------------------------------------------------------------------
SbaSbAttrDlg::~SbaSbAttrDlg()
{
    delete pNumberInfoItem;

    DBG_DTOR(SbaSbAttrDlg,NULL);
}

// -----------------------------------------------------------------------
void SbaSbAttrDlg::PageCreated( sal_uInt16 nPageId, SfxTabPage& rTabPage )
{
    SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));
    switch ( nPageId )
    {
        case RID_SVXPAGE_NUMBERFORMAT:
        {
            //CHINA001 ((SvxNumberFormatTabPage&)rTabPage).
                //CHINA001 SetNumberFormatList( *pNumberInfoItem );
            aSet.Put (SvxNumberInfoItem( pNumberInfoItem->GetNumberFormatter(), (const USHORT)SID_ATTR_NUMBERFORMAT_INFO));
            rTabPage.PageCreated(aSet);
        }
        break;

        case RID_SVXPAGE_CHAR_STD:
        {
            //  ((SvxCharStdPage&)rTabPage).SetFontList(SBA_MOD_EXT()->FontListItem());
        }
        break;

        case RID_SVXPAGE_ALIGNMENT:
        {
            //CHINA001 ((SvxAlignmentTabPage&)rTabPage).SetFlags(WBA_NO_ORIENTATION|WBA_NO_LINEBREAK|WBA_NO_GRIDLINES|WBA_NO_VERTICAL|WBA_NO_LEFTINDENT);
//           aSet.Put (SfxUInt32Item(SID_FLAG_TYPE, WBA_NO_ORIENTATION|WBA_NO_LINEBREAK|WBA_NO_GRIDLINES|WBA_NO_VERTICAL|WBA_NO_LEFTINDENT));
//           rTabPage.PageCreated(aSet);
        }
        break;

        default:
        break;
    }
}

<|endoftext|>


<commit_before><commit_msg>Re-flakify TEST_F(NPAPITester, FLAKY_ManyPlugins) Fails under valgrind  http://build.chromium.org/buildbot/memory/builders/Chromium%20Mac%20UI%20(valgrind)(4)/builds/2607/steps/valgrind%20test:%20ui/logs/stdio<commit_after><|endoftext|>


<commit_before><commit_msg>rewrite Variant(Type typeValue)<commit_after><|endoftext|>


<commit_before>#include <string.h>
#include "Log.h"
#include "Gost.h"
#include "CryptoKey.h"

namespace i2p
{
namespace crypto
{
	ElGamalEncryptor::ElGamalEncryptor (const uint8_t * pub)
	{
		memcpy (m_PublicKey, pub, 256);
	}

	void ElGamalEncryptor::Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx)
	{
		ElGamalEncrypt (m_PublicKey, data, encrypted, ctx, true);
	}

	ElGamalDecryptor::ElGamalDecryptor (const uint8_t * priv)
	{
		memcpy (m_PrivateKey, priv, 256);
	}

	bool ElGamalDecryptor::Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx)
	{
		return ElGamalDecrypt (m_PrivateKey, encrypted, data, ctx, true);
	}

	ECIESP256Encryptor::ECIESP256Encryptor (const uint8_t * pub)
	{
		m_Curve = EC_GROUP_new_by_curve_name (NID_X9_62_prime256v1);
		m_PublicKey = EC_POINT_new (m_Curve);
		BIGNUM * x = BN_bin2bn (pub, 32, nullptr);
		BIGNUM * y = BN_bin2bn (pub + 32, 32, nullptr);
		if (!EC_POINT_set_affine_coordinates_GFp (m_Curve, m_PublicKey, x, y, nullptr))
			LogPrint (eLogError, "ECICS P256 invalid public key");
		BN_free (x); BN_free (y);
	}

	ECIESP256Encryptor::~ECIESP256Encryptor ()
	{
		if (m_Curve) EC_GROUP_free (m_Curve);
		if (m_PublicKey) EC_POINT_free (m_PublicKey);
	}

	void ECIESP256Encryptor::Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx)
	{
		if (m_Curve && m_PublicKey)
			ECIESEncrypt (m_Curve, m_PublicKey, data, encrypted, ctx);
	}

	ECIESP256Decryptor::ECIESP256Decryptor (const uint8_t * priv)
	{
		m_Curve = EC_GROUP_new_by_curve_name (NID_X9_62_prime256v1);
		m_PrivateKey = BN_bin2bn (priv, 32, nullptr);
	}

	ECIESP256Decryptor::~ECIESP256Decryptor ()
	{
		if (m_Curve) EC_GROUP_free (m_Curve);
		if (m_PrivateKey) BN_free (m_PrivateKey);
	}

	bool ECIESP256Decryptor::Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx)
	{
		if (m_Curve && m_PrivateKey)
			return ECIESDecrypt (m_Curve, m_PrivateKey, encrypted, data, ctx);
		return false;
	}

	void CreateECIESP256RandomKeys (uint8_t * priv, uint8_t * pub)
	{
		EC_GROUP * curve = EC_GROUP_new_by_curve_name (NID_X9_62_prime256v1);
		EC_POINT * p = nullptr;
		BIGNUM * key = nullptr;
		GenerateECIESKeyPair (curve, key, p);
		bn2buf (key, priv, 32);
		RAND_bytes (priv + 32, 224);
		BN_free (key);
		BIGNUM * x = BN_new (), * y = BN_new ();
		EC_POINT_get_affine_coordinates_GFp (curve, p, x, y, NULL);
		bn2buf (x, pub, 32);
		bn2buf (y, pub + 32, 32);
		RAND_bytes (priv + 64, 192);
		EC_POINT_free (p);
		BN_free (x); BN_free (y);
		EC_GROUP_free (curve);
	}

	ECIESGOSTR3410Encryptor::ECIESGOSTR3410Encryptor (const uint8_t * pub)
	{
		auto& curve = GetGOSTR3410Curve (eGOSTR3410CryptoProA);
		m_PublicKey = EC_POINT_new (curve->GetGroup ());
		BIGNUM * x = BN_bin2bn (pub, 32, nullptr);
		BIGNUM * y = BN_bin2bn (pub + 32, 32, nullptr);
		if (!EC_POINT_set_affine_coordinates_GFp (curve->GetGroup (), m_PublicKey, x, y, nullptr))
			LogPrint (eLogError, "ECICS GOST R 34.10 invalid public key");
		BN_free (x); BN_free (y);
	}

	ECIESGOSTR3410Encryptor::~ECIESGOSTR3410Encryptor ()
	{
		if (m_PublicKey) EC_POINT_free (m_PublicKey);
	}

	void ECIESGOSTR3410Encryptor::Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx)
	{
		if (m_PublicKey)
			ECIESEncrypt (GetGOSTR3410Curve (eGOSTR3410CryptoProA)->GetGroup (), m_PublicKey, data, encrypted, ctx);
	}

	ECIESGOSTR3410Decryptor::ECIESGOSTR3410Decryptor (const uint8_t * priv)
	{
		m_PrivateKey = BN_bin2bn (priv, 32, nullptr);
	}

	ECIESGOSTR3410Decryptor::~ECIESGOSTR3410Decryptor ()
	{
		if (m_PrivateKey) BN_free (m_PrivateKey);
	}

	bool ECIESGOSTR3410Decryptor::Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx)
	{
		if (m_PrivateKey)
			return ECIESDecrypt (GetGOSTR3410Curve (eGOSTR3410CryptoProA)->GetGroup (), m_PrivateKey, encrypted, data, ctx);
		return false;
	}

	void CreateECIESGOSTR3410RandomKeys (uint8_t * priv, uint8_t * pub)
	{
		auto& curve = GetGOSTR3410Curve (eGOSTR3410CryptoProA);
		EC_POINT * p = nullptr;
		BIGNUM * key = nullptr;
		GenerateECIESKeyPair (curve->GetGroup (), key, p);
		bn2buf (key, priv, 32);
		RAND_bytes (priv + 32, 224);
		BN_free (key);
		BIGNUM * x = BN_new (), * y = BN_new ();
		EC_POINT_get_affine_coordinates_GFp (curve->GetGroup (), p, x, y, NULL);
		bn2buf (x, pub, 32);
		bn2buf (y, pub + 32, 32);
		RAND_bytes (priv + 64, 192);
		EC_POINT_free (p);
		BN_free (x); BN_free (y);
	}

}
}

<commit_msg>correct random padding for ICIES public key<commit_after>#include <string.h>
#include "Log.h"
#include "Gost.h"
#include "CryptoKey.h"

namespace i2p
{
namespace crypto
{
	ElGamalEncryptor::ElGamalEncryptor (const uint8_t * pub)
	{
		memcpy (m_PublicKey, pub, 256);
	}

	void ElGamalEncryptor::Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx)
	{
		ElGamalEncrypt (m_PublicKey, data, encrypted, ctx, true);
	}

	ElGamalDecryptor::ElGamalDecryptor (const uint8_t * priv)
	{
		memcpy (m_PrivateKey, priv, 256);
	}

	bool ElGamalDecryptor::Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx)
	{
		return ElGamalDecrypt (m_PrivateKey, encrypted, data, ctx, true);
	}

	ECIESP256Encryptor::ECIESP256Encryptor (const uint8_t * pub)
	{
		m_Curve = EC_GROUP_new_by_curve_name (NID_X9_62_prime256v1);
		m_PublicKey = EC_POINT_new (m_Curve);
		BIGNUM * x = BN_bin2bn (pub, 32, nullptr);
		BIGNUM * y = BN_bin2bn (pub + 32, 32, nullptr);
		if (!EC_POINT_set_affine_coordinates_GFp (m_Curve, m_PublicKey, x, y, nullptr))
			LogPrint (eLogError, "ECICS P256 invalid public key");
		BN_free (x); BN_free (y);
	}

	ECIESP256Encryptor::~ECIESP256Encryptor ()
	{
		if (m_Curve) EC_GROUP_free (m_Curve);
		if (m_PublicKey) EC_POINT_free (m_PublicKey);
	}

	void ECIESP256Encryptor::Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx)
	{
		if (m_Curve && m_PublicKey)
			ECIESEncrypt (m_Curve, m_PublicKey, data, encrypted, ctx);
	}

	ECIESP256Decryptor::ECIESP256Decryptor (const uint8_t * priv)
	{
		m_Curve = EC_GROUP_new_by_curve_name (NID_X9_62_prime256v1);
		m_PrivateKey = BN_bin2bn (priv, 32, nullptr);
	}

	ECIESP256Decryptor::~ECIESP256Decryptor ()
	{
		if (m_Curve) EC_GROUP_free (m_Curve);
		if (m_PrivateKey) BN_free (m_PrivateKey);
	}

	bool ECIESP256Decryptor::Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx)
	{
		if (m_Curve && m_PrivateKey)
			return ECIESDecrypt (m_Curve, m_PrivateKey, encrypted, data, ctx);
		return false;
	}

	void CreateECIESP256RandomKeys (uint8_t * priv, uint8_t * pub)
	{
		EC_GROUP * curve = EC_GROUP_new_by_curve_name (NID_X9_62_prime256v1);
		EC_POINT * p = nullptr;
		BIGNUM * key = nullptr;
		GenerateECIESKeyPair (curve, key, p);
		bn2buf (key, priv, 32);
		RAND_bytes (priv + 32, 224);
		BN_free (key);
		BIGNUM * x = BN_new (), * y = BN_new ();
		EC_POINT_get_affine_coordinates_GFp (curve, p, x, y, NULL);
		bn2buf (x, pub, 32);
		bn2buf (y, pub + 32, 32);
		RAND_bytes (pub + 64, 192);
		EC_POINT_free (p);
		BN_free (x); BN_free (y);
		EC_GROUP_free (curve);
	}

	ECIESGOSTR3410Encryptor::ECIESGOSTR3410Encryptor (const uint8_t * pub)
	{
		auto& curve = GetGOSTR3410Curve (eGOSTR3410CryptoProA);
		m_PublicKey = EC_POINT_new (curve->GetGroup ());
		BIGNUM * x = BN_bin2bn (pub, 32, nullptr);
		BIGNUM * y = BN_bin2bn (pub + 32, 32, nullptr);
		if (!EC_POINT_set_affine_coordinates_GFp (curve->GetGroup (), m_PublicKey, x, y, nullptr))
			LogPrint (eLogError, "ECICS GOST R 34.10 invalid public key");
		BN_free (x); BN_free (y);
	}

	ECIESGOSTR3410Encryptor::~ECIESGOSTR3410Encryptor ()
	{
		if (m_PublicKey) EC_POINT_free (m_PublicKey);
	}

	void ECIESGOSTR3410Encryptor::Encrypt (const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx)
	{
		if (m_PublicKey)
			ECIESEncrypt (GetGOSTR3410Curve (eGOSTR3410CryptoProA)->GetGroup (), m_PublicKey, data, encrypted, ctx);
	}

	ECIESGOSTR3410Decryptor::ECIESGOSTR3410Decryptor (const uint8_t * priv)
	{
		m_PrivateKey = BN_bin2bn (priv, 32, nullptr);
	}

	ECIESGOSTR3410Decryptor::~ECIESGOSTR3410Decryptor ()
	{
		if (m_PrivateKey) BN_free (m_PrivateKey);
	}

	bool ECIESGOSTR3410Decryptor::Decrypt (const uint8_t * encrypted, uint8_t * data, BN_CTX * ctx)
	{
		if (m_PrivateKey)
			return ECIESDecrypt (GetGOSTR3410Curve (eGOSTR3410CryptoProA)->GetGroup (), m_PrivateKey, encrypted, data, ctx);
		return false;
	}

	void CreateECIESGOSTR3410RandomKeys (uint8_t * priv, uint8_t * pub)
	{
		auto& curve = GetGOSTR3410Curve (eGOSTR3410CryptoProA);
		EC_POINT * p = nullptr;
		BIGNUM * key = nullptr;
		GenerateECIESKeyPair (curve->GetGroup (), key, p);
		bn2buf (key, priv, 32);
		RAND_bytes (priv + 32, 224);
		BN_free (key);
		BIGNUM * x = BN_new (), * y = BN_new ();
		EC_POINT_get_affine_coordinates_GFp (curve->GetGroup (), p, x, y, NULL);
		bn2buf (x, pub, 32);
		bn2buf (y, pub + 32, 32);
		RAND_bytes (priv + 64, 192);
		EC_POINT_free (p);
		BN_free (x); BN_free (y);
	}

}
}

<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS geordi2q10 (1.48.8); FILE MERGED 2003/11/27 10:28:47 rt 1.48.8.1: #111934#: join CWS vcl7pp1r2<commit_after><|endoftext|>


<commit_before>
/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBlurMaskFilter.h"
#include "SkBlurMask.h"
#include "SkBuffer.h"
#include "SkMaskFilter.h"

class SkBlurMaskFilterImpl : public SkMaskFilter {
public:
    SkBlurMaskFilterImpl(SkScalar radius, SkBlurMaskFilter::BlurStyle,
                         uint32_t flags);

    // overrides from SkMaskFilter
    virtual SkMask::Format getFormat();
    virtual bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&,
                            SkIPoint* margin);
    virtual BlurType asABlur(BlurInfo*);

    // overrides from SkFlattenable
    virtual Factory getFactory();
    virtual void flatten(SkFlattenableWriteBuffer&);

    static SkFlattenable* CreateProc(SkFlattenableReadBuffer&);

private:
    SkScalar                    fRadius;
    SkBlurMaskFilter::BlurStyle fBlurStyle;
    uint32_t                    fBlurFlags;

    SkBlurMaskFilterImpl(SkFlattenableReadBuffer&);

    typedef SkMaskFilter INHERITED;
};

SkMaskFilter* SkBlurMaskFilter::Create(SkScalar radius,
                                       SkBlurMaskFilter::BlurStyle style,
                                       uint32_t flags) {
    if (radius <= 0 || (unsigned)style >= SkBlurMaskFilter::kBlurStyleCount
        || flags > SkBlurMaskFilter::kAll_BlurFlag) {
        return NULL;
    }

    return SkNEW_ARGS(SkBlurMaskFilterImpl, (radius, style, flags));
}

///////////////////////////////////////////////////////////////////////////////

SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkScalar radius,
                                           SkBlurMaskFilter::BlurStyle style,
                                           uint32_t flags)
    : fRadius(radius), fBlurStyle(style), fBlurFlags(flags) {
#if 0
    fGamma = NULL;
    if (gammaScale) {
        fGamma = new U8[256];
        if (gammaScale > 0)
            SkBlurMask::BuildSqrGamma(fGamma, gammaScale);
        else
            SkBlurMask::BuildSqrtGamma(fGamma, -gammaScale);
    }
#endif
    SkASSERT(radius >= 0);
    SkASSERT((unsigned)style < SkBlurMaskFilter::kBlurStyleCount);
    SkASSERT(flags <= SkBlurMaskFilter::kAll_BlurFlag);
}

SkMask::Format SkBlurMaskFilterImpl::getFormat() {
    return SkMask::kA8_Format;
}

bool SkBlurMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src,
                                      const SkMatrix& matrix, SkIPoint* margin) {
    SkScalar radius;
    if (fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag) {
        radius = fRadius;
    } else {
        radius = matrix.mapRadius(fRadius);
    }

    // To avoid unseemly allocation requests (esp. for finite platforms like
    // handset) we limit the radius so something manageable. (as opposed to
    // a request like 10,000)
    static const SkScalar MAX_RADIUS = SkIntToScalar(128);
    radius = SkMinScalar(radius, MAX_RADIUS);
    SkBlurMask::Quality blurQuality =
        (fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag) ?
            SkBlurMask::kHigh_Quality : SkBlurMask::kLow_Quality;

#if defined(SK_BLUR_MASK_FILTER_IGNORE_MARGIN_FIX)
    if (SkBlurMask::Blur(dst, src, radius, (SkBlurMask::Style)fBlurStyle,
                         blurQuality)) {
        if (margin) {
            // we need to integralize radius for our margin, so take the ceil
            // just to be safe.
            margin->set(SkScalarCeil(radius), SkScalarCeil(radius));
        }
        return true;
    }
    return false;
#else
    return SkBlurMask::Blur(dst, src, radius, (SkBlurMask::Style)fBlurStyle,
                            blurQuality, margin);
#endif
}

SkFlattenable* SkBlurMaskFilterImpl::CreateProc(SkFlattenableReadBuffer& buffer) {
    return SkNEW_ARGS(SkBlurMaskFilterImpl, (buffer));
}

SkFlattenable::Factory SkBlurMaskFilterImpl::getFactory() {
    return CreateProc;
}

SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkFlattenableReadBuffer& buffer)
        : SkMaskFilter(buffer) {
    fRadius = buffer.readScalar();
    fBlurStyle = (SkBlurMaskFilter::BlurStyle)buffer.readS32();
    fBlurFlags = buffer.readU32() & SkBlurMaskFilter::kAll_BlurFlag;
    SkASSERT(fRadius >= 0);
    SkASSERT((unsigned)fBlurStyle < SkBlurMaskFilter::kBlurStyleCount);
}

void SkBlurMaskFilterImpl::flatten(SkFlattenableWriteBuffer& buffer) {
    this->INHERITED::flatten(buffer);
    buffer.writeScalar(fRadius);
    buffer.write32(fBlurStyle);
    buffer.write32(fBlurFlags);
}

static const SkMaskFilter::BlurType gBlurStyle2BlurType[] = {
    SkMaskFilter::kNormal_BlurType,
    SkMaskFilter::kSolid_BlurType,
    SkMaskFilter::kOuter_BlurType,
    SkMaskFilter::kInner_BlurType,
};

SkMaskFilter::BlurType SkBlurMaskFilterImpl::asABlur(BlurInfo* info) {
    if (info) {
        info->fRadius = fRadius;
        info->fIgnoreTransform = SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag);
        info->fHighQuality = SkToBool(fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag);
    }
    return gBlurStyle2BlurType[fBlurStyle];
}

///////////////////////////////////////////////////////////////////////////////

static SkFlattenable::Registrar gReg("SkBlurMaskFilter",
                                     SkBlurMaskFilterImpl::CreateProc);

<commit_msg>Now that layout tests are fixed, remove flag to ignore margin fix. http://codereview.appspot.com/5186044/<commit_after>
/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBlurMaskFilter.h"
#include "SkBlurMask.h"
#include "SkBuffer.h"
#include "SkMaskFilter.h"

class SkBlurMaskFilterImpl : public SkMaskFilter {
public:
    SkBlurMaskFilterImpl(SkScalar radius, SkBlurMaskFilter::BlurStyle,
                         uint32_t flags);

    // overrides from SkMaskFilter
    virtual SkMask::Format getFormat();
    virtual bool filterMask(SkMask* dst, const SkMask& src, const SkMatrix&,
                            SkIPoint* margin);
    virtual BlurType asABlur(BlurInfo*);

    // overrides from SkFlattenable
    virtual Factory getFactory();
    virtual void flatten(SkFlattenableWriteBuffer&);

    static SkFlattenable* CreateProc(SkFlattenableReadBuffer&);

private:
    SkScalar                    fRadius;
    SkBlurMaskFilter::BlurStyle fBlurStyle;
    uint32_t                    fBlurFlags;

    SkBlurMaskFilterImpl(SkFlattenableReadBuffer&);

    typedef SkMaskFilter INHERITED;
};

SkMaskFilter* SkBlurMaskFilter::Create(SkScalar radius,
                                       SkBlurMaskFilter::BlurStyle style,
                                       uint32_t flags) {
    if (radius <= 0 || (unsigned)style >= SkBlurMaskFilter::kBlurStyleCount
        || flags > SkBlurMaskFilter::kAll_BlurFlag) {
        return NULL;
    }

    return SkNEW_ARGS(SkBlurMaskFilterImpl, (radius, style, flags));
}

///////////////////////////////////////////////////////////////////////////////

SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkScalar radius,
                                           SkBlurMaskFilter::BlurStyle style,
                                           uint32_t flags)
    : fRadius(radius), fBlurStyle(style), fBlurFlags(flags) {
#if 0
    fGamma = NULL;
    if (gammaScale) {
        fGamma = new U8[256];
        if (gammaScale > 0)
            SkBlurMask::BuildSqrGamma(fGamma, gammaScale);
        else
            SkBlurMask::BuildSqrtGamma(fGamma, -gammaScale);
    }
#endif
    SkASSERT(radius >= 0);
    SkASSERT((unsigned)style < SkBlurMaskFilter::kBlurStyleCount);
    SkASSERT(flags <= SkBlurMaskFilter::kAll_BlurFlag);
}

SkMask::Format SkBlurMaskFilterImpl::getFormat() {
    return SkMask::kA8_Format;
}

bool SkBlurMaskFilterImpl::filterMask(SkMask* dst, const SkMask& src,
                                      const SkMatrix& matrix, SkIPoint* margin) {
    SkScalar radius;
    if (fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag) {
        radius = fRadius;
    } else {
        radius = matrix.mapRadius(fRadius);
    }

    // To avoid unseemly allocation requests (esp. for finite platforms like
    // handset) we limit the radius so something manageable. (as opposed to
    // a request like 10,000)
    static const SkScalar MAX_RADIUS = SkIntToScalar(128);
    radius = SkMinScalar(radius, MAX_RADIUS);
    SkBlurMask::Quality blurQuality =
        (fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag) ?
            SkBlurMask::kHigh_Quality : SkBlurMask::kLow_Quality;

    return SkBlurMask::Blur(dst, src, radius, (SkBlurMask::Style)fBlurStyle,
                            blurQuality, margin);
}

SkFlattenable* SkBlurMaskFilterImpl::CreateProc(SkFlattenableReadBuffer& buffer) {
    return SkNEW_ARGS(SkBlurMaskFilterImpl, (buffer));
}

SkFlattenable::Factory SkBlurMaskFilterImpl::getFactory() {
    return CreateProc;
}

SkBlurMaskFilterImpl::SkBlurMaskFilterImpl(SkFlattenableReadBuffer& buffer)
        : SkMaskFilter(buffer) {
    fRadius = buffer.readScalar();
    fBlurStyle = (SkBlurMaskFilter::BlurStyle)buffer.readS32();
    fBlurFlags = buffer.readU32() & SkBlurMaskFilter::kAll_BlurFlag;
    SkASSERT(fRadius >= 0);
    SkASSERT((unsigned)fBlurStyle < SkBlurMaskFilter::kBlurStyleCount);
}

void SkBlurMaskFilterImpl::flatten(SkFlattenableWriteBuffer& buffer) {
    this->INHERITED::flatten(buffer);
    buffer.writeScalar(fRadius);
    buffer.write32(fBlurStyle);
    buffer.write32(fBlurFlags);
}

static const SkMaskFilter::BlurType gBlurStyle2BlurType[] = {
    SkMaskFilter::kNormal_BlurType,
    SkMaskFilter::kSolid_BlurType,
    SkMaskFilter::kOuter_BlurType,
    SkMaskFilter::kInner_BlurType,
};

SkMaskFilter::BlurType SkBlurMaskFilterImpl::asABlur(BlurInfo* info) {
    if (info) {
        info->fRadius = fRadius;
        info->fIgnoreTransform = SkToBool(fBlurFlags & SkBlurMaskFilter::kIgnoreTransform_BlurFlag);
        info->fHighQuality = SkToBool(fBlurFlags & SkBlurMaskFilter::kHighQuality_BlurFlag);
    }
    return gBlurStyle2BlurType[fBlurStyle];
}

///////////////////////////////////////////////////////////////////////////////

static SkFlattenable::Registrar gReg("SkBlurMaskFilter",
                                     SkBlurMaskFilterImpl::CreateProc);

<|endoftext|>


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

#ifndef _PSPRINT_PRINTERJOB_HXX_
#define _PSPRINT_PRINTERJOB_HXX_

#ifndef __SGI_STL_LIST
#include <list>
#endif
#ifndef _PSPRINT_JOBDATA_HXX_
#include <psprint/jobdata.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif

namespace psp {

// forward declarations
class PrinterGfx;

class PrinterJob
{
private:            // private data

    rtl::OUString           maSpoolDirName;
    rtl::OUString           maFileName; // empty: spool to command, else spool to named file
    int                     mnFileMode;
    rtl::OUString           maJobName;

    osl::File*              mpJobHeader;
    osl::File*              mpJobTrailer;

    std::list< osl::File* > maPageList;
    std::list< osl::File* > maHeaderList;

    JobData                 m_aDocumentJobData;
    JobData                 m_aLastJobData;
    PrinterGfx*             m_pGraphics;

    sal_uInt32      mnResolution;

    sal_uInt32      mnWidthPt;
    sal_uInt32      mnHeightPt;
    sal_uInt32      mnMaxWidthPt;
    sal_uInt32      mnMaxHeightPt;

    sal_uInt32      mnLMarginPt;
    sal_uInt32      mnRMarginPt;
    sal_uInt32      mnTMarginPt;
    sal_uInt32      mnBMarginPt;

    double          mfXScale;
    double          mfYScale;

    sal_Int32       mnErrorCode;

private:            // private methods

    osl::File*      CreateSpoolFile (const rtl::OUString& rName,
                                     const rtl::OUString& rExtension);
    void            InitPaperSize (const JobData& rJobSetup);

    bool            writeFeatureList( osl::File* pFile, const JobData&, bool bDocumentSetup );
    bool            writeSetup( osl::File* pFile, const JobData& );
    bool            writePageSetup( osl::File* pFile, const JobData& );
    bool            writeProlog (osl::File* pFile);

public:             // for usage in PrinterGfx

    sal_uInt32      GetResolution () const { return mnResolution; }
    void            GetScale (double &rXScale, double &rYScale) const;
    sal_uInt16      GetDepth () const;
    sal_uInt16      GetPostscriptLevel (const JobData *pJobData = NULL) const;
    sal_Bool        IsColorPrinter () const;

    osl::File*      GetDocumentHeader ();
    osl::File*      GetDocumentTrailer ();
    osl::File*      GetCurrentPageHeader ();
    osl::File*      GetCurrentPageBody ();

    const ::rtl::OUString& GetPrinterName() const { return m_aLastJobData.m_aPrinterName; }

public:
    PrinterJob ();
    ~PrinterJob ();

    /*  rFileName: if length is greater than 0 save resulting PostScript
     *  to named file.
     *  nMode: only meaningful when saving to file: if nonzero, try
     *  to impose the mode on the resulting file's inode; for nonexistant
     *  files use open, for existant files try a chmod
     *  rJobName: text to appear in the %%Title comment
     *  rAppName: text to appear in the %%Creator comment
     *  rSetupData: JobData that apply to this job
     *  pGraphics: the graphics used to print this job;
     *             this graphics must live until End/AbortJob has returned
     */
    sal_Bool        StartJob (const rtl::OUString& rFileName,
                              int nMode,
                              const rtl::OUString& rJobName,
                              const rtl::OUString& rAppName,
                              const JobData& rSetupData,
                              PrinterGfx* pGraphics
                              );
    sal_Bool        EndJob ();

    sal_Bool        AbortJob ();

    sal_Bool        StartPage (const JobData& rJobSetup, sal_Bool bNewJobData);
    sal_Bool        EndPage ();

    sal_uInt32      GetErrorCode ();
};

}  /* namespace psp */

#endif /* _PSPRINT_PRINTERJOB_HXX_ */

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

#ifndef _PSPRINT_PRINTERJOB_HXX_
#define _PSPRINT_PRINTERJOB_HXX_

#ifndef __SGI_STL_LIST
#include <list>
#endif
#ifndef _PSPRINT_JOBDATA_HXX_
#include <psprint/jobdata.hxx>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif

namespace psp {

// forward declarations
class PrinterGfx;

class PrinterJob
{
private:            // private data

    rtl::OUString           maSpoolDirName;
    rtl::OUString           maFileName; // empty: spool to command, else spool to named file
    rtl::OUString           maJobTitle;
    int                     mnFileMode;

    osl::File*              mpJobHeader;
    osl::File*              mpJobTrailer;

    std::list< osl::File* > maPageList;
    std::list< osl::File* > maHeaderList;

    JobData                 m_aDocumentJobData;
    JobData                 m_aLastJobData;
    PrinterGfx*             m_pGraphics;

    sal_uInt32      mnResolution;

    sal_uInt32      mnWidthPt;
    sal_uInt32      mnHeightPt;
    sal_uInt32      mnMaxWidthPt;
    sal_uInt32      mnMaxHeightPt;

    sal_uInt32      mnLMarginPt;
    sal_uInt32      mnRMarginPt;
    sal_uInt32      mnTMarginPt;
    sal_uInt32      mnBMarginPt;

    double          mfXScale;
    double          mfYScale;

    sal_Int32       mnErrorCode;

private:            // private methods

    osl::File*      CreateSpoolFile (const rtl::OUString& rName,
                                     const rtl::OUString& rExtension);
    void            InitPaperSize (const JobData& rJobSetup);

    bool            writeFeatureList( osl::File* pFile, const JobData&, bool bDocumentSetup );
    bool            writeSetup( osl::File* pFile, const JobData& );
    bool            writePageSetup( osl::File* pFile, const JobData& );
    bool            writeProlog (osl::File* pFile);

public:             // for usage in PrinterGfx

    sal_uInt32      GetResolution () const { return mnResolution; }
    void            GetScale (double &rXScale, double &rYScale) const;
    sal_uInt16      GetDepth () const;
    sal_uInt16      GetPostscriptLevel (const JobData *pJobData = NULL) const;
    sal_Bool        IsColorPrinter () const;

    osl::File*      GetDocumentHeader ();
    osl::File*      GetDocumentTrailer ();
    osl::File*      GetCurrentPageHeader ();
    osl::File*      GetCurrentPageBody ();

    const ::rtl::OUString& GetPrinterName() const { return m_aLastJobData.m_aPrinterName; }

public:
    PrinterJob ();
    ~PrinterJob ();

    /*  rFileName: if length is greater than 0 save resulting PostScript
     *  to named file.
     *  nMode: only meaningful when saving to file: if nonzero, try
     *  to impose the mode on the resulting file's inode; for nonexistant
     *  files use open, for existant files try a chmod
     *  rJobName: text to appear in the %%Title comment
     *  rAppName: text to appear in the %%Creator comment
     *  rSetupData: JobData that apply to this job
     *  pGraphics: the graphics used to print this job;
     *             this graphics must live until End/AbortJob has returned
     */
    sal_Bool        StartJob (const rtl::OUString& rFileName,
                              int nMode,
                              const rtl::OUString& rJobName,
                              const rtl::OUString& rAppName,
                              const JobData& rSetupData,
                              PrinterGfx* pGraphics
                              );
    sal_Bool        EndJob ();

    sal_Bool        AbortJob ();

    sal_Bool        StartPage (const JobData& rJobSetup, sal_Bool bNewJobData);
    sal_Bool        EndPage ();

    sal_uInt32      GetErrorCode ();
};

}  /* namespace psp */

#endif /* _PSPRINT_PRINTERJOB_HXX_ */

<|endoftext|>


<commit_before>#include "argparser.h"

#include <cstddef>
#include <cstdlib>
#include <err.h>
#include <iostream>
#include "util.h"

void usage()
{
  std::cout <<
    "slock\n"
    "  -h  --help             - prints this message\n"
    "  -b  --bell             - sound signal on failed login\n"
    "  -v  --verbose          - make slock verbose\n"
    "      --debug            - produce debug messages\n"
    "      --logfile <FILE>   - sets the log file (default: " LOGFILE ")\n"
    "      --version          - report the version\n"
    ;
  std::cout.flush();
}

void parseArguments( char **argv )
{
  ++argv; // skip method name
  for ( char *arg; ( arg = *argv ); ++argv )
  {
    if ( streq( arg, "-h" ) || streq( arg, "--help" ) )
    {
      usage();
      exit( EXIT_SUCCESS );
    }
    else if ( streq( arg, "-b" ) || streq( arg, "--bell" ) )
    {
      enableBell = true;
    }
    else if ( streq( arg, "-v" ) || streq( arg, "--verbose" ) )
    {
      if ( Logger::LL_Verbose < logLevel )
        logLevel = Logger::LL_Verbose;
    }
    else if ( streq( arg, "--debug" ) )
    {
      logLevel = Logger::LL_Debug;
    }
    else if ( streq( arg, "--logfile" ) )
    {
      logfile = *(++argv);
      if ( ! logfile )
      {
        usage();
        errx( EXIT_FAILURE, "no logfile specified\n" );
      }
    }
    else if ( streq( arg, "--version" ) )
    {
      std::cout <<
        "slock2\n"
        "Version " VERSION "\n"
        __DATE__ "\n"
        "Immanuel Haffner\n"
        ;
    }
    else
    {
      /* Unknown argument. */
      std::cerr << "unknown argument: '" << arg << "'" << std::endl;
      usage();
      exit( EXIT_FAILURE );
    }
  }
}
<commit_msg>fixed --version: now exits, and does not lock the screen<commit_after>#include "argparser.h"

#include <cstddef>
#include <cstdlib>
#include <err.h>
#include <iostream>
#include "util.h"

void usage()
{
  std::cout <<
    "slock\n"
    "  -h  --help             - prints this message\n"
    "  -b  --bell             - sound signal on failed login\n"
    "  -v  --verbose          - make slock verbose\n"
    "      --debug            - produce debug messages\n"
    "      --logfile <FILE>   - sets the log file (default: " LOGFILE ")\n"
    "      --version          - report the version\n"
    ;
  std::cout.flush();
}

void parseArguments( char **argv )
{
  ++argv; // skip method name
  for ( char *arg; ( arg = *argv ); ++argv )
  {
    if ( streq( arg, "-h" ) || streq( arg, "--help" ) )
    {
      usage();
      exit( EXIT_SUCCESS );
    }
    else if ( streq( arg, "-b" ) || streq( arg, "--bell" ) )
    {
      enableBell = true;
    }
    else if ( streq( arg, "-v" ) || streq( arg, "--verbose" ) )
    {
      if ( Logger::LL_Verbose < logLevel )
        logLevel = Logger::LL_Verbose;
    }
    else if ( streq( arg, "--debug" ) )
    {
      logLevel = Logger::LL_Debug;
    }
    else if ( streq( arg, "--logfile" ) )
    {
      logfile = *(++argv);
      if ( ! logfile )
      {
        usage();
        errx( EXIT_FAILURE, "no logfile specified\n" );
      }
    }
    else if ( streq( arg, "--version" ) )
    {
      std::cout <<
        "slock2\n"
        "Version " VERSION "\n"
        __DATE__ "\n"
        "Immanuel Haffner\n"
        ;
      exit( EXIT_SUCCESS );
    }
    else
    {
      /* Unknown argument. */
      std::cerr << "unknown argument: '" << arg << "'" << std::endl;
      usage();
      exit( EXIT_FAILURE );
    }
  }
}
<|endoftext|>


<commit_before>#ifndef ARGUMENT_HXX_
#define ARGUMENT_HXX_

#include <string>

namespace tglng {
  class Command;
  class Interpreter;

  /**
   * Encapsulates the data and basic semantics for argument extraction.
   */
  class Argument {
  public:
    Interpreter& interp;
    const std::wstring& text;
    unsigned& offset;

  protected:
    Command*& left;

    Argument(Interpreter&, const std::wstring&, unsigned&, Command*&);

  public:
    /**
     * Tests whether the string matches.
     *
     * Default advances past all whitespace and then returns whether a
     * non-whitespace character was found.
     */
    bool match();
  };

#define CTOR(clazz) \
  clazz##Argument(Interpreter& i, const std::wstring& s, \
                  unsigned& u, Command*& c)              \
  : Argument(i,s,u,c) {}

  /**
   * Extracts a single non-whitespace character as an argument.
   */
  class CharArgument: public Argument {
  public:
    CTOR(Char)
    typedef wchar_t get_t;
    bool get(get_t&);
  };

  /**
   * Extracts a numeric literal as an argument.
   */
  class NumericArgument: public Argument {
  public:
    CTOR(Numeric)
    typedef signed get_t;
    bool get(get_t&);
    bool match();
  };

  /**
   * Extracts and parses a single Command as an argument.
   */
  class CommandArgument: public Argument {
  public:
    CTOR(Command)
    typedef Command* get_t;
    bool get(get_t&);
  };

  /**
   * Defines the type of a section arguement.
   */
  struct Section {
    Command* left, * right;
  };
  /**
   * Extracts a Section argument type from input.
   */
  class SectionArgument: public Argument {
  public:
    CTOR(Section)
    typedef Section get_t;
    bool get(get_t&);
    bool match();
  };

  /**
   * Extracts a string from point to the given sentinal. Does not match if the
   * sentinel is not found.
   */
  class SentinelStringArgument: public Argument {
    wchar_t sentinel;

  public:
    SentinelStringArgument(Interpreter&, const std::wstring&, unsigned&,
                           Command*&, wchar_t);
    typedef std::wstring get_t;
    bool get(get_t&);
    bool match();
  };

  /**
   * Extracts a non-empty string of alphanumeric characters starting at point
   * and continuing to (but not including) the first non-alphanumeric character
   * or end of input.
   */
  class AlnumStringArgument: public Argument {
  public:
    CTOR(AlnumString)
    typedef std::wstring get_t;
    bool get(get_t&);
    bool match();
  };

  /**
   * Extracts a non-empty string of characters starting at point and continuing
   * to (but not including) the first whitespace character, the first character
   * which is a valid section specifier, or end of input.
   */
  class NonSectionStringArgument: public Argument {
  public:
    CTOR(NonSectionString)
    typedef std::wstring get_t;
    bool get(get_t&);
    bool match();
  };

  /**
   * Extracts either a single parsed command, or a literal number which is
   * wrapped in a command and returned.
   */
  class ArithmeticArgument: public Argument {
  public:
    CTOR(Arithmetic)
    typedef Command* get_t;
    bool get(get_t&);
  };

  /**
   * Matches a single character. If matched, extracts true to a boolean.
   */
  class ExactCharacterArgument: public Argument {
    wchar_t expect;

  public:
    ExactCharacterArgument(Interpreter&, const std::wstring&, unsigned&,
                           Command*&, wchar_t);
    typedef bool get_t;
    bool get(get_t&);
    bool match();
  };
#undef CTOR

  /**
   * Wraps the Argument classes to store the destination reference within.
   */
  template<typename T>
  class ArgumentExtractor {
  protected:
    T it;
    typename T::get_t& dst;

  public:
    ArgumentExtractor(const T& t, typename T::get_t& d)
    : it(t), dst(d)
    { }

    bool match() { return it.match(); }
    bool get() { return it.get(dst); }

    Interpreter& interp() { return it.interp; }
    const std::wstring& text() { return it.text; }
    unsigned offset() { return it.offset; }
  };

  /**
   * Chains two ArgumentExtractor-compatible classes into one.
   */
  template<typename First, typename Rest>
  class ArgumentSequence {
    First first;
    Rest rest;

  public:
    ArgumentSequence(const First& f, const Rest& r)
    : first(f), rest(r) {}

    bool match() { return first.match(); }
    bool get() {
      if (!first.get()) return false;
      if (!rest.match()) {
        interp().error(L"Could not match next part of argument sequence.",
                       text(), offset());
        return false;
      }
      return rest.get();
    }

    Interpreter& interp() { return first.interp(); }
    const std::wstring& text() { return first.text(); }
    unsigned offset() { return first.offset(); }
  };

  /**
   * Tries to match with one ArgumentExtractor-compatible class, then falls
   * back on the other.
   */
  template<typename First, typename Rest>
  class ArgumentOptions {
    First first;
    Rest rest;

  public:
    ArgumentOptions(const First& f, const Rest& r)
    : first(f), rest(r) {}

    bool match() { return first.match() || rest.match(); }
    bool get() { return first.match()? first.get() : rest.get(); }

    Interpreter& interp() { return first.interp(); }
    const std::wstring& text() { return first.text(); }
    unsigned offset() { return first.offset(); }
  };

  /**
   * Wraps an ArgumentExtractor-compatible class to make it optional.
   */
  template<typename T>
  class OptionalArgument {
    T it;

  public:
    OptionalArgument(const T& t) : it(t) {}

    bool match() { return true; }
    bool get() { return !it.match() || it.get(); }

    Interpreter& interp() { return it.interp(); }
    const std::wstring& text() { return it.text(); }
    unsigned offset() { return it.offset(); }
  };

  /**
   * Adds operators to ArgumentExtractor which give a nice syntax sugar for
   * compound arguments:
   *
   *   arg1, arg2  -> ArgumentSequence<arg1,arg2>
   *   arg1 | arg2 -> ArgumentOptions<arg1,arg2>
   *   -arg1       -> OptionalArgument<arg1>
   */
  template<typename Contained>
  class ArgumentSyntaxSugar {
    Contained it;

  public:
    ArgumentSyntaxSugar(const Contained& t)
    : it(t) {}

    bool match() { return it.match(); }
    bool get() { return it.get(); }

    template<typename Next>
    ArgumentSyntaxSugar<ArgumentSequence<Contained, Next> >
    operator,(const Next& next) const {
      return ArgumentSyntaxSugar<ArgumentSequence<Contained, Next> >(
        ArgumentSequence<Contained,Next>(it, next));
    }

    template<typename Other>
    ArgumentSyntaxSugar<ArgumentOptions<Contained, Other> >
    operator|(const Other& other) const {
      return ArgumentSyntaxSugar<ArgumentOptions<Contained, Other> >(
        ArgumentOptions<Contained,Other>(it, other));
    }

    ArgumentSyntaxSugar<OptionalArgument<Contained> >
    operator-() const {
      return ArgumentSyntaxSugar<OptionalArgument<Contained> >(
        OptionalArgument<Contained>(it));
    }
  };

  /**
   * Simplifies the construction and testing of argument extractors.
   */
  class ArgumentParser {
    Interpreter& interp;
    const std::wstring& text;
    unsigned& offset;
    unsigned startingOffset;
    Command*& left;

  public:
    /**
     * Creates an ArgumentParser with the given arguments required for all
     * Arguments.
     */
    ArgumentParser(Interpreter&, const std::wstring&,
                   unsigned&, Command*& left);

    ///Returns a wrapped CharArgument which discards its character.
    ArgumentSyntaxSugar<ArgumentExtractor<CharArgument> > h();
    ///Returns a wrapped CharArgument storing the character into the given
    ///destination
    ArgumentSyntaxSugar<ArgumentExtractor<CharArgument> > h(wchar_t&);
    ///Returns a wrapped NumericArgument storing the integer into the given
    ///destination.
    ArgumentSyntaxSugar<ArgumentExtractor<NumericArgument> > n(signed&);
    ///Returns a wrapped ArithmeticArgument storing the Command* into the given
    ///destination.
    ArgumentSyntaxSugar<ArgumentExtractor<ArithmeticArgument> > a(Command*&);
    ///Returns a wrapped SectionArgument storing the Section into the given
    ///destination.
    ArgumentSyntaxSugar<ArgumentExtractor<SectionArgument> > s(Section&);
    ///Returns a wrapped SentinelStringArgument storing the string into the
    ///given destination and terminating on the given character.
    ArgumentSyntaxSugar<ArgumentExtractor<SentinelStringArgument> >
    to(std::wstring&, wchar_t);
    ///Returns a wrapped AlnumStringArgument storing the string into the given
    ///destination.
    ArgumentSyntaxSugar<ArgumentExtractor<AlnumStringArgument> >
    an(std::wstring&);
    ///Returns a wrapped NonSectionStringArgument storing the string into the
    ///given destination.
    ArgumentSyntaxSugar<ArgumentExtractor<NonSectionStringArgument> >
    ns(std::wstring&);
    ///Returns an ExactCharacterArgument matching the given character. The
    ///extracted boolean is dropped.
    ArgumentSyntaxSugar<ArgumentExtractor<ExactCharacterArgument> > x(wchar_t);
    ///Returns an ExactCharacterArgument storing the boolean into the given
    ///location and matching the given character.
    ArgumentSyntaxSugar<ArgumentExtractor<ExactCharacterArgument> >
    x(bool&, wchar_t);
    ///Returns a CommandArgument storing the command into the given destination.
    ArgumentSyntaxSugar<ArgumentExtractor<CommandArgument> > c(Command*&);

    /**
     * Tries to match the given compound argument agains the input. If matching
     * and parsing is successful, returns true. Otherwise, prints a diagnostic
     * and returns false.
     */
    template<typename T>
    bool operator[](T& t) {
      if (!t.match()) {
        diagnosticUnmatched();
        return false;
      }
      if (!t.get()) {
        diagnosticParseError();
        return false;
      }
      return true;
    }

  private:
    void diagnosticUnmatched() const;
    void diagnosticParseError() const;
  };
}

#endif /* ARGUMENT_HXX_ */
<commit_msg>Fix issues in argument.hxx.<commit_after>#ifndef ARGUMENT_HXX_
#define ARGUMENT_HXX_

#include <string>

namespace tglng {
  class Command;
  class Interpreter;

  /**
   * Encapsulates the data and basic semantics for argument extraction.
   */
  class Argument {
  public:
    Interpreter& interp;
    const std::wstring& text;
    unsigned& offset;

  protected:
    Command*& left;

    Argument(Interpreter&, const std::wstring&, unsigned&, Command*&);

  public:
    /**
     * Tests whether the string matches.
     *
     * Default advances past all whitespace and then returns whether a
     * non-whitespace character was found.
     */
    bool match();
  };

#define CTOR(clazz) \
  clazz##Argument(Interpreter& i, const std::wstring& s, \
                  unsigned& u, Command*& c)              \
  : Argument(i,s,u,c) {}

  /**
   * Extracts a single non-whitespace character as an argument.
   */
  class CharArgument: public Argument {
  public:
    CTOR(Char)
    typedef wchar_t get_t;
    bool get(get_t&);
  };

  /**
   * Extracts a numeric literal as an argument.
   */
  class NumericArgument: public Argument {
  public:
    CTOR(Numeric)
    typedef signed get_t;
    bool get(get_t&);
    bool match();
  };

  /**
   * Extracts and parses a single Command as an argument.
   */
  class CommandArgument: public Argument {
  public:
    CTOR(Command)
    typedef Command* get_t;
    bool get(get_t&);
  };

  /**
   * Defines the type of a section arguement.
   */
  struct Section {
    Command* left, * right;
  };
  /**
   * Extracts a Section argument type from input.
   */
  class SectionArgument: public Argument {
  public:
    CTOR(Section)
    typedef Section get_t;
    bool get(get_t&);
    bool match();
  };

  /**
   * Extracts a string from point to the given sentinal. Does not match if the
   * sentinel is not found.
   */
  class SentinelStringArgument: public Argument {
    wchar_t sentinel;

  public:
    SentinelStringArgument(Interpreter&, const std::wstring&, unsigned&,
                           Command*&, wchar_t);
    typedef std::wstring get_t;
    bool get(get_t&);
    bool match();
  };

  /**
   * Extracts a non-empty string of alphanumeric characters starting at point
   * and continuing to (but not including) the first non-alphanumeric character
   * or end of input.
   */
  class AlnumStringArgument: public Argument {
  public:
    CTOR(AlnumString)
    typedef std::wstring get_t;
    bool get(get_t&);
    bool match();
  };

  /**
   * Extracts a non-empty string of characters starting at point and continuing
   * to (but not including) the first whitespace character, the first character
   * which is a valid section specifier, or end of input.
   */
  class NonSectionStringArgument: public Argument {
  public:
    CTOR(NonSectionString)
    typedef std::wstring get_t;
    bool get(get_t&);
    bool match();
  };

  /**
   * Extracts either a single parsed command, or a literal number which is
   * wrapped in a command and returned.
   */
  class ArithmeticArgument: public Argument {
  public:
    CTOR(Arithmetic)
    typedef Command* get_t;
    bool get(get_t&);
  };

  /**
   * Matches a single character. If matched, extracts true to a boolean.
   */
  class ExactCharacterArgument: public Argument {
    wchar_t expect;

  public:
    ExactCharacterArgument(Interpreter&, const std::wstring&, unsigned&,
                           Command*&, wchar_t);
    typedef bool get_t;
    bool get(get_t&);
    bool match();
  };
#undef CTOR

  /**
   * Wraps the Argument classes to store the destination reference within.
   */
  template<typename T>
  class ArgumentExtractor {
  protected:
    T it;
    typename T::get_t& dst;

  public:
    ArgumentExtractor(const T& t, typename T::get_t& d)
    : it(t), dst(d)
    { }

    bool match() { return it.match(); }
    bool get() { return it.get(dst); }

    Interpreter& interp() { return it.interp; }
    const std::wstring& text() { return it.text; }
    unsigned offset() { return it.offset; }
  };

  /**
   * Chains two ArgumentExtractor-compatible classes into one.
   */
  template<typename First, typename Rest>
  class ArgumentSequence {
    First first;
    Rest rest;

  public:
    ArgumentSequence(const First& f, const Rest& r)
    : first(f), rest(r) {}

    bool match() { return first.match(); }
    bool get() {
      if (!first.get()) return false;
      if (!rest.match()) {
        interp().error(L"Could not match next part of argument sequence.",
                       text(), offset());
        return false;
      }
      return rest.get();
    }

    Interpreter& interp() { return first.interp(); }
    const std::wstring& text() { return first.text(); }
    unsigned offset() { return first.offset(); }
  };

  /**
   * Tries to match with one ArgumentExtractor-compatible class, then falls
   * back on the other.
   */
  template<typename First, typename Rest>
  class ArgumentOptions {
    First first;
    Rest rest;

  public:
    ArgumentOptions(const First& f, const Rest& r)
    : first(f), rest(r) {}

    bool match() { return first.match() || rest.match(); }
    bool get() { return first.match()? first.get() : rest.get(); }

    Interpreter& interp() { return first.interp(); }
    const std::wstring& text() { return first.text(); }
    unsigned offset() { return first.offset(); }
  };

  /**
   * Wraps an ArgumentExtractor-compatible class to make it optional.
   */
  template<typename T>
  class OptionalArgument {
    T it;

  public:
    OptionalArgument(const T& t) : it(t) {}

    bool match() { return true; }
    bool get() { return !it.match() || it.get(); }

    Interpreter& interp() { return it.interp(); }
    const std::wstring& text() { return it.text(); }
    unsigned offset() { return it.offset(); }
  };

  /**
   * Adds operators to ArgumentExtractor which give a nice syntax sugar for
   * compound arguments:
   *
   *   arg1, arg2  -> ArgumentSequence<arg1,arg2>
   *   arg1 | arg2 -> ArgumentOptions<arg1,arg2>
   *   -arg1       -> OptionalArgument<arg1>
   */
  template<typename Contained>
  class ArgumentSyntaxSugar {
  public:
    Contained it;

    typedef Contained contained_t;

    ArgumentSyntaxSugar(const Contained& t)
    : it(t) {}

    bool match() { return it.match(); }
    bool get() { return it.get(); }

    template<typename Next>
    ArgumentSyntaxSugar<ArgumentSequence<Contained,
                                         typename Next::contained_t> >
    operator,(const Next& next) const {
      return
        ArgumentSyntaxSugar<
          ArgumentSequence<
            Contained,
            typename Next::contained_t> >(
              ArgumentSequence<Contained,typename Next::contained_t>(it,
                                                                     next.it));
    }

    template<typename Other>
    ArgumentSyntaxSugar<ArgumentOptions<Contained,
                                        typename Other::contained_t> >
    operator|(const Other& other) const {
      return
        ArgumentSyntaxSugar<
          ArgumentOptions<
            Contained,
            typename Other::contained_t> >(
              ArgumentOptions<Contained,
                              typename Other::contained_t>(it, other.it));
    }

    ArgumentSyntaxSugar<OptionalArgument<Contained> >
    operator-() const {
      return ArgumentSyntaxSugar<OptionalArgument<Contained> >(
        OptionalArgument<Contained>(it));
    }
  };

  /**
   * Simplifies the construction and testing of argument extractors.
   */
  class ArgumentParser {
    Interpreter& interp;
    const std::wstring& text;
    unsigned& offset;
    unsigned startingOffset;
    Command*& left;

  public:
    /**
     * Creates an ArgumentParser with the given arguments required for all
     * Arguments.
     */
    ArgumentParser(Interpreter&, const std::wstring&,
                   unsigned&, Command*& left);

    ///Returns a wrapped CharArgument which discards its character.
    ArgumentSyntaxSugar<ArgumentExtractor<CharArgument> > h();
    ///Returns a wrapped CharArgument storing the character into the given
    ///destination
    ArgumentSyntaxSugar<ArgumentExtractor<CharArgument> > h(wchar_t&);
    ///Returns a wrapped NumericArgument storing the integer into the given
    ///destination.
    ArgumentSyntaxSugar<ArgumentExtractor<NumericArgument> > n(signed&);
    ///Returns a wrapped ArithmeticArgument storing the Command* into the given
    ///destination.
    ArgumentSyntaxSugar<ArgumentExtractor<ArithmeticArgument> > a(Command*&);
    ///Returns a wrapped SectionArgument storing the Section into the given
    ///destination.
    ArgumentSyntaxSugar<ArgumentExtractor<SectionArgument> > s(Section&);
    ///Returns a wrapped SentinelStringArgument storing the string into the
    ///given destination and terminating on the given character.
    ArgumentSyntaxSugar<ArgumentExtractor<SentinelStringArgument> >
    to(std::wstring&, wchar_t);
    ///Returns a wrapped AlnumStringArgument storing the string into the given
    ///destination.
    ArgumentSyntaxSugar<ArgumentExtractor<AlnumStringArgument> >
    an(std::wstring&);
    ///Returns a wrapped NonSectionStringArgument storing the string into the
    ///given destination.
    ArgumentSyntaxSugar<ArgumentExtractor<NonSectionStringArgument> >
    ns(std::wstring&);
    ///Returns an ExactCharacterArgument matching the given character. The
    ///extracted boolean is dropped.
    ArgumentSyntaxSugar<ArgumentExtractor<ExactCharacterArgument> > x(wchar_t);
    ///Returns an ExactCharacterArgument storing the boolean into the given
    ///location and matching the given character.
    ArgumentSyntaxSugar<ArgumentExtractor<ExactCharacterArgument> >
    x(bool&, wchar_t);
    ///Returns a CommandArgument storing the command into the given destination.
    ArgumentSyntaxSugar<ArgumentExtractor<CommandArgument> > c(Command*&);

    /**
     * Tries to match the given compound argument agains the input. If matching
     * and parsing is successful, returns true. Otherwise, prints a diagnostic
     * and returns false.
     */
    template<typename T>
    bool operator[](const T& t_) {
      T t(t_);
      if (!t.match()) {
        diagnosticUnmatched();
        return false;
      }
      if (!t.get()) {
        diagnosticParseError();
        return false;
      }
      return true;
    }

  private:
    void diagnosticUnmatched() const;
    void diagnosticParseError() const;
  };
}

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


<commit_before>/*
===========================================================================
Copyright (C) 2012-2013 Unvanquished Developers

This file is part of Daemon source code.

Daemon Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Daemon Source Code 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with Daemon Source Code.  If not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/

// Unicode & UTF-8 handling

#include "q_shared.h"
#include "q_unicode.h"

// never returns more than 4
int Q_UTF8_Width( const char *str )
{
  int                 ewidth;
  const unsigned char *s = (const unsigned char *)str;

  if( !str )
    return 0;

  if     (               *s <= 0x7F )
    ewidth = 0;
  else if( 0xC2 <= *s && *s <= 0xDF )
    ewidth = 1;
  else if( 0xE0 <= *s && *s <= 0xEF )
    ewidth = 2;
  else if( 0xF0 <= *s && *s <= 0xF4 )
    ewidth = 3;
  else
    ewidth = 0;

  for( ; *s && ewidth > 0; s++, ewidth-- );

  return s - (const unsigned char *)str + 1;
}

int Q_UTF8_WidthCP( int ch )
{
	if ( ch <=   0x007F ) { return 1; }
	if ( ch <=   0x07FF ) { return 2; }
	if ( ch <=   0xFFFF ) { return 3; }
	if ( ch <= 0x10FFFF ) { return 4; }
	return 0;
}

int Q_UTF8_Strlen( const char *str )
{
  int l = 0;

  while( *str )
  {
    l++;

    str += Q_UTF8_Width( str );
  }

  return l;
}

bool Q_UTF8_ContByte( char c )
{
  return (unsigned char )0x80 <= (unsigned char)c && (unsigned char)c <= (unsigned char )0xBF;
}

static bool getbit(const unsigned char *p, int pos)
{
  p   += pos / 8;
  pos %= 8;

  return (*p & (1 << (7 - pos))) != 0;
}

static void setbit(unsigned char *p, int pos, bool on)
{
  p   += pos / 8;
  pos %= 8;

  if( on )
    *p |= 1 << (7 - pos);
  else
    *p &= ~(1 << (7 - pos));
}

static void shiftbitsright(unsigned char *p, unsigned long num, unsigned long by)
{
  int step, off;
  unsigned char *e;

  if( by >= num )
  {
    for( ; num > 8; p++, num -= 8 )
      *p = 0;

    *p &= (~0x00) >> num;

    return;
  }

  step = by / 8;
  off  = by % 8;

  for( e = p + (num + 7) / 8 - 1; e > p + step; e-- )
    *e = (*(e - step) >> off) | (*(e - step - 1) << (8 - off));

  *e = *(e - step) >> off;

  for( e = p; e < p + step; e++ )
    *e = 0;
}

unsigned long Q_UTF8_CodePoint( const char *str )
{
  unsigned i, j;
  int n = 0;
  unsigned size = Q_UTF8_Width( str );
  unsigned long codepoint = 0;
  unsigned char *p = (unsigned char *) &codepoint;

  if( size > sizeof( codepoint ) )
    size = sizeof( codepoint );
  else if( size < 1 )
    size = 1;

  for( i = (size > 1 ? size + 1 : 1); i < 8; i++ )
    setbit(p, n++, getbit((const unsigned char *)str, i));
  for( i = 1; i < size; i++ )
    for( j = 2; j < 8; j++ )
      setbit(p, n++, getbit(((const unsigned char *)str) + i, j));

  /*
  if( n > 8 * sizeof(codepoint) )
  {
		Sys::Drop( "Q_UTF8_CodePoint: overflow caught" );

    return 0;
  }
  */

  shiftbitsright(p, 8 * sizeof(codepoint), 8 * sizeof(codepoint) - n);

#ifndef Q3_BIG_ENDIAN
  for( i = 0; i < sizeof(codepoint) / 2; i++ )
  {
    p[i] ^= p[sizeof(codepoint) - 1 - i];
    p[sizeof(codepoint) - 1 - i] ^= p[i];
    p[i] ^= p[sizeof(codepoint) - 1 - i];
  }
#endif

  return codepoint;
}

char *Q_UTF8_Encode( unsigned long codepoint )
{
  static char sbuf[2][5];
  static int index = 0;
  char *buf = sbuf[index++ & 1];

  if     (                        codepoint <= 0x007F )
  {
    buf[0] = codepoint;
    buf[1] = 0;
  }
  else if( 0x0080 <= codepoint && codepoint <= 0x07FF )
  {
    buf[0] = 0xC0 | ((codepoint & 0x07C0) >> 6);
    buf[1] = 0x80 | (codepoint & 0x003F);
    buf[2] = 0;
  }
  else if( 0x0800 <= codepoint && codepoint <= 0xFFFF )
  {
    buf[0] = 0xE0 | ((codepoint & 0xF000) >> 12);
    buf[1] = 0x80 | ((codepoint & 0x0FC0) >> 6);
    buf[2] = 0x80 | (codepoint & 0x003F);
    buf[3] = 0;
  }
  else if( 0x010000 <= codepoint && codepoint <= 0x10FFFF )
  {
    buf[0] = 0xF0 | ((codepoint & 0x1C0000) >> 18);
    buf[1] = 0x80 | ((codepoint & 0x03F000) >> 12);
    buf[2] = 0x80 | ((codepoint & 0x000FC0) >> 6);
    buf[3] = 0x80 | (codepoint & 0x00003F);
    buf[4] = 0;
  }
  else
  {
    buf[0] = 0;
  }

  return buf;
}

#include "unicode_data.h"

static int CmpHalfOpenInterval( const void *chp, const void *memb )
{
  unsigned ch = *(unsigned *)chp;
  const ucs2_pair_t *item = (ucs2_pair_t*) memb;

  return ( ch < item->c1 ) ? -1 : ( ch >= item->c2 ) ? 1 : 0;
}

static bool UnicodeRangeSearch( int ch, const ucs2_pair_t* array, size_t length )
{
	return !!bsearch(&ch, array, length, sizeof(array[0]), CmpHalfOpenInterval);
}

bool Q_Unicode_IsAlpha ( int ch ) {
	return UnicodeRangeSearch( ch, uc_prop_alphabetic, ARRAY_LEN( uc_prop_alphabetic ) );
}

bool Q_Unicode_IsUpper ( int ch ) {
	return UnicodeRangeSearch( ch, uc_prop_uppercase, ARRAY_LEN( uc_prop_uppercase ) );
}

bool Q_Unicode_IsLower ( int ch ) {
	return UnicodeRangeSearch( ch, uc_prop_lowercase, ARRAY_LEN( uc_prop_lowercase ) );
}

bool Q_Unicode_IsIdeo ( int ch ) {
	return UnicodeRangeSearch( ch, uc_prop_ideographic, ARRAY_LEN( uc_prop_ideographic ) );
}

bool Q_Unicode_IsDigit ( int ch ) {
	return UnicodeRangeSearch( ch, uc_prop_digit, ARRAY_LEN( uc_prop_digit ) );
}

bool Q_Unicode_IsAlphaOrIdeo( int ch )
{
  return Q_Unicode_IsAlpha( ch ) || Q_Unicode_IsIdeo( ch );
}

bool Q_Unicode_IsAlphaOrIdeoOrDigit( int ch )
{
  return Q_Unicode_IsAlpha( ch ) || Q_Unicode_IsIdeo( ch ) || Q_Unicode_IsDigit( ch );
}

bool Q_Unicode_IsPrivateUse( int ch )
{
    return (0xE000 <= ch && ch <= 0xF8FF)
        || (0xF0000 <= ch && ch <= 0xFFFFF)
        || (0x100000 <= ch && ch <= 0x10FFFF);
}

static int CmpFirstElement( const void *chp, const void *memb )
{
  unsigned ch = *(unsigned *)chp;
  const ucs2_pair_t *item = (ucs2_pair_t*) memb;

  return ( ch < item->c1 ) ? -1 : ( ch > item->c1 ) ? 1 : 0;
}

static int UnicodeCaseLookup( int ch, const ucs2_pair_t* array, size_t length )
{
	const ucs2_pair_t *converted = (ucs2_pair_t*) bsearch( &ch, array, length,
		                                                   sizeof( array[ 0 ] ), CmpFirstElement );
	return converted ? converted->c2 : ch;
}

int Q_Unicode_ToUpper( int ch )
{
	return UnicodeCaseLookup( ch, uc_case_upper, ARRAY_LEN(uc_case_upper) );
}

int Q_Unicode_ToLower( int ch )
{
	return UnicodeCaseLookup( ch, uc_case_lower, ARRAY_LEN(uc_case_lower) );
}
<commit_msg>[ub] Signed right shift is undefined behavior<commit_after>/*
===========================================================================
Copyright (C) 2012-2013 Unvanquished Developers

This file is part of Daemon source code.

Daemon Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Daemon Source Code 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with Daemon Source Code.  If not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/

// Unicode & UTF-8 handling

#include "q_shared.h"
#include "q_unicode.h"

// never returns more than 4
int Q_UTF8_Width( const char *str )
{
  int                 ewidth;
  const unsigned char *s = (const unsigned char *)str;

  if( !str )
    return 0;

  if     (               *s <= 0x7F )
    ewidth = 0;
  else if( 0xC2 <= *s && *s <= 0xDF )
    ewidth = 1;
  else if( 0xE0 <= *s && *s <= 0xEF )
    ewidth = 2;
  else if( 0xF0 <= *s && *s <= 0xF4 )
    ewidth = 3;
  else
    ewidth = 0;

  for( ; *s && ewidth > 0; s++, ewidth-- );

  return s - (const unsigned char *)str + 1;
}

int Q_UTF8_WidthCP( int ch )
{
	if ( ch <=   0x007F ) { return 1; }
	if ( ch <=   0x07FF ) { return 2; }
	if ( ch <=   0xFFFF ) { return 3; }
	if ( ch <= 0x10FFFF ) { return 4; }
	return 0;
}

int Q_UTF8_Strlen( const char *str )
{
  int l = 0;

  while( *str )
  {
    l++;

    str += Q_UTF8_Width( str );
  }

  return l;
}

bool Q_UTF8_ContByte( char c )
{
  return (unsigned char )0x80 <= (unsigned char)c && (unsigned char)c <= (unsigned char )0xBF;
}

static bool getbit(const unsigned char *p, int pos)
{
  p   += pos / 8;
  pos %= 8;

  return (*p & (1 << (7 - pos))) != 0;
}

static void setbit(unsigned char *p, int pos, bool on)
{
  p   += pos / 8;
  pos %= 8;

  if( on )
    *p |= 1 << (7 - pos);
  else
    *p &= ~(1 << (7 - pos));
}

static void shiftbitsright(unsigned char *p, unsigned long num, unsigned long by)
{
  int step, off;
  unsigned char *e;

  if( by >= num )
  {
    for( ; num > 8; p++, num -= 8 )
      *p = 0;

    *p &= (unsigned long)(~0x00) >> num;

    return;
  }

  step = by / 8;
  off  = by % 8;

  for( e = p + (num + 7) / 8 - 1; e > p + step; e-- )
    *e = (*(e - step) >> off) | (*(e - step - 1) << (8 - off));

  *e = *(e - step) >> off;

  for( e = p; e < p + step; e++ )
    *e = 0;
}

unsigned long Q_UTF8_CodePoint( const char *str )
{
  unsigned i, j;
  int n = 0;
  unsigned size = Q_UTF8_Width( str );
  unsigned long codepoint = 0;
  unsigned char *p = (unsigned char *) &codepoint;

  if( size > sizeof( codepoint ) )
    size = sizeof( codepoint );
  else if( size < 1 )
    size = 1;

  for( i = (size > 1 ? size + 1 : 1); i < 8; i++ )
    setbit(p, n++, getbit((const unsigned char *)str, i));
  for( i = 1; i < size; i++ )
    for( j = 2; j < 8; j++ )
      setbit(p, n++, getbit(((const unsigned char *)str) + i, j));

  /*
  if( n > 8 * sizeof(codepoint) )
  {
		Sys::Drop( "Q_UTF8_CodePoint: overflow caught" );

    return 0;
  }
  */

  shiftbitsright(p, 8 * sizeof(codepoint), 8 * sizeof(codepoint) - n);

#ifndef Q3_BIG_ENDIAN
  for( i = 0; i < sizeof(codepoint) / 2; i++ )
  {
    p[i] ^= p[sizeof(codepoint) - 1 - i];
    p[sizeof(codepoint) - 1 - i] ^= p[i];
    p[i] ^= p[sizeof(codepoint) - 1 - i];
  }
#endif

  return codepoint;
}

char *Q_UTF8_Encode( unsigned long codepoint )
{
  static char sbuf[2][5];
  static int index = 0;
  char *buf = sbuf[index++ & 1];

  if     (                        codepoint <= 0x007F )
  {
    buf[0] = codepoint;
    buf[1] = 0;
  }
  else if( 0x0080 <= codepoint && codepoint <= 0x07FF )
  {
    buf[0] = 0xC0 | ((codepoint & 0x07C0) >> 6);
    buf[1] = 0x80 | (codepoint & 0x003F);
    buf[2] = 0;
  }
  else if( 0x0800 <= codepoint && codepoint <= 0xFFFF )
  {
    buf[0] = 0xE0 | ((codepoint & 0xF000) >> 12);
    buf[1] = 0x80 | ((codepoint & 0x0FC0) >> 6);
    buf[2] = 0x80 | (codepoint & 0x003F);
    buf[3] = 0;
  }
  else if( 0x010000 <= codepoint && codepoint <= 0x10FFFF )
  {
    buf[0] = 0xF0 | ((codepoint & 0x1C0000) >> 18);
    buf[1] = 0x80 | ((codepoint & 0x03F000) >> 12);
    buf[2] = 0x80 | ((codepoint & 0x000FC0) >> 6);
    buf[3] = 0x80 | (codepoint & 0x00003F);
    buf[4] = 0;
  }
  else
  {
    buf[0] = 0;
  }

  return buf;
}

#include "unicode_data.h"

static int CmpHalfOpenInterval( const void *chp, const void *memb )
{
  unsigned ch = *(unsigned *)chp;
  const ucs2_pair_t *item = (ucs2_pair_t*) memb;

  return ( ch < item->c1 ) ? -1 : ( ch >= item->c2 ) ? 1 : 0;
}

static bool UnicodeRangeSearch( int ch, const ucs2_pair_t* array, size_t length )
{
	return !!bsearch(&ch, array, length, sizeof(array[0]), CmpHalfOpenInterval);
}

bool Q_Unicode_IsAlpha ( int ch ) {
	return UnicodeRangeSearch( ch, uc_prop_alphabetic, ARRAY_LEN( uc_prop_alphabetic ) );
}

bool Q_Unicode_IsUpper ( int ch ) {
	return UnicodeRangeSearch( ch, uc_prop_uppercase, ARRAY_LEN( uc_prop_uppercase ) );
}

bool Q_Unicode_IsLower ( int ch ) {
	return UnicodeRangeSearch( ch, uc_prop_lowercase, ARRAY_LEN( uc_prop_lowercase ) );
}

bool Q_Unicode_IsIdeo ( int ch ) {
	return UnicodeRangeSearch( ch, uc_prop_ideographic, ARRAY_LEN( uc_prop_ideographic ) );
}

bool Q_Unicode_IsDigit ( int ch ) {
	return UnicodeRangeSearch( ch, uc_prop_digit, ARRAY_LEN( uc_prop_digit ) );
}

bool Q_Unicode_IsAlphaOrIdeo( int ch )
{
  return Q_Unicode_IsAlpha( ch ) || Q_Unicode_IsIdeo( ch );
}

bool Q_Unicode_IsAlphaOrIdeoOrDigit( int ch )
{
  return Q_Unicode_IsAlpha( ch ) || Q_Unicode_IsIdeo( ch ) || Q_Unicode_IsDigit( ch );
}

bool Q_Unicode_IsPrivateUse( int ch )
{
    return (0xE000 <= ch && ch <= 0xF8FF)
        || (0xF0000 <= ch && ch <= 0xFFFFF)
        || (0x100000 <= ch && ch <= 0x10FFFF);
}

static int CmpFirstElement( const void *chp, const void *memb )
{
  unsigned ch = *(unsigned *)chp;
  const ucs2_pair_t *item = (ucs2_pair_t*) memb;

  return ( ch < item->c1 ) ? -1 : ( ch > item->c1 ) ? 1 : 0;
}

static int UnicodeCaseLookup( int ch, const ucs2_pair_t* array, size_t length )
{
	const ucs2_pair_t *converted = (ucs2_pair_t*) bsearch( &ch, array, length,
		                                                   sizeof( array[ 0 ] ), CmpFirstElement );
	return converted ? converted->c2 : ch;
}

int Q_Unicode_ToUpper( int ch )
{
	return UnicodeCaseLookup( ch, uc_case_upper, ARRAY_LEN(uc_case_upper) );
}

int Q_Unicode_ToLower( int ch )
{
	return UnicodeCaseLookup( ch, uc_case_lower, ARRAY_LEN(uc_case_lower) );
}
<|endoftext|>