コード例 #1
0
ファイル: SvgUtil.cpp プロジェクト: kolyden/mirror
NAMESPACE_UPP

#include "SvgInternal.h"

Color SvgParser::GetTextColor(const String& color) {
    struct Svg_color {
        const char *name;
        byte r, g, b;
    } colors[] = {
        {"aliceblue", 240, 248, 255},
        {"antiquewhite", 250, 235, 215},
        {"aqua", 0, 255, 255},
        {"aquamarine", 127, 255, 212},
        {"azure", 240, 255, 255},
        {"beige", 245, 245, 220},
        {"bisque", 255, 228, 196},
        {"black", 0, 0, 0},
        {"blanchedalmond", 255, 235, 205},
        {"blue", 0, 0, 255},
        {"blueviolet", 138, 43, 226},
        {"brown", 165, 42, 42},
        {"burlywood", 222, 184, 135},
        {"cadetblue", 95, 158, 160},
        {"chartreuse", 127, 255, 0},
        {"chocolate", 210, 105, 30},
        {"coral", 255, 127, 80},
        {"cornflowerblue", 100, 149, 237},
        {"cornsilk", 255, 248, 220},
        {"crimson", 237, 164, 61},
        {"cyan", 0, 255, 255},
        {"darkblue", 0, 0, 139},
        {"darkcyan", 0, 139, 139},
        {"darkgoldenrod", 184, 134, 11},
        {"darkgray", 169, 169, 169},
        {"darkgreen", 0, 100, 0},
        {"darkkhaki", 189, 183, 107},
        {"darkmagenta", 139, 0, 139},
        {"darkolivegreen", 85, 107, 47},
        {"darkorange", 255, 140, 0},
        {"darkorchid", 153, 50, 204},
        {"darkred", 139, 0, 0},
        {"darksalmon", 233, 150, 122},
        {"darkseagreen", 143, 188, 143},
        {"darkslateblue", 72, 61, 139},
        {"darkslategray", 47, 79, 79},
        {"darkturquoise", 0, 206, 209},
        {"darkviolet", 148, 0, 211},
        {"deeppink", 255, 20, 147},
        {"deepskyblue", 0, 191, 255},
        {"dimgray", 105, 105, 105},
        {"dodgerblue", 30, 144, 255},
        {"firebrick", 178, 34, 34},
        {"floralwhite", 255, 250, 240},
        {"forestgreen", 34, 139, 34},
        {"fuchsia", 255, 0, 255},
        {"gainsboro", 220, 220, 220},
        {"ghostwhite", 248, 248, 255},
        {"gold", 255, 215, 0},
        {"goldenrod", 218, 165, 32},
        {"gray", 128, 128, 128},
        {"green", 0, 128, 0},
        {"greenyellow", 173, 255, 47},
        {"honeydew", 240, 255, 240},
        {"hotpink", 255, 105, 180},
        {"indianred", 205, 92, 92},
        {"indigo", 75, 0, 130},
        {"ivory", 255, 255, 240},
        {"khaki", 240, 230, 140},
        {"lavender", 230, 230, 250},
        {"lavenderblush", 255, 240, 245},
        {"lawngreen", 124, 252, 0},
        {"lemonchiffon", 255, 250, 205},
        {"lightblue", 173, 216, 230},
        {"lightcoral", 240, 128, 128},
        {"lightcyan", 224, 255, 255},
        {"lightgoldenrodyellow", 250, 250, 210},
        {"lightgrey", 211, 211, 211},
        {"lightgreen", 144, 238, 144},
        {"lightpink", 255, 182, 193},
        {"lightsalmon", 255, 160, 122},
        {"lightseagreen", 32, 178, 170},
        {"lightskyblue", 135, 206, 250},
        {"lightslategray", 119, 136, 153},
        {"lightsteelblue", 176, 196, 222},
        {"lightyellow", 255, 255, 224},
        {"lime", 0, 255, 0},
        {"limegreen", 50, 205, 50},
        {"linen", 250, 240, 230},
        {"magenta", 255, 0, 255},
        {"maroon", 128, 0, 0},
        {"mediumaquamarine", 102, 205, 170},
        {"mediumblue", 0, 0, 205},
        {"mediumorchid", 186, 85, 211},
        {"mediumpurple", 147, 112, 219},
        {"mediumseagreen", 60, 179, 113},
        {"mediumslateblue", 123, 104, 238},
        {"mediumspringgreen", 0, 250, 154},
        {"mediumturquoise", 72, 209, 204},
        {"mediumvioletred", 199, 21, 133},
        {"midnightblue", 25, 25, 112},
        {"mintcream", 245, 255, 250},
        {"mistyrose", 255, 228, 225},
        {"moccasin", 255, 228, 181},
        {"navajowhite", 255, 222, 173},
        {"navy", 0, 0, 128},
        {"oldlace", 253, 245, 230},
        {"olive", 128, 128, 0},
        {"olivedrab", 107, 142, 35},
        {"orange", 255, 165, 0},
        {"orangered", 255, 69, 0},
        {"orchid", 218, 112, 214},
        {"palegoldenrod", 238, 232, 170},
        {"palegreen", 152, 251, 152},
        {"paleturquoise", 175, 238, 238},
        {"palevioletred", 219, 112, 147},
        {"papayawhip", 255, 239, 213},
        {"peachpuff", 255, 218, 185},
        {"peru", 205, 133, 63},
        {"pink", 255, 192, 203},
        {"plum", 221, 160, 221},
        {"powderblue", 176, 224, 230},
        {"purple", 128, 0, 128},
        {"red", 255, 0, 0},
        {"rosybrown", 188, 143, 143},
        {"royalblue", 65, 105, 225},
        {"saddlebrown", 139, 69, 19},
        {"salmon", 250, 128, 114},
        {"sandybrown", 244, 164, 96},
        {"seagreen", 46, 139, 87},
        {"seashell", 255, 245, 238},
        {"sienna", 160, 82, 45},
        {"silver", 192, 192, 192},
        {"skyblue", 135, 206, 235},
        {"slateblue", 106, 90, 205},
        {"slategray", 112, 128, 144},
        {"snow", 255, 250, 250},
        {"springgreen", 0, 255, 127},
        {"steelblue", 70, 130, 180},
        {"tan", 210, 180, 140},
        {"teal", 0, 128, 128},
        {"thistle", 216, 191, 216},
        {"tomato", 255, 99, 71},
        {"turquoise", 64, 224, 208},
        {"violet", 238, 130, 238},
        {"wheat", 245, 222, 179},
        {"white", 255, 255, 255},
        {"whitesmoke", 245, 245, 245},
        {"yellow", 255, 255, 0},
        {"yellowgreen", 154, 205, 50},
    };

    static VectorMap<String, Color> map;
    ONCELOCK {
        for(int i = 0; i < __countof(colors); i++)
            map.Add(colors[i].name, Color(colors[i].r, colors[i].g, colors[i].b));
    }

    return map.Get(color, map.Get(ToLower(color), Null));
}
コード例 #2
0
ファイル: strutils.hpp プロジェクト: myd7349/Ongoing-Study
 size_t operator()(const std::basic_string<CharT> &key) const {
     return hash_(ToLower(key));
 }
コード例 #3
0
ファイル: match.c プロジェクト: Gryllida/atheme
int match(const char *mask, const char *name)
{
	const unsigned char *m = (const unsigned char *)mask, *n = (const unsigned char *)name;
	const char *ma = mask, *na = name;
	int wild = 0, q = 0, calls = 0;

	if (!mask || !name)
		return 1;

	/* if the mask is "*", it matches everything */
	if ((*m == '*') && (*(m + 1) == '\0'))
		return 0;

	while (1)
	{
#ifdef  MAX_ITERATIONS
		if (calls++ > MAX_ITERATIONS)
			break;
#endif

		if (*m == '*')
		{
			while (*m == '*')
				m++;
			wild = 1;
			ma = (const char *)m;
			na = (const char *)n;
		}

		if (!*m)
		{
			if (!*n)
				return 0;
			for (m--; (m > (const unsigned char *) mask) && (*m == '?' || *m == '&' || *m == '#'); m--)
				;
			if ((m > (const unsigned char *) mask) && (*m == '*') && (m[-1] != '\\'))
				return 0;
			if (!wild)
				return 1;
			m = (const unsigned char *) ma;
			n = (const unsigned char *)++ na;
		}
		else if (!*n)
			return 1;
		if ((*m == '\\') && ((m[1] == '*') || (m[1] == '?') || (m[1] == '&') || (m[1] == '#') || (m[1] == '%')))
		{
			m++;
			q = 1;
		}
		else
			q = 0;

		if ((ToLower(*m) != ToLower(*n)) && (((*m != '?') && !(*m == '&' && IsAlpha(*n)) && !(*m == '#' && IsDigit(*n)) && !(*m == '%' && IsNon(*n))) || q))
		{
			if (!wild)
				return 1;
			m = (const unsigned char *) ma;
			n = (const unsigned char *)++ na;
		}
		else
		{
			if (*m)
				m++;
			if (*n)
				n++;
		}
	}

	return 1;
}
コード例 #4
0
ファイル: GSCrc.cpp プロジェクト: Asmodean-/pcsx2
// The exclusions list is a comma separated list of: the word "all" and/or CRCs in standard hex notation (0x and 8 digits with leading 0's if required).
// The list is case insensitive and order insensitive.
// E.g. Disable all CRC hacks:          CrcHacksExclusions=all
// E.g. Disable hacks for these CRCs:   CrcHacksExclusions=0x0F0C4A9C, 0x0EE5646B, 0x7ACF7E03
bool IsCrcExcluded(string exclusionList, uint32 crc)
{
	string target = format( "0x%08x", crc );
	exclusionList = ToLower( exclusionList );
	return ( exclusionList.find( target ) != string::npos || exclusionList.find( "all" ) != string::npos );
}
コード例 #5
0
ファイル: match.c プロジェクト: BackupTheBerlios/shadowircd
/* match()
 * 
 *  Compare if a given string (name) matches the given
 *  mask (which can contain wild cards: '*' - match any
 *  number of chars, '?' - match any single character.
 *
 *      return  1, if match
 *              0, if no match
 *
 *  Originally by Douglas A Lewis ([email protected])
 */
#define MATCH_MAX_CALLS 512  /* ACK! This dies when it's less that this
                                and we have long lines to parse */
