Example #1
0
bool
ReadAirspace(Airspaces &airspace_database, TLineReader &reader)
{
  int LineCount = 0;
  bool ignore = false;

  // Create and init ProgressDialog
  ProgressGlue::SetRange(1024);

  long file_size = reader.size();

  TempAirspaceType temp_area;
  asFileType filetype = ftUnknown;

  TCHAR *line;
  TCHAR *comment;
  // Iterate through the lines
  while ((line = reader.read()) != NULL) {
    // Increase line counter
    LineCount++;

    // Strip comments
    comment = _tcschr(line, _T('*'));
    if (comment != NULL)
      *comment = _T('\0');

    // Skip empty line
    if (string_is_empty(line))
      continue;

    if (filetype == ftUnknown) {
      filetype = DetectFileType(line);
      if (filetype == ftUnknown)
        continue;
    }

    // Parse the line
    if (filetype == ftOpenAir)
      if (!ParseLine(airspace_database, line, temp_area) &&
          !ShowParseWarning(LineCount, line))
        return false;

    if (filetype == ftTNP)
      if (!ParseLineTNP(airspace_database, line, temp_area, ignore) &&
          !ShowParseWarning(LineCount, line))
        return false;

    // Update the ProgressDialog
    if ((LineCount & 0xff) == 0)
      ProgressGlue::SetValue(reader.tell() * 1024 / file_size);
  }

  if (LineCount == 0)
    return false;

  if (filetype == ftUnknown) {
    MessageBoxX(_("Unknown Filetype."), _("Airspace"), MB_OK);
    return false;
  }

  // Process final area (if any)
  if (!temp_area.Waiting)
    temp_area.AddPolygon(airspace_database);

  return true;
}
STDMETHODIMP CXMLDOMDocument::load(VARIANT xmlSource, VARIANT_BOOL  *isSuccessful)
{
	ATLTRACE(_T("CXMLDOMDocument::load\n"));

	if (NULL == isSuccessful)
		return E_POINTER;

	*isSuccessful = VARIANT_FALSE;

	if (V_VT(&xmlSource) != VT_BSTR					&&
		V_VT(&xmlSource) != VT_DISPATCH				&&
		V_VT(&xmlSource) != (VT_ARRAY | VT_VARIANT)	&&
		V_VT(&xmlSource) != (VT_ARRAY | VT_UI1)		&&
		V_VT(&xmlSource) != VT_UNKNOWN)
		return E_INVALIDARG;

	// do not start another thread if there is another active
	if (NULL != m_hParseThread) {
		DWORD exitCode = 0;
		BOOL rc = ::GetExitCodeThread(m_hParseThread, &exitCode);
		if (!rc || STILL_ACTIVE == exitCode)
			return S_OK;
		
		::CloseHandle(m_hParseThread);
		m_hParseThread = NULL;
	}

	HRESULT hr = S_OK;
	m_bAbort = false;
	
	m_FileName = _T("");
	m_xml = _T("");
	m_TmpDocument = 0;
	m_bThreadValidate = m_bValidate;
	
	if (V_VT(&xmlSource) == VT_BSTR) {
		m_FileName = V_BSTR(&xmlSource);
		if (0 == m_FileName.length())
			return E_INVALIDARG;

		// see if the file is relative path
		if (!PathIsURL(m_FileName) && PathIsRelative(m_FileName)) {
			// try appending baseurl if exists
			_bstr_t baseURL;
			if (S_OK == GetBaseURL(baseURL)) {
				// change any backslashes to slashes
				LPTSTR loc = _tcschr(m_FileName,_T('\\'));
				while (loc != NULL) {
					*loc = _T('/');
					loc = _tcschr(m_FileName,_T('\\'));
				}
				m_FileName = baseURL + _T("/") + m_FileName;
			}
			else {
				TCHAR szCurDir[MAX_PATH];
				GetCurrentDirectory(MAX_PATH,szCurDir);
				m_FileName=_bstr_t(szCurDir) + _T("\\") + m_FileName;
			}
		}
	}
	else
	if (V_VT(&xmlSource) == VT_UNKNOWN) {
		CComQIPtr<IStream,&IID_IStream> pS(V_UNKNOWN(&xmlSource));
		if (!pS)
			return E_INVALIDARG;

		CComBSTR b;
		hr = b.ReadFromStream(pS);
		if (S_OK != hr)
			return hr;

		m_xml = b;
		if (0 == m_xml.length())
			return E_INVALIDARG;
	}
	else
	if (V_VT(&xmlSource) == VT_DISPATCH) {
		CComQIPtr<IXMLDOMDocument,&IID_IXMLDOMDocument> pDoc(V_DISPATCH(&xmlSource));
		if (!pDoc)
			return E_INVALIDARG;
		
		BSTR b = NULL;
		hr = pDoc->get_xml(&b);
		if (S_OK != hr)
			return hr;

		m_xml = b;
		::SysFreeString(b);

		if (0 == m_xml.length())
			return E_INVALIDARG;
	}
	else
	if (V_VT(&xmlSource) == (VT_ARRAY | VT_VARIANT)) {
		SAFEARRAY *pArray = reinterpret_cast<SAFEARRAY *> (xmlSource.byref);
		if (NULL == pArray)
			return E_INVALIDARG;

		long lLBoundVar = 0;
		long lUBoundVar = 0;
	
		UINT dims = ::SafeArrayGetDim(pArray);
		if (dims == 0)
			return E_INVALIDARG;
	
		hr = ::SafeArrayGetLBound(pArray, dims, &lLBoundVar);
		if (S_OK != hr)
			return hr;

		hr = ::SafeArrayGetUBound(pArray, dims, &lUBoundVar);
		if (S_OK != hr)
			return hr;

		if (lUBoundVar >= lLBoundVar) {
			VARIANT *pIndex = NULL;
			hr = ::SafeArrayAccessData(pArray, reinterpret_cast<void **> (&pIndex));
			if (S_OK != hr)
				return hr;

			int length = lUBoundVar-lLBoundVar+2;
			BYTE *body = new BYTE[length];
			for (long i = 0; i <= lUBoundVar-lLBoundVar; ++i) {	
				VARIANT var = pIndex[i];
				if (V_VT(&var) != VT_UI1) {
					hr = E_INVALIDARG;
					break;
				}
				body[i] = V_UI1(&var);
			}
			body[length-1] = 0;
					
			::SafeArrayUnaccessData(pArray);
			if (S_OK != hr) {
				delete [] body;
				return hr;
			}
			m_xml = reinterpret_cast<char*> (body);
			delete [] body;
			if (0 == m_xml.length())
				return E_INVALIDARG;
		}
	}	
	else
	if (V_VT(&xmlSource) == (VT_ARRAY | VT_UI1)) {
		SAFEARRAY *pArray = reinterpret_cast<SAFEARRAY *> (xmlSource.byref);
		if (NULL == pArray)
			return E_INVALIDARG;

		long lLBoundVar = 0;
		long lUBoundVar = 0;
	
		UINT dims = ::SafeArrayGetDim(pArray);
		if (dims == 0)
			return E_INVALIDARG;
	
		hr = ::SafeArrayGetLBound(pArray, dims, &lLBoundVar);
		if (S_OK != hr)
			return hr;

		hr = ::SafeArrayGetUBound(pArray, dims, &lUBoundVar);
		if (S_OK != hr)
			return hr;

		if (lUBoundVar >= lLBoundVar) {
			BYTE *pIndex = NULL;
			hr = ::SafeArrayAccessData(pArray, reinterpret_cast<void **> (&pIndex));
			if (S_OK != hr)
				return hr;

			int length = lUBoundVar-lLBoundVar+2;
			BYTE *body = new BYTE[length];
			for (long i = 0; i <= lUBoundVar-lLBoundVar; ++i)	
				body[i] = pIndex[i];
			
			body[length-1] = 0;
			::SafeArrayUnaccessData(pArray);
			m_xml = reinterpret_cast<char*> (body);
			delete [] body;
			if (0 == m_xml.length())
				return E_INVALIDARG;
		}
	}	

	UINT nthreadID = 0;
	m_hParseThread = reinterpret_cast<HANDLE> (_beginthreadex(NULL,
												 0,
											     CXMLDOMDocument::ParseThread,
												 (void *) this,
												 0,
												 &nthreadID));
	if (NULL == m_hParseThread)
		return S_OK;
	
	if (m_bAsync) {
		*isSuccessful = VARIANT_TRUE;
		return S_OK;
	}

	bool bWait = true;
	while (bWait) {
		DWORD dwEvt = MsgWaitForMultipleObjects(1,&m_hParseThread,FALSE,INFINITE,QS_ALLINPUT);
		switch(dwEvt) {
			case WAIT_OBJECT_0:
				bWait = false;
				break;
			case WAIT_OBJECT_0 + 1:
			{
				MSG msg;
				while(::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
					if (WM_CLOSE == msg.message || WM_QUIT == msg.message) {
						 bWait = false;
						 m_bAbort = true;
						 break;
					}
					else {
						PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
						TranslateMessage(&msg);
						DispatchMessage(&msg);
					}
				}
				break;
			}
			default:
				m_bAbort = true;
				bWait = false;
				break;
		}
	}

	if (m_bAbort)
		return S_OK;

	if (m_bParseError)
		return hr;

    if(m_Document)
        delete m_Document;
	m_Document = m_TmpDocument;
	m_TmpDocument = 0;
	
	m_url = m_FileName;
	*isSuccessful = VARIANT_TRUE;
	
	return hr;
}
Example #3
0
BOOL InterpretBSDLine(TCHAR *szLine, UINT uiStringLength, lFILEINFO *fileList)
{
    BOOL	bHashOK, bWasAbsolute = FALSE;
    int     iHashIndex = -1;

    FILEINFO fileinfoTmp = {0};
    fileinfoTmp.parentList=fileList;

    if(uiStringLength < 5)
        return FALSE;

    for(int i=0; i < NUM_HASH_TYPES; i++) {
        if(!_tcsncmp(szLine, g_hash_names[i], lstrlen(g_hash_names[i]))) {
            iHashIndex = i;
            break;
        }
    }
    if(iHashIndex<0)
        return FALSE;

    TCHAR *szFirstBrace = _tcschr(szLine, TEXT('('));
    TCHAR *szLastBrace = _tcsrchr(szLine, TEXT(')'));
    if(!szFirstBrace || !szLastBrace || szFirstBrace > szLastBrace)
        return FALSE;

    *szLastBrace = TEXT('\0');
    szLastBrace++;

    ReplaceChar(szFirstBrace + 1, MAX_PATH_EX, TEXT('/'), TEXT('\\'));
    bWasAbsolute = !ConstructCompleteFilename(fileinfoTmp.szFilename, fileList->g_szBasePath, szFirstBrace + 1);

    while(!IsLegalHexSymbol(*szLastBrace) && *szLastBrace != TEXT('\0') )
        szLastBrace++;

    UINT    uiHashLengthChars = g_hash_lengths[iHashIndex] * 2;

    if(lstrlen(szLastBrace) < (int)uiHashLengthChars)
        return FALSE;

    FILEINFO *fileInfo = &fileinfoTmp;
    bool alreadyInList = false;
    for(list<FILEINFO>::reverse_iterator it = fileList->fInfos.rbegin(); it != fileList->fInfos.rend(); it++) {
        if(it->szFilename == fileinfoTmp.szFilename) {
            fileInfo = &(*it);
            alreadyInList = true;
            break;
        }
    }

    if( IsLegalHexSymbol(*szLastBrace) ){
	    bHashOK = TRUE;
	    for(UINT uiIndex=0; uiIndex < uiHashLengthChars; ++uiIndex)
		    if(! IsLegalHexSymbol(szLastBrace[uiIndex]))
			    bHashOK = FALSE;
	    if(bHashOK){
		    fileInfo->hashInfo[iHashIndex].dwFound = TRUE;
            if(iHashIndex == HASH_TYPE_CRC32) {
                fileInfo->hashInfo[HASH_TYPE_CRC32].f.dwCrc32Found = HexToDword(szLastBrace, 8);
            } else {
		        for(UINT uiIndex=0; uiIndex < g_hash_lengths[iHashIndex]; ++uiIndex)
			        *((BYTE *)&fileInfo->hashInfo[iHashIndex].f + uiIndex) = (BYTE)HexToDword(szLastBrace + uiIndex * 2, 2);
            }
		    fileInfo->dwError = NOERROR;
	    }
	    else
		    fileInfo->dwError = APPL_ERROR_ILLEGAL_CRC;
        if(!alreadyInList)
	        fileList->fInfos.push_back(fileinfoTmp);
        fileList->bDoCalculate[iHashIndex] = true;
    }

    return bWasAbsolute;
}
Example #4
0
/** ini_puts()
 * \param Section     the name of the section to write the string in
 * \param Key         the name of the entry to write, or NULL to erase all keys in the section
 * \param Value       a pointer to the buffer the string, or NULL to erase the key
 * \param Filename    the name and full path of the .ini file to write to
 *
 * \return            1 if successful, otherwise 0
 */
