void WatcherData::updatePaths()
{
    // printf("updating paths...\n");
    {
        std::lock_guard<std::mutex> updateLocker(updateMutex);
        handleToPath.clear();
        pathToHandle.clear();
        pathData.clear();
    }
    for (HANDLE& h : changes) {
        //printf("closing %d\n", h);
        FindCloseChangeNotification(h);
    }
    changes.clear();

    std::lock_guard<std::mutex> locker(changeMutex);
    for(const Path& path : paths) {
#ifdef HAVE_CYGWIN
        const ssize_t len = cygwin_conv_path(CCP_POSIX_TO_WIN_A | CCP_ABSOLUTE, path.constData(), 0, 0);
        //printf("win path size %d\n", len);
        String winPath(len, '\0');
        cygwin_conv_path(CCP_POSIX_TO_WIN_A | CCP_ABSOLUTE, path.constData(), winPath.data(), winPath.size());
        //printf("hello %s\n", winPath.constData());
        const HANDLE h = FindFirstChangeNotification(winPath.constData(), TRUE,
                                                     FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE);
#else
        const HANDLE h = FindFirstChangeNotification(path.constData(), TRUE,
                                                     FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE);
#endif
        if (h == INVALID_HANDLE_VALUE) {
            fprintf(stderr, "Unable to watch: %lu (%s)\n",
                    static_cast<unsigned long>(GetLastError()), path.constData());
        } else {
            changes.push_back(h);

            std::lock_guard<std::mutex> updateLocker(updateMutex);
            handleToPath[h] = path;
            pathToHandle[path] = h;
            PathData& data = pathData[path];
            path.visit([&data](const Path &p) {
                    if (p.isFile()) {
                        data.modified[p] = p.lastModifiedMs();
                        return Path::Continue;
                    }
                    return Path::Recurse;
                });
        }
    }
}
bool DirectoryWinAPI::setWatch(const std::string& path, ICallbackBase<void>* cb)
{
	if(callbacks.size() > MAXIMUM_WAIT_OBJECTS)
	{
		LOGERROR("Too many objects being watched", "setWatch");
	}

	HANDLE watchHandle = FindFirstChangeNotification(path.c_str(), TRUE, FILE_NOTIFY_CHANGE_LAST_WRITE);
	if (watchHandle == INVALID_HANDLE_VALUE) 
	{
		DWORD err = GetLastError();
		LOGERROR(err, "FindFirstChangeNotification");
		return false;
	}

	HANDLE poolHandle;
	if(!RegisterWaitForSingleObject(&poolHandle, watchHandle, onEventTriggered, watchHandle, INFINITE, WT_EXECUTEINWAITTHREAD))
	{
		DWORD err = GetLastError();
		LOGERROR(err, "RegisterWaitForSingleObject");
		return false;
	}

	DirWinAPIWait waitStruct = { cb, poolHandle };
	callbacks[watchHandle] = waitStruct;

	return true;
}
void CFileSystemMonitor::InitMonitor() {
  _scraper_directory_on_a_network_drive = false;
  // http://msdn.microsoft.com/de-de/library/windows/desktop/bb773640%28v=vs.85%29.aspx
  if (PathIsNetworkPath(absolute_path_to_scraper_directory)) {
    // Network mapped drives are unsupported
    // and can lead to crashes.
    // http://www.maxinmontreal.com/forums/viewtopic.php?f=114&t=17677&p=122925#p122925
    write_log(Preferences()->debug_filesystem_monitor(), "[CFileSystemMonitor] Unsupported network mapped drive\n");
    _scraper_directory_on_a_network_drive = true;
    return;
  }
	int changes_to_monitor = FILE_NOTIFY_CHANGE_FILE_NAME
		| FILE_NOTIFY_CHANGE_SIZE
		| FILE_NOTIFY_CHANGE_LAST_WRITE;
  // Since OpenHoldem 13.0 we support a nested scraper-directory,
  // even with some "official" maps for real-world-casinos.
  const bool watch_subtree = TRUE;
	dwChangeHandle = FindFirstChangeNotification(
		absolute_path_to_scraper_directory,
    watch_subtree,	
		changes_to_monitor);
	if ((dwChangeHandle == INVALID_HANDLE_VALUE) || (dwChangeHandle == NULL)) {
		write_log(Preferences()->debug_filesystem_monitor(), "[CFileSystemMonitor] InitMonitor() failed.\n");
		write_log(Preferences()->debug_filesystem_monitor(), "[CFileSystemMonitor] Going to terminate...\n");
		ExitProcess(GetLastError()); 
	}
}
Example #4
0
DWORD WINAPI monitor_thread(VOID *p) {
    char watchme[PATH_MAX];
    HANDLE harr[2], fff;

    if(lock_engine()) {
	logg("^monitor_thread: failed to lock engine\n");
	return 0;
    }

    snprintf(watchme, sizeof(watchme), "%s\\forcerld", dbdir);
    watchme[sizeof(watchme)-1] = '\0';

    harr[0] = monitor_event;
    harr[1] = FindFirstChangeNotification(dbdir, FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_FILE_NAME);

    unlock_engine();

    if(harr[1] == INVALID_HANDLE_VALUE) {
	logg("^monitor_thread: failed to monitor directory changes on %s\n", dbdir);
	return 0;
    }

    logg("monitor_thread: watching directory changes on %s\n", dbdir);

    while(1) {
	WIN32_FIND_DATA wfd;
	SYSTEMTIME st;

	switch(WaitForMultipleObjects(2, harr, FALSE, INFINITE)) {
	case WAIT_OBJECT_0:
	    logg("*monitor_thread: terminating upon request\n");
	    FindCloseChangeNotification(harr[1]);
	    return 0;
	case WAIT_OBJECT_0 + 1:
	    break;
	default:
	    logg("*monitor_thread: unexpected wait failure - %u\n", GetLastError());
	    Sleep(1000);
	    continue;
	}
	FindNextChangeNotification(harr[1]);
	if((fff = FindFirstFile(watchme, &wfd)) == INVALID_HANDLE_VALUE)
	    continue;
	FindClose(fff);

	GetSystemTime(&st);
	SystemTimeToFileTime(&st, &wfd.ftCreationTime);
	if(CompareFileTime(&wfd.ftLastWriteTime, &wfd.ftCreationTime) > 0)
	    wfd.ftLastWriteTime = wfd.ftCreationTime;
	if(CompareFileTime(&wfd.ftLastWriteTime, &last_chk_time) <= 0)
	    continue;

	logg("monitor_thread: reload requested!\n");
	Scan_ReloadDatabase(minimal_definitions);
	GetSystemTime(&st);
	SystemTimeToFileTime(&st, &last_chk_time); /* FIXME: small race here */
    }
}
Example #5
0
int WINAPI FileSysWatcher (LPVOID arg)
{
	HWND hDlg = (HWND)arg;
	LuaPerWindowInfo& info = LuaWindowInfo[hDlg];

	while(true)
	{
		char filename [1024], directory [1024];

		strncpy(filename, info.filename.c_str(), 1024);
		filename[1023] = 0;
		strcpy(directory, filename);
		char* slash = strrchr(directory, '/');
		slash = std::max(slash, strrchr(directory, '\\'));
		if(slash)
			*slash = 0;

		char* bar = strchr(filename, '|');
		if(bar) *bar = '\0';

		WIN32_FILE_ATTRIBUTE_DATA origData;
		GetFileAttributesEx (filename,  GetFileExInfoStandard,  (LPVOID)&origData);

		HANDLE hNotify = FindFirstChangeNotification(directory, FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE);

		if(hNotify)
		{
			DWORD dwWaitResult = WaitForSingleObject(hNotify, 500);

			if(dwWaitResult != STATUS_TIMEOUT)
			{
				if(dwWaitResult == WAIT_ABANDONED)
					return dwWaitResult;

				WIN32_FILE_ATTRIBUTE_DATA data;
				GetFileAttributesEx (filename,  GetFileExInfoStandard,  (LPVOID)&data);

				// at this point it could be any file in the directory that changed
				// so check to make sure it was the file we care about
				if(memcmp(&origData.ftLastWriteTime, &data.ftLastWriteTime, sizeof(FILETIME)))
				{
					RequestAbortLuaScript((int)hDlg, "terminated to reload the script");
					PostMessage(hDlg, WM_COMMAND, IDC_BUTTON_LUARUN, 0);
				}
			}

			//FindNextChangeNotification(hNotify); // let's not try to reuse it...
			FindCloseChangeNotification(hNotify); // but let's at least make sure to release it!
		}
		else
		{
			Sleep(500);
		}
	}

	return 0;
}
Example #6
0
HRESULT CPigEngine::EnsureScriptsAreLoaded()
{
  // Return immediately if this initialization has already completed
  XLock lock(this);
  if (!m_hDirChange.IsNull() && m_pth)
    return S_OK;

  // Open the registry key of the AppID
  CRegKey key;
  RETURN_FAILED(_Module.OpenAppIDRegKey(key, KEY_READ));

  // Initialize the art path
  TCHAR szArtPath[_MAX_PATH];
  DWORD cch = sizeofArray(szArtPath);
  long lr = key.QueryValue(szArtPath, TEXT("ArtPath"), &cch);
  if (ERROR_SUCCESS != lr)
    return HRESULT_FROM_WIN32(lr);
  UTL::SetArtPath(szArtPath);

  // Convert the directory name to ANSI
  USES_CONVERSION;
  LPSTR pszScriptDir = OLE2A(m_bstrScriptDir);

  // Remove the whack at the end of the string
  cch = strlen(pszScriptDir);
  assert('\\' == pszScriptDir[cch - 1]);
  pszScriptDir[cch - 1] = '\0';

  // Ensure that the directory exists
  WIN32_FIND_DATA ffd;
  TCFileFindHandle hff = FindFirstFile(pszScriptDir, &ffd);
  if(hff.IsNull() || INVALID_HANDLE_VALUE == hff)
    return HRESULT_FROM_WIN32(GetLastError());

  // Initialize our record of the directory contents
  ProcessScriptDirChanges();

  // Create a directory change notification object
  const DWORD dwFilter = FILE_NOTIFY_CHANGE_FILE_NAME |
    FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_LAST_WRITE;
  m_hDirChange = FindFirstChangeNotification(pszScriptDir, false, dwFilter);
  if (INVALID_HANDLE_VALUE == m_hDirChange)
    return HRESULT_FROM_WIN32(GetLastError());

  // Create the thread that monitors the ProfileScriptDir folder
  m_pth = TCThread::BeginMsgThread(ScriptDirThunk, this,
    THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);
  if (!m_pth)
    return E_FAIL;
  m_pth->ResumeThread();

  // TODO: Create the thread that monitors the CLSID registry key

  // Indicate success
  return S_OK;
}
Example #7
0
	CheckDir( const wchar_t * path )
		:
		canceled(false)
	{
		handle = FindFirstChangeNotification(
			path, 
			FALSE,
			FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SECURITY
			);
	}
