Beispiel #1
0
/*
static struct unload
{
	IAgent* agent;
	~unload()
	{
		if(!agent)
			return;
		LPCRITICAL_SECTION gcs;
		agent->GetGlobalCriticalSection( &gcs );
		LeaveCriticalSection( gcs );
	}
} _unload;
*/
#pragma warning(disable:4995)
DWORD g_sessionId = DWORD(-1);

//bool  GetGlobalData( IAgent* agent,
//				    DWORD sessionId );
bool  TaskReceive( net_task &task,IAgent* agent,
					DWORD sessionId, 
					IGenericStream* inStream );

class net_task_interface_impl : public net_task_interface
{
 


 bool  TaskReceive( net_task &task,IAgent* agent,
					DWORD sessionId, 
					IGenericStream* inStream )
Beispiel #2
0
MappedFile::Handle MappedFile::Map(uint64_t offset, uint64_t size, string const & tag) const
{
#ifdef OMIM_OS_WINDOWS
  SYSTEM_INFO sysInfo;
  memset(&sysInfo, 0, sizeof(sysInfo));
  GetSystemInfo(&sysInfo);
  long const align = sysInfo.dwAllocationGranularity;
#else
  long const align = sysconf(_SC_PAGE_SIZE);
#endif

  uint64_t const alignedOffset = (offset / align) * align;
  ASSERT_LESS_OR_EQUAL(alignedOffset, offset, ());
  uint64_t const length = size + (offset - alignedOffset);
  ASSERT_GREATER_OR_EQUAL(length, size, ());

#ifdef OMIM_OS_WINDOWS
  void * pMap = MapViewOfFile(m_hMapping, FILE_MAP_READ, alignedOffset >> (sizeof(DWORD) * 8), DWORD(alignedOffset), length);
  if (pMap == NULL)
    MYTHROW(Reader::OpenException, ("Can't map section:", tag, "with [offset, size]:", offset, size, "win last error:", GetLastError()));
#else
  void * pMap = mmap(0, length, PROT_READ, MAP_SHARED, m_fd, alignedOffset);
  if (pMap == MAP_FAILED)
    MYTHROW(Reader::OpenException, ("Can't map section:", tag, "with [offset, size]:", offset, size, "errno:", strerror(errno)));
#endif

  char const * data = reinterpret_cast<char const *>(pMap);
  char const * d = data + (offset - alignedOffset);
  return Handle(d, data, size, length);
}
Beispiel #3
0
HRESULT CZlib::EncodeFile( LPCWSTR lpwszSrcFile, LPCWSTR lpwszDstFile, int level )
{
    if ( zlib_compress )
    {
        CAtlFile hInFile;
        HRESULT hr = hInFile.Create(
            lpwszSrcFile,
            GENERIC_READ,
            FILE_SHARE_READ | FILE_SHARE_DELETE,
            OPEN_EXISTING);
        if (FAILED(hr))
            return hr;

        CAtlFile hOutFile;
        hr = hOutFile.Create(
            lpwszDstFile,
            GENERIC_WRITE,
            FILE_SHARE_READ | FILE_SHARE_DELETE,
            CREATE_ALWAYS);
        if (FAILED(hr))
            return hr;

        ULONGLONG uInFileSize = 0;
        hr = hInFile.GetSize(uInFileSize);
        if (FAILED(hr))
            return hr;

        // 0长度文件不需要压缩
        if (0 == uInFileSize)
            return S_OK;

        // 太大的文件不压缩
        if (uInFileSize >  ZLIB_SINGLE_FILE_MAX_SIZE ) //假定压缩比为4:1
            return E_FAIL;

        // 读取输入
        CAtlArray<BYTE> bufRead;
        bufRead.SetCount((size_t)uInFileSize);
        if (uInFileSize != bufRead.GetCount())
            return E_OUTOFMEMORY;

        hr = hInFile.Read(bufRead.GetData(), (DWORD)bufRead.GetCount());
        if (FAILED(hr))
            return hr;

        // 准备压缩
        ULONGLONG uOutFileSize = max(uInFileSize, ZLIB_DECOMPRESS_INIT_BUFF_SIZE);
        CAtlArray<BYTE> bufWrite;
        try
        {
            while (uOutFileSize <= ZLIB_SINGLE_FILE_MAX_SIZE )
            {
                bufWrite.SetCount(0);
                bufWrite.SetCount((DWORD)uOutFileSize);
                if (uOutFileSize != bufWrite.GetCount())
                    return E_OUTOFMEMORY;

                DWORD dwcompressSize = DWORD(uOutFileSize);
                int nRet = zlib_compress2(
                    bufWrite.GetData(),
                    &dwcompressSize,
                    bufRead.GetData(),
                    (int)bufRead.GetCount(),
                    level
                    );
                if (nRet == Z_OK && dwcompressSize <= uOutFileSize)
                {
                    bufWrite.SetCount(dwcompressSize);
                    break;
                }

                if (nRet != Z_BUF_ERROR)
                    return E_FAIL;

                uOutFileSize *= 2;
            }	
        }
        catch (...)
        {
            return E_FAIL;
        }

        hr = hOutFile.Write(bufWrite.GetData(), (DWORD)bufWrite.GetCount());
        if (FAILED(hr))
            return hr;

        return S_OK;
    }
    else
    {
        return E_NOINTERFACE;
    }
}
bool vmsArchiveRAR::Extract(LPCSTR pszArchive, LPCSTR pszOutFolder)
{
	m_errExtract = AEE_GENERIC_ERROR;

	if (m_unrar.is_Loaded () == false) {
		if (false == m_unrar.Load ("Archive\\unrar.dll"))
			return false;
	}

	HANDLE hFile = CreateFile (pszArchive, GENERIC_READ, FILE_SHARE_READ, NULL, 
		OPEN_EXISTING, 0, NULL);
	if (hFile == INVALID_HANDLE_VALUE)
		return false;
	DWORD dwPkdSize = GetFileSize (hFile, NULL);
	CloseHandle (hFile);

	HANDLE hArcData;
	int RHCode, PFCode;
	char CmtBuf [16384];
	RARHeaderData HeaderData;
	RAROpenArchiveDataEx OpenArchiveData;

	ZeroMemory (&OpenArchiveData, sizeof (OpenArchiveData));
	OpenArchiveData.ArcName = (LPSTR)pszArchive;
	OpenArchiveData.CmtBuf = CmtBuf;
	OpenArchiveData.CmtBufSize = sizeof (CmtBuf);
	OpenArchiveData.OpenMode = RAR_OM_EXTRACT;
	
	hArcData = m_unrar.RAROpenArchiveEx (&OpenArchiveData);

	if (hArcData == NULL || OpenArchiveData.OpenResult != 0)
		return false;

	
	

	HeaderData.CmtBuf = NULL;
	DWORD dwProcessed = 0;

	CString strOutFolder = pszOutFolder;
	if (strOutFolder [strOutFolder.GetLength () - 1] != '\\')
		strOutFolder += '\\';

	vmsAC_OverwriteMode enOM;
	bool bAskOverwrite = true;

	TIME_ZONE_INFORMATION tzi;
	GetTimeZoneInformation (&tzi);

	while ((RHCode = m_unrar.RARReadHeader (hArcData, &HeaderData)) == 0)
	{
		bool bSkip = false;

		if (m_pAC) {
			if (false == m_pAC->BeforeExtract (HeaderData.FileName)) {
				RHCode = ERAR_END_ARCHIVE;
				break;
			}

			DWORD dwAttr = GetFileAttributes (strOutFolder + HeaderData.FileName);
			if (dwAttr != DWORD (-1) && (dwAttr & FILE_ATTRIBUTE_DIRECTORY) == 0)
			{
				if (bAskOverwrite)
				{
					vmsOverwriteFileInfo ofi;
					bool bForAll = false;

					CString strFile = strOutFolder + HeaderData.FileName;
					ofi.pszFile = strFile;
					UINT64 u = HeaderData.UnpSize;
					FILETIME time;
					DosDateTimeToFileTime (HIWORD (HeaderData.FileTime),
						LOWORD (HeaderData.FileTime), &time);
					*((UINT64*)&time) += Int32x32To64 (tzi.Bias, 60 * 10000000);
					ofi.ptimeNewLastWrite = &time;
					ofi.puNewSize = &u;

					m_pAC->AskOverwrite (ofi, enOM, bForAll);

					if (enOM == AC_OM_CANCEL) {
						m_errExtract = AEE_ABORTED_BY_USER;
						break;
					}

					if (bForAll)
						bAskOverwrite = false;
				}

				if (enOM == AC_OM_SKIP)
					bSkip = true;
			}
		}

		PFCode = m_unrar.RARProcessFile (hArcData, bSkip ? RAR_SKIP : RAR_EXTRACT, 
			(LPSTR)pszOutFolder, NULL);

		if (PFCode == 0) {
			if (m_pAC) {
				m_pAC->AfterExtract (HeaderData.FileName, AC_ER_OK);
				dwProcessed += HeaderData.PackSize;
				m_pAC->SetProgress (MulDiv (dwProcessed, 100, dwPkdSize));
			}
		}
		else
		{
			if (m_pAC)
				m_pAC->AfterExtract (HeaderData.FileName, AC_ER_FAILED);
			break;
		}
	}

	m_unrar.RARCloseArchive (hArcData);

	if (RHCode == ERAR_END_ARCHIVE)
		m_errExtract = AEE_NO_ERROR;

	return RHCode == ERAR_END_ARCHIVE;
}
Beispiel #5
0
// Saves the dialog in the form of DLGTEMPLATE[EX]
BYTE* CDialogTemplate::Save(DWORD& dwSize) {
  // We need the size first to know how much memory to allocate
  dwSize = GetSize();
  BYTE* pbDlg = new BYTE[dwSize];
  ZeroMemory(pbDlg, dwSize);
  BYTE* seeker = pbDlg;

  if (m_bExtended) {
    DLGTEMPLATEEX dh = {
      0x0001,
      0xFFFF,
      m_dwHelpId,
      m_dwExtStyle,
      m_dwStyle,
      m_vItems.size(),
      m_sX,
      m_sY,
      m_sWidth,
      m_sHeight
    };

    CopyMemory(seeker, &dh, sizeof(DLGTEMPLATEEX));
    seeker += sizeof(DLGTEMPLATEEX);
  }
  else {
    DLGTEMPLATE dh = {
      m_dwStyle,
      m_dwExtStyle,
      m_vItems.size(),
      m_sX,
      m_sY,
      m_sWidth,
      m_sHeight
    };

    CopyMemory(seeker, &dh, sizeof(DLGTEMPLATE));
    seeker += sizeof(DLGTEMPLATE);
  }

  // Write menu variant length array
  WriteStringOrId(m_szMenu);
  // Write class variant length array
  WriteStringOrId(m_szClass);
  // Write title variant length array
  WriteStringOrId(m_szTitle);

  // Write font variant length array, size, and extended info (if needed)
  if (m_dwStyle & DS_SETFONT) {
    *(short*)seeker = m_sFontSize;
    seeker += sizeof(short);
    if (m_bExtended) {
      *(short*)seeker = m_sFontWeight;
      seeker += sizeof(short);
      *(BYTE*)seeker = m_bItalic;
      seeker += sizeof(BYTE);
      *(BYTE*)seeker = m_bCharset;
      seeker += sizeof(BYTE);
    }
    WriteStringOrId(m_szFont);
  }

  // Write all of the items
  for (unsigned int i = 0; i < m_vItems.size(); i++) {
    // DLGITEMTEMPLATE[EX]s must be aligned on DWORD boundry
    if (DWORD(seeker - pbDlg) % sizeof(DWORD))
      seeker += sizeof(WORD);

    if (m_bExtended) {
      DLGITEMTEMPLATEEX dih = {
        m_vItems[i]->dwHelpId,
        m_vItems[i]->dwExtStyle,
        m_vItems[i]->dwStyle,
        m_vItems[i]->sX,
        m_vItems[i]->sY,
        m_vItems[i]->sWidth,
        m_vItems[i]->sHeight,
        m_vItems[i]->wId
      };

      CopyMemory(seeker, &dih, sizeof(DLGITEMTEMPLATEEX));
      seeker += sizeof(DLGITEMTEMPLATEEX);
    }
    else {
      DLGITEMTEMPLATE dih = {
        m_vItems[i]->dwStyle,
        m_vItems[i]->dwExtStyle,
        m_vItems[i]->sX,
        m_vItems[i]->sY,
        m_vItems[i]->sWidth,
        m_vItems[i]->sHeight,
        m_vItems[i]->wId
      };

      CopyMemory(seeker, &dih, sizeof(DLGITEMTEMPLATE));
      seeker += sizeof(DLGITEMTEMPLATE);
    }

    // Write class variant length array
    WriteStringOrId(m_vItems[i]->szClass);
    // Write title variant length array
    WriteStringOrId(m_vItems[i]->szTitle);

    // Write creation data variant length array
    // First write its size
    if (m_vItems[i]->wCreateDataSize) m_vItems[i]->wCreateDataSize += sizeof(WORD);
    *(WORD*)seeker = m_vItems[i]->wCreateDataSize;
    seeker += sizeof(WORD);
    // If size is nonzero write the data too
    if (m_vItems[i]->wCreateDataSize) {
      CopyMemory(seeker, m_vItems[i]->szCreationData, m_vItems[i]->wCreateDataSize);
      seeker += m_vItems[i]->wCreateDataSize;
    }
  }

  // DONE!
  return pbDlg;
}
BOOL CSetOverlayHandlers::OnApply()
{
	UpdateData();

	if (DWORD(m_regShowIgnoredOverlay) != DWORD(m_bShowIgnoredOverlay))
		m_restart = Restart_System;
	Store (m_bShowIgnoredOverlay, m_regShowIgnoredOverlay);

	if (DWORD(m_regShowUnversionedOverlay) != DWORD(m_bShowUnversionedOverlay))
		m_restart = Restart_System;
	Store (m_bShowUnversionedOverlay, m_regShowUnversionedOverlay);

	if (DWORD(m_regShowAddedOverlay) != DWORD(m_bShowAddedOverlay))
		m_restart = Restart_System;
	Store (m_bShowAddedOverlay, m_regShowAddedOverlay);

	if (DWORD(m_regShowLockedOverlay) != DWORD(m_bShowLockedOverlay))
		m_restart = Restart_System;
	Store (m_bShowLockedOverlay, m_regShowLockedOverlay);

	if (DWORD(m_regShowReadonlyOverlay) != DWORD(m_bShowReadonlyOverlay))
		m_restart = Restart_System;
	Store (m_bShowReadonlyOverlay, m_regShowReadonlyOverlay);

	if (DWORD(m_regShowDeletedOverlay) != DWORD(m_bShowDeletedOverlay))
		m_restart = Restart_System;
	Store (m_bShowDeletedOverlay, m_regShowDeletedOverlay);


	SetModified(FALSE);
	return ISettingsPropPage::OnApply();
}
	void CEditRenderPipeline::SetRenderStyle( const STATIC_RS& RenderStyle )
	{
		//m_pipeline->SetRenderStyle(RenderStyle);
		//return ;

		m_GraphicRenderStyle.m_Material = RenderStyle.m_Material;
		CRenderPipeline::GetInst()->SetShader(RenderStyle.m_ShaderType);
		_SetMaterial( m_GraphicRenderStyle.m_Material );
		_SetRenderStyle ( RS_ALPHAREF, RenderStyle.m_Alpharef );

		if (m_GraphicRenderStyle.m_Texturefactor!=RenderStyle.m_Texturefactor || bReFreshTexFactor)
		{
			m_GraphicRenderStyle.m_Texturefactor = RenderStyle.m_Texturefactor;
			_SetRenderStyle ( RS_TEXTUREFACTOR, m_GraphicRenderStyle.m_Texturefactor );
			CColor4 factor = m_GraphicRenderStyle.m_Texturefactor;
			SetFragmentShaderF(ACT_TEXTURE_FACTOR, factor.r, factor.g, factor.b, factor.a);
			bReFreshTexFactor = false;
		}

		float	Params[4];
		Params[0] = (float)RenderStyle.m_Alpharef;
		Params[1] = (float)RenderStyle.m_Material.Diffuse.a;
		Params[2] = (float)RenderStyle.m_Material.Specular.a;
		SetVertexShaderF(ACT_TEXTURE_FACTOR,Params,1);

		CColor4 tSpecular(0.0f,0.0f,0.0f,0.0f);
		if (RenderStyle.m_SpecularEnable)
		{
			tSpecular = m_GraphicRenderStyle.m_Material.Specular;
			tSpecular.a = m_GraphicRenderStyle.m_Material.Power;
		}

		SetVertexShaderF(ACT_MAT_DIFFUSE_COLOR	, (float*)&m_GraphicRenderStyle.m_Material.Diffuse, 1);
		SetVertexShaderF(ACT_MAT_AMBIENT_COLOR	, (float*)&m_GraphicRenderStyle.m_Material.Ambient, 1);
		SetVertexShaderF(ACT_MAT_SPECULAR_COLOR	, (float*)&tSpecular, 1);
		SetVertexShaderF(ACT_MAT_EMISSIVE_COLOR	, (float*)&m_GraphicRenderStyle.m_Material.Emissive, 1);
		
		SetVertexShaderF(ACT_REFRACT_SCALAR	, RenderStyle.m_fRefractIndex);
		SetVertexShaderF(ACT_UV_INDEX , float(RenderStyle.m_Uv_S0) , float(RenderStyle.m_Uv_S1) , float(RenderStyle.m_Uv_S2) );

		//_SetRenderStyle ( RS_SLOPESCALEDEPTHBIAS, *(DWORD*)&(RenderStyle.m_fSlopeScaleZBias));
		_SetRenderStyle ( RS_DEPTHBIAS, *(DWORD*)&(RenderStyle.m_fZBias));
		_SetRenderStyle ( RS_ALPHABLENDENABLE,  RenderStyle.m_AlphaBlendEnable );
		_SetRenderStyle ( RS_SRCBLEND, RenderStyle.m_SrcBlend );
		_SetRenderStyle ( RS_DESTBLEND, RenderStyle.m_DestBlend );
		_SetRenderStyle ( RS_ALPHATESTENABLE,  RenderStyle.m_AlphaTestEnable );
		_SetRenderStyle ( RS_ALPHAFUNC, RenderStyle.m_AlphaTestFun );
		_SetRenderStyle ( RS_LIGHTING, RenderStyle.m_LightEnable );
		_SetRenderStyle ( RS_SPECULARENABLE,  RenderStyle.m_SpecularEnable );
		_SetRenderStyle ( RS_ZENABLE,  RenderStyle.m_ZTestEnable );
		_SetRenderStyle ( RS_ZFUNC,  RenderStyle.m_ZTestFun );
		_SetRenderStyle ( RS_ZWRITEENABLE, RenderStyle.m_ZWrite );
		_SetRenderStyle ( RS_CULLMODE, RenderStyle.m_Cull );
		_SetRenderStyle ( RS_FILLMODE, RenderStyle.m_FillMode );
		bool isClipPlaneValid = RenderStyle.m_ClipPlane.IsValid();
		if (isClipPlaneValid)
		{
			CPlane plane = RenderStyle.m_ClipPlane;
			if (RenderStyle.m_ShaderType.GetVSShaderID())
			{
				// transform to clipping space
				CMatrix transform = m_CurViewProj;
				MatrixInverse(transform);
				transform.Transpose();
				plane.Transform(transform);
			}
			_SetClipPlane(0, plane);
		}
		_SetRenderStyle( RS_CLIPPLANEENABLE, DWORD(isClipPlaneValid ? CLIPPLANE0 : 0) );
		SetTextureEx(RenderStyle);
	}
Beispiel #8
0
void HwRender::setTextureTransform(int stage, const D3DXMATRIX *matrix)
{
	setTextureStageState(stage, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);
	setTransform(D3DTRANSFORMSTATETYPE(DWORD(D3DTS_TEXTURE0) + stage), matrix);
}
Beispiel #9
0
//确认道具
void CPropertyItem::OnBnClickedOk()
{
	//合法判断
	if ( m_nPropCount <= 0 || m_nPropCount > MAX_PROPERTY_COUNT )
	{
		CString strError;
		strError.Format(TEXT("赠送数目必须大于0且小于等于%d"), MAX_PROPERTY_COUNT);
		ShowInformationEx(strError,0,MB_ICONINFORMATION,TEXT("系统消息"));
		GetDlgItem(IDC_PURCHASE_COUNT)->SetFocus();
		((CEdit*)GetDlgItem(IDC_PURCHASE_COUNT))->SetSel(0,-1);

		return ;
	}

	//查找用户
	DWORD dwTargetUserID=0;
	tagUserData *pTargetUserData=NULL;
	CString strTargetName;
	if(!m_bPlazaRoom)
	{
		int nSelectItem = m_ComboBoxTargetUser.GetCurSel();
		if ( CB_ERR == nSelectItem ) return;

		//获取信息
		dwTargetUserID = DWORD(m_ComboBoxTargetUser.GetItemData(nSelectItem));
		m_ComboBoxTargetUser.GetLBText(nSelectItem, strTargetName);
		pTargetUserData = m_pIPurchaseInfo->SearchUserItem(dwTargetUserID);
	}
	else
	{
		//获取信息
		GetDlgItem(IDC_PRO_USER_ID)->GetWindowText(strTargetName);
		pTargetUserData = m_pIPurchaseInfo->SearchUserItem(strTargetName);
		if (pTargetUserData!=NULL)dwTargetUserID=pTargetUserData->dwUserID;
	}

	//判断在线
	if ( pTargetUserData == NULL )
	{
		CString strMessage;
		strMessage.Format(TEXT("[ % ]已经离开,请重新选择!"), strTargetName);
		ShowInformation(strMessage,0,MB_ICONINFORMATION);
		return;
	}

	//类型判断
	WORD wGameGenre= m_pIPurchaseInfo->GetGameGenre();

	if ( wGameGenre == GAME_GENRE_GOLD && ( m_nPropertyID==PROP_NEGAGIVE || m_nPropertyID == PROP_DOUBLE || m_nPropertyID == PROP_FOURDOLD ))
	{
		ShowInformation(TEXT("游戏币房间不可以使用此功能!"),0,MB_ICONINFORMATION);
		return ;
	}
	if ( wGameGenre == GAME_GENRE_MATCH && ( m_nPropertyID==PROP_NEGAGIVE || m_nPropertyID == PROP_DOUBLE ||
		m_nPropertyID == PROP_FOURDOLD || m_nPropertyID == PROP_BUGLE ))
	{
		ShowInformation(TEXT("比赛房间不可以使用此功能!"),0,MB_ICONINFORMATION);
		return ;
	}

	//获取玩家
	const tagUserData *pMeUserData = m_pIPurchaseInfo->GetMeUserInfo();

	//获取价格
	LONG lNormalPrice = 0, lMemberPrice = 0;
	GetPropertyPrice(lNormalPrice, lMemberPrice);
	
	//判断金额
	LONG lMePrice = pMeUserData->cbMemberOrder ? lMemberPrice : lNormalPrice;
	LONG lMeScore = pMeUserData->lInsureScore;
	if ( lMeScore < lMePrice )
	{
		if ( IDYES == ShowInformation(TEXT("您的游戏币不足,是否充值?"),0,MB_ICONQUESTION|MB_YESNO|MB_DEFBUTTON2) )	
		{
			ShellExecute(NULL,TEXT("open"),TEXT("http://www.123.com"),NULL,NULL,SW_SHOWDEFAULT);
		}
		
		return;
	}

	//设置数据
	CMD_GF_Property PropertyHeadInfo;
	ZeroMemory(&PropertyHeadInfo, sizeof(PropertyHeadInfo));
	PropertyHeadInfo.cbSendLocation = m_pIPurchaseInfo->GetLocation();
	PropertyHeadInfo.nPropertyID = m_nPropertyID;
	PropertyHeadInfo.dwSourceUserID = pMeUserData->dwUserID;
	PropertyHeadInfo.dwTargetUserID = dwTargetUserID;
	PropertyHeadInfo.dwPachurseCount = m_nPropCount;
	PropertyHeadInfo.dwOnceCount = (DWORD)m_nPropertyType;

	//发送数据
	m_pIPurchaseInfo->SendData(MDM_GF_PRESENT, SUB_GF_PROPERTY, &PropertyHeadInfo, sizeof(PropertyHeadInfo));

	OnOK();
	return;
}
Beispiel #10
0
UINT ExtractIcons::_ExtractFromExe( HANDLE hFile, int iconIndex, 
                                   int cxIconSize, int cyIconSize, 
                                   HICON *phicon, UINT *piconid, 
                                   UINT maxIcons, UINT flags )
{
    DWORD fileLen = GetFileSize( hFile, NULL );
    SmartHANDLE hFileMap( CreateFileMapping( hFile, NULL, PAGE_READONLY, 0, 0, NULL ) );
    if( hFileMap == NULL )
        return 0;

    SmartFileMapping pFile( MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 0) );
    if( pFile == NULL )
        return 0;

