CP_Main.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. // CP_Main.cpp : Defines the class behaviors for the application.
  2. //
  3. #include "stdafx.h"
  4. #include "CP_Main.h"
  5. #include "MainFrm.h"
  6. #include "Misc.h"
  7. #include "SelectDB.h"
  8. #include ".\cp_main.h"
  9. #include "server.h"
  10. #include "Client.h"
  11. #ifdef _DEBUG
  12. #define new DEBUG_NEW
  13. #undef THIS_FILE
  14. static char THIS_FILE[] = __FILE__;
  15. #endif
  16. /////////////////////////////////////////////////////////////////////////////
  17. // The one and only CCP_MainApp object
  18. CCP_MainApp theApp;
  19. /////////////////////////////////////////////////////////////////////////////
  20. // CCP_MainApp
  21. BEGIN_MESSAGE_MAP(CCP_MainApp, CWinApp)
  22. //{{AFX_MSG_MAP(CCP_MainApp)
  23. // NOTE - the ClassWizard will add and remove mapping macros here.
  24. // DO NOT EDIT what you see in these blocks of generated code!
  25. //}}AFX_MSG_MAP
  26. END_MESSAGE_MAP()
  27. /////////////////////////////////////////////////////////////////////////////
  28. // CCP_MainApp construction
  29. CCP_MainApp::CCP_MainApp()
  30. {
  31. m_bAppRunning = false;
  32. m_bAppExiting = false;
  33. m_MainhWnd = NULL;
  34. m_pMainFrame = NULL;
  35. m_bShowingQuickPaste = false;
  36. m_bShowingOptions = false;
  37. m_bShowCopyProperties = false;
  38. m_bRemoveOldEntriesPending = false;
  39. m_IC_bCopy = false;
  40. m_GroupDefaultID = 0;
  41. m_GroupID = 0;
  42. m_GroupParentID = 0;
  43. m_GroupText = "History";
  44. m_FocusID = -1; // -1 == keep previous position, 0 == go to latest ID
  45. m_pDatabase = NULL;
  46. // Place all significant initialization in InitInstance
  47. m_bAsynchronousRefreshView = true;
  48. ::InitializeCriticalSection(&m_CriticalSection);
  49. m_hHookDll = NULL;
  50. m_MonitorFocusChanges = NULL;
  51. m_StopMonitoringFocusChanges = NULL;
  52. m_GetCurrentFocus = NULL;
  53. }
  54. CCP_MainApp::~CCP_MainApp()
  55. {
  56. if(m_hHookDll)
  57. FreeLibrary(m_hHookDll);
  58. ::DeleteCriticalSection(&m_CriticalSection);
  59. }
  60. /////////////////////////////////////////////////////////////////////////////
  61. // CCP_MainApp initialization
  62. BOOL CCP_MainApp::InitInstance()
  63. {
  64. LOG("InitInstance");
  65. AfxEnableControlContainer();
  66. m_hMutex = CreateMutex(NULL, FALSE, "Ditto Is Now Running");
  67. DWORD dwError = GetLastError();
  68. if(dwError == ERROR_ALREADY_EXISTS)
  69. {
  70. HWND hWnd = (HWND)CGetSetOptions::GetMainHWND();
  71. if(hWnd)
  72. ::SendMessage(hWnd, WM_SHOW_TRAY_ICON, TRUE, TRUE);
  73. return TRUE;
  74. }
  75. m_cfIgnoreClipboard = ::RegisterClipboardFormat("Clipboard Viewer Ignore");
  76. if(CheckDBExists(CGetSetOptions::GetDBPath()) == FALSE)
  77. {
  78. AfxMessageBox("Error Opening Database.");
  79. return TRUE;
  80. }
  81. AfxOleInit();
  82. // if(g_Opt.m_bUseHookDllForFocus)
  83. // {
  84. // m_hHookDll = LoadLibrary("focus.dll");
  85. // if(m_hHookDll)
  86. // {
  87. // m_MonitorFocusChanges = (DWORD(*)(HWND,UINT))GetProcAddress(m_hHookDll, "_MonitorFocusChanges@8");
  88. // m_StopMonitoringFocusChanges = (DWORD(*)())GetProcAddress(m_hHookDll, "_StopMonitoringFocusChanges@0");
  89. // m_GetCurrentFocus = (HWND(*)())GetProcAddress(m_hHookDll, "_GetCurrentFocus@0");
  90. // }
  91. //
  92. // if( m_hHookDll == NULL || m_MonitorFocusChanges == NULL ||
  93. // m_StopMonitoringFocusChanges == NULL || m_GetCurrentFocus == NULL)
  94. // {
  95. // g_Opt.m_bUseHookDllForFocus = FALSE;
  96. // }
  97. // }
  98. // if(DoCleanups() == FALSE)
  99. // return TRUE;
  100. CMainFrame* pFrame = new CMainFrame;
  101. m_pMainWnd = m_pMainFrame = pFrame;
  102. // prevent no one having focus on startup
  103. TargetActiveWindow();
  104. pFrame->LoadFrame(IDR_MAINFRAME, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL, NULL);
  105. pFrame->ShowWindow(SW_SHOW);
  106. pFrame->UpdateWindow();
  107. // prevent no one having focus on startup
  108. ReleaseFocus();
  109. return TRUE;
  110. }
  111. void CCP_MainApp::AfterMainCreate()
  112. {
  113. m_MainhWnd = m_pMainFrame->m_hWnd;
  114. ASSERT( ::IsWindow(m_MainhWnd) );
  115. g_Opt.SetMainHWND((long)m_MainhWnd);
  116. g_HotKeys.Init( m_MainhWnd );
  117. // create hotkeys here. They are automatically deleted on exit
  118. m_pDittoHotKey = new CHotKey("DittoHotKey",704); //704 is ctrl-tilda
  119. m_pCopyHotKey = new CHotKey("CopyHotKey");
  120. m_pPosOne = new CHotKey("Position1", 0, true);
  121. m_pPosTwo = new CHotKey("Position2", 0, true);
  122. m_pPosThree = new CHotKey("Position3", 0, true);
  123. m_pPosFour = new CHotKey("Position4", 0, true);
  124. m_pPosFive = new CHotKey("Position5", 0, true);
  125. m_pPosSix = new CHotKey("Position6", 0, true);
  126. m_pPosSeven = new CHotKey("Position7", 0, true);
  127. m_pPosEight = new CHotKey("Position8", 0, true);
  128. m_pPosNine = new CHotKey("Position9", 0, true);
  129. m_pPosTen = new CHotKey("Position10", 0, true);
  130. g_HotKeys.RegisterAll();
  131. // CopyThread initialization
  132. StartCopyThread();
  133. AfxBeginThread(MTServerThread, m_MainhWnd);
  134. m_bAppRunning = true;
  135. m_pcpSendRecieveError = NULL;
  136. }
  137. void CCP_MainApp::BeforeMainClose()
  138. {
  139. ASSERT( m_bAppRunning && !m_bAppExiting );
  140. m_bAppRunning = false;
  141. m_bAppExiting = true;
  142. g_HotKeys.UnregisterAll();
  143. StopCopyThread();
  144. }
  145. /*
  146. Re: Targeting the previous focus window
  147. We usually gain focus after the following messages:
  148. keyboard: WM_KEYUP(0x0101),WM_CHAR(0x0102),WM_HOTKEY(0x0312)
  149. mouse: WM_MOUSEFIRST(0x0200),WM_MOUSEMOVE(0x0200),WM_LBUTTONDOWN(0x0201)
  150. CMainFrame::PreTranslateMessage is used to intercept messages before
  151. they are processed (before we are actually given focus) in order to
  152. save the previous window that had focus.
  153. - It currently just handles "activating" mouse messages when showing.
  154. ShowQPasteWnd also has a call to "TargetActiveWindow" which handles
  155. finding the Target on hotkey activation.
  156. This works well for most window switching (mouse or hotkey), but does
  157. not work well for <Alt>-<Tab> or other window switching applications
  158. (e.g. the taskbar tray), since the previous window was only a means to
  159. switching and not the target itself.
  160. - one solution might be to always monitor the current foreground
  161. window using system hooks or a short (e.g. 1 sec) timer... though this
  162. *might* be cpu intensive (slow). I'm currently looking into using
  163. WH_CBT system hooks in a separate dll (see: robpitt's
  164. http://website.lineone.net/~codebox/focuslog.zip).
  165. */
  166. bool CCP_MainApp::TargetActiveWindow()
  167. {
  168. if(g_Opt.m_bUseHookDllForFocus)
  169. return true;
  170. HWND hOld = m_hTargetWnd;
  171. HWND hNew = ::GetForegroundWindow();
  172. if( hNew == m_hTargetWnd || !::IsWindow(hNew) || IsAppWnd(hNew) )
  173. return false;
  174. m_hTargetWnd = hNew;
  175. if( QPasteWnd() )
  176. QPasteWnd()->UpdateStatus(true);
  177. // Tracking / Debugging
  178. /*
  179. LOG( StrF(
  180. "Target Changed" \
  181. "\n\tOld = 0x%08x: \"%s\"" \
  182. "\n\tNew = 0x%08x: \"%s\"\n",
  183. hOld, (LPCTSTR) GetWndText(hOld),
  184. hNew, (LPCTSTR) GetWndText(hNew) ) );
  185. */
  186. return true;
  187. }
  188. bool CCP_MainApp::ActivateTarget()
  189. {
  190. if( !::IsWindow(m_hTargetWnd) || m_hTargetWnd == ::GetForegroundWindow() )
  191. return false;
  192. ::SetForegroundWindow( m_hTargetWnd );
  193. // ::SetFocus( m_hTargetWnd );
  194. return true;
  195. }
  196. bool CCP_MainApp::ReleaseFocus()
  197. {
  198. if( IsAppWnd(::GetForegroundWindow()) )
  199. return ActivateTarget();
  200. return false;
  201. }
  202. // sends Ctrl-V to the TargetWnd
  203. void CCP_MainApp::SendPaste(bool bActivateTarget)
  204. {
  205. if(bActivateTarget && !ActivateTarget())
  206. {
  207. SetStatus("SendPaste FAILED!",TRUE);
  208. return;
  209. }
  210. keybd_event(VK_CONTROL, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
  211. keybd_event('V', 0, KEYEVENTF_EXTENDEDKEY | 0, 0);
  212. keybd_event('V', 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
  213. keybd_event(VK_CONTROL, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
  214. }
  215. // CopyThread
  216. void CCP_MainApp::StartCopyThread()
  217. {
  218. ASSERT( m_MainhWnd );
  219. CClipTypes* pTypes = LoadTypesFromDB();
  220. // initialize to:
  221. // - m_MainhWnd = send WM_CLIPBOARD_COPIED messages to m_MainhWnd
  222. // - true = use Asynchronous communication (PostMessage)
  223. // - true = enable copying on clipboard changes
  224. // - pTypes = the supported types to use
  225. m_CopyThread.Init( CCopyConfig( m_MainhWnd, true, true, pTypes ) );
  226. VERIFY( m_CopyThread.CreateThread(CREATE_SUSPENDED) );
  227. m_CopyThread.ResumeThread();
  228. }
  229. void CCP_MainApp::StopCopyThread()
  230. {
  231. EnableCbCopy(false);
  232. m_CopyThread.Quit();
  233. SaveCopyClips();
  234. }
  235. // Allocates a new CClipTypes
  236. CClipTypes* CCP_MainApp::LoadTypesFromDB()
  237. {
  238. CClipTypes* pTypes = new CClipTypes;
  239. try
  240. {
  241. CTypesTable recset;
  242. recset.Open(AFX_DAO_USE_DEFAULT_TYPE, "SELECT * FROM Types" ,NULL);
  243. while(!recset.IsEOF())
  244. {
  245. pTypes->Add( GetFormatID(recset.m_TypeText) );
  246. recset.MoveNext();
  247. }
  248. recset.Close();
  249. }
  250. catch(CDaoException* e)
  251. {
  252. ASSERT(FALSE);
  253. e->Delete();
  254. }
  255. if( pTypes->GetSize() <= 0 )
  256. {
  257. pTypes->Add(CF_TEXT);
  258. pTypes->Add(RegisterClipboardFormat(CF_RTF));
  259. }
  260. return pTypes;
  261. }
  262. void CCP_MainApp::ReloadTypes()
  263. {
  264. CClipTypes* pTypes = LoadTypesFromDB();
  265. if( pTypes )
  266. m_CopyThread.SetSupportedTypes( pTypes );
  267. }
  268. long CCP_MainApp::SaveCopyClips()
  269. {
  270. long lID = 0;
  271. int count;
  272. CClipList* pClips = m_CopyThread.GetClips(); // we now own pClips
  273. if( !pClips )
  274. return 0;
  275. count = pClips->AddToDB( true );
  276. if( count > 0 )
  277. {
  278. lID = pClips->GetTail()->m_ID;
  279. OnCopyCompleted(lID, count);
  280. if(g_Opt.m_lAutoSendClientCount > 0)
  281. {
  282. //The thread will free these
  283. CIDArray *pIDArray = new CIDArray;
  284. pIDArray->pIDs = new CID[count];
  285. pIDArray->lCount = count;
  286. CClip* pClip;
  287. POSITION pos;
  288. int nArrayPos = 0;
  289. pos = pClips->GetHeadPosition();
  290. while(pos)
  291. {
  292. pClip = pClips->GetNext(pos);
  293. pIDArray->pIDs[nArrayPos].lID = pClip->m_ID;
  294. pIDArray->pIDs[nArrayPos].m_csDesc = pClip->m_Desc;
  295. }
  296. AfxBeginThread(SendClientThread, pIDArray);
  297. }
  298. }
  299. delete pClips;
  300. return lID;
  301. }
  302. void CCP_MainApp::RefreshView()
  303. {
  304. if( m_bShowingQuickPaste )
  305. {
  306. ASSERT( QPasteWnd() );
  307. if(m_bAsynchronousRefreshView)
  308. QPasteWnd()->PostMessage(WM_REFRESH_VIEW);
  309. else
  310. QPasteWnd()->SendMessage(WM_REFRESH_VIEW);
  311. }
  312. }
  313. void CCP_MainApp::OnPasteCompleted()
  314. {
  315. // the list only changes if UpdateTimeOnPaste is true (updated time)
  316. if( g_Opt.m_bUpdateTimeOnPaste )
  317. RefreshView();
  318. }
  319. void CCP_MainApp::OnCopyCompleted(long lLastID, int count)
  320. {
  321. if( count <= 0 )
  322. return;
  323. // queue a message to RemoveOldEntries
  324. Delayed_RemoveOldEntries( 60000 );
  325. // update copy statistics
  326. CGetSetOptions::SetTripCopyCount( -count );
  327. CGetSetOptions::SetTotalCopyCount( -count );
  328. // if we are in the History group, focus on the latest copy
  329. if( m_GroupID == 0 )
  330. m_FocusID = 0;
  331. RefreshView();
  332. ShowCopyProperties( lLastID );
  333. }
  334. // Internal Clipboard for cut/copy/paste items between Groups
  335. // if NULL, this uses the current QPaste selection
  336. void CCP_MainApp::IC_Cut( ARRAY* pIDs )
  337. {
  338. if( pIDs == NULL )
  339. {
  340. if( QPasteWnd() )
  341. QPasteWnd()->m_lstHeader.GetSelectionItemData( m_IC_IDs );
  342. else
  343. m_IC_IDs.SetSize(0);
  344. }
  345. else
  346. m_IC_IDs.Copy( *pIDs );
  347. m_IC_bCopy = false;
  348. if( QPasteWnd() )
  349. QPasteWnd()->UpdateStatus();
  350. }
  351. // if NULL, this uses the current QPaste selection
  352. void CCP_MainApp::IC_Copy( ARRAY* pIDs )
  353. {
  354. if( pIDs == NULL )
  355. {
  356. if( QPasteWnd() )
  357. QPasteWnd()->m_lstHeader.GetSelectionItemData( m_IC_IDs );
  358. else
  359. m_IC_IDs.SetSize(0);
  360. }
  361. else
  362. m_IC_IDs.Copy( *pIDs );
  363. m_IC_bCopy = true;
  364. if( QPasteWnd() )
  365. QPasteWnd()->UpdateStatus();
  366. }
  367. void CCP_MainApp::IC_Paste()
  368. {
  369. if( m_IC_IDs.GetSize() <= 0 )
  370. return;
  371. if( m_IC_bCopy )
  372. m_IC_IDs.CopyTo( GetValidGroupID() );
  373. else // Move
  374. m_IC_IDs.MoveTo( GetValidGroupID() );
  375. // don't process the same items twice.
  376. m_IC_IDs.SetSize(0);
  377. RefreshView();
  378. }
  379. // Groups
  380. BOOL CCP_MainApp::EnterGroupID( long lID )
  381. {
  382. BOOL bResult = FALSE;
  383. if( m_GroupID == lID )
  384. return TRUE;
  385. // if we are switching to the parent, focus on the previous group
  386. if( m_GroupParentID == lID && m_GroupID > 0 )
  387. m_FocusID = m_GroupID;
  388. switch( lID )
  389. {
  390. case 0: // History Group "ID"
  391. m_GroupID = 0;
  392. m_GroupParentID = 0;
  393. m_GroupText = "History";
  394. bResult = TRUE;
  395. break;
  396. case -1: // All Groups "ID"
  397. m_GroupID = -1;
  398. m_GroupParentID = 0;
  399. m_GroupText = "Groups";
  400. bResult = TRUE;
  401. break;
  402. default: // Normal Group
  403. try
  404. {
  405. CMainTable recs;
  406. COleVariant varKey( lID, VT_I4 );
  407. recs.Open( dbOpenTable, "Main" );
  408. recs.SetCurrentIndex("lID");
  409. // Find first record whose [lID] field == lID
  410. if( recs.Seek(_T("="), &varKey) && recs.m_bIsGroup )
  411. {
  412. m_GroupID = recs.m_lID;
  413. m_GroupParentID = recs.m_lParentID;
  414. // if( m_GroupParentID == 0 )
  415. // m_GroupParentID = -1; // back out into "all top-level groups" list.
  416. m_GroupText = recs.m_strText;
  417. bResult = TRUE;
  418. }
  419. recs.Close();
  420. }
  421. CATCHDAO
  422. break;
  423. }
  424. if( bResult )
  425. {
  426. theApp.RefreshView();
  427. if( QPasteWnd() )
  428. QPasteWnd()->UpdateStatus( true );
  429. }
  430. return bResult;
  431. }
  432. // returns a usable group id (not negative)
  433. long CCP_MainApp::GetValidGroupID()
  434. {
  435. if( m_GroupID <= 0 )
  436. return 0;
  437. return m_GroupID;
  438. }
  439. // sets a valid id
  440. void CCP_MainApp::SetGroupDefaultID( long lID )
  441. {
  442. if( m_GroupDefaultID == lID )
  443. return;
  444. if( lID <= 0 )
  445. m_GroupDefaultID = 0;
  446. else
  447. m_GroupDefaultID = lID;
  448. if( QPasteWnd() )
  449. QPasteWnd()->UpdateStatus();
  450. }
  451. // Window States
  452. void CCP_MainApp::SetStatus( const char* status, bool bRepaintImmediately )
  453. {
  454. m_Status = status;
  455. if( QPasteWnd() )
  456. QPasteWnd()->UpdateStatus( bRepaintImmediately );
  457. }
  458. void CCP_MainApp::ShowPersistent( bool bVal )
  459. {
  460. g_Opt.SetShowPersistent( bVal );
  461. // give some visual indication
  462. if( m_bShowingQuickPaste )
  463. {
  464. ASSERT( QPasteWnd() );
  465. QPasteWnd()->SetCaptionColorActive( !g_Opt.m_bShowPersistent );
  466. QPasteWnd()->RefreshNc();
  467. }
  468. }
  469. void CCP_MainApp::ShowCopyProperties( long lID )
  470. {
  471. if( m_bShowCopyProperties && lID > 0 )
  472. {
  473. HWND hWndFocus = ::GetForegroundWindow();
  474. m_bShowCopyProperties = false;
  475. ::SendMessage(m_MainhWnd, WM_COPYPROPERTIES, lID, 0); // modal
  476. ::SetForegroundWindow(hWndFocus);
  477. }
  478. }
  479. void CCP_MainApp::Delayed_RemoveOldEntries( UINT delay )
  480. {
  481. if( !m_bRemoveOldEntriesPending )
  482. {
  483. m_bRemoveOldEntriesPending = true;
  484. ((CMainFrame*)theApp.m_pMainWnd)->SetTimer( REMOVE_OLD_ENTRIES_TIMER, delay, 0 );
  485. }
  486. }
  487. /////////////////////////////////////////////////////////////////////////////
  488. // CCP_MainApp message handlers
  489. int CCP_MainApp::ExitInstance()
  490. {
  491. LOG("ExitInstance");
  492. if(CGetSetOptions::GetCompactAndRepairOnExit())
  493. CompactDatabase();
  494. CloseDB();
  495. return CWinApp::ExitInstance();
  496. }
  497. CDaoDatabase* CCP_MainApp::EnsureOpenDB(CString csName)
  498. {
  499. try
  500. {
  501. if(!m_pDatabase)
  502. m_pDatabase = new CDaoDatabase;
  503. if(!m_pDatabase->IsOpen())
  504. {
  505. if(csName == "")
  506. m_pDatabase->Open(GetDBName());
  507. else
  508. m_pDatabase->Open(csName);
  509. }
  510. if(m_pMainWnd)
  511. ((CMainFrame *)m_pMainWnd)->ResetKillDBTimer();
  512. }
  513. CATCHDAO
  514. return m_pDatabase;
  515. }
  516. BOOL CCP_MainApp::CloseDB()
  517. {
  518. if(m_pDatabase)
  519. {
  520. if(m_pDatabase->IsOpen())
  521. m_pDatabase->Close();
  522. delete m_pDatabase;
  523. m_pDatabase = NULL;
  524. }
  525. return TRUE;
  526. }
  527. // return TRUE if there is more idle processing to do
  528. BOOL CCP_MainApp::OnIdle(LONG lCount)
  529. {
  530. // let winapp handle its idle processing
  531. if( CWinApp::OnIdle(lCount) )
  532. return TRUE;
  533. return FALSE;
  534. }
  535. CString CCP_MainApp::GetTargetName()
  536. {
  537. char cWindowText[100];
  538. HWND hParent = m_hTargetWnd;
  539. ::GetWindowText(hParent, cWindowText, 100);
  540. while(strlen(cWindowText) <= 0)
  541. {
  542. hParent = ::GetParent(hParent);
  543. if(hParent == NULL)
  544. break;
  545. ::GetWindowText(hParent, cWindowText, 100);
  546. }
  547. return cWindowText;
  548. }