コード例 #1
0
int Win::DoModal()
{
	WinID lastParentFC = parent ? parent->lastFocusChild : 0; 
	bool visibled = IsVisible();
	bool enabled = IsEnabled();
	try {
		if (!visibled) Show();
		if (!enabled) Enable(true);

		if (parent && type != WT_POPUP) parent->RecalcLayouts();

		AppBlock(GetID());
		UnblockTree(GetID());

		ModalStruct modalStruct;
		modal = &modalStruct;

		MSG msg;
		
		while (!modalStruct.end) 
		{
			wth_DoEvents();
			if (modalStruct.end) break;

			if (!PeekMessage(&msg, NULL, 0, 0,PM_NOREMOVE))
			{
				unsigned waitTime = RunTimers();
				if (waitTime > 5000) waitTime = 5000;
				if (modalStruct.end) break;

				HANDLE thEvent = wthInternalEvent.SignalFD();
				DWORD res = MsgWaitForMultipleObjects(1,&thEvent,FALSE, waitTime, QS_ALLINPUT);

				if (res == WAIT_TIMEOUT) CheckMousePosition();

				continue;
			}

			if (!GetMessage(&msg, NULL, 0, 0)) 
				break;

			DispatchMessage(&msg);
		}

		modal = 0;
		AppUnblock(GetID());
		if (!visibled) Hide();

///
		if (type == WT_POPUP || type == WT_CHILD && parent) 
		{
			Win *w = GetWinByID(lastParentFC);
			if (w) w->SetFocus();
		}

		return modalStruct.id;
	} catch (...) {
		modal = 0;
		AppUnblock(GetID());
		if (!visibled) Hide(); 
		throw;
	}
}
コード例 #2
0
int
rpl_select (int nfds, fd_set *rfds, fd_set *wfds, fd_set *xfds,
            struct timeval *timeout)
{
  static struct timeval tv0;
  static HANDLE hEvent;
  HANDLE h, handle_array[FD_SETSIZE + 2];
  fd_set handle_rfds, handle_wfds, handle_xfds;
  struct bitset rbits, wbits, xbits;
  unsigned char anyfds_in[FD_SETSIZE / CHAR_BIT];
  DWORD ret, wait_timeout, nhandles, nsock, nbuffer;
  MSG msg;
  int i, fd, rc;

  if (nfds > FD_SETSIZE)
    nfds = FD_SETSIZE;

  if (!timeout)
    wait_timeout = INFINITE;
  else
    {
      wait_timeout = timeout->tv_sec * 1000 + timeout->tv_usec / 1000;

      /* select is also used as a portable usleep.  */
      if (!rfds && !wfds && !xfds)
        {
          Sleep (wait_timeout);
          return 0;
        }
    }

  if (!hEvent)
    hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);

  handle_array[0] = hEvent;
  nhandles = 1;
  nsock = 0;

  /* Copy descriptors to bitsets.  At the same time, eliminate
     bits in the "wrong" direction for console input buffers
     and screen buffers, because screen buffers are waitable
     and they will block until a character is available.  */
  memset (&rbits, 0, sizeof (rbits));
  memset (&wbits, 0, sizeof (wbits));
  memset (&xbits, 0, sizeof (xbits));
  memset (anyfds_in, 0, sizeof (anyfds_in));
  if (rfds)
    for (i = 0; i < rfds->fd_count; i++)
      {
        fd = rfds->fd_array[i];
        h = (HANDLE) _get_osfhandle (fd);
        if (IsConsoleHandle (h)
            && !GetNumberOfConsoleInputEvents (h, &nbuffer))
          continue;

        rbits.in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
        anyfds_in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
      }
  else
    rfds = (fd_set *) alloca (sizeof (fd_set));

  if (wfds)
    for (i = 0; i < wfds->fd_count; i++)
      {
        fd = wfds->fd_array[i];
        h = (HANDLE) _get_osfhandle (fd);
        if (IsConsoleHandle (h)
            && GetNumberOfConsoleInputEvents (h, &nbuffer))
          continue;

        wbits.in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
        anyfds_in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
      }
  else
    wfds = (fd_set *) alloca (sizeof (fd_set));

  if (xfds)
    for (i = 0; i < xfds->fd_count; i++)
      {
        fd = xfds->fd_array[i];
        xbits.in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
        anyfds_in[fd / CHAR_BIT] |= 1 << (fd & (CHAR_BIT - 1));
      }
  else
    xfds = (fd_set *) alloca (sizeof (fd_set));

  /* Zero all the fd_sets, including the application's.  */
  FD_ZERO (rfds);
  FD_ZERO (wfds);
  FD_ZERO (xfds);
  FD_ZERO (&handle_rfds);
  FD_ZERO (&handle_wfds);
  FD_ZERO (&handle_xfds);

  /* Classify handles.  Create fd sets for sockets, poll the others. */
  for (i = 0; i < nfds; i++)
    {
      if ((anyfds_in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))) == 0)
        continue;

      h = (HANDLE) _get_osfhandle (i);
      if (!h)
        {
          errno = EBADF;
          return -1;
        }

      if (IsSocketHandle (h))
        {
          int requested = FD_CLOSE;

          /* See above; socket handles are mapped onto select, but we
             need to map descriptors to handles.  */
          if (rbits.in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
            {
              requested |= FD_READ | FD_ACCEPT;
              FD_SET ((SOCKET) h, rfds);
              FD_SET ((SOCKET) h, &handle_rfds);
            }
          if (wbits.in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
            {
              requested |= FD_WRITE | FD_CONNECT;
              FD_SET ((SOCKET) h, wfds);
              FD_SET ((SOCKET) h, &handle_wfds);
            }
          if (xbits.in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
            {
              requested |= FD_OOB;
              FD_SET ((SOCKET) h, xfds);
              FD_SET ((SOCKET) h, &handle_xfds);
            }

          WSAEventSelect ((SOCKET) h, hEvent, requested);
          nsock++;
        }
      else
        {
          handle_array[nhandles++] = h;

          /* Poll now.  If we get an event, do not wait below.  */
          if (wait_timeout != 0
              && windows_poll_handle (h, i, &rbits, &wbits, &xbits))
            wait_timeout = 0;
        }
    }

  if (wait_timeout == 0 || nsock == 0)
    rc = 0;
  else
    {
      /* See if we need to wait in the loop below.  If any select is ready,
         do MsgWaitForMultipleObjects anyway to dispatch messages, but
         no need to call select again.  */
      rc = select (0, &handle_rfds, &handle_wfds, &handle_xfds, &tv0);
      if (rc == 0)
        {
          /* Restore the fd_sets for the other select we do below.  */
          memcpy (&handle_rfds, rfds, sizeof (fd_set));
          memcpy (&handle_wfds, wfds, sizeof (fd_set));
          memcpy (&handle_xfds, xfds, sizeof (fd_set));
        }
      else
        wait_timeout = 0;
    }

  for (;;)
    {
      ret = MsgWaitForMultipleObjects (nhandles, handle_array, FALSE,
                                       wait_timeout, QS_ALLINPUT);

      if (ret == WAIT_OBJECT_0 + nhandles)
        {
          /* new input of some other kind */
          BOOL bRet;
          while ((bRet = PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) != 0)
            {
              TranslateMessage (&msg);
              DispatchMessage (&msg);
            }
        }
      else
        break;
    }

  /* If we haven't done it yet, check the status of the sockets.  */
  if (rc == 0 && nsock > 0)
    rc = select (0, &handle_rfds, &handle_wfds, &handle_xfds, &tv0);

  /* Now fill in the results.  */
  FD_ZERO (rfds);
  FD_ZERO (wfds);
  FD_ZERO (xfds);

  /* Place a sentinel at the end of the array.  */
  handle_array[nhandles] = NULL;
  nhandles = 1;
  for (i = 0; i < nfds; i++)
    {
      if ((anyfds_in[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1)))) == 0)
        continue;

      h = (HANDLE) _get_osfhandle (i);
      if (h != handle_array[nhandles])
        {
          /* Perform handle->descriptor mapping.  Don't update rc, as these
             results are counted in the return value of Winsock's select.  */
          WSAEventSelect ((SOCKET) h, NULL, 0);
          if (FD_ISSET (h, &handle_rfds))
            FD_SET (i, rfds);
          if (FD_ISSET (h, &handle_wfds))
            FD_SET (i, wfds);
          if (FD_ISSET (h, &handle_xfds))
            FD_SET (i, xfds);
        }
      else
        {
          /* Not a socket.  */
          nhandles++;
          windows_poll_handle (h, i, &rbits, &wbits, &xbits);
          if (rbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
            {
              rc++;
              FD_SET (i, rfds);
            }
          if (wbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
            {
              rc++;
              FD_SET (i, wfds);
            }
          if (xbits.out[i / CHAR_BIT] & (1 << (i & (CHAR_BIT - 1))))
            {
              rc++;
              FD_SET (i, xfds);
            }
        }
    }

  return rc;
}
コード例 #3
0
DWORD Scheduler::SchedulerThreadProcPrivate()
{
    HRESULT hr = S_OK;
    MSG     msg;
    LONG    lWait = INFINITE;
    BOOL    bExitThread = FALSE;

    // Force the system to create a message queue for this thread.
    // (See MSDN documentation for PostThreadMessage.)
    PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);

    // Signal to the scheduler that the thread is ready.
    SetEvent(m_hThreadReadyEvent);

    while( !bExitThread )
    {
        // Wait for a thread message OR until the wait time expires.
        DWORD dwResult = MsgWaitForMultipleObjects(0, NULL, FALSE, lWait, QS_POSTMESSAGE);

        if (dwResult == WAIT_TIMEOUT)
        {
            // If we timed out, then process the samples in the queue
            hr = ProcessSamplesInQueue(&lWait);
            if (FAILED(hr))
            {
                bExitThread = TRUE;
            }
        }

        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            BOOL bProcessSamples = TRUE;

            switch (msg.message) 
            {
            case eTerminate:
                TRACE((L"eTerminate\n"));
                bExitThread = TRUE;
                break;

            case eFlush:
                // Flushing: Clear the sample queue and set the event.
                m_ScheduledSamples.Clear();
                lWait = INFINITE;
                SetEvent(m_hFlushEvent);
                break;

            case eSchedule:
                // Process as many samples as we can.
                if (bProcessSamples)
                {
                    hr = ProcessSamplesInQueue(&lWait);
                    if (FAILED(hr))
                    {
                        bExitThread = TRUE;
                    }
                    bProcessSamples = (lWait != INFINITE); 
                }
                break;
            } // switch  

        } // while PeekMessage
    
    }  // while (!bExitThread)

    TRACE((L"Exit scheduler thread.\n"));
    return (SUCCEEDED(hr) ? 0 : 1);
}
コード例 #4
0
ファイル: prg2wav_gui.c プロジェクト: bitfixer/bitfixer
static void choose_destination_file_and_convert(HWND hwnd, struct prg2wav_params *params)
{
  char name[1024] = "";
  OPENFILENAMEA ofn;
  BOOL success;
  int freq;
  struct tapdec_params tapdec_params;
  struct play_pause_stop play_pause_stop = { .pause = 0 };
  HANDLE thread;
  DWORD thread_id;
  MSG msg;
  BOOL end_found = FALSE;
  uint8_t videotype;
  LRESULT selected_clock, selected_waveform;
  HBITMAP stop_icon;
  BOOL is_to_sound;

  name[0] = 0;
  freq = GetDlgItemInt(hwnd, IDC_FREQ, &success, FALSE);
  if (!success)
    freq = 44100;
  tapdec_params.volume = GetDlgItemInt(hwnd, IDC_VOL, &success, FALSE);
  if (!success)
    tapdec_params.volume = 254;
  if (tapdec_params.volume < 1)
    tapdec_params.volume = 1;
  tapdec_params.inverted = (IsDlgButtonChecked(hwnd, IDC_INVERTED) == BST_CHECKED);
  selected_clock =
    SendMessage(GetDlgItem(hwnd, IDC_MACHINE_TO), CB_GETCURSEL, 0, 0);
  switch(selected_clock){
    default:
      params->machine = TAP_MACHINE_C64;
      videotype = TAP_VIDEOTYPE_PAL;
      break;
    case 1:
      params->machine = TAP_MACHINE_C64;
      videotype = TAP_VIDEOTYPE_NTSC;
      break;
    case 2:
      params->machine = TAP_MACHINE_VIC;
      videotype = TAP_VIDEOTYPE_PAL;
      break;
    case 3:
      params->machine = TAP_MACHINE_VIC;
      videotype = TAP_VIDEOTYPE_NTSC;
      break;
    case 4:
      params->machine = TAP_MACHINE_C16;
      videotype = TAP_VIDEOTYPE_PAL;
      break;
    case 5:
      params->machine = TAP_MACHINE_C16;
      videotype = TAP_VIDEOTYPE_NTSC;
      break;
  }
  selected_waveform =
    SendMessage(GetDlgItem(hwnd, IDC_WAVEFORM), CB_GETCURSEL, 0, 0);
  switch(selected_waveform){
    default:
      tapdec_params.waveform = AUDIOTAP_WAVE_TRIANGLE;
      break;
    case 1:
      tapdec_params.waveform = AUDIOTAP_WAVE_SQUARE;
      break;
    case 2:
      tapdec_params.waveform = AUDIOTAP_WAVE_SINE;
      break;
  }

  if (IsDlgButtonChecked(hwnd, IDC_TO_WAV)) {
    if (audiotap_startup_status.audiofile_init_status != LIBRARY_OK) {
      MessageBoxA(hwnd,
                 "Cannot save to WAV: audiofile.dll is missing, invalid or incorrectly installed",
                 "WAV-PRG error", MB_ICONERROR);
      remove_all_simple_block_list_elements(&params->program);
      return;
    }
    memset(&ofn, 0, sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);
    ofn.hwndOwner = hwnd;
    ofn.lpstrFilter = "WAV files\0*.wav\0All files\0*.*\0\0";
    ofn.Flags = (OFN_EXPLORER | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT);
    ofn.lpstrFile = name;
    ofn.nMaxFile = sizeof(name);
    ofn.lpstrTitle = "Choose the WAV file to save to";
    ofn.lpstrDefExt = "wav";
    ofn.lpstrFile = name;
    ofn.nMaxFile = sizeof(name);

    if (!GetSaveFileNameA(&ofn)) {
      remove_all_simple_block_list_elements(&params->program);
      return;
    }
    if (tap2audio_open_to_wavfile4(&play_pause_stop.file, name, &tapdec_params, freq,
                            params->machine, videotype) != AUDIOTAP_OK) {
      MessageBoxA(hwnd, "Error opening file", "WAV-PRG error", MB_ICONERROR);
      remove_all_simple_block_list_elements(&params->program);
      return;
    }
  }
  else if (IsDlgButtonChecked(hwnd, IDC_TO_SOUND)) {
    if (audiotap_startup_status.portaudio_init_status != LIBRARY_OK) {
      MessageBoxA(hwnd,
                 "Cannot play to sound card: libportaudio.dll is missing, invalid or incorrectly installed",
                 "WAV-PRG error", MB_ICONERROR);
      remove_all_simple_block_list_elements(&params->program);
      return;
    }
    if (tap2audio_open_to_soundcard4(&play_pause_stop.file, &tapdec_params, freq,
                            params->machine, videotype) != AUDIOTAP_OK) {
      MessageBoxA(hwnd, "Error opening sound card", "WAV-PRG error",
                 MB_ICONERROR);
      remove_all_simple_block_list_elements(&params->program);
      return;
    }
  }
  else {
    uint8_t version;

    memset(&ofn, 0, sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);
    ofn.hwndOwner = hwnd;
    ofn.lpstrFilter = "TAP files\0*.tap\0All files\0*.*\0\0";
    ofn.Flags = (OFN_EXPLORER
                 | OFN_HIDEREADONLY
                 | OFN_OVERWRITEPROMPT | OFN_ENABLETEMPLATE | OFN_ENABLEHOOK);
    ofn.lpstrFile = name;
    ofn.nMaxFile = sizeof(name);
    ofn.lpstrTitle = "Choose the TAP file to save to";
    ofn.lpstrDefExt = "tap";
    ofn.lpfnHook = tap_save_hook_proc;
    ofn.lpstrFile = name;
    ofn.nMaxFile = sizeof(name);
    ofn.hInstance = instance;
    ofn.lpTemplateName = MAKEINTRESOURCEA(IDD_CHOOSE_TAP_VERSION);
    ofn.lCustData = (LPARAM)&version;

    if (!GetSaveFileNameA(&ofn)) {
      remove_all_simple_block_list_elements(&params->program);
      return;
    }
    if (tap2audio_open_to_tapfile3(&play_pause_stop.file, name, version, params->machine, videotype) !=
        AUDIOTAP_OK) {
      MessageBoxA(hwnd, "Error opening TAP file", "WAV-PRG error",
                 MB_ICONERROR);
      remove_all_simple_block_list_elements(&params->program);
      return;
    }
  }

  params->file = play_pause_stop.file;

  params->status_window =
    CreateDialog(instance, MAKEINTRESOURCE(IDD_PRG2WAV_STATUS), hwnd,
                 prg2wav_status_window_proc);
  EnableWindow(hwnd, FALSE);
  ShowWindow(params->status_window, SW_SHOWNORMAL);
  UpdateWindow(params->status_window);
  SetWindowLong(params->status_window, GWL_USERDATA, (LONG)&play_pause_stop);
  thread = CreateThread(NULL, 0, prg2wav_thread, params, 0, &thread_id);
  is_to_sound = IsDlgButtonChecked(hwnd, IDC_TO_SOUND);
  if (is_to_sound) {
    HWND stop_button = GetDlgItem(params->status_window, IDCANCEL);
    RECT window_rect, play_pause_button_rect;
    stop_icon = LoadBitmap(instance, MAKEINTRESOURCE(IDB_STOP));
    play_pause_stop.play_icon = LoadBitmap(instance, MAKEINTRESOURCE(IDB_PLAY));
    play_pause_stop.pause_icon = LoadBitmap(instance, MAKEINTRESOURCE(IDB_PAUSE));
    /* make sure the pause button is visible and shows the pause icon*/
    SendDlgItemMessage(params->status_window, IDC_PLAYPAUSE, BM_SETIMAGE, (WPARAM)IMAGE_BITMAP, (LPARAM)play_pause_stop.pause_icon);
    ShowWindow(GetDlgItem(params->status_window, IDC_PLAYPAUSE), SW_SHOW);
    /* get width of window */
    GetClientRect(params->status_window, &window_rect);
    /* get absolute position of play-pause button */
    GetWindowRect(GetDlgItem(params->status_window, IDC_PLAYPAUSE), &play_pause_button_rect);
    /* get position of play-pause button within window */
    MapWindowPoints(NULL, params->status_window, (LPPOINT)&play_pause_button_rect, 2);
    /* make stop button as big as play-pause button, top-aligned and symmetrically placed */
    MoveWindow(stop_button,
      window_rect.right - play_pause_button_rect.right,
      play_pause_button_rect.top,
      play_pause_button_rect.right - play_pause_button_rect.left,
      play_pause_button_rect.bottom - play_pause_button_rect.top,
      TRUE);
    /* make sure the stop button shows the stop icon instead of the word Cancel*/
    SetWindowLongPtr(stop_button, GWL_STYLE, GetWindowLongPtr(stop_button, GWL_STYLE) | BS_BITMAP);
    SendDlgItemMessage(params->status_window, IDCANCEL, BM_SETIMAGE, (WPARAM)IMAGE_BITMAP, (LPARAM)stop_icon);
  }

  while (1) {
    DWORD retval;
    retval =
      MsgWaitForMultipleObjects(1, &thread, FALSE, INFINITE, QS_ALLINPUT);
    if (retval == WAIT_OBJECT_0)
      break;
    while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
      if (is_to_sound && msg.message == WM_KEYDOWN) {
        if (msg.wParam == VK_MEDIA_PLAY_PAUSE)
          PostMessage (params->status_window, WM_COMMAND, IDC_PLAYPAUSE, 0);
        else if (msg.wParam == VK_MEDIA_STOP)
          PostMessage (params->status_window, WM_COMMAND, IDCANCEL, 0);
      }
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
  }

  EnableWindow(hwnd, TRUE);
  DestroyWindow(params->status_window);

  tap2audio_close(params->file);
  remove_all_simple_block_list_elements(&params->program);
  if (IsDlgButtonChecked(hwnd, IDC_TO_SOUND)) {
    DeleteObject(play_pause_stop.play_icon);
    DeleteObject(play_pause_stop.pause_icon);
    DeleteObject(stop_icon);
  }
}

