<commit_before>/*
memgrep a tool to grep accross processes on Windows

Released as open source by NCC Group Plc - http://www.nccgroup.com/

Developed by Ollie Whitehouse, ollie dot whitehouse at nccgroup dot com

https://github.com/nccgroup/memgrep

Released under AGPL see LICENSE for more information
*/

#include "stdafx.h"
#include "XGetopt.h"

// Globals
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
bool bDumpHex = false;

//
//
//
// Notes: http://druid.caughq.org/src/printhex.c
//
void printhex( unsigned char *buf, int size ) {
	int x, y;

	for( x=1; x<=size; x++ ) {

		if( x == 1 ) printf( "%04x  ", x-1 ); /* Print an offset line header */

		printf( "%02x ", buf[x-1] ); /* print the hex value */

		if( x % 8 == 0 ) printf( " " ); /* padding space at 8 and 16 bytes */

		if( x % 16 == 0 ) {
			/* We're at the end of a line of hex, print the printables */
			printf( " " );
			for( y = x - 15; y <= x; y++ ) {
				if( isprint( buf[y-1] ) ) printf( "%c", buf[y-1] ); /* if it's printable, print it */
				else printf( "." ); /* otherwise substitute a period */
				if( y % 8 == 0 ) printf( " " ); /* 8 byte padding space */
			}
			if( x < size ) printf( "\n%04x  ", x ); /* Print an offset line header */
		}
	}
	x--;

	/* If we didn't end on a 16 byte boundary, print some placeholder spaces before printing ascii */
	if( x % 16 != 0 ) {
		for( y = x+1; y <= x + (16-(x % 16)); y++ ) {
			printf( "   " ); /* hex value placeholder spaces */
			if( y % 8 == 0 ) printf( " " ); /* 8 and 16 byte padding spaces */
		};

		/* print the printables */
		printf( " " );
		for( y = (x+1) - (x % 16); y <= x; y++ ) {
			if( isprint( buf[y-1] ) ) printf( "%c", buf[y-1] ); /* if it's printable, print it */
			else printf( "." ); /* otherwise substitute a period */
			if( y % 8 == 0 ) printf( " " ); /* 8 and 16 byte padding space */
		}
	}

	/* Done! */
	printf( "\n" );
}

#ifdef WIN64
void PrintMemInfo(MEMORY_BASIC_INFORMATION64 memMeminfo)
#endif
#ifdef WIN32
void PrintMemInfo(MEMORY_BASIC_INFORMATION memMeminfo)
#endif
{

	switch (memMeminfo.AllocationProtect)
	{
		case PAGE_EXECUTE:
			fprintf(stdout,"[  x  ]");
			break;
		case PAGE_EXECUTE_READ:
			fprintf(stdout,"[r x  ]");
			break;
		case PAGE_EXECUTE_READWRITE:
			fprintf(stdout,"[rwx  ]");
			break;
		case PAGE_EXECUTE_WRITECOPY:
			fprintf(stdout,"[ wxc ]");
			break;
		case PAGE_NOACCESS:
			fprintf(stdout,"[     ]");
			break;
		case PAGE_READONLY:
			fprintf(stdout,"[r    ]");
			break;
		case PAGE_READWRITE:
			fprintf(stdout,"[rw   ]");
			break;
		case PAGE_WRITECOPY:
			fprintf(stdout,"[ w c ]");
			break;
	}

	switch (memMeminfo.Type){
		case MEM_IMAGE:
			fprintf(stdout," - image\n");
			break;
		case MEM_MAPPED:
			fprintf(stdout," - mapped\n");
			break;
		case MEM_PRIVATE:
			fprintf(stdout," - private\n");
			break;
	}
}

//
// Function	: ReadAndGrep
// Role		: Reads the process memory into our address space then we search it...
// Notes	:
//
#ifdef WIN64
void ReadAndGrep(SIZE_T szSize, ULONG_PTR lngAddress, HANDLE hProcess, char *strString, MEMORY_BASIC_INFORMATION64 memMeminfo)
#endif
#ifdef WIN32
void ReadAndGrep(SIZE_T szSize, ULONG_PTR lngAddress, HANDLE hProcess, char *strString, MEMORY_BASIC_INFORMATION memMeminfo)
#endif
{
	SIZE_T szBytesRead=0;
	unsigned char *strBuffer=(unsigned char *)VirtualAlloc(0,szSize+1024,MEM_COMMIT,PAGE_READWRITE);
	unsigned char *strBufferNow = strBuffer;
	unsigned char *strBufferEnd = (strBuffer + szSize) - (strlen(strString) +1);
	unsigned int intCounter =0;
	if(strBuffer==NULL) return;

	if(ReadProcessMemory(hProcess,(LPVOID)lngAddress,strBuffer,szSize,&szBytesRead)==0){
		if(GetLastError()!=299)	fprintf(stderr,"[!] Failed to read process memory %d at %p read %ld\n",GetLastError(),lngAddress,szBytesRead);
	} else {

		while(strBufferNow<strBufferEnd){

			//fprintf(stdout,"[i] Searching %p which is %ld big and ends at %p\n",strBufferNow,szSize+1024,strBufferEnd);
			if (memcmp(strString,strBufferNow,strlen(strString)) == 0){
				fprintf(stdout,"[*] Got hit for %s at %p",strString,lngAddress+intCounter);
				PrintMemInfo(memMeminfo);
				if(bDumpHex) printhex(strBufferNow,(int)strlen(strString));
			} else {
				bool bMatch = true;
				for(int intCount =0; intCount<strlen(strString) && strBufferEnd < strBufferEnd + strlen(strString) + 1;intCount+=2){
					if(strBufferNow[intCount] != strString[intCount] || strBufferNow[intCount+1] != 0x00){
						bMatch = false;
					}
				}
				if(bMatch) {
					fprintf(stdout,"[*] Got unicode hit for %s at %p",strString,lngAddress+intCounter);
					PrintMemInfo(memMeminfo);
					if(bDumpHex) printhex(strBufferNow,(int)(strlen(strString)*2)+2);
				}
			}

			strBufferNow++;
			intCounter++;
		}
	}

	VirtualFree(strBuffer,szSize,MEM_RELEASE);
}

//
// Function	: OpenAndGrep
// Role		: Open a process, enumerate mapped pages of memory and pass to grep routine
// Notes	:
//
void OpenAndGrep(bool bASCII, bool bUNICODE, char* strString, DWORD dwPID)
{
	DWORD dwRet, dwMods;
	HANDLE hProcess;
	HMODULE hModule[4096];
	char cProcess[MAX_PATH]; // Process name
	SYSTEM_INFO sysnfoSysNFO;
	BOOL bIsWow64=FALSE;
	BOOL bIsWow64Other=FALSE;
	DWORD dwRES=0;

	hProcess = OpenProcess(PROCESS_ALL_ACCESS |PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwPID);
	if (hProcess == NULL)
	{
		if(GetLastError()==5){
			hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwPID);
			if (hProcess == NULL){
				fprintf(stderr,"[!] OpenProcess(%d),%d\n", dwPID, GetLastError());
				return;
			}
		} else {
			fprintf(stderr,"[!] OpenProcess(%d),%d\n", dwPID, GetLastError());
			return;
		}
	}

	if (EnumProcessModules(hProcess,hModule,4096*sizeof(HMODULE), &dwRet) == 0)
	{
		if(GetLastError() == 299){
			fprintf(stderr,"[i] 64bit process and we're 32bit - sad panda! skipping PID %d\n",dwPID);
		} else {
			fprintf(stderr,"[!] OpenAndGrep(%d),%d\n", dwPID, GetLastError());
		}
		return;
	}
	dwMods = dwRet / sizeof(HMODULE);

	GetModuleBaseName(hProcess,hModule[0],cProcess,MAX_PATH);

	if(IsWow64Process(GetCurrentProcess(),&bIsWow64)){
		GetNativeSystemInfo(&sysnfoSysNFO);

		if(bIsWow64)
		{
			//fwprintf(stdout,L"[i] Running under WOW64 - Page Size %d\n",sysnfoSysNFO.dwPageSize);
		}
		else
		{
			//fwprintf(stdout,L"[i] Not running under WOW64 - Page Size %d\n",sysnfoSysNFO.dwPageSize);
		}
	} else {
		fwprintf(stdout,L"[!] Errot\n");
		return;
	}

	fprintf(stdout,"[i] Searching %s\n",cProcess);

	//
	// Walk the processes address space
	//
	unsigned char *pString = NULL;

	ULONG_PTR addrCurrent = 0;
    ULONG_PTR lastBase = (-1);

    for(;;)
    {
#ifdef WIN64
		MEMORY_BASIC_INFORMATION64 memMeminfo;
#endif
#ifdef WIN32
		MEMORY_BASIC_INFORMATION memMeminfo;
#endif
        VirtualQueryEx(hProcess, reinterpret_cast<LPVOID>(addrCurrent), reinterpret_cast<PMEMORY_BASIC_INFORMATION>(&memMeminfo), sizeof(memMeminfo) );

        if(lastBase == (ULONG_PTR) memMeminfo.BaseAddress) {
            break;
        }

        lastBase = (ULONG_PTR) memMeminfo.BaseAddress;

        if(memMeminfo.State == MEM_COMMIT) {
            //fprintf(stdout,"[i] %p\n", memMeminfo.BaseAddress);
			//fprintf(stdout,"[i] %ld\n", memMeminfo.RegionSize);
			ReadAndGrep(memMeminfo.RegionSize,(ULONG_PTR) memMeminfo.BaseAddress,hProcess,strString,memMeminfo);
        }

        addrCurrent += memMeminfo.RegionSize;
    }
}

//
// Function	: EnumerateProcesses
// Role		: Basic processes running
// Notes	:
//
void EnumerateProcesses(bool bASCII, bool bUNICODE, char* strString)
{
	DWORD dwPIDArray[2048], dwRet, dwPIDS, intCount;

	if (EnumProcesses(dwPIDArray,2048*sizeof(DWORD),&dwRet) == 0)
	{
		fprintf(stderr,"[!]  EnumProcesses(),%d\n", GetLastError());
		return;
	}

	dwPIDS = dwRet / sizeof(DWORD);

	for(intCount=0;intCount<dwPIDS;intCount++)
	{
		if(dwPIDArray[intCount] != GetCurrentProcessId()){
			OpenAndGrep(bASCII,bUNICODE,strString,dwPIDArray[intCount]);
		} else {
			fprintf(stdout,"[i] Skipping myself\n");
		}
	}
}

//
// Function	: SetDebugPrivilege
// Role		: Gets debug privs for our process
// Notes	:
//
BOOL SetDebugPrivilege(HANDLE hProcess)
{
	LUID luid ;
	TOKEN_PRIVILEGES privs ;
	HANDLE hToken = NULL ;
	DWORD dwBufLen = 0 ;
	char buf[1024] ;

	ZeroMemory( &luid,sizeof(luid) ) ;

	if(! LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &luid ))
		return false ;

	privs.PrivilegeCount = 1 ;
	privs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED ;
	memcpy( &privs.Privileges[0].Luid, &luid, sizeof(privs.Privileges[0].Luid )
		) ;

	if( ! OpenProcessToken( hProcess, TOKEN_ALL_ACCESS,&hToken))
		return false ;

	if( !AdjustTokenPrivileges( hToken, FALSE, &privs,
		sizeof(buf),(PTOKEN_PRIVILEGES)buf, &dwBufLen ) )
		return false ;

	CloseHandle(hProcess);
	CloseHandle(hToken);

	return true ;
}

//
// Function	: PrintHelp
// Role		:
// Notes	:
//
void PrintHelp(char *strExe){

	fprintf (stdout,"    i.e. %s -s <string>\n",strExe);
	fprintf (stdout,"    -s <string> to search for\n");
	fprintf (stdout,"    -x dump hex\n");
	fprintf (stdout,"\n");
	ExitProcess(1);
}

//
// Function	: _tmain
// Role		: Entry point
// Notes	:
//

int _tmain(int argc, _TCHAR* argv[])
{
	char	chOpt;
	char	*strString = NULL;

	// Extract all the options
	while ((chOpt = getopt(argc, argv, _T("s:xh"))) != EOF)
	switch(chOpt)
	{
		case _T('s'):
			strString = optarg;
			break;
		case _T('x'):
			bDumpHex = true;
			break;
		default:
			fwprintf(stderr,L"[!] No handler - %c\n", chOpt);
			break;
	}

	if(strString == NULL){
		PrintHelp(argv[0]);
		return -1;
	}

	SetDebugPrivilege(GetCurrentProcess());
	EnumerateProcesses(true,true,strString);
	return 0;
}

<commit_msg>Added searching a specific PID supplied on the command line, also fixed a bug in the UNICODE search<commit_after>/*
memgrep a tool to grep accross processes on Windows

Released as open source by NCC Group Plc - http://www.nccgroup.com/

Developed by Ollie Whitehouse, ollie dot whitehouse at nccgroup dot com

https://github.com/nccgroup/memgrep

Released under AGPL see LICENSE for more information
*/

#include "stdafx.h"
#include "XGetopt.h"

// Globals
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
bool bDumpHex = false;

//
//
//
// Notes: http://druid.caughq.org/src/printhex.c
//
void printhex( unsigned char *buf, int size ) {
	int x, y;

	for( x=1; x<=size; x++ ) {

		if( x == 1 ) printf( "%04x  ", x-1 ); /* Print an offset line header */

		printf( "%02x ", buf[x-1] ); /* print the hex value */

		if( x % 8 == 0 ) printf( " " ); /* padding space at 8 and 16 bytes */

		if( x % 16 == 0 ) {
			/* We're at the end of a line of hex, print the printables */
			printf( " " );
			for( y = x - 15; y <= x; y++ ) {
				if( isprint( buf[y-1] ) ) printf( "%c", buf[y-1] ); /* if it's printable, print it */
				else printf( "." ); /* otherwise substitute a period */
				if( y % 8 == 0 ) printf( " " ); /* 8 byte padding space */
			}
			if( x < size ) printf( "\n%04x  ", x ); /* Print an offset line header */
		}
	}
	x--;

	/* If we didn't end on a 16 byte boundary, print some placeholder spaces before printing ascii */
	if( x % 16 != 0 ) {
		for( y = x+1; y <= x + (16-(x % 16)); y++ ) {
			printf( "   " ); /* hex value placeholder spaces */
			if( y % 8 == 0 ) printf( " " ); /* 8 and 16 byte padding spaces */
		};

		/* print the printables */
		printf( " " );
		for( y = (x+1) - (x % 16); y <= x; y++ ) {
			if( isprint( buf[y-1] ) ) printf( "%c", buf[y-1] ); /* if it's printable, print it */
			else printf( "." ); /* otherwise substitute a period */
			if( y % 8 == 0 ) printf( " " ); /* 8 and 16 byte padding space */
		}
	}

	/* Done! */
	printf( "\n" );
}