int
match(const char *mask, const char *name)
{
  const unsigned char* m = (const unsigned char*)  mask;
  const unsigned char* n = (const unsigned char*)  name;
  const unsigned char* ma = (const unsigned char*) mask;
  const unsigned char* na = (const unsigned char*) name;
  int wild  = 0;
  int calls = 0;

  assert(mask != NULL);
  assert(name != NULL);

  if (!mask || !name)
    return(0);

  while (calls++ < MATCH_MAX_CALLS)
  {
    if (*m == '*')
    {
      /*
       * XXX - shouldn't need to spin here, the mask should have been
       * collapsed before match is called
       */
      while (*m == '*')
        m++;
      wild = 1;
      ma = m;
      na = n;
    }

    if (!*m)
    {
      if (!*n)
        return 1;
      for (m--; (m > (const unsigned char*) mask) && (*m == '?'); m--)
        ;
      if (*m == '*' && (m > (const unsigned char*) mask))
        return 1;
      if (!wild)
        return(0);
      m = ma;
      n = ++na;
    }
    else if (!*n)
    {
      /*
       * XXX - shouldn't need to spin here, the mask should have been
       * collapsed before match is called
       */
      while (*m == '*')
        m++;
      return (*m == 0);
    }
    if (ToLower(*m) != ToLower(*n) && *m != '?')
    {
      if (!wild)
        return(0);
      m = ma;
      n = ++na;
    }
    else
    {
      if (*m)
        m++;
      if (*n)
        n++;
    }
  }

  return(0);
}
コード例 #6
0
ファイル: CppBuilder.cpp プロジェクト: ultimatepp/mirror
Vector<String> CppBuilder::CustomStep(const String& pf, const String& package_, bool& error)
{
	String package = Nvl(package_, mainpackage);
	String path = (*pf == '.' && pf[1] != '.') ? target : SourcePath(package, pf);
	String file = GetHostPath(path);
	String ext = ToLower(GetFileExt(pf));
	if(ext == ".ext") {
		Vector<String> files;
		Vector<String> dirs;
		sGatherAllExt(files, dirs, GetFileFolder(path), "");
		
		Index<String> pkg_files;
		Package pkg;
		pkg.Load(PackagePath(package));
		for(int i = 0; i < pkg.GetCount(); i++)
			pkg_files.Add(pkg[i]);
		
		Index<String> out;
		Index<String> include_path;
		String f = LoadFile(path);
		try {
			CParser p(f);
			while(!p.IsEof()) {
				if(p.Id("files")) {
					Vector<String> e = ReadPatterns(p);
					for(int i = 0; i < files.GetCount(); i++)
						for(int j = 0; j < e.GetCount(); j++) {
							String f = files[i];
							if(PatternMatch(e[j], f) && pkg_files.Find(f) < 0)
								out.FindAdd(f);
						}
				}
				if(p.Id("exclude")) {
					ExtExclude(p, out);
				}
				if(p.Id("include_path")) {
					Vector<String> e = ReadPatterns(p);
					for(int j = 0; j < e.GetCount(); j++) {
						String ee = e[j];
						if(ee.Find('*') >= 0)
							for(int i = 0; i < dirs.GetCount(); i++) {
								String d = dirs[i];
								if(PatternMatch(e[j], d)) {
									include_path.FindAdd(d);
								}
							}
						else
							include_path.Add(ee);
					}
				}
				if(p.Id("exclude_path")) {
					ExtExclude(p, include_path);
				}
				if(p.Id("includes")) {
					Vector<String> e = ReadPatterns(p);
					for(int i = 0; i < files.GetCount(); i++)
						for(int j = 0; j < e.GetCount(); j++) {
							String f = files[i];
							if(PatternMatch(e[j], f) && pkg_files.Find(f) < 0)
								include_path.FindAdd(GetFileFolder(f));
						}
				}
			}
		}
		catch(CParser::Error) {
			PutConsole("Invalid .ext file");
			error = true;
			return Vector<String>();
		}
		
		for(int i = 0; i < include_path.GetCount(); i++)
			include.Add(NormalizePath(include_path[i], GetFileFolder(path)));
		
		Vector<String> o;
		for(int i = 0; i < out.GetCount(); i++)
			o.Add(SourcePath(package, out[i]));
		return o;
	}
	for(int i = 0; i < wspc.GetCount(); i++) {
		const Array< ::CustomStep >& mv = wspc.GetPackage(i).custom;
		for(int j = 0; j < mv.GetCount(); j++) {
			const ::CustomStep& m = mv[j];
			if(MatchWhen(m.when, config.GetKeys()) && m.MatchExt(ext)) {
				VectorMap<String, String> mac;
				AddPath(mac, "PATH", file);
				AddPath(mac, "RELPATH", pf);
				AddPath(mac, "DIR", GetFileFolder(PackagePath(package)));
				AddPath(mac, "FILEDIR", GetFileFolder(file));
				AddPath(mac, "PACKAGE", package);
				mac.Add("FILE", GetFileName(file));
				mac.Add("TITLE", GetFileTitle(file));
				AddPath(mac, "EXEPATH", GetHostPath(target));
				AddPath(mac, "EXEDIR", GetHostPath(GetFileFolder(target)));
				mac.Add("EXEFILE", GetFileName(target));
				mac.Add("EXETITLE", GetFileTitle(target));
				AddPath(mac, "OUTDIR", GetHostPath(outdir));
				//BW
				AddPath(mac, "OUTDIR", GetHostPath(GetFileFolder(target)));
				AddPath(mac, "OUTFILE", GetHostPath(GetFileName(target)));
				AddPath(mac, "OUTTITLE", GetHostPath(GetFileTitle(target)));

				mac.Add("INCLUDE", Join(include, ";"));

				Vector<String> out = Cuprep(m.output, mac, include);
				bool dirty = out.IsEmpty();
				for(int i = 0; !dirty && i < out.GetCount(); i++)
					dirty = (GetFileTime(file) > GetFileTime(out[i]));
				if(dirty) {
					HdependTimeDirty();
					PutConsole(GetFileName(file));
					Vector<String> cmd = Cuprep(m.command, mac, include);
					String cmdtext;
					for(int c = 0; c < cmd.GetCount(); c++) {
						PutVerbose(cmd[c]);
						if(!Cd(cmd[c]) && !Cp(cmd[c], package, error)) {
							String ctext = cmd[c];
							const char *cm = ctext;
							if(*cm == '?')
								cm++;
							if(*ctext != '?' && Execute(cm)) {
								for(int t = 0; t < out.GetCount(); t++)
									DeleteFile(out[t]);
								PutConsole("FAILED: " + ctext);
								error = true;
								return Vector<String>();
							}
						}
					}
				}
				return out;
			}
		}
	}
	Vector<String> out;
	out.Add(path);
	return out;
}
コード例 #7
0
void * Asc2Bin(const char *source,const MiI32 count,const char *spec,void *dest)
{

	MiI32   cnt = 0;
	MiI32   size  = 0;

	Atype types[MAXARG];

	const char *ctype = spec;

	while ( *ctype )
	{
		switch ( ToLower(*ctype) )
		{
			case 'f': size+= sizeof(MiF32); types[cnt] = AT_FLOAT; cnt++;  break;
			case 'd': size+= sizeof(MiI32);   types[cnt] = AT_INT;   cnt++;  break;
			case 'c': size+=sizeof(char);   types[cnt] = AT_CHAR;  cnt++;  break;
			case 'b': size+=sizeof(char);   types[cnt] = AT_BYTE;  cnt++;  break;
			case 'h': size+=sizeof(short);  types[cnt] = AT_SHORT; cnt++;  break;
			case 'p': size+=sizeof(const char *);  types[cnt] = AT_STR; cnt++;  break;
			case 'x':
				{
					Atype type = AT_HEX4;
					MiI32 sz = 4;
					switch ( ctype[1] )
					{
						case '1':  type = AT_HEX1; sz   = 1; ctype++;  break;
						case '2':  type = AT_HEX2; sz   = 2; ctype++;  break;
						case '4':  type = AT_HEX4; sz   = 4; ctype++;  break;
					}
					types[cnt] = type;
					size+=sz;
					cnt++;
				}
				break;
		}
		if ( cnt == MAXARG ) return 0; // over flowed the maximum specification!
		ctype++;
	}

	bool myalloc = false;

	if ( dest == 0 )
	{
		myalloc = true;
		dest = (char *) MI_ALLOC(sizeof(char)*count*size);
	}

	// ok...ready to parse lovely data....
	memset(dest,0,size_t(count*size)); // zero out memory

	char *dst = (char *) dest; // where we are storing the results
	for (MiI32 i=0; i<count; i++)
	{
		for (MiI32 j=0; j<cnt; j++)
		{
			source = SkipWhitespace(source); // skip white spaces.

			if (source == NULL ||  *source == 0 ) // we hit the end of the input data before we successfully parsed all input!
			{
				if ( myalloc )
				{
					MI_FREE(dest);
				}
				return 0;
			}

			switch ( types[j] )
			{
				case AT_FLOAT:
					{
						MiF32 *v = (MiF32 *) dst;
						*v = GetFloatValue(source,&source);
						dst+=sizeof(MiF32);
					}
					break;
				case AT_INT:
					{
						MiI32 *v = (MiI32 *) dst;
						*v = GetIntValue( source, &source );
						dst+=sizeof(MiI32);
					}
					break;
				case AT_CHAR:
					{
						*dst++ = *source++;
					}
					break;
				case AT_BYTE:
					{
						char *v = (char *) dst;
						*v = (char)GetIntValue(source,&source);
						dst+=sizeof(char);
					}
					break;
				case AT_SHORT:
					{
						short *v = (short *) dst;
						*v = (short)(unsigned short)GetIntValue( source,&source );
						dst+=sizeof(short);
					}
					break;
				case AT_STR:
					{
						const char **ptr = (const char **) dst;
						*ptr = source;
						dst+=sizeof(const char *);
						while ( *source && !IsWhitespace(*source) ) source++;
					}
					break;
				case AT_HEX1:
					{
						MiU32 hex = GetHEX1(source,&source);
						MiU8 *v = (MiU8 *) dst;
						*v = (MiU8)hex;
						dst+=sizeof(MiU8);
					}
					break;
				case AT_HEX2:
					{
						MiU32 hex = GetHEX2(source,&source);
						unsigned short *v = (unsigned short *) dst;
						*v = (unsigned short)hex;
						dst+=sizeof(unsigned short);
					}
					break;
				case AT_HEX4:
					{
						MiU32 hex = GetHEX4(source,&source);
						MiU32 *v = (MiU32 *) dst;
						*v = hex;
						dst+=sizeof(MiU32);
					}
					break;
				case AT_LAST: // Make compiler happy
					break;
			}
		}
	}

	return dest;
}
コード例 #8
0
ファイル: MakeFile.cpp プロジェクト: guowei8412/upp-mirror
void CppBuilder::AddMakeFile(MakeFile& makefile, String package,
	const Vector<String>& all_uses, const Vector<String>& all_libraries,
	const Index<String>& common_config, bool exporting)
{
	String packagepath = PackagePath(package);
	Package pkg;
	pkg.Load(packagepath);
	String packagedir = GetFileFolder(packagepath);
	Vector<String> src = GetUppDirs();
	for(int i = 0; i < src.GetCount(); i++)
		src[i] = UnixPath(src[i]);

	bool main = HasFlag("MAIN");
	bool is_shared = HasFlag("SO");
	bool libout = !main && !HasFlag("NOLIB");
	bool win32 = HasFlag("WIN32");

	String pack_ident = MakeIdent(package);
	String outdir = "OutDir_" + pack_ident;
	String macros = "Macro_" + pack_ident;
	String macdef = "$(Macro)";
	String objext = (HasFlag("MSC") || HasFlag("EVC") ? ".obj" : ".o");

	Vector<String> x(config.GetKeys(), 1);
	Sort(x);
	for(int i = 0; i < x.GetCount(); i++) {
		if(common_config.Find(x[i]) < 0)
			macdef << " -Dflag" << x[i];
		x[i] = InitCaps(x[i]);
	}

	makefile.outdir << "$(" << outdir << ")";
	makefile.outfile << AdjustMakePath(GetFileTitle(NativePath(package)));
	if(main)
		makefile.outfile << GetTargetExt();
	else if(is_shared)
		makefile.outfile << (win32 ? ".dll" : ".so");
	else
		makefile.outfile << (win32 && HasFlag("MSC") ? ".lib" : ".a");
	makefile.output << (main ? String("$(OutDir)") : makefile.outdir) << makefile.outfile;

	if(main) {
		makefile.config << "CXX = c++\n"
			"LINKER = $(CXX)\n";
		String flags;
		if(HasFlag("DEBUG"))
			flags << " -D_DEBUG " << debug_options;
		else
			flags << ' ' << release_options;
		if(HasFlag("DEBUG_MINIMAL"))
			flags << " -ggdb -g1";
		if(HasFlag("DEBUG_FULL"))
			flags << " -ggdb -g2";
		if(is_shared && !win32)
			flags << " -fPIC ";
		flags << ' ' << Gather(pkg.option, config.GetKeys());
		makefile.config << "CFLAGS =" << flags << "\n"
			"CXXFLAGS =" << flags << "\n"
			"LDFLAGS = " << (HasFlag("DEBUG") ? debug_link : release_link) << " $(LINKOPTIONS)\n"
			"LIBPATH =";
		for(int i = 0; i < libpath.GetCount(); i++)
			makefile.config << " -L" << GetMakePath(AdjustMakePath(GetHostPathQ(libpath[i])));
		makefile.config << "\n"
			"AR = ar -sr\n\n";
		makefile.install << "\t-mkdir -p $(OutDir)\n";
		Vector<String> lib;
		String lnk;
		lnk << "$(LINKER)";
		if(!HasFlag("SHARED"))
			lnk << " -static";
		if(HasFlag("WIN32")) {
			lnk << " -mwindows";
			if(!HasFlag("GUI"))
				makefile.linkfiles << " -mconsole";
		}
		lnk << " -o $(OutFile)";
		if(HasFlag("DEBUG") || HasFlag("DEBUG_MINIMAL") || HasFlag("DEBUG_FULL"))
			lnk << " -ggdb";
		else
			lnk << (!HasFlag("OSX11") ? " -Wl,-s" : "");

		lnk << " $(LIBPATH)";
		if (!HasFlag("OSX11"))
			lnk << " -Wl,-O,2";
		lnk << " $(LDFLAGS) -Wl,--start-group ";

		makefile.linkfiles = lnk;
	}

	makefile.config << outdir << " = $(UPPOUT)"
		<< GetMakePath(AdjustMakePath(String().Cat() << package << '/' << method << '-' << Join(x, "-") << '/')) << "\n"
		<< macros << " = " << macdef << "\n";

	makefile.install << "\t-mkdir -p $(" << outdir << ")\n";

	String libdep, libfiles;

	libdep << makefile.output << ":";
	if(is_shared)
	{
		libfiles = "c++ -shared -fPIC"; // -v";
		Point p = ExtractVersion();
		if(!IsNull(p.x)) {
			libfiles << " -Xlinker --major-image-version -Xlinker " << p.x;
			if(!IsNull(p.y))
				libfiles << " -Xlinker --minor-image-version -Xlinker " << p.y;
		}
		libfiles << " -o ";
	}
	else
		libfiles = "$(AR) ";
	libfiles << makefile.output;

	Vector<String> libs = Split(Gather(pkg.library, config.GetKeys()), ' ');
	for(int i = 0; i < libs.GetCount(); i++) {
		String ln = libs[i];
		String ext = ToLower(GetFileExt(ln));
		if(ext == ".a" || ext == ".so" || ext == ".dll")
			makefile.linkfileend << " \\\n\t\t\t" << GetHostPathQ(FindInDirs(libpath, ln));
		else
			makefile.linkfileend << " \\\n\t\t\t-l" << ln;
	}
	
	for(int i = 0; i < pkg.GetCount(); i++)
		if(!pkg[i].separator) {
			String gop = Gather(pkg[i].option, config.GetKeys());
			String fn = SourcePath(package, pkg[i]);
			String ext = ToLower(GetFileExt(fn));
			bool isc = ext == ".c";
			bool isrc = (ext == ".rc" && HasFlag("WIN32"));
			bool iscpp = (ext == ".cpp" || ext == ".cc" || ext == ".cxx");
			bool isicpp = (ext == ".icpp");
			if(ext == ".brc") {
				isc = true;
				fn << "c";
			}
			if(isc || isrc || iscpp || isicpp) {
				String outfile;
				outfile << makefile.outdir << AdjustMakePath(GetFileTitle(fn)) << (isrc ? "_rc" : "") << objext;
				String srcfile = GetMakePath(MakeSourcePath(src, fn, false, exporting));
				makefile.rules << outfile << ": " << srcfile;
				Vector<String> dep = HdependGetDependencies(fn);
				Sort(dep, GetLanguageInfo());
				for(int d = 0; d < dep.GetCount(); d++) {
					String dfn = MakeSourcePath(src, dep[d], true, exporting);
					if(!IsNull(dfn))
						makefile.rules << " \\\n\t" << GetMakePath(dfn);
				}
				makefile.rules << "\n"
					"\t$(CXX) -c " << (isc ? "-x c $(CFLAGS)" : "-x c++ $(CXXFLAGS)") << " $(CINC) $(" << macros << ") "
						<< gop << " " << srcfile << " -o " << outfile << "\n\n";
				if(!libout || isicpp) {
					makefile.linkdep << " \\\n\t" << outfile;
					makefile.linkfiles << " \\\n\t\t" << outfile;
				}
				else {
					libdep << " \\\n\t" << outfile;
					libfiles << " \\\n\t\t" << outfile;
				}
			}
			else
			if(ext == ".o" || ext == ".obj" || ext == ".a" || ext == ".so" || ext == ".lib" || ext == ".dll") {
				makefile.linkdep << " \\\n\t" << fn;
				makefile.linkfiles << ' ' << fn;
			}
		}

	if(libout) {
		makefile.rules << libdep << "\n\t" << libfiles << "\n\n";
		makefile.linkdep << " \\\n\t" << makefile.output;
		makefile.linkfiles << " \\\n\t\t\t" << makefile.output;
	}
/*
	if(main) {
		if(!HasFlag("SOLARIS")&&!HasFlag("OSX11"))
			makefile.linkfiles << " \\\n\t\t-Wl,--start-group ";
		DDUMPC(all_libraries);
		for(int i = 0; i < all_libraries.GetCount(); i++) {
			String ln = all_libraries[i];
			String ext = ToLower(GetFileExt(ln));
			if(ext == ".a" || ext == ".so" || ext == ".dll")
				makefile.linkfileend << " \\\n\t\t\t" << GetHostPathQ(FindInDirs(libpath, ln));
			else
				makefile.linkfileend << " \\\n\t\t\t-l" << ln;
		}
		if(!HasFlag("SOLARIS")&&!HasFlag("OSX11"))
			makefile.linkfileend << " \\\n\t\t-Wl,--end-group\n\n";
	}
*/
}
コード例 #9
0
ファイル: probability.c プロジェクト: pombredanne/solidircd
static int pavg_skip(unsigned char *s, int type)
{
    unsigned char c1, c2, lc1, lc2;
    int count = 0;
    int total = 0;

    if (pfoldedsets & type)
    {
        while(*s)
        {
            c1 = *s++;

            if (!(pcharset[c1] & type))
                continue;

            for (c2 = *s; c2; c2 = *++s)
                if (pcharset[c2] & type)
                    break;

            if (!c2)
                break;

            lc1 = ToLower(c1) - PMINCHAR;
            lc2 = ToLower(c2) - PMINCHAR;
            c1 = ToUpper(c1) - PMINCHAR;
            c2 = ToUpper(c2) - PMINCHAR;

            count++;
            total += probabilities[c1][c2];
            if (lc1 != c1)
            {
                total += probabilities[lc1][c2];
                if (lc2 != c2)
                    total += probabilities[lc1][lc2];
            }
            if (lc2 != c2)
                total += probabilities[c1][lc2];
        }
    }
    else
    {
        while (*s)
        {
            c1 = *s++;

            if (!(pcharset[c1] & type))
                continue;

            for (c2 = *s; c2; c2 = *++s)
                if (pcharset[c2] & type)
                    break;

            if (!c2)
                break;

            c1 -= PMINCHAR;
            c2 -= PMINCHAR;
            total += probabilities[c1][c2];
            count++;
        }
    }

    if (!count)
        return -1;

    return (total/count);
}
コード例 #10
0
	bool StringExtensions::CompareStrings( const std::string &lhs, const std::string &rhs )
	{
		return ( ToLower( lhs ) == ToLower( rhs ) );
	}
