Exemple #1
0
		void CConfig::save(const tstring& sFile)
		{	
			if(!sFile.empty())
			{
				m_sPath = sFile;
			}

			CXMLElement* pXML = new CXMLElement(NULL,_T("config"));			

			list<CParamItem*>::iterator iter = m_items.begin();
			while (iter != m_items.end())
			{
				(*iter)->save(pXML);
				iter++;
			}			
					
			pXML->toFile(m_sPath,true);
			delete pXML;			
		}		
Exemple #2
0
bool CgcUdpClient::setRemoteAddr(const tstring & sRemoteAddr)
{
	if (sRemoteAddr.empty()) return false;
	if (sRemoteAddr==m_ipRemote.address())
		return true;
	std::vector<std::string> pList;
	if (CgcBaseClient::ParseString(sRemoteAddr.c_str(),":",pList)==2)
	{
		std::string sIp;
		for (int i=0;i<20;i++)
		{
			sIp = CgcBaseClient::GetHostIp(pList[0].c_str(),"");
			if (!sIp.empty())
				break;
#ifdef WIN32
			Sleep(100);
#else
			usleep(100000);
#endif
		}
		if (sIp.empty())
		{
			// *
			return false;
			sIp = pList[0];
		}
		unsigned short nPort = atoi(pList[1].c_str());
		if (m_ipRemote.getport()!=nPort || m_ipRemote.getip()!=sIp)
		{
			m_ipRemote.address(sIp,nPort);
			boost::system::error_code ec;
			m_endpointRemote.address(boost::asio::ip::address_v4::from_string(sIp.c_str(),ec));
			m_endpointRemote.port(nPort);
		}
		if (m_udpClient.get()!=NULL && m_udpClient->socket()!=NULL)
		{
			boost::system::error_code ec;
			m_udpClient->socket()->connect(m_endpointRemote,ec);
		}
		return true;
	}
	return false;
}
Exemple #3
0
inline bool CMapMatchImpl::BuildIO(const tstring &strCon)
{
  assert(m_explainer);

  if(strCon.empty())
  {
#if __UE_WINDOWS__
    m_io = new CWinComIO(strCon, *m_explainer);
#else
#pragma message(__FILE__">> Need COMM functions invloved by current platform!")
#endif
  }
  else
  {
    m_io = new CFileIO(strCon, *m_explainer);
  }

  return m_io != 0;
}
Exemple #4
0
bool FileUtils::_isFileExistInternal(const tstring& strFilePath) const
{
	if (strFilePath.empty()) return false;

	tstring strPath = strFilePath;

#ifdef SHEET_X_UNICODE
	DWORD attr = GetFileAttributesW(strPath.c_str());
#else
	static WCHAR utf16Buf[512] = {0};
	MultiByteToWideChar(CP_ACP, 0, strPath.c_str(), -1, utf16Buf, sizeof(utf16Buf)/sizeof(utf16Buf[0]));
	DWORD attr = GetFileAttributesW(utf16Buf);
#endif
	
	if(attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY))
		return false;   //  not a file

	return true;
}
Exemple #5
0
void onEndTestSet()
{
	ASSERT(s_currentTestCase.empty());
	ASSERT(s_currentTestCaseAsserts.empty());

	if (!s_quiet && !s_verbose)
	{
		tcout << std::endl;
	}

	if (!s_failures.empty())
	{
		const tstring failureCount = (s_quiet) ? Core::fmt(TXT(" %s: %u failure(s)"), s_currentTestSet.c_str(), s_failures.size())
											   : Core::fmt(TXT(" %u failure(s)"), s_failures.size());

		tcout << std::endl;
		tcout << failureCount << std::endl;

		for (size_t i = 0; i != s_failures.size(); ++i)
		{
			debugWrite(TXT(" > %s\n"), s_failures[i].c_str());
			tcout << TXT(" > ") << s_failures[i] << std::endl;

			for (size_t j = 0; j != s_failuresAsserts[i].size(); ++j)
			{
				debugWrite(TXT("  %s\n"), s_failuresAsserts[i][j].c_str());
				tcout << TXT("  ") << s_failuresAsserts[i][j] << std::endl;
			}
		}
	}

	if (!s_quiet)
	{
		tcout << std::endl;
	}

	s_currentTestSet.clear();
	s_failures.clear();
	s_failuresAsserts.clear();
	s_executed.clear();
	s_setup = nullptr;
	s_teardown = nullptr;
}
Exemple #6
0
BOOL CMainWindow::HandleCustomPic(CRichEditUI * pRichEdit, LPCTSTR& p, tstring& strText)
{
	tstring strFileName = GetBetweenString(p+2, _T("[\""), _T("\"]"));
	if (!strFileName.empty())
	{
		if (!strText.empty())
		{
			_RichEdit_ReplaceSel(pRichEdit, strText.c_str()); 
			strText = _T("");
		}

		_RichEdit_InsertFace(pRichEdit, strFileName.c_str(), -1, -1);

		p = _tcsstr(p+2, _T("\"]"));
		p++;
		return TRUE;
	}
	return FALSE;
}
Exemple #7
0
bool FolderTree::HasGotSubEntries(const tstring &sDirectory)
{
	if(sDirectory.empty())
		return false;

	if(DriveHasRemovableMedia(sDirectory))
	{
		return true; //we do not bother searching for files on drives
					//which have removable media as this would cause
					//the drive to spin up, which for the case of a
					//floppy is annoying
	}
	else
	{
		//First check to see if there is any sub directories
		tstring sFile;
		if (sDirectory[sDirectory.size()-1] == _T('\\'))
			sFile = sDirectory + _T("*.*");
		else
			sFile = sDirectory + _T("\\*.*");

		WIN32_FIND_DATA fData;
		HANDLE hFind;
		hFind = FindFirstFile(sFile.c_str(), &fData);
		if(hFind != INVALID_HANDLE_VALUE)
		{
			do
			{
				tstring cFileName = fData.cFileName;
				if((fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && 
					(cFileName != _T(".")) && (cFileName != _T("..")))
				{
					FindClose(hFind);
					return true;
				}
			} while (FindNextFile(hFind, &fData));
		}

		FindClose(hFind);
	}

	return false;
}
Exemple #8
0
		void CConfig::load(const tstring& sFile)
		{
			if(!sFile.empty())
			{
				m_sPath = sFile;
			}	

			CXMLElement* pXML = CXMLElement::fromFile(m_sPath);
			if(pXML == NULL)
				return;

			list<CParamItem*>::iterator iter = m_items.begin();
			while (iter != m_items.end())
			{
				(*iter)->load(pXML);
				iter++;
			}			

			delete pXML;
		}
bool AsGroupsDlg::getItem(tstring& name, bool checkSel) {
	{
		CEdit wnd;
		wnd.Attach(GetDlgItem(IDC_NAME));
		name = WinUtil::getEditText(wnd);
		wnd.Detach();
		if (name.empty()) {
			MessageBox(_T("You must enter a group name!"), CTSTRING(MANAGE_GROUPS), MB_ICONERROR);
			return false;
		}
		else {
			int32_t pos = findGroup(name.c_str());
			if (pos != -1 && (checkSel == false || pos != ctrlGroups.GetSelectedIndex())) {
				MessageBox(_T("Item already exists!"), CTSTRING(MANAGE_GROUPS), MB_ICONERROR);
				return false;
			}
		}
	}
	return true;
}
Exemple #10
0
	/********************************************************************
	* [函数名]: output
	* [描述]: 打印信息
	* [修改记录]:
	*   2015-05-20,littledj: create
	********************************************************************/
	void GLogger::output(const tstring& msg, PRINT_COLOR color)
	{
		if (msg.empty())
			output_screen(TEXT("<empty message>"), color);

		// 判断是否输出到屏幕
		if (m_wpTarget == PRINT_TARGET::SCREEN)
			output_screen(msg, color);

		// 判断是否输出到日志文件
		else if (m_wpTarget == PRINT_TARGET::FILE)
			output_file(msg);

		// 都输出
		else if (m_wpTarget == PRINT_TARGET::BOTH)
		{
			output_screen(msg, color);
			output_file(msg);
		}
	}
int	CDBTableCollection::IndexOf(const tstring& tbl)
{
    int iRet = -1;
    if(tbl.empty())
    {
        _ASSERT(false);
        return iRet;
    }

    for (DBTableCollection::const_iterator iter = Tables.begin(); iter != Tables.end(); ++iter)
    {
        ++iRet;
        if((*iter)->GetName() == tbl)
        {
            return iRet;
        }
    }

    return -1;
}
Exemple #12
0
// Find a string value within an expanded string, returns the offset if found, else string::npos
// We need to match the entire string, so that we can match '3' in the following
// 1,2,33,3 and not match the 33
tstring::size_type FindValueInExpandedString(const tstring& szData, const tstring& szSearch, tstring::size_type iValueIndex)
{
	if (szData.empty())
		return tstring::npos;

	bool bCompleted = false;
	size_t iValueOffset = 0;
	tstring szTmpVal;

	if (iValueIndex > 0)
		iValueOffset = iValueIndex;
	else
		iValueIndex = tstring::npos;

	while (!bCompleted)
	{
		if (iValueOffset >= szData.length())
		{
			bCompleted = true;
			continue;
		}

		tstring::size_type iTmpIndex = szData.find(_T(";"), iValueOffset);

		if (iTmpIndex != tstring::npos)
			szTmpVal = szData.substr(iValueOffset, iTmpIndex - iValueOffset); // Grab up to the next seperator
		else
			szTmpVal = szData.substr(iValueOffset, szData.length()); // Grab up to the end of the line

		if (szTmpVal == szSearch) // Found it so stop searching
		{
			iValueIndex = iValueOffset;
			bCompleted = true;
			continue;
		}

		iValueOffset += szTmpVal.length() + 1; // Move to the next entry
	}

	return iValueIndex;
}
Exemple #13
0
BOOL CMainWindow::HandleSysFaceIndex(CRichEditUI * pRichEdit, LPCTSTR& p, tstring& strText)
{
	int nFaceIndex = GetBetweenInt(p+2, _T("[\""), _T("\"]"), -1);
	CFaceInfo * lpFaceInfo = m_FaceList.GetFaceInfoByIndex(nFaceIndex);
	if (lpFaceInfo != NULL)
	{
		if (!strText.empty())
		{
			_RichEdit_ReplaceSel(pRichEdit, strText.c_str()); 
			strText = _T("");
		}

		_RichEdit_InsertFace(pRichEdit, lpFaceInfo->m_strFileName.c_str(), 
			lpFaceInfo->m_nId, lpFaceInfo->m_nIndex);

		p = _tcsstr(p+2, _T("\"]"));
		p++;
		return TRUE;
	}
	return FALSE;
}
Exemple #14
0
///////////////////////////////////////////////////////////////////////////////
// Reads a value from the registry.  You can specify a relative path and the
// actual key to read.  The value parameter will be populated with valid data
// if this function returns true.
//
// The relativePath parameter should be separated by forward-slashes, but not
// start with one.  Example: Foo/Bar
//
bool SimpleConfig::Read( const tstring& relativePath, const tstring& key, tstring& value )
{
    bool wasRead = false;

    wxString oldPath = m_Config->GetPath();

    if ( !relativePath.empty() )
    {
        m_Config->SetPath( relativePath.c_str() );
    }

    wxString wxVal;
    if ( m_Config->Read( key.c_str(), &wxVal ) )
    {
        value = wxVal.c_str();
        wasRead = true;
    }
    m_Config->SetPath( oldPath );

    return wasRead;
}
Exemple #15
0
void onStartTestSet(const tchar* name)
{
	ASSERT(tstrlen(name) != 0);
	ASSERT(s_currentTestCase.empty());
	ASSERT(s_currentTestCaseAsserts.empty());

	if (!s_quiet)
	{
		tcout << name << std::endl;

		if (!s_verbose)
			tcout << TXT(" ");
	}

	s_currentTestSet = name;
	s_failures.clear();
	s_failuresAsserts.clear();
	s_executed.clear();
	s_setup = nullptr;
	s_teardown = nullptr;
}
Exemple #16
0
void ChatControl::onTab() {
  if (ctrlMessage.GetWindowTextLength() == 0) {
    //TODO handleTab(WinUtil::isShift());
    return;
  }		
  HWND focus = GetFocus();
  if( (focus == ctrlMessage.m_hWnd) && !WinUtil::isShift() ) 	{
    int n = ctrlMessage.GetWindowTextLength();
    AutoArray<TCHAR> buf(n+1);
    ctrlMessage.GetWindowText(buf, n+1);
    tstring text(buf, n);
    string::size_type textStart = text.find_last_of(_T(" \n\t"));
    if (complete.empty()) {
      if (textStart != string::npos) {
        complete = text.substr(textStart + 1);
      } 
      else {
        complete = text;
      }
      if (complete.empty()) {
        // Still empty, no text entered...
        m_listener->autoCompleteFaliure();
        return;
      }
      m_listener->autoCompleteBegin();
    }
    const tstring completedNick = m_listener->autoCompleteUserNick(complete);
    if (!completedNick.empty()) {
      if (textStart == string::npos) {
        textStart = 0;
      }
      else {
        textStart++;
      }
      ctrlMessage.SetSel(textStart, ctrlMessage.GetWindowTextLength(), TRUE);
      ctrlMessage.ReplaceSel(completedNick.c_str());
    }
  }
}
/**
 * Fallback thumbnail handler function.
 * @param cx
 * @param phbmp
 * @param pdwAlpha
 * @return HRESULT.
 */
HRESULT RP_ThumbnailProvider_Private::Fallback(UINT cx, HBITMAP *phbmp, WTS_ALPHATYPE *pdwAlpha)
{
	// TODO: Check HKCU first.

	// Get the file extension.
	const string filename = this->file->filename();
	if (filename.empty()) {
		return E_INVALIDARG;
	}
	const char *file_ext = FileSystem::file_ext(filename);
	if (!file_ext) {
		// Invalid or missing file extension.
		return E_INVALIDARG;
	}

	// Open the filetype key in HKCR.
	RegKey hkey_Assoc(HKEY_CLASSES_ROOT, U82T_c(file_ext), KEY_READ, false);
	if (!hkey_Assoc.isOpen()) {
		return hkey_Assoc.lOpenRes();
	}

	// If we have a ProgID, check it first.
	const tstring progID = hkey_Assoc.read(nullptr);
	if (!progID.empty()) {
		// Custom ProgID is registered.
		// TODO: Get the correct top-level registry key.
		RegKey hkcr_ProgID(HKEY_CLASSES_ROOT, progID.c_str(), KEY_READ, false);
		if (hkcr_ProgID.isOpen()) {
			HRESULT hr = Fallback_int(hkcr_ProgID, cx, phbmp, pdwAlpha);
			if (SUCCEEDED(hr)) {
				// ProgID thumbnail extracted.
				return hr;
			}
		}
	}

	// Extract the thumbnail from the filetype key.
	return Fallback_int(hkey_Assoc, cx, phbmp, pdwAlpha);
}
Exemple #18
0
tstring FileUtils::fullPathForFilename(const tstring &filename) const
{
	if (filename.empty())
	{
		return "";
	}

	if (_isAbsolutePath(filename))
	{
		return filename;
	}

	// Already Cached ?
	auto cacheIter = _fullPathCache.find(filename);
	if(cacheIter != _fullPathCache.end())
	{
		return cacheIter->second;
	}

	tstring unixFileName = _convertPathFormatToUnixStyle(filename);

	tstring fullpath;

	for (const auto& searchIt : _searchPathArray)
	{

		fullpath = _getPathForFilename(unixFileName, searchIt);

		if (fullpath.length() > 0)
		{
			// Using the filename passed in as key.
			_fullPathCache.insert(std::make_pair(filename, fullpath));
			return fullpath;
		}
	}

	// The file wasn't found, return empty string.
	return "";
}
Exemple #19
0
void ShellCache::CPathFilter::AddEntry (const tstring& s, bool include)
{
    if (s.empty())
        return;

    TCHAR lastChar = *s.rbegin();

    SEntry entry;
    entry.hasSubFolderEntries = false;
    entry.recursive = lastChar != '?';
    entry.included = include ? svn_tristate_true : svn_tristate_false;
    entry.subPathIncluded = include == entry.recursive
                          ? svn_tristate_true
                          : svn_tristate_false;

    entry.path = s;
    if ((lastChar == '?') || (lastChar == '*'))
        entry.path.erase (s.length()-1);
    if (!entry.path.empty() && (*entry.path.rbegin() == '\\'))
        entry.path.erase (entry.path.length()-1);

    data.push_back (entry);
}
Exemple #20
0
// HKEY_CLASSES_ROOT
//    FileMarker.AVI - AVI - Windows 기본 비디오 파일
//       shell
// 	       Mark - Daum 팟플레이어의 재생목록(&I)에 추가하기
// 		    command - "C:\Program Files (x86)\DAUM\PotPlayer\PotPlayer.exe" "%1" /ADD
bool CRegisterMenu::Register(const tstring& strAppName, tstring strExt, 
                             tstring strMenu, tstring strMenuDisplay, 
                             tstring strCommand, tstring strDesc)
{
  if (strAppName.empty() || strExt.empty() || strDesc.empty() || 
      strMenu.empty() || strMenuDisplay.empty() || strCommand.empty())
    return false;

  if (!RegisterExtKey(strExt, strMenu, strMenuDisplay, strCommand))
    return false;

  // remove '.'
  strExt.erase(std::remove(strExt.begin(), strExt.end(), _T('.')), strExt.end());

  // Uppercase extension
  CStringUtil::MakeUpper(strExt);
  tstring strAppExt = strAppName + _T(".") + strExt;

  LPCTSTR strSubKeys[] = { strAppExt.c_str(), 
                           _T("shell"), 
                           strMenu.c_str(), 
                           _T("command") };

  LPCTSTR strValues[] = { strDesc.c_str(),
                          _T(""),
                          strMenuDisplay.c_str(),
                          strCommand.c_str() };

  tstring strSubKey;
  tstring strValue;
  for (int i = 0; i < _countof(strSubKeys); ++i)
  {
    strSubKey += strSubKeys[i];
    strSubKey += _T("\\");
    strValue = strValues[i];

    if (!RegisterMenu(strSubKey, strValue))
      return false;
  }

//	SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_FLUSH, NULL, NULL);

  return true;
}
Exemple #21
0
bool CMagicKHelper::GeneratePng(tstring& strBinary, tstring& strOutputPath)
{
	bool bSucc = false;
	if (!strBinary.empty())
	{
		tstring strFileName = strOutputPath + _T(".png");

		Magick::Blob input_blob((void*)strBinary.c_str(),strBinary.length());
		Magick::Image input_image;
		input_image.magick("INLINE");

//		EnterCriticalSection(cs_);

		input_image.read(input_blob);
		CLogger::GetInstance()->PrintErrLog("read successed");
		input_image.magick("PNG");
		input_image.write(strFileName.c_str());

//		LeaveCriticalSection(cs_);
		bSucc = true;
	}

	return bSucc;
}
Exemple #22
0
///////////////////////////////////////////////////////////////////////////////
// Populates the custom colors of colorData with the values stored in the info
// string.  The info string is expected to have been generated by calling the
// above Save function.
// 
void CustomColors::Load( wxColourData& colorData, const tstring& info )
{
  if ( !info.empty() )
  {
    std::vector< tstring > colors;
    Tokenize( info, colors, s_ColorDelimiter );
    
    std::vector< tstring >::const_iterator colorItr = colors.begin();
    std::vector< tstring >::const_iterator colorEnd = colors.end();
    for ( i32 colorIndex = 0; colorItr != colorEnd && colorIndex < NumColors; ++colorItr, ++colorIndex )
    {
      const tstring& colorStr = *colorItr;
      if ( colorStr.length() >= 6 )
      {
        u32 red = 0;
        u32 green = 0;
        u32 blue = 0;
        _stscanf( colorStr.c_str(), TXT( "%02X%02X%02X" ), &red, &green, &blue );

        colorData.SetCustomColour( colorIndex, wxColour( (u8)red, (u8)green, (u8)blue ) );
      }
    }
  }
}
Exemple #23
0
void ChatControl::findText(tstring const& needle) throw() {
  int max = ctrlClient.GetWindowTextLength();
  // a new search? reset cursor to bottom
  if (needle != currentNeedle || currentNeedlePos == -1) {
    currentNeedle = needle;
    currentNeedlePos = max;
  }
  // set current selection
  FINDTEXT ft;
  ft.chrg.cpMin = currentNeedlePos;
  ft.chrg.cpMax = 0; // поиск идет в обратную сторону, поэтому параметры передаем в обратном порядке.
  ft.lpstrText = needle.c_str();
  // empty search? stop
  if (needle.empty()) {
    return;
  }
  // find upwards
  currentNeedlePos = (int) ctrlClient.SendMessage(EM_FINDTEXT, 0, (LPARAM)&ft);
  // not found? try again on full range
  if (currentNeedlePos == -1 && ft.chrg.cpMin != max) { // no need to search full range twice
    currentNeedlePos = max;
    ft.chrg.cpMin = currentNeedlePos;
    currentNeedlePos = (int)ctrlClient.SendMessage(EM_FINDTEXT, 0, (LPARAM)&ft);
  }
  // found? set selection
  if (currentNeedlePos != -1) {
    ft.chrg.cpMin = currentNeedlePos;
    ft.chrg.cpMax = currentNeedlePos + needle.length();
    ctrlClient.SetFocus();
    ctrlClient.SendMessage(EM_EXSETSEL, 0, (LPARAM)&ft);
  } 
  else {
    addSystemMessage(CTSTRING(STRING_NOT_FOUND) + needle);
    currentNeedle = Util::emptyStringT;
  }
}
bool FolderDialog::open(tstring& folder) {
	BROWSEINFO bws = { 0 };
	bws.hwndOwner = getParentHandle();
	bws.pidlRoot = itsPidlRoot;
	if(!itsTitle.empty()) {
		bws.lpszTitle = itsTitle.c_str();
	}
	bws.ulFlags = BIF_USENEWUI | BIF_RETURNONLYFSDIRS | BIF_EDITBOX;
	if(!folder.empty()) {
		bws.lParam = reinterpret_cast<LPARAM>(folder.c_str());
		bws.lpfn = &browseCallbackProc;
	}

	// Avoid errors about missing cdroms, floppies etc..
	UINT oldErrorMode = ::SetErrorMode(SEM_FAILCRITICALERRORS);
	
	LPITEMIDLIST lpIDL = SHBrowseForFolder( & bws );
	
	::SetErrorMode(oldErrorMode);
	
	if(lpIDL) {
		TCHAR buf[MAX_PATH + 1];
		if ( ::SHGetPathFromIDList( lpIDL, buf ) ) {
			folder = buf;
			
			if(folder.size() > 0 && folder[folder.size()-1] != _T('\\')) {
				folder += _T('\\');
			}
			
			::CoTaskMemFree(lpIDL);
			return true;
		}
		::CoTaskMemFree(lpIDL);
	}
	return false;
}
Exemple #25
0
LRESULT WaitingUsersFrame::onCustomDraw(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
{
	/*  [-] IRainman
	if (!BOOLSETTING(SHOW_PROGRESS_BARS))
	{
	    bHandled = FALSE;
	    return 0;
	}
	*/
	CRect rc;
	LPNMLVCUSTOMDRAW cd = reinterpret_cast<LPNMLVCUSTOMDRAW>(pnmh);
	UploadQueueItem *ii = (UploadQueueItem*)cd->nmcd.lItemlParam; // ??
	
	switch (cd->nmcd.dwDrawStage)
	{
		case CDDS_PREPAINT:
			return CDRF_NOTIFYITEMDRAW;
		case CDDS_ITEMPREPAINT:
#ifdef FLYLINKDC_USE_LIST_VIEW_MATTRESS
			Colors::alternationBkColor(cd); // [+] IRainman
#endif
			return CDRF_NOTIFYSUBITEMDRAW;
			
		case CDDS_SUBITEM | CDDS_ITEMPREPAINT:
		{
			// Let's draw a box if needed...
			if (BOOLSETTING(SHOW_PROGRESS_BARS) && m_ctrlList.findColumn(cd->iSubItem) == UploadQueueItem::COLUMN_TRANSFERRED) // [+] IRainman
			{
				// draw something nice...
				LocalArray<TCHAR, 256> buf;
				m_ctrlList.GetItemText((int)cd->nmcd.dwItemSpec, cd->iSubItem, buf.data(), 255);
				m_ctrlList.GetSubItemRect((int)cd->nmcd.dwItemSpec, cd->iSubItem, LVIR_BOUNDS, rc);
				// Real rc, the original one.
				CRect real_rc = rc;
				// We need to offset the current rc to (0, 0) to paint on the New dc
				rc.MoveToXY(0, 0);
				
				// Text rect
				CRect rc2 = rc;
				rc2.left += 6; // indented with 6 pixels
				rc2.right -= 2; // and without messing with the border of the cell
				
				// Set references
				CDC cdc;
				cdc.CreateCompatibleDC(cd->nmcd.hdc);
				HBITMAP hBmp = CreateCompatibleBitmap(cd->nmcd.hdc,  real_rc.Width(),  real_rc.Height());
				HBITMAP pOldBmp = cdc.SelectBitmap(hBmp);
				HDC& dc = cdc.m_hDC;
				
				HFONT oldFont = (HFONT)SelectObject(dc, Fonts::g_font);
				SetBkMode(dc, TRANSPARENT);
				
				CBarShader statusBar(rc.bottom - rc.top, rc.right - rc.left, RGB(150, 0, 0), ii->getSize());
				statusBar.FillRange(0, ii->getPos(), RGB(222, 160, 0));
				statusBar.Draw(cdc, rc.top, rc.left, SETTING(PROGRESS_3DDEPTH));
				
				SetTextColor(dc, SETTING(PROGRESS_TEXT_COLOR_UP));
				::ExtTextOut(dc, rc2.left, rc2.top + (rc2.Height() - WinUtil::getTextHeight(dc) - 1) / 2, ETO_CLIPPED, rc2, buf.data(), _tcslen(buf.data()), NULL);
				
				SelectObject(dc, oldFont);
				
				BitBlt(cd->nmcd.hdc, real_rc.left, real_rc.top, real_rc.Width(), real_rc.Height(), dc, 0, 0, SRCCOPY);
				
				DeleteObject(cdc.SelectBitmap(pOldBmp));
				return CDRF_SKIPDEFAULT;
			}
			
			// [!] Colors::getUserColor(ii->getUser(), cd->clrText, cd->clrTextBk); // [!] IRainman fix todo [1] https://www.box.net/shared/f7c509838c3a1125842b , https://crash-server.com/DumpGroup.aspx?ClientID=guest&DumpGroupID=59082
			// !SMT!-IP
			if (m_ctrlList.findColumn(cd->iSubItem) == UploadQueueItem::COLUMN_LOCATION)
			{
				const tstring l_text = ii->getText(UploadQueueItem::COLUMN_LOCATION);
				if (l_text.length() != 0)
				{
					m_ctrlList.GetSubItemRect((int)cd->nmcd.dwItemSpec, cd->iSubItem, LVIR_BOUNDS, rc);
					CRect rc2 = rc;
					m_ctrlList.SetItemFilled(cd, rc2, cd->clrText);
					LONG top = rc2.top + (rc2.Height() - 15) / 2;
					if ((top - rc2.top) < 2)
						top = rc2.top + 1;
						
					const POINT p = { rc2.left, top };
					if (ii->m_location.isKnown())
					{
						g_flagImage.DrawLocation(cd->nmcd.hdc, ii->m_location, p);
					}
					top = rc2.top + (rc2.Height() - 15 /*WinUtil::getTextHeight(cd->nmcd.hdc)*/ - 1) / 2;
					if (!l_text.empty())
					{
						::ExtTextOut(cd->nmcd.hdc, rc2.left + 30, top + 1, ETO_CLIPPED, rc2, l_text.c_str(), l_text.length(), NULL);
					}
					return CDRF_SKIPDEFAULT;
				}
			}
		} //[+]PPA
		// Fall through
		default:
			return CDRF_DODEFAULT;
	}
}
Exemple #26
0
///////////////////////////////////////////////////////////////////////////////
// Iterates over all the documents, calling save on each one.
// 
bool DocumentManager::SaveAll( tstring& error )
{
    bool savedAll = true;
    bool prompt = true;
    bool dirtyDocuments = true;

    // here, we loop until we couldn't save any more documents (or there was a failure to save a document),
    // because saving a document can cause other documents to need saving again
    while ( dirtyDocuments && savedAll )
    {
        dirtyDocuments = false;
        OS_DocumentSmartPtr::Iterator docItr = m_Documents.Begin();
        OS_DocumentSmartPtr::Iterator docEnd = m_Documents.End();
        for ( ; docItr != docEnd; ++docItr )
        {
            Document* document = *docItr;

            bool abort = false;
            bool save = true;
            if ( prompt )
            {
                switch ( QuerySave( document ) )
                {
                case SaveActions::SaveAll:
                    save = true;
                    prompt = false;
                    break;

                case SaveActions::Save:
                    save = true;
                    prompt = true;
                    break;

                case SaveActions::Skip:
                    save = false;
                    prompt = true;
                    break;

                case SaveActions::SkipAll:
                    save = false;
                case SaveActions::Abort:
                default:
                    abort = true;
                    break; 
                }
            }

            if ( abort )
            {
                break;
            }

            if ( save )
            {
                dirtyDocuments = true;

                tstring msg;
                if ( !SaveDocument( document, msg ) )
                {
                    savedAll = false;
                    if ( !error.empty() )
                    {
                        error += TXT( "\n" );
                    }
                    error += msg;
                }
            }
        }
    }

    return savedAll;
}
void CQuotesProviderBase::WriteContactRate(MCONTACT hContact, double dRate, const tstring& rsSymbol/* = ""*/)
{
	time_t nTime = ::time(NULL);

	if (false == rsSymbol.empty())
		db_set_ts(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_SYMBOL, rsSymbol.c_str());

	double dPrev = 0.0;
	bool bValidPrev = Quotes_DBReadDouble(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_CURR_VALUE, dPrev);
	if (true == bValidPrev)
		Quotes_DBWriteDouble(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_PREV_VALUE, dPrev);

	Quotes_DBWriteDouble(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_CURR_VALUE, dRate);
	db_set_dw(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_FETCH_TIME, nTime);

	tstring sSymbol = rsSymbol;

	tostringstream oNick;
	oNick.imbue(GetSystemLocale());
	if (false == m_sContactListFormat.empty()) {
		tstring s = format_rate(this, hContact, m_sContactListFormat);
		oNick << s;
	}
	else {
		if (true == sSymbol.empty())
			sSymbol = Quotes_DBGetStringT(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_SYMBOL);

		oNick << std::setfill(_T(' ')) << std::setw(10) << std::left << sSymbol << std::setw(6) << std::right << dRate;
	}
	CTendency tendency;

	if (true == tendency.Parse(this, m_sTendencyFormat, hContact))
		do_set_contact_extra_icon(hContact, tendency);

	db_set_ts(hContact, LIST_MODULE_NAME, CONTACT_LIST_NAME, oNick.str().c_str());

	tstring sStatusMsg = format_rate(this, hContact, m_sStatusMsgFormat);
	if (false == sStatusMsg.empty())
		db_set_ts(hContact, LIST_MODULE_NAME, STATUS_MSG_NAME, sStatusMsg.c_str());
	else
		db_unset(hContact, LIST_MODULE_NAME, STATUS_MSG_NAME);

	bool bUseContactSpecific = (db_get_b(hContact, QUOTES_PROTOCOL_NAME, DB_STR_CONTACT_SPEC_SETTINGS, 0) > 0);

	CAdvProviderSettings global_settings(this);

	WORD dwMode = (bUseContactSpecific)
		? db_get_w(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_LOG, static_cast<WORD>(lmDisabled))
		: global_settings.GetLogMode();
	if (dwMode&lmExternalFile) {
		bool bAdd = true;
		bool bOnlyIfChanged = (bUseContactSpecific)
			? (db_get_w(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_LOG_FILE_CONDITION, 1) > 0)
			: global_settings.GetLogOnlyChangedFlag();
		if (true == bOnlyIfChanged) {
			bAdd = ((false == bValidPrev) || (false == IsWithinAccuracy(dRate, dPrev)));
		}
		if (true == bAdd) {
			tstring sLogFileName = (bUseContactSpecific)
				? Quotes_DBGetStringT(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_LOG_FILE, global_settings.GetLogFileName().c_str())
				: global_settings.GetLogFileName();

			if (true == sSymbol.empty()) {
				sSymbol = Quotes_DBGetStringT(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_SYMBOL);
			}

			sLogFileName = GenerateLogFileName(sLogFileName, sSymbol);

			tstring sFormat = global_settings.GetLogFormat();
			if (bUseContactSpecific) {
				CQuotesProviderVisitorDbSettings visitor;
				Accept(visitor);
				sFormat = Quotes_DBGetStringT(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_FORMAT_LOG_FILE, visitor.m_pszDefLogFileFormat);
			}

			log_to_file(this, hContact, sLogFileName, sFormat);
		}
	}
	if (dwMode&lmInternalHistory) {
		bool bAdd = true;
		bool bOnlyIfChanged = (bUseContactSpecific)
			? (db_get_w(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_HISTORY_CONDITION, 1) > 0)
			: global_settings.GetHistoryOnlyChangedFlag();

		if (true == bOnlyIfChanged) {
			bAdd = ((false == bValidPrev) || (false == IsWithinAccuracy(dRate, dPrev)));
		}
		if (true == bAdd) {
			tstring sFormat = (bUseContactSpecific)
				? Quotes_DBGetStringT(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_FORMAT_HISTORY, global_settings.GetHistoryFormat().c_str())
				: global_settings.GetHistoryFormat();

			log_to_history(this, hContact, nTime, sFormat);
		}
	}

	if (dwMode&lmPopup) {
		bool bOnlyIfChanged = (bUseContactSpecific)
			? (1 == db_get_b(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_POPUP_CONDITION, 1) > 0)
			: global_settings.GetShowPopupIfValueChangedFlag();
		if ((false == bOnlyIfChanged)
			|| ((true == bOnlyIfChanged) && (true == bValidPrev) && (false == IsWithinAccuracy(dRate, dPrev)))) {
			tstring sFormat = (bUseContactSpecific)
				? Quotes_DBGetStringT(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_FORMAT_POPUP, global_settings.GetPopupFormat().c_str())
				: global_settings.GetPopupFormat();

			CPopupSettings ps = *(global_settings.GetPopupSettingsPtr());
			ps.InitForContact(hContact);
			show_popup(this, hContact, tendency, sFormat, ps);
		}
	}

	SetContactStatus(hContact, ID_STATUS_ONLINE);
}
Exemple #28
0
void ChatCtrl::AppendText(const Identity& i, const tstring& sMyNick, const tstring& sTime, tstring sMsg, CHARFORMAT2& cf, bool bUseEmo/* = true*/) {
	SetRedraw(FALSE);

	SCROLLINFO si = { 0 };
	POINT pt = { 0 };

	si.cbSize = sizeof(si);
	si.fMask = SIF_PAGE | SIF_RANGE | SIF_POS;
	GetScrollInfo(SB_VERT, &si);
	GetScrollPos(&pt);

	LONG lSelBegin = 0, lSelEnd = 0, lTextLimit = 0, lNewTextLen = 0;
	LONG lSelBeginSaved, lSelEndSaved;

	// Unify line endings
	tstring::size_type j = 0; 
	while((j = sMsg.find(_T("\r"), j)) != tstring::npos)
		sMsg.erase(j, 1);

	GetSel(lSelBeginSaved, lSelEndSaved);
	lSelEnd = lSelBegin = GetTextLengthEx(GTL_NUMCHARS);

	bool isMyMessage = i.getUser() == ClientManager::getInstance()->getMe();
	tstring sLine = sTime + sMsg;

	// Remove old chat if size exceeds
	lNewTextLen = sLine.size();
	lTextLimit = GetLimitText();

	if(lSelEnd + lNewTextLen > lTextLimit) {
		LONG lRemoveChars = 0;
		int multiplier = 1;

		if(lNewTextLen >= lTextLimit) {
			lRemoveChars = lSelEnd;
			magnets.clear();
		} else {
			while(lRemoveChars < lNewTextLen)
				lRemoveChars = LineIndex(LineFromChar(multiplier++ * lTextLimit / 10));
		}

		if(magnets.size()) {
			tstring buf;
			buf.resize(lRemoveChars);
			GetTextRange(0, lRemoveChars, &buf[0]);

			CHARFORMAT2 cfSel;
			cfSel.cbSize = sizeof(CHARFORMAT2);

			for(TStringMap::iterator i = magnets.begin(); i != magnets.end();) {
				tstring::size_type j = 0;
				while((j = buf.find(i->first, j)) != tstring::npos) {
					SetSel(j, j + i->first.size());
					GetSelectionCharFormat(cfSel);
					if(cfSel.dwEffects & CFE_LINK) {
						magnets.erase(i++);
						break;
					}
					j += i->first.size();
				} if(j == tstring::npos) {
					++i;
				}
			}
		}

		// Update selection ranges
		lSelEnd = lSelBegin -= lRemoveChars;
		lSelEndSaved -= lRemoveChars;
		lSelBeginSaved -= lRemoveChars;

		// ...and the scroll position
		pt.y -= PosFromChar(lRemoveChars).y;

		SetSel(0, lRemoveChars);
		ReplaceSel(_T(""));
	}


	// Add to the end
	SetSel(lSelBegin, lSelEnd);
	setText(sLine);

	CHARFORMAT2 enc;
	enc.bCharSet = RUSSIAN_CHARSET;
	enc.dwMask = CFM_CHARSET;

	SetSel(0, sLine.length());
	SetSelectionCharFormat(enc);

	// Format TimeStamp
	if(!sTime.empty()) {
		lSelEnd += sTime.size();
		SetSel(lSelBegin, lSelEnd - 1);
		SetSelectionCharFormat(WinUtil::m_TextStyleTimestamp);

		PARAFORMAT2 pf;
		memzero(&pf, sizeof(PARAFORMAT2));
		pf.dwMask = PFM_STARTINDENT; 
		pf.dxStartIndent = 0;
		SetParaFormat(pf);
	}

	// Authors nick
	tstring sAuthor = Text::toT(i.getNick());
	if(!sAuthor.empty()) {
		LONG iLen = (sMsg[0] == _T('*')) ? 1 : 0;
		LONG iAuthorLen = sAuthor.size() + 1;
		sMsg.erase(0, iAuthorLen + iLen);
   		
		lSelBegin = lSelEnd;
		lSelEnd += iAuthorLen + iLen;
		
		if(isMyMessage) {
			SetSel(lSelBegin, lSelBegin + iLen + 1);
			SetSelectionCharFormat(WinUtil::m_ChatTextMyOwn);
			SetSel(lSelBegin + iLen + 1, lSelBegin + iLen + iAuthorLen);
			SetSelectionCharFormat(WinUtil::m_TextStyleMyNick);
		} else {
			bool isFavorite = FavoriteManager::getInstance()->isFavoriteUser(i.getUser());

			if(BOOLSETTING(BOLD_AUTHOR_MESS) || isFavorite || i.isOp()) {
				SetSel(lSelBegin, lSelBegin + iLen + 1);
				SetSelectionCharFormat(cf);
				SetSel(lSelBegin + iLen + 1, lSelEnd);
				if(isFavorite){
					SetSelectionCharFormat(WinUtil::m_TextStyleFavUsers);
				} else if(i.isOp()) {
					SetSelectionCharFormat(WinUtil::m_TextStyleOPs);
				} else {
					SetSelectionCharFormat(WinUtil::m_TextStyleBold);
				}
			} else {
				SetSel(lSelBegin, lSelEnd);
				SetSelectionCharFormat(cf);
            }
		}
	} else {
		bool thirdPerson = false;
        switch(sMsg[0]) {
			case _T('*'):
				if(sMsg[1] != _T(' ')) break;
				thirdPerson = true;
            case _T('<'):
				tstring::size_type iAuthorLen = sMsg.find(thirdPerson ? _T(' ') : _T('>'), thirdPerson ? 2 : 1);
				if(iAuthorLen != tstring::npos) {
                    bool isOp = false, isFavorite = false;

                    if(client != NULL) {
						tstring nick(sMsg.c_str() + 1);
						nick.erase(iAuthorLen - 1);
						
						const OnlineUserPtr ou = client->findUser(Text::fromT(nick));
						if(ou != NULL) {
							isFavorite = FavoriteManager::getInstance()->isFavoriteUser(ou->getUser());
							isOp = ou->getIdentity().isOp();
						}
                    }
                    
					lSelBegin = lSelEnd;
					lSelEnd += iAuthorLen;
					sMsg.erase(0, iAuthorLen);

        			if(BOOLSETTING(BOLD_AUTHOR_MESS) || isFavorite || isOp) {
        				SetSel(lSelBegin, lSelBegin + 1);
        				SetSelectionCharFormat(cf);
						SetSel(lSelBegin + 1, lSelEnd);
						if(isFavorite){
							SetSelectionCharFormat(WinUtil::m_TextStyleFavUsers);
						} else if(isOp) {
							SetSelectionCharFormat(WinUtil::m_TextStyleOPs);
						} else {
							SetSelectionCharFormat(WinUtil::m_TextStyleBold);
						}
        			} else {
        				SetSel(lSelBegin, lSelEnd);
        				SetSelectionCharFormat(cf);
                    }
				}
        }
	}
				   			
	// Format the message part
	FormatChatLine(sMyNick, sMsg, cf, isMyMessage, sAuthor, lSelEnd, bUseEmo);

	SetSel(lSelBeginSaved, lSelEndSaved);
	if(	isMyMessage || ((si.nPage == 0 || (size_t)si.nPos >= (size_t)si.nMax - si.nPage - 5) &&
		(lSelBeginSaved == lSelEndSaved || !selectedUser.empty() || !selectedIP.empty() || !selectedURL.empty())))
	{
		PostMessage(EM_SCROLL, SB_BOTTOM, 0);
	} else {
		SetScrollPos(&pt);
	}

	// Force window to redraw
	SetRedraw(TRUE);
	InvalidateRect(NULL);
}
Exemple #29
0
 bool HasChildren() const {
   return !children.empty() || !text.empty();
 }
Exemple #30
0
bool CPicture::Load(tstring sFilePathName)
{
	bool bResult = false;
	bIsIcon = false;
	lpIcons = NULL;
	//CFile PictureFile;
	//CFileException e;
	FreePictureData(); // Important - Avoid Leaks...

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

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

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

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

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

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

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

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

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

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

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

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

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

			if (hFreeImageLib)
			{
				bool exportsValid = true;

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

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

				//const char* version = FreeImage_GetVersion();

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

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

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

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

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

									pBitmap->UnlockBits(&bitmapData);

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

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

				FreeLibrary(hFreeImageLib);
				hFreeImageLib = NULL;
			}
		}
	}