Example #1
0
void CSteamProto::ParsePollData(JSONNode *data)
{
	JSONNode *node, *item = NULL;

	std::string steamIds;
	for (size_t i = 0; i < json_size(data); i++)
	{
		item = json_at(data, i);
		if (item == NULL)
			break;

		node = json_get(item, "steamid_from");
		ptrA steamId(mir_t2a(ptrT(json_as_string(node))));

		node = json_get(item, "utc_timestamp");
		time_t timestamp = atol(ptrA(mir_t2a(ptrT(json_as_string(node)))));

		node = json_get(item, "type");
		ptrT type(json_as_string(node));
		if (!lstrcmpi(type, _T("saytext")) || !lstrcmpi(type, _T("emote")) ||
			!lstrcmpi(type, _T("my_saytext")) || !lstrcmpi(type, _T("my_emote")))
		{
			MCONTACT hContact = FindContact(steamId);
			if (!hContact)
				continue;

			node = json_get(item, "text");
			ptrT text(json_as_string(node));
			T2Utf szMessage(text);

			PROTORECVEVENT recv = { 0 };
			recv.timestamp = timestamp;
			recv.szMessage = szMessage;
			if (_tcsstr(type, _T("my_")) == NULL)
			{
				ProtoChainRecvMsg(hContact, &recv);
			}
			else
			{
				recv.flags = PREF_SENT;
				Proto_RecvMessage(hContact, &recv);
			}
		}
		else if (!lstrcmpi(type, _T("typing")))
		{
			MCONTACT hContact = FindContact(steamId);
			if (hContact)
			{
				CallService(MS_PROTO_CONTACTISTYPING, hContact, (LPARAM)STEAM_TYPING_TIME);
			}
		}
		else if (!lstrcmpi(type, _T("personastate")))
		{
			node = json_get(item, "persona_state");
			int status = node ? SteamToMirandaStatus(json_as_int(node)) : -1;

			if (IsMe(steamId))
			{
				node = json_get(item, "persona_name");
				setTString("Nick", ptrT(json_as_string(node)));

				if (status == -1 || status == ID_STATUS_OFFLINE)
					continue;

				if (status != m_iStatus)
				{
					debugLog(_T("CSteamProto::ParsePollData: Change own status to %i"), status);
					int oldStatus = m_iStatus;
					m_iStatus = m_iDesiredStatus = status;
					ProtoBroadcastAck(NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE)oldStatus, m_iStatus);
				}

				continue;
			}
			
			MCONTACT hContact = FindContact(steamId);
			if (hContact == NULL)
				continue; // probably this is info about random player playing on same server, so we ignore it

			if (status != -1)
				SetContactStatus(hContact, status);

			node = json_get(item, "persona_name");
			setTString(hContact, "Nick", ptrT(json_as_string(node)));

			// todo: find difference between state changing and info changing
			steamIds.append(steamId).append(",");
		}
		else if (!lstrcmpi(type, _T("personarelationship")))
		{
			node = json_get(item, "persona_state");
			int state = json_as_int(node);

			switch (state)
			{
			case 0:
				{// removed
					MCONTACT hContact = FindContact(steamId);
					if (hContact)
					{
						ContactIsRemoved(hContact);
					}
				}
				break;

			case 1:
				{// ignored
					MCONTACT hContact = FindContact(steamId);
					if (hContact)
					{
						ContactIsIgnored(hContact);
					}
				}
				break;

			case 2:
				{// auth request
					/*MCONTACT hContact = FindContact(steamId);
					if (!hContact)
						hContact = AddContact(steamId, true);*/

					//RaiseAuthRequestThread((void*)hContact);

					ptrA token(getStringA("TokenSecret"));

					PushRequest(
						new GetUserSummariesRequest(token, steamId),
						&CSteamProto::OnAuthRequested,
						mir_strdup(steamId),
						MirFreeArg);
				}
				break;

			case 3:
				// add to list
				// todo
				break;

			default: continue;
			}
		}
		/*else if (!lstrcmpi(type, _T("leftconversation")))
		{
		}*/
		else
		{
			continue;
		}
	}

	if (!steamIds.empty())
	{
		steamIds.pop_back();
		ptrA token(getStringA("TokenSecret"));

		PushRequest(
			new GetUserSummariesRequest(token, steamIds.c_str()),
			&CSteamProto::OnGotUserSummaries);
	}
}
SQLRETURN SQL_API SQLTables(
 SQLHSTMT StatementHandle, SQLTCHAR *CatalogName, SQLSMALLINT NameLength1, 
 SQLTCHAR *SchemaName, SQLSMALLINT NameLength2, 
 SQLTCHAR *TableName, SQLSMALLINT NameLength3, 
 SQLTCHAR *TableType, SQLSMALLINT NameLength4)
{
 HDRVSTMT hStmt = (HDRVSTMT)StatementHandle;
 
 LOG_DEBUG_F_FUNC(
  TEXT("%s: StatementHandle = 0x%08lX, CatalogName = %s, NameLength1 = %d, ")
  TEXT("SchemaName = %s, NameLength2 = %d, ")
  TEXT("TableName = %s, NameLength3 = %d, ")
  TEXT("TableType = %s, NameLength4 = %d, "),
  LOG_FUNCTION_NAME,
  (long)StatementHandle, CatalogName, NameLength1,
  SchemaName, NameLength2,
  TableName, NameLength3,
  TableType, NameLength4);

 /* SANITY CHECKS */
 ODBCAPIHelper helper(hStmt, SQL_HANDLE_STMT);
 if(!helper.IsValid())
  return SQL_INVALID_HANDLE;

 API_HOOK_ENTRY(SQLTables,
  StatementHandle, CatalogName, NameLength1, SchemaName, NameLength2,
  TableName, NameLength3, TableType, NameLength4);

 /**************************
  * close any existing result
  **************************/
 helper.CloseResults();

 /**************************
 * Check the input arguments for proper behavior
 **************************/
 /*
 #TODO: convert table search pattern from SQL pattern style to regex pattern 
        style (not currently supported)
 */
 // If TableName is NULL, then assume caller wants to retrieve all tables
 if(TableName == NULL)
 {
  TableName = (SQLTCHAR*)TEXT("*");
  NameLength3 = SQL_NTS;
 }

 // If TableType is NULL, then just assume that it implies all types, 
 // otherwise...
 if(TableType != NULL)
 {
  // If TableType is "", then just assume that it implies all types, 
  // otherwise...
  if(_tcscmp((TCHAR*)TableType, TEXT("")) != 0)
  {
   if(_tcsstr((TCHAR*)TableType, TEXT("TABLE")) == NULL)
   {
    // If the the TableType list does not contain "TABLE", then force zero
    // results.
    TableName = (SQLTCHAR*)TEXT("");
    NameLength3 = SQL_NTS;
   }
  }
 }

 /*
 #TODO: If TableType is SQL_ALL_TABLE_TYPES and CatalogName, SchemaName, and 
        TableName are empty strings, the result set should contain a list of 
        valid table types for the data source (which is just "TABLE" for 
        server right now). (All columns except the TABLE_TYPE column contain 
        NULLs.)
 */

 /**************************
 * retrieve the tables resultset
 **************************/
 ODBCDriver::ServerReturn serverRet = ODBCDriver::SERVER_ERROR;
 ODBCDriver::IService& service = ODBCDriver::Service::instance();

 try
 {
  serverRet = service.GetTables(
   ((HDRVDBC)hStmt->hDbc)->hDbcExtras->conn, 
   helper.GetSafeTString(TableName, NameLength3),
   &(hStmt->hStmtExtras->resultset));
 }
 catch(ODBCDriver::ClientException& ex)
 {
  LOG_ERROR_F_FUNC(TEXT("SQL_ERROR: SQLTables failed. %s"), ex.What());

  helper.FreeResults();
  API_HOOK_RETURN(SQL_ERROR);
 }

 assert(hStmt->hStmtExtras->resultset != NULL);

 /**************************
 * prepare the resultset for consumption
 **************************/
 SQLRETURN rc = helper.PrepareResults();

 LOG_WARN_F_FUNC(TEXT("%s: This function partially supported."),
                 LOG_FUNCTION_NAME);

 helper.LogSQLReturn(LOG_FUNCTION_NAME, rc);

 API_HOOK_RETURN(rc);
}
Example #3
0
/*
 *  display shell version info internal command.
 *
 *
 */