コード例 #11
0
ファイル: utils.c プロジェクト: cmouse/hbs
/**
 * rfc_match(mask,string)
 * param mask - mask to use
 * param string - string to mask against
 * return 1 if bad, 0 if ok
 */
int rfc_match (const char *mask, const char *string)
{
  const char *m = mask, *s = string;
  char ch;
  const char *bm, *bs;		/* Will be reg anyway on a decent CPU/compiler */
  /* Process the "head" of the mask, if any */
  while ((ch = *m++) && (ch != '*'))
    switch (ch)
      {
      case '\\':
	if (*m == '?' || *m == '*')
	  ch = *m++;
      default:
	if (ToLower (*s) != ToLower (ch))
	  return 1;
      case '?':
	if (!*s++)
	  return 1;
      };
  if (!ch)
    return *s;

  /* We got a star: quickly find if/where we match the next char */
got_star:
  bm = m;			/* Next try rollback here */
  while ((ch = *m++))
    switch (ch)
      {
      case '?':
	if (!*s++)
	  return 1;
      case '*':
	bm = m;
	continue;		/* while */
      case '\\':
	if (*m == '?' || *m == '*')
	  ch = *m++;
      default:
	goto break_while;	/* C is structured ? */
      };
break_while:
  if (!ch)
    return 0;			/* mask ends with '*', we got it */
  ch = ToLower (ch);
  while (ToLower (*s++) != ch)
    if (!*s)
      return 1;
  bs = s;			/* Next try start from here */

  /* Check the rest of the "chunk" */
  while ((ch = *m++))
    {
      switch (ch)
	{
	case '*':
	  goto got_star;
	case '\\':
	  if (*m == '?' || *m == '*')
	    ch = *m++;
	default:
	  if (ToLower (*s) != ToLower (ch))
	    {
	      /* If we've run out of string, give up */
	      if (!*bs)
		return 1;
	      m = bm;
	      s = bs;
	      goto got_star;
	    };
	case '?':
	  if (!*s++)
	    return 1;
	};
    };
  if (*s)
    {
      m = bm;
      s = bs;
      goto got_star;
    };
  return 0;
}
コード例 #12
0
ファイル: strencodings.cpp プロジェクト: JeremyRubin/bitcoin
void Downcase(std::string& str)
{
    std::transform(str.begin(), str.end(), str.begin(), [](char c){return ToLower(c);});
}
コード例 #13
0
ファイル: eval.c プロジェクト: gtaylor/btmux
void exec(char *buff, char **bufc, int tflags, dbref player, dbref cause,
		  int eval, char **dstr, char *cargs[], int ncargs)
{
#define	NFARGS	30
	char *fargs[NFARGS];
	char *preserve[MAX_GLOBAL_REGS];
	char *tstr, *tbuf, *tbufc, *savepos, *atr_gotten, *start, *oldp, *savestr;
	char savec, ch, *str;
	char *realbuff = NULL, *realbp = NULL;
	dbref aowner;
	int at_space, nfargs, gender, i, j, alldone, feval; long aflags;
	int is_trace, is_top, save_count;
	int ansi;
	FUN *fp;
	UFUN *ufp;

	static const char *subj[5] = { "", "it", "she", "he", "they" };
	static const char *poss[5] = { "", "its", "her", "his", "their" };
	static const char *obj[5] = { "", "it", "her", "him", "them" };
	static const char *absp[5] = { "", "its", "hers", "his", "theirs" };

	if(*dstr == NULL)
		return;

	// dprintk("%d/%s", player, *dstr);

	at_space = 1;
	gender = -1;
	alldone = 0;
	ansi = 0;

	is_trace = Trace(player) && !(eval & EV_NOTRACE);
	is_top = 0;

	/* Extend the buffer if we need to. */

	if(((*bufc) - buff) > (LBUF_SIZE - SBUF_SIZE)) {
		realbuff = buff;
		realbp = *bufc;
		buff = (char *) malloc(LBUF_SIZE);
		*bufc = buff;
	}

	oldp = start = *bufc;

	/*
	 * If we are tracing, save a copy of the starting buffer 
	 */

	savestr = NULL;
	if(is_trace) {
		is_top = tcache_empty();
		savestr = alloc_lbuf("exec.save");
		StringCopy(savestr, *dstr);
	}
	while (**dstr && !alldone) {
		switch (**dstr) {
		case ' ':
			/*
			 * A space.  Add a space if not compressing or if * * 
			 * 
			 * *  * * previous char was not a space 
			 */

			if(!(mudconf.space_compress && at_space) ||
			   (eval & EV_NO_COMPRESS)) {
				safe_chr(' ', buff, bufc);
				at_space = 1;
			}
			break;
		case '\\':
			/*
			 * General escape.  Add the following char without *
			 * * * * special processing 
			 */

			at_space = 0;
			(*dstr)++;
			if(**dstr)
				safe_chr(**dstr, buff, bufc);
			else
				(*dstr)--;
			break;
		case '[':
			/*
			 * Function start.  Evaluate the contents of the * *
			 * * * square brackets as a function.  If no closing
			 * * * * * bracket, insert the [ and continue. 
			 */

			at_space = 0;
			tstr = (*dstr)++;
			if(eval & EV_NOFCHECK) {
				safe_chr('[', buff, bufc);
				*dstr = tstr;
				break;
			}
			tbuf = parse_to(dstr, ']', 0);
			if(*dstr == NULL) {
				safe_chr('[', buff, bufc);
				*dstr = tstr;
			} else {
				str = tbuf;
				exec(buff, bufc, 0, player, cause,
					 (eval | EV_FCHECK | EV_FMAND), &str, cargs, ncargs);
				(*dstr)--;
			}
			break;
		case '{':
			/*
			 * Literal start.  Insert everything up to the * * *
			 * * terminating } without parsing.  If no closing *
			 * * * * brace, insert the { and continue. 
			 */

			at_space = 0;
			tstr = (*dstr)++;
			tbuf = parse_to(dstr, '}', 0);
			if(*dstr == NULL) {
				safe_chr('{', buff, bufc);
				*dstr = tstr;
			} else {
				if(!(eval & EV_STRIP)) {
					safe_chr('{', buff, bufc);
				}
				/*
				 * Preserve leading spaces (Felan) 
				 */

				if(*tbuf == ' ') {
					safe_chr(' ', buff, bufc);
					tbuf++;
				}
				str = tbuf;
				exec(buff, bufc, 0, player, cause,
					 (eval & ~(EV_STRIP | EV_FCHECK)), &str, cargs, ncargs);
				if(!(eval & EV_STRIP)) {
					safe_chr('}', buff, bufc);
				}
				(*dstr)--;
			}
			break;
		case '%':
			/*
			 * Percent-replace start.  Evaluate the chars * * *
			 * following * and perform the appropriate * * *
			 * substitution. 
			 */

			at_space = 0;
			(*dstr)++;
			savec = **dstr;
			savepos = *bufc;
			switch (savec) {
			case '\0':			/*
								 * Null - all done 
								 */
				(*dstr)--;
				break;
			case '|':			/* piped command output */
				safe_str(mudstate.pout, buff, bufc);
				break;
			case '%':			/*
								 * Percent - a literal % 
								 */
				safe_chr('%', buff, bufc);
				break;
			case 'c':
			case 'C':
				(*dstr)++;
				if(!**dstr)
					(*dstr)--;
				ansi = 1;
				switch (**dstr) {
				case 'h':		/*
								 * hilite 
								 */
					safe_str(ANSI_HILITE, buff, bufc);
					break;
				case 'i':		/*
								 * inverse 
								 */
					safe_str(ANSI_INVERSE, buff, bufc);
					break;
				case 'f':		/*
								 * flash 
								 */
					safe_str(ANSI_BLINK, buff, bufc);
					break;
				case 'u':		/* underline */
					safe_str(ANSI_UNDER, buff, bufc);
					break;
				case 'n':		/*
								 * normal 
								 */
					safe_str(ANSI_NORMAL, buff, bufc);
					ansi = 0;
					break;
				case 'x':		/*
								 * black fg 
								 */
					safe_str(ANSI_BLACK, buff, bufc);
					break;
				case 'r':		/*
								 * red fg 
								 */
					safe_str(ANSI_RED, buff, bufc);
					break;
				case 'g':		/*
								 * green fg 
								 */
					safe_str(ANSI_GREEN, buff, bufc);
					break;
				case 'y':		/*
								 * yellow fg 
								 */
					safe_str(ANSI_YELLOW, buff, bufc);
					break;
				case 'b':		/*
								 * blue fg 
								 */
					safe_str(ANSI_BLUE, buff, bufc);
					break;
				case 'm':		/*
								 * magenta fg 
								 */
					safe_str(ANSI_MAGENTA, buff, bufc);
					break;
				case 'c':		/*
								 * cyan fg 
								 */
					safe_str(ANSI_CYAN, buff, bufc);
					break;
				case 'w':		/*
								 * white fg 
								 */
					safe_str(ANSI_WHITE, buff, bufc);
					break;
				case 'X':		/*
								 * black bg 
								 */
					safe_str(ANSI_BBLACK, buff, bufc);
					break;
				case 'R':		/*
								 * red bg 
								 */
					safe_str(ANSI_BRED, buff, bufc);
					break;
				case 'G':		/*
								 * green bg 
								 */
					safe_str(ANSI_BGREEN, buff, bufc);
					break;
				case 'Y':		/*
								 * yellow bg 
								 */
					safe_str(ANSI_BYELLOW, buff, bufc);
					break;
				case 'B':		/*
								 * blue bg 
								 */
					safe_str(ANSI_BBLUE, buff, bufc);
					break;
				case 'M':		/*
								 * magenta bg 
								 */
					safe_str(ANSI_BMAGENTA, buff, bufc);
					break;
				case 'C':		/*
								 * cyan bg 
								 */
					safe_str(ANSI_BCYAN, buff, bufc);
					break;
				case 'W':		/*
								 * white bg 
								 */
					safe_str(ANSI_BWHITE, buff, bufc);
					break;
				default:
					safe_chr(**dstr, buff, bufc);
				}
				break;
			case 'r':			/*
								 * Carriage return 
								 */
			case 'R':
				safe_str((char *) "\r\n", buff, bufc);
				break;
			case 't':			/*
								 * Tab 
								 */
			case 'T':
				safe_chr('\t', buff, bufc);
				break;
			case 'B':			/*
								 * Blank 
								 */
			case 'b':
				safe_chr(' ', buff, bufc);
				break;
			case '0':			/*
								 * Command argument number N 
								 */
			case '1':
			case '2':
			case '3':
			case '4':
			case '5':
			case '6':
			case '7':
			case '8':
			case '9':
				i = (**dstr - '0');
				if((i < ncargs) && (cargs[i] != NULL))
					safe_str(cargs[i], buff, bufc);
				break;
			case 'V':			/*
								 * Variable attribute 
								 */
			case 'v':
				(*dstr)++;
				ch = ToUpper(**dstr);
				if(!**dstr)
					(*dstr)--;
				if((ch < 'A') || (ch > 'Z'))
					break;
				i = 100 + ch - 'A';
				atr_gotten = atr_pget(player, i, &aowner, &aflags);
				safe_str(atr_gotten, buff, bufc);
				free_lbuf(atr_gotten);
				break;
			case 'Q':
			case 'q':
				(*dstr)++;
				i = (**dstr - '0');
				if((i >= 0) && (i <= 9) && mudstate.global_regs[i]) {
					safe_str(mudstate.global_regs[i], buff, bufc);
				}
				if(!**dstr)
					(*dstr)--;
				break;
			case 'O':			/*
								 * Objective pronoun 
								 */
			case 'o':
				if(gender < 0)
					gender = get_gender(cause);
				if(!gender)
					tbuf = Name(cause);
				else
					tbuf = (char *) obj[gender];
				safe_str(tbuf, buff, bufc);
				break;
			case 'P':			/*
								 * Personal pronoun 
								 */
			case 'p':
				if(gender < 0)
					gender = get_gender(cause);
				if(!gender) {
					safe_str(Name(cause), buff, bufc);
					safe_chr('s', buff, bufc);
				} else {
					safe_str((char *) poss[gender], buff, bufc);
				}
				break;
			case 'S':			/*
								 * Subjective pronoun 
								 */
			case 's':
				if(gender < 0)
					gender = get_gender(cause);
				if(!gender)
					tbuf = Name(cause);
				else
					tbuf = (char *) subj[gender];
				safe_str(tbuf, buff, bufc);
				break;
			case 'A':			/*
								 * Absolute posessive 
								 */
			case 'a':			/*
								 * idea from Empedocles 
								 */
				if(gender < 0)
					gender = get_gender(cause);
				if(!gender) {
					safe_str(Name(cause), buff, bufc);
					safe_chr('s', buff, bufc);
				} else {
					safe_str((char *) absp[gender], buff, bufc);
				}
				break;
			case '#':			/*
								 * Invoker DB number 
								 */
				tbuf = alloc_sbuf("exec.invoker");
				sprintf(tbuf, "#%ld", cause);
				safe_str(tbuf, buff, bufc);
				free_sbuf(tbuf);
				break;
			case '!':			/*
								 * Executor DB number 
								 */
				tbuf = alloc_sbuf("exec.executor");
				sprintf(tbuf, "#%ld", player);
				safe_str(tbuf, buff, bufc);
				free_sbuf(tbuf);
				break;
			case 'N':			/*
								 * Invoker name 
								 */
			case 'n':
				safe_str(Name(cause), buff, bufc);
				break;
			case 'L':			/*
								 * Invoker location db# 
								 */
			case 'l':
				if(!(eval & EV_NO_LOCATION)) {
					tbuf = alloc_sbuf("exec.exloc");
					sprintf(tbuf, "#%ld", where_is(cause));
					safe_str(tbuf, buff, bufc);
					free_sbuf(tbuf);
				}

				break;
			default:			/*
								 * Just copy 
								 */
				safe_chr(**dstr, buff, bufc);
			}
			if(isupper(savec))
				*savepos = ToUpper(*savepos);
			break;
		case '(':
			/*
			 * Arglist start.  See if what precedes is a function. If so,
			 * execute it if we should.
			 */

			at_space = 0;
			if(!(eval & EV_FCHECK)) {
				safe_chr('(', buff, bufc);
				break;
			}
			/*
			 * Load an sbuf with an uppercase version of the func name, and
			 * see if the func exists.  Trim trailing spaces from the name
			 * if configured.
			 */

			**bufc = '\0';
			tbufc = tbuf = alloc_sbuf("exec.tbuf");
			safe_sb_str(oldp, tbuf, &tbufc);
			*tbufc = '\0';
			if(mudconf.space_compress) {
				while ((--tbufc >= tbuf) && isspace(*tbufc));
				tbufc++;
				*tbufc = '\0';
			}
			for(tbufc = tbuf; *tbufc; tbufc++)
				*tbufc = ToLower(*tbufc);
			fp = (FUN *) hashfind(tbuf, &mudstate.func_htab);

			/*
			 * If not a builtin func, check for global func 
			 */

			ufp = NULL;
			if(fp == NULL) {
				ufp = (UFUN *) hashfind(tbuf, &mudstate.ufunc_htab);
			}
			/*
			 * Do the right thing if it doesn't exist 
			 */

			if(!fp && !ufp) {
				if(eval & EV_FMAND) {
					*bufc = oldp;
					safe_str((char *) "#-1 FUNCTION (", buff, bufc);
					safe_str(tbuf, buff, bufc);
					safe_str((char *) ") NOT FOUND", buff, bufc);
					alldone = 1;
				} else {
					safe_chr('(', buff, bufc);
				}
				free_sbuf(tbuf);
				eval &= ~EV_FCHECK;
				break;
			}
			free_sbuf(tbuf);

			/*
			 * Get the arglist and count the number of args * Neg 
			 * 
			 * *  * *  * * # of args means catenate subsequent
			 * args 
			 */

			if(ufp)
				nfargs = NFARGS;
			else if(fp->nargs < 0)
				nfargs = -fp->nargs;
			else
				nfargs = NFARGS;
			tstr = *dstr;
			if(fp && (fp->flags & FN_NO_EVAL))
				feval = (eval & ~EV_EVAL) | EV_STRIP_ESC;
			else
				feval = eval;
			*dstr =
				parse_arglist(player, cause, *dstr + 1, ')', feval, fargs,
							  nfargs, cargs, ncargs);

			/*
			 * If no closing delim, just insert the '(' and * * * 
			 * 
			 * * continue normally 
			 */

			if(!*dstr) {
				*dstr = tstr;
				safe_chr(**dstr, buff, bufc);
				for(i = 0; i < nfargs; i++)
					if(fargs[i] != NULL)
						free_lbuf(fargs[i]);
				eval &= ~EV_FCHECK;
				break;
			}
			/*
			 * Count number of args returned 
			 */

			(*dstr)--;
			j = 0;
			for(i = 0; i < nfargs; i++)
				if(fargs[i] != NULL)
					j = i + 1;
			nfargs = j;

			/*
			 * If it's a user-defined function, perform it now. 
			 */

			if(ufp) {
				mudstate.func_nest_lev++;
				if(!check_access(player, ufp->perms)) {
					safe_str("#-1 PERMISSION DENIED", buff, &oldp);
					*bufc = oldp;
				} else {
					tstr = atr_get(ufp->obj, ufp->atr, &aowner, &aflags);
					if(ufp->flags & FN_PRIV)
						i = ufp->obj;
					else
						i = player;
					str = tstr;

					if(ufp->flags & FN_PRES) {
						for(j = 0; j < MAX_GLOBAL_REGS; j++) {
							if(!mudstate.global_regs[j])
								preserve[j] = NULL;
							else {
								preserve[j] = alloc_lbuf("eval_regs");
								StringCopy(preserve[j],
										   mudstate.global_regs[j]);
							}
						}
					}

					exec(buff, &oldp, 0, i, cause, feval, &str, fargs,
						 nfargs);
					*bufc = oldp;

					if(ufp->flags & FN_PRES) {
						for(j = 0; j < MAX_GLOBAL_REGS; j++) {
							if(preserve[j]) {
								if(!mudstate.global_regs[j])
									mudstate.global_regs[j] =
										alloc_lbuf("eval_regs");
								StringCopy(mudstate.global_regs[j],
										   preserve[j]);
								free_lbuf(preserve[j]);
							} else {
								if(mudstate.global_regs[j])
									*(mudstate.global_regs[i]) = '\0';
							}
						}
					}

					free_lbuf(tstr);
				}

				/*
				 * Return the space allocated for the args 
				 */

				mudstate.func_nest_lev--;
				for(i = 0; i < nfargs; i++)
					if(fargs[i] != NULL)
						free_lbuf(fargs[i]);
				eval &= ~EV_FCHECK;
				break;
			}
			/*
			 * If the number of args is right, perform the func.
			 * Otherwise return an error message.  Note
			 * that parse_arglist returns zero args as one
			 * null arg, so we have to handle that case
			 * specially. 
			 */

			if((fp->nargs == 0) && (nfargs == 1)) {
				if(!*fargs[0]) {
					free_lbuf(fargs[0]);
					fargs[0] = NULL;
					nfargs = 0;
				}
			}
			if((nfargs == fp->nargs) || (nfargs == -fp->nargs) ||
			   (fp->flags & FN_VARARGS)) {

				/*
				 * Check recursion limit 
				 */

				mudstate.func_nest_lev++;
				mudstate.func_invk_ctr++;
				if(mudstate.func_nest_lev >= mudconf.func_nest_lim) {
					safe_str("#-1 FUNCTION RECURSION LIMIT EXCEEDED", buff,
							 bufc);
				} else if(mudstate.func_invk_ctr == mudconf.func_invk_lim) {
					safe_str("#-1 FUNCTION INVOCATION LIMIT EXCEEDED",
							 buff, bufc);
				} else if(!check_access(player, fp->perms)) {
					safe_str("#-1 PERMISSION DENIED", buff, &oldp);
					*bufc = oldp;
				} else if(mudstate.func_invk_ctr < mudconf.func_invk_lim) {
					fp->fun(buff, &oldp, player, cause, fargs, nfargs,
							cargs, ncargs);
					*bufc = oldp;
				} else {
					**bufc = '\0';
				}
				mudstate.func_nest_lev--;
			} else {
				*bufc = oldp;
				tstr = alloc_sbuf("exec.funcargs");
				sprintf(tstr, "%d", fp->nargs);
				safe_str((char *) "#-1 FUNCTION (", buff, bufc);
				safe_str((char *) fp->name, buff, bufc);
				safe_str((char *) ") EXPECTS ", buff, bufc);
				safe_str(tstr, buff, bufc);
				safe_str((char *) " ARGUMENTS", buff, bufc);
				free_sbuf(tstr);
			}

			/*
			 * Return the space allocated for the arguments 
			 */

			for(i = 0; i < nfargs; i++)
				if(fargs[i] != NULL)
					free_lbuf(fargs[i]);
			eval &= ~EV_FCHECK;
			break;
		default:
			/*
			 * A mundane character.  Just copy it 
			 */

			at_space = 0;
			safe_chr(**dstr, buff, bufc);
		}
		(*dstr)++;
	}

	/*
	 * If we're eating spaces, and the last thing was a space, eat it
	 * up. Complicated by the fact that at_space is initially
	 * true. So check to see if we actually put something in the
	 * buffer, too. 
	 */

	if(mudconf.space_compress && at_space && !(eval & EV_NO_COMPRESS)
	   && (start != *bufc))
		(*bufc)--;

	/*
	 * The ansi() function knows how to take care of itself. However, 
	 * if the player used a %c sub in the string, and hasn't yet
	 * terminated the color with a %cn yet, we'll have to do it for 
	 * them. 
	 */

	if(ansi == 1)
		safe_str(ANSI_NORMAL, buff, bufc);

	**bufc = '\0';

	/*
	 * Report trace information 
	 */

	if(realbuff) {
		**bufc = '\0';
		*bufc = realbp;
		safe_str(buff, realbuff, bufc);
		free(buff);
		buff = realbuff;
	}

	if(is_trace) {
		tcache_add(savestr, start);
		save_count = tcache_count - mudconf.trace_limit;;
		if(is_top || !mudconf.trace_topdown)
			tcache_finish(player);
		if(is_top && (save_count > 0)) {
			tbuf = alloc_mbuf("exec.trace_diag");
			sprintf(tbuf, "%d lines of trace output discarded.", save_count);
			notify(player, tbuf);
			free_mbuf(tbuf);
		}
	}
}
コード例 #14
0
ファイル: match.c プロジェクト: Cloudxtreme/ircd-seven
/** Check a string against a mask.
 * This test checks using extended wildcards: '*' means match zero
 * or more characters of any type; '?' means match exactly one
 * character of any type; '#' means match exactly one character that
 * is a number; '@' means match exactly one character that is a
 * letter; '\s' means match a space.
 *
 * This function supports escaping, so that a wildcard may be matched 
 * exactly.
 *
 * @param[in] mask Wildcard-containing mask.
 * @param[in] name String to check against \a mask.
 * @return Zero if \a mask matches \a name, non-zero if no match.
 */