static void choose_file(HWND hwnd){
  char name[1024] = "";
  OPENFILENAMEA ofn;
  struct prg2wav_params params;

  params.program = NULL;

  memset(&ofn, 0, sizeof(ofn));
  ofn.lStructSize = sizeof(ofn);
  ofn.hwndOwner = hwnd;
  ofn.hInstance = instance;
  ofn.lpstrFilter =
    "All supported types\0*.t64;*.prg;*.p00\0Tape image files (*.t64)\0*.t64\0Program files (*.prg)\0*.prg\0PC64 files (*.p00)\0*.p00\0All files\0*.*\0\0";
  ofn.lpstrCustomFilter = NULL;
  ofn.nMaxCustFilter = 0;
  ofn.nFilterIndex = 1;
  ofn.lpstrFile = name;
  ofn.nMaxFile = sizeof(name);
  ofn.lpstrFileTitle = NULL;
  ofn.nMaxFileTitle = 0;
  ofn.lpstrInitialDir = NULL;
  ofn.lpstrTitle = "Choose the PRG, P00 or T64 file";
  ofn.Flags = (OFN_EXPLORER
               | OFN_HIDEREADONLY
               | OFN_NOTESTFILECREATE
               | OFN_FILEMUSTEXIST
               | OFN_ENABLEHOOK | OFN_ENABLETEMPLATE | OFN_SHAREAWARE);
  ofn.lpfnHook = frompc_hook_proc;
  ofn.lpTemplateName = MAKEINTRESOURCEA(IDD_CONTENTS);
  ofn.nFileOffset = 0;
  ofn.nFileExtension = 0;
  ofn.lpstrDefExt = NULL;
  ofn.lCustData = (LPARAM)&params.program;

  if (GetOpenFileNameA(&ofn))
    choose_destination_file_and_convert(hwnd, &params);
}
コード例 #5
0
STDMETHODIMP CXMLDOMDocument::loadXML(BSTR bstrXML, VARIANT_BOOL  *isSuccessful)
{
	ATLTRACE(_T("CXMLDOMDocument::loadXML\n"));

	if (NULL == isSuccessful)
		return E_POINTER;

	*isSuccessful = VARIANT_FALSE;

	// do not start another thread if there is another active
	if (NULL != m_hParseThread) {
		DWORD exitCode = 0;
		BOOL rc = ::GetExitCodeThread(m_hParseThread, &exitCode);
		if (!rc || STILL_ACTIVE == exitCode)
			return S_OK;
		
		::CloseHandle(m_hParseThread);
		m_hParseThread = NULL;
	}

	HRESULT hr = S_OK;
	m_bAbort = false;
	
	m_FileName = _T("");
	m_TmpDocument = 0;
	m_bThreadValidate = m_bValidate;
	
	m_xml = bstrXML;
	if (0 == m_xml.length())
		return E_INVALIDARG;

	UINT nthreadID = 0;
	m_hParseThread = reinterpret_cast<HANDLE> (_beginthreadex(NULL,
												 0,
											     CXMLDOMDocument::ParseThread,
												 (void *) this,
												 0,
												 &nthreadID));
	if (NULL == m_hParseThread)
		return S_OK;
	
	if (m_bAsync) {
		*isSuccessful = VARIANT_TRUE;
		return S_OK;
	}

	bool bWait = true;
	while (bWait) {
		DWORD dwEvt = MsgWaitForMultipleObjects(1,&m_hParseThread,FALSE,INFINITE,QS_ALLINPUT);
		switch(dwEvt) {
			case WAIT_OBJECT_0:
				bWait = false;
				break;
			case WAIT_OBJECT_0 + 1:
			{
				MSG msg;
				while(::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
					if (WM_CLOSE == msg.message || WM_QUIT == msg.message) {
						 bWait = false;
						 m_bAbort = true;
						 break;
					}
					else {
						PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
						TranslateMessage(&msg);
						DispatchMessage(&msg);
					}
				}
				break;
			}
			default:
				m_bAbort = true;
				bWait = false;
				break;
		}
	}

	if (m_bAbort)
		return S_OK;

	if (m_bParseError)
		return hr;

    if(m_Document)
        delete m_Document;
	m_Document = m_TmpDocument;
	m_TmpDocument = 0;
	
	m_url = m_FileName;
	*isSuccessful = VARIANT_TRUE;
	
	return hr;
}
コード例 #6
0
//on thread can only call putSync once on the callstack.
DSRequest DSRequestQueue::putSync(DSRequest req, BOOL bKeepUIActive)
{	
	HANDLE hEvents[1]; 
	DWORD dwWaitResult;
	int iDebug=0;
	HRESULT hr = S_OK;

	ASSERT(m_pSetRequests);
	if(!m_pSetRequests || !m_dwThreadWorker)
	{
		DSRequest req;
		req.setHR(E_FAIL);
		return req;
	}

	m_pSetRequests->AddRef();
	DSTSSetOfRequests *pSetRequests = m_pSetRequests;

	//not important what this handle is.
	hEvents[0]=m_hThreadWorker;
	ASSERT(hEvents[0]);
	EnterCriticalSection(&m_critsec);
		DSRequest returnValue;		
		
		//put into queue.
		req.putSync(m_dwTotalRequests);		
		put(req);
		
	//leave the critical section so others can put stuff in.		
	LeaveCriticalSection(&m_critsec);	

	//Wait for message to come.
	MSG msg;
	BOOL bRet;
	BOOL bQuit=FALSE;
	
	//
	//Note that we have the possibility of this call stack:
	// putsync (A)
	//    wait for (A).
	//        putsync (B).
	//            wait for (B).
	//                 (A) appears.
	//                 (B) appears.

	CString strMsg = "PutSync threadID:"+str(::GetCurrentThreadId())+"\n";
	TRACE(strMsg);

	DSTSSetOfRequests::FindResult fr;
				
	while(!bQuit)
	{
		dwWaitResult = MsgWaitForMultipleObjects(1,hEvents,FALSE,1000,QS_ALLEVENTS);
	
		if(dwWaitResult==WAIT_TIMEOUT)
			TRACE("PutSync::MsgWait timed out: %i\n", iDebug++);
		else if((dwWaitResult>=WAIT_OBJECT_0) && (dwWaitResult<= (WAIT_OBJECT_0 + 2)))
			TRACE("PutSync::MsgWait got a signal: %i\n", iDebug++);
		else if((dwWaitResult>=WAIT_ABANDONED_0) && (dwWaitResult <= (WAIT_ABANDONED_0 + 2 - 1 )))
			TRACE("PutSync::MsgWait abandoned: %i\n", iDebug++);
		else if((dwWaitResult>=WAIT_IO_COMPLETION) && (dwWaitResult <= (WAIT_IO_COMPLETION + 2 - 1)))
			TRACE("PutSync::MsgWait IO_COMPLETION: %i\n", iDebug++);		
		else if(dwWaitResult==0xFFFFFFFF)
		{
			TRACE("MsgWait failed: %i\n", iDebug++);		
			DWORD dwError = GetLastError();	
			LPVOID lpMsgBuf;
			FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
			    dwError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf,    0,    NULL );
			TRACE((LPTSTR)lpMsgBuf);
			LocalFree( lpMsgBuf );

			//This is caused by the invalid handle of the closed thread. It's okay.
		}
		else ASSERT(0);
		
		bRet = ::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);
		
		while(bRet && !bQuit)
		{
			bRet = ::GetMessage(&msg, NULL, 0, 0);
			
			ASSERT( (int)bRet != -1 );
			if (bRet)
			{
				if(msg.message==WM_SYNC_CALL_FINISHED)
				{				 			    
					ASSERT(msg.hwnd==NULL);

					DSRequest tempRetvalue;
					tempRetvalue.putSync(msg.wParam);

					//look for a response of ID tempRetValue. This will fill the rest of the struct out.
					fr = pSetRequests->find(tempRetvalue,tempRetvalue);
					if(fr == DSTSSetOfRequests::FR_TERMINATE)
					{
						TRACE("PutSync: The worker thread has terminated. Quiting without waiting for Signal\n.");
						bQuit=TRUE;					
					}
					else if(fr == DSTSSetOfRequests::FR_FOUND)
					{
						if(tempRetvalue==req)
						{
							//the operation is finished.
							bQuit=TRUE;
							
							//TODO: fire off event.
							returnValue=tempRetvalue;
						}
						else
						{
							//it's a different one.
							//check, just in case, if our req is in the map.
							fr = pSetRequests->find(req,returnValue);
							if(fr == DSTSSetOfRequests::FR_TERMINATE)
							{
								TRACE("PutSync: The worker thread has terminated. Quiting without waiting for Signal\n.");
								bQuit=TRUE;
							}
							else if(fr == DSTSSetOfRequests::FR_FOUND)
							{
								//The only time this should happen is below, the case where we're currently in 
								// a dispatch message.
								ASSERT(0);
								pSetRequests->remove(req);
								
								bQuit=TRUE;					
							}
						}
					}
				}
				else
				{
					// TRACE("DSQueue::PutSync: Got a non-queue message: %x.\n", msg.message);
					
					if(bKeepUIActive)
						::DispatchMessage(&msg);
							
					DSRequest outReq;
					//sets returnValue if found.
					fr = pSetRequests->find(req,returnValue);
					if(DSTSSetOfRequests::FR_FOUND == fr)
					{
						pSetRequests->remove(req);
						
						bQuit=TRUE;					
					}
					else if(DSTSSetOfRequests::FR_TERMINATE == fr)
					{
						bQuit=TRUE;					
					}
				}
			}

			bRet = ::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);		
		}
	}

	pSetRequests->Release();

	return returnValue;
}	
コード例 #7
0
ファイル: debug-helper.c プロジェクト: Jactry/virt-viewer
int
main(int argc, char *argv[])
{
    char pipe[2048];
    MSG msg;
    STARTUPINFO si = { 0, };
    PROCESS_INFORMATION pi = { 0, };
    gchar *program_path = get_program_path();
    gchar *command;
    int rv = 0;

    argv[0] = "gdb -ex run --args";
    command = g_strjoinv(" ", argv);

    snprintf(pipe, sizeof(pipe), "\\\\.\\pipe\\SpiceController-%lu", GetCurrentProcessId());

    SetEnvironmentVariable("SPICE_DEBUG", "1");
    SetEnvironmentVariable("G_MESSAGES_DEBUG", "all");
    SetEnvironmentVariable("SPICE_XPI_NAMEDPIPE", pipe);

    si.cb = sizeof(si);
    if (!CreateProcess(NULL,
                       command,
                       NULL,
                       NULL,
                       FALSE,
                       0,
                       NULL,
                       program_path,
                       &si,
                       &pi)) {
        printf("CreateProcess failed (%ld).\n", GetLastError());
        rv = 1;
        goto end;
    }


    while (1) {
        DWORD reason = MsgWaitForMultipleObjects(1, &pi.hProcess, FALSE,
                                                 INFINITE, QS_ALLINPUT);
        if (reason == WAIT_OBJECT_0)
            break;
        else {
            if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
    }

    // Close process and thread handles
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);

end:
    g_free(program_path);
    g_free(command);

    exit(rv);
    return rv;
}
コード例 #8
0
ファイル: GraphicsCaptureHook.cpp プロジェクト: Crehl/OBS
DWORD WINAPI CaptureThread(HANDLE hDllMainThread)
{
    bool bSuccess = false;

    //wait for dll initialization to finish before executing any initialization code
    if(hDllMainThread)
    {
        WaitForSingleObject(hDllMainThread, INFINITE);
        CloseHandle(hDllMainThread);
    }

    TCHAR lpLogPath[MAX_PATH];
    SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, lpLogPath);
    wcscat_s(lpLogPath, MAX_PATH, TEXT("\\OBS\\pluginData\\captureHookLog.txt"));

    dummyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

    if(!logOutput.is_open())
        logOutput.open(lpLogPath, ios_base::in | ios_base::out | ios_base::trunc, _SH_DENYNO);

    wstringstream str;
    str << OBS_KEEPALIVE_EVENT << UINT(GetCurrentProcessId());
    strKeepAlive = str.str();

    logOutput << CurrentDateTimeString() << "we're booting up: " << endl;

    InitializeCriticalSection(&d3d9EndMutex);
    InitializeCriticalSection(&glMutex);

    WNDCLASS wc;
    ZeroMemory(&wc, sizeof(wc));
    wc.hInstance = hinstMain;
    wc.lpszClassName = SENDER_WINDOWCLASS;
    wc.lpfnWndProc = (WNDPROC)DefWindowProc;

    DWORD procID = GetCurrentProcessId();

    wstringstream strRestartEvent, strEndEvent, strReadyEvent, strExitEvent, strInfoMemory;
    strRestartEvent << RESTART_CAPTURE_EVENT << procID;
    strEndEvent     << END_CAPTURE_EVENT     << procID;
    strReadyEvent   << CAPTURE_READY_EVENT   << procID;
    strExitEvent    << APP_EXIT_EVENT        << procID;
    strInfoMemory   << INFO_MEMORY           << procID;

    hSignalRestart  = GetEvent(strRestartEvent.str().c_str());
    hSignalEnd      = GetEvent(strEndEvent.str().c_str());
    hSignalReady    = GetEvent(strReadyEvent.str().c_str());
    hSignalExit     = GetEvent(strExitEvent.str().c_str());

    hInfoFileMap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(CaptureInfo), strInfoMemory.str().c_str());
    if(!hInfoFileMap)
    {
        logOutput << CurrentTimeString() << "CaptureThread: could not info file mapping" << endl;
        return 0;
    }

    infoMem = (CaptureInfo*)MapViewOfFile(hInfoFileMap, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(CaptureInfo));
    if(!infoMem)
    {
        logOutput << CurrentTimeString() << "CaptureThread: could not map view of info shared memory" << endl;
        CloseHandle(hInfoFileMap);
        hInfoFileMap = NULL;
        return 0;
    }

    hwndOBS = FindWindow(OBS_WINDOW_CLASS, NULL);
    if(!hwndOBS)
    {
        logOutput << CurrentTimeString() << "CaptureThread: could not find main application window?  wtf?  seriously?" << endl;
        return 0;
    }

    if (RegisterClass(&wc)) {
        hwndSender = CreateWindow(SENDER_WINDOWCLASS, NULL, 0, 0, 0, 0, 0, NULL, 0, hinstMain, 0);
        if (hwndSender) {
            textureMutexes[0] = OpenMutex(MUTEX_ALL_ACCESS, FALSE, TEXTURE_MUTEX1);
            if (textureMutexes[0]) {
                textureMutexes[1] = OpenMutex(MUTEX_ALL_ACCESS, FALSE, TEXTURE_MUTEX2);
                if (textureMutexes[1]) {
                    while(!AttemptToHookSomething())
                        Sleep(50);

                    logOutput << CurrentTimeString() << "(half life scientist) everything..  seems to be in order" << endl;

                    MSG msg;
                    while (MsgWaitForMultipleObjects(1, &dummyEvent, FALSE, 3000, QS_ALLPOSTMESSAGE) != WAIT_ABANDONED_0) {
                    //while (1) {
                        AttemptToHookSomething();

                        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
                            TranslateMessage(&msg);
                            DispatchMessage(&msg);
                        }

                        //Sleep(50);
                    }

                    CloseHandle(textureMutexes[1]);
                    textureMutexes[1] = NULL;
                } else {
                    logOutput << CurrentTimeString() << "could not open texture mutex 2" << endl;
                }

                CloseHandle(textureMutexes[0]);
                textureMutexes[0] = NULL;
            } else {
                logOutput << CurrentTimeString() << "could not open texture mutex 1" << endl;
            }

            DestroyWindow(hwndSender);
        } else {
            logOutput << CurrentTimeString() << "could not create sender window" << endl;
        }
    }

    logOutput << CurrentTimeString() << "exit out of the main thread loop somehow" << endl;

    return 0;
}
コード例 #9
0
ファイル: PigEngine.cpp プロジェクト: borgified/Allegiance
void CPigEngine::ScriptDirMonitor(HANDLE hevtExit)
{
  assert(m_hDirChange && INVALID_HANDLE_VALUE != m_hDirChange);

  // Enter this thread into the MTA
  _SVERIFYE(CoInitializeEx(NULL, COINIT_MULTITHREADED));

  // Declare an enum and an array of objects on which to wait
  enum {e_DirChange = WAIT_OBJECT_0, e_Exit, e_Msg};
  HANDLE hObjs[] = {m_hDirChange, hevtExit};
  const int cObjs = sizeofArray(hObjs);

  // Process change notification until exit
  UINT idTimer = 0;
  DWORD dwWait = MsgWaitForMultipleObjects(cObjs, hObjs, false, INFINITE,
    QS_ALLINPUT);
  while (e_Exit != dwWait)
  {
    if (e_DirChange == dwWait)
    {
      // Reset the timer
      if (idTimer)
        KillTimer(NULL, idTimer);
      idTimer = SetTimer(NULL, 0, 2000, NULL);

      // Continue waiting for change notifications
      if (!FindNextChangeNotification(m_hDirChange))
      {
        #ifdef _DEBUG
          DWORD dwLastError = ::GetLastError();
          debugf("\nCPigEngine::ScriptDirMonitor(): "
            "FindNextChangeNotification Failed : "
            "GetLastError() = 0x%08X, m_hDirChange = 0x%08X\n",
            dwLastError, m_hDirChange);
        #endif // _DEBUG
        Sleep(1000);
      }
    }
    else // (e_Msg == dwWait)
    {
      MSG msg;
      while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
      {
        if (WM_TIMER == msg.message)
        {
          assert(msg.wParam == idTimer);

          // Kill the timer
          KillTimer(NULL, idTimer);
          idTimer = 0;

          // Process the files in the directory
          ProcessScriptDirChanges();
        }
        else if (WM_QUIT == msg.message)
        {
          dwWait = e_Exit;
          break;
        }
      }
    }

    // Continue waiting
    dwWait = MsgWaitForMultipleObjects(cObjs, hObjs, false, INFINITE,
      QS_ALLINPUT);
  }

  // Remove this thread from the MTA
  CoUninitialize();

  // Clear the thread pointer
  InterlockedExchange((long*)&m_pth, 0);
}
コード例 #10
0
/// <summary>
/// Creates the main window and begins processing
/// </summary>
/// <param name="hInstance">handle to the application instance</param>
/// <param name="nCmdShow">whether to display minimized, maximized, or normally</param>
int Direct2DWindow::Run(HINSTANCE hInstance, int nCmdShow)
{
    MSG       msg = {0};
    WNDCLASS  wc;

    // Dialog custom window class
    ZeroMemory(&wc, sizeof(wc));
    wc.style         = CS_HREDRAW | CS_VREDRAW;
    wc.cbWndExtra    = DLGWINDOWEXTRA;
    wc.hInstance     = hInstance;
    wc.hCursor       = LoadCursorW(NULL, IDC_ARROW);
    wc.hIcon         = LoadIconW(hInstance, MAKEINTRESOURCE(IDI_APP));
    wc.lpfnWndProc   = DefDlgProcW;
    wc.lpszClassName = L"DepthBasicsAppDlgWndClass";

    if (!RegisterClassW(&wc))
    {
        return 0;
    }

    // Create main application window
    HWND hWndApp = CreateDialogParamW(
        hInstance,
        MAKEINTRESOURCE(IDD_APP),
        NULL,
        (DLGPROC)Direct2DWindow::MessageRouter, 
        reinterpret_cast<LPARAM>(this));

    // Show window
    ShowWindow(hWndApp, nCmdShow);

    const int eventCount = 2;
    HANDLE hEvents[eventCount];

    // Main message loop
    while (WM_QUIT != msg.message)
    {
        hEvents[0] = m_cdmap->GetNextDepthFrameEvent();
        hEvents[1] = m_cdmap->GetNextColorFrameEvent();

        // Check to see if we have either a message (by passing in QS_ALLINPUT)
        // Or a Kinect event (hEvents)
        // Update() will check for Kinect events individually, in case more than one are signalled
        MsgWaitForMultipleObjects(eventCount, hEvents, FALSE, INFINITE, QS_ALLINPUT);

        // Explicitly check the Kinect frame event since MsgWaitForMultipleObjects
        // can return for other reasons even though it is signaled.
        Update();

        while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE))
        {
            // If a dialog message will be taken care of by the dialog proc
            if ((hWndApp != NULL) && IsDialogMessageW(hWndApp, &msg))
            {
                continue;
            }

            TranslateMessage(&msg);
            DispatchMessageW(&msg);
        }
    }

    return static_cast<int>(msg.wParam);
}
コード例 #11
0
inline DWORD CSplashScreen::PumpMsgWaitForMultipleObjects(HWND hWnd, DWORD nCount, LPHANDLE pHandles, DWORD dwMilliseconds)
{
	// useful variables
	const DWORD dwStartTickCount = ::GetTickCount();
	// loop until done
	for (;;)
	{
		// calculate timeout
		const DWORD dwElapsed = GetTickCount() - dwStartTickCount;
		const DWORD dwTimeout = dwMilliseconds == INFINITE ? INFINITE :dwElapsed < dwMilliseconds ? dwMilliseconds - dwElapsed : 0;

		// wait for a handle to be signaled or a message
		const DWORD dwWaitResult = MsgWaitForMultipleObjects(nCount, pHandles, FALSE, dwTimeout, QS_ALLINPUT);

		if (dwWaitResult == WAIT_OBJECT_0 + nCount)
		{
			// pump messages
			MSG msg;

			while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != FALSE)
			{
				// check for WM_QUIT
				if (msg.message == WM_QUIT)
				{
					// repost quit message and return
					PostQuitMessage((int) msg.wParam);
					return WAIT_OBJECT_0 + nCount;
				}

				// dispatch thread message
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}
		else
		{
			// check fade event (pHandles[1]).  If the fade event is not set then we simply need to exit.  
			// if the fade event is set then we need to fade out  
			const DWORD dwWaitResult = MsgWaitForMultipleObjects(1, &pHandles[1], FALSE, 0, QS_ALLINPUT);
			if (dwWaitResult == WAIT_OBJECT_0) {
				MSG msg;
				// timeout on actual wait or any other object
				SetTimer(hWnd, 1, 30,NULL);
				m_nFadeoutEnd = GetTickCount()+m_nFadeoutTime;
				BOOL bRet;

				while( (bRet = GetMessage( &msg, hWnd, 0, 0 )) != 0)
				{ 
					if (bRet == -1)
					{
						// handle the error and possibly exit
					}
					else
					{
						if (msg.message==WM_TIMER) {
							if (FadeWindowOut(hWnd)) { // finished
								return dwWaitResult;
							}
						}
						TranslateMessage(&msg); 
						DispatchMessage(&msg); 
					}
				}
			}
			return dwWaitResult;
		}
	}
}
コード例 #12
0
ファイル: hidapi_ext_win.cpp プロジェクト: Finlod/Lohi
int hid_event_read_cancellable(hid_event_monitor* monitor, hid_event* event, hid_cancel_token* cancel_token) {
	auto current_thread_id = GetCurrentThreadId();
	auto monitor_thread_id = GetWindowThreadProcessId(monitor->hwnd, NULL);

	if (current_thread_id != monitor_thread_id) {
		printf("hid_event_read_cancellable failed, monitor have to be created" \
			   " in the same thread which is calling this function.");

		return -1;
	}

	DWORD res = 0;

	DWORD handle_count = 0;
	HANDLE handle = NULL;

	if (cancel_token) {
		handle_count = 1;
		handle = cancel_token->event_handle;
	}

	while (true) {
		//will wait for cancel event and events send/posted to this thread
		res = MsgWaitForMultipleObjects(handle_count, &handle, FALSE, INFINITE, QS_ALLINPUT);

		if (cancel_token && res == WAIT_OBJECT_0) {
			return READ_CANCELLED;
		}

		if (res != WAIT_OBJECT_0 + handle_count) {
			if (res == WAIT_FAILED) {
				DWORD last_error = GetLastError();
				printf("hid_event_read_cancellable failed, WAIT_FAILED, last error: %ul", last_error);
				return -1;
			}

			//some other error with no last error set
			return -1;
		}

		MSG msg;
		//PeekMesssage will call WindowProc where monitor->event struct is set
		//Because device messages are send not posted to queue, PeekMessage
		// will return as if there wasn't any messages, so msg struct & return
		// value is useless
		PeekMessage(&msg, monitor->hwnd, 0, 0, PM_REMOVE);

		//There might be messages other than what we want, if message was what we
		// wanted we set proc_real_event to true in WindowProc, else false
		if (monitor->proc_real_event) {
			//monitors event is reused on every WindowProc so we have to copy all of its contents
			event->action = monitor->proc_event.action;
			event->device_info->path = monitor->proc_event.device_info->path;

			if (event->action == EVENT_ADD) {
				parse_info_from_path(event, monitor->proc_event.device_info->path);
			}

			//we don't free string allocated in WindowProc here, its now part
			// of event and therefore caller of this function has the
			// responsibility of freeing event & its stuff (path)
			monitor->proc_event.device_info->path = NULL;

			monitor->proc_real_event = false;
			break;
		}
	}

	return 0;
}
コード例 #13
0
/**
 * Win32 select() will only work with sockets, so we roll our own
 * implementation here.
 * - If you supply only sockets, this simply passes through to winsock select().
 * - If you supply file handles, there is no way to distinguish between
 *   ready for read/write or OOB, so any set in which the handle is found will
 *   be marked as ready.
 * - If you supply a mixture of handles and sockets, the system will interleave
 *   calls between select() and WaitForMultipleObjects(). The time slicing may
 *   cause this function call to take up to 100 ms longer than you specified.
 * - Pipes are not checked for writability or errors (errno = ENOSYS)
 */