INT cmd_ver (LPTSTR param)
{
	INT i;

  nErrorLevel = 0;

	if (_tcsstr (param, _T("/?")) != NULL)
	{
		ConOutResPaging(TRUE,STRING_VERSION_HELP1);
		return 0;
	}

	ShortVersion();

	/* Basic copyright notice */
	if (param[0] != _T('\0'))
	{

		ConOutPuts (_T("Copyright (C) 1994-1998 FreeDOS, Tim Norman and others."));
		ConOutPuts (_T("Copyright (C) 1998-2016 ReactOS, Eric Kohl and others."));
		ConOutPuts (_T("Copyright (C) 2016-") _T(COPYRIGHT_YEAR) _T(" IRTriageCMD, Alain Martel and others."));

		for (i = 0; param[i]; i++)
		{
			/* skip spaces */
			if (param[i] == _T(' '))
				continue;

			if (param[i] == _T('/'))
			{
				/* is this a lone '/' ? */
				if (param[i + 1] == 0)
				{
					error_invalid_switch (_T(' '));
					return 1;
				}
				continue;
			}

			if (_totupper (param[i]) == _T('W'))
			{
				/* Warranty notice */
				ConOutResPuts(STRING_VERSION_HELP3);
			}
			else if (_totupper (param[i]) == _T('R'))
			{
				/* Redistribution notice */
				ConOutResPuts(STRING_VERSION_HELP4);
			}
			else if (_totupper (param[i]) == _T('C'))
			{
				/* Developer listing */
				ConOutResPuts(STRING_VERSION_HELP6);
				ConOutResPuts(STRING_FREEDOS_DEV);
				ConOutResPuts(STRING_VERSION_HELP7);
                ConOutResPuts(STRING_REACTOS_DEV);
			}
			else
			{
				error_invalid_switch ((TCHAR)_totupper (param[i]));
				return 1;
			}
		}
		ConOutResPuts(STRING_VERSION_HELP5);
	}
	return 0;
}
Example #4
0
gcc_pure
static inline const TCHAR *
StringFind(const TCHAR *haystack, const TCHAR *needle)
{
  return _tcsstr(haystack, needle);
}
Example #5
0
bool
WaypointReaderSeeYou::ParseLine(const TCHAR* line, const unsigned linenum,
                              Waypoints &waypoints)
{
  enum {
    iName = 0,
    iLatitude = 3,
    iLongitude = 4,
    iElevation = 5,
    iStyle = 6,
    iRWDir = 7,
    iRWLen = 8,
    iFrequency = 9,
    iDescription = 10,
  };

  if (linenum == 0)
    ignore_following = false;

  // If (end-of-file or comment)
  if (StringIsEmpty(line) ||
      StringStartsWith(line, _T("**")) ||
      StringStartsWith(line, _T("*")))
    // -> return without error condition
    return true;

  TCHAR ctemp[4096];
  if (_tcslen(line) >= ARRAY_SIZE(ctemp))
    /* line too long for buffer */
    return false;

  // Skip first line if it doesn't begin with a quotation character
  // (usually the field order line)
  if (linenum == 0 && line[0] != _T('\"'))
    return true;

  // If task marker is reached ignore all following lines
  if (_tcsstr(line, _T("-----Related Tasks-----")) == line)
    ignore_following = true;
  if (ignore_following)
    return true;

  // Get fields
  const TCHAR *params[20];
  size_t n_params = ExtractParameters(line, ctemp, params,
                                      ARRAY_SIZE(params), true, _T('"'));

  // Check if the basic fields are provided
  if (iName >= n_params ||
      iLatitude >= n_params ||
      iLongitude >= n_params)
    return false;

  Waypoint new_waypoint;

  // Latitude (e.g. 5115.900N)
  if (!ParseAngle(params[iLatitude], new_waypoint.location.latitude, true))
    return false;

  // Longitude (e.g. 00715.900W)
  if (!ParseAngle(params[iLongitude], new_waypoint.location.longitude, false))
    return false;

  new_waypoint.location.Normalize(); // ensure longitude is within -180:180

  new_waypoint.file_num = file_num;
  new_waypoint.original_id = 0;

  // Name (e.g. "Some Turnpoint")
  if (*params[iName] == _T('\0'))
    return false;
  new_waypoint.name = params[iName];

  // Elevation (e.g. 458.0m)
  /// @todo configurable behaviour
  if ((iElevation >= n_params ||
      !ParseAltitude(params[iElevation], new_waypoint.elevation)) &&
      !CheckAltitude(new_waypoint))
    return false;

  // Style (e.g. 5)
  if (iStyle < n_params)
    ParseStyle(params[iStyle], new_waypoint.type);

  new_waypoint.flags.turn_point = true;

  // Frequency & runway direction/length (for airports and landables)
  // and description (e.g. "Some Description")
  if (new_waypoint.IsLandable()) {
    if (iFrequency < n_params)
      new_waypoint.radio_frequency = RadioFrequency::Parse(params[iFrequency]);

    // Runway length (e.g. 546.0m)
    fixed rwlen = fixed_minus_one;
    if (iRWLen < n_params && ParseDistance(params[iRWLen], rwlen) &&
        positive(rwlen))
      new_waypoint.runway.SetLength(uround(rwlen));

    if (iRWDir < n_params && *params[iRWDir]) {
      TCHAR *end;
      int direction =_tcstol(params[iRWDir], &end, 10);
      if (end == params[iRWDir] || direction < 0 || direction > 360 ||
          (direction == 0 && !positive(rwlen)))
        direction = -1;
      else if (direction == 360)
        direction = 0;
      if (direction >= 0)
        new_waypoint.runway.SetDirectionDegrees(direction);
    }
  }

  if (iDescription < n_params)
    new_waypoint.comment = params[iDescription];

  waypoints.Append(new_waypoint);
  return true;
}
Example #6
0
//------------------------------------------------------------------------------
// DWORD WINAPI EnumComPorts(DWORD dwIndex, LPTSTR lptszName,
//      DWORD dwNumOfElements)
//
// User-mode code fragment to identify attached VCP COMnn port[s] with a
// specific device instance ID based on USB VID and PID and returns the COMnn
// port that the OS embeds into the device instance ID. When called with
// dwIndex = 0, the function will enumerate all COMPORT class devices and
// return the name of the first one that was found. Subsequent calls using an
// incremented dwIndex parameter can be performed until ERROR_NO_MORE_ITEMS
// is returned.
//
// IN:  dwIndex               COMPORT class device # 0, 1, 2, ... to check
//      dwNumOfElements       The size of the lptszName buffer
// OUT: lptszName             COMnn name of given device #
//      return()              ERROR_SUCCESS - lpszName is valid
//                            ERROR_NO_MORE_ITEMS - End of device list reached
//------------------------------------------------------------------------------
DWORD WINAPI EnumComPorts(DWORD dwIndex, LPTSTR lptszName, DWORD dwNumOfElements)
{
    HDEVINFO hDevInfo;
    SP_DEVINFO_DATA DeviceInfoData;
    DWORD i;
    TCHAR *pcParse;

    // Create a HDEVINFO with all present devices
    hDevInfo = SetupDiGetClassDevs(
                    NULL,
                    0, // Enumerator
                    0,
                    DIGCF_PRESENT | DIGCF_ALLCLASSES);
    
    if (INVALID_HANDLE_VALUE == hDevInfo)
    {
        return GetLastError();
    }
    
    // Enumerate through all devices in set
    DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);

    for (i = 0; SetupDiEnumDeviceInfo(hDevInfo, i, &DeviceInfoData); i++)
    {
        LPTSTR buffer     = NULL;
        DWORD  buffersize = 0;

        // Get the device instance ID that is associated with the device information element
        while (!SetupDiGetDeviceInstanceId(
                    hDevInfo, 
                    &DeviceInfoData, 
                    buffer, 
                    buffersize, 
                    &buffersize))
        {
            if (buffer)
            {
               LocalFree(buffer);
            }
                
            if (ERROR_INSUFFICIENT_BUFFER == GetLastError())
            {
                // Change the buffer size. Double the size to avoid problems on
                // W2K MBCS systems per KB 888609.
                buffer = (LPTSTR)LocalAlloc(LPTR, buffersize * 2);
            }
            else
            {
                // Error: could not get device instance ID
                // Cleanup and return error code
                SetupDiDestroyDeviceInfoList(hDevInfo);
                return GetLastError();
            }
        }

        if (buffer)
        {
            // Look for the "Application UART" of common MSP430 EVMs. The application UART
            // has an USB VID of 0x0451 (Texas Instruments) and an PID of 0xF432.
			const TCHAR testval[] = _T("USB\\VID_0451&PID_F432&MI_00");

			if (NULL != _tcsstr(buffer, testval))
            {
				TCHAR szFriendlyName[MAX_PATH];
			    
				if (SetupDiGetDeviceRegistryProperty(
					hDevInfo,
					&DeviceInfoData,
					SPDRP_FRIENDLYNAME,
					NULL,
					(PBYTE)szFriendlyName,
					sizeof(szFriendlyName) - 1,
					NULL))
				{
                    // Check if we have reached the dwIndex-th element, if not keep looking
                    if (dwIndex == 0)
                    {
                        // Find pointer to "COM" substring (secure)
                        szFriendlyName[sizeof(szFriendlyName) - 1] = 0x00;
                        pcParse = _tcsstr(szFriendlyName, _T("COM"));

                        if (pcParse != NULL)
                        {
                            // Zero-terminate COM port string after last digit
                            if (!isdigit(pcParse[4])) {
                                pcParse[4] = 0;
                            }
                            else if (!isdigit(pcParse[5])) {
                                pcParse[5] = 0;
                            }
                            else {
                                pcParse[6] = 0;
                            }

                            // Pass string to the return parameter
                            _tcscpy_s(lptszName, dwNumOfElements, pcParse);

                            // Cleanup
                            SetupDiDestroyDeviceInfoList(hDevInfo);

                            return ERROR_SUCCESS;
                        }
                    }
                    else
                    {
                        dwIndex--;
                    }
				}
			}
		}
    }
   
    //  Cleanup
    SetupDiDestroyDeviceInfoList(hDevInfo);
    
    return ERROR_NO_MORE_ITEMS;
}
Example #7
0
void fnRebuildEntireList(HWND hwnd, struct ClcData *dat)
{
	DWORD style = GetWindowLongPtr(hwnd, GWL_STYLE);
	ClcGroup *group;

	dat->list.expanded = 1;
	dat->list.hideOffline = db_get_b(NULL, "CLC", "HideOfflineRoot", 0) && style&CLS_USEGROUPS;
	dat->list.cl.count = dat->list.cl.limit = 0;
	dat->selection = -1;

	for (int i = 1;; i++) {
		DWORD groupFlags;
		TCHAR *szGroupName = cli.pfnGetGroupName(i, &groupFlags);
		if (szGroupName == NULL)
			break;
		cli.pfnAddGroup(hwnd, dat, szGroupName, groupFlags, i, 0);
	}

	for (MCONTACT hContact = db_find_first(); hContact; hContact = db_find_next(hContact)) {
		if (style & CLS_SHOWHIDDEN || !db_get_b(hContact, "CList", "Hidden", 0)) {
			DBVARIANT dbv;
			if (db_get_ts(hContact, "CList", "Group", &dbv))
				group = &dat->list;
			else {
				group = cli.pfnAddGroup(hwnd, dat, dbv.ptszVal, (DWORD) - 1, 0, 0);
				if (group == NULL && style & CLS_SHOWHIDDEN) group = &dat->list;
				mir_free(dbv.ptszVal);
			}

			if (group != NULL) {
				group->totalMembers++;

				if (dat->filterSearch && dat->szQuickSearch[0] != '\0') {
					TCHAR *name = cli.pfnGetContactDisplayName(hContact, 0);
					TCHAR *lowered_name = CharLowerW(NEWTSTR_ALLOCA(name));
					TCHAR *lowered_search = CharLowerW(NEWTSTR_ALLOCA(dat->szQuickSearch));

					if (_tcsstr(lowered_name, lowered_search))
						cli.pfnAddContactToGroup(dat, group, hContact);
				}
				else if (!(style & CLS_NOHIDEOFFLINE) && (style & CLS_HIDEOFFLINE || group->hideOffline)) {
					char *szProto = GetContactProto(hContact);
					if (szProto == NULL) {
						if (!cli.pfnIsHiddenMode(dat, ID_STATUS_OFFLINE))
							cli.pfnAddContactToGroup(dat, group, hContact);
					}
					else if (!cli.pfnIsHiddenMode(dat, db_get_w(hContact, szProto, "Status", ID_STATUS_OFFLINE)))
						cli.pfnAddContactToGroup(dat, group, hContact);
				}
				else cli.pfnAddContactToGroup(dat, group, hContact);
			}
		}
	}

	if (style & CLS_HIDEEMPTYGROUPS) {
		group = &dat->list;
		group->scanIndex = 0;
		for (;;) {
			if (group->scanIndex == group->cl.count) {
				group = group->parent;
				if (group == NULL)
					break;
			}
			else if (group->cl.items[group->scanIndex]->type == CLCIT_GROUP) {
				if (group->cl.items[group->scanIndex]->group->cl.count == 0) {
					group = cli.pfnRemoveItemFromGroup(hwnd, group, group->cl.items[group->scanIndex], 0);
				}
				else {
					group = group->cl.items[group->scanIndex]->group;
					group->scanIndex = 0;
				}
				continue;
			}
			group->scanIndex++;
		}
	}

	cli.pfnSortCLC(hwnd, dat, 0);
	cli.pfnSetAllExtraIcons(0);
}
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int nCmdShow)
{
	g_strSkinDir = ::GetModulePath();
	g_strSkinDir += _T("\\Skin\\");
	ThreadCacheDC::InitializeThreadCacheDC();
	ThreadCacheDC::CreateThreadCacheDC();


	Gdiplus::GdiplusStartupInput gdiplusStartupInput;
	ULONG_PTR gdiplusToken;
	Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

	// 临时目录
	_TempCachePath = GetTempCachePath(hInstance);

	if (IsRunning())
		return 0;

	if(!_tcsstr( lpstrCmdLine, _T("/h") ))
	{
		wchar_t wcsTmpPath[MAX_PATH] = {0};
		GetModuleFileNameW(NULL,wcsTmpPath,_countof(wcsTmpPath) );
		mhMessageBox(NULL,(wcscat_s(wcsTmpPath, _countof(wcsTmpPath), L" 不是有效的 win32 应用程序。"), wcsTmpPath),L"提示",MB_OK);
		exit(1);
	}	
	//////////////////////////////////////////////////////////////////////////
	// (1)是安装情况
	
	if ( !IsDownload(lpstrCmdLine, &_Module.m_bByUserClick, &_Module.m_hOuterParent)   )//moneyhub.exe execute
	{
		CDownloadOperation dop;
		int index = dop.isValid();

		if( index )
		{
			CBankProcessMgr BankMgr;
			std::vector<HANDLE> vecProcess;

			// 让所有bank退出
			::PostMessage(HWND_BROADCAST, WM_BROADCAST_QUIT, 0, 0);
			Sleep(1000);

			if (BankMgr.GetProcList(_T("MoneyHub.exe"), vecProcess) > 0)
				BankMgr.TermProcList(vecProcess);

			// 运行安装包
			InstallPack();
		}
		else
		{
			deleteAllReg();
			dop.deleteAllUpdataFile();
			ShellExecuteA(GetDesktopWindow(),"open",getModulePath().c_str(),NULL,NULL,SW_SHOWNORMAL);
		}

		return 0;
	}
	else if( isDownLoadOK()  )
	{
		return 0;
	}

	//////////////////////////////////////////////////////////////////////////
	// (2)是下载情况

	HRESULT hRes = ::CoInitialize(NULL);
// If you are running on NT 4.0 or higher you can use the following call instead to 
// make the EXE free threaded. This means that calls come in on a random RPC thread.
//	HRESULT hRes = ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
	ATLASSERT(SUCCEEDED(hRes));

	// this resolves ATL window thunking problem when Microsoft Layer for Unicode (MSLU) is used
	::DefWindowProc(NULL, 0, 0, 0L);

	AtlInitCommonControls(ICC_WIN95_CLASSES | ICC_PROGRESS_CLASS | ICC_BAR_CLASSES);	// add flags to support other controls

	hRes = _Module.Init(NULL, hInstance);
	ATLASSERT(SUCCEEDED(hRes));

	int nRet = Run(lpstrCmdLine, nCmdShow);

	_Module.Term();
	::CoUninitialize();

	if (_hUpdateMutex)
		CloseHandle(_hUpdateMutex);

	return nRet;
}
Example #9
0
int OnDBEventFilterAdd(WPARAM wParam, LPARAM lParam)
{
	HANDLE hContact = (HANDLE)wParam;
	DBEVENTINFO *dbei = (DBEVENTINFO *)lParam;
	char *msgblob;
	POPUPDATA ppdp = {0};
	DBTIMETOSTRING tts = {0};
	char protoOption[256] = {0};
	char *response, *tmp, *challenge;
	int buflen = MAX_BUFFER_LENGTH;
	TCHAR buf[MAX_BUFFER_LENGTH];
	TCHAR *message = NULL, *challengeW = NULL, *tmpW = NULL;
	TCHAR *whitelist = NULL, *ptok;
	TCHAR mexpr[64];
	int maxmsglen = 0, a, b, i;
	BOOL bayesEnabled = _getOptB("BayesEnabled", defaultBayesEnabled);
	BOOL bCorrectResponse = FALSE;

	// get hContact from DBEVENTINFO as icq_proto.c doesn't pass hContact the usual way for some reason.
	if (dbei->eventType == EVENTTYPE_AUTHREQUEST)
		hContact = *((PHANDLE)(dbei->pBlob+sizeof(DWORD)));

	// get maximum length of the message a protocol supports
	maxmsglen = CallProtoService(dbei->szModule, PS_GETCAPS, PFLAG_MAXLENOFMESSAGE, (LPARAM)hContact);

	
	/*** Dequeue and learn messages ***/
	
	if (bayesEnabled && _getOptB("BayesAutolearnNotApproved", defaultBayesAutolearnNotApproved))
		if (time(NULL) - last_queue_check > 4*3600) { // dequeue every 4 hours
			dequeue_messages();
			last_queue_check = time(NULL);
		}


	/*** Check for conditional and unconditional approval ***/

	// Pass-through if protocol is not enabled
	strcat(protoOption, "proto_");
	strcat(protoOption, dbei->szModule);
	if (_getOptB(protoOption, 0) == 0) // Protocol is not handled by Spam-o-tron
		return 0;

	// Pass-through if the event is not of type EVENTTYPE_MESSAGE or EVENTTYPE_AUTHREQUEST
	if (dbei->eventType != EVENTTYPE_MESSAGE && dbei->eventType != EVENTTYPE_AUTHREQUEST)
		return 0;

	// Pass-through if contact is already verified.
	if (_getCOptB(hContact, "Verified", 0) == 1)
		return 0;

	// Pass-through if the event is already read.
	if (dbei->flags & DBEF_READ)
		return 0;

	// Pass-through if event is from a contact that is already in the list. 
	if (db_get_b(hContact, "CList", "NotOnList", 1) == 0) // Already in the list
		return 0;

	// Pass-through if event is from a contact that is already in the server-side contact list
	if (db_get_w(hContact, dbei->szModule, "ServerId", 0))
		return 0;

	// Pass-through if contact is a MetaContact
	if (db_get_dw(hContact, "MetaContacts", "NumContacts", 0))
		return 0;

	// Pass-through and approve if outgoing event.
	if (dbei->flags & DBEF_SENT) {
		if (_getOptB("ApproveOnMsgOut", 0)) {
			_setCOptB(hContact, "Verified", 1);
			if (_getOptB("AddPermanently", defaultAddPermanently))
				db_unset(hContact, "CList", "NotOnList");
			db_unset(hContact, "CList", "Delete");
		}
		return 0;
	}

	// Hide the contact until verified if option set.
	if (_getOptB("HideUnverified", defaultHideUnverified))
		db_set_b(hContact, "CList", "Hidden", 1);

	// Fetch the incoming message body
	if (dbei->eventType == EVENTTYPE_MESSAGE) {
		msgblob = (char *)dbei->pBlob;
	} else if (dbei->eventType == EVENTTYPE_AUTHREQUEST) {
		msgblob = (char *)(dbei->pBlob + sizeof(DWORD) + sizeof(HANDLE));
		for(a=4;a>0;a--)
			msgblob += strlen(msgblob)+1;
	}

	if (dbei->flags & DBEF_UTF)
		message = mir_utf8decodeW(msgblob);
	else
		message = mir_a2u(msgblob);

	
	/*** Check for words in white-list ***/

	if (_getOptB("ApproveOnMsgIn", defaultApproveOnMsgIn)) {
		whitelist = (TCHAR*)malloc(2048 * sizeof(TCHAR));
		if (whitelist != NULL) {
			_getOptS(whitelist, 2048, "ApproveOnMsgInWordlist", defaultApproveOnMsgInWordlist);
			if (_isregex(whitelist)) {
				if (_regmatch(message, whitelist))
					bCorrectResponse = TRUE;
			} else {
				ptok = _tcstok(whitelist, L" ");
				while (ptok != NULL) {
					if (_tcsstr(message, ptok)) {
						bCorrectResponse = TRUE;
						break;
					}
					ptok = _tcstok(NULL, L" ");
				}
			}
			free(whitelist);

			if (bCorrectResponse) {
				_setCOptB(hContact, "Verified", 1);
				if (_getOptB("HideUnverified", defaultHideUnverified))
					db_unset(hContact, "CList", "Hidden");
				if (_getOptB("AddPermanently", defaultAddPermanently))
					db_unset(hContact, "CList", "NotOnList");
				db_unset(hContact, "CList", "Delete");
				if (_getOptB("ReplyOnSuccess", defaultReplyOnSuccess) && (_getCOptB(hContact, "MsgSent", 0))) {
					tmp = mir_u2a(_getOptS(buf, buflen, "SuccessResponse", defaultSuccessResponse));
					response = mir_utf8encode(tmp);
					mir_free(tmp);
					CallContactService(hContact, PSS_MESSAGE, PREF_UTF,	(LPARAM)response);
					mir_free(response);
				}
				return 0;
			}
		}
	}


	/*** Check for correct answer ***/
	
	switch (_getOptB("Mode", defaultMode))
	{
		case SPAMOTRON_MODE_ROTATE:
		case SPAMOTRON_MODE_RANDOM:
			get_response(buf, buflen, _getCOptD(hContact, "ResponseNum", 0));
			if (_isregex(buf)) {
				if (_regmatch(message, buf))
					bCorrectResponse = TRUE;
			} else {
				if (_tcsstr_cc(message, buf, _getOptB("ResponseCC", defaultResponseCC)) &&
					(_tcslen(message) == _tcslen(buf)))
					bCorrectResponse = TRUE;
			}
			break;
		
		case SPAMOTRON_MODE_PLAIN:
			_getOptS(buf, buflen, "Response", defaultResponse);
			i = get_response_num(buf);
			while (i-- > 0) {
				get_response(buf, buflen, i-1);
				if (_isregex(buf)) {
					if (_regmatch(message, buf)) {
						bCorrectResponse = TRUE;
						break;
					}
				} else {
					if (_tcsstr_cc(message, buf, _getOptB("ResponseCC", defaultResponseCC)) &&
						(_tcslen(message) == _tcslen(buf))) {
						bCorrectResponse = TRUE;
						break;
					}
				}
			}
			break;

		case SPAMOTRON_MODE_MATH:
			if (message == NULL)
				break;
			_itot(_getCOptD(hContact, "ResponseMath", -1), buf, 10);
			if (_tcsstr(message, buf) && (_tcslen(buf) == _tcslen(message))) {
				bCorrectResponse = TRUE;
			}
			break;
	}

	if (bCorrectResponse)
	{
		_setCOptB(hContact, "Verified", 1);
		if (_getOptB("HideUnverified", defaultHideUnverified))
			db_unset(hContact, "CList", "Hidden");
		if (_getOptB("AddPermanently", defaultAddPermanently))
			db_unset(hContact, "CList", "NotOnList");
		db_unset(hContact, "CList", "Delete");
		db_unset(hContact, "CList", "ResponseNum");
		if (_getOptB("ReplyOnSuccess", defaultReplyOnSuccess)) {
			tmp = mir_u2a(_getOptS(buf, buflen, "SuccessResponse", defaultSuccessResponse));
			response = mir_utf8encode(tmp);
			mir_free(tmp);
			CallContactService(hContact, PSS_MESSAGE, PREF_UTF,	(LPARAM)response);
			mir_free(response);
		}
		_notify(hContact, POPUP_APPROVED, TranslateT("Contact %s approved."), NULL);

		// Resubmit pending authorization request
		if (_getCOptB(hContact, "AuthEventPending", FALSE)) {
			DBVARIANT _dbv;
			TCHAR AuthEventModule[100];
			char* szAuthEventModule;
			if (db_get(hContact, PLUGIN_NAME, "AuthEvent", &_dbv) == 0) {
				DBEVENTINFO *_dbei = (DBEVENTINFO *)malloc(sizeof(DBEVENTINFO));
				if (_dbei != NULL) {
					memcpy(&_dbei->cbBlob, _dbv.pbVal, sizeof(DWORD));
					_dbei->eventType = EVENTTYPE_AUTHREQUEST;
					_getCOptS(AuthEventModule, 100, hContact, "AuthEventModule", _T("ICQ"));
					szAuthEventModule = mir_u2a(AuthEventModule);
					_dbei->szModule = szAuthEventModule;
					_dbei->timestamp = dbei->timestamp;
					_dbei->flags = 0;
					_dbei->cbSize = sizeof(DBEVENTINFO);
					_dbei->pBlob = _dbv.pbVal + sizeof(DWORD);
					db_event_add(hContact,_dbei);
					db_unset(hContact, PLUGIN_NAME, "AuthEvent");
					db_unset(hContact, PLUGIN_NAME, "AuthEventPending");
					db_unset(hContact, PLUGIN_NAME, "AuthEventModule");
					mir_free(szAuthEventModule);
					free(_dbei);
				}
				db_free(&_dbv);
			}
		}

		// User approved, learn from previous messages
		if (bayesEnabled && _getOptB("BayesAutolearnApproved", defaultBayesAutolearnApproved))
			bayes_approve_contact(hContact);

		// Mark previous messages unread if option set
		if (_getOptB("KeepBlockedMsg", defaultKeepBlockedMsg) && 
			_getOptB("MarkMsgUnreadOnApproval", defaultMarkMsgUnreadOnApproval) &&
			hContact != NULL) {
			// We will mark unread all blocked messages for the most recent day
			MarkUnread(hContact);
		}

		return 1;
	}


	
	/*** Check for rejection ***/

	// Completely reject if challenge was already sent today for MaxMsgContactCountPerDay times
	// and the option is turned on.
	if (isOneDay(dbei->timestamp, _getCOptD(hContact, "MsgSentTime", 0)) &&
		_getOptD("MaxMsgContactCountPerDay", defaultMaxMsgContactCountPerDay) > 0 &&
		_getCOptD(hContact, "MsgSent", 0) >= _getOptD("MaxMsgContactCountPerDay", defaultMaxMsgContactCountPerDay)) {
			_notify(hContact, POPUP_BLOCKED, TranslateT("Message from %s rejected because it reached a maximum for challenge requests per day."), message);
			if (bayesEnabled)
				queue_message(hContact, dbei->timestamp, message);
			return 1;
	}

	// Completely reject if duplicate incoming message found
	if (_getOptD("MaxSameMsgCountPerDay", defaultMaxSameMsgCountPerDay) > 0 &&
		_getCOptD(hContact, "SameMsgCount", 0) >= _getOptD("MaxSameMsgCountPerDay", defaultMaxSameMsgCountPerDay) &&
		_tcscmp(message, _getCOptS(buf, buflen, hContact, "LastInMsg", _T(""))) == 0) {
			_notify(hContact, POPUP_BLOCKED, TranslateT("Message from %s rejected because it reached a maximum for same responses per day."), message);
			if (bayesEnabled)
				queue_message(hContact, dbei->timestamp, message);
			return 1;
	}

	// Completely reject if incoming message contains any word from DontReplyMsgWordlist option
	if (_getOptB("DontReplyMsg", defaultDontReplyMsg) &&
		Contains(message, _getOptS(buf, buflen, "DontReplyMsgWordlist", defaultDontReplyMsgWordlist))) {
		_notify(hContact, POPUP_BLOCKED, TranslateT("Message from %s dropped because it has a word from black list."), message);
		return 1;
	}

	
	/*** Bayes checks ***/

	// Drop if score > spam score
	if (bayesEnabled && _getOptB("BayesBlockMsg", defaultBayesBlockMsg))
		if (get_msg_score(message) >= (double)_getOptD("BayesSpamScore", defaultBayesSpamScore) * SCORE_C) {
			_notify(hContact, POPUP_BLOCKED, TranslateT("Message from %s dropped because of high spam score."), message);
			if (bayesEnabled && _getOptB("BayesAutolearnNotApproved", defaultBayesAutolearnNotApproved))
				queue_message(hContact, dbei->timestamp, message);
			return 1;
		}

	// Accept if score < ham score
	if (bayesEnabled && _getOptB("BayesAutoApprove", defaultBayesAutoApprove)) 
		if (get_msg_score(message) <= (double)_getOptD("BayesHamScore", defaultBayesHamScore) * SCORE_C) {
			_notify(hContact, POPUP_APPROVED, TranslateT("Contact %s approved."), message);
			_setCOptB(hContact, "Verified", 1);
			if (_getOptB("HideUnverified", defaultHideUnverified))
				db_unset(hContact, "CList", "Hidden");
			if (_getOptB("AddPermanently", defaultAddPermanently))
				db_unset(hContact, "CList", "NotOnList");
			db_unset(hContact, "CList", "Delete");
			if (bayesEnabled && 
				_getOptB("BayesAutolearnApproved", defaultBayesAutolearnApproved) &&
				_getOptB("BayesAutolearnAutoApproved", defaultBayesAutolearnAutoApproved)) {
				queue_message(hContact, dbei->timestamp, message);
				bayes_approve_contact(hContact);
			}
			return 0;
		}

	// Accept if event is EVENTTYPE_AUTHREQUEST and ReplyOnAuth is NOT set
		if (dbei->eventType == EVENTTYPE_AUTHREQUEST && !_getOptB("ReplyOnAuth", defaultReplyOnAuth))
			return 0;
	// Accept if event is EVENTTYPE_MESSAGE and ReplyOnMsg is NOT set
		if (dbei->eventType == EVENTTYPE_MESSAGE && !_getOptB("ReplyOnMsg", defaultReplyOnMsg))
			return 0;
		
	/*** Send Challenge ***/

	challengeW = (TCHAR *)malloc(maxmsglen*sizeof(TCHAR));
	tmpW = (TCHAR *)malloc(maxmsglen*sizeof(TCHAR));
	switch (_getOptB("Mode", defaultMode))
	{
		case SPAMOTRON_MODE_PLAIN:
			if (dbei->eventType == EVENTTYPE_AUTHREQUEST)
				_getOptS(challengeW, maxmsglen, "AuthChallenge", defaultAuthChallenge);
			else
				_getOptS(challengeW, maxmsglen, "Challenge", defaultChallenge);
			ReplaceVars(challengeW, maxmsglen);
			tmp = mir_u2a(challengeW);
			challenge = mir_utf8encode(tmp);
			mir_free(tmp);
			CallContactService(hContact, PSS_MESSAGE, PREF_UTF, (LPARAM)challenge);
			mir_free(challenge);
			_notify(hContact, POPUP_CHALLENGE, TranslateT("Sending plain challenge to %s."), message);
			break;
		
		case SPAMOTRON_MODE_ROTATE:
			if (dbei->eventType == EVENTTYPE_AUTHREQUEST)
				_getOptS(challengeW, maxmsglen, "AuthChallenge", defaultAuthChallenge);
			else
				_getOptS(challengeW, maxmsglen, "Challenge", defaultChallenge);
			_getOptS(buf, buflen, "Response", defaultResponse);
			if (_getCOptD(hContact, "ResponseNum", 0) >= (unsigned int)(get_response_num(buf)-1)) {
				_setCOptD(hContact, "ResponseNum", -1);
			}
			_setCOptD(hContact, "ResponseNum", _getCOptD(hContact, "ResponseNum", -1) + 1);
			ReplaceVarsNum(challengeW, maxmsglen, _getCOptD(hContact, "ResponseNum", 0));

			tmp = mir_u2a(challengeW);
			challenge = mir_utf8encode(tmp);
			mir_free(tmp);
			CallContactService(hContact, PSS_MESSAGE, PREF_UTF, (LPARAM)challenge);
			mir_free(challenge);
			_notify(hContact, POPUP_CHALLENGE, TranslateT("Sending round-robin challenge to %s."), message);
			break;

		case SPAMOTRON_MODE_RANDOM:
			if (dbei->eventType == EVENTTYPE_AUTHREQUEST)
				_getOptS(challengeW, maxmsglen, "AuthChallenge", defaultAuthChallenge);
			else
				_getOptS(challengeW, maxmsglen, "Challenge", defaultChallenge);
			_getOptS(buf, buflen, "Response", defaultResponse);
			srand(time(NULL));
			_setCOptD(hContact, "ResponseNum", rand() % get_response_num(buf));
			ReplaceVarsNum(challengeW, maxmsglen, _getCOptD(hContact, "ResponseNum", 0));
			tmp = mir_u2a(challengeW);
			challenge = mir_utf8encode(tmp);
			mir_free(tmp);
			CallContactService(hContact, PSS_MESSAGE, PREF_UTF, (LPARAM)challenge);
			mir_free(challenge);
			_notify(hContact, POPUP_CHALLENGE, TranslateT("Sending random challenge to %s."), message);
			break;

		case SPAMOTRON_MODE_MATH:
			a = (rand() % 10) + 1;
			b = (rand() % 10) + 1;
			mir_sntprintf(mexpr, sizeof(mexpr), _T("%d + %d"), a, b);
			if (dbei->eventType == EVENTTYPE_AUTHREQUEST)
				_getOptS(challengeW, maxmsglen, "AuthChallengeMath", defaultAuthChallengeMath);
			else
				_getOptS(challengeW, maxmsglen, "ChallengeMath", defaultChallengeMath);
			ReplaceVar(challengeW, maxmsglen, _T("%mathexpr%"), mexpr);
			_setCOptD(hContact, "ResponseMath", a + b);
			tmp = mir_u2a(challengeW);
			challenge = mir_utf8encode(tmp);
			mir_free(tmp);
			CallContactService(hContact, PSS_MESSAGE, PREF_UTF, (LPARAM)challenge);
			mir_free(challenge);
			_notify(hContact, POPUP_CHALLENGE, TranslateT("Sending math expression challenge to %s."), message);
			break;
	}
	free(challengeW);
	free(tmpW);

	// As a workaround for temporary NotOnList contact not being deleted from server-side list
	// (which was added by the ICQ server itself upon first outgoing challenge request message)
	// we need to set Delete setting, so that contacts gets deleted on next restart/connect.
	db_set_b(hContact, "CList", "Delete", 1);

	// Queue user message in Bayes db
	if (bayesEnabled && message != NULL)
		queue_message(hContact, dbei->timestamp, message);


	/*** Do any post-send procedures we need to do ***/

	// Increment MsgSent if it was sent the same day. Otherwise set it to 1.
	if (isOneDay(dbei->timestamp, _getCOptD(hContact, "MsgSentTime",0)))
		_setCOptD(hContact, "MsgSent", _getCOptD(hContact, "MsgSent", 0)+1);
	else 
		_setCOptD(hContact, "MsgSent", 1);
	_setCOptD(hContact, "MsgSentTime", dbei->timestamp);

	// Save Last Msg and update SameMsgCount
	if (message != NULL) {
		if (_tcscmp(_getCOptS(buf, buflen, hContact, "LastInMsg", _T("")), message) == 0)
			_setCOptD(hContact, "SameMsgCount", 1+_getCOptD(hContact, "SameMsgCount", 0));
		else 
			_setCOptD(hContact, "SameMsgCount", 1);
		_setCOptTS(hContact, "LastInMsg", message);
	}

	if (message != NULL)
		mir_free(message);

	// Finally silently save the message to contact history if corresponding option is set
	if (_getOptB("KeepBlockedMsg", defaultKeepBlockedMsg)) {
		if (dbei->eventType == EVENTTYPE_AUTHREQUEST) {
			// Save the request to database so that it can be automatically submitted on user approval
			PBYTE eventdata = (PBYTE)malloc(sizeof(DWORD) + dbei->cbBlob);
			if (eventdata != NULL && dbei->cbBlob > 0) {
				memcpy(eventdata, &dbei->cbBlob, sizeof(DWORD));
				memcpy(eventdata + sizeof(DWORD), dbei->pBlob, dbei->cbBlob);
				db_set_blob(hContact, PLUGIN_NAME, "AuthEvent", eventdata, sizeof(DWORD) + dbei->cbBlob);
				_setCOptS(hContact, "AuthEventModule", dbei->szModule);
				_setCOptB(hContact, "AuthEventPending", TRUE);
				free(eventdata);
			}
		} else {
			if (_getOptB("MarkMsgUnreadOnApproval", defaultMarkMsgUnreadOnApproval)) {
				DBVARIANT _dbv;
				DWORD dbei_size = 3*sizeof(DWORD) + sizeof(WORD) + dbei->cbBlob + (DWORD)strlen(dbei->szModule)+1;
				PBYTE eventdata = (PBYTE)malloc(dbei_size);
				PBYTE pos = eventdata;
				if (eventdata != NULL && dbei->cbBlob > 0) {
					if (db_get(hContact, PLUGIN_NAME, "LastMsgEvents", &_dbv) == 0) {
						eventdata = (PBYTE)realloc(eventdata, dbei_size + _dbv.cpbVal);
						pos = eventdata;
						memcpy(eventdata, _dbv.pbVal, _dbv.cpbVal);
						pos += _dbv.cpbVal;
						db_free(&_dbv);
					}
					memcpy(pos, &dbei->eventType, sizeof(WORD));
					memcpy(pos+sizeof(WORD), &dbei->flags, sizeof(DWORD));
					memcpy(pos+sizeof(WORD)+sizeof(DWORD), &dbei->timestamp, sizeof(DWORD));
					memcpy(pos+sizeof(WORD)+sizeof(DWORD)*2, dbei->szModule, strlen(dbei->szModule)+1);
					memcpy(pos+sizeof(WORD)+sizeof(DWORD)*2+strlen(dbei->szModule)+1, &dbei->cbBlob, sizeof(DWORD));
					memcpy(pos+sizeof(WORD)+sizeof(DWORD)*3+strlen(dbei->szModule)+1, dbei->pBlob, dbei->cbBlob);
					db_set_blob(hContact, PLUGIN_NAME, "LastMsgEvents", eventdata, (pos - eventdata) + dbei_size);
					free(eventdata);
				}
				
			} else {
				dbei->flags |= DBEF_READ;
				db_event_add(hContact, dbei);
			}
		}
	}
	return 1;
}
Example #10
0
//
// TODO CHECK BUFFER SIZE, which is 100 (set in Buttons).
//
bool ExpandMacros(const TCHAR *In, TCHAR *OutBuffer, size_t Size){

  TCHAR *a;
  LK_tcsncpy(OutBuffer, In, Size - 1);

  if (_tcsstr(OutBuffer, TEXT("$(")) == NULL) {
	return false;
  }

  short items=1;
  bool invalid = false;

  // Accelerator for entire label replacement- only one macro per label accepted
  a =_tcsstr(OutBuffer, TEXT("$(AC"));
  if (a != NULL) {
	TCHAR tbuf[20];
	short i;
	i= (*(a+4)-'0')*10;
	i+= *(a+5)-'0';
	LKASSERT(i>=0 && i<41);

	switch(i) {
		case 0:	// LOCKMODE
			_tcscpy(OutBuffer,_T(""));	// default is button invisible
			if (LockMode(0)) {	// query availability
				if (LockMode(1)) // query status
					_tcscpy(OutBuffer,MsgToken(965)); // UNLOCK\nSCREEN
				else
					_tcscpy(OutBuffer,MsgToken(966)); // LOCK\nSCREEN

				if (!LockMode(3)) invalid=true; // button not usable
			}
			break;

		case 1:	// Pan Supertoggle  PanModeStatus  mode=pan location=8
			if ( MapWindow::mode.AnyPan() )
				_stprintf(OutBuffer, _T("%s%s"),MsgToken(2004),MsgToken(491));	// OFF
			else
				_stprintf(OutBuffer, _T("%s%s"),MsgToken(2004),MsgToken(894));	// ON
			break;

		case 2:	// Pan Supertoggle  PanModeStatus  mode=ScreenMode location=8
			if ( MapWindow::mode.AnyPan() )
				_stprintf(OutBuffer, _T("%s\n%s"),MsgToken(2082),MsgToken(491));	// OFF
			else
				_stprintf(OutBuffer, _T("%s\n%s"),MsgToken(2082),MsgToken(894));	// ON
			break;

		case 3: // DISABLED
			_tcscpy(OutBuffer,MsgToken(2023)); // Reserved
			invalid=true;
			break;

		case 4: // MacCreadyValue + 2078
			_stprintf(tbuf,_T("%2.1lf"), iround(LIFTMODIFY*MACCREADY*10)/10.0);
			_stprintf(OutBuffer, _T("%s\n%s"), MsgToken(2078), tbuf);
			break;

		case 5:
			if (CALCULATED_INFO.AutoMacCready)  {
				switch(AutoMcMode) {
					case amcFinalGlide:
						_stprintf(tbuf,_T("%s"), MsgToken(1681));
						break;
					case amcAverageClimb:
						_stprintf(tbuf,_T("%s"), MsgToken(1682));
						break;
					case amcEquivalent:
						_stprintf(tbuf,_T("%s"), MsgToken(1683));
						break;
					case amcFinalAndClimb:
						if (CALCULATED_INFO.FinalGlide)
							_stprintf(tbuf,_T("%s"), MsgToken(1681));
						else
							_stprintf(tbuf,_T("%s"), MsgToken(1682));
						break;
					default:
						// LKTOKEN _@M1202_ "Auto"
						_stprintf(tbuf,_T("%s"), MsgToken(1202));
						break;
				}
			} else {
				// LKTOKEN _@M1201_ "Man"
				_stprintf(tbuf,_T("%s"), MsgToken(1201));
			}
			_stprintf(OutBuffer,_T("Mc %s\n%2.1lf"), tbuf,iround(LIFTMODIFY*MACCREADY*10)/10.0);

			break;

		case 6: // WaypointNext
			invalid = !ValidTaskPoint(ActiveTaskPoint+1);
			if (!ValidTaskPoint(ActiveTaskPoint+2))
				_tcscpy(OutBuffer,MsgToken(801)); // Waypoint Finish
			else
				_tcscpy(OutBuffer,MsgToken(802)); // Waypoint Next
			break;

		case 7: // WaypointPrevious

			if (ActiveTaskPoint==1) {
				invalid = !ValidTaskPoint(ActiveTaskPoint-1);
				_tcscpy(OutBuffer,MsgToken(804)); // Waypoint Start
			} else if (EnableMultipleStartPoints) {
				invalid = !ValidTaskPoint(0);

				if (ActiveTaskPoint==0)
					_tcscpy(OutBuffer,_T("StartPnt\nCycle"));
				else
					_tcscpy(OutBuffer,MsgToken(803)); // Waypoint Previous
			} else {
				invalid = (ActiveTaskPoint<=0);
				_tcscpy(OutBuffer,MsgToken(803)); // Waypoint Previous
			}
			break;

		case 8: // RealTask  check for Task reset

			if (! (ValidTaskPoint(ActiveTaskPoint) && ValidTaskPoint(1))) {
				invalid=true;
			}

			_tcscpy(OutBuffer,MsgToken(2019)); // Task reset
			break;

		case 9: // TerrainVisible for ChangeBack topology color
			if (CALCULATED_INFO.TerrainValid && IsMultimapTerrain() && !LKVarioBar) {
				invalid = true;
			}
			_tcscpy(OutBuffer,MsgToken(2037)); // Change topo back
			break;

		case 10: // TOGGLEHBAR HBARAVAILABLE for Toggle HBAR button

			if (!GPS_INFO.BaroAltitudeAvailable) {
				_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2045),MsgToken(1068)); // Nav by HBAR
				invalid=true;
			} else {
				if (EnableNavBaroAltitude)
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2045),MsgToken(1174)); // Nav by HGPS
				else
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2045),MsgToken(1068)); // Nav by HBAR
			}
			break;

		case 11: // SIM MENU SIMONLY
			if (SIMMODE)
				_tcscpy(OutBuffer,MsgToken(2074)); // SIM MENU
			else
				_tcscpy(OutBuffer,_T(""));
			break;

		case 12: // THIS MACRO IS AVAILABLE FOR USE
			break;

		case 13:
			if(UseTotalEnergy) {
				_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2115),MsgToken(894)); // TE ON
            } else {
                _stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2115),MsgToken(491)); // TE OFF
			}
			break;

		case 14:
			if ( Shading )
				_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2080),MsgToken(491)); // OFF
			else
				_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2080),MsgToken(894)); // ON
			break;

		case 15:
			if (EnableSoundModes)
				_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2055),MsgToken(491)); // OFF
			else
				_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2055),MsgToken(894)); // ON
			break;

		case 16: // ActiveMap no more used now Radio Button
                        #ifdef RADIO_ACTIVE
			if (RadioPara.Enabled) {
			   _stprintf(OutBuffer,_T("%s\n"),MsgToken(2306)); // TEXT
			   invalid=false;
			} else {
			  _stprintf(OutBuffer,_T("%s\n"),MsgToken(2306)); // TEXT
			  invalid=true;
			}

                        #else
                                invalid=true;
                        #endif
			break;
		case 17:
			// Order is:  ALL ON, TEXT ONLY, GAUGES ONLY, ALL OFF
			if (!HaveGauges()) {
				if (!IsMultimapOverlaysText()) {
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2079),MsgToken(2234)); // TEXT
				} else {
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2079),MsgToken(491)); // OFF
				}
				break;
			}
			if (!IsMultimapOverlaysText()&&!IsMultimapOverlaysGauges()) {
				_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2079),MsgToken(899)); // ALL ON
			} else {
				if (IsMultimapOverlaysAll()) {
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2079),MsgToken(2234)); // TEXT
				} else {
					if (IsMultimapOverlaysText())
						_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2079),MsgToken(2235)); // GAUGES
					else
						_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2079),MsgToken(898)); // ALL OFF
				}
			}
			break;

		case 18:
			if (Orbiter)
				_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2065),MsgToken(491)); // OFF
			else
				_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2065),MsgToken(894)); // ON
			if (!EnableThermalLocator) invalid = true;
			break;

		case 19:
			if (IsMultimapAirspace())
				_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2029),MsgToken(491)); // OFF
			else
				_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2029),MsgToken(894)); // ON
			break;

		case 20:
			if (MapWindow::zoom.AutoZoom() )
				_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2009),MsgToken(418));
			else
				_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2009),MsgToken(897));
			break;

		case 21:
			if (IsMultimapTopology())
				_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2027),MsgToken(491)); // OFF
			else
				_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2027),MsgToken(894)); // ON
			break;

		case 22:
			if (IsMultimapTerrain())
				_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2028),MsgToken(491)); // OFF
			else
				_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2028),MsgToken(894)); // ON
			break;

		case 23:
			if (MapSpaceMode!=MSM_MAP) invalid=true;
			if (MapWindow::mode.UserForcedMode() == MapWindow::Mode::MODE_FLY_CIRCLING)
				_stprintf(OutBuffer,_T("DspMode\n_%s_"),MsgToken(2031));
			else
				_stprintf(OutBuffer,_T("DspMode\n%s"),MsgToken(2031));
			break;

		case 24:
			if (MapSpaceMode!=MSM_MAP) invalid=true;
			if (MapWindow::mode.UserForcedMode() == MapWindow::Mode::MODE_FLY_CRUISE)
				_stprintf(OutBuffer,_T("DspMode\n_%s_"),MsgToken(2032));
			else
				_stprintf(OutBuffer,_T("DspMode\n%s"),MsgToken(2032));
			break;
		case 25:
			if (MapSpaceMode!=MSM_MAP) invalid=true;
			if (MapWindow::mode.UserForcedMode() == MapWindow::Mode::MODE_FLY_NONE)
				_stprintf(OutBuffer,_T("DspMode\n_%s_"),MsgToken(2034));
			else
				_stprintf(OutBuffer,_T("DspMode\n%s"),MsgToken(2034));
			break;
		case 26:
			if (MapSpaceMode!=MSM_MAP) invalid=true;
			if (MapWindow::mode.UserForcedMode() == MapWindow::Mode::MODE_FLY_FINAL_GLIDE)
				_stprintf(OutBuffer,_T("DspMode\n_%s_"),MsgToken(2033));
			else
				_stprintf(OutBuffer,_T("DspMode\n%s"),MsgToken(2033));
			break;

		case 27: // amcIsBoth
			if (CALCULATED_INFO.AutoMacCready && AutoMcMode==amcFinalAndClimb)
				_stprintf(OutBuffer,_T("Auto\n_%s_"),MsgToken(2117));
			else
				_stprintf(OutBuffer,_T("Auto\n%s"),MsgToken(2117));
			break;
		case 28: // amcIsFinal
			if (CALCULATED_INFO.AutoMacCready && AutoMcMode==amcFinalGlide)
				_stprintf(OutBuffer,_T("Auto\n_%s_"),MsgToken(2033));
			else
				_stprintf(OutBuffer,_T("Auto\n%s"),MsgToken(2033));
			break;
		case 29: // amcIsClimb
			if (CALCULATED_INFO.AutoMacCready && AutoMcMode==amcAverageClimb)
				_stprintf(OutBuffer,_T("Auto\n_%s_"),MsgToken(2075));
			else
				_stprintf(OutBuffer,_T("Auto\n%s"),MsgToken(2075));
			break;
		case 30: // amcIsEquiv
			if (CALCULATED_INFO.AutoMacCready && AutoMcMode==amcEquivalent)
				_stprintf(OutBuffer,_T("Auto\n_%s_"),MsgToken(2076));
			else
				_stprintf(OutBuffer,_T("Auto\n%s"),MsgToken(2076));
			break;
		case 31: // CheckManMc
			if (CALCULATED_INFO.AutoMacCready)
				_stprintf(OutBuffer,_T("Mc\n%s"),MsgToken(2077));
			else
				_stprintf(OutBuffer,_T("Mc\n_%s_"),MsgToken(2077));
			break;

		case 32: // AirspaceMode
			switch(AltitudeMode) {
				case 0:
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2029),MsgToken(184)); // Clip
					break;
				case 1:
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2029),MsgToken(897)); // Auto
					break;
				case 2:
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2029),MsgToken(139)); // Below
					break;
				case 3:
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2029),MsgToken(359)); // Inside
					break;
				case 4:
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2029),MsgToken(75)); // All Off
					break;
				case 5:
				default:
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2029),MsgToken(76)); // All On
					break;
			}
			break;

		case 33: // SnailTrailToggleName
			if (MapSpaceMode!=MSM_MAP) invalid=true;
                        // Since we show the next choice, but the order is not respected in 5.0:
                        // the new order is artificially off-short-long-full, as in the inputevents button management
			switch(TrailActive) {
				case 0: // off to short
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2035),MsgToken(612)); // Short
					break;
				case 1: // long to full
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2035),MsgToken(312)); // Full
					break;
				case 2: // short to long
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2035),MsgToken(410)); // Long
					break;
				case 3: // full to off
				default:
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2035),MsgToken(491)); // OFF
					break;
			}
			break;

		case 34: // MapLabelsToggleActionName
			switch(GetMultimap_Labels()) {
				case MAPLABELS_ALLON:
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2026),MsgToken(1203)); // WPTS
					break;
				case MAPLABELS_ONLYWPS:
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2026),MsgToken(1204)); // TOPO
					break;
				case MAPLABELS_ONLYTOPO:
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2026),MsgToken(898));
					break;
				case MAPLABELS_ALLOFF:
				default:
					_stprintf(OutBuffer,_T("%s\n%s"),MsgToken(2026),MsgToken(899));
					break;
			}
			break;

		case 35: // SIM PAN MODE REPOSITION, PANREPOS
			if (SIMMODE)
				_tcscpy(OutBuffer,MsgToken(2133)); // Position
			else
				_tcscpy(OutBuffer,_T(""));
			break;

		case 36: //
			// Order is:  ALL ON, TASK ONLY, FAI ONLY, ALL OFF
			if (Flags_DrawTask&&Flags_DrawFAI) {
				_tcscpy(OutBuffer,MsgToken(2238)); // Draw Task
			} else {
				if (Flags_DrawTask&&!Flags_DrawFAI) {
					_tcscpy(OutBuffer,MsgToken(2239)); // Draw FAI
				} else {
					if (!Flags_DrawTask&&Flags_DrawFAI) {
						_tcscpy(OutBuffer,MsgToken(2240)); // NoDraw TaskFAI
					} else {
						_tcscpy(OutBuffer,MsgToken(2241)); // Draw TaskFAI
					}
				}
			}
			break;
		case 37: //
			if (SonarWarning)
				_tcscpy(OutBuffer,MsgToken(2243)); // Sonar OFF
			else
				_tcscpy(OutBuffer,MsgToken(2242)); // Sonar ON
			break;
		case 38: //
			if (MapSpaceMode!=MSM_MAP) invalid=true;
			_tcscpy(OutBuffer,MsgToken(2081)); // Set Map
			break;
		case 39:
			if (! (ValidTaskPoint(ActiveTaskPoint) && ValidTaskPoint(1))) {
				invalid=true;
			}

			_tcscpy(OutBuffer,MsgToken(1850)); // Task reverse
			break;
        case 40:
            if(IsKobo()) {
#ifdef KOBO
                if(IsKoboWifiOn()) {
                    _tcscpy(OutBuffer,_T("Wifi\nOff"));
                } else {
                    _tcscpy(OutBuffer,_T("Wifi\nOn"));
                }
#endif
            } else {
                _tcscpy(OutBuffer,_T(""));
            }
            break;
		default:
			_stprintf(OutBuffer, _T("INVALID\n%d"),i);
			break;
	}
	goto label_ret;
  } // ACcelerator

  // No accelerator? First check if we have a second macro embedded in string

  a =_tcsstr(OutBuffer, TEXT("&("));
  if (a != NULL) {
	*a=_T('$');
	items=2;
  }

  // Then go for one-by-one match search, slow



  if (_tcsstr(OutBuffer, TEXT("$(AdvanceArmed)"))) {
    switch (AutoAdvance) {
    case 0:
      ReplaceInString(OutBuffer, TEXT("$(AdvanceArmed)"), MsgToken(892), Size); // (manual)
      invalid = true;
      break;
    case 1:
      ReplaceInString(OutBuffer, TEXT("$(AdvanceArmed)"), MsgToken(893), Size); // (auto)
      invalid = true;
      break;
    case 2:
      if (ActiveTaskPoint>0) {
        if (ValidTaskPoint(ActiveTaskPoint+1)) {
          CondReplaceInString(AdvanceArmed, OutBuffer, TEXT("$(AdvanceArmed)"),
		MsgToken(161),  // Cancel
		MsgToken(678), Size); // TURN
        } else {
          ReplaceInString(OutBuffer, TEXT("$(AdvanceArmed)"), MsgToken(8), Size); // (finish)
          invalid = true;
        }
      } else {
        CondReplaceInString(AdvanceArmed, OutBuffer, TEXT("$(AdvanceArmed)"),
		MsgToken(161),  // Cancel
		MsgToken(571), Size); // START
      }
      break;
    case 3:
      if (ActiveTaskPoint==0) {
        CondReplaceInString(AdvanceArmed, OutBuffer, TEXT("$(AdvanceArmed)"),
		MsgToken(161),  // Cancel
		MsgToken(571), Size); // START
      } else if (ActiveTaskPoint==1) {
        CondReplaceInString(AdvanceArmed, OutBuffer, TEXT("$(AdvanceArmed)"),
		MsgToken(161),  // Cancel
		MsgToken(539), Size); // RESTART
      } else {
        ReplaceInString(OutBuffer, TEXT("$(AdvanceArmed)"), MsgToken(893), Size); // (auto)
        invalid = true;
      }
      break;
      // TODO bug: no need to arm finish
    case 4:
      if (ActiveTaskPoint>0) {
        if (ValidTaskPoint(ActiveTaskPoint+1)) {
          CondReplaceInString(AdvanceArmed, OutBuffer, TEXT("$(AdvanceArmed)"),
		MsgToken(161),  // Cancel
		MsgToken(678), Size); // TURN
        } else {
          ReplaceInString(OutBuffer, TEXT("$(AdvanceArmed)"), MsgToken(8), Size); // (finish)
          invalid = true;
        }
      }
      else {
        ReplaceInString(OutBuffer, TEXT("$(AdvanceArmed)"), MsgToken(893), Size); // (auto)
        invalid = true;
      }
      break;
    default:
      break;
    }
	if (--items<=0) goto label_ret; // 100517
  }


  if (_tcsstr(OutBuffer, TEXT("$(CheckFlying)"))) {
    if (!CALCULATED_INFO.Flying) {
      invalid = true;
    }
    ReplaceInString(OutBuffer, TEXT("$(CheckFlying)"), TEXT(""), Size);
	if (--items<=0) goto label_ret;
  }

  if (_tcsstr(OutBuffer, TEXT("$(NotInReplay)"))) {
    if (ReplayLogger::IsEnabled()) {
      invalid = true;
    }
    ReplaceInString(OutBuffer, TEXT("$(NotInReplay)"), TEXT(""), Size);
	if (--items<=0) goto label_ret; // 100517
  }

  if (_tcsstr(OutBuffer, TEXT("$(CheckWaypointFile)"))) {
    if (!ValidWayPoint(NUMRESWP)) {
      invalid = true;
    }
    ReplaceInString(OutBuffer, TEXT("$(CheckWaypointFile)"), TEXT(""), Size);
	if (--items<=0) goto label_ret; // 100517
  }
  if (_tcsstr(OutBuffer, TEXT("$(CheckSettingsLockout)"))) {
    if (LockSettingsInFlight && CALCULATED_INFO.Flying) {
      invalid = true;
    }
    ReplaceInString(OutBuffer, TEXT("$(CheckSettingsLockout)"), TEXT(""), Size);
	if (--items<=0) goto label_ret; // 100517
  }
  if (_tcsstr(OutBuffer, TEXT("$(CheckTask)"))) {
    if (!ValidTaskPoint(ActiveTaskPoint)) {
      invalid = true;
    }
    ReplaceInString(OutBuffer, TEXT("$(CheckTask)"), TEXT(""), Size);
	if (--items<=0) goto label_ret; // 100517
  }
  if (_tcsstr(OutBuffer, TEXT("$(CheckAirspace)"))) {
	if (!CAirspaceManager::Instance().ValidAirspaces()) {
      invalid = true;
    }
    ReplaceInString(OutBuffer, TEXT("$(CheckAirspace)"), TEXT(""), Size);
	if (--items<=0) goto label_ret; // 100517
  }
  if (_tcsstr(OutBuffer, TEXT("$(CheckFLARM)"))) {
    if (!GPS_INFO.FLARM_Available) {
      invalid = true;
    }
    ReplaceInString(OutBuffer, TEXT("$(CheckFLARM)"), TEXT(""), Size);
	if (--items<=0) goto label_ret; // 100517
  }



  // If it is not SIM mode, it is invalid
  if (_tcsstr(OutBuffer, TEXT("$(OnlyInSim)"))) {
	if (!SIMMODE) invalid = true;
	ReplaceInString(OutBuffer, TEXT("$(OnlyInSim)"), TEXT(""), Size);
	if (--items<=0) goto label_ret; // 100517
  }
  if (_tcsstr(OutBuffer, TEXT("$(OnlyInFly)"))) {
	#if TESTBENCH
	invalid=false;
	#else
	if (SIMMODE) invalid = true;
	#endif
	ReplaceInString(OutBuffer, TEXT("$(OnlyInFly)"), TEXT(""), Size);
	if (--items<=0) goto label_ret; // 100517
  }


  if (_tcsstr(OutBuffer, TEXT("$(WCSpeed)"))) {
	TCHAR tbuf[10];
	_stprintf(tbuf,_T("%.0f%s"),SPEEDMODIFY*WindCalcSpeed,Units::GetUnitName(Units::GetUserHorizontalSpeedUnit()) );
	ReplaceInString(OutBuffer, TEXT("$(WCSpeed)"), tbuf, Size);
	if (--items<=0) goto label_ret; // 100517
  }

  if (_tcsstr(OutBuffer, TEXT("$(GS"))) {
	TCHAR tbuf[10];
	_stprintf(tbuf,_T("%.0f%s"),SPEEDMODIFY*GPS_INFO.Speed,Units::GetUnitName(Units::GetUserHorizontalSpeedUnit()) );
	ReplaceInString(OutBuffer, TEXT("$(GS)"), tbuf, Size);
	if (--items<=0) goto label_ret;
  }
  if (_tcsstr(OutBuffer, TEXT("$(HGPS"))) {
	TCHAR tbuf[10];
	_stprintf(tbuf,_T("%.0f%s"),ALTITUDEMODIFY*GPS_INFO.Altitude,Units::GetUnitName(Units::GetUserAltitudeUnit()) );
	ReplaceInString(OutBuffer, TEXT("$(HGPS)"), tbuf, Size);
	if (--items<=0) goto label_ret;
  }
  if (_tcsstr(OutBuffer, TEXT("$(TURN"))) {
	TCHAR tbuf[10];
	_stprintf(tbuf,_T("%.0f"),SimTurn);
	ReplaceInString(OutBuffer, TEXT("$(TURN)"), tbuf, Size);
	if (--items<=0) goto label_ret;
  }
  if (_tcsstr(OutBuffer, TEXT("$(NETTO"))) {
	TCHAR tbuf[10];
	_stprintf(tbuf,_T("%.1f"),SimNettoVario);
	ReplaceInString(OutBuffer, TEXT("$(NETTO)"), tbuf, Size);
	if (--items<=0) goto label_ret;
  }


  if (_tcsstr(OutBuffer, TEXT("$(LoggerActive)"))) {
	CondReplaceInString(LoggerActive, OutBuffer, TEXT("$(LoggerActive)"), MsgToken(670), MsgToken(657), Size); // Stop Start
	if (--items<=0) goto label_ret; // 100517
  }


  if (_tcsstr(OutBuffer, TEXT("$(NoSmart)"))) {
	if (DisplayOrientation == NORTHSMART) invalid = true;
	ReplaceInString(OutBuffer, TEXT("$(NoSmart)"), TEXT(""), Size);
	if (--items<=0) goto label_ret; // 100517
  }


  if (_tcsstr(OutBuffer, TEXT("$(FinalForceToggleActionName)"))) {
    CondReplaceInString(ForceFinalGlide, OutBuffer,
                        TEXT("$(FinalForceToggleActionName)"),
                        MsgToken(896), // Unforce
                        MsgToken(895), // Force
			Size);
    if (AutoForceFinalGlide) {
      invalid = true;
    }
	if (--items<=0) goto label_ret; // 100517
  }



  if (_tcsstr(OutBuffer, TEXT("$(PCONLY)"))) {
      if(IsEmbedded()) {
        _tcscpy(OutBuffer,_T(""));
        invalid = true;
      } else {
        ReplaceInString(OutBuffer, TEXT("$(PCONLY)"), TEXT(""), Size);
      }
    if (--items<=0) goto label_ret;
  }
  if (_tcsstr(OutBuffer, TEXT("$(NOTPC)"))) {
      if(IsEmbedded()) {
        ReplaceInString(OutBuffer, TEXT("$(NOTPC)"), TEXT(""), Size);
      } else {
        _tcscpy(OutBuffer,_T(""));
        invalid = true;
      }
      if (--items<=0) goto label_ret;
  }

  if (_tcsstr(OutBuffer, TEXT("$(ONLYMAP)"))) {
    if (MapSpaceMode!=MSM_MAP) invalid=true;
    ReplaceInString(OutBuffer, TEXT("$(ONLYMAP)"), TEXT(""), Size);

    if (--items<=0) goto label_ret;
  }

  if (_tcsstr(OutBuffer, TEXT("$(SCREENROTATE)"))) {
      if(CanRotateScreen()) {
        ReplaceInString(OutBuffer, TEXT("$(SCREENROTATE)"), TEXT(""), Size);
      } else {
        _tcscpy(OutBuffer,_T(""));
        invalid = true;
      }
      if (--items<=0) goto label_ret;
  }

  extern unsigned int CustomKeyLabel[];
  // We dont replace macro, we do replace the entire label
  a =_tcsstr(OutBuffer, TEXT("$(MM"));
  if (a != NULL) {
	short i;
	i= *(a+4)-48;
        LKASSERT(i>=0 && i<11);
	// get the label for the custom menu item here
	// Decide if invalid=true or if no label at all, setting Replace to empty string

	unsigned int ckeymode;
	// test mode only
	switch(i) {
	      case 1:
	              ckeymode=CustomMenu1;
	              break;
	      case 2:
	              ckeymode=CustomMenu2;
	              break;
	      case 3:
	              ckeymode=CustomMenu3;
	              break;
	      case 4:
	              ckeymode=CustomMenu4;
	              break;
	      case 5:
	              ckeymode=CustomMenu5;
	              break;
	      case 6:
	              ckeymode=CustomMenu6;
	              break;
	      case 7:
	              ckeymode=CustomMenu7;
	              break;
	      case 8:
	              ckeymode=CustomMenu8;
	              break;
	      case 9:
	              ckeymode=CustomMenu9;
	              break;
	      case 0:
	              ckeymode=CustomMenu10;
	              break;
	      default:
		        ckeymode=0;
		        break;
	}
	if (ckeymode==0 || ckeymode>=ckTOP) {
		invalid=true;			// non selectable

		// _stprintf(OutBuffer,_T("Key\n%d"),i);
		 _tcscpy(OutBuffer,_T(""));	// make it invisible
	} else {
		_tcscpy(OutBuffer,MsgToken( CustomKeyLabel[ckeymode] ));
	}

  } // MM