#ifdef WIN64
void PrintMemInfo(MEMORY_BASIC_INFORMATION64 memMeminfo)
#endif
#ifdef WIN32
void PrintMemInfo(MEMORY_BASIC_INFORMATION memMeminfo)
#endif
{

	switch (memMeminfo.AllocationProtect)
	{
		case PAGE_EXECUTE:
			fprintf(stdout,"[  x  ]");
			break;
		case PAGE_EXECUTE_READ:
			fprintf(stdout,"[r x  ]");
			break;
		case PAGE_EXECUTE_READWRITE:
			fprintf(stdout,"[rwx  ]");
			break;
		case PAGE_EXECUTE_WRITECOPY:
			fprintf(stdout,"[ wxc ]");
			break;
		case PAGE_NOACCESS:
			fprintf(stdout,"[     ]");
			break;
		case PAGE_READONLY:
			fprintf(stdout,"[r    ]");
			break;
		case PAGE_READWRITE:
			fprintf(stdout,"[rw   ]");
			break;
		case PAGE_WRITECOPY:
			fprintf(stdout,"[ w c ]");
			break;
	}

	switch (memMeminfo.Type){
		case MEM_IMAGE:
			fprintf(stdout," - image\n");
			break;
		case MEM_MAPPED:
			fprintf(stdout," - mapped\n");
			break;
		case MEM_PRIVATE:
			fprintf(stdout," - private\n");
			break;
	}
}

//
// Function	: ReadAndGrep
// Role		: Reads the process memory into our address space then we search it...
// Notes	:
//
#ifdef WIN64
void ReadAndGrep(SIZE_T szSize, ULONG_PTR lngAddress, HANDLE hProcess, char *strString, MEMORY_BASIC_INFORMATION64 memMeminfo)
#endif
#ifdef WIN32
void ReadAndGrep(SIZE_T szSize, ULONG_PTR lngAddress, HANDLE hProcess, char *strString, MEMORY_BASIC_INFORMATION memMeminfo)
#endif
{
	SIZE_T szBytesRead=0;
	unsigned char *strBuffer=(unsigned char *)VirtualAlloc(0,szSize+1024,MEM_COMMIT,PAGE_READWRITE);
	unsigned char *strBufferNow = strBuffer;
	unsigned char *strBufferEnd = (strBuffer + szSize) - (strlen(strString) +1);
	unsigned int intCounter =0;
	if(strBuffer==NULL) return;

	if(ReadProcessMemory(hProcess,(LPVOID)lngAddress,strBuffer,szSize,&szBytesRead)==0){
		if(GetLastError()!=299)	fprintf(stderr,"[!] Failed to read process memory %d at %p read %ld\n",GetLastError(),lngAddress,szBytesRead);
	} else {

		while(strBufferNow<strBufferEnd){

			//fprintf(stdout,"[i] Searching %p which is %ld big and ends at %p\n",strBufferNow,szSize+1024,strBufferEnd);
			if (memcmp(strString,strBufferNow,strlen(strString)) == 0){
				fprintf(stdout,"[*] Got hit for %s at %p",strString,lngAddress+intCounter);
				PrintMemInfo(memMeminfo);
				if(bDumpHex) printhex(strBufferNow,(int)strlen(strString));
			} else {

				bool bMatch = true;

				int intCount2 = 0;

				for(int intCount =0; intCount<strlen(strString)*2 && strBufferEnd < strBufferEnd + strlen(strString) + 1; intCount+=2){

					if(strBufferNow[intCount] != strString[intCount2] || strBufferNow[intCount+1] != 0x00){
						bMatch = false;
						break;
					}

					intCount2++;

				}

				if(bMatch) {
					fprintf(stdout,"[*] Got unicode hit for %s at %p",strString,lngAddress+intCounter);
					PrintMemInfo(memMeminfo);
					if(bDumpHex) printhex(strBufferNow,(int)(strlen(strString)*2)+2);
				}
			}

			strBufferNow++;
			intCounter++;
		}
	}

	VirtualFree(strBuffer,szSize,MEM_RELEASE);
}

//
// Function	: OpenAndGrep
// Role		: Open a process, enumerate mapped pages of memory and pass to grep routine
// Notes	:
//
void OpenAndGrep(bool bASCII, bool bUNICODE, char* strString, DWORD dwPID)
{
	DWORD dwRet, dwMods;
	HANDLE hProcess;
	HMODULE hModule[4096];
	char cProcess[MAX_PATH]; // Process name
	SYSTEM_INFO sysnfoSysNFO;
	BOOL bIsWow64=FALSE;
	BOOL bIsWow64Other=FALSE;
	DWORD dwRES=0;

	hProcess = OpenProcess(PROCESS_ALL_ACCESS |PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwPID);
	if (hProcess == NULL)
	{
		if(GetLastError()==5){
			hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwPID);
			if (hProcess == NULL){
				fprintf(stderr,"[!] Failed to OpenProcess(%d),%d\n", dwPID, GetLastError());
				return;
			}
		} else {
			fprintf(stderr,"[!] Failed to OpenProcess(%d),%d\n", dwPID, GetLastError());
			return;
		}
	}

	if (EnumProcessModules(hProcess,hModule,4096*sizeof(HMODULE), &dwRet) == 0)
	{
		if(GetLastError() == 299){
			fprintf(stderr,"[i] 64bit process and we're 32bit - sad panda! skipping PID %d\n",dwPID);
		} else {
			fprintf(stderr,"[!] OpenAndGrep(%d),%d\n", dwPID, GetLastError());
		}
		return;
	}
	dwMods = dwRet / sizeof(HMODULE);

	GetModuleBaseName(hProcess,hModule[0],cProcess,MAX_PATH);

	if(IsWow64Process(GetCurrentProcess(),&bIsWow64)){
		GetNativeSystemInfo(&sysnfoSysNFO);

		if(bIsWow64)
		{
			//fwprintf(stdout,L"[i] Running under WOW64 - Page Size %d\n",sysnfoSysNFO.dwPageSize);
		}
		else
		{
			//fwprintf(stdout,L"[i] Not running under WOW64 - Page Size %d\n",sysnfoSysNFO.dwPageSize);
		}
	} else {
		fwprintf(stdout,L"[!] Errot\n");
		return;
	}

	fprintf(stdout,"[i] Searching %s - %d\n",cProcess, dwPID);

	//
	// Walk the processes address space
	//
	unsigned char *pString = NULL;

	ULONG_PTR addrCurrent = 0;
    ULONG_PTR lastBase = (-1);

    for(;;)
    {
#ifdef WIN64
		MEMORY_BASIC_INFORMATION64 memMeminfo;
#endif
#ifdef WIN32
		MEMORY_BASIC_INFORMATION memMeminfo;
#endif
        VirtualQueryEx(hProcess, reinterpret_cast<LPVOID>(addrCurrent), reinterpret_cast<PMEMORY_BASIC_INFORMATION>(&memMeminfo), sizeof(memMeminfo) );

        if(lastBase == (ULONG_PTR) memMeminfo.BaseAddress) {
            break;
        }

        lastBase = (ULONG_PTR) memMeminfo.BaseAddress;

        if(memMeminfo.State == MEM_COMMIT) {
            //fprintf(stdout,"[i] %p\n", memMeminfo.BaseAddress);
			//fprintf(stdout,"[i] %ld\n", memMeminfo.RegionSize);
			ReadAndGrep(memMeminfo.RegionSize,(ULONG_PTR) memMeminfo.BaseAddress,hProcess,strString,memMeminfo);
        }

        addrCurrent += memMeminfo.RegionSize;
    }
}

//
// Function	: EnumerateProcesses
// Role		: Basic processes running
// Notes	:
//
void EnumerateProcesses(bool bASCII, bool bUNICODE, char* strString)
{
	DWORD dwPIDArray[2048], dwRet, dwPIDS, intCount;

	if (EnumProcesses(dwPIDArray,2048*sizeof(DWORD),&dwRet) == 0)
	{
		fprintf(stderr,"[!]  EnumProcesses(),%d\n", GetLastError());
		return;
	}

	dwPIDS = dwRet / sizeof(DWORD);

	for(intCount=0;intCount<dwPIDS;intCount++)
	{
		if(dwPIDArray[intCount] != GetCurrentProcessId()){
			OpenAndGrep(bASCII,bUNICODE,strString,dwPIDArray[intCount]);
		} else {
			fprintf(stdout,"[i] Skipping myself\n");
		}
	}
}

//
// Function	: SetDebugPrivilege
// Role		: Gets debug privs for our process
// Notes	:
//
BOOL SetDebugPrivilege(HANDLE hProcess)
{
	LUID luid ;
	TOKEN_PRIVILEGES privs ;
	HANDLE hToken = NULL ;
	DWORD dwBufLen = 0 ;
	char buf[1024] ;

	ZeroMemory( &luid,sizeof(luid) ) ;

	if(! LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &luid ))
		return false ;

	privs.PrivilegeCount = 1 ;
	privs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED ;
	memcpy( &privs.Privileges[0].Luid, &luid, sizeof(privs.Privileges[0].Luid )
		) ;

	if( ! OpenProcessToken( hProcess, TOKEN_ALL_ACCESS,&hToken))
		return false ;

	if( !AdjustTokenPrivileges( hToken, FALSE, &privs,
		sizeof(buf),(PTOKEN_PRIVILEGES)buf, &dwBufLen ) )
		return false ;

	CloseHandle(hProcess);
	CloseHandle(hToken);

	return true ;
}

//
// Function	: PrintHelp
// Role		:
// Notes	:
//
void PrintHelp(char *strExe){

	fprintf (stdout,"    i.e. %s -s <string>\n",strExe);
	fprintf (stdout,"    -s <string> to search for\n");
	fprintf (stdout,"    -x dump hex\n");
	fprintf (stdout,"\n");
	ExitProcess(1);
}

//
// Function	: _tmain
// Role		: Entry point
// Notes	:
//

int _tmain(int argc, _TCHAR* argv[])
{
	char	chOpt;
	char	*strString = NULL;
	DWORD	dwPID = 0;

	// Extract all the options
	while ((chOpt = getopt(argc, argv, _T("s:p:xh"))) != EOF)
	switch(chOpt)
	{
		case _T('s'):
			strString = optarg;
			break;
		case _T('x'):
			bDumpHex = true;
			break;
		case _T('p'):
			dwPID = atoi(optarg);
			break;
		default:
			fwprintf(stderr,L"[!] No handler - %c\n", chOpt);
			break;
	}

	if(strString == NULL){
		PrintHelp(argv[0]);
		return -1;
	}

	SetDebugPrivilege(GetCurrentProcess());

	if(dwPID != 0 ){
		OpenAndGrep(true,true,strString,dwPID);
	} else {
		EnumerateProcesses(true,true,strString);
	}
	return 0;
}

<|endoftext|>


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

#include <iostream>

#include "yg1006.h"

using namespace upm;
using namespace std;

YG1006::YG1006(int pin)
{
  if ( !(m_gpio = mraa_gpio_init(pin)) )
    {
      cerr << __FUNCTION__ << ": mraa_gpio_init() failed" << endl;
      return;
    }

  mraa_gpio_dir(m_gpio, MRAA_GPIO_IN);
}

YG1006::~YG1006()
{
  mraa_gpio_close(m_gpio);
}

