Prepare release and bump version numbers to 2.17.0.2
[TortoiseGit.git] / test / Cache / CacheDlg.cpp
blobc3f2769b8c5254a57c533ccb29a29b8ea32dc057
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2012, 2014-2019, 2023 - TortoiseGit
4 // Copyright (C) 2003-2006, 2009, 2015 - TortoiseSVN
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.
20 #include "stdafx.h"
21 #include "Cache.h"
22 #include "DirFileEnum.h"
23 #include "CacheInterface.h"
24 #include <WinInet.h>
25 #include "CacheDlg.h"
26 #include <random>
28 #ifdef _DEBUG
29 #define new DEBUG_NEW
30 #endif
33 CCacheDlg::CCacheDlg(CWnd* pParent /*=nullptr*/)
34 : CDialog(CCacheDlg::IDD, pParent)
36 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
39 void CCacheDlg::DoDataExchange(CDataExchange* pDX)
41 CDialog::DoDataExchange(pDX);
42 DDX_Text(pDX, IDC_ROOTPATH, m_sRootPath);
45 BEGIN_MESSAGE_MAP(CCacheDlg, CDialog)
46 ON_WM_PAINT()
47 ON_WM_QUERYDRAGICON()
48 //}}AFX_MSG_MAP
49 ON_BN_CLICKED(IDOK, OnBnClickedOk)
50 ON_BN_CLICKED(IDC_WATCHTESTBUTTON, OnBnClickedWatchtestbutton)
51 END_MESSAGE_MAP()
54 // CCacheDlg message handlers
56 BOOL CCacheDlg::OnInitDialog()
58 CDialog::OnInitDialog();
60 // Set the icon for this dialog. The framework does this automatically
61 // when the application's main window is not a dialog
62 SetIcon(m_hIcon, TRUE); // Set big icon
63 SetIcon(m_hIcon, FALSE); // Set small icon
65 return TRUE; // return TRUE unless you set the focus to a control
68 // If you add a minimize button to your dialog, you will need the code below
69 // to draw the icon. For MFC applications using the document/view model,
70 // this is automatically done for you by the framework.
72 void CCacheDlg::OnPaint()
74 if (IsIconic())
76 CPaintDC dc(this); // device context for painting
78 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
80 // Center icon in client rectangle
81 int cxIcon = GetSystemMetrics(SM_CXICON);
82 int cyIcon = GetSystemMetrics(SM_CYICON);
83 CRect rect;
84 GetClientRect(&rect);
85 int x = (rect.Width() - cxIcon + 1) / 2;
86 int y = (rect.Height() - cyIcon + 1) / 2;
88 // Draw the icon
89 dc.DrawIcon(x, y, m_hIcon);
91 else
93 CDialog::OnPaint();
97 // The system calls this function to obtain the cursor to display while the user drags
98 // the minimized window.
99 HCURSOR CCacheDlg::OnQueryDragIcon()
101 return m_hIcon;
104 void CCacheDlg::OnBnClickedOk()
106 UpdateData();
107 AfxBeginThread(TestThreadEntry, this);
109 UINT CCacheDlg::TestThreadEntry(LPVOID pVoid)
111 return static_cast<CCacheDlg*>(pVoid)->TestThread();
114 //this is the thread function which calls the subversion function
115 UINT CCacheDlg::TestThread()
117 CDirFileEnum direnum(m_sRootPath);
118 m_filelist.RemoveAll();
119 while (auto file = direnum.NextFile())
121 CString filepath = file->GetFilePath();
122 if (filepath.Find(L".git") < 0)
123 m_filelist.Add(filepath);
126 CTime starttime = CTime::GetCurrentTime();
127 GetDlgItem(IDC_STARTTIME)->SetWindowText(starttime.Format(L"%H:%M:%S"));
129 ULONGLONG startticks = GetTickCount64();
131 CString sNumber;
132 std::random_device rd;
133 std::mt19937 mt(rd());
134 std::uniform_int_distribution<INT_PTR> dist(0, max(INT_PTR(0), m_filelist.GetCount() - 1));
135 std::uniform_int_distribution<INT_PTR> dist2(0, 9);
136 for (int i=0; i < 1; ++i)
138 CString filepath2;
139 //do {
140 filepath2 = m_filelist.GetAt(dist(mt));
141 //}while(filepath.Find(L".git") >= 0);
142 GetDlgItem(IDC_FILEPATH)->SetWindowText(filepath2);
143 GetStatusFromRemoteCache(CTGitPath(filepath2), true);
144 sNumber.Format(L"%d", i);
145 GetDlgItem(IDC_DONE)->SetWindowText(sNumber);
146 if ((GetTickCount64()%10)==1)
147 Sleep(10);
148 if (dist2(mt) == 3)
149 RemoveFromCache(filepath2);
151 CTime endtime = CTime::GetCurrentTime();
152 CString sEnd = endtime.Format(L"%H:%M:%S");
154 ULONGLONG endticks = GetTickCount64();
156 CString sEndText;
157 sEndText.Format(L"%s - %I64u ms", static_cast<LPCTSTR>(sEnd), endticks - startticks);
159 GetDlgItem(IDC_ENDTIME)->SetWindowText(sEndText);
161 return 0;
165 bool CCacheDlg::EnsurePipeOpen()
167 if(m_hPipe != INVALID_HANDLE_VALUE)
169 return true;
172 m_hPipe = CreateFile(
173 GetCachePipeName(), // pipe name
174 GENERIC_READ | // read and write access
175 GENERIC_WRITE,
176 0, // no sharing
177 nullptr, // default security attributes
178 OPEN_EXISTING, // opens existing pipe
179 FILE_FLAG_OVERLAPPED, // default attributes
180 nullptr); // no template file
182 if (m_hPipe == INVALID_HANDLE_VALUE && GetLastError() == ERROR_PIPE_BUSY)
184 // TSVNCache is running but is busy connecting a different client.
185 // Do not give up immediately but wait for a few milliseconds until
186 // the server has created the next pipe instance
187 if (WaitNamedPipe(GetCachePipeName(), 50))
189 m_hPipe = CreateFile(
190 GetCachePipeName(), // pipe name
191 GENERIC_READ | // read and write access
192 GENERIC_WRITE,
193 0, // no sharing
194 nullptr, // default security attributes
195 OPEN_EXISTING, // opens existing pipe
196 FILE_FLAG_OVERLAPPED, // default attributes
197 nullptr); // no template file
202 if (m_hPipe != INVALID_HANDLE_VALUE)
204 // The pipe connected; change to message-read mode.
205 DWORD dwMode;
207 dwMode = PIPE_READMODE_MESSAGE;
208 if(!SetNamedPipeHandleState(
209 m_hPipe, // pipe handle
210 &dwMode, // new pipe mode
211 nullptr, // don't set maximum bytes
212 nullptr)) // don't set maximum time
214 ATLTRACE("SetNamedPipeHandleState failed");
215 CloseHandle(m_hPipe);
216 m_hPipe = INVALID_HANDLE_VALUE;
217 return false;
219 // create an unnamed (=local) manual reset event for use in the overlapped structure
220 m_hEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr);
221 if (m_hEvent)
222 return true;
223 ATLTRACE("CreateEvent failed");
224 ClosePipe();
225 return false;
228 return false;
232 void CCacheDlg::ClosePipe()
234 if(m_hPipe != INVALID_HANDLE_VALUE)
236 CloseHandle(m_hPipe);
237 CloseHandle(m_hEvent);
238 m_hPipe = INVALID_HANDLE_VALUE;
239 m_hEvent = INVALID_HANDLE_VALUE;
243 bool CCacheDlg::GetStatusFromRemoteCache(const CTGitPath& Path, bool bRecursive)
245 if(!EnsurePipeOpen())
247 STARTUPINFO startup = { 0 };
248 PROCESS_INFORMATION process = { 0 };
249 startup.cb = sizeof(startup);
251 CString sCachePath = L"TGitCache.exe";
252 if (CreateProcess(sCachePath.GetBuffer(sCachePath.GetLength() + 1), nullptr, nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup, &process) == 0)
254 // It's not appropriate to do a message box here, because there may be hundreds of calls
255 sCachePath.ReleaseBuffer();
256 ATLTRACE("Failed to start cache\n");
257 return false;
259 sCachePath.ReleaseBuffer();
261 // Wait for the cache to open
262 ULONGLONG endTime = GetTickCount64()+1000;
263 while(!EnsurePipeOpen())
265 if((GetTickCount64() - endTime) > 0)
267 return false;
273 DWORD nBytesRead;
274 TGITCacheRequest request;
275 request.flags = TGITCACHE_FLAGS_NONOTIFICATIONS;
276 if(bRecursive)
278 request.flags |= TGITCACHE_FLAGS_RECUSIVE_STATUS;
280 wcsncpy_s(request.path, Path.GetWinPath(), MAX_PATH);
281 SecureZeroMemory(&m_Overlapped, sizeof(OVERLAPPED));
282 m_Overlapped.hEvent = m_hEvent;
283 // Do the transaction in overlapped mode.
284 // That way, if anything happens which might block this call
285 // we still can get out of it. We NEVER MUST BLOCK THE SHELL!
286 // A blocked shell is a very bad user impression, because users
287 // who don't know why it's blocked might find the only solution
288 // to such a problem is a reboot and therefore they might loose
289 // valuable data.
290 // Sure, it would be better to have no situations where the shell
291 // even can get blocked, but the timeout of 5 seconds is long enough
292 // so that users still recognize that something might be wrong and
293 // report back to us so we can investigate further.
295 TGITCacheResponse ReturnedStatus;
296 BOOL fSuccess = TransactNamedPipe(m_hPipe,
297 &request, sizeof(request),
298 &ReturnedStatus, sizeof(ReturnedStatus),
299 &nBytesRead, &m_Overlapped);
301 if (!fSuccess)
303 if (GetLastError()!=ERROR_IO_PENDING)
305 ClosePipe();
306 return false;
309 // TransactNamedPipe is working in an overlapped operation.
310 // Wait for it to finish
311 DWORD dwWait = WaitForSingleObject(m_hEvent, INFINITE);
312 if (dwWait == WAIT_OBJECT_0)
314 GetOverlappedResult(m_hPipe, &m_Overlapped, &nBytesRead, FALSE);
315 return TRUE;
319 ClosePipe();
320 return false;
323 void CCacheDlg::RemoveFromCache(const CString& path)
325 // if we use the external cache, we tell the cache directly that something
326 // has changed, without the detour via the shell.
327 HANDLE hPipe = CreateFile(
328 GetCacheCommandPipeName(), // pipe name
329 GENERIC_READ | // read and write access
330 GENERIC_WRITE,
331 0, // no sharing
332 nullptr, // default security attributes
333 OPEN_EXISTING, // opens existing pipe
334 FILE_FLAG_OVERLAPPED, // default attributes
335 nullptr); // no template file
338 if (hPipe != INVALID_HANDLE_VALUE)
340 // The pipe connected; change to message-read mode.
341 DWORD dwMode;
343 dwMode = PIPE_READMODE_MESSAGE;
344 if(SetNamedPipeHandleState(
345 hPipe, // pipe handle
346 &dwMode, // new pipe mode
347 NULL, // don't set maximum bytes
348 NULL)) // don't set maximum time
350 DWORD cbWritten;
351 TGITCacheCommand cmd;
352 cmd.command = TGITCACHECOMMAND_CRAWL;
353 wcsncpy_s(cmd.path, path, MAX_PATH);
354 BOOL fSuccess = WriteFile(
355 hPipe, // handle to pipe
356 &cmd, // buffer to write from
357 sizeof(cmd), // number of bytes to write
358 &cbWritten, // number of bytes written
359 NULL); // not overlapped I/O
361 if (! fSuccess || sizeof(cmd) != cbWritten)
363 DisconnectNamedPipe(hPipe);
364 CloseHandle(hPipe);
365 hPipe = INVALID_HANDLE_VALUE;
367 if (hPipe != INVALID_HANDLE_VALUE)
369 // now tell the cache we don't need it's command thread anymore
370 DWORD cbWritten2;
371 TGITCacheCommand cmd2;
372 cmd2.command = TGITCACHECOMMAND_END;
373 WriteFile(
374 hPipe, // handle to pipe
375 &cmd2, // buffer to write from
376 sizeof(cmd2), // number of bytes to write
377 &cbWritten2, // number of bytes written
378 NULL); // not overlapped I/O
379 DisconnectNamedPipe(hPipe);
380 CloseHandle(hPipe);
381 hPipe = INVALID_HANDLE_VALUE;
384 else
386 ATLTRACE("SetNamedPipeHandleState failed");
387 CloseHandle(hPipe);
391 void CCacheDlg::OnBnClickedWatchtestbutton()
393 UpdateData();
394 AfxBeginThread(WatchTestThreadEntry, this);
397 UINT CCacheDlg::WatchTestThreadEntry(LPVOID pVoid)
399 return static_cast<CCacheDlg*>(pVoid)->WatchTestThread();
402 //this is the thread function which calls the subversion function
403 UINT CCacheDlg::WatchTestThread()
405 CDirFileEnum direnum(m_sRootPath);
406 m_filelist.RemoveAll();
407 while (auto file = direnum.NextFile())
408 m_filelist.Add(file->GetFilePath());
410 CTime starttime = CTime::GetCurrentTime();
411 GetDlgItem(IDC_STARTTIME)->SetWindowText(starttime.Format(L"%H:%M:%S"));
413 ULONGLONG startticks = GetTickCount64();
415 CString sNumber;
416 std::random_device rd;
417 std::mt19937 mt(rd());
418 std::uniform_int_distribution<INT_PTR> dist(0, max(INT_PTR(0), m_filelist.GetCount() - 1));
419 CString filepath = m_filelist.GetAt(dist(mt));
420 GetStatusFromRemoteCache(CTGitPath(m_sRootPath), false);
421 for (int i=0; i < 10000; ++i)
423 filepath = m_filelist.GetAt(dist(mt));
424 GetDlgItem(IDC_FILEPATH)->SetWindowText(filepath);
425 TouchFile(filepath);
426 CopyRemoveCopy(filepath);
427 sNumber.Format(L"%d", i);
428 GetDlgItem(IDC_DONE)->SetWindowText(sNumber);
431 // create dummy directories and remove them again several times
432 for (int outer = 0; outer<100; ++outer)
434 for (int i=0; i<10; ++i)
436 filepath.Format(L"__MyDummyFolder%d", i);
437 CreateDirectory(m_sRootPath + L'\\' + filepath, nullptr);
438 HANDLE hFile = CreateFile(m_sRootPath + L'\\' + filepath + L"\\file", GENERIC_READ, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
439 CloseHandle(hFile);
440 SHChangeNotify(SHCNE_UPDATEITEM, SHCNF_PATH | SHCNF_FLUSHNOWAIT, m_sRootPath + L'\\' + filepath + L"\\file", NULL);
442 Sleep(500);
443 for (int i=0; i<10; ++i)
445 filepath.Format(L"__MyDummyFolder%d", i);
446 DeleteFile(m_sRootPath + L'\\' + filepath + L"\\file");
447 RemoveDirectory(m_sRootPath + L'\\' + filepath);
449 sNumber.Format(L"%d", outer);
450 GetDlgItem(IDC_DONE)->SetWindowText(sNumber);
453 CTime endtime = CTime::GetCurrentTime();
454 CString sEnd = endtime.Format(L"%H:%M:%S");
456 ULONGLONG endticks = GetTickCount64();
458 CString sEndText;
459 sEndText.Format(L"%s - %I64u ms", static_cast<LPCTSTR>(sEnd), endticks - startticks);
461 GetDlgItem(IDC_ENDTIME)->SetWindowText(sEndText);
463 return 0;
466 void CCacheDlg::TouchFile(const CString& path)
468 SetFileAttributes(path, FILE_ATTRIBUTE_NORMAL);
469 HANDLE hFile = CreateFile(path, GENERIC_WRITE, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
470 if (hFile == INVALID_HANDLE_VALUE)
471 return;
473 FILETIME ft;
474 SYSTEMTIME st;
476 GetSystemTime(&st); // gets current time
477 SystemTimeToFileTime(&st, &ft); // converts to file time format
478 SetFileTime(hFile, // sets last-write time for file
479 nullptr, nullptr, &ft);
481 CloseHandle(hFile);
484 void CCacheDlg::CopyRemoveCopy(const CString& path)
486 if (PathIsDirectory(path))
487 return;
488 if (path.Find(L".git") >= 0)
489 return;
490 if (CopyFile(path, path+L".tmp", FALSE))
492 if (DeleteFile(path))
494 if (MoveFile(path+L".tmp", path))
495 return;
496 else
497 MessageBox(L"could not move file!", path);
499 else
500 MessageBox(L"could not delete file!", path);
502 else
503 MessageBox(L"could not copy file!", path);