Exemple #1
0
Common::Common( int &argc, char **argv )
:	QtSingleApplication( argc, argv )
,	m_noNativeFileDialog( false )
{
	setStyleSheet(
		"QDialogButtonBox { dialogbuttonbox-buttons-have-icons: 0; }\n" );
	QPalette p = palette();
	p.setBrush( QPalette::Link, QBrush( "#509B00" ) );
	p.setBrush( QPalette::LinkVisited, QBrush( "#509B00" ) );
	setPalette( p );

	qRegisterMetaType<QSslCertificate>("QSslCertificate");
	qRegisterMetaType<TokenData>("TokenData");

	QDesktopServices::setUrlHandler( "browse", this, "browse" );
	QDesktopServices::setUrlHandler( "mailto", this, "mailTo" );

#if defined(Q_OS_WIN)
	AllowSetForegroundWindow( ASFW_ANY );
#elif defined(Q_OS_MAC)
	macEvents = 0;
#ifndef QT_MAC_USE_COCOA
	initMacEvents();
#endif
#endif
	m_noNativeFileDialog = arguments().contains( "-noNativeFileDialog" );
}
Exemple #2
0
// http://www.codeproject.com/Tips/76427/How-to-bring-window-to-top-with-SetForegroundWindo
void SetForegroundWindowInternal(HWND hWnd)
{
    SetWindowPos(hWnd,HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
    SetWindowPos(hWnd,HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
    SetWindowPos(hWnd,HWND_NOTOPMOST, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE);
    return;
    //relation time of SetForegroundWindow lock
    DWORD lockTimeOut = 0;
    HWND  hCurrWnd = GetForegroundWindow();
    DWORD dwThisTID = GetCurrentThreadId(),
        dwCurrTID = GetWindowThreadProcessId(hCurrWnd, 0);

    //we need to bypass some limitations from Microsoft :)
    if (dwThisTID != dwCurrTID)
    {
        AttachThreadInput(dwThisTID, dwCurrTID, TRUE);

        SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, &lockTimeOut, 0);
        SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, 0, SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE);

        AllowSetForegroundWindow(ASFW_ANY);
    }

    SetForegroundWindow(hWnd);

    if (dwThisTID != dwCurrTID)
    {
        SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (PVOID)lockTimeOut, SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE);
        AttachThreadInput(dwThisTID, dwCurrTID, FALSE);
    }
}
Exemple #3
0
BOOL SetForegroundWindowInternal(HWND hWnd) {
	BOOL ret = false;
	if (!IsWindow(hWnd)) return ret;

	//relation time of SetForegroundWindow lock
	DWORD lockTimeOut = 0;
	HWND  hCurrWnd = GetForegroundWindow();
	DWORD dwThisTID = GetCurrentThreadId(),
	dwCurrTID = GetWindowThreadProcessId(hCurrWnd, 0);

	//we need to bypass some limitations from Microsoft :)
	if (dwThisTID != dwCurrTID)
	{
		AttachThreadInput(dwThisTID, dwCurrTID, TRUE);

		SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, &lockTimeOut, 0);
		SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, 0, SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE);

		AllowSetForegroundWindow(ASFW_ANY);
	}

	ret = SetForegroundWindow(hWnd);

	if (dwThisTID != dwCurrTID)
	{
		SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (PVOID)lockTimeOut, SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE);
		AttachThreadInput(dwThisTID, dwCurrTID, FALSE);
	}

	return ret;
}
Exemple #4
0
BOOL GuiSetForeground(HWND hWnd)
{
	BOOL lbRc = FALSE;

	if (ghConEmuWndDC)
	{
		CESERVER_REQ *pIn = (CESERVER_REQ*)malloc(sizeof(*pIn)), *pOut;
		if (pIn)
		{
			ExecutePrepareCmd(pIn, CECMD_SETFOREGROUND, sizeof(CESERVER_REQ_HDR)+sizeof(u64)); //-V119

			DWORD nConEmuPID = ASFW_ANY;
			GetWindowThreadProcessId(ghConEmuWndDC, &nConEmuPID);
			AllowSetForegroundWindow(nConEmuPID);

			pIn->qwData[0] = (u64)hWnd;
			HWND hConWnd = GetRealConsoleWindow();
			pOut = ExecuteGuiCmd(hConWnd, pIn, hConWnd);

			if (pOut)
			{
				if (pOut->hdr.cbSize == (sizeof(CESERVER_REQ_HDR)+sizeof(DWORD)))
					lbRc = pOut->dwData[0];
				ExecuteFreeResult(pOut);
			}
			free(pIn);
		}
	}

	return lbRc;
}
Exemple #5
0
void PassFilesToInstance(void)
{
    int argc = __argc;
    char **argv = __argv;
    AllowSetForegroundWindow(ASFW_ANY);
//	argv = CmdLineToC(&argc, GetCommandLineA());
    if (argv)
    {
        if (argc <= 1)
        {
            SendFileName("###TOP###");
        }
        else
        {
            int i;
            for (i=1; i < argc; i++)
            {
                char buf[260], *p = buf;
                strcpy(buf, argv[i]);
                while (isspace(*p)) p++;
                    if (*p != '/' && *p != '-')
                    {
                        abspath(p, NULL);
                        SendFileName(p);
                    }
            }
        }
    }
}
bool CCommonAppUtils::LaunchApplication
    ( const CString& sCommandLine
    , UINT idErrMessageFormat
    , bool bWaitForStartup
    , bool bWaitForExit
    , HANDLE hWaitHandle)
{
    PROCESS_INFORMATION process;

    // make sure we get a writable copy of the command line

    size_t bufferLen = sCommandLine.GetLength()+1;
    std::unique_ptr<TCHAR[]> cleanCommandLine (new TCHAR[bufferLen]);
    memcpy (cleanCommandLine.get(),
            (LPCTSTR)sCommandLine,
            sizeof (TCHAR) * bufferLen);

    if (!CCreateProcessHelper::CreateProcess(NULL, cleanCommandLine.get(), sOrigCWD, &process))
    {
        if(idErrMessageFormat != 0)
        {
            CFormatMessageWrapper errorDetails;
            CString msg;
            msg.Format(idErrMessageFormat, (LPCTSTR)errorDetails);
            CString title;
            title.LoadString(IDS_APPNAME);
            MessageBox(NULL, msg, title, MB_OK | MB_ICONINFORMATION);
        }
        return false;
    }
    AllowSetForegroundWindow(process.dwProcessId);

    if (bWaitForStartup)
        WaitForInputIdle(process.hProcess, 10000);

    if (bWaitForExit)
    {
        DWORD count = 1;
        HANDLE handles[2];
        handles[0] = process.hProcess;
        if (hWaitHandle)
        {
            count = 2;
            handles[1] = hWaitHandle;
        }
        WaitForMultipleObjects(count, handles, FALSE, INFINITE);
        if (hWaitHandle)
            CloseHandle(hWaitHandle);
    }

    CloseHandle(process.hThread);
    CloseHandle(process.hProcess);

    return true;
}
Exemple #7
0
static void MyShellDispatch_AllowSetForegroundWindow(const HWND &hwnd)
{
	DWORD dwProcessId = 0;
	if(GetWindowThreadProcessId(hwnd, &dwProcessId))
	{
		if(dwProcessId != 0)
		{
			AllowSetForegroundWindow(dwProcessId);
		}
	}
}
Exemple #8
0
/* Hack required for Windows.  */
void
gnupg_allow_set_foregound_window (pid_t pid)
{
  if (!pid)
    log_info ("%s called with invalid pid %lu\n",
              "gnupg_allow_set_foregound_window", (unsigned long)pid);
#ifdef HAVE_W32_SYSTEM
  else if (!AllowSetForegroundWindow ((pid_t)pid == (pid_t)(-1)?ASFW_ANY:pid))
    log_info ("AllowSetForegroundWindow(%lu) failed: %s\n",
               (unsigned long)pid, w32_strerror (-1));
#endif
}
Exemple #9
0
void win_system::onCreate()
{
  HINSTANCE hInstance = GetModuleHandle(NULL);
  
  mainWindow = new main_window_com(this);
  mainWindow->init("MAIN", hInstance, NULL);
  mainWindow->create("CrashUtils", 300, 300, 1280, 800);
  mainWindow->SetWindowPos(200, 30, 1280, 800);
  mainWindow->ShowWindow(SW_SHOW/*nCmdShow*/);
  mainWindow->UpdateWindow();
  
  AllowSetForegroundWindow(ASFW_ANY);
}
void CTextService::_StartConfigure()
{
	HANDLE hMutex = OpenMutexW(SYNCHRONIZE, FALSE, cnfmutexname);
	if(hMutex != nullptr)
	{
		CloseHandle(hMutex);
		return;
	}

	AllowSetForegroundWindow(ASFW_ANY);

	_CommandDic(REQ_EXEC_CNF);
}
Exemple #11
0
// Called after plotting is done
void qt_text()
{
    if (qt_optionRaise)
    {
#ifdef _WIN32
        // The qt graph window is in another process and we must explicitly allow it to "raise".
        AllowSetForegroundWindow(qt->pid);
#endif
        qt->out << GERaise;
    }
    qt->out << GEDone;
    qt_flushOutBuffer();
}
Exemple #12
0
static HWND FindPrevInstWindow(HANDLE *hMutex)
{
    // create a unique identifier for this executable
    // (allows independent side-by-side installations)
    ScopedMem<WCHAR> exePath(GetExePath());
    str::ToLower(exePath);
    uint32_t hash = MurmurHash2(exePath.Get(), str::Len(exePath) * sizeof(WCHAR));
    ScopedMem<WCHAR> mapId(str::Format(L"SumatraPDF-%08x", hash));

    int retriesLeft = 3;
Retry:
    // use a memory mapping containing a process id as mutex
    HANDLE hMap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(DWORD), mapId);
    if (!hMap)
        goto Error;
    bool hasPrevInst = GetLastError() == ERROR_ALREADY_EXISTS;
    DWORD *procId = (DWORD *)MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(DWORD));
    if (!procId) {
        CloseHandle(hMap);
        goto Error;
    }
    if (!hasPrevInst) {
        *procId = GetCurrentProcessId();
        UnmapViewOfFile(procId);
        *hMutex = hMap;
        return NULL;
    }

    // if the mapping already exists, find one window belonging to the original process
    DWORD prevProcId = *procId;
    UnmapViewOfFile(procId);
    CloseHandle(hMap);
    HWND hwnd = NULL;
    while ((hwnd = FindWindowEx(HWND_DESKTOP, hwnd, FRAME_CLASS_NAME, NULL)) != NULL) {
        DWORD wndProcId;
        GetWindowThreadProcessId(hwnd, &wndProcId);
        if (wndProcId == prevProcId) {
            AllowSetForegroundWindow(prevProcId);
            return hwnd;
        }
    }

    // fall through
