Misc.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  1. #include "stdafx.h"
  2. #include "CP_Main.h"
  3. #include "Misc.h"
  4. #include "OptionsSheet.h"
  5. #include "shared/TextConvert.h"
  6. #include "AlphaBlend.h"
  7. #include "Tlhelp32.h"
  8. #include <Wininet.h>
  9. #include "sqlite\utext.h"
  10. CString GetIPAddress()
  11. {
  12. WORD wVersionRequested;
  13. WSADATA wsaData;
  14. char name[255];
  15. CString IP;
  16. PHOSTENT hostinfo;
  17. wVersionRequested = MAKEWORD(2,0);
  18. if (WSAStartup(wVersionRequested, &wsaData)==0)
  19. {
  20. if(gethostname(name, sizeof(name))==0)
  21. {
  22. if((hostinfo=gethostbyname(name)) != NULL)
  23. {
  24. IP = inet_ntoa(*(struct in_addr*)* hostinfo->h_addr_list);
  25. }
  26. }
  27. WSACleanup();
  28. }
  29. IP.MakeUpper();
  30. return IP;
  31. }
  32. CString GetComputerName()
  33. {
  34. TCHAR ComputerName[MAX_COMPUTERNAME_LENGTH+1] = _T("");
  35. DWORD Size=MAX_COMPUTERNAME_LENGTH+1;
  36. GetComputerName(ComputerName, &Size);
  37. CString cs(ComputerName);
  38. cs.MakeUpper();
  39. return cs;
  40. }
  41. void AppendToFile(const TCHAR* fn, const TCHAR* msg)
  42. {
  43. #ifdef _UNICODE
  44. FILE *file = _wfopen(fn, _T("a"));
  45. #else
  46. FILE *file = fopen(fn, _T("a"));
  47. #endif
  48. ASSERT( file );
  49. if(file != NULL)
  50. {
  51. #ifdef _UNICODE
  52. fwprintf(file, _T("%s"), msg);
  53. #else
  54. fprintf(file, _T("%s"),msg);
  55. #endif
  56. fclose(file);
  57. }
  58. }
  59. void log(const TCHAR* msg, bool bFromSendRecieve, CString csFile, long lLine)
  60. {
  61. ASSERT(AfxIsValidString(msg));
  62. SYSTEMTIME st;
  63. GetLocalTime(&st);
  64. CString csText;
  65. csText.Format(_T("[%d/%d/%d %02d:%02d:%02d.%03d - "), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
  66. CString csFileLine;
  67. csFile = GetFileName(csFile);
  68. csFileLine.Format(_T("%s %d] "), csFile, lLine);
  69. csText += csFileLine;
  70. csText += msg;
  71. csText += "\n";
  72. #ifndef _DEBUG
  73. if(CGetSetOptions::m_bOutputDebugString)
  74. #endif
  75. {
  76. OutputDebugString(csText);
  77. }
  78. #ifndef _DEBUG
  79. if(!bFromSendRecieve)
  80. {
  81. if(!g_Opt.m_bEnableDebugLogging)
  82. return;
  83. }
  84. #endif
  85. CString csExeFile = CGetSetOptions::GetPath(PATH_LOG_FILE);
  86. csExeFile += "Ditto.log";
  87. AppendToFile(csExeFile, csText);
  88. }
  89. void logsendrecieveinfo(CString cs, CString csFile, long lLine)
  90. {
  91. if(g_Opt.m_bLogSendReceiveErrors)
  92. log(cs, true, csFile, lLine);
  93. }
  94. CString GetErrorString( int err )
  95. {
  96. CString str;
  97. LPVOID lpMsgBuf;
  98. ::FormatMessage(
  99. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  100. NULL,
  101. err,
  102. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  103. (LPTSTR) &lpMsgBuf,
  104. 0,
  105. NULL
  106. );
  107. str = (LPCTSTR) lpMsgBuf;
  108. // Display the string.
  109. // ::MessageBox( NULL, lpMsgBuf, "GetLastError", MB_OK|MB_ICONINFORMATION );
  110. ::LocalFree( lpMsgBuf );
  111. return str;
  112. }
  113. int g_funnyGetTickCountAdjustment = -1;
  114. double IdleSeconds()
  115. {
  116. LASTINPUTINFO info;
  117. info.cbSize = sizeof(info);
  118. GetLastInputInfo(&info);
  119. DWORD currentTick = GetTickCount();
  120. if(g_funnyGetTickCountAdjustment == -1)
  121. {
  122. if(currentTick < info.dwTime)
  123. {
  124. g_funnyGetTickCountAdjustment = 1;
  125. }
  126. else
  127. {
  128. g_funnyGetTickCountAdjustment = 0;
  129. }
  130. }
  131. if(g_funnyGetTickCountAdjustment == 1 || g_funnyGetTickCountAdjustment == 2)
  132. {
  133. //Output message the first time
  134. if(g_funnyGetTickCountAdjustment == 1)
  135. {
  136. Log(StrF(_T("Adjusting time of get tickcount by: %d, on startup we found GetTickCount to be less than last input"), CGetSetOptions::GetFunnyTickCountAdjustment()));
  137. g_funnyGetTickCountAdjustment = 2;
  138. }
  139. currentTick += CGetSetOptions::GetFunnyTickCountAdjustment();
  140. }
  141. double idleSeconds = (currentTick - info.dwTime)/1000.0;
  142. return idleSeconds;
  143. }
  144. CString StrF(const TCHAR * pszFormat, ...)
  145. {
  146. ASSERT( AfxIsValidString( pszFormat ) );
  147. CString str;
  148. va_list argList;
  149. va_start( argList, pszFormat );
  150. str.FormatV( pszFormat, argList );
  151. va_end( argList );
  152. return str;
  153. }
  154. BYTE GetEscapeChar( BYTE ch )
  155. {
  156. switch(ch)
  157. {
  158. case '\'': return '\''; // Single quotation mark (') = 39 or 0x27
  159. case '\"': return '\"'; // Double quotation mark (") = 34 or 0x22
  160. case '?': return '\?'; // Question mark (?) = 63 or 0x3f
  161. case '\\': return '\\'; // Backslash (\) = 92 or 0x5c
  162. case 'a': return '\a'; // Alert (BEL) = 7
  163. case 'b': return '\b'; // Backspace (BS) = 8
  164. case 'f': return '\f'; // Formfeed (FF) = 12 or 0x0c
  165. case 'n': return '\n'; // Newline (NL or LF) = 10 or 0x0a
  166. case 'r': return '\r'; // Carriage Return (CR) = 13 or 0x0d
  167. case 't': return '\t'; // Horizontal tab (HT) = 9
  168. case 'v': return '\v'; // Vertical tab (VT) = 11 or 0x0b
  169. case '0': return '\0'; // Null character (NUL) = 0
  170. }
  171. return 0; // invalid
  172. }
  173. CString RemoveEscapes( const TCHAR* str )
  174. {
  175. ASSERT( str );
  176. CString ret;
  177. TCHAR* pSrc = (TCHAR*) str;
  178. TCHAR* pDest = ret.GetBuffer((int)STRLEN(pSrc));
  179. TCHAR* pStart = pDest;
  180. while( *pSrc != '\0' )
  181. {
  182. if( *pSrc == '\\' )
  183. {
  184. pSrc++;
  185. *pDest = GetEscapeChar((BYTE)pSrc );
  186. }
  187. else
  188. *pDest = *pSrc;
  189. pSrc++;
  190. pDest++;
  191. }
  192. ret.ReleaseBuffer((int)(pDest - pStart));
  193. return ret;
  194. }
  195. CString GetWndText( HWND hWnd )
  196. {
  197. CString text;
  198. if( !IsWindow(hWnd) )
  199. return "! NOT A VALID WINDOW !";
  200. CWnd* pWnd = CWnd::FromHandle(hWnd);
  201. pWnd->GetWindowText(text);
  202. return text;
  203. }
  204. bool IsAppWnd( HWND hWnd )
  205. {
  206. DWORD dwMyPID = ::GetCurrentProcessId();
  207. DWORD dwTestPID;
  208. ::GetWindowThreadProcessId( hWnd, &dwTestPID );
  209. return dwMyPID == dwTestPID;
  210. }
  211. /*----------------------------------------------------------------------------*\
  212. Global Memory Helper Functions
  213. \*----------------------------------------------------------------------------*/
  214. // make sure the given HGLOBAL is valid.
  215. BOOL IsValid(HGLOBAL hGlobal)
  216. {
  217. void* pvData = ::GlobalLock(hGlobal);
  218. ::GlobalUnlock(hGlobal);
  219. return (pvData != NULL);
  220. }
  221. // asserts if hDest isn't big enough
  222. void CopyToGlobalHP(HGLOBAL hDest, LPVOID pBuf, SIZE_T ulBufLen)
  223. {
  224. ASSERT(hDest && pBuf && ulBufLen);
  225. LPVOID pvData = GlobalLock(hDest);
  226. ASSERT(pvData);
  227. SIZE_T size = GlobalSize(hDest);
  228. ASSERT(size >= ulBufLen); // assert if hDest isn't big enough
  229. memcpy(pvData, pBuf, ulBufLen);
  230. GlobalUnlock(hDest);
  231. }
  232. void CopyToGlobalHH(HGLOBAL hDest, HGLOBAL hSource, SIZE_T ulBufLen)
  233. {
  234. ASSERT(hDest && hSource && ulBufLen);
  235. LPVOID pvData = GlobalLock(hSource);
  236. ASSERT(pvData );
  237. SIZE_T size = GlobalSize(hSource);
  238. ASSERT(size >= ulBufLen); // assert if hSource isn't big enough
  239. CopyToGlobalHP(hDest, pvData, ulBufLen);
  240. GlobalUnlock(hSource);
  241. }
  242. HGLOBAL NewGlobalP(LPVOID pBuf, SIZE_T nLen)
  243. {
  244. ASSERT(pBuf && nLen);
  245. HGLOBAL hDest = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE, nLen);
  246. ASSERT(hDest );
  247. CopyToGlobalHP(hDest, pBuf, nLen);
  248. return hDest;
  249. }
  250. HGLOBAL NewGlobal(SIZE_T nLen)
  251. {
  252. ASSERT(nLen);
  253. HGLOBAL hDest = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE, nLen);
  254. return hDest;
  255. }
  256. HGLOBAL NewGlobalH(HGLOBAL hSource, SIZE_T nLen)
  257. {
  258. ASSERT(hSource && nLen);
  259. LPVOID pvData = GlobalLock(hSource);
  260. HGLOBAL hDest = NewGlobalP(pvData, nLen);
  261. GlobalUnlock(hSource);
  262. return hDest;
  263. }
  264. int CompareGlobalHP(HGLOBAL hLeft, LPVOID pBuf, SIZE_T ulBufLen)
  265. {
  266. ASSERT(hLeft && pBuf && ulBufLen);
  267. LPVOID pvData = GlobalLock(hLeft);
  268. ASSERT(pvData);
  269. ASSERT(ulBufLen <= GlobalSize(hLeft));
  270. int result = memcmp(pvData, pBuf, ulBufLen);
  271. GlobalUnlock(hLeft);
  272. return result;
  273. }
  274. int CompareGlobalHH( HGLOBAL hLeft, HGLOBAL hRight, SIZE_T ulBufLen)
  275. {
  276. ASSERT(hLeft && hRight && ulBufLen);
  277. ASSERT(ulBufLen <= GlobalSize(hRight));
  278. LPVOID pvData = GlobalLock(hRight);
  279. ASSERT(pvData);
  280. int result = CompareGlobalHP(hLeft, pvData, ulBufLen);
  281. GlobalUnlock(hLeft);
  282. return result;
  283. }
  284. //Do not change these these are stored in the database
  285. CLIPFORMAT GetFormatID(LPCTSTR cbName)
  286. {
  287. if(STRCMP(cbName, _T("CF_TEXT")) == 0)
  288. return CF_TEXT;
  289. else if(STRCMP(cbName, _T("CF_METAFILEPICT")) == 0)
  290. return CF_METAFILEPICT;
  291. else if(STRCMP(cbName, _T("CF_SYLK")) == 0)
  292. return CF_SYLK;
  293. else if(STRCMP(cbName, _T("CF_DIF")) == 0)
  294. return CF_DIF;
  295. else if(STRCMP(cbName, _T("CF_TIFF")) == 0)
  296. return CF_TIFF;
  297. else if(STRCMP(cbName, _T("CF_OEMTEXT")) == 0)
  298. return CF_OEMTEXT;
  299. else if(STRCMP(cbName, _T("CF_DIB")) == 0)
  300. return CF_DIB;
  301. else if(STRCMP(cbName, _T("CF_PALETTE")) == 0)
  302. return CF_PALETTE;
  303. else if(STRCMP(cbName, _T("CF_PENDATA")) == 0)
  304. return CF_PENDATA;
  305. else if(STRCMP(cbName, _T("CF_RIFF")) == 0)
  306. return CF_RIFF;
  307. else if(STRCMP(cbName, _T("CF_WAVE")) == 0)
  308. return CF_WAVE;
  309. else if(STRCMP(cbName, _T("CF_UNICODETEXT")) == 0)
  310. return CF_UNICODETEXT;
  311. else if(STRCMP(cbName, _T("CF_ENHMETAFILE")) == 0)
  312. return CF_ENHMETAFILE;
  313. else if(STRCMP(cbName, _T("CF_HDROP")) == 0)
  314. return CF_HDROP;
  315. else if(STRCMP(cbName, _T("CF_LOCALE")) == 0)
  316. return CF_LOCALE;
  317. else if(STRCMP(cbName, _T("CF_OWNERDISPLAY")) == 0)
  318. return CF_OWNERDISPLAY;
  319. else if(STRCMP(cbName, _T("CF_DSPTEXT")) == 0)
  320. return CF_DSPTEXT;
  321. else if(STRCMP(cbName, _T("CF_DSPBITMAP")) == 0)
  322. return CF_DSPBITMAP;
  323. else if(STRCMP(cbName, _T("CF_DSPMETAFILEPICT")) == 0)
  324. return CF_DSPMETAFILEPICT;
  325. else if(STRCMP(cbName, _T("CF_DSPENHMETAFILE")) == 0)
  326. return CF_DSPENHMETAFILE;
  327. return ::RegisterClipboardFormat(cbName);
  328. }
  329. //Do not change these these are stored in the database
  330. CString GetFormatName(CLIPFORMAT cbType)
  331. {
  332. switch(cbType)
  333. {
  334. case CF_TEXT:
  335. return _T("CF_TEXT");
  336. case CF_BITMAP:
  337. return _T("CF_BITMAP");
  338. case CF_METAFILEPICT:
  339. return _T("CF_METAFILEPICT");
  340. case CF_SYLK:
  341. return _T("CF_SYLK");
  342. case CF_DIF:
  343. return _T("CF_DIF");
  344. case CF_TIFF:
  345. return _T("CF_TIFF");
  346. case CF_OEMTEXT:
  347. return _T("CF_OEMTEXT");
  348. case CF_DIB:
  349. return _T("CF_DIB");
  350. case CF_PALETTE:
  351. return _T("CF_PALETTE");
  352. case CF_PENDATA:
  353. return _T("CF_PENDATA");
  354. case CF_RIFF:
  355. return _T("CF_RIFF");
  356. case CF_WAVE:
  357. return _T("CF_WAVE");
  358. case CF_UNICODETEXT:
  359. return _T("CF_UNICODETEXT");
  360. case CF_ENHMETAFILE:
  361. return _T("CF_ENHMETAFILE");
  362. case CF_HDROP:
  363. return _T("CF_HDROP");
  364. case CF_LOCALE:
  365. return _T("CF_LOCALE");
  366. case CF_OWNERDISPLAY:
  367. return _T("CF_OWNERDISPLAY");
  368. case CF_DSPTEXT:
  369. return _T("CF_DSPTEXT");
  370. case CF_DSPBITMAP:
  371. return _T("CF_DSPBITMAP");
  372. case CF_DSPMETAFILEPICT:
  373. return _T("CF_DSPMETAFILEPICT");
  374. case CF_DSPENHMETAFILE:
  375. return _T("CF_DSPENHMETAFILE");
  376. default:
  377. //Not a default type get the name from the clipboard
  378. if (cbType != 0)
  379. {
  380. TCHAR szFormat[256];
  381. GetClipboardFormatName(cbType, szFormat, 256);
  382. return szFormat;
  383. }
  384. break;
  385. }
  386. return "ERROR";
  387. }
  388. CString GetFilePath(CString csFileName)
  389. {
  390. long lSlash = csFileName.ReverseFind('\\');
  391. if(lSlash > -1)
  392. {
  393. csFileName = csFileName.Left(lSlash + 1);
  394. }
  395. return csFileName;
  396. }
  397. CString GetFileName(CString csFileName)
  398. {
  399. long lSlash = csFileName.ReverseFind('\\');
  400. if(lSlash > -1)
  401. {
  402. csFileName = csFileName.Right(csFileName.GetLength() - lSlash - 1);
  403. }
  404. return csFileName;
  405. }
  406. /****************************************************************************************************
  407. BOOL CALLBACK MyMonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
  408. ***************************************************************************************************/
  409. typedef struct
  410. {
  411. long lFlags; // Flags
  412. LPRECT pVirtualRect; // Ptr to rect that receives the results, or the src of the monitor search method
  413. int iMonitor; // Ndx to the mointor to look at, -1 for all, -or- result of the monitor search method
  414. int nMonitorCount; // Total number of monitors found, -1 for monitor search method
  415. } MONITOR_ENUM_PARAM;
  416. #define MONITOR_SEARCH_METOHD 0x00000001
  417. BOOL CALLBACK MyMonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
  418. {
  419. // Typecast param
  420. MONITOR_ENUM_PARAM* pParam = (MONITOR_ENUM_PARAM*)dwData;
  421. if(pParam)
  422. {
  423. // If a dest rect was passed
  424. if(pParam->pVirtualRect)
  425. {
  426. // If MONITOR_SEARCH_METOHD then we are being asked for the index of the monitor
  427. // that the rect falls inside of
  428. if(pParam->lFlags & MONITOR_SEARCH_METOHD)
  429. {
  430. if( (pParam->pVirtualRect->right < lprcMonitor->left) ||
  431. (pParam->pVirtualRect->left > lprcMonitor->right) ||
  432. (pParam->pVirtualRect->bottom < lprcMonitor->top) ||
  433. (pParam->pVirtualRect->top > lprcMonitor->bottom))
  434. {
  435. // Nothing
  436. }
  437. else
  438. {
  439. // This is the one
  440. pParam->iMonitor = pParam->nMonitorCount;
  441. // Stop the enumeration
  442. return FALSE;
  443. }
  444. }
  445. else
  446. {
  447. if(pParam->iMonitor == pParam->nMonitorCount)
  448. {
  449. *pParam->pVirtualRect = *lprcMonitor;
  450. }
  451. else
  452. if(pParam->iMonitor == -1)
  453. {
  454. pParam->pVirtualRect->left = min(pParam->pVirtualRect->left, lprcMonitor->left);
  455. pParam->pVirtualRect->top = min(pParam->pVirtualRect->top, lprcMonitor->top);
  456. pParam->pVirtualRect->right = max(pParam->pVirtualRect->right, lprcMonitor->right);
  457. pParam->pVirtualRect->bottom = max(pParam->pVirtualRect->bottom, lprcMonitor->bottom);
  458. }
  459. }
  460. }
  461. // Up the count if necessary
  462. pParam->nMonitorCount++;
  463. }
  464. return TRUE;
  465. }
  466. int GetScreenWidth(void)
  467. {
  468. OSVERSIONINFO OS_Version_Info;
  469. DWORD dwPlatform = 0;
  470. if(GetVersionEx(&OS_Version_Info) != 0)
  471. {
  472. dwPlatform = OS_Version_Info.dwPlatformId;
  473. }
  474. if(dwPlatform == VER_PLATFORM_WIN32_NT)
  475. {
  476. int width, height;
  477. width = GetSystemMetrics(SM_CXSCREEN);
  478. height = GetSystemMetrics(SM_CYSCREEN);
  479. switch(width)
  480. {
  481. default:
  482. case 640:
  483. case 800:
  484. case 1024:
  485. return(width);
  486. case 1280:
  487. if(height == 480)
  488. {
  489. return(width / 2);
  490. }
  491. return(width);
  492. case 1600:
  493. if(height == 600)
  494. {
  495. return(width / 2);
  496. }
  497. return(width);
  498. case 2048:
  499. if(height == 768)
  500. {
  501. return(width / 2);
  502. }
  503. return(width);
  504. }
  505. }
  506. else
  507. {
  508. return(GetSystemMetrics(SM_CXVIRTUALSCREEN));
  509. }
  510. }
  511. int GetScreenHeight(void)
  512. {
  513. OSVERSIONINFO OS_Version_Info;
  514. DWORD dwPlatform = 0;
  515. if(GetVersionEx(&OS_Version_Info) != 0)
  516. {
  517. dwPlatform = OS_Version_Info.dwPlatformId;
  518. }
  519. if(dwPlatform == VER_PLATFORM_WIN32_NT)
  520. {
  521. int width, height;
  522. width = GetSystemMetrics(SM_CXSCREEN);
  523. height = GetSystemMetrics(SM_CYSCREEN);
  524. switch(height)
  525. {
  526. default:
  527. case 480:
  528. case 600:
  529. case 768:
  530. return(height);
  531. case 960:
  532. if(width == 640)
  533. {
  534. return(height / 2);
  535. }
  536. return(height);
  537. case 1200:
  538. if(width == 800)
  539. {
  540. return(height / 2);
  541. }
  542. return(height);
  543. case 1536:
  544. if(width == 1024)
  545. {
  546. return(height / 2);
  547. }
  548. return(height);
  549. }
  550. }
  551. else
  552. {
  553. return(GetSystemMetrics(SM_CYVIRTUALSCREEN));
  554. }
  555. }
  556. int GetMonitorFromRect(LPRECT lpMonitorRect)
  557. {
  558. // Build up the param
  559. MONITOR_ENUM_PARAM EnumParam;
  560. ZeroMemory(&EnumParam, sizeof(EnumParam));
  561. EnumParam.lFlags = MONITOR_SEARCH_METOHD;
  562. EnumParam.pVirtualRect = lpMonitorRect;
  563. EnumParam.iMonitor = -1;
  564. // Enum Displays
  565. EnumDisplayMonitors(NULL, NULL, MyMonitorEnumProc, (long)&EnumParam);
  566. // Return the result
  567. return EnumParam.iMonitor;
  568. }
  569. void GetMonitorRect(int iMonitor, LPRECT lpDestRect)
  570. {
  571. // Build up the param
  572. MONITOR_ENUM_PARAM EnumParam;
  573. ZeroMemory(&EnumParam, sizeof(EnumParam));
  574. EnumParam.iMonitor = iMonitor;
  575. EnumParam.pVirtualRect = lpDestRect;
  576. // Zero out dest rect
  577. lpDestRect->bottom = lpDestRect->left = lpDestRect->right = lpDestRect->top = 0;
  578. // Enum Displays
  579. EnumDisplayMonitors(NULL, NULL, MyMonitorEnumProc, (long)&EnumParam);
  580. // If not successful, default to the screen dimentions
  581. if(lpDestRect->right == 0 || lpDestRect->bottom == 0)
  582. {
  583. lpDestRect->right = GetScreenWidth();
  584. lpDestRect->bottom = GetScreenHeight();
  585. }
  586. //adjust the rect for the taskbar
  587. APPBARDATA appBarData;
  588. appBarData.cbSize=sizeof(appBarData);
  589. if (SHAppBarMessage(ABM_GETTASKBARPOS, &appBarData))
  590. {
  591. switch(appBarData.uEdge)
  592. {
  593. case ABE_LEFT:
  594. lpDestRect->left += appBarData.rc.right - appBarData.rc.left;
  595. break;
  596. case ABE_RIGHT:
  597. lpDestRect->right -= appBarData.rc.right - appBarData.rc.left;
  598. break;
  599. case ABE_TOP:
  600. lpDestRect->top += appBarData.rc.bottom - appBarData.rc.top;
  601. break;
  602. case ABE_BOTTOM:
  603. lpDestRect->bottom -= appBarData.rc.bottom - appBarData.rc.top;
  604. break;
  605. }
  606. return;
  607. }
  608. }
  609. /*------------------------------------------------------------------*\
  610. ID based Globals
  611. \*------------------------------------------------------------------*/
  612. long NewGroupID(int parentID, CString text)
  613. {
  614. long lID=0;
  615. CTime time;
  616. time = CTime::GetCurrentTime();
  617. try
  618. {
  619. //sqlite doesn't like single quotes ' replace them with double ''
  620. if(text.IsEmpty())
  621. text = time.Format("NewGroup %y/%m/%d %H:%M:%S");
  622. text.Replace(_T("'"), _T("''"));
  623. CString cs;
  624. cs.Format(_T("insert into Main (lDate, mText, lDontAutoDelete, bIsGroup, lParentID, stickyClipOrder, stickyClipGroupOrder) values(%d, '%s', %d, 1, %d, -(2147483647), -(2147483647));"),
  625. (int)time.GetTime(),
  626. text,
  627. (int)time.GetTime(),
  628. parentID);
  629. theApp.m_db.execDML(cs);
  630. lID = (long)theApp.m_db.lastRowId();
  631. }
  632. CATCH_SQLITE_EXCEPTION_AND_RETURN(0)
  633. return lID;
  634. }
  635. BOOL DeleteAllIDs()
  636. {
  637. try
  638. {
  639. theApp.m_db.execDML(_T("DELETE FROM Data;"));
  640. theApp.m_db.execDML(_T("DELETE FROM Main;"));
  641. }
  642. CATCH_SQLITE_EXCEPTION
  643. return TRUE;
  644. }
  645. BOOL DeleteFormats(int parentID, ARRAY& formatIDs)
  646. {
  647. if(formatIDs.GetSize() <= 0)
  648. return TRUE;
  649. try
  650. {
  651. //Delete the requested data formats
  652. INT_PTR count = formatIDs.GetSize();
  653. for(int i = 0; i < count; i++)
  654. {
  655. int count = theApp.m_db.execDMLEx(_T("DELETE FROM Data WHERE lID = %d;"), formatIDs[i]);
  656. int k = 0;
  657. }
  658. CClip clip;
  659. if(clip.LoadFormats(parentID))
  660. {
  661. DWORD CRC = clip.GenerateCRC();
  662. //Update the main table with new size
  663. theApp.m_db.execDMLEx(_T("UPDATE Main SET CRC = %d WHERE lID = %d"), CRC, parentID);
  664. }
  665. }
  666. CATCH_SQLITE_EXCEPTION
  667. return TRUE;
  668. }
  669. CRect CenterRect(CRect startingRect)
  670. {
  671. CRect crMonitor;
  672. int nMonitor = GetMonitorFromRect(&startingRect);
  673. if(nMonitor < 0)
  674. {
  675. GetMonitorRect(0, crMonitor);
  676. }
  677. else
  678. {
  679. GetMonitorRect(nMonitor, crMonitor);
  680. }
  681. return CenterRectFromRect(startingRect, crMonitor);
  682. }
  683. CRect CenterRectFromRect(CRect startingRect, CRect outerRect)
  684. {
  685. CPoint center = outerRect.CenterPoint();
  686. CRect centerRect;
  687. centerRect.left = center.x - (startingRect.Width() / 2);
  688. centerRect.top = center.y - (startingRect.Height() / 2);
  689. centerRect.right = centerRect.left + startingRect.Width();
  690. centerRect.bottom = centerRect.top + startingRect.Height();
  691. return centerRect;
  692. }
  693. BOOL EnsureWindowVisible(CRect *pcrRect)
  694. {
  695. int nMonitor = GetMonitorFromRect(pcrRect);
  696. if(nMonitor < 0)
  697. {
  698. GetMonitorRect(0, pcrRect);
  699. pcrRect->right = pcrRect->left + 300;
  700. pcrRect->bottom = pcrRect->top + 300;
  701. return TRUE;
  702. }
  703. BOOL ret = FALSE;
  704. CRect crMonitor;
  705. GetMonitorRect(nMonitor, crMonitor);
  706. bool movedLeft = false;
  707. //Validate the left
  708. long lDiff = pcrRect->left - crMonitor.left;
  709. if(lDiff < 0)
  710. {
  711. pcrRect->left += abs(lDiff);
  712. pcrRect->right += abs(lDiff);
  713. ret = TRUE;
  714. movedLeft = true;
  715. }
  716. //Right side
  717. lDiff = pcrRect->right - crMonitor.right;
  718. if(lDiff > 0)
  719. {
  720. if(movedLeft == false)
  721. {
  722. pcrRect->left -= abs(lDiff);
  723. }
  724. pcrRect->right -= abs(lDiff);
  725. ret = TRUE;
  726. }
  727. bool movedTop = false;
  728. //Top
  729. lDiff = pcrRect->top - crMonitor.top;
  730. if(lDiff < 0)
  731. {
  732. pcrRect->top += abs(lDiff);
  733. pcrRect->bottom += abs(lDiff);
  734. ret = TRUE;
  735. movedTop = true;
  736. }
  737. //Bottom
  738. lDiff = pcrRect->bottom - crMonitor.bottom;
  739. if(lDiff > 0)
  740. {
  741. if(movedTop == false)
  742. {
  743. pcrRect->top -= abs(lDiff);
  744. }
  745. pcrRect->bottom -= abs(lDiff);
  746. ret = TRUE;
  747. }
  748. return ret;
  749. }
  750. __int64 GetLastWriteTime(const CString &csFile)
  751. {
  752. __int64 nLastWrite = 0;
  753. CFileFind finder;
  754. BOOL bResult = finder.FindFile(csFile);
  755. if (bResult)
  756. {
  757. finder.FindNextFile();
  758. FILETIME ft;
  759. finder.GetLastWriteTime(&ft);
  760. memcpy(&nLastWrite, &ft, sizeof(ft));
  761. }
  762. return nLastWrite;
  763. }
  764. CString GetProcessName(HWND hWnd, DWORD processId)
  765. {
  766. DWORD startTick = GetTickCount();
  767. CString strProcessName;
  768. DWORD Id = processId;
  769. if (Id == 0)
  770. {
  771. GetWindowThreadProcessId(hWnd, &Id);
  772. }
  773. PROCESSENTRY32 processEntry = { 0 };
  774. HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  775. processEntry.dwSize = sizeof(PROCESSENTRY32);
  776. if (Process32First(hSnapShot, &processEntry))
  777. {
  778. do
  779. {
  780. if (processEntry.th32ProcessID == Id)
  781. {
  782. strProcessName = processEntry.szExeFile;
  783. break;
  784. }
  785. } while(Process32Next(hSnapShot, &processEntry));
  786. }
  787. CloseHandle(hSnapShot);
  788. DWORD endTick = GetTickCount();
  789. DWORD diff = endTick - startTick;
  790. if(diff > 5)
  791. {
  792. Log(StrF(_T("GetProcessName Time (ms): %d"), endTick-startTick));
  793. }
  794. return strProcessName;
  795. }
  796. BOOL IsVista()
  797. {
  798. OSVERSIONINFO osver;
  799. osver.dwOSVersionInfoSize = sizeof( OSVERSIONINFO );
  800. if (::GetVersionEx( &osver ) &&
  801. osver.dwPlatformId == VER_PLATFORM_WIN32_NT &&
  802. (osver.dwMajorVersion >= 6 ) )
  803. {
  804. return TRUE;
  805. }
  806. return FALSE;
  807. }
  808. bool IsRunningLimited()
  809. {
  810. LPCTSTR pszSubKey = _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System");
  811. LPCTSTR pszValue = _T("EnableLUA");
  812. DWORD dwType = 0;
  813. DWORD dwValue = 0;
  814. DWORD dwValueSize = sizeof(DWORD);
  815. if(ERROR_SUCCESS != SHGetValue(HKEY_LOCAL_MACHINE, pszSubKey, pszValue, &dwType, &dwValue, &dwValueSize))
  816. {
  817. //failed to read the reg key, either it's not there or we don't have access to the registry
  818. //If we are vista then assume we don't have access and we are running as a limited app
  819. //otherwise we are xp and the reg key probably doesn't exist and we are not a limited running app
  820. if(IsVista())
  821. {
  822. OutputDebugString(_T("Ditto - Failed to read registry entry finding UAC, Running as limited application"));
  823. return true;
  824. }
  825. }
  826. if(dwValue == 1)
  827. {
  828. OutputDebugString(_T("Ditto - UAC ENABLED, Running as limited application"));
  829. return true;
  830. }
  831. OutputDebugString(_T("Ditto - Running as standard application"));
  832. return false;
  833. }
  834. void DeleteDittoTempFiles(BOOL checkFileLastAccess)
  835. {
  836. CString csDir = CGetSetOptions::GetPath(PATH_REMOTE_FILES);
  837. if (FileExists(csDir))
  838. {
  839. DeleteFolderFiles(csDir, checkFileLastAccess);
  840. }
  841. csDir = CGetSetOptions::GetPath(PATH_DRAG_FILES);
  842. if (FileExists(csDir))
  843. {
  844. DeleteFolderFiles(csDir, checkFileLastAccess);
  845. }
  846. csDir = CGetSetOptions::GetPath(PATH_CLIP_DIFF);
  847. if (FileExists(csDir))
  848. {
  849. DeleteFolderFiles(csDir, checkFileLastAccess);
  850. }
  851. }
  852. void DeleteFolderFiles(CString csDir, BOOL checkFileLastAccess)
  853. {
  854. if (csDir.Find(_T("\\ReceivedFiles\\")) == -1 && csDir.Find(_T("\\DragFiles\\")) == -1 && csDir.Find(_T("ClipCompare")) == -1)
  855. return;
  856. Log(StrF(_T("Deleting files in Folder %s Check Last Access %d"), csDir, checkFileLastAccess));
  857. FIX_CSTRING_PATH(csDir);
  858. CTime ctOld = CTime::GetCurrentTime();
  859. CTime ctFile;
  860. ctOld -= CTimeSpan(0, 0, 0, 1);
  861. CFileFind Find;
  862. CString csFindString;
  863. csFindString.Format(_T("%s*.*"), csDir);
  864. BOOL bFound = Find.FindFile(csFindString);
  865. while(bFound)
  866. {
  867. bFound = Find.FindNextFile();
  868. if(Find.IsDots())
  869. continue;
  870. if(Find.IsDirectory())
  871. {
  872. CString csDir(Find.GetFilePath());
  873. DeleteFolderFiles(csDir, checkFileLastAccess);
  874. RemoveDirectory(csDir);
  875. }
  876. if(checkFileLastAccess &&
  877. Find.GetLastAccessTime(ctFile))
  878. {
  879. //Delete the remote copied file if it hasn't been used for the last day
  880. if(ctFile < ctOld)
  881. {
  882. Log(StrF(_T("Deleting temp file %s"), Find.GetFilePath()));
  883. DeleteFile(Find.GetFilePath());
  884. }
  885. }
  886. else
  887. {
  888. Log(StrF(_T("Deleting temp file %s"), Find.GetFilePath()));
  889. DeleteFile(Find.GetFilePath());
  890. }
  891. }
  892. }
  893. __int64 FileSize(const TCHAR *fileName)
  894. {
  895. __stat64 buf;
  896. if (_wstat64(fileName, &buf) != 0)
  897. return -1; // error, could use errno to find out more
  898. return buf.st_size;
  899. }
  900. int FindNoCaseAndInsert(CString& mainStr, CString& findStr, CString preInsert, CString postInsert, int linesPerRow)
  901. {
  902. int replaceCount = 0;
  903. //Prevent infinite loop when user tries to replace nothing.
  904. if (findStr != "")
  905. {
  906. int oldLen = findStr.GetLength();
  907. int foundPos = 0;
  908. int startFindPos = 0;
  909. int newPos = 0;
  910. int insertedLength = 0;
  911. int firstFindPos = 0;
  912. //use icu::UnicodeString because it handles upper/lowercase characters for all languages, CSTring only hanldes ascii characters
  913. icu::UnicodeString mainLow(mainStr);
  914. mainLow.toLower();
  915. icu::UnicodeString findLow(findStr);
  916. findLow.toLower();
  917. int preLength = preInsert.GetLength();
  918. int postLength = postInsert.GetLength();
  919. int x = mainLow.indexOf(findLow, 0);
  920. while(TRUE)
  921. {
  922. foundPos = mainLow.indexOf(findLow, startFindPos);
  923. if (foundPos < 0)
  924. break;
  925. if (replaceCount == 0)
  926. {
  927. firstFindPos = foundPos + preLength;
  928. }
  929. newPos = foundPos + insertedLength;
  930. mainStr.Insert(newPos, preInsert);
  931. mainStr.Insert(newPos + preLength + oldLen, postInsert);
  932. startFindPos = foundPos + oldLen;
  933. insertedLength += preLength + postLength;
  934. replaceCount++;
  935. //safety check, make sure we don't look forever
  936. if (replaceCount > 100)
  937. break;
  938. }
  939. startFindPos = 0;
  940. int line = 0;
  941. int prevLinePos = 0;
  942. int prevPrevLinePos = 0;
  943. while (TRUE)
  944. {
  945. foundPos = mainStr.Find(_T("\n"), startFindPos);
  946. if (foundPos < 0)
  947. break;
  948. if (firstFindPos < foundPos)
  949. {
  950. if (line > linesPerRow - 1)
  951. {
  952. int lineStart = prevLinePos;
  953. if (linesPerRow > 1)
  954. {
  955. lineStart = prevPrevLinePos;
  956. }
  957. mainStr = _T("... ") + mainStr.Mid(lineStart + 1);
  958. }
  959. break;
  960. }
  961. startFindPos = foundPos + 1;
  962. prevPrevLinePos = prevLinePos;
  963. prevLinePos = foundPos;
  964. line++;
  965. //safety check, make sure we don't look forever
  966. if (line > 1000)
  967. break;
  968. }
  969. if(replaceCount > 0)
  970. {
  971. mainStr.Replace(_T("\r\n"), _T("<br>"));
  972. int l = mainStr.Replace(_T("\r"), _T("<br>"));
  973. int m = mainStr.Replace(_T("\n"), _T("<br>"));
  974. }
  975. }
  976. return replaceCount;
  977. }
  978. void OnInitMenuPopupEx(CMenu *pPopupMenu, UINT nIndex, BOOL bSysMenu, CWnd *pWnd)
  979. {
  980. ASSERT(pPopupMenu != NULL);
  981. // Check the enabled state of various menu items.
  982. CCmdUI state;
  983. state.m_pMenu = pPopupMenu;
  984. ASSERT(state.m_pOther == NULL);
  985. ASSERT(state.m_pParentMenu == NULL);
  986. // Determine if menu is popup in top-level menu and set m_pOther to
  987. // it if so (m_pParentMenu == NULL indicates that it is secondary popup).
  988. HMENU hParentMenu;
  989. if (AfxGetThreadState()->m_hTrackingMenu == pPopupMenu->m_hMenu)
  990. {
  991. state.m_pParentMenu = pPopupMenu; // Parent == child for tracking popup.
  992. }
  993. else if ((hParentMenu = ::GetMenu(pWnd->m_hWnd)) != NULL)
  994. {
  995. CWnd* pParent = pWnd;
  996. // Child windows don't have menus--need to go to the top!
  997. if (pParent != NULL &&
  998. (hParentMenu = ::GetMenu(pParent->m_hWnd)) != NULL)
  999. {
  1000. int nIndexMax = ::GetMenuItemCount(hParentMenu);
  1001. for (int nIndex = 0; nIndex < nIndexMax; nIndex++)
  1002. {
  1003. if (::GetSubMenu(hParentMenu, nIndex) == pPopupMenu->m_hMenu)
  1004. {
  1005. // When popup is found, m_pParentMenu is containing menu.
  1006. state.m_pParentMenu = CMenu::FromHandle(hParentMenu);
  1007. break;
  1008. }
  1009. }
  1010. }
  1011. }
  1012. state.m_nIndexMax = pPopupMenu->GetMenuItemCount();
  1013. for (state.m_nIndex = 0; state.m_nIndex < state.m_nIndexMax;
  1014. state.m_nIndex++)
  1015. {
  1016. state.m_nID = pPopupMenu->GetMenuItemID(state.m_nIndex);
  1017. if (state.m_nID == 0)
  1018. continue; // Menu separator or invalid cmd - ignore it.
  1019. ASSERT(state.m_pOther == NULL);
  1020. ASSERT(state.m_pMenu != NULL);
  1021. if (state.m_nID == (UINT)-1)
  1022. {
  1023. // Possibly a popup menu, route to first item of that popup.
  1024. state.m_pSubMenu = pPopupMenu->GetSubMenu(state.m_nIndex);
  1025. if (state.m_pSubMenu == NULL ||
  1026. (state.m_nID = state.m_pSubMenu->GetMenuItemID(0)) == 0 ||
  1027. state.m_nID == (UINT)-1)
  1028. {
  1029. continue; // First item of popup can't be routed to.
  1030. }
  1031. state.DoUpdate(pWnd, TRUE); // Popups are never auto disabled.
  1032. }
  1033. else
  1034. {
  1035. // Normal menu item.
  1036. // Auto enable/disable if frame window has m_bAutoMenuEnable
  1037. // set and command is _not_ a system command.
  1038. state.m_pSubMenu = NULL;
  1039. state.DoUpdate(pWnd, FALSE);
  1040. }
  1041. // Adjust for menu deletions and additions.
  1042. UINT nCount = pPopupMenu->GetMenuItemCount();
  1043. if (nCount < state.m_nIndexMax)
  1044. {
  1045. state.m_nIndex -= (state.m_nIndexMax - nCount);
  1046. while (state.m_nIndex < nCount &&
  1047. pPopupMenu->GetMenuItemID(state.m_nIndex) == state.m_nID)
  1048. {
  1049. state.m_nIndex++;
  1050. }
  1051. }
  1052. state.m_nIndexMax = nCount;
  1053. }
  1054. }
  1055. CString InternetEncode(CString text)
  1056. {
  1057. CString ret = _T("");
  1058. LPTSTR lpOutputBuffer = new TCHAR[1];
  1059. DWORD dwSize = 1;
  1060. BOOL fRes = ::InternetCanonicalizeUrl(text, lpOutputBuffer, &dwSize, ICU_DECODE | ICU_NO_ENCODE);
  1061. DWORD dwError = ::GetLastError();
  1062. if (!fRes && dwError == ERROR_INSUFFICIENT_BUFFER)
  1063. {
  1064. delete lpOutputBuffer;
  1065. lpOutputBuffer = new TCHAR[dwSize];
  1066. fRes = ::InternetCanonicalizeUrl(text, lpOutputBuffer, &dwSize, ICU_DECODE | ICU_NO_ENCODE);
  1067. if (fRes)
  1068. {
  1069. ret = lpOutputBuffer;
  1070. //lpOutputBuffer has decoded url
  1071. }
  1072. else
  1073. {
  1074. //failed to decode
  1075. }
  1076. if (lpOutputBuffer != NULL)
  1077. {
  1078. delete [] lpOutputBuffer;
  1079. lpOutputBuffer = NULL;
  1080. }
  1081. }
  1082. else
  1083. {
  1084. //some other error OR the input string url is just 1 char and was successfully decoded
  1085. }
  1086. return ret;
  1087. }
  1088. bool WriteCF_DIBToFile(CString csPath, LPVOID data, ULONG size)
  1089. {
  1090. bool bRet = false;
  1091. BITMAPINFO *lpBI = (BITMAPINFO *) data;
  1092. int nPaletteEntries = 1 << lpBI->bmiHeader.biBitCount;
  1093. if (lpBI->bmiHeader.biBitCount > 8)
  1094. nPaletteEntries = 0;
  1095. else if (lpBI->bmiHeader.biClrUsed != 0)
  1096. nPaletteEntries = lpBI->bmiHeader.biClrUsed;
  1097. BITMAPFILEHEADER BFH;
  1098. memset(&BFH, 0, sizeof(BITMAPFILEHEADER));
  1099. BFH.bfType = 'MB';
  1100. BFH.bfSize = sizeof(BITMAPFILEHEADER) + size;
  1101. BFH.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + nPaletteEntries * sizeof(RGBQUAD);
  1102. // Create stream with 0 size
  1103. IStream* pIStream = NULL;
  1104. if (CreateStreamOnHGlobal(NULL, TRUE, (LPSTREAM*) &pIStream) != S_OK)
  1105. {
  1106. TRACE("Failed to create stream on global memory!\n");
  1107. return FALSE;
  1108. }
  1109. //write the file to the stream object
  1110. pIStream->Write(&BFH, sizeof(BITMAPFILEHEADER), NULL);
  1111. pIStream->Write(data, size, NULL);
  1112. CImage i;
  1113. i.Load(pIStream);
  1114. if(i.Save(csPath) == S_OK)
  1115. {
  1116. bRet = true;
  1117. }
  1118. return bRet;
  1119. }