int _win_select(int max_fd, fd_set * rfds, fd_set * wfds, fd_set * efds,
                const struct timeval *tv)
{
  DWORD ms_total, limit;
  HANDLE handles[MAXIMUM_WAIT_OBJECTS], hPipes[MAXIMUM_WAIT_OBJECTS];
  int handle_slot_to_fd[MAXIMUM_WAIT_OBJECTS];
  int n_handles, i, iPipes;
  fd_set sock_read, sock_write, sock_except;
  fd_set aread, awrite, aexcept;
  int sock_max_fd;
  struct timeval tvslice;
  int retcode;

#define SAFE_FD_ISSET(fd, set)	(set != NULL && FD_ISSET(fd, set))

  n_handles = 0;
  sock_max_fd = -1;
  iPipes = 0;

  /* calculate how long we need to wait in milliseconds */
  if(tv == NULL)
    ms_total = INFINITE;
  else
  {
    ms_total = tv->tv_sec * 1000;
    ms_total += tv->tv_usec / 1000;
  }

  /* select() may be used as a portable way to sleep */
  if (!(rfds || wfds || efds))
  {
    Sleep(ms_total);

    return 0;
  }

  FD_ZERO(&sock_read);
  FD_ZERO(&sock_write);
  FD_ZERO(&sock_except);

  /* build an array of handles for non-sockets */
  for(i = 0; i < max_fd; i++)
  {
    if(SAFE_FD_ISSET(i, rfds) || SAFE_FD_ISSET(i, wfds) ||
       SAFE_FD_ISSET(i, efds))
    {
      unsigned long ulVal;

      if (ioctlsocket(i, FIONREAD, &ulVal) != SOCKET_ERROR && _get_osfhandle(i) == -1) 
      {
        /* socket */
        if(SAFE_FD_ISSET(i, rfds))
          FD_SET(i, &sock_read);

        if(SAFE_FD_ISSET(i, wfds))
          FD_SET(i, &sock_write);

        if(SAFE_FD_ISSET(i, efds))
          FD_SET(i, &sock_except);

        if(i > sock_max_fd)
          sock_max_fd = i;
      }
      else
      {
        if (GetFileType((HANDLE) i) == FILE_TYPE_PIPE)
          hPipes[iPipes++] = (HANDLE) i;  /* Pipe */
        else
        {
          handles[n_handles] = (HANDLE) _get_osfhandle(i);
          if ((DWORD) handles[n_handles] == 0xffffffff)
            handles[n_handles] = (HANDLE) i;
          handle_slot_to_fd[n_handles] = i;
          n_handles++;
        }
      }
    }
  }

  if((n_handles == 0) && (iPipes == 0))
  {
    /* plain sockets only - let winsock handle the whole thing */
    if ((retcode = select(max_fd, rfds, wfds, efds, tv)) == SOCKET_ERROR)
      SetErrnoFromWinsockError(WSAGetLastError());
    return retcode;  
  }

  /* mixture of handles and sockets; lets multiplex between
   * winsock and waiting on the handles */

  FD_ZERO(&aread);
  FD_ZERO(&awrite);
  FD_ZERO(&aexcept);

  limit = GetTickCount() + ms_total;
  do
  {
    retcode = 0;

    if(sock_max_fd >= 0)
    {
      /* overwrite the zero'd sets here; the select call
       * will clear those that are not active */
      aread = sock_read;
      awrite = sock_write;
      aexcept = sock_except;

      tvslice.tv_sec = 0;
      tvslice.tv_usec = 100000;

      if ((retcode = select(sock_max_fd + 1, &aread, &awrite, &aexcept,
                            &tvslice)) == SOCKET_ERROR)
      {
        SetErrnoFromWinsockError(WSAGetLastError());

        return -1;
      }
    }

    if(n_handles > 0)
    {
      /* check handles */
      DWORD wret;

      wret =
        MsgWaitForMultipleObjects(n_handles, handles, FALSE,
                                  retcode > 0 ? 0 : 100, QS_ALLEVENTS);

      if(wret == WAIT_TIMEOUT)
      {
        /* set retcode to 0; this is the default.
         * select() may have set it to something else,
         * in which case we leave it alone, so this branch
         * does nothing */
        ;
      }
      else if(wret == WAIT_FAILED)
      {
        SetErrnoFromWinError(GetLastError());

        return -1;
      }
      else
      {
        for(i = 0; i < n_handles; i++)
        {
          if(WAIT_OBJECT_0 == WaitForSingleObject(handles[i], 0))
          {
            if(SAFE_FD_ISSET(handle_slot_to_fd[i], rfds))
            {
              FD_SET(handle_slot_to_fd[i], &aread);
            }

            if(SAFE_FD_ISSET(handle_slot_to_fd[i], wfds))
              FD_SET(handle_slot_to_fd[i], &awrite);

            if(SAFE_FD_ISSET(handle_slot_to_fd[i], efds))
              FD_SET(handle_slot_to_fd[i], &aexcept);

            retcode++;
          }
        }
      }
    }

    /* Poll Pipes */
    for(i = 0; i < iPipes; i++)
    {
      DWORD dwBytes;
      if(SAFE_FD_ISSET(hPipes[i], rfds))
      {
	    if (! PeekNamedPipe(hPipes[i], NULL, 0, NULL, &dwBytes, NULL))
	    {
	      retcode = -1;
	      SetErrnoFromWinError(GetLastError());
	    }
	    else if (dwBytes)
	    {
	      FD_SET((int) hPipes[i], &aread);
	      retcode++;
	    }
      }
      else if (SAFE_FD_ISSET(hPipes[i], wfds) || SAFE_FD_ISSET(hPipes[i], efds))
      {
        errno = ENOSYS;
        return -1;  /* Not implemented */
      }
    }
  }
  while(retcode == 0 && (ms_total == INFINITE || GetTickCount() < limit));

  if(rfds)
    *rfds = aread;

  if(wfds)
    *wfds = awrite;

  if(efds)
    *efds = aexcept;

  return retcode;
}
コード例 #14
0
ファイル: ddeclient.c プロジェクト: Moteesh/reactos
/******************************************************************
 *		WDML_SyncWaitTransactionReply
 *
 * waits until an answer for a sent request is received
 * time out is also handled. only used for synchronous transactions
 */