bool YG1006::flameDetected()
{
  return (!mraa_gpio_read(m_gpio) ? true : false);
}
<commit_msg>yg1006: throw exception(s) on fatal errors<commit_after>/*
 * Author: Jon Trulson <jtrulson@ics.com>
 * Copyright (c) 2014 Intel Corporation.
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include <iostream>
#include <string>
#include <stdexcept>

#include "yg1006.h"

using namespace upm;
using namespace std;

YG1006::YG1006(int pin)
{
  if ( !(m_gpio = mraa_gpio_init(pin)) )
    {
      throw std::invalid_argument(std::string(__FUNCTION__) +
                                  ": mraa_gpio_init() failed, invalid pin?");
      return;
    }

  mraa_gpio_dir(m_gpio, MRAA_GPIO_IN);
}

YG1006::~YG1006()
{
  mraa_gpio_close(m_gpio);
}

bool YG1006::flameDetected()
{
  return (!mraa_gpio_read(m_gpio) ? true : false);
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_FWD_MAT_HPP
#define STAN_MATH_FWD_MAT_HPP

#include <stan/math/fwd/core.hpp>
#include <stan/math/fwd/scal/meta/is_fvar.hpp>
#include <stan/math/fwd/scal/meta/partials_type.hpp>

#include <stan/math/fwd/mat/vectorize/apply_scalar_unary.hpp>
#include <stan/math/prim/mat.hpp>
#include <stan/math/fwd/arr.hpp>

#include <stan/math/fwd/mat/fun/Eigen_NumTraits.hpp>
#include <stan/math/fwd/mat/fun/columns_dot_product.hpp>
#include <stan/math/fwd/mat/fun/columns_dot_self.hpp>
#include <stan/math/fwd/mat/fun/crossprod.hpp>
#include <stan/math/fwd/mat/fun/determinant.hpp>
#include <stan/math/fwd/mat/fun/divide.hpp>
#include <stan/math/fwd/mat/fun/dot_product.hpp>
#include <stan/math/fwd/mat/fun/dot_self.hpp>
#include <stan/math/fwd/mat/fun/inverse.hpp>
#include <stan/math/fwd/mat/fun/log_determinant.hpp>
#include <stan/math/fwd/mat/fun/log_softmax.hpp>
#include <stan/math/fwd/mat/fun/log_sum_exp.hpp>
#include <stan/math/fwd/mat/fun/mdivide_left.hpp>
#include <stan/math/fwd/mat/fun/mdivide_left_ldlt.hpp>
#include <stan/math/fwd/mat/fun/mdivide_left_tri_low.hpp>
#include <stan/math/fwd/mat/fun/mdivide_right.hpp>
#include <stan/math/fwd/mat/fun/mdivide_right_tri_low.hpp>
#include <stan/math/fwd/mat/fun/multiply.hpp>
#include <stan/math/fwd/mat/fun/multiply_lower_tri_self_transpose.hpp>
#include <stan/math/fwd/mat/fun/qr_Q.hpp>
#include <stan/math/fwd/mat/fun/qr_R.hpp>
#include <stan/math/fwd/mat/fun/quad_form_sym.hpp>
#include <stan/math/fwd/mat/fun/rows_dot_product.hpp>
#include <stan/math/fwd/mat/fun/rows_dot_self.hpp>
#include <stan/math/fwd/mat/fun/softmax.hpp>
#include <stan/math/fwd/mat/fun/squared_distance.hpp>
#include <stan/math/fwd/mat/fun/sum.hpp>
#include <stan/math/fwd/mat/fun/tcrossprod.hpp>
#include <stan/math/fwd/mat/fun/to_fvar.hpp>
#include <stan/math/fwd/mat/fun/trace_gen_quad_form.hpp>
#include <stan/math/fwd/mat/fun/trace_quad_form.hpp>
#include <stan/math/fwd/mat/fun/typedefs.hpp>
#include <stan/math/fwd/mat/fun/unit_vector_constrain.hpp>

#include <stan/math/fwd/mat/functor/gradient.hpp>
#include <stan/math/fwd/mat/functor/hessian.hpp>
#include <stan/math/fwd/mat/functor/jacobian.hpp>

#include <stan/math/fwd/mat/meta/operands_and_partials.hpp>

#endif
<commit_msg>reordering fwd/mat.hpp properly<commit_after>#ifndef STAN_MATH_FWD_MAT_HPP
#define STAN_MATH_FWD_MAT_HPP

#include <stan/math/fwd/core.hpp>
#include <stan/math/fwd/scal/meta/is_fvar.hpp>
#include <stan/math/fwd/scal/meta/partials_type.hpp>
#include <stan/math/fwd/mat/meta/operands_and_partials.hpp>

#include <stan/math/fwd/mat/vectorize/apply_scalar_unary.hpp>
#include <stan/math/prim/mat.hpp>
#include <stan/math/fwd/arr.hpp>

#include <stan/math/fwd/mat/fun/Eigen_NumTraits.hpp>
#include <stan/math/fwd/mat/fun/columns_dot_product.hpp>
#include <stan/math/fwd/mat/fun/columns_dot_self.hpp>
#include <stan/math/fwd/mat/fun/crossprod.hpp>
#include <stan/math/fwd/mat/fun/determinant.hpp>
#include <stan/math/fwd/mat/fun/divide.hpp>
#include <stan/math/fwd/mat/fun/dot_product.hpp>
#include <stan/math/fwd/mat/fun/dot_self.hpp>
#include <stan/math/fwd/mat/fun/inverse.hpp>
#include <stan/math/fwd/mat/fun/log_determinant.hpp>
#include <stan/math/fwd/mat/fun/log_softmax.hpp>
#include <stan/math/fwd/mat/fun/log_sum_exp.hpp>
#include <stan/math/fwd/mat/fun/mdivide_left.hpp>
#include <stan/math/fwd/mat/fun/mdivide_left_ldlt.hpp>
#include <stan/math/fwd/mat/fun/mdivide_left_tri_low.hpp>
#include <stan/math/fwd/mat/fun/mdivide_right.hpp>
#include <stan/math/fwd/mat/fun/mdivide_right_tri_low.hpp>
#include <stan/math/fwd/mat/fun/multiply.hpp>
#include <stan/math/fwd/mat/fun/multiply_lower_tri_self_transpose.hpp>
#include <stan/math/fwd/mat/fun/qr_Q.hpp>
#include <stan/math/fwd/mat/fun/qr_R.hpp>
#include <stan/math/fwd/mat/fun/quad_form_sym.hpp>
#include <stan/math/fwd/mat/fun/rows_dot_product.hpp>
#include <stan/math/fwd/mat/fun/rows_dot_self.hpp>
#include <stan/math/fwd/mat/fun/softmax.hpp>
#include <stan/math/fwd/mat/fun/squared_distance.hpp>
#include <stan/math/fwd/mat/fun/sum.hpp>
#include <stan/math/fwd/mat/fun/tcrossprod.hpp>
#include <stan/math/fwd/mat/fun/to_fvar.hpp>
#include <stan/math/fwd/mat/fun/trace_gen_quad_form.hpp>
#include <stan/math/fwd/mat/fun/trace_quad_form.hpp>
#include <stan/math/fwd/mat/fun/typedefs.hpp>
#include <stan/math/fwd/mat/fun/unit_vector_constrain.hpp>

#include <stan/math/fwd/mat/functor/gradient.hpp>
#include <stan/math/fwd/mat/functor/hessian.hpp>
#include <stan/math/fwd/mat/functor/jacobian.hpp>

#endif
<|endoftext|>


<commit_before>// DormantNodeView.cpp

#include "DormantNodeView.h"
// DormantNodeView
#include "DormantNodeWindow.h"
#include "DormantNodeListItem.h"
// InfoWindow
#include "InfoWindowManager.h"

// Interface Kit
#include <Deskbar.h>
#include <Region.h>
#include <Screen.h>
#include <ScrollBar.h>
// Media Kit
#include <MediaRoster.h>
// Storage Kit
#include <Mime.h>

__USE_CORTEX_NAMESPACE

#include <Debug.h>
#define D_ALLOC(x) //PRINT (x)		// ctor/dtor
#define D_HOOK(x) //PRINT (x)		// BListView impl.
#define D_MESSAGE(x) //PRINT (x)	// MessageReceived()
#define D_INTERNAL(x) //PRINT (x)	// internal operations

// -------------------------------------------------------- //
// ctor/dtor (public)
// -------------------------------------------------------- //

DormantNodeView::DormantNodeView(
	BRect frame,
	const char *name,
	uint32 resizeMode)
	: BListView(frame, name, B_SINGLE_SELECTION_LIST, resizeMode),
	  m_lastItemUnder(0) {
	D_ALLOC(("DormantNodeView::DormantNodeView()\n"));

}

DormantNodeView::~DormantNodeView() {
	D_ALLOC(("DormantNodeView::~DormantNodeView()\n"));

}

// -------------------------------------------------------- //
// BListView impl. (public)
// -------------------------------------------------------- //

void DormantNodeView::AttachedToWindow() {
	D_HOOK(("DormantNodeView::AttachedToWindow()\n"));

	// populate the list
	_populateList();

	// Start watching the MediaRoster for flavor changes
	BMediaRoster *roster = BMediaRoster::CurrentRoster();
	if (roster) {
		BMessenger messenger(this, Window());
		roster->StartWatching(messenger, B_MEDIA_FLAVORS_CHANGED);
	}
}

void DormantNodeView::DetachedFromWindow() {
	D_HOOK(("DormantNodeView::DetachedFromWindow()\n"));

	// delete the lists contents
	_freeList();

	// Stop watching the MediaRoster for flavor changes
	BMediaRoster *roster = BMediaRoster::CurrentRoster();
	if (roster) {
		BMessenger messenger(this, Window());
		roster->StopWatching(messenger, B_MEDIA_FLAVORS_CHANGED);
	}
}

void DormantNodeView::GetPreferredSize(
	float* width,
	float* height) {
	D_HOOK(("DormantNodeView::GetPreferredSize()\n"));

	// calculate the accumulated size of all list items
	*width = 0;
	*height = 0;
	for (int32 i = 0; i < CountItems(); i++) {
		DormantNodeListItem *item;
		item = dynamic_cast<DormantNodeListItem *>(ItemAt(i));
		if (item) {
			BRect r = item->getRealFrame(be_plain_font);
			if (r.Width() > *width) {
				*width = r.Width();
			}
			*height += r.Height() + 1.0;
		}
	}
}

void DormantNodeView::MessageReceived(
	BMessage *message) {
	D_MESSAGE(("DormantNodeView::MessageReceived()\n"));

	switch (message->what) {
		case B_MEDIA_FLAVORS_CHANGED: {
			D_MESSAGE((" -> B_MEDIA_FLAVORS_CHANGED\n"));

			// init & re-populate the list
			int32 addOnID = 0;
			if (message->FindInt32("be:addon_id", &addOnID) != B_OK) {
				D_MESSAGE((" -> messages doesn't contain 'be:addon_id'!\n"));
				return;
			}
			_updateList(addOnID);
			break;
		}
		case InfoWindowManager::M_INFO_WINDOW_REQUESTED: {
			D_MESSAGE((" -> InfoWindowManager::M_INFO_WINDOW_REQUESTED)\n"));

			DormantNodeListItem *item;
			item = dynamic_cast<DormantNodeListItem *>(ItemAt(CurrentSelection()));
			if (item) {
				InfoWindowManager *manager = InfoWindowManager::Instance();
				if (manager && manager->Lock()) {
					manager->openWindowFor(item->info());
					manager->Unlock();
				}
			}
			break;
		}
		default: {
			_inherited::MessageReceived(message);
		}
	}
}

void DormantNodeView::MouseDown(
	BPoint point) {
	D_HOOK(("DormantNodeView::MouseDown()\n"));

	BMessage* message = Window()->CurrentMessage();
	int32 buttons = message->FindInt32("buttons");
	if (buttons == B_SECONDARY_MOUSE_BUTTON) {
		int32 index;
		if ((index = IndexOf(point)) >= 0) {
			DormantNodeListItem *item = dynamic_cast<DormantNodeListItem *>(ItemAt(index));
			if (item) {
				Select(index);
				BRect r = item->getRealFrame(be_plain_font);
				if (r.Contains(point)) {
					item->showContextMenu(point, this);
				}
			}
		}
	}
	else {
		_inherited::MouseDown(point);
	}
}

void DormantNodeView::MouseMoved(
	BPoint point,
	uint32 transit,
	const BMessage *message) {
	D_HOOK(("DormantNodeView::MouseMoved()\n"));

	int32 index;
	if (!message && ((index = IndexOf(point)) >= 0)) {
		DormantNodeListItem *item = dynamic_cast<DormantNodeListItem *>(ItemAt(index));
		DormantNodeListItem *last = dynamic_cast<DormantNodeListItem *>(m_lastItemUnder);
		BRect r = item->getRealFrame(be_plain_font);
		if (item && r.Contains(point)) {
			if (item != last) {
				if (last)
					last->mouseOver(this, point, B_EXITED_VIEW);
				item->mouseOver(this, point, B_ENTERED_VIEW);
				m_lastItemUnder = item;
			}
			else {
				item->mouseOver(this, point, B_INSIDE_VIEW);
			}
		}
		else if (last) {
			last->mouseOver(this, point, B_EXITED_VIEW);
		}
	}
}

bool DormantNodeView::InitiateDrag(
	BPoint point,
	int32 index,
	bool wasSelected) {
	D_HOOK(("DormantNodeView::InitiateDrag()\n"));

	DormantNodeListItem *item = dynamic_cast<DormantNodeListItem *>(ItemAt(CurrentSelection()));
	if (item) {
		BMessage dragMsg(M_INSTANTIATE_NODE);
		dragMsg.AddData("which", B_RAW_TYPE,
						reinterpret_cast<const void *>(&item->info()),
						sizeof(item->info()));
		point -= ItemFrame(index).LeftTop();
		DragMessage(&dragMsg, item->getDragBitmap(), B_OP_ALPHA, point);
		return true;
	}
	return false;
}

// -------------------------------------------------------- //
// internal operations (private)
// -------------------------------------------------------- //

void DormantNodeView::_populateList() {
	D_INTERNAL(("DormantNodeView::_populateList()\n"));

	// init the resizable node-info buffer
	BMediaRoster *roster = BMediaRoster::CurrentRoster();
	const int32 bufferInc = 64;
	int32 bufferSize = bufferInc;
	dormant_node_info *infoBuffer = new dormant_node_info[bufferSize];
	int32 numNodes;

	// fill the buffer
	while (true) {
		numNodes = bufferSize;
		status_t error = roster->GetDormantNodes(infoBuffer, &numNodes);
		if (error) {
			return;
		}
		if (numNodes < bufferSize) {
			break;
		}

		// reallocate buffer & try again
		delete [] infoBuffer;
		bufferSize += bufferInc;
		infoBuffer = new dormant_node_info[bufferSize];
	}

	// populate the list
	for (int32 i = 0; i < numNodes; i++) {
		DormantNodeListItem *item = new DormantNodeListItem(infoBuffer[i]);
		AddItem(item);
	}
	SortItems(compareName);
}

void DormantNodeView::_freeList() {
	D_HOOK(("DormantNodeView::_freeList()\n"));

	// remove and delete all items in the list
	while (CountItems() > 0) {
		BListItem *item = ItemAt(0);
		if (RemoveItem(item)) {
			delete item;
		}
	}
}

void DormantNodeView::_updateList(
	int32 addOnID) {
	D_INTERNAL(("DormantNodeView::_updateList(%ld)\n", addOnID));

	// init the resizable node-info buffer
	BMediaRoster *roster = BMediaRoster::CurrentRoster();
	const int32 bufferInc = 64;
	int32 bufferSize = bufferInc;
	dormant_node_info *infoBuffer = new dormant_node_info[bufferSize];
	int32 numNodes;

	// fill the buffer
	while (true) {
		numNodes = bufferSize;
		status_t error = roster->GetDormantNodes(infoBuffer, &numNodes);
		if (error) {
			return;
		}
		if (numNodes < bufferSize) {
			break;
		}

		// reallocate buffer & try again
		delete [] infoBuffer;
		bufferSize += bufferInc;
		infoBuffer = new dormant_node_info[bufferSize];
	}

	// sort the list by add-on id to avoid multiple searches through
	// the list
	SortItems(compareAddOnID);

	// Remove all nodes managed by this add-on
	int32 start;
	for (start = 0; start < CountItems(); start++) {
		DormantNodeListItem *item = dynamic_cast<DormantNodeListItem *>(ItemAt(start));
		if (item && (item->info().addon == addOnID)) {
			break;
		}
	}
	int32 count = 0;
	for (int32 i = start; start < CountItems(); i++) {
		DormantNodeListItem *item = dynamic_cast<DormantNodeListItem *>(ItemAt(i));
		if (!item || (item->info().addon != addOnID)) {
			break;
		}
		count++;
	}
	RemoveItems(start, count);

	// add the items
	for (int32 i = 0; i < numNodes; i++) {
		if (infoBuffer[i].addon != addOnID) {
			continue;
		}
		AddItem(new DormantNodeListItem(infoBuffer[i]));
	}

	SortItems(compareName);
}

// END -- DormantNodeView.cpp --
<commit_msg>fix broken drag behavior (hand off to base MouseXXX() methods)<commit_after>// DormantNodeView.cpp

#include "DormantNodeView.h"
// DormantNodeView
#include "DormantNodeWindow.h"
#include "DormantNodeListItem.h"
// InfoWindow
#include "InfoWindowManager.h"

// Interface Kit
#include <Deskbar.h>
#include <Region.h>
#include <Screen.h>
#include <ScrollBar.h>
// Media Kit
#include <MediaRoster.h>
// Storage Kit
#include <Mime.h>

__USE_CORTEX_NAMESPACE

#include <Debug.h>
#define D_ALLOC(x) //PRINT (x)		// ctor/dtor
#define D_HOOK(x) //PRINT (x)		// BListView impl.
#define D_MESSAGE(x) //PRINT (x)	// MessageReceived()
#define D_INTERNAL(x) //PRINT (x)	// internal operations

// -------------------------------------------------------- //
// ctor/dtor (public)
// -------------------------------------------------------- //

DormantNodeView::DormantNodeView(
	BRect frame,
	const char *name,
	uint32 resizeMode)
	: BListView(frame, name, B_SINGLE_SELECTION_LIST, resizeMode),
	  m_lastItemUnder(0) {
	D_ALLOC(("DormantNodeView::DormantNodeView()\n"));

}

DormantNodeView::~DormantNodeView() {
	D_ALLOC(("DormantNodeView::~DormantNodeView()\n"));

}

// -------------------------------------------------------- //
// BListView impl. (public)
// -------------------------------------------------------- //

void DormantNodeView::AttachedToWindow() {
	D_HOOK(("DormantNodeView::AttachedToWindow()\n"));

	// populate the list
	_populateList();

	// Start watching the MediaRoster for flavor changes
	BMediaRoster *roster = BMediaRoster::CurrentRoster();
	if (roster) {
		BMessenger messenger(this, Window());
		roster->StartWatching(messenger, B_MEDIA_FLAVORS_CHANGED);
	}
}

void DormantNodeView::DetachedFromWindow() {
	D_HOOK(("DormantNodeView::DetachedFromWindow()\n"));

	// delete the lists contents
	_freeList();

	// Stop watching the MediaRoster for flavor changes
	BMediaRoster *roster = BMediaRoster::CurrentRoster();
	if (roster) {
		BMessenger messenger(this, Window());
		roster->StopWatching(messenger, B_MEDIA_FLAVORS_CHANGED);
	}
}

void DormantNodeView::GetPreferredSize(
	float* width,
	float* height) {
	D_HOOK(("DormantNodeView::GetPreferredSize()\n"));

	// calculate the accumulated size of all list items
	*width = 0;
	*height = 0;
	for (int32 i = 0; i < CountItems(); i++) {
		DormantNodeListItem *item;
		item = dynamic_cast<DormantNodeListItem *>(ItemAt(i));
		if (item) {
			BRect r = item->getRealFrame(be_plain_font);
			if (r.Width() > *width) {
				*width = r.Width();
			}
			*height += r.Height() + 1.0;
		}
	}
}

void DormantNodeView::MessageReceived(
	BMessage *message) {
	D_MESSAGE(("DormantNodeView::MessageReceived()\n"));

	switch (message->what) {
		case B_MEDIA_FLAVORS_CHANGED: {
			D_MESSAGE((" -> B_MEDIA_FLAVORS_CHANGED\n"));

			// init & re-populate the list
			int32 addOnID = 0;
			if (message->FindInt32("be:addon_id", &addOnID) != B_OK) {
				D_MESSAGE((" -> messages doesn't contain 'be:addon_id'!\n"));
				return;
			}
			_updateList(addOnID);
			break;
		}
		case InfoWindowManager::M_INFO_WINDOW_REQUESTED: {
			D_MESSAGE((" -> InfoWindowManager::M_INFO_WINDOW_REQUESTED)\n"));

			DormantNodeListItem *item;
			item = dynamic_cast<DormantNodeListItem *>(ItemAt(CurrentSelection()));
			if (item) {
				InfoWindowManager *manager = InfoWindowManager::Instance();
				if (manager && manager->Lock()) {
					manager->openWindowFor(item->info());
					manager->Unlock();
				}
			}
			break;
		}
		default: {
			_inherited::MessageReceived(message);
		}
	}
}

void DormantNodeView::MouseDown(
	BPoint point) {
	D_HOOK(("DormantNodeView::MouseDown()\n"));

	BMessage* message = Window()->CurrentMessage();
	int32 buttons = message->FindInt32("buttons");
	if (buttons == B_SECONDARY_MOUSE_BUTTON) {
		int32 index;
		if ((index = IndexOf(point)) >= 0) {
			DormantNodeListItem *item = dynamic_cast<DormantNodeListItem *>(ItemAt(index));
			if (item) {
				Select(index);
				BRect r = item->getRealFrame(be_plain_font);
				if (r.Contains(point)) {
					item->showContextMenu(point, this);
				}
			}
		}
	}

	_inherited::MouseDown(point);
}

void DormantNodeView::MouseMoved(
	BPoint point,
	uint32 transit,
	const BMessage *message) {
	D_HOOK(("DormantNodeView::MouseMoved()\n"));

	int32 index;
	if (!message && ((index = IndexOf(point)) >= 0)) {
		DormantNodeListItem *item = dynamic_cast<DormantNodeListItem *>(ItemAt(index));
		DormantNodeListItem *last = dynamic_cast<DormantNodeListItem *>(m_lastItemUnder);
		BRect r = item->getRealFrame(be_plain_font);
		if (item && r.Contains(point)) {
			if (item != last) {
				if (last)
					last->mouseOver(this, point, B_EXITED_VIEW);
				item->mouseOver(this, point, B_ENTERED_VIEW);
				m_lastItemUnder = item;
			}
			else {
				item->mouseOver(this, point, B_INSIDE_VIEW);
			}
		}
		else if (last) {
			last->mouseOver(this, point, B_EXITED_VIEW);
		}
	}

	_inherited::MouseMoved(point, transit, message);
}

bool DormantNodeView::InitiateDrag(
	BPoint point,
	int32 index,
	bool wasSelected) {
	D_HOOK(("DormantNodeView::InitiateDrag()\n"));

	DormantNodeListItem *item = dynamic_cast<DormantNodeListItem *>(ItemAt(CurrentSelection()));
	if (item) {
		BMessage dragMsg(M_INSTANTIATE_NODE);
		dragMsg.AddData("which", B_RAW_TYPE,
						reinterpret_cast<const void *>(&item->info()),
						sizeof(item->info()));
		point -= ItemFrame(index).LeftTop();
		DragMessage(&dragMsg, item->getDragBitmap(), B_OP_ALPHA, point);
		return true;
	}
	return false;
}

// -------------------------------------------------------- //
// internal operations (private)
// -------------------------------------------------------- //

void DormantNodeView::_populateList() {
	D_INTERNAL(("DormantNodeView::_populateList()\n"));

	// init the resizable node-info buffer
	BMediaRoster *roster = BMediaRoster::CurrentRoster();
	const int32 bufferInc = 64;
	int32 bufferSize = bufferInc;
	dormant_node_info *infoBuffer = new dormant_node_info[bufferSize];
	int32 numNodes;

	// fill the buffer
	while (true) {
		numNodes = bufferSize;
		status_t error = roster->GetDormantNodes(infoBuffer, &numNodes);
		if (error) {
			return;
		}
		if (numNodes < bufferSize) {
			break;
		}

		// reallocate buffer & try again
		delete [] infoBuffer;
		bufferSize += bufferInc;
		infoBuffer = new dormant_node_info[bufferSize];
	}

	// populate the list
	for (int32 i = 0; i < numNodes; i++) {
		DormantNodeListItem *item = new DormantNodeListItem(infoBuffer[i]);
		AddItem(item);
	}
	SortItems(compareName);
}

void DormantNodeView::_freeList() {
	D_HOOK(("DormantNodeView::_freeList()\n"));

	// remove and delete all items in the list
	while (CountItems() > 0) {
		BListItem *item = ItemAt(0);
		if (RemoveItem(item)) {
			delete item;
		}
	}
}

void DormantNodeView::_updateList(
	int32 addOnID) {
	D_INTERNAL(("DormantNodeView::_updateList(%ld)\n", addOnID));

	// init the resizable node-info buffer
	BMediaRoster *roster = BMediaRoster::CurrentRoster();
	const int32 bufferInc = 64;
	int32 bufferSize = bufferInc;
	dormant_node_info *infoBuffer = new dormant_node_info[bufferSize];
	int32 numNodes;

	// fill the buffer
	while (true) {
		numNodes = bufferSize;
		status_t error = roster->GetDormantNodes(infoBuffer, &numNodes);
		if (error) {
			return;
		}
		if (numNodes < bufferSize) {
			break;
		}

		// reallocate buffer & try again
		delete [] infoBuffer;
		bufferSize += bufferInc;
		infoBuffer = new dormant_node_info[bufferSize];
	}

	// sort the list by add-on id to avoid multiple searches through
	// the list
	SortItems(compareAddOnID);

	// Remove all nodes managed by this add-on
	int32 start;
	for (start = 0; start < CountItems(); start++) {
		DormantNodeListItem *item = dynamic_cast<DormantNodeListItem *>(ItemAt(start));
		if (item && (item->info().addon == addOnID)) {
			break;
		}
	}
	int32 count = 0;
	for (int32 i = start; start < CountItems(); i++) {
		DormantNodeListItem *item = dynamic_cast<DormantNodeListItem *>(ItemAt(i));
		if (!item || (item->info().addon != addOnID)) {
			break;
		}
		count++;
	}
	RemoveItems(start, count);

	// add the items
	for (int32 i = 0; i < numNodes; i++) {
		if (infoBuffer[i].addon != addOnID) {
			continue;
		}
		AddItem(new DormantNodeListItem(infoBuffer[i]));
	}

	SortItems(compareName);
}

// END -- DormantNodeView.cpp --
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>

#include "util/bitmap.h"
#include "block.h"
#include "object/heart.h"
#include "util/load_exception.h"
#include "util/funcs.h"
#include "object/object.h"
#include "scene.h"
#include "globals.h"
#include "util/token.h"
#include "util/tokenreader.h"
#include "environment/atmosphere.h"

using namespace std;

static const string dataPath( const string & str ){
	return Util::getDataPath() + str;
}

Panel::Panel( Bitmap * _pic, Bitmap * _neon, Bitmap * _my_screen ){
	pic = _pic;
	neon = _neon;
	screen_overlay = _my_screen;
}

Panel::~Panel(){
	if ( pic ) delete pic;
	if ( neon ) delete neon;
	if ( screen_overlay ) delete screen_overlay;
}

Scene::Scene( const char * filename ) throw( LoadException ):
background( NULL ),
block_length( 0 ),
minimum_z( 0 ),
maximum_z( 0 ),
current_block( NULL ),
blockNumber( 1 ),
backgroundParallax( 5 ),
foregroundParallax( 1.2 ),
atmosphere( NULL ){

	TokenReader tr( filename );

	// Token * current = tr.readToken();
	Token * current;

	/* the first panel index */
	// char panel_num = 'a';

	try {
		current = tr.readToken();

		if ( *current != "level" )
			throw LoadException("Not a level");

		while ( current->hasTokens() ){

			Token * tok;
			*current >> tok;
			if ( *tok == "music" ){
				*tok >> music;
			} else if ( *tok == "background" ){
				string n;
				*tok >> n;
				background = new Bitmap( dataPath( n ) );
			} else if ( *tok == "background-parallax" ){
				double d;
				*tok >> d;
				setBackgroundParallax( d );
			} else if ( *tok == "foreground-parallax" ){
				double d;
				*tok >> d;
				setForegroundParallax( d );
			} else if ( *tok == "atmosphere" ){
				string s;
				*tok >> s;
				atmosphere = Atmosphere::createAtmosphere( s );
			} else if ( *tok == "z" ){
				while ( tok->hasTokens() ){
					Token * next;
					*tok >> next;
					if ( *next == "minimum" ){
						int m;
						*next >> m;
						setMinimumZ( m );
					} else if ( *next == "maximum" ){
						int m;
						*next >> m;
						setMaximumZ( m );
					}
				}
			} else if ( *tok == "panel" ){
				int num;
				string normal, neon, s_screen;
				*tok >> num >> normal >> neon >> s_screen;

				Bitmap * x_normal = NULL;
				Bitmap * x_neon = NULL;
				Bitmap * x_screen = NULL;
				if ( normal != "none" ){
					x_normal = new Bitmap( dataPath( normal ) );
				}
				x_neon = new Bitmap();
				x_screen = new Bitmap();
				/*
				if ( neon != "none" ){
					x_neon = new Bitmap( neon );
				}
				if ( s_screen != "none" ){
					x_screen = new Bitmap( s_screen );
				}
				*/
				Panel * p = new Panel( x_normal, x_neon, x_screen );
				panels[ num ] = p;
				// panel_num++;
			} else if ( *tok == "block" ){
				Block * b = new Block( tok );
				level_blocks.push_back( b );
			} else if ( *tok == "frontpanel" ){
				string file;
				*tok >> file;
				Bitmap * front = new Bitmap( dataPath( file ) );
				front_panels.push_back( front );
			} else if ( *tok == "order" ){
				// *tok >> order;
				while ( tok->hasTokens() ){
					int x;
					*tok >> x;
					order.push_back( x );
				}
			} else {
				Global::debug( 0 ) <<"Unhandled scene attribute: "<<endl;
				tok->print(" ");
			}
		}

	} catch ( const TokenException & ex ){
		// delete current;
		string m( "Level parse error: " );
		m += ex.getReason();
		throw LoadException( m );
	} catch ( const LoadException & ex ){
		// delete current;
		throw ex;
	}

	if ( level_blocks.empty() )
		throw LoadException("No level blocks defined");

	current_block = level_blocks.front();
	level_blocks.pop_front();

	arrow = new Bitmap( Util::getDataPath() + "/sprites/arrow.png" );
	arrow_blink = 0;

	// delete current;

	Global::debug( 1 ) <<"Loaded level "<< filename << endl;

	calculateLength();

	int blength = 0;
	for ( deque< Block * >::iterator it = level_blocks.begin(); it != level_blocks.end(); it++ ){
		blength += (*it)->getLength();
	}
	Global::debug( 1 ) <<"Scene length = "<<scene_length<<". Length used = "<<blength<<endl;

}