Error:
    if (--retriesLeft < 0)
        return NULL;
    Sleep(100);
    goto Retry;
}
Exemple #13
0
LRESULT TrayIcon::HandleMessage(HWND window, UINT message, WPARAM wParam, LPARAM lParam, NPARAM) {
  if (message >= WM_MOUSEFIRST && message <= WM_MOUSELAST) {
    AllowSetForegroundWindow(mData.processId);

    if (mData.version >= NOTIFYICON_VERSION) {
      SendCallback(message, wParam, lParam);
      if (message == WM_RBUTTONUP) {
        SendCallback(WM_CONTEXTMENU, wParam, lParam);
      } else if (message == WM_LBUTTONUP) {
        SendCallback(NIN_SELECT, wParam, lParam);
      }
    } else {
      SendCallback(message, wParam, lParam);
    }
  }
  return DefWindowProc(window, message, wParam, lParam);
};
Exemple #14
0
int main(int argc, char *argv[])
{
    //FileLogger logger("absinthe.log");
    //qInstallMessageHandler(FileLogger::message);

    AllowSetForegroundWindow(ASFW_ANY);

    QApplication app(argc, argv);
    app.setOrganizationName("QtProject");
    app.setApplicationName("Application Example");

    MainWindow win;

    qApp->setQuitOnLastWindowClosed(false);

    return app.exec();
}
void CSplashScreen::Show() {
	CoInitialize(0);

	// create the named close splash screen event, making sure we're the first process to create it
	SetLastError(ERROR_SUCCESS);

	std::basic_string <TCHAR> strEvent1 = _T("CloseSplashScreenEvent")+m_strPrefix;
	HANDLE hCloseSplashEvent = CreateEvent(NULL, TRUE, FALSE, strEvent1.c_str());

	if (GetLastError() == ERROR_ALREADY_EXISTS) {
		ExitProcess(0);
	}

	std::basic_string <TCHAR> strEvent2 = _T("CloseSplashScreenWithoutFadeEvent")+m_strPrefix;
	HANDLE hCloseSplashWithoutFadeEvent = CreateEvent(NULL, TRUE, FALSE, strEvent2.c_str());
	if (GetLastError() == ERROR_ALREADY_EXISTS) {
		ExitProcess(0);
	}

	HBITMAP hb = m_pImgLoader->LoadSplashImage();
	HWND wnd= NULL;
	RegisterWindowClass();

	if (hb!=NULL) {
		wnd=CreateSplashWindow();
		SetSplashImage(wnd, hb);
	}

	// launch the WPF application
	HANDLE hProcess = LaunchWpfApplication();

	AllowSetForegroundWindow(GetProcessId(hProcess));

	if (wnd!=NULL) {
		// display the splash screen for as long as it's needed
		HANDLE aHandles[3] = { hProcess, hCloseSplashEvent, hCloseSplashWithoutFadeEvent };
		PumpMsgWaitForMultipleObjects(wnd, 3, &aHandles[0], INFINITE);
	}

	CloseHandle(hCloseSplashEvent);
	CloseHandle(hCloseSplashWithoutFadeEvent);

	UnregisterWindowClass();
}
Exemple #16
0
void CWinSystemWin32::SetForegroundWindowInternal(HWND hWnd)
{
    if (!IsWindow(hWnd)) return;

    // if the window isn't focused, bring it to front or SetFullScreen will fail
    BYTE keyState[256] = { 0 };
    // to unlock SetForegroundWindow we need to imitate Alt pressing
    if (GetKeyboardState((LPBYTE)&keyState) && !(keyState[VK_MENU] & 0x80))
        keybd_event(VK_MENU, 0, KEYEVENTF_EXTENDEDKEY | 0, 0);

    BOOL res = SetForegroundWindow(hWnd);

    if (GetKeyboardState((LPBYTE)&keyState) && !(keyState[VK_MENU] & 0x80))
        keybd_event(VK_MENU, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);

    if (!res)
    {
        //relation time of SetForegroundWindow lock
        DWORD lockTimeOut = 0;
        HWND  hCurrWnd = GetForegroundWindow();
        DWORD dwThisTID = GetCurrentThreadId(),
              dwCurrTID = GetWindowThreadProcessId(hCurrWnd, 0);

        // we need to bypass some limitations from Microsoft
        if (dwThisTID != dwCurrTID)
        {
            AttachThreadInput(dwThisTID, dwCurrTID, TRUE);
            SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, &lockTimeOut, 0);
            SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, 0, SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE);
            AllowSetForegroundWindow(ASFW_ANY);
        }

        SetForegroundWindow(hWnd);

        if (dwThisTID != dwCurrTID)
        {
            SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (PVOID)lockTimeOut, SPIF_SENDWININICHANGE | SPIF_UPDATEINIFILE);
            AttachThreadInput(dwThisTID, dwCurrTID, FALSE);
        }
    }
}
BOOL UserImp::allowSetForegroundWindow(DWORD dwProcessId)
{
	if (!bUserLoaded && !loadExports(bAllowLoadLibrary))
	{
		_ASSERTEX(hUser32!=NULL);
		return FALSE;
	}
	
	BOOL lbRc = AllowSetForegroundWindow(dwProcessId);
	/*
	if (allowSetForegroundWindow_f)
	{
		lbRc = allowSetForegroundWindow_f(dwProcessId);
	}
	else
	{
		_ASSERTEX(allowSetForegroundWindow_f!=NULL);
	}
	*/
	return lbRc;
}
Exemple #18
0
void CTextService::_StartConfigure()
{
	HANDLE hMutex = OpenMutexW(SYNCHRONIZE, FALSE, cnfmutexname);
	if(hMutex != nullptr)
	{
		CloseHandle(hMutex);
		return;
	}

	hMutex = OpenMutexW(SYNCHRONIZE, FALSE, mgrmutexname);
	if(hMutex != nullptr)
	{
		CloseHandle(hMutex);

		AllowSetForegroundWindow(ASFW_ANY);

		_CommandDic(REQ_EXEC_CNF);
	}
	else
	{
		StartProcess(g_hInst, IMCRVCNFEXE);
	}
}
bool QtLocalPeer::sendMessage(const QString &message, int timeout)
{
	if (!isClient())
		return false;

	QLocalSocket socket;
	bool connOk = false;
	for(int i = 0; i < 2; i++) {
		// Try twice, in case the other instance is just starting up
		socket.connectToServer(socketName);
		connOk = socket.waitForConnected(timeout/2);
		if (connOk || i)
			break;
		int ms = 250;
#if defined(Q_OS_WIN)
		Sleep(DWORD(ms));
#else
		struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
		nanosleep(&ts, NULL);
#endif
	}
	if (!connOk)
		return false;

#if defined(Q_OS_WIN)
	AllowSetForegroundWindow(ASFW_ANY);
#endif

	QByteArray uMsg(message.toUtf8());
	QDataStream ds(&socket);
	ds.writeBytes(uMsg.constData(), uMsg.size());
	bool res = socket.waitForBytesWritten(timeout);
	res &= socket.waitForReadyRead(timeout);   // wait for ack
	res &= (socket.read(qstrlen(ack)) == ack);
	return res;
}
Exemple #20
0
int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
    TCHAR basedir[LAUNCHER_MAXPATH] = {0};
    TCHAR java[LAUNCHER_MAXPATH] = {0};
    TCHAR appFolder[LAUNCHER_MAXPATH] = {0};
    TCHAR java_escaped[LAUNCHER_MAXPATH] = {0};
    TCHAR jar[LAUNCHER_MAXPATH] = {0};
    LPTSTR *szArgList;
    int argCount;

    // Parse command line arguments to see if /Debug is there
    szArgList = CommandLineToArgvW(GetCommandLine(), &argCount);

    // [RT-31061] otherwise UI can be left in back of other windows
    AllowSetForegroundWindow(ASFW_ANY);

    enableDebugIfNeeded(argCount, szArgList);

    if (isDebug) {
        AllocConsole();
        SetConsoleOutputCP(CP_UTF8);
    }

    if (GetModuleFileNameW(NULL, basedir, LAUNCHER_MAXPATH) != 0) {
        TCHAR *end = _tcsrchr(basedir, '\\');
        if (end != NULL) {
            *end = 0;

            if (!getMainJar(basedir, jar, LAUNCHER_MAXPATH)) {
                showError(
                    (jar[0] == 0) ? _T("Failed to parse package configuration file") : jar,
                    _T("Failed to find main application jar!"));
                return -1;
            }

            getAppFolder(basedir, appFolder, LAUNCHER_MAXPATH);

            //DO Launch
            //this will concatenate arguments using space,
            // we need to make sure spaces are properly escaped if we have any
            _tchdir(appFolder);

            if (!startJVM(basedir, appFolder, jar, argCount, szArgList)) {
                showError(_T("Failed to launch JVM"), NULL);
                return -1;
            }
        }
    }

    if (szArgList != NULL) {
        LocalFree(szArgList);
    }

    if (isDebug) {
      showError(_T("Exiting application"), NULL);
    }
    return 1;
}
Exemple #21
0
Error WordViewer::showDocument(QString& path)
{
   Error errorHR = Success();
   HRESULT hr = S_OK;

   // Allow Word to become the foreground window. CoAllowSetForegroundWindow
   // would be preferable here, since we'd be able to restrict activation to
   // only the process we started, but it is not exposed by MinGW headers.
   // Note that AllowSetForegroundWindow already limits activation to processes
   // initiated by the foreground process, and self-expires on user input.
   AllowSetForegroundWindow(ASFW_ANY);

   // If we have an active IDispatch pointer to Word, check to see whether
   // it has been closed
   if (idispWord_ != NULL)
   {
      // Test the interface by looking up a known DISPID
      const WCHAR* wstrQuit = L"Quit";
      DISPID dispid;
      hr = idispWord_->GetIDsOfNames(IID_NULL, const_cast<WCHAR**>(&wstrQuit),
                                     1, LOCALE_USER_DEFAULT, &dispid);

      // If the lookup fails, release this IDispatch pointer--it's stale.
      // We'll CoCreate a new instance of Word below.
      if (FAILED(hr) &&
          SCODE_CODE(hr) == RPC_S_SERVER_UNAVAILABLE)
      {
         idispWord_->Release();
         idispWord_ = NULL;
      }
   }

   // Get an IDispatch for the Word Application root object
   if (idispWord_ == NULL)
   {
      CLSID clsid;
      LPCOLESTR progId = L"Word.Application";
      CoInitialize(NULL);
      VERIFY_HRESULT(CLSIDFromProgID(progId, &clsid));
      VERIFY_HRESULT(CoCreateInstance(clsid, NULL, CLSCTX_LOCAL_SERVER,
                                      IID_IDispatch,
                                      reinterpret_cast<void**>(&idispWord_)));
      idispWord_->AddRef();
   }

   // Make Word visible
   errorHR = showWord();
   if (errorHR)
      return errorHR;

   IDispatch* idispDocs;
   IDispatch* idispDoc;
   VERIFY_HRESULT(getIDispatchProp(idispWord_, L"Documents", &idispDocs));

   // Open the documenet
   path = path.replace(QChar(L'/'), QChar(L'\\'));
   errorHR = openDocument(path, idispDocs, &idispDoc);
   if (errorHR)
      return errorHR;
   if (docPath_ == path)
   {
      // Reopening the last-opened doc: apply the scroll position if we have
      // one cached
      if (docScrollX_ > 0 || docScrollY_ > 0)
         setDocumentPosition(idispDoc, docScrollX_, docScrollY_);
   }
   else
   {
      // Opening a different doc: forget scroll position and save the doc name
      docScrollX_ = 0;
      docScrollY_ = 0;
      docPath_ = path;
   }

   // Bring Word to the foreground
   VERIFY_HRESULT(invokeDispatch(DISPATCH_METHOD, NULL, idispWord_,
                                 L"Activate", 0));

LErrExit:
   return errorHR;
}
Exemple #22
0
/**
 * Tries to switch to the main window of the VM process.
 *
 * @return true if successfully switched and false otherwise.
 */