    IMAGE_DOS_HEADER* pDosHeader = (IMAGE_DOS_HEADER*)(void*)pFile;
    if( pDosHeader->e_magic != IMAGE_DOS_SIGNATURE )
        return 0;
    if( pDosHeader->e_lfanew <= 0 )
        return 0;
    if( DWORD(pDosHeader->e_lfanew) >= fileLen )
        return 0;

    void* pRes = _GetResourceTable( pDosHeader );
    if( pRes == NULL)
        return 0; // cant find the resource 

    DWORD cbSize = 0;

    if( phicon == NULL )
    {
        //  we want the count
        int count = _FindResourceCount( pRes, (INT_PTR)RT_GROUP_ICON );
        return count;
    }

    UINT res = 0;
    while( res < maxIcons )
    {
        //  find the icon dir for this icon.
        NEWHEADER* pIconDir = (NEWHEADER*)_FindResource( pDosHeader, pRes, iconIndex, (INT_PTR)RT_GROUP_ICON, &cbSize );
        if( pIconDir == NULL )
            return res;

        if( pIconDir->Reserved != 0 || pIconDir->ResType != RES_ICON ) // 1 == iconType
        {
            _ASSERT( 0 );
            return res;
        }

        int idIcon = LookupIconIdFromDirectoryEx( (LPBYTE)pIconDir, TRUE,
                                                   cxIconSize, cyIconSize, flags );
        void* pIcon = _FindResource( pDosHeader, pRes, -idIcon, (INT_PTR)RT_ICON, &cbSize );
        if( pIcon == NULL )
            return res;

        if( (((LPBITMAPINFOHEADER)pIcon)->biSize != sizeof(BITMAPINFOHEADER)) &&
            (((LPBITMAPINFOHEADER)pIcon)->biSize != sizeof(BITMAPCOREHEADER)) )
        {
            _ASSERT( 0 );
            return res;
        }

        if( piconid )
            piconid[res] = idIcon;

        phicon[res] = CreateIconFromResourceEx( (LPBYTE)pIcon, cbSize,
                                                TRUE, VER30, cxIconSize, cyIconSize, flags );

        res++;
        iconIndex++;       // next icon index
    }