void Scene::calculateLength(){
	scene_length = 0;
	for ( unsigned int q = 0; q < order.size(); q++ ){
		Panel *& cur = panels[ order[q] ];
		if ( cur == NULL ){
			continue;
		}
		Bitmap * normal = cur->pic;
		// normal->draw( fx-x, 0, *work );
		scene_length += normal->getWidth();
	}
}

/* returns the farthest point the player can go */
int Scene::getLimit(){
	return block_length + current_block->getLength();
}

const int Scene::getFinished() const {
	int finished = current_block->getFinished();
	if ( finished == -1 ){
		return -1;
	}
	return block_length + current_block->getFinished();
}

void Scene::clearHearts(){
	for ( vector< Heart * >::iterator it = hearts.begin(); it != hearts.end(); ){
		Heart * h = *it;
		if ( !h->getAlive() ){
			// delete h;
			it = hearts.erase( it );
		} else
			it++;
	}
}

void Scene::act( int min_x, int max_x, vector< Object * > * objects ){
	clearHearts();

	// cout<<"Min_x = "<<min_x<<" block_length = "<<block_length<<endl;
	if ( hearts.empty() && current_block->empty() && min_x >= getLimit() - 320 ){
		if ( ! level_blocks.empty() ){

			// cout<<"Next block"<<endl;
			block_length += current_block->getLength();
			delete current_block;
			current_block = level_blocks.front();
			level_blocks.pop_front();
			blockNumber += 1;
			Global::debug( 3 ) << "[Scene] Current block is " << blockNumber << ". Length is " << current_block->getLength() << " Minimum x is " << min_x << endl;
		}
	}

	vector< Heart * > new_hearts = current_block->createObjects( block_length, min_x, max_x, getMinimumZ(), getMaximumZ(), objects );
	hearts.insert( hearts.end(), new_hearts.begin(), new_hearts.end() );

	if ( atmosphere ){
		atmosphere->act();
	}
}