label_ret:

  return invalid;
}
Example #11
0
static INT_PTR CALLBACK DlgProcHistory(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	HANDLE hContact;

	hContact=(HANDLE)GetWindowLongPtr(hwndDlg,GWLP_USERDATA);
	switch (msg) {
	case WM_INITDIALOG:
		TranslateDialogDefault(hwndDlg);
		SetWindowLongPtr(hwndDlg,GWLP_USERDATA,(LONG_PTR)lParam);
		hContact = (HANDLE)lParam;
		WindowList_Add(hWindowList,hwndDlg,hContact);
		Utils_RestoreWindowPosition(hwndDlg,hContact,"History","");
		{
			TCHAR* contactName, str[200];
			contactName = cli.pfnGetContactDisplayName( hContact, 0 );
			mir_sntprintf(str,SIZEOF(str),TranslateT("History for %s"),contactName);
			SetWindowText(hwndDlg,str);
		}
		Window_SetIcon_IcoLib(hwndDlg, SKINICON_OTHER_HISTORY);
		SendMessage(hwndDlg,DM_HREBUILD,0,0);
		return TRUE;

	case DM_HREBUILD:
		{
			THistoryThread* hInfo = (THistoryThread*)mir_alloc(sizeof(THistoryThread));
			EnableWindow(GetDlgItem(hwndDlg, IDC_LIST), FALSE);
			hInfo->hContact = hContact;
			hInfo->hwnd = hwndDlg;
			forkthread(FillHistoryThread, 0, hInfo);
		}
		return TRUE;

	case WM_DESTROY:
		Window_FreeIcon_IcoLib(hwndDlg);
		Utils_SaveWindowPosition(hwndDlg,hContact,"History","");
		WindowList_Remove(hWindowList,hwndDlg);
		return TRUE;

	case WM_GETMINMAXINFO:
		((MINMAXINFO*)lParam)->ptMinTrackSize.x=300;
		((MINMAXINFO*)lParam)->ptMinTrackSize.y=230;

	case WM_SIZE:
		{
			UTILRESIZEDIALOG urd={0};
			urd.cbSize=sizeof(urd);
			urd.hwndDlg=hwndDlg;
			urd.hInstance=hMirandaInst;
			urd.lpTemplate=MAKEINTRESOURCEA(IDD_HISTORY);
			urd.lParam=(LPARAM)NULL;
			urd.pfnResizer=HistoryDlgResizer;
			CallService(MS_UTILS_RESIZEDIALOG,0,(LPARAM)&urd);
			return TRUE;
		}
	case WM_COMMAND:
		switch ( LOWORD( wParam )) {
		case IDOK:
		case IDCANCEL:
			DestroyWindow(hwndDlg);
			return TRUE;

		case IDC_FIND:
			ShowWindow(CreateDialogParam(hMirandaInst, MAKEINTRESOURCE(IDD_HISTORY_FIND), hwndDlg, DlgProcHistoryFind, (LPARAM)hwndDlg), SW_SHOW);
			return TRUE;

		case IDC_DELETEHISTORY:
			{
				HANDLE hDbevent;
				int index = SendDlgItemMessage(hwndDlg,IDC_LIST,LB_GETCURSEL,0,0);
				if ( index == LB_ERR )
					break;

				if ( MessageBox(hwndDlg,TranslateT("Are you sure you want to delete this history item?"),TranslateT("Delete History"),MB_YESNO|MB_ICONQUESTION)==IDYES) {
					hDbevent = (HANDLE)SendDlgItemMessage(hwndDlg,IDC_LIST,LB_GETITEMDATA,index,0);
					CallService(MS_DB_EVENT_DELETE,(WPARAM)hContact,(LPARAM)hDbevent);
					SendMessage(hwndDlg,DM_HREBUILD,0,0);
				}
				return TRUE;
			}
		case IDC_LIST:
			if ( HIWORD(wParam) == LBN_SELCHANGE ) {
				TCHAR str[8192],*contactName;
				HANDLE hDbEvent;
				DBEVENTINFO dbei;
				int sel;
				sel=SendDlgItemMessage(hwndDlg,IDC_LIST,LB_GETCURSEL,0,0);
				if(sel==LB_ERR) { EnableWindow(GetDlgItem(hwndDlg,IDC_DELETEHISTORY),FALSE); break; }
				EnableWindow(GetDlgItem(hwndDlg,IDC_DELETEHISTORY),TRUE);
				contactName = cli.pfnGetContactDisplayName( hContact, 0 );
				hDbEvent=(HANDLE)SendDlgItemMessage(hwndDlg,IDC_LIST,LB_GETITEMDATA,sel,0);
				ZeroMemory(&dbei,sizeof(dbei));
				dbei.cbSize=sizeof(dbei);
				dbei.cbBlob=CallService(MS_DB_EVENT_GETBLOBSIZE,(WPARAM)hDbEvent,0);
				if ((int)dbei.cbBlob != -1)
				{
					dbei.pBlob=(PBYTE)mir_alloc(dbei.cbBlob);
					if (CallService(MS_DB_EVENT_GET,(WPARAM)hDbEvent,(LPARAM)&dbei) == 0)
					{
						GetObjectDescription(&dbei,str,SIZEOF(str));
						if ( str[0] )
							SetDlgItemText(hwndDlg, IDC_EDIT, str);
					}
					mir_free(dbei.pBlob);
				}
			}
			return TRUE;
		}
		break;
	case DM_FINDNEXT:
		{
			TCHAR str[1024];
			HANDLE hDbEvent,hDbEventStart;
			DBEVENTINFO dbei;
			int newBlobSize,oldBlobSize;

			int index = SendDlgItemMessage(hwndDlg,IDC_LIST,LB_GETCURSEL,0,0);
			if ( index == LB_ERR )
				break;

			hDbEventStart=(HANDLE)SendDlgItemMessage(hwndDlg,IDC_LIST,LB_GETITEMDATA,index,0);
			ZeroMemory(&dbei,sizeof(dbei));
			dbei.cbSize=sizeof(dbei);
			dbei.pBlob=NULL;
			oldBlobSize=0;
			for(;;) {
				hDbEvent = (HANDLE)SendDlgItemMessage(hwndDlg,IDC_LIST,LB_GETITEMDATA,++index,0);
				if(hDbEvent == ( HANDLE )LB_ERR) {
					index = -1;
					continue;
				}
				if(hDbEvent==hDbEventStart) break;
				newBlobSize=CallService(MS_DB_EVENT_GETBLOBSIZE,(WPARAM)hDbEvent,0);
				if(newBlobSize>oldBlobSize) {
					dbei.pBlob=(PBYTE)mir_realloc(dbei.pBlob,newBlobSize);
					oldBlobSize=newBlobSize;
				}
				dbei.cbBlob=oldBlobSize;
				CallService(MS_DB_EVENT_GET,(WPARAM)hDbEvent,(LPARAM)&dbei);
				GetObjectDescription(&dbei,str,SIZEOF(str));
				if(str[0]) {
					CharUpperBuff(str,lstrlen(str));
					if( _tcsstr(str,(const TCHAR*)lParam)!=NULL) {
						SendDlgItemMessage(hwndDlg,IDC_LIST,LB_SETCURSEL,index,0);
						SendMessage(hwndDlg,WM_COMMAND,MAKEWPARAM(IDC_LIST,LBN_SELCHANGE),0);
						break;
			}	}	}
			
			mir_free(dbei.pBlob);
			break;
		}
	}
	return FALSE;
}
unsigned int 
USBDeviceFactory_DiscoverDevices(
  LPSKYETEK_DEVICE** lpDevices
  )
{	
	GUID hidGuid;
	HDEVINFO deviceInfo;
	BOOL isSuccess = FALSE;
	unsigned long bytes = 0;   
	SP_INTERFACE_DEVICE_DATA deviceData; 
	PSP_INTERFACE_DEVICE_DETAIL_DATA deviceInterfaceData = 0;   
	unsigned int ix, deviceCount = 0;
	size_t size = 0; 
	SKYETEK_STATUS status;

	if((lpDevices == NULL) || (*lpDevices != NULL))
		return 0;

	g_usbDevCount = 0;
	HidD_GetHidGuid (&hidGuid); 
	deviceInfo = SetupDiGetClassDevs ( &hidGuid, 0, 0, (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE  )); 
	if ( deviceInfo == INVALID_HANDLE_VALUE ) 
		return 0; 

	*lpDevices = (LPSKYETEK_DEVICE*)malloc(20 * sizeof(LPSKYETEK_DEVICE));
	memset(*lpDevices,0,(20*sizeof(LPSKYETEK_DEVICE)));
	size = sizeof(SP_INTERFACE_DEVICE_DETAIL_DATA); 
	for ( ix = 0; ix < 20; ix++ ) 
	{       
		memset( &deviceData, 0, sizeof(SP_INTERFACE_DEVICE_DATA) );   
		deviceData.cbSize = sizeof (SP_INTERFACE_DEVICE_DATA); 
		isSuccess = SetupDiEnumDeviceInterfaces ( deviceInfo, 0, &hidGuid, ix, &deviceData);     
    if ( !isSuccess ) 
		{ 
      if ( ERROR_NO_MORE_ITEMS == GetLastError() ) 
        break; 
      else 
        continue; 
    } 
    SetupDiGetInterfaceDeviceDetail( deviceInfo, &deviceData, 0, 0, &bytes, 0);       
    deviceInterfaceData = (PSP_INTERFACE_DEVICE_DETAIL_DATA)malloc(bytes * sizeof(BYTE));
    if ( !deviceInterfaceData ) { 
      SetupDiDestroyDeviceInfoList( deviceInfo ); 
      return deviceCount; 
    } 
    memset( deviceInterfaceData, 0, bytes ); 
    deviceInterfaceData->cbSize  = size;
    isSuccess = SetupDiGetInterfaceDeviceDetail( deviceInfo, &deviceData, deviceInterfaceData, bytes, &bytes, 0); 
    if ( !isSuccess ) { 
      free(deviceInterfaceData);
      SetupDiDestroyDeviceInfoList( deviceInfo ); 
      return deviceCount; 
    }

		if((_tcsstr(deviceInterfaceData->DevicePath, _T("vid_afef")) != NULL)
			&& (_tcsstr(deviceInterfaceData->DevicePath, _T("pid_0f01")) != NULL))
		{
			/*printf("DevicePath = %s\r\n", deviceInterfaceData->DevicePath);*/
			status = USBDeviceFactory_CreateDevice(deviceInterfaceData->DevicePath, &((*lpDevices)[deviceCount]));
			if( status != SKYETEK_SUCCESS )
			{
				free(deviceInterfaceData);
				continue;
			}
			deviceCount++;
		}

		free(deviceInterfaceData);
  }

	return deviceCount;
}
Example #13
0
void CRemote::Output(LPCTSTR pszName)
{
	if ( _tcsstr( pszName, L".." ) || _tcschr( pszName, L'/' ) ) return;

	CString strValue = Settings.General.Path + L"\\Remote\\" + pszName + L".html";

	CFile hFile;
	if ( ! hFile.Open( strValue, CFile::modeRead ) ) return;

	int nBytes = (int)hFile.GetLength();
	CAutoVectorPtr< BYTE > pBytes( new BYTE[ nBytes ] );
	hFile.Read( pBytes, nBytes );
	hFile.Close();
	LPCSTR pBody = (LPCSTR)(BYTE*)pBytes;
	if ( nBytes > 3 && pBytes[0] == 0xEF && pBytes[1] == 0xBB && pBytes[2] == 0xBF )
	{
		// Skip BOM
		pBody  += 3;
		nBytes -= 3;
	}

	CString strBody = UTF8Decode( pBody, nBytes );

	CList<BOOL> pDisplayStack;

	for ( BOOL bDisplay = TRUE; ; )
	{
		int nStart = strBody.Find( L"<%" );

		if ( nStart < 0 )
		{
			if ( bDisplay )
				m_sResponse += strBody;
			break;
		}
		else if ( nStart >= 0 )
		{
			if ( bDisplay && nStart > 0 )
				m_sResponse += strBody.Left( nStart );
			strBody = strBody.Mid( nStart + 2 );
		}

		int nEnd = strBody.Find( L"%>" );
		if ( nEnd < 0 ) break;

		CString strKey = strBody.Left( nEnd );
		strBody = strBody.Mid( nEnd + 2 );

		strKey.Trim();
		ToLower( strKey );

		if ( strKey.IsEmpty() )
		{
			// Nothing
		}
		else if ( strKey.GetAt( 0 ) == L'=' && bDisplay )
		{
			strKey = strKey.Mid( 1 );
			strKey.Trim();
			if ( m_pKeys.Lookup( strKey, strValue ) )
				m_sResponse += strValue;
		}
		else if ( strKey.GetAt( 0 ) == L'?' )
		{
			strKey = strKey.Mid( 1 );
			strKey.Trim();

			if ( strKey.IsEmpty() )
			{
				if ( ! pDisplayStack.IsEmpty() )
					bDisplay = pDisplayStack.RemoveTail();
			}
			else
			{
				if ( strKey.GetAt( 0 ) == L'!' )
				{
					strKey = strKey.Mid( 1 );
					strKey.Trim();
					if ( ! m_pKeys.Lookup( strKey, strValue ) ) strValue.Empty();
					pDisplayStack.AddTail( bDisplay );
					bDisplay = bDisplay && strValue.IsEmpty();
				}
				else
				{
					if ( ! m_pKeys.Lookup( strKey, strValue ) ) strValue.Empty();
					pDisplayStack.AddTail( bDisplay );
					bDisplay = bDisplay && ! strValue.IsEmpty();
				}
			}
		}
	}
}
Example #14
0
INT_PTR CALLBACK SettingsProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {
  switch(msg) {
    case WM_INITDIALOG:
    {
      int i = 0;

      for(i = (int)COMPRESSOR_SCRIPT; i <= (int)COMPRESSOR_BEST; i++) {
        SendDlgItemMessage(hwndDlg, IDC_COMPRESSOR, CB_ADDSTRING, 0, (LPARAM)compressor_display_names[i]);
      }
      SendDlgItemMessage(hwndDlg, IDC_COMPRESSOR, CB_SETCURSEL, (WPARAM)g_sdata.default_compressor, (LPARAM)0);

      SetSymbols(hwndDlg, g_sdata.symbols);
      SetFocus(GetDlgItem(hwndDlg, IDC_SYMBOL));
      break;
    }
    case WM_MAKENSIS_LOADSYMBOLSET:
    {
      TCHAR *name = (TCHAR *)wParam;
      TCHAR **symbols = LoadSymbolSet(name);
      HGLOBAL hMem;

      SetSymbols(hwndDlg, symbols);
      if(symbols) {
        hMem = GlobalHandle(symbols);
        GlobalUnlock(hMem);
        GlobalFree(hMem);
      }
      break;
    }
    case WM_MAKENSIS_SAVESYMBOLSET:
    {
      TCHAR *name = (TCHAR *)wParam;
      TCHAR **symbols = GetSymbols(hwndDlg);
      HGLOBAL hMem;

      if(symbols) {
        SaveSymbolSet(name, symbols);
        hMem = GlobalHandle(symbols);
        GlobalUnlock(hMem);
        GlobalFree(hMem);
      }
      break;
    }
    case WM_COMMAND:
    {
      switch (LOWORD(wParam)) {
        case IDOK:
        {
          ResetObjects();
          ResetSymbols();
          g_sdata.symbols = GetSymbols(hwndDlg);

          int n = SendDlgItemMessage(hwndDlg, IDC_COMPRESSOR, CB_GETCURSEL, (WPARAM)0, (LPARAM)0);
          if (n >= (int)COMPRESSOR_SCRIPT && n <= (int)COMPRESSOR_BEST) {
            g_sdata.default_compressor = (NCOMPRESSOR)n;
          }
          else {
            g_sdata.default_compressor = COMPRESSOR_SCRIPT;
          }
          EndDialog(hwndDlg, TRUE);
          SetCompressor(g_sdata.default_compressor);
        }
        break;
        case IDCANCEL:
          EndDialog(hwndDlg, TRUE);
          break;
        case IDC_RIGHT:
        {
          int n = SendDlgItemMessage(hwndDlg, IDC_SYMBOL, WM_GETTEXTLENGTH, 0, 0);
          if(n > 0) {
            TCHAR *buf = (TCHAR*) MemAllocZI((n+1)*sizeof(TCHAR));
            SendDlgItemMessage(hwndDlg, IDC_SYMBOL, WM_GETTEXT, n+1, (LPARAM)buf);
            if(_tcsstr(buf,_T(" ")) || _tcsstr(buf,_T("\t"))) {
              MessageBox(hwndDlg,SYMBOLSERROR,ERRBOXTITLE,MB_OK|MB_ICONSTOP);
              MemFree(buf);
              break;
            }

            n = SendDlgItemMessage(hwndDlg, IDC_VALUE, WM_GETTEXTLENGTH, 0, 0);
            if(n > 0) {
              TCHAR *buf2 = (TCHAR*) MemAllocZI((n+1)*sizeof(TCHAR));
              SendDlgItemMessage(hwndDlg, IDC_VALUE, WM_GETTEXT, n+1, (LPARAM)buf2);
              TCHAR *buf3 = (TCHAR*) MemAllocZI((lstrlen(buf)+lstrlen(buf2)+2)*sizeof(TCHAR));
              wsprintf(buf3,_T("%s=%s"),buf,buf2);
              MemFree(buf);
              buf = buf3;
              MemFree(buf2);
            }
            int idx = SendDlgItemMessage(hwndDlg, IDC_SYMBOLS, LB_ADDSTRING, 0, (LPARAM)buf);
            if (idx >= 0)
            {
              SendDlgItemMessage(hwndDlg, IDC_SYMBOLS, LB_SETSEL, FALSE, -1);
              SendDlgItemMessage(hwndDlg, IDC_SYMBOLS, LB_SETSEL, TRUE, idx);
            }
            EnableSymbolEditButtons(hwndDlg);
            SendDlgItemMessage(hwndDlg, IDC_SYMBOL, WM_SETTEXT, 0, 0);
            SendDlgItemMessage(hwndDlg, IDC_VALUE, WM_SETTEXT, 0, 0);
            MemFree(buf);
            EnableSymbolSetButtons(hwndDlg);
          }
        }
        break;
        case IDC_LEFT:
        {
          if (SendDlgItemMessage(hwndDlg, IDC_SYMBOLS, LB_GETSELCOUNT, 0, 0) != 1)
            break;

          int index;
          int num = SendDlgItemMessage(hwndDlg, IDC_SYMBOLS, LB_GETSELITEMS, 1, (LPARAM) &index);
          if(num == 1) {
            int n = SendDlgItemMessage(hwndDlg, IDC_SYMBOLS, LB_GETTEXTLEN, (WPARAM)index, 0);
            if(n > 0) {
              TCHAR *buf = (TCHAR*) MemAllocZI((n+1)*sizeof(TCHAR));
              SendDlgItemMessage(hwndDlg, IDC_SYMBOLS, LB_GETTEXT, (WPARAM)index, (LPARAM)buf);
              TCHAR *p = _tcsstr(buf,_T("="));
              if(p) {
                SendDlgItemMessage(hwndDlg, IDC_VALUE, WM_SETTEXT, 0, (LPARAM)(p+1));
                *p=0;
              }
              SendDlgItemMessage(hwndDlg, IDC_SYMBOL, WM_SETTEXT, 0, (LPARAM)buf);
              MemFree(buf);
              SendDlgItemMessage(hwndDlg, IDC_SYMBOLS, LB_DELETESTRING, (WPARAM)index, 0);
              EnableWindow(GetDlgItem(hwndDlg, IDC_LEFT), FALSE);
              EnableWindow(GetDlgItem(hwndDlg, IDC_DEL), FALSE);
              EnableSymbolSetButtons(hwndDlg);
            }
          }
        }
        break;
        case IDC_CLEAR:
        {
          SendDlgItemMessage(hwndDlg, IDC_SYMBOLS, LB_RESETCONTENT , 0, 0);
          EnableSymbolSetButtons(hwndDlg);
        }
        break;
        case IDC_LOAD:
        case IDC_SAVE:
        {
          g_symbol_set_mode = IDC_LOAD == LOWORD(wParam) ? 1 : 2;
          DialogBox(g_sdata.hInstance,MAKEINTRESOURCE(DLG_SYMBOLSET),hwndDlg,(DLGPROC)SymbolSetProc);
        }
        break;
        case IDC_DEL:
        {
          int n = SendDlgItemMessage(hwndDlg, IDC_SYMBOLS, LB_GETSELCOUNT, 0, 0);
          int *items = (int*) MemAllocZI(n*sizeof(int));
          if (items) {
            SendDlgItemMessage(hwndDlg, IDC_SYMBOLS, LB_GETSELITEMS, (WPARAM)n, (LPARAM)items);
            for(int i=n-1;i>=0;i--)
              SendDlgItemMessage(hwndDlg, IDC_SYMBOLS, LB_DELETESTRING, (WPARAM)items[i], 0);
            MemFree(items);
          }
          EnableSymbolEditButtons(hwndDlg);
          EnableSymbolSetButtons(hwndDlg);
        }
        break;
        case IDC_SYMBOL:
          if(HIWORD(wParam) == EN_CHANGE)
          {
            int n = SendDlgItemMessage(hwndDlg, IDC_SYMBOL, WM_GETTEXTLENGTH, 0, 0);
            EnableWindow(GetDlgItem(hwndDlg, IDC_RIGHT), n > 0);
          }
          break;
        case IDC_SYMBOLS:
          if (HIWORD(wParam) == LBN_SELCHANGE)
          {
            EnableSymbolEditButtons(hwndDlg);
          }
          else if (HIWORD(wParam) == LBN_DBLCLK)
          {
            SendDlgItemMessage(hwndDlg, IDC_LEFT, BM_CLICK, 0, 0);
          }
          break;
        }
      break;
    }
  }
  return FALSE;
}
Example #15
0
FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
{
	FT_Error err = FT_Err_Cannot_Open_Resource;
	HKEY hKey;
	LONG ret;
	TCHAR vbuffer[MAX_PATH], dbuffer[256];
	TCHAR *pathbuf;
	const char *font_path;
	uint index;
	size_t path_len;

	/* On windows NT (2000, NT3.5, XP, etc.) the fonts are stored in the
	 * "Windows NT" key, on Windows 9x in the Windows key. To save us having
	 * to retrieve the windows version, we'll just query both */
	ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(FONT_DIR_NT), 0, KEY_READ, &hKey);
	if (ret != ERROR_SUCCESS) ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(FONT_DIR_9X), 0, KEY_READ, &hKey);

	if (ret != ERROR_SUCCESS) {
		DEBUG(freetype, 0, "Cannot open registry key HKLM\\SOFTWARE\\Microsoft\\Windows (NT)\\CurrentVersion\\Fonts");
		return err;
	}

	/* Convert font name to file system encoding. */
	TCHAR *font_namep = _tcsdup(OTTD2FS(font_name));

	for (index = 0;; index++) {
		TCHAR *s;
		DWORD vbuflen = lengthof(vbuffer);
		DWORD dbuflen = lengthof(dbuffer);

		ret = RegEnumValue(hKey, index, vbuffer, &vbuflen, NULL, NULL, (byte*)dbuffer, &dbuflen);
		if (ret != ERROR_SUCCESS) goto registry_no_font_found;

		/* The font names in the registry are of the following 3 forms:
		 * - ADMUI3.fon
		 * - Book Antiqua Bold (TrueType)
		 * - Batang & BatangChe & Gungsuh & GungsuhChe (TrueType)
		 * We will strip the font-type '()' if any and work with the font name
		 * itself, which must match exactly; if...
		 * TTC files, font files which contain more than one font are separated
		 * by '&'. Our best bet will be to do substr match for the fontname
		 * and then let FreeType figure out which index to load */
		s = _tcschr(vbuffer, _T('('));
		if (s != NULL) s[-1] = '\0';

		if (_tcschr(vbuffer, _T('&')) == NULL) {
			if (_tcsicmp(vbuffer, font_namep) == 0) break;
		} else {
			if (_tcsstr(vbuffer, font_namep) != NULL) break;
		}
	}

	if (!SUCCEEDED(OTTDSHGetFolderPath(NULL, CSIDL_FONTS, NULL, SHGFP_TYPE_CURRENT, vbuffer))) {
		DEBUG(freetype, 0, "SHGetFolderPath cannot return fonts directory");
		goto folder_error;
	}

	/* Some fonts are contained in .ttc files, TrueType Collection fonts. These
	 * contain multiple fonts inside this single file. GetFontData however
	 * returns the whole file, so we need to check each font inside to get the
	 * proper font. */
	path_len = _tcslen(vbuffer) + _tcslen(dbuffer) + 2; // '\' and terminating nul.
	pathbuf = AllocaM(TCHAR, path_len);
	_sntprintf(pathbuf, path_len, _T("%s\\%s"), vbuffer, dbuffer);

	/* Convert the path into something that FreeType understands. */
	font_path = GetShortPath(pathbuf);

	index = 0;
	do {
		err = FT_New_Face(_library, font_path, index, face);
		if (err != FT_Err_Ok) break;

		if (strncasecmp(font_name, (*face)->family_name, strlen((*face)->family_name)) == 0) break;
		/* Try english name if font name failed */
		if (strncasecmp(font_name + strlen(font_name) + 1, (*face)->family_name, strlen((*face)->family_name)) == 0) break;
		err = FT_Err_Cannot_Open_Resource;

	} while ((FT_Long)++index != (*face)->num_faces);