static HDDEDATA WDML_SyncWaitTransactionReply(HCONV hConv, DWORD dwTimeout, const WDML_XACT* pXAct, DWORD *ack)
{
    DWORD	start, elapsed;
    DWORD	err;
    WDML_CONV*	pConv;

    TRACE("Starting wait for a timeout of %d ms\n", dwTimeout);

    start = GetTickCount();
    while ((elapsed = GetTickCount() - start) < dwTimeout)
    {
	/* we cannot be in the crit sect all the time because when client and server run in a
	 * single process they need to share the access to the internal data
	 */
	if (MsgWaitForMultipleObjects(0, NULL, FALSE,
				      dwTimeout - elapsed, QS_POSTMESSAGE) == WAIT_OBJECT_0)
	{
	    MSG		msg;

	    while (PeekMessageW(&msg, 0, WM_DDE_FIRST, WM_DDE_LAST, PM_REMOVE))
	    {
                HDDEDATA hdd = NULL;

                pConv = WDML_GetConv(hConv, FALSE);
                if (pConv == NULL)
                {
                    /* conversation no longer available... return failure */
                    return 0;
                }
                if (msg.hwnd == pConv->hwndClient)
                {
                    /* check that either pXAct has been processed or no more xActions are pending */
                    BOOL ret = (pConv->transactions == pXAct);
                    if (WDML_HandleReply(pConv, &msg, &hdd, ack) == WDML_QS_HANDLED)
                    {
                        TRACE("WDML_HandleReply returned WDML_QS_HANDLED\n");
                        ret = TRUE;
                    }
                    else
                        ret = (pConv->transactions == NULL || ret);

                    if (ret)
                    {
                        pConv->instance->lastError = hdd ? DMLERR_NO_ERROR : DMLERR_NOTPROCESSED;
                        return hdd;
                    }
                }
                else
                {
                    DispatchMessageW(&msg);
                }
            }
	}
    }

    TRACE("Timeout !!\n");

    pConv = WDML_GetConv(hConv, FALSE);
    if (pConv != NULL)
    {
	if (pConv->transactions)
	{
	    switch (pConv->transactions->ddeMsg)
	    {
	    case WM_DDE_ADVISE:		err = DMLERR_ADVACKTIMEOUT;	break;
	    case WM_DDE_REQUEST:	err = DMLERR_DATAACKTIMEOUT; 	break;
	    case WM_DDE_EXECUTE:	err = DMLERR_EXECACKTIMEOUT;	break;
	    case WM_DDE_POKE:		err = DMLERR_POKEACKTIMEOUT;	break;
	    case WM_DDE_UNADVISE:	err = DMLERR_UNADVACKTIMEOUT;	break;
	    default:			err = DMLERR_INVALIDPARAMETER;	break;
	    }

	    pConv->instance->lastError = err;
	}
    }

    return 0;
}
コード例 #15
0
void CGame::SleepUntilInput( int time )
{
	MsgWaitForMultipleObjects(1, &m_hEvent, FALSE, time, QS_KEY );
}
コード例 #16
0
ファイル: wf_client.c プロジェクト: Distrotech/FreeRDP
DWORD WINAPI wf_client_thread(LPVOID lpParam)
{
	MSG msg;
	int width;
	int height;
	BOOL msg_ret;
	int quit_msg;
	DWORD nCount;
	HANDLE handles[64];
	wfContext* wfc;
	freerdp* instance;
	rdpContext* context;
	rdpChannels* channels;
	rdpSettings* settings;
	BOOL async_input;
	BOOL async_transport;
	HANDLE input_thread;

	instance = (freerdp*) lpParam;
	context = instance->context;
	wfc = (wfContext*) instance->context;

	if (!freerdp_connect(instance))
		return 0;

	channels = instance->context->channels;
	settings = instance->context->settings;

	async_input = settings->AsyncInput;
	async_transport = settings->AsyncTransport;

	if (async_input)
	{
		if (!(input_thread = CreateThread(NULL, 0,
				(LPTHREAD_START_ROUTINE) wf_input_thread,
				instance, 0, NULL)))
		{
			WLog_ERR(TAG, "Failed to create async input thread.");
			goto disconnect;
		}
	}

	while (1)
	{
		nCount = 0;

		if (freerdp_focus_required(instance))
		{
			wf_event_focus_in(wfc);
			wf_event_focus_in(wfc);
		}

		if (!async_transport)
		{
			DWORD tmp = freerdp_get_event_handles(context, &handles[nCount], 64 - nCount);

			if (tmp == 0)
			{
				WLog_ERR(TAG, "freerdp_get_event_handles failed");
				break;
			}

			nCount += tmp;
		}

		if (MsgWaitForMultipleObjects(nCount, handles, FALSE, 1000, QS_ALLINPUT) == WAIT_FAILED)
		{
			WLog_ERR(TAG, "wfreerdp_run: WaitForMultipleObjects failed: 0x%04X", GetLastError());
			break;
		}

		if (!async_transport)
		{
			if (!freerdp_check_event_handles(context))
			{
				if (wf_auto_reconnect(instance))
					continue;

				WLog_ERR(TAG, "Failed to check FreeRDP file descriptor");
				break;
			}
		}

		if (freerdp_shall_disconnect(instance))
			break;

		quit_msg = FALSE;

		while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
		{
			msg_ret = GetMessage(&msg, NULL, 0, 0);

			if (instance->settings->EmbeddedWindow)
			{
				if ((msg.message == WM_SETFOCUS) && (msg.lParam == 1))
				{
					PostMessage(wfc->hwnd, WM_SETFOCUS, 0, 0);
				}
				else if ((msg.message == WM_KILLFOCUS) && (msg.lParam == 1))
				{
					PostMessage(wfc->hwnd, WM_KILLFOCUS, 0, 0);
				}
			}

			if (msg.message == WM_SIZE)
			{
				width = LOWORD(msg.lParam);
				height = HIWORD(msg.lParam);

				SetWindowPos(wfc->hwnd, HWND_TOP, 0, 0, width, height, SWP_FRAMECHANGED);
			}

			if ((msg_ret == 0) || (msg_ret == -1))
			{
				quit_msg = TRUE;
				break;
			}

			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}

		if (quit_msg)
			break;
	}

	/* cleanup */
	freerdp_channels_disconnect(channels, instance);

	if (async_input)
	{
		wMessageQueue* input_queue;
		input_queue = freerdp_get_message_queue(instance, FREERDP_INPUT_MESSAGE_QUEUE);
		if (MessageQueue_PostQuit(input_queue, 0))
			WaitForSingleObject(input_thread, INFINITE);
		CloseHandle(input_thread);
	}

disconnect:
	freerdp_disconnect(instance);
	WLog_DBG(TAG, "Main thread exited.");

	ExitThread(0);
	return 0;
}
コード例 #17
0
ファイル: radish-runner.c プロジェクト: taxler/radish
int WINAPI WinMain(HINSTANCE instance, HINSTANCE prev_instance, char* command_line, int show_command) {
#else
int main(int argc, char*[] argv) {
#endif
	radish_state* radish;
	radish_window host_window;
	radish_init_for_states();
	radish = radish_create_state(L"main.lua");
	radish->main_fiber = ConvertThreadToFiber(NULL);
	radish->script_fiber = radish_create_script_fiber(radish);
	radish_init_host_window(radish, &host_window);

	if (radish_script_step(radish)) {
		radish_create_window(radish, &host_window);
		radish_update_first(radish);
		// script may have terminated during the create window phase
		while (radish_script_running(radish)) {
			DWORD timeout = radish_update_timeout(radish);
			DWORD result = MsgWaitForMultipleObjects(
				radish->wait_object_count,
				radish->wait_objects,
				FALSE,
				timeout,
				QS_ALLINPUT);
			if (result == WAIT_OBJECT_0 + radish->wait_object_count) {
				while (PeekMessage(&radish->msg, NULL, 0, 0, PM_REMOVE)) {
					UINT message = radish->msg.message;
					HWND hwnd = radish->msg.hwnd;
					WPARAM wparam = radish->msg.wParam;
					LPARAM lparam = radish->msg.lParam;
					if (hwnd == NULL) {
						radish_script_step(radish);
						// overridable default behaviours
						if (radish->msg.message != WMRADISH_HANDLED) {
							switch (message) {
								case WMRADISH_DIALOG_REQUEST:
									radish_do_dialog(radish, (radish_dialog*)lparam);
									if (wparam != 0) {
										PostThreadMessage((UINT)wparam, WMRADISH_DIALOG_RESPONSE, 0, lparam);
									}
									else {
										radish->msg.message = WMRADISH_DIALOG_RESPONSE;
										radish->msg.lParam = lparam;
										radish_script_step(radish);
										radish_free_dialog(radish, (radish_dialog*)lparam);
									}
									break;
							}
						}
						// non-overridable default behaviours
						switch (message) {
							case WMRADISH_THREAD_TERMINATED:
								// TODO: make sure all strings etc are freed too
								free((radish_state*)lparam);
								break;
							case WMRADISH_THREAD_SEND_DATA:
								radish_buffer_free((radish_buffer*)lparam);
								break;
						}
					}
					else {
		                if (radish->accelerator_table != NULL && TranslateAccelerator(
								radish->msg.hwnd, radish->accelerator_table, &radish->msg)) {
		                    // don't TranslateMessage
		                }
		                else {
							TranslateMessage(&radish->msg);
							DispatchMessageW(&radish->msg);
						}
					}

				}
			}
			else if (result >= WAIT_OBJECT_0 && result < (WAIT_OBJECT_0 + radish->wait_object_count)) {
				radish->msg.message = WMRADISH_WAIT_OBJECT_SIGNALLED;
				radish->msg.hwnd = NULL;
				radish->msg.lParam = (LPARAM)(result - WAIT_OBJECT_0);
				radish->msg.wParam = (WPARAM)radish->wait_objects[radish->msg.lParam];
				radish_script_step(radish);
				radish_update_maybe(radish);
			}
			else if (result >= WAIT_ABANDONED_0 && result < (WAIT_ABANDONED_0 + radish->wait_object_count)) {
				radish->msg.message = WMRADISH_MUTEX_ABANDONED;
				radish->msg.hwnd = NULL;
				radish->msg.lParam = (LPARAM)(result - WAIT_ABANDONED_0);
				radish->msg.wParam = (WPARAM)radish->wait_objects[radish->msg.lParam];
				radish_script_step(radish);
				radish_update_maybe(radish);
			}
			else if (result == WAIT_TIMEOUT) {
				radish_update_certain(radish);
				if (timeout == 0) Sleep(0);
			}
			else if (result == WAIT_FAILED) {
				radish->error = L"MsgWaitForMultipleObjects Error";
				goto finalize;
			}
			else {
				radish->error = L"Unknown result from MsgWaitForMultipleObjects";
				goto finalize;
			}
		}
	}

finalize:

	if (radish->error != NULL) {
		MessageBoxW(NULL, radish->error, radish_get_title(), MB_OK | MB_ICONERROR);
		return EXIT_FAILURE;
	}
	return EXIT_SUCCESS;
}

int fseek64_wrap(FILE* f, __int64 off, int whence) {
	if(f == NULL) return -1;

#ifdef __MINGW32__
	return fseeko64(f, off, whence);
#elif defined (_WIN32)
	return _fseeki64(f, off, whence);
#else
	return fseek(f, off, whence);
#endif

}
コード例 #18
0
static int Launch()
{
  Log(L"Launching browser...");

  DWORD processID;

  // The interface that allows us to activate the browser
  CComPtr<IApplicationActivationManager> activateMgr;
  if (FAILED(CoCreateInstance(CLSID_ApplicationActivationManager, nullptr,
                              CLSCTX_LOCAL_SERVER,
                              IID_IApplicationActivationManager,
                              (void**)&activateMgr))) {
    Fail(false, L"CoCreateInstance CLSID_ApplicationActivationManager failed.");
    return FAILURE;
  }
  
  HRESULT hr;
  WCHAR appModelID[256];
  // Activation is based on the browser's registered app model id
  if (!GetDefaultBrowserAppModelID(appModelID, (sizeof(appModelID)/sizeof(WCHAR)))) {
    Fail(false, L"GetDefaultBrowserAppModelID failed.");
    return FAILURE;
  }
  Log(L"App model id='%s'", appModelID);

  // Hand off focus rights if the terminal has focus to the out-of-process
  // activation server (explorer.exe). Without this the metro interface
  // won't launch.
  hr = CoAllowSetForegroundWindow(activateMgr, nullptr);
  if (FAILED(hr)) {
    // Log but don't fail. This has happened on vms with certain terminals run by
    // QA during mozmill testing.
    Log(L"Windows focus rights hand off failed (HRESULT=0x%X). Ignoring.", hr);
  }

  Log(L"Harness process id: %d", GetCurrentProcessId());

  // If provided, validate the firefox path passed in.
  int binLen = wcslen(kFirefoxExe);
  if (sFirefoxPath.GetLength() && sFirefoxPath.Right(binLen) != kFirefoxExe) {
    Log(L"firefoxpath is missing a valid bin name! Assuming '%s'.", kFirefoxExe);
    if (sFirefoxPath.Right(1) != L"\\") {
      sFirefoxPath += L"\\";
    }
    sFirefoxPath += kFirefoxExe;
  }

  // Because we can't pass command line args, we store params in a
  // tests.ini file in dist/bin which the browser picks up on launch.
  CStringA testFilePath;
  if (sFirefoxPath.GetLength()) {
    // Use the firefoxpath passed to us by the test harness
    int index = sFirefoxPath.ReverseFind('\\');
    if (index == -1) {
      Fail(false, L"Bad firefoxpath path");
      return FAILURE;
    }
    testFilePath = sFirefoxPath.Mid(0, index);
    testFilePath += "\\";
    testFilePath += kMetroTestFile;
  } else {
    // Use the module path
    char path[MAX_PATH];
    if (!GetModuleFileNameA(nullptr, path, MAX_PATH)) {
      Fail(false, L"GetModuleFileNameA errorno=%d", GetLastError());
      return FAILURE;
    }
    char* slash = strrchr(path, '\\');
    if (!slash)
      return FAILURE;
    *slash = '\0'; // no trailing slash
    testFilePath = path;
    testFilePath += "\\";
    sFirefoxPath = testFilePath;
    sFirefoxPath += kFirefoxExe;
    testFilePath += kMetroTestFile;
  }

  // Make sure the firefox bin exists
  if (GetFileAttributesW(sFirefoxPath) == INVALID_FILE_ATTRIBUTES) {
    Fail(false, L"Invalid bin path: '%s'", sFirefoxPath);
    return FAILURE;
  }

  Log(L"Using bin path: '%s'", sFirefoxPath);

  Log(L"Writing out tests.ini to: '%s'", CStringW(testFilePath));
  HANDLE hTestFile = CreateFileA(testFilePath, GENERIC_WRITE,
                                 0, nullptr, CREATE_ALWAYS,
                                 FILE_ATTRIBUTE_NORMAL,
                                 nullptr);
  if (hTestFile == INVALID_HANDLE_VALUE) {
    Fail(false, L"CreateFileA errorno=%d", GetLastError());
    return FAILURE;
  }

  DeleteTestFileHelper dtf(testFilePath);

  // nsAppRunner expects the first param to be the bin path, just like a
  // normal startup. So prepend our bin path to our param string we write.
  CStringA asciiParams = sFirefoxPath;
  asciiParams += " ";
  asciiParams += sAppParams;
  asciiParams.Trim();
  Log(L"Browser command line args: '%s'", CString(asciiParams));
  if (!WriteFile(hTestFile, asciiParams, asciiParams.GetLength(),
                 nullptr, 0)) {
    CloseHandle(hTestFile);
    Fail(false, L"WriteFile errorno=%d", GetLastError());
    return FAILURE;
  }
  FlushFileBuffers(hTestFile);
  CloseHandle(hTestFile);

  // Create a named stdout pipe for the browser
  if (!SetupTestOutputPipe()) {
    Fail(false, L"SetupTestOutputPipe failed (errno=%d)", GetLastError());
    return FAILURE;
  }

  // Launch firefox
  hr = activateMgr->ActivateApplication(appModelID, L"", AO_NOERRORUI, &processID);
  if (FAILED(hr)) {
    Fail(true, L"ActivateApplication result %X", hr);
    return RETRY;
  }

  Log(L"Activation succeeded.");

  // automation.py picks up on this, don't mess with it.
  Log(L"METRO_BROWSER_PROCESS=%d", processID);

  HANDLE child = OpenProcess(SYNCHRONIZE, FALSE, processID);
  if (!child) {
    Fail(false, L"Couldn't find child process. (%d)", GetLastError());
    return FAILURE;
  }

  Log(L"Waiting on child process...");

  MSG msg;
  DWORD waitResult = WAIT_TIMEOUT;
  HANDLE handles[2] = { child, gTestOutputPipe };
  while ((waitResult = MsgWaitForMultipleObjects(2, handles, FALSE, INFINITE, QS_ALLINPUT)) != WAIT_OBJECT_0) {
    if (waitResult == WAIT_FAILED) {
      Log(L"Wait failed (errno=%d)", GetLastError());
      break;
    } else if (waitResult == WAIT_OBJECT_0 + 1) {
      ReadPipe();
    } else if (waitResult == WAIT_OBJECT_0 + 2 &&
               PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
  }

  ReadPipe();
  CloseHandle(gTestOutputPipe);
  CloseHandle(child);

  Log(L"Exiting.");
  return SUCCESS;
}
コード例 #19
0
ファイル: winmain.c プロジェクト: mojca/gnuplot
int ConsoleGetch()
{
    int fd = fileno(stdin);
    HANDLE h;
    DWORD waitResult;

    if (!isatty(fd))
        h = CreateThread(NULL, 0, stdin_pipe_reader, NULL, 0, NULL);
    else
        h = (HANDLE)_get_osfhandle(fd);

    do
    {
        waitResult = MsgWaitForMultipleObjects(1, &h, FALSE, INFINITE, QS_ALLINPUT);
        if (waitResult == WAIT_OBJECT_0)
        {
            if (isatty(fd))
            {
                INPUT_RECORD rec;
                DWORD recRead;

                ReadConsoleInput(h, &rec, 1, &recRead);
                if (recRead == 1 && rec.EventType == KEY_EVENT && rec.Event.KeyEvent.bKeyDown &&
                        (rec.Event.KeyEvent.wVirtualKeyCode < VK_SHIFT ||
                         rec.Event.KeyEvent.wVirtualKeyCode > VK_MENU))
                {
                    if (rec.Event.KeyEvent.uChar.AsciiChar)
                        return rec.Event.KeyEvent.uChar.AsciiChar;
                    else
                        switch (rec.Event.KeyEvent.wVirtualKeyCode)
                        {
                            case VK_UP: return 020;
                            case VK_DOWN: return 016;
                            case VK_LEFT: return 002;
                            case VK_RIGHT: return 006;
                            case VK_HOME: return 001;
                            case VK_END: return 005;
                            case VK_DELETE: return 0117;
                        }
                }
            }
            else
            {
                DWORD c;
                GetExitCodeThread(h, &c);
                CloseHandle(h);
                return c;
            }
        }
        else if (waitResult == WAIT_OBJECT_0+1)
        {
            MSG msg;

            while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
        else
            break;
    } while (1);
}
コード例 #20
0
ファイル: main.c プロジェクト: MortenRoenne/wine
/*********************************************************************
 * test_dlgproc [internal]
 *
 */
static INT_PTR CALLBACK test_dlgproc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
    static HANDLE thread;
    static struct JoystickData *data;
    TRACE("(%p, 0x%08x/%d, 0x%lx)\n", hwnd, msg, msg, lparam);

    switch (msg)
    {
        case WM_INITDIALOG:
        {
            int i;

            data = (struct JoystickData*) ((PROPSHEETPAGEW*)lparam)->lParam;

            /* Add enumerated joysticks to the combobox */
            for (i = 0; i < data->num_joysticks; i++)
            {
                struct Joystick *joy = &data->joysticks[i];
                SendDlgItemMessageW(hwnd, IDC_TESTSELECTCOMBO, CB_ADDSTRING, 0, (LPARAM) joy->instance.tszInstanceName);
            }

            draw_joystick_buttons(hwnd, data);
            draw_joystick_axes(hwnd, data);

            return TRUE;
        }

        case WM_COMMAND:
            switch(wparam)
            {
                case MAKEWPARAM(IDC_TESTSELECTCOMBO, CBN_SELCHANGE):
                    test_handle_joychange(hwnd, data);
                break;
            }
            return TRUE;

        case WM_NOTIFY:
            switch(((LPNMHDR)lparam)->code)
            {
                case PSN_SETACTIVE:
                {
                    DWORD tid;

                    /* Initialize input thread */
                    if (data->num_joysticks > 0)
                    {
                        data->stop = FALSE;

                        /* Set the first joystick as default */
                        SendDlgItemMessageW(hwnd, IDC_TESTSELECTCOMBO, CB_SETCURSEL, 0, 0);
                        test_handle_joychange(hwnd, data);

                        thread = CreateThread(NULL, 0, input_thread, (void*) data, 0, &tid);
                    }
                }
                break;

                case PSN_RESET: /* intentional fall-through */
                case PSN_KILLACTIVE:
                    /* Stop input thread */
                    data->stop = TRUE;
                    MsgWaitForMultipleObjects(1, &thread, FALSE, INFINITE, 0);
                    CloseHandle(thread);
                break;
            }
            return TRUE;
    }
    return FALSE;
}
コード例 #21
0
DWORD FWindowsNativeFeedbackContext::SlowTaskThreadProc(void* ThreadParam)
{
	FWindowsNativeFeedbackContext* Context = (FWindowsNativeFeedbackContext*)ThreadParam;

	HINSTANCE HInstance = (HINSTANCE)GetModuleHandle(NULL);

	WNDCLASSEX WndClassEx;
	ZeroMemory(&WndClassEx, sizeof(WndClassEx));
	WndClassEx.cbSize = sizeof(WndClassEx);
	WndClassEx.style = CS_HREDRAW | CS_VREDRAW | (Context->bShowCancelButton? 0 : CS_NOCLOSE);
	WndClassEx.lpfnWndProc = &SlowTaskWindowProc;
	WndClassEx.hIcon = LoadIcon(HInstance, MAKEINTRESOURCE(FWindowsPlatformMisc::GetAppIcon()));
	WndClassEx.hCursor = LoadCursor(NULL, IDC_ARROW);
	WndClassEx.hInstance = HInstance;
	WndClassEx.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
	WndClassEx.lpszClassName = TEXT("FFeedbackContextWindows");
	ATOM WndClassAtom = RegisterClassEx(&WndClassEx);

	NONCLIENTMETRICS NonClientMetrics;
	NonClientMetrics.cbSize = sizeof(NonClientMetrics);
	SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(NonClientMetrics), &NonClientMetrics, 0);
	HANDLE hFont = CreateFontIndirect(&NonClientMetrics.lfMessageFont);

	int FontHeight = -MulDiv(8, GetDeviceCaps(GetDC(NULL), LOGPIXELSY), 72);
	HANDLE hLogFont = CreateFont(FontHeight, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, FIXED_PITCH | FF_MODERN, TEXT("Courier New"));

	TEXTMETRIC TextMetric;
	HDC hDC = CreateCompatibleDC(NULL);
	HGDIOBJ hPrevObj = SelectObject(hDC, hFont);
	GetTextMetrics(hDC, &TextMetric);
	SelectObject(hDC, hPrevObj);
	DeleteDC(hDC);

	FWindowParams Params;
	Params.Context = Context;
	Params.ScaleX = TextMetric.tmAveCharWidth;
	Params.ScaleY = TextMetric.tmHeight;
	Params.StandardW = Params.ScaleX * 80;
	Params.StandardH = Params.ScaleY * 4;
	Params.bLogVisible = false;

	DWORD WindowStyle = WS_VISIBLE | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME;

	RECT WindowRect;
	ZeroMemory(&WindowRect, sizeof(WindowRect));
	WindowRect.left = (GetSystemMetrics(SM_CXSCREEN) - Params.StandardW) / 2;
	WindowRect.top = (GetSystemMetrics(SM_CYSCREEN) - Params.StandardH) / 2;
	WindowRect.right = WindowRect.left + Params.StandardW;
	WindowRect.bottom = WindowRect.top + Params.StandardH;
	AdjustWindowRectEx(&WindowRect, WindowStyle, 0, 0);

	const TCHAR* WindowClassName = MAKEINTATOM( WndClassAtom );
	HWND hWnd = CreateWindow(WindowClassName, TEXT("Unreal Engine"), WindowStyle, WindowRect.left, WindowRect.top, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top, NULL, NULL, HInstance, NULL);
	SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)&Params);
	SendMessage(hWnd, WM_SETFONT, (WPARAM)hFont, 0);

	HWND hWndOpenLog = CreateWindow(WC_BUTTON, TEXT("Show log"), BS_CENTER | BS_VCENTER | BS_PUSHBUTTON | BS_TEXT | WS_CHILD | WS_VISIBLE, 10, 10, 10, 10, hWnd, (HMENU)ShowLogCtlId, HInstance, NULL);
	SendMessage(hWndOpenLog, WM_SETFONT, (WPARAM)hFont, 0);

	HWND hWndStatus = CreateWindow(WC_STATIC, TEXT(""), SS_CENTER | WS_CHILD | WS_VISIBLE, 10, 10, 10, 10, hWnd, (HMENU)StatusCtlId, HInstance, NULL);
	SendMessage(hWndStatus, WM_SETFONT, (WPARAM)hFont, 0);

	HWND hWndProgress = CreateWindowEx(0, PROGRESS_CLASS, TEXT(""), WS_CHILD | WS_VISIBLE, 10, 10, 10, 10, hWnd, (HMENU)ProgressCtlId, HInstance, NULL);
	SendMessage(hWndProgress, PBM_SETRANGE32, 0, 1000);

	HWND hWndLogOutput = CreateWindowEx(WS_EX_STATICEDGE, WC_EDIT, TEXT(""), ES_MULTILINE | ES_READONLY | WS_HSCROLL | WS_VSCROLL | WS_CHILD | WS_VISIBLE, 10, 10, 10, 10, hWnd, (HMENU)LogOutputCtlId, HInstance, NULL);
	SendMessage(hWndLogOutput, WM_SETFONT, (WPARAM)hLogFont, 0);

	LayoutControls(hWnd, &Params);
	SetEvent(Context->hUpdateEvent);

	ShowWindow(hWnd, SW_SHOW);
	UpdateWindow(hWnd);

	SetForegroundWindow(hWnd);

	FString PrevStatus;
	float PrevProgress = 0.0f;
	int32 PrevLogOutputLength = 0;
	for(;;)
	{
		HANDLE Handles[] = { Context->hCloseEvent, Context->hUpdateEvent };
		DWORD Result = MsgWaitForMultipleObjects(2, Handles, 0, INFINITE, QS_ALLEVENTS);
		if(Result == WAIT_OBJECT_0)
		{
			break;
		}
		else if(Result == WAIT_OBJECT_0 + 1)
		{
			FScopeLock Lock(&Context->CriticalSection);
			if(Context->Status != PrevStatus)
			{
				SetWindowText(hWndStatus, *Context->Status);
				PrevStatus = Context->Status;
			}
			if(Context->Progress != PrevProgress)
			{
				SendMessage(hWndProgress, PBM_SETPOS, (int32)(Context->Progress * 1000.0f), 0);
				PrevProgress = Context->Progress;
			}
			if(Context->LogOutput.Len() > PrevLogOutputLength)
			{
				SendMessage(hWndLogOutput, EM_SETSEL, PrevLogOutputLength, PrevLogOutputLength);
				SendMessage(hWndLogOutput, EM_REPLACESEL, FALSE, (LPARAM)(*Context->LogOutput + PrevLogOutputLength));
				SendMessage(hWndLogOutput, EM_SCROLLCARET, 0, 0);
				PrevLogOutputLength = Context->LogOutput.Len();
			}
		}

		MSG Msg;
		while(PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&Msg);
			DispatchMessage(&Msg);
		}
	}

	DestroyWindow(hWnd);
	DeleteObject(hLogFont);
	DeleteObject(hFont);
	UnregisterClass(WindowClassName, HInstance);

	return 0;
}
コード例 #22
0
ファイル: main.c プロジェクト: MortenRoenne/wine
/*********************************************************************
 * ff_dlgproc [internal]
 *
 */