int
match_esc(const char *mask, const char *name)
{
	const unsigned char *m = (const unsigned char *)mask;
	const unsigned char *n = (const unsigned char *)name;
	const unsigned char *ma = (const unsigned char *)mask;
	const unsigned char *na = (const unsigned char *)name;
	int wild = 0;
	int calls = 0;
	int quote = 0;
	int match1 = 0;

	s_assert(mask != NULL);
	s_assert(name != NULL);

	if(!mask || !name)
		return 0;

	/* if the mask is "*", it matches everything */
	if((*m == '*') && (*(m + 1) == '\0'))
		return 1;

	while(calls++ < MATCH_MAX_CALLS)
	{
		if(quote)
			quote++;
		if(quote == 3)
			quote = 0;
		if(*m == '\\' && !quote)
		{
			m++;
			quote = 1;
			continue;
		}
		if(!quote && *m == '*')
		{
			/*
			 * XXX - shouldn't need to spin here, the mask should have been
			 * collapsed before match is called
			 */
			while(*m == '*')
				m++;

			wild = 1;
			ma = m;
			na = n;

			if(*m == '\\')
			{
				m++;
				/* This means it is an invalid mask -A1kmm. */
				if(!*m)
					return 0;
				quote++;
				continue;
			}
		}

		if(!*m)
		{
			if(!*n)
				return 1;
			if(quote)
				return 0;
			for(m--; (m > (const unsigned char *)mask) && (*m == '?'); m--);;

			if(*m == '*' && (m > (const unsigned char *)mask))
				return 1;
			if(!wild)
				return 0;
			m = ma;
			n = ++na;
		}
		else if(!*n)
		{
			/*
			 * XXX - shouldn't need to spin here, the mask should have been
			 * collapsed before match is called
			 */
			if(quote)
				return 0;
			while(*m == '*')
				m++;
			return (*m == 0);
		}

		if(quote)
			match1 = *m == 's' ? *n == ' ' : ToLower(*m) == ToLower(*n);
		else if(*m == '?')
			match1 = 1;
		else if(*m == '@')
			match1 = IsLetter(*n);
		else if(*m == '#')
			match1 = IsDigit(*n);
		else
			match1 = ToLower(*m) == ToLower(*n);
		if(match1)
		{
			if(*m)
				m++;
			if(*n)
				n++;
		}
		else
		{
			if(!wild)
				return 0;
			m = ma;
			n = ++na;
		}
	}
	return 0;
}
コード例 #15
0
ファイル: Workspace.cpp プロジェクト: kolyden/mirror
bool IsCHeaderFile(const char *path)
{
	String ext = ToLower(GetFileExt(path));
	return ext == ".h" || ext == ".hpp" || ext == ".hh" || ext == ".hxx";
}
コード例 #16
0
bool GAMESSUKFormat::ReadVariables(istream &ifs, double factor, string stopstr)
{
	/*
	 * This takes an input stream that is positioned where the list of variables
	 * starts and the reads the variables into the supplied map
	 * 
	 * This is different to ReadGeometry (which takes a vector of strings as input) because 
	 * currently the variables always need to be read after the geometry, so we need to save the
	 * geometry and then read the variables. However this means that we can parse the variables 
	 * directly into a map and don't need to keep a copy of the specifcation as strings.
	 * 
	 * stopstr is a string that defines when we stop reading
	 */
	
	string line;
	vector<string> tokens;
	
	// Now read in all the varibles
	while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)) {

		// Skip commnents
		if (EQn(buffer, "#", 1) || EQn(buffer, "?", 1))
			continue;

		// Copy line to a C++ string and convert to lower case
		// & remove leading and trailing spaces
		line = buffer;
		// transform(method.begin(), method.end(), method.begin(), ::tolower);
		ToLower(line);
		Trim(line);

		// Check for end of variables
		if (line.length()==0 and stopstr.length()==0) break;
		if (stopstr.length()>0 && line.compare(0, stopstr.length(), stopstr)==0) break;
		
		// Check for commas & split with that as the separator if necessary
		if (line.find(',')!=string::npos) {
			tokenize(tokens, line, ",");
		} else {
			tokenize(tokens, line, " \t\n");
		}

		char *endptr;
		double var = strtod((char*)tokens[1].c_str(), &endptr);
		if (endptr == (char*)tokens[1].c_str()) {
			errorMsg << "Problems reading a GAMESS-UK  file: "
					<< "Could not read variable line: " << line;
			obErrorLog.ThrowError(__FUNCTION__, errorMsg.str() , obWarning);
			return false;
		}
		// Add to list of variables
		variables[tokens[0]]=var*factor;
	}
	
	/*
	 cerr << "Got list of variables: " << endl;
	 for (map<string,double>::iterator i=variables.begin(); i
	 != variables.end(); i++) {
	 cerr << "Name: " << i->first << " Value: " << i->second << endl;
	 }
	 */
	 
	return true;
	
}
コード例 #17
0
ファイル: Menu.c プロジェクト: tobynet/clcl
/*
 * menu_accelerator - メニューアクセラレータ
 */