int ini_puts(const TCHAR *Section, const TCHAR *Key, const TCHAR *Value, const TCHAR *Filename)
{
  INI_FILETYPE rfp;
  INI_FILETYPE wfp;
  INI_FILEPOS mark;
  TCHAR *sp, *ep;
  TCHAR LocalBuffer[INI_BUFFERSIZE];
  int len, match, flag, cachelen;

  assert(Filename != NULL);
  if (!ini_openread(Filename, &rfp)) {
    /* If the .ini file doesn't exist, make a new file */
    if (Key != NULL && Value != NULL) {
      if (!ini_openwrite(Filename, &wfp))
        return 0;
      writesection(LocalBuffer, Section, &wfp);
      writekey(LocalBuffer, Key, Value, &wfp);
      (void)ini_close(&wfp);
    } /* if */
    return 1;
  } /* if */

  /* If parameters Key and Value are valid (so this is not an "erase" request)
   * and the setting already exists and it already has the correct value, do
   * nothing. This early bail-out avoids rewriting the INI file for no reason.
   */
  if (Key != NULL && Value != NULL) {
    (void)ini_tell(&rfp, &mark);
    match = getkeystring(&rfp, Section, Key, -1, -1, LocalBuffer, sizearray(LocalBuffer));
    if (match && _tcscmp(LocalBuffer,Value) == 0) {
      (void)ini_close(&rfp);
      return 1;
    } /* if */
    /* key not found, or different value -> proceed (but rewind the input file first) */
    (void)ini_seek(&rfp, &mark);
  } /* if */

  /* Get a temporary file name to copy to. Use the existing name, but with
   * the last character set to a '~'.
   */
  ini_tempname(LocalBuffer, Filename, INI_BUFFERSIZE);
  if (!ini_openwrite(LocalBuffer, &wfp)) {
    (void)ini_close(&rfp);
    return 0;
  } /* if */
  (void)ini_tell(&rfp, &mark);
  cachelen = 0;

  /* Move through the file one line at a time until a section is
   * matched or until EOF. Copy to temp file as it is read.
   */
  len = (Section != NULL) ? _tcslen(Section) : 0;
  if (len > 0) {
    do {
      if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
        /* Failed to find section, so add one to the end */
        flag = cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
        if (Key!=NULL && Value!=NULL) {
          if (!flag)
            (void)ini_write(INI_LINETERM, &wfp);  /* force a new line behind the last line of the INI file */
          writesection(LocalBuffer, Section, &wfp);
          writekey(LocalBuffer, Key, Value, &wfp);
        } /* if */
        return close_rename(&rfp, &wfp, Filename, LocalBuffer);  /* clean up and rename */
      } /* if */
      /* Copy the line from source to dest, but not if this is the section that
       * we are looking for and this section must be removed
       */
      sp = skipleading(LocalBuffer);
      ep = _tcschr(sp, ']');
      match = (*sp == '[' && ep != NULL && (int)(ep-sp-1) == len && _tcsnicmp(sp + 1,Section,len) == 0);
      if (!match || Key != NULL) {
        if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) {
          cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
          (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
          cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
        } /* if */
      } /* if */
    } while (!match);
  } /* if */
  cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
  /* when deleting a section, the section head that was just found has not been
   * copied to the output file, but because this line was not "accumulated" in
   * the cache, the position in the input file was reset to the point just
   * before the section; this must now be skipped (again)
   */
  if (Key == NULL) {
    (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
    (void)ini_tell(&rfp, &mark);
  } /* if */

  /* Now that the section has been found, find the entry. Stop searching
   * upon leaving the section's area. Copy the file as it is read
   * and create an entry if one is not found.
   */
  len = (Key!=NULL) ? _tcslen(Key) : 0;
  for( ;; ) {
    if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
      /* EOF without an entry so make one */
      flag = cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
      if (Key!=NULL && Value!=NULL) {
        if (!flag)
          (void)ini_write(INI_LINETERM, &wfp);  /* force a new line behind the last line of the INI file */
        writekey(LocalBuffer, Key, Value, &wfp);
      } /* if */
      return close_rename(&rfp, &wfp, Filename, LocalBuffer);  /* clean up and rename */
    } /* if */
    sp = skipleading(LocalBuffer);
    ep = _tcschr(sp, '='); /* Parse out the equal sign */
    if (ep == NULL)
      ep = _tcschr(sp, ':');
    match = (ep != NULL && (int)(skiptrailing(ep,sp)-sp) == len && _tcsnicmp(sp,Key,len) == 0);
    if ((Key != NULL && match) || *sp == '[')
      break;  /* found the key, or found a new section */
    /* copy other keys in the section */
    if (Key == NULL) {
      (void)ini_tell(&rfp, &mark);  /* we are deleting the entire section, so update the read position */
    } else {
      if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) {
        cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
        (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
        cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
      } /* if */
    } /* if */
  } /* for */
  /* the key was found, or we just dropped on the next section (meaning that it
   * wasn't found); in both cases we need to write the key, but in the latter
   * case, we also need to write the line starting the new section after writing
   * the key
   */
  flag = (*sp == '[');
  cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
  if (Key != NULL && Value != NULL)
    writekey(LocalBuffer, Key, Value, &wfp);
  /* cache_flush() reset the "read pointer" to the start of the line with the
   * previous key or the new section; read it again (because writekey() destroyed
   * the buffer)
   */
  (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
  if (flag) {
    /* the new section heading needs to be copied to the output file */
    cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
  } else {
    /* forget the old key line */
    (void)ini_tell(&rfp, &mark);
  } /* if */
  /* Copy the rest of the INI file */
  while (ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
    if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) {
      cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
      (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp);
      cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE);
    } /* if */
  } /* while */
  cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark);
  return close_rename(&rfp, &wfp, Filename, LocalBuffer);  /* clean up and rename */
}
Example #5
0
HRESULT VariantChangeTypeSpecial(VARIANT* pvargDest, VARIANT* pVArg, VARTYPE vt, IServiceProvider* pSrvProvider/*=NULL*/, DWORD dwFlags/*=0*/)
{
    HRESULT hr;
    IVariantChangeType* pVarChangeType = NULL;

    if(pSrvProvider)
    {
        hr = pSrvProvider->QueryService(SID_VariantConversion,
            IID_IVariantChangeType, (void**)&pVarChangeType);
        if(hr)
        {
            goto OldWay;
        }

        // Use script engine conversion routine.
        hr = pVarChangeType->ChangeType(pvargDest, pVArg, 0, vt);

        if(!hr)
        {
            goto Cleanup; // ChangeType suceeded we're done...
        }
    }

    // Fall back to our tried & trusted type coercions
OldWay:
    hr = S_OK;

    if(vt==VT_BSTR && V_VT(pVArg)==VT_NULL)
    {
        // Converting a NULL to BSTR
        V_VT(pvargDest) = VT_BSTR;
        hr = FormsAllocString(_T("null"), &V_BSTR(pvargDest));
        goto Cleanup;
    }
    else if(vt==VT_BSTR && V_VT(pVArg)==VT_EMPTY)
    {
        // Converting "undefined" to BSTR
        V_VT(pvargDest) = VT_BSTR;
        hr = FormsAllocString(_T("undefined"), &V_BSTR(pvargDest));
        goto Cleanup;
    }
    else if(vt==VT_BOOL && V_VT(pVArg)==VT_BSTR)
    {
        // Converting from BSTR to BOOL
        // To match Navigator compatibility empty strings implies false when
        // assigned to a boolean type any other string implies true.
        V_VT(pvargDest) = VT_BOOL;
        V_BOOL(pvargDest) = FormsStringLen(V_BSTR(pVArg))==0 ? VARIANT_FALSE : VARIANT_TRUE;
        goto Cleanup;
    }
    else if(V_VT(pVArg)==VT_BOOL && vt==VT_BSTR)
    {
        // Converting from BOOL to BSTR
        // To match Nav we either get "true" or "false"
        V_VT(pvargDest) = VT_BSTR;
        hr = FormsAllocString(
            V_BOOL(pVArg)==VARIANT_TRUE?_T("true"):_T("false"),
            &V_BSTR(pvargDest));
        goto Cleanup;
    }
    // If we're converting R4 or R8 to a string then we need special handling to
    // map Nan and +/-Inf.
    else if(vt==VT_BSTR && (V_VT(pVArg)==VT_R8||V_VT(pVArg)==VT_R4))
    {
        double dblValue = V_VT(pVArg)==VT_R8 ? V_R8(pVArg) : (double)(V_R4(pVArg));

        // Infinity or NAN?
        if(!isFinite(dblValue))
        {
            if(isNAN(dblValue))
            {
                // NAN
                hr = FormsAllocStringW(_T("NaN"), &(V_BSTR(pvargDest)));
            }
            else
            {
                // Infinity
                hr = FormsAllocStringW((dblValue<0)?_T("-Infinity"):_T("Infinity"), &(V_BSTR(pvargDest)));
            }
        }
        else
        {
            goto DefaultConvert;
        }

        // Any error from allocating string?
        if(hr)
        {
            goto Cleanup;
        }

        V_VT(pvargDest) = vt;
        goto Cleanup;
    }

DefaultConvert:
    // Default VariantChangeTypeEx.

    // VARIANT_NOUSEROVERRIDE flag is undocumented flag that tells OLEAUT to convert to the lcid
    // given. Without it the conversion is done to user localeid
    hr = VariantChangeTypeEx(pvargDest, pVArg, LCID_SCRIPTING, dwFlags|VARIANT_NOUSEROVERRIDE, vt);

    if(hr == DISP_E_TYPEMISMATCH)
    {
        if(V_VT(pVArg) == VT_NULL)
        {
            hr = S_OK;
            switch(vt)
            {
            case VT_BOOL:
                V_BOOL(pvargDest) = VARIANT_FALSE;
                V_VT(pvargDest) = VT_BOOL;
                break;

                // For NS compatability - NS treats NULL args as 0
            default:
                V_I4(pvargDest)=0;
                break;
            }
        }
        else if(V_VT(pVArg) == VT_DISPATCH)
        {
            // Nav compatability - return the string [object] or null 
            V_VT(pvargDest) = VT_BSTR;
            hr = FormsAllocString((V_DISPATCH(pVArg))?_T("[object]"):_T("null"), &V_BSTR(pvargDest));
        }
        else if(V_VT(pVArg)==VT_BSTR &&
            (V_BSTR(pVArg) && ((V_BSTR(pVArg))[0]==_T('\0')) ||!V_BSTR(pVArg)) &&
            (vt==VT_I4 || vt==VT_I2 || vt==VT_UI2||vt==VT_UI4 
            || vt==VT_I8||vt==VT_UI8 || vt==VT_INT || vt==VT_UINT))
        {
            // Converting empty string to integer => Zero
            hr = S_OK;
            V_VT(pvargDest) = vt;
            V_I4(pvargDest) = 0;
            goto Cleanup;
        }
    }
    else if(hr==DISP_E_OVERFLOW && vt==VT_I4 && (V_VT(pVArg)==VT_R8 || V_VT(pVArg)==VT_R4))
    {
        // Nav compatability - return MAXLONG on overflow
        V_VT(pvargDest) = VT_I4;
        V_I4(pvargDest) = MAXLONG;
        hr = S_OK;
        goto Cleanup;
    }

    // To match Navigator change any scientific notation E to e.
    if(!hr && (vt==VT_BSTR && (V_VT(pVArg)==VT_R8 || V_VT(pVArg)==VT_R4)))
    {
        TCHAR* pENotation;

        pENotation = _tcschr(V_BSTR(pvargDest), _T('E'));
        if(pENotation)
        {
            *pENotation = _T('e');
        }
    }

Cleanup:
    ReleaseInterface(pVarChangeType);

    RRETURN(hr);
}
Example #6
0
ButtonLabel::Expanded
ButtonLabel::Expand(const TCHAR *text, TCHAR *buffer, size_t size)
{
  Expanded expanded;
  const TCHAR *dollar;

  if ((text == NULL) || (*text == _T('\0')) || (*text == _T(' '))) {
    expanded.visible = false;
    return expanded;
  } else if ((dollar = _tcschr(text, '$')) == NULL) {
    /* no macro, we can just translate the text */
    expanded.visible = true;
    expanded.enabled = true;
    const TCHAR *nl;
    if (((nl = _tcschr(text, '\n')) != NULL) && OnlyDigitsAndPunctuation(nl+1)) {
      /* Quick hack for skipping the translation for second line of a two line
         label with only digits and punctuation in the second line, e.g.
         for menu labels like "Config\n2/3" */

      /* copy the text up to the '\n' to a new buffer and translate it */
      TCHAR translatable[256];
      std::copy(text, nl, translatable);
      translatable[nl - text] = _T('\0');

      const TCHAR *translated = StringIsEmpty(translatable)
        ? _T("") : gettext(translatable);

      /* concatenate the translated text and the part starting with '\n' */
      _tcscpy(buffer, translated);
      _tcscat(buffer, nl);

      expanded.text = buffer;
    } else
      expanded.text = gettext(text);
    return expanded;
  } else {
    const TCHAR *macros = dollar;
    /* backtrack until the first non-whitespace character, because we
       don't want to translate whitespace between the text and the
       macro */
    while (macros > text && IsWhitespaceOrNull(macros[-1]))
      --macros;

    TCHAR s[100];
    expanded.enabled = !ExpandMacros(text, s, ARRAY_SIZE(s));
    if (s[0] == _T('\0') || s[0] == _T(' ')) {
      expanded.visible = false;
      return expanded;
    }

    /* copy the text (without trailing whitespace) to a new buffer and
       translate it */
    TCHAR translatable[256];
    std::copy(text, macros, translatable);
    translatable[macros - text] = _T('\0');

    const TCHAR *translated = StringIsEmpty(translatable)
      ? _T("") : gettext(translatable);

    /* concatenate the translated text and the macro output */
    _tcscpy(buffer, translated);
    _tcscat(buffer, s + (macros - text));

    expanded.visible = true;
    expanded.text = buffer;
    return expanded;
  }
}
Example #7
0
File: rp.cpp Project: biglad/WinUAE
int port_insert_custom (int inputmap_port, int devicetype, DWORD flags, const TCHAR *custom)
{
	const TCHAR *p = custom;
	int mode, *events, *axistable;
	int max, evtnum;
	int kb;
	const TCHAR **eventorder;

	eventorder = getcustomeventorder (&devicetype);
	if (!eventorder)
		return FALSE;

	kb = inputdevice_get_device_total (IDTYPE_JOYSTICK) + inputdevice_get_device_total (IDTYPE_MOUSE);

	inputdevice_updateconfig_internal (&changed_prefs);
	inputdevice_compa_prepare_custom (&changed_prefs, inputmap_port, devicetype);
	inputdevice_updateconfig_internal (&changed_prefs);
	max = inputdevice_get_compatibility_input (&changed_prefs, inputmap_port, &mode, &events, &axistable);
	write_log (_T("custom='%s' max=%d port=%d dt=%d kb=%d kbnum=%d\n"), custom, max, inputmap_port, devicetype, kb, inputdevice_get_device_total (IDTYPE_KEYBOARD));
	if (!max)
		return FALSE;

	while (p && p[0]) {
		int idx = -1, kc = -1;
		int flags = 0;
		int eventlen;

		const TCHAR *p2 = _tcschr (p, '=');
		if (!p2)
			break;
		const TCHAR *p4 = p;
		eventlen = -1;
		for (;;) {
			const TCHAR *p3 = _tcschr (p4, '.');
			if (!p3 || p3 >= p2) {
				p3 = NULL;
				if (eventlen < 0)
					eventlen = p2 - p;
				break;
			}
			if (eventlen < 0)
				eventlen = p3 - p;
			if (!_tcsnicmp (p3 + 1, L"autorepeat", 10))
				flags |= IDEV_MAPPED_AUTOFIRE_SET;
			p4 = p3 + 1;
		}
		
		for (int i = 0; eventorder[i]; i++) {
			if (_tcslen (eventorder[i]) == eventlen && !_tcsncmp (p, eventorder[i], eventlen)) {
				idx = i;
				break;
			}
		}
		p2++;
		if (p2[0] == '0' && (p2[1] == 'x' || p2[1] == 'X'))
			kc = _tcstol (p2 + 2, NULL, 16);
		else
			kc = _tstol (p2);
		p = _tcschr (p2, ' ');
		if (p)
			p++;

		if (idx < 0)
			continue;
		if (kc < 0)
			continue;

		evtnum = events[idx];

		write_log (_T("kb=%d evt=%d kc=%02x flags=%08x\n"), kb, evtnum, kc, flags);

		for (int j = 0; j < inputdevice_get_device_total (IDTYPE_KEYBOARD); j++) {
			int wdnum = -1;
			for (int i = 0; i < inputdevicefunc_keyboard.get_widget_num (j); i++) {
				uae_u32 kc2 = 0;
				inputdevicefunc_keyboard.get_widget_type (j, i, NULL, &kc2);
				if (kc == kc2) {
					wdnum = i;
					break;
				}
			}
			if (wdnum >= 0) {
				//write_log (_T("kb=%d (%s) wdnum=%d\n"), j, inputdevicefunc_keyboard.get_friendlyname (j), wdnum);
				inputdevice_set_gameports_mapping (&changed_prefs, kb + j, wdnum, evtnum, flags, inputmap_port);
				inputdevice_set_gameports_mapping (&currprefs, kb + j, wdnum, evtnum, flags, inputmap_port);
			} else {
				write_log (_T("kb=%d (%): keycode %02x not found!\n"), j, inputdevicefunc_keyboard.get_friendlyname (j), kc);
			}
		}
	}

	inputdevice_updateconfig_internal (&changed_prefs);
	inputdevice_updateconfig (&currprefs);
	return TRUE;
}
INT_PTR AddToList(WPARAM, LPARAM lParam)
{
	PROTOSEARCHRESULT *psr = (PROTOSEARCHRESULT *) lParam;
	DBVARIANT dbv;
	MCONTACT hContact;
	int sameurl = 0;
	int samename = 0;

	if (psr == NULL)
		return 0;
	if (psr->nick.t == NULL) {
		WErrorPopup((UINT_PTR)"ERROR", TranslateT("Please select site in Find/Add contacts..."));
		return 0;
	}   
	// if contact with the same ID was not found, add it
	if (psr->cbSize != sizeof(PROTOSEARCHRESULT))
		return NULL;
	// search for existing contact
	for (hContact = db_find_first(MODULENAME); hContact != NULL; hContact = db_find_next(hContact, MODULENAME)) {
		// check ID to see if the contact already exist in the database
		if (db_get_ts(hContact, MODULENAME, "URL", &dbv))
			continue;
		if (!mir_tstrcmpi(psr->nick.t, dbv.ptszVal)) {
			// remove the flag for not on list and hidden, thus make the
			// contact visible
			// and add them on the list
			sameurl ++;
			if (db_get_b(hContact, "CList", "NotOnList", 1)) {
				db_unset(hContact, "CList", "NotOnList");
				db_unset(hContact, "CList", "Hidden");
			}
		}
		db_free(&dbv);
	}

	hContact = (MCONTACT)CallService(MS_DB_CONTACT_ADD, 0, 0);
	Proto_AddToContact(hContact, MODULENAME);

	/////////write to db
	db_set_b(hContact, MODULENAME, ON_TOP_KEY, 0);
	db_set_b(hContact, MODULENAME, DBLE_WIN_KEY, 1);
	db_set_s(hContact, MODULENAME, END_STRING_KEY, "");
	db_set_b(hContact, MODULENAME, RWSPACE_KEY, 1);

	//Convert url into a name for contact
	TCHAR Cnick[255];
	if (psr->nick.t != NULL)
		_tcsncpy(Cnick, psr->nick.t, _countof(Cnick));
	else
		Cnick[0] = 0;

	TCHAR *Oldnick = _tcsstr(Cnick, _T("://"));
	if (Oldnick != 0)
		Oldnick += 3;
	else
		Oldnick = Cnick;

	TCHAR *Newnick = _tcsstr(Oldnick, _T("www."));
	if (Newnick != 0)
		Newnick += 4;
	else {
		Newnick = _tcsstr(Oldnick, _T("WWW."));
		if (Newnick != 0)
			Newnick += 4;
		else
			Newnick = Oldnick;
	}

	TCHAR *Nend = _tcschr(Newnick, '.');
	if (Nend) *Nend = '\0';

	for (MCONTACT hContact2 = db_find_first(MODULENAME); hContact2 != NULL; hContact2 = db_find_next(hContact2, MODULENAME)) {
		if (!db_get_ts(hContact2, MODULENAME, PRESERVE_NAME_KEY, &dbv)) {
			if (!mir_tstrcmpi(Newnick, dbv.ptszVal)) {
				// remove the flag for not on list and hidden, thus make the
				// contact visible
				// and add them on the list
				samename++;
				if (db_get_b(hContact2, "CList", "NotOnList", 1)) {
					db_unset(hContact2, "CList", "NotOnList");
					db_unset(hContact2, "CList", "Hidden");
				}
				db_free(&dbv);
			}
		}
		db_free(&dbv);
	}

	if ((sameurl > 0) || (samename > 0)) // contact has the same url or name as another contact, add rand num to name
	{
		srand((unsigned) time(NULL));
		
		TCHAR ranStr[10];
		_itot((int) 10000 *rand() / (RAND_MAX + 1.0), ranStr, 10);
		mir_tstrcat(Newnick, ranStr);
	}
	//end convert

	db_set_ts(hContact, "CList", "MyHandle", Newnick);
	db_set_ts(hContact, MODULENAME, PRESERVE_NAME_KEY, Newnick);
	db_set_ts(hContact, MODULENAME, "Nick", Newnick);
	db_set_b(hContact, MODULENAME, CLEAR_DISPLAY_KEY, 1);
	db_set_s(hContact, MODULENAME, START_STRING_KEY, "");
	db_set_ts(hContact, MODULENAME, URL_KEY, psr->nick.t);
	db_set_ts(hContact, MODULENAME, "Homepage", psr->nick.t);
	db_set_b(hContact, MODULENAME, U_ALLSITE_KEY, 1);
	db_set_w(hContact, MODULENAME, "Status", ID_STATUS_ONLINE);

	// ignore status change
	db_set_dw(hContact, "Ignore", "Mask", 8);

	Sleep(2);

	db_free(&dbv);


	return (INT_PTR)hContact;
}
Example #9
0
static int runmain (int argc, wchar_t *argv[])
{
	CONSOLE_SCREEN_BUFFER_INFO csbi;
	STARTUPINFO si;
	TCHAR *cmd, *parms2;
	int len, parmlen, i;
	HANDLE cp;
	HANDLE out_rd = NULL, out_wr = NULL, out_rd_tmp = NULL;
	HANDLE in_rd = NULL, in_wr = NULL, in_wr_tmp = NULL;
	HANDLE err_wr;
	DWORD tid;
	HANDLE thread;
	SECURITY_ATTRIBUTES sa;

	len = _tcslen (argv[0]);
	if (len < 4)
		return 0;
	cmd = (TCHAR*)malloc ((len + 4 + 1) * sizeof (TCHAR));
	_tcscpy (cmd, argv[0]);
	if (_tcsicmp (cmd + len - 4, _T(".com")))
		_tcscat (cmd + len, _T(".exe"));
	else
		_tcscpy (cmd + len - 4, _T(".exe"));

	parmlen = 0;
	for (i = 1; i < argc; i++) {
		if (parmlen > 0)
			parmlen ++;
		parmlen += 1 + _tcslen (argv[i]) + 1;
	}
	parms2 = (TCHAR*)malloc ((_tcslen (cmd) + 1 + parmlen + 1 + _tcslen (conpar) + 1) * sizeof (TCHAR));
	_tcscpy (parms2, cmd);
	_tcscat (parms2, _T(" "));
	_tcscat (parms2, conpar);
	for (i = 1; i < argc; i++) {
		int isspace = 0;
		_tcscat (parms2, _T(" "));
		if (_tcschr (argv[i], ' '))
			isspace = 1;
		if (isspace)
			_tcscat (parms2, _T("\""));
		_tcscat (parms2, argv[i]);
		if (isspace)
			_tcscat (parms2, _T("\""));
	}

	cp = GetCurrentProcess ();
	sa.nLength = sizeof sa;
	sa.bInheritHandle = TRUE;
	sa.lpSecurityDescriptor = NULL;

	stdout_save = GetStdHandle (STD_OUTPUT_HANDLE);
	stdin_save = GetStdHandle (STD_INPUT_HANDLE);
	stderr_save = GetStdHandle (STD_ERROR_HANDLE);

	//SetConsoleMode (stdin_save, ENABLE_PROCESSED_INPUT|ENABLE_LINE_INPUT|ENABLE_ECHO_INPUT|ENABLE_PROCESSED_OUTPUT);
	SetConsoleMode (stdin_save, ENABLE_PROCESSED_INPUT|ENABLE_PROCESSED_OUTPUT);
	SetConsoleCP (65001);
	SetConsoleOutputCP (65001);
	if (GetConsoleScreenBufferInfo (stdout_save, &csbi)) {
		if (csbi.dwMaximumWindowSize.Y < 900) {
			csbi.dwMaximumWindowSize.Y = 900;
			SetConsoleScreenBufferSize (stdout_save, csbi.dwMaximumWindowSize);
		}
	}

	CreatePipe (&out_rd_tmp, &out_wr, &sa, 0);
	CreatePipe (&in_rd, &in_wr_tmp, &sa, 0);

	DuplicateHandle (cp, out_wr, cp, &err_wr, 0, TRUE, DUPLICATE_SAME_ACCESS);
	DuplicateHandle (cp, out_rd_tmp, cp, &out_rd, 0, FALSE, DUPLICATE_SAME_ACCESS);
	DuplicateHandle (cp, in_wr_tmp, cp, &in_wr, 0, FALSE, DUPLICATE_SAME_ACCESS);

	CloseHandle (out_rd_tmp);
	CloseHandle (in_wr_tmp);

	memset (&si, 0, sizeof si);
	si.cb = sizeof si;
	si.dwFlags = STARTF_USESTDHANDLES;
	si.hStdInput = in_rd;
	si.hStdOutput = out_wr;
	si.hStdError = err_wr;

	SetConsoleCtrlHandler (&ctrlhandler, TRUE);

	if (!CreateProcess (cmd, parms2,
		NULL, NULL, TRUE,
		CREATE_SUSPENDED | CREATE_NEW_CONSOLE | GetPriorityClass (GetCurrentProcess ()),
		NULL, NULL, &si, &pi)) {
			_tprintf (_T("CreateProcess(%s) failed\n"), cmd);
			goto end;
	}

	CloseHandle (out_wr);
	CloseHandle (in_rd);
	CloseHandle (err_wr);

	thread = CreateThread (NULL, 0, pipethread, (LPVOID)in_wr, 0, &tid);

	ResumeThread (pi.hThread);

	HandleOutput (out_rd);
	runthread = 0;
	CloseHandle (stdin_save);
	WaitForSingleObject (thread, INFINITE);

	CloseHandle (out_rd);
	CloseHandle (in_wr);

	CloseHandle (pi.hProcess);
	CloseHandle (pi.hThread);
end:
	free (parms2);
	free (cmd);
	return 0;
}
// <TAG attr1="value1" attr2='value2' attr3=value3 >
// </TAG>
// or
// <TAG />
//        ^- return pointer
//========================================================
// Desc   : load xml plain text
// Param  : pszXml - plain xml text
//          pi = parser information
// Return : advanced std::string pointer 
//========================================================
char* _tagXMLNode::load( const char* pszXml, LPPARSEINFO pi /*= &piDefault*/ )
{
	char* xml = (char*)pszXml;

	// initilize 
	parent = NULL;
	childs.clear();
	attrs.clear();

	xml = _tcschr( xml, chXMLTagOpen );
	if( xml == NULL )
		return xml;

	// Close Tag
	if( *(xml+1) == chXMLTagPre ) // </Close
		return xml;

	// XML Node Tag Name Open
	xml++;
	char* pTagEnd = _tcspbrk( xml, " />" );
	_Setstring( xml, pTagEnd, &name );
	xml = pTagEnd;
	// Generate XML Attributte List
	if( xml = loadAttributes( xml, pi ) )
	{
		// alone tag <TAG ... />
		if( *xml == chXMLTagPre )
		{
			xml++;
			if( *xml == chXMLTagClose )
				// wel-formed tag
				return ++xml;
			else
			{
				// error: <TAG ... / >
				if( pi->erorr_occur == false ) 
				{
					pi->erorr_occur = true;
					pi->error_pointer = xml;
					pi->error_code = PIE_ALONE_NOT_CLOSED;
					pi->error_string = "Element must be closed.";
				}
				// not wel-formed tag
				return xml;
			}
		}
		else
			// open/close tag <TAG ..> ... </TAG>
			//                        ^- current pointer
		{
			// insert if no text value
			if( this->value.empty() )
			{
				// Text Value 
				char* pEnd = _tcsechr( ++xml, chXMLTagOpen, chXMLEscape );
				if( pEnd == NULL ) 
				{
					if( pi->erorr_occur == false ) 
					{
						pi->erorr_occur = true;
						pi->error_pointer = xml;
						pi->error_code = PIE_NOT_CLOSED;
						pi->error_string = "%s must be closed with </%s>", name;
						pi->error_string += name;
					}
					// error cos not exist CloseTag </TAG>
					return xml;
				}

				bool trim = pi->trim_value;
				_Setstring( xml, pEnd, &value, trim, chXMLEscape );
				xml = pEnd;
				// TEXTVALUE reference
				if( pi->entity_value && pi->entitys )
					value = pi->entitys->ref2Entity(value.c_str());
			}

			// generate child nodes
			while( xml && *xml )
			{
				LPXNode node = new XNode;
				node->parent = this;

				xml = node->load( xml,pi );
				if( node->name.empty() == FALSE )
				{
					std::transform(	node->name.begin(), node->name.end(),	node->name.begin(), static_cast<int(*)(int)>(::tolower) );
					//node->name.MakeLower();
					childs.push_back( node );
				}
				else
				{
					delete node;
				}

				// open/close tag <TAG ..> ... </TAG>
				//                             ^- current pointer
				// CloseTag case
				if( xml && *xml && *(xml+1) && *xml == chXMLTagOpen && *(xml+1) == chXMLTagPre )
				{
					// </Close>
					xml+=2; // C

					if( xml = _tcsskip( xml ) )
					{
						std::string closename;
						char* pEnd = _tcspbrk( xml, " >" );
						if( pEnd == NULL ) 
						{
							if( pi->erorr_occur == false ) 
							{
								pi->erorr_occur = true;
								pi->error_pointer = xml;
								pi->error_code = PIE_NOT_CLOSED;
								pi->error_string = "it must be closed with";
								pi->error_string += name;
							}
							// error
							return xml;
						}
						_Setstring( xml, pEnd, &closename );
						if( closename == this->name )
						{
							// wel-formed open/close
							xml = pEnd+1;
							// return '>' or ' ' after pointer
							return xml;
						}
						else
						{
							xml = pEnd+1;
							// not welformed open/close
							if( pi->erorr_occur == false ) 
							{
								pi->erorr_occur = true;
								pi->error_pointer = xml;
								pi->error_code = PIE_NOT_NESTED;
								pi->error_string = name + "..." + closename + " is not wel-formed.";
							}
							return xml;
						}
					}
				}
				else	// Alone child Tag Loaded
				{

					if( xml && this->value.empty() && *xml !=chXMLTagOpen )
					{
						// Text Value 
						char* pEnd = _tcsechr( xml, chXMLTagOpen, chXMLEscape );
						if( pEnd == NULL ) 
						{
							// error cos not exist CloseTag </TAG>
							if( pi->erorr_occur == false )  
							{
								pi->erorr_occur = true;
								pi->error_pointer = xml;
								pi->error_code = PIE_NOT_CLOSED;
								pi->error_string = "it must be closed with"+ name;
							}
							return xml;
						}

						bool trim = pi->trim_value;
						_Setstring( xml, pEnd, &value, trim, chXMLEscape );
						xml = pEnd;
						//TEXTVALUE
						if( pi->entity_value && pi->entitys )
							value = pi->entitys->ref2Entity(value.c_str());
					}
				}
			}
		}
	}

	return xml;
}
int DBSettingChanged(WPARAM wParam, LPARAM lParam)
{
	// We can't upload changes to NULL contact
	MCONTACT hContact = wParam;
	if (hContact == NULL)
		return 0;

	DBCONTACTWRITESETTING *cws = (DBCONTACTWRITESETTING *) lParam;
	if (!mir_strcmp(cws->szModule, "CList")) {
		int invalidpresent = 0;

		char *szProto = GetContactProto(hContact);
		if (szProto == NULL || mir_strcmp(szProto, MODULENAME))
			return 0;

		// A contact is renamed
		if (!mir_strcmp(cws->szSetting, "MyHandle")) {
			ptrT oldName( db_get_tsa(hContact, MODULENAME, PRESERVE_NAME_KEY));
			if (oldName == NULL)
				return 0;

			TCHAR nick[100];
			ptrT oldnick( db_get_tsa(hContact, "CList", "MyHandle"));
			if (oldnick != NULL)
				_tcsncpy_s(nick, oldnick, _TRUNCATE);
			else
				nick[0] = 0;

			for (int i=0; i < _countof(szInvalidChars); i++ ) {
				TCHAR *p = _tcschr(nick, szInvalidChars[i]);
				if (p != NULL) {
					WErrorPopup((UINT_PTR)"ERROR", TranslateT("Invalid symbol present in contact name."));
					*p = '_';
					invalidpresent =1;
				}
			}

			if (invalidpresent) {
				srand((unsigned)time(NULL));
				TCHAR ranStr[7];
				_itot((int)10000 *rand() / (RAND_MAX + 1.0), ranStr, 10);
				mir_tstrcat(nick, ranStr); 
			}  

			if ( _tcschr(nick, '(') == 0) {
				db_set_ts(hContact, MODULENAME, PRESERVE_NAME_KEY, nick);
				db_set_ts(hContact, MODULENAME, "Nick", nick);
				db_set_ts(hContact, "CList", "MyHandle", nick);
			}

			// TEST GET NAME FOR CACHE
			TCHAR cachepath[MAX_PATH], cachedirectorypath[MAX_PATH];
			GetModuleFileName(hInst, cachepath, _countof(cachepath));
			TCHAR *cacheend = _tcsrchr(cachepath, '\\');
			cacheend++;
			*cacheend = '\0';
			mir_sntprintf(cachedirectorypath, _T("%s")_T(MODULENAME)_T("cache\\"), cachepath);
			CreateDirectory(cachedirectorypath, NULL);

			TCHAR newcachepath[MAX_PATH + 50], renamedcachepath[MAX_PATH + 50];
			mir_sntprintf(newcachepath, _T("%s")_T(MODULENAME)_T("cache\\%s.txt"), cachepath, oldName);
			mir_sntprintf(renamedcachepath, _T("%s")_T(MODULENAME)_T("cache\\%s.txt"), cachepath, nick);

			// file exists?
			if ( _taccess(newcachepath, 0) != -1) {
				FILE *pcachefile = _tfopen(newcachepath, _T("r"));
				if (pcachefile != NULL) {
					fclose(pcachefile);
					if (mir_tstrcmp(newcachepath, renamedcachepath)) {
						MoveFile(newcachepath, renamedcachepath);
						db_set_ts(hContact, MODULENAME, CACHE_FILE_KEY, renamedcachepath);
					}
				}
			}
		}
	}
	return 0;
}
Example #12
0
int _tmain(int argc, TCHAR** argv)
{
	int iFirstParam = 1;

	// Turn on the "termination on heap corruption" flag.
	(void)HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);

	// generate output for HTML Help format
	BOOL fHTMLFormat = FALSE;

	// <include.h> filename to be copied
	const TCHAR *pszIncludeFilename = NULL;

	// additional include path
	const TCHAR *pszIncludePath = NULL;

	if( argc > 1 && _tcsicmp(argv[1], _T("/h")) == 0 )
	{
		fHTMLFormat = TRUE;
		iFirstParam++;

		if( ( argc > 3 ) && _tcsicmp(argv[2], _T("/a")) == 0 ) // copy file operation
		{
			pszIncludeFilename = argv[3];
			iFirstParam += 2;

			if( argc > 5 && _tcsicmp(argv[4], _T("/i")) == 0 )
			{
				pszIncludePath = argv[5];
				iFirstParam += 2;
			}
		}
	}

	// add symbol mappings to the map.
	BOOL fAddedToMap = FALSE;
	int i;
	for (i = iFirstParam; i < argc && _tcschr(argv[i], _T(',')) != NULL; i++)
	{
		AddToMap(argv[i]);
		fAddedToMap = TRUE;
	}

	// must only have 1-2 parms left on command line.
	if (!fAddedToMap || i < argc-2 || i > argc-1)
	{
		UsageErr(NULL, NULL);
		ASSERT(FALSE);
	}

	// open input file.
	CLineFile fileIn;
	fileIn.SafeOpen(argv[i], CLineFile::modeRead);

	// open/hook up output file.
	CLineFile fileOut;
	if (i+1 < argc)
		fileOut.SafeOpen(argv[i+1], CLineFile::modeWrite | CLineFile::modeCreate);
	else
		fileOut.m_pStream = stdout;

	// process the file.
	CString strLine;
	while (fileIn.ReadLine(strLine))
	{
		if (MapLine(strLine, fHTMLFormat))
		{
			fileOut.WriteLine(strLine);
		}
	}

	// close input file.
	fileIn.Close();

	if( pszIncludeFilename != NULL )
	{
		CString strIncludeFilePath = FindIncludeFile( pszIncludeFilename, pszIncludePath );
		if( strIncludeFilePath.IsEmpty() )
		{
			_ftprintf(stderr, _T("Error: Additional include file %s not found\n\n"), pszIncludeFilename );
			fileOut.Close();
			exit(1);
		}

		fileIn.SafeOpen(strIncludeFilePath, CLineFile::modeRead);

		while (fileIn.ReadLine(strLine))
		{
			fileOut.WriteLine(strLine);
		}
	}

	// close output file.
	fileOut.Close();

	return 0;
}
Example #13
0
void
processLine(
    char *s,
    unsigned *count,
    char **vector[]
    )
{
    char *t;
    char *u;
    size_t m;
    size_t n;
    BOOL allocFlag = FALSE;

    if (!(t = _tcschr(s,'"'))) {            // no quoted strings,
        tokenizeLine(s,count,vector);       // just standard fare
    } else {
        // There are two kinds of situations in which quotes can occur:
        //   1. "FOO = bar baz"
        //   2. FOO="bar baz"

        if ((t == s) || (*(t-1) != '='))  {
            // Case 1 above
            *t++ = '\0';                    // quoted macrodef
            tokenizeLine(s,count,vector);   // get tokens before "
        } else {
            // Case 2 above
            *t-- = ' ';
            for (u = t; u > s; --u) //    find the beginning of the macro name
                if (*u == ' ' || *u == '\t' || *u == '\n')
                    break;

            if (u != s) {
                *u++ = '\0';
                tokenizeLine(s, count, vector);
            }

            t = u;
        }

        n = _tcslen(t);
        for (u = t; *u; ++u) {              // look for closing "
            if (*u == '"') {                // need " and not ""
                if (*(u+1) == '"') {
                    _tcscpy(u,u+1);
                    continue;
                }
                *u++ = '\0';                // terminate macrodef
                addArgument(t,*count,vector);   // treat as one arg
                ++*count;
                processLine(u+1,count,vector);  // recurse on rest of line
                break;
            }                       // TAIL RECURSION                                  

            if ((*u == '\\')
                && WHITESPACE(*(u-1))
                && (*(u+1) == '\n')) {      // \n always last char
                *u = '\0';                  // 2 chars go to 1
                m = (n = n-2);              // adjust length count
                if (!allocFlag) {
                    allocFlag = TRUE;
                    t = makeString(t);
                }
                getRestOfLine(&t,&n);       // get some more text
                u = t + m ;                 // reset u & continue looping
            }
        }

        if (u == t + n) {                   // if at end of line
            makeError(0,SYNTAX_NO_QUOTE);   // and no ", error
        }

        if (allocFlag) {
            FREE(t);
        }
    }
}
Example #14
0
File: main.cpp Project: mega-t72/vc
bool translate(_TCHAR**lpszInput,size_t ilen,int*marker,LPCTSTR lpszFormat,...){
	FILE file;
	va_list args;
	//
	file._flag	= _IOREAD|_IOSTRG|_IOMYBUF;
	file._ptr	= file._base = (char*)(*lpszInput);
	file._cnt	= (int)ilen * sizeof(**lpszInput);
	//
	*marker		= -1;
	//
	va_start(args,lpszFormat);
#if defined(_UNICODE)
	if( (_winput_s_l(&file,lpszFormat,NULL,args) >= 0) && (*marker >= 0) ){
#else
	if( (_input_s_l(&file,(const unsigned char*)lpszFormat,NULL,args) >= 0) && (*marker >= 0) ){
#endif
		*lpszInput	= ( (_TCHAR*)file._ptr ) - 1;
		va_end(args);
		return true;
	}
	va_end(args);
	return false;
}
int _tmain(int argc, _TCHAR* argv[]){
	_TCHAR szINI[MAX_PATH];
	_TCHAR mode[64];
	LARGE_INTEGER version;
	LPTSTR lpszInput,lpszOutput,lpszINI,lpszBuffer,lpCh,lpCCs;
	FILE*output,*input;
	size_t i,len,ilen,std_out,hidden;
	errno_t err;
	long bomlen;
	int line,marker;
	unsigned int x;
	_TCHAR ccs;
	//
	if( argc < 4 ){
		return usage();
	}
	//
	lpszINI		= argv[argc - 3];
	lpszInput	= argv[argc - 2];
	lpszOutput	= argv[argc - 1];
	//
	if( ::GetFileAttributes(lpszInput) == INVALID_FILE_ATTRIBUTES ){
		return usage();
	}
	//
	for(ccs	= _T('a'),i = argc - 4;i--;){
		lpCh	= argv[i + 1];
		if( !_tcschr(_T("-/"),*lpCh) )continue;
		for(len = 0; *lpCh ;++len,++lpCh);
		if( !len )continue;
		for(--lpCh; len-- && !_tcschr(_T("aUue"),*lpCh) ; --lpCh);
		if( !++len )continue;
		ccs	= *lpCh;
		break;
	}
	switch( ccs ){
		case _T('a'):{
			lpCCs	= _T("");
			break;
		}
		case _T('U'):{
			lpCCs	= _T(", ccs=UNICODE");
			break;
		}
		case _T('u'):{
			lpCCs	= _T(", ccs=UTF-8");
			break;
		}
		case _T('e'):{
			lpCCs	= _T(", ccs=UTF-16LE");
			break;
		}
	}
	_stprintf_s(mode,_T("rt%s"),lpCCs);
	if( err = _tfopen_s(&input,lpszInput,mode) ){
		lc_print(_T(".866"),_T("\r\nошибка при открытии файла-шаблона\r\n"));
		return usage();
	}
	_stprintf_s(mode,_T("wt%s"),lpCCs);
	if( err = _tfopen_s(&output,lpszOutput,mode) ){
		lc_print(_T(".866"),_T("\r\nошибка при создании выходного файла\r\n"));
		fclose(input);
		return usage();
	}
	//
	bomlen	= ftell(input);
	for(len = 0; !feof(input) ;_fgettc(input),++len);
	lpszBuffer		= (LPTSTR)malloc( (len + 1) * sizeof(_TCHAR) );
	lpszBuffer[len]	= _T('\0');
	fseek(input,bomlen,SEEK_SET);
	for(lpCh = lpszBuffer; !feof(input) ;*(lpCh++) = _fgettc(input));
	fclose(input);
	//
	::GetFullPathName(lpszINI,sizeof(szINI) / sizeof(_TCHAR),szINI,NULL);
	version.LowPart		= ::GetPrivateProfileInt(_T("general"),_T("low"),0x00000000,szINI);
	version.HighPart	= ::GetPrivateProfileInt(_T("general"),_T("high"),0x00000000,szINI);
	//
	for(line = 1,hidden = 0,std_out = 0,lpCh = lpszBuffer; *lpCh ;++lpCh){
		switch( *lpCh ){
			case _T('\n'):{
				++line;
				break;
			}
			case _T('%'):{
				if( lpCh[1] == _T('%') ){
					++lpCh;
				}else{
					ilen	= len - (lpCh - lpszBuffer);
					if( translate(&lpCh,ilen,&marker,_T("%%<*%n"),&marker) ){
						++hidden;
						continue;
					}
					if( translate(&lpCh,ilen,&marker,_T("%%*>%n"),&marker) ){
						--hidden;
						continue;
					}
					if( translate(&lpCh,ilen,&marker,_T("%%<<%n"),&marker) ){
						++std_out;
						continue;
					}
					if( translate(&lpCh,ilen,&marker,_T("%%>>%n"),&marker) ){
						--std_out;
						continue;
					}
					if( translate(&lpCh,ilen,&marker,_T("%%qw++%n"),&marker) ){
						if( !hidden ){
							_ftprintf(output,_T("%I64u"),version.QuadPart);
						}
						if( std_out ){
							_ftprintf(stdout,_T("%I64u"),version.QuadPart);
						}
						++version.QuadPart;
						continue;
					}
					if( translate(&lpCh,ilen,&marker,_T("%%++qw%n"),&marker) ){
						++version.QuadPart;
						if( !hidden ){
							_ftprintf(output,_T("%I64u"),version.QuadPart);
						}
						if( std_out ){
							_ftprintf(stdout,_T("%I64u"),version.QuadPart);
						}
						continue;
					}
					if( translate(&lpCh,ilen,&marker,_T("%%qw%n"),&marker) ){
						if( !hidden ){
							_ftprintf(output,_T("%I64u"),version.QuadPart);
						}
						if( std_out ){
							_ftprintf(stdout,_T("%I64u"),version.QuadPart);
						}
						continue;
					}
					if( translate(&lpCh,ilen,&marker,_T("%%dw.%u++%n"),&x,&marker) ){
						if(x > 1){
							fclose(output);
							return out_of_range(lpszInput,line);
						}
						DWORD&value	= ((LPDWORD)&version.LowPart)[x];
						if( !hidden ){
							_ftprintf(output,_T("%I32u"),value);
						}
						if( std_out ){
							_ftprintf(stdout,_T("%I32u"),value);
						}
						++value;
						continue;
					}
					if( translate(&lpCh,ilen,&marker,_T("%%++dw.%u%n"),&x,&marker) ){
						if(x > 1){
							fclose(output);
							return out_of_range(lpszInput,line);
						}
						DWORD&value	= ((LPDWORD)&version.LowPart)[x];
						++value;
						if( !hidden ){
							_ftprintf(output,_T("%I32u"),value);
						}
						if( std_out ){
							_ftprintf(stdout,_T("%I32u"),value);
						}
						continue;
					}
					if( translate(&lpCh,ilen,&marker,_T("%%dw.%u%n"),&x,&marker) ){
						if(x > 1){
							fclose(output);
							return out_of_range(lpszInput,line);
						}
						DWORD&value	= ((LPDWORD)&version.LowPart)[x];
						if( !hidden ){
							_ftprintf(output,_T("%I32u"),value);
						}
						if( std_out ){
							_ftprintf(stdout,_T("%I32u"),value);
						}
						continue;
					}
					if( translate(&lpCh,ilen,&marker,_T("%%w.%u++%n"),&x,&marker) ){
						if(x > 3){
							fclose(output);
							return out_of_range(lpszInput,line);
						}
						WORD&value	= ((LPWORD)&version.LowPart)[x];
						if( !hidden ){
							_ftprintf(output,_T("%hu"),value);
						}
						if( std_out ){
							_ftprintf(stdout,_T("%hu"),value);
						}
						++value;
						continue;
					}
					if( translate(&lpCh,ilen,&marker,_T("%%++w.%u%n"),&x,&marker) ){
						if(x > 3){
							fclose(output);
							return out_of_range(lpszInput,line);
						}
						WORD&value	= ((LPWORD)&version.LowPart)[x];
						++value;
						if( !hidden ){
							_ftprintf(output,_T("%hu"),value);
						}
						if( std_out ){
							_ftprintf(stdout,_T("%hu"),value);
						}
						continue;
					}
					if( translate(&lpCh,ilen,&marker,_T("%%w.%u%n"),&x,&marker) ){
						if(x > 3){
							fclose(output);
							return out_of_range(lpszInput,line);
						}
						WORD&value	= ((LPWORD)&version.LowPart)[x];
						if( !hidden ){
							_ftprintf(output,_T("%hu"),value);
						}
						if( std_out ){
							_ftprintf(stdout,_T("%hu"),value);
						}
						continue;
					}
					if( translate(&lpCh,ilen,&marker,_T("%%b.%u++%n"),&x,&marker) ){
						if(x > 7){
							fclose(output);
							return out_of_range(lpszInput,line);
						}
						BYTE&value	= ((LPBYTE)&version.LowPart)[x];
						if( !hidden ){
							_ftprintf(output,_T("%hu"),(WORD)value);
						}
						if( std_out ){
							_ftprintf(stdout,_T("%hu"),(WORD)value);
						}
						++value;
						continue;
					}
					if( translate(&lpCh,ilen,&marker,_T("%%++b.%u%n"),&x,&marker) ){
						if(x > 7){
							fclose(output);
							return out_of_range(lpszInput,line);
						}
						BYTE&value	= ((LPBYTE)&version.LowPart)[x];
						++value;
						if( !hidden ){
							_ftprintf(output,_T("%hu"),(WORD)value);
						}
						if( std_out ){
							_ftprintf(stdout,_T("%hu"),(WORD)value);
						}
						continue;
					}
					if( translate(&lpCh,ilen,&marker,_T("%%b.%u%n"),&x,&marker) ){
						if(x > 7){
							fclose(output);
							return out_of_range(lpszInput,line);
						}
						BYTE&value	= ((LPBYTE)&version.LowPart)[x];
						if( !hidden ){
							_ftprintf(output,_T("%hu"),(WORD)value);
						}
						if( std_out ){
							_ftprintf(stdout,_T("%hu"),(WORD)value);
						}
						continue;
					}
				}
			}
		}
		if( !hidden ){
			_fputtc(*lpCh,output);
		}
		if(std_out){
			if( _tcschr(_T("Uue"),ccs) ){
				lc_print(_T(".OCP"),_T("%c"),*lpCh);
			}else{
				oem_print(_T("%c"),*lpCh);
			}
		}
	}
	free(lpszBuffer);
	fclose(output);
	//
	for(i = argc - 4;i--;){
		lpCh	= argv[i + 1];
		if( _tcschr(_T("-/"),*lpCh) ){
			if( _tcschr(lpCh + 1,_T('r')) ){
				break;
			}
		}
	}
	if( !(i + 1) ){
		_stprintf_s(mode,_T("%#.8x"),version.LowPart);
		::WritePrivateProfileString(_T("general"),_T("low"),mode,szINI);
		_stprintf_s(mode,_T("%#.8x"),version.HighPart);
		::WritePrivateProfileString(_T("general"),_T("high"),mode,szINI);
	}
	//
	return S_OK;
}
void CLangData::EnumAttributesCallback(bool bGroup, const tchar_t* pszName, const tchar_t* pszValue, ptr_t pData)
{
	CLangData* pLangData = (CLangData*)pData;
	assert(pLangData);
	assert(pszName);
	if(!pLangData || !pszName)
		return;

	if(bGroup && _tcsicmp(pszName, _t("Info")) == 0)
		return;
	if(bGroup)
	{
		// new section - remember in member
		pLangData->m_uiSectionID = _ttoi(pszName);
	}
	else
	{
		uint_t uiID = 0;
		uint_t uiChecksum = 0;

		// parse the pszName to get both the string id and checksum
		const tchar_t* pszChecksum = _tcschr(pszName, _T('['));
		if(pszChecksum == NULL)
		{
			TRACE(_T("Warning! Old-style translation string %s.\n"), pszName);

			int iCount = _stscanf(pszName, UIFMT, &uiID);
			if(iCount != 1)
			{
				TRACE(_T("Warning! Problem retrieving id from string '%s'\n"), pszName);
				return;
			}
		}
		else
		{
			int iCount = _stscanf(pszName, UIFMT _T("[0x%lx]"), &uiID, &uiChecksum);
			if(iCount != 2)
			{
				TRACE(_T("Warning! Problem retrieving id/checksum from string '%s'\n"), pszName);
				return;
			}
		}

		uint_t uiKey = pLangData->m_uiSectionID << 16 | uiID;
		translation_map::iterator itTranslation = pLangData->m_mapTranslation.end();
		if(pLangData->m_bUpdating)
		{
			// check if the checksum exists and matches
			itTranslation = pLangData->m_mapTranslation.find(uiKey);
			if(itTranslation == pLangData->m_mapTranslation.end())
			{
				TRACE(_T("Warning! Superfluous entry %lu in processed language file\n"), uiKey);
				return;		// entry not found - probably superfluous entry in the language file
			}

			if((*itTranslation).second.GetChecksum() != uiChecksum)
			{
				TRACE(_T("Warning! Invalid checksum for string ID %lu in processed language file\n"), uiKey);
				return;		// entry has invalid checksum (older version of translation)
			}
		}
		else
		{
			std::pair<translation_map::iterator, bool> pairTranslation = pLangData->m_mapTranslation.insert(translation_map::value_type(uiKey, CTranslationItem()));
			itTranslation = pairTranslation.first;
		}

		assert(itTranslation != pLangData->m_mapTranslation.end());
		if(itTranslation != pLangData->m_mapTranslation.end())
		{
			(*itTranslation).second.SetText(pszValue, true);
			if(!pLangData->m_bUpdating)
				(*itTranslation).second.SetChecksum(uiChecksum);
		}
	}
}
Example #16
0
//内核配置
bool __cdecl CClientKernel::InitClientKernel(LPCTSTR lpszComLine, IUnknownEx * pIUnknownEx)
{
	//效验参数
	ASSERT(lpszComLine!=NULL);
	if (lpszComLine==NULL) return false;

	//创建窗口
	if (m_hWnd==NULL) 
	{
		CRect rcCreate(0,0,0,0);
		Create(NULL,NULL,WS_CHILD,rcCreate,GetDesktopWindow(),100);
	}

	//获取框架
	m_pIClientKernelSink=GET_OBJECTPTR_INTERFACE(pIUnknownEx,IClientKernelSink);
	if (m_pIClientKernelSink==NULL) return false;
	m_hWndGameFrame=m_pIClientKernelSink->GetFrameWnd();

	//读取配置
	m_bAllowUserLookon=AfxGetApp()->GetProfileInt(TEXT("GameOption"),TEXT("AllowLookon"),FALSE)?true:false;

	//视频设置
	CVideoServiceManager * pVideoServiceManager=CVideoServiceManager::GetInstance();
	if (pVideoServiceManager!=NULL) pVideoServiceManager->SetClientKernel(GET_OBJECTPTR_INTERFACE(this,IUnknownEx));

	//命令行处理
	if (lpszComLine[0]!=0)
	{
		//提出 TOKEN
		int nStringLength=0;
		CString strRoomToken;
		LPCTSTR pszRoomToken=TEXT("/RoomToken:");
		LPCTSTR lpszBeginString=lpszComLine;
		while (true)
		{
			LPCTSTR lpszEndString=_tcschr(lpszBeginString,TEXT(' '));
			nStringLength=(lpszEndString==NULL)?lstrlen(lpszBeginString):(int)(lpszEndString-lpszBeginString);

			//判断标识
			const int nTokenLength=lstrlen(pszRoomToken);
			if ((nStringLength>=nTokenLength)&&(memcmp(lpszBeginString,pszRoomToken,nTokenLength*sizeof(TCHAR))==0))
			{
				CopyMemory(strRoomToken.GetBufferSetLength(nStringLength-nTokenLength),lpszBeginString+nTokenLength,
					(nStringLength-nTokenLength)*sizeof(TCHAR));
				strRoomToken.ReleaseBuffer();
				break;
			}

			//设置变量
			if (lpszEndString==NULL) break;
			lpszBeginString=(lpszEndString+1);
		}

		//共享内存
		if (strRoomToken.GetLength()>0)
		{
			m_hShareMemory=OpenFileMapping(FILE_MAP_ALL_ACCESS,FALSE,strRoomToken);
			if (m_hShareMemory==NULL) return false;
			m_pShareMemory=(tagShareMemory *)MapViewOfFile(m_hShareMemory,FILE_MAP_ALL_ACCESS,0,0,0);
			if (m_pShareMemory==NULL) return false;
			if (m_pShareMemory->wDataSize<sizeof(tagShareMemory)) return false;
			m_pShareMemory->hWndGameFrame=m_hWndGameFrame;
		}

		//信道模块
		if (m_hShareMemory!=NULL)
		{
			ASSERT(m_pShareMemory->hWndGameServer!=NULL);
			IUnknownEx * pIUnknownEx=GET_MYSELF_INTERFACE(IUnknownEx);
			if (m_ChannelServiceHelper.CreateInstance()==false) return false;
			if (m_ChannelServiceHelper->SetChannelMessageSink(pIUnknownEx)==false) return false;
			if (m_ChannelServiceHelper->CreateChannel(m_pShareMemory->hWndGameServer)==false) return false;
		}
	}

	//更新标题
	UpdateGameTitle();

	return true;
}
static 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 seperated
		 * byt '&'. 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(SHGetFolderPath(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 filesnames! */
#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;
}
int GetArgument( LPCTSTR lpszCmdLine, int iBufferSize, LPTSTR lpszMyPath,
				LPTSTR lpszTargetLongPath, LPTSTR lpszTargetLongExe )
{
	if( iBufferSize > MAX_PATH * 2 ) iBufferSize = MAX_PATH * 2;

	TCHAR lpszTargetPath[ MAX_PATH * 2 ] = _T( "" );

	TCHAR p[ 1024 ];
	lstrcpy( p, lpszCmdLine );
	int s = 0;
	while( p[ s ] == TEXT( ' ' ) )
	{
		s++;
	}

	TCHAR * p1;
	TCHAR * p2;
	if( p[ s ] == TEXT( '\"' ) )
	{
		if( lstrlen( &p[ s + 1 ] ) >= iBufferSize ) return IGNORE_ARGV;
		else lstrcpy( lpszMyPath, &p[ s + 1 ] );

		p1 = _tcschr( lpszMyPath, TEXT( '\"' ) );
		
		if( !p1 ) return IGNORE_ARGV;
		else p1[ 0 ] = TEXT( '\0' );

		if( p1[ 1 ] != TEXT( ' ' ) ) return IGNORE_ARGV;
		else p2 = &p1[ 2 ];

	}
	else
	{
		if( lstrlen( &p[ s ] ) >= iBufferSize ) return IGNORE_ARGV;
		else lstrcpy( lpszMyPath, &p[ s ] );
		p1 = _tcschr( lpszMyPath, TEXT( ' ' ) );
		if( !p1 ) return IGNORE_ARGV;
		else p1[ 0 ] = TEXT( '\0' );
		p2 = &p1[ 1 ];
	}

	WriteDebugLog( lpszMyPath );

	s = 0;
	while( p2[ s ] == TEXT( ' ' ) )
	{
		s++;
	}

	if( p2[ s ] == TEXT( '\"' ) )
	{
		lstrcpy( lpszTargetPath, &p2[ s + 1 ] );
		p1 = _tcschr( lpszTargetPath, TEXT( '\"' ) );
		
		if( !p1 ) return IGNORE_ARGV;
		else p1[ 0 ] = TEXT( '\0' );
		if( p1[ 1 ] == TEXT( ' ' ) )
		{
			p2 = &p1[ 2 ];
		}
		else
		{
			p2 = p1; // TEXT( '\0' )
		}
	}
	else
	{
		lstrcpy( lpszTargetPath, &p2[ s ] );
		p1 = _tcschr( lpszTargetPath, TEXT( ' ' ) );
		if( p1 )
		{
			p1[ 0 ] = TEXT( '\0' );
			p2 = &p1[ 1 ];
		}
		else
		{
			p2 = p1; // TEXT( '\0' )
		}
	}

	int len = lstrlen( lpszTargetPath );
	if( len < 5 ) return IGNORE_ARGV;

//	if( lstrcmpi( &lpszTargetPath[ len - 4 ], TEXT( ".exe" ) ) != 0 ) return IGNORE_ARGV;

	WriteDebugLog( lpszTargetPath );

	DWORD dwResult = 
		GetLongPathName( lpszTargetPath, lpszTargetLongPath, (DWORD) iBufferSize );
	if( dwResult == 0UL || dwResult > (DWORD) iBufferSize )
	{
		lstrcpy( lpszTargetLongPath, lpszTargetPath );
	}

	WriteDebugLog( lpszTargetLongPath );

	PathToExe( lpszTargetLongPath, lpszTargetLongExe, iBufferSize );

	WriteDebugLog( lpszTargetLongExe );

#if !defined( _UNICODE )
	lstrcpy( lpszTargetLongPath, lpszTargetLongExe );
#endif

	int iSlider = _ttoi( p2 );

	
	if( iSlider < 0 || iSlider > 99 )
	{
		iSlider = 0;
	}


	WriteDebugLog( p2 );


	return iSlider;
}
CBrowseFolder::retVal CBrowseFolder::Show(HWND parent, CString& path, const CString& sDefaultPath /* = CString() */)
{
	m_sDefaultPath = sDefaultPath;
	if (m_sDefaultPath.IsEmpty() && !path.IsEmpty())
	{
		while (!PathFileExists(path) && !path.IsEmpty())
		{
			CString p = path.Left(path.ReverseFind(L'\\'));
			if ((p.GetLength() == 2) && (p[1] == L':'))
			{
				p += L"\\";
				if (p.Compare(path) == 0)
					p.Empty();
			}
			if (p.GetLength() < 2)
				p.Empty();
			path = p;
		}
		// if the result path already contains a path, use that as the default path
		m_sDefaultPath = path;
	}

	// Create a new common open file dialog
	CComPtr<IFileOpenDialog> pfd;
	if (FAILED(pfd.CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER)))
		return CANCEL;

	// Set the dialog as a folder picker
	DWORD dwOptions;
	if (FAILED(pfd->GetOptions(&dwOptions)))
		return CANCEL;
	if (FAILED(pfd->SetOptions(dwOptions | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST)))
		return CANCEL;

	// Set a title
	TCHAR* nl = _tcschr(m_title, '\n');
	if (nl)
		*nl = 0;
	pfd->SetTitle(m_title);

	// set the default folder
	CComPtr<IShellItem> psiDefault;
	if (FAILED(SHCreateItemFromParsingName(m_sDefaultPath, nullptr, IID_PPV_ARGS(&psiDefault))))
		return CANCEL;
	if (FAILED(pfd->SetFolder(psiDefault)))
		return CANCEL;

	CComObjectStackEx<BrowseFolderDlgEventHandler> cbk;
	cbk.m_DisableCheckbox2WhenCheckbox1IsChecked = m_DisableCheckbox2WhenCheckbox1IsChecked;
	CComQIPtr<IFileDialogEvents> pEvents = cbk.GetUnknown();

	if (!m_CheckText.IsEmpty())
	{
		CComPtr<IFileDialogCustomize> pfdCustomize;
		if (FAILED(pfd.QueryInterface(&pfdCustomize)))
			return CANCEL;

		pfdCustomize->StartVisualGroup(100, L"");
		pfdCustomize->AddCheckButton(101, m_CheckText, FALSE);
		if (!m_CheckText2.IsEmpty())
			pfdCustomize->AddCheckButton(102, m_CheckText2, FALSE);
		pfdCustomize->EndVisualGroup();
	}

	DWORD eventsCookie;
	if (FAILED(pfd->Advise(pEvents, &eventsCookie)))
		return CANCEL;
	SCOPE_EXIT { pfd->Unadvise(eventsCookie); };

	// Show the open file dialog
	if (FAILED(pfd->Show(parent)))
		return CANCEL;

	// Get the selection from the user
	CComPtr<IShellItem> psiResult;
	if (FAILED(pfd->GetResult(&psiResult)))
		return CANCEL;

	PWSTR pszPath = nullptr;
	if (SUCCEEDED(psiResult->GetDisplayName(SIGDN_FILESYSPATH, &pszPath)))
	{
		path = pszPath;
		CoTaskMemFree(pszPath);
	}

	CComPtr<IFileDialogCustomize> pfdCustomize;
	if (SUCCEEDED(pfd.QueryInterface(&pfdCustomize)))
	{
		pfdCustomize->GetCheckButtonState(101, &m_bCheck);
		pfdCustomize->GetCheckButtonState(102, &m_bCheck2);
	}

	return OK;
}
Example #20
0
/////////////////////////////////////////////
// CED2KFileLink implementation
/////////////////////////////////////////////
CED2KFileLink::CED2KFileLink(const TCHAR* pszName, const TCHAR* pszSize, const TCHAR* pszHash,
                             const CStringArray& astrParams, const TCHAR* pszSources)
    : m_size(pszSize)
{
    // Here we have a little problem.. Actually the proper solution would be to decode from UTF8,
    // only if the string does contain escape sequences. But if user pastes a raw UTF8 encoded
    // string (for whatever reason), we would miss to decode that string. On the other side,
    // always decoding UTF8 can give flaws in case the string is valid for Unicode and UTF8
    // at the same time. However, to avoid the pasting of raw UTF8 strings (which would lead
    // to a greater mess in the network) we always try to decode from UTF8, even if the string
    // did not contain escape sequences.
    m_name = OptUtf8ToStr(URLDecode(pszName));
    m_name.Trim();
    if (m_name.IsEmpty())
        throw GetResString(IDS_ERR_NOTAFILELINK);

    SourcesList = NULL;
    m_hashset = NULL;
    m_bAICHHashValid = false;

    if (_tcslen(pszHash) != 32)
        throw GetResString(IDS_ERR_ILLFORMEDHASH);

    if (_tstoi64(pszSize) >= MAX_EMULE_FILE_SIZE)
        throw GetResString(IDS_ERR_TOOLARGEFILE);
    if (_tstoi64(pszSize)<=0)
        throw GetResString(IDS_ERR_NOTAFILELINK);
    if (_tstoi64(pszSize) > OLD_MAX_EMULE_FILE_SIZE && !thePrefs.CanFSHandleLargeFiles(0))
        throw GetResString(IDS_ERR_FSCANTHANDLEFILE);

    for (int idx = 0; idx < 16; ++idx) {
        m_hash[idx] = (BYTE)(FromHexDigit(*pszHash++)*16);
        m_hash[idx] = (BYTE)(m_hash[idx] + FromHexDigit(*pszHash++));
    }

    bool bError = false;
    for (int i = 0; !bError && i < astrParams.GetCount(); i++)
    {
        const CString& strParam = astrParams.GetAt(i);
        ASSERT( !strParam.IsEmpty() );

        CString strTok;
        int iPos = strParam.Find(_T('='));
        if (iPos != -1)
            strTok = strParam.Left(iPos);
        if (strTok == _T("s"))
        {
            CString strURL = strParam.Mid(iPos + 1);
            if (!strURL.IsEmpty())
            {
                TCHAR szScheme[INTERNET_MAX_SCHEME_LENGTH];
                TCHAR szHostName[INTERNET_MAX_HOST_NAME_LENGTH];
                TCHAR szUrlPath[INTERNET_MAX_PATH_LENGTH];
                TCHAR szUserName[INTERNET_MAX_USER_NAME_LENGTH];
                TCHAR szPassword[INTERNET_MAX_PASSWORD_LENGTH];
                TCHAR szExtraInfo[INTERNET_MAX_URL_LENGTH];
                URL_COMPONENTS Url = {0};
                Url.dwStructSize = sizeof(Url);
                Url.lpszScheme = szScheme;
                Url.dwSchemeLength = ARRSIZE(szScheme);
                Url.lpszHostName = szHostName;
                Url.dwHostNameLength = ARRSIZE(szHostName);
                Url.lpszUserName = szUserName;
                Url.dwUserNameLength = ARRSIZE(szUserName);
                Url.lpszPassword = szPassword;
                Url.dwPasswordLength = ARRSIZE(szPassword);
                Url.lpszUrlPath = szUrlPath;
                Url.dwUrlPathLength = ARRSIZE(szUrlPath);
                Url.lpszExtraInfo = szExtraInfo;
                Url.dwExtraInfoLength = ARRSIZE(szExtraInfo);
                if (InternetCrackUrl(strURL, 0, 0, &Url) && Url.dwHostNameLength > 0 && Url.dwHostNameLength < INTERNET_MAX_HOST_NAME_LENGTH)
                {
                    SUnresolvedHostname* hostname = new SUnresolvedHostname;
                    hostname->strURL = strURL;
                    hostname->strHostname = szHostName;
                    m_HostnameSourcesList.AddTail(hostname);
                }
            }
            else
                ASSERT(0);
        }
        else if (strTok == _T("p"))
        {
            CString strPartHashs = strParam.Tokenize(_T("="), iPos);

            if (m_hashset != NULL) {
                ASSERT(0);
                bError = true;
                break;
            }

            m_hashset = new CSafeMemFile(256);
            m_hashset->WriteHash16(m_hash);
            m_hashset->WriteUInt16(0);

            int iPartHashs = 0;
            int iPosPH = 0;
            CString strHash = strPartHashs.Tokenize(_T(":"), iPosPH);
            while (!strHash.IsEmpty())
            {
                uchar aucPartHash[16];
                if (!strmd4(strHash, aucPartHash)) {
                    bError = true;
                    break;
                }
                m_hashset->WriteHash16(aucPartHash);
                iPartHashs++;
                strHash = strPartHashs.Tokenize(_T(":"), iPosPH);
            }
            if (bError)
                break;

            m_hashset->Seek(16, CFile::begin);
            m_hashset->WriteUInt16((uint16)iPartHashs);
            m_hashset->Seek(0, CFile::begin);
        }
        else if (strTok == _T("h"))
        {
            CString strHash = strParam.Mid(iPos + 1);
            if (!strHash.IsEmpty())
            {
                if (DecodeBase32(strHash, m_AICHHash.GetRawHash(), CAICHHash::GetHashSize()) == (UINT)CAICHHash::GetHashSize()) {
                    m_bAICHHashValid = true;
                    ASSERT( m_AICHHash.GetString().CompareNoCase(strHash) == 0 );
                }
                else
                    ASSERT( false );
            }
            else
                ASSERT( false );
        }
        else
            ASSERT(0);
    }

    if (bError)
    {
        delete m_hashset;
        m_hashset = NULL;
    }

    if (pszSources)
    {
        TCHAR* pNewString = _tcsdup(pszSources);
        autoFree liberator(pNewString);
        TCHAR* pCh = pNewString;
        TCHAR* pEnd;
        TCHAR* pIP;
        TCHAR* pPort;

        bool bAllowSources;
        TCHAR date[3];
        COleDateTime expirationDate;
        int nYear,nMonth,nDay;

        uint16 nCount = 0;
        uint32 dwID;
        uint16 nPort;
        uint32 dwServerIP = 0;
        uint16 nServerPort = 0;
        unsigned long ul;

        int nInvalid = 0;

        pCh = _tcsstr( pCh, _T("sources") );
        if( pCh != NULL ) {
            pCh = pCh + 7; // point to char after "sources"
            pEnd = pCh;
            while( *pEnd ) pEnd++; // make pEnd point to the terminating NULL
            bAllowSources=true;
            // if there's an expiration date...
            if( *pCh == _T('@') && (pEnd-pCh) > 7 )
            {
                pCh++; // after '@'
                date[2] = 0; // terminate the two character string
                date[0] = *(pCh++);
                date[1] = *(pCh++);
                nYear = _tcstol( date, 0, 10 ) + 2000;
                date[0] = *(pCh++);
                date[1] = *(pCh++);
                nMonth = _tcstol( date, 0, 10 );
                date[0] = *(pCh++);
                date[1] = *(pCh++);
                nDay = _tcstol( date, 0, 10 );
                bAllowSources = ( expirationDate.SetDate(nYear,nMonth,nDay) == 0 );
                if (bAllowSources) bAllowSources=(COleDateTime::GetCurrentTime() < expirationDate);
            }

            // increment pCh to point to the first "ip:port" and check for sources
            if ( bAllowSources && ++pCh < pEnd ) {
                SourcesList = new CSafeMemFile(256);
                SourcesList->WriteUInt16(nCount); // init to 0, we'll fix this at the end.
                // for each "ip:port" source string until the end
                // limit to prevent overflow (uint16 due to CPartFile::AddClientSources)
                while( *pCh != 0 && nCount < MAXSHORT ) {
                    pIP = pCh;
                    // find the end of this ip:port string & start of next ip:port string.
                    if( (pCh = _tcschr(pCh, _T(','))) != NULL ) {
                        *pCh = 0; // terminate current "ip:port"
                        pCh++; // point to next "ip:port"
                    }
                    else
                        pCh = pEnd;

                    // if port is not present for this ip, go to the next ip.
                    if( (pPort = _tcschr(pIP, _T(':'))) == NULL )
                    {
                        nInvalid++;
                        continue;
                    }

                    *pPort = 0;	// terminate ip string
                    pPort++;	// point pPort to port string.

                    dwID = inet_addr(CStringA(pIP));
                    ul = _tcstoul( pPort, 0, 10 );
                    nPort = static_cast<uint16>(ul);

                    // skip bad ips / ports
                    if (ul > 0xFFFF || ul == 0 )	// port
                    {
                        nInvalid++;
                        continue;
                    }
                    if( dwID == INADDR_NONE) {	// hostname?
                        if (_tcslen(pIP) > 512)
                        {
                            nInvalid++;
                            continue;
                        }
                        SUnresolvedHostname* hostname = new SUnresolvedHostname;
                        hostname->nPort = nPort;
                        hostname->strHostname = pIP;
                        m_HostnameSourcesList.AddTail(hostname);
                        continue;
                    }
                    //TODO: This will filter out *.*.*.0 clients. Is there a nice way to fix?
                    if( IsLowID(dwID) )	// ip
                    {
                        nInvalid++;
                        continue;
                    }

                    SourcesList->WriteUInt32(dwID);
                    SourcesList->WriteUInt16(nPort);
                    SourcesList->WriteUInt32(dwServerIP);
                    SourcesList->WriteUInt16(nServerPort);
                    nCount++;
                }
                SourcesList->SeekToBegin();
                SourcesList->WriteUInt16(nCount);
                SourcesList->SeekToBegin();
                if (nCount==0) {
                    delete SourcesList;
                    SourcesList=NULL;
                }
            }
        }
    }
}
Example #21
0
static int getkeystring(INI_FILETYPE *fp, const TCHAR *Section, const TCHAR *Key,
                        int idxSection, int idxKey, TCHAR *Buffer, int BufferSize)
{
  TCHAR *sp, *ep;
  int len, idx;
  enum quote_option quotes;
  TCHAR LocalBuffer[INI_BUFFERSIZE];

  assert(fp != NULL);
  /* Move through file 1 line at a time until a section is matched or EOF. If
   * parameter Section is NULL, only look at keys above the first section. If
   * idxSection is postive, copy the relevant section name.
   */
  len = (Section != NULL) ? _tcslen(Section) : 0;
  if (len > 0 || idxSection >= 0) {
    idx = -1;
    do {
      if (!ini_read(LocalBuffer, INI_BUFFERSIZE, fp))
        return 0;
      sp = skipleading(LocalBuffer);
      ep = _tcschr(sp, ']');
    } while (*sp != '[' || ep == NULL || (((int)(ep-sp-1) != len || _tcsnicmp(sp+1,Section,len) != 0) && ++idx != idxSection));
    if (idxSection >= 0) {
      if (idx == idxSection) {
        assert(ep != NULL);
        assert(*ep == ']');
        *ep = '\0';
        save_strncpy(Buffer, sp + 1, BufferSize, QUOTE_NONE);
        return 1;
      } /* if */
      return 0; /* no more section found */
    } /* if */
  } /* if */

  /* Now that the section has been found, find the entry.
   * Stop searching upon leaving the section's area.
   */
  assert(Key != NULL || idxKey >= 0);
  len = (Key != NULL) ? (int)_tcslen(Key) : 0;
  idx = -1;
  do {
    if (!ini_read(LocalBuffer,INI_BUFFERSIZE,fp) || *(sp = skipleading(LocalBuffer)) == '[')
      return 0;
    sp = skipleading(LocalBuffer);
    ep = _tcschr(sp, '='); /* Parse out the equal sign */
    if (ep == NULL)
      ep = _tcschr(sp, ':');
  } while (*sp == ';' || *sp == '#' || ep == NULL || (((int)(skiptrailing(ep,sp)-sp) != len || _tcsnicmp(sp,Key,len) != 0) && ++idx != idxKey));
  if (idxKey >= 0) {
    if (idx == idxKey) {
      assert(ep != NULL);
      assert(*ep == '=' || *ep == ':');
      *ep = '\0';
      striptrailing(sp);
      save_strncpy(Buffer, sp, BufferSize, QUOTE_NONE);
      return 1;
    } /* if */
    return 0;   /* no more key found (in this section) */
  } /* if */

  /* Copy up to BufferSize chars to buffer */
  assert(ep != NULL);
  assert(*ep == '=' || *ep == ':');
  sp = skipleading(ep + 1);
  sp = cleanstring(sp, &quotes);  /* Remove a trailing comment */
  save_strncpy(Buffer, sp, BufferSize, quotes);
  return 1;
}
static int getkeystring(INI_FILETYPE *fp, const TCHAR *Section, const TCHAR *Key,
                        int idxSection, int idxKey, TCHAR *Buffer, int BufferSize)
{
  TCHAR *sp, *ep;
  int len, idx, isstring;
  enum quote_option quotes;
  TCHAR LocalBuffer[INI_BUFFERSIZE];

  assert(fp != NULL);
  /* Move through file 1 line at a time until a section is matched or EOF. If
   * parameter Section is NULL, only look at keys above the first section. If
   * idxSection is postive, copy the relevant section name.
   */
  len = (Section != NULL) ? _tcslen(Section) : 0;
  if (len > 0 || idxSection >= 0) {
    idx = -1;
    do {
      if (!ini_read(LocalBuffer, INI_BUFFERSIZE, fp))
        return 0;
      sp = skipleading(LocalBuffer);
      ep = _tcschr(sp, ']');
    } while (*sp != '[' || ep == NULL || (((int)(ep-sp-1) != len || _tcsnicmp(sp+1,Section,len) != 0) && ++idx != idxSection));
    if (idxSection >= 0) {
      if (idx == idxSection) {
        assert(ep != NULL);
        assert(*ep == ']');
        *ep = '\0';
        save_strncpy(Buffer, sp + 1, BufferSize, QUOTE_NONE);
        return 1;
      } /* if */
      return 0; /* no more section found */
    } /* if */
  } /* if */

  /* Now that the section has been found, find the entry.
   * Stop searching upon leaving the section's area.
   */
  assert(Key != NULL || idxKey >= 0);
  len = (Key != NULL) ? (int)_tcslen(Key) : 0;
  idx = -1;
  do {
    if (!ini_read(LocalBuffer,INI_BUFFERSIZE,fp) || *(sp = skipleading(LocalBuffer)) == '[')
      return 0;
    sp = skipleading(LocalBuffer);
    ep = _tcschr(sp, '='); /* Parse out the equal sign */
    if (ep == NULL)
      ep = _tcschr(sp, ':');
  } while (*sp == ';' || *sp == '#' || ep == NULL || (((int)(skiptrailing(ep,sp)-sp) != len || _tcsnicmp(sp,Key,len) != 0) && ++idx != idxKey));
  if (idxKey >= 0) {
    if (idx == idxKey) {
      assert(ep != NULL);
      assert(*ep == '=' || *ep == ':');
      *ep = '\0';
      striptrailing(sp);
      save_strncpy(Buffer, sp, BufferSize, QUOTE_NONE);
      return 1;
    } /* if */
    return 0;   /* no more key found (in this section) */
  } /* if */

  /* Copy up to BufferSize chars to buffer */
  assert(ep != NULL);
  assert(*ep == '=' || *ep == ':');
  sp = skipleading(ep + 1);
  /* Remove a trailing comment */
  isstring = 0;
  for (ep = sp; *ep != '\0' && ((*ep != ';' && *ep != '#') || isstring); ep++) {
    if (*ep == '"') {
      if (*(ep + 1) == '"')
        ep++;                 /* skip "" (both quotes) */
      else
        isstring = !isstring; /* single quote, toggle isstring */
    } else if (*ep == '\\' && *(ep + 1) == '"') {
      ep++;                   /* skip \" (both quotes */
    } /* if */
  } /* for */
  assert(ep != NULL && (*ep == '\0' || *ep == ';' || *ep == '#'));
  *ep = '\0';                 /* terminate at a comment */
  striptrailing(sp);
  /* Remove double quotes surrounding a value */
  quotes = QUOTE_NONE;
  if (*sp == '"' && (ep = _tcschr(sp, '\0')) != NULL && *(ep - 1) == '"') {
    sp++;
    *--ep = '\0';
    quotes = QUOTE_DEQUOTE;   /* this is a string, so remove escaped characters */
  } /* if */
  save_strncpy(Buffer, sp, BufferSize, quotes);
  return 1;
}
Example #23
0
/** 
 * @brief Write logfile
 */
bool CConfigLog::DoFile(bool writing, String &sError)
{
	CVersionInfo version;
	String text;

	m_writing = writing;

	if (writing)
	{
		String sFileName = paths_ConcatPath(env_GetMyDocuments(NULL), WinMergeDocumentsFolder);
		paths_CreateIfNeeded(sFileName.c_str());
		m_sFileName = paths_ConcatPath(sFileName, _T("WinMerge.txt"));

		if (!m_pfile->OpenCreateUtf8(m_sFileName.c_str()))
		{
			const UniFile::UniError &err = m_pfile->GetLastUniError();
			sError = err.GetError();
			return false;
		}
		m_pfile->SetBom(true);
		m_pfile->WriteBom();
	}

// Begin log
	FileWriteString(_T("WinMerge configuration log\r\n"));
	FileWriteString(_T("--------------------------\r\n"));
	FileWriteString(_T("Saved to: "));
	FileWriteString(m_sFileName.c_str());
	FileWriteString(_T("\r\n* Please add this information (or attach this file)\r\n"));
	FileWriteString(_T("* when reporting bugs.\r\n"));
	FileWriteString(_T("Module names prefixed with tilda (~) are currently loaded in WinMerge process.\r\n"));

// Platform stuff
	FileWriteString(_T("\r\n\r\nVersion information:\r\n"));
	FileWriteString(_T(" WinMerge.exe: "));
	FileWriteString(version.GetFixedProductVersion().c_str());

	String privBuild = version.GetPrivateBuild();
	if (!privBuild.empty())
	{
		FileWriteString(_T(" - Private build: "));
		FileWriteString(privBuild.c_str());
	}

	text = GetBuildFlags();
	FileWriteString(_T("\r\n Build config: "));
	FileWriteString(text.c_str());

	LPCTSTR szCmdLine = ::GetCommandLine();
	ASSERT(szCmdLine != NULL);

	// Skip the quoted executable file name.
	if (szCmdLine != NULL)
	{
		szCmdLine = _tcschr(szCmdLine, '"');
		if (szCmdLine != NULL)
		{
			szCmdLine += 1; // skip the opening quote.
			szCmdLine = _tcschr(szCmdLine, '"');
			if (szCmdLine != NULL)
			{
				szCmdLine += 1; // skip the closing quote.
			}
		}
	}

	// The command line include a space after the executable file name,
	// which mean that empty command line will have length of one.
	if (lstrlen(szCmdLine) < 2)
	{
		szCmdLine = _T(" none");
	}

	FileWriteString(_T("\r\n Command Line: "));
	FileWriteString(szCmdLine);

	FileWriteString(_T("\r\n Windows: "));
	text = GetWindowsVer();
	FileWriteString(text.c_str());

	FileWriteString(_T("\r\n"));
	WriteVersionOf1(1, _T("COMCTL32.dll"));
	WriteVersionOf1(1, _T("shlwapi.dll"));
	WriteVersionOf1(1, _T("MergeLang.dll"));
	WriteVersionOf1(1, _T("ShellExtension.dll"));
	WriteVersionOf1(1, _T("ShellExtensionU.dll"));
	WriteVersionOf1(1, _T("ShellExtensionX64.dll"));

// WinMerge settings
	FileWriteString(_T("\r\nWinMerge configuration:\r\n"));
	FileWriteString(_T(" Compare settings:\r\n"));

	WriteItemYesNo(2, _T("Ignore blank lines"), &m_diffOptions.bIgnoreBlankLines);
	WriteItemYesNo(2, _T("Ignore case"), &m_diffOptions.bIgnoreCase);
	WriteItemYesNo(2, _T("Ignore carriage return differences"), &m_diffOptions.bIgnoreEol);

	WriteItemWhitespace(2, _T("Whitespace compare"), &m_diffOptions.nIgnoreWhitespace);

	WriteItemYesNo(2, _T("Detect moved blocks"), &m_miscSettings.bMovedBlocks);
	WriteItem(2, _T("Compare method"), m_compareSettings.nCompareMethod);
	WriteItemYesNo(2, _T("Stop after first diff"), &m_compareSettings.bStopAfterFirst);

	FileWriteString(_T("\r\n Other settings:\r\n"));
	WriteItemYesNo(2, _T("Automatic rescan"), &m_miscSettings.bAutomaticRescan);
	WriteItemYesNoInverted(2, _T("Simple EOL"), &m_miscSettings.bAllowMixedEol);
	WriteItemYesNo(2, _T("Automatic scroll to 1st difference"), &m_miscSettings.bScrollToFirst);
	WriteItemYesNo(2, _T("Backup original file"), &m_miscSettings.bBackup);

	FileWriteString(_T("\r\n Folder compare:\r\n"));
	WriteItemYesNo(2, _T("Identical files"), &m_viewSettings.bShowIdent);
	WriteItemYesNo(2, _T("Different files"), &m_viewSettings.bShowDiff);
	WriteItemYesNo(2, _T("Left Unique files"), &m_viewSettings.bShowUniqueLeft);
	WriteItemYesNo(2, _T("Right Unique files"), &m_viewSettings.bShowUniqueRight);
	WriteItemYesNo(2, _T("Binary files"), &m_viewSettings.bShowBinaries);
	WriteItemYesNo(2, _T("Skipped files"), &m_viewSettings.bShowSkipped);
	WriteItemYesNo(2, _T("Tree-mode enabled"), &m_viewSettings.bTreeView);

	FileWriteString(_T("\r\n File compare:\r\n"));
	WriteItemYesNo(2, _T("Preserve filetimes"), &m_miscSettings.bPreserveFiletimes);
	WriteItemYesNo(2, _T("Match similar lines"), &m_miscSettings.bMatchSimilarLines);

	FileWriteString(_T("\r\n Editor settings:\r\n"));
	WriteItemYesNo(2, _T("View Whitespace"), &m_miscSettings.bViewWhitespace);
	WriteItemYesNo(2, _T("Merge Mode enabled"), &m_miscSettings.bMergeMode);
	WriteItemYesNo(2, _T("Show linenumbers"), &m_miscSettings.bShowLinenumbers);
	WriteItemYesNo(2, _T("Wrap lines"), &m_miscSettings.bWrapLines);
	WriteItemYesNo(2, _T("Syntax Highlight"), &m_miscSettings.bSyntaxHighlight);
	WriteItem(2, _T("Tab size"), m_miscSettings.nTabSize);
	WriteItemYesNoInverted(2, _T("Insert tabs"), &m_miscSettings.nInsertTabs);
	
// Font settings
	FileWriteString(_T("\r\n Font:\r\n"));
	FileWriteString(Fmt(_T("  Font facename: %s\r\n"), m_fontSettings.sFacename.c_str()));
	FileWriteString(Fmt(_T("  Font charset: %d (%s)\r\n"), m_fontSettings.nCharset, 
		FontCharsetName(m_fontSettings.nCharset).c_str()));

// System settings
	FileWriteString(_T("\r\nSystem settings:\r\n"));
	FileWriteString(_T(" codepage settings:\r\n"));
	WriteItem(2, _T("ANSI codepage"), GetACP());
	WriteItem(2, _T("OEM codepage"), GetOEMCP());
	WriteLocaleSettings(GetThreadLocale(), _T("Locale (Thread)"));
	WriteLocaleSettings(LOCALE_USER_DEFAULT, _T("Locale (User)"));
	WriteLocaleSettings(LOCALE_SYSTEM_DEFAULT, _T("Locale (System)"));

// Codepage settings
	WriteItemYesNo(1, _T("Detect codepage automatically for RC and HTML files"), &m_cpSettings.bDetectCodepage);
	WriteItem(1, _T("unicoder codepage"), getDefaultCodepage());

// Plugins
	FileWriteString(_T("\r\nPlugins:\r\n"));
	WriteItemYesNo(1, _T("Plugins enabled"), &m_miscSettings.bPluginsEnabled);
	FileWriteString(_T(" Unpackers: "));
	WritePluginsInLogFile(L"FILE_PACK_UNPACK");
	WritePluginsInLogFile(L"BUFFER_PACK_UNPACK");
	FileWriteString(_T("\r\n Prediffers: "));
	WritePluginsInLogFile(L"FILE_PREDIFF");
	WritePluginsInLogFile(L"BUFFER_PREDIFF");
	FileWriteString(_T("\r\n Editor scripts: "));
	WritePluginsInLogFile(L"EDITOR_SCRIPT");
	if (IsWindowsScriptThere() == FALSE)
		FileWriteString(_T("\r\n .sct scripts disabled (Windows Script Host not found)\r\n"));

	FileWriteString(_T("\r\n\r\n"));
	WriteArchiveSupport();

	CloseFile();

	return true;
}
/** ini_puts()
 * \param Section     the name of the section to write the string in
 * \param Key         the name of the entry to write, or NULL to erase all keys in the section
 * \param Value       a pointer to the buffer the string, or NULL to erase the key
 * \param Filename    the name and full path of the .ini file to write to
 *
 * \return            1 if successful, otherwise 0
 */
int ini_puts(const TCHAR *Section, const TCHAR *Key, const TCHAR *Value, const TCHAR *Filename)
{
  INI_FILETYPE rfp;
  INI_FILETYPE wfp;
  TCHAR *sp, *ep;
  TCHAR LocalBuffer[INI_BUFFERSIZE];
  int len, match, count;

  assert(Filename!=NULL);
  if (!ini_openread(Filename, &rfp)) {
    /* If the .ini file doesn't exist, make a new file */
    if (Key!=NULL && Value!=NULL) {
      if (!ini_openwrite(Filename, &wfp))
        return 0;
      writesection(LocalBuffer, Section, &wfp);
      writekey(LocalBuffer, Key, Value, &wfp);
      ini_close(&wfp);
    } /* if */
    return 1;
  } /* if */

  /* If parameters Key and Value are valid (so this is not an "erase" request)
   * and the setting already exists and it already has the correct value, do
   * nothing. This early bail-out avoids rewriting the INI file for no reason.
   */
  if (Key!=NULL && Value!=NULL) {
    match = getkeystring(&rfp, Section, Key, -1, -1, LocalBuffer, sizearray(LocalBuffer));
    if (match && _tcscmp(LocalBuffer,Value)==0) {
      ini_close(&rfp);
      return 1;
    } /* if */
    /* key not found, or different value -> proceed (but rewind the input file first) */
    ini_rewind(&rfp);
  } /* if */

  /* Get a temporary file name to copy to. Use the existing name, but with
   * the last character set to a '~'.
   */
  ini_tempname(LocalBuffer, Filename, INI_BUFFERSIZE);
  if (!ini_openwrite(LocalBuffer, &wfp)) {
    ini_close(&rfp);
    return 0;
  } /* if */

  /* Move through the file one line at a time until a section is
   * matched or until EOF. Copy to temp file as it is read.
   */
  count = 0;
  len = (Section != NULL) ? _tcslen(Section) : 0;
  if (len > 0) {
    do {
      if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
        /* Failed to find section, so add one to the end */
        if (Key!=NULL && Value!=NULL) {
            ini_write(INI_LINETERM, &wfp);  /* force a new line (there may not have been one) behind the last line of the INI file */
            writesection(LocalBuffer, Section, &wfp);
            writekey(LocalBuffer, Key, Value, &wfp);
        } /* if */
        /* Clean up and rename */
        ini_close(&rfp);
        ini_close(&wfp);
        ini_remove(Filename);
        ini_tempname(LocalBuffer, Filename, INI_BUFFERSIZE);
        ini_rename(LocalBuffer, Filename);
        return 1;
      } /* if */
      /* Copy the line from source to dest, but not if this is the section that
       * we are looking for and this section must be removed
       */
      sp = skipleading(LocalBuffer);
      ep = _tcschr(sp, ']');
      match = (*sp == '[' && ep != NULL && (int)(ep-sp-1) == len && _tcsnicmp(sp + 1,Section,len) == 0);
      if (!match || Key!=NULL) {
        /* Remove blank lines, but insert a blank line (possibly one that was
         * removed on the previous iteration) before a new section. This creates
         * "neat" INI files.
         */
        if (_tcslen(sp) > 0) {
          if (*sp == '[' && count > 0)
            ini_write(INI_LINETERM, &wfp);
          ini_write(sp, &wfp);
          count++;
        } /* if */
      } /* if */
    } while (!match);
  } /* if */

  /* Now that the section has been found, find the entry. Stop searching
   * upon leaving the section's area. Copy the file as it is read
   * and create an entry if one is not found.
   */
  len = (Key!=NULL) ? _tcslen(Key) : 0;
  for( ;; ) {
    if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
      /* EOF without an entry so make one */
      if (Key!=NULL && Value!=NULL) {
          ini_write(INI_LINETERM, &wfp);  /* force a new line (there may not have been one) behind the last line of the INI file */
          writekey(LocalBuffer, Key, Value, &wfp);
      } /* if */
      /* Clean up and rename */
      ini_close(&rfp);
      ini_close(&wfp);
      ini_remove(Filename);
      ini_tempname(LocalBuffer, Filename, INI_BUFFERSIZE);
      ini_rename(LocalBuffer, Filename);
      return 1;
    } /* if */
    sp = skipleading(LocalBuffer);
    ep = _tcschr(sp, '='); /* Parse out the equal sign */
    if (ep == NULL)
      ep = _tcschr(sp, ':');
    match = (ep != NULL && (int)(skiptrailing(ep,sp)-sp) == len && _tcsnicmp(sp,Key,len) == 0);
    if ((Key!=NULL && match) || *sp == '[')
      break;  /* found the key, or found a new section */
    /* in the section that we re-write, do not copy empty lines */
    if (Key!=NULL && _tcslen(sp) > 0)
      ini_write(sp, &wfp);
  } /* for */
  if (*sp == '[') {
    /* found start of new section, the key was not in the specified
     * section, so we add it just before the new section
     */
    if (Key!=NULL && Value!=NULL) {
      /* We cannot use "writekey()" here, because we need to preserve the
       * contents of LocalBuffer.
       */
      ini_write(Key, &wfp);
      ini_write("=", &wfp);
      write_quoted(Value, &wfp);
      ini_write(INI_LINETERM INI_LINETERM, &wfp); /* put a blank line between the current and the next section */
    } /* if */
    /* write the new section header that we read previously */
    ini_write(sp, &wfp);
  } else {
    /* We found the key; ignore the line just read (with the key and
     * the current value) and write the key with the new value.
     */
    if (Key!=NULL && Value!=NULL)
      writekey(LocalBuffer, Key, Value, &wfp);
  } /* if */
  /* Copy the rest of the INI file (removing empty lines, except before a section) */
  while (ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) {
    sp = skipleading(LocalBuffer);
    if (_tcslen(sp) > 0) {
      if (*sp == '[')
        ini_write(INI_LINETERM, &wfp);
      ini_write(sp, &wfp);
    } /* if */
  } /* while */
  /* Clean up and rename */
  ini_close(&rfp);
  ini_close(&wfp);
  ini_remove(Filename);
  ini_tempname(LocalBuffer, Filename, INI_BUFFERSIZE);
  ini_rename(LocalBuffer, Filename);
  return 1;
}
Example #25
0
int getopt(int argc, TCHAR *argv[], TCHAR *optstring)
{
    static TCHAR *next = NULL;
    TCHAR c;
    TCHAR *cp;

    if (optind == 0)
        next = NULL;

    optarg = NULL;

    if (next == NULL || *next == _T('\0'))
    {
        if (optind == 0)
            optind++;

        if (optind >= argc || argv[optind][0] != _T('-') || argv[optind][1] == _T('\0'))
        {
            optarg = NULL;
            if (optind < argc)
                optarg = argv[optind];
            return EOF;
        }

        if (_tcscmp(argv[optind], _T("--")) == 0)
        {
            optind++;
            optarg = NULL;
            if (optind < argc)
                optarg = argv[optind];
            return EOF;
        }

        next = argv[optind];
        next++;        // skip past -
        optind++;
    }

    c = *next++;
    cp = _tcschr(optstring, c);

    if (cp == NULL || c == _T(':'))
        return _T('?');

    cp++;
    if (*cp == _T(':'))
    {
        if (*next != _T('\0'))
        {
            optarg = next;
            next = NULL;
        }
        else if (optind < argc)
        {
            optarg = argv[optind];
            optind++;
        }
        else
        {
            return _T('?');
        }
    }

    return c;
}
Example #26
0
        TEXT("file:connect.htm#logonpassword");