/* draw the background */
void Scene::drawBack( int x, Bitmap * work ){
	if ( background ){
		int y = 0;
		background->Blit( (int)(x/getBackgroundParallax()) % background->getWidth() - background->getWidth(), 0, 0, y, *work );
		background->Blit( (int)(x/getBackgroundParallax()) % background->getWidth(), 0, 0, y, *work );
	}

	int fx = 0;
	for ( unsigned int q = 0; q < order.size(); q++ ){
		Panel *& cur = panels[ order[q] ];
		if ( cur == NULL ){
			continue;
		}
		Bitmap * normal = cur->pic;
		normal->draw( fx-x, 0, *work );

		Bitmap * xscreen = cur->screen_overlay;
		if ( xscreen )
			xscreen->draw( fx-x, 0, *work );

		Bitmap * neon = cur->neon;
		if ( neon )
			neon->draw( fx-x, 0, *work );

		fx += normal->getWidth();
	}
}

/* draw the foreground */
void Scene::drawFront( int x, Bitmap * work ){
	double fx = 0;
	if ( front_panels.size() > 0 ){
		while ( fx < scene_length * getForegroundParallax() ){
			for ( vector< Bitmap * >::iterator it = front_panels.begin(); it != front_panels.end(); it++ ){
				Bitmap * b = *it;
				b->draw( (int)(fx - x * getForegroundParallax()), 0, *work );
				fx += b->getWidth();
			}
		}
	}

	if ( hearts.empty() && current_block->empty() && x < getLimit() - 320 ){
		if ( arrow_blink++ > 5 ){
			arrow->draw( work->getWidth() - ( arrow->getWidth() + 10 ), 50, *work );
		}
		if ( arrow_blink > 10 )
			arrow_blink = 0;
	}

	if ( atmosphere ){
		atmosphere->draw( work );
	}

	/*
	for ( vector< Bitmap * >::iterator it = front_panels.begin(); it != front_panels.end(); it++ ){
		Bitmap * b = *it;
		b->draw( fx - x, 0, *work );
		fx += b->getWidth();
	}
	*/
	/*
	for ( unsigned int q = 0; q < order.size(); q++ ){
		Panel *& cur = panels[ order[q] ];
		Bitmap * normal = cur->pic;
		normal->draw( fx-x, 100, *work );
		fx += normal->getWidth();
	}
	*/
}

/*
void Scene::Draw( int x, Bitmap * work ){
	if ( background )
		background->Blit( x, 0, 0, 20, *work );

	int fx = 0;
	for ( unsigned int q = 0; q < order.size(); q++ ){
		Panel *& cur = panels[ order[q] ];
		Bitmap * normal = cur->pic;
		normal->draw( fx-x, 100, *work );
		fx += normal->getWidth();
	}
}
*/

Scene::~Scene(){
	delete current_block;
	for ( deque< Block * >::iterator it = level_blocks.begin(); it != level_blocks.end(); it++ ){
		delete *it;
	}

	if ( background )
		delete background;

	if ( arrow )
		delete arrow;

	for ( vector< Bitmap * >::iterator it = front_panels.begin(); it != front_panels.end(); it++ ){
		delete *it;
	}
	for ( map< int, Panel * >::iterator it = panels.begin(); it != panels.end(); it++ ){
		delete (*it).second;
	}
	if ( atmosphere ){
		delete atmosphere;
	}

	/*
	for ( vector< Heart * >::iterator it = hearts.begin(); it != hearts.end(); it++ ){
		delete *it;
	}
	*/

}
<commit_msg>get rid of garbage surfaces<commit_after>#include <iostream>
#include <string>
#include <vector>

#include "util/bitmap.h"
#include "block.h"
#include "object/heart.h"
#include "util/load_exception.h"
#include "util/funcs.h"
#include "object/object.h"
#include "scene.h"
#include "globals.h"
#include "util/token.h"
#include "util/tokenreader.h"
#include "environment/atmosphere.h"

using namespace std;

static const string dataPath( const string & str ){
	return Util::getDataPath() + str;
}

Panel::Panel( Bitmap * _pic, Bitmap * _neon, Bitmap * _my_screen ){
	pic = _pic;
	neon = _neon;
	screen_overlay = _my_screen;
}

Panel::~Panel(){
	if ( pic ) delete pic;
	if ( neon ) delete neon;
	if ( screen_overlay ) delete screen_overlay;
}

Scene::Scene( const char * filename ) throw( LoadException ):
background( NULL ),
block_length( 0 ),
minimum_z( 0 ),
maximum_z( 0 ),
current_block( NULL ),
blockNumber( 1 ),
backgroundParallax( 5 ),
foregroundParallax( 1.2 ),
atmosphere( NULL ){

	TokenReader tr( filename );

	// Token * current = tr.readToken();
	Token * current;

	/* the first panel index */
	// char panel_num = 'a';

	try {
		current = tr.readToken();

		if ( *current != "level" )
			throw LoadException("Not a level");

		while ( current->hasTokens() ){

			Token * tok;
			*current >> tok;
			if ( *tok == "music" ){
				*tok >> music;
			} else if ( *tok == "background" ){
				string n;
				*tok >> n;
				background = new Bitmap( dataPath( n ) );
			} else if ( *tok == "background-parallax" ){
				double d;
				*tok >> d;
				setBackgroundParallax( d );
			} else if ( *tok == "foreground-parallax" ){
				double d;
				*tok >> d;
				setForegroundParallax( d );
			} else if ( *tok == "atmosphere" ){
				string s;
				*tok >> s;
				atmosphere = Atmosphere::createAtmosphere( s );
			} else if ( *tok == "z" ){
				while ( tok->hasTokens() ){
					Token * next;
					*tok >> next;
					if ( *next == "minimum" ){
						int m;
						*next >> m;
						setMinimumZ( m );
					} else if ( *next == "maximum" ){
						int m;
						*next >> m;
						setMaximumZ( m );
					}
				}
			} else if ( *tok == "panel" ){
				int num;
				string normal, neon, s_screen;
				*tok >> num >> normal >> neon >> s_screen;

				Bitmap * x_normal = NULL;
				Bitmap * x_neon = NULL;
				Bitmap * x_screen = NULL;
				if ( normal != "none" ){
					x_normal = new Bitmap( dataPath( normal ) );
				}
				x_neon = new Bitmap();
				x_screen = new Bitmap();
				/*
				if ( neon != "none" ){
					x_neon = new Bitmap( neon );
				}
				if ( s_screen != "none" ){
					x_screen = new Bitmap( s_screen );
				}
				*/
				Panel * p = new Panel( x_normal, x_neon, x_screen );
				panels[ num ] = p;
				// panel_num++;
			} else if ( *tok == "block" ){
				Block * b = new Block( tok );
				level_blocks.push_back( b );
			} else if ( *tok == "frontpanel" ){
				string file;
				*tok >> file;
				Bitmap * front = new Bitmap( dataPath( file ) );
				front_panels.push_back( front );
			} else if ( *tok == "order" ){
				// *tok >> order;
				while ( tok->hasTokens() ){
					int x;
					*tok >> x;
					order.push_back( x );
				}
			} else {
				Global::debug( 0 ) <<"Unhandled scene attribute: "<<endl;
				tok->print(" ");
			}
		}

	} catch ( const TokenException & ex ){
		// delete current;
		string m( "Level parse error: " );
		m += ex.getReason();
		throw LoadException( m );
	} catch ( const LoadException & ex ){
		// delete current;
		throw ex;
	}

	if ( level_blocks.empty() )
		throw LoadException("No level blocks defined");

	current_block = level_blocks.front();
	level_blocks.pop_front();

	arrow = new Bitmap( Util::getDataPath() + "/sprites/arrow.png" );
	arrow_blink = 0;

	// delete current;

	Global::debug( 1 ) <<"Loaded level "<< filename << endl;

	calculateLength();

	int blength = 0;
	for ( deque< Block * >::iterator it = level_blocks.begin(); it != level_blocks.end(); it++ ){
		blength += (*it)->getLength();
	}
	Global::debug( 1 ) <<"Scene length = "<<scene_length<<". Length used = "<<blength<<endl;

}

void Scene::calculateLength(){
	scene_length = 0;
	for ( unsigned int q = 0; q < order.size(); q++ ){
		Panel *& cur = panels[ order[q] ];
		if ( cur == NULL ){
			continue;
		}
		Bitmap * normal = cur->pic;
		// normal->draw( fx-x, 0, *work );
		scene_length += normal->getWidth();
	}
}

/* returns the farthest point the player can go */
int Scene::getLimit(){
	return block_length + current_block->getLength();
}

const int Scene::getFinished() const {
	int finished = current_block->getFinished();
	if ( finished == -1 ){
		return -1;
	}
	return block_length + current_block->getFinished();
}

void Scene::clearHearts(){
	for ( vector< Heart * >::iterator it = hearts.begin(); it != hearts.end(); ){
		Heart * h = *it;
		if ( !h->getAlive() ){
			// delete h;
			it = hearts.erase( it );
		} else
			it++;
	}
}

void Scene::act( int min_x, int max_x, vector< Object * > * objects ){
	clearHearts();

	// cout<<"Min_x = "<<min_x<<" block_length = "<<block_length<<endl;
	if ( hearts.empty() && current_block->empty() && min_x >= getLimit() - 320 ){
		if ( ! level_blocks.empty() ){

			// cout<<"Next block"<<endl;
			block_length += current_block->getLength();
			delete current_block;
			current_block = level_blocks.front();
			level_blocks.pop_front();
			blockNumber += 1;
			Global::debug( 3 ) << "[Scene] Current block is " << blockNumber << ". Length is " << current_block->getLength() << " Minimum x is " << min_x << endl;
		}
	}

	vector< Heart * > new_hearts = current_block->createObjects( block_length, min_x, max_x, getMinimumZ(), getMaximumZ(), objects );
	hearts.insert( hearts.end(), new_hearts.begin(), new_hearts.end() );

	if ( atmosphere ){
		atmosphere->act();
	}
}

/* draw the background */
void Scene::drawBack( int x, Bitmap * work ){
	if ( background ){
		int y = 0;
		background->Blit( (int)(x/getBackgroundParallax()) % background->getWidth() - background->getWidth(), 0, 0, y, *work );
		background->Blit( (int)(x/getBackgroundParallax()) % background->getWidth(), 0, 0, y, *work );
	}

	int fx = 0;
	for ( unsigned int q = 0; q < order.size(); q++ ){
		Panel *& cur = panels[ order[q] ];
		if ( cur == NULL ){
			continue;
		}
		Bitmap * normal = cur->pic;
		normal->draw( fx-x, 0, *work );

		/* This stuff is from beats of rage, but I probably
		 * wont use it anymore
		 */
		/*
		Bitmap * xscreen = cur->screen_overlay;
		if ( xscreen )
			xscreen->draw( fx-x, 0, *work );

		Bitmap * neon = cur->neon;
		if ( neon )
			neon->draw( fx-x, 0, *work );
		*/

		fx += normal->getWidth();
	}
}