Example #8
0
    void WatchDirModifacationProcess::VOnInit(void)
    {
        std::wstring s(m_dir.begin(), m_dir.end());
        m_fileHandle = FindFirstChangeNotification(s.c_str(), false, FILE_NOTIFY_CHANGE_LAST_WRITE);
        if(INVALID_HANDLE_VALUE == m_fileHandle)
        {
            LOG_CRITICAL_ERROR("FindFirstChangeNotification failed hard");
        }
        m_closeHandle = CreateEvent(NULL, false, false, NULL);

        RealtimeProcess::VOnInit();
    }
Example #9
0
FileReader::FileReader(Timer& timer, ILineBuffer& linebuffer, FileType::type filetype, const std::wstring& filename) :
    LogSource(timer, SourceType::File, linebuffer),
    m_end(true),
    m_filename(Str(filename).str()),
    m_fileType(filetype),
    m_name(Str(boost::filesystem::wpath(filename).filename().string()).str()),
    m_handle(FindFirstChangeNotification(boost::filesystem::wpath(m_filename).parent_path().wstring().c_str(), false, FILE_NOTIFY_CHANGE_SIZE)), //todo: maybe using FILE_NOTIFY_CHANGE_LAST_WRITE could have benefits, not sure what though.
    m_ifstream(m_filename, std::ios::in),
    m_filenameOnly(boost::filesystem::wpath(m_filename).filename().string()),
    m_initialized(false)
{
    SetDescription(filename);
}
Example #10
0
	virtual DWORD Run()
	{
		SetThreadPriority(myHandle, THREAD_PRIORITY_IDLE);

		TCHAR aLocaleDir[1000];
		myMan->GetLocalizationBasePath(aLocaleDir, 1000);

		myMonitorHandle = FindFirstChangeNotification(
			aLocaleDir,
			FALSE,
			FILE_NOTIFY_CHANGE_LAST_WRITE);

		if ( myMonitorHandle == INVALID_HANDLE_VALUE)
			return 1;

		HANDLE aObjs[2] = { myMonitorHandle, myTerminateEvent };

		while (true)
		{
			DWORD aRes = WaitForMultipleObjects(2, aObjs, FALSE, INFINITE);

			if ( aRes == WAIT_FAILED)
				break;

			else if (aRes == WAIT_OBJECT_0 + 0)		//directory change
			{
				//HACK
				HWND aWnd = RootWindow::FindSingleInstance();

				if (aWnd == 0)
					break;
				//end HACK

				PostMessage(aWnd, RootWindow::WM_USER_LOADLOCALE, 0, 0);

				BOOL aRet = FindNextChangeNotification(myMonitorHandle);

				if (aRet == 0)
				{
					ATLTRACE("LocalizationDirectoryMonitorThread -- failed on FindNextChangeNotification, returning.\n");
					break;
				}
			}

			else if (aRes == WAIT_OBJECT_0 + 1)	//the terminate event occurred
				break;
		}

		FindCloseChangeNotification(myMonitorHandle);
		return 0;
	}