bool UIVMItem::switchTo()
{
#ifdef VBOX_WS_MAC
    ULONG64 id = m_machine.ShowConsoleWindow();
#else
    WId id = (WId) m_machine.ShowConsoleWindow();
#endif
    AssertWrapperOk(m_machine);
    if (!m_machine.isOk())
        return false;

    /* winId = 0 it means the console window has already done everything
     * necessary to implement the "show window" semantics. */
    if (id == 0)
        return true;

#if defined (VBOX_WS_WIN) || defined (VBOX_WS_X11)

    return vboxGlobal().activateWindow(id, true);

#elif defined (VBOX_WS_MAC)
    /*
     * This is just for the case were the other process cannot steal
     * the focus from us. It will send us a PSN so we can try.
     */
    ProcessSerialNumber psn;
    psn.highLongOfPSN = id >> 32;
    psn.lowLongOfPSN = (UInt32)id;
    OSErr rc = ::SetFrontProcess(&psn);
    if (!rc)
        Log(("GUI: %#RX64 couldn't do SetFrontProcess on itself, the selector (we) had to do it...\n", id));
    else
        Log(("GUI: Failed to bring %#RX64 to front. rc=%#x\n", id, rc));
    return !rc;

#endif

    return false;

    /// @todo Below is the old method of switching to the console window
    //  based on the process ID of the console process. It should go away
    //  after the new (callback-based) method is fully tested.
#if 0

    if (!canSwitchTo())
        return false;

#if defined (VBOX_WS_WIN)

    HWND hwnd = mWinId;

    /* if there are blockers (modal and modeless dialogs, etc), find the
     * topmost one */
    HWND hwndAbove = NULL;
    do
    {
        hwndAbove = GetNextWindow(hwnd, GW_HWNDPREV);
        HWND hwndOwner;
        if (hwndAbove != NULL &&
            ((hwndOwner = GetWindow(hwndAbove, GW_OWNER)) == hwnd ||
             hwndOwner  == hwndAbove))
            hwnd = hwndAbove;
        else
            break;
    }
    while (1);

    /* first, check that the primary window is visible */
    if (IsIconic(mWinId))
        ShowWindow(mWinId, SW_RESTORE);
    else if (!IsWindowVisible(mWinId))
        ShowWindow(mWinId, SW_SHOW);

#if 0
    LogFlowFunc(("mWinId=%08X hwnd=%08X\n", mWinId, hwnd));
#endif

    /* then, activate the topmost in the group */
    AllowSetForegroundWindow(m_pid);
    SetForegroundWindow(hwnd);

    return true;

#elif defined (VBOX_WS_X11)

    return false;

#elif defined (VBOX_WS_MAC)

    ProcessSerialNumber psn;
    OSStatus rc = ::GetProcessForPID(m_pid, &psn);
    if (!rc)
    {
        rc = ::SetFrontProcess(&psn);

        if (!rc)
        {
            ShowHideProcess(&psn, true);
            return true;
        }
    }
    return false;

#else

    return false;

#endif

#endif
}
Exemple #23
0
LRESULT CMainWindow::DoCommand(int id, LPARAM lParam)
{
    switch (id)
    {
    case ID_FILE_OPEN:
        {
            if (OpenDialog())
            {
                picWindow1.SetPic(leftpicpath, L"", true);
                picWindow2.SetPic(rightpicpath, L"", false);
                if (bOverlap)
                {
                    picWindow1.SetSecondPic(picWindow2.GetPic(), rightpictitle, rightpicpath);
                }
                else
                {
                    picWindow1.SetSecondPic();
                }
                RECT rect;
                GetClientRect(*this, &rect);
                PositionChildren(&rect);
                picWindow1.FitImageInWindow();
                picWindow2.FitImageInWindow();
            }
        }
        break;
    case ID_VIEW_IMAGEINFO:
        {
            bShowInfo = !bShowInfo;
            HMENU hMenu = GetMenu(*this);
            UINT uCheck = MF_BYCOMMAND;
            uCheck |= bShowInfo ? MF_CHECKED : MF_UNCHECKED;
            CheckMenuItem(hMenu, ID_VIEW_IMAGEINFO, uCheck);

            picWindow1.ShowInfo(bShowInfo);
            picWindow2.ShowInfo(bShowInfo);
            picWindow3.ShowInfo(bShowInfo);

            // change the state of the toolbar button
            TBBUTTONINFO tbi;
            tbi.cbSize = sizeof(TBBUTTONINFO);
            tbi.dwMask = TBIF_STATE;
            tbi.fsState = bShowInfo ? TBSTATE_CHECKED | TBSTATE_ENABLED : TBSTATE_ENABLED;
            SendMessage(hwndTB, TB_SETBUTTONINFO, ID_VIEW_IMAGEINFO, (LPARAM)&tbi);
        }
        break;
    case ID_VIEW_OVERLAPIMAGES:
        {
            bOverlap = !bOverlap;
            HMENU hMenu = GetMenu(*this);
            UINT uCheck = MF_BYCOMMAND;
            uCheck |= bOverlap ? MF_CHECKED : MF_UNCHECKED;
            CheckMenuItem(hMenu, ID_VIEW_OVERLAPIMAGES, uCheck);
            uCheck |= ((m_BlendType == CPicWindow::BLEND_ALPHA) && bOverlap) ? MF_CHECKED : MF_UNCHECKED;
            CheckMenuItem(hMenu, ID_VIEW_BLENDALPHA, uCheck);
            UINT uEnabled = MF_BYCOMMAND;
            uEnabled |= bOverlap ? MF_ENABLED : MF_DISABLED | MF_GRAYED;
            EnableMenuItem(hMenu, ID_VIEW_BLENDALPHA, uEnabled);

            // change the state of the toolbar button
            TBBUTTONINFO tbi;
            tbi.cbSize = sizeof(TBBUTTONINFO);
            tbi.dwMask = TBIF_STATE;
            tbi.fsState = bOverlap ? TBSTATE_CHECKED | TBSTATE_ENABLED : TBSTATE_ENABLED;
            SendMessage(hwndTB, TB_SETBUTTONINFO, ID_VIEW_OVERLAPIMAGES, (LPARAM)&tbi);

            tbi.fsState = ((m_BlendType == CPicWindow::BLEND_ALPHA) && bOverlap) ? TBSTATE_CHECKED : 0;
            if (bOverlap)
                tbi.fsState |= TBSTATE_ENABLED;
            else
                tbi.fsState = 0;
            SendMessage(hwndTB, TB_SETBUTTONINFO, ID_VIEW_BLENDALPHA, (LPARAM)&tbi);

            if (bOverlap)
                tbi.fsState = 0;
            else
                tbi.fsState = bVertical ? TBSTATE_ENABLED | TBSTATE_CHECKED : TBSTATE_ENABLED;
            SendMessage(hwndTB, TB_SETBUTTONINFO, ID_VIEW_ARRANGEVERTICAL, (LPARAM)&tbi);

            if (bOverlap)
            {
                bLinkedPositions = true;
                picWindow1.LinkPositions(bLinkedPositions);
                picWindow2.LinkPositions(bLinkedPositions);
                tbi.fsState = TBSTATE_CHECKED;
            }
            else
                tbi.fsState = bLinkedPositions ? TBSTATE_ENABLED | TBSTATE_CHECKED : TBSTATE_ENABLED;
            SendMessage(hwndTB, TB_SETBUTTONINFO, ID_VIEW_LINKIMAGESTOGETHER, (LPARAM)&tbi);

            ShowWindow(picWindow2, bOverlap ? SW_HIDE : SW_SHOW);

            if (bOverlap)
            {
                picWindow1.StopTimer();
                picWindow2.StopTimer();
                picWindow1.SetSecondPic(picWindow2.GetPic(), rightpictitle, rightpicpath,
                    picWindow2.GetHPos(), picWindow2.GetVPos());
                picWindow1.SetBlendAlpha(m_BlendType, 0.5f);
            }
            else
            {
                picWindow1.SetSecondPic();
            }
            picWindow1.SetOverlapMode(bOverlap);
            picWindow2.SetOverlapMode(bOverlap);


            RECT rect;
            GetClientRect(*this, &rect);
            PositionChildren(&rect);

            return 0;
        }
        break;
    case ID_VIEW_BLENDALPHA:
        {
            if (m_BlendType == CPicWindow::BLEND_ALPHA)
                m_BlendType = CPicWindow::BLEND_XOR;
            else
                m_BlendType = CPicWindow::BLEND_ALPHA;

            HMENU hMenu = GetMenu(*this);
            UINT uCheck = MF_BYCOMMAND;
            uCheck |= ((m_BlendType == CPicWindow::BLEND_ALPHA) && bOverlap) ? MF_CHECKED : MF_UNCHECKED;
            CheckMenuItem(hMenu, ID_VIEW_BLENDALPHA, uCheck);
            UINT uEnabled = MF_BYCOMMAND;
            uEnabled |= bOverlap ? MF_ENABLED : MF_DISABLED | MF_GRAYED;
            EnableMenuItem(hMenu, ID_VIEW_BLENDALPHA, uEnabled);

            // change the state of the toolbar button
            TBBUTTONINFO tbi;
            tbi.cbSize = sizeof(TBBUTTONINFO);
            tbi.dwMask = TBIF_STATE;
            tbi.fsState = ((m_BlendType == CPicWindow::BLEND_ALPHA) && bOverlap) ? TBSTATE_CHECKED | TBSTATE_ENABLED : TBSTATE_ENABLED;
            SendMessage(hwndTB, TB_SETBUTTONINFO, ID_VIEW_BLENDALPHA, (LPARAM)&tbi);
            picWindow1.SetBlendAlpha(m_BlendType, picWindow1.GetBlendAlpha());
            PositionChildren();
        }
        break;
    case ID_VIEW_TRANSPARENTCOLOR:
        {
            static COLORREF customColors[16] = {0};
            CHOOSECOLOR ccDlg = { 0 };
            ccDlg.lStructSize = sizeof(ccDlg);
            ccDlg.hwndOwner = m_hwnd;
            ccDlg.rgbResult = transparentColor;
            ccDlg.lpCustColors = customColors;
            ccDlg.Flags = CC_RGBINIT | CC_FULLOPEN;
            if(ChooseColor(&ccDlg))
            {
                transparentColor = ccDlg.rgbResult;
                picWindow1.SetTransparentColor(transparentColor);
                picWindow2.SetTransparentColor(transparentColor);
                picWindow3.SetTransparentColor(transparentColor);
                // The color picker takes the focus and we don't get it back.
                ::SetFocus(picWindow1);
            }
        }
        break;
    case ID_VIEW_FITIMAGEWIDTHS:
        {
            bFitWidths = !bFitWidths;
            picWindow1.FitWidths(bFitWidths);
            picWindow2.FitWidths(bFitWidths);
            picWindow3.FitWidths(bFitWidths);

            HMENU hMenu = GetMenu(*this);
            UINT uCheck = MF_BYCOMMAND;
            uCheck |= bFitWidths ? MF_CHECKED : MF_UNCHECKED;
            CheckMenuItem(hMenu, ID_VIEW_FITIMAGEWIDTHS, uCheck);

            // change the state of the toolbar button
            TBBUTTONINFO tbi;
            tbi.cbSize = sizeof(TBBUTTONINFO);
            tbi.dwMask = TBIF_STATE;
            tbi.fsState = bFitWidths ? TBSTATE_CHECKED | TBSTATE_ENABLED : TBSTATE_ENABLED;
            SendMessage(hwndTB, TB_SETBUTTONINFO, ID_VIEW_FITIMAGEWIDTHS, (LPARAM)&tbi);
        }
        break;
    case ID_VIEW_FITIMAGEHEIGHTS:
        {
            bFitHeights = !bFitHeights;
            picWindow1.FitHeights(bFitHeights);
            picWindow2.FitHeights(bFitHeights);
            picWindow3.FitHeights(bFitHeights);

            HMENU hMenu = GetMenu(*this);
            UINT uCheck = MF_BYCOMMAND;
            uCheck |= bFitHeights ? MF_CHECKED : MF_UNCHECKED;
            CheckMenuItem(hMenu, ID_VIEW_FITIMAGEHEIGHTS, uCheck);

            // change the state of the toolbar button
            TBBUTTONINFO tbi;
            tbi.cbSize = sizeof(TBBUTTONINFO);
            tbi.dwMask = TBIF_STATE;
            tbi.fsState = bFitHeights ? TBSTATE_CHECKED | TBSTATE_ENABLED : TBSTATE_ENABLED;
            SendMessage(hwndTB, TB_SETBUTTONINFO, ID_VIEW_FITIMAGEHEIGHTS, (LPARAM)&tbi);
        }
        break;
    case ID_VIEW_LINKIMAGESTOGETHER:
        {
            bLinkedPositions = !bLinkedPositions;
            picWindow1.LinkPositions(bLinkedPositions);
            picWindow2.LinkPositions(bLinkedPositions);
            picWindow3.LinkPositions(bLinkedPositions);

            HMENU hMenu = GetMenu(*this);
            UINT uCheck = MF_BYCOMMAND;
            uCheck |= bLinkedPositions ? MF_CHECKED : MF_UNCHECKED;
            CheckMenuItem(hMenu, ID_VIEW_LINKIMAGESTOGETHER, uCheck);

            // change the state of the toolbar button
            TBBUTTONINFO tbi;
            tbi.cbSize = sizeof(TBBUTTONINFO);
            tbi.dwMask = TBIF_STATE;
            tbi.fsState = bLinkedPositions ? TBSTATE_CHECKED | TBSTATE_ENABLED : TBSTATE_ENABLED;
            SendMessage(hwndTB, TB_SETBUTTONINFO, ID_VIEW_LINKIMAGESTOGETHER, (LPARAM)&tbi);
        }
        break;
    case ID_VIEW_ALPHA0:
        picWindow1.SetBlendAlpha(m_BlendType, 0.0f);
        break;
    case ID_VIEW_ALPHA255:
        picWindow1.SetBlendAlpha(m_BlendType, 1.0f);
        break;
    case ID_VIEW_ALPHA127:
        picWindow1.SetBlendAlpha(m_BlendType, 0.5f);
        break;
    case ID_VIEW_ALPHATOGGLE:
        picWindow1.ToggleAlpha();
        break;
    case ID_VIEW_FITIMAGESINWINDOW:
        {
            picWindow1.FitImageInWindow();
            picWindow2.FitImageInWindow();
            picWindow3.FitImageInWindow();
        }
        break;
    case ID_VIEW_ORININALSIZE:
        {
            picWindow1.SetZoom(100, false);
            picWindow2.SetZoom(100, false);
            picWindow3.SetZoom(100, false);
            picWindow1.CenterImage();
            picWindow2.CenterImage();
            picWindow3.CenterImage();
        }
        break;
    case ID_VIEW_ZOOMIN:
        {
            picWindow1.Zoom(true, false);
            if ((!(bFitWidths || bFitHeights))&&(!bOverlap))
            {
                picWindow2.Zoom(true, false);
                picWindow3.Zoom(true, false);
            }
        }
        break;
    case ID_VIEW_ZOOMOUT:
        {
            picWindow1.Zoom(false, false);
            if ((!(bFitWidths || bFitHeights))&&(!bOverlap))
            {
                picWindow2.Zoom(false, false);
                picWindow3.Zoom(false, false);
            }
        }
        break;
    case ID_VIEW_ARRANGEVERTICAL:
        {
            bVertical = !bVertical;
            RECT rect;
            GetClientRect(*this, &rect);
            if (bVertical)
            {
                RECT tbRect;
                GetWindowRect(hwndTB, &tbRect);
                LONG tbHeight = tbRect.bottom-tbRect.top-1;
                if (selectionPaths.size() != 3)
                {
                    nSplitterPos = (rect.bottom-rect.top)/2+tbHeight;
                    nSplitterPos2 = 0;
                }
                else
                {
                    nSplitterPos = (rect.bottom-rect.top)/3+tbHeight;
                    nSplitterPos2 = (rect.bottom-rect.top)*2/3+tbHeight;
                }
            }
            else
            {
                if (selectionPaths.size() != 3)
                {
                    nSplitterPos = (rect.right-rect.left)/2;
                    nSplitterPos2 = 0;
                }
                else
                {
                    nSplitterPos = (rect.right-rect.left)/3;
                    nSplitterPos2 = (rect.right-rect.left)*2/3;
                }
            }
            HMENU hMenu = GetMenu(*this);
            UINT uCheck = MF_BYCOMMAND;
            uCheck |= bVertical ? MF_CHECKED : MF_UNCHECKED;
            CheckMenuItem(hMenu, ID_VIEW_ARRANGEVERTICAL, uCheck);
            // change the state of the toolbar button
            TBBUTTONINFO tbi;
            tbi.cbSize = sizeof(TBBUTTONINFO);
            tbi.dwMask = TBIF_STATE;
            tbi.fsState = bVertical ? TBSTATE_CHECKED | TBSTATE_ENABLED : TBSTATE_ENABLED;
            SendMessage(hwndTB, TB_SETBUTTONINFO, ID_VIEW_ARRANGEVERTICAL, (LPARAM)&tbi);

            PositionChildren(&rect);
        }
        break;
    case ID_ABOUT:
        {
            CAboutDlg dlg(*this);
            dlg.DoModal(hInst, IDD_ABOUT, *this);
        }
        break;
    case SELECTBUTTON_ID:
        {
            HWND hSource = (HWND)lParam;
            FileType resolveWith;
            if (picWindow1 == hSource)
                resolveWith = FileTypeMine;
            else if (picWindow2 == hSource)
                resolveWith = FileTypeBase;
            else if (picWindow3 == hSource)
                resolveWith = FileTypeTheirs;
            else
                break;

            if (selectionResult.empty())
            {
                PostQuitMessage(resolveWith);
                break;
            }

            CopyFile(selectionPaths[resolveWith].c_str(), selectionResult.c_str(), FALSE);

            CAutoBuf projectRoot;
            if (git_repository_discover(projectRoot, CUnicodeUtils::GetUTF8(selectionResult.c_str()), FALSE, nullptr) < 0 && strstr(projectRoot->ptr, "/.git/"))
            {
                PostQuitMessage(resolveWith);
                break;
            }

            CAutoRepository repository(projectRoot->ptr);
            if (!repository)
            {
                PostQuitMessage(resolveWith);
                break;
            }

            CStringA subpath = CUnicodeUtils::GetUTF8(selectionResult.c_str()).Mid((int)strlen(git_repository_workdir(repository)));

            CAutoIndex index;
            if (git_repository_index(index.GetPointer(), repository) || (git_index_get_bypath(index, subpath, 1) == nullptr && git_index_get_bypath(index, subpath, 2) == nullptr))
            {
                PostQuitMessage(resolveWith);
                break;
            }

            CString sTemp;
            sTemp.Format(ResString(hResource, IDS_MARKASRESOLVED), (LPCTSTR)CPathUtils::GetFileNameFromPath(selectionResult.c_str()));
            if (MessageBox(m_hwnd, sTemp, L"TortoiseGitMerge", MB_YESNO | MB_ICONQUESTION) != IDYES)
                break;

            CString cmd;
            cmd.Format(L"\"%sTortoiseGitProc.exe\" /command:resolve /path:\"%s\" /closeonend:1 /noquestion /skipcheck /silent", (LPCTSTR)CPathUtils::GetAppDirectory(), selectionResult.c_str());
            if (resolveMsgWnd)
                cmd.AppendFormat(L" /resolvemsghwnd:%I64d /resolvemsgwparam:%I64d /resolvemsglparam:%I64d", (__int64)resolveMsgWnd, (__int64)resolveMsgWParam, (__int64)resolveMsgLParam);

            STARTUPINFO startup = { 0 };
            PROCESS_INFORMATION process = { 0 };
            startup.cb = sizeof(startup);

            if (!CreateProcess(nullptr, cmd.GetBuffer(), nullptr, nullptr, FALSE, CREATE_UNICODE_ENVIRONMENT, nullptr, nullptr, &startup, &process))
            {
                cmd.ReleaseBuffer();
                PostQuitMessage(resolveWith);
                break;
            }
            cmd.ReleaseBuffer();

            AllowSetForegroundWindow(process.dwProcessId);

            CloseHandle(process.hThread);
            CloseHandle(process.hProcess);

            PostQuitMessage(resolveWith);
        }
        break;
    case IDM_EXIT:
        ::PostQuitMessage(0);
        return 0;
        break;
    default:
        break;
    };
    return 1;
}
Exemple #24
0
// Если (anFromShowWindow != -1), значит функу зовут из ShowWindow
void OnGuiWindowAttached(HWND hWindow, HMENU hMenu, LPCSTR asClassA, LPCWSTR asClassW, DWORD anStyle, DWORD anStyleEx, BOOL abStyleHidden, int anFromShowWindow/*=-1*/)
{
	DWORD nCurStyle = (DWORD)GetWindowLongPtr(hWindow, GWL_STYLE);
	DWORD nCurStyleEx = (DWORD)GetWindowLongPtr(hWindow, GWL_EXSTYLE);

	AllowSetForegroundWindow(ASFW_ANY);

	// VLC создает несколько "подходящих" окон, но ShowWindow зовет
	// только для одного из них. Поэтому фактический аттач делаем
	// только в том случае, если окно "видимое"
	if ((!(nCurStyle & WS_VISIBLE)) && (anFromShowWindow <= SW_HIDE))
	{
		// Значит потом, из ShowWindow
		return;
	}

	ghAttachGuiClient = hWindow;
	gnAttachGuiClientThreadId = GetWindowThreadProcessId(hWindow, NULL);
	gbForceShowGuiClient = TRUE;
	gbAttachGuiClient = FALSE; // Только одно окно приложения. Пока?

#if 0
	// Для WS_CHILDWINDOW меню нельзя указать при создании окна
	if (!hMenu && !ghAttachGuiClientMenu && (asClassA || asClassW))
	{
		BOOL lbRcClass;
		WNDCLASSEXA wca = {sizeof(WNDCLASSEXA)};
		WNDCLASSEXW wcw = {sizeof(WNDCLASSEXW)};
		if (asClassA)
		{
			lbRcClass = GetClassInfoExA(GetModuleHandle(NULL), asClassA, &wca);
			if (lbRcClass)
				ghAttachGuiClientMenu = LoadMenuA(wca.hInstance, wca.lpszMenuName);
		}
		else
		{
			lbRcClass = GetClassInfoExW(GetModuleHandle(NULL), asClassW, &wcw);
			if (lbRcClass)
				ghAttachGuiClientMenu = LoadMenuW(wca.hInstance, wcw.lpszMenuName);
		}
		hMenu = ghAttachGuiClientMenu;
	}
	if (hMenu)
	{
		// Для WS_CHILDWINDOW - не работает
		SetMenu(hWindow, hMenu);
		HMENU hSys = GetSystemMenu(hWindow, FALSE);
		TODO("Это в принципе прокатывает, но нужно транслировать WM_SYSCOMMAND -> WM_COMMAND, соответственно, перехватывать WndProc, или хук ставить");
		if (hSys)
		{
			TODO("Хотя, хорошо бы не все в Popup засоывать, а извлечь ChildPopups из hMenu");
			InsertMenu(hSys, 0, MF_BYPOSITION|MF_POPUP, (UINT_PTR)hMenu, L"Window menu");
			InsertMenu(hSys, 1, MF_BYPOSITION|MF_SEPARATOR, NULL, NULL);
		}
	}
#endif

	DWORD nSize = sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_ATTACHGUIAPP);
	CESERVER_REQ *pIn = ExecuteNewCmd(CECMD_ATTACHGUIAPP, nSize);

	gnAttachGuiClientFlags = agaf_Success;
	// С приложенями .Net - приходится работать как с WS_CHILD,
	// иначе в них "не нажимаются" тулбары и меню
	if (IsDotNetWindow(hWindow))
	{
		gnAttachGuiClientFlags |= (agaf_DotNet|agaf_WS_CHILD);
	}
	// Если в окне нет меню - работаем с ним как с WS_CHILD
	// так не возникает проблем с активацией и т.д.
	else if (GetMenu(hWindow) == NULL)
	{
		if (IsQtWindow(asClassA, asClassW))
			gnAttachGuiClientFlags |= (agaf_NoMenu|agaf_QtWindow|agaf_WS_CHILD);
		else
			gnAttachGuiClientFlags |= (agaf_NoMenu|agaf_WS_CHILD);
	}
	pIn->AttachGuiApp.nFlags = gnAttachGuiClientFlags;
	pIn->AttachGuiApp.nPID = GetCurrentProcessId();
	pIn->AttachGuiApp.nServerPID = gnServerPID;
	pIn->AttachGuiApp.hAppWindow = hWindow;
	pIn->AttachGuiApp.Styles.nStyle = nCurStyle; // стили могли измениться после создания окна,
	pIn->AttachGuiApp.Styles.nStyleEx = nCurStyleEx; // поэтому получим актуальные
	GetWindowRect(hWindow, &pIn->AttachGuiApp.rcWindow);
	GetModuleFileName(NULL, pIn->AttachGuiApp.sAppFilePathName, countof(pIn->AttachGuiApp.sAppFilePathName));
	pIn->AttachGuiApp.hkl = (DWORD)(LONG)(LONG_PTR)GetKeyboardLayout(0);

	wchar_t szGuiPipeName[128];
	msprintf(szGuiPipeName, countof(szGuiPipeName), CEGUIPIPENAME, L".", (DWORD)ghConEmuWnd);


	// AttachThreadInput
	DWORD nConEmuTID = GetWindowThreadProcessId(ghConEmuWnd, NULL);
	DWORD nTID = GetCurrentThreadId();
	_ASSERTEX(nTID==gnHookMainThreadId || nTID==gnAttachGuiClientThreadId);
	BOOL bAttachRc = AttachThreadInput(nTID, nConEmuTID, TRUE);
	DWORD nAttachErr = GetLastError();
	UNREFERENCED_PARAMETER(bAttachRc); UNREFERENCED_PARAMETER(nAttachErr);

	HWND hPreFocus = GetFocus();


	CESERVER_REQ* pOut = ExecuteCmd(szGuiPipeName, pIn, 0/*Default timeout*/, NULL);

	ExecuteFreeResult(pIn);

	// abStyleHidden == TRUE, если окно при создании указало флаг WS_VISIBLE (т.е. не собиралось звать ShowWindow)

	if (pOut)
	{
		if (pOut->hdr.cbSize > sizeof(CESERVER_REQ_HDR))
		{
			_ASSERTE((pOut->AttachGuiApp.nFlags & agaf_Success) == agaf_Success);

			BOOL lbRc = FALSE;

			_ASSERTE(pOut->AttachGuiApp.hConEmuBack && pOut->AttachGuiApp.hConEmuDc && (HWND)pOut->AttachGuiApp.hConEmuDc!=(HWND)pOut->AttachGuiApp.hConEmuBack);
			_ASSERTE((ghConEmuWndBack==NULL) || (pOut->AttachGuiApp.hConEmuBack==ghConEmuWndBack));
			_ASSERTE(ghConEmuWnd && (ghConEmuWnd==pOut->AttachGuiApp.hConEmuWnd));
			ghConEmuWnd = pOut->AttachGuiApp.hConEmuWnd;
			SetConEmuHkWindows(pOut->AttachGuiApp.hConEmuDc, pOut->AttachGuiApp.hConEmuBack);

			//gbGuiClientHideCaption = pOut->AttachGuiApp.bHideCaption;
			gGuiClientStyles = pOut->AttachGuiApp.Styles;

			#ifdef _DEBUG
			HWND hFocus = GetFocus();
			DWORD nFocusPID = 0;

			if (hFocus)
			{
				GetWindowThreadProcessId(hFocus, &nFocusPID);
				DWORD nConEmuPID = 0; GetWindowThreadProcessId(ghConEmuWnd, &nConEmuPID);
				if (nFocusPID != GetCurrentProcessId() && nFocusPID != nConEmuPID)
				{
					// Допустимая ситуация, когда одновременно во вкладки цепляется
					// несколько ChildGui. Например, при запуске из bat-файла...
					hFocus = hWindow;
				}
			}
			#endif

			if (pOut->AttachGuiApp.hkl)
			{
				LONG_PTR hkl = (LONG_PTR)(LONG)pOut->AttachGuiApp.hkl;
				lbRc = ActivateKeyboardLayout((HKL)hkl, KLF_SETFORPROCESS) != NULL;
				UNREFERENCED_PARAMETER(lbRc);
			}

			//grcAttachGuiClientPos = pOut->AttachGuiApp.rcWindow;
			ReplaceGuiAppWindow(abStyleHidden);

			//if (hPreFocus)
			//{
			//	SetFocus(hPreFocus);
			//}
			UINT nMsgID = RegisterWindowMessageW(CONEMUMSG_RESTORECHILDFOCUS);
			PostMessageW(ghConEmuWndBack, nMsgID, 0,0);

			//// !!! OnSetForegroundWindow не подходит - он дергает Cmd.
			////SetForegroundWindow(ghConEmuWnd);
			//#if 0
			//wchar_t szClass[64] = {}; GetClassName(hFocus, szClass, countof(szClass));
			//MessageBox(NULL, szClass, L"WasFocused", MB_SYSTEMMODAL);
			//#endif
			////if (!(nCurStyle & WS_CHILDWINDOW))
			//{
			//	// Если ставить WS_CHILD - пропадет меню!
			//	//nCurStyle = (nCurStyle | WS_CHILDWINDOW|WS_TABSTOP); // & ~(WS_THICKFRAME/*|WS_CAPTION|WS_MINIMIZEBOX|WS_MAXIMIZEBOX*/);
			//	//SetWindowLongPtr(hWindow, GWL_STYLE, nCurStyle);
			//	if (gnAttachGuiClientFlags & agaf_DotNet)
			//	{
			//	}
			//	else
			//	{
			//		SetParent(hWindow, ghConEmuWndBack);
			//	}
			//}
			//
			//RECT rcGui = grcAttachGuiClientPos = pOut->AttachGuiApp.rcWindow;
			//if (SetWindowPos(hWindow, HWND_TOP, rcGui.left,rcGui.top, rcGui.right-rcGui.left, rcGui.bottom-rcGui.top,
			//	SWP_DRAWFRAME | /*SWP_FRAMECHANGED |*/ (abStyleHidden ? SWP_SHOWWINDOW : 0)))
			//{
			//	if (abStyleHidden)
			//		abStyleHidden = FALSE;
			//}
			//
			//// !!! OnSetForegroundWindow не подходит - он дергает Cmd.
			//SetForegroundWindow(ghConEmuWnd);
			////if (hFocus)
			////SetFocus(hFocus ? hFocus : hWindow); // hFocus==NULL, эффекта нет
			////OnSetForegroundWindow(hWindow);
			////PostMessageW(ghConEmuWnd, WM_NCACTIVATE, TRUE, 0);
			////PostMessageW(ghConEmuWnd, WM_NCPAINT, 0, 0);
			//PostMessageW(hWindow, WM_NCPAINT, 0, 0);
		}
		ExecuteFreeResult(pOut);
	}

	if (abStyleHidden)
	{
		ShowWindow(hWindow, SW_SHOW);
	}
}
Exemple #25
0
/*************************************************************************
* SHCreateFromDesktop			[BROWSEUI.106]
* parameter is a FolderInfo
*/
BOOL WINAPI SHCreateFromDesktop(ExplorerCommandLineParseResults * parseResults)
{
    DbgPrint("SHCreateFromDesktop\n");

    IEThreadParamBlock * parameters = SHCreateIETHREADPARAM(0, 0, 0, 0);
    if (!parameters)
        return FALSE;

    PCWSTR strPath = NULL;
    if (parseResults->dwFlags & SH_EXPLORER_CMDLINE_FLAG_STRING)
    {
        if (parseResults->pidlPath)
        {
            WARN("strPath and pidlPath are both assigned. This shouldn't happen.\n");
        }

        strPath = parseResults->strPath;
    }

    parameters->dwFlags = parseResults->dwFlags;
    parameters->offset8 = parseResults->offsetC;

    LPITEMIDLIST pidl = parseResults->pidlPath ? ILClone(parseResults->pidlPath) : NULL;
    if (!pidl && parseResults->dwFlags & SH_EXPLORER_CMDLINE_FLAG_STRING)
    {
        if (parseResults->strPath && parseResults->strPath[0])
        {
            pidl = ILCreateFromPathW(parseResults->strPath);
        }
    }

    parameters->directoryPIDL = pidl;

    // Try to find the owner of the idlist, if we aren't running /SEPARATE
    HWND desktop = NULL;
    if (!(parseResults->dwFlags & SH_EXPLORER_CMDLINE_FLAG_SEPARATE))
        desktop = FindShellProxy(parameters->directoryPIDL);

    // If found, ask it to open the new window
    if (desktop)
    {
        DbgPrint("Found desktop hwnd=%p\n", desktop);

        DWORD dwProcessId;

        GetWindowThreadProcessId(desktop, &dwProcessId);
        AllowSetForegroundWindow(dwProcessId);

        HANDLE hShared = MakeSharedPacket(parameters, strPath, dwProcessId);
        if (hShared)
        {
            DbgPrint("Sending open message...\n");

            PostMessageW(desktop, WM_EXPLORER_OPEN_NEW_WINDOW, 0, (LPARAM) hShared);
        }

        SHDestroyIETHREADPARAM(parameters);
        return TRUE;
    }

    DbgPrint("Desktop not found or separate flag requested.\n");

    // Else, start our own message loop!
    HRESULT hr = CoInitialize(NULL);
    CProxyDesktop * proxy = CreateProxyDesktop(parameters);
    if (proxy)
    {
        LONG refCount;
        CComPtr<IUnknown> thread;
        if (SHCreateThreadRef(&refCount, &thread) >= 0)
        {
            SHSetInstanceExplorer(thread);
            if (strPath)
                parameters->directoryPIDL = ILCreateFromPath(strPath);
            SHOpenFolderWindow(parameters);
            parameters = NULL;
            thread.Release();
        }

        MSG Msg;
        while (GetMessageW(&Msg, 0, 0, 0) && refCount)
        {
            TranslateMessage(&Msg);
            DispatchMessageW(&Msg);
        }

        delete proxy;
    }

    if (SUCCEEDED(hr))
        CoUninitialize();

    SHDestroyIETHREADPARAM(parameters);

    return TRUE;
}
Exemple #26
0
BOOL CFusicCartsDlg::OnInitDialog()
{
	mysqlpp::StoreQueryResult resFuse;
	mysqlpp::StoreQueryResult resUser;
	CDialog::OnInitDialog();

	//set the stop all button dialog pointer:
	m_ctlBtnStopall.fnSetCartsDialogPointer((void*)this);

	//set up button maps:
	fnSetupButtonMaps();

	//set up all nav buttons:
	for(mapNav::iterator i = m_mapBtnNavBottom.begin(); i != m_mapBtnNavBottom.end();
		i++)
	{
		i->second->fnSetupNavButtonForPage(i->first, USERCARTS, (void*)this);
	}

	for(mapNav::iterator i = m_mapBtnNavTop.begin(); i != m_mapBtnNavTop.end();
		i++)
	{
		i->second->fnSetupNavButtonForPage(i->first, FUSECARTS, (void*)this);
	}

	//setup all carts buttons:
	for(mapCart::iterator i = m_mapBtnCartBottom.begin(); i != m_mapBtnCartBottom.end();
		i++)
	{
		i->second->fnSetDefaultButton();
	}

	for(mapCart::iterator i = m_mapBtnCartTop.begin(); i != m_mapBtnCartTop.end();
		i++)
	{
		i->second->fnSetDefaultButton();
	}



	//setup stopall button:
	m_ctlBtnStopall.fnSetBackColour(255,0,0, true);
	m_ctlBtnStopall.fnSetFontColour(255,255,0);
	m_ctlBtnStopall.fnSetEdgeColour(255,255,0);
	m_ctlBtnStopall.fnSetClickColourChange(true);

	//setup logout button:
	m_ctlBtnLogout.fnSetBackColour(255,0,0,true);
	m_ctlBtnLogout.fnSetFontColour(255,255,0);
	m_ctlBtnLogout.fnSetEdgeColour(255,255,0);
	m_ctlBtnLogout.fnSetClickColourChange(true);

	//setup reconnect button:
	m_ctlBtnReconnect.fnSetBackColour(255,0,0,true);
	m_ctlBtnReconnect.fnSetFontColour(255,255,0);
	m_ctlBtnReconnect.fnSetEdgeColour(255,255,0);
	m_ctlBtnReconnect.fnSetClickColourChange(true);

	//setup refresh button:
	m_ctlBtnRefresh.fnSetBackColour(255,0,0,true);
	m_ctlBtnRefresh.fnSetFontColour(255,255,0);
	m_ctlBtnRefresh.fnSetEdgeColour(255,255,0);
	m_ctlBtnRefresh.fnSetClickColourChange(true);


	//create the connection to mysql:
	if(!connect())
	{
		//we didnt connect:
		CString strError;
		strError = "Error: could not connecto the mysql database: ";
		strError += m_PMYSQLConn->error();
		strError += ".";
		MessageBox(strError, "Carts Pane", MB_OK | MB_ICONERROR);
	}

	//need to get all fuse carts:
	resFuse = fnGetResultSetForQuery("SELECT * FROM tbl_carts where Show_ID = 0 and Cart_ID like '1%'");

	//setup fuse carts:
	fnSetupButtonForPageData(resFuse, FUSECARTS);

	//do the query for user carts:
	CString strQuery;
	CString strShowID;
	strShowID.Format("%d", g_intShowID);
	strQuery = "SELECT * FROM tbl_carts where Show_ID = ";
	strQuery += strShowID;
	strQuery += " and Cart_ID like '1%'";

	//do the query:
	resUser = fnGetResultSetForQuery(strQuery);

	//setup the user buttons:
	fnSetupButtonForPageData(resUser, USERCARTS);

	//we need now to get carts that where left playing on logout:
	for(std::vector<SCartsList>::iterator i = m_pLoginDlg->m_vecCartsList.begin();
		i != m_pLoginDlg->m_vecCartsList.end(); i++)
	{
		//we want to set all current first buttons up (as these will be displaied first):
		//get the button we firstly need to change:
		CCartsButton* curBtn = NULL;
		if(i->intPageNumber == 1)
		{
			curBtn = m_mapBtnCartTop[i->strCartPosistion];
			if(curBtn == NULL)
				break;

			for(T_mapCallback::iterator j = g_mapCartCallbacks.begin(); j != g_mapCartCallbacks.end();
				j++)
			{
				if(j->first == i->hsyCartsSync)
				{
					g_mapCartCallbacks.erase(j);
					break;
				}
			}


			//set all settings back;
			curBtn->fnPageMoveOn(i->hstCartsStream, i->hsyCartsSync);

			//also reset the callback:
			BASS_ChannelRemoveSync(i->hstCartsStream, i->hsyCartsSync);

			//set the new callback for the button:
			HSYNC callback = BASS_ChannelSetSync(i->hstCartsStream, BASS_SYNC_END, 0, 
				&CCallbackButton::fnEndCallback, 0);

			//add to the callback map:
			g_mapCartCallbacks[callback] = (CCallbackButton*)curBtn;
		}
		else
		{
			//the other buttons arn't on the first page.
			//so we need to put them back into the Navigation stream vector:
			//fist find the nav button that this cart will corrispond to:
			CNavigationButton* navBtn = m_mapBtnNavTop[i->intPageNumber];

			//remove the callback before we change it from the map:
			for(T_mapCallback::iterator j = g_mapCartCallbacks.begin();
				j != g_mapCartCallbacks.end(); j++)
			{
				if(j->first == i->hsyCartsSync)
				{
					g_mapCartCallbacks.erase(j);
					break;
				}
			}

			BASS_ChannelRemoveSync(i->hstCartsStream, i->hsyCartsSync);
			HSYNC synx = BASS_ChannelSetSync(i->hstCartsStream, BASS_SYNC_END,0,
				&CCallbackButton::fnEndCallback, 0);

			SNavigationStreams sNav;
			sNav.intPageNumber = i->intPageNumber;
			sNav.stream = i->hstCartsStream;
			sNav.syncHandle = i->hsyCartsSync;
			sNav.syncHandle = synx;
			//sNav.

			//now the tricky part, we need to create a std::mapCart::iterator for the
			//button that we can store in the struct; the only way I can see of doing this
			//is to iterate over the buttons untill we find one with the appropriate ID:
			for(mapCart::iterator ii = m_mapBtnCartTop.begin(); ii != m_mapBtnCartTop.end();
				ii++)
			{
				if(ii->first == i->strCartPosistion)
				{
					sNav.btnIterator = ii;
					break;
				}
			}

			//reset the callback:
			g_mapCartCallbacks[i->hsyCartsSync] = navBtn;

			//incrase the reference count on the nav button (to start it flashing):
			navBtn->fnIncreasePlayCount();

			//also add to the nav stream map:
			m_vecNavStreamsTop.push_back(sNav);
		}

	}

	//allow the window to be changed.
	AllowSetForegroundWindow(ASFW_ANY);

	//clear out the vector on the login dialog for the next logout population:
	m_pLoginDlg->m_vecCartsList.clear();

	//begin the fader start timer:
	SetTimer(WM_USER + 10, 10, NULL);

	return TRUE;  // return TRUE unless you set the focus to a control
}
Exemple #27
0
int ComspecInit()
{
    TODO("Определить код родительского процесса, и если это FAR - запомнить его (для подключения к пайпу плагина)");
    TODO("Размер получить из GUI, если оно есть, иначе - по умолчанию");
    TODO("GUI может скорректировать размер с учетом полосы прокрутки");
    WARNING("CreateFile(CONOUT$) по идее возвращает текущий ScreenBuffer. Можно его самим возвращать в ComspecDone");

    // Правда нужно проверить, что там происходит с ghConOut.Close(),...
    // Размер должен менять сам GUI, через серверный ConEmuC!
#ifdef SHOW_STARTED_MSGBOX
    MessageBox(GetConEmuHWND(2), L"ConEmuC (comspec mode) is about to START", L"ConEmuC.ComSpec", 0);
#endif
    //int nNewBufferHeight = 0;
    //COORD crNewSize = {0,0};
    //SMALL_RECT rNewWindow = gpSrv->sbi.srWindow;
    BOOL lbSbiRc = FALSE;
    gbRootWasFoundInCon = 2; // не добавлять к "Press Enter to close console" - "or wait"
    gbComspecInitCalled = TRUE; // Нельзя вызывать ComspecDone, если не было вызова ComspecInit
    // в режиме ComSpec - запрещено!
    gbAlwaysConfirmExit = FALSE;
    gbAutoDisableConfirmExit = FALSE;
#ifdef _DEBUG
    xf_validate();
    xf_dump_chk();
#endif
    // Это наверное и не нужно, просто для информации...
    lbSbiRc = GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &gpSrv->sbi);