static INT_PTR CALLBACK ff_dlgproc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
    static HANDLE thread;
    static struct JoystickData *data;
    TRACE("(%p, 0x%08x/%d, 0x%lx)\n", hwnd, msg, msg, lparam);

    switch (msg)
    {
        case WM_INITDIALOG:
        {
            int i, cur = 0;

            data = (struct JoystickData*) ((PROPSHEETPAGEW*)lparam)->lParam;

            /* Add joysticks with FF support to the combobox and get the effects */
            for (i = 0; i < data->num_joysticks; i++)
            {
                struct Joystick *joy = &data->joysticks[i];

                if (joy->forcefeedback)
                {
                    SendDlgItemMessageW(hwnd, IDC_FFSELECTCOMBO, CB_ADDSTRING, 0, (LPARAM) joy->instance.tszInstanceName);
                    SendDlgItemMessageW(hwnd, IDC_FFSELECTCOMBO, CB_SETITEMDATA, cur, i);

                    cur++;

                    /* Count device effects and then store them */
                    joy->num_effects = 0;
                    joy->effects = NULL;
                    IDirectInputDevice8_EnumEffects(joy->device, ff_effects_callback, (void *) joy, 0);
                    joy->effects = HeapAlloc(GetProcessHeap(), 0, sizeof(struct Effect) * joy->num_effects);

                    joy->cur_effect = 0;
                    IDirectInputDevice8_EnumEffects(joy->device, ff_effects_callback, (void*) joy, 0);
                    FIXME("%d --- %d\n", joy->num_effects, joy->cur_effect);
                    joy->num_effects = joy->cur_effect;

                }
            }

            draw_ff_axis(hwnd, data);

            return TRUE;
        }

        case WM_COMMAND:
            switch(wparam)
            {
                case MAKEWPARAM(IDC_FFSELECTCOMBO, CBN_SELCHANGE):
                    ff_handle_joychange(hwnd, data);

                    SendDlgItemMessageW(hwnd, IDC_FFEFFECTLIST, LB_SETCURSEL, 0, 0);
                    ff_handle_effectchange(hwnd, &data->joysticks[data->chosen_joystick]);
                break;

                case MAKEWPARAM(IDC_FFEFFECTLIST, LBN_SELCHANGE):
                    ff_handle_effectchange(hwnd, &data->joysticks[data->chosen_joystick]);
                break;
            }
            return TRUE;

        case WM_NOTIFY:
            switch(((LPNMHDR)lparam)->code)
            {
                case PSN_SETACTIVE:
                    if (data->num_ff > 0)
                    {
                        DWORD tid;

                        data->stop = FALSE;
                        /* Set the first joystick as default */
                        SendDlgItemMessageW(hwnd, IDC_FFSELECTCOMBO, CB_SETCURSEL, 0, 0);
                        ff_handle_joychange(hwnd, data);

                        SendDlgItemMessageW(hwnd, IDC_FFEFFECTLIST, LB_SETCURSEL, 0, 0);
                        ff_handle_effectchange(hwnd, &data->joysticks[data->chosen_joystick]);

                        thread = CreateThread(NULL, 0, ff_input_thread, (void*) data, 0, &tid);
                    }
                break;

                case PSN_RESET: /* intentional fall-through */
                case PSN_KILLACTIVE:
                    /* Stop ff thread */
                    data->stop = TRUE;
                    MsgWaitForMultipleObjects(1, &thread, FALSE, INFINITE, 0);
                    CloseHandle(thread);
                break;
            }
            return TRUE;
    }
    return FALSE;
}
コード例 #23
0
ファイル: poll.c プロジェクト: AtomicKity/guile
int
poll (struct pollfd *pfd, nfds_t nfd, int timeout)
{
#ifndef WINDOWS_NATIVE
  fd_set rfds, wfds, efds;
  struct timeval tv;
  struct timeval *ptv;
  int maxfd, rc;
  nfds_t i;

# ifdef _SC_OPEN_MAX
  static int sc_open_max = -1;

  if (nfd < 0
      || (nfd > sc_open_max
          && (sc_open_max != -1
              || nfd > (sc_open_max = sysconf (_SC_OPEN_MAX)))))
    {
      errno = EINVAL;
      return -1;
    }
# else /* !_SC_OPEN_MAX */
#  ifdef OPEN_MAX
  if (nfd < 0 || nfd > OPEN_MAX)
    {
      errno = EINVAL;
      return -1;
    }
#  endif /* OPEN_MAX -- else, no check is needed */
# endif /* !_SC_OPEN_MAX */

  /* EFAULT is not necessary to implement, but let's do it in the
     simplest case. */
  if (!pfd && nfd)
    {
      errno = EFAULT;
      return -1;
    }

  /* convert timeout number into a timeval structure */
  if (timeout == 0)
    {
      ptv = &tv;
      ptv->tv_sec = 0;
      ptv->tv_usec = 0;
    }
  else if (timeout > 0)
    {
      ptv = &tv;
      ptv->tv_sec = timeout / 1000;
      ptv->tv_usec = (timeout % 1000) * 1000;
    }
  else if (timeout == INFTIM)
    /* wait forever */
    ptv = NULL;
  else
    {
      errno = EINVAL;
      return -1;
    }

  /* create fd sets and determine max fd */
  maxfd = -1;
  FD_ZERO (&rfds);
  FD_ZERO (&wfds);
  FD_ZERO (&efds);
  for (i = 0; i < nfd; i++)
    {
      if (pfd[i].fd < 0)
        continue;

      if (pfd[i].events & (POLLIN | POLLRDNORM))
        FD_SET (pfd[i].fd, &rfds);

      /* see select(2): "the only exceptional condition detectable
         is out-of-band data received on a socket", hence we push
         POLLWRBAND events onto wfds instead of efds. */
      if (pfd[i].events & (POLLOUT | POLLWRNORM | POLLWRBAND))
        FD_SET (pfd[i].fd, &wfds);
      if (pfd[i].events & (POLLPRI | POLLRDBAND))
        FD_SET (pfd[i].fd, &efds);
      if (pfd[i].fd >= maxfd
          && (pfd[i].events & (POLLIN | POLLOUT | POLLPRI
                               | POLLRDNORM | POLLRDBAND
                               | POLLWRNORM | POLLWRBAND)))
        {
          maxfd = pfd[i].fd;
          if (maxfd > FD_SETSIZE)
            {
              errno = EOVERFLOW;
              return -1;
            }
        }
    }

  /* examine fd sets */
  rc = select (maxfd + 1, &rfds, &wfds, &efds, ptv);
  if (rc < 0)
    return rc;

  /* establish results */
  rc = 0;
  for (i = 0; i < nfd; i++)
    if (pfd[i].fd < 0)
      pfd[i].revents = 0;
    else
      {
        int happened = compute_revents (pfd[i].fd, pfd[i].events,
                                        &rfds, &wfds, &efds);
        if (happened)
          {
            pfd[i].revents = happened;
            rc++;
          }
      }

  return rc;
#else
  static struct timeval tv0;
  static HANDLE hEvent;
  WSANETWORKEVENTS ev;
  HANDLE h, handle_array[FD_SETSIZE + 2];
  DWORD ret, wait_timeout, nhandles;
  fd_set rfds, wfds, xfds;
  BOOL poll_again;
  MSG msg;
  int rc = 0;
  nfds_t i;

  if (nfd < 0 || timeout < -1)
    {
      errno = EINVAL;
      return -1;
    }

  if (!hEvent)
    hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);

