Misc.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  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 <sys/types.h>
  10. #include <sys/stat.h>
  11. #include "Path.h"
  12. #include <regex>
  13. #include <vector>
  14. CString GetIPAddress()
  15. {
  16. WORD wVersionRequested;
  17. WSADATA wsaData;
  18. char name[255];
  19. CString IP;
  20. PHOSTENT hostinfo;
  21. wVersionRequested = MAKEWORD(2,0);
  22. if (WSAStartup(wVersionRequested, &wsaData)==0)
  23. {
  24. if(gethostname(name, sizeof(name))==0)
  25. {
  26. if((hostinfo=gethostbyname(name)) != NULL)
  27. {
  28. IP = inet_ntoa(*(struct in_addr*)* hostinfo->h_addr_list);
  29. }
  30. }
  31. WSACleanup();
  32. }
  33. IP.MakeUpper();
  34. return IP;
  35. }
  36. CString GetComputerName()
  37. {
  38. TCHAR ComputerName[MAX_COMPUTERNAME_LENGTH+1] = _T("");
  39. DWORD Size=MAX_COMPUTERNAME_LENGTH+1;
  40. GetComputerName(ComputerName, &Size);
  41. CString cs(ComputerName);
  42. cs.MakeUpper();
  43. return cs;
  44. }
  45. void AppendToFile(const TCHAR* fn, const TCHAR* msg)
  46. {
  47. #ifdef _UNICODE
  48. FILE *file = _wfopen(fn, _T("a"));
  49. #else
  50. FILE *file = fopen(fn, _T("a"));
  51. #endif
  52. ASSERT( file );
  53. if(file != NULL)
  54. {
  55. #ifdef _UNICODE
  56. fwprintf(file, _T("%s"), msg);
  57. #else
  58. fprintf(file, _T("%s"),msg);
  59. #endif
  60. fclose(file);
  61. }
  62. }
  63. void log(const TCHAR* msg, bool bFromSendRecieve, CString csFile, long lLine)
  64. {
  65. ASSERT(AfxIsValidString(msg));
  66. SYSTEMTIME st;
  67. GetLocalTime(&st);
  68. CString csText;
  69. csText.Format(_T("[%d/%d/%d %02d:%02d:%02d.%03d - "), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
  70. CString csFileLine;
  71. csFile = GetFileName(csFile);
  72. csFileLine.Format(_T("%s %d] "), csFile, lLine);
  73. csText += csFileLine;
  74. csText += msg;
  75. csText += "\n";
  76. #ifndef _DEBUG
  77. if(CGetSetOptions::m_outputDebugStringLogging)
  78. #endif
  79. {
  80. OutputDebugString(csText);
  81. }
  82. #ifndef _DEBUG
  83. if(!bFromSendRecieve)
  84. {
  85. if(!CGetSetOptions::m_bEnableDebugLogging)
  86. return;
  87. }
  88. #endif
  89. CString csExeFile = CGetSetOptions::GetPath(PATH_LOG_FILE);
  90. csExeFile += "Ditto.log";
  91. AppendToFile(csExeFile, csText);
  92. }
  93. void logsendrecieveinfo(CString cs, CString csFile, long lLine)
  94. {
  95. if(CGetSetOptions::m_bLogSendReceiveErrors)
  96. log(cs, true, csFile, lLine);
  97. }
  98. CString GetErrorString( int err )
  99. {
  100. CString str;
  101. LPVOID lpMsgBuf;
  102. ::FormatMessage(
  103. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
  104. NULL,
  105. err,
  106. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  107. (LPTSTR) &lpMsgBuf,
  108. 0,
  109. NULL
  110. );
  111. str = (LPCTSTR) lpMsgBuf;
  112. // Display the string.
  113. // ::MessageBox( NULL, lpMsgBuf, "GetLastError", MB_OK|MB_ICONINFORMATION );
  114. ::LocalFree( lpMsgBuf );
  115. return str;
  116. }
  117. int g_funnyGetTickCountAdjustment = -1;
  118. double IdleSeconds()
  119. {
  120. LASTINPUTINFO info;
  121. info.cbSize = sizeof(info);
  122. GetLastInputInfo(&info);
  123. DWORD currentTick = GetTickCount();
  124. if(g_funnyGetTickCountAdjustment == -1)
  125. {
  126. if(currentTick < info.dwTime)
  127. {
  128. g_funnyGetTickCountAdjustment = 1;
  129. }
  130. else
  131. {
  132. g_funnyGetTickCountAdjustment = 0;
  133. }
  134. }
  135. if(g_funnyGetTickCountAdjustment == 1 || g_funnyGetTickCountAdjustment == 2)
  136. {
  137. //Output message the first time
  138. if(g_funnyGetTickCountAdjustment == 1)
  139. {
  140. Log(StrF(_T("Adjusting time of get tickcount by: %d, on startup we found GetTickCount to be less than last input"), CGetSetOptions::GetFunnyTickCountAdjustment()));
  141. g_funnyGetTickCountAdjustment = 2;
  142. }
  143. currentTick += CGetSetOptions::GetFunnyTickCountAdjustment();
  144. }
  145. double idleSeconds = (currentTick - info.dwTime)/1000.0;
  146. return idleSeconds;
  147. }
  148. CString StrF(const TCHAR * pszFormat, ...)
  149. {
  150. ASSERT( AfxIsValidString( pszFormat ) );
  151. CString str;
  152. va_list argList;
  153. va_start( argList, pszFormat );
  154. str.FormatV( pszFormat, argList );
  155. va_end( argList );
  156. return str;
  157. }
  158. BYTE GetEscapeChar( BYTE ch )
  159. {
  160. switch(ch)
  161. {
  162. case '\'': return '\''; // Single quotation mark (') = 39 or 0x27
  163. case '\"': return '\"'; // Double quotation mark (") = 34 or 0x22
  164. case '?': return '\?'; // Question mark (?) = 63 or 0x3f
  165. case '\\': return '\\'; // Backslash (\) = 92 or 0x5c
  166. case 'a': return '\a'; // Alert (BEL) = 7
  167. case 'b': return '\b'; // Backspace (BS) = 8
  168. case 'f': return '\f'; // Formfeed (FF) = 12 or 0x0c
  169. case 'n': return '\n'; // Newline (NL or LF) = 10 or 0x0a
  170. case 'r': return '\r'; // Carriage Return (CR) = 13 or 0x0d
  171. case 't': return '\t'; // Horizontal tab (HT) = 9
  172. case 'v': return '\v'; // Vertical tab (VT) = 11 or 0x0b
  173. case '0': return '\0'; // Null character (NUL) = 0
  174. }
  175. return 0; // invalid
  176. }
  177. CString RemoveEscapes( const TCHAR* str )
  178. {
  179. ASSERT( str );
  180. CString ret;
  181. TCHAR* pSrc = (TCHAR*) str;
  182. TCHAR* pDest = ret.GetBuffer((int)STRLEN(pSrc));
  183. TCHAR* pStart = pDest;
  184. while( *pSrc != '\0' )
  185. {
  186. if( *pSrc == '\\' )
  187. {
  188. pSrc++;
  189. *pDest = GetEscapeChar((BYTE)pSrc );
  190. }
  191. else
  192. *pDest = *pSrc;
  193. pSrc++;
  194. pDest++;
  195. }
  196. ret.ReleaseBuffer((int)(pDest - pStart));
  197. return ret;
  198. }
  199. CString GetWndText(HWND hWnd)
  200. {
  201. TCHAR cWindowText[200];
  202. HWND hParent = hWnd;
  203. ::GetWindowText(hParent, cWindowText, 100);
  204. int nCount = 0;
  205. while (STRLEN(cWindowText) <= 0)
  206. {
  207. hParent = ::GetParent(hParent);
  208. if (hParent == NULL)
  209. break;
  210. ::GetWindowText(hParent, cWindowText, 100);
  211. nCount++;
  212. if (nCount > 100)
  213. {
  214. Log(_T("GetTargetName reached maximum search depth of 100"));
  215. break;
  216. }
  217. }
  218. return cWindowText;
  219. }
  220. CString TopLevelWindowText(DWORD pid)
  221. {
  222. std::pair<CString, DWORD> params = { _T(""), pid };
  223. // Enumerate the windows using a lambda to process each window
  224. BOOL bResult = EnumWindows([](HWND hwnd, LPARAM lParam) -> BOOL
  225. {
  226. auto pParams = (std::pair<CString, DWORD>*)(lParam);
  227. DWORD processId;
  228. if (GetWindowThreadProcessId(hwnd, &processId) &&
  229. processId == pParams->second &&
  230. ::GetWindow(hwnd, GW_OWNER) == 0)
  231. {
  232. TCHAR cWindowText[500];
  233. ::GetWindowText(hwnd, cWindowText, 500);
  234. if (STRLEN(cWindowText) > 0)
  235. {
  236. pParams->first = cWindowText;
  237. return FALSE;
  238. }
  239. }
  240. // Continue enumerating
  241. return TRUE;
  242. }, (LPARAM)&params);
  243. return params.first;
  244. }
  245. bool IsAppWnd( HWND hWnd )
  246. {
  247. DWORD dwMyPID = ::GetCurrentProcessId();
  248. DWORD dwTestPID;
  249. ::GetWindowThreadProcessId( hWnd, &dwTestPID );
  250. return dwMyPID == dwTestPID;
  251. }
  252. /*----------------------------------------------------------------------------*\
  253. Global Memory Helper Functions
  254. \*----------------------------------------------------------------------------*/
  255. // make sure the given HGLOBAL is valid.
  256. BOOL IsValid(HGLOBAL hGlobal)
  257. {
  258. void* pvData = ::GlobalLock(hGlobal);
  259. ::GlobalUnlock(hGlobal);
  260. return (pvData != NULL);
  261. }
  262. // asserts if hDest isn't big enough
  263. void CopyToGlobalHP(HGLOBAL hDest, LPVOID pBuf, SIZE_T ulBufLen)
  264. {
  265. ASSERT(hDest && pBuf && ulBufLen);
  266. LPVOID pvData = GlobalLock(hDest);
  267. ASSERT(pvData);
  268. SIZE_T size = GlobalSize(hDest);
  269. ASSERT(size >= ulBufLen); // assert if hDest isn't big enough
  270. memcpy(pvData, pBuf, ulBufLen);
  271. GlobalUnlock(hDest);
  272. }
  273. void CopyToGlobalHH(HGLOBAL hDest, HGLOBAL hSource, SIZE_T ulBufLen)
  274. {
  275. ASSERT(hDest && hSource && ulBufLen);
  276. LPVOID pvData = GlobalLock(hSource);
  277. ASSERT(pvData );
  278. SIZE_T size = GlobalSize(hSource);
  279. ASSERT(size >= ulBufLen); // assert if hSource isn't big enough
  280. CopyToGlobalHP(hDest, pvData, ulBufLen);
  281. GlobalUnlock(hSource);
  282. }
  283. HGLOBAL NewGlobalP(LPVOID pBuf, SIZE_T nLen)
  284. {
  285. ASSERT(pBuf && nLen);
  286. HGLOBAL hDest = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE, nLen);
  287. ASSERT(hDest );
  288. CopyToGlobalHP(hDest, pBuf, nLen);
  289. return hDest;
  290. }
  291. HGLOBAL NewGlobal(SIZE_T nLen)
  292. {
  293. ASSERT(nLen);
  294. HGLOBAL hDest = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE, nLen);
  295. return hDest;
  296. }
  297. HGLOBAL NewGlobalH(HGLOBAL hSource, SIZE_T nLen)
  298. {
  299. ASSERT(hSource && nLen);
  300. LPVOID pvData = GlobalLock(hSource);
  301. HGLOBAL hDest = NewGlobalP(pvData, nLen);
  302. GlobalUnlock(hSource);
  303. return hDest;
  304. }
  305. int CompareGlobalHP(HGLOBAL hLeft, LPVOID pBuf, SIZE_T ulBufLen)
  306. {
  307. ASSERT(hLeft && pBuf && ulBufLen);
  308. LPVOID pvData = GlobalLock(hLeft);
  309. ASSERT(pvData);
  310. ASSERT(ulBufLen <= GlobalSize(hLeft));
  311. int result = memcmp(pvData, pBuf, ulBufLen);
  312. GlobalUnlock(hLeft);
  313. return result;
  314. }
  315. int CompareGlobalHH( HGLOBAL hLeft, HGLOBAL hRight, SIZE_T ulBufLen)
  316. {
  317. ASSERT(hLeft && hRight && ulBufLen);
  318. ASSERT(ulBufLen <= GlobalSize(hRight));
  319. LPVOID pvData = GlobalLock(hRight);
  320. ASSERT(pvData);
  321. int result = CompareGlobalHP(hLeft, pvData, ulBufLen);
  322. GlobalUnlock(hLeft);
  323. return result;
  324. }
  325. // https://learn.microsoft.com/en-us/windows/win32/dataxchg/standard-clipboard-formats
  326. std::vector<CLIPFORMAT> GetSystemClipFormats()
  327. {
  328. std::vector<CLIPFORMAT> v = {
  329. CF_TEXT,
  330. CF_BITMAP,
  331. CF_METAFILEPICT,
  332. CF_SYLK,
  333. CF_DIF,
  334. CF_TIFF,
  335. CF_OEMTEXT,
  336. CF_DIB,
  337. CF_PALETTE,
  338. CF_PENDATA,
  339. CF_RIFF,
  340. CF_WAVE,
  341. CF_UNICODETEXT,
  342. CF_ENHMETAFILE,
  343. CF_HDROP,
  344. CF_LOCALE,
  345. CF_OWNERDISPLAY,
  346. CF_DSPTEXT,
  347. CF_DSPBITMAP,
  348. CF_DSPMETAFILEPICT,
  349. CF_DSPENHMETAFILE
  350. };
  351. return v;
  352. }
  353. //Do not change these these are stored in the database
  354. CLIPFORMAT GetFormatID(LPCTSTR cbName)
  355. {
  356. if(STRCMP(cbName, _T("CF_TEXT")) == 0)
  357. return CF_TEXT;
  358. else if(STRCMP(cbName, _T("CF_METAFILEPICT")) == 0)
  359. return CF_METAFILEPICT;
  360. else if(STRCMP(cbName, _T("CF_SYLK")) == 0)
  361. return CF_SYLK;
  362. else if(STRCMP(cbName, _T("CF_DIF")) == 0)
  363. return CF_DIF;
  364. else if(STRCMP(cbName, _T("CF_TIFF")) == 0)
  365. return CF_TIFF;
  366. else if(STRCMP(cbName, _T("CF_OEMTEXT")) == 0)
  367. return CF_OEMTEXT;
  368. else if(STRCMP(cbName, _T("CF_DIB")) == 0)
  369. return CF_DIB;
  370. else if(STRCMP(cbName, _T("CF_PALETTE")) == 0)
  371. return CF_PALETTE;
  372. else if(STRCMP(cbName, _T("CF_PENDATA")) == 0)
  373. return CF_PENDATA;
  374. else if(STRCMP(cbName, _T("CF_RIFF")) == 0)
  375. return CF_RIFF;
  376. else if(STRCMP(cbName, _T("CF_WAVE")) == 0)
  377. return CF_WAVE;
  378. else if(STRCMP(cbName, _T("CF_UNICODETEXT")) == 0)
  379. return CF_UNICODETEXT;
  380. else if(STRCMP(cbName, _T("CF_ENHMETAFILE")) == 0)
  381. return CF_ENHMETAFILE;
  382. else if(STRCMP(cbName, _T("CF_HDROP")) == 0)
  383. return CF_HDROP;
  384. else if(STRCMP(cbName, _T("CF_LOCALE")) == 0)
  385. return CF_LOCALE;
  386. else if(STRCMP(cbName, _T("CF_OWNERDISPLAY")) == 0)
  387. return CF_OWNERDISPLAY;
  388. else if(STRCMP(cbName, _T("CF_DSPTEXT")) == 0)
  389. return CF_DSPTEXT;
  390. else if(STRCMP(cbName, _T("CF_DSPBITMAP")) == 0)
  391. return CF_DSPBITMAP;
  392. else if(STRCMP(cbName, _T("CF_DSPMETAFILEPICT")) == 0)
  393. return CF_DSPMETAFILEPICT;
  394. else if(STRCMP(cbName, _T("CF_DSPENHMETAFILE")) == 0)
  395. return CF_DSPENHMETAFILE;
  396. return ::RegisterClipboardFormat(cbName);
  397. }
  398. //Do not change these these are stored in the database
  399. CString GetFormatName(CLIPFORMAT cbType)
  400. {
  401. switch(cbType)
  402. {
  403. case CF_TEXT:
  404. return _T("CF_TEXT");
  405. case CF_BITMAP:
  406. return _T("CF_BITMAP");
  407. case CF_METAFILEPICT:
  408. return _T("CF_METAFILEPICT");
  409. case CF_SYLK:
  410. return _T("CF_SYLK");
  411. case CF_DIF:
  412. return _T("CF_DIF");
  413. case CF_TIFF:
  414. return _T("CF_TIFF");
  415. case CF_OEMTEXT:
  416. return _T("CF_OEMTEXT");
  417. case CF_DIB:
  418. return _T("CF_DIB");
  419. case CF_PALETTE:
  420. return _T("CF_PALETTE");
  421. case CF_PENDATA:
  422. return _T("CF_PENDATA");
  423. case CF_RIFF:
  424. return _T("CF_RIFF");
  425. case CF_WAVE:
  426. return _T("CF_WAVE");
  427. case CF_UNICODETEXT:
  428. return _T("CF_UNICODETEXT");
  429. case CF_ENHMETAFILE:
  430. return _T("CF_ENHMETAFILE");
  431. case CF_HDROP:
  432. return _T("CF_HDROP");
  433. case CF_LOCALE:
  434. return _T("CF_LOCALE");
  435. case CF_OWNERDISPLAY:
  436. return _T("CF_OWNERDISPLAY");
  437. case CF_DSPTEXT:
  438. return _T("CF_DSPTEXT");
  439. case CF_DSPBITMAP:
  440. return _T("CF_DSPBITMAP");
  441. case CF_DSPMETAFILEPICT:
  442. return _T("CF_DSPMETAFILEPICT");
  443. case CF_DSPENHMETAFILE:
  444. return _T("CF_DSPENHMETAFILE");
  445. default:
  446. //Not a default type get the name from the clipboard
  447. if (cbType != 0)
  448. {
  449. TCHAR szFormat[256];
  450. GetClipboardFormatName(cbType, szFormat, 256);
  451. return szFormat;
  452. }
  453. break;
  454. }
  455. return "ERROR";
  456. }
  457. CString GetFilePath(CString csFileName)
  458. {
  459. long lSlash = csFileName.ReverseFind('\\');
  460. if(lSlash > -1)
  461. {
  462. csFileName = csFileName.Left(lSlash + 1);
  463. }
  464. return csFileName;
  465. }
  466. CString GetFileName(CString csFileName)
  467. {
  468. long lSlash = csFileName.ReverseFind('\\');
  469. if(lSlash > -1)
  470. {
  471. csFileName = csFileName.Right(csFileName.GetLength() - lSlash - 1);
  472. }
  473. return csFileName;
  474. }
  475. /****************************************************************************************************
  476. BOOL CALLBACK MyMonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
  477. ***************************************************************************************************/
  478. typedef struct
  479. {
  480. long lFlags; // Flags
  481. LPRECT pVirtualRect; // Ptr to rect that receives the results, or the src of the monitor search method
  482. int iMonitor; // Ndx to the mointor to look at, -1 for all, -or- result of the monitor search method
  483. int nMonitorCount; // Total number of monitors found, -1 for monitor search method
  484. } MONITOR_ENUM_PARAM;
  485. #define MONITOR_SEARCH_METOHD 0x00000001
  486. BOOL CALLBACK MyMonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
  487. {
  488. // Typecast param
  489. MONITOR_ENUM_PARAM* pParam = (MONITOR_ENUM_PARAM*)dwData;
  490. if(pParam)
  491. {
  492. // If a dest rect was passed
  493. if(pParam->pVirtualRect)
  494. {
  495. // If MONITOR_SEARCH_METOHD then we are being asked for the index of the monitor
  496. // that the rect falls inside of
  497. if(pParam->lFlags & MONITOR_SEARCH_METOHD)
  498. {
  499. if( (pParam->pVirtualRect->right < lprcMonitor->left) ||
  500. (pParam->pVirtualRect->left > lprcMonitor->right) ||
  501. (pParam->pVirtualRect->bottom < lprcMonitor->top) ||
  502. (pParam->pVirtualRect->top > lprcMonitor->bottom))
  503. {
  504. // Nothing
  505. }
  506. else
  507. {
  508. // This is the one
  509. pParam->iMonitor = pParam->nMonitorCount;
  510. // Stop the enumeration
  511. return FALSE;
  512. }
  513. }
  514. else
  515. {
  516. if(pParam->iMonitor == pParam->nMonitorCount)
  517. {
  518. *pParam->pVirtualRect = *lprcMonitor;
  519. }
  520. else
  521. if(pParam->iMonitor == -1)
  522. {
  523. pParam->pVirtualRect->left = min(pParam->pVirtualRect->left, lprcMonitor->left);
  524. pParam->pVirtualRect->top = min(pParam->pVirtualRect->top, lprcMonitor->top);
  525. pParam->pVirtualRect->right = max(pParam->pVirtualRect->right, lprcMonitor->right);
  526. pParam->pVirtualRect->bottom = max(pParam->pVirtualRect->bottom, lprcMonitor->bottom);
  527. }
  528. }
  529. }
  530. // Up the count if necessary
  531. pParam->nMonitorCount++;
  532. }
  533. return TRUE;
  534. }
  535. int GetScreenWidth(void)
  536. {
  537. OSVERSIONINFO OS_Version_Info;
  538. DWORD dwPlatform = 0;
  539. if(GetVersionEx(&OS_Version_Info) != 0)
  540. {
  541. dwPlatform = OS_Version_Info.dwPlatformId;
  542. }
  543. if(dwPlatform == VER_PLATFORM_WIN32_NT)
  544. {
  545. int width, height;
  546. width = GetSystemMetrics(SM_CXSCREEN);
  547. height = GetSystemMetrics(SM_CYSCREEN);
  548. switch(width)
  549. {
  550. default:
  551. case 640:
  552. case 800:
  553. case 1024:
  554. return(width);
  555. case 1280:
  556. if(height == 480)
  557. {
  558. return(width / 2);
  559. }
  560. return(width);
  561. case 1600:
  562. if(height == 600)
  563. {
  564. return(width / 2);
  565. }
  566. return(width);
  567. case 2048:
  568. if(height == 768)
  569. {
  570. return(width / 2);
  571. }
  572. return(width);
  573. }
  574. }
  575. else
  576. {
  577. return(GetSystemMetrics(SM_CXVIRTUALSCREEN));
  578. }
  579. }
  580. int GetScreenHeight(void)
  581. {
  582. OSVERSIONINFO OS_Version_Info;
  583. DWORD dwPlatform = 0;
  584. if(GetVersionEx(&OS_Version_Info) != 0)
  585. {
  586. dwPlatform = OS_Version_Info.dwPlatformId;
  587. }
  588. if(dwPlatform == VER_PLATFORM_WIN32_NT)
  589. {
  590. int width, height;
  591. width = GetSystemMetrics(SM_CXSCREEN);
  592. height = GetSystemMetrics(SM_CYSCREEN);
  593. switch(height)
  594. {
  595. default:
  596. case 480:
  597. case 600:
  598. case 768:
  599. return(height);
  600. case 960:
  601. if(width == 640)
  602. {
  603. return(height / 2);
  604. }
  605. return(height);
  606. case 1200:
  607. if(width == 800)
  608. {
  609. return(height / 2);
  610. }
  611. return(height);
  612. case 1536:
  613. if(width == 1024)
  614. {
  615. return(height / 2);
  616. }
  617. return(height);
  618. }
  619. }
  620. else
  621. {
  622. return(GetSystemMetrics(SM_CYVIRTUALSCREEN));
  623. }
  624. }
  625. /*------------------------------------------------------------------*\
  626. ID based Globals
  627. \*------------------------------------------------------------------*/
  628. long NewGroupID(int parentID, CString text)
  629. {
  630. long lID=0;
  631. CTime time;
  632. time = CTime::GetCurrentTime();
  633. try
  634. {
  635. //sqlite doesn't like single quotes ' replace them with double ''
  636. if(text.IsEmpty())
  637. text = time.Format("NewGroup %y/%m/%d %H:%M:%S");
  638. text.Replace(_T("'"), _T("''"));
  639. CString cs;
  640. cs.Format(_T("insert into Main (lDate, mText, lDontAutoDelete, bIsGroup, lParentID, stickyClipOrder, stickyClipGroupOrder) values(%d, '%s', %d, 1, %d, -(2147483647), -(2147483647));"),
  641. (int)time.GetTime(),
  642. text,
  643. (int)time.GetTime(),
  644. parentID);
  645. theApp.m_db.execDML(cs);
  646. lID = (long)theApp.m_db.lastRowId();
  647. }
  648. CATCH_SQLITE_EXCEPTION_AND_RETURN(0)
  649. return lID;
  650. }
  651. BOOL DeleteAllIDs()
  652. {
  653. try
  654. {
  655. theApp.m_db.execDML(_T("DELETE FROM Data;"));
  656. theApp.m_db.execDML(_T("DELETE FROM Main;"));
  657. }
  658. CATCH_SQLITE_EXCEPTION
  659. return TRUE;
  660. }
  661. BOOL DeleteFormats(int parentID, ARRAY& formatIDs)
  662. {
  663. if(formatIDs.GetSize() <= 0)
  664. return TRUE;
  665. try
  666. {
  667. //Delete the requested data formats
  668. INT_PTR count = formatIDs.GetSize();
  669. for(int i = 0; i < count; i++)
  670. {
  671. int count = theApp.m_db.execDMLEx(_T("DELETE FROM Data WHERE lID = %d;"), formatIDs[i]);
  672. }
  673. CClip clip;
  674. if(clip.LoadFormats(parentID))
  675. {
  676. DWORD CRC = clip.GenerateCRC();
  677. //Update the main table with new size
  678. theApp.m_db.execDMLEx(_T("UPDATE Main SET CRC = %d WHERE lID = %d"), CRC, parentID);
  679. }
  680. }
  681. CATCH_SQLITE_EXCEPTION
  682. return TRUE;
  683. }
  684. CRect CenterRect(CRect startingRect)
  685. {
  686. CRect crMonitor;
  687. HMONITOR monitorHandle = MonitorFromPoint(startingRect.TopLeft(), MONITOR_DEFAULTTONEAREST);
  688. if (monitorHandle == NULL)
  689. {
  690. monitorHandle = MonitorFromPoint(startingRect.TopLeft(), MONITOR_DEFAULTTOPRIMARY);
  691. MONITORINFO lpmi;
  692. lpmi.cbSize = sizeof(MONITORINFO);
  693. if (GetMonitorInfo(monitorHandle, &lpmi))
  694. {
  695. crMonitor.CopyRect(&lpmi.rcWork);
  696. }
  697. }
  698. else
  699. {
  700. MONITORINFO lpmi;
  701. lpmi.cbSize = sizeof(MONITORINFO);
  702. if (GetMonitorInfo(monitorHandle, &lpmi))
  703. {
  704. crMonitor.CopyRect(&lpmi.rcWork);
  705. }
  706. }
  707. return CenterRectFromRect(startingRect, crMonitor);
  708. }
  709. CRect CenterRectFromRect(CRect startingRect, CRect outerRect)
  710. {
  711. CPoint center = outerRect.CenterPoint();
  712. CRect centerRect;
  713. centerRect.left = center.x - (startingRect.Width() / 2);
  714. centerRect.top = center.y - (startingRect.Height() / 2);
  715. centerRect.right = centerRect.left + startingRect.Width();
  716. centerRect.bottom = centerRect.top + startingRect.Height();
  717. return centerRect;
  718. }
  719. CRect DefaultMonitorRect()
  720. {
  721. CRect crMonitor;
  722. CRect invalidRect(INT32_MAX, INT32_MAX, INT32_MAX, INT32_MAX);
  723. HMONITOR monitorHandle = MonitorFromPoint(invalidRect.TopLeft(), MONITOR_DEFAULTTOPRIMARY);
  724. MONITORINFO lpmi;
  725. lpmi.cbSize = sizeof(MONITORINFO);
  726. if (GetMonitorInfo(monitorHandle, &lpmi))
  727. {
  728. crMonitor.CopyRect(&lpmi.rcWork);
  729. }
  730. return crMonitor;
  731. }
  732. CRect MonitorRectFromRect(CRect rect)
  733. {
  734. BOOL ret = FALSE;
  735. CRect crMonitor;
  736. HMONITOR monitorHandle = MonitorFromPoint(rect.TopLeft(), MONITOR_DEFAULTTONEAREST);
  737. if (monitorHandle == NULL)
  738. {
  739. monitorHandle = MonitorFromPoint(rect.TopLeft(), MONITOR_DEFAULTTOPRIMARY);
  740. MONITORINFO lpmi;
  741. lpmi.cbSize = sizeof(MONITORINFO);
  742. if (GetMonitorInfo(monitorHandle, &lpmi))
  743. {
  744. crMonitor.CopyRect(&lpmi.rcWork);
  745. }
  746. }
  747. else
  748. {
  749. MONITORINFO lpmi;
  750. lpmi.cbSize = sizeof(MONITORINFO);
  751. if (GetMonitorInfo(monitorHandle, &lpmi))
  752. {
  753. crMonitor.CopyRect(&lpmi.rcWork);
  754. }
  755. }
  756. return crMonitor;
  757. }
  758. BOOL EnsureWindowVisible(CRect *pcrRect)
  759. {
  760. BOOL ret = FALSE;
  761. CRect crMonitor;
  762. HMONITOR monitorHandle = MonitorFromRect(pcrRect, MONITOR_DEFAULTTONEAREST);
  763. if (monitorHandle == NULL)
  764. {
  765. monitorHandle = MonitorFromRect(pcrRect, MONITOR_DEFAULTTOPRIMARY);
  766. MONITORINFO lpmi;
  767. lpmi.cbSize = sizeof(MONITORINFO);
  768. if (GetMonitorInfo(monitorHandle, &lpmi))
  769. {
  770. crMonitor.CopyRect(&lpmi.rcWork);
  771. *pcrRect = CenterRectFromRect(*pcrRect, crMonitor);
  772. }
  773. }
  774. else
  775. {
  776. MONITORINFO lpmi;
  777. lpmi.cbSize = sizeof(MONITORINFO);
  778. if (GetMonitorInfo(monitorHandle, &lpmi))
  779. {
  780. crMonitor.CopyRect(&lpmi.rcWork);
  781. }
  782. }
  783. bool movedLeft = false;
  784. //Validate the left
  785. long lDiff = pcrRect->left - crMonitor.left;
  786. if (lDiff < 0)
  787. {
  788. pcrRect->left += abs(lDiff);
  789. pcrRect->right += abs(lDiff);
  790. ret = TRUE;
  791. movedLeft = true;
  792. }
  793. //Right side
  794. lDiff = pcrRect->right - crMonitor.right;
  795. if (lDiff > 0)
  796. {
  797. if (movedLeft == false)
  798. {
  799. pcrRect->left -= abs(lDiff);
  800. }
  801. pcrRect->right -= abs(lDiff);
  802. ret = TRUE;
  803. }
  804. bool movedTop = false;
  805. //Top
  806. lDiff = pcrRect->top - crMonitor.top;
  807. if (lDiff < 0)
  808. {
  809. pcrRect->top += abs(lDiff);
  810. pcrRect->bottom += abs(lDiff);
  811. ret = TRUE;
  812. movedTop = true;
  813. }
  814. //Bottom
  815. lDiff = pcrRect->bottom - crMonitor.bottom;
  816. if (lDiff > 0)
  817. {
  818. if (movedTop == false)
  819. {
  820. pcrRect->top -= abs(lDiff);
  821. }
  822. pcrRect->bottom -= abs(lDiff);
  823. ret = TRUE;
  824. }
  825. return ret;
  826. }
  827. __int64 GetLastWriteTime(const CString &csFile)
  828. {
  829. __int64 nLastWrite = 0;
  830. CFileFind finder;
  831. BOOL bResult = finder.FindFile(csFile);
  832. if (bResult)
  833. {
  834. finder.FindNextFile();
  835. FILETIME ft;
  836. finder.GetLastWriteTime(&ft);
  837. memcpy(&nLastWrite, &ft, sizeof(ft));
  838. }
  839. return nLastWrite;
  840. }
  841. typedef struct
  842. {
  843. DWORD ownerpid;
  844. DWORD childpid;
  845. } windowinfo;
  846. BOOL CALLBACK EnumChildWindowsCallback(HWND hWnd, LPARAM lp)
  847. {
  848. windowinfo* info = (windowinfo*)lp;
  849. DWORD pid = 0;
  850. GetWindowThreadProcessId(hWnd, &pid);
  851. if (pid != info->ownerpid)
  852. info->childpid = pid;
  853. return TRUE;
  854. }
  855. CString UWP_AppName(HWND active_window, DWORD ownerpid)
  856. {
  857. CString uwpAppName;
  858. windowinfo info = { 0 };
  859. info.ownerpid = ownerpid;
  860. info.childpid = info.ownerpid;
  861. EnumChildWindows(active_window, EnumChildWindowsCallback, (LPARAM)&info);
  862. HANDLE active_process = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, info.childpid);
  863. if (active_process != NULL)
  864. {
  865. WCHAR image_name[MAX_PATH] = { 0 };
  866. DWORD bufsize = MAX_PATH;
  867. QueryFullProcessImageName(active_process, 0, image_name, &bufsize);
  868. CloseHandle(active_process);
  869. nsPath::CPath path(image_name);
  870. uwpAppName = path.GetName();
  871. }
  872. return uwpAppName;
  873. }
  874. CString GetProcessName(HWND hWnd, DWORD processId)
  875. {
  876. DWORD startTick = GetTickCount();
  877. CString strProcessName;
  878. DWORD Id = processId;
  879. if (Id == 0)
  880. {
  881. GetWindowThreadProcessId(hWnd, &Id);
  882. }
  883. HANDLE active_process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, Id);
  884. if (active_process != NULL)
  885. {
  886. WCHAR image_name[MAX_PATH] = { 0 };
  887. DWORD bufsize = MAX_PATH;
  888. QueryFullProcessImageName(active_process, 0, image_name, &bufsize);
  889. CloseHandle(active_process);
  890. nsPath::CPath path(image_name);
  891. strProcessName = path.GetName();
  892. }
  893. if (strProcessName == _T(""))
  894. {
  895. Log(StrF(_T("failed to get process name from open process, LastError: %d, looping over process names to find process"), GetLastError()));
  896. PROCESSENTRY32 processEntry = { 0 };
  897. HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  898. processEntry.dwSize = sizeof(PROCESSENTRY32);
  899. if (Process32First(hSnapShot, &processEntry))
  900. {
  901. do
  902. {
  903. if (processEntry.th32ProcessID == Id)
  904. {
  905. strProcessName = processEntry.szExeFile;
  906. break;
  907. }
  908. } while (Process32Next(hSnapShot, &processEntry));
  909. }
  910. CloseHandle(hSnapShot);
  911. }
  912. //uwp apps are wrapped in another app called, if this has focus then try and find the child uwp process
  913. if (strProcessName == _T("ApplicationFrameHost.exe"))
  914. {
  915. strProcessName = UWP_AppName(hWnd, Id);
  916. }
  917. DWORD endTick = GetTickCount();
  918. DWORD diff = endTick - startTick;
  919. if(diff > 5)
  920. {
  921. Log(StrF(_T("GetProcessName Time (ms): %d, pid: %d, name: %s"), endTick-startTick, Id, strProcessName));
  922. }
  923. return strProcessName;
  924. }
  925. BOOL IsVista()
  926. {
  927. OSVERSIONINFO osver;
  928. osver.dwOSVersionInfoSize = sizeof( OSVERSIONINFO );
  929. if (::GetVersionEx( &osver ) &&
  930. osver.dwPlatformId == VER_PLATFORM_WIN32_NT &&
  931. (osver.dwMajorVersion >= 6 ) )
  932. {
  933. return TRUE;
  934. }
  935. return FALSE;
  936. }
  937. bool IsRunningLimited()
  938. {
  939. LPCTSTR pszSubKey = _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System");
  940. LPCTSTR pszValue = _T("EnableLUA");
  941. DWORD dwType = 0;
  942. DWORD dwValue = 0;
  943. DWORD dwValueSize = sizeof(DWORD);
  944. if(ERROR_SUCCESS != SHGetValue(HKEY_LOCAL_MACHINE, pszSubKey, pszValue, &dwType, &dwValue, &dwValueSize))
  945. {
  946. //failed to read the reg key, either it's not there or we don't have access to the registry
  947. //If we are vista then assume we don't have access and we are running as a limited app
  948. //otherwise we are xp and the reg key probably doesn't exist and we are not a limited running app
  949. if(IsVista())
  950. {
  951. OutputDebugString(_T("Ditto - Failed to read registry entry finding UAC, Running as limited application"));
  952. return true;
  953. }
  954. }
  955. if(dwValue == 1)
  956. {
  957. OutputDebugString(_T("Ditto - UAC ENABLED, Running as limited application"));
  958. return true;
  959. }
  960. OutputDebugString(_T("Ditto - Running as standard application"));
  961. return false;
  962. }
  963. void DeleteDittoTempFiles(BOOL checkFileLastAccess)
  964. {
  965. CString csDir = CGetSetOptions::GetPath(PATH_REMOTE_FILES);
  966. if (FileExists(csDir))
  967. {
  968. DeleteFolderFiles(csDir, checkFileLastAccess, CTimeSpan(0, 1, 0, 0));
  969. }
  970. csDir = CGetSetOptions::GetPath(PATH_DRAG_FILES);
  971. if (FileExists(csDir))
  972. {
  973. DeleteFolderFiles(csDir, checkFileLastAccess, CTimeSpan(0, 1, 0, 0));
  974. }
  975. csDir = CGetSetOptions::GetPath(PATH_CLIP_DIFF);
  976. if (FileExists(csDir))
  977. {
  978. DeleteFolderFiles(csDir, checkFileLastAccess, CTimeSpan(0, 1, 0, 0));
  979. }
  980. }
  981. void DeleteFolderFiles(CString csDir, BOOL checkFileLastAccess, CTimeSpan lastAccessOffset)
  982. {
  983. if (csDir.Find(_T("\\ReceivedFiles\\")) == -1 && csDir.Find(_T("\\DragFiles\\")) == -1 && csDir.Find(_T("ClipCompare")) == -1 && csDir.Find(_T("EditClips")) == -1)
  984. return;
  985. Log(StrF(_T("Deleting files in Folder %s Check Last Access %d"), csDir, checkFileLastAccess));
  986. FIX_CSTRING_PATH(csDir);
  987. CTime ctOld = CTime::GetCurrentTime();
  988. CTime ctFile;
  989. ctOld -= lastAccessOffset;
  990. CFileFind Find;
  991. CString csFindString;
  992. csFindString.Format(_T("%s*.*"), csDir);
  993. BOOL bFound = Find.FindFile(csFindString);
  994. while(bFound)
  995. {
  996. bFound = Find.FindNextFile();
  997. if(Find.IsDots())
  998. continue;
  999. if(checkFileLastAccess &&
  1000. Find.GetLastAccessTime(ctFile))
  1001. {
  1002. //Delete the remote copied file if it hasn't been used for the last day
  1003. if(ctFile < ctOld)
  1004. {
  1005. Log(StrF(_T("Deleting temp file %s"), Find.GetFilePath()));
  1006. DeleteFile(Find.GetFilePath());
  1007. }
  1008. }
  1009. else
  1010. {
  1011. Log(StrF(_T("Deleting temp file %s"), Find.GetFilePath()));
  1012. DeleteFile(Find.GetFilePath());
  1013. }
  1014. }
  1015. }
  1016. __int64 FileSize(const TCHAR *fileName)
  1017. {
  1018. struct _stat64 buf;
  1019. if (_wstat64((wchar_t const*)fileName, &buf) != 0)
  1020. return -1; // error, could use errno to find out more
  1021. return buf.st_size;
  1022. }
  1023. int FindNoCaseAndInsert(CString& mainStr, CString& findStr, CString preInsert, CString postInsert, int linesPerRow)
  1024. {
  1025. int replaceCount = 0;
  1026. //Prevent infinite loop when user tries to replace nothing.
  1027. if (findStr != "")
  1028. {
  1029. int oldLen = findStr.GetLength();
  1030. int foundPos = 0;
  1031. int startFindPos = 0;
  1032. int newPos = 0;
  1033. int insertedLength = 0;
  1034. int firstFindPos = 0;
  1035. CString mainLow(theApp.m_icuString.ToLowerStringEx(mainStr));
  1036. CString findLow(theApp.m_icuString.ToLowerStringEx(findStr));
  1037. findLow.MakeLower();
  1038. int preLength = preInsert.GetLength();
  1039. int postLength = postInsert.GetLength();
  1040. int x = mainLow.Find(findLow, 0);
  1041. while(TRUE)
  1042. {
  1043. foundPos = mainLow.Find(findLow, startFindPos);
  1044. if (foundPos < 0)
  1045. break;
  1046. if (replaceCount == 0)
  1047. {
  1048. firstFindPos = foundPos + preLength;
  1049. }
  1050. newPos = foundPos + insertedLength;
  1051. mainStr.Insert(newPos, preInsert);
  1052. mainStr.Insert(newPos + preLength + oldLen, postInsert);
  1053. startFindPos = foundPos + oldLen;
  1054. insertedLength += preLength + postLength;
  1055. replaceCount++;
  1056. //safety check, make sure we don't look forever
  1057. if (replaceCount > 100)
  1058. break;
  1059. }
  1060. startFindPos = 0;
  1061. int line = 0;
  1062. int prevLinePos = 0;
  1063. int prevPrevLinePos = 0;
  1064. while (TRUE)
  1065. {
  1066. foundPos = mainStr.Find(_T("\n"), startFindPos);
  1067. if (foundPos < 0)
  1068. break;
  1069. if (firstFindPos < foundPos)
  1070. {
  1071. if (line > linesPerRow - 1)
  1072. {
  1073. int lineStart = prevLinePos;
  1074. if (linesPerRow > 1)
  1075. {
  1076. lineStart = prevPrevLinePos;
  1077. }
  1078. mainStr = _T("... ") + mainStr.Mid(lineStart + 1);
  1079. }
  1080. break;
  1081. }
  1082. startFindPos = foundPos + 1;
  1083. prevPrevLinePos = prevLinePos;
  1084. prevLinePos = foundPos;
  1085. line++;
  1086. //safety check, make sure we don't look forever
  1087. if (line > 1000)
  1088. break;
  1089. }
  1090. if(replaceCount > 0)
  1091. {
  1092. //use unprintable characters so it doesn't find copied html to convert
  1093. mainStr.Replace(_T("\r\n"), _T("\x01\x05\x02"));
  1094. int l = mainStr.Replace(_T("\r"), _T("\x01\x05\x02"));
  1095. int m = mainStr.Replace(_T("\n"), _T("\x01\x05\x02"));
  1096. }
  1097. }
  1098. return replaceCount;
  1099. }
  1100. void OnInitMenuPopupEx(CMenu *pPopupMenu, UINT nIndex, BOOL bSysMenu, CWnd *pWnd)
  1101. {
  1102. ASSERT(pPopupMenu != NULL);
  1103. // Check the enabled state of various menu items.
  1104. CCmdUI state;
  1105. state.m_pMenu = pPopupMenu;
  1106. ASSERT(state.m_pOther == NULL);
  1107. ASSERT(state.m_pParentMenu == NULL);
  1108. // Determine if menu is popup in top-level menu and set m_pOther to
  1109. // it if so (m_pParentMenu == NULL indicates that it is secondary popup).
  1110. HMENU hParentMenu;
  1111. if (AfxGetThreadState()->m_hTrackingMenu == pPopupMenu->m_hMenu)
  1112. {
  1113. state.m_pParentMenu = pPopupMenu; // Parent == child for tracking popup.
  1114. }
  1115. else if ((hParentMenu = ::GetMenu(pWnd->m_hWnd)) != NULL)
  1116. {
  1117. CWnd* pParent = pWnd;
  1118. // Child windows don't have menus--need to go to the top!
  1119. if (pParent != NULL &&
  1120. (hParentMenu = ::GetMenu(pParent->m_hWnd)) != NULL)
  1121. {
  1122. int nIndexMax = ::GetMenuItemCount(hParentMenu);
  1123. for (int nIndex = 0; nIndex < nIndexMax; nIndex++)
  1124. {
  1125. if (::GetSubMenu(hParentMenu, nIndex) == pPopupMenu->m_hMenu)
  1126. {
  1127. // When popup is found, m_pParentMenu is containing menu.
  1128. state.m_pParentMenu = CMenu::FromHandle(hParentMenu);
  1129. break;
  1130. }
  1131. }
  1132. }
  1133. }
  1134. state.m_nIndexMax = pPopupMenu->GetMenuItemCount();
  1135. for (state.m_nIndex = 0; state.m_nIndex < state.m_nIndexMax;
  1136. state.m_nIndex++)
  1137. {
  1138. state.m_nID = pPopupMenu->GetMenuItemID(state.m_nIndex);
  1139. if (state.m_nID == 0)
  1140. continue; // Menu separator or invalid cmd - ignore it.
  1141. ASSERT(state.m_pOther == NULL);
  1142. ASSERT(state.m_pMenu != NULL);
  1143. if (state.m_nID == (UINT)-1)
  1144. {
  1145. // Possibly a popup menu, route to first item of that popup.
  1146. state.m_pSubMenu = pPopupMenu->GetSubMenu(state.m_nIndex);
  1147. if (state.m_pSubMenu == NULL ||
  1148. (state.m_nID = state.m_pSubMenu->GetMenuItemID(0)) == 0 ||
  1149. state.m_nID == (UINT)-1)
  1150. {
  1151. continue; // First item of popup can't be routed to.
  1152. }
  1153. state.DoUpdate(pWnd, TRUE); // Popups are never auto disabled.
  1154. }
  1155. else
  1156. {
  1157. // Normal menu item.
  1158. // Auto enable/disable if frame window has m_bAutoMenuEnable
  1159. // set and command is _not_ a system command.
  1160. state.m_pSubMenu = NULL;
  1161. state.DoUpdate(pWnd, FALSE);
  1162. }
  1163. // Adjust for menu deletions and additions.
  1164. UINT nCount = pPopupMenu->GetMenuItemCount();
  1165. if (nCount < state.m_nIndexMax)
  1166. {
  1167. state.m_nIndex -= (state.m_nIndexMax - nCount);
  1168. while (state.m_nIndex < nCount &&
  1169. pPopupMenu->GetMenuItemID(state.m_nIndex) == state.m_nID)
  1170. {
  1171. state.m_nIndex++;
  1172. }
  1173. }
  1174. state.m_nIndexMax = nCount;
  1175. }
  1176. }
  1177. CString InternetEncode(CString text)
  1178. {
  1179. CString ret = _T("");
  1180. LPTSTR lpOutputBuffer = new TCHAR[1];
  1181. DWORD dwSize = 1;
  1182. BOOL fRes = ::InternetCanonicalizeUrl(text, lpOutputBuffer, &dwSize, ICU_BROWSER_MODE);
  1183. DWORD dwError = ::GetLastError();
  1184. if (!fRes && dwError == ERROR_INSUFFICIENT_BUFFER)
  1185. {
  1186. delete lpOutputBuffer;
  1187. lpOutputBuffer = new TCHAR[dwSize];
  1188. fRes = ::InternetCanonicalizeUrl(text, lpOutputBuffer, &dwSize, ICU_BROWSER_MODE);
  1189. if (fRes)
  1190. {
  1191. ret = lpOutputBuffer;
  1192. //lpOutputBuffer has decoded url
  1193. }
  1194. else
  1195. {
  1196. //failed to decode
  1197. }
  1198. if (lpOutputBuffer != NULL)
  1199. {
  1200. delete [] lpOutputBuffer;
  1201. lpOutputBuffer = NULL;
  1202. }
  1203. }
  1204. else
  1205. {
  1206. //some other error OR the input string url is just 1 char and was successfully decoded
  1207. }
  1208. return ret;
  1209. }
  1210. void DeleteParamFromRTF(CStringA &test, CStringA find, bool searchForTrailingDigits)
  1211. {
  1212. int start = 0;
  1213. while (start >= 0)
  1214. {
  1215. start = test.Find(find, start);
  1216. if (start >= 0)
  1217. {
  1218. if (start > 0)
  1219. {
  1220. //leave it if the preceding character is \\, i was seeing the double slash if the actual text contained slash
  1221. if (test[start - 1] == '\\')
  1222. {
  1223. start++;
  1224. continue;
  1225. }
  1226. }
  1227. int end = -1;
  1228. int innerStart = start + find.GetLength();
  1229. if (searchForTrailingDigits)
  1230. {
  1231. for (int i = innerStart; i < test.GetLength(); i++)
  1232. {
  1233. if (isdigit(test[i]) == false)
  1234. {
  1235. end = i;
  1236. break;
  1237. }
  1238. }
  1239. }
  1240. else
  1241. {
  1242. end = innerStart;
  1243. }
  1244. if (end > 0)
  1245. {
  1246. if (searchForTrailingDigits == false ||
  1247. end != innerStart)
  1248. {
  1249. test.Delete(start, (end - start));
  1250. }
  1251. else
  1252. {
  1253. start++;
  1254. }
  1255. }
  1256. else
  1257. {
  1258. break;
  1259. }
  1260. }
  1261. }
  1262. }
  1263. bool RemoveRTFSection(CStringA &str, CStringA section)
  1264. {
  1265. bool removedSection = false;
  1266. int start2 = str.Find(section, 0);
  1267. int end2 = 0;
  1268. if (start2 >= 0)
  1269. {
  1270. int in = 0;
  1271. for (int pos = start2+1; pos < str.GetLength(); pos++)
  1272. {
  1273. if (str[pos] == '{')
  1274. {
  1275. in++;
  1276. }
  1277. if (str[pos] == '}')
  1278. {
  1279. if (in > 0)
  1280. {
  1281. in--;
  1282. }
  1283. else
  1284. {
  1285. end2 = pos;
  1286. break;
  1287. }
  1288. }
  1289. }
  1290. if (end2 > start2)
  1291. {
  1292. str.Delete(start2, (end2 - start2) + 1);
  1293. removedSection = true;
  1294. }
  1295. }
  1296. return removedSection;
  1297. }
  1298. CString NewGuidString()
  1299. {
  1300. CString guidString;
  1301. GUID guid;
  1302. CoCreateGuid(&guid);
  1303. guidString.Format(_T("%08lX-%04hX-%04hX-%02hhX%02hhX-%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX"),
  1304. guid.Data1, guid.Data2, guid.Data3,
  1305. guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
  1306. guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
  1307. return guidString;
  1308. }
  1309. CString FolderPath(int folderId)
  1310. {
  1311. CString folder = _T("");
  1312. if (folderId > 0)
  1313. {
  1314. try
  1315. {
  1316. CStringArray arr;
  1317. for (int i = 0; i < 100; i++)
  1318. {
  1319. CppSQLite3Query parent = theApp.m_db.execQueryEx(_T("SELECT lID, mText, lParentID FROM Main WHERE lID = %d"), folderId);
  1320. if (parent.eof() == false)
  1321. {
  1322. arr.Add(parent.getStringField(_T("mText")));
  1323. folderId = parent.getIntField(_T("lParentID"));
  1324. }
  1325. else
  1326. {
  1327. break;
  1328. }
  1329. }
  1330. folder = _T("Group Path: \\");
  1331. for (int folderPos = arr.GetCount() - 1; folderPos >= 0; folderPos--)
  1332. {
  1333. folder += _T("\\");
  1334. folder += arr[folderPos];
  1335. }
  1336. }
  1337. CATCH_SQLITE_EXCEPTION
  1338. }
  1339. return folder;
  1340. }
  1341. BOOL DarkAppWindows10Setting()
  1342. {
  1343. BOOL darkMode = false;
  1344. HKEY hkKey;
  1345. long lResult = ::RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"), NULL, KEY_READ, &hkKey);
  1346. if (lResult == ERROR_SUCCESS)
  1347. {
  1348. DWORD buffer;
  1349. DWORD len = sizeof(buffer);
  1350. DWORD type;
  1351. lResult = ::RegQueryValueEx(hkKey, _T("AppsUseLightTheme"), 0, &type, (LPBYTE)&buffer, &len);
  1352. if (lResult == ERROR_SUCCESS)
  1353. {
  1354. darkMode = (buffer == 0);
  1355. }
  1356. RegCloseKey(hkKey);
  1357. }
  1358. return darkMode;
  1359. }
  1360. DWORD Windows10AccentColor()
  1361. {
  1362. DWORD color = -1;
  1363. BOOL darkMode = false;
  1364. HKEY hkKey;
  1365. long lResult = ::RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\DWM"), NULL, KEY_READ, &hkKey);
  1366. if (lResult == ERROR_SUCCESS)
  1367. {
  1368. DWORD buffer;
  1369. DWORD len = sizeof(buffer);
  1370. DWORD type;
  1371. lResult = ::RegQueryValueEx(hkKey, _T("ColorizationColor"), 0, &type, (LPBYTE)&buffer, &len);
  1372. if (lResult == ERROR_SUCCESS)
  1373. {
  1374. color = buffer;
  1375. }
  1376. RegCloseKey(hkKey);
  1377. }
  1378. return color;
  1379. }
  1380. BOOL Windows10ColorTitleBar()
  1381. {
  1382. BOOL colorTitleBar = FALSE;
  1383. BOOL darkMode = false;
  1384. HKEY hkKey;
  1385. long lResult = ::RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\DWM"), NULL, KEY_READ, &hkKey);
  1386. if (lResult == ERROR_SUCCESS)
  1387. {
  1388. DWORD buffer;
  1389. DWORD len = sizeof(buffer);
  1390. DWORD type;
  1391. lResult = ::RegQueryValueEx(hkKey, _T("ColorPrevalence"), 0, &type, (LPBYTE)&buffer, &len);
  1392. if (lResult == ERROR_SUCCESS)
  1393. {
  1394. colorTitleBar = (buffer == 1);
  1395. }
  1396. RegCloseKey(hkKey);
  1397. }
  1398. return colorTitleBar;
  1399. }
  1400. BOOL RestoreDbPrompt(HWND hwnd)
  1401. {
  1402. BOOL ret = false;
  1403. OPENFILENAME ofn;
  1404. TCHAR szFile[400];
  1405. TCHAR szDir[400];
  1406. memset(&szFile, 0, sizeof(szFile));
  1407. memset(szDir, 0, sizeof(szDir));
  1408. memset(&ofn, 0, sizeof(ofn));
  1409. ofn.lStructSize = sizeof(OPENFILENAME);
  1410. ofn.hwndOwner = hwnd;
  1411. ofn.lpstrFile = szFile;
  1412. ofn.nMaxFile = sizeof(szFile);
  1413. ofn.lpstrFilter = _T("Ditto database backups (.zdb)\0*.zdb\0\0");
  1414. ofn.nFilterIndex = 1;
  1415. ofn.lpstrFileTitle = NULL;
  1416. ofn.nMaxFileTitle = 0;
  1417. //ofn.lpstrInitialDir = szDir;
  1418. ofn.lpstrDefExt = _T("zdb");
  1419. ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR;
  1420. if (GetOpenFileName(&ofn))
  1421. {
  1422. CWaitCursor wait;
  1423. CString dbPath = CGetSetOptions::GetDBPath();
  1424. CString backupPath(ofn.lpstrFile);
  1425. ret = RestoreDB(backupPath);
  1426. }
  1427. return ret;
  1428. }
  1429. BOOL BackupDbPrompt(HWND hwnd)
  1430. {
  1431. BOOL ret = FALSE;
  1432. OPENFILENAME ofn;
  1433. TCHAR szFile[400];
  1434. TCHAR szDir[400];
  1435. memset(&szFile, 0, sizeof(szFile));
  1436. memset(szDir, 0, sizeof(szDir));
  1437. memset(&ofn, 0, sizeof(ofn));
  1438. ofn.lStructSize = sizeof(OPENFILENAME);
  1439. ofn.hwndOwner = hwnd;
  1440. ofn.lpstrFile = szFile;
  1441. ofn.nMaxFile = sizeof(szFile);
  1442. ofn.lpstrFilter = _T("Ditto database backups (.zdb)\0*.zdb\0\0");
  1443. ofn.nFilterIndex = 1;
  1444. ofn.lpstrFileTitle = NULL;
  1445. ofn.nMaxFileTitle = 0;
  1446. //ofn.lpstrInitialDir = szDir;
  1447. ofn.lpstrDefExt = _T("zdb");
  1448. ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR;
  1449. if (GetSaveFileName(&ofn))
  1450. {
  1451. CWaitCursor wait;
  1452. CString dbPath = CGetSetOptions::GetDBPath();
  1453. CString backupPath(ofn.lpstrFile);
  1454. ret = BackupDB(dbPath, backupPath);
  1455. }
  1456. return ret;
  1457. }
  1458. int WordCount(const CString &text)
  1459. {
  1460. #define OUT 0
  1461. #define IN 1
  1462. int state = OUT;
  1463. unsigned wc = 0; // word count
  1464. // Scan all characters one by one
  1465. for(int pos = 0; pos < text.GetLength(); pos++)
  1466. {
  1467. auto str = text[pos];
  1468. if (str == ' ' || str == '\r' || str == '\n' || str == '\t')
  1469. {
  1470. state = OUT;
  1471. }
  1472. else if (state == OUT)
  1473. {
  1474. state = IN;
  1475. wc++;
  1476. }
  1477. }
  1478. return wc;
  1479. }
  1480. CString GetVersionString(VersionInfo version)
  1481. {
  1482. CString csLine;
  1483. csLine.Format(_T("%02i.%02i.%02i.%02i"),
  1484. version.Major,
  1485. version.Minor,
  1486. version.Revision,
  1487. version.Build);
  1488. return csLine;
  1489. }
  1490. VersionInfo GetRunningVersion()
  1491. {
  1492. VersionInfo verInfo;
  1493. CString csFileName = CGetSetOptions::GetExeFileName();
  1494. DWORD dwSize, dwHandle;
  1495. LPBYTE lpData;
  1496. UINT iBuffSize;
  1497. VS_FIXEDFILEINFO* lpFFI;
  1498. dwSize = GetFileVersionInfoSize(csFileName.GetBuffer(csFileName.GetLength()), &dwHandle);
  1499. if (dwSize != 0)
  1500. {
  1501. csFileName.ReleaseBuffer();
  1502. if ((lpData = (unsigned char*)malloc(dwSize)) != NULL)
  1503. {
  1504. if (GetFileVersionInfo(csFileName.GetBuffer(csFileName.GetLength()), dwHandle, dwSize, lpData) != 0)
  1505. {
  1506. if (VerQueryValue(lpData, _T("\\"), (LPVOID*)&lpFFI, &iBuffSize) != 0)
  1507. {
  1508. if (iBuffSize > 0)
  1509. {
  1510. verInfo.Major = (lpFFI->dwProductVersionMS >> 16) & 0xffff;
  1511. verInfo.Minor = (lpFFI->dwProductVersionMS >> 0) & 0xffff;
  1512. verInfo.Revision = (lpFFI->dwProductVersionLS >> 16) & 0xffff;
  1513. verInfo.Build = (lpFFI->dwProductVersionLS >> 0) & 0xffff;
  1514. }
  1515. }
  1516. }
  1517. free(lpData);
  1518. }
  1519. }
  1520. return(verInfo);
  1521. }