folder_error:
registry_no_font_found:
	free(font_namep);
	RegCloseKey(hKey);
	return err;
}
Example #16
0
 /**
  * Does this item have a dynamic label?  It may need updates more
  * often, because the variables that the label depends on may change
  * at any time.
  */
 gcc_pure
 bool IsDynamic() const {
     return label != NULL && _tcsstr(label, _T("$(")) != NULL;
 }
Example #17
0
// Sends a key string
bool CSendKeys::SendKeys(LPCTSTR KeysString, bool Wait)
{
    WORD MKey, NumTimes;
    TCHAR KeyString[300] = {0};
    bool retval  = false;
    int  keyIdx;

    LPTSTR pKey = (LPTSTR) KeysString;
    TCHAR  ch;

    m_bWait = Wait;

    m_bWinDown = m_bShiftDown = m_bControlDown = m_bAltDown = m_bUsingParens = false;

    while (ch = *pKey)
    {
        switch (ch)
        {
        // begin modifier group
        case _TXCHAR('('):
            m_bUsingParens = true;
            break;

        // end modifier group
        case _TXCHAR(')'):
            m_bUsingParens = false;
            PopUpShiftKeys(); // pop all shift keys when we finish a modifier group close
            break;

        // ALT key
        case _TXCHAR('%'):
            m_bAltDown = true;
            SendKeyDown(VK_MENU, 1, false);
            break;

        // SHIFT key
        case _TXCHAR('+'):
            m_bShiftDown = true;
            SendKeyDown(VK_SHIFT, 1, false);
            break;

        // CTRL key
        case _TXCHAR('^'):
            m_bControlDown = true;
            SendKeyDown(VK_CONTROL, 1, false);
            break;

        // WINKEY (Left-WinKey)
        case '@':
            m_bWinDown = true;
            SendKeyDown(VK_LWIN, 1, false);
            break;

        // enter
        case _TXCHAR('~'):
            SendKeyDown(VK_RETURN, 1, true);
            PopUpShiftKeys();
            break;

        // begin special keys
        case _TXCHAR('{'):
        {
            LPTSTR p = pKey+1; // skip past the beginning '{'
            size_t t;

            // find end of close
            while (*p && *p != _TXCHAR('}'))
                p++;

            t = p - pKey;
            // special key definition too big?
            if (t > sizeof(KeyString))
                return false;

            // Take this KeyString into local buffer
            _tcsncpy(KeyString, pKey+1, t);

            KeyString[t-1] = _TXCHAR('\0');
            keyIdx = -1;

            pKey += t; // skip to next keystring

            // Invalidate key
            MKey = INVALIDKEY;

            // sending arbitrary vkeys?
            if (_tcsnicmp(KeyString, _T("VKEY"), 4) == 0)
            {
                p = KeyString + 4;
                MKey = _ttoi(p);
            }
            else if (_tcsnicmp(KeyString, _T("BEEP"), 4) == 0)
            {
                p = KeyString + 4 + 1;
                LPTSTR p1 = p;
                DWORD frequency, delay;

                if ((p1 = _tcsstr(p, _T(" "))) != NULL)
                {
                    *p1++ = _TXCHAR('\0');
                    frequency = _ttoi(p);
                    delay = _ttoi(p1);
                    ::Beep(frequency, delay);
                }
            }
            // Should activate a window?
            else if (_tcsnicmp(KeyString, _T("APPACTIVATE"), 11) == 0)
            {
                p = KeyString + 11 + 1;
                AppActivate(p);
            }
            // want to send/set delay?
            else if (_tcsnicmp(KeyString, _T("DELAY"), 5) == 0)
            {
                // Advance to parameters
                p = KeyString + 5;
                // set "sleep factor"
                if (*p == _TXCHAR('='))
                    m_nDelayAlways = _ttoi(p + 1); // Take number after the '=' character
                else
                    // set "sleep now"
                    m_nDelayNow = _ttoi(p);
            }
            // not command special keys, then process as keystring to VKey
            else
            {
                MKey = StringToVKey(KeyString, keyIdx);
                // Key found in table
                if (keyIdx != -1)
                {
                    NumTimes = 1;

                    // Does the key string have also count specifier?
                    t = _tcslen(KeyNames[keyIdx].keyName);
                    if (_tcslen(KeyString) > t)
                    {
                        p = KeyString + t;
                        // Take the specified number of times
                        NumTimes = _ttoi(p);
                    }

                    if (KeyNames[keyIdx].normalkey)
                        MKey = ::VkKeyScan(KeyNames[keyIdx].VKey);
                }
            }

            // A valid key to send?
            if (MKey != INVALIDKEY)
            {
                SendKey(MKey, NumTimes, true);
                PopUpShiftKeys();
            }
        }
        break;

        // a normal key was pressed
        default:
            // Get the VKey from the key
            MKey = ::VkKeyScan(ch);
            SendKey(MKey, 1, true);
            PopUpShiftKeys();
        }
        pKey++;
    }

    m_bUsingParens = false;
    PopUpShiftKeys();
    return true;
}
Example #18
0
FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
{
	FT_Error err = FT_Err_Cannot_Open_Resource;
	HKEY hKey;
	LONG ret;
	TCHAR vbuffer[MAX_PATH], dbuffer[256];
	TCHAR *font_namep;
	char *font_path;
	uint index;

	/* On windows NT (2000, NT3.5, XP, etc.) the fonts are stored in the
	 * "Windows NT" key, on Windows 9x in the Windows key. To save us having
	 * to retrieve the windows version, we'll just query both */
	ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(FONT_DIR_NT), 0, KEY_READ, &hKey);
	if (ret != ERROR_SUCCESS) ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(FONT_DIR_9X), 0, KEY_READ, &hKey);

	if (ret != ERROR_SUCCESS) {
		DEBUG(freetype, 0, "Cannot open registry key HKLM\\SOFTWARE\\Microsoft\\Windows (NT)\\CurrentVersion\\Fonts");
		return err;
	}

	/* For Unicode we need some conversion between widechar and
	 * normal char to match the data returned by RegEnumValue,
	 * otherwise just use parameter */