restart:
  handle_array[0] = hEvent;
  nhandles = 1;
  FD_ZERO (&rfds);
  FD_ZERO (&wfds);
  FD_ZERO (&xfds);

  /* Classify socket handles and create fd sets. */
  for (i = 0; i < nfd; i++)
    {
      int sought = pfd[i].events;
      pfd[i].revents = 0;
      if (pfd[i].fd < 0)
        continue;
      if (!(sought & (POLLIN | POLLRDNORM | POLLOUT | POLLWRNORM | POLLWRBAND
                      | POLLPRI | POLLRDBAND)))
        continue;

      h = (HANDLE) _get_osfhandle (pfd[i].fd);
      assert (h != NULL);
      if (IsSocketHandle (h))
        {
          int requested = FD_CLOSE;

          /* see above; socket handles are mapped onto select.  */
          if (sought & (POLLIN | POLLRDNORM))
            {
              requested |= FD_READ | FD_ACCEPT;
              FD_SET ((SOCKET) h, &rfds);
            }
          if (sought & (POLLOUT | POLLWRNORM | POLLWRBAND))
            {
              requested |= FD_WRITE | FD_CONNECT;
              FD_SET ((SOCKET) h, &wfds);
            }
          if (sought & (POLLPRI | POLLRDBAND))
            {
              requested |= FD_OOB;
              FD_SET ((SOCKET) h, &xfds);
            }

          if (requested)
            WSAEventSelect ((SOCKET) h, hEvent, requested);
        }
      else
        {
          /* Poll now.  If we get an event, do not poll again.  Also,
             screen buffer handles are waitable, and they'll block until
             a character is available.  windows_compute_revents eliminates
             bits for the "wrong" direction. */
          pfd[i].revents = windows_compute_revents (h, &sought);
          if (sought)
            handle_array[nhandles++] = h;
          if (pfd[i].revents)
            timeout = 0;
        }
    }

  if (select (0, &rfds, &wfds, &xfds, &tv0) > 0)
    {
      /* Do MsgWaitForMultipleObjects anyway to dispatch messages, but
         no need to call select again.  */
      poll_again = FALSE;
      wait_timeout = 0;
    }
  else
    {
      poll_again = TRUE;
      if (timeout == INFTIM)
        wait_timeout = INFINITE;
      else
        wait_timeout = timeout;
    }

  for (;;)
    {
      ret = MsgWaitForMultipleObjects (nhandles, handle_array, FALSE,
                                       wait_timeout, QS_ALLINPUT);

      if (ret == WAIT_OBJECT_0 + nhandles)
        {
          /* new input of some other kind */
          BOOL bRet;
          while ((bRet = PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) != 0)
            {
              TranslateMessage (&msg);
              DispatchMessage (&msg);
            }
        }
      else
        break;
    }

  if (poll_again)
    select (0, &rfds, &wfds, &xfds, &tv0);

  /* Place a sentinel at the end of the array.  */
  handle_array[nhandles] = NULL;
  nhandles = 1;
  for (i = 0; i < nfd; i++)
    {
      int happened;

      if (pfd[i].fd < 0)
        continue;
      if (!(pfd[i].events & (POLLIN | POLLRDNORM |
                             POLLOUT | POLLWRNORM | POLLWRBAND)))
        continue;

      h = (HANDLE) _get_osfhandle (pfd[i].fd);
      if (h != handle_array[nhandles])
        {
          /* It's a socket.  */
          WSAEnumNetworkEvents ((SOCKET) h, NULL, &ev);
          WSAEventSelect ((SOCKET) h, 0, 0);

          /* If we're lucky, WSAEnumNetworkEvents already provided a way
             to distinguish FD_READ and FD_ACCEPT; this saves a recv later.  */
          if (FD_ISSET ((SOCKET) h, &rfds)
              && !(ev.lNetworkEvents & (FD_READ | FD_ACCEPT)))
            ev.lNetworkEvents |= FD_READ | FD_ACCEPT;
          if (FD_ISSET ((SOCKET) h, &wfds))
            ev.lNetworkEvents |= FD_WRITE | FD_CONNECT;
          if (FD_ISSET ((SOCKET) h, &xfds))
            ev.lNetworkEvents |= FD_OOB;

          happened = windows_compute_revents_socket ((SOCKET) h, pfd[i].events,
                                                     ev.lNetworkEvents);
        }
      else
        {
          /* Not a socket.  */
          int sought = pfd[i].events;
          happened = windows_compute_revents (h, &sought);
          nhandles++;
        }

       if ((pfd[i].revents |= happened) != 0)
        rc++;
    }

  if (!rc && timeout == INFTIM)
    {
      SleepEx (1, TRUE);
      goto restart;
    }

  return rc;