LRESULT menu_accelerator(const HMENU hMenu, const TCHAR key)
{
#define ToLower(c)		((c >= TEXT('A') && c <= TEXT('Z')) ? (c - TEXT('A') + TEXT('a')) : c)
	MENUITEMINFO mii;
	int i, sel;
	int cnt;
	int ret = -1;

	cnt = GetMenuItemCount(hMenu);

	// 選択位置取得
	for (sel = 0; sel < cnt; sel++) {
		if (GetMenuState(hMenu, sel, MF_BYPOSITION) & MF_HILITE) {
			break;
		}
	}
	if (sel >= cnt) {
		sel = -1;
	}

	// アクセラレータ位置取得
	for (i = sel + 1; i < cnt; i++) {
		ZeroMemory(&mii, sizeof(mii));
		mii.cbSize = sizeof(mii);
		mii.fMask = MIIM_TYPE | MIIM_DATA;
		if (GetMenuItemInfo(hMenu, i, TRUE, &mii) == 0 ||
			!(mii.fType & MFT_OWNERDRAW) ||
			mii.dwItemData == 0 || 
			((MENU_ITEM_INFO *)mii.dwItemData)->text == NULL) {
			continue;
		}
		if (ToLower(menu_get_accelerator(((MENU_ITEM_INFO *)mii.dwItemData)->text)) != ToLower(key)) {
			continue;
		}
		if (ret != -1) {
			// 選択
			return MAKELRESULT(ret, MNC_SELECT);
		}
		ret = i;
	}
	for (i = 0; i <= sel; i++) {
		ZeroMemory(&mii, sizeof(mii));
		mii.cbSize = sizeof(mii);
		mii.fMask = MIIM_TYPE | MIIM_DATA;
		if (GetMenuItemInfo(hMenu, i, TRUE, &mii) == 0 ||
			!(mii.fType & MFT_OWNERDRAW) ||
			mii.dwItemData == 0 || 
			((MENU_ITEM_INFO *)mii.dwItemData)->text == NULL) {
			continue;
		}
		if (ToLower(menu_get_accelerator(((MENU_ITEM_INFO *)mii.dwItemData)->text)) != ToLower(key)) {
			continue;
		}
		if (ret != -1) {
			// 選択
			return MAKELRESULT(ret, MNC_SELECT);
		}
		ret = i;
	}
	return ((ret != -1) ? MAKELRESULT(ret, MNC_EXECUTE) : 0);
}
コード例 #18
0
	bool GAMESSUKInputFormat::ReadMolecule(OBBase* pOb, OBConversion* pConv)