    return res;
}
Beispiel #11
0
QPCSCReader::QPCSCReader( const QString &reader, QPCSC *parent )
	: QObject( parent )
	, d( new QPCSCReaderPrivate( parent->d ) )
{
	d->reader = reader.toUtf8();
	d->state.szReader = d->reader.constData();
	if( !d->updateState() )
		return;

	/* Use DIRECT mode only if there is no card in the reader */
	if( !isPresent() )
	{
#ifndef Q_OS_WIN /* Apple 10.5.7 and pcsc-lite previous to v1.5.5 do not support 0 as protocol identifier */
		DWORD proto = SCARD_PROTOCOL_T0|SCARD_PROTOCOL_T1;
#else
		DWORD proto = 0;
#endif
		LONG rv = SCardConnect( d->d->context, d->state.szReader, SCARD_SHARE_DIRECT, proto, &d->card, &d->proto );
		// Assume that there is a card in the reader in shared mode if direct communcation failed
		if( rv == LONG(SCARD_E_SHARING_VIOLATION) && !connect() )
			return;
	}
	else if( !connect() )
		return;

	d->friendlyName = d->attrib( SCARD_ATTR_DEVICE_FRIENDLY_NAME_A );
#if 0
	qDebug() << "SCARD_ATTR_DEVICE_FRIENDLY_NAME:" << d->attrib( SCARD_ATTR_DEVICE_FRIENDLY_NAME_A );
	qDebug() << "SCARD_ATTR_DEVICE_SYSTEM_NAME:" << d->attrib( SCARD_ATTR_DEVICE_SYSTEM_NAME_A );
	qDebug() << "SCARD_ATTR_DEVICE_UNIT:" << d->attrib( SCARD_ATTR_DEVICE_UNIT );
	qDebug() << "SCARD_ATTR_VENDOR_IFD_SERIAL_NO:" << d->attrib( SCARD_ATTR_VENDOR_IFD_SERIAL_NO );
	qDebug() << "SCARD_ATTR_VENDOR_IFD_TYPE:" << d->attrib( SCARD_ATTR_VENDOR_IFD_TYPE );
	qDebug() << "SCARD_ATTR_VENDOR_IFD_VERSION:" << d->attrib( SCARD_ATTR_VENDOR_IFD_VERSION );
	qDebug() << "SCARD_ATTR_VENDOR_NAME:" << d->attrib( SCARD_ATTR_VENDOR_NAME );
#endif

	DWORD size = 0;
	BYTE feature[256];
	LONG rv = SCardControl( d->card, CM_IOCTL_GET_FEATURE_REQUEST, 0, 0, feature, sizeof(feature), &size );
	if( rv == SCARD_S_SUCCESS && (size % sizeof(PCSC_TLV_STRUCTURE)) == 0 )
	{
		size /= sizeof(PCSC_TLV_STRUCTURE);
		PCSC_TLV_STRUCTURE *pcsc_tlv = (PCSC_TLV_STRUCTURE *)feature;
		for( DWORD i = 0; i < size; i++ )
			d->ioctl[DRIVER_FEATURES(pcsc_tlv[i].tag)] = ntohl( pcsc_tlv[i].value );
	}

	if( DWORD ioctl = d->ioctl.value(FEATURE_GET_TLV_PROPERTIES) )
	{
		DWORD size = 0;
		BYTE recv[256];
		rv = SCardControl( d->card, ioctl, 0, 0, recv, sizeof(recv), &size );
		unsigned char *p = recv;
		while( DWORD(p-recv) < size )
		{
			int tag = *p++, len = *p++, value = -1;
			switch( len )
			{
			case 1: value = *p; break;
			case 2: value = *p + (*(p+1)<<8); break;
			case 4: value = *p + (*(p+1)<<8) + (*(p+2)<<16) + (*(p+3)<<24); break;
			default: break;
			}
			p += len;
			d->properties[Properties(tag)] = value;
		}
	}

	if( DWORD ioctl = d->ioctl.value(FEATURE_IFD_PIN_PROPERTIES) )
	{
		DWORD size = 0;
		BYTE recv[256];
		DWORD rv = SCardControl( d->card, ioctl, 0, 0, recv, sizeof(recv), &size );
		if( rv == SCARD_S_SUCCESS )
		{
			PIN_PROPERTIES_STRUCTURE *caps = (PIN_PROPERTIES_STRUCTURE *)recv;
			d->display = caps->wLcdLayout > 0;
		}
	}

	disconnect();
}
Beispiel #12
0
static inline const QList<GuidFlagsPair>& guidFlagsPairs()
{
    static const QList<GuidFlagsPair> guidFlagsPairList = QList<GuidFlagsPair>()
               // Standard Setup Ports Class GUID
            << qMakePair(QUuid(0x4D36E978, 0xE325, 0x11CE, 0xBF, 0xC1, 0x08, 0x00, 0x2B, 0xE1, 0x03, 0x18), DWORD(DIGCF_PRESENT))
               // Standard Setup Modems Class GUID
            << qMakePair(QUuid(0x4D36E96D, 0xE325, 0x11CE, 0xBF, 0xC1, 0x08, 0x00, 0x2B, 0xE1, 0x03, 0x18), DWORD(DIGCF_PRESENT))
               // Standard Serial Port Device Interface Class GUID
            << qMakePair(QUuid(0x86E0D1E0, 0x8089, 0x11D0, 0x9C, 0xE4, 0x08, 0x00, 0x3E, 0x30, 0x1F, 0x73), DWORD(DIGCF_PRESENT | DIGCF_DEVICEINTERFACE))
               // Standard Modem Device Interface Class GUID
            << qMakePair(QUuid(0x2C7089AA, 0x2E0E, 0x11D1, 0xB1, 0x14, 0x00, 0xC0, 0x4F, 0xC2, 0xAA, 0xE4), DWORD(DIGCF_PRESENT | DIGCF_DEVICEINTERFACE));
    return guidFlagsPairList;
}
int os_msw::terminate_process_by_name( const wxString& named_process_to_terminate )
{

    // A more wxWindows type interface
    const char *szToTerminate = named_process_to_terminate.c_str();

    // See notes to is_named_process_running for credits and info.

	BOOL bResult,bResultm;
	DWORD aiPID[1000],iCb=1000,iNumProc,iV2000=0;
	DWORD iCbneeded,i,iFound=0;
	char szName[MAX_PATH],szToTermUpper[MAX_PATH];
	HANDLE hProc,hSnapShot,hSnapShotm;
	OSVERSIONINFO osvi;
    HINSTANCE hInstLib;
	int iLen,iLenP,indx;
    HMODULE hMod;
	PROCESSENTRY32 procentry;      
	MODULEENTRY32 modentry;

	// Transfer Process name into "szToTermUpper" and
	// convert it to upper case
	iLenP=strlen(szToTerminate);
	if(iLenP<1 || iLenP>MAX_PATH) return 632;
	for(indx=0;indx<iLenP;indx++)
		szToTermUpper[indx]=toupper(szToTerminate[indx]);
	szToTermUpper[iLenP]=0;

     // PSAPI Function Pointers.
     BOOL (WINAPI *lpfEnumProcesses)( DWORD *, DWORD cb, DWORD * );
     BOOL (WINAPI *lpfEnumProcessModules)( HANDLE, HMODULE *,
        DWORD, LPDWORD );
     DWORD (WINAPI *lpfGetModuleBaseName)( HANDLE, HMODULE,
        LPTSTR, DWORD );

      // ToolHelp Function Pointers.
      HANDLE (WINAPI *lpfCreateToolhelp32Snapshot)(DWORD,DWORD) ;
      BOOL (WINAPI *lpfProcess32First)(HANDLE,LPPROCESSENTRY32) ;
      BOOL (WINAPI *lpfProcess32Next)(HANDLE,LPPROCESSENTRY32) ;
      BOOL (WINAPI *lpfModule32First)(HANDLE,LPMODULEENTRY32) ;
      BOOL (WINAPI *lpfModule32Next)(HANDLE,LPMODULEENTRY32) ;

	// First check what version of Windows we're in
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    bResult=GetVersionEx(&osvi);
	if(!bResult)     // Unable to identify system version
	    return 606;

	// At Present we only support Win/NT/2000/XP or Win/9x/ME
	if((osvi.dwPlatformId != VER_PLATFORM_WIN32_NT) &&
		(osvi.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS))
		return 607;

    if(osvi.dwPlatformId==VER_PLATFORM_WIN32_NT)
	{
		// Win/NT or 2000 or XP

         // Load library and get the procedures explicitly. We do
         // this so that we don't have to worry about modules using
         // this code failing to load under Windows 9x, because
         // it can't resolve references to the PSAPI.DLL.
         hInstLib = LoadLibraryA("PSAPI.DLL");
         if(hInstLib == NULL)
            return 605;

         // Get procedure addresses.
         lpfEnumProcesses = (BOOL(WINAPI *)(DWORD *,DWORD,DWORD*))
            GetProcAddress( hInstLib, "EnumProcesses" ) ;
         lpfEnumProcessModules = (BOOL(WINAPI *)(HANDLE, HMODULE *,
            DWORD, LPDWORD)) GetProcAddress( hInstLib,
            "EnumProcessModules" ) ;
         lpfGetModuleBaseName =(DWORD (WINAPI *)(HANDLE, HMODULE,
            LPTSTR, DWORD )) GetProcAddress( hInstLib,
            "GetModuleBaseNameA" ) ;

         if(lpfEnumProcesses == NULL ||
            lpfEnumProcessModules == NULL ||
            lpfGetModuleBaseName == NULL)
            {
               FreeLibrary(hInstLib);
               return 700;
            }
		 
		bResult=lpfEnumProcesses(aiPID,iCb,&iCbneeded);
		if(!bResult)
		{
			// Unable to get process list, EnumProcesses failed
            FreeLibrary(hInstLib);
			return 701;
		}

		// How many processes are there?
		iNumProc=iCbneeded/sizeof(DWORD);

		// Get and match the name of each process
		for(i=0;i<iNumProc;i++)
		{
			// Get the (module) name for this process

	        strcpy(szName,"Unknown");
			// First, get a handle to the process
	        hProc=OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,FALSE,
				aiPID[i]);
	        // Now, get the process name
	        if(hProc)
			{
               if(lpfEnumProcessModules(hProc,&hMod,sizeof(hMod),&iCbneeded) )
			   {
                  iLen=lpfGetModuleBaseName(hProc,hMod,szName,MAX_PATH);
			   }
			}
	        CloseHandle(hProc);
			// We will match regardless of lower or upper case
#ifdef __BORLANDC__
            if(strcmp(strupr(szName),szToTermUpper)==0)
#else
			if(strcmp(_strupr(szName),szToTermUpper)==0)
#endif
			{
				// Process found, now terminate it
				iFound=1;
				// First open for termination
				hProc=OpenProcess(PROCESS_TERMINATE,FALSE,aiPID[i]);
				if(hProc)
				{
					if(TerminateProcess(hProc,0))
					{
						// process terminated
						CloseHandle(hProc);
                        FreeLibrary(hInstLib);
						return 0;
					}
					else
					{
						// Unable to terminate process
						CloseHandle(hProc);
                        FreeLibrary(hInstLib);
						return 602;
					}
				}
				else
				{
					// Unable to open process for termination
                    FreeLibrary(hInstLib);
					return 604;
				}
			}
		}
	}

	if(osvi.dwPlatformId==VER_PLATFORM_WIN32_WINDOWS)
	{
		// Win/95 or 98 or ME
			
		hInstLib = LoadLibraryA("Kernel32.DLL");
		if( hInstLib == NULL )
			return 702;

		// Get procedure addresses.
		// We are linking to these functions of Kernel32
		// explicitly, because otherwise a module using
		// this code would fail to load under Windows NT,
		// which does not have the Toolhelp32
		// functions in the Kernel 32.
		lpfCreateToolhelp32Snapshot=
			(HANDLE(WINAPI *)(DWORD,DWORD))
			GetProcAddress( hInstLib,
			"CreateToolhelp32Snapshot" ) ;
		lpfProcess32First=
			(BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
			GetProcAddress( hInstLib, "Process32First" ) ;
		lpfProcess32Next=
			(BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
			GetProcAddress( hInstLib, "Process32Next" ) ;
		lpfModule32First=
			(BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32))
			GetProcAddress( hInstLib, "Module32First" ) ;
		lpfModule32Next=
			(BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32))
			GetProcAddress( hInstLib, "Module32Next" ) ;
		if( lpfProcess32Next == NULL ||
			lpfProcess32First == NULL ||
		    lpfModule32Next == NULL ||
			lpfModule32First == NULL ||
			lpfCreateToolhelp32Snapshot == NULL )
		{
			FreeLibrary(hInstLib);
			return 703;
		}
			
		// The Process32.. and Module32.. routines return names in all uppercase

		// Get a handle to a Toolhelp snapshot of all the systems processes.

		hSnapShot = lpfCreateToolhelp32Snapshot(
			TH32CS_SNAPPROCESS, 0 ) ;
		if( hSnapShot == INVALID_HANDLE_VALUE )
		{
			FreeLibrary(hInstLib);
			return 704;
		}
		
        // Get the first process' information.
        procentry.dwSize = sizeof(PROCESSENTRY32);
        bResult=lpfProcess32First(hSnapShot,&procentry);

        // While there are processes, keep looping and checking.
        while(bResult)
        {
		    // Get a handle to a Toolhelp snapshot of this process.
		    hSnapShotm = lpfCreateToolhelp32Snapshot(
			    TH32CS_SNAPMODULE, procentry.th32ProcessID) ;
		    if( hSnapShotm == INVALID_HANDLE_VALUE )
			{
				CloseHandle(hSnapShot);
			    FreeLibrary(hInstLib);
			    return 704;
			}
			// Get the module list for this process
			modentry.dwSize=sizeof(MODULEENTRY32);
			bResultm=lpfModule32First(hSnapShotm,&modentry);

			// While there are modules, keep looping and checking
			while(bResultm)
			{
		        if(strcmp(modentry.szModule,szToTermUpper)==0)
				{
				    // Process found, now terminate it
				    iFound=1;
				    // First open for termination
				    hProc=OpenProcess(PROCESS_TERMINATE,FALSE,procentry.th32ProcessID);
				    if(hProc)
					{
					    //ROB: Replaced with best_terminate_process
					    //if(TerminateProcess(hProc,0))
					    if ( best_terminate_process( hProc, 0 ) )
						{
						    // process terminated
							CloseHandle(hSnapShotm);
							CloseHandle(hSnapShot);
							CloseHandle(hProc);
			                FreeLibrary(hInstLib);
						    return 0;
						}
					    else
						{
						    // Unable to terminate process
							CloseHandle(hSnapShotm);
							CloseHandle(hSnapShot);
							CloseHandle(hProc);
			                FreeLibrary(hInstLib);
						    return 602;
						}
					}
				    else
					{
					    // Unable to open process for termination
						CloseHandle(hSnapShotm);
						CloseHandle(hSnapShot);
			            FreeLibrary(hInstLib);
					    return 604;
					}
				}
				else
				{  // Look for next modules for this process
					modentry.dwSize=sizeof(MODULEENTRY32);
					bResultm=lpfModule32Next(hSnapShotm,&modentry);
				}
			}

			//Keep looking
			CloseHandle(hSnapShotm);
            procentry.dwSize = sizeof(PROCESSENTRY32);
            bResult = lpfProcess32Next(hSnapShot,&procentry);
        }
		CloseHandle(hSnapShot);
	}
	if(iFound==0)
	{
		FreeLibrary(hInstLib);
		return 603;
	}
	FreeLibrary(hInstLib);
	return 0;
}
bool os_msw::is_named_process_running( const wxString& process_name )
{

    // A more wxWindows type interface
    const char *szToTerminate = process_name.c_str();

    // Created: 6/23/2000  (RK)
    // Last modified: 3/10/2002  (RK)
    // Please report any problems or bugs to [email protected]
    // The latest version of this routine can be found at:
    //     http://www.neurophys.wisc.edu/ravi/software/killproc/
    // Terminate the process "szToTerminate" if it is currently running
    // This works for Win/95/98/ME and also Win/NT/2000/XP
    // The process name is case-insensitive, i.e. "notepad.exe" and "NOTEPAD.EXE"
    // will both work (for szToTerminate)
    // Return codes are as follows:
    //   0   = Process was successfully terminated
    //   603 = Process was not currently running
    //   604 = No permission to terminate process
    //   605 = Unable to load PSAPI.DLL
    //   602 = Unable to terminate process for some other reason
    //   606 = Unable to identify system type
    //   607 = Unsupported OS
    //   632 = Invalid process name
    //   700 = Unable to get procedure address from PSAPI.DLL
    //   701 = Unable to get process list, EnumProcesses failed
    //   702 = Unable to load KERNEL32.DLL
    //   703 = Unable to get procedure address from KERNEL32.DLL
    //   704 = CreateToolhelp32Snapshot failed
    // Change history:
    //   modified 3/8/2002  - Borland-C compatible if BORLANDC is defined as
    //                        suggested by Bob Christensen
    //   modified 3/10/2002 - Removed memory leaks as suggested by
    //					      Jonathan Richard-Brochu (handles to Proc and Snapshot
    //                        were not getting closed properly in some cases)
	
	BOOL bResult,bResultm;
	DWORD aiPID[1000],iCb=1000,iNumProc,iV2000=0;
	DWORD iCbneeded,i,iFound=0;
	char szName[MAX_PATH],szToTermUpper[MAX_PATH];
	HANDLE hProc,hSnapShot,hSnapShotm;
	OSVERSIONINFO osvi;
    HINSTANCE hInstLib;
	int iLen,iLenP,indx;
    HMODULE hMod;
	PROCESSENTRY32 procentry;      
	MODULEENTRY32 modentry;

	// Transfer Process name into "szToTermUpper" and
	// convert it to upper case
	iLenP=strlen(szToTerminate);
	if(iLenP<1 || iLenP>MAX_PATH) return FALSE;
	for(indx=0;indx<iLenP;indx++)
		szToTermUpper[indx]=toupper(szToTerminate[indx]);
	szToTermUpper[iLenP]=0;

     // PSAPI Function Pointers.
     BOOL (WINAPI *lpfEnumProcesses)( DWORD *, DWORD cb, DWORD * );
     BOOL (WINAPI *lpfEnumProcessModules)( HANDLE, HMODULE *,
        DWORD, LPDWORD );
     DWORD (WINAPI *lpfGetModuleBaseName)( HANDLE, HMODULE,
        LPTSTR, DWORD );

      // ToolHelp Function Pointers.
      HANDLE (WINAPI *lpfCreateToolhelp32Snapshot)(DWORD,DWORD) ;
      BOOL (WINAPI *lpfProcess32First)(HANDLE,LPPROCESSENTRY32) ;
      BOOL (WINAPI *lpfProcess32Next)(HANDLE,LPPROCESSENTRY32) ;
      BOOL (WINAPI *lpfModule32First)(HANDLE,LPMODULEENTRY32) ;
      BOOL (WINAPI *lpfModule32Next)(HANDLE,LPMODULEENTRY32) ;

	// First check what version of Windows we're in
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    bResult=GetVersionEx(&osvi);
	if(!bResult)     // Unable to identify system version
	    return FALSE;

	// At Present we only support Win/NT/2000/XP or Win/9x/ME
	if((osvi.dwPlatformId != VER_PLATFORM_WIN32_NT) &&
		(osvi.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS))
		return FALSE;

    if(osvi.dwPlatformId==VER_PLATFORM_WIN32_NT)
	{
		// Win/NT or 2000 or XP

         // Load library and get the procedures explicitly. We do
         // this so that we don't have to worry about modules using
         // this code failing to load under Windows 9x, because
         // it can't resolve references to the PSAPI.DLL.
         hInstLib = LoadLibraryA("PSAPI.DLL");
         if(hInstLib == NULL)
            return FALSE;

         // Get procedure addresses.
         lpfEnumProcesses = (BOOL(WINAPI *)(DWORD *,DWORD,DWORD*))
            GetProcAddress( hInstLib, "EnumProcesses" ) ;
         lpfEnumProcessModules = (BOOL(WINAPI *)(HANDLE, HMODULE *,
            DWORD, LPDWORD)) GetProcAddress( hInstLib,
            "EnumProcessModules" ) ;
         lpfGetModuleBaseName =(DWORD (WINAPI *)(HANDLE, HMODULE,
            LPTSTR, DWORD )) GetProcAddress( hInstLib,
            "GetModuleBaseNameA" ) ;

         if(lpfEnumProcesses == NULL ||
            lpfEnumProcessModules == NULL ||
            lpfGetModuleBaseName == NULL)
            {
               FreeLibrary(hInstLib);
               return FALSE;
            }
		 
		bResult=lpfEnumProcesses(aiPID,iCb,&iCbneeded);
		if(!bResult)
		{
			// Unable to get process list, EnumProcesses failed
            FreeLibrary(hInstLib);
			return FALSE;
		}

		// How many processes are there?
		iNumProc=iCbneeded/sizeof(DWORD);

		// Get and match the name of each process
		for(i=0;i<iNumProc;i++)
		{
			// Get the (module) name for this process

	        strcpy(szName,"Unknown");
			// First, get a handle to the process
	        hProc=OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,FALSE,
				aiPID[i]);
	        // Now, get the process name
	        if(hProc)
			{
               if(lpfEnumProcessModules(hProc,&hMod,sizeof(hMod),&iCbneeded) )
			   {
                  iLen=lpfGetModuleBaseName(hProc,hMod,szName,MAX_PATH);
			   }
			}
	        CloseHandle(hProc);
			// We will match regardless of lower or upper case
#ifdef __BORLANDC__
            if(strcmp(strupr(szName),szToTermUpper)==0)
#else
			if(strcmp(_strupr(szName),szToTermUpper)==0)
#endif
			{
				// Process found
				iFound=1;
                FreeLibrary(hInstLib);
    			return TRUE;
			}			
		}
	}

	if(osvi.dwPlatformId==VER_PLATFORM_WIN32_WINDOWS)
	{
		// Win/95 or 98 or ME
			
		hInstLib = LoadLibraryA("Kernel32.DLL");
		if( hInstLib == NULL )
			return FALSE;

		// Get procedure addresses.
		// We are linking to these functions of Kernel32
		// explicitly, because otherwise a module using
		// this code would fail to load under Windows NT,
		// which does not have the Toolhelp32
		// functions in the Kernel 32.
		lpfCreateToolhelp32Snapshot=
			(HANDLE(WINAPI *)(DWORD,DWORD))
			GetProcAddress( hInstLib,
			"CreateToolhelp32Snapshot" ) ;
		lpfProcess32First=
			(BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
			GetProcAddress( hInstLib, "Process32First" ) ;
		lpfProcess32Next=
			(BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
			GetProcAddress( hInstLib, "Process32Next" ) ;
		lpfModule32First=
			(BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32))
			GetProcAddress( hInstLib, "Module32First" ) ;
		lpfModule32Next=
			(BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32))
			GetProcAddress( hInstLib, "Module32Next" ) ;
		if( lpfProcess32Next == NULL ||
			lpfProcess32First == NULL ||
		    lpfModule32Next == NULL ||
			lpfModule32First == NULL ||
			lpfCreateToolhelp32Snapshot == NULL )
		{
			FreeLibrary(hInstLib);
			return FALSE;
		}
			
		// The Process32.. and Module32.. routines return names in all uppercase

		// Get a handle to a Toolhelp snapshot of all the systems processes.

		hSnapShot = lpfCreateToolhelp32Snapshot(
			TH32CS_SNAPPROCESS, 0 ) ;
		if( hSnapShot == INVALID_HANDLE_VALUE )
		{
			FreeLibrary(hInstLib);
			return FALSE;
		}
		
        // Get the first process' information.
        procentry.dwSize = sizeof(PROCESSENTRY32);
        bResult=lpfProcess32First(hSnapShot,&procentry);

        // While there are processes, keep looping and checking.
        while(bResult)
        {
		    // Get a handle to a Toolhelp snapshot of this process.
		    hSnapShotm = lpfCreateToolhelp32Snapshot(
			    TH32CS_SNAPMODULE, procentry.th32ProcessID) ;
		    if( hSnapShotm == INVALID_HANDLE_VALUE )
			{
				CloseHandle(hSnapShot);
			    FreeLibrary(hInstLib);
			    return FALSE;
			}
			// Get the module list for this process
			modentry.dwSize=sizeof(MODULEENTRY32);
			bResultm=lpfModule32First(hSnapShotm,&modentry);

			// While there are modules, keep looping and checking
			while(bResultm)
			{
		        if(strcmp(modentry.szModule,szToTermUpper)==0)
				{
				    // Process found
				    iFound=1;
				    // Found one, return TRUE
					CloseHandle(hSnapShotm);
					CloseHandle(hSnapShot);
		            FreeLibrary(hInstLib);
				    return TRUE;					
				}
				else
				{  // Look for next modules for this process
					modentry.dwSize=sizeof(MODULEENTRY32);
					bResultm=lpfModule32Next(hSnapShotm,&modentry);
				}
			}

			//Keep looking
			CloseHandle(hSnapShotm);
            procentry.dwSize = sizeof(PROCESSENTRY32);
            bResult = lpfProcess32Next(hSnapShot,&procentry);
        }
		CloseHandle(hSnapShot);
	}
	if(iFound==0)
	{
		FreeLibrary(hInstLib);
		return FALSE;
	}
	FreeLibrary(hInstLib);
	return FALSE;
}
Beispiel #15
0
static void test_GetFileVersionInfoEx(void)
{
    char *ver, *p;
    BOOL ret;
    UINT size, translation, i;
    HMODULE mod;
    BOOL (WINAPI *pGetFileVersionInfoExW)(DWORD, LPCWSTR, DWORD, DWORD, LPVOID);
    DWORD (WINAPI *pGetFileVersionInfoSizeExW)(DWORD, LPCWSTR, LPDWORD);
    const LANGID lang = GetUserDefaultUILanguage();
    const LANGID english = MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT);
    const WORD unicode = 1200; /* = UNICODE */
    const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
    const DWORD test_flags[] = {
        0, FILE_VER_GET_LOCALISED, FILE_VER_GET_NEUTRAL,
        FILE_VER_GET_LOCALISED | FILE_VER_GET_NEUTRAL,
        0xdeadbeef, /* invalid value (ignored) */
    };
    char desc[MAX_PATH];

    mod = GetModuleHandleA("kernel32.dll");
    assert(mod);

    if (!FindResourceExA(mod, (LPCSTR)RT_VERSION, (LPCSTR)VS_VERSION_INFO, lang) &&
        !FindResourceExA(mod, (LPCSTR)RT_VERSION, (LPCSTR)VS_VERSION_INFO,
                         MAKELANGID(PRIMARYLANGID(lang),SUBLANG_NEUTRAL)))
    {
        skip("Translation is not available\n");
        return;
    }

    size = GetFileVersionInfoSizeW(kernel32W, NULL);
    ok(size, "GetFileVersionInfoSize(kernel32) error %u\n", GetLastError());

    ver = HeapAlloc(GetProcessHeap(), 0, size);
    assert(ver);

    ret = GetFileVersionInfoW(kernel32W, 0, size, ver);
    ok(ret, "GetFileVersionInfo error %u\n", GetLastError());

    ret = VerQueryValueA(ver, "\\VarFileInfo\\Translation", (void **)&p, &size);
    translation = *(UINT *)p;
    ok(ret, "VerQueryValue error %u\n", GetLastError());
    ok(size == 4, "VerQueryValue returned %u, expected 4\n", size);

    /* test default version resource */
    ok(LOWORD(translation) == lang, "got %u, expected lang is %u\n",
       LOWORD(translation), lang);
    ok(HIWORD(translation) == unicode, "got %u, expected codepage is %u\n",
       HIWORD(translation), unicode);

    HeapFree(GetProcessHeap(), 0, ver);

    mod = GetModuleHandleA("version.dll");
    assert(mod);

    /* prefer W-version as A-version is not available on Windows 7 */
    pGetFileVersionInfoExW = (void *)GetProcAddress(mod, "GetFileVersionInfoExW");
    pGetFileVersionInfoSizeExW = (void *)GetProcAddress(mod, "GetFileVersionInfoSizeExW");
    if (!pGetFileVersionInfoExW && !pGetFileVersionInfoSizeExW)
    {
        win_skip("GetFileVersionInfoEx family is not available\n");
        return;
    }

    for (i = 0; i < ARRAY_SIZE(test_flags); i++)
    {
        size = pGetFileVersionInfoSizeExW(test_flags[i], kernel32W, NULL);
        ok(size, "[%u] GetFileVersionInfoSizeEx(kernel32) error %u\n", i, GetLastError());

        ver = HeapAlloc(GetProcessHeap(), 0, size);
        assert(ver);

        ret = pGetFileVersionInfoExW(test_flags[i], kernel32W, 0, size, ver);
        ok(ret, "[%u] GetFileVersionInfoEx error %u\n", i, GetLastError());

        ret = VerQueryValueA(ver, "\\VarFileInfo\\Translation", (void **)&p, &size);
        ok(ret, "[%u] VerQueryValue error %u\n", i, GetLastError());
        ok(size == 4, "[%u] VerQueryValue returned %u, expected 4\n", i, size);
        translation = *(UINT *)p;

        /* test MUI version resource */
        if (test_flags[i] & FILE_VER_GET_LOCALISED)
            ok(LOWORD(translation) == lang, "[%u] got %u, expected lang is %u\n",
               i, LOWORD(translation), lang);
        else
            ok(LOWORD(translation) == english, "[%u] got %u, expected lang is %u\n",
               i, LOWORD(translation), english);
        ok(HIWORD(translation) == unicode, "[%u] got %u, expected codepage is %u\n",
           i, HIWORD(translation), unicode);

        /* test string info using translation info */
        size = 0;
        sprintf(desc, "\\StringFileInfo\\%04x%04x\\FileDescription",
                LOWORD(translation), HIWORD(translation));
        ret = VerQueryValueA(ver, desc, (void **)&p, &size);
        ok(ret, "[%u] VerQueryValue error %u\n", i, GetLastError());
        ok(size == strlen(p) + 1, "[%u] VerQueryValue returned %u\n", i, size);

        HeapFree(GetProcessHeap(), 0, ver);
    }

    return;
}
HRESULT Inpin::Start()
{
    m_bEndOfStream = false;
    m_bFlush = false;
    m_bDone = false;

    ogg_packet& pkt = m_packet;

    assert(pkt.packetno < 0);

    if (!bool(m_pPinConnection))
        return S_FALSE;

    const Outpin& outpin = m_pFilter->m_outpin;

    if (!bool(outpin.m_pPinConnection))
        return S_FALSE;

    typedef VorbisTypes::VORBISFORMAT2 FMT;

    const AM_MEDIA_TYPE& mt = m_connection_mtv[0];
    assert(mt.cbFormat > sizeof(FMT));
    assert(mt.pbFormat);

    BYTE* pb = mt.pbFormat;
    BYTE* const pb_end = pb + mt.cbFormat;

    const FMT& fmt = (const FMT&)(*pb);

    pb += sizeof(FMT);
    assert(pb < pb_end);

    const ULONG id_len = fmt.headerSize[0];
    assert(id_len > 0);

    const ULONG comment_len = fmt.headerSize[1];
    assert(comment_len > 0);

    const ULONG setup_len = fmt.headerSize[2];
    assert(setup_len > 0);

    BYTE* const id_buf = pb;
    assert(id_buf < pb_end);

    BYTE* const comment_buf = pb += id_len;
    assert(comment_buf < pb_end);

    BYTE* const setup_buf = pb += comment_len;
    assert(setup_buf < pb_end);

    pb += setup_len;
    assert(pb == pb_end);

    pkt.packet = id_buf;
    pkt.bytes = id_len;
    pkt.b_o_s = 1;
    pkt.e_o_s = 0;
    pkt.granulepos = 0;
    pkt.packetno = 0;

    int status = vorbis_synthesis_idheader(&pkt);
    assert(status == 1);  //TODO

    vorbis_info& info = m_info;
    vorbis_info_init(&info);

    vorbis_comment& comment = m_comment;
    vorbis_comment_init(&comment);

    status = vorbis_synthesis_headerin(&info, &comment, &pkt);
    assert(status == 0);
    assert((info.channels >= 0) && (DWORD(info.channels) == fmt.channels));
    assert((info.rate >= 0) && (DWORD(info.rate) == fmt.samplesPerSec));

    pkt.packet = comment_buf;
    pkt.bytes = comment_len;
    pkt.b_o_s = 0;
    ++pkt.packetno;

    status = vorbis_synthesis_headerin(&info, &comment, &pkt);
    assert(status == 0);

    pkt.packet = setup_buf;
    pkt.bytes = setup_len;
    ++pkt.packetno;

    status = vorbis_synthesis_headerin(&info, &comment, &pkt);
    assert(status == 0);

    status = vorbis_synthesis_init(&m_dsp_state, &info);
    assert(status == 0);

    status = vorbis_block_init(&m_dsp_state, &m_block);
    assert(status == 0);

    m_first_reftime = -1;
    //m_start_reftime
    //m_samples

    m_channels.clear();
    m_channels.resize(fmt.channels);

    assert(m_buffers.empty());

    return S_OK;
}
Beispiel #17
0
void CFGFilterLAVVideo::Settings::LoadSettings()
{
    CMPlayerCApp* pApp = AfxGetMyApp();
    ASSERT(pApp);

    bTrayIcon = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO, _T("TrayIcon"), bTrayIcon);

    dwStreamAR = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO, _T("StreamAR"), dwStreamAR);

    dwNumThreads = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO, _T("NumThreads"), dwNumThreads);

    dwDeintFieldOrder = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO, _T("DeintFieldOrder"), dwDeintFieldOrder);

    deintMode = (LAVDeintMode)pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO, _T("DeintMode"), deintMode);

    dwRGBRange = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO, _T("RGBRange"), dwRGBRange);

    dwSWDeintMode = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO, _T("SWDeintMode"), dwSWDeintMode);

    dwSWDeintOutput = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO, _T("SWDeintOutput"), dwSWDeintOutput);

    dwDitherMode = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO, _T("DitherMode"), dwDitherMode);

    for (int i = 0; i < LAVOutPixFmt_NB; ++i) {
        bPixFmts[i] = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO_OUTPUTFORMAT, pixFmtSettingsMap[i], bPixFmts[i]);
    }
    // Force disable, for future use
    bPixFmts[LAVOutPixFmt_YV16] = FALSE;

    dwHWAccel = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO_HWACCEL, _T("HWAccel"), -1);
    if (dwHWAccel == DWORD(-1)) {
        dwHWAccel = HWAccel_None; // Ensure that a valid state is selected if no HW acceleration is available

        // We enable by default DXVA2 native on Vista+ and CUVID on XP if an nVidia adapter is found
        if (SysVersion::IsVistaOrLater()) {
            dwHWAccel = HWAccel_DXVA2Native;
        } else {
            CComPtr<IDirect3D9> pD3D9 = Direct3DCreate9(D3D_SDK_VERSION);
            if (pD3D9) {
                D3DADAPTER_IDENTIFIER9 adapterIdentifier;

                for (UINT adp = 0, num_adp = pD3D9->GetAdapterCount(); adp < num_adp; ++adp) {
                    if (pD3D9->GetAdapterIdentifier(adp, 0, &adapterIdentifier) == S_OK
                            && adapterIdentifier.VendorId == 0x10DE) {
                        dwHWAccel = HWAccel_CUDA;
                        break;
                    }
                }
            }
        }
    }

    bHWFormats[HWCodec_H264] = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO_HWACCEL, _T("h264"), bHWFormats[HWCodec_H264]);

    bHWFormats[HWCodec_VC1] = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO_HWACCEL, _T("vc1"), bHWFormats[HWCodec_VC1]);

    bHWFormats[HWCodec_MPEG2] = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO_HWACCEL, _T("mpeg2"), bHWFormats[HWCodec_MPEG2]);

    bHWFormats[HWCodec_MPEG4] = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO_HWACCEL, _T("mpeg4"), bHWFormats[HWCodec_MPEG4]);

    bHWFormats[HWCodec_MPEG2DVD] = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO_HWACCEL, _T("dvd"), bHWFormats[HWCodec_MPEG2DVD]);

    dwHWAccelResFlags = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO_HWACCEL, _T("HWResFlags"), dwHWAccelResFlags);

    dwHWDeintMode = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO_HWACCEL, _T("HWDeintMode"), dwHWDeintMode);

    dwHWDeintOutput = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO_HWACCEL, _T("HWDeintOutput"), dwHWDeintOutput);

    bHWDeintHQ = pApp->GetProfileInt(IDS_R_INTERNAL_LAVVIDEO_HWACCEL, _T("HWDeintHQ"), bHWDeintHQ);
}
Beispiel #18
0
/**
 *	Handles the removal of a corpse from the landscape.
 *
 *	This function should be called periodically to check for corpse removal.
 *	If a corpse is to be removed, the corpse is removed from the given landblock list and from the CorpseCleaner list
 */