/* draw the foreground */
void Scene::drawFront( int x, Bitmap * work ){
	double fx = 0;
	if ( front_panels.size() > 0 ){
		while ( fx < scene_length * getForegroundParallax() ){
			for ( vector< Bitmap * >::iterator it = front_panels.begin(); it != front_panels.end(); it++ ){
				Bitmap * b = *it;
				b->draw( (int)(fx - x * getForegroundParallax()), 0, *work );
				fx += b->getWidth();
			}
		}
	}

	if ( hearts.empty() && current_block->empty() && x < getLimit() - 320 ){
		if ( arrow_blink++ > 5 ){
			arrow->draw( work->getWidth() - ( arrow->getWidth() + 10 ), 50, *work );
		}
		if ( arrow_blink > 10 )
			arrow_blink = 0;
	}

	if ( atmosphere ){
		atmosphere->draw( work );
	}

	/*
	for ( vector< Bitmap * >::iterator it = front_panels.begin(); it != front_panels.end(); it++ ){
		Bitmap * b = *it;
		b->draw( fx - x, 0, *work );
		fx += b->getWidth();
	}
	*/
	/*
	for ( unsigned int q = 0; q < order.size(); q++ ){
		Panel *& cur = panels[ order[q] ];
		Bitmap * normal = cur->pic;
		normal->draw( fx-x, 100, *work );
		fx += normal->getWidth();
	}
	*/
}

/*
void Scene::Draw( int x, Bitmap * work ){
	if ( background )
		background->Blit( x, 0, 0, 20, *work );

	int fx = 0;
	for ( unsigned int q = 0; q < order.size(); q++ ){
		Panel *& cur = panels[ order[q] ];
		Bitmap * normal = cur->pic;
		normal->draw( fx-x, 100, *work );
		fx += normal->getWidth();
	}
}
*/

Scene::~Scene(){
	delete current_block;
	for ( deque< Block * >::iterator it = level_blocks.begin(); it != level_blocks.end(); it++ ){
		delete *it;
	}

	if ( background )
		delete background;

	if ( arrow )
		delete arrow;

	for ( vector< Bitmap * >::iterator it = front_panels.begin(); it != front_panels.end(); it++ ){
		delete *it;
	}
	for ( map< int, Panel * >::iterator it = panels.begin(); it != panels.end(); it++ ){
		delete (*it).second;
	}
	if ( atmosphere ){
		delete atmosphere;
	}

	/*
	for ( vector< Heart * >::iterator it = hearts.begin(); it != hearts.end(); it++ ){
		delete *it;
	}
	*/

}
<|endoftext|>


<commit_before>///
/// @file  PiTable.cpp
/// @see   PiTable.hpp for documentation.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <PiTable.hpp>
#include <bit_sieve.hpp>

#include <stdint.h>
#include <vector>

namespace primecount {

PiTable::PiTable(uint64_t max) :
  max_(max)
{
  init();
}

void PiTable::init()
{
  bit_sieve sieve(max_ + 1);
  sieve.memset(0);

  // sieve of Eratosthenes
  for (uint64_t i = 3; i * i <= max_; i += 2)
    if (sieve[i])
      for (uint64_t j = i * i; j <= max_; j += i * 2)
        sieve.unset(j);

  uint32_t pix = 0;
  pi_.resize(max_ / 64 + 1);

  // fill pi_[x] table
  for (uint64_t x = 2; x <= max_; x++)
  {
    if (x % 64 == 0)
      pi_[x / 64].prime_count = pix;

    // check whether x is a prime
    if (sieve[x])
    {
      // set bit corresponding to x to 1
      uint64_t one = 1;
      pi_[x / 64].bits |= one << (x % 64);
      pix++;
    }
  }
}

} // namespace
<commit_msg>Comment<commit_after>///
/// @file  PiTable.cpp
/// @see   PiTable.hpp for documentation.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <PiTable.hpp>
#include <bit_sieve.hpp>

#include <stdint.h>
#include <vector>