#if defined(UNICODE)
	font_namep = MallocT<TCHAR>(MAX_PATH);
	MB_TO_WIDE_BUFFER(font_name, font_namep, MAX_PATH * sizeof(TCHAR));
#else
	font_namep = const_cast<char *>(font_name); // only cast because in unicode pointer is not const
#endif

	for (index = 0;; index++) {
		TCHAR *s;
		DWORD vbuflen = lengthof(vbuffer);
		DWORD dbuflen = lengthof(dbuffer);

		ret = RegEnumValue(hKey, index, vbuffer, &vbuflen, NULL, NULL, (byte*)dbuffer, &dbuflen);
		if (ret != ERROR_SUCCESS) goto registry_no_font_found;

		/* The font names in the registry are of the following 3 forms:
		 * - ADMUI3.fon
		 * - Book Antiqua Bold (TrueType)
		 * - Batang & BatangChe & Gungsuh & GungsuhChe (TrueType)
		 * We will strip the font-type '()' if any and work with the font name
		 * itself, which must match exactly; if...
		 * TTC files, font files which contain more than one font are separated
		 * by '&'. Our best bet will be to do substr match for the fontname
		 * and then let FreeType figure out which index to load */
		s = _tcschr(vbuffer, _T('('));
		if (s != NULL) s[-1] = '\0';

		if (_tcschr(vbuffer, _T('&')) == NULL) {
			if (_tcsicmp(vbuffer, font_namep) == 0) break;
		} else {
			if (_tcsstr(vbuffer, font_namep) != NULL) break;
		}
	}

	if (!SUCCEEDED(OTTDSHGetFolderPath(NULL, CSIDL_FONTS, NULL, SHGFP_TYPE_CURRENT, vbuffer))) {
		DEBUG(freetype, 0, "SHGetFolderPath cannot return fonts directory");
		goto folder_error;
	}

	/* Some fonts are contained in .ttc files, TrueType Collection fonts. These
	 * contain multiple fonts inside this single file. GetFontData however
	 * returns the whole file, so we need to check each font inside to get the
	 * proper font.
	 * Also note that FreeType does not support UNICODE filenames! */
