Misc.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736
  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(!g_Opt.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(g_Opt.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. int k = 0;
  673. }
  674. CClip clip;
  675. if(clip.LoadFormats(parentID))
  676. {
  677. DWORD CRC = clip.GenerateCRC();
  678. //Update the main table with new size
  679. theApp.m_db.execDMLEx(_T("UPDATE Main SET CRC = %d WHERE lID = %d"), CRC, parentID);
  680. }
  681. }
  682. CATCH_SQLITE_EXCEPTION
  683. return TRUE;
  684. }
  685. CRect CenterRect(CRect startingRect)
  686. {
  687. CRect crMonitor;
  688. HMONITOR monitorHandle = MonitorFromPoint(startingRect.TopLeft(), MONITOR_DEFAULTTONEAREST);
  689. if (monitorHandle == NULL)
  690. {
  691. monitorHandle = MonitorFromPoint(startingRect.TopLeft(), MONITOR_DEFAULTTOPRIMARY);
  692. MONITORINFO lpmi;
  693. lpmi.cbSize = sizeof(MONITORINFO);
  694. if (GetMonitorInfo(monitorHandle, &lpmi))
  695. {
  696. crMonitor.CopyRect(&lpmi.rcWork);
  697. }
  698. }
  699. else
  700. {
  701. MONITORINFO lpmi;
  702. lpmi.cbSize = sizeof(MONITORINFO);
  703. if (GetMonitorInfo(monitorHandle, &lpmi))
  704. {
  705. crMonitor.CopyRect(&lpmi.rcWork);
  706. }
  707. }
  708. return CenterRectFromRect(startingRect, crMonitor);
  709. }
  710. CRect CenterRectFromRect(CRect startingRect, CRect outerRect)
  711. {
  712. CPoint center = outerRect.CenterPoint();
  713. CRect centerRect;
  714. centerRect.left = center.x - (startingRect.Width() / 2);
  715. centerRect.top = center.y - (startingRect.Height() / 2);
  716. centerRect.right = centerRect.left + startingRect.Width();
  717. centerRect.bottom = centerRect.top + startingRect.Height();
  718. return centerRect;
  719. }
  720. CRect DefaultMonitorRect()
  721. {
  722. CRect crMonitor;
  723. CRect invalidRect(INT32_MAX, INT32_MAX, INT32_MAX, INT32_MAX);
  724. HMONITOR monitorHandle = MonitorFromPoint(invalidRect.TopLeft(), MONITOR_DEFAULTTOPRIMARY);
  725. MONITORINFO lpmi;
  726. lpmi.cbSize = sizeof(MONITORINFO);
  727. if (GetMonitorInfo(monitorHandle, &lpmi))
  728. {
  729. crMonitor.CopyRect(&lpmi.rcWork);
  730. }
  731. return crMonitor;
  732. }
  733. CRect MonitorRectFromRect(CRect rect)
  734. {
  735. BOOL ret = FALSE;
  736. CRect crMonitor;
  737. HMONITOR monitorHandle = MonitorFromPoint(rect.TopLeft(), MONITOR_DEFAULTTONEAREST);
  738. if (monitorHandle == NULL)
  739. {
  740. monitorHandle = MonitorFromPoint(rect.TopLeft(), MONITOR_DEFAULTTOPRIMARY);
  741. MONITORINFO lpmi;
  742. lpmi.cbSize = sizeof(MONITORINFO);
  743. if (GetMonitorInfo(monitorHandle, &lpmi))
  744. {
  745. crMonitor.CopyRect(&lpmi.rcWork);
  746. }
  747. }
  748. else
  749. {
  750. MONITORINFO lpmi;
  751. lpmi.cbSize = sizeof(MONITORINFO);
  752. if (GetMonitorInfo(monitorHandle, &lpmi))
  753. {
  754. crMonitor.CopyRect(&lpmi.rcWork);
  755. }
  756. }
  757. return crMonitor;
  758. }
  759. BOOL EnsureWindowVisible(CRect *pcrRect)
  760. {
  761. BOOL ret = FALSE;
  762. CRect crMonitor;
  763. HMONITOR monitorHandle = MonitorFromRect(pcrRect, MONITOR_DEFAULTTONEAREST);
  764. if (monitorHandle == NULL)
  765. {
  766. monitorHandle = MonitorFromRect(pcrRect, MONITOR_DEFAULTTOPRIMARY);
  767. MONITORINFO lpmi;
  768. lpmi.cbSize = sizeof(MONITORINFO);
  769. if (GetMonitorInfo(monitorHandle, &lpmi))
  770. {
  771. crMonitor.CopyRect(&lpmi.rcWork);
  772. *pcrRect = CenterRectFromRect(*pcrRect, crMonitor);
  773. }
  774. }
  775. else
  776. {
  777. MONITORINFO lpmi;
  778. lpmi.cbSize = sizeof(MONITORINFO);
  779. if (GetMonitorInfo(monitorHandle, &lpmi))
  780. {
  781. crMonitor.CopyRect(&lpmi.rcWork);
  782. }
  783. }
  784. bool movedLeft = false;
  785. //Validate the left
  786. long lDiff = pcrRect->left - crMonitor.left;
  787. if (lDiff < 0)
  788. {
  789. pcrRect->left += abs(lDiff);
  790. pcrRect->right += abs(lDiff);
  791. ret = TRUE;
  792. movedLeft = true;
  793. }
  794. //Right side
  795. lDiff = pcrRect->right - crMonitor.right;
  796. if (lDiff > 0)
  797. {
  798. if (movedLeft == false)
  799. {
  800. pcrRect->left -= abs(lDiff);
  801. }
  802. pcrRect->right -= abs(lDiff);
  803. ret = TRUE;
  804. }
  805. bool movedTop = false;
  806. //Top
  807. lDiff = pcrRect->top - crMonitor.top;
  808. if (lDiff < 0)
  809. {
  810. pcrRect->top += abs(lDiff);
  811. pcrRect->bottom += abs(lDiff);
  812. ret = TRUE;
  813. movedTop = true;
  814. }
  815. //Bottom
  816. lDiff = pcrRect->bottom - crMonitor.bottom;
  817. if (lDiff > 0)
  818. {
  819. if (movedTop == false)
  820. {
  821. pcrRect->top -= abs(lDiff);
  822. }
  823. pcrRect->bottom -= abs(lDiff);
  824. ret = TRUE;
  825. }
  826. return ret;
  827. }
  828. __int64 GetLastWriteTime(const CString &csFile)
  829. {
  830. __int64 nLastWrite = 0;
  831. CFileFind finder;
  832. BOOL bResult = finder.FindFile(csFile);
  833. if (bResult)
  834. {
  835. finder.FindNextFile();
  836. FILETIME ft;
  837. finder.GetLastWriteTime(&ft);
  838. memcpy(&nLastWrite, &ft, sizeof(ft));
  839. }
  840. return nLastWrite;
  841. }
  842. typedef struct
  843. {
  844. DWORD ownerpid;
  845. DWORD childpid;
  846. } windowinfo;
  847. BOOL CALLBACK EnumChildWindowsCallback(HWND hWnd, LPARAM lp)
  848. {
  849. windowinfo* info = (windowinfo*)lp;
  850. DWORD pid = 0;
  851. GetWindowThreadProcessId(hWnd, &pid);
  852. if (pid != info->ownerpid)
  853. info->childpid = pid;
  854. return TRUE;
  855. }
  856. CString UWP_AppName(HWND active_window, DWORD ownerpid)
  857. {
  858. CString uwpAppName;
  859. windowinfo info = { 0 };
  860. info.ownerpid = ownerpid;
  861. info.childpid = info.ownerpid;
  862. EnumChildWindows(active_window, EnumChildWindowsCallback, (LPARAM)&info);
  863. HANDLE active_process = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, info.childpid);
  864. if (active_process != NULL)
  865. {
  866. WCHAR image_name[MAX_PATH] = { 0 };
  867. DWORD bufsize = MAX_PATH;
  868. QueryFullProcessImageName(active_process, 0, image_name, &bufsize);
  869. CloseHandle(active_process);
  870. nsPath::CPath path(image_name);
  871. uwpAppName = path.GetName();
  872. }
  873. return uwpAppName;
  874. }
  875. CString GetProcessName(HWND hWnd, DWORD processId)
  876. {
  877. DWORD startTick = GetTickCount();
  878. CString strProcessName;
  879. DWORD Id = processId;
  880. if (Id == 0)
  881. {
  882. GetWindowThreadProcessId(hWnd, &Id);
  883. }
  884. HANDLE active_process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, Id);
  885. if (active_process != NULL)
  886. {
  887. WCHAR image_name[MAX_PATH] = { 0 };
  888. DWORD bufsize = MAX_PATH;
  889. QueryFullProcessImageName(active_process, 0, image_name, &bufsize);
  890. CloseHandle(active_process);
  891. nsPath::CPath path(image_name);
  892. strProcessName = path.GetName();
  893. }
  894. if (strProcessName == _T(""))
  895. {
  896. Log(StrF(_T("failed to get process name from open process, LastError: %d, looping over process names to find process"), GetLastError()));
  897. PROCESSENTRY32 processEntry = { 0 };
  898. HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  899. processEntry.dwSize = sizeof(PROCESSENTRY32);
  900. if (Process32First(hSnapShot, &processEntry))
  901. {
  902. do
  903. {
  904. if (processEntry.th32ProcessID == Id)
  905. {
  906. strProcessName = processEntry.szExeFile;
  907. break;
  908. }
  909. } while (Process32Next(hSnapShot, &processEntry));
  910. }
  911. CloseHandle(hSnapShot);
  912. }
  913. //uwp apps are wrapped in another app called, if this has focus then try and find the child uwp process
  914. if (strProcessName == _T("ApplicationFrameHost.exe"))
  915. {
  916. strProcessName = UWP_AppName(hWnd, Id);
  917. }
  918. DWORD endTick = GetTickCount();
  919. DWORD diff = endTick - startTick;
  920. if(diff > 5)
  921. {
  922. Log(StrF(_T("GetProcessName Time (ms): %d, pid: %d, name: %s"), endTick-startTick, Id, strProcessName));
  923. }
  924. return strProcessName;
  925. }
  926. BOOL IsVista()
  927. {
  928. OSVERSIONINFO osver;
  929. osver.dwOSVersionInfoSize = sizeof( OSVERSIONINFO );
  930. if (::GetVersionEx( &osver ) &&
  931. osver.dwPlatformId == VER_PLATFORM_WIN32_NT &&
  932. (osver.dwMajorVersion >= 6 ) )
  933. {
  934. return TRUE;
  935. }
  936. return FALSE;
  937. }
  938. bool IsRunningLimited()
  939. {
  940. LPCTSTR pszSubKey = _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System");
  941. LPCTSTR pszValue = _T("EnableLUA");
  942. DWORD dwType = 0;
  943. DWORD dwValue = 0;
  944. DWORD dwValueSize = sizeof(DWORD);
  945. if(ERROR_SUCCESS != SHGetValue(HKEY_LOCAL_MACHINE, pszSubKey, pszValue, &dwType, &dwValue, &dwValueSize))
  946. {
  947. //failed to read the reg key, either it's not there or we don't have access to the registry
  948. //If we are vista then assume we don't have access and we are running as a limited app
  949. //otherwise we are xp and the reg key probably doesn't exist and we are not a limited running app
  950. if(IsVista())
  951. {
  952. OutputDebugString(_T("Ditto - Failed to read registry entry finding UAC, Running as limited application"));
  953. return true;
  954. }
  955. }
  956. if(dwValue == 1)
  957. {
  958. OutputDebugString(_T("Ditto - UAC ENABLED, Running as limited application"));
  959. return true;
  960. }
  961. OutputDebugString(_T("Ditto - Running as standard application"));
  962. return false;
  963. }
  964. void DeleteDittoTempFiles(BOOL checkFileLastAccess)
  965. {
  966. CString csDir = CGetSetOptions::GetPath(PATH_REMOTE_FILES);
  967. if (FileExists(csDir))
  968. {
  969. DeleteFolderFiles(csDir, checkFileLastAccess);
  970. }
  971. csDir = CGetSetOptions::GetPath(PATH_DRAG_FILES);
  972. if (FileExists(csDir))
  973. {
  974. DeleteFolderFiles(csDir, checkFileLastAccess);
  975. }
  976. csDir = CGetSetOptions::GetPath(PATH_CLIP_DIFF);
  977. if (FileExists(csDir))
  978. {
  979. DeleteFolderFiles(csDir, checkFileLastAccess);
  980. }
  981. }
  982. void DeleteFolderFiles(CString csDir, BOOL checkFileLastAccess)
  983. {
  984. if (csDir.Find(_T("\\ReceivedFiles\\")) == -1 && csDir.Find(_T("\\DragFiles\\")) == -1 && csDir.Find(_T("ClipCompare")) == -1)
  985. return;
  986. Log(StrF(_T("Deleting files in Folder %s Check Last Access %d"), csDir, checkFileLastAccess));
  987. FIX_CSTRING_PATH(csDir);
  988. CTime ctOld = CTime::GetCurrentTime();
  989. CTime ctFile;
  990. ctOld -= CTimeSpan(0, 0, 0, 1);
  991. CFileFind Find;
  992. CString csFindString;
  993. csFindString.Format(_T("%s*.*"), csDir);
  994. BOOL bFound = Find.FindFile(csFindString);
  995. while(bFound)
  996. {
  997. bFound = Find.FindNextFile();
  998. if(Find.IsDots())
  999. continue;
  1000. if(Find.IsDirectory())
  1001. {
  1002. CString csDir(Find.GetFilePath());
  1003. DeleteFolderFiles(csDir, checkFileLastAccess);
  1004. RemoveDirectory(csDir);
  1005. }
  1006. if(checkFileLastAccess &&
  1007. Find.GetLastAccessTime(ctFile))
  1008. {
  1009. //Delete the remote copied file if it hasn't been used for the last day
  1010. if(ctFile < ctOld)
  1011. {
  1012. Log(StrF(_T("Deleting temp file %s"), Find.GetFilePath()));
  1013. DeleteFile(Find.GetFilePath());
  1014. }
  1015. }
  1016. else
  1017. {
  1018. Log(StrF(_T("Deleting temp file %s"), Find.GetFilePath()));
  1019. DeleteFile(Find.GetFilePath());
  1020. }
  1021. }
  1022. }
  1023. __int64 FileSize(const TCHAR *fileName)
  1024. {
  1025. struct _stat64 buf;
  1026. if (_wstat64((wchar_t const*)fileName, &buf) != 0)
  1027. return -1; // error, could use errno to find out more
  1028. return buf.st_size;
  1029. }
  1030. int FindNoCaseAndInsert(CString& mainStr, CString& findStr, CString preInsert, CString postInsert, int linesPerRow)
  1031. {
  1032. int replaceCount = 0;
  1033. //Prevent infinite loop when user tries to replace nothing.
  1034. if (findStr != "")
  1035. {
  1036. int oldLen = findStr.GetLength();
  1037. int foundPos = 0;
  1038. int startFindPos = 0;
  1039. int newPos = 0;
  1040. int insertedLength = 0;
  1041. int firstFindPos = 0;
  1042. CString mainLow(theApp.m_icuString.ToLowerStringEx(mainStr));
  1043. CString findLow(theApp.m_icuString.ToLowerStringEx(findStr));
  1044. findLow.MakeLower();
  1045. int preLength = preInsert.GetLength();
  1046. int postLength = postInsert.GetLength();
  1047. int x = mainLow.Find(findLow, 0);
  1048. while(TRUE)
  1049. {
  1050. foundPos = mainLow.Find(findLow, startFindPos);
  1051. if (foundPos < 0)
  1052. break;
  1053. if (replaceCount == 0)
  1054. {
  1055. firstFindPos = foundPos + preLength;
  1056. }
  1057. newPos = foundPos + insertedLength;
  1058. mainStr.Insert(newPos, preInsert);
  1059. mainStr.Insert(newPos + preLength + oldLen, postInsert);
  1060. startFindPos = foundPos + oldLen;
  1061. insertedLength += preLength + postLength;
  1062. replaceCount++;
  1063. //safety check, make sure we don't look forever
  1064. if (replaceCount > 100)
  1065. break;
  1066. }
  1067. startFindPos = 0;
  1068. int line = 0;
  1069. int prevLinePos = 0;
  1070. int prevPrevLinePos = 0;
  1071. while (TRUE)
  1072. {
  1073. foundPos = mainStr.Find(_T("\n"), startFindPos);
  1074. if (foundPos < 0)
  1075. break;
  1076. if (firstFindPos < foundPos)
  1077. {
  1078. if (line > linesPerRow - 1)
  1079. {
  1080. int lineStart = prevLinePos;
  1081. if (linesPerRow > 1)
  1082. {
  1083. lineStart = prevPrevLinePos;
  1084. }
  1085. mainStr = _T("... ") + mainStr.Mid(lineStart + 1);
  1086. }
  1087. break;
  1088. }
  1089. startFindPos = foundPos + 1;
  1090. prevPrevLinePos = prevLinePos;
  1091. prevLinePos = foundPos;
  1092. line++;
  1093. //safety check, make sure we don't look forever
  1094. if (line > 1000)
  1095. break;
  1096. }
  1097. if(replaceCount > 0)
  1098. {
  1099. //use unprintable characters so it doesn't find copied html to convert
  1100. mainStr.Replace(_T("\r\n"), _T("\x01\x05\x02"));
  1101. int l = mainStr.Replace(_T("\r"), _T("\x01\x05\x02"));
  1102. int m = mainStr.Replace(_T("\n"), _T("\x01\x05\x02"));
  1103. }
  1104. }
  1105. return replaceCount;
  1106. }
  1107. void OnInitMenuPopupEx(CMenu *pPopupMenu, UINT nIndex, BOOL bSysMenu, CWnd *pWnd)
  1108. {
  1109. ASSERT(pPopupMenu != NULL);
  1110. // Check the enabled state of various menu items.
  1111. CCmdUI state;
  1112. state.m_pMenu = pPopupMenu;
  1113. ASSERT(state.m_pOther == NULL);
  1114. ASSERT(state.m_pParentMenu == NULL);
  1115. // Determine if menu is popup in top-level menu and set m_pOther to
  1116. // it if so (m_pParentMenu == NULL indicates that it is secondary popup).
  1117. HMENU hParentMenu;
  1118. if (AfxGetThreadState()->m_hTrackingMenu == pPopupMenu->m_hMenu)
  1119. {
  1120. state.m_pParentMenu = pPopupMenu; // Parent == child for tracking popup.
  1121. }
  1122. else if ((hParentMenu = ::GetMenu(pWnd->m_hWnd)) != NULL)
  1123. {
  1124. CWnd* pParent = pWnd;
  1125. // Child windows don't have menus--need to go to the top!
  1126. if (pParent != NULL &&
  1127. (hParentMenu = ::GetMenu(pParent->m_hWnd)) != NULL)
  1128. {
  1129. int nIndexMax = ::GetMenuItemCount(hParentMenu);
  1130. for (int nIndex = 0; nIndex < nIndexMax; nIndex++)
  1131. {
  1132. if (::GetSubMenu(hParentMenu, nIndex) == pPopupMenu->m_hMenu)
  1133. {
  1134. // When popup is found, m_pParentMenu is containing menu.
  1135. state.m_pParentMenu = CMenu::FromHandle(hParentMenu);
  1136. break;
  1137. }
  1138. }
  1139. }
  1140. }
  1141. state.m_nIndexMax = pPopupMenu->GetMenuItemCount();
  1142. for (state.m_nIndex = 0; state.m_nIndex < state.m_nIndexMax;
  1143. state.m_nIndex++)
  1144. {
  1145. state.m_nID = pPopupMenu->GetMenuItemID(state.m_nIndex);
  1146. if (state.m_nID == 0)
  1147. continue; // Menu separator or invalid cmd - ignore it.
  1148. ASSERT(state.m_pOther == NULL);
  1149. ASSERT(state.m_pMenu != NULL);
  1150. if (state.m_nID == (UINT)-1)
  1151. {
  1152. // Possibly a popup menu, route to first item of that popup.
  1153. state.m_pSubMenu = pPopupMenu->GetSubMenu(state.m_nIndex);
  1154. if (state.m_pSubMenu == NULL ||
  1155. (state.m_nID = state.m_pSubMenu->GetMenuItemID(0)) == 0 ||
  1156. state.m_nID == (UINT)-1)
  1157. {
  1158. continue; // First item of popup can't be routed to.
  1159. }
  1160. state.DoUpdate(pWnd, TRUE); // Popups are never auto disabled.
  1161. }
  1162. else
  1163. {
  1164. // Normal menu item.
  1165. // Auto enable/disable if frame window has m_bAutoMenuEnable
  1166. // set and command is _not_ a system command.
  1167. state.m_pSubMenu = NULL;
  1168. state.DoUpdate(pWnd, FALSE);
  1169. }
  1170. // Adjust for menu deletions and additions.
  1171. UINT nCount = pPopupMenu->GetMenuItemCount();
  1172. if (nCount < state.m_nIndexMax)
  1173. {
  1174. state.m_nIndex -= (state.m_nIndexMax - nCount);
  1175. while (state.m_nIndex < nCount &&
  1176. pPopupMenu->GetMenuItemID(state.m_nIndex) == state.m_nID)
  1177. {
  1178. state.m_nIndex++;
  1179. }
  1180. }
  1181. state.m_nIndexMax = nCount;
  1182. }
  1183. }
  1184. CString InternetEncode(CString text)
  1185. {
  1186. CString ret = _T("");
  1187. LPTSTR lpOutputBuffer = new TCHAR[1];
  1188. DWORD dwSize = 1;
  1189. BOOL fRes = ::InternetCanonicalizeUrl(text, lpOutputBuffer, &dwSize, ICU_BROWSER_MODE);
  1190. DWORD dwError = ::GetLastError();
  1191. if (!fRes && dwError == ERROR_INSUFFICIENT_BUFFER)
  1192. {
  1193. delete lpOutputBuffer;
  1194. lpOutputBuffer = new TCHAR[dwSize];
  1195. fRes = ::InternetCanonicalizeUrl(text, lpOutputBuffer, &dwSize, ICU_BROWSER_MODE);
  1196. if (fRes)
  1197. {
  1198. ret = lpOutputBuffer;
  1199. //lpOutputBuffer has decoded url
  1200. }
  1201. else
  1202. {
  1203. //failed to decode
  1204. }
  1205. if (lpOutputBuffer != NULL)
  1206. {
  1207. delete [] lpOutputBuffer;
  1208. lpOutputBuffer = NULL;
  1209. }
  1210. }
  1211. else
  1212. {
  1213. //some other error OR the input string url is just 1 char and was successfully decoded
  1214. }
  1215. return ret;
  1216. }
  1217. void DeleteParamFromRTF(CStringA &test, CStringA find, bool searchForTrailingDigits)
  1218. {
  1219. int start = 0;
  1220. while (start >= 0)
  1221. {
  1222. start = test.Find(find, start);
  1223. if (start >= 0)
  1224. {
  1225. if (start > 0)
  1226. {
  1227. //leave it if the preceding character is \\, i was seeing the double slash if the actual text contained slash
  1228. if (test[start - 1] == '\\')
  1229. {
  1230. start++;
  1231. continue;
  1232. }
  1233. }
  1234. int end = -1;
  1235. int innerStart = start + find.GetLength();
  1236. if (searchForTrailingDigits)
  1237. {
  1238. for (int i = innerStart; i < test.GetLength(); i++)
  1239. {
  1240. if (isdigit(test[i]) == false)
  1241. {
  1242. end = i;
  1243. break;
  1244. }
  1245. }
  1246. }
  1247. else
  1248. {
  1249. end = innerStart;
  1250. }
  1251. if (end > 0)
  1252. {
  1253. if (searchForTrailingDigits == false ||
  1254. end != innerStart)
  1255. {
  1256. test.Delete(start, (end - start));
  1257. }
  1258. else
  1259. {
  1260. start++;
  1261. }
  1262. }
  1263. else
  1264. {
  1265. break;
  1266. }
  1267. }
  1268. }
  1269. }
  1270. bool RemoveRTFSection(CStringA &str, CStringA section)
  1271. {
  1272. bool removedSection = false;
  1273. int start2 = str.Find(section, 0);
  1274. int end2 = 0;
  1275. if (start2 >= 0)
  1276. {
  1277. int in = 0;
  1278. for (int pos = start2+1; pos < str.GetLength(); pos++)
  1279. {
  1280. if (str[pos] == '{')
  1281. {
  1282. in++;
  1283. }
  1284. if (str[pos] == '}')
  1285. {
  1286. if (in > 0)
  1287. {
  1288. in--;
  1289. }
  1290. else
  1291. {
  1292. end2 = pos;
  1293. break;
  1294. }
  1295. }
  1296. }
  1297. if (end2 > start2)
  1298. {
  1299. str.Delete(start2, (end2 - start2) + 1);
  1300. removedSection = true;
  1301. }
  1302. }
  1303. return removedSection;
  1304. }
  1305. CString NewGuidString()
  1306. {
  1307. CString guidString;
  1308. GUID guid;
  1309. CoCreateGuid(&guid);
  1310. guidString.Format(_T("%08lX-%04hX-%04hX-%02hhX%02hhX-%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX"),
  1311. guid.Data1, guid.Data2, guid.Data3,
  1312. guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
  1313. guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
  1314. return guidString;
  1315. }
  1316. CString FolderPath(int folderId)
  1317. {
  1318. CString folder = _T("");
  1319. if (folderId > 0)
  1320. {
  1321. try
  1322. {
  1323. CStringArray arr;
  1324. for (int i = 0; i < 100; i++)
  1325. {
  1326. CppSQLite3Query parent = theApp.m_db.execQueryEx(_T("SELECT lID, mText, lParentID FROM Main WHERE lID = %d"), folderId);
  1327. if (parent.eof() == false)
  1328. {
  1329. arr.Add(parent.getStringField(_T("mText")));
  1330. folderId = parent.getIntField(_T("lParentID"));
  1331. }
  1332. else
  1333. {
  1334. break;
  1335. }
  1336. }
  1337. folder = _T("Group Path: \\");
  1338. for (int folderPos = arr.GetCount() - 1; folderPos >= 0; folderPos--)
  1339. {
  1340. folder += _T("\\");
  1341. folder += arr[folderPos];
  1342. }
  1343. }
  1344. CATCH_SQLITE_EXCEPTION
  1345. }
  1346. return folder;
  1347. }
  1348. BOOL DarkAppWindows10Setting()
  1349. {
  1350. BOOL darkMode = false;
  1351. HKEY hkKey;
  1352. long lResult = ::RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"), NULL, KEY_READ, &hkKey);
  1353. if (lResult == ERROR_SUCCESS)
  1354. {
  1355. DWORD buffer;
  1356. DWORD len = sizeof(buffer);
  1357. DWORD type;
  1358. lResult = ::RegQueryValueEx(hkKey, _T("AppsUseLightTheme"), 0, &type, (LPBYTE)&buffer, &len);
  1359. if (lResult == ERROR_SUCCESS)
  1360. {
  1361. darkMode = (buffer == 0);
  1362. }
  1363. RegCloseKey(hkKey);
  1364. }
  1365. return darkMode;
  1366. }
  1367. DWORD Windows10AccentColor()
  1368. {
  1369. DWORD color = -1;
  1370. BOOL darkMode = false;
  1371. HKEY hkKey;
  1372. long lResult = ::RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\DWM"), NULL, KEY_READ, &hkKey);
  1373. if (lResult == ERROR_SUCCESS)
  1374. {
  1375. DWORD buffer;
  1376. DWORD len = sizeof(buffer);
  1377. DWORD type;
  1378. lResult = ::RegQueryValueEx(hkKey, _T("ColorizationColor"), 0, &type, (LPBYTE)&buffer, &len);
  1379. if (lResult == ERROR_SUCCESS)
  1380. {
  1381. color = buffer;
  1382. }
  1383. RegCloseKey(hkKey);
  1384. }
  1385. return color;
  1386. }
  1387. BOOL Windows10ColorTitleBar()
  1388. {
  1389. BOOL colorTitleBar = FALSE;
  1390. BOOL darkMode = false;
  1391. HKEY hkKey;
  1392. long lResult = ::RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\DWM"), NULL, KEY_READ, &hkKey);
  1393. if (lResult == ERROR_SUCCESS)
  1394. {
  1395. DWORD buffer;
  1396. DWORD len = sizeof(buffer);
  1397. DWORD type;
  1398. lResult = ::RegQueryValueEx(hkKey, _T("ColorPrevalence"), 0, &type, (LPBYTE)&buffer, &len);
  1399. if (lResult == ERROR_SUCCESS)
  1400. {
  1401. colorTitleBar = (buffer == 1);
  1402. }
  1403. RegCloseKey(hkKey);
  1404. }
  1405. return colorTitleBar;
  1406. }
  1407. BOOL RestoreDbPrompt(HWND hwnd)
  1408. {
  1409. BOOL ret = false;
  1410. OPENFILENAME ofn;
  1411. TCHAR szFile[400];
  1412. TCHAR szDir[400];
  1413. memset(&szFile, 0, sizeof(szFile));
  1414. memset(szDir, 0, sizeof(szDir));
  1415. memset(&ofn, 0, sizeof(ofn));
  1416. ofn.lStructSize = sizeof(OPENFILENAME);
  1417. ofn.hwndOwner = hwnd;
  1418. ofn.lpstrFile = szFile;
  1419. ofn.nMaxFile = sizeof(szFile);
  1420. ofn.lpstrFilter = _T("Ditto database backups (.zdb)\0*.zdb\0\0");
  1421. ofn.nFilterIndex = 1;
  1422. ofn.lpstrFileTitle = NULL;
  1423. ofn.nMaxFileTitle = 0;
  1424. //ofn.lpstrInitialDir = szDir;
  1425. ofn.lpstrDefExt = _T("zdb");
  1426. ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR;
  1427. if (GetOpenFileName(&ofn))
  1428. {
  1429. CWaitCursor wait;
  1430. CString dbPath = CGetSetOptions::GetDBPath();
  1431. CString backupPath(ofn.lpstrFile);
  1432. ret = RestoreDB(backupPath);
  1433. }
  1434. return ret;
  1435. }
  1436. BOOL BackupDbPrompt(HWND hwnd)
  1437. {
  1438. BOOL ret = FALSE;
  1439. OPENFILENAME ofn;
  1440. TCHAR szFile[400];
  1441. TCHAR szDir[400];
  1442. memset(&szFile, 0, sizeof(szFile));
  1443. memset(szDir, 0, sizeof(szDir));
  1444. memset(&ofn, 0, sizeof(ofn));
  1445. ofn.lStructSize = sizeof(OPENFILENAME);
  1446. ofn.hwndOwner = hwnd;
  1447. ofn.lpstrFile = szFile;
  1448. ofn.nMaxFile = sizeof(szFile);
  1449. ofn.lpstrFilter = _T("Ditto database backups (.zdb)\0*.zdb\0\0");
  1450. ofn.nFilterIndex = 1;
  1451. ofn.lpstrFileTitle = NULL;
  1452. ofn.nMaxFileTitle = 0;
  1453. //ofn.lpstrInitialDir = szDir;
  1454. ofn.lpstrDefExt = _T("zdb");
  1455. ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR;
  1456. if (GetSaveFileName(&ofn))
  1457. {
  1458. CWaitCursor wait;
  1459. CString dbPath = CGetSetOptions::GetDBPath();
  1460. CString backupPath(ofn.lpstrFile);
  1461. ret = BackupDB(dbPath, backupPath);
  1462. }
  1463. return ret;
  1464. }
  1465. int WordCount(const CString &text)
  1466. {
  1467. #define OUT 0
  1468. #define IN 1
  1469. int state = OUT;
  1470. unsigned wc = 0; // word count
  1471. // Scan all characters one by one
  1472. for(int pos = 0; pos < text.GetLength(); pos++)
  1473. {
  1474. auto str = text[pos];
  1475. if (str == ' ' || str == '\r' || str == '\n' || str == '\t')
  1476. {
  1477. state = OUT;
  1478. }
  1479. else if (state == OUT)
  1480. {
  1481. state = IN;
  1482. wc++;
  1483. }
  1484. }
  1485. return wc;
  1486. }