{
	/*
	 * Stuff to think about:
	 * - At outset check whether we are in zmatrix, cartesian or nw-chem format
	 *   (we currently only suppot homogeneous formats - not mixed).
	 * 
	 * For each line need to check:
	 * - Is this a comment (?,#)
	 * - Are the tokens separated by commas, if so use tokenize to split at commas
	 * - Is there an 'end' token on the line
	 * 
	 * For each line we want to check that we haven't hit a change from c to zm or vv
	 * 
	 */

	OBMol* pmol = dynamic_cast<OBMol*>(pOb);
	if (pmol==NULL)
		return false;

	//Define some references so we can use the old parameter names
	istream& ifs = *pConv->GetInStream();
	OBMol &mol = *pmol;
	
	// Get a default title as the filename
    const char* title = pConv->GetTitle();    
    mol.BeginModify();
    mol.SetTitle(title);
    mol.EndModify();

	vector<string> geomList, tokens; // list of lines and list of tokens on a line
	string line; // For convenience so we can refer to lines from the iterator as 'line'
	ReadMode_t ReadMode=SKIP;
	double factor=BOHR_TO_ANGSTROM;
	
	// Read File and copy geometry specification into geomList
	while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)) {
		
		// Skip commnents
		if (EQn(buffer, "#", 1) || EQn(buffer, "?", 1)) continue;

		// Copy line to a C++ string and convert to lower case
		// & remove leading and trailing spaces
		line = buffer;
		// transform(method.begin(), method.end(), method.begin(), ::tolower);
		ToLower(line);
		Trim(line);

		// Start of coordinate specifiation
		if (line.compare(0, 4, "zmat")==0) {
			ReadMode=ZMATRIX;
			geomList.push_back(line);
			continue;
		} else if (line.compare(0, 4, "geom")==0) {
			ReadMode=CARTESIAN;
			geomList.push_back(line);
			continue;
		}

		
		// Reading the coordinate specification into the list
		if (ReadMode==ZMATRIX || ReadMode==CARTESIAN) {
		
			// Variables specification - process directly from filestream
			// and then remove from the geometry specification
			if (line.compare(0, 4, "vari")==0 || line.compare(0, 4, "const")==0) {
				
				// Check for commas & split with that as the separator if necessary
				if (line.find(',')!=string::npos) {
					tokenize(tokens, line, ",");
				} else {
					tokenize(tokens, line, " \t\n");
				}	

				// See if we need to rescale
				if (IsUnits(tokens[1])) factor=Rescale(tokens[1]);	
				
				if (! ReadVariables(ifs, factor, "end")) return false;
				ReadMode=SKIP;
				geomList.push_back("end\n");	
				continue;
			}
			
			if (line.compare(0, 3, "end")==0) ReadMode=SKIP;			
			geomList.push_back(line);
		}

	}// End while reading loop

	// Now go and process the coordinate specification if we got any
	bool ok = ReadGeometry(mol, geomList);
	
    if (mol.NumAtoms() == 0) { // e.g., if we're at the end of a file PR#1737209
    	mol.EndModify();
    	return false;
    } else {
    	return ok;
    }

} // End ReadMolecule	
コード例 #19
0
ファイル: StrUtil.cpp プロジェクト: dreamsxin/ultimatepp
int CharFilterAlphaToLower(int c)
{
	return IsAlpha(c) ? IsLower(c) ? c : ToLower(c) : 0;
}
コード例 #20
0
  bool GAMESSUKOutputFormat::ReadMolecule(OBBase* pOb, OBConversion* pConv) {

	/*
	 
	Read in coordinates after any reorientation due to the symmetry code
	- if there is a field called "input z-matrix" then we read the initial zmatrix in here
	  This geometry is not needed if we are optimising as we can use the optimised geometry
	  However, we need to keep this geometry as it's the only one we have if it's not an opt.
	  
	- if there is no zmat, we need to read the "molecular geometry" field. This geometry
	  only needs to be used if we are not in an optimisation.
	  
	 Read the RUN TYPE field to work out whether we need to use the first geometry.
	 
	 If it's a single point caculation, we can return the molecule at this point
	 
	 If it's some form of structure search, we need to go and find the final structure

	 */

	OBMol* pmol = dynamic_cast<OBMol*>(pOb);
	if (pmol==NULL)
		return false;

	//Define some references so we can use the old parameter names
	istream& ifs = *pConv->GetInStream();
	OBMol &mol = *pmol;
	
	// Get a default title as the filename
    const char* title = pConv->GetTitle();    
    mol.BeginModify();
    mol.SetTitle(title);
    mol.EndModify();

	vector<string> tokens, geomList; // list of lines and list of tokens on a line
	string line; // For convenience so we can refer to lines from the iterator as 'line'
	//ReadMode_t ReadMode=SKIP;
	
	enum RunType_t { UNKNOWN, SINGLEPOINT, OPTXYZ, OPTZMAT, SADDLE };
	RunType_t RunType=UNKNOWN;
	bool ok;
	
	while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)) {
		
		/* The zmatrix entered by the user
		 * REM:  need to add stuff for "automatic z-matrix generation" as we currently
		 * ignore the zmatrix & just read the cartesian coordinates 
		 */
		
		if (strstr(buffer,"                              input z-matrix") != NULL){
			
			// Set Runtype to SINGLEPOINT so we don't read in the cartesians
			RunType=SINGLEPOINT;
			
			geomList.clear();
			
			// skip 2 lines
			ifs.getline(buffer, BUFF_SIZE) && ifs.getline(buffer, BUFF_SIZE);
			
			// Stick a header line first
			geomList.push_back("zmatrix bohr");
			
			// Read zmatrix into list until blank line 
			while (ifs.good() && ifs.getline(buffer, BUFF_SIZE) && strlen(buffer) != 0){
				line = buffer;
				// transform(method.begin(), method.end(), method.begin(), ::tolower);
				ToLower(line);
				Trim(line);
				geomList.push_back(line);
			}
			
			// Skip 3 lines
			ifs.getline(buffer, BUFF_SIZE) && 
			ifs.getline(buffer, BUFF_SIZE) && 
			ifs.getline(buffer, BUFF_SIZE);
			
			// Read in the variables till we hit blank line
			if (! ReadVariables(ifs, BOHR_TO_ANGSTROM, "")) return false;
			
			// Now go and process the geometry
			ok = ReadGeometry(mol, geomList);
					
		} // End Reading user z-matrix
		
		// Read the cartesian coordinates if we've not read in the ZMATRIX
		if (strstr(buffer,"*            charge       x             y              z       shells") != NULL &&
				RunType==UNKNOWN){
			
			// Skip 3 lines
			ifs.getline(buffer, BUFF_SIZE) && 
			ifs.getline(buffer, BUFF_SIZE) && 
			ifs.getline(buffer, BUFF_SIZE);
			
			// Create regex for the coords
			regex_t *myregex = new regex_t;
			int iok;
			iok = regcomp( myregex,
					//     ------label--------   -------charge-------- < seems enough for a match
					" *\\* *[a-zA-Z]{1,2}[0-9]* *[0-9]{1,3}\\.[0-9]{1}",
					REG_EXTENDED | REG_NOSUB);
			if (iok !=0) cerr << "Error compiling regex in GUK OUTPUT!\n";
			
			// Read in the coordinates - we process them directly rather 
			// then use ReadGeometry as we probably should do...
			mol.BeginModify();
			while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)){
				
				// End of geometry block
				if (strstr(buffer,"*************************")!=NULL)break;
				
				if (regexec( myregex, buffer, 0, 0, 0)==0) {
					//cerr << "Got Coord line: " << buffer << endl;
					OBAtom *atom = mol.NewAtom();
					tokenize(tokens,buffer," ");
					atom->SetAtomicNum(atoi(tokens[2].c_str()));
					double x=atof(tokens[3].c_str())*BOHR_TO_ANGSTROM;
					double y=atof(tokens[4].c_str())*BOHR_TO_ANGSTROM;
					double z=atof(tokens[5].c_str())*BOHR_TO_ANGSTROM;
					atom->SetVector(x, y, z);
				}
			}
			mol.EndModify();			
			regfree(myregex);
			
		} // End Read Cartesian Coords
		
		
		// Determine the RunType - affects how we move on from here.
		if (strstr(buffer," * RUN TYPE") != NULL){
			tokenize(tokens,buffer," \t\n");
			
			if(tokens[3].compare(0,6,"optxyz")==0){
				//cerr << "runtype is optxyz\n";
				RunType=OPTXYZ;
				break;
			} else if (tokens[3].compare(0,8,"optimize")==0){
				//cerr << "runtype is optimise\n";
				RunType=OPTZMAT;
				break;
			} else if (tokens[3].compare(0,6,"saddle")==0){
				//cerr << "runtype is optimise\n";
				RunType=SADDLE;
				break;
			} else {
				RunType=SINGLEPOINT;
				break;
			}
		}
	} // End First Reading loop
	
	
	if(RunType==SINGLEPOINT){
		// We can return the molecule that we've read in
		if (mol.NumAtoms() == 0) { // e.g., if we're at the end of a file PR#1737209
			mol.EndModify();
			return false;
		} else {
			return true;
		}
	}
	
	
	// Clear the Molecule as we're going to start from scratch again.
	mol.BeginModify();
	mol.Clear();
	mol.EndModify();
	
	// Start trundling through the file again - just get the last geometry
	while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)) {
		if (strstr(buffer,"optimization converged") != NULL)
		{	
			if (RunType==OPTXYZ){
				//cerr << "Got converged for OPTXYZ\n";
				
				// FF to start of coordinate specification
				while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)) {
					if (strstr(buffer,
							"atom     znuc       x             y             z") != NULL) break;
				}
				
				// Skip 3 lines - should then be at the coordinates
				ifs.getline(buffer, BUFF_SIZE) && 
				ifs.getline(buffer, BUFF_SIZE) && 
				ifs.getline(buffer, BUFF_SIZE);
				
				// Read in the coordinates - we process them directly rather 
				// then use ReadGeometry as we probably should do...
				mol.BeginModify();
				while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)){
					
					// End of geometry block
					if (strstr(buffer,"*************************")!=NULL)break;
					
					//cerr << "Got Coord line: " << buffer << endl;
					OBAtom *atom = mol.NewAtom();
					tokenize(tokens,buffer," ");
					atom->SetAtomicNum(atoi(tokens[2].c_str()));
					double x=atof(tokens[3].c_str())*BOHR_TO_ANGSTROM;
					double y=atof(tokens[4].c_str())*BOHR_TO_ANGSTROM;
					double z=atof(tokens[5].c_str())*BOHR_TO_ANGSTROM;
					atom->SetVector(x, y, z);
				}
				
				mol.EndModify();
				return true;
				
				
			} else if (RunType==OPTZMAT || RunType==SADDLE) {
				// Original geometry specification should still be in geomList
				// So just update the variables
				//cerr << "Got converged for OPTZMAT\n";				
				
				// FF to variable specification
				while (ifs.good() && ifs.getline(buffer, BUFF_SIZE)) {
					if (strstr(buffer,
							" variable           value                hessian") != NULL) break;
				}
				// Skip a line - should then be at variable specification
				ifs.getline(buffer, BUFF_SIZE);
				
				// Process them
				if (! ReadVariables(ifs, BOHR_TO_ANGSTROM,
						"===============================================")) return false;
				
				// Now go and process with the geometry we read before
				return ReadGeometry(mol, geomList);
				
			}
		}
		
	} // End Second Reading loop		

	return true;

} // End GAMESSUKOutputFormat::ReadMolecule
コード例 #21
0
ファイル: Font.cpp プロジェクト: dreamsxin/ultimatepp
int FontFilter(int c)
{
	return c >= 'a' && c <= 'z' || c >= '0' && c <= '9' ? c : c >= 'A' && c <= 'Z' ? ToLower(c) : 0;
}
コード例 #22
0
ファイル: parser.c プロジェクト: Jvlythical/ECS40
int
NextUnit (char **p)
{	// Main parser routine
	int coord[4], n, result, piece, i;
	char type[4], promoted, separator, slash, *oldp, *commentEnd, c;
        int wom = quickFlag ? quickFlag&1 : WhiteOnMove(yyboardindex);

	// ********* try white first, because it is so common **************************
	if(**p == ' ' || **p == '\n' || **p == '\t') { parseStart = (*p)++; return Nothing; }


	if(**p == NULLCHAR) { // make sure there is something to parse
	    if(fromString) return 0; // we are parsing string, so the end is really the end
	    *p = inPtr = inputBuf;
	    if(!ReadLine()) return 0; // EOF
	} else if(inPtr > inputBuf + PARSEBUFSIZE/2) { // buffer fills up with already parsed stuff
	    char *q = *p, *r = inputBuf;
	    while(*r++ = *q++);
	    *p = inputBuf; inPtr = r - 1;
	}
	parseStart = oldp = *p; // remember where we begin


	// ********* attempt to recognize a SAN move in the leading non-blank text *****
	piece = separator = promoted = slash = n = 0;
	for(i=0; i<4; i++) coord[i] = -1, type[i] = NOTHING;
	if(**p == '+') (*p)++, promoted++;
	if(**p >= 'a' && **p <= 'z' && (*p)[1]== '@') piece =*(*p)++ + 'A' - 'a'; else
	if(**p >= 'A' && **p <= 'Z') {
	     piece = *(*p)++; // Note we could test for 2-byte non-ascii names here
	     if(**p == '/') slash = *(*p)++;
	}
        while(n < 4) {
	    if(**p >= 'a' && **p < 'x') coord[n] = *(*p)++ - 'a', type[n++] = ALPHABETIC;
	    else if((i = Number(p)) != BADNUMBER) coord[n] = i, type[n++] = NUMERIC;
	    else break;
	    if(n == 2 && type[0] == type[1]) { // if two identical types, the opposite type in between must have been missing
		type[2] = type[1]; coord[2] = coord[1];
		type[1] = NOTHING; coord[1] = -1; n++;
	    }
	}
	// we always get here, and might have read a +, a piece, and upto 4 potential coordinates
	if(n <= 2) { // could be from-square or disambiguator, when -:xX follow, or drop with @ directly after piece, but also to-square
	     if(**p == '-' || **p == ':' || **p == 'x' || **p == 'X' || // these cannot be move suffix, so to-square must follow
		 (**p == '@' || **p == '*') && n == 0 && !promoted && piece) { // [email protected] must also be followed by to-square
		separator = *(*p)++;
		if(n == 1) coord[1] = coord[0]; // must be disambiguator, but we do not know which yet
		n = 2;
		while(n < 4) { // attempt to read to-square
		    if(**p >= 'a' && **p < 'x') coord[n] = *(*p)++ - 'a', type[n++] = ALPHABETIC;
		    else if((i = Number(p)) != BADNUMBER) coord[n] = i, type[n++] = NUMERIC;
		    else break;
		}
	    } else if((**p == '+' || **p == '=') && n == 1 && piece && type[0] == NUMERIC) { // can be traditional Xiangqi notation
		separator = *(*p)++;
		n = 2;
		if((i = Number(p)) != BADNUMBER) coord[n] = i, type[n++] = NUMERIC;
	    } else if(n == 2) { // only one square mentioned, must be to-square
		while(n < 4) { coord[n] = coord[n-2], type[n] = type[n-2], coord[n-2] = -1, type[n-2] = NOTHING; n++; }
	    }
	} else if(n == 3 && type[1] != NOTHING) { // must be hyphenless disambiguator + to-square
	    for(i=3; i>0; i--) coord[i] = coord[i-1], type[i] = type[i-1]; // move to-square to where it belongs
	    type[1] = NOTHING; // disambiguator goes in first two positions
	    n = 4;
	}
	// we always get here; move must be completely read now, with to-square coord(s) at end
	if(n == 3) { // incomplete to-square. Could be Xiangqi traditional, or stuff like fxg
	    if(piece && type[1] == NOTHING && type[0] == NUMERIC && type[2] == NUMERIC &&
		(separator == '+' || separator == '=' || separator == '-')) {
		     // Xiangqi traditional

		return ImpossibleMove; // for now treat as invalid
	    }
	    // fxg stuff, but also things like 0-0, 0-1 and 1-0
	    if(!piece && type[1] == NOTHING && type[0] == ALPHABETIC && type[2] == ALPHABETIC
		 && (coord[0] != 14 || coord[2] != 14) /* reserve oo for castling! */ ) {
		piece = 'P'; n = 4; // kludge alert: fake full to-square
	    }
	} else if(n == 1 && type[0] == NUMERIC && coord[0] > 1) { while(**p == '.') (*p)++; return Nothing; } // fast exit for move numbers
	if(n == 4 && type[2] != type[3] && // we have a valid to-square (kludge: type[3] can be NOTHING on fxg type move)
		     (piece || !promoted) && // promoted indicator only valid on named piece type
	             (type[2] == ALPHABETIC || gameInfo.variant == VariantShogi)) { // in Shogi also allow alphabetic rank
	    DisambiguateClosure cl;
	    int fromX, fromY, toX, toY;

	    if(slash && (!piece || type[1] == NOTHING)) goto badMove; // slash after piece only in ICS long format
	    if (yyskipmoves) return (int) AmbiguousMove; /* not disambiguated */

	    if(type[2] == NUMERIC) { // alpha-rank
		coord[2] = BOARD_RGHT - BOARD_LEFT - coord[2];
		coord[3] = BOARD_HEIGHT - coord[3];
		if(coord[0] >= 0) coord[0] = BOARD_RGHT - BOARD_LEFT - coord[0];
		if(coord[1] >= 0) coord[1] = BOARD_HEIGHT - coord[1];
	    }
	    toX = cl.ftIn = (currentMoveString[2] = coord[2] + 'a') - AAA;
	    toY = cl.rtIn = (currentMoveString[3] = coord[3] + '0') - ONE;
	    if(type[3] == NOTHING) cl.rtIn = -1; // for fxg type moves ask for toY disambiguation
	    else if(toY >= BOARD_HEIGHT || toY < 0)   return ImpossibleMove; // vert off-board to-square
	    if(toX < BOARD_LEFT || toX >= BOARD_RGHT) return ImpossibleMove;
	    if(piece) {
		cl.pieceIn = CharToPiece(wom ? piece : ToLower(piece));
		if(cl.pieceIn == EmptySquare) return ImpossibleMove; // non-existent piece
		if(promoted) cl.pieceIn = (ChessSquare) (PROMOTED cl.pieceIn);
	    } else cl.pieceIn = EmptySquare;
	    if(separator == '@' || separator == '*') { // drop move. We only get here without from-square or promoted piece
		fromY = DROP_RANK; fromX = cl.pieceIn;
		currentMoveString[0] = piece;
		currentMoveString[1] = '@';
		return LegalityTest(boards[yyboardindex], PosFlags(yyboardindex)&~F_MANDATORY_CAPTURE, fromY, fromX, toY, toX, NULLCHAR);
	    }
	    if(type[1] == NOTHING && type[0] != NOTHING) { // there is a disambiguator
		if(type[0] != type[2]) coord[0] = -1, type[1] = type[0], type[0] = NOTHING; // it was a rank-disambiguator
	    }
	    if(  type[1] != type[2] && // means fromY is of opposite type as ToX, or NOTHING
		(type[0] == NOTHING || type[0] == type[2]) ) { // well formed

		fromX = (currentMoveString[0] = coord[0] + 'a') - AAA;
		fromY = (currentMoveString[1] = coord[1] + '0') - ONE;
		currentMoveString[4] = cl.promoCharIn = PromoSuffix(p);
		currentMoveString[5] = NULLCHAR;
		if(type[0] != NOTHING && type[1] != NOTHING && type[3] != NOTHING) { // fully specified.
		    // Note that Disambiguate does not work for illegal moves, but flags them as impossible
		    if(piece) { // check if correct piece indicated
			ChessSquare realPiece = boards[yyboardindex][fromY][fromX];
			if(PieceToChar(realPiece) == '~') realPiece = (ChessSquare) (DEMOTED realPiece);
			if(!(appData.icsActive && PieceToChar(realPiece) == '+') && // trust ICS if it moves promoted pieces
			   piece && realPiece != cl.pieceIn) return ImpossibleMove;
		    }
		    result = LegalityTest(boards[yyboardindex], PosFlags(yyboardindex), fromY, fromX, toY, toX, cl.promoCharIn);
		    if (currentMoveString[4] == NULLCHAR) { // suppy missing mandatory promotion character
		      if(result == WhitePromotion  || result == BlackPromotion) {
		        switch(gameInfo.variant) {
			  case VariantCourier:
			  case VariantShatranj: currentMoveString[4] = PieceToChar(BlackFerz); break;
			  case VariantGreat:    currentMoveString[4] = PieceToChar(BlackMan); break;
			  case VariantShogi:    currentMoveString[4] = '+'; break;
			  default:              currentMoveString[4] = PieceToChar(BlackQueen);
			}
		      } else if(result == WhiteNonPromotion  || result == BlackNonPromotion) {
						currentMoveString[4] = '=';
		      }
		    } else if(appData.testLegality && gameInfo.variant != VariantSChess && // strip off unnecessary and false promo characters
		       !(result == WhitePromotion  || result == BlackPromotion ||
		         result == WhiteNonPromotion || result == BlackNonPromotion)) currentMoveString[4] = NULLCHAR;
		    return result;
		} else if(cl.pieceIn == EmptySquare) cl.pieceIn = wom ? WhitePawn : BlackPawn;
		cl.ffIn = type[0] == NOTHING ? -1 : coord[0] + 'a' - AAA;
		cl.rfIn = type[1] == NOTHING ? -1 : coord[1] + '0' - ONE;

	        Disambiguate(boards[yyboardindex], PosFlags(yyboardindex), &cl);

		if(cl.kind == ImpossibleMove && !piece && type[1] == NOTHING // fxg5 type
			&& toY == (wom ? 4 : 3)) { // could be improperly written e.p.
		    cl.rtIn += wom ? 1 : -1; // shift target square to e.p. square
		    Disambiguate(boards[yyboardindex], PosFlags(yyboardindex), &cl);
		    if((cl.kind != WhiteCapturesEnPassant && cl.kind != BlackCapturesEnPassant))
			return ImpossibleMove; // nice try, but no cigar
		}

		currentMoveString[0] = cl.ff + AAA;
		currentMoveString[1] = cl.rf + ONE;
		currentMoveString[3] = cl.rt + ONE;
		currentMoveString[4] = cl.promoChar;

		if((cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) && (Match("ep", p) || Match("e.p.", p)));

		return (int) cl.kind;
	    }
	}
badMove:// we failed to find algebraic move
	*p = oldp;


	// Next we do some common symbols where the first character commits us to things that cannot possibly be a move

	// ********* PGN tags ******************************************
	if(**p == '[') {
	    oldp = ++(*p);
	    if(Match("--", p)) { // "[--" could be start of position diagram
		if(!Scan(']', p) && (*p)[-3] == '-' && (*p)[-2] == '-') return PositionDiagram;
		*p = oldp;
	    }
	    SkipWhite(p);
	    if(isdigit(**p) || isalpha(**p)) {
		do (*p)++; while(isdigit(**p) || isalpha(**p) || **p == '+' ||
				**p == '-' || **p == '=' || **p == '_' || **p == '#');
		SkipWhite(p);
		if(**p == '"') {
		    (*p)++;
		    while(**p != '\n' && (*(*p)++ != '"'|| (*p)[-2] == '\\')); // look for unescaped quote
		    if((*p)[-1] !='"') { *p = oldp; Scan(']', p); return Comment; } // string closing delimiter missing
		    SkipWhite(p); if(*(*p)++ == ']') return PGNTag;
		}
	    }
	    Scan(']', p); return Comment;
	}

	// ********* SAN Castings *************************************
	if(**p == 'O' || **p == 'o' || **p == '0' && !Match("00:", p)) { // exclude 00 in time stamps
	    int castlingType = 0;
	    if(Match("O-O-O", p) || Match("o-o-o", p) || Match("0-0-0", p) ||
	       Match("OOO", p) || Match("ooo", p) || Match("000", p)) castlingType = 2;
	    else if(Match("O-O", p) || Match("o-o", p) || Match("0-0", p) ||
		    Match("OO", p) || Match("oo", p) || Match("00", p)) castlingType = 1;
	    if(castlingType) { //code from old parser, collapsed for both castling types, and streamlined a bit
		int rf, ff, rt, ft; ChessSquare king;
		char promo=NULLCHAR;

		if(gameInfo.variant == VariantSChess) promo = PromoSuffix(p);

		if (yyskipmoves) return (int) AmbiguousMove; /* not disambiguated */

		if (wom) {
		    rf = 0;
		    rt = 0;
		    king = WhiteKing;
		} else {
	            rf = BOARD_HEIGHT-1;
        	    rt = BOARD_HEIGHT-1;
		    king = BlackKing;
		}
		ff = (BOARD_WIDTH-1)>>1; // this would be d-file
	        if (boards[yyboardindex][rf][ff] == king) {
		    /* ICS wild castling */
        	    ft = castlingType == 1 ? BOARD_LEFT+1 : (gameInfo.variant == VariantJanus ? BOARD_RGHT-2 : BOARD_RGHT-3);
		} else {
        	    ff = BOARD_WIDTH>>1; // e-file
	            ft = castlingType == 1 ? BOARD_RGHT-2 : BOARD_LEFT+2;
		}
		if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
		    if (wom) {
			ff = initialRights[2];
			ft = initialRights[castlingType-1];
		    } else {
			ff = initialRights[5];
			ft = initialRights[castlingType+2];
		    }
		    if (appData.debugMode) fprintf(debugFP, "Parser FRC (type=%d) %d %d\n", castlingType, ff, ft);
		    if(ff == NoRights || ft == NoRights) return ImpossibleMove;
		}
		sprintf(currentMoveString, "%c%c%c%c%c",ff+AAA,rf+ONE,ft+AAA,rt+ONE,promo);
		if (appData.debugMode) fprintf(debugFP, "(%d-type) castling %d %d\n", castlingType, ff, ft);

	        return (int) LegalityTest(boards[yyboardindex],
			      PosFlags(yyboardindex)&~F_MANDATORY_CAPTURE, // [HGM] losers: e.p.!
			      rf, ff, rt, ft, promo);
	    }
	}