#if defined(UNICODE)
	/* We need a cast here back from wide because FreeType doesn't support
	 * widechar filenames. Just use the buffer we allocated before for the
	 * font_name search */
	font_path = (char*)font_namep;
	WIDE_TO_MB_BUFFER(vbuffer, font_path, MAX_PATH * sizeof(TCHAR));
#else
	font_path = vbuffer;
#endif

	ttd_strlcat(font_path, "\\", MAX_PATH * sizeof(TCHAR));
	ttd_strlcat(font_path, WIDE_TO_MB(dbuffer), MAX_PATH * sizeof(TCHAR));

	/* Convert the path into something that FreeType understands */
	font_path = GetShortPath(font_path);

	index = 0;
	do {
		err = FT_New_Face(_library, font_path, index, face);
		if (err != FT_Err_Ok) break;

		if (strncasecmp(font_name, (*face)->family_name, strlen((*face)->family_name)) == 0) break;
		/* Try english name if font name failed */
		if (strncasecmp(font_name + strlen(font_name) + 1, (*face)->family_name, strlen((*face)->family_name)) == 0) break;
		err = FT_Err_Cannot_Open_Resource;

	} while ((FT_Long)++index != (*face)->num_faces);


folder_error:
registry_no_font_found:
#if defined(UNICODE)
	free(font_namep);
#endif
	RegCloseKey(hKey);
	return err;
}
Example #19
0
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nShowCmd)
{
    CONTEXT("WinMain()");

    BOOL any_desktop_running = IsAnyDesktopRunning();

    BOOL startup_desktop;

    // strip extended options from the front of the command line
    String ext_options;

    while(*lpCmdLine == '-') {
        while(*lpCmdLine && !_istspace((unsigned)*lpCmdLine))
            ext_options += *lpCmdLine++;

        while(_istspace((unsigned)*lpCmdLine))
            ++lpCmdLine;
    }

     // command line option "-install" to replace previous shell application with ROS Explorer
    if (_tcsstr(ext_options,TEXT("-install"))) {
        // install ROS Explorer into the registry
        TCHAR path[MAX_PATH];

        int l = GetModuleFileName(0, path, COUNTOF(path));
        if (l) {
            HKEY hkey;

            if (!RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"), &hkey)) {

                ///@todo save previous shell application in config file

                RegSetValueEx(hkey, TEXT("Shell"), 0, REG_SZ, (LPBYTE)path, l*sizeof(TCHAR));
                RegCloseKey(hkey);
            }

            if (!RegOpenKey(HKEY_CURRENT_USER, TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"), &hkey)) {

                ///@todo save previous shell application in config file

                RegSetValueEx(hkey, TEXT("Shell"), 0, REG_SZ, (LPBYTE)TEXT(""), l*sizeof(TCHAR));
                RegCloseKey(hkey);
            }
        }

        HWND shellWindow = GetShellWindow();

        if (shellWindow) {
            DWORD pid;

            // terminate shell process for NT like systems
            GetWindowThreadProcessId(shellWindow, &pid);
            HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);

             // On Win 9x it's sufficient to destroy the shell window.
            DestroyWindow(shellWindow);

            if (TerminateProcess(hProcess, 0))
                WaitForSingleObject(hProcess, INFINITE);

            CloseHandle(hProcess);
        }

        startup_desktop = TRUE;
    } else {
         // create desktop window and task bar only, if there is no other shell and we are
         // the first explorer instance
         // MS Explorer looks additionally into the registry entry HKCU\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\shell,
         // to decide wether it is currently configured as shell application.
        startup_desktop = !any_desktop_running;
    }


    bool autostart = !any_desktop_running;

    // disable autostart if the SHIFT key is pressed
    if (GetAsyncKeyState(VK_SHIFT) < 0)
        autostart = false;

#ifdef _DEBUG    //MF: disabled for debugging
    autostart = false;
#endif

    // If there is given the command line option "-desktop", create desktop window anyways
    if (_tcsstr(ext_options,TEXT("-desktop")))
        startup_desktop = TRUE;
#ifndef ROSSHELL
    else if (_tcsstr(ext_options,TEXT("-nodesktop")))
        startup_desktop = FALSE;

    // Don't display cabinet window in desktop mode
    if (startup_desktop && !_tcsstr(ext_options,TEXT("-explorer")))
        nShowCmd = SW_HIDE;
#endif

    if (_tcsstr(ext_options,TEXT("-noautostart")))
        autostart = false;
    else if (_tcsstr(ext_options,TEXT("-autostart")))
        autostart = true;

#ifndef __WINE__
    if (_tcsstr(ext_options,TEXT("-console"))) {
        AllocConsole();

        _dup2(_open_osfhandle((long)GetStdHandle(STD_INPUT_HANDLE), _O_RDONLY), 0);
        _dup2(_open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), 0), 1);
        _dup2(_open_osfhandle((long)GetStdHandle(STD_ERROR_HANDLE), 0), 2);

        g_Globals._log = _fdopen(1, "w");
        setvbuf(g_Globals._log, 0, _IONBF, 0);

        LOG(TEXT("starting explorer debug log\n"));
    }
#endif


    if (startup_desktop) {
         // hide the XP login screen (Credit to Nicolas Escuder)
         // another undocumented event: "Global\\msgina: ReturnToWelcome"
        if (!SetShellReadyEvent(TEXT("msgina: ShellReadyEvent")))
            SetShellReadyEvent(TEXT("Global\\msgina: ShellReadyEvent"));
    }
#ifdef ROSSHELL
    else
        return 0;    // no shell to launch, so exit immediatelly
#endif


    if (!any_desktop_running) {
        // launch the shell DDE server
        if (g_SHDOCVW_ShellDDEInit)
            (*g_SHDOCVW_ShellDDEInit)(TRUE);
    }


    bool use_gdb_stub = false;    // !IsDebuggerPresent();

    if (_tcsstr(ext_options,TEXT("-debug")))
        use_gdb_stub = true;

    if (_tcsstr(ext_options,TEXT("-break"))) {
        LOG(TEXT("debugger breakpoint"));
        __debugbreak();
    }

#ifdef _M_IX86
    // activate GDB remote debugging stub if no other debugger is running
    if (use_gdb_stub) {
        LOG(TEXT("waiting for debugger connection...\n"));

        initialize_gdb_stub();
    }
#endif

    g_Globals.init(hInstance);

    // initialize COM and OLE before creating the desktop window
    OleInit usingCOM;

    // init common controls library
    CommonControlInit usingCmnCtrl;

    g_Globals.read_persistent();

    if (startup_desktop) {
        WaitCursor wait;

        g_Globals._desktops.init();

        g_Globals._hwndDesktop = DesktopWindow::Create();
#ifdef _USE_HDESK
        g_Globals._desktops.get_current_Desktop()->_hwndDesktop = g_Globals._hwndDesktop;
#endif
    }

    if (_tcsstr(ext_options,TEXT("-?"))) {
        MessageBoxA(g_Globals._hwndDesktop,
            "/e        open cabinet window in explorer mode\r\n"
            "/root        open cabinet window in rooted mode\r\n"
            "/mdi        open cabinet window in MDI mode\r\n"
            "/sdi        open cabinet window in SDI mode\r\n"
            "\r\n"
            "-?        display command line options\r\n"
            "\r\n"
            "-desktop        start in desktop mode regardless of an already running shell\r\n"
            "-nodesktop    disable desktop mode\r\n"
            "-explorer        display cabinet window regardless of enabled desktop mode\r\n"
            "\r\n"
            "-install        replace previous shell application with ROS Explorer\r\n"
            "\r\n"
            "-noautostart    disable autostarts\r\n"
            "-autostart    enable autostarts regardless of debug build\r\n"
            "\r\n"
            "-console        open debug console\r\n"
            "\r\n"
            "-debug        activate GDB remote debugging stub\r\n"
            "-break        activate debugger breakpoint\r\n",
            "ROS Explorer - command line options", MB_OK);
    }

    Thread* pSSOThread = NULL;

    if (startup_desktop) {
        // launch SSO thread to allow message processing independent from the explorer main thread
        pSSOThread = new SSOThread;
        pSSOThread->Start();
    }

    /**TODO launching autostart programs can be moved into a background thread. */
    if (autostart) {
        const char* argv[] = {"", "s"};    // call startup routine in SESSION_START mode
        startup(2, argv);
    }

#ifndef ROSSHELL
    if (g_Globals._hwndDesktop)
        g_Globals._desktop_mode = true;