Example #11
0
DWORD __stdcall ChangeNotifyThread(LPVOID param)
{
	CoInitialize(NULL);

	CComQIPtr<IWebSite> site = (IWebSite*)param;

	CWebSite* pSite = ((CWebSite*)site.p);
	
	BSTR rootPath;
	site->get_rootPath(&rootPath);

	HANDLE m_hChangeHandle;

	m_hChangeHandle = FindFirstChangeNotification(_bstr_t(rootPath),
			TRUE,
			FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME |
			FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SIZE
			);

	SysFreeString(rootPath);

	while (1)
	{
		DWORD nObject = MsgWaitForMultipleObjectsEx(
		  1,          // number of handles in handle array
		  &m_hChangeHandle,     // pointer to an object-handle array
		  INFINITE,  // time-out interval in milliseconds
		  QS_ALLEVENTS,      // type of input events to wait for
		  0         // wait flags
		);

		if (nObject == WAIT_OBJECT_0)
		{
			pSite->m_pRootDir->ScanFiles(TRUE, TRUE);
			pSite->Fire_FileTreeChanged();
		}
		else
		{
			break;
		}

		FindNextChangeNotification(m_hChangeHandle);
	}

	FindCloseChangeNotification(m_hChangeHandle);

	CoUninitialize();

	return 0;
}
Example #12
0
unsigned int __stdcall CMainWindow::WatcherThread( LPVOID lpvParam )
{
    CMainWindow * pThis = (CMainWindow*)lpvParam;

    DWORD dwWaitStatus;
    HANDLE dwChangeHandle;
    std::wstring monitorPath;

    while (pThis->threadRunning)
    {
        monitorPath = pThis->wpPath;
        // Watch the directory for file creation and deletion.
        std::wstring dirPath = monitorPath.substr(0, monitorPath.find_last_of('\\'));
        dwChangeHandle = FindFirstChangeNotification(
            dirPath.c_str(),
            FALSE,
            FILE_NOTIFY_CHANGE_LAST_WRITE);

        if (dwChangeHandle != INVALID_HANDLE_VALUE)
        {
            // Change notification is set.
            while ((pThis->threadRunning)&&(monitorPath.compare(pThis->wpPath) == 0))
            {
                // Wait for notification.
                dwWaitStatus = WaitForSingleObject(dwChangeHandle, 1000);

                switch (dwWaitStatus)
                {
                case WAIT_OBJECT_0:
                    SendMessage(*pThis, WM_SETTINGCHANGE, 0, 0);
                    break;

                case WAIT_TIMEOUT:
                    // A timeout occurred
                    if (monitorPath.compare(pThis->wpPath) != 0)
                    {
                        SendMessage(*pThis, WM_SETTINGCHANGE, 0, 0);
                    }
                    break;
                }
                FindNextChangeNotification(dwChangeHandle);
            }
            FindCloseChangeNotification(dwChangeHandle);
            monitorPath.clear();
        }
        Sleep(10);
    }
    return 0;
}
static void watchDirectory(const char * dir) {

	for (int i=0;  i<_SIZE; i++) {
		if (notifyHandles[i] != NULL) {
			if (!strcmp(dir,notifyHandles[i]->dir))
				break;
		} else {
			notifyHandles[i] = (struct DirInfo *)malloc(sizeof(struct DirInfo));
			notifyHandles[i]->dir = (const char*)calloc(strlen(dir)+1,sizeof(char));
			strcpy((char*)notifyHandles[i]->dir,dir);
			notifyHandles[i]->notifyHandle = FindFirstChangeNotification(dir,false,FILE_NOTIFY_CHANGE_LAST_WRITE);
			break;
		}
	}
}
Example #14
0
int InitIni(void)
{
	TCHAR szMirandaDir[MAX_PATH];

	bModuleInitialized = true;

	DoAutoExec();
	pathToAbsoluteT(_T("."), szMirandaDir, NULL);
	hIniChangeNotification=FindFirstChangeNotification(szMirandaDir, 0, FILE_NOTIFY_CHANGE_FILE_NAME);
	if (hIniChangeNotification != INVALID_HANDLE_VALUE) {
		CreateServiceFunction("DB/Ini/CheckImportNow", CheckIniImportNow);
		CallService(MS_SYSTEM_WAITONHANDLE, (WPARAM)hIniChangeNotification, (LPARAM)"DB/Ini/CheckImportNow");
	}
	return 0;
}
Example #15
0
//  StartClipWatcher
//
void StartClipWatcher(ClipWatcher* watcher)
{
    if (watcher->notifier == INVALID_HANDLE_VALUE) {
        watcher->notifier = FindFirstChangeNotification(
                                watcher->srcdir, FALSE,
                                (FILE_NOTIFY_CHANGE_FILE_NAME |
                                 FILE_NOTIFY_CHANGE_SIZE |
                                 FILE_NOTIFY_CHANGE_ATTRIBUTES |
                                 FILE_NOTIFY_CHANGE_LAST_WRITE));
        if (logfp != NULL) {
            fwprintf(logfp, L"register: srcdir=%s, notifier=%p\n",
                     watcher->srcdir, watcher->notifier);
        }
    }
}
Example #16
0
void FilesystemChangesRunnable::startWatching()
{
   BOOL recursive = TRUE;

   // Watch the directory for file creation and deletion. 
   const DWORD flags = FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_CREATION;
   m_dwChangeHandle = FindFirstChangeNotification( m_filesystemRoot.c_str(), recursive, flags );
   if ( m_dwChangeHandle == INVALID_HANDLE_VALUE )
   {
      LOG( "FilesystemChangesTracker: Error (%d): FindFirstChangeNotification function failed.", GetLastError() );
      return;
   }

   // flag that we're ready to process
   m_initialized = true;
}
Example #17
0
void CFileListener::Initialize() {
    m_handles[ATF_WAIT_HANDLE] = 
        FindFirstChangeNotification(
            m_srcDir, 
            false, 
            FILE_NOTIFY_CHANGE_FILE_NAME);

    m_handles[ATF_STOP_HANDLE] = CreateEvent(NULL, true, false, NULL);

    LOG_INFO(GetLogger(), ATF_INFO, 
              "File listener initialized for ["+m_srcDir+"] directory");

    if ( m_retryUncompleted ) {
        RetryUncompleted();
    }
};
Example #18
0
void do_listen(fsmonitor_t *monitor) {
  HANDLE hChange = FindFirstChangeNotification(U2W(monitor->path), TRUE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_ATTRIBUTES);
  assert(hChange != INVALID_HANDLE_VALUE);
  printf("Listening to changes in %s\n", monitor->path);
  while (TRUE) {
    DWORD status = WaitForMultipleObjects(1, &hChange, FALSE, INFINITE);
    if (status == WAIT_OBJECT_0) {
      printf("Detected change in %s\n", monitor->path);
      invoke_on_main_thread((INVOKE_LATER_FUNC) fsmonitor_did_detect_change, monitor);
      DWORD result = FindNextChangeNotification(hChange);
      assert(result);
    } else {
      assert(!"WaitForMultipleObjects returned error");
    }
  }
}
Example #19
0
void InitDialogCache(void)
{
	TCHAR szFilePath[MAX_PATH], *p;

	InitializeCriticalSection(&csDialogCache);

	hServiceFileChange = CreateServiceFunction("Help/HelpPackChanged", ServiceFileChanged);
	hFileChange = INVALID_HANDLE_VALUE;
	if (GetModuleFileName(NULL, szFilePath, _countof(szFilePath))) {
		p = _tcsrchr(szFilePath, _T('\\'));
		if (p != NULL)
			*(p + 1) = _T('\0');
		hFileChange = FindFirstChangeNotification(szFilePath, FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE);
		if (hFileChange != INVALID_HANDLE_VALUE)
			CallService(MS_SYSTEM_WAITONHANDLE, (WPARAM)hFileChange, (LPARAM)"Help/HelpPackChanged");
	}
}
Example #20
0
//-----------------------------------------------------------------------------
// Purpose: Startup our file watch
//-----------------------------------------------------------------------------
void UpdateConfigsStatus_Init( void )
{
	// Watch our config file for changes
	if ( g_dwChangeHandle == NULL)
	{
		char szConfigDir[MAX_PATH];
		Q_strncpy( szConfigDir, GetBaseDirectory(), sizeof( szConfigDir ) );

		g_dwChangeHandle = FindFirstChangeNotification( 
			szConfigDir,													// directory to watch 
			false,															// watch the subtree 
			FILE_NOTIFY_CHANGE_LAST_WRITE );								// watch file and dir name changes 
 
		if ( g_dwChangeHandle == INVALID_HANDLE_VALUE )
		{
			// FIXME: Unable to watch the file
		}
	}
}	 
Example #21
0
BOOL WaitForSingleFile(_In_ LPCTTSTR lpPathName, _In_ DWORD dwNotifyFilter)
{
    UUIDCreate()
    StringFromCLSID
    GetTempPath(tmpdir, MAX_PATH);
    CreateDirectory(tmpdir+guid);
    CreateHardLink(tmpdir+guid+guid, srcpath, NULL);
    handle = FindFirstChangeNotification(tmpdir, FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE);
    if(handle == INVALID_HANDLE_VALUE)
    {
        printf("OHH NO\n");
        ExitProcess(1);
    }
    WaitForSingleObject(handle, INFINITE);

    DeleteFile(tmpdir+guid+guid);
    DeleteDirectory(tmpdir+guid);


}
Example #22
0
void FileChangeWatcher::SetFile(const wxFileName& fileName)
{

    // If the file is in the same directory, we don't need to update anything.
    bool sameDirectory = (fileName.GetPath() == m_fileName.GetPath());

    m_fileName = fileName;
    UpdateFileAttributes();

    if (!sameDirectory || m_handle == NULL)
    {

        if (m_thread != NULL)
        {
            EndThread();
        }

        if (m_handle != NULL)
        {
            FindCloseChangeNotification(m_handle);
            m_handle = NULL;
        }

        m_handle = FindFirstChangeNotification(m_fileName.GetPath(), FALSE, FILE_NOTIFY_CHANGE_ATTRIBUTES);

        // Sometimes the return is NULL and sometimes it's INVALID_HANDLE_VALUE
        // in error conditions.
        if (m_handle == INVALID_HANDLE_VALUE)
        {
            m_handle = NULL;
        }

        if (m_handle != NULL)
        {
            DWORD threadId;
            m_thread = CreateThread(NULL, 0, ThreadProc, this, 0, &threadId);
        }
    
    }

}
Example #23
0
BOOL StartWatchDir(LPCTSTR dir, HWND hWnd, DWORD messageID, LPVOID watchHand)
{
   // Watch for changes in the specified directory and report with the specified message id to the specified window
   pWatchInfo pInf = new tWatchInfo;
   BOOL ok =  pInf != NULL;
   if (ok)
   {
      pInf->hWnd = hWnd;
      pInf->messageID = messageID;
   }

   ok = ok && (pInf->hChange = FindFirstChangeNotification(dir, TRUE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE)) != INVALID_HANDLE_VALUE;
   ok = ok && (pInf->hThread = CreateThread(NULL, 0, WatchThreadProc, pInf, 0, NULL)) != NULL;

   if (ok && watchHand)
      watchHand = (PVOID)pInf;
   else if (!ok)
      delete pInf;

   return ok;
}
Example #24
0
unsigned int WINAPI DirChangeNotifier::task() {
	m_hChangeDir = FindFirstChangeNotification(
		m_path,                        // directory to watch
		FALSE,                         // do not watch subtree
		FILE_NOTIFY_CHANGE_FILE_NAME); // watch for file names

	if (m_hChangeDir == INVALID_HANDLE_VALUE) {
		OutputDebugStringW(L"ERROR: FindFirstChangeNotification");
		_endthreadex(0);
		return 0;
	}

	while (TRUE) {
		DWORD dwWaitStatus = WaitForSingleObject(m_hChangeDir, INFINITE);
		if (dwWaitStatus == WAIT_OBJECT_0) {
			if (m_fTerminate) {
				break;
			}
			// A file was created, renamed, or deleted in the directory.
			// Refresh this directory and restart the notification.
			if (isChecked()) {
				::Info.AdvControl(&MainGuid, ACTL_SYNCHRO, 0, (void*)m_hPanel);
			}

			if (!FindNextChangeNotification(m_hChangeDir)) {
				OutputDebugStringW(L"ERROR: FindNextChangeNotification");
				break;
			}
		}
		else {
			OutputDebugStringW(L"WaitForSingleObject");
			break;
		}
	}
	if (!m_fTerminate)
		FindCloseChangeNotification(m_hChangeDir);
	m_hChangeDir = INVALID_HANDLE_VALUE;
	_endthreadex(0);
	return 0;
}
Example #25
0
Scene::Scene()
	: d3d9(NULL)
	, device(NULL)
	, vertexDecl(NULL)
	, quadVB(NULL)
	, initialState(NULL)
	, state0(NULL)
	, state1(NULL)
	, rtMain(NULL)
	, rtState0(NULL)
	, rtState1(NULL)
	, parity(0)
	, hWnd(NULL)
{
	wchar_t curDir[MAX_PATH];
	GetCurrentDirectory(MAX_PATH, curDir);

	shaderDirWatcherHandle = FindFirstChangeNotification(curDir, TRUE, 
		FILE_NOTIFY_CHANGE_FILE_NAME |
		FILE_NOTIFY_CHANGE_DIR_NAME |
		FILE_NOTIFY_CHANGE_ATTRIBUTES |
		FILE_NOTIFY_CHANGE_SIZE |
		FILE_NOTIFY_CHANGE_LAST_WRITE |
		FILE_NOTIFY_CHANGE_SECURITY
		); 

	if (shaderDirWatcherHandle != INVALID_HANDLE_VALUE)
	{
		OutputDebugString(L"Watch for dir '");
		OutputDebugString(curDir);
		OutputDebugString(L"'\n");
	} else
	{
		OutputDebugString(L"Watch for dir - failed!\n");
	}

	//D3DXQuaternionRotationYawPitchRoll(&cameraRotation, 0.0f, 0.0f, 0.0f);
}
Example #26
0
void RegesterFolderAndFileDetect()
{
    HANDLE notify = FindFirstChangeNotification(
        L"D:\\test", TRUE,
        FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES |
        FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_SIZE);

    if (notify == INVALID_HANDLE_VALUE)
    {
        assert(notify);
        return;
    }

    while(1)
    {
        WaitForSingleObject(notify, INFINITE);
        OutputDebugString(L"目录有改变\n");
        FindNextChangeNotification(notify);
    }

    FindCloseChangeNotification(notify);

}
Example #27
0
DWORD WINAPI ChangeNotifyThread(NOTIFY_DATA *pnd)
{
	HANDLE hChange;
	DWORD  dwResult;
	TCHAR  szDirectory[MAX_PATH];

	lstrcpy(szDirectory, pnd->szFile);

	// get the directory name from filename
	if(GetFileAttributes(szDirectory) != FILE_ATTRIBUTE_DIRECTORY)
	{
		TCHAR *slash = _tcsrchr(szDirectory, _T('\\'));
		if(slash) *slash = '\0';
	}
	
	// watch the specified directory for changes
	hChange = FindFirstChangeNotification(szDirectory, FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE);

	do
	{
		HANDLE hEventList[2] = { hChange, pnd->hQuitEvent };
		
		if((dwResult = WaitForMultipleObjects(1, hEventList, FALSE, INFINITE)) == WAIT_OBJECT_0)
		{
			PostMessage(pnd->hwndNotify, pnd->uMsg, 0, (LPARAM)pnd);
		}

		FindNextChangeNotification(hChange);
	} 
	while(dwResult == WAIT_OBJECT_0);

	// cleanup
	FindCloseChangeNotification(hChange);
	free(pnd);

	return 0;
}
Example #28
0
	virtual void OnInitDialog()
	{
		// set columns
		LVCOLUMN col;
		col.mask = LVCF_TEXT | LVCF_WIDTH;
		col.pszText = TranslateT("Profile");
		col.cx = 100;
		m_profileList.InsertColumn(0, &col);

		col.pszText = TranslateT("Driver");
		col.cx = 150 - GetSystemMetrics(SM_CXVSCROLL);
		m_profileList.InsertColumn(1, &col);

		col.pszText = TranslateT("Size");
		col.cx = 60;
		m_profileList.InsertColumn(2, &col);

		// icons
		HIMAGELIST hImgList = ImageList_Create(16, 16, ILC_MASK | ILC_COLOR32, 2, 1);
		ImageList_AddIcon_NotShared(hImgList, MAKEINTRESOURCE(IDI_USERDETAILS));
		ImageList_AddIcon_NotShared(hImgList, MAKEINTRESOURCE(IDI_DELETE));
		ImageList_AddIcon_NotShared(hImgList, MAKEINTRESOURCE(IDI_MWARNING));
		ImageList_AddIcon_NotShared(hImgList, MAKEINTRESOURCE(IDI_MFATAL));

		// LV will destroy the image list
		m_profileList.SetImageList(hImgList, LVSIL_SMALL);
		m_profileList.SetExtendedListViewStyle(m_profileList.GetExtendedListViewStyle() | LVS_EX_DOUBLEBUFFER | LVS_EX_INFOTIP | LVS_EX_LABELTIP | LVS_EX_FULLROWSELECT);

		// find all the profiles
		ProfileEnumData ped(m_profileList, m_pd->ptszProfile);
		findProfiles(m_pd->ptszProfileDir, EnumProfilesForList, (LPARAM)&ped);
		PostMessage(m_hwnd, WM_FOCUSTEXTBOX, 0, 0);

		m_hFileNotify = FindFirstChangeNotification(m_pd->ptszProfileDir, TRUE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE);
		if (m_hFileNotify != INVALID_HANDLE_VALUE)
			SetTimer(m_hwnd, 0, 1200, NULL);
	}
