Show copy icon in log message context menu
[TortoiseGit.git] / src / TGitCache / TGITCache.cpp
blobe01e74d7b6f157d37d5e5f83b7978f397e8f01dd
1 // TortoiseGit - a Windows shell extension for easy version control
3 // External Cache Copyright (C) 2005 - 2006,2010 - Will Dean, Stefan Kueng
4 // Copyright (C) 2008-2014 - TortoiseGit
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include "stdafx.h"
22 #include <ShellAPI.h>
23 #include "TGITCache.h"
24 #include "GitStatusCache.h"
25 #include "CacheInterface.h"
26 #include "Resource.h"
27 #include "registry.h"
28 #include "CrashReport.h"
29 #include "GitAdminDir.h"
30 #include <Dbt.h>
31 #include <InitGuid.h>
32 #include <Ioevent.h>
33 #include "..\version.h"
34 #include "SmartHandle.h"
35 #include "DllVersion.h"
36 #include "CreateProcessHelper.h"
38 #ifndef GET_X_LPARAM
39 #define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp))
40 #endif
41 #ifndef GET_Y_LPARAM
42 #define GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp))
43 #endif
46 #pragma comment(linker, "\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
48 #if ENABLE_CRASHHANLDER
49 CCrashReportTGit crasher(L"TGitCache " _T(APP_X64_STRING), TGIT_VERMAJOR, TGIT_VERMINOR, TGIT_VERMICRO, TGIT_VERBUILD, TGIT_VERDATE);
50 #endif
52 DWORD WINAPI InstanceThread(LPVOID);
53 DWORD WINAPI PipeThread(LPVOID);
54 DWORD WINAPI CommandWaitThread(LPVOID);
55 DWORD WINAPI CommandThread(LPVOID);
56 LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
57 bool bRun = true;
58 bool bRestart = false;
59 NOTIFYICONDATA niData;
60 HWND hWnd;
61 HWND hTrayWnd;
62 TCHAR szCurrentCrawledPath[MAX_CRAWLEDPATHS][MAX_CRAWLEDPATHSLEN];
63 int nCurrentCrawledpathIndex = 0;
64 CComAutoCriticalSection critSec;
66 volatile LONG nThreadCount = 0;
68 #define PACKVERSION(major,minor) MAKELONG(minor,major)
70 void DebugOutputLastError()
72 LPVOID lpMsgBuf;
73 if (!FormatMessage(
74 FORMAT_MESSAGE_ALLOCATE_BUFFER |
75 FORMAT_MESSAGE_FROM_SYSTEM |
76 FORMAT_MESSAGE_IGNORE_INSERTS,
77 NULL,
78 GetLastError(),
79 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
80 (LPTSTR) &lpMsgBuf,
82 NULL ))
84 return;
87 // Display the string.
88 OutputDebugStringA("TGitCache GetLastError(): ");
89 OutputDebugString((LPCTSTR)lpMsgBuf);
90 OutputDebugStringA("\n");
92 // Free the buffer.
93 LocalFree( lpMsgBuf );
96 void HandleCommandLine(LPSTR lpCmdLine)
98 char *ptr = strstr(lpCmdLine, "/kill:");
99 if (ptr)
101 DWORD pid = (DWORD)atoi(ptr + strlen("/kill:"));
102 HANDLE hProcess = ::OpenProcess(PROCESS_TERMINATE, FALSE, pid);
103 if (hProcess)
105 if (::WaitForSingleObject(hProcess, 5000) != WAIT_OBJECT_0)
107 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Killing previous TGitCache PID %d\n", pid);
108 if (!::TerminateProcess(hProcess, (UINT)-1))
109 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Kill previous TGitCache PID %d failed\n", pid);
110 ::WaitForSingleObject(hProcess, 5000);
112 ::CloseHandle(hProcess);
113 for (int i = 0; i < 5; i++)
115 HANDLE hMutex = ::OpenMutex(MUTEX_ALL_ACCESS, FALSE, GetCacheMutexName());
116 if (!hMutex)
117 break;
118 ::CloseHandle(hMutex);
119 ::Sleep(1000);
125 void HandleRestart()
127 if (bRestart)
129 TCHAR exeName[MAX_PATH] = { 0 };
130 ::GetModuleFileName(nullptr, exeName, _countof(exeName));
131 TCHAR cmdLine[20] = { 0 };
132 _stprintf_s(cmdLine, _T(" /kill:%d"), GetCurrentProcessId());
133 if (!CCreateProcessHelper::CreateProcessDetached(exeName, cmdLine))
134 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Failed to start cache\n");
138 int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPSTR lpCmdLine, int /*cmdShow*/)
140 SetDllDirectory(L"");
141 HandleCommandLine(lpCmdLine);
142 CAutoGeneralHandle hReloadProtection = ::CreateMutex(NULL, FALSE, GetCacheMutexName());
144 if ((!hReloadProtection) || (GetLastError() == ERROR_ALREADY_EXISTS))
146 // An instance of TGitCache is already running
147 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": TGitCache ignoring restart\n");
148 return 0;
151 CGitStatusCache::Create();
152 CGitStatusCache::Instance().Init();
154 SecureZeroMemory(szCurrentCrawledPath, sizeof(szCurrentCrawledPath));
156 DWORD dwThreadId;
157 MSG msg;
158 TCHAR szWindowClass[] = {TGIT_CACHE_WINDOW_NAME};
160 // create a hidden window to receive window messages.
161 WNDCLASSEX wcex;
162 wcex.cbSize = sizeof(WNDCLASSEX);
163 wcex.style = CS_HREDRAW | CS_VREDRAW;
164 wcex.lpfnWndProc = (WNDPROC)WndProc;
165 wcex.cbClsExtra = 0;
166 wcex.cbWndExtra = 0;
167 wcex.hInstance = hInstance;
168 wcex.hIcon = 0;
169 wcex.hCursor = 0;
170 wcex.hbrBackground = 0;
171 wcex.lpszMenuName = NULL;
172 wcex.lpszClassName = szWindowClass;
173 wcex.hIconSm = 0;
174 RegisterClassEx(&wcex);
175 hWnd = CreateWindow(TGIT_CACHE_WINDOW_NAME, TGIT_CACHE_WINDOW_NAME, WS_CAPTION, 0, 0, 800, 300, NULL, 0, hInstance, 0);
176 hTrayWnd = hWnd;
177 if (hWnd == NULL)
179 return 0;
181 if (CRegStdDWORD(_T("Software\\TortoiseGit\\CacheTrayIcon"), FALSE)==TRUE)
183 SecureZeroMemory(&niData,sizeof(NOTIFYICONDATA));
185 DWORD dwMajor = 0;
186 DWORD dwMinor = 0;
187 GetShellVersion(&dwMajor, &dwMinor);
188 DWORD dwVersion = PACKVERSION(dwMajor, dwMinor);
189 if (dwVersion >= PACKVERSION(6,0))
190 niData.cbSize = sizeof(NOTIFYICONDATA);
191 else if (dwVersion >= PACKVERSION(5,0))
192 niData.cbSize = NOTIFYICONDATA_V2_SIZE;
193 else
194 niData.cbSize = NOTIFYICONDATA_V1_SIZE;
196 niData.uID = TRAY_ID; // own tray icon ID
197 niData.hWnd = hWnd;
198 niData.uFlags = NIF_ICON|NIF_MESSAGE;
200 // load the icon
201 niData.hIcon =
202 (HICON)LoadImage(hInstance,
203 MAKEINTRESOURCE(IDI_TGITCACHE),
204 IMAGE_ICON,
205 GetSystemMetrics(SM_CXSMICON),
206 GetSystemMetrics(SM_CYSMICON),
207 LR_DEFAULTCOLOR);
209 // set the message to send
210 // note: the message value should be in the
211 // range of WM_APP through 0xBFFF
212 niData.uCallbackMessage = TRAY_CALLBACK;
213 Shell_NotifyIcon(NIM_ADD,&niData);
214 // free icon handle
215 if(niData.hIcon && DestroyIcon(niData.hIcon))
216 niData.hIcon = NULL;
219 // Create a thread which waits for incoming pipe connections
220 CAutoGeneralHandle hPipeThread = CreateThread(
221 NULL, // no security attribute
222 0, // default stack size
223 PipeThread,
224 (LPVOID) &bRun, // thread parameter
225 0, // not suspended
226 &dwThreadId); // returns thread ID
228 if (!hPipeThread)
230 return 0;
232 else hPipeThread.CloseHandle();
234 // Create a thread which waits for incoming pipe connections
235 CAutoGeneralHandle hCommandWaitThread = CreateThread(
236 NULL, // no security attribute
237 0, // default stack size
238 CommandWaitThread,
239 (LPVOID) &bRun, // thread parameter
240 0, // not suspended
241 &dwThreadId); // returns thread ID
243 if (!hCommandWaitThread)
245 return 0;
249 // loop to handle window messages.
250 while (bRun)
252 BOOL bLoopRet = GetMessage(&msg, NULL, 0, 0);
253 if ((bLoopRet != -1)&&(bLoopRet != 0))
255 DispatchMessage(&msg);
259 bRun = false;
261 Shell_NotifyIcon(NIM_DELETE,&niData);
262 CGitStatusCache::Destroy();
263 HandleRestart();
265 return 0;
268 LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
270 switch (message)
272 case TRAY_CALLBACK:
274 switch(lParam)
276 case WM_LBUTTONDBLCLK:
277 if (IsWindowVisible(hWnd))
278 ShowWindow(hWnd, SW_HIDE);
279 else
280 ShowWindow(hWnd, SW_RESTORE);
281 break;
282 case WM_MOUSEMOVE:
284 CString sInfoTip;
285 NOTIFYICONDATA SystemTray;
286 sInfoTip.Format(_T("TortoiseGit Overlay Icon Server\nCached Directories: %Id\nWatched paths: %d"),
287 CGitStatusCache::Instance().GetCacheSize(),
288 CGitStatusCache::Instance().GetNumberOfWatchedPaths());
290 SystemTray.cbSize = sizeof(NOTIFYICONDATA);
291 SystemTray.hWnd = hTrayWnd;
292 SystemTray.uID = TRAY_ID;
293 SystemTray.uFlags = NIF_TIP;
294 _tcscpy_s(SystemTray.szTip, sInfoTip);
295 Shell_NotifyIcon(NIM_MODIFY, &SystemTray);
297 break;
298 case WM_RBUTTONUP:
299 case WM_CONTEXTMENU:
301 POINT pt;
302 GetCursorPos(&pt);
303 HMENU hMenu = CreatePopupMenu();
304 if(hMenu)
306 bool enabled = (DWORD)CRegStdDWORD(_T("Software\\TortoiseGit\\CacheType"), GetSystemMetrics(SM_REMOTESESSION) ? ShellCache::dll : ShellCache::exe) != ShellCache::none;
307 InsertMenu(hMenu, (UINT)-1, MF_BYPOSITION, TRAYPOP_ENABLE, enabled ? _T("Disable Status Cache") : _T("Enable Status Cache"));
308 InsertMenu(hMenu, (UINT)-1, MF_BYPOSITION, TRAYPOP_EXIT, _T("Exit"));
309 SetForegroundWindow(hWnd);
310 TrackPopupMenu(hMenu, TPM_BOTTOMALIGN, pt.x, pt.y, 0, hWnd, NULL);
311 DestroyMenu(hMenu);
314 break;
317 break;
318 case WM_PAINT:
320 PAINTSTRUCT ps;
321 HDC hdc = BeginPaint(hWnd, &ps);
322 RECT rect;
323 GetClientRect(hWnd, &rect);
324 // clear the background
325 HBRUSH background = CreateSolidBrush(::GetSysColor(COLOR_WINDOW));
326 HGDIOBJ oldbrush = SelectObject(hdc, background);
327 FillRect(hdc, &rect, background);
329 int line = 0;
330 SIZE fontsize = {0};
331 AutoLocker print(critSec);
332 GetTextExtentPoint32( hdc, szCurrentCrawledPath[0], (int)_tcslen(szCurrentCrawledPath[0]), &fontsize );
333 for (int i=nCurrentCrawledpathIndex; i<MAX_CRAWLEDPATHS; ++i)
335 TextOut(hdc, 0, line*fontsize.cy, szCurrentCrawledPath[i], (int)_tcslen(szCurrentCrawledPath[i]));
336 ++line;
338 for (int i=0; i<nCurrentCrawledpathIndex; ++i)
340 TextOut(hdc, 0, line*fontsize.cy, szCurrentCrawledPath[i], (int)_tcslen(szCurrentCrawledPath[i]));
341 ++line;
344 SelectObject(hdc,oldbrush);
345 EndPaint(hWnd, &ps);
346 DeleteObject(background);
347 return 0L;
349 break;
350 case WM_COMMAND:
352 WORD wmId = LOWORD(wParam);
354 switch (wmId)
356 case TRAYPOP_ENABLE:
358 CRegStdDWORD reg = CRegStdDWORD(_T("Software\\TortoiseGit\\CacheType"), GetSystemMetrics(SM_REMOTESESSION) ? ShellCache::dll : ShellCache::exe);
359 bool enabled = (DWORD)reg != ShellCache::none;
360 reg = enabled ? ShellCache::none : ShellCache::exe;
361 if (enabled)
363 bRestart = true;
364 DestroyWindow(hWnd);
366 break;
368 case TRAYPOP_EXIT:
369 DestroyWindow(hWnd);
370 break;
372 return 1;
374 case WM_QUERYENDSESSION:
376 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": WM_QUERYENDSESSION\n");
377 CAutoWriteWeakLock writeLock(CGitStatusCache::Instance().GetGuard(), 200);
378 CGitStatusCache::Instance().Stop();
379 return TRUE;
381 break;
382 case WM_CLOSE:
383 case WM_ENDSESSION:
384 case WM_DESTROY:
385 case WM_QUIT:
387 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": WM_CLOSE/DESTROY/ENDSESSION/QUIT\n");
388 CAutoWriteLock writeLock(CGitStatusCache::Instance().GetGuard());
389 CGitStatusCache::Instance().Stop();
390 CGitStatusCache::Instance().SaveCache();
391 if (message != WM_QUIT)
392 PostQuitMessage(0);
393 bRun = false;
394 return 1;
396 break;
397 case WM_DEVICECHANGE:
399 DEV_BROADCAST_HDR * phdr = (DEV_BROADCAST_HDR*)lParam;
400 switch (wParam)
402 case DBT_CUSTOMEVENT:
404 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": WM_DEVICECHANGE with DBT_CUSTOMEVENT\n");
405 if (phdr->dbch_devicetype == DBT_DEVTYP_HANDLE)
407 DEV_BROADCAST_HANDLE * phandle = (DEV_BROADCAST_HANDLE*)lParam;
408 if (IsEqualGUID(phandle->dbch_eventguid, GUID_IO_VOLUME_DISMOUNT))
410 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Device to be dismounted\n");
411 CAutoWriteLock writeLock(CGitStatusCache::Instance().GetGuard());
412 CGitStatusCache::Instance().CloseWatcherHandles(phandle->dbch_handle);
414 if (IsEqualGUID(phandle->dbch_eventguid, GUID_IO_VOLUME_LOCK))
416 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Device lock event\n");
417 CAutoWriteLock writeLock(CGitStatusCache::Instance().GetGuard());
418 CGitStatusCache::Instance().CloseWatcherHandles(phandle->dbch_handle);
422 break;
423 case DBT_DEVICEREMOVEPENDING:
424 case DBT_DEVICEQUERYREMOVE:
425 case DBT_DEVICEREMOVECOMPLETE:
426 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": WM_DEVICECHANGE with DBT_DEVICEREMOVEPENDING/DBT_DEVICEQUERYREMOVE/DBT_DEVICEREMOVECOMPLETE\n");
427 if (phdr->dbch_devicetype == DBT_DEVTYP_HANDLE)
429 DEV_BROADCAST_HANDLE * phandle = (DEV_BROADCAST_HANDLE*)lParam;
430 CAutoWriteLock writeLock(CGitStatusCache::Instance().GetGuard());
431 CGitStatusCache::Instance().CloseWatcherHandles(phandle->dbch_handle);
433 else if (phdr->dbch_devicetype == DBT_DEVTYP_VOLUME)
435 DEV_BROADCAST_VOLUME * pVolume = (DEV_BROADCAST_VOLUME*)lParam;
436 CAutoWriteLock writeLock(CGitStatusCache::Instance().GetGuard());
437 for (BYTE i = 0; i < 26; ++i)
439 if (pVolume->dbcv_unitmask & (1 << i))
441 TCHAR driveletter = 'A' + i;
442 CString drive = CString(driveletter);
443 drive += L":\\";
444 CGitStatusCache::Instance().CloseWatcherHandles(CTGitPath(drive));
448 else
450 CAutoWriteLock writeLock(CGitStatusCache::Instance().GetGuard());
451 CGitStatusCache::Instance().CloseWatcherHandles(INVALID_HANDLE_VALUE);
453 break;
456 break;
457 default:
458 break;
460 return DefWindowProc(hWnd, message, wParam, lParam);
463 //////////////////////////////////////////////////////////////////////////
465 VOID GetAnswerToRequest(const TGITCacheRequest* pRequest, TGITCacheResponse* pReply, DWORD* pResponseLength)
467 CTGitPath path;
468 *pResponseLength = 0;
469 if(pRequest->flags & TGITCACHE_FLAGS_FOLDERISKNOWN)
471 path.SetFromWin(pRequest->path, !!(pRequest->flags & TGITCACHE_FLAGS_ISFOLDER));
473 else
475 path.SetFromWin(pRequest->path);
478 CAutoReadWeakLock readLock(CGitStatusCache::Instance().GetGuard(), 2000);
479 if (readLock.IsAcquired())
481 CGitStatusCache::Instance().GetStatusForPath(path, pRequest->flags, false).BuildCacheResponse(*pReply, *pResponseLength);
483 else
485 CStatusCacheEntry entry;
486 entry.BuildCacheResponse(*pReply, *pResponseLength);
490 DWORD WINAPI PipeThread(LPVOID lpvParam)
492 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": PipeThread started\n");
493 bool * bRun = (bool *)lpvParam;
494 // The main loop creates an instance of the named pipe and
495 // then waits for a client to connect to it. When the client
496 // connects, a thread is created to handle communications
497 // with that client, and the loop is repeated.
498 DWORD dwThreadId;
499 BOOL fConnected;
500 CAutoFile hPipe;
502 while (*bRun)
504 hPipe = CreateNamedPipe(
505 GetCachePipeName(),
506 PIPE_ACCESS_DUPLEX, // read/write access
507 PIPE_TYPE_MESSAGE | // message type pipe
508 PIPE_READMODE_MESSAGE | // message-read mode
509 PIPE_WAIT, // blocking mode
510 PIPE_UNLIMITED_INSTANCES, // max. instances
511 BUFSIZE, // output buffer size
512 BUFSIZE, // input buffer size
513 NMPWAIT_USE_DEFAULT_WAIT, // client time-out
514 NULL); // NULL DACL
516 if (!hPipe)
518 if (*bRun)
519 Sleep(200);
520 continue; // never leave the thread!
523 // Wait for the client to connect; if it succeeds,
524 // the function returns a nonzero value. If the function returns
525 // zero, GetLastError returns ERROR_PIPE_CONNECTED.
526 fConnected = ConnectNamedPipe(hPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
527 if (fConnected)
529 // Create a thread for this client.
530 CAutoGeneralHandle hInstanceThread = CreateThread(
531 NULL, // no security attribute
532 0, // default stack size
533 InstanceThread,
534 (HANDLE) hPipe, // thread parameter
535 0, // not suspended
536 &dwThreadId); // returns thread ID
538 if (!hInstanceThread)
540 DisconnectNamedPipe(hPipe);
541 // since we're now closing this thread, we also have to close the whole application!
542 // otherwise the thread is dead, but the app is still running, refusing new instances
543 // but no pipe will be available anymore.
544 PostMessage(hWnd, WM_CLOSE, 0, 0);
545 return 1;
547 // detach the handle, since we passed it to the thread
548 hPipe.Detach();
550 else
552 // The client could not connect, so close the pipe.
553 hPipe.CloseHandle();
554 if (*bRun)
555 Sleep(200);
556 continue; // don't end the thread!
559 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Pipe thread exited\n");
560 return 0;
563 DWORD WINAPI CommandWaitThread(LPVOID lpvParam)
565 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": CommandWaitThread started\n");
566 bool * bRun = (bool *)lpvParam;
567 // The main loop creates an instance of the named pipe and
568 // then waits for a client to connect to it. When the client
569 // connects, a thread is created to handle communications
570 // with that client, and the loop is repeated.
571 DWORD dwThreadId;
572 BOOL fConnected;
573 CAutoFile hPipe;
575 while (*bRun)
577 hPipe = CreateNamedPipe(
578 GetCacheCommandPipeName(),
579 PIPE_ACCESS_DUPLEX, // read/write access
580 PIPE_TYPE_MESSAGE | // message type pipe
581 PIPE_READMODE_MESSAGE | // message-read mode
582 PIPE_WAIT, // blocking mode
583 PIPE_UNLIMITED_INSTANCES, // max. instances
584 BUFSIZE, // output buffer size
585 BUFSIZE, // input buffer size
586 NMPWAIT_USE_DEFAULT_WAIT, // client time-out
587 NULL); // NULL DACL
589 if (!hPipe)
591 if (*bRun)
592 Sleep(200);
593 continue; // never leave the thread!
596 // Wait for the client to connect; if it succeeds,
597 // the function returns a nonzero value. If the function returns
598 // zero, GetLastError returns ERROR_PIPE_CONNECTED.
599 fConnected = ConnectNamedPipe(hPipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
600 if (fConnected)
602 // Create a thread for this client.
603 CAutoGeneralHandle hCommandThread = CreateThread(
604 NULL, // no security attribute
605 0, // default stack size
606 CommandThread,
607 (HANDLE) hPipe, // thread parameter
608 0, // not suspended
609 &dwThreadId); // returns thread ID
611 if (!hCommandThread)
613 DisconnectNamedPipe(hPipe);
614 hPipe.CloseHandle();
615 // since we're now closing this thread, we also have to close the whole application!
616 // otherwise the thread is dead, but the app is still running, refusing new instances
617 // but no pipe will be available anymore.
618 PostMessage(hWnd, WM_CLOSE, 0, 0);
619 return 1;
621 // detach the handle, since we passed it to the thread
622 hPipe.Detach();
624 else
626 // The client could not connect, so close the pipe.
627 hPipe.CloseHandle();
628 if (*bRun)
629 Sleep(200);
630 continue; // don't end the thread!
633 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": CommandWait thread exited\n");
634 return 0;
637 DWORD WINAPI InstanceThread(LPVOID lpvParam)
639 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": InstanceThread started\n");
640 TGITCacheResponse response;
641 DWORD cbBytesRead, cbWritten;
642 CAutoFile hPipe;
644 // The thread's parameter is a handle to a pipe instance.
646 hPipe = lpvParam;
647 InterlockedIncrement(&nThreadCount);
648 while (bRun)
650 // Read client requests from the pipe.
651 TGITCacheRequest request;
652 BOOL fSuccess = ReadFile(
653 hPipe, // handle to pipe
654 &request, // buffer to receive data
655 sizeof(request), // size of buffer
656 &cbBytesRead, // number of bytes read
657 NULL); // not overlapped I/O
659 if (! fSuccess || cbBytesRead == 0)
661 DisconnectNamedPipe(hPipe);
662 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Instance thread exited\n");
663 InterlockedDecrement(&nThreadCount);
664 if (nThreadCount == 0)
665 PostMessage(hWnd, WM_CLOSE, 0, 0);
666 return 1;
669 DWORD responseLength;
670 GetAnswerToRequest(&request, &response, &responseLength);
672 // Write the reply to the pipe.
673 fSuccess = WriteFile(
674 hPipe, // handle to pipe
675 &response, // buffer to write from
676 responseLength, // number of bytes to write
677 &cbWritten, // number of bytes written
678 NULL); // not overlapped I/O
680 if (! fSuccess || responseLength != cbWritten)
682 DisconnectNamedPipe(hPipe);
683 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Instance thread exited\n");
684 InterlockedDecrement(&nThreadCount);
685 if (nThreadCount == 0)
686 PostMessage(hWnd, WM_CLOSE, 0, 0);
687 return 1;
691 // Flush the pipe to allow the client to read the pipe's contents
692 // before disconnecting. Then disconnect the pipe, and close the
693 // handle to this pipe instance.
695 FlushFileBuffers(hPipe);
696 DisconnectNamedPipe(hPipe);
697 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Instance thread exited\n");
698 InterlockedDecrement(&nThreadCount);
699 if (nThreadCount == 0)
700 PostMessage(hWnd, WM_CLOSE, 0, 0);
701 return 0;
704 DWORD WINAPI CommandThread(LPVOID lpvParam)
706 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": CommandThread started\n");
707 DWORD cbBytesRead;
708 CAutoFile hPipe;
710 // The thread's parameter is a handle to a pipe instance.
712 hPipe = lpvParam;
714 while (bRun)
716 // Read client requests from the pipe.
717 TGITCacheCommand command;
718 BOOL fSuccess = ReadFile(
719 hPipe, // handle to pipe
720 &command, // buffer to receive data
721 sizeof(command), // size of buffer
722 &cbBytesRead, // number of bytes read
723 NULL); // not overlapped I/O
725 if (! fSuccess || cbBytesRead == 0)
727 DisconnectNamedPipe(hPipe);
728 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Command thread exited\n");
729 return 1;
732 switch (command.command)
734 case TGITCACHECOMMAND_END:
735 FlushFileBuffers(hPipe);
736 DisconnectNamedPipe(hPipe);
737 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Command thread exited\n");
738 return 0;
739 case TGITCACHECOMMAND_CRAWL:
741 CTGitPath changedpath;
742 changedpath.SetFromWin(command.path, true);
743 // remove the path from our cache - that will 'invalidate' it.
745 CAutoWriteLock writeLock(CGitStatusCache::Instance().GetGuard());
746 CGitStatusCache::Instance().RemoveCacheForPath(changedpath);
748 CGitStatusCache::Instance().AddFolderForCrawling(changedpath.GetDirectory());
750 break;
751 case TGITCACHECOMMAND_REFRESHALL:
753 CAutoWriteLock writeLock(CGitStatusCache::Instance().GetGuard());
754 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": refresh all\n"));
755 CGitStatusCache::Instance().Refresh();
757 break;
758 case TGITCACHECOMMAND_RELEASE:
760 CTGitPath changedpath;
761 changedpath.SetFromWin(command.path, true);
762 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": release handle for path %s\n"), changedpath.GetWinPath());
763 CAutoWriteLock writeLock(CGitStatusCache::Instance().GetGuard());
764 CGitStatusCache::Instance().CloseWatcherHandles(changedpath);
765 CGitStatusCache::Instance().RemoveCacheForPath(changedpath);
767 break;
768 case TGITCACHECOMMAND_BLOCK:
770 CTGitPath changedpath;
771 changedpath.SetFromWin(command.path);
772 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": block path %s\n"), changedpath.GetWinPath());
773 CGitStatusCache::Instance().BlockPath(changedpath);
775 break;
776 case TGITCACHECOMMAND_UNBLOCK:
778 CTGitPath changedpath;
779 changedpath.SetFromWin(command.path);
780 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": unblock path %s\n"), changedpath.GetWinPath());
781 CGitStatusCache::Instance().UnBlockPath(changedpath);
783 break;
787 // Flush the pipe to allow the client to read the pipe's contents
788 // before disconnecting. Then disconnect the pipe, and close the
789 // handle to this pipe instance.
791 FlushFileBuffers(hPipe);
792 DisconnectNamedPipe(hPipe);
793 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": Command thread exited\n");
794 return 0;