Misc.cpp 38 KB

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