namespace primecount {

PiTable::PiTable(uint64_t max) :
  max_(max)
{
  init();
}

void PiTable::init()
{
  bit_sieve sieve(max_ + 1);
  sieve.memset(0);

  // sieve of Eratosthenes
  for (uint64_t i = 3; i * i <= max_; i += 2)
    if (sieve[i])
      for (uint64_t j = i * i; j <= max_; j += i * 2)
        sieve.unset(j);

  uint32_t pix = 0;
  pi_.resize(max_ / 64 + 1);

  // fill pi_[x] table
  for (uint64_t x = 2; x <= max_; x++)
  {
    if (x % 64 == 0)
      pi_[x / 64].prime_count = pix;

    // check whether x is a prime
    if (sieve[x])
    {
      uint64_t one = 1;
      pi_[x / 64].bits |= one << (x % 64);
      pix++;
    }
  }
}

} // namespace
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* libwps
 * Version: MPL 2.0 / LGPLv2.1+
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Major Contributor(s):
 * Copyright (C) 2009, 2011 Alonso Laurent (alonso@loria.fr)
 * Copyright (C) 2006, 2007 Andrew Ziem
 * Copyright (C) 2004-2006 Fridrich Strba (fridrich.strba@bluewin.ch)
 * Copyright (C) 2004 Marc Maurer (uwog@uwog.net)
 * Copyright (C) 2003-2005 William Lachance (william.lachance@sympatico.ca)
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms
 * of the GNU Lesser General Public License Version 2.1 or later
 * (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are
 * applicable instead of those above.
 *
 * For further information visit http://libwps.sourceforge.net
 */

#include <time.h>

#include <iomanip>
#include <sstream>

#include <libwpd/libwpd.h>

#include "WPSCell.h"

void WPSCellFormat::setBorders(int wh, WPSBorder const &border)
{
	int const allBits = WPSBorder::LeftBit|WPSBorder::RightBit|WPSBorder::TopBit|WPSBorder::BottomBit;
	if (wh & (~allBits))
	{
		WPS_DEBUG_MSG(("WPSCellFormat::setBorders: unknown borders\n"));
		return;
	}
	if (m_bordersList.size() < 4)
	{
		WPSBorder emptyBorder;
		emptyBorder.m_style = WPSBorder::None;
		m_bordersList.resize(4, emptyBorder);
	}
	if (wh & WPSBorder::LeftBit) m_bordersList[WPSBorder::Left] = border;
	if (wh & WPSBorder::RightBit) m_bordersList[WPSBorder::Right] = border;
	if (wh & WPSBorder::TopBit) m_bordersList[WPSBorder::Top] = border;
	if (wh & WPSBorder::BottomBit) m_bordersList[WPSBorder::Bottom] = border;
}

int WPSCellFormat::compare(WPSCellFormat const &cell) const
{
	int diff = int(m_hAlign) - int(cell.m_hAlign);
	if (diff) return diff;
	diff = int(m_backgroundColor) - int(cell.m_backgroundColor);
	if (diff) return diff;
	diff = int(m_bordersList.size()) - int(cell.m_bordersList.size());
	if (diff) return diff;
	for (size_t c = 0; c < m_bordersList.size(); c++)
	{
		diff = m_bordersList[c].compare(cell.m_bordersList[c]);
		if (diff) return diff;
	}
	return 0;
}

std::ostream &operator<<(std::ostream &o, WPSCellFormat const &cell)
{
	switch(cell.m_hAlign)
	{
	case WPSCellFormat::HALIGN_LEFT:
		o << ",left";
		break;
	case WPSCellFormat::HALIGN_CENTER:
		o << ",centered";
		break;
	case WPSCellFormat::HALIGN_RIGHT:
		o << ",right";
		break;
	case WPSCellFormat::HALIGN_FULL:
		o << ",full";
		break;
	case WPSCellFormat::HALIGN_DEFAULT:
	default:
		break; // default
	}
	if (cell.m_backgroundColor != 0xFFFFFF)
		o << ",backColor=" << std::hex << cell.m_backgroundColor << ",";
	for (size_t i = 0; i < cell.m_bordersList.size(); i++)
	{
		if (cell.m_bordersList[i].m_style == WPSBorder::None)
			continue;
		o << "bord";
		char const *wh[] = { "L", "R", "T", "B", "MiddleH", "MiddleV" };
		if (i < 4) o << wh[i];
		else o << "[#wh=" << i << "]";
		o << "=" << cell.m_bordersList[i] << ",";
	}
	return o;
}

////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
std::ostream &operator<<(std::ostream &o, WPSCell const &cell)
{
	o << "C" << cell.m_position << ":";
	if (cell.numSpannedCells()[0] != 1 || cell.numSpannedCells()[1] != 1)
		o << "span=[" << cell.numSpannedCells()[0] << "," << cell.numSpannedCells()[1] << "],";
	o << "box=" << cell.m_box;
	if (cell.m_verticalSet) o << "[ySet]";
	o << ",";
	o << static_cast<WPSCellFormat const &>(cell);

	return o;
}

/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */
<commit_msg>coverity: setting of formatting base is permanent<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* libwps
 * Version: MPL 2.0 / LGPLv2.1+
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Major Contributor(s):
 * Copyright (C) 2009, 2011 Alonso Laurent (alonso@loria.fr)
 * Copyright (C) 2006, 2007 Andrew Ziem
 * Copyright (C) 2004-2006 Fridrich Strba (fridrich.strba@bluewin.ch)
 * Copyright (C) 2004 Marc Maurer (uwog@uwog.net)
 * Copyright (C) 2003-2005 William Lachance (william.lachance@sympatico.ca)
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms
 * of the GNU Lesser General Public License Version 2.1 or later
 * (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are
 * applicable instead of those above.
 *
 * For further information visit http://libwps.sourceforge.net
 */

#include <time.h>

#include <sstream>

#include <libwpd/libwpd.h>

#include "WPSCell.h"

void WPSCellFormat::setBorders(int wh, WPSBorder const &border)
{
	int const allBits = WPSBorder::LeftBit|WPSBorder::RightBit|WPSBorder::TopBit|WPSBorder::BottomBit;
	if (wh & (~allBits))
	{
		WPS_DEBUG_MSG(("WPSCellFormat::setBorders: unknown borders\n"));
		return;
	}
	if (m_bordersList.size() < 4)
	{
		WPSBorder emptyBorder;
		emptyBorder.m_style = WPSBorder::None;
		m_bordersList.resize(4, emptyBorder);
	}
	if (wh & WPSBorder::LeftBit) m_bordersList[WPSBorder::Left] = border;
	if (wh & WPSBorder::RightBit) m_bordersList[WPSBorder::Right] = border;
	if (wh & WPSBorder::TopBit) m_bordersList[WPSBorder::Top] = border;
	if (wh & WPSBorder::BottomBit) m_bordersList[WPSBorder::Bottom] = border;
}

int WPSCellFormat::compare(WPSCellFormat const &cell) const
{
	int diff = int(m_hAlign) - int(cell.m_hAlign);
	if (diff) return diff;
	diff = int(m_backgroundColor) - int(cell.m_backgroundColor);
	if (diff) return diff;
	diff = int(m_bordersList.size()) - int(cell.m_bordersList.size());
	if (diff) return diff;
	for (size_t c = 0; c < m_bordersList.size(); c++)
	{
		diff = m_bordersList[c].compare(cell.m_bordersList[c]);
		if (diff) return diff;
	}
	return 0;
}

std::ostream &operator<<(std::ostream &o, WPSCellFormat const &cell)
{
	switch(cell.m_hAlign)
	{
	case WPSCellFormat::HALIGN_LEFT:
		o << ",left";
		break;
	case WPSCellFormat::HALIGN_CENTER:
		o << ",centered";
		break;
	case WPSCellFormat::HALIGN_RIGHT:
		o << ",right";
		break;
	case WPSCellFormat::HALIGN_FULL:
		o << ",full";
		break;
	case WPSCellFormat::HALIGN_DEFAULT:
	default:
		break; // default
	}
	if (cell.m_backgroundColor != 0xFFFFFF)
	{
		std::ios::fmtflags oldflags = o.setf(std::ios::hex, std::ios::basefield);
		o << ",backColor=" << cell.m_backgroundColor << ",";
		o.setf(oldflags, std::ios::basefield);
	}
	for (size_t i = 0; i < cell.m_bordersList.size(); i++)
	{
		if (cell.m_bordersList[i].m_style == WPSBorder::None)
			continue;
		o << "bord";
		char const *wh[] = { "L", "R", "T", "B", "MiddleH", "MiddleV" };
		if (i < 4) o << wh[i];
		else o << "[#wh=" << i << "]";
		o << "=" << cell.m_bordersList[i] << ",";
	}
	return o;
}

////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
std::ostream &operator<<(std::ostream &o, WPSCell const &cell)
{
	o << "C" << cell.m_position << ":";
	if (cell.numSpannedCells()[0] != 1 || cell.numSpannedCells()[1] != 1)
		o << "span=[" << cell.numSpannedCells()[0] << "," << cell.numSpannedCells()[1] << "],";
	o << "box=" << cell.m_box;
	if (cell.m_verticalSet) o << "[ySet]";
	o << ",";
	o << static_cast<WPSCellFormat const &>(cell);

	return o;
}

/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */
<|endoftext|>


<commit_before>/**
 * @file
 * @brief Dynamic memory management
 * @date 04.06.12
 * @author Ilia Vaprol
 */

#include <new>

const std::nothrow_t std::nothrow = { };

static std::new_handler __new_handler = 0;

std::new_handler std::set_new_handler(std::new_handler handler) throw() {
	std::new_handler prev_handler = __new_handler;
	__new_handler = handler;
	return prev_handler;
}

// Implementation of new and delete operators for single object
void* operator new(std::size_t size) throw(std::bad_alloc) {
	void *ptr;

	if (size == 0) { /* std::malloc(0) is not predictable */
		size = 1;
	}

	while ((ptr = std::malloc(size)) == 0) {
		std::new_handler handler = __new_handler;
		if (handler == 0) {
			throw std::bad_alloc();
		}
		handler();
	}

	return ptr;
}

void* operator new(std::size_t size, const std::nothrow_t& nothrow_const) throw() {
	void *ptr;

	if (size == 0) { /* std::malloc(0) is not predictable */
		size = 1;
	}

	while ((ptr = std::malloc(size)) == 0) {
		std::new_handler handler = __new_handler;
		if (handler == 0) {
			return 0;
		}
		try {
			handler();
		}
		catch (const std::bad_alloc&) {
			return 0;
		}
	}

	return ptr;
}

void operator delete(void* ptr) throw() {
	std::free(ptr);
}

void operator delete(void* ptr, const std::nothrow_t* nothrow_const) throw() {
	::operator delete(ptr);
}

// Forwarding functions for array of objects
void* operator new[](std::size_t size) throw(std::bad_alloc) {
	return ::operator new(size);
}

void* operator new[](std::size_t size, const std::nothrow_t& nothrow_const) throw() {
	return ::operator new(size, nothrow_const);
}

void operator delete[](void* ptr) throw() {
	::operator delete(ptr);
}

void operator delete[](void* ptr, const std::nothrow_t* nothrow_const) throw() {
	::operator delete(ptr, nothrow_const);
}

<commit_msg>c++: Fix delete prorotype<commit_after>/**
 * @file
 * @brief Dynamic memory management
 * @date 04.06.12
 * @author Ilia Vaprol
 */

#include <new>

const std::nothrow_t std::nothrow = { };

static std::new_handler __new_handler = 0;

std::new_handler std::set_new_handler(std::new_handler handler) throw() {
	std::new_handler prev_handler = __new_handler;
	__new_handler = handler;
	return prev_handler;
}

// Implementation of new and delete operators for single object
void* operator new(std::size_t size) throw(std::bad_alloc) {
	void *ptr;

	if (size == 0) { /* std::malloc(0) is not predictable */
		size = 1;
	}

	while ((ptr = std::malloc(size)) == 0) {
		std::new_handler handler = __new_handler;
		if (handler == 0) {
			throw std::bad_alloc();
		}
		handler();
	}

	return ptr;
}

void* operator new(std::size_t size, const std::nothrow_t& nothrow_const) throw() {
	void *ptr;

	if (size == 0) { /* std::malloc(0) is not predictable */
		size = 1;
	}

	while ((ptr = std::malloc(size)) == 0) {
		std::new_handler handler = __new_handler;
		if (handler == 0) {
			return 0;
		}
		try {
			handler();
		}
		catch (const std::bad_alloc&) {
			return 0;
		}
	}

	return ptr;
}

void operator delete(void* ptr) throw() {
	std::free(ptr);
}

void operator delete(void* ptr, const std::nothrow_t& nothrow_const) throw() {
	::operator delete(ptr);
}

// Forwarding functions for array of objects
void* operator new[](std::size_t size) throw(std::bad_alloc) {
	return ::operator new(size);
}

void* operator new[](std::size_t size, const std::nothrow_t& nothrow_const) throw() {
	return ::operator new(size, nothrow_const);
}

void operator delete[](void* ptr) throw() {
	::operator delete(ptr);
}

void operator delete[](void* ptr, const std::nothrow_t& nothrow_const) throw() {
	::operator delete(ptr, nothrow_const);
}

<|endoftext|>


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

#include <iostream>
#include <fstream>
using std::ifstream;
#include <memory>

#include <sparrowhawk/logger.h>

namespace speech {
namespace sparrowhawk {

string IOStream::LoadFileToString(const string &filename) {
  ifstream strm(filename.c_str(), std::ios_base::in);
  if (!strm) {
    LoggerFatal("Error loading from file %s", filename.c_str());
  }
  strm.seekg(0, strm.end);
  int length = strm.tellg();
  strm.seekg(0, strm.beg);
  std::unique_ptr<char> data;
  data.reset(new char[length + 1]);
  strm.read(data.get(), length);
  data.get()[length] = 0;
  return string(data.get());
}

}  // namespace sparrowhawk
}  // namespace speech
<commit_msg>Small fixes to make io_utils.cc more robust.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright 2015 and onwards Google, Inc.
#include <sparrowhawk/io_utils.h>

#include <iostream>
#include <fstream>
using std::ifstream;
#include <memory>

#include <sparrowhawk/logger.h>

namespace speech {
namespace sparrowhawk {

string IOStream::LoadFileToString(const string &filename) {
  ifstream strm(filename.c_str(), std::ios_base::in);
  if (!strm) {
    LoggerFatal("Error opening file %s", filename.c_str());
  }
  strm.seekg(0, strm.end);
  int length = strm.tellg();
  strm.seekg(0, strm.beg);
  std::unique_ptr<char[]> data(new char[length + 1],
                               std::default_delete<char[]>());
  strm.read(data.get(), length);
  if (strm.fail()) {
    LoggerFatal("Error loading from file %s", filename.c_str());
  }
  data.get()[length] = 0;
  return string(data.get(), length);
}

}  // namespace sparrowhawk
}  // namespace speech
<|endoftext|>


<commit_before>// mjpDate.cc
// Author MIZUKOSHI Keita

#include <iostream>
#include <string>
#include <sstream>
#include "../include/mjpDate.hpp"

mjpDate::mjpDate()
{
	auto  now = time(nullptr);
	auto  lt = localtime(&now);

	year = 1900 + lt->tm_year;
	month =  lt->tm_mon +1;;
	day = lt->tm_mday;
	hour = lt->tm_hour;
	min = lt->tm_min;
	sec = lt->tm_sec;
}

std::string mjpDate::getTimeStamp()
{

	std::stringstream ss;
	ss << year << " "
		<< month << " "
		<< day   << " "
		<< hour  << " "
		<< min   << " "
		<< sec;

	return ss.str();
}
<commit_msg>Bug fix<commit_after>// mjpDate.cc
// Author MIZUKOSHI Keita

#include <iostream>
#include <string>
#include <sstream>
#include "mjpDate.hpp"

mjpDate::mjpDate()
{
	auto  now = time(nullptr);
	auto  lt = localtime(&now);

	year = 1900 + lt->tm_year;
	month =  lt->tm_mon +1;;
	day = lt->tm_mday;
	hour = lt->tm_hour;
	min = lt->tm_min;
	sec = lt->tm_sec;
}

std::string mjpDate::getTimeStamp()
{

	std::stringstream ss;
	ss << year << " "
		<< month << " "
		<< day   << " "
		<< hour  << " "
		<< min   << " "
		<< sec;

	return ss.str();
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 Plenluno All rights reserved.

#include <list>
//#include <forward_list>   // since c++11
#include "libj/linked_list.h"
#include "libj/error.h"
#include "libj/exception.h"
#include "libj/string_buffer.h"

namespace libj {

class LinkedListImpl : public LinkedList {
    typedef std::list<Value> container;
//  typedef std::forward_list<Value> container;
    typedef container::iterator it;
    typedef container::const_iterator cit;

 public:
    Size size() const {
        return list_.size();
    }

    Boolean add(const Value& v) {
        list_.push_back(v);
        return true;
    }

    Boolean add(Size i, const Value& v) {
        if (i > list_.size()) {
            return false;
        } else {
            it pos = list_.begin();
            for (; i; i--) ++pos;
            list_.insert(pos, v);
            return true;
        }
    }

    Boolean set(Size i, const Value& v) {
        if (i > list_.size()) {
            return false;
        } else {
            it pos = list_.begin();
            for (; i; i--) ++pos;
            *pos = v;
            return true;
        }
    }

    Value get(Size i) const {
        if (i >= list_.size()) {
#ifdef LIBJ_USE_EXCEPTION
            LIBJ_THROW(Error::INDEX_OUT_OF_BOUNDS);
#else
            return Error::create(Error::INDEX_OUT_OF_BOUNDS);
#endif  // LIBJ_USE_EXCEPTION
        } else {
            cit pos = list_.begin();
            for (; i; i--) ++pos;
            return *pos;
        }
    }

    Value remove(Size i) {
        if (i >= list_.size()) {
#ifdef LIBJ_USE_EXCEPTION
            LIBJ_THROW(Error::INDEX_OUT_OF_BOUNDS);
#else
            return Error::create(Error::INDEX_OUT_OF_BOUNDS);
#endif  // LIBJ_USE_EXCEPTION
        } else {
            it pos = list_.begin();
            for (; i; i--) ++pos;
            Value v = *pos;
            list_.erase(pos);
            return v;
        }
    }

    Boolean remove(const Value& v) {
        for (it i = list_.begin(), e = list_.end(); i != e; ++i) {
            if (!i->compareTo(v)) {
                list_.erase(i);
                return true;
            }
        }
        return false;
    }

    void clear() {
        list_.clear();
    }

    LinkedList::Ptr clone() const {
        LinkedListImpl* ls = new LinkedListImpl();
        LinkedList::Ptr p (ls);
        for (cit i = list_.begin(), e = list_.end(); i != e; ++i) {
            ls->add(*i);
        }
        return p;
    }

 private:
    class IteratorImpl : public Iterator {
        friend class LinkedListImpl;
        const container* list_;
        container::const_iterator itr_;

        IteratorImpl(const container *l)
            : list_(l)
            , itr_(l->begin()) {}

     public:
        Boolean hasNext() const {
            return itr_ != list_->end();
        }

        Value next() {
            if (itr_ == list_->end()) {
#ifdef LIBJ_USE_EXCEPTION
                LIBJ_THROW(Error::NO_SUCH_ELEMENT);
#else
                return Error::create(Error::NO_SUCH_ELEMENT);
#endif  // LIBJ_USE_EXCEPTION
            } else {
                Value v = *itr_;
                ++itr_;
                return v;
            }
        }

        String::CPtr toString() const {
            return String::create();
        }
    };

 public:
    Iterator::Ptr iterator() const {
        Iterator::Ptr p(new IteratorImpl(&list_));
        return p;
    }

 private:
    container list_;
    LinkedListImpl() : list_(container()) {}

 public:
    static LinkedList::Ptr create() {
        LinkedList::Ptr p(new LinkedListImpl());
        return p;
    }
}; // LinkedListImpl

LinkedList::Ptr LinkedList::create() {
    return LinkedListImpl::create();
}

}  // namespace libj
<commit_msg>modify for cpplint<commit_after>// Copyright (c) 2012 Plenluno All rights reserved.

#include <list>

#include "libj/linked_list.h"
#include "libj/error.h"
#include "libj/exception.h"
#include "libj/string_buffer.h"

namespace libj {

class LinkedListImpl : public LinkedList {
    typedef std::list<Value> container;
    typedef container::iterator it;
    typedef container::const_iterator cit;

 public:
    Size size() const {
        return list_.size();
    }

    Boolean add(const Value& v) {
        list_.push_back(v);
        return true;
    }

    Boolean add(Size i, const Value& v) {
        if (i > list_.size()) {
            return false;
        } else {
            it pos = list_.begin();
            for (; i; i--) ++pos;
            list_.insert(pos, v);
            return true;
        }
    }

    Boolean set(Size i, const Value& v) {
        if (i > list_.size()) {
            return false;
        } else {
            it pos = list_.begin();
            for (; i; i--) ++pos;
            *pos = v;
            return true;
        }
    }

    Value get(Size i) const {
        if (i >= list_.size()) {
#ifdef LIBJ_USE_EXCEPTION
            LIBJ_THROW(Error::INDEX_OUT_OF_BOUNDS);
#else
            return Error::create(Error::INDEX_OUT_OF_BOUNDS);
#endif  // LIBJ_USE_EXCEPTION
        } else {
            cit pos = list_.begin();
            for (; i; i--) ++pos;
            return *pos;
        }
    }

    Value remove(Size i) {
        if (i >= list_.size()) {
#ifdef LIBJ_USE_EXCEPTION
            LIBJ_THROW(Error::INDEX_OUT_OF_BOUNDS);
#else
            return Error::create(Error::INDEX_OUT_OF_BOUNDS);
#endif  // LIBJ_USE_EXCEPTION
        } else {
            it pos = list_.begin();
            for (; i; i--) ++pos;
            Value v = *pos;
            list_.erase(pos);
            return v;
        }
    }

    Boolean remove(const Value& v) {
        for (it i = list_.begin(), e = list_.end(); i != e; ++i) {
            if (!i->compareTo(v)) {
                list_.erase(i);
                return true;
            }
        }
        return false;
    }

    void clear() {
        list_.clear();
    }

    LinkedList::Ptr clone() const {
        LinkedListImpl* ls = new LinkedListImpl();
        LinkedList::Ptr p(ls);
        for (cit i = list_.begin(), e = list_.end(); i != e; ++i) {
            ls->add(*i);
        }
        return p;
    }

 private:
    class IteratorImpl : public Iterator {
        friend class LinkedListImpl;
        const container* list_;
        container::const_iterator itr_;

        IteratorImpl(const container *l)
            : list_(l)
            , itr_(l->begin()) {}

     public:
        Boolean hasNext() const {
            return itr_ != list_->end();
        }

        Value next() {
            if (itr_ == list_->end()) {
#ifdef LIBJ_USE_EXCEPTION
                LIBJ_THROW(Error::NO_SUCH_ELEMENT);
#else
                return Error::create(Error::NO_SUCH_ELEMENT);
#endif  // LIBJ_USE_EXCEPTION
            } else {
                Value v = *itr_;
                ++itr_;
                return v;
            }
        }

        String::CPtr toString() const {
            return String::create();
        }
    };

 public:
    Iterator::Ptr iterator() const {
        Iterator::Ptr p(new IteratorImpl(&list_));
        return p;
    }

 private:
    container list_;
    LinkedListImpl() : list_(container()) {}

 public:
    static LinkedList::Ptr create() {
        LinkedList::Ptr p(new LinkedListImpl());
        return p;
    }
};

LinkedList::Ptr LinkedList::create() {
    return LinkedListImpl::create();
}

}  // namespace libj
<|endoftext|>


<commit_before>/*
  Copyright (c) 2011-2012 - Tőkés Attila
  Copyright (C) 2015 Daniel Nicoletti <dantti12@gmail.com>

x
  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  See the LICENSE file for more details.
*/

#include "mimemessage_p.h"

#include <QtCore/QDebug>
#include "quotedprintable.h"
#include <typeinfo>

#include <QDateTime>
#include <QLoggingCategory>

Q_LOGGING_CATEGORY(SIMPLEMAIL_MIMEMSG, "simplemail.mimemessage")

using namespace SimpleMail;

MimeMessage::MimeMessage(bool createAutoMimeContent) :
    d_ptr(new MimeMessagePrivate)
{
    Q_D(MimeMessage);
    if (createAutoMimeContent) {
        d->content = new MimeMultiPart();
    }

    d->autoMimeContentCreated = createAutoMimeContent;
}

MimeMessage::~MimeMessage()
{
    delete d_ptr;
}

MimePart& MimeMessage::getContent()
{
    Q_D(MimeMessage);
    return *d->content;
}

void MimeMessage::setContent(MimePart *content)
{
    Q_D(MimeMessage);
    if (d->autoMimeContentCreated) {
      d->autoMimeContentCreated = false;
      delete d->content;
    }
    d->content = content;
}

bool MimeMessage::write(QIODevice *device)
{
    Q_D(const MimeMessage);

    // Headers
    QByteArray data;

    data = MimeMessagePrivate::encode(QByteArrayLiteral("From: "), QList<EmailAddress>() << d->sender, d->encoding);
    if (device->write(data) != data.size()) {
        return false;
    }

    data = MimeMessagePrivate::encode(QByteArrayLiteral("To: "), d->recipientsTo, d->encoding);
    if (device->write(data) != data.size()) {
        return false;
    }

    data = MimeMessagePrivate::encode(QByteArrayLiteral("Cc: "), d->recipientsCc, d->encoding);
    if (device->write(data) != data.size()) {
        return false;
    }

    data = QByteArrayLiteral("Date: ") + QDateTime::currentDateTime().toString(Qt::RFC2822Date).toLatin1();
    if (device->write(data) != data.size()) {
        return false;
    }

    data = QByteArrayLiteral("Subject: ") + MimeMessagePrivate::encodeData(d->encoding, d->subject, true);
    if (device->write(data) != data.size()) {
        return false;
    }

    data = QByteArrayLiteral("\r\nMIME-Version: 1.0\r\n");
    if (device->write(data) != data.size()) {
        return false;
    }

    if (!d->content->write(device)) {
        return false;
    }

    return true;
}

void MimeMessage::setSender(const EmailAddress &sender)
{
    Q_D(MimeMessage);
    d->sender = sender;
}

void MimeMessage::setToRecipients(const QList<EmailAddress> &toList)
{
    Q_D(MimeMessage);
    d->recipientsTo = toList;
}

QList<EmailAddress> MimeMessage::toRecipients() const
{
    Q_D(const MimeMessage);
    return d->recipientsTo;
}

void MimeMessage::addTo(const EmailAddress &rcpt)
{
    Q_D(MimeMessage);
    d->recipientsTo.append(rcpt);
}

void MimeMessage::setCcRecipients(const QList<EmailAddress> &ccList)
{
    Q_D(MimeMessage);
    d->recipientsCc = ccList;
}

void MimeMessage::addCc(const EmailAddress &rcpt)
{
    Q_D(MimeMessage);
    d->recipientsCc.append(rcpt);
}

QList<EmailAddress> MimeMessage::ccRecipients() const
{
    Q_D(const MimeMessage);
    return d->recipientsCc;
}

void MimeMessage::setBccRecipients(const QList<EmailAddress> &bccList)
{
    Q_D(MimeMessage);
    d->recipientsBcc = bccList;
}

QList<EmailAddress> MimeMessage::bccRecipients() const
{
    Q_D(const MimeMessage);
    return d->recipientsBcc;
}

void MimeMessage::addBcc(const EmailAddress &rcpt)
{
    Q_D(MimeMessage);
    d->recipientsBcc.append(rcpt);
}

void MimeMessage::setSubject(const QString & subject)
{
    Q_D(MimeMessage);
    d->subject = subject;
}

void MimeMessage::addPart(MimePart *part)
{
    Q_D(MimeMessage);
    if (typeid(*d->content) == typeid(MimeMultiPart)) {
        ((MimeMultiPart*) d->content)->addPart(part);
    }
}

void MimeMessage::setHeaderEncoding(MimePart::Encoding hEnc)
{
    Q_D(MimeMessage);
    d->encoding = hEnc;
}

EmailAddress MimeMessage::sender() const
{
    Q_D(const MimeMessage);
    return d->sender;
}

QString MimeMessage::subject() const
{
    Q_D(const MimeMessage);
    return d->subject;
}

QList<MimePart*> MimeMessage::parts() const
{
    Q_D(const MimeMessage);

    QList<MimePart*> ret;
    if (typeid(*d->content) == typeid(MimeMultiPart)) {
        ret = static_cast<MimeMultiPart*>(d->content)->parts();
    } else {
        ret.append(d->content);
    }

    return ret;
}

MimeMessagePrivate::~MimeMessagePrivate()
{
    delete content;
}

QByteArray MimeMessagePrivate::encode(const QByteArray &addressKind, const QList<EmailAddress> &emails, MimePart::Encoding codec)
{
    if (emails.isEmpty()) {
        return QByteArray();
    }

    QByteArray mime = addressKind;
    bool first = true;
    for (const EmailAddress &email : emails) {
        if (!first) {
            mime.append(',');
        } else {
            first = false;
        }

        const QString name = email.name();
        if (!name.isEmpty()) {
            mime.append(MimeMessagePrivate::encodeData(codec, name, true));
            mime.append(" <" + email.address().toLatin1() + '>');
        } else {
            mime.append('<' + email.address().toLatin1() + '>');
        }
    }
    mime.append(QByteArrayLiteral("\r\n"));

    return mime;
}

QByteArray MimeMessagePrivate::encodeData(MimePart::Encoding codec, const QString &data, bool autoencoding)
{
    const QString simpleData = data.simplified();
    const QByteArray simple = simpleData.toUtf8();
    if (autoencoding) {
        if (simpleData.toLatin1() == simple) {
            return simple;
        }

        int printable = 0;
        int encoded = 0;
        const QByteArray result = QuotedPrintable::encode(simple, true, &printable, &encoded);
        int sum = printable + encoded;
        qCDebug(SIMPLEMAIL_MIMEMSG) << data << result << printable << encoded << sum << ((double) printable/sum) << (encoded/sum);
        if (sum != 0 && ((double) printable/sum) >= 0.8) {
            return " =?utf-8?Q?" + result + "?=";
        } else {
            return " =?utf-8?B?" + data.toUtf8().toBase64() + "?=";
        }
    } else {
        switch (codec) {
        case MimePart::Base64:
            return " =?utf-8?B?" + simple.toBase64() + "?=";
        case MimePart::QuotedPrintable:
            return " =?utf-8?Q?" + QuotedPrintable::encode(simple, true) + "?=";
        default:
            return ' ' + data.toLatin1();
        }
    }
}
<commit_msg>Date header field: add missing new line on field end<commit_after>/*
  Copyright (c) 2011-2012 - Tőkés Attila
  Copyright (C) 2015 Daniel Nicoletti <dantti12@gmail.com>

x
  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  See the LICENSE file for more details.
*/

#include "mimemessage_p.h"

#include <QtCore/QDebug>
#include "quotedprintable.h"
#include <typeinfo>

#include <QDateTime>
#include <QLoggingCategory>

Q_LOGGING_CATEGORY(SIMPLEMAIL_MIMEMSG, "simplemail.mimemessage")

using namespace SimpleMail;

MimeMessage::MimeMessage(bool createAutoMimeContent) :
    d_ptr(new MimeMessagePrivate)
{
    Q_D(MimeMessage);
    if (createAutoMimeContent) {
        d->content = new MimeMultiPart();
    }

    d->autoMimeContentCreated = createAutoMimeContent;
}

MimeMessage::~MimeMessage()
{
    delete d_ptr;
}

MimePart& MimeMessage::getContent()
{
    Q_D(MimeMessage);
    return *d->content;
}

void MimeMessage::setContent(MimePart *content)
{
    Q_D(MimeMessage);
    if (d->autoMimeContentCreated) {
      d->autoMimeContentCreated = false;
      delete d->content;
    }
    d->content = content;
}

bool MimeMessage::write(QIODevice *device)
{
    Q_D(const MimeMessage);

    // Headers
    QByteArray data;

    data = MimeMessagePrivate::encode(QByteArrayLiteral("From: "), QList<EmailAddress>() << d->sender, d->encoding);
    if (device->write(data) != data.size()) {
        return false;
    }

    data = MimeMessagePrivate::encode(QByteArrayLiteral("To: "), d->recipientsTo, d->encoding);
    if (device->write(data) != data.size()) {
        return false;
    }

    data = MimeMessagePrivate::encode(QByteArrayLiteral("Cc: "), d->recipientsCc, d->encoding);
    if (device->write(data) != data.size()) {
        return false;
    }

    data = QByteArrayLiteral("Date: ") + QDateTime::currentDateTime().toString(Qt::RFC2822Date).toLatin1() + QByteArrayLiteral("\r\n");
    if (device->write(data) != data.size()) {
        return false;
    }

    data = QByteArrayLiteral("Subject: ") + MimeMessagePrivate::encodeData(d->encoding, d->subject, true);
    if (device->write(data) != data.size()) {
        return false;
    }

    data = QByteArrayLiteral("\r\nMIME-Version: 1.0\r\n");
    if (device->write(data) != data.size()) {
        return false;
    }

    if (!d->content->write(device)) {
        return false;
    }

    return true;
}

void MimeMessage::setSender(const EmailAddress &sender)
{
    Q_D(MimeMessage);
    d->sender = sender;
}

void MimeMessage::setToRecipients(const QList<EmailAddress> &toList)
{
    Q_D(MimeMessage);
    d->recipientsTo = toList;
}

QList<EmailAddress> MimeMessage::toRecipients() const
{
    Q_D(const MimeMessage);
    return d->recipientsTo;
}

void MimeMessage::addTo(const EmailAddress &rcpt)
{
    Q_D(MimeMessage);
    d->recipientsTo.append(rcpt);
}

void MimeMessage::setCcRecipients(const QList<EmailAddress> &ccList)
{
    Q_D(MimeMessage);
    d->recipientsCc = ccList;
}

void MimeMessage::addCc(const EmailAddress &rcpt)
{
    Q_D(MimeMessage);
    d->recipientsCc.append(rcpt);
}

QList<EmailAddress> MimeMessage::ccRecipients() const
{
    Q_D(const MimeMessage);
    return d->recipientsCc;
}

void MimeMessage::setBccRecipients(const QList<EmailAddress> &bccList)
{
    Q_D(MimeMessage);
    d->recipientsBcc = bccList;
}

QList<EmailAddress> MimeMessage::bccRecipients() const
{
    Q_D(const MimeMessage);
    return d->recipientsBcc;
}

void MimeMessage::addBcc(const EmailAddress &rcpt)
{
    Q_D(MimeMessage);
    d->recipientsBcc.append(rcpt);
}

void MimeMessage::setSubject(const QString & subject)
{
    Q_D(MimeMessage);
    d->subject = subject;
}

void MimeMessage::addPart(MimePart *part)
{
    Q_D(MimeMessage);
    if (typeid(*d->content) == typeid(MimeMultiPart)) {
        ((MimeMultiPart*) d->content)->addPart(part);
    }
}

void MimeMessage::setHeaderEncoding(MimePart::Encoding hEnc)
{
    Q_D(MimeMessage);
    d->encoding = hEnc;
}

EmailAddress MimeMessage::sender() const
{
    Q_D(const MimeMessage);
    return d->sender;
}

QString MimeMessage::subject() const
{
    Q_D(const MimeMessage);
    return d->subject;
}

QList<MimePart*> MimeMessage::parts() const
{
    Q_D(const MimeMessage);

    QList<MimePart*> ret;
    if (typeid(*d->content) == typeid(MimeMultiPart)) {
        ret = static_cast<MimeMultiPart*>(d->content)->parts();
    } else {
        ret.append(d->content);
    }

    return ret;
}

MimeMessagePrivate::~MimeMessagePrivate()
{
    delete content;
}

QByteArray MimeMessagePrivate::encode(const QByteArray &addressKind, const QList<EmailAddress> &emails, MimePart::Encoding codec)
{
    if (emails.isEmpty()) {
        return QByteArray();
    }

    QByteArray mime = addressKind;
    bool first = true;
    for (const EmailAddress &email : emails) {
        if (!first) {
            mime.append(',');
        } else {
            first = false;
        }

        const QString name = email.name();
        if (!name.isEmpty()) {
            mime.append(MimeMessagePrivate::encodeData(codec, name, true));
            mime.append(" <" + email.address().toLatin1() + '>');
        } else {
            mime.append('<' + email.address().toLatin1() + '>');
        }
    }
    mime.append(QByteArrayLiteral("\r\n"));

    return mime;
}

QByteArray MimeMessagePrivate::encodeData(MimePart::Encoding codec, const QString &data, bool autoencoding)
{
    const QString simpleData = data.simplified();
    const QByteArray simple = simpleData.toUtf8();
    if (autoencoding) {
        if (simpleData.toLatin1() == simple) {
            return simple;
        }

        int printable = 0;
        int encoded = 0;
        const QByteArray result = QuotedPrintable::encode(simple, true, &printable, &encoded);
        int sum = printable + encoded;
        qCDebug(SIMPLEMAIL_MIMEMSG) << data << result << printable << encoded << sum << ((double) printable/sum) << (encoded/sum);
        if (sum != 0 && ((double) printable/sum) >= 0.8) {
            return " =?utf-8?Q?" + result + "?=";
        } else {
            return " =?utf-8?B?" + data.toUtf8().toBase64() + "?=";
        }
    } else {
        switch (codec) {
        case MimePart::Base64:
            return " =?utf-8?B?" + simple.toBase64() + "?=";
        case MimePart::QuotedPrintable:
            return " =?utf-8?Q?" + QuotedPrintable::encode(simple, true) + "?=";
        default:
            return ' ' + data.toLatin1();
        }
    }
}
<|endoftext|>