Example #29
0
unsigned int FileSystemWatcher::WatchRegister(LPVOID lpParameter)
{
	HANDLE Handle=FindFirstChangeNotification(Directory.data(), WatchSubtree,
									FILE_NOTIFY_CHANGE_FILE_NAME|
									FILE_NOTIFY_CHANGE_DIR_NAME|
									FILE_NOTIFY_CHANGE_ATTRIBUTES|
									FILE_NOTIFY_CHANGE_SIZE|
									FILE_NOTIFY_CHANGE_LAST_WRITE);
	WatchRegistered.Set();

	MultiWaiter waiter;
	waiter.Add(Handle);
	waiter.Add(Done);
	if (waiter.Wait(false, INFINITE) == WAIT_OBJECT_0)
	{
		Changed.Set();
		Done.Wait();
	}

	DoneDone.Set();
	FindCloseChangeNotification(Handle);

	return 0;
}
Example #30
0
static void watch_directory(folder_watcher* pfw)
{
	DWORD dwWaitStatus;
	HANDLE dwChangeHandles[2];
	TCHAR lpDrive[4];
	TCHAR lpFile[_MAX_FNAME];
	TCHAR lpExt[_MAX_EXT];

	_tsplitpath_s(LPTSTR(pfw->get_directory().data()), lpDrive, 4, NULL, 0, lpFile, _MAX_FNAME, lpExt, _MAX_EXT);

	lpDrive[2] = (TCHAR)'\\';
	lpDrive[3] = (TCHAR)'\0';

	// Watch the directory for file creation and deletion. 

	dwChangeHandles[0] = FindFirstChangeNotification(
		LPTSTR(pfw->get_directory().data()), // directory to watch 
		TRUE,                         // do not watch subtree 
		pfw->get_filter()); // watch file name changes 

	if (dwChangeHandles[0] == INVALID_HANDLE_VALUE)
	{
		printf("\n ERROR: FindFirstChangeNotification function failed.\n");
		ExitProcess(GetLastError());
	}

	// Watch the subtree for directory creation and deletion. 
	
	dwChangeHandles[1] = FindFirstChangeNotification(
		lpDrive,                       // directory to watch 
		TRUE,                          // watch the subtree 
		FILE_NOTIFY_CHANGE_DIR_NAME);  // watch dir name changes 

	if (dwChangeHandles[1] == INVALID_HANDLE_VALUE)
	{
		printf("\n ERROR: FindFirstChangeNotification function failed.\n");
		ExitProcess(GetLastError());
	}


	// Make a final validation check on our handles.

	if ((dwChangeHandles[0] == NULL) || (dwChangeHandles[1] == NULL))
	{
		printf("\n ERROR: Unexpected NULL from FindFirstChangeNotification.\n");
		ExitProcess(GetLastError());
	}

	// Change notification is set. Now wait on both notification 
	// handles and refresh accordingly. 

	while (true)
	{
		// Wait for notification.

		//printf("\nWaiting for notification...\n");

		dwWaitStatus = WaitForMultipleObjects(2, dwChangeHandles, FALSE, WAIT_TIME);

		if (!pfw->is_running())
		{
			break;
		}

		switch (dwWaitStatus)
		{
		case WAIT_OBJECT_0:

			// A file was created, renamed, or deleted in the directory.
			// Refresh this directory and restart the notification.
			//printf("fileupdate\n");
			pfw->call_callback();
			if (FindNextChangeNotification(dwChangeHandles[0]) == FALSE)
			{
				printf("\n ERROR: FindNextChangeNotification function failed.\n");
				ExitProcess(GetLastError());
			}
			
			break;

		case WAIT_OBJECT_0 + 1:

			// A directory was created, renamed, or deleted.
			// Refresh the tree and restart the notification.
			//printf("folderupdate\n");
			pfw->call_callback();
			if (FindNextChangeNotification(dwChangeHandles[1]) == FALSE)
			{
				printf("\n ERROR: FindNextChangeNotification function failed.\n");
				ExitProcess(GetLastError());
			}
			break;

		case WAIT_TIMEOUT:

			// A timeout occurred, this would happen if some value other 
			// than INFINITE is used in the Wait call and no changes occur.
			// In a single-threaded environment you might not want an
			// INFINITE wait.

			//printf("\nNo changes in the timeout period.\n");
			break;

		default:
			printf("\n ERROR: Unhandled dwWaitStatus.\n");
			ExitProcess(GetLastError());
			break;
		}
	}
}