#ifdef _DEBUG
    DWORD nErrCode = lbSbiRc ? 0 : GetLastError();
    // Процесс запущен с редиректом вывода?
    _ASSERTE(lbSbiRc || (nErrCode == ERROR_INVALID_HANDLE));
#endif

#if 0
    // 111211 - "-new_console" теперь передается в GUI и исполняется в нем
    // Сюда мы попадаем если был ключик -new_console
    // А этом случае нужно завершить ЭТОТ экземпляр и запустить в ConEmu новую вкладку
    if (gpSrv->bNewConsole)
    {
#ifdef _DEBUG
        xf_validate();
        xf_dump_chk();
#endif
        PROCESS_INFORMATION pi;
        memset(&pi, 0, sizeof(pi));
        STARTUPINFOW si;
        memset(&si, 0, sizeof(si));
        si.cb = sizeof(si);
        si.dwFlags = STARTF_USESHOWWINDOW|STARTF_USECOUNTCHARS;
        si.dwXCountChars = gpSrv->sbi.dwSize.X;
        si.dwYCountChars = gpSrv->sbi.dwSize.Y;
        si.wShowWindow = SW_HIDE;
        PRINT_COMSPEC(L"Creating new console for:\n%s\n", gpszRunCmd);
#ifdef _DEBUG
        xf_validate();
        xf_dump_chk();
#endif
        // CREATE_NEW_PROCESS_GROUP - низя, перестает работать Ctrl-C
        // Запускается новый сервер (новая консоль), сюда хуки ставить не надо.
        BOOL lbRc = createProcess(TRUE, NULL, gpszRunCmd, NULL,NULL, TRUE,
                                  NORMAL_PRIORITY_CLASS|CREATE_NEW_CONSOLE,
                                  NULL, NULL, &si, &pi);
        DWORD dwErr = GetLastError();

        if (!lbRc)
        {
            PrintExecuteError(gpszRunCmd, dwErr);
            return CERR_CREATEPROCESS;
        }

#ifdef _DEBUG
        xf_validate();
        xf_dump_chk();
#endif
        //delete psNewCmd; psNewCmd = NULL;
        AllowSetForegroundWindow(pi.dwProcessId);
        PRINT_COMSPEC(L"New console created. PID=%i. Exiting...\n", pi.dwProcessId);
        SafeCloseHandle(pi.hProcess);
        SafeCloseHandle(pi.hThread);
        DisableAutoConfirmExit();
        //gpSrv->nProcessStartTick = GetTickCount() - 2*CHECK_ROOTSTART_TIMEOUT; // менять nProcessStartTick не нужно. проверка только по флажкам
#ifdef _DEBUG
        xf_validate();
        xf_dump_chk();
#endif
        return CERR_RUNNEWCONSOLE;
    }
