Misc.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538
  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. CDPI dpi;
  735. HMONITOR monitorHandle = MonitorFromRect(pcrRect, MONITOR_DEFAULTTONEAREST);
  736. if (monitorHandle == NULL)
  737. {
  738. monitorHandle = MonitorFromRect(pcrRect, MONITOR_DEFAULTTOPRIMARY);
  739. MONITORINFO lpmi;
  740. lpmi.cbSize = sizeof(MONITORINFO);
  741. if (GetMonitorInfo(monitorHandle, &lpmi))
  742. {
  743. crMonitor.CopyRect(&lpmi.rcWork);
  744. *pcrRect = CenterRectFromRect(*pcrRect, crMonitor);
  745. }
  746. }
  747. else
  748. {
  749. MONITORINFO lpmi;
  750. lpmi.cbSize = sizeof(MONITORINFO);
  751. if (GetMonitorInfo(monitorHandle, &lpmi))
  752. {
  753. crMonitor.CopyRect(&lpmi.rcWork);
  754. }
  755. }
  756. bool movedLeft = false;
  757. //Validate the left
  758. long lDiff = pcrRect->left - crMonitor.left;
  759. if (lDiff < 0)
  760. {
  761. pcrRect->left += abs(lDiff);
  762. pcrRect->right += abs(lDiff);
  763. ret = TRUE;
  764. movedLeft = true;
  765. }
  766. //Right side
  767. lDiff = pcrRect->right - crMonitor.right;
  768. if (lDiff > 0)
  769. {
  770. if (movedLeft == false)
  771. {
  772. pcrRect->left -= abs(lDiff);
  773. }
  774. pcrRect->right -= abs(lDiff);
  775. ret = TRUE;
  776. }
  777. bool movedTop = false;
  778. //Top
  779. lDiff = pcrRect->top - crMonitor.top;
  780. if (lDiff < 0)
  781. {
  782. pcrRect->top += abs(lDiff);
  783. pcrRect->bottom += abs(lDiff);
  784. ret = TRUE;
  785. movedTop = true;
  786. }
  787. //Bottom
  788. lDiff = pcrRect->bottom - crMonitor.bottom;
  789. if (lDiff > 0)
  790. {
  791. if (movedTop == false)
  792. {
  793. pcrRect->top -= abs(lDiff);
  794. }
  795. pcrRect->bottom -= abs(lDiff);
  796. ret = TRUE;
  797. }
  798. return ret;
  799. }
  800. __int64 GetLastWriteTime(const CString &csFile)
  801. {
  802. __int64 nLastWrite = 0;
  803. CFileFind finder;
  804. BOOL bResult = finder.FindFile(csFile);
  805. if (bResult)
  806. {
  807. finder.FindNextFile();
  808. FILETIME ft;
  809. finder.GetLastWriteTime(&ft);
  810. memcpy(&nLastWrite, &ft, sizeof(ft));
  811. }
  812. return nLastWrite;
  813. }
  814. typedef struct
  815. {
  816. DWORD ownerpid;
  817. DWORD childpid;
  818. } windowinfo;
  819. BOOL CALLBACK EnumChildWindowsCallback(HWND hWnd, LPARAM lp)
  820. {
  821. windowinfo* info = (windowinfo*)lp;
  822. DWORD pid = 0;
  823. GetWindowThreadProcessId(hWnd, &pid);
  824. if (pid != info->ownerpid)
  825. info->childpid = pid;
  826. return TRUE;
  827. }
  828. CString UWP_AppName(HWND active_window, DWORD ownerpid)
  829. {
  830. CString uwpAppName;
  831. windowinfo info = { 0 };
  832. info.ownerpid = ownerpid;
  833. info.childpid = info.ownerpid;
  834. EnumChildWindows(active_window, EnumChildWindowsCallback, (LPARAM)&info);
  835. HANDLE active_process = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, info.childpid);
  836. if (active_process != NULL)
  837. {
  838. WCHAR image_name[MAX_PATH] = { 0 };
  839. DWORD bufsize = MAX_PATH;
  840. QueryFullProcessImageName(active_process, 0, image_name, &bufsize);
  841. CloseHandle(active_process);
  842. nsPath::CPath path(image_name);
  843. uwpAppName = path.GetName();
  844. }
  845. return uwpAppName;
  846. }
  847. CString GetProcessName(HWND hWnd, DWORD processId)
  848. {
  849. DWORD startTick = GetTickCount();
  850. CString strProcessName;
  851. DWORD Id = processId;
  852. if (Id == 0)
  853. {
  854. GetWindowThreadProcessId(hWnd, &Id);
  855. }
  856. HANDLE active_process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, Id);
  857. if (active_process != NULL)
  858. {
  859. WCHAR image_name[MAX_PATH] = { 0 };
  860. DWORD bufsize = MAX_PATH;
  861. QueryFullProcessImageName(active_process, 0, image_name, &bufsize);
  862. CloseHandle(active_process);
  863. nsPath::CPath path(image_name);
  864. strProcessName = path.GetName();
  865. }
  866. if (strProcessName == _T(""))
  867. {
  868. Log(StrF(_T("failed to get process name from open process, LastError: %d, looping over process names to find process"), GetLastError()));
  869. PROCESSENTRY32 processEntry = { 0 };
  870. HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  871. processEntry.dwSize = sizeof(PROCESSENTRY32);
  872. if (Process32First(hSnapShot, &processEntry))
  873. {
  874. do
  875. {
  876. if (processEntry.th32ProcessID == Id)
  877. {
  878. strProcessName = processEntry.szExeFile;
  879. break;
  880. }
  881. } while (Process32Next(hSnapShot, &processEntry));
  882. }
  883. CloseHandle(hSnapShot);
  884. }
  885. //uwp apps are wrapped in another app called, if this has focus then try and find the child uwp process
  886. if (strProcessName == _T("ApplicationFrameHost.exe"))
  887. {
  888. strProcessName = UWP_AppName(hWnd, Id);
  889. }
  890. DWORD endTick = GetTickCount();
  891. DWORD diff = endTick - startTick;
  892. if(diff > 5)
  893. {
  894. Log(StrF(_T("GetProcessName Time (ms): %d, pid: %d, name: %s"), endTick-startTick, Id, strProcessName));
  895. }
  896. return strProcessName;
  897. }
  898. BOOL IsVista()
  899. {
  900. OSVERSIONINFO osver;
  901. osver.dwOSVersionInfoSize = sizeof( OSVERSIONINFO );
  902. if (::GetVersionEx( &osver ) &&
  903. osver.dwPlatformId == VER_PLATFORM_WIN32_NT &&
  904. (osver.dwMajorVersion >= 6 ) )
  905. {
  906. return TRUE;
  907. }
  908. return FALSE;
  909. }
  910. bool IsRunningLimited()
  911. {
  912. LPCTSTR pszSubKey = _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System");
  913. LPCTSTR pszValue = _T("EnableLUA");
  914. DWORD dwType = 0;
  915. DWORD dwValue = 0;
  916. DWORD dwValueSize = sizeof(DWORD);
  917. if(ERROR_SUCCESS != SHGetValue(HKEY_LOCAL_MACHINE, pszSubKey, pszValue, &dwType, &dwValue, &dwValueSize))
  918. {
  919. //failed to read the reg key, either it's not there or we don't have access to the registry
  920. //If we are vista then assume we don't have access and we are running as a limited app
  921. //otherwise we are xp and the reg key probably doesn't exist and we are not a limited running app
  922. if(IsVista())
  923. {
  924. OutputDebugString(_T("Ditto - Failed to read registry entry finding UAC, Running as limited application"));
  925. return true;
  926. }
  927. }
  928. if(dwValue == 1)
  929. {
  930. OutputDebugString(_T("Ditto - UAC ENABLED, Running as limited application"));
  931. return true;
  932. }
  933. OutputDebugString(_T("Ditto - Running as standard application"));
  934. return false;
  935. }
  936. void DeleteDittoTempFiles(BOOL checkFileLastAccess)
  937. {
  938. CString csDir = CGetSetOptions::GetPath(PATH_REMOTE_FILES);
  939. if (FileExists(csDir))
  940. {
  941. DeleteFolderFiles(csDir, checkFileLastAccess);
  942. }
  943. csDir = CGetSetOptions::GetPath(PATH_DRAG_FILES);
  944. if (FileExists(csDir))
  945. {
  946. DeleteFolderFiles(csDir, checkFileLastAccess);
  947. }
  948. csDir = CGetSetOptions::GetPath(PATH_CLIP_DIFF);
  949. if (FileExists(csDir))
  950. {
  951. DeleteFolderFiles(csDir, checkFileLastAccess);
  952. }
  953. }
  954. void DeleteFolderFiles(CString csDir, BOOL checkFileLastAccess)
  955. {
  956. if (csDir.Find(_T("\\ReceivedFiles\\")) == -1 && csDir.Find(_T("\\DragFiles\\")) == -1 && csDir.Find(_T("ClipCompare")) == -1)
  957. return;
  958. Log(StrF(_T("Deleting files in Folder %s Check Last Access %d"), csDir, checkFileLastAccess));
  959. FIX_CSTRING_PATH(csDir);
  960. CTime ctOld = CTime::GetCurrentTime();
  961. CTime ctFile;
  962. ctOld -= CTimeSpan(0, 0, 0, 1);
  963. CFileFind Find;
  964. CString csFindString;
  965. csFindString.Format(_T("%s*.*"), csDir);
  966. BOOL bFound = Find.FindFile(csFindString);
  967. while(bFound)
  968. {
  969. bFound = Find.FindNextFile();
  970. if(Find.IsDots())
  971. continue;
  972. if(Find.IsDirectory())
  973. {
  974. CString csDir(Find.GetFilePath());
  975. DeleteFolderFiles(csDir, checkFileLastAccess);
  976. RemoveDirectory(csDir);
  977. }
  978. if(checkFileLastAccess &&
  979. Find.GetLastAccessTime(ctFile))
  980. {
  981. //Delete the remote copied file if it hasn't been used for the last day
  982. if(ctFile < ctOld)
  983. {
  984. Log(StrF(_T("Deleting temp file %s"), Find.GetFilePath()));
  985. DeleteFile(Find.GetFilePath());
  986. }
  987. }
  988. else
  989. {
  990. Log(StrF(_T("Deleting temp file %s"), Find.GetFilePath()));
  991. DeleteFile(Find.GetFilePath());
  992. }
  993. }
  994. }
  995. __int64 FileSize(const TCHAR *fileName)
  996. {
  997. struct _stat64 buf;
  998. if (_wstat64((wchar_t const*)fileName, &buf) != 0)
  999. return -1; // error, could use errno to find out more
  1000. return buf.st_size;
  1001. }
  1002. int FindNoCaseAndInsert(CString& mainStr, CString& findStr, CString preInsert, CString postInsert, int linesPerRow)
  1003. {
  1004. int replaceCount = 0;
  1005. //Prevent infinite loop when user tries to replace nothing.
  1006. if (findStr != "")
  1007. {
  1008. int oldLen = findStr.GetLength();
  1009. int foundPos = 0;
  1010. int startFindPos = 0;
  1011. int newPos = 0;
  1012. int insertedLength = 0;
  1013. int firstFindPos = 0;
  1014. //use icu::UnicodeString because it handles upper/lowercase characters for all languages, CSTring only hanldes ascii characters
  1015. icu::UnicodeString mainLow(mainStr);
  1016. mainLow.foldCase(U_FOLD_CASE_DEFAULT);
  1017. icu::UnicodeString findLow(findStr);
  1018. findLow.foldCase(U_FOLD_CASE_DEFAULT);
  1019. int preLength = preInsert.GetLength();
  1020. int postLength = postInsert.GetLength();
  1021. int x = mainLow.indexOf(findLow, 0);
  1022. while(TRUE)
  1023. {
  1024. foundPos = mainLow.indexOf(findLow, startFindPos);
  1025. if (foundPos < 0)
  1026. break;
  1027. if (replaceCount == 0)
  1028. {
  1029. firstFindPos = foundPos + preLength;
  1030. }
  1031. newPos = foundPos + insertedLength;
  1032. mainStr.Insert(newPos, preInsert);
  1033. mainStr.Insert(newPos + preLength + oldLen, postInsert);
  1034. startFindPos = foundPos + oldLen;
  1035. insertedLength += preLength + postLength;
  1036. replaceCount++;
  1037. //safety check, make sure we don't look forever
  1038. if (replaceCount > 100)
  1039. break;
  1040. }
  1041. startFindPos = 0;
  1042. int line = 0;
  1043. int prevLinePos = 0;
  1044. int prevPrevLinePos = 0;
  1045. while (TRUE)
  1046. {
  1047. foundPos = mainStr.Find(_T("\n"), startFindPos);
  1048. if (foundPos < 0)
  1049. break;
  1050. if (firstFindPos < foundPos)
  1051. {
  1052. if (line > linesPerRow - 1)
  1053. {
  1054. int lineStart = prevLinePos;
  1055. if (linesPerRow > 1)
  1056. {
  1057. lineStart = prevPrevLinePos;
  1058. }
  1059. mainStr = _T("... ") + mainStr.Mid(lineStart + 1);
  1060. }
  1061. break;
  1062. }
  1063. startFindPos = foundPos + 1;
  1064. prevPrevLinePos = prevLinePos;
  1065. prevLinePos = foundPos;
  1066. line++;
  1067. //safety check, make sure we don't look forever
  1068. if (line > 1000)
  1069. break;
  1070. }
  1071. if(replaceCount > 0)
  1072. {
  1073. //use unprintable characters so it doesn't find copied html to convert
  1074. mainStr.Replace(_T("\r\n"), _T("\x01\x05\x02"));
  1075. int l = mainStr.Replace(_T("\r"), _T("\x01\x05\x02"));
  1076. int m = mainStr.Replace(_T("\n"), _T("\x01\x05\x02"));
  1077. }
  1078. }
  1079. return replaceCount;
  1080. }
  1081. void OnInitMenuPopupEx(CMenu *pPopupMenu, UINT nIndex, BOOL bSysMenu, CWnd *pWnd)
  1082. {
  1083. ASSERT(pPopupMenu != NULL);
  1084. // Check the enabled state of various menu items.
  1085. CCmdUI state;
  1086. state.m_pMenu = pPopupMenu;
  1087. ASSERT(state.m_pOther == NULL);
  1088. ASSERT(state.m_pParentMenu == NULL);
  1089. // Determine if menu is popup in top-level menu and set m_pOther to
  1090. // it if so (m_pParentMenu == NULL indicates that it is secondary popup).
  1091. HMENU hParentMenu;
  1092. if (AfxGetThreadState()->m_hTrackingMenu == pPopupMenu->m_hMenu)
  1093. {
  1094. state.m_pParentMenu = pPopupMenu; // Parent == child for tracking popup.
  1095. }
  1096. else if ((hParentMenu = ::GetMenu(pWnd->m_hWnd)) != NULL)
  1097. {
  1098. CWnd* pParent = pWnd;
  1099. // Child windows don't have menus--need to go to the top!
  1100. if (pParent != NULL &&
  1101. (hParentMenu = ::GetMenu(pParent->m_hWnd)) != NULL)
  1102. {
  1103. int nIndexMax = ::GetMenuItemCount(hParentMenu);
  1104. for (int nIndex = 0; nIndex < nIndexMax; nIndex++)
  1105. {
  1106. if (::GetSubMenu(hParentMenu, nIndex) == pPopupMenu->m_hMenu)
  1107. {
  1108. // When popup is found, m_pParentMenu is containing menu.
  1109. state.m_pParentMenu = CMenu::FromHandle(hParentMenu);
  1110. break;
  1111. }
  1112. }
  1113. }
  1114. }
  1115. state.m_nIndexMax = pPopupMenu->GetMenuItemCount();
  1116. for (state.m_nIndex = 0; state.m_nIndex < state.m_nIndexMax;
  1117. state.m_nIndex++)
  1118. {
  1119. state.m_nID = pPopupMenu->GetMenuItemID(state.m_nIndex);
  1120. if (state.m_nID == 0)
  1121. continue; // Menu separator or invalid cmd - ignore it.
  1122. ASSERT(state.m_pOther == NULL);
  1123. ASSERT(state.m_pMenu != NULL);
  1124. if (state.m_nID == (UINT)-1)
  1125. {
  1126. // Possibly a popup menu, route to first item of that popup.
  1127. state.m_pSubMenu = pPopupMenu->GetSubMenu(state.m_nIndex);
  1128. if (state.m_pSubMenu == NULL ||
  1129. (state.m_nID = state.m_pSubMenu->GetMenuItemID(0)) == 0 ||
  1130. state.m_nID == (UINT)-1)
  1131. {
  1132. continue; // First item of popup can't be routed to.
  1133. }
  1134. state.DoUpdate(pWnd, TRUE); // Popups are never auto disabled.
  1135. }
  1136. else
  1137. {
  1138. // Normal menu item.
  1139. // Auto enable/disable if frame window has m_bAutoMenuEnable
  1140. // set and command is _not_ a system command.
  1141. state.m_pSubMenu = NULL;
  1142. state.DoUpdate(pWnd, FALSE);
  1143. }
  1144. // Adjust for menu deletions and additions.
  1145. UINT nCount = pPopupMenu->GetMenuItemCount();
  1146. if (nCount < state.m_nIndexMax)
  1147. {
  1148. state.m_nIndex -= (state.m_nIndexMax - nCount);
  1149. while (state.m_nIndex < nCount &&
  1150. pPopupMenu->GetMenuItemID(state.m_nIndex) == state.m_nID)
  1151. {
  1152. state.m_nIndex++;
  1153. }
  1154. }
  1155. state.m_nIndexMax = nCount;
  1156. }
  1157. }
  1158. CString InternetEncode(CString text)
  1159. {
  1160. CString ret = _T("");
  1161. LPTSTR lpOutputBuffer = new TCHAR[1];
  1162. DWORD dwSize = 1;
  1163. BOOL fRes = ::InternetCanonicalizeUrl(text, lpOutputBuffer, &dwSize, ICU_BROWSER_MODE);
  1164. DWORD dwError = ::GetLastError();
  1165. if (!fRes && dwError == ERROR_INSUFFICIENT_BUFFER)
  1166. {
  1167. delete lpOutputBuffer;
  1168. lpOutputBuffer = new TCHAR[dwSize];
  1169. fRes = ::InternetCanonicalizeUrl(text, lpOutputBuffer, &dwSize, ICU_BROWSER_MODE);
  1170. if (fRes)
  1171. {
  1172. ret = lpOutputBuffer;
  1173. //lpOutputBuffer has decoded url
  1174. }
  1175. else
  1176. {
  1177. //failed to decode
  1178. }
  1179. if (lpOutputBuffer != NULL)
  1180. {
  1181. delete [] lpOutputBuffer;
  1182. lpOutputBuffer = NULL;
  1183. }
  1184. }
  1185. else
  1186. {
  1187. //some other error OR the input string url is just 1 char and was successfully decoded
  1188. }
  1189. return ret;
  1190. }
  1191. void DeleteParamFromRTF(CStringA &test, CStringA find, bool searchForTrailingDigits)
  1192. {
  1193. int start = 0;
  1194. while (start >= 0)
  1195. {
  1196. start = test.Find(find, start);
  1197. if (start >= 0)
  1198. {
  1199. if (start > 0)
  1200. {
  1201. //leave it if the preceding character is \\, i was seeing the double slash if the actual text contained slash
  1202. if (test[start - 1] == '\\')
  1203. {
  1204. start++;
  1205. continue;
  1206. }
  1207. }
  1208. int end = -1;
  1209. int innerStart = start + find.GetLength();
  1210. if (searchForTrailingDigits)
  1211. {
  1212. for (int i = innerStart; i < test.GetLength(); i++)
  1213. {
  1214. if (isdigit(test[i]) == false)
  1215. {
  1216. end = i;
  1217. break;
  1218. }
  1219. }
  1220. }
  1221. else
  1222. {
  1223. end = innerStart;
  1224. }
  1225. if (end > 0)
  1226. {
  1227. if (searchForTrailingDigits == false ||
  1228. end != innerStart)
  1229. {
  1230. test.Delete(start, (end - start));
  1231. }
  1232. else
  1233. {
  1234. start++;
  1235. }
  1236. }
  1237. else
  1238. {
  1239. break;
  1240. }
  1241. }
  1242. }
  1243. }
  1244. bool RemoveRTFSection(CStringA &str, CStringA section)
  1245. {
  1246. bool removedSection = false;
  1247. int start2 = str.Find(section, 0);
  1248. int end2 = 0;
  1249. if (start2 >= 0)
  1250. {
  1251. int in = 0;
  1252. for (int pos = start2+1; pos < str.GetLength(); pos++)
  1253. {
  1254. if (str[pos] == '{')
  1255. {
  1256. in++;
  1257. }
  1258. if (str[pos] == '}')
  1259. {
  1260. if (in > 0)
  1261. {
  1262. in--;
  1263. }
  1264. else
  1265. {
  1266. end2 = pos;
  1267. break;
  1268. }
  1269. }
  1270. }
  1271. if (end2 > start2)
  1272. {
  1273. str.Delete(start2, (end2 - start2) + 1);
  1274. removedSection = true;
  1275. }
  1276. }
  1277. return removedSection;
  1278. }
  1279. CString NewGuidString()
  1280. {
  1281. CString guidString;
  1282. GUID guid;
  1283. CoCreateGuid(&guid);
  1284. guidString.Format(_T("%08lX-%04hX-%04hX-%02hhX%02hhX-%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX"),
  1285. guid.Data1, guid.Data2, guid.Data3,
  1286. guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
  1287. guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
  1288. return guidString;
  1289. }
  1290. CString FolderPath(int folderId)
  1291. {
  1292. CString folder = _T("");
  1293. if (folderId > 0)
  1294. {
  1295. try
  1296. {
  1297. CStringArray arr;
  1298. for (int i = 0; i < 100; i++)
  1299. {
  1300. CppSQLite3Query parent = theApp.m_db.execQueryEx(_T("SELECT lID, mText, lParentID FROM Main WHERE lID = %d"), folderId);
  1301. if (parent.eof() == false)
  1302. {
  1303. arr.Add(parent.getStringField(_T("mText")));
  1304. folderId = parent.getIntField(_T("lParentID"));
  1305. }
  1306. else
  1307. {
  1308. break;
  1309. }
  1310. }
  1311. folder = _T("Group Path: \\");
  1312. for (int folderPos = arr.GetCount() - 1; folderPos >= 0; folderPos--)
  1313. {
  1314. folder += _T("\\");
  1315. folder += arr[folderPos];
  1316. }
  1317. }
  1318. CATCH_SQLITE_EXCEPTION
  1319. }
  1320. return folder;
  1321. }