コード例 #23
0
ファイル: match.c プロジェクト: BackupTheBerlios/shadowircd
/* match_esc()
 *
 * The match() function with support for escaping characters such
 * as '*' and '?'
 */
int
match_esc(const char *mask, const char *name)
{
  const unsigned char* m = (const unsigned char*)  mask;
  const unsigned char* n = (const unsigned char*)  name;
  const unsigned char* ma = (const unsigned char*) mask;
  const unsigned char* na = (const unsigned char*) name;
  int wild  = 0;
  int calls = 0;
  int quote = 0;

  assert(mask != NULL);
  assert(name != NULL);

  if (!mask || !name)
    return(0);

  while (calls++ < MATCH_MAX_CALLS)
  {
    if (quote)
      quote++;
    if (quote == 3)
      quote = 0;
    if (*m == '\\' && !quote)
    {
      m++;
      quote = 1;
      continue;
    }
    if (!quote && *m == '*')
    {
      /*
       * XXX - shouldn't need to spin here, the mask should have been
       * collapsed before match is called
       */
      while (*m == '*')
        m++;
      if (*m == '\\')
      {
	m++;
	/* This means it is an invalid mask -A1kmm. */
	if (!*m)
	  return(0);
	quote = 2;
      }
      wild = 1;
      ma = m;
      na = n;
    }

    if (!*m)
    {
      if (!*n)
        return 1;
      if (quote)
        return 0;
      for (m--; (m > (const unsigned char*) mask) && (*m == '?'); m--)
        ;
      if (*m == '*' && (m > (const unsigned char*) mask))
        return(1);
      if (!wild)
        return(0);
      m = ma;
      n = ++na;
    }
    else if (!*n)
    {
      /*
       * XXX - shouldn't need to spin here, the mask should have been
       * collapsed before match is called
       */
      if (quote)
        return(0);
      while (*m == '*')
        m++;
      return (*m == 0);
    }
    if (ToLower(*m) != ToLower(*n) && !(!quote && *m == '?'))
    {
      if (!wild)
        return(0);
      m = ma;
      n = ++na;
    }
    else
    {
      if (*m)
        m++;
      if (*n)
        n++;
    }
  }

  return(0);
}
コード例 #24
0
ファイル: regsvr42.cpp プロジェクト: softkannan/privateprj
int wmain(int argc, wchar_t* argv[])
{
    if (argc < 2)
    {
        PrintUsage();
        return 1;
    }

    bool doTrace = false;
    bool generateHash = false;
    bool generateClientManifest = false;
    std::wstring fileName;

    std::wstring outputFileName;
    std::wstring assemblyVersion;
    std::wstring assemblyName;
    std::wstring clientFileName;

    bool batchMode = false;
    std::wstring batchFileName;

    bool directoryMode = false;
    std::wstring directoryPath;

    // Get the command line arguments
    for (int i = 1; i < argc; ++i)
    {
        std::wstring arg = argv[i];
               
		// Hopefully the filename doesn't start with -
		if (arg[0] != L'-')
        {
            fileName = arg;

            TrimQuotes(fileName);
        }
        else if (ToLower(arg.substr(1)) == L"trace")
        {
            doTrace = true;
        }
        else if (ToLower(arg.substr(1, 8)) == L"version")
        {
            assemblyVersion = arg.substr(10);
        }
        else if (ToLower(arg.substr(1, 4)) == L"name")
        {
            assemblyName = arg.substr(6);

            TrimQuotes(assemblyName);
        }
        else if (ToLower(arg.substr(1, 4)) == L"hash")
        {
            generateHash = true;
        }
        else if (ToLower(arg.substr(1, 6)) == L"client")
        {
            generateClientManifest = true;
            clientFileName = arg.substr(8) + L".manifest";
            
            TrimQuotes(clientFileName);
        }
        else if (ToLower(arg.substr(1, 5)) == L"batch")
        {
            batchMode = true;
            batchFileName = arg.substr(7);
        }
        else if (ToLower(arg.substr(1, 3)) == L"dir")
        {
            directoryMode = true;
            directoryPath = arg.substr(5);

            TrimQuotes(directoryPath);
        }
        else
        {
            std::wcout << L"Parameter: " << arg << L" was not recognised" << std::endl;;
        }
    }
        
    // Processing and validation of command line arguments
    if (fileName.empty() && !batchMode && !directoryMode)
    {
        std::wcout << L"No com_dll was given!" << std::endl;
        return 1;
    }

    if (assemblyName.empty() && !batchMode && !directoryMode)
    {
        std::wstring localFile = fileName.substr(fileName.rfind(L'\\') + 1);
        assemblyName = localFile.substr(0, localFile.rfind(L'.')) + L".sxs";
    }
    else if (assemblyName.empty() && directoryMode)
    {
        assemblyName = directoryPath.substr(directoryPath.rfind(L'\\') + 1);
    }
    else if (!assemblyName.empty() && directoryMode)
    {
        std::wcout << L"Directory mode: assemblyName cannot be used!" << std::endl;
        return 1;
    }

    
    if (!assemblyName.empty() && batchMode)
    {
       std::wcout << L"Batch mode: assemblyName cannot be used!" << std::endl;
       return 1;
    }

    std::wstring clientFileNamePath = clientFileName.substr(0, clientFileName.rfind(L'\\') + 1);

    if (clientFileName.empty())
    {
        std::wstring fileNamePath = fileName.substr(0, fileName.rfind(L'\\') + 1);
        outputFileName = fileNamePath + assemblyName + L".manifest";
    }
    else if (directoryMode)
    {
        outputFileName = assemblyName + L".manifest";
    }
    else
    {
        outputFileName = clientFileNamePath + assemblyName + L".manifest";
    }


    if (assemblyVersion.empty() && !batchMode)
    {
        assemblyVersion = L"1.0.0.0";
    }
    else if (!assemblyVersion.empty() && batchMode)
    {
        std::wcout << L"Batch mode: assemblyVersion cannot be used!" << std::endl;
        return 1;
    }

    if (directoryMode && batchMode)
    {
        std::wcout << L"Batch mode and Directory mode cannot be used together!" << std::endl;
        return 1;
    }

    // Generation of the manifest files
    std::vector<DependencyInfo> depencencyList;

    if (batchMode)
    {
        std::wifstream file(batchFileName.c_str());
        std::wstring line;

        while (std::getline(file, line))
        {
            std::wistringstream wis;
            wis.str(line);

            std::getline(wis, fileName, L'|');

            TrimSpaces(fileName);
            TrimQuotes(fileName);

            bool isDirectory = IsDirectory(fileName);
            
            if (!std::getline(wis, assemblyName, L'|') || isDirectory)          
            {
                std::wstring localFile = fileName.substr(fileName.rfind(L'\\') + 1);
                assemblyName = localFile.substr(0, localFile.rfind(L'.'));

                if (!isDirectory)
                {
                    assemblyName += + L".sxs";
                }
            }

            if (!std::getline(wis, assemblyVersion, L'|'))
            {
                assemblyVersion = L"1.0.0.0";
            }

            outputFileName = clientFileNamePath + assemblyName + L".manifest";

            if (isDirectory)
            {
                CreateManifestForDirectory(fileName, doTrace, assemblyName, assemblyVersion, generateHash, outputFileName);
            }
            else
            {
                CreateManifestForModule(fileName, doTrace, assemblyName, assemblyVersion, generateHash, outputFileName);
            }

            depencencyList.push_back(DependencyInfo(assemblyName, assemblyVersion));
        }
    }
    else if (directoryMode)
    {
        CreateManifestForDirectory(directoryPath, doTrace, assemblyName, assemblyVersion, generateHash, outputFileName);

        depencencyList.push_back(DependencyInfo(assemblyName, assemblyVersion));
    }
    else
    {
        CreateManifestForModule(fileName, doTrace, assemblyName, assemblyVersion, generateHash, outputFileName);

        depencencyList.push_back(DependencyInfo(assemblyName, assemblyVersion));
    }

    if (generateClientManifest)
    {
        ManifestWriter::WriteClientManifest(clientFileName, depencencyList);
    }

	return 0;
}
コード例 #25
0
ファイル: value_parser.cpp プロジェクト: klusark/sat
std::string toLower(const std::string& s) {
	std::string ret; ret.reserve(s.size());
	std::transform(s.begin(), s.end(), std::back_inserter(ret), ToLower());
	return ret;
}
コード例 #26
0
ファイル: dice.c プロジェクト: Acidburn0zzz/atheme
static bool eval_dice(sourceinfo_t *si, char *s_input)
{
	static char buffer[1024], result[32];

	char op = '\0', *c = s_input;
	unsigned int dice, roll, x, y, z = 0;
	double total;

	while (*c && isspace(*c))
		++c;
	if (!*c || !isdigit(*c))
	{
		gs_command_report(si, _("Syntax: XdY [ {-|+|*|/} Z ]"));
		return false;
	}

	x = strtoul(c, &c, 10);
	if (x == 0 || c == NULL || ToLower(*c++) != 'd' || !isdigit(*c))
	{
		if (x < 1 || x > DICE_MAX_DICE)
		{
			gs_command_report(si, _("Only 1-100 dice may be thrown at once."));
			return false;
		}

		gs_command_report(si, _("Syntax: XdY [ {-|+|*|/} Z ]"));
		return false;
	}

	y = strtoul(c, &c, 10);
	if (c != NULL)
	{
		while (*c && isspace(*c))
			++c;

		if (*c && strchr("-+*/", *c) == NULL)
		{
			gs_command_report(si, _("Syntax: XdY [ {-|+|*|/} Z ]"));
			return false;
		}
	}

	if (x < 1 || x > 100)
	{
		gs_command_report(si, _("Syntax: XdY [ {-|+|*|/} Z ]"));
		return false;
	}

	if (y < 1 || y > DICE_MAX_SIDES)
	{
		gs_command_report(si, _("Only 1-100 sides may be used on a dice."));
		return false;
	}

	if (*c)
	{
		op = *c++;

		z = strtoul(c, &c, 10);

		while (*c && isspace(*c))
			++c;

		if (*c)
		{
			gs_command_report(si, _("Syntax: XdY [ {-|+|*|/} Z ]"));
			return false;
		}
		else if (op == '/' && z == 0)
		{
			gs_command_report(si, _("Can't divide by zero."));
			return false;
		}
	}

	total = 0.0;
	snprintf(buffer, 1024, "\2%s\2 rolled %ud%u: ", si->su->nick, x, y);
	for (roll = 0; roll < x; ++roll)
	{
		snprintf(result, 32, "%d ", dice = (1 + (arc4random() % y)));
		mowgli_strlcat(buffer, result, sizeof(buffer));
		total += dice;
	}

	if (op == '\0')
		snprintf(result, 32, " <Total: %g>", total);
	else
	{
		snprintf(result, 32, " <Total: %g(%c%u) = ", total, op, z);
		mowgli_strlcat(buffer, result, sizeof(buffer));
		switch (op)
		{
		  case '+':
			  total += z;
			  break;
		  case '-':
			  total -= z;
			  break;
		  case '/':
			  total /= z;
			  break;
		  case '*':
			  total *= z;
			  break;
		  default:
			  break;
		}
		snprintf(result, 32, "%g>", total);
	}
	mowgli_strlcat(buffer, result, sizeof(buffer));

	gs_command_report(si, "%s", buffer);
	return true;
}
コード例 #27
0
	bool Config::doInitialize()
	{
		LOG_DEBUG(LOG_PREFIX_MENU_MULTIMENU << "Entering...");

		// Loading the area
		loadAreaFromTDF("config", "gui/config.area");

		if (lp_CONFIG->restorestart)
		{
			lp_CONFIG->restorestart = false;
			lp_CONFIG->quickstart = false;
		}

		*saved_config = *lp_CONFIG;

		if (pArea->get_object("*.fps_limit") )
		{
			fps_limits = pArea->get_object("*.fps_limit")->Text;
			fps_limits.erase( fps_limits.begin());
		}
		else
		{
			fps_limits.push_back("50");
			fps_limits.push_back("60");
			fps_limits.push_back("70");
			fps_limits.push_back("80");
			fps_limits.push_back("90");
			fps_limits.push_back("100");
			fps_limits.push_back("no limit");
		}
		I18N::Translate(fps_limits);

		nb_res = 0;

		SDL_Rect **mode_list = SDL_ListModes(NULL, SDL_FULLSCREEN | SDL_OPENGL);

		if (mode_list == (SDL_Rect**)0)         // No resolution available (normally this shouldn't be possible if we get here)
			nb_res = 0;
		else if (mode_list == (SDL_Rect**)-1)   // Ok, everything is possible so let's use standard sizes
		{
#define ADD_RES(w,h)  \
			res_bpp[nb_res++] = 16;\
			res_width[nb_res++] = w;\
			res_height[nb_res++] = h;\
			res_bpp[nb_res++] = 32;\
			res_width[nb_res++] = w;\
			res_height[nb_res++] = h;

			ADD_RES(640,480)
				ADD_RES(800,480)
				ADD_RES(800,600)
				ADD_RES(1024,768)
				ADD_RES(1024,600)
				ADD_RES(1280,960)
				ADD_RES(1280,1024)
				ADD_RES(1440,900)
				ADD_RES(1680,1050)
				ADD_RES(1600,1200)
				ADD_RES(1920,1200)
				ADD_RES(2560,1600)
		}
		else
		{
			for (unsigned int i = 0; mode_list[i] != NULL; ++i)
			{
				// Reference to the current SDL Rect
				const SDL_Rect& rect = *(mode_list[i]);

				if (rect.w >= 640 && rect.h >= 480)
				{
					# ifndef YUNI_OS_MAC
					if(SDL_VideoModeOK(rect.w, rect.h, 16, SDL_FULLSCREEN | SDL_OPENGL) == 16)
					{
						res_bpp[nb_res]    = 16;
						res_width[nb_res ] = rect.w;
						res_height[nb_res] = rect.h;
						++nb_res;
					}
					# endif
					if (SDL_VideoModeOK(rect.w, rect.h, 32, SDL_FULLSCREEN | SDL_OPENGL) == 32)
					{
						res_bpp[nb_res]    = 32;
						res_width[ nb_res] = rect.w;
						res_height[nb_res] = rect.h;
						++nb_res;
					}
				}
			}
		}

		pArea->set_state("*.showfps", lp_CONFIG->showfps);
		pArea->caption("*.fps_limit", fps_limits[fps_limits.size()-1]);
		for (String::Vector::const_iterator i = fps_limits.begin(); i != fps_limits.end(); ++i)
		{
			if ( (String() << (int)lp_CONFIG->fps_limit) == *i )
				pArea->caption("*.fps_limit", *i);
		}
		pArea->set_value("*.texture_quality", lp_CONFIG->unitTextureQuality);
		pArea->set_value("*.interface_transparency", int(lp_CONFIG->menuTransparency * 255.0f));
		pArea->set_value("*.shadow_map_size", lp_CONFIG->shadowmap_size);
		pArea->set_state("*.grab_inputs", lp_CONFIG->grab_inputs);
		pArea->set_value("*.sound_volume", lp_CONFIG->sound_volume);
		pArea->set_value("*.music_volume", lp_CONFIG->music_volume);
		pArea->set_state("*.far_sight", lp_CONFIG->far_sight);
		pArea->set_value("*.anisotropy", lp_CONFIG->anisotropy);
		pArea->set_value("*.mouse_sensitivity", (int)(lp_CONFIG->mouse_sensivity * 100.0f));
		pArea->set_state("*.disable_perspective", lp_CONFIG->ortho_camera);
		pArea->set_state("*.right_click_interface", lp_CONFIG->right_click_interface);
		pArea->set_state("*.disable_GLSL", lp_CONFIG->disable_GLSL);
		pArea->set_state("*.underwater_bright", lp_CONFIG->underwater_bright);
		pArea->set_state("*.use_texture_compression", lp_CONFIG->use_texture_compression);
		pArea->set_state("*.low_definition_map", lp_CONFIG->low_definition_map);
		pArea->set_state("*.sky", lp_CONFIG->render_sky);
		pArea->set_state("*.particle", lp_CONFIG->particle);
		pArea->set_state("*.explosion_particles", lp_CONFIG->explosion_particles);
		pArea->set_state("*.waves", lp_CONFIG->waves);
		pArea->set_state("*.height_line", lp_CONFIG->height_line);
		pArea->set_state("*.detail_tex", lp_CONFIG->detail_tex);
		pArea->set_state("*.use_texture_cache", lp_CONFIG->use_texture_cache);
		pArea->set_state("*.draw_console_loading", lp_CONFIG->draw_console_loading);
		pArea->set_state("*.fullscreen", lp_CONFIG->fullscreen);
		pArea->set_state("*.developer_mode", lp_CONFIG->developerMode);
		pArea->set_state("*.tool_tips", lp_CONFIG->tooltips);
		I18N::Instance()->retrieveAllLanguages(languageList);
		if (pArea->get_object("*.LANG"))
		{
			Gui::GUIOBJ::Ptr objLang = pArea->get_object("*.LANG");
			objLang->Text.clear();
			I18N::Language *l = I18N::Instance()->language(lp_CONFIG->Lang);
			if (l)
				objLang->Text.push_back(l->caption());
			else
				objLang->Text.push_back(lp_CONFIG->Lang);
			for (unsigned int i = 0; i < languageList.size(); i++)
				objLang->Text.push_back(languageList[i].caption());
		}
		if (pArea->get_object("*.camera_zoom") )
			pArea->caption( "*.camera_zoom", pArea->get_object("*.camera_zoom")->Text[1+lp_CONFIG->camera_zoom]);
		pArea->caption( "*.camera_def_angle", String() << lp_CONFIG->camera_def_angle );
		pArea->caption( "*.camera_def_h", String() << lp_CONFIG->camera_def_h );
		pArea->caption( "*.camera_zoom_speed", String() << lp_CONFIG->camera_zoom_speed );
		if (pArea->get_object("*.screenres") )
		{
			Gui::GUIOBJ::Ptr obj = pArea->get_object("*.screenres");
			obj->Text.clear();
			int current = 0;
			while( current < nb_res &&
				   ( res_width[ current ] != lp_CONFIG->screen_width
					 || res_height[ current ] != lp_CONFIG->screen_height
					 || res_bpp[ current ] != lp_CONFIG->color_depth ) )
				current++;
			if (current >= nb_res ) current = 0;
			obj->Text.push_back( String() << res_width[ current ] << "x" << res_height[ current ] << "x" << res_bpp[ current ] );
			for( int i = 0 ; i < nb_res ; i++ )
				obj->Text.push_back( String() << res_width[ i ] << "x" << res_height[ i ] << "x" << res_bpp[ i ] );
		}
		Gui::GUIOBJ::Ptr tmpO = pArea->get_object("*.shadow_quality");
		if (tmpO)
		{
			const unsigned int indx = 1 + Math::Max(0, Math::Min((int)lp_CONFIG->shadow_quality, 3));
			if (indx < tmpO->Text.size())
				pArea->caption("*.shadow_quality", tmpO->Text[indx]);
		}

		pArea->caption("*.timefactor", String() << (int)lp_CONFIG->timefactor);
		switch( lp_CONFIG->fsaa )
		{
			case 2: pArea->caption("*.fsaa", "x2");    break;
			case 4: pArea->caption("*.fsaa", "x4");    break;
			case 6: pArea->caption("*.fsaa", "x6");    break;
			case 8: pArea->caption("*.fsaa", "x8");    break;
			default: pArea->caption("*.fsaa", I18N::Translate("no fsaa"));
		}
		if (pArea->get_object("*.water_quality"))
		{
			Gui::GUIOBJ::Ptr obj = pArea->get_object("*.water_quality");
			pArea->caption("*.water_quality", obj->Text[1 + lp_CONFIG->water_quality]);
		}

		if (pArea->get_object("*.mod"))
		{
			Gui::GUIOBJ::Ptr obj = pArea->get_object("*.mod");

			if (obj->Text.size() >= 2)
				obj->Text[0] = obj->Text[1];
			else
				obj->Text.resize(1);

			String current_selection = TA3D_CURRENT_MOD.length() > 6 ? Substr(TA3D_CURRENT_MOD, 5, TA3D_CURRENT_MOD.length() - 6 ) : "";
			String::List mod_list = Mods::instance()->getModNameList(Mods::MOD_INSTALLED);
			mod_list.sort();
			mod_list.unique();
			for (String::List::iterator i = mod_list.begin() ; i != mod_list.end() ; ++i)
			{
				obj->Text.push_back( *i );
				if (ToLower( *i ) == ToLower(current_selection))
					obj->Text[0] = *i;
			}
		}

		pArea->caption("*.player_name", lp_CONFIG->player_name);

		if (pArea->get_object("*.skin"))
		{
			Gui::GUIOBJ::Ptr obj = pArea->get_object("*.skin");

			obj->Text.resize(1);
			obj->Text[0] = I18N::Translate( "default.skn");

			String::Vector skin_list;
			VFS::Instance()->getFilelist("gui\\*.skn", skin_list);

			String skin_name;
			const String::Vector::iterator end = skin_list.end();
			for (String::Vector::iterator i = skin_list.begin(); i != end; ++i)
			{
				skin_name = Paths::ExtractFileName(*i, false);
				obj->Text.push_back(skin_name);
				if (String("gui/") << ToLower(skin_name) == ToLower(lp_CONFIG->skin_name))
					obj->Text[0] = skin_name;
			}
		}

		if (pArea->get_object("*.l_files"))
		{
			Gui::GUIOBJ::Ptr obj = pArea->get_object("*.l_files");
			sound_manager->getPlayListFiles(obj->Text);
		}

		if (lp_CONFIG->quickstart)
			I_Msg( TA3D::TA3D_IM_GUI_MSG, "config_confirm.show");

		save = false;
		timer = msec_timer;

		return true;
	}