#endif


    int ret = explorer_main(hInstance, lpCmdLine, nShowCmd);


    // write configuration file
    g_Globals.write_persistent();

    if (pSSOThread) {
        pSSOThread->Stop();
        delete pSSOThread;
    }

    if (!any_desktop_running) {
        // shutdown the shell DDE server
        if (g_SHDOCVW_ShellDDEInit)
            (*g_SHDOCVW_ShellDDEInit)(FALSE);
    }

    return ret;
}
Example #20
0
// Get function prototype and parameter info from ip address and stack address
static BOOL GetFunctionInfoFromAddresses( ULONG fnAddress, ULONG stackAddress, LPTSTR lpszSymbol )
{
	BOOL              ret = FALSE;
	DWORD             dwSymSize = 10000;
	TCHAR             lpszUnDSymbol[BUFFERSIZE]=_T("?");
	CHAR              lpszNonUnicodeUnDSymbol[BUFFERSIZE]="?";
	LPTSTR            lpszParamSep = nullptr;
	LPTSTR            lpszParsed = lpszUnDSymbol;
	PIMAGEHLP_SYMBOL  pSym = (PIMAGEHLP_SYMBOL)GlobalAlloc( GMEM_FIXED, dwSymSize );

	::ZeroMemory( pSym, dwSymSize );
	pSym->SizeOfStruct = dwSymSize;
	pSym->MaxNameLength = dwSymSize - sizeof(IMAGEHLP_SYMBOL);

	// Set the default to unknown
	_tcscpy( lpszSymbol, _T("?") );

	// Get symbol info for IP
	DWORD64           dwDisp = 0;
	if ( SymGetSymFromAddr( GetCurrentProcess(), (ULONG)fnAddress, (PDWORD64)&dwDisp, pSym ) )
	{
		// Make the symbol readable for humans
		UnDecorateSymbolName( pSym->Name, lpszNonUnicodeUnDSymbol, BUFFERSIZE,
			UNDNAME_COMPLETE |
			UNDNAME_NO_THISTYPE |
			UNDNAME_NO_SPECIAL_SYMS |
			UNDNAME_NO_MEMBER_TYPE |
			UNDNAME_NO_MS_KEYWORDS |
			UNDNAME_NO_ACCESS_SPECIFIERS );

		// Symbol information is ANSI string
		PCSTR2LPTSTR( lpszNonUnicodeUnDSymbol, lpszUnDSymbol );

		// I am just smarter than the symbol file :)
		if ( _tcscmp(lpszUnDSymbol, _T("_WinMain@16")) == 0 )
			_tcscpy(lpszUnDSymbol, _T("WinMain(HINSTANCE,HINSTANCE,LPCTSTR,int)"));
		else
			if ( _tcscmp(lpszUnDSymbol, _T("_main")) == 0 )
				_tcscpy(lpszUnDSymbol, _T("main(int,TCHAR * *)"));
			else
				if ( _tcscmp(lpszUnDSymbol, _T("_mainCRTStartup")) == 0 )
					_tcscpy(lpszUnDSymbol, _T("mainCRTStartup()"));
				else
					if ( _tcscmp(lpszUnDSymbol, _T("_wmain")) == 0 )
						_tcscpy(lpszUnDSymbol, _T("wmain(int,TCHAR * *,TCHAR * *)"));
					else
						if ( _tcscmp(lpszUnDSymbol, _T("_wmainCRTStartup")) == 0 )
							_tcscpy(lpszUnDSymbol, _T("wmainCRTStartup()"));

		lpszSymbol[0] = _T('\0');

		// Let's go through the stack, and modify the function prototype, and insert the actual
		// parameter values from the stack
		if ( _tcsstr( lpszUnDSymbol, _T("(void)") ) == nullptr && _tcsstr( lpszUnDSymbol, _T("()") ) == nullptr)
		{
			ULONG index = 0;
			for ( ; ; index++ )
			{
				lpszParamSep = _tcschr( lpszParsed, _T(',') );
				if ( lpszParamSep == nullptr )
					break;

				*lpszParamSep = _T('\0');

				_tcscat( lpszSymbol, lpszParsed );
				_stprintf( lpszSymbol + _tcslen(lpszSymbol), _T("=0x%08X,"), *((ULONG*)(stackAddress) + 2 + index) );

				lpszParsed = lpszParamSep + 1;
			}

			lpszParamSep = _tcschr( lpszParsed, _T(')') );
			if ( lpszParamSep != nullptr )
			{
				*lpszParamSep = _T('\0');

				_tcscat( lpszSymbol, lpszParsed );
				_stprintf( lpszSymbol + _tcslen(lpszSymbol), _T("=0x%08X)"), *((ULONG*)(stackAddress) + 2 + index) );

				lpszParsed = lpszParamSep + 1;
			}
		}

		_tcscat( lpszSymbol, lpszParsed );

		ret = TRUE;
	}
	GlobalFree( pSym );

	return ret;
}
Example #21
0
void RasterTerrain::OpenTerrain(void)
{
  terrain_initialised = false;
  #if TESTBENCH
  StartupStore(TEXT(". Loading Terrain... %s"),NEWLINE);
  #endif
  CreateProgressDialog(gettext(TEXT("_@M900_"))); // Loading Terrain File...

  TCHAR szFile[MAX_PATH] = _T("\0");

  _tcscpy(szFile,szTerrainFile);

  TCHAR szOrigFile[MAX_PATH] = _T("\0");
  ExpandLocalPath(szFile);
  _tcscpy(szOrigFile, szFile);
  ContractLocalPath(szOrigFile);

  // If no terrain will be found, the registry will be invalid on next run
  _tcscpy(szTerrainFile,_T(""));


#ifdef LKMTERRAIN
  static TCHAR  szMFile[MAX_PATH] = TEXT("\0");
  if (_tcslen(szFile)==0) {
    StartupStore(_T(". NO TERRAIN file configured%s"),NEWLINE);
    _tcscpy(szMFile,szMapFile);
    ExpandLocalPath(szMFile);
    _tcscpy(szFile,szMFile);

     _tcscpy(szFile,szMFile);
     _tcscat(szFile, _T("/terrain.dem")); 
     StartupStore(_T(". Attempting to use DEM <%s> inside mapfile%s"),szFile,NEWLINE);
  }

  if (CreateTerrainMap(szFile)) {
	_tcscpy(szTerrainFile,szOrigFile);
	terrain_initialised = true;
	return;
  } else {
	_tcscpy(szFile,szMFile);
	_tcscat(szFile, _T("/terrain.dat")); 
	StartupStore(_T(". Attempting to use DAT <%s> inside mapfile%s"),szFile,NEWLINE);

	if (CreateTerrainMap(szFile)) {
		_tcscpy(szTerrainFile,szOrigFile);
		terrain_initialised = true;
		return;
	}
   }
#else

  if ( (_tcslen(szFile)>0) && ( _tcsstr(szFile, _T(".DEM")) || _tcsstr(szFile, _T(".dem")) ) ) {
	if (CreateTerrainMap(szFile)) {
		_tcscpy(szterrainFile,szOrigFile);
		terrain_initialised = true;
		return;
	} else {
		StartupStore(_T("... INVALID TERRAIN file <%s>%s"),szFile,NEWLINE);
	}
  }

#endif

  if (TerrainMap) {
	TerrainMap->Close();
	delete TerrainMap;
	TerrainMap = NULL;
  }
  terrain_initialised = false;
  StartupStore(_T(". NO TERRAIN file available.%s"),NEWLINE);
}
Example #22
0
int CLVM_GetContactHiddenStatus(MCONTACT hContact, char *szProto, struct ClcData *dat)
{
	int dbHidden = db_get_b(hContact, "CList", "Hidden", 0);		// default hidden state, always respect it.

	// always hide subcontacts (but show them on embedded contact lists)
	if (dat != NULL && dat->bHideSubcontacts && cfg::dat.bMetaEnabled && db_mc_isSub(hContact))
		return 1;

	if (!cfg::dat.bFilterEffective)
		return dbHidden;

	if (szProto == NULL)
		szProto = GetContactProto(hContact);
	// check stickies first (priority), only if we really have stickies defined (CLVM_STICKY_CONTACTS is set).
	if (cfg::dat.bFilterEffective & CLVM_STICKY_CONTACTS) {
		DWORD dwLocalMask = db_get_dw(hContact, "CLVM", cfg::dat.current_viewmode, 0);
		if (dwLocalMask != 0) {
			if (cfg::dat.bFilterEffective & CLVM_FILTER_STICKYSTATUS) {
				WORD wStatus = db_get_w(hContact, szProto, "Status", ID_STATUS_OFFLINE);
				return !((1 << (wStatus - ID_STATUS_OFFLINE)) & HIWORD(dwLocalMask));
			}
			return 0;
		}
	}

	// check the proto, use it as a base filter result for all further checks
	int filterResult = 1;
	if (cfg::dat.bFilterEffective & CLVM_FILTER_PROTOS) {
		char szTemp[64];
		mir_snprintf(szTemp, "%s|", szProto);
		filterResult = strstr(cfg::dat.protoFilter, szTemp) ? 1 : 0;
	}
	
	if (cfg::dat.bFilterEffective & CLVM_FILTER_GROUPS) {
		ptrT tszGroup(db_get_tsa(hContact, "CList", "Group"));
		if (tszGroup != NULL) {
			TCHAR szGroupMask[256];
			mir_sntprintf(szGroupMask, _T("%s|"), tszGroup);
			int bHasGroup = _tcsstr(cfg::dat.groupFilter, szGroupMask) ? 1 : 0;
			filterResult = (cfg::dat.filterFlags & CLVM_PROTOGROUP_OP) ? (filterResult | bHasGroup) : (filterResult & bHasGroup);
		}
		else if (cfg::dat.filterFlags & CLVM_INCLUDED_UNGROUPED)
			filterResult = (cfg::dat.filterFlags & CLVM_PROTOGROUP_OP) ? filterResult : filterResult & 1;
		else
			filterResult = (cfg::dat.filterFlags & CLVM_PROTOGROUP_OP) ? filterResult : filterResult & 0;
	}

	if (cfg::dat.bFilterEffective & CLVM_FILTER_STATUS) {
		WORD wStatus = db_get_w(hContact, szProto, "Status", ID_STATUS_OFFLINE);
		filterResult = (cfg::dat.filterFlags & CLVM_GROUPSTATUS_OP) ? ((filterResult | ((1 << (wStatus - ID_STATUS_OFFLINE)) & cfg::dat.statusMaskFilter ? 1 : 0))) : (filterResult & ((1 << (wStatus - ID_STATUS_OFFLINE)) & cfg::dat.statusMaskFilter ? 1 : 0));
	}

	if (cfg::dat.bFilterEffective & CLVM_FILTER_LASTMSG) {
		TExtraCache *p = cfg::getCache(hContact, szProto);
		if (p) {
			DWORD now = cfg::dat.t_now;
			now -= cfg::dat.lastMsgFilter;
			if (cfg::dat.bFilterEffective & CLVM_FILTER_LASTMSG_OLDERTHAN)
				filterResult = filterResult & (p->dwLastMsgTime < now);
			else if (cfg::dat.bFilterEffective & CLVM_FILTER_LASTMSG_NEWERTHAN)
				filterResult = filterResult & (p->dwLastMsgTime > now);
		}
	}
	return (dbHidden | !filterResult);
}
Example #23
0
static INT_PTR CALLBACK DlgUpdate(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	HWND hwndList = GetDlgItem(hDlg, IDC_LIST_UPDATES);

	switch (message) {
	case WM_INITDIALOG:
		TranslateDialogDefault(hDlg);
		SendMessage(hwndList, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT | LVS_EX_CHECKBOXES);
		SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)Skin_GetIcon("check_update"));
		SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)Skin_GetIcon("check_update", 1));
		{
			OSVERSIONINFO osver = { sizeof(osver) };
			if (GetVersionEx(&osver) && osver.dwMajorVersion >= 6)
			{
				wchar_t szPath[MAX_PATH];
				GetModuleFileName(NULL, szPath, SIZEOF(szPath));
				TCHAR *ext = _tcsrchr(szPath, '.');
				if (ext != NULL)
					*ext = '\0';
				_tcscat(szPath, _T(".test"));
				HANDLE hFile = CreateFile(szPath, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
				if (hFile == INVALID_HANDLE_VALUE)
					// Running Windows Vista or later (major version >= 6).
					Button_SetElevationRequiredState(GetDlgItem(hDlg, IDOK), !IsProcessElevated());
				else
				{
					CloseHandle(hFile);
					DeleteFile(szPath);
				}
			}
			LVCOLUMN lvc = {0};
			// Initialize the LVCOLUMN structure.
			// The mask specifies that the format, width, text, and
			// subitem members of the structure are valid.
			lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT;
			lvc.fmt = LVCFMT_LEFT;

			lvc.iSubItem = 0;
			lvc.pszText = TranslateT("Component Name");
			lvc.cx = 220; // width of column in pixels
			ListView_InsertColumn(hwndList, 0, &lvc);

			lvc.iSubItem = 1;
			lvc.pszText = TranslateT("State");
			lvc.cx = 120 - GetSystemMetrics(SM_CXVSCROLL); // width of column in pixels
			ListView_InsertColumn(hwndList, 1, &lvc);

			//enumerate plugins, fill in list
			ListView_DeleteAllItems(hwndList);
			///
			LVGROUP lvg;
			lvg.cbSize = sizeof(LVGROUP);
			lvg.mask = LVGF_HEADER | LVGF_GROUPID;

			lvg.pszHeader = TranslateT("Plugins");
			lvg.iGroupId = 1;
			ListView_InsertGroup(hwndList, 0, &lvg);
			
			lvg.pszHeader = TranslateT("Miranda NG Core");
			lvg.iGroupId = 2;
			ListView_InsertGroup(hwndList, 0, &lvg);

			lvg.pszHeader = TranslateT("Languages");
			lvg.iGroupId = 3;
			ListView_InsertGroup(hwndList, 0, &lvg);

			lvg.pszHeader = TranslateT("Icons");
			lvg.iGroupId = 4;
			ListView_InsertGroup(hwndList, 0, &lvg);
			
			ListView_EnableGroupView(hwndList, TRUE);

			bool enableOk = false;
			OBJLIST<FILEINFO> &todo = *(OBJLIST<FILEINFO> *)lParam;
			for (int i = 0; i < todo.getCount(); ++i) {
				LVITEM lvI = {0};
				lvI.mask = LVIF_TEXT | LVIF_PARAM | LVIF_GROUPID | LVIF_NORECOMPUTE;
				lvI.iGroupId = (_tcsstr(todo[i].tszOldName, _T("Plugins")) != NULL) ? 1 : 
					((_tcsstr(todo[i].tszOldName, _T("Languages")) != NULL) ? 3 : 
						((_tcsstr(todo[i].tszOldName, _T("Icons")) != NULL) ? 4 : 2));
				lvI.iSubItem = 0;
				lvI.lParam = (LPARAM)&todo[i];
				lvI.pszText = todo[i].tszOldName;
				lvI.iItem = i;
				ListView_InsertItem(hwndList, &lvI);

				ListView_SetCheckState(hwndList, lvI.iItem, todo[i].bEnabled);
				if (todo[i].bEnabled)
					enableOk = true;

				SetStringText(hwndList,i,todo[i].bDeleteOnly ? TranslateT("Deprecated!") : TranslateT("Update found!"));
			}
			if(enableOk)
				EnableWindow(GetDlgItem(hDlg, IDOK), TRUE);
		}

		bShowDetails = false;
		ResizeVert(hDlg, 60);

		// do this after filling list - enables 'ITEMCHANGED' below
		SetWindowLongPtr(hDlg, GWLP_USERDATA, lParam);
		Utils_RestoreWindowPositionNoSize(hDlg, 0, MODNAME, "ConfirmWindow");
		return TRUE;

	case WM_NOTIFY:
		if (((LPNMHDR) lParam)->hwndFrom == hwndList) {
			switch (((LPNMHDR) lParam)->code) {
			case LVN_ITEMCHANGED:
				if (GetWindowLongPtr(hDlg, GWLP_USERDATA)) {
					NMLISTVIEW *nmlv = (NMLISTVIEW *)lParam;
					if ((nmlv->uNewState ^ nmlv->uOldState) & LVIS_STATEIMAGEMASK) {
						LVITEM lvI = {0};
						lvI.iItem = nmlv->iItem;
						lvI.iSubItem = 0;
						lvI.mask = LVIF_PARAM;
						ListView_GetItem(hwndList, &lvI);

						FILEINFO *p = (FILEINFO*)lvI.lParam;
						db_set_b(NULL, DB_MODULE_FILES, StrToLower(_T2A(p->tszOldName)), p->bEnabled = ListView_GetCheckState(hwndList, nmlv->iItem));

						// Toggle the Download button
						bool enableOk = false;
						OBJLIST<FILEINFO> &todo = *(OBJLIST<FILEINFO> *)GetWindowLongPtr(hDlg, GWLP_USERDATA);
						for (int i=0; i < todo.getCount(); ++i) {
							if (todo[i].bEnabled) {
								enableOk = true;
								break;
							}
						}
						EnableWindow(GetDlgItem(hDlg, IDOK), enableOk ? TRUE : FALSE);
					}
				}
				break;
			}
		}
		break;

	case WM_COMMAND:
		if (HIWORD( wParam ) == BN_CLICKED) {
			switch(LOWORD(wParam)) {
			case IDOK:
				EnableWindow( GetDlgItem(hDlg, IDOK), FALSE);
				EnableWindow( GetDlgItem(hDlg, IDC_SELALL), FALSE);
				EnableWindow( GetDlgItem(hDlg, IDC_SELNONE), FALSE);

				mir_forkthread(ApplyUpdates, hDlg);
				return TRUE;

			case IDC_DETAILS:
				bShowDetails = !bShowDetails;
				ResizeVert(hDlg, bShowDetails ? 242 : 60);
				SetDlgItemText(hDlg, IDC_DETAILS, (bShowDetails ? TranslateT("<< Details") : TranslateT("Details >>")));
				break;

			case IDC_SELALL:
				SelectAll(hDlg, true);
				break;

			case IDC_SELNONE:
				SelectAll(hDlg, false);
				break;

			case IDCANCEL:
				DestroyWindow(hDlg);
				return TRUE;
			}
		}
		break;

	case UM_ERROR:
		MessageBox(hDlg, TranslateT("Update failed! One of the components wasn't downloaded correctly. Try it again later."), TranslateT("Plugin Updater"), MB_OK | MB_ICONERROR);
		DestroyWindow(hDlg);
		break;

	case WM_CLOSE:
		DestroyWindow(hDlg);
		break;

	case WM_DESTROY:
		Skin_ReleaseIcon((HICON)SendMessage(hDlg, WM_SETICON, ICON_SMALL, 0));
		Utils_SaveWindowPosition(hDlg, NULL, MODNAME, "ConfirmWindow");
		hwndDialog = NULL;
		delete (OBJLIST<FILEINFO> *)GetWindowLongPtr(hDlg, GWLP_USERDATA);
		SetWindowLongPtr(hDlg, GWLP_USERDATA, 0);
#if MIRANDA_VER >= 0x0A00
		db_set_dw(NULL, MODNAME, DB_SETTING_LAST_UPDATE, time(NULL));
#endif
		mir_forkthread(InitTimer, 0);
		break;
	}

	return FALSE;
}
Example #24
0
// RegFind      - match a regexp against a string
// Returns      - Returns position of regexp or -1
//                        if regular expression not found
// Note         - The regular expression should have been
//                        previously compiled using RegComp
int CRegExp::RegFind(const TCHAR *str)
{
        TCHAR *string = (TCHAR *)str;   // avert const poisoning 
        TCHAR *s;

        // Delete any previously stored found string
        delete sFoundText;
        sFoundText = NULL;

        // Be paranoid. 
        if(string == NULL) 
        {
                //TRACE0("NULL argument to regexec\n");
				LastError = "NULL argument to regexec";
                return(-1);
        }

        // Check validity of regex
        if (!bCompiled) 
        {
                //TRACE0("No regular expression provided yet.\n");
				LastError = "No regular expression provided yet.";
                return(-1);
        }

        // If there is a "must appear" string, look for it. 
        if (regmust != NULL && _tcsstr(string, regmust) == NULL)
                return(-1);

        // Mark beginning of line for ^
        regbol = string;

        // Simplest case:  anchored match need be tried only once. 
        if (reganch)
        {
                if( regtry(string) )
                {
                        // Save the found substring in case we need it
                        sFoundText = new TCHAR[GetFindLen()+1];
                        sFoundText[GetFindLen()] = _T('\0');
                        _tcsncpy(sFoundText, string, GetFindLen() );

                        return 0;
                }
                //String not found
                return -1;
        }

        // Messy cases:  unanchored match. 
        if (regstart != _T('\0')) 
        {
                // We know what TCHAR it must start with. 
                for (s = string; s != NULL; s = _tcschr(s+1, regstart))
                        if (regtry(s))
                        {
                                int nPos = s-str;

                                // Save the found substring in case we need it later
                                sFoundText = new TCHAR[GetFindLen()+1];
                                sFoundText[GetFindLen()] = _T('\0');
                                _tcsncpy(sFoundText, s, GetFindLen() );

                                return nPos;
                        }
                return -1;
        } 
        else 
        {
                // We don't -- general case
                for (s = string; !regtry(s); s++)
                        if (*s == _T('\0'))
                                return(-1);

                int nPos = s-str;

                // Save the found substring in case we need it later
                sFoundText = new TCHAR[GetFindLen()+1];
                sFoundText[GetFindLen()] = _T('\0');
                _tcsncpy(sFoundText, s, GetFindLen() );

                return nPos;
        }
        // NOTREACHED 
}
Example #25
0
static BOOL
devInit(LPCTSTR CommandLine)
{
  int i;
  PDeviceDescriptor_t pDevNmeaOut = NULL;

  for (i=0; i<NUMDEV; i++){
    DeviceList[i].Port = -1;
    DeviceList[i].fhLogFile = NULL;
    DeviceList[i].Name[0] = '\0';
    DeviceList[i].Driver = NULL;
    DeviceList[i].pDevPipeTo = NULL;
  }

  pDevPrimaryBaroSource = NULL;
  pDevSecondaryBaroSource=NULL;

  DWORD PortIndex1, PortIndex2, SpeedIndex1, SpeedIndex2;
#ifdef GNAV
  PortIndex1 = 2; SpeedIndex1 = 5;
  PortIndex2 = 0; SpeedIndex2 = 5;
#else
  PortIndex1 = 0; SpeedIndex1 = 2;
  PortIndex2 = 0; SpeedIndex2 = 2;
#endif
  ReadPort1Settings(&PortIndex1,&SpeedIndex1);
  ReadPort2Settings(&PortIndex2,&SpeedIndex2);

  devInitOne(devA(), 0, COMMPort[PortIndex1], dwSpeed[SpeedIndex1], pDevNmeaOut);

  if (PortIndex1 != PortIndex2)
    devInitOne(devB(), 1, COMMPort[PortIndex2], dwSpeed[SpeedIndex2], pDevNmeaOut);

  CommandLine = LOGGDEVCOMMANDLINE;

  if (CommandLine != NULL){
    TCHAR *pC, *pCe;
    TCHAR wcLogFileName[MAX_PATH];
    TCHAR sTmp[128];

    pC = _tcsstr(CommandLine, TEXT("-logA="));
    if (pC != NULL){
      pC += strlen("-logA=");
      if (*pC == '"'){
        pC++;
        pCe = pC;
        while (*pCe != '"' && *pCe != '\0') pCe++;
      } else{
        pCe = pC;
        while (*pCe != ' ' && *pCe != '\0') pCe++;
      }
      if (pCe != NULL && pCe-1 > pC){

        _tcsncpy(wcLogFileName, pC, pCe-pC);
        wcLogFileName[pCe-pC] = '\0';

        if (devOpenLog(devA(), wcLogFileName)){
          _stprintf(sTmp, TEXT("Device A logs to\r\n%s"), wcLogFileName);
          MessageBoxX (sTmp,
                      gettext(TEXT("Information")),
                      MB_OK|MB_ICONINFORMATION);
        } else {
          _stprintf(sTmp,
                    TEXT("Unable to open log\r\non device A\r\n%s"), wcLogFileName);
          MessageBoxX (sTmp,
                      gettext(TEXT("Error")),
                      MB_OK|MB_ICONWARNING);
        }

      }

    }

    pC = _tcsstr(CommandLine, TEXT("-logB="));
    if (pC != NULL){
      pC += strlen("-logA=");
      if (*pC == '"'){
        pC++;
        pCe = pC;
        while (*pCe != '"' && *pCe != '\0') pCe++;
      } else{
        pCe = pC;
        while (*pCe != ' ' && *pCe != '\0') pCe++;
      }
      if (pCe != NULL && pCe > pC){

        _tcsncpy(wcLogFileName, pC, pCe-pC);
        wcLogFileName[pCe-pC] = '\0';

        if (devOpenLog(devB(), wcLogFileName)){
          _stprintf(sTmp, TEXT("Device B logs to\r\n%s"), wcLogFileName);
          MessageBoxX (sTmp,
                      gettext(TEXT("Information")),
                      MB_OK|MB_ICONINFORMATION);
        } else {
          _stprintf(sTmp, TEXT("Unable to open log\r\non device B\r\n%s"),
                    wcLogFileName);
          MessageBoxX (sTmp,
                      gettext(TEXT("Error")),
                      MB_OK|MB_ICONWARNING);
        }

      }

    }

  }

  if (pDevNmeaOut != NULL){
    if (pDevNmeaOut == devA()){
      devB()->pDevPipeTo = devA();
    }
    if (pDevNmeaOut == devB()){
      devA()->pDevPipeTo = devB();
    }
  }

  return(TRUE);
}
Example #26
0
bool CPicture::Load(tstring sFilePathName)
{
	bool bResult = false;
	bIsIcon = false;
	lpIcons = NULL;
	//CFile PictureFile;
	//CFileException e;
	FreePictureData(); // Important - Avoid Leaks...

	// No-op if no file specified
	if (sFilePathName.empty())
		return true;

	// Load & initialize the GDI+ library if available
	HMODULE hGdiPlusLib = AtlLoadSystemLibraryUsingFullPath(_T("gdiplus.dll"));
	if (hGdiPlusLib && GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL) == Ok)
	{
		bHaveGDIPlus = true;
	}
	// Since we loaded the gdiplus.dll only to check if it's available, we
	// can safely free the library here again - GdiplusStartup() loaded it too
	// and reference counting will make sure that it stays loaded until GdiplusShutdown()
	// is called.
	FreeLibrary(hGdiPlusLib);

	// Attempt to load using GDI+ if available
	if (bHaveGDIPlus)
	{
		pBitmap = new Bitmap(sFilePathName.c_str(), FALSE);
		GUID guid;
		pBitmap->GetRawFormat(&guid);

		if (pBitmap->GetLastStatus() != Ok)
		{
			delete pBitmap;
			pBitmap = NULL;
		}

		// gdiplus only loads the first icon found in an icon file
		// so we have to handle icon files ourselves :(

		// Even though gdiplus can load icons, it can't load the new
		// icons from Vista - in Vista, the icon format changed slightly.
		// But the LoadIcon/LoadImage API still can load those icons,
		// at least those dimensions which are also used on pre-Vista
		// systems.
		// For that reason, we don't rely on gdiplus telling us if
		// the image format is "icon" or not, we also check the
		// file extension for ".ico".
		std::transform(sFilePathName.begin(), sFilePathName.end(), sFilePathName.begin(), ::tolower);
		bIsIcon = (guid == ImageFormatIcon) || (wcsstr(sFilePathName.c_str(), L".ico") != NULL) || (wcsstr(sFilePathName.c_str(), L".cur") != NULL);
		bIsTiff = (guid == ImageFormatTIFF) || (_tcsstr(sFilePathName.c_str(), _T(".tiff")) != NULL);
		m_Name = sFilePathName;

		if (bIsIcon)
		{
			// Icon file, get special treatment...
			if (pBitmap)
			{
				// Cleanup first...
				delete (pBitmap);
				pBitmap = NULL;
				bIsIcon = true;
			}

			CAutoFile hFile = CreateFile(sFilePathName.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
			if (hFile)
			{
				BY_HANDLE_FILE_INFORMATION fileinfo;
				if (GetFileInformationByHandle(hFile, &fileinfo))
				{
					lpIcons = new BYTE[fileinfo.nFileSizeLow];
					DWORD readbytes;
					if (ReadFile(hFile, lpIcons, fileinfo.nFileSizeLow, &readbytes, NULL))
					{
						// we have the icon. Now gather the information we need later
						if (readbytes >= sizeof(ICONDIR))
						{
							// we are going to open same file second time so we have to close the file now
							hFile.CloseHandle();

							LPICONDIR lpIconDir = (LPICONDIR)lpIcons;
							if ((lpIconDir->idCount) && ((lpIconDir->idCount * sizeof(ICONDIR)) <= fileinfo.nFileSizeLow))
							{
								try
								{
									bResult = false;
									nCurrentIcon = 0;
									hIcons = new HICON[lpIconDir->idCount];
									// check that the pointers point to data that we just loaded
									if (((BYTE*)lpIconDir->idEntries > (BYTE*)lpIconDir) && 
										(((BYTE*)lpIconDir->idEntries) + (lpIconDir->idCount * sizeof(ICONDIRENTRY)) < ((BYTE*)lpIconDir) + fileinfo.nFileSizeLow))
									{
										m_Width = lpIconDir->idEntries[0].bWidth;
										m_Height = lpIconDir->idEntries[0].bHeight;
										bResult = true;
										for (int i=0; i<lpIconDir->idCount; ++i)
										{
											hIcons[i] = (HICON)LoadImage(NULL, sFilePathName.c_str(), IMAGE_ICON,
																		 lpIconDir->idEntries[i].bWidth,
																		 lpIconDir->idEntries[i].bHeight,
																		 LR_LOADFROMFILE);
											if (hIcons[i] == NULL)
											{
												// if the icon couldn't be loaded, the data is most likely corrupt
												delete [] lpIcons;
												lpIcons = NULL;
												bResult = false;
												break;
											}
										}
									}
								}
								catch (...)
								{
									delete [] lpIcons;
									lpIcons = NULL;
									bResult = false;
								}
							}
							else
							{
								delete [] lpIcons;
								lpIcons = NULL;
								bResult = false;
							}
						}
						else
						{
							delete [] lpIcons;
							lpIcons = NULL;
							bResult = false;
						}
					}
					else
					{
						delete [] lpIcons;
						lpIcons = NULL;
					}
				}
			}
		}
		else if (pBitmap)	// Image loaded successfully with GDI+
		{
			m_Height = pBitmap->GetHeight();
			m_Width = pBitmap->GetWidth();
			bResult = true;
		}

		// If still failed to load the file...
		if (!bResult)
		{
			// Attempt to load the FreeImage library as an optional DLL to support additional formats

			// NOTE: Currently just loading via FreeImage & using GDI+ for drawing.
			// It might be nice to remove this dependency in the future.
			HMODULE hFreeImageLib = LoadLibrary(_T("FreeImage.dll"));

			// FreeImage DLL functions
			typedef const char* (__stdcall *FreeImage_GetVersion_t)(void);
			typedef int			(__stdcall *FreeImage_GetFileType_t)(const TCHAR *filename, int size);
			typedef int			(__stdcall *FreeImage_GetFIFFromFilename_t)(const TCHAR *filename);
			typedef void*		(__stdcall *FreeImage_Load_t)(int format, const TCHAR *filename, int flags);
			typedef void		(__stdcall *FreeImage_Unload_t)(void* dib);
			typedef int			(__stdcall *FreeImage_GetColorType_t)(void* dib);
			typedef unsigned	(__stdcall *FreeImage_GetWidth_t)(void* dib);
			typedef unsigned	(__stdcall *FreeImage_GetHeight_t)(void* dib);
			typedef void		(__stdcall *FreeImage_ConvertToRawBits_t)(BYTE *bits, void *dib, int pitch, unsigned bpp, unsigned red_mask, unsigned green_mask, unsigned blue_mask, BOOL topdown);

			//FreeImage_GetVersion_t FreeImage_GetVersion = NULL;
			FreeImage_GetFileType_t FreeImage_GetFileType = NULL;
			FreeImage_GetFIFFromFilename_t FreeImage_GetFIFFromFilename = NULL;
			FreeImage_Load_t FreeImage_Load = NULL;
			FreeImage_Unload_t FreeImage_Unload = NULL;
			//FreeImage_GetColorType_t FreeImage_GetColorType = NULL;
			FreeImage_GetWidth_t FreeImage_GetWidth = NULL;
			FreeImage_GetHeight_t FreeImage_GetHeight = NULL;
			FreeImage_ConvertToRawBits_t  FreeImage_ConvertToRawBits = NULL;

			if (hFreeImageLib)
			{
				bool exportsValid = true;

				//FreeImage_GetVersion = (FreeImage_GetVersion_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_GetVersion@0", valid);
				FreeImage_GetWidth = (FreeImage_GetWidth_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_GetWidth@4", exportsValid);
				FreeImage_GetHeight = (FreeImage_GetHeight_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_GetHeight@4", exportsValid);
				FreeImage_Unload = (FreeImage_Unload_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_Unload@4", exportsValid);
				FreeImage_ConvertToRawBits = (FreeImage_ConvertToRawBits_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_ConvertToRawBits@32", exportsValid);

#ifdef UNICODE
				FreeImage_GetFileType = (FreeImage_GetFileType_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_GetFileTypeU@8", exportsValid);
				FreeImage_GetFIFFromFilename = (FreeImage_GetFIFFromFilename_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_GetFIFFromFilenameU@4", exportsValid);
				FreeImage_Load = (FreeImage_Load_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_LoadU@12", exportsValid);
#else
				FreeImage_GetFileType = (FreeImage_GetFileType_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_GetFileType@8", exportsValid);
				FreeImage_GetFIFFromFilename = (FreeImage_GetFIFFromFilename_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_GetFIFFromFilename@4", exportsValid);
				FreeImage_Load = (FreeImage_Load_t)s_GetProcAddressEx(hFreeImageLib, "_FreeImage_Load@12", exportsValid);
#endif

				//const char* version = FreeImage_GetVersion();

				// Check the DLL is using compatible exports
				if (exportsValid)
				{
					// Derive file type from file header.
					int fileType = FreeImage_GetFileType(sFilePathName.c_str(), 0);
					if (fileType < 0)
					{
						// No file header available, attempt to parse file name for extension.
						fileType = FreeImage_GetFIFFromFilename(sFilePathName.c_str());
					}

					// If we have a valid file type
					if (fileType >= 0)
					{
						void* dib = FreeImage_Load(fileType, sFilePathName.c_str(), 0);

						if (dib)
						{
							unsigned width = FreeImage_GetWidth(dib);
							unsigned height = FreeImage_GetHeight(dib);

							// Create a GDI+ bitmap to load into...
							pBitmap = new Bitmap(width, height, PixelFormat32bppARGB);

							if (pBitmap && pBitmap->GetLastStatus() == Ok)
							{
								// Write & convert the loaded data into the GDI+ Bitmap
								Rect rect(0, 0, width, height);
								BitmapData bitmapData;
								if (pBitmap->LockBits(&rect, ImageLockModeWrite, PixelFormat32bppARGB, &bitmapData) == Ok)
								{
									FreeImage_ConvertToRawBits((BYTE*)bitmapData.Scan0, dib, bitmapData.Stride, 32, 0xff << RED_SHIFT, 0xff << GREEN_SHIFT, 0xff << BLUE_SHIFT, FALSE);

									pBitmap->UnlockBits(&bitmapData);

									m_Width = width;
									m_Height = height;
									bResult = true;
								}
								else    // Failed to lock the destination Bitmap
								{
									delete pBitmap;
									pBitmap = NULL;
								}
							}
							else    // Bitmap allocation failed
							{
								delete pBitmap;
								pBitmap = NULL;
							}

							FreeImage_Unload(dib);
							dib = NULL;
						}
					}
				}

				FreeLibrary(hFreeImageLib);
				hFreeImageLib = NULL;
			}
		}
	}
Example #27
0
// Check the specified ISO, and proceed accordingly
static int NeoCDList_CheckISO(TCHAR* pszFile)
{
	if(!pszFile) {
		// error
		return 0;
	}

	// Make sure we have a valid ISO file extension...
	if(_tcsstr(pszFile, _T(".iso")) || _tcsstr(pszFile, _T(".ISO")) ) 
	{
		FILE* fp = _tfopen(pszFile, _T("rb"));
		if(fp) 
		{
			// Read ISO and look for 68K ROM standard program header, ID is always there
			// Note: This function works very quick, doesn't compromise performance :)
			// it just read each sector first 264 bytes aproximately only.

			// Get ISO Size (bytes)
			fseek(fp, 0, SEEK_END);
			unsigned int lSize = 0;
			lSize = ftell(fp);
			//rewind(fp);
			fseek(fp, 0, SEEK_SET);

			// If it has at least 16 sectors proceed
			if(lSize > (2048 * 16)) 
			{	
				// Check for Standard ISO9660 Identifier
				unsigned char IsoHeader[2048 * 16 + 1];
				unsigned char IsoCheck[6];
		
				fread(IsoHeader, 1, 2048 * 16 + 1, fp); // advance to sector 16 and PVD Field 2
				fread(IsoCheck, 1, 5, fp);	// get Standard Identifier Field from PVD
				
				// Verify that we have indeed a valid ISO9660 MODE1/2048
				if(!memcmp(IsoCheck, "CD001", 5))
				{
					//bprintf(PRINT_NORMAL, _T("    Standard ISO9660 Identifier Found. \n"));
					iso9660_VDH vdh;

					// Get Volume Descriptor Header			
					memset(&vdh, 0, sizeof(vdh));
					//memcpy(&vdh, iso9660_ReadOffset(fp, (2048 * 16), sizeof(vdh)), sizeof(vdh));
					iso9660_ReadOffset((unsigned char*)&vdh, fp, 2048 * 16, 1, sizeof(vdh));

					// Check for a valid Volume Descriptor Type
					if(vdh.vdtype == 0x01) 
					{
#if 0
// This will fail on 64-bit due to differing variable sizes in the pvd struct
						// Get Primary Volume Descriptor
						iso9660_PVD pvd;
						memset(&pvd, 0, sizeof(pvd));
						//memcpy(&pvd, iso9660_ReadOffset(fp, (2048 * 16), sizeof(pvd)), sizeof(pvd));
						iso9660_ReadOffset((unsigned char*)&pvd, fp, 2048 * 16, 1, sizeof(pvd));

						// ROOT DIRECTORY RECORD

						// Handle Path Table Location
						char szRootSector[32];
						unsigned int nRootSector = 0;

						sprintf(szRootSector, "%02X%02X%02X%02X", 
							pvd.root_directory_record.location_of_extent[4], 
							pvd.root_directory_record.location_of_extent[5], 
							pvd.root_directory_record.location_of_extent[6], 
							pvd.root_directory_record.location_of_extent[7]);

						// Convert HEX string to Decimal
						sscanf(szRootSector, "%X", &nRootSector);
#else
// Just read from the file directly at the correct offset (0x8000 + 0x9e for the start of the root directory record)
						unsigned char buffer[8];
						char szRootSector[4];
						unsigned int nRootSector = 0;
						
						fseek(fp, 0x809e, SEEK_SET);
						fread(buffer, 1, 8, fp);
						
						sprintf(szRootSector, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]);
						
						sscanf(szRootSector, "%x", &nRootSector);
#endif						
						
						// Process the Root Directory Records
						NeoCDList_iso9660_CheckDirRecord(fp, nRootSector);

						// Path Table Records are not processed, since NeoGeo CD should not have subdirectories
						// ...
					}
				} else {

					//bprintf(PRINT_NORMAL, _T("    Standard ISO9660 Identifier Not Found, cannot continue. \n"));
					return 0;
				}
			}
		} else {

			//bprintf(PRINT_NORMAL, _T("    Couldn't open %s \n"), GetIsoPath());
			return 0;
		}

		if(fp) fclose(fp);

	} else {

		//bprintf(PRINT_NORMAL, _T("    File doesn't have a valid ISO extension [ .iso / .ISO ] \n"));
		return 0;
	}

	return 1;
}
Example #28
0
static BOOL RegisterForRawInputs()
{
	BOOL result = FALSE;
	PRAWINPUTDEVICELIST pRawInputDeviceList = NULL;
	do
	{
		BYTE data[2048];
		UINT dataSize;
		UINT nDevices;
		TCHAR vidStr[10];
		RAWINPUTDEVICE rawInputDevice;	
		
		if (GetRawInputDeviceList(NULL, &nDevices, sizeof(RAWINPUTDEVICELIST)) < 0)
		{
			printf("GetRawInputDeviceList failed to get device count. Error code 0x%08X.\n", GetLastError());		
			break;
		}

		pRawInputDeviceList = (PRAWINPUTDEVICELIST)malloc(sizeof(RAWINPUTDEVICELIST) * nDevices);
		if (NULL == pRawInputDeviceList)
		{
			printf("Malloc failed for pRawInputDeviceList.\n");	
			break;
		}

		nDevices = GetRawInputDeviceList(pRawInputDeviceList, (PUINT)&nDevices, sizeof(RAWINPUTDEVICELIST));
		if (nDevices < 0)
		{
			printf("GetRawInputDeviceList failed to get device list. Error code 0x%08X.\n", GetLastError());	
			break;
		}

		_stprintf_s(vidStr, sizeof(vidStr) / sizeof(TCHAR), _T("%04X"), HARDWARE_VID);
		for (UINT i = 0; i < nDevices; i++)
		{
			dataSize = 0;
			GetRawInputDeviceInfo(pRawInputDeviceList[i].hDevice, RIDI_DEVICENAME, data, &dataSize);
			GetRawInputDeviceInfo(pRawInputDeviceList[i].hDevice, RIDI_DEVICENAME, data, &dataSize);
			data[dataSize] = '\0';
			if ((_tcsstr((TCHAR*)data, vidStr) > 0))
			{	
				memcpy(&rawInputDeviceList, &pRawInputDeviceList[i], sizeof(rawInputDeviceList));
				break;
			}
		}

		memset(&rawInputDevice, 0, sizeof(rawInputDevice));
		rawInputDevice.dwFlags = RIDEV_INPUTSINK;
		rawInputDevice.hwndTarget = hWnd;
	
		/* Set "Usage" and "Usage Page" for mouse
         * https://msdn.microsoft.com/en-us/library/windows/hardware/ff543477(v=vs.85).aspx
		 */
		rawInputDevice.usUsagePage = DEVICE_USAGE_PAGE;
		rawInputDevice.usUsage     = DEVICE_USAGE;

		if (RegisterRawInputDevices(&rawInputDevice, 1, sizeof(rawInputDevice)))
		{
			result = TRUE;
			printf("Registered for raw inputs\n");
		}
		else
		{			
			printf("Registered for raw inputs failed. Error code 0x%08X.\n", GetLastError());
		}

	} while (false);

	if (NULL != pRawInputDeviceList)
	{
		free(pRawInputDeviceList);
	}
	
	return result;
}
Example #29
0
static int unpack2 (const TCHAR *src, const TCHAR *match, int level)
{
	struct zdirectory *h;
	struct zvolume *zv;
	int ret;
	uae_u8 *b;
	int size;
	TCHAR fn[MAX_DPATH];

	ret = 0;
	zv = zfile_fopen_archive_root (src, ZFD_ALL | ZFD_NORECURSE);
	if (zv == NULL) {
		geterror();
		_tprintf (L"Couldn't open archive '%s'\n", src);
		return 0;
	}
	h = zfile_opendir_archive (src);
	if (!h) {
		geterror();
		_tprintf (L"Couldn't open directory '%s'\n", src);
		return 0;
	}
	while (zfile_readdir_archive (h, fn)) {
		TCHAR tmp[MAX_DPATH];
		TCHAR *dst;
		struct zfile *s, *d;
		int isdir, flags;

		_tcscpy (tmp, src);
		_tcscat (tmp, sep);
		_tcscat (tmp, fn);
		zfile_fill_file_attrs_archive (tmp, &isdir, &flags, NULL);
		if (isdir) {
			TCHAR *p = _tcsstr (fn, L".DIR");
			if (isdir == ZNODE_VDIR && p && _tcslen (p) == 4) {
				p[0] = 0;
				if (pattern_match (fn, match))
					continue;
				p[0] = '.';
			}
			unpack2 (tmp, match, 1);
			continue;
		}

		if (pattern_match (fn, match)) {
			struct _stat64 st;

			if (!zfile_stat_archive (tmp, &st)) {
				st.st_mtime = -1;
			}
			found = 1;
			dst = fn;
			s = zfile_open_archive (tmp, ZFD_NORECURSE);
			if (!s) {
				geterror();
				_tprintf (L"Couldn't open '%s' for reading\n", tmp);
				continue;
			}
			zfile_fseek (s, 0, SEEK_END); 
			size = zfile_ftell (s);
			zfile_fseek (s, 0, SEEK_SET);
			b = xcalloc (uae_u8, size);
			if (b) {
				if (zfile_fread (b, size, 1, s) == 1) {
					d = zfile_fopen (dst, L"wb", 0);
					if (d) {
						if (zfile_fwrite (b, size, 1, d) == 1) {
							ret = 1;
							_tprintf (L"%s extracted, %d bytes\n", dst, size);
						}
						zfile_fclose (d);
						setdate (dst, st.st_mtime);
					}
				}
				xfree (b);
			}
			zfile_fclose (s);
		}
	}
	geterror ();
	if (!found && !level) {
		_tprintf (L"'%s' not matched\n", match);
	}
	return ret;
}
Example #30
0
static int GetCustomVideoModes(ConfigSettings *cs, ModeLine VideoMode[MAX_MODELINES]) {
    HKEY hKey;
    int dwIndex = 0, j = -1;
    int  hactive, vactive, vfreq;
    LONG lRes;
    TCHAR dv[1024];
    TCHAR *DefaultVideo = NULL;
    DWORD type;

    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("HARDWARE\\DEVICEMAP\\VIDEO"), 0, KEY_ALL_ACCESS, &hKey) == ERROR_SUCCESS) {
        TCHAR *chsrc, *chdst;

        DefaultVideo = reg_query_string(hKey, TEXT("\\Device\\Video0"));
        RegCloseKey(hKey);

        if (DefaultVideo == NULL) {
            mame_printf_error("SwitchRes: Failed opening \\Device\\Video0 registry\n");
            return -1;
        }

        chdst = dv;

        for (chsrc = DefaultVideo + 18; *chsrc != 0; chsrc++)
            *chdst++ = *chsrc;
        *chdst = 0;
    } else {
        mame_printf_error("SwitchRes: Failed opening DefaultVideo registry\n");
        return -1;
    }

    if (cs->verbose)
        mame_printf_verbose("SwitchRes: DefaultVideo '%s'\n", utf8_from_tstring(dv));

    if ((lRes = RegOpenKeyEx(HKEY_LOCAL_MACHINE, dv, 0, KEY_ALL_ACCESS, &hKey)) == ERROR_SUCCESS) {
        type = 0;
        TCHAR lpValueName[1024];
        char lpData[1024];
        DWORD lpcValueName = 1024;
        DWORD lpcData = 1024;

        while (RegEnumValue (hKey, dwIndex, lpValueName, &lpcValueName, NULL, &type, (LPBYTE)lpData, &lpcData) != ERROR_NO_MORE_ITEMS) {
            dwIndex++;

            if (_tcsstr(lpValueName, TEXT("DALDTMCRTBCD"))) {
                int hhh = 0, hhi = 0, hhf = 0, hht = 0, vvv = 0, vvi = 0, vvf = 0, vvt = 0, interlace = 0;
                double dotclock = 0;
                int checksum;
                int i = 0, k = 0;
                int active = 0;

                if (cs->verbose)
                    mame_printf_verbose("SwitchRes: %s:\n ", utf8_from_tstring(lpValueName));

                dotclock = (double)CustomModeDataWord(38, lpData);
                hhh = (int)RealRes(CustomModeDataWord(10, lpData));
                hhi = (int)RealRes(CustomModeDataWord(14, lpData));
                hhf = (int)RealRes(CustomModeDataWord(18, lpData)) + hhi;
                hht = (int)RealRes(CustomModeDataWord(6, lpData));
                vvv = CustomModeDataWord(26, lpData);
                vvi = CustomModeDataWord(30, lpData);
                vvf = CustomModeDataWord(34, lpData) + vvi;
                vvt = CustomModeDataWord(22, lpData);
                interlace = (lpData[3] == 0x0e)?1:0;

                checksum = CustomModeDataWordBCD(66, lpData);

                if (cs->verbose)
                    mame_printf_verbose("SwitchRes: (%d/%d) Modeline %.6f %d %d %d %d %d %d %d %d%s\n",
                                        checksum, (int)lpcData, (double)((double)dotclock * 10000.0)/1000000.0,
                                        (int)RealRes (hhh), (int)RealRes (hhi), (int)RealRes (hhf), (int)RealRes (hht),
                                        vvv, vvi, vvf, vvt, (interlace)?" interlace":"");

                if (sscanf(utf8_from_tstring(lpValueName), "DALDTMCRTBCD%dx%dx0x%d", &hactive, &vactive, &vfreq) != 3) {
                    if (sscanf(utf8_from_tstring(lpValueName), "DALDTMCRTBCD%dX%dX0X%d", &hactive, &vactive, &vfreq) != 3) {
                        mame_printf_info("SwitchRes: Failed getting resolution values from %s\n", utf8_from_tstring(lpValueName));
                        continue;
                    }
                }

                for (k = 0; k < MAX_MODELINES; k++) {
                    if (VideoMode[k].hactive == hactive &&
                            VideoMode[k].vactive == vactive &&
                            VideoMode[k].vfreq == vfreq)
                    {
                        active = 1;
                        break;
                    }
                }

                if (active) {
                    sprintf(VideoMode[k].name, "%dx%d@%d", hactive, vactive, vfreq);

                    VideoMode[k].a_width = hactive;
                    VideoMode[k].a_height = vactive;

                    sprintf(VideoMode[k].resolution, "%dx%d@%d", hactive, vactive, vfreq);
                    VideoMode[k].vfreq = vfreq;
                    VideoMode[k].a_vfreq = (double)(dotclock * 10000.0) / (vvt * hht);
                    VideoMode[k].pclock  = dotclock * 10000;
                    VideoMode[k].hactive = hhh;
                    VideoMode[k].hbegin  = hhi;
                    VideoMode[k].hend    = hhf;
                    VideoMode[k].htotal  = hht;
                    VideoMode[k].vactive = vvv;
                    VideoMode[k].vbegin  = vvi;
                    VideoMode[k].vend    = vvf;
                    VideoMode[k].vtotal  = vvt;
                    VideoMode[k].interlace  = interlace;
                    VideoMode[k].doublescan  = 0;
                    VideoMode[k].custom  = 1;

                    for(i=0; i < lpcValueName; i++) {
                        VideoMode[k].label[i] = lpValueName[i];
                    }
                    VideoMode[k].regdata_size = lpcData;

                    for(i=0; i < VideoMode[k].regdata_size; i++) {
                        VideoMode[k].regdata[i] = lpData[i];
                        if (cs->verbose > 4)
                            mame_printf_verbose("[%02X]", lpData[i]);
                    }
                    if (cs->verbose > 4)
                        mame_printf_verbose("\n");

                    j++;
                }
            }

            lpcValueName = 1024;
            lpcData = 1024;
        }

        RegCloseKey(hKey);
    } else {
        mame_printf_error("SwitchRes: Failed opening %s registry entry with error %d\n", utf8_from_tstring(dv), (int)lRes);
        j = -1;
    }

    if (DefaultVideo != NULL)
        global_free(DefaultVideo);

    return j;
}