#endif

    // Если определена ComSpecC - значит ConEmuC переопределил стандартный ComSpec
    // Вернем его
    wchar_t szComSpec[MAX_PATH+1];
    const wchar_t* pszComSpecName;

    //110202 - comspec более не переопределяется
    //if (GetEnvironmentVariable(L"ComSpecC", szComSpec, MAX_PATH) && szComSpec[0] != 0)
    WARNING("TCC/ComSpec");
    if (GetEnvironmentVariable(L"ComSpec", szComSpec, MAX_PATH) && szComSpec[0] != 0)
    {
        //// Только если это (случайно) не conemuc.exe
        //wchar_t* pwszCopy = (wchar_t*)PointToName(szComSpec); //wcsrchr(szComSpec, L'\\');
        ////if (!pwszCopy) pwszCopy = szComSpec;

        //#pragma warning( push )
        //#pragma warning(disable : 6400)
        //if (lstrcmpiW(pwszCopy, L"ConEmuC")==0 || lstrcmpiW(pwszCopy, L"ConEmuC.exe")==0
        //        /*|| lstrcmpiW(pwszCopy, L"ConEmuC64")==0 || lstrcmpiW(pwszCopy, L"ConEmuC64.exe")==0*/)
        //	szComSpec[0] = 0;
        //#pragma warning( pop )

        //if (szComSpec[0])
        //{
        //	SetEnvironmentVariable(L"ComSpec", szComSpec);
        //	SetEnvironmentVariable(L"ComSpecC", NULL);
        //}

        pszComSpecName = (wchar_t*)PointToName(szComSpec);
    }
    else
    {
        WARNING("TCC/ComSpec");
        pszComSpecName = L"cmd.exe";
    }

    lstrcpyn(gpSrv->szComSpecName, pszComSpecName, countof(gpSrv->szComSpecName));

    if (pszComSpecName)
    {
        wchar_t szSelf[MAX_PATH+1];

        if (GetModuleFileName(NULL, szSelf, MAX_PATH))
        {
            lstrcpyn(gpSrv->szSelfName, (wchar_t*)PointToName(szSelf), countof(gpSrv->szSelfName));

            if (!GetAliases(gpSrv->szSelfName, &gpSrv->pszPreAliases, &gpSrv->nPreAliasSize))
            {
                if (gpSrv->pszPreAliases)
                {
                    _wprintf(gpSrv->pszPreAliases);
                    free(gpSrv->pszPreAliases);
                    gpSrv->pszPreAliases = NULL;
                }
            }
        }
    }

    SendStarted();
    //ConOutCloseHandle()
    return 0;
}
Exemple #28
0
int command_start(wchar_t *cmd, COMMAND_HANDLE *commandHandle, LPWSTR* pEnv, DWORD flags)
{
	SECURITY_ATTRIBUTES sa;
	HANDLE hReadOut = INVALID_HANDLE_VALUE, hWriteOut = INVALID_HANDLE_VALUE, hReadIn = INVALID_HANDLE_VALUE, hWriteIn = INVALID_HANDLE_VALUE, hReadError = INVALID_HANDLE_VALUE, hWriteError = INVALID_HANDLE_VALUE;
	STARTUPINFOW si = { 0 };
	PROCESS_INFORMATION pi = { 0 };

	si.cb = sizeof(STARTUPINFOW);

	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = TRUE;
	if (!CreatePipe(&hReadOut, &hWriteOut, &sa, 0)) {
		giterr_set(GITERR_OS, "Could not create pipe");
		return -1;
	}
	if (!CreatePipe(&hReadIn, &hWriteIn, &sa, 0)) {
		giterr_set(GITERR_OS, "Could not create pipe");
		CloseHandle(hReadOut);
		CloseHandle(hWriteOut);
		return -1;
	}
	if (commandHandle->errBuf && !CreatePipe(&hReadError, &hWriteError, &sa, 0)) {
		giterr_set(GITERR_OS, "Could not create pipe");
		CloseHandle(hReadOut);
		CloseHandle(hWriteOut);
		CloseHandle(hReadIn);
		CloseHandle(hWriteIn);
		return -1;
	}

	si.hStdOutput = hWriteOut;
	si.hStdInput = hReadIn;
	si.hStdError = hWriteError;

	// Ensure the read/write handle to the pipe for STDOUT resp. STDIN are not inherited.
	if (!SetHandleInformation(hReadOut, HANDLE_FLAG_INHERIT, 0) || !SetHandleInformation(hWriteIn, HANDLE_FLAG_INHERIT, 0) || (commandHandle->errBuf && !SetHandleInformation(hReadError, HANDLE_FLAG_INHERIT, 0))) {
		giterr_set(GITERR_OS, "SetHandleInformation failed");
		CloseHandle(hReadOut);
		CloseHandle(hWriteOut);
		CloseHandle(hReadIn);
		CloseHandle(hWriteIn);
		safeCloseHandle(&hReadError);
		safeCloseHandle(&hWriteError);
		return -1;
	}

	si.wShowWindow = SW_HIDE;
	si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;

	if (!CreateProcessW(NULL, cmd, NULL, NULL, TRUE, CREATE_UNICODE_ENVIRONMENT | flags, pEnv ? *pEnv : NULL, NULL, &si, &pi)) {
		giterr_set(GITERR_OS, "Could not start external tool");
		CloseHandle(hReadOut);
		CloseHandle(hWriteOut);
		CloseHandle(hReadIn);
		CloseHandle(hWriteIn);
		safeCloseHandle(&hReadError);
		safeCloseHandle(&hWriteError);
		return -1;
	}

	AllowSetForegroundWindow(pi.dwProcessId);
	WaitForInputIdle(pi.hProcess, 10000);

	CloseHandle(hReadIn);
	CloseHandle(hWriteOut);
	if (commandHandle->errBuf) {
		HANDLE asyncReadErrorThread;
		CloseHandle(hWriteError);
		commandHandle->err = hReadError;
		asyncReadErrorThread = commmand_start_reading_thread(&commandHandle->err, commandHandle->errBuf);
		if (!asyncReadErrorThread) {
			CloseHandle(hReadOut);
			CloseHandle(hWriteIn);
			CloseHandle(hReadError);
			return -1;
		}
		commandHandle->asyncReadErrorThread = asyncReadErrorThread;
	}

	commandHandle->pi = pi;
	commandHandle->out = hReadOut;
	commandHandle->in = hWriteIn;
	commandHandle->running = TRUE;
	return 0;
}
Exemple #29
0
Common::Common( int &argc, char **argv, const QString &app, const QString &icon )
	: BaseApplication( argc, argv )
{
	setApplicationName( app );
	setApplicationVersion( QString( "%1.%2.%3.%4" )
		.arg( MAJOR_VER ).arg( MINOR_VER ).arg( RELEASE_VER ).arg( BUILD_VER ) );
	setOrganizationDomain( "ria.ee" );
	setOrganizationName( ORG );
	setWindowIcon( QIcon( icon ) );
	if( QFile::exists( QString("%1/%2.log").arg( QDir::tempPath(), app ) ) )
		qInstallMessageHandler(msgHandler);

#ifdef BREAKPAD
	new QBreakPad(this);
#ifdef TESTING
	if( arguments().contains( "-crash" ) )
	{
		QBreakPad *crash;
		delete crash;
	}
#endif
#endif

	Q_INIT_RESOURCE(common_images);
	Q_INIT_RESOURCE(common_tr);
#if defined(Q_OS_WIN)
	setLibraryPaths( QStringList() << applicationDirPath() );
#elif defined(Q_OS_MAC)
	setLibraryPaths( QStringList() << applicationDirPath() + "/../PlugIns" );
#endif
	setStyleSheet(
		"QDialogButtonBox { dialogbuttonbox-buttons-have-icons: 0; }\n" );
	QPalette p = palette();
	p.setBrush( QPalette::Link, QBrush( "#509B00" ) );
	p.setBrush( QPalette::LinkVisited, QBrush( "#509B00" ) );
	setPalette( p );

	qRegisterMetaType<TokenData>("TokenData");

	QNetworkProxyFactory::setUseSystemConfiguration(true);

#if defined(Q_OS_WIN)
	AllowSetForegroundWindow( ASFW_ANY );
#elif defined(Q_OS_MAC)
#ifdef BREAKPAD
	if(arguments().contains("-crashreport", Qt::CaseInsensitive))
		return;
#endif
	if(!QSettings().value("plugins").isNull())
		return;

	QTimer *timer = new QTimer(this);
	timer->setSingleShot(true);
	connect(timer, &QTimer::timeout, this, [=]{
		timer->deleteLater();
		QMessageBox *b = new QMessageBox(QMessageBox::Information, tr("Browser plugins"),
			tr("If you are using e-services for authentication and signing documents in addition to "
				"Mobile-ID an ID-card or only ID-card, you should install the browser integration packages.<br />"
				"<a href='http://installer.id.ee'>http://installer.id.ee</a>"),
			0, activeWindow());
		QAbstractButton *install = b->addButton(tr("Install"), QMessageBox::AcceptRole);
		b->addButton(tr("Remind later"), QMessageBox::AcceptRole);
		QAbstractButton *ignore = b->addButton(tr("Ignore forever"), QMessageBox::AcceptRole);
		b->exec();
		if(b->clickedButton() == install)
			QDesktopServices::openUrl(QUrl("http://installer.id.ee"));
		else if(b->clickedButton() == ignore)
			QSettings().setValue("plugins", "ignore");
	});
	timer->start(1000);
#endif
}
bool CCommonAppUtils::LaunchApplication(const CString& sCommandLine, UINT idErrMessageFormat, bool bWaitForStartup, CString *cwd, bool uac)
{
	CString theCWD = sOrigCWD;
	if (cwd != NULL)
		theCWD = *cwd;

	if (uac)
	{
		CString file, param;
		SHELLEXECUTEINFO shellinfo;
		memset(&shellinfo, 0, sizeof(shellinfo));
		shellinfo.cbSize = sizeof(shellinfo);
		shellinfo.hwnd = NULL;
		shellinfo.lpVerb = _T("runas");
		shellinfo.nShow = SW_SHOWNORMAL;
		shellinfo.fMask = SEE_MASK_NOCLOSEPROCESS;
		shellinfo.lpDirectory = theCWD;

		int pos = sCommandLine.Find('"');
		if (pos == 0)
		{
			pos = sCommandLine.Find('"', 2);
			if (pos > 1)
			{
				file = sCommandLine.Mid(1, pos - 1);
				param = sCommandLine.Mid(pos + 1);
			}
			else
			{
				if (idErrMessageFormat != 0)
				{
					CString temp;
					temp.Format(idErrMessageFormat, CFormatMessageWrapper());
					MessageBox(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
				}
				return false;
			}
		}
		else
		{
			pos = sCommandLine.Find(' ', 1);
			if (pos > 0)
			{
				file = sCommandLine.Mid(0, pos);
				param = sCommandLine.Mid(pos + 1);
			}
			else
				file = sCommandLine;
		}

		shellinfo.lpFile = file;
		shellinfo.lpParameters = param;

		if (!ShellExecuteEx(&shellinfo))
		{
			if (idErrMessageFormat != 0)
			{
				CString temp;
				temp.Format(idErrMessageFormat, (CString)CFormatMessageWrapper());
				MessageBox(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
			}
			return false;
		}

		if (bWaitForStartup)
		{
			WaitForInputIdle(shellinfo.hProcess, 10000);
		}

		CloseHandle(shellinfo.hProcess);
	}
	else
	{
		STARTUPINFO startup;
		PROCESS_INFORMATION process;
		memset(&startup, 0, sizeof(startup));
		startup.cb = sizeof(startup);
		memset(&process, 0, sizeof(process));

		CString cleanCommandLine(sCommandLine);

		if (CreateProcess(NULL, const_cast<TCHAR*>((LPCTSTR)cleanCommandLine), NULL, NULL, FALSE, 0, 0, theCWD, &startup, &process)==0)
		{
			if(idErrMessageFormat != 0)
			{
				CString temp;
				temp.Format(idErrMessageFormat, (CString)CFormatMessageWrapper());
				MessageBox(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
			}
			return false;
		}

		AllowSetForegroundWindow(process.dwProcessId);

		if (bWaitForStartup)
		{
			WaitForInputIdle(process.hProcess, 10000);
		}

		CloseHandle(process.hThread);
		CloseHandle(process.hProcess);
	}
	return true;
}