コード例 #28
0
ファイル: Workspace.cpp プロジェクト: kolyden/mirror
bool IsCSourceFile(const char *path)
{
	String ext = ToLower(GetFileExt(path));
	return ext == ".cpp" || ext == ".c" || ext == ".cc" || ext == ".cxx"
	                     || ext == ".m" || ext == ".mm" || ext == ".icpp";
}
コード例 #29
0
ファイル: GlueFile.cpp プロジェクト: jason-amju/amjulib
bool GlueFile::AddItem(const std::string& filename)
{
  AMJU_CALL_STACK;

  string lowname = ToLower(filename);

  // Convert \ to /
  // So we can add files in subdirs in DOS, which uses "\", and use "/" to 
  //  retrieve the subdirs 
  lowname = Replace(lowname, "\\", "/"); 

  // Check for sub-file already existing.
  if (m_table.find(lowname) != m_table.end())
  {
    // Sub-file already exists
    std::string s = "GLUE FILE: file already exists in glue file: ";
    s += filename;
    ReportError(s);
    return false;
  }

  // Stick the contents of the file onto the end of the final sub-file.
  // Then update the number of files, the table position, and
  // rewrite the table.
  
  // Get the new sub-file size.
  struct stat buf;  
  if (stat(filename.c_str(), &buf) != 0)
  {
    // Couldn't get info for the sub-file. 
    std::string s = "GLUE FILE: failed to stat file: ";
    s += filename;
    ReportError(s);
    return false;
  }

  uint32 subfilesize = buf.st_size;

  // Open the new sub-file for reading.
  ifstream subfile;
  subfile.open(filename.c_str(), ios::in | ios::binary);
  if (!subfile.is_open())
  {
    std::string s = "GLUE FILE: failed to open file for reading: ";
    s += filename;
    ReportError(s);
    return false;
  }

  // Work out where the new sub-file should go in the GlueFile.
  // It's the position of the final sub-file plus its size.
  uint32 newpos = BASE;
  FileList::reverse_iterator rit = m_filenames.rbegin();
  if (rit != m_filenames.rend())
  {
    string last = *rit;
    uint32 lastsize = (m_table[last]).first;
    uint32 lastpos = (m_table[last]).second;
    newpos = lastpos + lastsize;
  } 
  // Seek to the new position.
  m_gluefile.seekg(newpos);

  // Write the new sub-file to the GlueFile.
#ifdef GLUE_FILE_DEBUG
std::cout << "GLUE FILE: Writing file " << filename.c_str() << " starting at pos: " << newpos << " size: " << subfilesize << "\n";
#endif
  unsigned char* filebuf = new unsigned char[subfilesize];
  subfile.read((char*)filebuf, subfilesize);
  m_gluefile.write((char*)filebuf, subfilesize);
  delete [] filebuf;

  // Add the new sub-file to the table.
  m_table[lowname] = make_pair(subfilesize, newpos);
  // This reorders m_table, so we also maintain a list of the files
  // in the order in which they were added to the glue file.
  m_filenames.push_back(lowname);

  // New table position
  m_tablePos += subfilesize;

  // Rewrite the table.
  WriteTable();

  return true;
}
コード例 #30
0
ファイル: bbAuth.c プロジェクト: tsupo/bookey
void
doYahooStep1(
        char       *buffer,
        const char *target,
        const char *username,
        const char *password,
        char       *cookie,
        size_t     *cookieSize
    )
{
    char    *request;
    char    *p, *q;
    char    src[MAX_NAMELEN];
    char    done[MAX_WEBPAGENAME];
    char    challenge[MAX_KEYLENGTH];
    char    u[MAX_USERIDLEN];
    char    passwd[BUFSIZ * 2];
    char    url[BUFSIZ * 2];
    int     tries     = 1;
    BOOL    escapeURL = TRUE;

    dputs( "doYahooStep1(): 実行開始\n" );

    // Yahoo! Japan にログイン
    request  = (char *)malloc( RCV_BUFFER_SIZE );
    if ( !request ) 
        return;

    src[0]       = NUL;
    done[0]      = NUL;
    challenge[0] = NUL;
    u[0]         = NUL;
    passwd[0]    = NUL;

    p = strstr( buffer, "name=\".tries\" value=\"" );
    if ( p ) {
        p += 21;
        q = strchr( p, '"' );
        if ( q ) {
            char    buf[BUFSIZ];

            strncpy( buf, p, q - p );
            buf[q - p] = NUL;
            tries = atol( buf );
        }
    }

    p = strstr( buffer, "name=\".src\" value=\"" );
    if ( p ) {
        p += 19;
        q = strchr( p, '"' );
        if ( q ) {
            strncpy( src, p, q - p );
            src[q - p] = NUL;
        }
    }
    p = strstr( buffer, "name=\".done\" value=\"" );
    if ( p ) {
        p += 20;
        q = strchr( p, '"' );
        if ( q ) {
            strncpy( done, p, q - p );
            done[q - p] = NUL;
        }
    }
    p = strstr( buffer, "name=\".challenge\" value=\"" );
    if ( p ) {
        p += 25;
        q = strchr( p, '"' );
        if ( q ) {
            strncpy( challenge, p, q - p );
            challenge[q - p] = NUL;
        }
    }
    p = strstr( buffer, "name=\".u\" value=\"" );
    if ( p ) {
        p += 17;
        q = strchr( p, '"' );
        if ( q ) {
            strncpy( u, p, q - p );
            u[q - p] = NUL;
        }
    }

    sprintf( passwd, "%s%s", ToLower(MD5(password)), challenge );
    strcpy( passwd, ToLower( MD5( passwd ) ) );

    strcpy( done, translateURL( done ) );
    p = strstr( done, "appdata" );
    if ( p ) {
        char    *r;
        p += 7;
        while ( ((q = strstr( p, "%3A" )) != NULL) ||
                ((q = strstr( p, "%2F" )) != NULL) ||
                ((q = strstr( p, "%2E" )) != NULL)    ) {
            r = p + strlen( p );
            while ( r > q ) {
                *(r + 2) = *r;
                r--;
            }
            *++q = '2';
            *++q = '5';
        }
    }

    strcpy( url, "http://login.yahoo.co.jp/config/login?" );
    sprintf( request,
             ".tries=%d&"
             ".src=%s&"
             ".md5=&"
             ".hash=&"
             ".js=1&"
             ".last=&"
             "promo=&"
             ".intl=jp&"
             ".bypass=&"
             ".partner=&"
             ".u=%s&"
             ".v=0&"
             ".challenge=%s&"
             ".yplus=&"
             ".emailCode=&"
             "pkg=&"
             "stepid=&"
             ".ev=&"
             "hasMsgr=0&"
             ".chkP=Y&"
             ".done=%s&"
             ".pd=&"
             ".protoctl=&"
             "login=%s&"
             "passwd=%s&"
             ".persistent=y&"
             ".hash=1&"
             ".md5=1",
             tries,
             src,
             u,
             challenge,
             done,
             username,
             passwd );
    strcat( url, request );

    if ( !strcmp( src, "ba_newsing" ) )
        escapeURL = FALSE;

    _httpGetIC( url, buffer, FALSE, escapeURL );
    if ( *buffer )
        doYahooStep1a( buffer, request, target,
                       username, password, cookie, cookieSize );

    free( request );
}