#endif
}
コード例 #24
0
ファイル: DownloadMgr.cpp プロジェクト: VelocityRa/citizenMP
bool DownloadManager::Process()
{
    switch (m_downloadState)
    {
    case DS_IDLE:
    {
        m_downloadState = DS_FETCHING_CONFIG;

        m_httpClient = new HttpClient();

        std::wstring hostname = m_gameServer.GetWAddress();

        std::map<std::string, std::string> postMap;
        postMap["method"] = "getConfiguration";

        bool isUpdate = false;

        if (!m_updateQueue.empty())
        {
            std::string resourceString;

            while (!m_updateQueue.empty())
            {
                resourceString += m_updateQueue.front();

                m_updateQueue.pop();

                if (!m_updateQueue.empty())
                {
                    resourceString += ";";
                }
            }

            postMap["resources"] = resourceString;

            isUpdate = true;
        }

        m_httpClient->DoPostRequest(hostname, m_gameServer.GetPort(), L"/client", postMap, [=] (bool result, std::string connData)
        {
            if (!result)
            {
                // TODO: make this a non-fatal error leading back to UI
                GlobalError("Obtaining configuration from server failed.");

                return;
            }

            if (!isUpdate)
            {
                m_requiredResources.clear();
            }

            std::string serverHost = m_gameServer.GetAddress();
            serverHost += va(":%d", m_gameServer.GetPort());

            // parse the received YAML file
            //try
            //{
            //auto node = YAML::Load(connData);
            rapidjson::Document node;
            node.Parse(connData.c_str());

            if (node.HasParseError())
            {
                auto err = node.GetParseError();

                GlobalError("parse error %d", err);
            }

            if (node.HasMember("loadScreen"))
            {
                m_serverLoadScreen = node["loadScreen"].GetString();
            }

            auto& resources = node["resources"];

            std::string origBaseUrl = node["fileServer"].GetString();

            for (auto it = resources.Begin(); it != resources.End(); it++)
            {
                auto& resource = *it;

                std::string baseUrl = origBaseUrl;

                if (it->HasMember("fileServer"))
                {
                    baseUrl = (*it)["fileServer"].GetString();
                }

                ResourceData resData(resource["name"].GetString(), va(baseUrl.c_str(), serverHost.c_str()));

                //for (auto& file : resource["files"])
                auto& files = resource["files"];
                for (auto i = files.MemberBegin(); i != files.MemberEnd(); i++)
                {
                    std::string filename = i->name.GetString();
                    std::string hash = i->value.GetString();

                    resData.AddFile(filename, hash);
                }

                if (resource.HasMember("streamFiles"))
                {
                    auto& streamFiles = resource["streamFiles"];

                    //for (auto& file : resource["streamFiles"])
                    for (auto i = streamFiles.MemberBegin(); i != streamFiles.MemberEnd(); i++)
                    {
                        std::string filename = i->name.GetString();
                        std::string hash = i->value["hash"].GetString();
                        uint32_t rscFlags = i->value["rscFlags"].GetUint();
                        uint32_t rscVersion = i->value["rscVersion"].GetUint();
                        uint32_t size = i->value["size"].GetUint();

                        AddStreamingFile(resData, filename, hash, rscFlags, rscVersion, size);
                    }
                }

                if (isUpdate)
                {
                    for (auto ite = m_requiredResources.begin(); ite != m_requiredResources.end(); ite++)
                    {
                        if (ite->GetName() == resData.GetName())
                        {
                            m_requiredResources.erase(ite);
                            break;
                        }
                    }
                }

                trace("%s\n", resData.GetName().c_str());

                m_isUpdate = isUpdate;

                m_requiredResources.push_back(resData);
            }
            /*}
            catch (std::exception& e)
            {
            	GlobalError("YAML parsing error in server configuration (%s)", e.msg);

            	return;
            }*/

            if (isUpdate)
            {
                assert(m_isUpdate);
            }

            m_downloadState = DS_CONFIG_FETCHED;
        });

        break;
    }

    case DS_CONFIG_FETCHED:
    {
        // check cache existence (TODO: and integrity?)
        auto resourceCache = TheResources.GetCache();

        auto downloadList = resourceCache->GetDownloadsFromList(m_requiredResources);

        resourceCache->ClearMark();
        resourceCache->MarkList(m_requiredResources);
        resourceCache->MarkStreamingList(m_streamingFiles);

        m_downloadList = std::queue<ResourceDownload>();

        for (auto& download : downloadList)
        {
            m_downloadList.push(download);
        }

        if (m_downloadList.empty())
        {
            m_downloadState = DS_DOWNLOADED_SINGLE;
        }
        else
        {
            m_downloadState = DS_DOWNLOADING;
        }

        break;
    }

    case DS_DOWNLOADING:
    {
        if (!m_currentDownload.get())
        {
            m_currentDownload = std::make_shared<ResourceDownload>(m_downloadList.front());
            m_downloadList.pop();

            std::wstring hostname, path;
            uint16_t port;

            m_httpClient->CrackUrl(m_currentDownload->sourceUrl, hostname, path, port);

            m_httpClient->DoFileGetRequest(hostname, port, path, TheResources.GetCache()->GetCacheDevice(), m_currentDownload->targetFilename, [=] (bool result, std::string connData)
            {
                m_downloadState = DS_DOWNLOADED_SINGLE;
            });
        }

        break;
    }

    case DS_DOWNLOADED_SINGLE:
    {
        if (m_currentDownload.get())
        {
            TheResources.GetCache()->AddFile(m_currentDownload->targetFilename, m_currentDownload->filename, m_currentDownload->resname);

            m_currentDownload = nullptr;
        }

        if (!m_downloadList.empty())
        {
            m_downloadState = DS_DOWNLOADING;
        }
        else
        {
            if (!m_isUpdate)
            {
                TheResources.Reset();
            }
            else
            {
                // unload any resources we already know that are currently unprocessed
                for (auto& resource : m_requiredResources)
                {
                    // this is one we just got from the configuration redownload
                    if (!resource.IsProcessed())
                    {
                        auto resourceData = TheResources.GetResource(resource.GetName());

                        if (!resourceData.get())
                        {
                            continue;
                        }

                        // sanity check: is the resource not running?
                        if (resourceData->GetState() == ResourceStateRunning)
                        {
                            FatalError("Tried to unload a running resource in DownloadMgr. (%s)", resource.GetName().c_str());
                        }

                        // remove all packfiles related to this old resource
                        auto packfiles = resourceData->GetPackFiles();

                        for (auto& packfile : packfiles)
                        {
                            // FIXME: implementation detail from same class
                            fiDevice::Unmount(va("resources:/%s/", resourceData->GetName().c_str()));

                            packfile->closeArchive();

                            // remove from the to-close list (!)
                            for (auto it = m_packFiles.begin(); it != m_packFiles.end(); it++)
                            {
                                if (it->second == packfile)
                                {
                                    m_packFiles.erase(it);
                                    break;
                                }
                            }
                        }

                        // and delete the resource (hope nobody kept a reference to that sucker, ha!)
                        TheResources.DeleteResource(resourceData);
                    }
                }
            }

            //std::string resourcePath = "citizen:/resources/";
            //TheResources.ScanResources(fiDevice::GetDevice("citizen:/setup2.xml", true), resourcePath);

            std::list<std::shared_ptr<Resource>> loadedResources;

            // mount any RPF files that we include
            for (auto& resource : m_requiredResources)
            {
                if (m_isUpdate && resource.IsProcessed())
                {
                    continue;
                }

                std::vector<rage::fiPackfile*> packFiles;

                for (auto& file : resource.GetFiles())
                {
                    if (file.filename.find(".rpf") != std::string::npos)
                    {
                        // get the path of the RPF
                        std::string markedFile = TheResources.GetCache()->GetMarkedFilenameFor(resource.GetName(), file.filename);

                        rage::fiPackfile* packFile = new rage::fiPackfile();
                        packFile->openArchive(markedFile.c_str(), true, false, 0);
                        packFile->mount(va("resources:/%s/", resource.GetName().c_str()));

                        packFiles.push_back(packFile);
                        m_packFiles.push_back(std::make_pair(va("resources:/%s/", resource.GetName().c_str()), packFile));
                    }
                }

                // load the resource
                auto resourceLoad = TheResources.AddResource(resource.GetName(), va("resources:/%s/", resource.GetName().c_str()));

                if (resourceLoad.get())
                {
                    resourceLoad->AddPackFiles(packFiles);

                    loadedResources.push_back(resourceLoad);
                }

                resource.SetProcessed();
            }

            if (m_isUpdate)
            {
                for (auto& resource : loadedResources)
                {
                    resource->Start();
                }
            }

            m_loadedResources = loadedResources;

            m_downloadState = DS_DONE;
        }

        break;
    }

    case DS_DONE:
        m_downloadState = DS_IDLE;

        if (m_isUpdate && !m_updateQueue.empty())
        {
            ProcessQueuedUpdates();
        }

        if (!m_serverLoadScreen.empty() && !m_isUpdate)
        {
            CustomLoadScreens::PrepareSwitchTo(m_serverLoadScreen);
        }

        m_isUpdate = false;

        g_netLibrary->DownloadsComplete();

        while (!g_netLibrary->ProcessPreGameTick())
        {
            HANDLE hThread = GetCurrentThread();

            MsgWaitForMultipleObjects(1, &hThread, TRUE, 15, 0);
        }

        return true;
    }

    return false;
}
コード例 #25
0
STDMETHODIMP CXMLDOMDocument::load(VARIANT xmlSource, VARIANT_BOOL  *isSuccessful)
{
	ATLTRACE(_T("CXMLDOMDocument::load\n"));

	if (NULL == isSuccessful)
		return E_POINTER;

	*isSuccessful = VARIANT_FALSE;

	if (V_VT(&xmlSource) != VT_BSTR					&&
		V_VT(&xmlSource) != VT_DISPATCH				&&
		V_VT(&xmlSource) != (VT_ARRAY | VT_VARIANT)	&&
		V_VT(&xmlSource) != (VT_ARRAY | VT_UI1)		&&
		V_VT(&xmlSource) != VT_UNKNOWN)
		return E_INVALIDARG;

	// do not start another thread if there is another active
	if (NULL != m_hParseThread) {
		DWORD exitCode = 0;
		BOOL rc = ::GetExitCodeThread(m_hParseThread, &exitCode);
		if (!rc || STILL_ACTIVE == exitCode)
			return S_OK;
		
		::CloseHandle(m_hParseThread);
		m_hParseThread = NULL;
	}

	HRESULT hr = S_OK;
	m_bAbort = false;
	
	m_FileName = _T("");
	m_xml = _T("");
	m_TmpDocument = 0;
	m_bThreadValidate = m_bValidate;
	
	if (V_VT(&xmlSource) == VT_BSTR) {
		m_FileName = V_BSTR(&xmlSource);
		if (0 == m_FileName.length())
			return E_INVALIDARG;

		// see if the file is relative path
		if (!PathIsURL(m_FileName) && PathIsRelative(m_FileName)) {
			// try appending baseurl if exists
			_bstr_t baseURL;
			if (S_OK == GetBaseURL(baseURL)) {
				// change any backslashes to slashes
				LPTSTR loc = _tcschr(m_FileName,_T('\\'));
				while (loc != NULL) {
					*loc = _T('/');
					loc = _tcschr(m_FileName,_T('\\'));
				}
				m_FileName = baseURL + _T("/") + m_FileName;
			}
			else {
				TCHAR szCurDir[MAX_PATH];
				GetCurrentDirectory(MAX_PATH,szCurDir);
				m_FileName=_bstr_t(szCurDir) + _T("\\") + m_FileName;
			}
		}
	}
	else
	if (V_VT(&xmlSource) == VT_UNKNOWN) {
		CComQIPtr<IStream,&IID_IStream> pS(V_UNKNOWN(&xmlSource));
		if (!pS)
			return E_INVALIDARG;

		CComBSTR b;
		hr = b.ReadFromStream(pS);
		if (S_OK != hr)
			return hr;

		m_xml = b;
		if (0 == m_xml.length())
			return E_INVALIDARG;
	}
	else
	if (V_VT(&xmlSource) == VT_DISPATCH) {
		CComQIPtr<IXMLDOMDocument,&IID_IXMLDOMDocument> pDoc(V_DISPATCH(&xmlSource));
		if (!pDoc)
			return E_INVALIDARG;
		
		BSTR b = NULL;
		hr = pDoc->get_xml(&b);
		if (S_OK != hr)
			return hr;

		m_xml = b;
		::SysFreeString(b);

		if (0 == m_xml.length())
			return E_INVALIDARG;
	}
	else
	if (V_VT(&xmlSource) == (VT_ARRAY | VT_VARIANT)) {
		SAFEARRAY *pArray = reinterpret_cast<SAFEARRAY *> (xmlSource.byref);
		if (NULL == pArray)
			return E_INVALIDARG;

		long lLBoundVar = 0;
		long lUBoundVar = 0;
	
		UINT dims = ::SafeArrayGetDim(pArray);
		if (dims == 0)
			return E_INVALIDARG;
	
		hr = ::SafeArrayGetLBound(pArray, dims, &lLBoundVar);
		if (S_OK != hr)
			return hr;

		hr = ::SafeArrayGetUBound(pArray, dims, &lUBoundVar);
		if (S_OK != hr)
			return hr;

		if (lUBoundVar >= lLBoundVar) {
			VARIANT *pIndex = NULL;
			hr = ::SafeArrayAccessData(pArray, reinterpret_cast<void **> (&pIndex));
			if (S_OK != hr)
				return hr;

			int length = lUBoundVar-lLBoundVar+2;
			BYTE *body = new BYTE[length];
			for (long i = 0; i <= lUBoundVar-lLBoundVar; ++i) {	
				VARIANT var = pIndex[i];
				if (V_VT(&var) != VT_UI1) {
					hr = E_INVALIDARG;
					break;
				}
				body[i] = V_UI1(&var);
			}
			body[length-1] = 0;
					
			::SafeArrayUnaccessData(pArray);
			if (S_OK != hr) {
				delete [] body;
				return hr;
			}
			m_xml = reinterpret_cast<char*> (body);
			delete [] body;
			if (0 == m_xml.length())
				return E_INVALIDARG;
		}
	}	
	else
	if (V_VT(&xmlSource) == (VT_ARRAY | VT_UI1)) {
		SAFEARRAY *pArray = reinterpret_cast<SAFEARRAY *> (xmlSource.byref);
		if (NULL == pArray)
			return E_INVALIDARG;

		long lLBoundVar = 0;
		long lUBoundVar = 0;
	
		UINT dims = ::SafeArrayGetDim(pArray);
		if (dims == 0)
			return E_INVALIDARG;
	
		hr = ::SafeArrayGetLBound(pArray, dims, &lLBoundVar);
		if (S_OK != hr)
			return hr;

		hr = ::SafeArrayGetUBound(pArray, dims, &lUBoundVar);
		if (S_OK != hr)
			return hr;

		if (lUBoundVar >= lLBoundVar) {
			BYTE *pIndex = NULL;
			hr = ::SafeArrayAccessData(pArray, reinterpret_cast<void **> (&pIndex));
			if (S_OK != hr)
				return hr;

			int length = lUBoundVar-lLBoundVar+2;
			BYTE *body = new BYTE[length];
			for (long i = 0; i <= lUBoundVar-lLBoundVar; ++i)	
				body[i] = pIndex[i];
			
			body[length-1] = 0;
			::SafeArrayUnaccessData(pArray);
			m_xml = reinterpret_cast<char*> (body);
			delete [] body;
			if (0 == m_xml.length())
				return E_INVALIDARG;
		}
	}	

	UINT nthreadID = 0;
	m_hParseThread = reinterpret_cast<HANDLE> (_beginthreadex(NULL,
												 0,
											     CXMLDOMDocument::ParseThread,
												 (void *) this,
												 0,
												 &nthreadID));
	if (NULL == m_hParseThread)
		return S_OK;
	
	if (m_bAsync) {
		*isSuccessful = VARIANT_TRUE;
		return S_OK;
	}

	bool bWait = true;
	while (bWait) {
		DWORD dwEvt = MsgWaitForMultipleObjects(1,&m_hParseThread,FALSE,INFINITE,QS_ALLINPUT);
		switch(dwEvt) {
			case WAIT_OBJECT_0:
				bWait = false;
				break;
			case WAIT_OBJECT_0 + 1:
			{
				MSG msg;
				while(::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
					if (WM_CLOSE == msg.message || WM_QUIT == msg.message) {
						 bWait = false;
						 m_bAbort = true;
						 break;
					}
					else {
						PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
						TranslateMessage(&msg);
						DispatchMessage(&msg);
					}
				}
				break;
			}
			default:
				m_bAbort = true;
				bWait = false;
				break;
		}
	}

	if (m_bAbort)
		return S_OK;

	if (m_bParseError)
		return hr;

    if(m_Document)
        delete m_Document;
	m_Document = m_TmpDocument;
	m_TmpDocument = 0;
	
	m_url = m_FileName;
	*isSuccessful = VARIANT_TRUE;
	
	return hr;
}
コード例 #26
0
// Waits for the HANDLE hObject.  While waiting messages sent
// to windows on our thread by SendMessage will be processed.
// Using this function to do waits and mutual exclusion
// avoids some deadlocks in objects with windows.
// Return codes are the same as for WaitForSingleObject
DWORD WINAPI WaitDispatchingMessages(
    HANDLE hObject,
    DWORD dwWait,
    HWND hwnd,
    UINT uMsg,
    HANDLE hEvent)
{
    BOOL bPeeked = FALSE;
    DWORD dwResult;
    DWORD dwStart;
    DWORD dwThreadPriority;

    static UINT uMsgId = 0;

    HANDLE hObjects[2] = { hObject, hEvent };
    if (dwWait != INFINITE && dwWait != 0) {
        dwStart = GetTickCount();
    }
    for (; ; ) {
        DWORD nCount = NULL != hEvent ? 2 : 1;

        //  Minimize the chance of actually dispatching any messages
        //  by seeing if we can lock immediately.
        dwResult = WaitForMultipleObjects(nCount, hObjects, FALSE, 0);
        if (dwResult < WAIT_OBJECT_0 + nCount) {
            break;
        }

        DWORD dwTimeOut = dwWait;
        if (dwTimeOut > 10) {
            dwTimeOut = 10;
        }
        dwResult = MsgWaitForMultipleObjects(
                             nCount,
                             hObjects,
                             FALSE,
                             dwTimeOut,
                             hwnd == NULL ? QS_SENDMESSAGE :
                                            QS_SENDMESSAGE + QS_POSTMESSAGE);
        if (dwResult == WAIT_OBJECT_0 + nCount ||
            dwResult == WAIT_TIMEOUT && dwTimeOut != dwWait) {
            MSG msg;
            if (hwnd != NULL) {
                while (PeekMessage(&msg, hwnd, uMsg, uMsg, PM_REMOVE)) {
                    DispatchMessage(&msg);
                }
            }
            // Do this anyway - the previous peek doesn't flush out the
            // messages
            PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);

            if (dwWait != INFINITE && dwWait != 0) {
                DWORD dwNow = GetTickCount();

                // Working with differences handles wrap-around
                DWORD dwDiff = dwNow - dwStart;
                if (dwDiff > dwWait) {
                    dwWait = 0;
                } else {
                    dwWait -= dwDiff;
                }
                dwStart = dwNow;
            }
            if (!bPeeked) {
                //  Raise our priority to prevent our message queue
                //  building up
                dwThreadPriority = GetThreadPriority(GetCurrentThread());
                if (dwThreadPriority < THREAD_PRIORITY_HIGHEST) {
                    SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
                }
                bPeeked = TRUE;
            }
        } else {
            break;
        }
    }
    if (bPeeked) {
        SetThreadPriority(GetCurrentThread(), dwThreadPriority);
        if (HIWORD(GetQueueStatus(QS_POSTMESSAGE)) & QS_POSTMESSAGE) {
            if (uMsgId == 0) {
                uMsgId = RegisterWindowMessage(TEXT("AMUnblock"));
            }
            if (uMsgId != 0) {
                MSG msg;
                //  Remove old ones
                while (PeekMessage(&msg, (HWND)-1, uMsgId, uMsgId, PM_REMOVE)) {
                }
            }
            PostThreadMessage(GetCurrentThreadId(), uMsgId, 0, 0);
        }
    }
    return dwResult;
}
コード例 #27
0
ファイル: XMLHTTPRequest.cpp プロジェクト: gitrider/wxsj2
STDMETHODIMP CXMLHttpRequest::send(VARIANT varBody)
{
	ATLTRACE(_T("CXMLHttpRequest::send\n"));

	if (V_VT(&varBody) != VT_BSTR					&& 
		V_VT(&varBody) != VT_DISPATCH				&&
		V_VT(&varBody) != (VT_ARRAY | VT_VARIANT)	&&
		V_VT(&varBody) != (VT_ARRAY | VT_UI1)		&&
		V_VT(&varBody) != VT_UNKNOWN)
		return E_INVALIDARG;

	// do not start another thread if there is another active  
	if (NULL != m_hThread) {
		DWORD exitCode = 0;
		BOOL rc = ::GetExitCodeThread(m_hThread, &exitCode);
		if (!rc || STILL_ACTIVE == exitCode) 
			return E_PENDING;
		
		::CloseHandle(m_hThread);
		m_hThread = NULL;
	}

	HRESULT hr = S_OK;
	m_bSuccess = true;
	m_bAbort = false;
	delete [] m_pBody;
	m_pBody = NULL;
	m_lBodyLength = 0;
	delete [] m_pResponseBody;
	m_pResponseBody = NULL;
	m_lResponseBodyLength = 0;
	m_dwStatus	 = 0;
	m_StatusText = _T("");
	m_ResponseHeaders = _T("");

	if (V_VT(&varBody) == VT_BSTR) {
		_bstr_t body = V_BSTR(&varBody);
		m_lBodyLength = body.length() + 1;
		m_pBody = new BYTE[m_lBodyLength];
		memset(m_pBody,0,m_lBodyLength);
		memcpy(m_pBody,static_cast<char*> (body),body.length());
	}
	else
	if (V_VT(&varBody) == VT_UNKNOWN) {
		CComQIPtr<IStream,&IID_IStream> pS(V_UNKNOWN(&varBody));
		if (!pS)
			return E_INVALIDARG;

		CComBSTR b;
		hr = b.ReadFromStream(pS);
		if (S_OK != hr)
			return hr;

		_bstr_t body = b;
		m_lBodyLength = body.length() + 1;
		m_pBody = new BYTE[m_lBodyLength];
		memset(m_pBody,0,m_lBodyLength);
		memcpy(m_pBody,static_cast<char*> (body),body.length());
	}
	else
	if (V_VT(&varBody) == VT_DISPATCH) {
		CComQIPtr<IXMLDOMDocument,&IID_IXMLDOMDocument> pDoc(V_DISPATCH(&varBody));
		if (!pDoc)
			return E_INVALIDARG;
		
		BSTR b = NULL;
		hr = pDoc->get_xml(&b);
		if (S_OK != hr)
			return hr;

		_bstr_t body = b;
		::SysFreeString(b);

		m_lBodyLength = body.length() + 1;
		m_pBody = new BYTE[m_lBodyLength];
		memset(m_pBody,0,m_lBodyLength);
		memcpy(m_pBody,static_cast<char*> (body),body.length());
	}
	else
	if (V_VT(&varBody) == (VT_ARRAY | VT_VARIANT)) {
		SAFEARRAY *pArray = reinterpret_cast<SAFEARRAY *> (varBody.byref);
		if (NULL == pArray)
			return E_INVALIDARG;

		long lLBoundVar = 0;
		long lUBoundVar = 0;
	
		UINT dims = ::SafeArrayGetDim(pArray);
		if (dims == 0)
			return E_INVALIDARG;
	
		hr = ::SafeArrayGetLBound(pArray, dims, &lLBoundVar);
		if (S_OK != hr)
			return hr;

		hr = ::SafeArrayGetUBound(pArray, dims, &lUBoundVar);
		if (S_OK != hr)
			return hr;

		if (lUBoundVar >= lLBoundVar) {
			VARIANT *pIndex = NULL; 
			hr = ::SafeArrayAccessData(pArray, reinterpret_cast<void **> (&pIndex));
			if (S_OK != hr)
				return hr;

			m_lBodyLength = lUBoundVar-lLBoundVar+1;
			m_pBody = new BYTE[m_lBodyLength];
			for (long i = 0; i <= lUBoundVar-lLBoundVar; ++i) {	
				VARIANT var = pIndex[i];
				if (V_VT(&var) != VT_UI1) {
					hr = E_INVALIDARG;
					break;
				}
				m_pBody[i] = V_UI1(&var); 
			}
					
			::SafeArrayUnaccessData(pArray);
			if (S_OK != hr) {
				delete [] m_pBody;
				m_pBody = NULL;
				m_lBodyLength = 0;
				return hr;
			}
		}
	}	
	else
	if (V_VT(&varBody) == (VT_ARRAY | VT_UI1)) {
		SAFEARRAY *pArray = reinterpret_cast<SAFEARRAY *> (varBody.byref);
		if (NULL == pArray)
			return E_INVALIDARG;

		long lLBoundVar = 0;
		long lUBoundVar = 0;
	
		UINT dims = ::SafeArrayGetDim(pArray);
		if (dims == 0)
			return E_INVALIDARG;
	
		hr = ::SafeArrayGetLBound(pArray, dims, &lLBoundVar);
		if (S_OK != hr)
			return hr;

		hr = ::SafeArrayGetUBound(pArray, dims, &lUBoundVar);
		if (S_OK != hr)
			return hr;

		if (lUBoundVar >= lLBoundVar) {
			BYTE *pIndex = NULL; 
			hr = ::SafeArrayAccessData(pArray, reinterpret_cast<void **> (&pIndex));
			if (S_OK != hr)
				return hr;

			m_lBodyLength = lUBoundVar-lLBoundVar+1;
			m_pBody = new BYTE[m_lBodyLength];
			for (long i = 0; i <= lUBoundVar-lLBoundVar; ++i)	
				m_pBody[i] = pIndex[i]; 
								
			::SafeArrayUnaccessData(pArray);
		}
	}	

	m_HwndParent = GetParentWindow();

	UINT nthreadID = 0;
	m_hThread = reinterpret_cast<HANDLE> (_beginthreadex(NULL,
												 0,
											     CXMLHttpRequest::SendThread,
												 (void *) this, 
												 0,
												 &nthreadID));
	if (NULL == m_hThread) 
		return E_FAIL;
	
	if (m_bAsync) 
		return S_OK;
	
	bool bWait = true;
	while (bWait) {
		DWORD dwEvt = MsgWaitForMultipleObjects(1,&m_hThread,FALSE,INFINITE,QS_ALLINPUT);
		switch(dwEvt) {
			case WAIT_OBJECT_0:
				bWait = false;
				break;
			case WAIT_OBJECT_0 + 1:
			{
				MSG msg;
				while(::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { 
					if (WM_CLOSE == msg.message || WM_QUIT == msg.message) {
						 bWait = false;
						 m_bAbort = true;
						 break;
					}
					else {
						PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
						TranslateMessage(&msg);  
						DispatchMessage(&msg);
					}
				}
				break;
			}
			default:
				m_bAbort = true;
				bWait = false;
				break;
		}
	}

	return S_OK;
}
コード例 #28
0
/// <summary>
/// Creates the main window and begins processing
/// </summary>
/// <param name="hInstance">handle to the application instance</param>
/// <param name="nCmdShow">whether to display minimized, maximized, or normally</param>
int KinectEasyGrabber::Run(HINSTANCE hInstance, int nCmdShow)
{
    MSG       msg = {0};
    WNDCLASS  wc;

    // Dialog custom window class
    ZeroMemory(&wc, sizeof(wc));
    wc.style         = CS_HREDRAW | CS_VREDRAW;
    wc.cbWndExtra    = DLGWINDOWEXTRA;
    wc.hInstance     = hInstance;
    wc.hCursor       = LoadCursorW(NULL, IDC_ARROW);
    wc.hIcon         = LoadIconW(hInstance, MAKEINTRESOURCE(IDI_APP));
    wc.lpfnWndProc   = DefDlgProcW;
    wc.lpszClassName = L"KinectEasyGrabberAppDlgWndClass";

    if (!RegisterClassW(&wc))
    {
        return 0;
    }

    // Create main application window
    HWND hWndApp = CreateDialogParamW(
        hInstance,
        MAKEINTRESOURCE(IDD_APP),
        NULL,
        (DLGPROC)KinectEasyGrabber::MessageRouter, 
        reinterpret_cast<LPARAM>(this));

    // Show window
    ShowWindow(hWndApp, nCmdShow);

    const int eventCount = 2;
    HANDLE hEvents[eventCount];

    LoadResourceImage(L"Background", L"Image", m_colorWidth*m_colorHeight*cBytesPerPixel, m_backgroundRGBX);

    // Main message loop
    while (WM_QUIT != msg.message)
    {
        hEvents[0] = m_hNextDepthFrameEvent;
        hEvents[1] = m_hNextColorFrameEvent;

        // Check to see if we have either a message (by passing in QS_ALLINPUT)
        // Or a Kinect event (hEvents)
        // Update() will check for Kinect events individually, in case more than one are signalled
        DWORD dwEvent = MsgWaitForMultipleObjects(eventCount, hEvents, FALSE, INFINITE, QS_ALLINPUT);

        // Check if this is an event we're waiting on and not a timeout or message
        if (WAIT_OBJECT_0 == dwEvent || WAIT_OBJECT_0 + 1 == dwEvent)
        {
            //Update();
			//Record();
			RecordArray();
        }

        if (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE))
        {
            // If a dialog message will be taken care of by the dialog proc
            if ((hWndApp != NULL) && IsDialogMessageW(hWndApp, &msg))
            {
                continue;
            }

            TranslateMessage(&msg);
            DispatchMessageW(&msg);
        }
    }

    return static_cast<int>(msg.wParam);
}
コード例 #29
0
ファイル: wfreerdp.c プロジェクト: johnsonyes/FreeRDP
int wfreerdp_run(freerdp* instance)
{
	MSG msg;
	int index;
	int rcount;
	int wcount;
	BOOL msg_ret;
	int quit_msg;
	void* rfds[32];
	void* wfds[32];
	int fds_count;
	HANDLE fds[64];
	rdpChannels* channels;

	memset(rfds, 0, sizeof(rfds));
	memset(wfds, 0, sizeof(wfds));

	if (freerdp_connect(instance) != true)
		return 0;

	channels = instance->context->channels;

	while (1)
	{
		rcount = 0;
		wcount = 0;

		if (freerdp_get_fds(instance, rfds, &rcount, wfds, &wcount) != true)
		{
			printf("Failed to get FreeRDP file descriptor\n");
			break;
		}
		if (wf_get_fds(instance, rfds, &rcount, wfds, &wcount) != true)
		{
			printf("Failed to get wfreerdp file descriptor\n");
			break;
		}
		if (freerdp_channels_get_fds(channels, instance, rfds, &rcount, wfds, &wcount) != true)
		{
			printf("Failed to get channel manager file descriptor\n");
			break;
		}

		fds_count = 0;
		/* setup read fds */
		for (index = 0; index < rcount; index++)
		{
			fds[fds_count++] = rfds[index];
		}
		/* setup write fds */
		for (index = 0; index < wcount; index++)
		{
			fds[fds_count++] = wfds[index];
		}
		/* exit if nothing to do */
		if (fds_count == 0)
		{
			printf("wfreerdp_run: fds_count is zero\n");
			break;
		}

		/* do the wait */
		if (MsgWaitForMultipleObjects(fds_count, fds, FALSE, 1, QS_ALLINPUT) == WAIT_FAILED)
		{
			printf("wfreerdp_run: WaitForMultipleObjects failed: 0x%04X\n", GetLastError());
			break;
		}

		if (freerdp_check_fds(instance) != true)
		{
			printf("Failed to check FreeRDP file descriptor\n");
			break;
		}
		if (wf_check_fds(instance) != true)
		{
			printf("Failed to check wfreerdp file descriptor\n");
			break;
		}
		if (freerdp_channels_check_fds(channels, instance) != true)
		{
			printf("Failed to check channel manager file descriptor\n");
			break;
		}
		wf_process_channel_event(channels, instance);

		quit_msg = FALSE;
		while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
		{
			msg_ret = GetMessage(&msg, NULL, 0, 0);

			if (msg_ret == 0 || msg_ret == -1)
			{
				quit_msg = TRUE;
				break;
			}

			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}

		if (quit_msg)
			break;
	}

	/* cleanup */
	freerdp_channels_free(channels);
	freerdp_free(instance);
	
	return 0;
}
コード例 #30
0
ファイル: system.win32.c プロジェクト: STLVNUB/blitzmax
void bbSystemWait(){
	MsgWaitForMultipleObjects( 0,0,0,INFINITE,QS_ALLINPUT );	//QS_ALLEVENTS );
	bbSystemPoll();
}