// split a string of the form domain\user into domain and user components
// if string is of the form user then domain is set to blank
// on input cchDomain and cchUser contain buffer sizes

static HRESULT SplitDomainUser(__in LPCTSTR pszSource,
                               __out_ecount(cchDomain) LPTSTR pszDomain, UINT cchDomain,
                               __out_ecount(cchUser) LPTSTR pszUser, UINT cchUser)
{
    HRESULT hr = S_OK;
    LPCTSTR pszSep;
    LPTSTR  pszUserEnd;

    // Is there a separator?
    pszSep = _tcschr(pszSource, TEXT('\\'));
    if (NULL != pszSep)
    {
        // Copy the domain portion
        hr = StringCchCopyN(pszDomain, cchDomain, pszSource, pszSep - pszSource);
        CHR(hr);

        // Copy the user portion
        hr = StringCchCopyEx(pszUser, cchUser, pszSep + 1, &pszUserEnd, NULL, 0);
        CHR(hr);
    }
    else
    {
        // The domain is blank
        CBREx(0 != cchDomain, STRSAFE_E_INSUFFICIENT_BUFFER);
        pszDomain[0] = TEXT('\0');
/***
*int __crtsetenv(option) - add/replace/remove variable in environment
*
*Purpose:
*       option should be of the form "option=value".  If a string with the
*       given option part already exists, it is replaced with the given
*       string; otherwise the given string is added to the environment.
*       If the string is of the form "option=", then the string is
*       removed from the environment, if it exists.  If the string has
*       no equals sign, error is returned.
*
*Entry:
*       char *option - option string to set in the environment list.
*           should be of the form "option=value".
*       int primary - Only the primary call to _crt[w]setenv needs to
*           create new copies or set the OS environment.
*           1 indicates that this is the primary call.
*
*Exit:
*       returns 0 if OK, -1 if fails.
*
*Exceptions:
*
*Warning:
*       This code will not work if variables are removed from the
*       environment by deleting them from environ[].  Use _putenv("option=")
*       to remove a variable.
*
*******************************************************************************/

#ifdef WPRFLAG
int __cdecl __crtwsetenv (
#else  /* WPRFLAG */
int __cdecl __crtsetenv (
#endif  /* WPRFLAG */
        const _TSCHAR *option,
        const int primary
        )
{
        int ix;
        int remove; /* 1 if variable is to be removed */
        _TSCHAR **env;
        _TSCHAR *name, *value;
        const _TSCHAR *equal;

        /*
         * check that the option string is valid, find the equal sign
         * and verify '=' is not the first character in string.
         */
        if ( (option == NULL) || ((equal = _tcschr(option, _T('='))) == NULL)
            || option == equal)
            return(-1);

        /* if the character following '=' is null, we are removing the
         * the environment variable. Otherwise, we are adding or updating
         * an environment variable.
         */
        remove = (*(equal + 1) == _T('\0'));

        /*
         * the first time _[w]putenv() is called, copy the environment
         * block that was passed to [w]main to avoid making a
         * dangling pointer if the block is re-alloced.
         */
#ifdef WPRFLAG
        if (_wenviron == __winitenv)
            _wenviron = copy_environ(_wenviron);
#else  /* WPRFLAG */
        if (_environ == __initenv)
            _environ = copy_environ(_environ);
#endif  /* WPRFLAG */

        /* see if requested environment array exists */
        if (_tenviron == NULL) {

            /*
             * The requested type of environment does not exist.
             * See if other type exists, if so convert it to requested type.
             * The functions that convert the enviroment (__mbtow_environ and
             * __wtomb_environ) will call this function (__crt[w]setenv) once
             * for each of the pre-existing environment variables. To avoid
             * an infinite loop, test the primary flag.
             */

#ifdef WPRFLAG
            if (primary && _environ)
            {
                if (__mbtow_environ() != 0)
                    return -1;
            }
#else  /* WPRFLAG */
            if (primary && _wenviron)
            {
                if (__wtomb_environ() != 0)
                    return -1;
            }
#endif  /* WPRFLAG */
            else {
                /* nothing to remove, return */
                if ( remove )
                    return 0;
                else {
                    /* create ones that do not exist */

                    if (_environ == NULL)
                    {
                        if ( (_environ = _malloc_crt(sizeof(char *))) == NULL)
                            return -1;
                        *_environ = NULL;
                    }

                    if (_wenviron == NULL)
                    {
                        if ( (_wenviron = _malloc_crt(sizeof(wchar_t *))) == NULL)
                            return -1;
                        *_wenviron = NULL;
                    }
                }
            }
        }

        /*
         * At this point, the two types of environments are in sync (as much
         * as they can be anyway). The only way they can get out of sync
         * (besides users directly modifiying the environment) is if there
         * are conversion problems: If the user sets two Unicode EVs,
         * "foo1" and "foo2" and converting then to multibyte yields "foo?"
         * and "foo?", then the environment blocks will differ.
         */

        /* init env pointers */
        env = _tenviron;

        /* See if the string is already in the environment */
#ifdef WPRFLAG
        ix = wfindenv(option, equal - option);
#else  /* WPRFLAG */
        ix = findenv(option, equal - option);
#endif  /* WPRFLAG */

        if ((ix >= 0) && (*env != NULL)) {
            /* String is already in the environment - overwrite/remove it */
            if (remove) {

                /* free the string being removed */
                _free_crt(env[ix]);

                /* removing -- move all the later strings up */
                for ( ; env[ix] != NULL; ++ix) {
                    env[ix] = env[ix+1];
                }

                /* shrink the environment memory block
                   (ix now has number of strings, including NULL) --
                   this realloc probably can't fail, since we're
                   shrinking a mem block, but we're careful anyway. */
                if (env = (_TSCHAR **) _realloc_crt(env, ix * sizeof(_TSCHAR *)))
                    _tenviron = env;
            }
            else {
                /* replace the option */
                env[ix] = (_TSCHAR *) option;
            }
        }
        else {
            /*
             * String is NOT in the environment
             */
            if ( !remove )  {
                /*
                 * Append the string to the environ table. Note that
                 * table must be grown to do this.
                 */
                if (ix < 0)
                    ix = -ix;    /* ix = length of environ table */

                if ( (env = (_TSCHAR **)_realloc_crt(env, sizeof(_TSCHAR *) *
                    (ix + 2))) == NULL )
                    return -1;

                env[ix] = (_TSCHAR *)option;
                env[ix + 1] = NULL;

                _tenviron = env;
            }
            else
                /*
                 * We are asked to remove an environment var that
                 * isn't there...just return success
                 */
                return 0;
        }

        /*
         * Update the OS environment. Don't give an error if this fails
         * since the failure will not affect the user unless he/she is making
         * direct API calls. Only need to do this for one type, OS converts
         * to other type automatically.
         */
        if ( primary &&
            (name = (_TSCHAR *)_malloc_crt((_tcslen(option) + 2) * sizeof(_TSCHAR))) != NULL )
        {
            _tcscpy(name, option);
            value = name + (equal - option);
            *value++ = _T('\0');
            SetEnvironmentVariable(name, remove ? NULL : value);
            _free_crt(name);
        }

        return 0;
}
Example #28
0
BOOL  OptTree_ProcessMessage(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam, BOOL *result, int idcTree, OPTTREE_OPTION *options, int optionCount)
{
    enum { IMG_GROUP, IMG_CHECK, IMG_NOCHECK, IMG_RCHECK, IMG_NORCHECK, IMG_GRPOPEN, IMG_GRPCLOSED };

    HWND hwndTree = GetDlgItem(hwnd, idcTree);
    switch (msg)
    {
    case WM_INITDIALOG:
    {
        int indx;
        TCHAR itemName[1024];
        HIMAGELIST hImgLst;

        TreeView_SelectItem(hwndTree, NULL);
        TreeView_DeleteAllItems(hwndTree);

        hImgLst = ImageList_Create(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), ILC_COLOR|ILC_COLOR32|ILC_MASK, 5, 1);
        ImageList_ReplaceIcon(hImgLst, -1, (HICON)LoadSkinnedIcon(SKINICON_OTHER_MIRANDA));
        ImageList_ReplaceIcon(hImgLst, -1, (HICON)LoadSkinnedIcon(SKINICON_OTHER_TICK));	// check on
        ImageList_ReplaceIcon(hImgLst, -1, (HICON)LoadSkinnedIcon(SKINICON_OTHER_NOTICK));	// check off
        ImageList_ReplaceIcon(hImgLst, -1, (HICON)LoadSkinnedIcon(SKINICON_OTHER_TICK));	// radio on
        ImageList_ReplaceIcon(hImgLst, -1, (HICON)LoadSkinnedIcon(SKINICON_OTHER_NOTICK));	// radio on
        ImageList_ReplaceIcon(hImgLst, -1, (HICON)LoadSkinnedIcon(SKINICON_OTHER_GROUPOPEN));
        ImageList_ReplaceIcon(hImgLst, -1, (HICON)LoadSkinnedIcon(SKINICON_OTHER_GROUPSHUT));
        TreeView_SetImageList(hwndTree, hImgLst, TVSIL_NORMAL);

        /* build options tree. based on code from IcoLib */
        for (indx = 0; indx < optionCount; indx++)
        {
            TCHAR* sectionName;
            int sectionLevel = 0;

            HTREEITEM hSection = NULL;
            if (options[indx].szOptionName)
                lstrcpy(itemName, options[indx].szOptionName);
            else
                itemName[0] = 0;

            sectionName = itemName;

            while (sectionName)
            {
                // allow multi-level tree
                TCHAR* pItemName = sectionName;
                HTREEITEM hItem;

                if (sectionName = _tcschr(sectionName, '/'))
                {
                    // one level deeper
                    *sectionName = 0;
                    sectionName++;
                }

                hItem = OptTree_FindNamedTreeItemAt(hwndTree, hSection, pItemName);
                //if (!sectionName || !hItem)
                if ((!sectionName || !hItem) && !(options[indx].dwFlag & OPTTREE_INVISIBLE))
                {
                    if (!hItem)
                    {
                        TVINSERTSTRUCT tvis = {0};

                        tvis.hParent = hSection;
                        tvis.hInsertAfter = TVI_LAST;//TVI_SORT;
                        tvis.item.mask = TVIF_TEXT|TVIF_PARAM|TVIF_STATE|TVIF_IMAGE|TVIF_SELECTEDIMAGE;
                        tvis.item.pszText = pItemName;
                        tvis.item.state = tvis.item.stateMask = TVIS_EXPANDED;
                        if (sectionName)
                        {
                            tvis.item.lParam = -1;
                            tvis.item.state |= TVIS_BOLD;
                            tvis.item.stateMask |= TVIS_BOLD;
                            tvis.item.iImage = tvis.item.iSelectedImage = IMG_GRPOPEN;
                        } else
                        {
                            tvis.item.lParam = indx;
                            if (options[indx].groupId == OPTTREE_CHECK)
                            {
                                tvis.item.iImage = tvis.item.iSelectedImage = IMG_NOCHECK;
                            } else
                            {
                                tvis.item.iImage = tvis.item.iSelectedImage = IMG_NORCHECK;
                            }
                        }
                        hItem = TreeView_InsertItem(hwndTree, &tvis);
                        if (!sectionName)
                            options[indx].hItem = hItem;
                    }
                }
                sectionLevel++;
                hSection = hItem;
            }
        }

        OptTree_Translate(hwndTree);
        ShowWindow(hwndTree, SW_SHOW);
        TreeView_SelectItem(hwndTree, OptTree_FindNamedTreeItemAt(hwndTree, 0, NULL));
        break;
    }

    case WM_DESTROY:
    {
        ImageList_Destroy(TreeView_GetImageList(hwndTree, TVSIL_NORMAL));
        break;
    }

    case WM_NOTIFY:
    {
        LPNMHDR lpnmhdr = (LPNMHDR)lparam;
        if (lpnmhdr->idFrom != idcTree) break;
        switch (lpnmhdr->code)
        {
        case NM_CLICK:
        {
            TVHITTESTINFO hti;
            hti.pt.x=(short)LOWORD(GetMessagePos());
            hti.pt.y=(short)HIWORD(GetMessagePos());
            ScreenToClient(lpnmhdr->hwndFrom,&hti.pt);
            if(TreeView_HitTest(lpnmhdr->hwndFrom,&hti))
            {
                if(hti.flags&TVHT_ONITEMICON)
                {
                    TVITEM tvi;
                    tvi.mask=TVIF_HANDLE|TVIF_PARAM|TVIF_IMAGE|TVIF_SELECTEDIMAGE;
                    tvi.hItem=hti.hItem;
                    TreeView_GetItem(lpnmhdr->hwndFrom,&tvi);
                    switch (tvi.iImage)
                    {
                    case IMG_GRPOPEN:
                        tvi.iImage = tvi.iSelectedImage = IMG_GRPCLOSED;
                        TreeView_Expand(lpnmhdr->hwndFrom, tvi.hItem, TVE_COLLAPSE);
                        break;
                    case IMG_GRPCLOSED:
                        tvi.iImage = tvi.iSelectedImage = IMG_GRPOPEN;
                        TreeView_Expand(lpnmhdr->hwndFrom, tvi.hItem, TVE_EXPAND);
                        break;

                    case IMG_CHECK:
                        tvi.iImage = tvi.iSelectedImage = IMG_NOCHECK;
                        SendMessage(GetParent(hwnd), PSM_CHANGED, 0, 0);
                        break;
                    case IMG_NOCHECK:
                        tvi.iImage = tvi.iSelectedImage = IMG_CHECK;
                        SendMessage(GetParent(hwnd), PSM_CHANGED, 0, 0);
                        break;
                    case IMG_NORCHECK:
                    {
                        int i;
                        for (i = 0; i < optionCount; ++i)
                        {
                            if (options[i].groupId == options[tvi.lParam].groupId)
                            {
                                TVITEM tvi_tmp;
                                tvi_tmp.mask = TVIF_HANDLE|TVIF_IMAGE|TVIF_SELECTEDIMAGE;
                                tvi_tmp.hItem = options[i].hItem;
                                tvi_tmp.iImage = tvi_tmp.iSelectedImage = IMG_NORCHECK;
                                TreeView_SetItem(lpnmhdr->hwndFrom, &tvi_tmp);
                            }
                        }
                        tvi.iImage = tvi.iSelectedImage = IMG_RCHECK;
                        SendMessage(GetParent(hwnd), PSM_CHANGED, 0, 0);
                        break;
                    }
                    }
                    TreeView_SetItem(lpnmhdr->hwndFrom,&tvi);
                }
            }
            break;
        }

        case TVN_ITEMEXPANDEDW:
        {
            LPNMTREEVIEWW lpnmtv = (LPNMTREEVIEWW)lparam;
            TVITEM tvi;
            tvi.mask=TVIF_HANDLE|TVIF_IMAGE|TVIF_SELECTEDIMAGE;
            tvi.hItem = lpnmtv->itemNew.hItem;
            tvi.iImage = tvi.iSelectedImage =
                             (lpnmtv->itemNew.state & TVIS_EXPANDED) ? IMG_GRPOPEN : IMG_GRPCLOSED;
            SendMessageW(lpnmhdr->hwndFrom, TVM_SETITEMW, 0, (LPARAM)&tvi);
            break;
        }

        case TVN_ITEMEXPANDEDA:
        {
            LPNMTREEVIEWA lpnmtv = (LPNMTREEVIEWA)lparam;
            TVITEM tvi;
            tvi.mask=TVIF_HANDLE|TVIF_IMAGE|TVIF_SELECTEDIMAGE;
            tvi.hItem = lpnmtv->itemNew.hItem;
            tvi.iImage = tvi.iSelectedImage =
                             (lpnmtv->itemNew.state & TVIS_EXPANDED) ? IMG_GRPOPEN : IMG_GRPCLOSED;
            SendMessageA(lpnmhdr->hwndFrom, TVM_SETITEMA, 0, (LPARAM)&tvi);
            break;
        }
        }
        break;
    }
    }
    return FALSE;
}
BOOL CJabberProto::OnRosterPushRequest(HXML, CJabberIqInfo *pInfo)
{
	HXML queryNode = pInfo->GetChildNode();

	// RFC 3921 #7.2 Business Rules
	if (pInfo->GetFrom()) {
		TCHAR *szFrom = JabberPrepareJid(pInfo->GetFrom());
		if (!szFrom)
			return TRUE;

		TCHAR *szTo = JabberPrepareJid(m_ThreadInfo->fullJID);
		if (!szTo) {
			mir_free(szFrom);
			return TRUE;
		}

		TCHAR *pDelimiter = _tcschr(szFrom, _T('/'));
		if (pDelimiter) *pDelimiter = 0;

		pDelimiter = _tcschr(szTo, _T('/'));
		if (pDelimiter) *pDelimiter = 0;

		BOOL bRetVal = _tcscmp(szFrom, szTo) == 0;

		mir_free(szFrom);
		mir_free(szTo);

		// invalid JID
		if (!bRetVal) {
			debugLogA("<iq/> attempt to hack via roster push from %S", pInfo->GetFrom());
			return TRUE;
		}
	}

	JABBER_LIST_ITEM *item;
	HANDLE hContact = NULL;
	const TCHAR *jid, *str, *name;
	TCHAR *nick;

	debugLogA("<iq/> Got roster push, query has %d children", xmlGetChildCount(queryNode));
	for (int i=0; ; i++) {
		HXML itemNode = xmlGetChild(queryNode ,i);
		if (!itemNode)
			break;

		if (_tcscmp(xmlGetName(itemNode), _T("item")) != 0)
			continue;
		if ((jid = xmlGetAttrValue(itemNode, _T("jid"))) == NULL)
			continue;
		if ((str = xmlGetAttrValue(itemNode, _T("subscription"))) == NULL)
			continue;

		// we will not add new account when subscription=remove
		if (!_tcscmp(str, _T("to")) || !_tcscmp(str, _T("both")) || !_tcscmp(str, _T("from")) || !_tcscmp(str, _T("none"))) {
			if ((name = xmlGetAttrValue(itemNode, _T("name"))) != NULL)
				nick = mir_tstrdup(name);
			else
				nick = JabberNickFromJID(jid);

			if (nick != NULL) {
				if ((item=ListAdd(LIST_ROSTER, jid)) != NULL) {
					replaceStrT(item->nick, nick);

					HXML groupNode = xmlGetChild(itemNode , "group");
					replaceStrT(item->group, xmlGetText(groupNode));

					if ((hContact=HContactFromJID(jid, 0)) == NULL) {
						// Received roster has a new JID.
						// Add the jid (with empty resource) to Miranda contact list.
						hContact = DBCreateContact(jid, nick, FALSE, FALSE);
					}
					else setTString(hContact, "jid", jid);

					if (name != NULL) {
						ptrT tszNick( getTStringA(hContact, "Nick"));
						if (tszNick != NULL) {
							if (_tcscmp(nick, tszNick) != 0)
								db_set_ts(hContact, "CList", "MyHandle", nick);
							else
								db_unset(hContact, "CList", "MyHandle");
						}
						else db_set_ts(hContact, "CList", "MyHandle", nick);
					}
					else db_unset(hContact, "CList", "MyHandle");

					if (!m_options.IgnoreRosterGroups) {
						if (item->group != NULL) {
							Clist_CreateGroup(0, item->group);
							db_set_ts(hContact, "CList", "Group", item->group);
						}
						else db_unset(hContact, "CList", "Group");
					}
				}
				mir_free(nick);
			}
		}

		if ((item=ListGetItemPtr(LIST_ROSTER, jid)) != NULL) {
			if (!_tcscmp(str, _T("both"))) item->subscription = SUB_BOTH;
			else if (!_tcscmp(str, _T("to"))) item->subscription = SUB_TO;
			else if (!_tcscmp(str, _T("from"))) item->subscription = SUB_FROM;
			else item->subscription = SUB_NONE;
			debugLogA("Roster push for jid=%S, set subscription to %S", jid, str);
			// subscription = remove is to remove from roster list
			// but we will just set the contact to offline and not actually
			// remove, so that history will be retained.
			if (!_tcscmp(str, _T("remove"))) {
				if ((hContact=HContactFromJID(jid)) != NULL) {
					SetContactOfflineStatus(hContact);
					ListRemove(LIST_ROSTER, jid);
				}
			}
			else if ( isChatRoom(hContact))
				db_unset(hContact, "CList", "Hidden");
			else
				UpdateSubscriptionInfo(hContact, item);
		}
	}

	UI_SAFE_NOTIFY(m_pDlgServiceDiscovery, WM_JABBER_TRANSPORT_REFRESH);
	RebuildInfoFrame();
	return TRUE;
}
static const TCHAR *rawcmdline(void)
{
  #if defined __WIN32__ || defined _WIN32 || defined WIN32
  #elif defined _Windows || defined __MSDOS__
    static char cmdbuffer[128];   /* DOS & Windows 3.1 are never in Unicode mode */
  #elif defined __LINUX__
    static char cmdbuffer[1024];  /* some arbitrary maximum */
  #endif
  const TCHAR *ptr;
  int skip = 0;

  if (cmdline == NULL) {
    #if defined __WIN32__ || defined _WIN32 || defined WIN32
      cmdline = GetCommandLine();
      skip++;
    #elif defined _Windows || defined __MSDOS__
      #if defined _Windows
        unsigned short _psp = GetCurrentPDB();
      #endif
      char _far *cmd = (char _far *)MK_FP(_psp, 128);
      unsigned char length = (unsigned char)*cmd++;
      assert(length < 128);
      assert(length < sizeof cmdbuffer);
      memcpy(cmdbuffer, cmd, length);
      cmdbuffer[length] = '\0';
      if ((cmd == strchr(cmdbuffer, '\r')) != NULL)
        *cmd = '\0';    /* also erase \r after the last option (if any) */
      cmdline = cmdbuffer;
    #elif defined __LINUX__
      /* Options in /proc/<pid>/cmdline are delimited with '\0' characters
       * rather than spaces.
       */
      FILE *fp;
      size_t fsize;
      sprintf(cmdbuffer, "/proc/%d/cmdline", getpid());
      if ((fp = fopen(cmdbuffer, "r")) != NULL) {
        char *ptr;
        fseek(fp, 0, SEEK_END);
        fsize = ftell(fp);
        fseek(fp, 0, SEEK_SET);
        if (fsize >= sizeof cmdbuffer)
          fsize = sizeof cmdbuffer - 1;
        fread(cmdbuffer, 1, fsize, fp);
        fclose(fp);
        cmdbuffer[fsize] = '\0';        /* terminate with double-zero */
        /* convert '\0' characters to spaces, for uniform parsing */
        for (ptr = cmdbuffer; *ptr != ' '; ptr = strchr(ptr, '\0') + 1)
          *ptr = ' ';
        cmdline = cmdbuffer;
        skip++;
      } /* if */
    #else
      #error Platform not supported
    #endif

    /* skip leading white space */
    while (*cmdline <= __T(' ') && *cmdline != __T('\0'))
      cmdline++;

    #if AMXARGS_SKIPARG
      skip++;
    #endif
    /* skip the first option(s), because it is the name of the host program
     * and the name of the script
     */
    if ((ptr = tokenize(cmdline, skip, NULL)) != NULL)
      cmdline = ptr;
    else
      cmdline = _tcschr(cmdline, __T('\0'));

  } /* if */

  return cmdline;
}