void CorpseCleaner::Cleanup()
{
	for(int i = 0; i < MAX_CORPSES; i++)
	{
		time(&longtime);

		if( ( Corpses[i][0] != 0 ) && ( longtime > Corpses[i][1] ) && ( Corpses[i][1] != 0 ) )
		{
			cObject* pcObject = cWorldManager::FindObject( Corpses[i][0] );
			if(pcObject)
			{
				// Remove the Corpse from the landscape
				cMessage cmRemModel;
				cmRemModel << 0xF747L << Corpses[i][0] << DWORD( 1 );
				cWorldManager::SendToAllWithin( 5, pcObject->m_Location, cmRemModel, 3 );
				SimpleAI::RemoveMonster(Corpses[i][0]);

				if( Corpses[i][2] == 0 )
				{
					RemoveCorpse( Corpses[i][0] );
					
					// Destory the Object completely
					cWorldManager::RemoveObject( pcObject );
				}
				else  
				{
					// this is a Respawning Object So Do Not Destroy it
					// Set Corpse Timer to zero
					Corpses[i][1] = 0;
					
					// And Remove from the Landblock
					cWorldManager::MoveRemObject( pcObject );
					pcObject->m_Location.m_dwLandBlock = 0xE9E9002F;
					cWorldManager::MoveAddObject( pcObject );
				}
			}
			else
			{
				//Nothing to Do Here - Object is not valid
			}
		}
		else
		{
		}

		if( ( Corpses[i][0] != 0 ) && ( longtime > Corpses[i][2] ) && ( Corpses[i][1] == 0 ))
		{
			// ReSpawn Activation code
			cObject* pcObjectb = cWorldManager::FindObject( Corpses[i][0] );
			if(pcObjectb)
			{
				// ReSpawn the Monster
				pcObjectb->ReSpawn( pcObjectb );
				
				// Finally Clear the entry from the Corpse Cleaner array
				RemoveCorpse( Corpses[i][0] );
			}
			else
			{
				//Nothing to Do Here - Object is not valid
				RemoveCorpse( Corpses[i][0] );
			}

		}
		else
		{
			// Do absolutely nothing 
		}
	}
	// Set time of Next Cleanup Run
	time(&NextCleanTime + DELAY);
}
BOOL Notepad_plus::notify(SCNotification *notification)
{
	//Important, keep track of which element generated the message
	bool isFromPrimary = (_mainEditView.getHSelf() == notification->nmhdr.hwndFrom || _mainDocTab.getHSelf() == notification->nmhdr.hwndFrom);
	bool isFromSecondary = !isFromPrimary && (_subEditView.getHSelf() == notification->nmhdr.hwndFrom || _subDocTab.getHSelf() == notification->nmhdr.hwndFrom);
	ScintillaEditView * notifyView = isFromPrimary?&_mainEditView:&_subEditView;
	DocTabView *notifyDocTab = isFromPrimary?&_mainDocTab:&_subDocTab;
	TBHDR * tabNotification = (TBHDR*) notification;
	switch (notification->nmhdr.code) 
	{
		case SCN_MODIFIED:
		{
			static bool prevWasEdit = false;
			if (notification->modificationType & (SC_MOD_DELETETEXT | SC_MOD_INSERTTEXT))
			{
				_pEditView->updateBeginEndSelectPosition(notification->modificationType & SC_MOD_INSERTTEXT, notification->position, notification->length);
				prevWasEdit = true;
				_linkTriggered = true;
				::InvalidateRect(notifyView->getHSelf(), NULL, TRUE);
			}

			if (notification->modificationType & (SC_MOD_DELETETEXT | SC_MOD_INSERTTEXT | SC_PERFORMED_UNDO | SC_PERFORMED_REDO))
			{
				// for the backup system
				_pEditView->getCurrentBuffer()->setModifiedStatus(true);
			}

			if (notification->modificationType & SC_MOD_CHANGEFOLD)
			{
				if (prevWasEdit) 
				{
					notifyView->foldChanged(notification->line, notification->foldLevelNow, notification->foldLevelPrev);
					prevWasEdit = false;
				}
			}
			else if (!(notification->modificationType & (SC_MOD_DELETETEXT | SC_MOD_INSERTTEXT)))
			{
				prevWasEdit = false;
			}


		}
		break;

		case SCN_SAVEPOINTREACHED:
		case SCN_SAVEPOINTLEFT:
		{
			Buffer * buf = 0;
			if (isFromPrimary)
			{
				buf = _mainEditView.getCurrentBuffer();
			}
			else if (isFromSecondary)
			{
				buf = _subEditView.getCurrentBuffer();
			}
			else
			{
				//Done by invisibleEditView?
				BufferID id = BUFFER_INVALID;
				if (notification->nmhdr.hwndFrom == _invisibleEditView.getHSelf()) {
					id = MainFileManager->getBufferFromDocument(_invisibleEditView.execute(SCI_GETDOCPOINTER));
				} else if (notification->nmhdr.hwndFrom == _fileEditView.getHSelf()) {
					id = MainFileManager->getBufferFromDocument(_fileEditView.execute(SCI_GETDOCPOINTER));
				} else {
					break;	//wrong scintilla
				}
				if (id != BUFFER_INVALID) {
					buf = MainFileManager->getBufferByID(id);
				} else {
					break;
				}
			}
			bool isDirty = notification->nmhdr.code == SCN_SAVEPOINTLEFT;
			buf->setDirty(isDirty);
			break; 
		}

		case  SCN_MODIFYATTEMPTRO :
			// on fout rien
			break;

		case SCN_KEY:
			break;

	case TCN_TABDROPPEDOUTSIDE:
	case TCN_TABDROPPED:
	{
        TabBarPlus *sender = reinterpret_cast<TabBarPlus *>(notification->nmhdr.idFrom);
        bool isInCtrlStat = (::GetKeyState(VK_LCONTROL) & 0x80000000) != 0;
        if (notification->nmhdr.code == TCN_TABDROPPEDOUTSIDE)
        {
            POINT p = sender->getDraggingPoint();

			//It's the coordinate of screen, so we can call 
			//"WindowFromPoint" function without converting the point
            HWND hWin = ::WindowFromPoint(p);
			if (hWin == _pEditView->getHSelf()) // In the same view group
			{
				if (!_tabPopupDropMenu.isCreated())
				{
					TCHAR goToView[32] = TEXT("Move to other view");
					TCHAR cloneToView[32] = TEXT("Clone to other View");
					vector<MenuItemUnit> itemUnitArray;
					itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_GOTO_ANOTHER_VIEW, goToView));
					itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_CLONE_TO_ANOTHER_VIEW, cloneToView));
					_tabPopupDropMenu.create(_pPublicInterface->getHSelf(), itemUnitArray, _mainMenuHandle);
					_nativeLangSpeaker.changeLangTabDrapContextMenu(_tabPopupDropMenu.getMenuHandle());
				}
				_tabPopupDropMenu.display(p);
			}
			else if ((hWin == _pNonDocTab->getHSelf()) || 
				     (hWin == _pNonEditView->getHSelf())) // In the another view group
			{
                docGotoAnotherEditView(isInCtrlStat?TransferClone:TransferMove);
			}/*
			else if ((hWin == _pProjectPanel_1->getTreeHandle()))
			{
				
                //printStr(TEXT("IN!!!"));
			}*/
			else
			{
				RECT nppZone;
				::GetWindowRect(_pPublicInterface->getHSelf(), &nppZone);
				bool isInNppZone = (((p.x >= nppZone.left) && (p.x <= nppZone.right)) && (p.y >= nppZone.top) && (p.y <= nppZone.bottom));
				if (isInNppZone)
				{
					// Do nothing
					return TRUE;
				}
				generic_string quotFileName = TEXT("\"");
				quotFileName += _pEditView->getCurrentBuffer()->getFullPathName();
				quotFileName += TEXT("\"");
				COPYDATASTRUCT fileNamesData;
				fileNamesData.dwData = COPYDATA_FILENAMES;
				fileNamesData.lpData = (void *)quotFileName.c_str();
				fileNamesData.cbData = long(quotFileName.length() + 1)*(sizeof(TCHAR));

				HWND hWinParent = ::GetParent(hWin);
				TCHAR className[MAX_PATH];
				::GetClassName(hWinParent,className, sizeof(className));
				if (lstrcmp(className, _pPublicInterface->getClassName()) == 0 && hWinParent != _pPublicInterface->getHSelf()) // another Notepad++
				{
					int index = _pDocTab->getCurrentTabIndex();
					BufferID bufferToClose = notifyDocTab->getBufferByIndex(index);
					Buffer * buf = MainFileManager->getBufferByID(bufferToClose);
					int iView = isFromPrimary?MAIN_VIEW:SUB_VIEW;
					if (buf->isDirty()) 
					{
						generic_string msg, title;
						_nativeLangSpeaker.messageBox("CannotMoveDoc",
							_pPublicInterface->getHSelf(),
							TEXT("Document is modified, save it then try again."),
							TEXT("Move to new Notepad++ Instance"),
							MB_OK);
					}
					else
					{
						::SendMessage(hWinParent, NPPM_INTERNAL_SWITCHVIEWFROMHWND, 0, (LPARAM)hWin);
						::SendMessage(hWinParent, WM_COPYDATA, (WPARAM)_pPublicInterface->getHinst(), (LPARAM)&fileNamesData);
                        if (!isInCtrlStat)
						{
							fileClose(bufferToClose, iView);
							if (noOpenedDoc())
								::SendMessage(_pPublicInterface->getHSelf(), WM_CLOSE, 0, 0);
						}
					}
				}
                else // Not Notepad++, we open it here
                {
					docOpenInNewInstance(isInCtrlStat?TransferClone:TransferMove, p.x, p.y);
                }
			}
        }
		//break;
		sender->resetDraggingPoint();
		return TRUE;
	}

	case TCN_TABDELETE:
	{
		int index = tabNotification->tabOrigin;
		BufferID bufferToClose = notifyDocTab->getBufferByIndex(index);
		Buffer * buf = MainFileManager->getBufferByID(bufferToClose);
		int iView = isFromPrimary?MAIN_VIEW:SUB_VIEW;
		if (buf->isDirty())
		{
			activateBuffer(bufferToClose, iView);
		}
		fileClose(bufferToClose, iView);
		break;
	}

	case TCN_SELCHANGE:
	{
		int iView = -1;
        if (notification->nmhdr.hwndFrom == _mainDocTab.getHSelf())
		{
			iView = MAIN_VIEW;
		}
		else if (notification->nmhdr.hwndFrom == _subDocTab.getHSelf())
		{
			iView = SUB_VIEW;
		}
		else
		{
			break;
		}

		switchEditViewTo(iView);
		BufferID bufid = _pDocTab->getBufferByIndex(_pDocTab->getCurrentTabIndex());
		if (bufid != BUFFER_INVALID)
			activateBuffer(bufid, iView);
		
		break;
	}

	case NM_CLICK :
    {        
		if (notification->nmhdr.hwndFrom == _statusBar.getHSelf())
        {
            LPNMMOUSE lpnm = (LPNMMOUSE)notification;
			if (lpnm->dwItemSpec == DWORD(STATUSBAR_TYPING_MODE))
			{
				bool isOverTypeMode = (_pEditView->execute(SCI_GETOVERTYPE) != 0);
				_pEditView->execute(SCI_SETOVERTYPE, !isOverTypeMode);
				_statusBar.setText((_pEditView->execute(SCI_GETOVERTYPE))?TEXT("OVR"):TEXT("INS"), STATUSBAR_TYPING_MODE);
			}
        }
		else if (notification->nmhdr.hwndFrom == _mainDocTab.getHSelf() && _activeView == SUB_VIEW)
		{
			bool isSnapshotMode = NppParameters::getInstance()->getNppGUI().isSnapshotMode();
			if (isSnapshotMode)
			{
				// Before switching off, synchronize backup file
				MainFileManager->backupCurrentBuffer();
			}
			// Switch off
            switchEditViewTo(MAIN_VIEW);
		}
        else if (notification->nmhdr.hwndFrom == _subDocTab.getHSelf() && _activeView == MAIN_VIEW)
        {
			bool isSnapshotMode = NppParameters::getInstance()->getNppGUI().isSnapshotMode();
			if (isSnapshotMode)
			{
				// Before switching off, synchronize backup file
				MainFileManager->backupCurrentBuffer();
			}
			// Switch off
            switchEditViewTo(SUB_VIEW);
        }

		break;
	}

	case NM_DBLCLK :
    {        
		if (notification->nmhdr.hwndFrom == _statusBar.getHSelf())
        {
            LPNMMOUSE lpnm = (LPNMMOUSE)notification;
			if (lpnm->dwItemSpec == DWORD(STATUSBAR_CUR_POS))
			{
				bool isFirstTime = !_goToLineDlg.isCreated();
                _goToLineDlg.doDialog(_nativeLangSpeaker.isRTL());
				if (isFirstTime)
                    _nativeLangSpeaker.changeDlgLang(_goToLineDlg.getHSelf(), "GoToLine");
			}
            else if (lpnm->dwItemSpec == DWORD(STATUSBAR_DOC_SIZE))
			{
				command(IDM_VIEW_SUMMARY);
			}
        }
		break;
	}

    case NM_RCLICK :
    {
		POINT p;
		::GetCursorPos(&p);

		if (notification->nmhdr.hwndFrom == _mainDocTab.getHSelf())
		{
            switchEditViewTo(MAIN_VIEW);
		}
        else if (notification->nmhdr.hwndFrom == _subDocTab.getHSelf())
        {
            switchEditViewTo(SUB_VIEW);
        }
		else if (_pFileSwitcherPanel && notification->nmhdr.hwndFrom == _pFileSwitcherPanel->getHSelf())
        {
			// Already switched, so do nothing here.

			if (_pFileSwitcherPanel->nbSelectedFiles() > 1)
			{
				if (!_fileSwitcherMultiFilePopupMenu.isCreated())
				{
					vector<MenuItemUnit> itemUnitArray;
					itemUnitArray.push_back(MenuItemUnit(IDM_FILESWITCHER_FILESCLOSE, TEXT("Close Selected files")));
					itemUnitArray.push_back(MenuItemUnit(IDM_FILESWITCHER_FILESCLOSEOTHERS, TEXT("Close others files")));

					_fileSwitcherMultiFilePopupMenu.create(_pPublicInterface->getHSelf(), itemUnitArray);
					_nativeLangSpeaker.changeLangTabContextMenu(_fileSwitcherMultiFilePopupMenu.getMenuHandle());
				}
				_fileSwitcherMultiFilePopupMenu.display(p);
				return TRUE;
			}
		}
		else // From tool bar or Status Bar
			return TRUE;
			//break;

		if (!_tabPopupMenu.isCreated())
		{
			vector<MenuItemUnit> itemUnitArray;
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_CLOSE, TEXT("Close")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_CLOSEALL_BUT_CURRENT, TEXT("Close All BUT This")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_CLOSEALL_TOLEFT, TEXT("Close All to the Left")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_CLOSEALL_TORIGHT, TEXT("Close All to the Right")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_SAVE, TEXT("Save")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_SAVEAS, TEXT("Save As...")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_RENAME, TEXT("Rename")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_DELETE, TEXT("Move to Recycle Bin")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_RELOAD, TEXT("Reload")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_PRINT, TEXT("Print")));
			itemUnitArray.push_back(MenuItemUnit(0, NULL));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_OPEN_FOLDER, TEXT("Open Containing Folder in Explorer")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_OPEN_CMD, TEXT("Open Containing Folder in cmd")));
			itemUnitArray.push_back(MenuItemUnit(0, NULL));
			itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_SETREADONLY, TEXT("Read-Only")));
			itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_CLEARREADONLY, TEXT("Clear Read-Only Flag")));
			itemUnitArray.push_back(MenuItemUnit(0, NULL));
			itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_FULLPATHTOCLIP,	TEXT("Full File Path to Clipboard")));
			itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_FILENAMETOCLIP,   TEXT("Filename to Clipboard")));
			itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_CURRENTDIRTOCLIP, TEXT("Current Dir. Path to Clipboard")));
			itemUnitArray.push_back(MenuItemUnit(0, NULL));
			itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_GOTO_ANOTHER_VIEW, TEXT("Move to Other View")));
			itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_CLONE_TO_ANOTHER_VIEW, TEXT("Clone to Other View")));
			itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_GOTO_NEW_INSTANCE, TEXT("Move to New Instance")));
			itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_LOAD_IN_NEW_INSTANCE, TEXT("Open in New Instance")));

			_tabPopupMenu.create(_pPublicInterface->getHSelf(), itemUnitArray);
            _nativeLangSpeaker.changeLangTabContextMenu(_tabPopupMenu.getMenuHandle());
		}

		bool isEnable = ((::GetMenuState(_mainMenuHandle, IDM_FILE_SAVE, MF_BYCOMMAND)&MF_DISABLED) == 0);
		_tabPopupMenu.enableItem(IDM_FILE_SAVE, isEnable);
		
		Buffer * buf = _pEditView->getCurrentBuffer();
		bool isUserReadOnly = buf->getUserReadOnly();
		_tabPopupMenu.checkItem(IDM_EDIT_SETREADONLY, isUserReadOnly);

		bool isSysReadOnly = buf->getFileReadOnly();
		_tabPopupMenu.enableItem(IDM_EDIT_SETREADONLY, !isSysReadOnly);
		_tabPopupMenu.enableItem(IDM_EDIT_CLEARREADONLY, isSysReadOnly);

		bool isFileExisting = PathFileExists(buf->getFullPathName()) != FALSE;
		_tabPopupMenu.enableItem(IDM_FILE_DELETE, isFileExisting);
		_tabPopupMenu.enableItem(IDM_FILE_RENAME, isFileExisting);

		bool isDirty = buf->isDirty();
		bool isUntitled = buf->isUntitled();
		_tabPopupMenu.enableItem(IDM_VIEW_GOTO_NEW_INSTANCE, !(isDirty||isUntitled));
		_tabPopupMenu.enableItem(IDM_VIEW_LOAD_IN_NEW_INSTANCE, !(isDirty||isUntitled));

		_tabPopupMenu.display(p);
		return TRUE;
    }

    
	case SCN_MARGINCLICK:
    {
        if (notification->nmhdr.hwndFrom == _mainEditView.getHSelf())
            switchEditViewTo(MAIN_VIEW);
		else if (notification->nmhdr.hwndFrom == _subEditView.getHSelf())
            switchEditViewTo(SUB_VIEW);

        int lineClick = int(_pEditView->execute(SCI_LINEFROMPOSITION, notification->position));
        
		if (notification->margin == ScintillaEditView::_SC_MARGE_FOLDER)
        {
            _pEditView->marginClick(notification->position, notification->modifiers);
			if (_pDocMap)
				_pDocMap->fold(lineClick, _pEditView->isFolded(lineClick));
        }
        else if ((notification->margin == ScintillaEditView::_SC_MARGE_SYBOLE) && !notification->modifiers)
        {
			if (!_pEditView->markerMarginClick(lineClick))
				bookmarkToggle(lineClick);
        }
		break;
	}

	case SCN_FOLDINGSTATECHANGED :
	{
		if ((notification->nmhdr.hwndFrom == _mainEditView.getHSelf())
		|| (notification->nmhdr.hwndFrom == _subEditView.getHSelf()))
		{
			int lineClicked = notification->line;
			
			if (!_isFolding)
			{
				int urlAction = (NppParameters::getInstance())->getNppGUI()._styleURL;
				if ((urlAction == 1) || (urlAction == 2))
					addHotSpot();
			}

			if (_pDocMap)
				_pDocMap->fold(lineClicked, _pEditView->isFolded(lineClicked));
		}
		return TRUE;
	}

	case SCN_CHARADDED:
	{
		const NppGUI & nppGui = NppParameters::getInstance()->getNppGUI();
		bool indentMaintain = nppGui._maitainIndent;
		if (indentMaintain)
			MaintainIndentation(static_cast<TCHAR>(notification->ch));
		
		AutoCompletion * autoC = isFromPrimary?&_autoCompleteMain:&_autoCompleteSub;
		
		if (nppGui._matchedPairConf.hasAnyPairsPair())
			autoC->insertMatchedChars(notification->ch, nppGui._matchedPairConf);
		autoC->update(notification->ch);

		break;
	}

	case SCN_DOUBLECLICK :
	{
		if(notification->modifiers == SCMOD_CTRL)
		{
			const NppGUI & nppGUI = NppParameters::getInstance()->getNppGUI();

			std::string bufstring;
			unsigned int position_of_click;

			// Anonymous scope to limit use of the buf pointer (much easier to deal with std::string).
			{
				char *buf;
				int length;
				
				if(nppGUI._delimiterSelectionOnEntireDocument)
				{
					// Get entire document.
					length = notifyView->execute(SCI_GETLENGTH);
					buf = new char[length + 1];
					notifyView->execute(SCI_GETTEXT, (LPARAM)(length + 1), (WPARAM)buf);

					// For some reason Ctrl+DoubleClick on an empty line means that notification->position == 1.
					// In that case we use SCI_GETCURRENTPOS to get the position.
					if(notification->position != -1)
						position_of_click = notification->position;
					else
						position_of_click = int(_pEditView->execute(SCI_GETCURRENTPOS));
				}
				else
				{
					// Get single line.
					length = notifyView->execute(SCI_GETCURLINE);
					buf = new char[length + 1];
					notifyView->execute(SCI_GETCURLINE, (WPARAM)length, (LPARAM)buf);

					// Compute the position of the click (relative to the beginning of the line).
					const int line_position = notifyView->execute(SCI_POSITIONFROMLINE, notifyView->getCurrentLineNumber());
					position_of_click = notification->position - line_position;
				}

				bufstring = buf;
				delete [] buf;
			}

			int leftmost_position = -1;
			int rightmost_position = -1;

			if(nppGUI._rightmostDelimiter == nppGUI._leftmostDelimiter)
			{
				// If the delimiters are the same (e.g. they are both a quotation mark), choose the ones
				// which are closest to the clicked position.

				for(unsigned int i = position_of_click; i >= 0; --i)
				{
					if(bufstring.at(i) == nppGUI._leftmostDelimiter)
					{
						// Respect escaped quotation marks.
						if(nppGUI._leftmostDelimiter == '"')
						{
							if(! (i > 0 && bufstring.at(i - 1) == '\\'))
							{
								leftmost_position = i;
								break;
							}
						}
						else
						{
							leftmost_position = i;
							break;
						}
					}
				}

				if(leftmost_position == -1)
					break;

				// Scan for right delimiter.
				for(unsigned int i = position_of_click; i < bufstring.length(); ++i)
				{
					if(bufstring.at(i) == nppGUI._rightmostDelimiter)
					{
						// Respect escaped quotation marks.
						if(nppGUI._rightmostDelimiter == '"')
						{
							if(! (i > 0 && bufstring.at(i - 1) == '\\'))
							{
								rightmost_position = i;
								break;
							}
						}
						else
						{
							rightmost_position = i;
							break;
						}
					}
				}
			}
			else
			{
				// Find matching pairs of delimiters (e.g. parantheses).
				// The pair where the distance from the left delimiter to position_of_click is at a minimum is the one we're looking for.
				// Of course position_of_click must lie between the delimiters.

				// This logic is required to handle cases like this:
				// (size_t i = function(); i < _buffers.size(); i++)

				std::stack<unsigned int> leftmost_delimiter_positions;

				for(unsigned int i = 0; i < bufstring.length(); ++i)
				{
					if(bufstring.at(i) == nppGUI._leftmostDelimiter)
						leftmost_delimiter_positions.push(i);
					else if(bufstring.at(i) == nppGUI._rightmostDelimiter && ! leftmost_delimiter_positions.empty())
					{
						unsigned int matching_leftmost = leftmost_delimiter_positions.top();
						leftmost_delimiter_positions.pop();

						// We have either 1) chosen neither the left- or rightmost position, or 2) chosen both left- and rightmost position.
						assert( (leftmost_position == -1 && rightmost_position == -1) || (leftmost_position >= 0 && rightmost_position >= 0) );

						// Note: cast of leftmost_position to unsigned int is safe, since if leftmost_position is not -1 then it is guaranteed to be positive.
						// If it was possible, leftmost_position and rightmost_position should be of type optional<unsigned int>.
						if( matching_leftmost <= position_of_click && i >= position_of_click &&  (leftmost_position == -1 ||  matching_leftmost > (unsigned int)leftmost_position) )
						{
							leftmost_position = matching_leftmost;
							rightmost_position = i;
						}
					}
				}
			}

			// Set selection to the position we found (if any).
			if(rightmost_position != -1 && leftmost_position != -1)
			{
				if(nppGUI._delimiterSelectionOnEntireDocument)
				{
					notifyView->execute(SCI_SETCURRENTPOS, rightmost_position);
					notifyView->execute(SCI_SETANCHOR, leftmost_position + 1);
				}
				else
				{
					const int line_position = notifyView->execute(SCI_POSITIONFROMLINE, notifyView->getCurrentLineNumber());
					notifyView->execute(SCI_SETCURRENTPOS, line_position + rightmost_position);
					notifyView->execute(SCI_SETANCHOR, line_position + leftmost_position + 1);
				}
			}
		}
		else if (_isHotspotDblClicked)
		{
			int pos = notifyView->execute(SCI_GETCURRENTPOS);
			notifyView->execute(SCI_SETCURRENTPOS, pos);
			notifyView->execute(SCI_SETANCHOR, pos);
			_isHotspotDblClicked = false;
		}
	}
	break;

	case SCN_UPDATEUI:
	{
		NppParameters *nppParam = NppParameters::getInstance();

		// replacement for obsolete custom SCN_SCROLLED
		if (notification->updated & SC_UPDATE_V_SCROLL)
		{
			int urlAction = (NppParameters::getInstance())->getNppGUI()._styleURL;
			if ((urlAction == 1) || (urlAction == 2))
				addHotSpot();
		}

		// if it's searching/replacing, then do nothing
		if (nppParam->_isFindReplacing)
			break;

		if (notification->nmhdr.hwndFrom != _pEditView->getHSelf())
			break;
		
        braceMatch();

		NppGUI & nppGui = (NppGUI &)nppParam->getNppGUI();

		if (nppGui._enableTagsMatchHilite)
		{
			XmlMatchedTagsHighlighter xmlTagMatchHiliter(_pEditView);
			xmlTagMatchHiliter.tagMatch(nppGui._enableTagAttrsHilite);
		}
		
		if (nppGui._enableSmartHilite)
		{
			if (nppGui._disableSmartHiliteTmp)
				nppGui._disableSmartHiliteTmp = false;
			else
				_smartHighlighter.highlightView(notifyView);
		}

		updateStatusBar();
		AutoCompletion * autoC = isFromPrimary?&_autoCompleteMain:&_autoCompleteSub;
		autoC->update(0);

        break;
	}

    case TTN_GETDISPINFO:
    {
		try {
			LPTOOLTIPTEXT lpttt = (LPTOOLTIPTEXT)notification; 

			//Joce's fix
			lpttt->hinst = NULL; 

			POINT p;
			::GetCursorPos(&p);
			::ScreenToClient(_pPublicInterface->getHSelf(), &p);
			HWND hWin = ::RealChildWindowFromPoint(_pPublicInterface->getHSelf(), p);
			const int tipMaxLen = 1024;
			static TCHAR docTip[tipMaxLen];
			docTip[0] = '\0';

			generic_string tipTmp(TEXT(""));
			int id = int(lpttt->hdr.idFrom);

			if (hWin == _rebarTop.getHSelf())
			{
				getNameStrFromCmd(id, tipTmp);
				if (tipTmp.length() >= 80)
					return FALSE;

				lstrcpy(lpttt->szText, tipTmp.c_str());
				return TRUE;
			}
			else if (hWin == _mainDocTab.getHSelf())
			{
				BufferID idd = _mainDocTab.getBufferByIndex(id);
				Buffer * buf = MainFileManager->getBufferByID(idd);
				tipTmp = buf->getFullPathName();

				if (tipTmp.length() >= tipMaxLen)
					return FALSE;
				lstrcpy(docTip, tipTmp.c_str());
				lpttt->lpszText = docTip;
				return TRUE;
			}
			else if (hWin == _subDocTab.getHSelf())
			{
				BufferID idd = _subDocTab.getBufferByIndex(id);
				Buffer * buf = MainFileManager->getBufferByID(idd);
				tipTmp = buf->getFullPathName();

				if (tipTmp.length() >= tipMaxLen)
					return FALSE;
				lstrcpy(docTip, tipTmp.c_str());
				lpttt->lpszText = docTip;
				return TRUE;
			}
			else
			{
				return FALSE;
			}
		} catch (...) {
			//printStr(TEXT("ToolTip crash is caught!"));
		}
    }
	break;


    case SCN_ZOOM:
		break;

    case SCN_MACRORECORD:
        _macro.push_back(recordedMacroStep(notification->message, notification->wParam, notification->lParam, _pEditView->execute(SCI_GETCODEPAGE)));
		break;

	case SCN_PAINTED:
	{
		//--FLS: ViewMoveAtWrappingDisableFix: Disable wrapping messes up visible lines. Therefore save view position before in IDM_VIEW_WRAP and restore after SCN_PAINTED, as doc. says
		if (_mainEditView.isWrapRestoreNeeded())
		{
			_mainEditView.restoreCurrentPos();
			_mainEditView.setWrapRestoreNeeded(false);
		}

		if (_subEditView.isWrapRestoreNeeded())
		{
			_subEditView.restoreCurrentPos();
			_subEditView.setWrapRestoreNeeded(false);
		}
		notifyView->updateLineNumberWidth();
		if (_syncInfo.doSync()) 
			doSynScorll(HWND(notification->nmhdr.hwndFrom));

		NppParameters *nppParam = NppParameters::getInstance();
		
		// if it's searching/replacing, then do nothing
		if ((_linkTriggered && !nppParam->_isFindReplacing) || notification->wParam == LINKTRIGGERED)
		{
			int urlAction = (NppParameters::getInstance())->getNppGUI()._styleURL;
			if ((urlAction == 1) || (urlAction == 2))
				addHotSpot();
			_linkTriggered = false;
		}

		if (_pDocMap)
		{
			_pDocMap->wrapMap();
			_pDocMap->scrollMap();
		}
		break;
	}

	case SCN_HOTSPOTDOUBLECLICK :
	{
		notifyView->execute(SCI_SETWORDCHARS, 0, (LPARAM)"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-+.,:?&@=/%#()");
		
		int pos = notifyView->execute(SCI_GETCURRENTPOS);
		int startPos = static_cast<int>(notifyView->execute(SCI_WORDSTARTPOSITION, pos, false));
		int endPos = static_cast<int>(notifyView->execute(SCI_WORDENDPOSITION, pos, false));

		notifyView->execute(SCI_SETTARGETSTART, startPos);
		notifyView->execute(SCI_SETTARGETEND, endPos);
	
		int posFound = notifyView->execute(SCI_SEARCHINTARGET, strlen(URL_REG_EXPR), (LPARAM)URL_REG_EXPR);
		if (posFound != -2)
		{
			if (posFound != -1)
			{
				startPos = int(notifyView->execute(SCI_GETTARGETSTART));
				endPos = int(notifyView->execute(SCI_GETTARGETEND));
			}

			// Prevent buffer overflow in getGenericText().
			if(endPos - startPos > 2*MAX_PATH)
				endPos = startPos + 2*MAX_PATH;

			TCHAR currentWord[2*MAX_PATH];

			notifyView->getGenericText(currentWord, MAX_PATH*2, startPos, endPos);

			// This treatment would fail on some valid URLs where there's actually supposed to be a comma or parenthesis at the end.
			int lastCharIndex = _tcsnlen(currentWord, MAX_PATH*2) - 1;
			if(lastCharIndex >= 0 && (currentWord[lastCharIndex] == ',' || currentWord[lastCharIndex] == ')' || currentWord[lastCharIndex] == '('))
				currentWord[lastCharIndex] = '\0';

			::ShellExecute(_pPublicInterface->getHSelf(), TEXT("open"), currentWord, NULL, NULL, SW_SHOW);
			_isHotspotDblClicked = true;
			notifyView->execute(SCI_SETCHARSDEFAULT);
		}
		break;
	}

	case SCN_NEEDSHOWN :
	{
		int begin = notifyView->execute(SCI_LINEFROMPOSITION, notification->position);
		int end = notifyView->execute(SCI_LINEFROMPOSITION, notification->position + notification->length);
		int firstLine = begin < end ? begin : end;
		int lastLine = begin > end ? begin : end;
		for (int line = firstLine; line <= lastLine; ++line)
		{
			notifyView->execute(SCI_ENSUREVISIBLE, line, 0);
		}
		break;
	}

	case SCN_CALLTIPCLICK:
	{
		AutoCompletion * autoC = isFromPrimary?&_autoCompleteMain:&_autoCompleteSub;
		autoC->callTipClick(notification->position);
		break;
	}

	case RBN_HEIGHTCHANGE:
	{
		SendMessage(_pPublicInterface->getHSelf(), WM_SIZE, 0, 0);
		break;
	}
	case RBN_CHEVRONPUSHED:
	{
		NMREBARCHEVRON * lpnm = (NMREBARCHEVRON*) notification;
		ReBar * notifRebar = &_rebarTop;
		if (_rebarBottom.getHSelf() == lpnm->hdr.hwndFrom)
			notifRebar = &_rebarBottom;
		//If N++ ID, use proper object
		switch(lpnm->wID) {
			case REBAR_BAR_TOOLBAR: {
				POINT pt;
				pt.x = lpnm->rc.left;
				pt.y = lpnm->rc.bottom;
				ClientToScreen(notifRebar->getHSelf(), &pt);
				_toolBar.doPopop(pt);
				return TRUE;
				break; }
		}
		//Else forward notification to window of rebarband
		REBARBANDINFO rbBand;
		ZeroMemory(&rbBand, REBARBAND_SIZE);
		rbBand.cbSize  = REBARBAND_SIZE;

		rbBand.fMask = RBBIM_CHILD;
		::SendMessage(notifRebar->getHSelf(), RB_GETBANDINFO, lpnm->uBand, (LPARAM)&rbBand);
		::SendMessage(rbBand.hwndChild, WM_NOTIFY, 0, (LPARAM)lpnm);
		break;
	}

	default :
		break;

  }
  return FALSE;
}
Beispiel #20
0
/*#$%
==============================================================
	通信回線をオープンする
--------------------------------------------------------------
PortName : 回線の名前
pCP		 : COMMPARAのポインタ(ヌルの時はデフォルトで初期化)
RBufSize : 受信バッファのサイズ(default=2048)
TBufSize : 送信バッファのサイズ(default=2048)
--------------------------------------------------------------
TRUE/FALSE
--------------------------------------------------------------
==============================================================
*/
BOOL __fastcall CComm::Open(LPCTSTR PortName, int inv, COMMPARA *cp)
{

	if( m_CreateON == TRUE ) Close();
	m_Execute = 0;
	m_fHnd = ::CreateFile( PortName, GENERIC_READ | GENERIC_WRITE,
						0, NULL,
						OPEN_EXISTING,
						FILE_ATTRIBUTE_NORMAL,
						NULL
	);
	if( m_fHnd == INVALID_HANDLE_VALUE ){
		m_pEXT = new CEXTFSK(PortName);
		if( m_pEXT->IsLib() ){
			LONG para;
			if( cp != NULL ){
				para = (cp->Baud << 16);
				para |= cp->Stop;
				para |= (cp->BitLen << 2);
			}
			else {
				para = (45 << 16);
			}
			m_pEXT->Open(para);
			m_CreateON = TRUE;
			return TRUE;
		}
		else {
			delete m_pEXT;
			m_pEXT = NULL;
		}
		return FALSE;
	}
	m_inv = inv;
	// setup device buffers
	if( ::SetupComm( m_fHnd, DWORD(1024), DWORD(2) ) == FALSE ){
		::CloseHandle(m_fHnd);
		return FALSE;
	}

	// purge any information in the buffer
	::PurgeComm( m_fHnd, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR );

	// set up for overlapped I/O
	COMMTIMEOUTS TimeOut;

	TimeOut.ReadIntervalTimeout = 0xffffffff;
	TimeOut.ReadTotalTimeoutMultiplier = 0;
	TimeOut.ReadTotalTimeoutConstant = 0;
	TimeOut.WriteTotalTimeoutMultiplier = 0;
	TimeOut.WriteTotalTimeoutConstant = 20000;
//	TimeOut.WriteTotalTimeoutConstant = 1;
	if( !::SetCommTimeouts( m_fHnd, &TimeOut ) ){
		::CloseHandle( m_fHnd );
		return FALSE;
	}
	::GetCommState( m_fHnd, &m_dcb );
	m_dcb.BaudRate = (cp != NULL) ? cp->Baud : 9600;
	m_dcb.fBinary = TRUE;
	m_dcb.ByteSize = BYTE((cp != NULL) ? cp->BitLen : 8);
	m_dcb.Parity = BYTE((cp != NULL) ? cp->Parity : NOPARITY);
	m_dcb.StopBits = BYTE((cp != NULL ) ? cp->Stop : ONESTOPBIT);
//	Application->MainForm->Caption = int(cp ? cp->Stop == TWOSTOPBITS : FALSE);
	m_dcb.XonChar = 0x11;	// XON
	m_dcb.XoffChar = 0x13;	// XOFF
	m_dcb.fParity = 0;
	m_dcb.fOutxCtsFlow = FALSE;
	m_dcb.fInX = m_dcb.fOutX = FALSE;
	m_dcb.fOutxDsrFlow = FALSE;
	m_dcb.EvtChar = 0x0d;

	m_dcb.fRtsControl = m_inv ? RTS_CONTROL_ENABLE : RTS_CONTROL_DISABLE;		// 送信禁止
	m_dcb.fDtrControl = m_inv ? DTR_CONTROL_ENABLE : DTR_CONTROL_DISABLE;		// 送信禁止

//	m_dcb.fTXContinueOnXoff = TRUE;
	m_dcb.XonLim = USHORT(1024/4);			// 1/4 of RBufSize
	m_dcb.XoffLim = USHORT(1024*3/4);		// 3/4 of RBufSize
	m_dcb.DCBlength = sizeof( DCB );

	if( m_dcb.StopBits != ONESTOPBIT ){
		m_addcount = DWORD((1000.0/double(m_dcb.BaudRate)) * double(m_dcb.ByteSize + 2.7));
	}
	else {
		m_addcount = DWORD((1000.0/double(m_dcb.BaudRate)) * double(m_dcb.ByteSize + 2.2));
	}
#if 0	// debug
	m_dcb.BaudRate = 9600;
	m_dcb.ByteSize = 8;
#endif

	if( !::SetCommState( m_fHnd, &m_dcb ) ){
		::CloseHandle( m_fHnd );
		return FALSE;
	}

	// get any early notifications
	if( !::SetCommMask( m_fHnd, EV_RXFLAG ) ){
		::CloseHandle(m_fHnd);
		return FALSE;
	}
	m_CreateON = TRUE;
	return TRUE;
}
Beispiel #21
0
DWORD CrashExceptionHandler (qboolean iswatchdog, DWORD exceptionCode, LPEXCEPTION_POINTERS exceptionInfo)
{
	char dumpPath[1024];
	HANDLE hProc = GetCurrentProcess();
	DWORD procid = GetCurrentProcessId();
	HANDLE dumpfile;
	HMODULE hDbgHelp;
	MINIDUMPWRITEDUMP fnMiniDumpWriteDump;
	HMODULE hKernel;
	BOOL (WINAPI *pIsDebuggerPresent)(void);

	DWORD (WINAPI *pSymSetOptions)(DWORD SymOptions);
	BOOL (WINAPI *pSymInitialize)(HANDLE hProcess, PSTR UserSearchPath, BOOL fInvadeProcess);
	BOOL (WINAPI *pSymFromAddr)(HANDLE hProcess, DWORD64 Address, PDWORD64 Displacement, PSYMBOL_INFO Symbol);

#ifdef _WIN64
#define DBGHELP_POSTFIX "64"
	BOOL (WINAPI *pStackWalkX)(DWORD MachineType, HANDLE hProcess, HANDLE hThread, LPSTACKFRAME64 StackFrame, PVOID ContextRecord, PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
	PVOID (WINAPI *pSymFunctionTableAccessX)(HANDLE hProcess, DWORD64 AddrBase);
	DWORD64 (WINAPI *pSymGetModuleBaseX)(HANDLE hProcess, DWORD64 qwAddr);
	BOOL (WINAPI *pSymGetLineFromAddrX)(HANDLE hProcess, DWORD64 qwAddr, PDWORD pdwDisplacement, PIMAGEHLP_LINE64 Line64);
	BOOL (WINAPI *pSymGetModuleInfoX)(HANDLE hProcess, DWORD64 qwAddr, PIMAGEHLP_MODULE64 ModuleInfo);
	#define STACKFRAMEX STACKFRAME64
	#define IMAGEHLP_LINEX IMAGEHLP_LINE64
	#define IMAGEHLP_MODULEX IMAGEHLP_MODULE64
#else
#define DBGHELP_POSTFIX ""
	BOOL (WINAPI *pStackWalkX)(DWORD MachineType, HANDLE hProcess, HANDLE hThread, LPSTACKFRAME StackFrame, PVOID ContextRecord, PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine, PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine, PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine, PTRANSLATE_ADDRESS_ROUTINE TranslateAddress);
	PVOID (WINAPI *pSymFunctionTableAccessX)(HANDLE hProcess, DWORD AddrBase);
	DWORD (WINAPI *pSymGetModuleBaseX)(HANDLE hProcess, DWORD dwAddr);
	BOOL (WINAPI *pSymGetLineFromAddrX)(HANDLE hProcess, DWORD dwAddr, PDWORD pdwDisplacement, PIMAGEHLP_LINE Line);
	BOOL (WINAPI *pSymGetModuleInfoX)(HANDLE hProcess, DWORD dwAddr, PIMAGEHLP_MODULE ModuleInfo);
	#define STACKFRAMEX STACKFRAME
	#define IMAGEHLP_LINEX IMAGEHLP_LINE
	#define IMAGEHLP_MODULEX IMAGEHLP_MODULE
#endif
	dllfunction_t debughelpfuncs[] =
	{
		{(void*)&pSymFromAddr,				"SymFromAddr"},
		{(void*)&pSymSetOptions,			"SymSetOptions"},
		{(void*)&pSymInitialize,			"SymInitialize"},
		{(void*)&pStackWalkX,				"StackWalk"DBGHELP_POSTFIX},
		{(void*)&pSymFunctionTableAccessX,	"SymFunctionTableAccess"DBGHELP_POSTFIX},
		{(void*)&pSymGetModuleBaseX,		"SymGetModuleBase"DBGHELP_POSTFIX},
		{(void*)&pSymGetLineFromAddrX,		"SymGetLineFromAddr"DBGHELP_POSTFIX},
		{(void*)&pSymGetModuleInfoX,		"SymGetModuleInfo"DBGHELP_POSTFIX},
		{NULL, NULL}
	};

		switch(exceptionCode)
	{
	case EXCEPTION_ACCESS_VIOLATION:
	case EXCEPTION_DATATYPE_MISALIGNMENT:
	case EXCEPTION_BREAKPOINT:
	case EXCEPTION_SINGLE_STEP:
	case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
	case EXCEPTION_FLT_DENORMAL_OPERAND:
	case EXCEPTION_FLT_DIVIDE_BY_ZERO:
	case EXCEPTION_FLT_INEXACT_RESULT:
	case EXCEPTION_FLT_INVALID_OPERATION:
	case EXCEPTION_FLT_OVERFLOW:
	case EXCEPTION_FLT_STACK_CHECK:
	case EXCEPTION_FLT_UNDERFLOW:
	case EXCEPTION_INT_DIVIDE_BY_ZERO:
	case EXCEPTION_INT_OVERFLOW:
	case EXCEPTION_PRIV_INSTRUCTION:
	case EXCEPTION_IN_PAGE_ERROR:
	case EXCEPTION_ILLEGAL_INSTRUCTION:
	case EXCEPTION_NONCONTINUABLE_EXCEPTION:
	case EXCEPTION_STACK_OVERFLOW:
	case EXCEPTION_INVALID_DISPOSITION:
	case EXCEPTION_GUARD_PAGE:
	case EXCEPTION_INVALID_HANDLE:
//	case EXCEPTION_POSSIBLE_DEADLOCK:
		break;
	default:
		//because windows is a steaming pile of s***e, we have to ignore any software-generated exceptions, because most of them are not in fact fatal, *EVEN IF THEY CLAIM TO BE NON-CONTINUABLE*
		return exceptionCode;
	}

	hKernel = LoadLibrary ("kernel32");
	pIsDebuggerPresent = (void*)GetProcAddress(hKernel, "IsDebuggerPresent");

	if (pIsDebuggerPresent && pIsDebuggerPresent())
		return EXCEPTION_CONTINUE_SEARCH;
#ifdef GLQUAKE
	GLVID_Crashed();
#endif

#if 1//ndef _MSC_VER
	{
		if (Sys_LoadLibrary("DBGHELP", debughelpfuncs))
		{
			STACKFRAMEX stack;
			CONTEXT *pcontext = exceptionInfo->ContextRecord;
			IMAGEHLP_LINEX line;
			IMAGEHLP_MODULEX module;
			struct
			{
				SYMBOL_INFO sym;
				char name[1024];
			} sym;
			int frameno;
			char stacklog[8192];
			int logpos, logstart;
			char *logline;

			stacklog[logpos=0] = 0;

			pSymInitialize(hProc, NULL, TRUE);
			pSymSetOptions(SYMOPT_LOAD_LINES);

			memset(&stack, 0, sizeof(stack));
#ifdef _WIN64
			#define IMAGE_FILE_MACHINE_THIS IMAGE_FILE_MACHINE_AMD64
			stack.AddrPC.Mode = AddrModeFlat;
			stack.AddrPC.Offset = pcontext->Rip;
			stack.AddrFrame.Mode = AddrModeFlat;
			stack.AddrFrame.Offset = pcontext->Rbp;
			stack.AddrStack.Mode = AddrModeFlat;
			stack.AddrStack.Offset = pcontext->Rsp;
#else
			#define IMAGE_FILE_MACHINE_THIS IMAGE_FILE_MACHINE_I386
			stack.AddrPC.Mode = AddrModeFlat;
			stack.AddrPC.Offset = pcontext->Eip;
			stack.AddrFrame.Mode = AddrModeFlat;
			stack.AddrFrame.Offset = pcontext->Ebp;
			stack.AddrStack.Mode = AddrModeFlat;
			stack.AddrStack.Offset = pcontext->Esp;
#endif

			Q_strncpyz(stacklog+logpos, FULLENGINENAME " or dependancy has crashed. The following stack dump been copied to your windows clipboard.\n"
#ifdef _MSC_VER
				"Would you like to generate a core dump too?\n"
#endif
				"\n", sizeof(stacklog)-logpos);
			logstart = logpos += strlen(stacklog+logpos);

			//so I know which one it is
#if defined(DEBUG) || defined(_DEBUG)
	#define BUILDDEBUGREL "Debug"
#else
	#define BUILDDEBUGREL "Optimised"
#endif
#ifdef MINIMAL
	#define BUILDMINIMAL "Min"
#else
	#define BUILDMINIMAL ""
#endif
#if defined(GLQUAKE) && !defined(D3DQUAKE)
	#define BUILDTYPE "GL"
#elif !defined(GLQUAKE) && defined(D3DQUAKE)
	#define BUILDTYPE "D3D"
#else
	#define BUILDTYPE "Merged"
#endif

			Q_snprintfz(stacklog+logpos, sizeof(stacklog)-logpos, "Build: %s %s %s: %s\r\n", BUILDDEBUGREL, PLATFORM, BUILDMINIMAL BUILDTYPE, version_string());
			logpos += strlen(stacklog+logpos);

			for(frameno = 0; ; frameno++)
			{
				DWORD64 symdisp;
				DWORD linedisp;
				DWORD_PTR symaddr;
				if (!pStackWalkX(IMAGE_FILE_MACHINE_THIS, hProc, GetCurrentThread(), &stack, pcontext, NULL, pSymFunctionTableAccessX, pSymGetModuleBaseX, NULL))
					break;
				memset(&module, 0, sizeof(module));
				module.SizeOfStruct = sizeof(module);
				pSymGetModuleInfoX(hProc, stack.AddrPC.Offset, &module);
				memset(&line, 0, sizeof(line));
				line.SizeOfStruct = sizeof(line);
				symdisp = 0;
				memset(&sym, 0, sizeof(sym));
				sym.sym.MaxNameLen = sizeof(sym.name);
				symaddr = stack.AddrPC.Offset;
				sym.sym.SizeOfStruct = sizeof(sym.sym);
				if (pSymFromAddr(hProc, symaddr, &symdisp, &sym.sym))
				{
					if (pSymGetLineFromAddrX(hProc, stack.AddrPC.Offset, &linedisp, &line))
						logline = va("%-20s - %s:%i (%s)\r\n", sym.sym.Name, line.FileName, (int)line.LineNumber, module.LoadedImageName);
					else
						logline = va("%-20s+%#x (%s)\r\n", sym.sym.Name, (unsigned int)symdisp, module.LoadedImageName);
				}
				else
					logline = va("0x%p (%s)\r\n", (void*)(DWORD_PTR)stack.AddrPC.Offset, module.LoadedImageName);
				Q_strncpyz(stacklog+logpos, logline, sizeof(stacklog)-logpos);
				logpos += strlen(stacklog+logpos);
				if (logpos+1 >= sizeof(stacklog))
					break;
			}
			Sys_Printf("%s", stacklog+logstart);
			return EXCEPTION_EXECUTE_HANDLER;
		}
		else
		{
			Sys_Printf("We crashed.\nUnable to load dbghelp library. Stack info is not available\n");
			return EXCEPTION_EXECUTE_HANDLER;
		}
	}
#endif


	hDbgHelp = LoadLibrary ("DBGHELP");
	if (hDbgHelp)
		fnMiniDumpWriteDump = (MINIDUMPWRITEDUMP)GetProcAddress (hDbgHelp, "MiniDumpWriteDump");
	else
		fnMiniDumpWriteDump = NULL;

	if (fnMiniDumpWriteDump)
	{
		if (MessageBox(NULL, "KABOOM! We crashed!\nBlame the monkey in the corner.\nI hope you saved your work.\nWould you like to take a dump now?", DISTRIBUTION " Sucks", MB_ICONSTOP|MB_YESNO) != IDYES)
		{
			if (pIsDebuggerPresent ())
			{
				//its possible someone attached a debugger while we were showing that message
				return EXCEPTION_CONTINUE_SEARCH;
			}
			return EXCEPTION_EXECUTE_HANDLER;
		}

		/*take a dump*/
		GetTempPath (sizeof(dumpPath)-16, dumpPath);
		Q_strncatz(dumpPath, DISTRIBUTION"CrashDump.dmp", sizeof(dumpPath));
		dumpfile = CreateFile (dumpPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		if (dumpfile)
		{
			MINIDUMP_EXCEPTION_INFORMATION crashinfo;
			crashinfo.ClientPointers = TRUE;
			crashinfo.ExceptionPointers = exceptionInfo;
			crashinfo.ThreadId = GetCurrentThreadId ();
			if (fnMiniDumpWriteDump(hProc, procid, dumpfile, MiniDumpWithIndirectlyReferencedMemory|MiniDumpWithDataSegs, &crashinfo, NULL, NULL))
			{
				CloseHandle(dumpfile);
				MessageBox(NULL, va("You can find the crashdump at\n%s\nPlease send this file to someone.\n\nWarning: sensitive information (like your current user name) might be present in the dump.\nYou will probably want to compress it.", dumpPath), DISTRIBUTION " Sucks", 0);
				return EXCEPTION_EXECUTE_HANDLER;
			}
		}
	}
	else
		MessageBox(NULL, "Kaboom! Sorry. No MiniDumpWriteDump function.", FULLENGINENAME " Sucks", 0);
	return EXCEPTION_EXECUTE_HANDLER;
}
	void Reset()
	{
		mRed = (float)RPART(DWORD(*mCVar));
		mGreen = (float)GPART(DWORD(*mCVar));
		mBlue = (float)BPART(DWORD(*mCVar));
	}
Beispiel #23
0
AddrInfo GetAddr(uint32_t module, uint64_t addr)
{
  AddrInfo ret;
  ZeroMemory(&ret, sizeof(ret));

  if(module > 0 && module <= modules.size())
  {
    SymTagEnum tag = SymTagFunction;
    IDiaSymbol *pFunc = NULL;
    HRESULT hr = modules[module - 1].pSession->findSymbolByVA(addr, tag, &pFunc);

    if(hr != S_OK)
    {
      if(pFunc)
        pFunc->Release();

      // try again looking for public symbols
      tag = SymTagPublicSymbol;
      hr = modules[module - 1].pSession->findSymbolByVA(addr, tag, &pFunc);

      if(hr != S_OK)
      {
        if(pFunc)
          pFunc->Release();
        return ret;
      }
    }

    DWORD opts = 0;
    opts |= UNDNAME_NO_LEADING_UNDERSCORES;
    opts |= UNDNAME_NO_MS_KEYWORDS;
    opts |= UNDNAME_NO_FUNCTION_RETURNS;
    opts |= UNDNAME_NO_ALLOCATION_MODEL;
    opts |= UNDNAME_NO_ALLOCATION_LANGUAGE;
    opts |= UNDNAME_NO_THISTYPE;
    opts |= UNDNAME_NO_ACCESS_SPECIFIERS;
    opts |= UNDNAME_NO_THROW_SIGNATURES;
    opts |= UNDNAME_NO_MEMBER_TYPE;
    opts |= UNDNAME_NO_RETURN_UDT_MODEL;
    opts |= UNDNAME_32_BIT_DECODE;
    opts |= UNDNAME_NO_LEADING_UNDERSCORES;

    // first try undecorated name
    BSTR file;
    hr = pFunc->get_undecoratedNameEx(opts, &file);

    // if not, just try name
    if(hr != S_OK)
    {
      hr = pFunc->get_name(&file);

      if(hr != S_OK)
      {
        pFunc->Release();
        SysFreeString(file);
        return ret;
      }

      wcsncpy_s(ret.funcName, file, 126);
    }
    else
    {
      wcsncpy_s(ret.funcName, file, 126);

      wchar_t *voidparam = wcsstr(ret.funcName, L"(void)");

      // remove stupid (void) for empty parameters
      if(voidparam != NULL)
      {
        *(voidparam + 1) = L')';
        *(voidparam + 2) = 0;
      }
    }

    pFunc->Release();
    pFunc = NULL;

    SysFreeString(file);

    // find the line numbers touched by this address.
    IDiaEnumLineNumbers *lines = NULL;
    hr = modules[module - 1].pSession->findLinesByVA(addr, DWORD(4), &lines);
    if(FAILED(hr))
    {
      if(lines)
        lines->Release();
      return ret;
    }

    IDiaLineNumber *line = NULL;
    ULONG count = 0;

    // just take the first one
    if(SUCCEEDED(lines->Next(1, &line, &count)) && count == 1)
    {
      IDiaSourceFile *dia_source = NULL;
      hr = line->get_sourceFile(&dia_source);
      if(FAILED(hr))
      {
        line->Release();
        lines->Release();
        if(dia_source)
          dia_source->Release();
        return ret;
      }

      hr = dia_source->get_fileName(&file);
      if(FAILED(hr))
      {
        line->Release();
        lines->Release();
        dia_source->Release();
        return ret;
      }

      wcsncpy_s(ret.fileName, file, 126);

      SysFreeString(file);

      dia_source->Release();
      dia_source = NULL;

      DWORD line_num = 0;
      hr = line->get_lineNumber(&line_num);
      if(FAILED(hr))
      {
        line->Release();
        lines->Release();
        return ret;
      }

      ret.lineNum = line_num;

      line->Release();
    }

    lines->Release();
  }

  return ret;
}
	void Drawer()
	{
		Super::Drawer();

		if (mCVar == NULL) return;
		int y = (-mDesc->mPosition + BigFont->GetHeight() + mDesc->mItems.Size() * OptionSettings.mLinespacing) * CleanYfac_1;
		int h = (screen->GetHeight() - y) / 16;
		int fh = OptionSettings.mLinespacing * CleanYfac_1;
		int w = fh;
		int yy = y;

		if (h > fh) h = fh;
		else if (h < 4) return;	// no space to draw it.
		
		int indent = (screen->GetWidth() / 2);
		int p = 0;

		for(int i = 0; i < 16; i++, y += h)
		{
			int box_x, box_y;
			int x1;

			box_y = y - 2 * CleanYfac_1;
			box_x = indent - 16*w;
			for (x1 = 0; x1 < 16; ++x1, p++)
			{
				screen->Clear (box_x, box_y, box_x + w, box_y + h, p, 0);
				if ((mDesc->mSelectedItem == mStartItem+7) && 
					(/*p == CurrColorIndex ||*/ (i == mGridPosY && x1 == mGridPosX)))
				{
					int r, g, b;
					DWORD col;
					double blinky;
					if (i == mGridPosY && x1 == mGridPosX)
					{
						r = 255, g = 128, b = 0;
					}
					else
					{
						r = 200, g = 200, b = 255;
					}
					// Make sure the cursors stand out against similar colors
					// by pulsing them.
					blinky = fabs(sin(I_MSTime()/1000.0)) * 0.5 + 0.5;
					col = MAKEARGB(255,int(r*blinky),int(g*blinky),int(b*blinky));

					screen->Clear (box_x, box_y, box_x + w, box_y + 1, -1, col);
					screen->Clear (box_x, box_y + h-1, box_x + w, box_y + h, -1, col);
					screen->Clear (box_x, box_y, box_x + 1, box_y + h, -1, col);
					screen->Clear (box_x + w - 1, box_y, box_x + w, box_y + h, -1, col);
				}
				box_x += w;
			}
		}
		y = yy;
		DWORD newColor = MAKEARGB(255, int(mRed), int(mGreen), int(mBlue));
		DWORD oldColor = DWORD(*mCVar) | 0xFF000000;

		int x = screen->GetWidth()*2/3;

		screen->Clear (x, y, x + 48*CleanXfac_1, y + 48*CleanYfac_1, -1, oldColor);
		screen->Clear (x + 48*CleanXfac_1, y, x + 48*2*CleanXfac_1, y + 48*CleanYfac_1, -1, newColor);

		y += 49*CleanYfac_1;
		screen->DrawText (SmallFont, CR_GRAY, x+(24-SmallFont->StringWidth("Old")/2)*CleanXfac_1, y,
			"Old", DTA_CleanNoMove_1, true, TAG_DONE);
		screen->DrawText (SmallFont, CR_WHITE, x+(48+24-SmallFont->StringWidth("New")/2)*CleanXfac_1, y,
			"New", DTA_CleanNoMove_1, true, TAG_DONE);
	}
Beispiel #25
0
CDialogTemplate::CDialogTemplate(BYTE* pbData, unsigned int uCodePage) {
  m_uCodePage = uCodePage;

  m_szClass = 0;
  m_szFont = 0;
  m_szMenu = 0;
  m_szTitle = 0;

  WORD wItems = 0;

  if (*(DWORD*)pbData == 0xFFFF0001) { // Extended dialog template signature
    m_bExtended = true;

    DLGTEMPLATEEX* dTemplateEx = (DLGTEMPLATEEX*)pbData;

    m_dwHelpId = dTemplateEx->helpID;
    m_dwStyle = dTemplateEx->style;
    m_dwExtStyle = dTemplateEx->exStyle;
    m_sX = dTemplateEx->x;
    m_sY = dTemplateEx->y;
    m_sWidth = dTemplateEx->cx;
    m_sHeight = dTemplateEx->cy;

    wItems = dTemplateEx->cDlgItems;
  }
  else {
    m_bExtended = false;
    DLGTEMPLATE* dTemplate = (DLGTEMPLATE*)pbData;

    m_dwStyle = dTemplate->style;
    m_dwExtStyle = dTemplate->dwExtendedStyle;
    m_sX = dTemplate->x;
    m_sY = dTemplate->y;
    m_sWidth = dTemplate->cx;
    m_sHeight = dTemplate->cy;

    wItems = dTemplate->cdit;
  }

  BYTE* seeker = pbData + (m_bExtended ? sizeof(DLGTEMPLATEEX) : sizeof(DLGTEMPLATE));

  // Read menu variant length array
  ReadVarLenArr(seeker, m_szMenu, m_uCodePage);
  // Read class variant length array
  ReadVarLenArr(seeker, m_szClass, m_uCodePage);
  // Read title variant length array
  ReadVarLenArr(seeker, m_szTitle, m_uCodePage);
  // Read font size and variant length array (only if style DS_SETFONT is used!)
  if (m_dwStyle & DS_SETFONT) {
    m_sFontSize = *(short*)seeker;
    seeker += sizeof(short);
    if (m_bExtended) {
      m_sFontWeight = *(short*)seeker;
      seeker += sizeof(short);
      m_bItalic = *(BYTE*)seeker;
      seeker += sizeof(BYTE);
      m_bCharset = *(BYTE*)seeker;
      seeker += sizeof(BYTE);
    }
    ReadVarLenArr(seeker, m_szFont, m_uCodePage);
  }

  // Read items
  for (int i = 0; i < wItems; i++) {
    // DLGITEMTEMPLATE[EX]s must be aligned on DWORD boundry
    if (DWORD(seeker - pbData) % sizeof(DWORD))
      seeker += sizeof(WORD);

    DialogItemTemplate* item = new DialogItemTemplate;
    ZeroMemory(item, sizeof(DialogItemTemplate));

    if (m_bExtended) {
      DLGITEMTEMPLATEEX* rawItem = (DLGITEMTEMPLATEEX*)seeker;

      item->dwHelpId = rawItem->helpID;
      item->dwStyle = rawItem->style;
      item->dwExtStyle = rawItem->exStyle;
      item->sX = rawItem->x;
      item->sY = rawItem->y;
      item->sWidth = rawItem->cx;
      item->sHeight = rawItem->cy;
      item->wId = rawItem->id;

      seeker += sizeof(DLGITEMTEMPLATEEX);
    }
    else {
      DLGITEMTEMPLATE* rawItem = (DLGITEMTEMPLATE*)seeker;

      item->dwStyle = rawItem->style;
      item->dwExtStyle = rawItem->dwExtendedStyle;
      item->sX = rawItem->x;
      item->sY = rawItem->y;
      item->sWidth = rawItem->cx;
      item->sHeight = rawItem->cy;
      item->wId = rawItem->id;

      seeker += sizeof(DLGITEMTEMPLATE);
    }

    // Read class variant length array
    ReadVarLenArr(seeker, item->szClass, m_uCodePage);
    // Read title variant length array
    ReadVarLenArr(seeker, item->szTitle, m_uCodePage);

    // Read creation data variant length array
    // First read the size of the array (no null termination)
    item->wCreateDataSize = *(WORD*)seeker;
    seeker += sizeof(WORD);
    // Then read the array it self (if size is not 0)
    if (item->wCreateDataSize) {
      item->wCreateDataSize -= sizeof(WORD); // Size includes size field itself...
      item->szCreationData = new char[item->wCreateDataSize];
      CopyMemory(item->szCreationData, seeker, item->wCreateDataSize);
      seeker += item->wCreateDataSize;
    }

    // Add the item to the vector
    m_vItems.push_back(item);
  }
}
Beispiel #26
0
void CItemFindDialog::Parse( DWORD serverIndex, const MSGROOT* message )
{
	//ShowWindow( SW_SHOW );

	switch( message->Protocol )
	{
	case MP_RM_ITEM_FIND_OWNER_ACK:
		{
			const MSG_RM_ITEM_OWNER* m = ( MSG_RM_ITEM_OWNER* )message;

			if( mResultListCtrl.GetItemCount() )
			{
				if( ! m->mSize )
				{
					CString textThereIsNoResult;
					textThereIsNoResult.LoadString( IDS_STRING1 );

					MessageBox( textThereIsNoResult, _T( "" ), MB_ICONINFORMATION | MB_OK );
					return;
				}				
			}
			else if( ! m->mSize )
			{
				mViewPlayerButton.EnableWindow( FALSE );

				mResultStatic.SetWindowText( _T( "" ) );

				CString textThereIsNoResult;
				textThereIsNoResult.LoadString( IDS_STRING1 );

				MessageBox( textThereIsNoResult, _T( "" ), MB_ICONINFORMATION | MB_OK );
				return;
			}
			
			// add page
			{
				Page& page = mPageMap[ DWORD( mPageMap.size() ) ];

				const ItemScript& itemScript = mApplication.GetItemScript(
					m->mItemIndex);

				for( DWORD i = 0; i < m->mSize; ++i )
				{
					const MSG_RM_ITEM_OWNER::Player& player = m->mPlayer[ i ];

					if( page.end() != page.find( player.mIndex ) )
					{
						ASSERT( 0 && "Duplicated index is found" );
						continue;
					}

					Player& data	= page[ player.mIndex ];
					data.mItemIndex	= m->mItemIndex;
					data.mItemSize	= (itemScript.Stack ? player.mQuantity : player.mSlotSize);
					data.mName		= player.mName;
					data.mUserIndex	= player.mUserIndex;
				}
			}

			PutPage( DWORD( mPageMap.size() - 1 ) );

			const DWORD maxSize = sizeof( m->mPlayer ) / sizeof( m->mPlayer[ 0 ] );

			// 정보/컨트롤 갱신
			{
				mMoreFindButton.EnableWindow( maxSize == mResultListCtrl.GetItemCount() );

				CString text;
				text.Format( _T( "%d/%d" ), mPageMap.size(), mPageMap.size() );
				mPageStatic.SetWindowText( text );

				mPageNextButton.EnableWindow( FALSE );
				mPagePrevButton.EnableWindow( 1 < mPageMap.size() );

				mViewPlayerButton.EnableWindow( TRUE );
			}

			{
				const size_t size = max( mPageMap.size() - 1, 0 ) * maxSize + mResultListCtrl.GetItemCount();

				CString textFormat;
				textFormat.LoadString( IDS_STRING116 );

				CString text;
				text.Format( textFormat, mApplication.GetItemName( m->mItemIndex ), mSelectedServerName, size );

				mResultStatic.SetWindowText( _T( " " )+ text );
			}

			break;
		}
	case MP_RM_ITEM_FIND_OWNER_NACK:
		{
			ASSERT( 0 && "system fault detected" );
			break;
		}
	case MP_RM_ITEM_FIND_OWNER_NACK_BY_AUTH:
		{
			CString textYouHaveNoAuthority;
			textYouHaveNoAuthority.LoadString( IDS_STRING18 );

			MessageBox( textYouHaveNoAuthority, _T( "" ), MB_OK | MB_ICONERROR );
			break;
		}
	default:
		{
			ASSERT( 0 );
			break;
		}
	}
}
Beispiel #27
0
void CServerDlg::OnBnClickedStartServer()
{
	// TODO: Add your control notification handler code here

	char MapName[1024];
	if (!GetMapName(MapName)) return;
	SaveMapList();

	int iCatchInput = 1;
	int iDedicated = 0;
	int iSpectatorOnly = 0;
	int iBuild = 0;
	int iPrefetch = 1;
	int iR2 = 0;
	int iDistort = 1;
	int NameLen = 0;
	char Name[1024];
	char NameAdd[1024];
	char pTeam[2][1024] = {"/team=1", "/team=2"};
	char sLogsPath[1024] = "";
	char sCDKeyStr[1024] = "";
	
	int FragLimit = 0;
	int TimeLimit = 0;
	char FragLimStr[1024];
	char TimeLimStr[1024];
	char SpectrStr[1024];
	char ArtefactNumStr[1024]; 
	int ArtefactDelay = 0;
	char ArtefactDelayStr[1024]; 
	int ArtefactStay = 0;
	char ArtefactStayStr[1024]; 
	char ReinforcementStr[1024];
	
	
	if (m_pSVGameOptDlg->m_pFragLimit.GetWindowTextLength())
	{
		CString tmpText;
		m_pSVGameOptDlg->m_pFragLimit.GetWindowText(tmpText);
		FragLimit = atoi(tmpText);
		sprintf(FragLimStr, "/fraglimit=%d", FragLimit);
	};
	if (m_pSVGameOptDlg->m_pTimeLimit.GetWindowTextLength())
	{
		CString tmpText;
		m_pSVGameOptDlg->m_pTimeLimit.GetWindowText(tmpText);
		TimeLimit = atoi(tmpText);
		sprintf(TimeLimStr, "/timelimit=%d", TimeLimit);
	};
	char FriendlyFireStr[1024];
	sprintf(FriendlyFireStr, "/ffire=%d", m_pSVGameOptDlg->m_pFriedlyFire.GetPos());
	char AutoTeamBalanceStr[1024] = "";
	if (m_pSVGameOptDlg->m_pAutoTeamBalance.IsWindowEnabled())
		if (m_pSVGameOptDlg->m_pAutoTeamBalance.GetCheck())
			sprintf(AutoTeamBalanceStr, "/abalance=1");
	
	char AutoTeamSwapStr[1024] = "";
	if (m_pSVGameOptDlg->m_pAutoTeamSwap.IsWindowEnabled())
		if (m_pSVGameOptDlg->m_pAutoTeamSwap.GetCheck())
			sprintf(AutoTeamSwapStr, "/aswap=1");
	
	if (m_GameType == GAME_ARTEFACTHUNT)
	{
		DWORD_PTR ItemData = m_pSVGameOptDlg->m_pArtefactsNum.GetItemData(m_pSVGameOptDlg->m_pArtefactsNum.GetCurSel());
		sprintf(ArtefactNumStr, "/anum=%d", ItemData);
	
		CString tmpText;
		m_pSVGameOptDlg->m_pArtefactDelay.GetWindowText(tmpText);
		ArtefactDelay = atoi(tmpText);
		sprintf(ArtefactDelayStr, "/ardelta=%d", ArtefactDelay);
		
		m_pSVGameOptDlg->m_pArtefactStay.GetWindowText(tmpText);
		ArtefactStay = atoi(tmpText);
		sprintf(ArtefactStayStr, "/astime=%d", ArtefactStay);

		if (m_pSVRepawnDlg->m_pACaptured.GetCheck())
		{
			sprintf(ReinforcementStr, "/reinf=-1", tmpText);
		}
		else
		{

			m_pSVRepawnDlg->m_pReinforcementTime.GetWindowText(tmpText);
			int ReinfTime = atoi(tmpText);
			if (ReinfTime > 0)
				sprintf(ReinforcementStr, "/reinf=%s", tmpText);
			else
				sprintf(ReinforcementStr, "");
		};;
	}
	CStalker_netDlg* pMainDlg = (CStalker_netDlg*) (GetParent()->GetParent());
	if (pMainDlg)
	{
		iCatchInput = pMainDlg->m_pCatchInput.GetCheck();

		NameLen = pMainDlg->m_pPlayerName.GetWindowTextLength();
		if (NameLen) 
		{
			pMainDlg->m_pPlayerName.GetWindowText(Name, 1023);
			Name[32] = 0;
			sprintf(NameAdd, "/name=%s", Name);
		};

		iBuild = pMainDlg->m_pBuild.GetCheck();
		iPrefetch  = pMainDlg->m_pPrefetch.GetCheck();
		iR2 = pMainDlg->m_pR2.GetCheck();
		iDistort = pMainDlg->m_pDistort.GetCheck();
		if (pMainDlg->m_pLogsPath.GetWindowTextLength() != 0)
		{
			char tmp[1024];
			pMainDlg->m_pLogsPath.GetWindowText(tmp, 1024);
			sprintf(sLogsPath, "-overlaypath %s ", tmp);
		}
		if (pMainDlg->m_pCDKeyBtn.GetWindowTextLength() != 0)
		{
			char tmp[1024];
			pMainDlg->m_pCDKeyBtn.GetWindowText(tmp, 1024);
			if (xr_strcmp(tmp, "- No CD Key -") != 0)
				sprintf(sCDKeyStr, "/cdkey=%s", tmp);
		}
	};
	//--------- Server Options -----------------------------
	char HostNameStr[1024] = "";
	if (m_pSVServerOptDlg->m_pHostName.GetWindowTextLength() > 0)
	{
		char tmp[1024];
		m_pSVServerOptDlg->m_pHostName.GetWindowText(tmp, 1024);
		sprintf(HostNameStr, "/hname=%s", tmp);
	};
	char PasswordStr[1024] = "";
	if (m_pSVServerOptDlg->m_pPassword.GetWindowTextLength() > 0)
	{
		char tmp[1024];
		m_pSVServerOptDlg->m_pPassword.GetWindowText(tmp, 1024);
		sprintf(PasswordStr, "/psw=%s", tmp);
	}
	char MaxPlayersStr[1024] = "";
	if (m_pSVServerOptDlg->m_pMaxPlayers.GetWindowTextLength() > 0)
	{
		char tmp[1024];
		m_pSVServerOptDlg->m_pMaxPlayers.GetWindowText(tmp, 1024);
		sprintf(MaxPlayersStr, "/maxplayers=%s", tmp);
	};
	iDedicated = m_pSVServerOptDlg->m_pDedicated.GetCheck();
	iSpectatorOnly = m_pSVServerOptDlg->m_pSpectrMode.GetCheck();
	if (iSpectatorOnly)
	{
		CString tmpText;
		m_pSVServerOptDlg->m_pSpectrSwitchTime.GetWindowText(tmpText);
		int SpectrTime = atoi(tmpText);
		sprintf(SpectrStr, "/spectr=%d", SpectrTime);
	};
	int iPublic = m_pSVServerOptDlg->m_pPublic.GetCheck();
	int iCheckCDKey = 0;
	if (m_pSVServerOptDlg->m_pCheckCDKey.IsWindowEnabled())
		iCheckCDKey = m_pSVServerOptDlg->m_pCheckCDKey.GetCheck();

	int iRPFreezeTime = 0;
	char RPFreezeTimeStr[1024] = "";
	if (m_pSVRepawnDlg->m_pRPFreezeTime.GetWindowTextLength())
	{
		CString tmpText;
		m_pSVRepawnDlg->m_pRPFreezeTime.GetWindowText(tmpText);
		iRPFreezeTime = atoi(tmpText);
		sprintf(RPFreezeTimeStr, "/rpfrz=%i", iRPFreezeTime);
	}
	char MapRotStr[1024] = "";
//	if (m_pSVServerOptDlg->m_pMapRotation.GetCheck() &&
//		m_pSVServerOptDlg->m_pMapRotationFile.GetWindowTextLength())
//	{
//		CString MapRotFileName;
//		m_pSVServerOptDlg->m_pMapRotationFile.GetWindowText(MapRotFileName);
//		MapRotFileName += ".ltx";
//		sprintf(MapRotStr, "/maprot=%s", MapRotFileName);
//	}
	
	char VoteStr[1024] = "";
	if (m_pSVServerOptDlg->m_pVotingAllowed.GetCheck())
	{
		sprintf(VoteStr, "/vote=1");
	}
	char FIStr[1024] = "";
	if (m_pSVGameOptDlg->m_pFriendlyIndicators.IsWindowEnabled() && m_pSVGameOptDlg->m_pFriendlyIndicators.GetCheck())
	{
		sprintf(FIStr, "/fi=1");
	}
	char FNStr[1024] = "";
	if (m_pSVGameOptDlg->m_pFriendlyNames.IsWindowEnabled() && m_pSVGameOptDlg->m_pFriendlyNames.GetCheck())
	{
		sprintf(FNStr, "/fn=1");
	}
	char DmgBlkStr[1024] = "";
	if (m_pSVRepawnDlg->m_pDmBlockLimit.GetWindowTextLength())
	{
		CString DmgBlkLimit;
		m_pSVRepawnDlg->m_pDmBlockLimit.GetWindowText(DmgBlkLimit);
		sprintf(DmgBlkStr, "/dmgblock=%d", atol(DmgBlkLimit));
	}
	char DmgBlkStrInd[1024] = "";
	if (m_pSVRepawnDlg->m_pDmgBlkInd.IsWindowEnabled() && m_pSVRepawnDlg->m_pDmgBlkInd.GetCheck())
	{
		sprintf(DmgBlkStrInd, "/dmbi=1");
	}
	char ForceRespawnStr[1024] = "";
	if (m_pSVRepawnDlg->m_pForceRespawn.IsWindowEnabled() && m_pSVRepawnDlg->m_pForceRespawn.GetCheck())
	{
		CString ForceRespawnTime;
		m_pSVRepawnDlg->m_pForceRespawnTime.GetWindowText(ForceRespawnTime);
		if (atol(ForceRespawnTime))
		{
			sprintf(DmgBlkStr, "/frcrspwn=%d", atol(ForceRespawnTime));
		}
	};
	//-------------------------------------------
	char AnomalySetTimeStr[1024] = "";
	if (m_pSVGameOptDlg->m_pNoAnomalies.GetCheck()==0)
	{
		CString AnomalySetTime;
		m_pSVGameOptDlg->m_pAnomalySetTime.GetWindowText(AnomalySetTime);
		sprintf(DmgBlkStr, "/anslen=%d", atol(AnomalySetTime));
	}
//-----------------------------------------------------------------------------
	char WarmUpStr[1024] = "";
	if (m_pSVGameOptDlg->m_pWarmUpTime.GetWindowTextLength()>0)
	{
		CString WarmUpTime;
		m_pSVGameOptDlg->m_pWarmUpTime.GetWindowText(WarmUpTime);
		if (atol(WarmUpTime)>0)
			sprintf(WarmUpStr, "/warmup=%d", atol(WarmUpTime));
	}
//-----------------------------------------------------------------------------
	//------------- Weather ---------------------------
	char WeatherCoeff[1024] = "";
	char WeatherTime[1024] = "";
	if (m_pSVWeatherOptDlg->m_pWeatherSpeedCoeff.GetWindowTextLength())
	{
		CString WeatherSpeedCoeff;
		m_pSVWeatherOptDlg->m_pWeatherSpeedCoeff.GetWindowText(WeatherSpeedCoeff);
		sprintf(WeatherCoeff, "/etimef=%d", atol(WeatherSpeedCoeff));
	};
	if (m_pSVWeatherOptDlg->m_pStartWeather.GetCount())
	{
		DWORD Time = DWORD(m_pSVWeatherOptDlg->m_pStartWeather.GetItemData(m_pSVWeatherOptDlg->m_pStartWeather.GetCurSel()));
		sprintf(WeatherTime, "/estime=%d:%d", Time/60, Time%60);
	}

	//-------------------------------------------------
	//ports
	string512 SVPortStr = "";
	if (m_pSVServerOptDlg->m_pSVPort.GetWindowTextLength() > 0)
	{
		char tmp[1024];
		m_pSVServerOptDlg->m_pSVPort.GetWindowText(tmp, 1024);
		int Port = atol(tmp);		
		clamp(Port, START_PORT, END_PORT);
		sprintf(SVPortStr, "/portsv=%d", Port);
	};
	string512 CLPortStr = "";
	if (m_pSVServerOptDlg->m_pCLPort.GetWindowTextLength() > 0)
	{
		char tmp[1024];
		m_pSVServerOptDlg->m_pCLPort.GetWindowText(tmp, 1024);
		int Port = atol(tmp);		
		clamp(Port, START_PORT, END_PORT);
		sprintf(CLPortStr, "/portcl=%d", Port);
	};
	string512 GSPortStr = "";
	if (m_pSVServerOptDlg->m_pGSPort.GetWindowTextLength() > 0)
	{
		char tmp[1024];
		m_pSVServerOptDlg->m_pGSPort.GetWindowText(tmp, 1024);
		int Port = atol(tmp);		
		clamp(Port, START_PORT, END_PORT);
		sprintf(GSPortStr, "/portgs=%d", Port);
	};

//	-noprefetch
	string512	temp;
	char cmdline[4096];
	sprintf(cmdline, "%sxr_3da.exe %s -xclsx %s%s%s%s%s%s%s -nointro -external -nocache -start Server(%s/%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s) client(localhost%s%s%s)", 
			(iDedicated == 1) ? "dedicated\\" : "",
			(iDedicated == 1) ? "-nosound" : "",
			//---------------------------------
			(iCatchInput == 1 || iDedicated == 1) ? "-i " : "", 
			(iBuild == 1) ? "-build " : "",
			(iPrefetch == 1) ? "" : "-noprefetch ",
			(iR2 == 1) ? "-r2 " : "",
			(iDistort == 1) ? "" : "-nodistort ",
			(sLogsPath[0] == 0) ? "" : sLogsPath,
			//---------------------------------
			LTX,
			//---------------------------------
			MapName,
			//---------------------------------
			g_GameTypeName[m_GameType],
			HostNameStr,
			PasswordStr,
			MaxPlayersStr,
			(iPublic) ? "/public=1" : "",
			(iCheckCDKey) ? "/cdkey=1" : "",
			(iSpectatorOnly) ? SpectrStr : "",
			(FragLimit) ? FragLimStr : "",
			(TimeLimit) ? TimeLimStr : "",
			AutoTeamBalanceStr,
			AutoTeamSwapStr,
			(m_GameType != GAME_DEATHMATCH) ? FriendlyFireStr :"",
			(m_GameType == GAME_ARTEFACTHUNT) ? ArtefactNumStr : "",
			(m_GameType == GAME_ARTEFACTHUNT) ? ArtefactStayStr : "",
			(m_GameType == GAME_ARTEFACTHUNT) ? ArtefactDelayStr : "",
			(m_GameType == GAME_ARTEFACTHUNT) ? ReinforcementStr : "",
			(iRPFreezeTime) ? RPFreezeTimeStr : "",
			(m_pSVGameOptDlg->m_pNoAnomalies.GetCheck() == 1) ? "/ans=0" : "/ans=1",	
			(AnomalySetTimeStr[0]) ? AnomalySetTimeStr : "",
			(MapRotStr[0]) ? MapRotStr : "",
			(VoteStr[0]) ? VoteStr : "",
			(FIStr[0]) ? FIStr : "",
			(FNStr[0]) ? FNStr : "",
			(DmgBlkStr[0]) ? DmgBlkStr : "",
			(DmgBlkStrInd[0]) ? DmgBlkStrInd : "",
			(WeatherTime[0]) ? WeatherTime : "",
			(WeatherCoeff[0]) ? WeatherCoeff : "",
			(WarmUpStr[0]) ? WarmUpStr : "",
			m_pSVSpectatorOptsDlg->GetSpectatorModesStr(temp,sizeof(temp)),
			(SVPortStr[0]) ? SVPortStr : "",
			(GSPortStr[0]) ? GSPortStr : "",			
			//-------------------------------------
			(NameLen) ? NameAdd : "",
			(CLPortStr[0]) ? CLPortStr : "",
			(sCDKeyStr[0]) ? sCDKeyStr : ""
			);
	
//	if (xr_strlen(cmdline) > 4096) _ASSERT(0);
	OutputDebugString( cmdline );
	int res = WinExec(cmdline, SW_SHOW);	
	//-------------------------------------------------------
	/*
	char* _args[3];
	// check for need to execute something external

	{
		string4096 ModuleFileName = "";		
		GetModuleFileName(NULL, ModuleFileName, 4096);

		string4096 ModuleFilePath = "";
		char* ModuleName = NULL;
		GetFullPathName(ModuleFileName, 4096, ModuleFilePath, &ModuleName);
		ModuleName[0] = 0;

		if (iDedicated == 1)
		{
			char* envpath =getenv("PATH");
			string4096	NewEnvPath = "";
			sprintf(NewEnvPath , "PATH=%s;%s", ModuleFilePath,envpath);
			_putenv(NewEnvPath);

			strcat(ModuleFilePath, "dedicated\\xr_3DA.exe");
		}
		else
			strcat(ModuleFilePath, "xr_3da.exe");

		_args[0] = ModuleFilePath;//g_sLaunchOnExit_app;
		_args[1] = cmdline;//g_sLaunchOnExit_params;
		_args[2] = NULL;		

		_spawnv(_P_NOWAIT, _args[0], _args);//, _envvar);
	}
	*/
}
STDMETHODIMP CFdmUplShlExt::Initialize(LPCITEMIDLIST pidlFolder, IDataObject *pDataObj, HKEY hkeyProgID)
{
	CRegKey key;
	if (ERROR_SUCCESS == key.Open (HKEY_CURRENT_USER, 
			"Software\\FreeDownloadManager.ORG\\Free Upload Manager\\Settings\\Integration", KEY_READ))
	{
		DWORD dw = TRUE;
		key.QueryValue (dw, "ShowInExplorerContextMenu");
		if (dw == FALSE)
			return E_FAIL;
	}

	FORMATETC fmt = { CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
	STGMEDIUM stg = { TYMED_HGLOBAL };
	HDROP hDrop;

	if (FAILED (pDataObj->GetData (&fmt, &stg)))
		return E_INVALIDARG;

	hDrop = (HDROP) GlobalLock (stg.hGlobal);

	if (hDrop == NULL)
		return E_INVALIDARG;

	int cFiles = DragQueryFile (hDrop, 0xFFFFFFFF, NULL, 0);

	if (cFiles == 0)
	{
		GlobalUnlock (stg.hGlobal);
		ReleaseStgMedium (&stg);
		return E_INVALIDARG;
	}

	bool bHasNotLnkFiles = false;

	for (int i = 0; i < cFiles; i++)
	{
		char szFile [MAX_PATH];
		if (0 == DragQueryFile (hDrop, i, szFile, MAX_PATH))
			continue;

		DWORD dwAttribs = GetFileAttributes (szFile);
		if (dwAttribs == DWORD (-1))
			continue;

		if (bHasNotLnkFiles == false)
		{
			LPSTR psz = strrchr (szFile, '.');
			if (psz == NULL || stricmp (psz + 1, "lnk"))
				bHasNotLnkFiles = true;
		}
		
		

		m_vFiles.push_back (szFile);
	}

	GlobalUnlock (stg.hGlobal);
	ReleaseStgMedium (&stg);

	if (bHasNotLnkFiles == false)
		return E_INVALIDARG;

	return S_OK;
}
Beispiel #29
0
DWORD CMraProto::MraMessage(BOOL bAddToQueue, MCONTACT hContact, DWORD dwAckType, DWORD dwFlags, const CMStringA &szEmail, const CMStringW &lpwszMessage, LPBYTE lpbMultiChatData, size_t dwMultiChatDataSize)
{
	debugLogA("Sending message: flags %08x, to '%S', message '%S'\n", dwFlags, szEmail, lpwszMessage);

	DWORD dwRet = 0;
	LPSTR lpszMessageConverted = (LPSTR)lpwszMessage.GetString();
	LPSTR lpszMessageRTF = NULL;
	size_t dwMessageConvertedSize = lpwszMessage.GetLength()*sizeof(WCHAR), dwMessageRTFSize = 0;

	if (MraIsMessageFlashAnimation(lpwszMessage))
		dwFlags |= MESSAGE_FLAG_FLASH;

	// pack auth message
	if (dwFlags & MESSAGE_FLAG_AUTHORIZE) {
		OutBuffer buf;
		buf.SetUL(2);
		buf.SetLPSW(_T(""));//***deb possible nick here
		buf.SetLPSW(lpwszMessage);
		lpszMessageConverted = mir_base64_encode(buf.Data(), (int)buf.Len());
		dwMessageConvertedSize = mir_strlen(lpszMessageConverted);
	}
	// messages with Flash
	else if (dwFlags & MESSAGE_FLAG_FLASH) {
		dwFlags |= MESSAGE_FLAG_RTF;

		CMStringA lpszBuf(mir_u2a(lpwszMessage));

		OutBuffer buf;
		buf.SetUL(4);
		buf.SetLPS(lpszBuf);// сообщение что у собеседника плохая версия :)
		buf.SetUL(4);
		buf.SetUL(getDword("RTFBackgroundColour", MRA_DEFAULT_RTF_BACKGROUND_COLOUR));
		buf.SetLPS(lpszBuf);// сам мульт ANSI
		buf.SetLPSW(lpwszMessage);// сам мульт UNICODE

		DWORD dwBufSize = DWORD(buf.Len() + 128);
		lpszBuf.Truncate(dwBufSize);
		if (compress2((LPBYTE)(LPCSTR)lpszBuf, &dwBufSize, buf.Data(), (int)buf.Len(), Z_BEST_COMPRESSION) == Z_OK) {
			lpszMessageRTF = mir_base64_encode((LPBYTE)(LPCSTR)lpszBuf, dwBufSize);
			dwMessageRTFSize = mir_strlen(lpszMessageRTF);
		}
	}
	// standart message
	else if ((dwFlags & (MESSAGE_FLAG_CONTACT | MESSAGE_FLAG_NOTIFY | MESSAGE_FLAG_SMS)) == 0) {
		// Only if message is simple text message or RTF or ALARM
		if (dwFlags & MESSAGE_FLAG_RTF) { // add RFT part
			CMStringA lpbRTFData; lpbRTFData.Truncate(lpwszMessage.GetLength() * 16 + 4096);
			if (!MraConvertToRTFW(lpwszMessage, lpbRTFData)) {
				DWORD dwBackColour = getDword("RTFBackgroundColour", MRA_DEFAULT_RTF_BACKGROUND_COLOUR);

				OutBuffer buf;
				buf.SetUL(2);
				buf.SetLPS(lpbRTFData);
				buf.SetUL(4);
				buf.SetUL(dwBackColour);

				DWORD dwRTFDataSize = lpbRTFData.GetLength();
				if (compress2((LPBYTE)(LPCSTR)lpbRTFData, &dwRTFDataSize, buf.Data(), (int)buf.Len(), Z_BEST_COMPRESSION) == Z_OK) {
					lpszMessageRTF = mir_base64_encode((LPBYTE)(LPCSTR)lpbRTFData, dwRTFDataSize);
					dwMessageRTFSize = mir_strlen(lpszMessageRTF);
				}
			}
		}
	}

	if (lpszMessageRTF == NULL || dwMessageRTFSize == 0) dwFlags &= ~(MESSAGE_FLAG_RTF | MESSAGE_FLAG_FLASH);
	if (lpbMultiChatData == NULL || dwMultiChatDataSize == 0) dwFlags &= ~MESSAGE_FLAG_MULTICHAT;

	OutBuffer buf;
	buf.SetUL(dwFlags);
	buf.SetLPSLowerCase(szEmail);
	buf.SetLPS(CMStringA(lpszMessageConverted, (int)dwMessageConvertedSize));
	buf.SetLPS(lpszMessageRTF);
	if (dwFlags & MESSAGE_FLAG_MULTICHAT)
		buf.SetLPS(CMStringA((LPSTR)lpbMultiChatData, (int)dwMultiChatDataSize));

	if (bAddToQueue)
		dwRet = MraSendQueueCMD(hSendQueueHandle, 0, hContact, dwAckType, NULL, 0, MRIM_CS_MESSAGE, buf.Data(), buf.Len());
	else
		dwRet = MraSendCMD(MRIM_CS_MESSAGE, buf.Data(), buf.Len());

	return dwRet;
}
Beispiel #30
0
// Play
void AudioStream::Play(long volume, int looping)
{
	if (m_pdsb)
	{
		// If playing, stop
		if (m_fPlaying)
		{
			if (m_bIsPaused == FALSE)
				Stop_and_Rewind();
		}

		// Cue for playback if necessary
		if (!m_fCued)
		{
			Cue();
		}

		if (looping)
			m_bLooping = 1;
		else
			m_bLooping = 0;

		// Begin DirectSound playback
		HRESULT hr = m_pdsb->Play(0, 0, DSBPLAY_LOOPING);
		if (hr == DS_OK)
		{
			m_nTimeStarted = timer_get_milliseconds();
			Set_Volume(volume);
			// Kick off timer to service buffer
			m_timer.constructor();

			m_timer.Create(m_nBufService, m_nBufService, DWORD(this), TimerCallback);

			// Playback begun, no longer cued
			m_fPlaying = TRUE;
			m_bIsPaused = FALSE;
		}
		else
		{
			// If the buffer was lost, try to restore it
			if (hr == DSERR_BUFFERLOST)
			{
				hr = m_pdsb->Restore();
				if (hr == DS_OK)
				{
					hr = m_pdsb->Play(0, 0, DSBPLAY_LOOPING);
				}
				else
				{
					nprintf(("Sound", "Sound => Lost a buffer, tried restoring but got %s\n", get_DSERR_text(hr)));
					Int3();	// get Alan, he wants to see this
				}
			}

			if (hr != DS_OK)
			{
				nprintf(("Sound", "Sound => Play failed with return value %s\n", get_DSERR_text(hr)));
			}
		}
	}
}