Esempio n. 1
0
LRESULT CMainFrame::OnScMaximize(UINT, INT, HWND)
{
    ShowWindow(SW_SHOW);
    BringWindowToTop();
    return 0;
}
Esempio n. 2
0
void TaskManager_OnTabWndSelChange(void)
{
    int    i;
    HMENU  hMenu;
    HMENU  hOptionsMenu;
    HMENU  hViewMenu;
    HMENU  hSubMenu;
    WCHAR  szTemp[256];
    SYSTEM_INFO sysInfo;

    hMenu = GetMenu(hMainWnd);
    hViewMenu = GetSubMenu(hMenu, 2);
    hOptionsMenu = GetSubMenu(hMenu, 1);
    TaskManagerSettings.ActiveTabPage = TabCtrl_GetCurSel(hTabWnd);
    for (i = GetMenuItemCount(hViewMenu) - 1; i > 2; i--) {
        hSubMenu = GetSubMenu(hViewMenu, i);
        if (hSubMenu)
            DestroyMenu(hSubMenu);
        RemoveMenu(hViewMenu, i, MF_BYPOSITION);
    }
    RemoveMenu(hOptionsMenu, 3, MF_BYPOSITION);
    switch (TaskManagerSettings.ActiveTabPage) {
    case 0:
        ShowWindow(hApplicationPage, SW_SHOW);
        ShowWindow(hProcessPage, SW_HIDE);
        ShowWindow(hPerformancePage, SW_HIDE);
        BringWindowToTop(hApplicationPage);

        LoadStringW(hInst, IDS_MENU_LARGEICONS, szTemp, 256);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_LARGE, szTemp);

        LoadStringW(hInst, IDS_MENU_SMALLICONS, szTemp, 256);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_SMALL, szTemp);

        LoadStringW(hInst, IDS_MENU_DETAILS, szTemp, 256);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_DETAILS, szTemp);

        if (GetMenuItemCount(hMenu) <= 4) {
            hSubMenu = LoadMenuW(hInst, MAKEINTRESOURCEW(IDR_WINDOWSMENU));

            LoadStringW(hInst, IDS_MENU_WINDOWS, szTemp, 256);
            InsertMenuW(hMenu, 3, MF_BYPOSITION|MF_POPUP, (UINT_PTR) hSubMenu, szTemp);

            DrawMenuBar(hMainWnd);
        }
        CheckMenuRadioItem(hViewMenu, ID_VIEW_LARGE, ID_VIEW_DETAILS, TaskManagerSettings.ViewMode, MF_BYCOMMAND);

        /*
         * Give the application list control focus
         */
        SetFocus(hApplicationPageListCtrl);
        break;

    case 1:
        ShowWindow(hApplicationPage, SW_HIDE);
        ShowWindow(hProcessPage, SW_SHOW);
        ShowWindow(hPerformancePage, SW_HIDE);
        BringWindowToTop(hProcessPage);

        LoadStringW(hInst, IDS_MENU_SELECTCOLUMNS, szTemp, 256);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_SELECTCOLUMNS, szTemp);

        LoadStringW(hInst, IDS_MENU_16BITTASK, szTemp, 256);
        AppendMenuW(hOptionsMenu, MF_STRING, ID_OPTIONS_SHOW16BITTASKS, szTemp);

        if (TaskManagerSettings.Show16BitTasks)
            CheckMenuItem(hOptionsMenu, ID_OPTIONS_SHOW16BITTASKS, MF_BYCOMMAND|MF_CHECKED);
        if (GetMenuItemCount(hMenu) > 4)
        {
            DeleteMenu(hMenu, 3, MF_BYPOSITION);
            DrawMenuBar(hMainWnd);
        }
        /*
         * Give the process list control focus
         */
        SetFocus(hProcessPageListCtrl);
        break;

    case 2:
        ShowWindow(hApplicationPage, SW_HIDE);
        ShowWindow(hProcessPage, SW_HIDE);
        ShowWindow(hPerformancePage, SW_SHOW);
        BringWindowToTop(hPerformancePage);
        if (GetMenuItemCount(hMenu) > 4) {
            DeleteMenu(hMenu, 3, MF_BYPOSITION);
            DrawMenuBar(hMainWnd);
        }

        GetSystemInfo(&sysInfo);

        /* Hide CPU graph options on single CPU systems */
        if (sysInfo.dwNumberOfProcessors > 1)
        {
            hSubMenu = CreatePopupMenu();

            LoadStringW(hInst, IDS_MENU_ONEGRAPHALLCPUS, szTemp, 256);
            AppendMenuW(hSubMenu, MF_STRING, ID_VIEW_CPUHISTORY_ONEGRAPHALL, szTemp);

            LoadStringW(hInst, IDS_MENU_ONEGRAPHPERCPU, szTemp, 256);
            AppendMenuW(hSubMenu, MF_STRING, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, szTemp);

            LoadStringW(hInst, IDS_MENU_CPUHISTORY, szTemp, 256);
            AppendMenuW(hViewMenu, MF_STRING|MF_POPUP, (UINT_PTR) hSubMenu, szTemp);

            if (TaskManagerSettings.CPUHistory_OneGraphPerCPU)
                CheckMenuRadioItem(hSubMenu, ID_VIEW_CPUHISTORY_ONEGRAPHALL, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, MF_BYCOMMAND);
            else
                CheckMenuRadioItem(hSubMenu, ID_VIEW_CPUHISTORY_ONEGRAPHALL, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, ID_VIEW_CPUHISTORY_ONEGRAPHALL, MF_BYCOMMAND);
        }

        LoadStringW(hInst, IDS_MENU_SHOWKERNELTIMES, szTemp, 256);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_SHOWKERNELTIMES, szTemp);

        if (TaskManagerSettings.ShowKernelTimes)
            CheckMenuItem(hViewMenu, ID_VIEW_SHOWKERNELTIMES, MF_BYCOMMAND|MF_CHECKED);
        else
            CheckMenuItem(hViewMenu, ID_VIEW_SHOWKERNELTIMES, MF_BYCOMMAND|MF_UNCHECKED);

        /*
         * Give the tab control focus
         */
        SetFocus(hTabWnd);
        break;
    }
}
Esempio n. 3
0
Bool
winCreateBoundingWindowFullScreen(ScreenPtr pScreen)
{
    winScreenPriv(pScreen);
    winScreenInfo *pScreenInfo = pScreenPriv->pScreenInfo;
    int iX = pScreenInfo->dwInitialX;
    int iY = pScreenInfo->dwInitialY;
    int iWidth = pScreenInfo->dwWidth;
    int iHeight = pScreenInfo->dwHeight;
    HWND *phwnd = &pScreenPriv->hwndScreen;
    WNDCLASSEX wc;
    char szTitle[256];

#if CYGDEBUG
    winDebug("winCreateBoundingWindowFullScreen\n");
#endif

    /* Setup our window class */
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = winWindowProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = g_hInstance;
    wc.hIcon =
        (HICON) LoadImage(g_hInstance, MAKEINTRESOURCE(IDI_XWIN), IMAGE_ICON,
                          GetSystemMetrics(SM_CXICON),
                          GetSystemMetrics(SM_CYICON), 0);
    wc.hCursor = 0;
    wc.hbrBackground = 0;
    wc.lpszMenuName = NULL;
    wc.lpszClassName = WINDOW_CLASS;
    wc.hIconSm =
        (HICON) LoadImage(g_hInstance, MAKEINTRESOURCE(IDI_XWIN), IMAGE_ICON,
                          GetSystemMetrics(SM_CXSMICON),
                          GetSystemMetrics(SM_CYSMICON), LR_DEFAULTSIZE);
    RegisterClassEx(&wc);

    /* Set display and screen-specific tooltip text */
    if (g_pszQueryHost != NULL)
        snprintf(szTitle,
                 sizeof(szTitle),
                 WINDOW_TITLE_XDMCP,
                 g_pszQueryHost, display, (int) pScreenInfo->dwScreen);
    else
        snprintf(szTitle,
                 sizeof(szTitle),
                 WINDOW_TITLE, display, (int) pScreenInfo->dwScreen);

    /* Create the window */
    *phwnd = CreateWindowExA(0, /* Extended styles */
                             WINDOW_CLASS,      /* Class name */
                             szTitle,   /* Window name */
                             WS_POPUP, iX,      /* Horizontal position */
                             iY,        /* Vertical position */
                             iWidth,    /* Right edge */
                             iHeight,   /* Bottom edge */
                             (HWND) NULL,       /* No parent or owner window */
                             (HMENU) NULL,      /* No menu */
                             GetModuleHandle(NULL),     /* Instance handle */
                             pScreenPriv);      /* ScreenPrivates */

    /* Hide the window */
    ShowWindow(*phwnd, SW_SHOWNORMAL);

    /* Send first paint message */
    UpdateWindow(*phwnd);

    /* Attempt to bring our window to the top of the display */
    BringWindowToTop(*phwnd);

    return TRUE;
}
Esempio n. 4
0
int App::run(void)
{
    const char *QUICK_COCOS2DX_ROOT = getenv("QUICK_COCOS2DX_ROOT");
    SimulatorConfig::sharedDefaults()->setQuickCocos2dxRootPath(QUICK_COCOS2DX_ROOT);

    loadProjectConfig();

    HWND hwndConsole = NULL;
    if (m_project.isShowConsole())
    {
        AllocConsole();
        freopen("CONOUT$", "wt", stdout);
        freopen("CONOUT$", "wt", stderr);

        // disable close console
        hwndConsole = GetConsoleWindow();
        if (hwndConsole != NULL)
        {
            HMENU hMenu = GetSystemMenu(hwndConsole, FALSE);
            if (hMenu != NULL) DeleteMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);

            ShowWindow(hwndConsole, SW_SHOW);
            BringWindowToTop(hwndConsole);
        }
    }

    m_project.dump();

    if (m_project.isWriteDebugLogToFile())
    {
        const string debugLogFilePath = m_project.getDebugLogFilePath();
        m_writeDebugLogFile = fopen(debugLogFilePath.c_str(), "w");
        if (!m_writeDebugLogFile)
        {
            CCLOG("Cannot create debug log file %s", debugLogFilePath.c_str());
        }
    }

    do
    {
        m_exit = TRUE;

        // create the application instance
        m_app = new AppDelegate();
        m_app->setProjectConfig(m_project);

        // set environments
        SetCurrentDirectoryA(m_project.getProjectDir().c_str());
        CCFileUtils::sharedFileUtils()->setSearchRootPath(m_project.getProjectDir().c_str());
        CCFileUtils::sharedFileUtils()->setWritablePath(m_project.getWritableRealPath().c_str());

        // create opengl view
        CCEGLView* eglView = CCEGLView::sharedOpenGLView();
        eglView->setMenuResource(MAKEINTRESOURCE(IDC_LUAHOSTWIN32));
        eglView->setWndProc(WindowProc);
        eglView->setFrameSize(m_project.getFrameSize().width, m_project.getFrameSize().height);
        eglView->setFrameZoomFactor(m_project.getFrameScale());

        // make window actived
        m_hwnd = eglView->getHWnd();
        BringWindowToTop(m_hwnd);
        SetWindowTextA(m_hwnd, "sanguo");

        // restore window position
        const CCPoint windowOffset = m_project.getWindowOffset();
        if (windowOffset.x != 0 || windowOffset.y != 0)
        {
            eglView->moveWindow(windowOffset.x, windowOffset.y);
        }

        // set icon
        HICON icon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_LUAHOSTWIN32));
        SendMessage(m_hwnd, WM_SETICON, ICON_BIG, (LPARAM)icon);

        if (hwndConsole)
        {
            SendMessage(hwndConsole, WM_SETICON, ICON_BIG, (LPARAM)icon);
        }

        // update menu
        createViewMenu();
        updateMenu();

        // run game
        CCLuaStack *stack = CCLuaEngine::defaultEngine()->getLuaStack();
        const vector<string> arr = m_project.getPackagePathArray();
        for (vector<string>::const_iterator it = arr.begin(); it != arr.end(); ++it)
        {
            stack->addSearchPath(it->c_str());
        }

        m_app->run();

        // cleanup
        CCScriptEngineManager::sharedManager()->removeScriptEngine();
        CCScriptEngineManager::purgeSharedManager();
        CocosDenshion::SimpleAudioEngine::end();

        delete m_app;
        m_app = NULL;
    } while (!m_exit);

    FreeConsole();
    if (m_writeDebugLogFile) fclose(m_writeDebugLogFile);
    return 0;
}
Esempio n. 5
0
int WINAPI WinMain(HINSTANCE _hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow)
{
	// Windows Vista and above: alert Windows that PPSSPP is DPI aware,
	// so that we don't flicker in fullscreen on some PCs.
	MakePPSSPPDPIAware();

	// FMA3 support in the 2013 CRT is broken on Vista and Windows 7 RTM (fixed in SP1). Just disable it.
#ifdef _M_X64
	_set_FMA3_enable(0);
#endif

	EnableCrashingOnCrashes();

	wchar_t modulePath[MAX_PATH];
	GetModuleFileName(NULL, modulePath, MAX_PATH);
	for (size_t i = wcslen(modulePath) - 1; i > 0; i--) {
		if (modulePath[i] == '\\') {
			modulePath[i] = 0;
			break;
		}
	}
	SetCurrentDirectory(modulePath);
	// GetCurrentDirectory(MAX_PATH, modulePath);  // for checking in the debugger

#ifndef _DEBUG
	bool showLog = false;
#else
	bool showLog = false;
#endif

	VFSRegister("", new DirectoryAssetReader("assets/"));
	VFSRegister("", new DirectoryAssetReader(""));

	wchar_t lcCountry[256];

	// LOCALE_SNAME is only available in WinVista+
	// Really should find a way to do this in XP too :/
	if (0 != GetLocaleInfo(LOCALE_NAME_USER_DEFAULT, LOCALE_SNAME, lcCountry, 256)) {
		langRegion = ConvertWStringToUTF8(lcCountry);
		for (size_t i = 0; i < langRegion.size(); i++) {
			if (langRegion[i] == '-')
				langRegion[i] = '_';
		}
	} else {
		langRegion = "en_US";
	}

	osName = GetWindowsVersion() + " " + GetWindowsSystemArchitecture();

	const char *configFilename = NULL;
	const char *configOption = "--config=";

	const char *controlsConfigFilename = NULL;
	const char *controlsOption = "--controlconfig=";

	for (int i = 1; i < __argc; ++i)
	{
		if (__argv[i][0] == '\0')
			continue;
		if (__argv[i][0] == '-')
		{
			if (!strncmp(__argv[i], configOption, strlen(configOption)) && strlen(__argv[i]) > strlen(configOption)) {
				configFilename = __argv[i] + strlen(configOption);
			}
			if (!strncmp(__argv[i], controlsOption, strlen(controlsOption)) && strlen(__argv[i]) > strlen(controlsOption)) {
				controlsConfigFilename = __argv[i] + strlen(controlsOption);
			}
		}
	}

	// On Win32 it makes more sense to initialize the system directories here 
	// because the next place it was called was in the EmuThread, and it's too late by then.
	InitSysDirectories();

	// Load config up here, because those changes below would be overwritten
	// if it's not loaded here first.
	g_Config.AddSearchPath("");
	g_Config.AddSearchPath(GetSysDirectory(DIRECTORY_SYSTEM));
	g_Config.SetDefaultPath(GetSysDirectory(DIRECTORY_SYSTEM));
	g_Config.Load(configFilename, controlsConfigFilename);

	bool debugLogLevel = false;

	// The rest is handled in NativeInit().
	for (int i = 1; i < __argc; ++i)
	{
		if (__argv[i][0] == '\0')
			continue;

		if (__argv[i][0] == '-')
		{
			switch (__argv[i][1])
			{
			case 'l':
				showLog = true;
				g_Config.bEnableLogging = true;
				break;
			case 's':
				g_Config.bAutoRun = false;
				g_Config.bSaveSettings = false;
				break;
			case 'd':
				debugLogLevel = true;
				break;
			}

			if (!strncmp(__argv[i], "--fullscreen", strlen("--fullscreen")))
				g_Config.bFullScreen = true;

			if (!strncmp(__argv[i], "--windowed", strlen("--windowed")))
				g_Config.bFullScreen = false;
		}
	}
#ifdef _DEBUG
	g_Config.bEnableLogging = true;
#endif

	LogManager::Init();
	// Consider at least the following cases before changing this code:
	//   - By default in Release, the console should be hidden by default even if logging is enabled.
	//   - By default in Debug, the console should be shown by default.
	//   - The -l switch is expected to show the log console, REGARDLESS of config settings.
	//   - It should be possible to log to a file without showing the console.
	LogManager::GetInstance()->GetConsoleListener()->Init(showLog, 150, 120, "PPSSPP Debug Console");
	
	if (debugLogLevel)
		LogManager::GetInstance()->SetAllLogLevels(LogTypes::LDEBUG);

	//Windows, API init stuff
	INITCOMMONCONTROLSEX comm;
	comm.dwSize = sizeof(comm);
	comm.dwICC = ICC_BAR_CLASSES | ICC_LISTVIEW_CLASSES | ICC_TAB_CLASSES;
	InitCommonControlsEx(&comm);
	timeBeginPeriod(1);
	MainWindow::Init(_hInstance);

	g_hPopupMenus = LoadMenu(_hInstance, (LPCWSTR)IDR_POPUPMENUS);

	MainWindow::Show(_hInstance, iCmdShow);

	HWND hwndMain = MainWindow::GetHWND();
	
	//initialize custom controls
	CtrlDisAsmView::init();
	CtrlMemView::init();
	CtrlRegisterList::init();
	CGEDebugger::Init();

	DialogManager::AddDlg(vfpudlg = new CVFPUDlg(_hInstance, hwndMain, currentDebugMIPS));

	host = new WindowsHost(hwndMain);
	host->SetWindowTitle(0);

	MainWindow::CreateDebugWindows();

	// Emu thread is always running!
	EmuThread_Start();
	InputDevice::BeginPolling();

	HACCEL hAccelTable = LoadAccelerators(_hInstance, (LPCTSTR)IDR_ACCELS);
	HACCEL hDebugAccelTable = LoadAccelerators(_hInstance, (LPCTSTR)IDR_DEBUGACCELS);

	//so.. we're at the message pump of the GUI thread
	for (MSG msg; GetMessage(&msg, NULL, 0, 0); )	// for no quit
	{
		if (msg.message == WM_KEYDOWN)
		{
			//hack to enable/disable menu command accelerate keys
			MainWindow::UpdateCommands();

			//hack to make it possible to get to main window from floating windows with Esc
			if (msg.hwnd != hwndMain && msg.wParam == VK_ESCAPE)
				BringWindowToTop(hwndMain);
		}

		//Translate accelerators and dialog messages...
		HWND wnd;
		HACCEL accel;
		switch (g_activeWindow)
		{
		case WINDOW_MAINWINDOW:
			wnd = hwndMain;
			accel = hAccelTable;
			break;
		case WINDOW_CPUDEBUGGER:
			wnd = disasmWindow[0] ? disasmWindow[0]->GetDlgHandle() : 0;
			accel = hDebugAccelTable;
			break;
		case WINDOW_GEDEBUGGER:
		default:
			wnd = 0;
			accel = 0;
			break;
		}

		if (!TranslateAccelerator(wnd, accel, &msg))
		{
			if (!DialogManager::IsDialogMessage(&msg))
			{
				//and finally translate and dispatch
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}
	}

	VFSShutdown();

	InputDevice::StopPolling();
	EmuThread_Stop();

	MainWindow::DestroyDebugWindows();
	DialogManager::DestroyAll();
	timeEndPeriod(1);
	delete host;
	g_Config.Save();
	LogManager::Shutdown();
	return 0;
}
Esempio n. 6
0
/* PauseBox */
int WDPROC
PauseBox(LPPW lppw)
{
    MSG msg;
    HDC hdc;
    int width, height;
    TEXTMETRIC tm;
    RECT rect;
    char *current_pause_title = lppw->Title;
    static char TITLE_PAUSE_MOUSE[] = "waiting for mouse click";

    if (paused_for_mouse)
        current_pause_title = TITLE_PAUSE_MOUSE;

    if (!lppw->hPrevInstance)
        CreatePauseClass(lppw);
    GetWindowRect(GetDesktopWindow(), &rect);
    if ( (lppw->Origin.x == CW_USEDEFAULT) || (lppw->Origin.x == 0) )
        lppw->Origin.x = (rect.right + rect.left) / 2;
    if ( (lppw->Origin.y == CW_USEDEFAULT) || (lppw->Origin.y == 0) )
        lppw->Origin.y = (rect.bottom + rect.top) / 2;

    hdc = GetDC(NULL);
    SelectObject(hdc, GetStockObject(SYSTEM_FONT));
    GetTextMetrics(hdc, &tm);
    width  = max(24, 4 + strlen(lppw->Message)) * tm.tmAveCharWidth;
    width = min(width, rect.right-rect.left);
    height = 28 * (tm.tmHeight + tm.tmExternalLeading) / 4;
    ReleaseDC(NULL,hdc);

    lppw->hWndPause = CreateWindowEx(
                          WS_EX_DLGMODALFRAME | WS_EX_APPWINDOW,
                          szPauseClass, current_pause_title,
                          /* HBB 981202: WS_POPUPWINDOW would have WS_SYSMENU in it, but we don't
                           * want, nor need, a System menu in our Pause windows. */
                          WS_POPUP | WS_BORDER | WS_CAPTION,
                          lppw->Origin.x - width/2, lppw->Origin.y - height/2,
                          width, height,
                          lppw->hWndParent, NULL, lppw->hInstance, lppw);

    /* Don't show the pause "OK CANCEL" dialog for "pause mouse ..." -- well, show
       it only for "pause -1".
       Note: maybe to show in the window titlebar or somewhere else a message like
       graphwin.Title = "gnuplot pausing (waiting for mouse click)";
    */
    if (!paused_for_mouse) {
        ShowWindow(lppw->hWndPause, SW_SHOWNORMAL);
        BringWindowToTop(lppw->hWndPause);
        UpdateWindow(lppw->hWndPause);
    }

    lppw->bPause = TRUE;
    lppw->bPauseCancel = IDCANCEL;

    while (lppw->bPause) {
        /* HBB 20021211: Nigel Nunn found a better way to avoid
         * 100% CPU load --> use it */
        if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
            /* wait until window closed */
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        } else
            WaitMessage();
    }

    DestroyWindow(lppw->hWndPause);

    return lppw->bPauseCancel;
}
Esempio n. 7
0
LRESULT CALLBACK BrowseProc(HWND hwnd, UINT iMessage, WPARAM
    wParam, LPARAM lParam)
{
    static HFONT font;
    LV_ITEM item;
    POINT pt;
    LV_COLUMN lvC;
    RECT r;
    int i;
    LPNMHDR nmh;
    static LVITEM pressed;
    switch (iMessage)
    {
        case WM_USER+1:
        {
            DWINFO info;
            char *q;
            memset(&info,0, sizeof(info));
            strcpy(info.dwName, browselist[pressed.lParam]->file);
            q = strrchr(info.dwName, '\\');
            if (q)
                strcpy(info.dwTitle, q + 1);
            else
                strcpy(info.dwTitle, info.dwName);
            info.dwLineNo = TagNewLine(browselist[pressed.lParam]->file, browselist[pressed.lParam]->line);
            info.logMRU = FALSE;
            info.newFile = FALSE;
            CreateDrawWindow(&info, TRUE);
            break;
        }
        case WM_CTLCOLORSTATIC:
        {
            return (LRESULT)(HBRUSH)(COLOR_INACTIVECAPTION + 1);
        }
        case WM_CTLCOLORBTN:
        {
            return (LRESULT)GetStockObject(NULL_BRUSH);
        }

        case WM_NOTIFY:
            nmh = (LPNMHDR)lParam;
            if (nmh->code == NM_SETFOCUS)
            {
                PostMessage(hwndFrame, WM_REDRAWTOOLBAR, 0, 0);
                SendMessage(GetParent(hwnd), WM_ACTIVATEME, 0, 0);
            }
            else if (nmh->code == LVN_GETDISPINFO)
            {
                LV_DISPINFO *p = (LV_DISPINFO *)lParam;
                char name[512] = "", *q;
                switch (p->item.iSubItem)
                {
                    case 1: /* id*/
                        sprintf(name,"%d", p->item.lParam +1);
                        break;
                    case 2: /*name*/
                        strcpy(name, browselist[p->item.lParam]->name);
                        break;
                    case 3: /* browse */
                        sprintf(name, "%d", browselist[p->item.lParam]->line);
                        break;
                    case 4: /*file*/
                        q = strrchr(browselist[p->item.lParam]->file, '\\');
                        if (!q)
                            q = browselist[p->item.lParam]->file;
                        else
                            q++;
                        strcpy(name, q);
                        break;
                }
                if (name[0])
                {
                    p->item.mask |= LVIF_TEXT | LVIF_DI_SETITEM;
                    p->item.mask &= ~LVIF_STATE;
                    p->item.pszText = name;
                }
            }
            else if (((LPNMHDR)lParam)->code == NM_DBLCLK)
            {
                LVHITTESTINFO hittest;
                GetCursorPos(&hittest.pt);
                ScreenToClient(hwndLV, &hittest.pt);
                if (ListView_SubItemHitTest(hwndLV, &hittest) >= 0)
                {
                    LVITEM lvitem;
                    lvitem.iItem = hittest.iItem;
                    lvitem.iSubItem = 0;
                    lvitem.mask = LVIF_PARAM;
                    ListView_GetItem(hwndLV, &lvitem);
                    memcpy(&pressed, &lvitem, sizeof(pressed));
                    SendMessage(hwnd, WM_USER + 1, 0, 0);
                }
            }
            else if (nmh->code == LVN_KEYDOWN)
            {
                switch (((LPNMLVKEYDOWN)lParam)->wVKey)
                {
                    case 'C':
                        if (GetKeyState(VK_CONTROL) &0x80000000)
                        {
                            CopyText(hwnd);
                        }
                        break;
                    case VK_UP:
                        if (curSel > 0)
                            SendMessage(hwnd, WM_USER, curSel-1, 0);
                        break;
                    case VK_DOWN:
                        if (curSel < ListView_GetItemCount(hwndLV) - 1)
                            SendMessage(hwnd, WM_USER, curSel + 1, 0);
                        break;
                }
            }
            break;
        case WM_COMMAND:
            switch(wParam)
            {
                case IDC_RETURN:
                    GetWindowText(hwndEdit, brsName, sizeof(brsName));
                    SendMessage(hwndCombo, WM_SAVEHISTORY, 0, 0);
                    CreateUsageList();
                    return 0;
                case IDC_ESCAPE:
                    SendMessage(hwndEdit, WM_SETTEXT, 0, (LPARAM)brsName);
                    return 0;
                default:
                    if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == 300)
                    {
                        displayFull = !displayFull;
                        PostMessage(hwnd, WM_USER, 0, 0);
                    }
                    if (HIWORD(wParam) == CBN_SELENDOK && LOWORD(wParam) == 500)
                    {
                        PostMessage(hwnd, WM_COMMAND, IDC_RETURN, 0);
                    }
                    break;
            }
            break;
            
        case WM_USER:
        {
            int k = 0;
            char buf[40];
            sprintf(buf, "%d Usages", browsecount);
            SetWindowText(hwndButton, buf);
            
            ListView_DeleteAllItems(hwndLV);
            memset(&item, 0, sizeof(item));
            for (i=0; i < browsecount; i++)
            {
                if (displayFull || browselist[i]->definition || browselist[i]->declaration)
                {
                    item.iItem = k++;
                    item.iSubItem = 0;
                    item.mask = LVIF_IMAGE | LVIF_PARAM;
                    item.lParam = i;
                    item.iImage = browselist[i]->definition ? 0 : browselist[i]->declaration ? 1 : 2;
                    ListView_InsertItem(hwndLV, &item);
                }            
            }
        }
            break;
        case WM_DRAWITEM:
        {
            LPDRAWITEMSTRUCT pDis = (LPDRAWITEMSTRUCT)lParam;
            HDC memdc;
            char staticText[256];
            BOOL state = !! displayFull;
            int len = SendMessage(pDis->hwndItem, WM_GETTEXT, 
                sizeof(staticText), (LPARAM)staticText);
            SIZE sz;
            RECT r;
            POINT textpos, iconpos;
            GetClientRect(pDis->hwndItem, &r);
            GetTextExtentPoint32(pDis->hDC, staticText, len, &sz);
            SetBkMode(pDis->hDC, TRANSPARENT);   
            iconpos.x = 4;
            iconpos.y = (r.bottom - r.top - 16)/2;
            textpos.x = r.right - 4 - sz.cx;
            textpos.y = (r.bottom - r.top - sz.cy)/2;
            DrawFrameControl(pDis->hDC, &pDis->rcItem, DFC_BUTTON, DFCS_BUTTONPUSH | (state ? DFCS_PUSHED : 0));
            TextOut(pDis->hDC, pDis->rcItem.left+ textpos.x, pDis->rcItem.top+textpos.y, staticText, len);
            memdc = CreateCompatibleDC(pDis->hDC);
            SelectObject(memdc, buttonbmp);
            TransparentBlt(pDis->hDC, pDis->rcItem.left+ iconpos.x, pDis->rcItem.top+iconpos.y, 16, 16, memdc, 0, 0, 16, 16, 0xc0c0c0);
            DeleteDC(memdc);
        }
        return 0;
        case WM_CREATE:
            hwndBrowse = hwnd;
            GetClientRect(hwnd, &r);
            hwndBackground = CreateWindow("static", "", WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS,
                                                0,0, r.right - r.bottom, BUTTONHEIGHT + 4, hwnd, 0, hInstance, 0);
            hwndButton = CreateWindow("button", "0 Usages",  WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
                                         2,2,BUTTONWIDTH,BUTTONHEIGHT, hwnd, (HMENU)300, hInstance, 0);
            ApplyDialogFont(hwndButton);
            hwndCombo = CreateWindow("COMBOBOX", "", WS_CHILD + WS_CLIPSIBLINGS +
                WS_BORDER + WS_VISIBLE + CBS_DROPDOWN + CBS_AUTOHSCROLL, 
                                BUTTONWIDTH + 10, 4, 200, 100, hwnd, (HMENU)500, hInstance, 0);
            ApplyDialogFont(hwndCombo);
            SubClassHistoryCombo(hwndCombo);
            SendMessage(hwndCombo, WM_SETHISTORY, 0, (LPARAM)varinfohist);
            pt.x = pt.y = 5;
            hwndEdit = ChildWindowFromPoint(hwndCombo, pt);
            oldproc = (WNDPROC)SetWindowLong(hwndEdit, GWL_WNDPROC, (int)EditHook);
            BringWindowToTop(hwndButton);
            BringWindowToTop(hwndCombo);
            font = CreateFontIndirect(&systemDialogFont);
            SendMessage(hwndErrButton, WM_SETFONT, (WPARAM)font, 0);
            SendMessage(hwndWarnButton, WM_SETFONT, (WPARAM)font, 0);
            hwndLV = CreateWindowEx(0, WC_LISTVIEW, "", 
                           LVS_REPORT | LVS_SINGLESEL | WS_CHILD | WS_VISIBLE | WS_BORDER,
                           0,BUTTONHEIGHT + 4,r.right-r.left, r.bottom - r.top-BUTTONHEIGHT-4, hwnd, 0, hInstance, 0);
            ListView_SetExtendedListViewStyle(hwndLV, LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVS_EX_DOUBLEBUFFER);
            ApplyDialogFont(hwndLV);
            GetWindowRect(hwndLV, &r);
            lvC.mask = LVCF_WIDTH;
            lvC.cx = 50;
            lvC.iSubItem = 0;
            ListView_InsertColumn(hwndLV, 0, &lvC);
            lvC.mask = LVCF_WIDTH | LVCF_SUBITEM | LVCF_TEXT;
            lvC.cx = 50;            lvC.iSubItem = 1;
            lvC.pszText = "Id";
            ListView_InsertColumn(hwndLV, 1, &lvC);
            lvC.mask = LVCF_WIDTH | LVCF_SUBITEM | LVCF_TEXT;
            lvC.cx = 250;
            lvC.iSubItem = 2;
            lvC.pszText = "Name";
            ListView_InsertColumn(hwndLV, 2, &lvC);
            lvC.mask = LVCF_WIDTH | LVCF_SUBITEM | LVCF_TEXT;
            lvC.cx = 50;
            lvC.iSubItem = 3;
            lvC.pszText = "Line";
            ListView_InsertColumn(hwndLV, 3, &lvC);
            lvC.mask = LVCF_WIDTH | LVCF_SUBITEM | LVCF_TEXT;
            lvC.cx = r.right - r.left - 375;
            lvC.iSubItem = 4;
            lvC.pszText = "File";
            ListView_InsertColumn(hwndLV, 4, &lvC);
            ListView_SetImageList(hwndLV, tagImageList, LVSIL_SMALL);
            break;
        case WM_RESETHISTORY:
            SendMessage(hwndCombo, WM_SETHISTORY, 0, (LPARAM)varinfohist);
            break;
        case WM_SIZE:
            r.left = r.top = 0;
            r.right = LOWORD(lParam);
            r.bottom = HIWORD(lParam);
            MoveWindow(hwndLV, r.left, r.top+BUTTONHEIGHT + 4, r.right - r.left,
                r.bottom - r.top-BUTTONHEIGHT - 4, 1);
            MoveWindow(hwndBackground, r.left, r.top, r.right - r.left, BUTTONHEIGHT + 4, 1);
            lvC.mask = LVCF_WIDTH;
            lvC.cx = r.right - r.left - 375;
            ListView_SetColumn(hwndLV, 4, &lvC);
            break;
        case WM_DESTROY:
            hwndBrowse = 0;
            break;
        case WM_SETFOCUS:
            break;
        case WM_KILLFOCUS:
            break;
    }
    return DefWindowProc(hwnd, iMessage, wParam, lParam);
}
Esempio n. 8
0
INT_PTR CALLBACK MainWndProc(
    __in HWND hwndDlg,
    __in UINT uMsg,
    __in WPARAM wParam,
    __in LPARAM lParam
    )
{
    switch (uMsg)
    {
    case WM_INITDIALOG:
        {
            // Add the Graphics card name to the Window Title.
            //PPH_STRING gpuname = GetDriverName();
            //PPH_STRING title = PhFormatString(L"Graphics Information (%s)", gpuname->Buffer);

            //SetWindowText(hwndDlg, title->Buffer);  

            //PhDereferenceObject(gpuname);
            //PhDereferenceObject(title);

            // We have already set the group boxes to have WS_EX_TRANSPARENT to fix
            // the drawing issue that arises when using WS_CLIPCHILDREN. However
            // in removing the flicker from the graphs the group boxes will now flicker.
            // It's a good tradeoff since no one stares at the group boxes.
            PhSetWindowStyle(hwndDlg, WS_CLIPCHILDREN, WS_CLIPCHILDREN);
         
            PhCenterWindow(hwndDlg, PhMainWndHandle);
            
            PhInitializeLayoutManager(&WindowLayoutManager, hwndDlg);
  
            PhAddLayoutItem(&WindowLayoutManager, GetDlgItem(hwndDlg, IDC_ALWAYSONTOP), NULL, PH_ANCHOR_RIGHT | PH_ANCHOR_BOTTOM);
            PhAddLayoutItem(&WindowLayoutManager, GetDlgItem(hwndDlg, IDOK), NULL, PH_ANCHOR_RIGHT | PH_ANCHOR_BOTTOM);

            PhLoadWindowPlacementFromSetting(SETTING_NAME_GFX_WINDOW_POSITION, SETTING_NAME_GFX_WINDOW_SIZE, hwndDlg);

            PhInitializeGraphState(&GpuGraphState);
            PhInitializeGraphState(&CoreGraphState);
            PhInitializeGraphState(&MemGraphState);

            // TEMP
            if (GpuHistory.Count == 0)
            {
                PhInitializeCircularBuffer_FLOAT(&GpuHistory, PhGetIntegerSetting(L"SampleCount"));
                PhInitializeCircularBuffer_FLOAT(&CoreHistory, PhGetIntegerSetting(L"SampleCount"));
                PhInitializeCircularBuffer_ULONG(&MemHistory, PhGetIntegerSetting(L"SampleCount"));
            }

            GpuGraphHandle = CreateWindow(
                PH_GRAPH_CLASSNAME,
                NULL,
                WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE,
                0,
                0,
                3,
                3,
                hwndDlg,
                (HMENU)110,
                PluginInstance->DllBase,
                NULL
                );
            Graph_SetTooltip(GpuGraphHandle, TRUE);
            BringWindowToTop(GpuGraphHandle);
     
            CoreGraphHandle = CreateWindow(
                PH_GRAPH_CLASSNAME,
                NULL,
                WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE,
                0,
                0,
                3,
                3,
                hwndDlg,
                (HMENU)111,
                PluginInstance->DllBase,
                NULL
                );
            Graph_SetTooltip(CoreGraphHandle, TRUE);
            BringWindowToTop(CoreGraphHandle);

            MemGraphHandle = CreateWindow(
                PH_GRAPH_CLASSNAME,
                NULL,
                WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE,
                0,
                0,
                3,
                3,
                hwndDlg,
                (HMENU)109,
                PluginInstance->DllBase,
                NULL
                );
            Graph_SetTooltip(MemGraphHandle, TRUE);
            BringWindowToTop(MemGraphHandle);
      
            PhRegisterCallback(
				PhGetGeneralCallback(GeneralCallbackProcessesUpdated),
				GfxUpdateHandler,
				NULL,
				&ProcessesUpdatedRegistration
				);
        }
        break;
    case WM_DESTROY:
        {     
            // Unregister our callbacks.
            PhUnregisterCallback(&PhProcessesUpdatedEvent, &ProcessesUpdatedRegistration);

            // Save our settings.
            PhSetIntegerSetting(SETTING_NAME_GFX_ALWAYS_ON_TOP, AlwaysOnTop);
            PhSaveWindowPlacementToSetting(SETTING_NAME_GFX_WINDOW_POSITION, SETTING_NAME_GFX_WINDOW_SIZE, hwndDlg);

            // Reset our Window Management.
            PhDeleteLayoutManager(&WindowLayoutManager);

            // TEMP commented out.
            // Clear our buffers.
            //PhDeleteCircularBuffer_FLOAT(&GpuHistory);
            //PhDeleteCircularBuffer_ULONG(&MemHistory);

            // Clear our state.
            PhDeleteGraphState(&GpuGraphState);
            PhDeleteGraphState(&MemGraphState);

            // Quit.
            PostQuitMessage(0);
        }
        break;
    case WM_NOTIFY:
        {
            LPNMHDR header = (LPNMHDR)lParam;

            switch (header->code)
            {
            case GCN_GETDRAWINFO:
                {
                    PPH_GRAPH_GETDRAWINFO getDrawInfo = (PPH_GRAPH_GETDRAWINFO)header;
                    PPH_GRAPH_DRAW_INFO drawInfo = getDrawInfo->DrawInfo;

                    if (header->hwndFrom == GpuGraphHandle)
                    {
                        if (PhGetIntegerSetting(L"GraphShowText"))
                        {
                            HDC hdc;

                            PhSwapReference2(
                                &GpuGraphState.TooltipText,
                                PhFormatString(
                                L"%.0f%%",
                                CurrentGpuUsage * 100
                                ));

                            hdc = Graph_GetBufferedContext(GpuGraphHandle);
                            SelectObject(hdc, PhApplicationFont);
                            PhSetGraphText(hdc, drawInfo, &GpuGraphState.TooltipText->sr,
                                &NormalGraphTextMargin, &NormalGraphTextPadding, PH_ALIGN_TOP | PH_ALIGN_LEFT);
                        }
                        else
                        {
                            drawInfo->Text.Buffer = NULL;
                        }

                        drawInfo->Flags = PH_GRAPH_USE_GRID;
                        drawInfo->LineColor1 = PhGetIntegerSetting(L"ColorCpuKernel");
                        //drawInfo->LineColor2 = PhGetIntegerSetting(L"ColorCpuUser");
                        drawInfo->LineBackColor1 = PhHalveColorBrightness(drawInfo->LineColor1);
                        //drawInfo->LineBackColor2 = PhHalveColorBrightness(drawInfo->LineColor2);

                        PhGraphStateGetDrawInfo(
                            &GpuGraphState,
                            getDrawInfo,
                            GpuHistory.Count
                            );

                        if (!GpuGraphState.Valid)
                        {
                            PhCopyCircularBuffer_FLOAT(
                                &GpuHistory, 
                                getDrawInfo->DrawInfo->LineData1, 
                                getDrawInfo->DrawInfo->LineDataCount
                                );

                            GpuGraphState.Valid = TRUE;
                        }
                    }
                    else if (header->hwndFrom == MemGraphHandle)
                    {
                        if (PhGetIntegerSetting(L"GraphShowText"))
                        {
                            HDC hdc;

                            PhSwapReference2(&MemGraphState.TooltipText,
                                PhFormatString(
                                L"%s / %s (%.2f%%)",
                                PhaFormatSize(UInt32x32To64(CurrentMemUsage, 1024), -1)->Buffer,
                                PhaFormatSize(UInt32x32To64(MaxMemUsage, 1024), -1)->Buffer,
                                (FLOAT)CurrentMemUsage / MaxMemUsage * 100
                                ));

                            hdc = Graph_GetBufferedContext(MemGraphHandle);
                            SelectObject(hdc, PhApplicationFont);
                            PhSetGraphText(
                                hdc, 
                                drawInfo, 
                                &MemGraphState.TooltipText->sr,  
                                &NormalGraphTextMargin, 
                                &NormalGraphTextPadding, 
                                PH_ALIGN_TOP | PH_ALIGN_LEFT
                                );
                        }
                        else
                        {
                            drawInfo->Text.Buffer = NULL;
                        }

                        drawInfo->Flags = PH_GRAPH_USE_GRID;
                        drawInfo->LineColor1 = PhGetIntegerSetting(L"ColorCpuKernel");
                        //drawInfo->LineColor2 = PhGetIntegerSetting(L"ColorCpuUser");
                        drawInfo->LineBackColor1 = PhHalveColorBrightness(drawInfo->LineColor1);
                        //drawInfo->LineBackColor2 = PhHalveColorBrightness(drawInfo->LineColor2);

                        PhGraphStateGetDrawInfo(
                            &MemGraphState,
                            getDrawInfo,
                            MemHistory.Count
                            );

                        if (!MemGraphState.Valid)
                        {
                            ULONG i = 0;

                            for (i = 0; i < drawInfo->LineDataCount; i++)
                            {
                                MemGraphState.Data1[i] =
                                    (FLOAT)PhGetItemCircularBuffer_ULONG(&MemHistory, i);
                            }

                            // Scale the data.
                            PhxfDivideSingle2U(
                                MemGraphState.Data1,
                                (FLOAT)MaxMemUsage,
                                drawInfo->LineDataCount
                                );

                            MemGraphState.Valid = TRUE;
                        }
                    }
                    else if (header->hwndFrom == CoreGraphHandle)
                    {
                        if (PhGetIntegerSetting(L"GraphShowText"))
                        {
                            HDC hdc;

                            PhSwapReference2(
                                &CoreGraphState.TooltipText,
                                PhFormatString(
                                L"%.0f%%",
                                CurrentCoreUsage * 100
                                ));

                            hdc = Graph_GetBufferedContext(CoreGraphHandle);
                            SelectObject(hdc, PhApplicationFont);
                            PhSetGraphText(hdc, drawInfo, &CoreGraphState.TooltipText->sr,
                                &NormalGraphTextMargin, &NormalGraphTextPadding, PH_ALIGN_TOP | PH_ALIGN_LEFT);
                        }
                        else
                        {
                            drawInfo->Text.Buffer = NULL;
                        }

                        drawInfo->Flags = PH_GRAPH_USE_GRID;
                        drawInfo->LineColor1 = PhGetIntegerSetting(L"ColorCpuKernel");
                        //drawInfo->LineColor2 = PhGetIntegerSetting(L"ColorCpuUser");
                        drawInfo->LineBackColor1 = PhHalveColorBrightness(drawInfo->LineColor1);
                        //drawInfo->LineBackColor2 = PhHalveColorBrightness(drawInfo->LineColor2);

                        PhGraphStateGetDrawInfo(
                            &CoreGraphState,
                            getDrawInfo,
                            CoreHistory.Count
                            );

                        if (!CoreGraphState.Valid)
                        {
                            PhCopyCircularBuffer_FLOAT(
                                &CoreHistory, 
                                getDrawInfo->DrawInfo->LineData1, 
                                getDrawInfo->DrawInfo->LineDataCount
                                );

                            CoreGraphState.Valid = TRUE;
                        }
                    }
                }
                break;
            case GCN_GETTOOLTIPTEXT:
                {
                    PPH_GRAPH_GETTOOLTIPTEXT getTooltipText = (PPH_GRAPH_GETTOOLTIPTEXT)lParam;

                    if (getTooltipText->Index < getTooltipText->TotalCount)
                    {
                        if (header->hwndFrom == GpuGraphHandle)
                        {
                            if (GpuGraphState.TooltipIndex != getTooltipText->Index)
                            {
                                FLOAT usage;

                                usage = PhGetItemCircularBuffer_FLOAT(&GpuHistory, getTooltipText->Index);

                                PhSwapReference2(&GpuGraphState.TooltipText, PhFormatString(
                                    L"%.0f%%",
                                    usage * 100
                                    ));
                            }

                            getTooltipText->Text = GpuGraphState.TooltipText->sr;
                        }
                        else if (header->hwndFrom == MemGraphHandle)
                        {
                            if (MemGraphState.TooltipIndex != getTooltipText->Index)
                            {
                                ULONG usage;

                                usage = PhGetItemCircularBuffer_ULONG(&MemHistory, getTooltipText->Index);

                                PhSwapReference2(&MemGraphState.TooltipText,
                                    PhFormatString(
                                    L"%s / %s (%.2f%%)",
                                    PhaFormatSize(UInt32x32To64(usage, 1024), -1)->Buffer,
                                    PhaFormatSize(UInt32x32To64(MaxMemUsage, 1024), -1)->Buffer,
                                    (FLOAT)usage / MaxMemUsage * 100
                                    ));
                            }

                            getTooltipText->Text = MemGraphState.TooltipText->sr;
                        }
                        else if (header->hwndFrom == CoreGraphHandle)
                        {
                            if (CoreGraphState.TooltipIndex != getTooltipText->Index)
                            {
                                FLOAT usage;

                                usage = PhGetItemCircularBuffer_FLOAT(&CoreHistory, getTooltipText->Index);

                                PhSwapReference2(&CoreGraphState.TooltipText, 
                                    PhFormatString(
                                    L"%.0f%%",
                                    usage * 100
                                    ));
                            }

                            getTooltipText->Text = CoreGraphState.TooltipText->sr;
                        }
                    }
                }
                break;
            case GCN_MOUSEEVENT:
                {
                    PPH_GRAPH_MOUSEEVENT mouseEvent = (PPH_GRAPH_MOUSEEVENT)lParam;

                    if (mouseEvent->Message == WM_LBUTTONDBLCLK)
                    {
                        if (header->hwndFrom == GpuGraphHandle)
                        {
                            PhShowInformation(hwndDlg, L"Double clicked!");
                        }
                    }
                }
                break;
            }
        }
        break;
    case WM_SHOWWINDOW:
        {
            RECT margin;

            GfxPanelWindowHandle = CreateDialog(
                PluginInstance->DllBase,
                MAKEINTRESOURCE(IDD_SYSGFX_PANEL),
                hwndDlg,
                MainPanelDlgProc
                );

            SetWindowPos(
                GfxPanelWindowHandle, 
                NULL, 
                10, 0, 0, 0,
                SWP_NOACTIVATE | SWP_NOREDRAW | SWP_NOSIZE | SWP_NOZORDER
                );

            ShowWindow(GfxPanelWindowHandle, SW_SHOW);

            AlwaysOnTop = (BOOLEAN)PhGetIntegerSetting(SETTING_NAME_GFX_ALWAYS_ON_TOP);
            Button_SetCheck(GetDlgItem(hwndDlg, IDC_ALWAYSONTOP), AlwaysOnTop ? BST_CHECKED : BST_UNCHECKED);
            GfxSetAlwaysOnTop();

            margin.left = 0;
            margin.top = 0;
            margin.right = 0;
            margin.bottom = 25;
            MapDialogRect(hwndDlg, &margin);

            PhAddLayoutItemEx(
                &WindowLayoutManager, 
                GfxPanelWindowHandle, 
                NULL, 
                PH_ANCHOR_BOTTOM | PH_ANCHOR_LEFT, 
                margin
                );

            SendMessage(hwndDlg, WM_SIZE, 0, 0);
            SendMessage(hwndDlg, WM_GFX_UPDATE, 0, 0);
        }
        break;
    case WM_SIZE:
        {                      
            HDWP deferHandle;
            HWND cpuGroupBox = GetDlgItem(hwndDlg, IDC_GROUPCONTROLLER);
            HWND diskGroupBox = GetDlgItem(hwndDlg, IDC_GROUPGPU);
            HWND networkGroupBox = GetDlgItem(hwndDlg, IDC_GROUPMEM);
            RECT clientRect;
            RECT panelRect;
            RECT margin = { 13, 13, 13, 13 };
            RECT innerMargin = { 10, 20, 10, 10 };
            LONG between = 3;
            LONG width;
            LONG height;

            PhLayoutManagerLayout(&WindowLayoutManager);

            GpuGraphState.Valid = FALSE;
            MemGraphState.Valid = FALSE;

            GetClientRect(hwndDlg, &clientRect);
            // Limit the rectangle bottom to the top of the panel.
            GetWindowRect(GfxPanelWindowHandle, &panelRect);
            MapWindowPoints(NULL, hwndDlg, (POINT *)&panelRect, 2);
            clientRect.bottom = panelRect.top;

            width = clientRect.right - margin.left - margin.right;
            height = (clientRect.bottom - margin.top - margin.bottom - between * 2) / 3;

            deferHandle = BeginDeferWindowPos(6);

            deferHandle = DeferWindowPos(deferHandle, diskGroupBox, NULL, margin.left, margin.top,  width, height, SWP_NOACTIVATE | SWP_NOZORDER);
            deferHandle = DeferWindowPos(
                deferHandle,
                GpuGraphHandle,
                NULL,
                margin.left + innerMargin.left,
                margin.top + innerMargin.top,
                width - innerMargin.left - innerMargin.right,
                height - innerMargin.top - innerMargin.bottom,
                SWP_NOACTIVATE | SWP_NOZORDER
                );

            deferHandle = DeferWindowPos(deferHandle, networkGroupBox, NULL, margin.left, margin.top + height + between, width, height, SWP_NOACTIVATE | SWP_NOZORDER);
            deferHandle = DeferWindowPos(
                deferHandle,
                MemGraphHandle,
                NULL,
                margin.left + innerMargin.left,
                margin.top + height + between + innerMargin.top,
                width - innerMargin.left - innerMargin.right,
                height - innerMargin.top - innerMargin.bottom,
                SWP_NOACTIVATE | SWP_NOZORDER
                );

            deferHandle = DeferWindowPos(deferHandle, cpuGroupBox, NULL, margin.left, margin.top + (height + between) * 2, width, height, SWP_NOACTIVATE | SWP_NOZORDER);
            deferHandle = DeferWindowPos(
                deferHandle,
                CoreGraphHandle,
                NULL,
                margin.left + innerMargin.left,
                margin.top + (height + between) * 2 + innerMargin.top,
                width - innerMargin.left - innerMargin.right,
                height - innerMargin.top - innerMargin.bottom,
                SWP_NOACTIVATE | SWP_NOZORDER
                );

            EndDeferWindowPos(deferHandle);
        }
        break;

    case WM_SIZING:
        {
            PhResizingMinimumSize((PRECT)lParam, wParam, 500, 400);
        }
        break;
    case WM_COMMAND:
        {
            switch (LOWORD(wParam))
            {
            case IDCANCEL:
            case IDOK:
                DestroyWindow(hwndDlg);
                break;
            case IDC_ALWAYSONTOP:
                {
                    AlwaysOnTop = Button_GetCheck(GetDlgItem(hwndDlg, IDC_ALWAYSONTOP)) == BST_CHECKED;
                    GfxSetAlwaysOnTop();
                }
                break;
            }
        }
        break;
    case WM_GFX_ACTIVATE:
        {
            if (IsIconic(hwndDlg))
                ShowWindow(hwndDlg, SW_RESTORE);
            else
                ShowWindow(hwndDlg, SW_SHOW);

            SetForegroundWindow(hwndDlg);
        }
        break;
    case WM_GFX_UPDATE:
        {
            GetGfxUsages();
            GetGfxTemp();
            GetGfxClockSpeeds();

            GpuGraphState.Valid = FALSE;
            GpuGraphState.TooltipIndex = -1;
            Graph_MoveGrid(GpuGraphHandle, 1);
            Graph_Draw(GpuGraphHandle);
            Graph_UpdateTooltip(GpuGraphHandle);
            InvalidateRect(GpuGraphHandle, NULL, FALSE);

            CoreGraphState.Valid = FALSE;
            CoreGraphState.TooltipIndex = -1;
            Graph_MoveGrid(CoreGraphHandle, 1);
            Graph_Draw(CoreGraphHandle);
            Graph_UpdateTooltip(CoreGraphHandle);
            InvalidateRect(CoreGraphHandle, NULL, FALSE);

            MemGraphState.Valid = FALSE;
            MemGraphState.TooltipIndex = -1;
            Graph_MoveGrid(MemGraphHandle, 1);
            Graph_Draw(MemGraphHandle);
            Graph_UpdateTooltip(MemGraphHandle);
            InvalidateRect(MemGraphHandle, NULL, FALSE);

            SendMessage(GfxPanelWindowHandle, WM_GFX_PANEL_UPDATE, 0, 0);
        }
        break;
    }

    return FALSE;
}
Esempio n. 9
0
int WINAPI WinMain(HINSTANCE _hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow)
{
	Common::EnableCrashingOnCrashes();

	char *token = szCmdLine;
	char fileToLoad[256] = "";

	token = strtok(szCmdLine," ");

	g_Config.Load();
	VFSRegister("", new DirectoryAssetReader(""));

	while (token)
	{
		if (strcmp(token,"-run"))
		{
			//run immediately
		}

		token = strtok(NULL," ");
	}

	//Windows, API init stuff
	INITCOMMONCONTROLSEX comm;
	comm.dwSize = sizeof(comm);
	comm.dwICC = ICC_BAR_CLASSES | ICC_LISTVIEW_CLASSES | ICC_TAB_CLASSES;
	InitCommonControlsEx(&comm);
	timeBeginPeriod(1);
	MainWindow::Init(_hInstance);

	HACCEL hAccelTable = LoadAccelerators(_hInstance, (LPCTSTR)IDR_ACCELS);
	g_hPopupMenus = LoadMenu(_hInstance, (LPCSTR)IDR_POPUPMENUS);

	MainWindow::Show(_hInstance, iCmdShow);
	host = new WindowsHost(MainWindow::GetHWND(), MainWindow::GetDisplayHWND());

	HWND hwndMain = MainWindow::GetHWND();
	HMENU menu = GetMenu(hwndMain);

	//initialize custom controls
	CtrlDisAsmView::init();
	CtrlMemView::init();
	CtrlRegisterList::init();

	DialogManager::AddDlg(memoryWindow[0] = new CMemoryDlg(_hInstance, hwndMain, currentDebugMIPS));
	DialogManager::AddDlg(vfpudlg = new CVFPUDlg(_hInstance, hwndMain, currentDebugMIPS));

	MainWindow::Update();
	MainWindow::UpdateMenus();

	LogManager::Init();
	bool hidden = false;
#ifndef _DEBUG
	hidden = true;
#endif
	LogManager::GetInstance()->GetConsoleListener()->Open(hidden, 150, 120, "PPSSPP Debug Console");
	LogManager::GetInstance()->SetLogLevel(LogTypes::G3D, LogTypes::LERROR);
	if (strlen(fileToLoad))
	{
		// TODO: load the thing
	}

	//so.. we're at the message pump of the GUI thread
	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0))	//while no quit
	{
		//DSound_UpdateSound();

		//hack to make it possible to get to main window from floating windows with Esc
		if (msg.hwnd != hwndMain && msg.message==WM_KEYDOWN && msg.wParam==VK_ESCAPE)
			BringWindowToTop(hwndMain);

		//Translate accelerators and dialog messages...
		if (!TranslateAccelerator(hwndMain, hAccelTable, &msg))
		{
			if (!DialogManager::IsDialogMessage(&msg))
			{
				//and finally translate and dispatch
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}
	}

	LogManager::Shutdown();
	DialogManager::DestroyAll();
	timeEndPeriod(1);
	g_Config.Save();
	delete host;
	return 0;
}
Esempio n. 10
0
void CChatWnd::Open()
{
    if ( IsIconic() ) ShowWindow( SW_SHOWNORMAL );
    BringWindowToTop();
    SetForegroundWindow();
}
Esempio n. 11
0
int ShowHide(WPARAM wParam,LPARAM lParam) 
{
	HWND hwndContactList=(HWND)CallService(MS_CLUI_GETHWND,0,0);
	BOOL bShow = FALSE;

	int iVisibleState = GetWindowVisibleState(hwndContactList,0,0);
	int method;
	method=DBGetContactSettingByte(NULL, "ModernData", "HideBehind", 0);; //(0-none, 1-leftedge, 2-rightedge);
	if (method)
	{
		if (DBGetContactSettingByte(NULL, "ModernData", "BehindEdge", 0)==0 && lParam!=1)
		{
			//hide
			BehindEdge_Hide();
		}
		else
		{
			BehindEdge_Show();
		}
		bShow=TRUE;
		iVisibleState=GWVS_HIDDEN;
	}

	if (!method && DBGetContactSettingByte(NULL, "ModernData", "BehindEdge", 0)>0)
	{
		BehindEdgeSettings=DBGetContactSettingByte(NULL, "ModernData", "BehindEdge", 0);
		BehindEdge_Show();
		BehindEdgeSettings=0;
		BehindEdge_State=0;
		DBDeleteContactSetting(NULL, "ModernData", "BehindEdge");
	}

	//bShow is FALSE when we enter the switch if no hide behind edge.
	switch (iVisibleState) {
		case GWVS_PARTIALLY_COVERED:
			//If we don't want to bring it to top, we can use a simple break. This goes against readability ;-) but the comment explains it.			
		case GWVS_COVERED: //Fall through (and we're already falling)
			if (DBGetContactSettingByte(NULL,"CList","OnDesktop",0) || !DBGetContactSettingByte(NULL, "CList", "BringToFront", SETTING_BRINGTOFRONT_DEFAULT)) break;            
		case GWVS_HIDDEN:
			bShow = TRUE; break;
		case GWVS_VISIBLE: //This is not needed, but goes for readability.
			bShow = FALSE; break;
		case -1: //We can't get here, both hwndContactList and iStepX and iStepY are right.
			return 0;
	}
	if(bShow == TRUE || lParam) {
		WINDOWPLACEMENT pl={0};
		HMONITOR (WINAPI *MyMonitorFromWindow)(HWND,DWORD);
		RECT rcScreen,rcWindow;
		int offScreen=0;

		SystemParametersInfo(SPI_GETWORKAREA,0,&rcScreen,FALSE);
		GetWindowRect(hwndContactList,&rcWindow);

		ActivateSubContainers(TRUE);
		ShowWindowNew(hwndContactList, SW_RESTORE);

		if (!DBGetContactSettingByte(NULL,"CList","OnDesktop",0))
		{
			OnShowHide(hwndContactList,1);
			SetWindowPos(hwndContactList, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE |SWP_NOACTIVATE);           
			CALLED_FROM_SHOWHIDE=1;
			BringWindowToTop(hwndContactList);			     
			if (!DBGetContactSettingByte(NULL,"CList","OnTop",SETTING_ONTOP_DEFAULT))
				//&& ((DBGetContactSettingByte(NULL, "CList", "BringToFront", SETTING_BRINGTOFRONT_DEFAULT) /*&& iVisibleState>=2*/)))
				SetWindowPos(hwndContactList, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
			SetForegroundWindow(hwndContactList);	     
			CALLED_FROM_SHOWHIDE=0;
		}
		else
		{
			SetWindowPos(hwndContactList, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
			OnShowHide(hwndContactList,1);
			SetForegroundWindow(hwndContactList);	
		}
		DBWriteContactSettingByte(NULL,"CList","State",SETTING_STATE_NORMAL);
		//this forces the window onto the visible screen
		MyMonitorFromWindow=(HMONITOR (WINAPI *)(HWND,DWORD))GetProcAddress(GetModuleHandle(TEXT("USER32")),"MonitorFromWindow");
		if(MyMonitorFromWindow) {
			if(MyMonitorFromWindow(hwndContactList,0)==NULL) {
				BOOL (WINAPI *MyGetMonitorInfoA)(HMONITOR,LPMONITORINFO);
				MONITORINFO mi={0};
				HMONITOR hMonitor=MyMonitorFromWindow(hwndContactList,2);
				MyGetMonitorInfoA=(BOOL (WINAPI *)(HMONITOR,LPMONITORINFO))GetProcAddress(GetModuleHandle(TEXT("USER32")),"GetMonitorInfoA");
				mi.cbSize=sizeof(mi);
				MyGetMonitorInfoA(hMonitor,&mi);
				rcScreen=mi.rcWork;
				offScreen=1;
			}
		}
		else {
			RECT rcDest;
			if(IntersectRect(&rcDest,&rcScreen,&rcWindow)==0) offScreen=1;
		}
		if(offScreen) {
			if(rcWindow.top>=rcScreen.bottom) OffsetRect(&rcWindow,0,rcScreen.bottom-rcWindow.bottom);
			else if(rcWindow.bottom<=rcScreen.top) OffsetRect(&rcWindow,0,rcScreen.top-rcWindow.top);
			if(rcWindow.left>=rcScreen.right) OffsetRect(&rcWindow,rcScreen.right-rcWindow.right,0);
			else if(rcWindow.right<=rcScreen.left) OffsetRect(&rcWindow,rcScreen.left-rcWindow.left,0);
			SetWindowPos(hwndContactList,0,rcWindow.left,rcWindow.top,rcWindow.right-rcWindow.left,rcWindow.bottom-rcWindow.top,SWP_NOZORDER);
		}
		//if (DBGetContactSettingByte(NULL,"CList","OnDesktop",0))
		//    SetWindowPos(hwndContactList, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);

	}
	else { //It needs to be hidden

		HideWindow(hwndContactList, SW_HIDE);
		//OnShowHide(hwndContactList,0);

		DBWriteContactSettingByte(NULL,"CList","State",SETTING_STATE_HIDDEN);
		if(MySetProcessWorkingSetSize!=NULL && DBGetContactSettingByte(NULL,"CList","DisableWorkingSet",1)) MySetProcessWorkingSetSize(GetCurrentProcess(),-1,-1);
	}
	return 0;
}
BOOL CSelectDrivesDlg::OnInitDialog()
{
	CWaitCursor wc;

	CDialog::OnInitDialog();

	if (WMU_THREADFINISHED == 0)
	{
		TRACE("RegisterMessage() failed. Using WM_USER + 123\r\n");
		WMU_THREADFINISHED = WM_USER + 123;
	}

	ModifyStyle(0, WS_CLIPCHILDREN);

	m_layout.AddControl(IDOK,				1, 0, 0, 0);
	m_layout.AddControl(IDCANCEL,			1, 0, 0, 0);
	m_layout.AddControl(IDC_DRIVES,			0, 0, 1, 1);
	m_layout.AddControl(IDC_AFOLDER,		0, 1, 0, 0);
	m_layout.AddControl(IDC_FOLDERNAME,		0, 1, 1, 0);
	m_layout.AddControl(IDC_BROWSEFOLDER,	1, 1, 0, 0);

	m_layout.OnInitDialog(true);

	m_list.ShowGrid(GetOptions()->IsListGrid());
	m_list.ShowStripes(GetOptions()->IsListStripes());
	m_list.ShowFullRowSelection(GetOptions()->IsListFullRowSelection());

	m_list.SetExtendedStyle(m_list.GetExtendedStyle() | LVS_EX_HEADERDRAGDROP);
	// If we set an ImageList here, OnMeasureItem will have no effect ?!

	m_list.InsertColumn(COL_NAME,		LoadString(IDS_DRIVECOL_NAME),		LVCFMT_LEFT, 120, COL_NAME);
	m_list.InsertColumn(COL_TOTAL,		LoadString(IDS_DRIVECOL_TOTAL),		LVCFMT_RIGHT, 55, COL_TOTAL);
	m_list.InsertColumn(COL_FREE,		LoadString(IDS_DRIVECOL_FREE),		LVCFMT_RIGHT, 55, COL_FREE);
	m_list.InsertColumn(COL_GRAPH,		LoadString(IDS_DRIVECOL_GRAPH),		LVCFMT_LEFT, 100, COL_GRAPH);
	m_list.InsertColumn(COL_PERCENTUSED,LoadString(IDS_DRIVECOL_PERCENTUSED),LVCFMT_RIGHT, 55, COL_PERCENTUSED);

	m_list.OnColumnsInserted();

	m_folderName= CPersistence::GetSelectDrivesFolder();
	CPersistence::GetSelectDrivesDrives(m_selectedDrives);

	ShowWindow(SW_SHOWNORMAL);
	UpdateWindow();
	BringWindowToTop();
	SetForegroundWindow();

	DWORD drives= GetLogicalDrives();
	int i;
	DWORD mask= 0x00000001;
	for (i=0; i < 32; i++, mask <<= 1)
	{
		if ((drives & mask) == 0)
			continue;

		CString s;
		s.Format(_T("%c:\\"), i + _T('A'));

		UINT type= GetDriveType(s);
		if (type == DRIVE_UNKNOWN || type == DRIVE_NO_ROOT_DIR)
			continue;

		// The check of remote drives will be done in the backgound by the CDriveInformationThread.
		if (type != DRIVE_REMOTE && !DriveExists(s))
			continue;

		CDriveItem *item= new CDriveItem(&m_list, s);
		m_list.InsertListItem(m_list.GetItemCount(), item);
		item->StartQuery(m_hWnd, _serial);

		for (int k=0; k < m_selectedDrives.GetSize(); k++)
		{
			if (item->GetDrive() == m_selectedDrives[k])
			{
				m_list.SelectItem(item);
				break;
			}
		}
	}

	m_list.SortItems();

	m_radio= CPersistence::GetSelectDrivesRadio();
	UpdateData(false);

	switch (m_radio)
	{
	case RADIO_ALLLOCALDRIVES:
	case RADIO_AFOLDER:
		m_okButton.SetFocus();
		break;
	case RADIO_SOMEDRIVES:
		m_list.SetFocus();
		break;
	}

	UpdateButtons();
	return false; // we have set the focus.
}
LRESULT CALLBACK DeskBandWindow::WndProc(HWND hWnd, UINT uMessage, WPARAM wParam, LPARAM lParam)
{
	LRESULT lResult = 0;
	DeskBandWindow *pDeskBand = (DeskBandWindow*)pBandWin;
	TRACKMOUSEEVENT tme;
	if (uMessage == Shell)
	{
		switch (wParam)
		{
		case HSHELL_WINDOWREPLACED:
			if (pDeskBand->mShow && ((HWND)lParam == pIcon->mIconHwnd))
				BringWindowToTop(pIcon->mIconHwnd);
			break;
		case HSHELL_RUDEAPPACTIVATED:
		case HSHELL_WINDOWACTIVATED:
			if ((HWND)lParam == pIcon->mIconHwnd)
				break;
			if (pConfig != nullptr)
				pConfig->Update((HWND)lParam);
			break;
		}
	}
	switch (uMessage)
	{

	case WM_MOUSEMOVE:
	    tme.cbSize = sizeof(TRACKMOUSEEVENT);
	    tme.dwFlags = TME_LEAVE;
	    tme.hwndTrack = pDeskBand->mHwnd;
	    tme.dwHoverTime = 0;
	    ::TrackMouseEvent(&tme);

		if (pDeskBand->Mouse == Left)
		{
			pDeskBand->Mouse = Entered;
			InvalidateRect(pDeskBand->mHwnd, NULL, true);
			UpdateWindow(pDeskBand->mHwnd);
		}
	    break;

	case WM_LBUTTONDOWN:
		if (pDeskBand->Mouse == Entered)
		{
			pDeskBand->Mouse = ClickDown;
			InvalidateRect(pDeskBand->mHwnd, NULL, true);
			UpdateWindow(pDeskBand->mHwnd);
		}
		break;

	case WM_LBUTTONUP:
		if (pDeskBand->Mouse == ClickDown)
		{
			pDeskBand->Mouse = Entered;
			InvalidateRect(pDeskBand->mHwnd, NULL, true);
			UpdateWindow(pDeskBand->mHwnd);
			pDeskBand->mIconWin.Show(pDeskBand->mShow = !pDeskBand->mShow);
			pDeskBand->mTouchDetector.Set(pDeskBand->mShow);
			if (pDeskBand->mShow)
			{
				pConfig->mEventMode = (pConfig->mEventMode == Configuration::EEventMouse) ? Configuration::EEventNormal : Configuration::EEventMouse; // only for testing
				pConfig->Refresh();
				pConfig->UpdateEvents();
			}		
		}
		break;

	case WM_MOUSELEAVE:
		if (pDeskBand->Mouse != Left)
		{
			pDeskBand->Mouse = Left;
			InvalidateRect(pDeskBand->mHwnd, NULL, true);
			UpdateWindow(pDeskBand->mHwnd);
		}
		break;

	case WM_PAINT:
		pDeskBand->OnPaint(NULL);
		break;

	case WM_PRINTCLIENT:
		pDeskBand->OnPaint(reinterpret_cast<HDC>(wParam));
		break;

	case WM_ERASEBKGND:
		if (pDeskBand->m_fCompositionEnabled)
		{
			lResult = 1;
		}
		break;
	case USER_F_CHANGE:
		if (pConfig != nullptr)
			pConfig->Update((HWND)wParam);
		break;
	case USER_DOWN:
	{
					  Point Location = { (int)GET_X_LPARAM(lParam), (int)GET_Y_LPARAM(lParam) };
					  pTouch->Update(GET_POINTERID_WPARAM(wParam), ETouchDown, Location);
					  break;
	}
	case USER_UP:
	{
					  Point Location = { (int)GET_X_LPARAM(lParam), (int)GET_Y_LPARAM(lParam) };
					  pTouch->Update(GET_POINTERID_WPARAM(wParam), ETouchUp, Location);
					  break;
	}
	case USER_MOVE:
	{
					  Point Location = { (int)GET_X_LPARAM(lParam), (int)GET_Y_LPARAM(lParam) };
					  pTouch->Update(GET_POINTERID_WPARAM(wParam), ETouchMove, Location);
					  break;
	}
	}

	if (uMessage != WM_ERASEBKGND)
	{
		lResult = DefWindowProc(hWnd, uMessage, wParam, lParam);
	}

	return lResult;
};
Esempio n. 14
0
/*
 * Create - displays the dialog box
 */
HWND RemoteWnd_Create(HWND parentWnd)
{
    HWND remoteWnd;

    if (Prog_remoteWnd) {
        if (IsIconic(Prog_remoteWnd)) {
            OpenIcon(Prog_remoteWnd);
        }
        BringWindowToTop(Prog_remoteWnd);
        remoteWnd = Prog_remoteWnd;
    } else {
        RECT wndRect = { 60, 60, 685, 120 };
        DWORD wndExStyles = WS_EX_LEFT;
        DWORD wndStyles = WS_POPUPWINDOW | WS_CAPTION | WS_SYSMENU;
        int i;

        if (!AdjustWindowRectEx(&wndRect, wndStyles, FALSE, wndExStyles)) {
            MsgBox_LastErrorF(parentWnd, _T("Error adjusting window rect"));
        }
        remoteWnd = CreateWindowEx(
                wndExStyles                               /* extended styles */
                , RemoteWnd_className                     /* window class */
                , _T("Remote")                            /* caption text */
                , wndStyles                               /* styles */
                , wndRect.left, wndRect.top               /* left, top */
                , RECT_W(wndRect), RECT_H(wndRect)        /* width, height */
                , NULL                                    /* parent window */
                , (HMENU) NULL                            /* menu */
                , Prog_instance                           /* program instance */
                , NULL                                    /* creation data */
            );
        if (!remoteWnd) {
            MsgBox_LastErrorF(parentWnd
                    , _T("Error creating remote control window"));
            return NULL;
        }
        /*
         * Add "Stay On Top" system menu item.
         */
        Window_AddSysMenuItem(remoteWnd, _T("Stay On Top"), IDM_STAY_ON_TOP
                , TRUE);
        rw_StayOnTop(remoteWnd);

        /*
         * Initialize buttons.
         */
        for (i = 0; i < btnInitCnt; i++) {
            HWND btn = CreateWindowEx(
                    0                                         /* extended styles */
                    , _T("BUTTON")                            /* window class */
                    , _T("TX81Z Remote")                      /* caption text */
                    , BS_OWNERDRAW | WS_CHILD | WS_VISIBLE    /* styles */
                    , btnInits[i].x, btnInits[i].y            /* left, top */
                    , btnInits[i].w, btnInits[i].h            /* width, height */
                    , remoteWnd                               /* parent window */
                    , (HMENU) btnInits[i].btnID               /* menu */
                    , Prog_instance                           /* program instance */
                    , NULL                                    /* creation data */
                );
            if (!btn) {
                MsgBox_LastErrorF(parentWnd
                        , _T("Error creating remote control button"));
                return NULL;
            }
            rw_origBtnProc = (WNDPROC) SetWindowLong(btn, GWL_WNDPROC
                    , (long) rw_BtnProc);
        }
        ShowWindow(remoteWnd, SW_SHOW);
    }

    return remoteWnd;
}
Esempio n. 15
0
/*
============
CameraWndProc
============
*/
LONG WINAPI WCam_WndProc (
    HWND    hWnd,
    UINT    uMsg,
    WPARAM  wParam,
    LPARAM  lParam)
{
	int		fwKeys, xPos, yPos;
    RECT	rect;

    GetClientRect(hWnd, &rect);

    switch (uMsg)
    {
	case WM_CREATE:
		{
			HFONT	hfont;
			
            g_qeglobals.d_hdcBase = GetDC(hWnd);
			QEW_SetupPixelFormat(g_qeglobals.d_hdcBase, true);

            if ( ( g_qeglobals.d_hglrcBase = wglCreateContext( g_qeglobals.d_hdcBase ) ) == 0 )
				Error ("wglCreateContext failed");
            if (!wglMakeCurrent( g_qeglobals.d_hdcBase, g_qeglobals.d_hglrcBase ))
				Error ("wglMakeCurrent failed");

			Texture_SetMode(g_qeglobals.d_savedinfo.iTexMenu);

			//
			// create GL font
			//
			hfont = CreateFont(
				10,	// logical height of font 
				7,	// logical average character width 
				0,	// angle of escapement 
				0,	// base-line orientation angle 
				0,	// font weight 
				0,	// italic attribute flag 
				0,	// underline attribute flag 
				0,	// strikeout attribute flag 
				0,	// character set identifier 
				0,	// output precision 
				0,	// clipping precision 
				0,	// output quality 
				0,	// pitch and family 
				0 	// pointer to typeface name string 
				);

			if ( !hfont )
				Error( "couldn't create font" );

			SelectObject (g_qeglobals.d_hdcBase, hfont);

			if ( ( g_qeglobals.d_font_list = glGenLists (256) ) == 0 )
				Error( "couldn't create font dlists" );
			
			// create the bitmap display lists
			// we're making images of glyphs 0 thru 255
			if ( !wglUseFontBitmaps (g_qeglobals.d_hdcBase, 1, 255, g_qeglobals.d_font_list) )
				Error( "wglUseFontBitmaps faileD" );
			
			// indicate start of glyph display lists
			glListBase (g_qeglobals.d_font_list);

			// report OpenGL information
			Sys_Printf ("GL_VENDOR: %s\n", glGetString (GL_VENDOR));
			Sys_Printf ("GL_RENDERER: %s\n", glGetString (GL_RENDERER));
			Sys_Printf ("GL_VERSION: %s\n", glGetString (GL_VERSION));
			Sys_Printf ("GL_EXTENSIONS: %s\n", glGetString (GL_EXTENSIONS));
		}
		return 0;
	case WM_PAINT:
        { 
			PAINTSTRUCT	ps;
			
            if (!wglMakeCurrent( g_qeglobals.d_hdcBase, g_qeglobals.d_hglrcBase ))
				Error ("wglMakeCurrent failed");

			if ( BeginPaint(hWnd, &ps) )
			{
				QE_CheckOpenGLForErrors();
				Cam_Draw ();
				QE_CheckOpenGLForErrors();

				EndPaint(hWnd, &ps);
				SwapBuffers(g_qeglobals.d_hdcBase);
			}
        }
		return 0;
		
	case WM_USER+267:	// benchmark
        { 
			PAINTSTRUCT	ps;
			WINDOWPLACEMENT wp;
			double	start, end;
			int		i;
			
			memset( &wp, 0, sizeof( wp ) );
			wp.length = sizeof( wp );
			GetWindowPlacement( g_qeglobals.d_hwndCamera, &wp );
			
			MoveWindow( g_qeglobals.d_hwndCamera, 30, 30, 400, 400, TRUE );
			
			BeginPaint(hWnd, &ps);
            if (!wglMakeCurrent( g_qeglobals.d_hdcBase, g_qeglobals.d_hglrcBase))
				Error ("wglMakeCurrent failed");
			glDrawBuffer (GL_FRONT);
			
			start = Sys_DoubleTime ();
			for (i=0 ; i<100 ; i++)
			{
				camera.angles[YAW] = i*4;
				Cam_Draw ();
			}
			wglSwapBuffers(g_qeglobals.d_hdcBase);
			glDrawBuffer (GL_BACK);
			end = Sys_DoubleTime ();
			EndPaint(hWnd, &ps);
			Sys_Printf ("%5.2f seconds\n", end-start);

			SetWindowPlacement( g_qeglobals.d_hwndCamera, &wp );
        }
		break;
		
	case WM_KEYDOWN:
		if ( QE_KeyDown (wParam) )
			return 0;
		else 
			return DefWindowProc( hWnd, uMsg, wParam, lParam );
		
	case WM_MBUTTONDOWN:
	case WM_RBUTTONDOWN:
	case WM_LBUTTONDOWN:
		if (GetTopWindow(g_qeglobals.d_hwndMain) != hWnd)
			BringWindowToTop(hWnd);
		
		SetFocus (g_qeglobals.d_hwndCamera);
		SetCapture (g_qeglobals.d_hwndCamera);
		fwKeys = wParam;        // key flags 
		xPos = (short)LOWORD(lParam);  // horizontal position of cursor 
		yPos = (short)HIWORD(lParam);  // vertical position of cursor 
		yPos = (int)rect.bottom - 1 - yPos;
		Cam_MouseDown (xPos, yPos, fwKeys);
		return 0;
		
	case WM_MBUTTONUP:
	case WM_RBUTTONUP:
	case WM_LBUTTONUP:
		fwKeys = wParam;        // key flags 
		xPos = (short)LOWORD(lParam);  // horizontal position of cursor 
		yPos = (short)HIWORD(lParam);  // vertical position of cursor 
		yPos = (int)rect.bottom - 1 - yPos;
		Cam_MouseUp (xPos, yPos, fwKeys);
		if (! (fwKeys & (MK_LBUTTON|MK_RBUTTON|MK_MBUTTON)))
			ReleaseCapture ();
		return 0;
		
	case WM_MOUSEMOVE:
		fwKeys = wParam;        // key flags 
		xPos = (short)LOWORD(lParam);  // horizontal position of cursor 
		yPos = (short)HIWORD(lParam);  // vertical position of cursor 
		yPos = (int)rect.bottom - 1 - yPos;
		Cam_MouseMoved (xPos, yPos, fwKeys);
		return 0;
		
	case WM_SIZE:
		camera.width = rect.right;
		camera.height = rect.bottom;
		InvalidateRect(g_qeglobals.d_hwndCamera, NULL, false);
		return 0;

	case WM_KILLFOCUS:
	case WM_SETFOCUS:
		SendMessage( hWnd, WM_NCACTIVATE, uMsg == WM_SETFOCUS, 0 );
		return 0;

	case WM_NCCALCSIZE:// don't let windows copy pixels
		DefWindowProc (hWnd, uMsg, wParam, lParam);
		return WVR_REDRAW;

	case WM_CLOSE:
		DestroyWindow (hWnd);
		return 0;
		
	case WM_DESTROY:
		QEW_StopGL( hWnd, g_qeglobals.d_hglrcBase, g_qeglobals.d_hdcBase );
		return 0;
    }

	return DefWindowProc( hWnd, uMsg, wParam, lParam );
}
Esempio n. 16
0
INT_PTR CALLBACK PhpProcessThreadsDlgProc(
    _In_ HWND hwndDlg,
    _In_ UINT uMsg,
    _In_ WPARAM wParam,
    _In_ LPARAM lParam
    )
{
    LPPROPSHEETPAGE propSheetPage;
    PPH_PROCESS_PROPPAGECONTEXT propPageContext;
    PPH_PROCESS_ITEM processItem;
    PPH_THREADS_CONTEXT threadsContext;
    HWND tnHandle;

    if (PhpPropPageDlgProcHeader(hwndDlg, uMsg, lParam,
        &propSheetPage, &propPageContext, &processItem))
    {
        threadsContext = (PPH_THREADS_CONTEXT)propPageContext->Context;

        if (threadsContext)
            tnHandle = threadsContext->ListContext.TreeNewHandle;
    }
    else
    {
        return FALSE;
    }

    switch (uMsg)
    {
    case WM_INITDIALOG:
        {
            threadsContext = propPageContext->Context =
                PhAllocate(PhEmGetObjectSize(EmThreadsContextType, sizeof(PH_THREADS_CONTEXT)));

            // The thread provider has a special registration mechanism.
            threadsContext->Provider = PhCreateThreadProvider(
                processItem->ProcessId
                );
            PhRegisterCallback(
                &threadsContext->Provider->ThreadAddedEvent,
                ThreadAddedHandler,
                threadsContext,
                &threadsContext->AddedEventRegistration
                );
            PhRegisterCallback(
                &threadsContext->Provider->ThreadModifiedEvent,
                ThreadModifiedHandler,
                threadsContext,
                &threadsContext->ModifiedEventRegistration
                );
            PhRegisterCallback(
                &threadsContext->Provider->ThreadRemovedEvent,
                ThreadRemovedHandler,
                threadsContext,
                &threadsContext->RemovedEventRegistration
                );
            PhRegisterCallback(
                &threadsContext->Provider->UpdatedEvent,
                ThreadsUpdatedHandler,
                threadsContext,
                &threadsContext->UpdatedEventRegistration
                );
            PhRegisterCallback(
                &threadsContext->Provider->LoadingStateChangedEvent,
                ThreadsLoadingStateChangedHandler,
                threadsContext,
                &threadsContext->LoadingStateChangedEventRegistration
                );
            threadsContext->WindowHandle = hwndDlg;

            // Initialize the list.
            tnHandle = GetDlgItem(hwndDlg, IDC_LIST);
            BringWindowToTop(tnHandle);
            PhInitializeThreadList(hwndDlg, tnHandle, &threadsContext->ListContext);
            TreeNew_SetEmptyText(tnHandle, &EmptyThreadsText, 0);
            PhInitializeProviderEventQueue(&threadsContext->EventQueue, 100);

            // Use Cycles instead of Context Switches on Vista and above, but only when we can
            // open the process, since cycle time information requires sufficient access to the
            // threads.
            if (WINDOWS_HAS_CYCLE_TIME)
            {
                HANDLE processHandle;
                PROCESS_EXTENDED_BASIC_INFORMATION extendedBasicInfo;

                // We make a distinction between PROCESS_QUERY_INFORMATION and PROCESS_QUERY_LIMITED_INFORMATION since
                // the latter can be used when opening audiodg.exe even though we can't access its threads using
                // THREAD_QUERY_LIMITED_INFORMATION.

                if (processItem->ProcessId == SYSTEM_IDLE_PROCESS_ID)
                {
                    threadsContext->ListContext.UseCycleTime = TRUE;
                }
                else if (NT_SUCCESS(PhOpenProcess(&processHandle, PROCESS_QUERY_INFORMATION, processItem->ProcessId)))
                {
                    threadsContext->ListContext.UseCycleTime = TRUE;
                    NtClose(processHandle);
                }
                else if (NT_SUCCESS(PhOpenProcess(&processHandle, PROCESS_QUERY_LIMITED_INFORMATION, processItem->ProcessId)))
                {
                    threadsContext->ListContext.UseCycleTime = TRUE;

                    // We can't use cycle time for protected processes (without KProcessHacker).
                    if (NT_SUCCESS(PhGetProcessExtendedBasicInformation(processHandle, &extendedBasicInfo)) && extendedBasicInfo.IsProtectedProcess)
                    {
                        threadsContext->ListContext.UseCycleTime = FALSE;
                    }

                    NtClose(processHandle);
                }
            }

            if (processItem->ServiceList && processItem->ServiceList->Count != 0 && WINDOWS_HAS_SERVICE_TAGS)
                threadsContext->ListContext.HasServices = TRUE;

            PhEmCallObjectOperation(EmThreadsContextType, threadsContext, EmObjectCreate);

            if (PhPluginsEnabled)
            {
                PH_PLUGIN_TREENEW_INFORMATION treeNewInfo;

                treeNewInfo.TreeNewHandle = tnHandle;
                treeNewInfo.CmData = &threadsContext->ListContext.Cm;
                treeNewInfo.SystemContext = threadsContext;
                PhInvokeCallback(PhGetGeneralCallback(GeneralCallbackThreadTreeNewInitializing), &treeNewInfo);
            }

            PhLoadSettingsThreadList(&threadsContext->ListContext);

            PhThreadProviderInitialUpdate(threadsContext->Provider);
            PhRegisterThreadProvider(threadsContext->Provider, &threadsContext->ProviderRegistration);

            SET_BUTTON_ICON(IDC_OPENSTARTMODULE, PH_LOAD_SHARED_ICON_SMALL(MAKEINTRESOURCE(IDI_FOLDER)));
        }
        break;
    case WM_DESTROY:
        {
            PhEmCallObjectOperation(EmThreadsContextType, threadsContext, EmObjectDelete);

            PhUnregisterCallback(
                &threadsContext->Provider->ThreadAddedEvent,
                &threadsContext->AddedEventRegistration
                );
            PhUnregisterCallback(
                &threadsContext->Provider->ThreadModifiedEvent,
                &threadsContext->ModifiedEventRegistration
                );
            PhUnregisterCallback(
                &threadsContext->Provider->ThreadRemovedEvent,
                &threadsContext->RemovedEventRegistration
                );
            PhUnregisterCallback(
                &threadsContext->Provider->UpdatedEvent,
                &threadsContext->UpdatedEventRegistration
                );
            PhUnregisterCallback(
                &threadsContext->Provider->LoadingStateChangedEvent,
                &threadsContext->LoadingStateChangedEventRegistration
                );
            PhUnregisterThreadProvider(threadsContext->Provider, &threadsContext->ProviderRegistration);
            PhSetTerminatingThreadProvider(threadsContext->Provider);
            PhDereferenceObject(threadsContext->Provider);
            PhDeleteProviderEventQueue(&threadsContext->EventQueue);

            if (PhPluginsEnabled)
            {
                PH_PLUGIN_TREENEW_INFORMATION treeNewInfo;

                treeNewInfo.TreeNewHandle = tnHandle;
                treeNewInfo.CmData = &threadsContext->ListContext.Cm;
                PhInvokeCallback(PhGetGeneralCallback(GeneralCallbackThreadTreeNewUninitializing), &treeNewInfo);
            }

            PhSaveSettingsThreadList(&threadsContext->ListContext);
            PhDeleteThreadList(&threadsContext->ListContext);

            PhFree(threadsContext);

            PhpPropPageDlgProcDestroy(hwndDlg);
        }
        break;
    case WM_SHOWWINDOW:
        {
            if (!propPageContext->LayoutInitialized)
            {
                PPH_LAYOUT_ITEM dialogItem;

                dialogItem = PhAddPropPageLayoutItem(hwndDlg, hwndDlg,
                    PH_PROP_PAGE_TAB_CONTROL_PARENT, PH_ANCHOR_ALL);
                PhAddPropPageLayoutItem(hwndDlg, GetDlgItem(hwndDlg, IDC_LIST),
                    dialogItem, PH_ANCHOR_ALL);

#define ADD_BL_ITEM(Id) \
    PhAddPropPageLayoutItem(hwndDlg, GetDlgItem(hwndDlg, Id), dialogItem, PH_ANCHOR_LEFT | PH_ANCHOR_BOTTOM)

                // Thread details area
                {
                    ULONG id;

                    for (id = IDC_STATICBL1; id <= IDC_STATICBL11; id++)
                        ADD_BL_ITEM(id);

                    // Not in sequence
                    ADD_BL_ITEM(IDC_STATICBL12);
                }

                PhAddPropPageLayoutItem(hwndDlg, GetDlgItem(hwndDlg, IDC_STARTMODULE),
                    dialogItem, PH_ANCHOR_LEFT | PH_ANCHOR_RIGHT | PH_ANCHOR_BOTTOM);
                PhAddPropPageLayoutItem(hwndDlg, GetDlgItem(hwndDlg, IDC_OPENSTARTMODULE),
                    dialogItem, PH_ANCHOR_RIGHT | PH_ANCHOR_BOTTOM);
                ADD_BL_ITEM(IDC_STARTED);
                ADD_BL_ITEM(IDC_KERNELTIME);
                ADD_BL_ITEM(IDC_USERTIME);
                ADD_BL_ITEM(IDC_CONTEXTSWITCHES);
                ADD_BL_ITEM(IDC_CYCLES);
                ADD_BL_ITEM(IDC_STATE);
                ADD_BL_ITEM(IDC_PRIORITY);
                ADD_BL_ITEM(IDC_BASEPRIORITY);
                ADD_BL_ITEM(IDC_IOPRIORITY);
                ADD_BL_ITEM(IDC_PAGEPRIORITY);
                ADD_BL_ITEM(IDC_IDEALPROCESSOR);

                PhDoPropPageLayout(hwndDlg);

                propPageContext->LayoutInitialized = TRUE;
            }
        }
        break;
    case WM_COMMAND:
        {
            INT id = LOWORD(wParam);

            switch (id)
            {
            case ID_SHOWCONTEXTMENU:
                {
                    PhShowThreadContextMenu(hwndDlg, processItem, threadsContext, (PPH_TREENEW_CONTEXT_MENU)lParam);
                }
                break;
            case ID_THREAD_INSPECT:
                {
                    PPH_THREAD_ITEM threadItem = PhGetSelectedThreadItem(&threadsContext->ListContext);

                    if (threadItem)
                    {
                        PhReferenceObject(threadsContext->Provider);
                        PhShowThreadStackDialog(
                            hwndDlg,
                            threadsContext->Provider->ProcessId,
                            threadItem->ThreadId,
                            threadsContext->Provider
                            );
                        PhDereferenceObject(threadsContext->Provider);
                    }
                }
                break;
            case ID_THREAD_TERMINATE:
                {
                    PPH_THREAD_ITEM *threads;
                    ULONG numberOfThreads;

                    PhGetSelectedThreadItems(&threadsContext->ListContext, &threads, &numberOfThreads);
                    PhReferenceObjects(threads, numberOfThreads);

                    if (PhUiTerminateThreads(hwndDlg, threads, numberOfThreads))
                        PhDeselectAllThreadNodes(&threadsContext->ListContext);

                    PhDereferenceObjects(threads, numberOfThreads);
                    PhFree(threads);
                }
                break;
            case ID_THREAD_SUSPEND:
                {
                    PPH_THREAD_ITEM *threads;
                    ULONG numberOfThreads;

                    PhGetSelectedThreadItems(&threadsContext->ListContext, &threads, &numberOfThreads);
                    PhReferenceObjects(threads, numberOfThreads);
                    PhUiSuspendThreads(hwndDlg, threads, numberOfThreads);
                    PhDereferenceObjects(threads, numberOfThreads);
                    PhFree(threads);
                }
                break;
            case ID_THREAD_RESUME:
                {
                    PPH_THREAD_ITEM *threads;
                    ULONG numberOfThreads;

                    PhGetSelectedThreadItems(&threadsContext->ListContext, &threads, &numberOfThreads);
                    PhReferenceObjects(threads, numberOfThreads);
                    PhUiResumeThreads(hwndDlg, threads, numberOfThreads);
                    PhDereferenceObjects(threads, numberOfThreads);
                    PhFree(threads);
                }
                break;
            case ID_THREAD_AFFINITY:
                {
                    PPH_THREAD_ITEM threadItem = PhGetSelectedThreadItem(&threadsContext->ListContext);

                    if (threadItem)
                    {
                        PhReferenceObject(threadItem);
                        PhShowProcessAffinityDialog(hwndDlg, NULL, threadItem);
                        PhDereferenceObject(threadItem);
                    }
                }
                break;
            case ID_THREAD_PERMISSIONS:
                {
                    PPH_THREAD_ITEM threadItem = PhGetSelectedThreadItem(&threadsContext->ListContext);
                    PH_STD_OBJECT_SECURITY stdObjectSecurity;
                    PPH_ACCESS_ENTRY accessEntries;
                    ULONG numberOfAccessEntries;

                    if (threadItem)
                    {
                        stdObjectSecurity.OpenObject = PhpThreadPermissionsOpenThread;
                        stdObjectSecurity.ObjectType = L"Thread";
                        stdObjectSecurity.Context = threadItem->ThreadId;

                        if (PhGetAccessEntries(L"Thread", &accessEntries, &numberOfAccessEntries))
                        {
                            PhEditSecurity(
                                hwndDlg,
                                PhaFormatString(L"Thread %u", HandleToUlong(threadItem->ThreadId))->Buffer,
                                PhStdGetObjectSecurity,
                                PhStdSetObjectSecurity,
                                &stdObjectSecurity,
                                accessEntries,
                                numberOfAccessEntries
                                );
                            PhFree(accessEntries);
                        }
                    }
                }
                break;
            case ID_THREAD_TOKEN:
                {
                    NTSTATUS status;
                    PPH_THREAD_ITEM threadItem = PhGetSelectedThreadItem(&threadsContext->ListContext);
                    HANDLE threadHandle;

                    if (threadItem)
                    {
                        if (NT_SUCCESS(status = PhOpenThread(
                            &threadHandle,
                            ThreadQueryAccess,
                            threadItem->ThreadId
                            )))
                        {
                            PhShowTokenProperties(
                                hwndDlg,
                                PhpOpenThreadTokenObject,
                                (PVOID)threadHandle,
                                NULL
                                );

                            NtClose(threadHandle);
                        }
                        else
                        {
                            PhShowStatus(hwndDlg, L"Unable to open the thread", status, 0);
                        }
                    }
                }
                break;
            case ID_ANALYZE_WAIT:
                {
                    PPH_THREAD_ITEM threadItem = PhGetSelectedThreadItem(&threadsContext->ListContext);

                    if (threadItem)
                    {
                        PhReferenceObject(threadsContext->Provider->SymbolProvider);
                        PhUiAnalyzeWaitThread(
                            hwndDlg,
                            processItem->ProcessId,
                            threadItem->ThreadId,
                            threadsContext->Provider->SymbolProvider
                            );
                        PhDereferenceObject(threadsContext->Provider->SymbolProvider);
                    }
                }
                break;
            case ID_PRIORITY_TIMECRITICAL:
            case ID_PRIORITY_HIGHEST:
            case ID_PRIORITY_ABOVENORMAL:
            case ID_PRIORITY_NORMAL:
            case ID_PRIORITY_BELOWNORMAL:
            case ID_PRIORITY_LOWEST:
            case ID_PRIORITY_IDLE:
                {
                    PPH_THREAD_ITEM threadItem = PhGetSelectedThreadItem(&threadsContext->ListContext);

                    if (threadItem)
                    {
                        ULONG threadPriorityWin32;

                        switch (id)
                        {
                        case ID_PRIORITY_TIMECRITICAL:
                            threadPriorityWin32 = THREAD_PRIORITY_TIME_CRITICAL;
                            break;
                        case ID_PRIORITY_HIGHEST:
                            threadPriorityWin32 = THREAD_PRIORITY_HIGHEST;
                            break;
                        case ID_PRIORITY_ABOVENORMAL:
                            threadPriorityWin32 = THREAD_PRIORITY_ABOVE_NORMAL;
                            break;
                        case ID_PRIORITY_NORMAL:
                            threadPriorityWin32 = THREAD_PRIORITY_NORMAL;
                            break;
                        case ID_PRIORITY_BELOWNORMAL:
                            threadPriorityWin32 = THREAD_PRIORITY_BELOW_NORMAL;
                            break;
                        case ID_PRIORITY_LOWEST:
                            threadPriorityWin32 = THREAD_PRIORITY_LOWEST;
                            break;
                        case ID_PRIORITY_IDLE:
                            threadPriorityWin32 = THREAD_PRIORITY_IDLE;
                            break;
                        }

                        PhReferenceObject(threadItem);
                        PhUiSetPriorityThread(hwndDlg, threadItem, threadPriorityWin32);
                        PhDereferenceObject(threadItem);
                    }
                }
                break;
            case ID_IOPRIORITY_VERYLOW:
            case ID_IOPRIORITY_LOW:
            case ID_IOPRIORITY_NORMAL:
            case ID_IOPRIORITY_HIGH:
                {
                    PPH_THREAD_ITEM threadItem = PhGetSelectedThreadItem(&threadsContext->ListContext);

                    if (threadItem)
                    {
                        IO_PRIORITY_HINT ioPriority;

                        switch (id)
                        {
                        case ID_IOPRIORITY_VERYLOW:
                            ioPriority = IoPriorityVeryLow;
                            break;
                        case ID_IOPRIORITY_LOW:
                            ioPriority = IoPriorityLow;
                            break;
                        case ID_IOPRIORITY_NORMAL:
                            ioPriority = IoPriorityNormal;
                            break;
                        case ID_IOPRIORITY_HIGH:
                            ioPriority = IoPriorityHigh;
                            break;
                        }

                        PhReferenceObject(threadItem);
                        PhUiSetIoPriorityThread(hwndDlg, threadItem, ioPriority);
                        PhDereferenceObject(threadItem);
                    }
                }
                break;
            case ID_PAGEPRIORITY_VERYLOW:
            case ID_PAGEPRIORITY_LOW:
            case ID_PAGEPRIORITY_MEDIUM:
            case ID_PAGEPRIORITY_BELOWNORMAL:
            case ID_PAGEPRIORITY_NORMAL:
                {
                    PPH_THREAD_ITEM threadItem = PhGetSelectedThreadItem(&threadsContext->ListContext);

                    if (threadItem)
                    {
                        ULONG pagePriority;

                        switch (id)
                        {
                            case ID_PAGEPRIORITY_VERYLOW:
                                pagePriority = MEMORY_PRIORITY_VERY_LOW;
                                break;
                            case ID_PAGEPRIORITY_LOW:
                                pagePriority = MEMORY_PRIORITY_LOW;
                                break;
                            case ID_PAGEPRIORITY_MEDIUM:
                                pagePriority = MEMORY_PRIORITY_MEDIUM;
                                break;
                            case ID_PAGEPRIORITY_BELOWNORMAL:
                                pagePriority = MEMORY_PRIORITY_BELOW_NORMAL;
                                break;
                            case ID_PAGEPRIORITY_NORMAL:
                                pagePriority = MEMORY_PRIORITY_NORMAL;
                                break;
                        }

                        PhReferenceObject(threadItem);
                        PhUiSetPagePriorityThread(hwndDlg, threadItem, pagePriority);
                        PhDereferenceObject(threadItem);
                    }
                }
                break;
            case ID_THREAD_COPY:
                {
                    PPH_STRING text;

                    text = PhGetTreeNewText(tnHandle, 0);
                    PhSetClipboardString(tnHandle, &text->sr);
                    PhDereferenceObject(text);
                }
                break;
            case IDC_OPENSTARTMODULE:
                {
                    PPH_THREAD_ITEM threadItem = PhGetSelectedThreadItem(&threadsContext->ListContext);

                    if (threadItem && threadItem->StartAddressFileName)
                    {
                        PhShellExploreFile(hwndDlg, threadItem->StartAddressFileName->Buffer);
                    }
                }
                break;
            }
        }
        break;
    case WM_NOTIFY:
        {
            LPNMHDR header = (LPNMHDR)lParam;

            switch (header->code)
            {
            case PSN_SETACTIVE:
                break;
            case PSN_KILLACTIVE:
                // Can't disable, it screws up the deltas.
                break;
            }
        }
        break;
    case WM_PH_THREADS_UPDATED:
        {
            ULONG upToRunId = (ULONG)wParam;
            BOOLEAN firstRun = !!lParam;
            PPH_PROVIDER_EVENT events;
            ULONG count;
            ULONG i;

            events = PhFlushProviderEventQueue(&threadsContext->EventQueue, upToRunId, &count);

            if (events)
            {
                TreeNew_SetRedraw(tnHandle, FALSE);

                for (i = 0; i < count; i++)
                {
                    PH_PROVIDER_EVENT_TYPE type = PH_PROVIDER_EVENT_TYPE(events[i]);
                    PPH_THREAD_ITEM threadItem = PH_PROVIDER_EVENT_OBJECT(events[i]);

                    switch (type)
                    {
                    case ProviderAddedEvent:
                        PhAddThreadNode(&threadsContext->ListContext, threadItem, firstRun);
                        PhDereferenceObject(threadItem);
                        break;
                    case ProviderModifiedEvent:
                        PhUpdateThreadNode(&threadsContext->ListContext, PhFindThreadNode(&threadsContext->ListContext, threadItem->ThreadId));
                        break;
                    case ProviderRemovedEvent:
                        PhRemoveThreadNode(&threadsContext->ListContext, PhFindThreadNode(&threadsContext->ListContext, threadItem->ThreadId));
                        break;
                    }
                }

                PhFree(events);
            }

            PhTickThreadNodes(&threadsContext->ListContext);

            if (count != 0)
                TreeNew_SetRedraw(tnHandle, TRUE);

            if (propPageContext->PropContext->SelectThreadId)
            {
                PPH_THREAD_NODE threadNode;

                if (threadNode = PhFindThreadNode(&threadsContext->ListContext, propPageContext->PropContext->SelectThreadId))
                {
                    if (threadNode->Node.Visible)
                    {
                        TreeNew_SetFocusNode(tnHandle, &threadNode->Node);
                        TreeNew_SetMarkNode(tnHandle, &threadNode->Node);
                        TreeNew_SelectRange(tnHandle, threadNode->Node.Index, threadNode->Node.Index);
                        TreeNew_EnsureVisible(tnHandle, &threadNode->Node);
                    }
                }

                propPageContext->PropContext->SelectThreadId = NULL;
            }

            PhpUpdateThreadDetails(hwndDlg, threadsContext, FALSE);
        }
        break;
    case WM_PH_THREAD_SELECTION_CHANGED:
        {
            PhpUpdateThreadDetails(hwndDlg, threadsContext, TRUE);
        }
        break;
    }

    return FALSE;
}
Esempio n. 17
0
struct Box_s *About_Create(struct Box_s *roster)
{
	struct Box_s *dialog, *subbox;
	char txt[120];
	int x, y;

	{
		RECT windowrect;
		HMONITOR hm;
		MONITORINFO mi;

		windowrect.left = roster->x;
		windowrect.right = windowrect.left + roster->w - 1;
		windowrect.top = roster->y;
		windowrect.bottom = windowrect.top + roster->h - 1;

		hm = MonitorFromRect(&windowrect, MONITOR_DEFAULTTONEAREST);

		mi.cbSize = sizeof(mi);
		GetMonitorInfo(hm, &mi);

		x = mi.rcWork.left + (mi.rcWork.right - mi.rcWork.left - 360) / 2;
		y = mi.rcWork.top  + (mi.rcWork.bottom - mi.rcWork.top - 270/*490*/) / 2;
	}

	dialog = Box_Create(x, y, 360, 270 + 80/*490*/, BOX_VISIBLE);
	dialog->bgcol = DefaultBG;
	dialog->fgcol = UserInfoFG2;

	dialog->titlebar = TitleBarCloseOnly_Add(dialog, _("About Chesspark"), About_OnClose);
	dialog->OnActive = TitleBarRoot_OnActive;
	dialog->OnInactive = TitleBarRoot_OnInactive;

	subbox = Box_Create((dialog->w - 300) / 2, 40, 300, 180, BOX_VISIBLE | BOX_TRANSPARENT);
	subbox->img = ImageMgr_GetImage("bigLogo.gif");
	Box_AddChild(dialog, subbox);

	subbox = Box_Create(20, 230, 320, 20, BOX_VISIBLE | BOX_TRANSPARENT | BOX_CENTERTEXT);
	subbox->fgcol = UserInfoFG2;
	subbox->font = tahoma11b_f;
	i18n_stringsub(txt, 120, _("Version %1, Build %2"), CHESSPARK_VERSION, CHESSPARK_BUILD);
	Box_SetText(subbox, txt);
	Box_AddChild(dialog, subbox);

	subbox = Text_Create(20, 250, 320, 100/*240*/, BOX_VISIBLE | BOX_TRANSPARENT, TX_CENTERED | TX_WRAP);
	subbox->fgcol = UserInfoFG2;
	Text_SetText(subbox, 
		_("Copyright 2005, 2006 Chesspark.  All rights reserved.\n\n")
		/*
		"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT "
		"HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRAN"
		"TIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCH"
		"ANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN N"
		"O EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY "
		"DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL D"
		"AMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOO"
		"DS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPT"
		"ION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTR"
		"ACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) A"
		"RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED O"
		"F THE POSSIBILITY OF SUCH DAMAGE.");
		*/
		);
	Box_AddChild(dialog, subbox);
 
	Box_CreateWndCustom(dialog, _("About Chesspark"), NULL);

	BringWindowToTop(dialog->hwnd);

	return dialog;
}
Esempio n. 18
0
LRESULT W_CALLBACK SliderWndProc(HWND hWnd, UINT msg, 
				 WPARAM wParam, LPARAM lParam)
{
    HWND hSBWnd;
    LONG lResult;
    ITEMID idWidget, idVertical, idMin = NULLID, idMax = NULLID;
    ITEMID idDesc, idVisible;
    double fMinV, fMaxV, fValue;
    RECT rCrect;
    double dSliderPos;
    BOOL bCommand = TRUE;
    short nTextHgt, nTitleHgt, nSlideHgt, nSlideLeft;

    switch (msg) {
      case WM_SETFOCUS:
          hSBWnd = GetDlgItem(hWnd, HSLIDERID);
          if (!hSBWnd)
              hSBWnd = GetDlgItem(hWnd, VSLIDERID);
          if (hSBWnd)
              SetFocus(hSBWnd);
          break;

      case WM_HSCROLL:
          hSBWnd = GetDlgItem(hWnd, HSLIDERID);
		  SetFocus(hSBWnd);
          idWidget = KpsGetWidgetFromWindow(hWnd);

          if (hSBWnd)
              dSliderPos = (double) GetScrollPos(hSBWnd, SB_CTL);

          switch (wParam) {
            case SB_LINEUP:
                break;

            case SB_LINEDOWN:
                break;

            case SB_PAGEUP:
                dSliderPos -= 1000;
                break;

            case SB_PAGEDOWN:
                dSliderPos += 1000;
                break;

            case SB_THUMBTRACK:
            case SB_THUMBPOSITION:
                dSliderPos = LOWORD(lParam);
                break;

            default:
                bCommand = FALSE;
                break;
          }
          if (bCommand)
          {
              if (dSliderPos > 10000.0)
                  dSliderPos = 10000.0;
              if (dSliderPos < 0.0)
                  dSliderPos = 0.0;

              GetSliderValue(idWidget, hWnd, wParam, dSliderPos);
          }
          break;
      case WM_VSCROLL:
          hSBWnd = GetDlgItem(hWnd, VSLIDERID);
		  SetFocus(hSBWnd);
          idWidget = KpsGetWidgetFromWindow(hWnd);

          if (hSBWnd)
              dSliderPos = (double) GetScrollPos(hSBWnd, SB_CTL);

          switch (wParam){
            case SB_LINEUP:
                break;
            case SB_LINEDOWN:
                break;
            case SB_PAGEUP:
                dSliderPos -= 1000;
                break;
            case SB_PAGEDOWN:
                dSliderPos += 1000;
                break;
            case SB_THUMBTRACK:
            case SB_THUMBPOSITION:
                dSliderPos = (short) LOWORD(lParam);
                break;

            default:
                bCommand = FALSE;
                break;
          }
          if (bCommand)
          {
              if (dSliderPos < -10000.0)
                  dSliderPos = -10000.0;
              if (dSliderPos > 0.0)
                  dSliderPos = 0.0;

              GetSliderValue(idWidget, hWnd, wParam, dSliderPos);
          }
          break;

      case IDG_RESET:
          idWidget = KpsGetWidgetFromWindow(hWnd);
          idVisible = KppGetSlotValue(idWidget, lpSNs->idVisibleSN);
          if (idVisible != lpIDs->idFalse)
          {
              GetClientRect(hWnd, (LPRECT) & rCrect);
              nSlideLeft = (rCrect.right / 2) - (SLIDERPAD / 2);
              GetSliderParam(hWnd, &nTitleHgt, &nTextHgt, &nSlideHgt);
              idVertical = KppGetSlotValue(idWidget, lpSNs->idVerticalSN);

              if (RetrieveSliderData(idWidget, &idMin, &idMax,
                                     (ITEMID *) NULL,
                                     &fMinV, &fMaxV, &fValue, &idDesc))
              {
                  if (idVertical == lpIDs->idTrue)
                  {
                      hSBWnd = GetDlgItem(hWnd, HSLIDERID);
                      if (hSBWnd)
                          DestroyWindow(hSBWnd);

                      hSBWnd = GetDlgItem(hWnd, VSLIDERID);
                      if (!hSBWnd)
                      {
                          hSBWnd = CreateWindow((LPSTR) "Scrollbar",
                                                (LPSTR) NULL,
                                                WS_CHILD | WS_CLIPSIBLINGS |
                                                SBS_VERT,
                                                nSlideLeft,
                                                nTitleHgt + (2 * HEIGHTPAD),
                                                SLIDERPAD, nSlideHgt,
                                                hWnd, VSLIDERID,
                                                hInstThisDll, (LPSTR) NULL);
                          SetScrollRange(hSBWnd, SB_CTL, -10000, 0, TRUE);
                          SetScrollPos(hSBWnd, SB_CTL, 0, TRUE);
                          ShowWindow(hSBWnd, SW_HIDE);
						  SetProp(hSBWnd, HORIZONTAL, FALSE); 

                          if (!lpOrigSliderProc)
                              lpOrigSliderProc =
                                  (FARPROC) GetClassLong(hSBWnd, GCL_WNDPROC);

                          SetWindowLong(hSBWnd, GWL_WNDPROC,
                                        (LONG) NewSliderProc);
                      }
                      else
                          MoveWindow(hSBWnd, nSlideLeft,
                                     nTitleHgt + (2 * HEIGHTPAD),
                                     SLIDERPAD, nSlideHgt, TRUE);
                  }
                  else
                  {
                      hSBWnd = GetDlgItem(hWnd, VSLIDERID);
                      if (hSBWnd)
                          DestroyWindow(hSBWnd);

                      hSBWnd = GetDlgItem(hWnd, HSLIDERID);
                      if (!hSBWnd)
                      {
                          hSBWnd = CreateWindow((LPSTR) "Scrollbar",
                                                (LPSTR) NULL,
                                                WS_CHILD | WS_CLIPSIBLINGS |
                                                SBS_HORZ,
                                                SLIDERPAD,
                                                nTitleHgt + (2 * HEIGHTPAD),
                                                rCrect.right - (2 * SLIDERPAD),
                                                nSlideHgt,
                                                hWnd, HSLIDERID,
                                                hInstThisDll, (LPSTR) NULL);
                          SetScrollRange(hSBWnd, SB_CTL, 0, 10000, TRUE);
                          ShowWindow(hSBWnd, SW_HIDE);
						  SetProp(hSBWnd, HORIZONTAL, TRUE); 

                          if (!lpOrigSliderProc)
                              lpOrigSliderProc =
                                  (FARPROC) GetClassLong(hSBWnd, GCL_WNDPROC);

                          SetWindowLong(hSBWnd, GWL_WNDPROC,
                                        (LONG) NewSliderProc);
                      }
                      else
                          MoveWindow(hSBWnd, SLIDERPAD, nTitleHgt + (2 * HEIGHTPAD),
                           rCrect.right - (2 * SLIDERPAD), nSlideHgt, TRUE);
                  }
              }
              BringWindowToTop(hWnd);
              hSBWnd = GetDlgItem(hWnd, HSLIDERID);
              if (!hSBWnd)
                  hSBWnd = GetDlgItem(hWnd, VSLIDERID);
              if (hSBWnd)
                  ShowWindow(hSBWnd, SW_SHOW);
          }
          InvalidateRect(hWnd, (LPRECT) NULL, TRUE);
          UpdateWindow(hWnd);
          return (LONG) TRUE;

      case WM_SIZE:
          if (wParam == SIZENORMAL)
              KpsSizeWidget(hWnd, LOWORD(lParam), HIWORD(lParam));
          GetClientRect(hWnd, (LPRECT) &rCrect);
          GetSliderParam(hWnd, &nTitleHgt, &nTextHgt, &nSlideHgt);

          hSBWnd = GetDlgItem(hWnd, VSLIDERID);
          if (hSBWnd != NULL)
          {
              nSlideLeft = (rCrect.right / 2) - (SLIDERPAD / 2);
              MoveWindow(hSBWnd, nSlideLeft, nTitleHgt + (2 * HEIGHTPAD),
                         SLIDERPAD, nSlideHgt, TRUE);
          }
          else
          {
              hSBWnd = GetDlgItem(hWnd, HSLIDERID);
              if (hSBWnd)
              {
                  MoveWindow(hSBWnd, SLIDERPAD, nTitleHgt + (2 * HEIGHTPAD),
                           rCrect.right - (2 * SLIDERPAD), nSlideHgt, TRUE);
              }
          }
          break;

      case WM_PAINT:
          lResult = (LONG) KpsDrawWidget(hWnd);
          hSBWnd = GetDlgItem(hWnd, VSLIDERID);
          if (!hSBWnd)
              hSBWnd = GetDlgItem(hWnd, HSLIDERID);
          if (hSBWnd)
          {
              InvalidateRect(hSBWnd, (LPRECT) NULL, TRUE);
              UpdateWindow(hSBWnd);
          }

          return (LONG) lResult;

      default:
          break;
    }

    return DefWindowProc(hWnd, msg, wParam, lParam);
}
Esempio n. 19
0
static BOOL guiOnCreate(HWND hwnd, LPCREATESTRUCT lpCreateStruct)
{
	ghwndConsole = CreateWindowEx(
		0,
		RICHEDIT_CLASS,
		NULL,
		WS_CHILD|WS_VISIBLE|ES_READONLY|ES_MULTILINE|WS_VSCROLL|WS_HSCROLL|ES_NOHIDESEL,
		0, 0,
		0, 0,
		hwnd,
		0,
		0,
		NULL);
	
	if(!ghwndConsole) return FALSE;
	
	gui.hwndUsers = CreateWindowEx(
		WS_EX_CLIENTEDGE,
		"LISTBOX",
		NULL,
		WS_CHILD|WS_VISIBLE|LBS_STANDARD|LBS_NOINTEGRALHEIGHT,
		0, 0,
		0, 0,
		hwnd,
		0,
		0,
		NULL);
	
	if(!gui.hwndUsers) return FALSE;
	
	//amadeo: temp. button for useredit until rightcklick is working....
	gui.hwndUserEditButton = CreateWindow(
		"button",
		"Edit User Status",
		WS_CHILD | WS_VISIBLE | ES_LEFT,
		0, 0,
		0, 0,
		hwnd,
		(HMENU) 881,
		0,
		NULL) ;
	
	if(!gui.hwndUserEditButton) return FALSE;
	
	gui.hwndUserCount = CreateWindowEx(
		WS_EX_CLIENTEDGE,
		"edit",
		" 0 user(s) online:",
		WS_CHILD|WS_VISIBLE|ES_CENTER|ES_READONLY,
		0, 0,
		0, 0,
		hwnd,
		0,
		0,
		NULL);
	
	if(!gui.hwndUserCount) return FALSE;
	
	SendMessage(gui.hwndUserCount, WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),0);
	SendMessage(gui.hwndUsers, WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),0);
	SendMessage(gui.hwndUserEditButton, WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT),0);
	BringWindowToTop(gui.hwndUsers);
	strcpy( gui.szDefaultStatus, "Void" );
	
	gui.y_ratio = (100<<10)/100;
	gui.x_ratio = (0<<10)/100;
	
	return TRUE;
}
Esempio n. 20
0
int WINAPI WinMain(HINSTANCE _hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow)
{
	setCurrentThreadName("Main");

	CoInitializeEx(NULL, COINIT_MULTITHREADED);

	PROFILE_INIT();

	// FMA3 support in the 2013 CRT is broken on Vista and Windows 7 RTM (fixed in SP1). Just disable it.
#ifdef _M_X64
	_set_FMA3_enable(0);
#endif

	EnableCrashingOnCrashes();

	wchar_t modulePath[MAX_PATH];
	GetModuleFileName(NULL, modulePath, MAX_PATH);
	for (size_t i = wcslen(modulePath) - 1; i > 0; i--) {
		if (modulePath[i] == '\\') {
			modulePath[i] = 0;
			break;
		}
	}
	SetCurrentDirectory(modulePath);
	// GetCurrentDirectory(MAX_PATH, modulePath);  // for checking in the debugger

#ifndef _DEBUG
	bool showLog = false;
#else
	bool showLog = false;
#endif

	VFSRegister("", new DirectoryAssetReader("assets/"));
	VFSRegister("", new DirectoryAssetReader(""));

	wchar_t lcCountry[256];

	// LOCALE_SNAME is only available in WinVista+
	// Really should find a way to do this in XP too :/
	if (0 != GetLocaleInfo(LOCALE_NAME_USER_DEFAULT, LOCALE_SNAME, lcCountry, 256)) {
		langRegion = ConvertWStringToUTF8(lcCountry);
		for (size_t i = 0; i < langRegion.size(); i++) {
			if (langRegion[i] == '-')
				langRegion[i] = '_';
		}
	} else {
		langRegion = "en_US";
	}

	osName = GetWindowsVersion() + " " + GetWindowsSystemArchitecture();

	char configFilename[MAX_PATH] = { 0 };
	const std::wstring configOption = L"--config=";

	char controlsConfigFilename[MAX_PATH] = { 0 };
	const std::wstring controlsOption = L"--controlconfig=";

	std::vector<std::wstring> wideArgs = GetWideCmdLine();

	for (size_t i = 1; i < wideArgs.size(); ++i) {
		if (wideArgs[i][0] == L'\0')
			continue;
		if (wideArgs[i][0] == L'-') {
			if (wideArgs[i].find(configOption) != std::wstring::npos && wideArgs[i].size() > configOption.size()) {
				const std::wstring tempWide = wideArgs[i].substr(configOption.size());
				const std::string tempStr = ConvertWStringToUTF8(tempWide);
				std::strncpy(configFilename, tempStr.c_str(), MAX_PATH);
			}

			if (wideArgs[i].find(controlsOption) != std::wstring::npos && wideArgs[i].size() > controlsOption.size()) {
				const std::wstring tempWide = wideArgs[i].substr(controlsOption.size());
				const std::string tempStr = ConvertWStringToUTF8(tempWide);
				std::strncpy(controlsConfigFilename, tempStr.c_str(), MAX_PATH);
			}
		}
	}

	// On Win32 it makes more sense to initialize the system directories here 
	// because the next place it was called was in the EmuThread, and it's too late by then.
	InitSysDirectories();

	// Load config up here, because those changes below would be overwritten
	// if it's not loaded here first.
	g_Config.AddSearchPath("");
	g_Config.AddSearchPath(GetSysDirectory(DIRECTORY_SYSTEM));
	g_Config.SetDefaultPath(GetSysDirectory(DIRECTORY_SYSTEM));
	g_Config.Load(configFilename, controlsConfigFilename);

	bool debugLogLevel = false;

	const std::wstring gpuBackend = L"--graphics=";

	// The rest is handled in NativeInit().
	for (size_t i = 1; i < wideArgs.size(); ++i) {
		if (wideArgs[i][0] == L'\0')
			continue;

		if (wideArgs[i][0] == L'-') {
			switch (wideArgs[i][1]) {
			case L'l':
				showLog = true;
				g_Config.bEnableLogging = true;
				break;
			case L's':
				g_Config.bAutoRun = false;
				g_Config.bSaveSettings = false;
				break;
			case L'd':
				debugLogLevel = true;
				break;
			}

			if (wideArgs[i] == L"--fullscreen")
				g_Config.bFullScreen = true;

			if (wideArgs[i] == L"--windowed")
				g_Config.bFullScreen = false;

			if (wideArgs[i].find(gpuBackend) != std::wstring::npos && wideArgs[i].size() > gpuBackend.size()) {
				const std::wstring restOfOption = wideArgs[i].substr(gpuBackend.size());

				// Force software rendering off, as picking directx9 or gles implies HW acceleration.
				// Once software rendering supports Direct3D9/11, we can add more options for software,
				// such as "software-gles", "software-d3d9", and "software-d3d11", or something similar.
				// For now, software rendering force-activates OpenGL.
				if (restOfOption == L"directx9") {
					g_Config.iGPUBackend = GPU_BACKEND_DIRECT3D9;
					g_Config.bSoftwareRendering = false;
				}
				else if (restOfOption == L"gles") {
					g_Config.iGPUBackend = GPU_BACKEND_OPENGL;
					g_Config.bSoftwareRendering = false;
				}
				
				else if (restOfOption == L"software") {
					g_Config.iGPUBackend = GPU_BACKEND_OPENGL;
					g_Config.bSoftwareRendering = true;
				}
			}
		}
	}
#ifdef _DEBUG
	g_Config.bEnableLogging = true;
#endif

	LogManager::Init();
	// Consider at least the following cases before changing this code:
	//   - By default in Release, the console should be hidden by default even if logging is enabled.
	//   - By default in Debug, the console should be shown by default.
	//   - The -l switch is expected to show the log console, REGARDLESS of config settings.
	//   - It should be possible to log to a file without showing the console.
	LogManager::GetInstance()->GetConsoleListener()->Init(showLog, 150, 120, "PPSSPP Debug Console");
	
	if (debugLogLevel)
		LogManager::GetInstance()->SetAllLogLevels(LogTypes::LDEBUG);

	//Windows, API init stuff
	INITCOMMONCONTROLSEX comm;
	comm.dwSize = sizeof(comm);
	comm.dwICC = ICC_BAR_CLASSES | ICC_LISTVIEW_CLASSES | ICC_TAB_CLASSES;
	InitCommonControlsEx(&comm);
	timeBeginPeriod(1);
	MainWindow::Init(_hInstance);

	g_hPopupMenus = LoadMenu(_hInstance, (LPCWSTR)IDR_POPUPMENUS);

	MainWindow::Show(_hInstance);

	HWND hwndMain = MainWindow::GetHWND();
	HWND hwndDisplay = MainWindow::GetDisplayHWND();
	
	//initialize custom controls
	CtrlDisAsmView::init();
	CtrlMemView::init();
	CtrlRegisterList::init();
	CGEDebugger::Init();

	DialogManager::AddDlg(vfpudlg = new CVFPUDlg(_hInstance, hwndMain, currentDebugMIPS));

	host = new WindowsHost(hwndMain, hwndDisplay);
	host->SetWindowTitle(0);

	MainWindow::CreateDebugWindows();

	// Emu thread is always running!
	EmuThread_Start();
	InputDevice::BeginPolling();

	HACCEL hAccelTable = LoadAccelerators(_hInstance, (LPCTSTR)IDR_ACCELS);
	HACCEL hDebugAccelTable = LoadAccelerators(_hInstance, (LPCTSTR)IDR_DEBUGACCELS);

	//so.. we're at the message pump of the GUI thread
	for (MSG msg; GetMessage(&msg, NULL, 0, 0); )	// for no quit
	{
		if (msg.message == WM_KEYDOWN)
		{
			//hack to enable/disable menu command accelerate keys
			MainWindow::UpdateCommands();

			//hack to make it possible to get to main window from floating windows with Esc
			if (msg.hwnd != hwndMain && msg.wParam == VK_ESCAPE)
				BringWindowToTop(hwndMain);
		}

		//Translate accelerators and dialog messages...
		HWND wnd;
		HACCEL accel;
		switch (g_activeWindow)
		{
		case WINDOW_MAINWINDOW:
			wnd = hwndMain;
			accel = hAccelTable;
			break;
		case WINDOW_CPUDEBUGGER:
			wnd = disasmWindow[0] ? disasmWindow[0]->GetDlgHandle() : 0;
			accel = hDebugAccelTable;
			break;
		case WINDOW_GEDEBUGGER:
		default:
			wnd = 0;
			accel = 0;
			break;
		}

		if (!TranslateAccelerator(wnd, accel, &msg))
		{
			if (!DialogManager::IsDialogMessage(&msg))
			{
				//and finally translate and dispatch
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}
	}

	VFSShutdown();

	InputDevice::StopPolling();
	EmuThread_Stop();

	MainWindow::DestroyDebugWindows();
	DialogManager::DestroyAll();
	timeEndPeriod(1);
	delete host;

	// Is there a safer place to do this?
	// Doing this in Config::Save requires knowing if the UI state is UISTATE_EXIT,
	// but that causes UnitTest to fail linking with 400 errors if System.h is included..
	if (g_Config.iTempGPUBackend != g_Config.iGPUBackend) {
		g_Config.iGPUBackend = g_Config.iTempGPUBackend;

		// For now, turn off software rendering too, similar to the command-line.
		g_Config.bSoftwareRendering = false;
	}

	g_Config.Save();
	LogManager::Shutdown();

	if (g_Config.bRestartRequired) {
		W32Util::ExitAndRestart();
	}
	CoUninitialize();
	return 0;
}
Esempio n. 21
0
*/	DEVICE_CMD Open_IO(REBREQ *req)
/*
***********************************************************************/
{
    REBDEV *dev;
    REBCHR *title = TEXT("REBOL 3 Alpha");
    HANDLE win;

    dev = Devices[req->device];

    // Avoid opening the console twice (compare dev and req flags):
    if (GET_FLAG(dev->flags, RDF_OPEN)) {
        // Device was opened earlier as null, so req must have that flag:
        if (GET_FLAG(dev->flags, SF_DEV_NULL))
            SET_FLAG(req->modes, RDM_NULL);
        SET_FLAG(req->flags, RRF_OPEN);
        return DR_DONE; // Do not do it again
    }

    if (!GET_FLAG(req->modes, RDM_NULL)) {

        // Get the raw stdio handles:
        Std_Out = GetStdHandle(STD_OUTPUT_HANDLE);
        Std_Inp = GetStdHandle(STD_INPUT_HANDLE);
        //Std_Err = GetStdHandle(STD_ERROR_HANDLE);
        Std_Echo = 0;

        Redir_Out = (GetFileType(Std_Out) != 0);
        Redir_Inp = (GetFileType(Std_Inp) != 0);

        // attach_console();  // merges streams, not good

        // If output not redirected, open a console:
        if (!Redir_Out) {
            if (!AllocConsole()) {
                req->error = GetLastError();
                return DR_ERROR;
            }

            SetConsoleTitle(title);

            // The goof-balls at MS seem to require this:
            // See: http://support.microsoft.com/kb/124103
            Sleep(40);
            win = FindWindow(NULL, title); // What if more than one open ?!
            if (win) {
                SetForegroundWindow(win);
                BringWindowToTop(win);
            }

            // Get the new stdio handles:
            Std_Out = GetStdHandle(STD_OUTPUT_HANDLE);

            if (!Redir_Inp)	{
                Std_Inp = GetStdHandle(STD_INPUT_HANDLE);
                // Make the Win32 console a bit smarter by default:
                SetConsoleMode(Std_Inp, CONSOLE_MODES);
            }
        }

        Std_Buf = OS_Make(BUF_SIZE * sizeof(REBCHR));

        // Handle stdio CTRL-C interrupt:
        SetConsoleCtrlHandler(Handle_Break, TRUE);
    }
    else
        SET_FLAG(dev->flags, SF_DEV_NULL);

    SET_FLAG(req->flags, RRF_OPEN);
    SET_FLAG(dev->flags, RDF_OPEN);

    return DR_DONE;
}
Esempio n. 22
0
MStatus preview(const MArgList& args,bool useVertexColor)
{
	//单实例先清除
	if(MaterialSet::getSingletonPtr())
		MaterialSet::getSingletonPtr()->clear();

	char tempPath[MAX_PATH];
	GetTempPath(MAX_PATH, tempPath);
	std::string tempFileName(tempPath);
	ExportOptions::instance().m_outFilePath = tempFileName.c_str();
	tempFileName += "\\";
	tempFileName += _T("maya.mz");

	ExportOptions::instance().m_outFile = tempFileName.c_str();

	ExportOptions::instance().clipList.clear();
	MTime kTimeMin   = MAnimControl::animationStartTime();		//整个场景的起始帧
	MTime kTimeMax   = MAnimControl::animationEndTime();		//整个场景的结束帧

	clipInfo clip;
	clip.name = "Animation";
	clip.startFrame = (int)kTimeMin.value();
	clip.endFrame = (int)kTimeMax.value();
	clip.stepFrame = 1;
	ExportOptions::instance().clipList.push_back(clip);
	ExportOptions::instance().exportAnims = true;
	ExportOptions::instance().exportVertexColour = useVertexColor;

	/*BindPoseTool bindPoseTool;
	bindPoseTool.GoIntoBindPose();*/

	MWriter writer;
	writer.read();
	MStatus status = writer.write();

#ifdef RELEASEDEBUG
#define DLL_NAME "MayaPreview_rd.exe"
#elif _DEBUG
#define DLL_NAME "MayaPreview_d.exe"
#else
#define DLL_NAME "MayaPreview.exe"
#endif

	if(status == MS::kSuccess)
	{
		HWND hWnd = FindWindowEx(0,0,0,"MayaPreview");
		//if(hWnd)
		//{
		//	SendMessage(hWnd,WM_CLOSE,0,0);
		//	hWnd = 0;
		//}
		if(!hWnd)
		{
			static const std::string tMaxProgramName("Maya.exe");
			char path[257];
			GetModuleFileName(GetModuleHandle(tMaxProgramName.c_str()),path,256);
			std::string parentPath(path);
			parentPath.erase(parentPath.size() - tMaxProgramName.size(), tMaxProgramName.size());
			std::string previewProgramPath(parentPath + "preview\\" + DLL_NAME); 
			
			if(!ShellExecute(0,"open",previewProgramPath.c_str(),"","",SW_SHOW))
			{

				MessageBox(0,previewProgramPath.c_str(),"Can't Find MayaPreview Program",0);
				return MS::kFailure;
			}			
			hWnd = FindWindowEx(0,0,0,"MayaPreview");
			DWORD tick = GetTickCount();
			while(!hWnd)
			{
				DWORD tickNow = GetTickCount();
				if(tickNow - tick > 3000)break;
				Sleep(1);
				hWnd = FindWindowEx(0,0,0,"MayaPreview");
			}
		}
		if(hWnd)
		{
			SendMessage(hWnd,WM_USER + 128,0,0);
			SetActiveWindow(hWnd);
			SetForegroundWindow(hWnd);
			BringWindowToTop(hWnd);
		}
	}
	/*bindPoseTool	.UndoGoIntoBindPose();*/

	return MS::kSuccess;
}
Esempio n. 23
0
bool CBrowseRefsDlg::DoDeleteRef(CString completeRefName, bool bForce)
{
	bool bIsRemoteBranch = false;
	bool bIsBranch = false;
	if		(wcsncmp(completeRefName, L"refs/remotes/",13) == 0)	{bIsBranch = true; bIsRemoteBranch = true;}
	else if	(wcsncmp(completeRefName, L"refs/heads/",11) == 0)		{bIsBranch = true;}

	if(bIsBranch)
	{
		CString branchToDelete = completeRefName.Mid(bIsRemoteBranch ? 13 : 11);
		CString cmd;
		if(bIsRemoteBranch)
		{
			CString remoteName, remoteBranchToDelete;
			if (SplitRemoteBranchName(branchToDelete, remoteName, remoteBranchToDelete))
				return false;

			if(CAppUtils::IsSSHPutty())
			{
				CAppUtils::LaunchPAgent(NULL, &remoteName);
			}

			cmd.Format(L"git.exe push \"%s\" :refs/heads/%s", remoteName, remoteBranchToDelete);
		}
		else
			cmd.Format(L"git.exe branch -%c -- %s",bForce?L'D':L'd',branchToDelete);
		CSysProgressDlg sysProgressDlg;
		if (bIsRemoteBranch)
		{
			sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
			sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_DELETING_REMOTE_REFS)));
			sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
			sysProgressDlg.SetShowProgressBar(false);
			sysProgressDlg.ShowModal(this, true);
		}
		CString errorMsg;
		if(g_Git.Run(cmd,&errorMsg,CP_UTF8)!=0)
		{
			CMessageBox::Show(m_hWnd, errorMsg, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
			if (bIsRemoteBranch)
				sysProgressDlg.Stop();
			BringWindowToTop();
			return false;
		}
		if (bIsRemoteBranch)
			sysProgressDlg.Stop();
		BringWindowToTop();
	}
	else if (wcsncmp(completeRefName, L"refs/tags/", 10) == 0)
	{
		CString tagToDelete = completeRefName.Mid(10);
		CString cmd;
		cmd.Format(L"git.exe tag -d -- %s",tagToDelete);
		CString errorMsg;
		if(g_Git.Run(cmd,&errorMsg,CP_UTF8)!=0)
		{
			CMessageBox::Show(m_hWnd, errorMsg, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
			return false;
		}
	}
	return true;
}
Esempio n. 24
0
int SimulatorWin::run()
{
    INITCOMMONCONTROLSEX InitCtrls;
    InitCtrls.dwSize = sizeof(InitCtrls);
    InitCtrls.dwICC = ICC_WIN95_CLASSES;
    InitCommonControlsEx(&InitCtrls);

    parseCocosProjectConfig(_project);

    // load project config from command line args
    vector<string> args;
    for (int i = 0; i < __argc; ++i)
    {
        wstring ws(__wargv[i]);
        string s;
        s.assign(ws.begin(), ws.end());
        args.push_back(s);
    }
    _project.parseCommandLine(args);

    if (_project.getProjectDir().empty())
    {
        if (args.size() == 2)
        {
            // for Code IDE before RC2
            _project.setProjectDir(args.at(1));
            _project.setDebuggerType(kCCRuntimeDebuggerCodeIDE);
        }
    }

    // create the application instance
    _app = new AppDelegate();
    RuntimeEngine::getInstance()->setProjectConfig(_project);

#if (SIMULATOR_WITH_CONSOLE_AND_MENU > 0)
    // create console window
    if (_project.isShowConsole())
    {
        AllocConsole();
        _hwndConsole = GetConsoleWindow();
        if (_hwndConsole != NULL)
        {
            ShowWindow(_hwndConsole, SW_SHOW);
            BringWindowToTop(_hwndConsole);
            freopen("CONOUT$", "wt", stdout);
            freopen("CONOUT$", "wt", stderr);

            HMENU hmenu = GetSystemMenu(_hwndConsole, FALSE);
            if (hmenu != NULL)
            {
                DeleteMenu(hmenu, SC_CLOSE, MF_BYCOMMAND);
            }
        }
    }
#endif

    // log file
    if (_project.isWriteDebugLogToFile())
    {
        const string debugLogFilePath = _project.getDebugLogFilePath();
        _writeDebugLogFile = fopen(debugLogFilePath.c_str(), "w");
        if (!_writeDebugLogFile)
        {
            CCLOG("Cannot create debug log file %s", debugLogFilePath.c_str());
        }
    }

    // set environments
    SetCurrentDirectoryA(_project.getProjectDir().c_str());
    FileUtils::getInstance()->setDefaultResourceRootPath(_project.getProjectDir());
    FileUtils::getInstance()->setWritablePath(_project.getWritableRealPath().c_str());

    // check screen DPI
    HDC screen = GetDC(0);
    int dpi = GetDeviceCaps(screen, LOGPIXELSX);
    ReleaseDC(0, screen);

    // set scale with DPI
    //  96 DPI = 100 % scaling
    // 120 DPI = 125 % scaling
    // 144 DPI = 150 % scaling
    // 192 DPI = 200 % scaling
    // http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#dpi_and_the_desktop_scaling_factor
    //
    // enable DPI-Aware with DeclareDPIAware.manifest
    // http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#declaring_dpi_awareness
    float screenScale = 1.0f;
    if (dpi >= 120 && dpi < 144)
    {
        screenScale = 1.25f;
    }
    else if (dpi >= 144 && dpi < 192)
    {
        screenScale = 1.5f;
    }
    else if (dpi >= 192)
    {
        screenScale = 2.0f;
    }
    CCLOG("SCREEN DPI = %d, SCREEN SCALE = %0.2f", dpi, screenScale);

    // create opengl view
    Size frameSize = _project.getFrameSize();
    float frameScale = 1.0f;
    if (_project.isRetinaDisplay())
    {
        frameSize.width *= screenScale;
        frameSize.height *= screenScale;
    }
    else
    {
        frameScale = screenScale;
    }

    const Rect frameRect = Rect(0, 0, frameSize.width, frameSize.height);
    ConfigParser::getInstance()->setInitViewSize(frameSize);
    const bool isResize = _project.isResizeWindow();
    std::stringstream title;
    title << "Cocos Simulator - " << ConfigParser::getInstance()->getInitViewName();
    initGLContextAttrs();
    auto glview = GLViewImpl::createWithRect(title.str(), frameRect, frameScale);
    _hwnd = glview->getWin32Window();
    player::PlayerWin::createWithHwnd(_hwnd);
    DragAcceptFiles(_hwnd, TRUE);
    //SendMessage(_hwnd, WM_SETICON, ICON_BIG, (LPARAM)icon);
    //SendMessage(_hwnd, WM_SETICON, ICON_SMALL, (LPARAM)icon);
    //FreeResource(icon);

    auto director = Director::getInstance();
    director->setOpenGLView(glview);

    director->setAnimationInterval(1.0 / 60.0);

    // set window position
    if (_project.getProjectDir().length())
    {
        setZoom(_project.getFrameScale());
    }
    Vec2 pos = _project.getWindowOffset();
    if (pos.x != 0 && pos.y != 0)
    {
        RECT rect;
        GetWindowRect(_hwnd, &rect);
        MoveWindow(_hwnd, pos.x, pos.y, rect.right - rect.left, rect.bottom - rect.top, FALSE);
    }

    // path for looking Lang file, Studio Default images
    FileUtils::getInstance()->addSearchPath(getApplicationPath().c_str());

#if SIMULATOR_WITH_CONSOLE_AND_MENU > 0
    // init player services
    setupUI();
    DrawMenuBar(_hwnd);
#endif

    // prepare
    FileUtils::getInstance()->setPopupNotify(false);
    _project.dump();
    auto app = Application::getInstance();

    g_oldWindowProc = (WNDPROC)SetWindowLong(_hwnd, GWL_WNDPROC, (LONG)SimulatorWin::windowProc);

    // startup message loop
    return app->run();
}
Esempio n. 25
0
static void TaskManager_OnTabWndSelChange(void)
{
    int   i;
    HMENU hMenu;
    HMENU hOptionsMenu;
    HMENU hViewMenu;
    HMENU hSubMenu;

    WCHAR wszLargeIcons[255];
    WCHAR wszSmallIcons[255];
    WCHAR wszDetails[255];
    WCHAR wszWindows[255];
    WCHAR wszSelectColumns[255];
    WCHAR wszShow16bTasks[255];
    WCHAR wszOneGraphAllCPU[255];
    WCHAR wszOneGraphPerCPU[255];
    WCHAR wszCPUHistory[255];
    WCHAR wszShowKernelTimes[255];

    LoadStringW(hInst, IDS_VIEW_LARGE, wszLargeIcons, sizeof(wszLargeIcons)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_VIEW_SMALL, wszSmallIcons, sizeof(wszSmallIcons)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_VIEW_DETAILS, wszDetails, sizeof(wszDetails)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_WINDOWS, wszWindows, sizeof(wszWindows)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_VIEW_SELECTCOLUMNS, wszSelectColumns, sizeof(wszSelectColumns)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_OPTIONS_SHOW16BITTASKS, wszShow16bTasks, sizeof(wszShow16bTasks)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_VIEW_CPUHISTORY_ONEGRAPHALL, wszOneGraphAllCPU, sizeof(wszOneGraphAllCPU)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_VIEW_CPUHISTORY_ONEGRAPHPERCPU, wszOneGraphPerCPU, sizeof(wszOneGraphPerCPU)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_VIEW_CPUHISTORY, wszCPUHistory, sizeof(wszCPUHistory)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_VIEW_SHOWKERNELTIMES, wszShowKernelTimes, sizeof(wszShowKernelTimes)/sizeof(WCHAR));

    hMenu = GetMenu(hMainWnd);
    hViewMenu = GetSubMenu(hMenu, 2);
    hOptionsMenu = GetSubMenu(hMenu, 1);
    TaskManagerSettings.ActiveTabPage = TabCtrl_GetCurSel(hTabWnd);
    for (i = GetMenuItemCount(hViewMenu) - 1; i > 2; i--) {
        hSubMenu = GetSubMenu(hViewMenu, i);
        if (hSubMenu)
            DestroyMenu(hSubMenu);
        RemoveMenu(hViewMenu, i, MF_BYPOSITION);
    }
    RemoveMenu(hOptionsMenu, 3, MF_BYPOSITION);
    switch (TaskManagerSettings.ActiveTabPage) {
    case 0:
        ShowWindow(hApplicationPage, SW_SHOW);
        ShowWindow(hProcessPage, SW_HIDE);
        ShowWindow(hPerformancePage, SW_HIDE);
        BringWindowToTop(hApplicationPage);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_LARGE, wszLargeIcons);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_SMALL, wszSmallIcons);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_DETAILS, wszDetails);

        if (GetMenuItemCount(hMenu) <= 4) {
            hSubMenu = LoadMenuW(hInst, MAKEINTRESOURCEW(IDR_WINDOWSMENU));
            InsertMenuW(hMenu, 3, MF_BYPOSITION|MF_POPUP, (UINT_PTR)hSubMenu, wszWindows);
            DrawMenuBar(hMainWnd);
        }
        if (TaskManagerSettings.View_LargeIcons)
            CheckMenuRadioItem(hViewMenu, ID_VIEW_LARGE, ID_VIEW_DETAILS, ID_VIEW_LARGE, MF_BYCOMMAND);
        else if (TaskManagerSettings.View_SmallIcons)
            CheckMenuRadioItem(hViewMenu, ID_VIEW_LARGE, ID_VIEW_DETAILS, ID_VIEW_SMALL, MF_BYCOMMAND);
        else
            CheckMenuRadioItem(hViewMenu, ID_VIEW_LARGE, ID_VIEW_DETAILS, ID_VIEW_DETAILS, MF_BYCOMMAND);
        /*
         * Give the application list control focus
         */
        SetFocus(hApplicationPageListCtrl);
        break;

    case 1:
        ShowWindow(hApplicationPage, SW_HIDE);
        ShowWindow(hProcessPage, SW_SHOW);
        ShowWindow(hPerformancePage, SW_HIDE);
        BringWindowToTop(hProcessPage);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_SELECTCOLUMNS, wszSelectColumns);
        AppendMenuW(hOptionsMenu, MF_STRING, ID_OPTIONS_SHOW16BITTASKS, wszShow16bTasks);
        if (TaskManagerSettings.Show16BitTasks)
            CheckMenuItem(hOptionsMenu, ID_OPTIONS_SHOW16BITTASKS, MF_BYCOMMAND|MF_CHECKED);
        if (GetMenuItemCount(hMenu) > 4)
        {
            RemoveMenu(hMenu, 3, MF_BYPOSITION);
            DrawMenuBar(hMainWnd);
        }
        /*
         * Give the process list control focus
         */
        SetFocus(hProcessPageListCtrl);
        break;

    case 2:
        ShowWindow(hApplicationPage, SW_HIDE);
        ShowWindow(hProcessPage, SW_HIDE);
        ShowWindow(hPerformancePage, SW_SHOW);
        BringWindowToTop(hPerformancePage);
        if (GetMenuItemCount(hMenu) > 4) {
            RemoveMenu(hMenu, 3, MF_BYPOSITION);
            DrawMenuBar(hMainWnd);
        }
        hSubMenu = CreatePopupMenu();
        AppendMenuW(hSubMenu, MF_STRING, ID_VIEW_CPUHISTORY_ONEGRAPHALL, wszOneGraphAllCPU);
        AppendMenuW(hSubMenu, MF_STRING, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, wszOneGraphPerCPU);
        AppendMenuW(hViewMenu, MF_STRING|MF_POPUP, (UINT_PTR)hSubMenu, wszCPUHistory);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_SHOWKERNELTIMES, wszShowKernelTimes);
        if (TaskManagerSettings.ShowKernelTimes)
            CheckMenuItem(hViewMenu, ID_VIEW_SHOWKERNELTIMES, MF_BYCOMMAND|MF_CHECKED);
        else
            CheckMenuItem(hViewMenu, ID_VIEW_SHOWKERNELTIMES, MF_BYCOMMAND|MF_UNCHECKED);
        if (TaskManagerSettings.CPUHistory_OneGraphPerCPU)
            CheckMenuRadioItem(hSubMenu, ID_VIEW_CPUHISTORY_ONEGRAPHALL, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, MF_BYCOMMAND);
        else
            CheckMenuRadioItem(hSubMenu, ID_VIEW_CPUHISTORY_ONEGRAPHALL, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, ID_VIEW_CPUHISTORY_ONEGRAPHALL, MF_BYCOMMAND);
        /*
         * Give the tab control focus
         */
        SetFocus(hTabWnd);
        break;
    }
}
Esempio n. 26
0
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nCmdShow)
{
    PF_CONSOLE_INIT_ALL()

    // Set global handle
    gHInst = hInst;

    CCmdParser cmdParser(s_cmdLineArgs, arrsize(s_cmdLineArgs));
    cmdParser.Parse();

    bool doIntroDialogs = true;
#ifndef PLASMA_EXTERNAL_RELEASE
    if (cmdParser.IsSpecified(kArgSkipLoginDialog))
        doIntroDialogs = false;
    if (cmdParser.IsSpecified(kArgLocalData))
    {
        gDataServerLocal = true;
        gSkipPreload = true;
    }
    if (cmdParser.IsSpecified(kArgSkipPreload))
        gSkipPreload = true;
#endif

    plFileName serverIni = "server.ini";
    if (cmdParser.IsSpecified(kArgServerIni))
        serverIni = plString::FromWchar(cmdParser.GetString(kArgServerIni));

    // check to see if we were launched from the patcher
    bool eventExists = false;
    // we check to see if the event exists that the patcher should have created
    HANDLE hPatcherEvent = CreateEventW(nil, TRUE, FALSE, L"UruPatcherEvent");
    if (hPatcherEvent != NULL)
    {
        // successfully created it, check to see if it was already created
        if (GetLastError() == ERROR_ALREADY_EXISTS)
        {
            // it already existed, so the patcher is waiting, signal it so the patcher can die
            SetEvent(hPatcherEvent);
            eventExists = true;
        }
    }

#ifdef PLASMA_EXTERNAL_RELEASE
    // if the client was started directly, run the patcher, and shutdown
    STARTUPINFOW si;
    PROCESS_INFORMATION pi; 
    memset(&si, 0, sizeof(si));
    memset(&pi, 0, sizeof(pi));
    si.cb = sizeof(si);

    const char** addrs;
    
    if (!eventExists) // if it is missing, assume patcher wasn't launched
    {
        plStringStream cmdLine;

        GetAuthSrvHostnames(&addrs);
        if (strlen(addrs[0]))
            cmdLine << " /AuthSrv=" << addrs[0];

        GetFileSrvHostnames(&addrs);
        if (strlen(addrs[0]))
            cmdLine << " /FileSrv=" << addrs[0];

        GetGateKeeperSrvHostnames(&addrs);
        if (strlen(addrs[0]))
            cmdLine << " /GateKeeperSrv=" << addrs[0];

        if(!CreateProcessW(s_patcherExeName, (LPWSTR)cmdLine.GetString().ToUtf16().GetData(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
        {
            hsMessageBox("Failed to launch patcher", "Error", hsMessageBoxNormal);
        }
        CloseHandle( pi.hThread );
        CloseHandle( pi.hProcess );
        return PARABLE_NORMAL_EXIT;
    }
#endif

    // Load an optional general.ini
    plFileName gipath = plFileName::Join(plFileSystem::GetInitPath(), "general.ini");
    FILE *generalini = plFileSystem::Open(gipath, "rb");
    if (generalini)
    {
        fclose(generalini);
        pfConsoleEngine tempConsole;
        tempConsole.ExecuteFile(gipath);
    }

#ifdef PLASMA_EXTERNAL_RELEASE
    // If another instance is running, exit.  We'll automatically release our
    // lock on the mutex when our process exits
    HANDLE hOneInstance = CreateMutex(nil, FALSE, "UruExplorer");
    if (WaitForSingleObject(hOneInstance,0) != WAIT_OBJECT_0)
    {
        switch (plLocalization::GetLanguage())
        {
            case plLocalization::kFrench:
                hsMessageBox("Une autre copie d'URU est déjà en cours d'exécution", "Erreur", hsMessageBoxNormal);
                break;
            case plLocalization::kGerman:
                hsMessageBox("URU wird bereits in einer anderen Instanz ausgeführt", "Fehler", hsMessageBoxNormal);
                break;
            case plLocalization::kSpanish:
                hsMessageBox("En estos momentos se está ejecutando otra copia de URU", "Error", hsMessageBoxNormal);
                break;
            case plLocalization::kItalian:
                hsMessageBox("Un'altra copia di URU è già aperta", "Errore", hsMessageBoxNormal);
                break;
            // default is English
            default:
                hsMessageBox("Another copy of URU is already running", "Error", hsMessageBoxNormal);
                break;
        }
        return PARABLE_NORMAL_EXIT;
    }
#endif

    FILE *serverIniFile = plFileSystem::Open(serverIni, "rb");
    if (serverIniFile)
    {
        fclose(serverIniFile);
        pfConsoleEngine tempConsole;
        tempConsole.ExecuteFile(serverIni);
    }
    else
    {
        hsMessageBox("No server.ini file found.  Please check your URU installation.", "Error", hsMessageBoxNormal);
        return PARABLE_NORMAL_EXIT;
    }

    NetCliAuthAutoReconnectEnable(false);

    NetCommSetReadIniAccountInfo(!doIntroDialogs);
    InitNetClientComm();

    curl_global_init(CURL_GLOBAL_ALL);

    bool                needExit = false;
    LoginDialogParam    loginParam;
    memset(&loginParam, 0, sizeof(loginParam));
    LoadUserPass(&loginParam);

    if (!doIntroDialogs && loginParam.remember) {
        ENetError auth;

        wchar_t wusername[kMaxAccountNameLength];
        StrToUnicode(wusername, loginParam.username, arrsize(wusername));
        NetCommSetAccountUsernamePassword(wusername, loginParam.namePassHash);
        bool cancelled = AuthenticateNetClientComm(&auth, NULL);

        if (IS_NET_ERROR(auth) || cancelled) {
            doIntroDialogs = true;

            loginParam.authError = auth;

            if (cancelled)
            {
                NetCommDisconnect();
            }
        }
    }

    if (doIntroDialogs) {
        needExit = ::DialogBoxParam( hInst, MAKEINTRESOURCE( IDD_URULOGIN_MAIN ), NULL, UruLoginDialogProc, (LPARAM)&loginParam ) <= 0;
    }

    if (doIntroDialogs && !needExit) {
        HINSTANCE hRichEdDll = LoadLibrary("RICHED20.DLL");
        INT_PTR val = ::DialogBoxParam( hInst, MAKEINTRESOURCE( IDD_URULOGIN_EULA ), NULL, UruTOSDialogProc, (LPARAM)hInst);
        FreeLibrary(hRichEdDll);
        if (val <= 0) {
            DWORD error = GetLastError();
            needExit = true;
        }
    }

    curl_global_cleanup();

    if (needExit) {
        DeInitNetClientComm();
        return PARABLE_NORMAL_EXIT;
    }

    NetCliAuthAutoReconnectEnable(true);

    // VERY VERY FIRST--throw up our splash screen
    HWND splashDialog = ::CreateDialog( hInst, MAKEINTRESOURCE( IDD_LOADING ), NULL, SplashDialogProc );

    // Install our unhandled exception filter for trapping all those nasty crashes in release build
#ifndef HS_DEBUGGING
    LPTOP_LEVEL_EXCEPTION_FILTER oldFilter;
    oldFilter = SetUnhandledExceptionFilter( plCustomUnhandledExceptionFilter );
#endif

    //
    // Set up to log errors by using hsDebugMessage
    //
    DebugInit();
    DebugMsgF("Plasma 2.0.%i.%i - %s", PLASMA2_MAJOR_VERSION, PLASMA2_MINOR_VERSION, plProduct::ProductString().c_str());

    for (;;) {
        // Create Window
        if (!WinInit(hInst, nCmdShow) || gClient->GetDone())
            break;

        // We don't have multiplayer localized assets for Italian or Spanish, so force them to English in that case.
    /*  if (!plNetClientMgr::GetInstance()->InOfflineMode() &&
            (plLocalization::GetLanguage() == plLocalization::kItalian || 
            plLocalization::GetLanguage() == plLocalization::kSpanish))
        {
            plLocalization::SetLanguage(plLocalization::kEnglish);
        }
    */

        // Done with our splash now
        ::DestroyWindow( splashDialog );

        if (!gClient)
            break;

        // Show the main window
        ShowWindow(gClient->GetWindowHandle(), SW_SHOW);

        gHasMouse = GetSystemMetrics(SM_MOUSEPRESENT);
            
        // Be really REALLY forceful about being in the front
        BringWindowToTop( gClient->GetWindowHandle() );

        // Update the window
        UpdateWindow(gClient->GetWindowHandle());

        // 
        // Init Application here
        //
        if( !gClient->StartInit() )
            break;
        
        // I want it on top! I mean it!
        BringWindowToTop( gClient->GetWindowHandle() );

        // initialize dinput here:
        if (gClient && gClient->GetInputManager())
            gClient->GetInputManager()->InitDInput(hInst, (HWND)gClient->GetWindowHandle());
        
        // Seriously!
        BringWindowToTop( gClient->GetWindowHandle() );
        
        //
        // Main loop
        //
        MSG msg;
        do
        {   
            gClient->MainLoop();

            if( gClient->GetDone() )
                break;

            // Look for a message
            while (PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ))
            {
                // Handle the message
                TranslateMessage( &msg );
                DispatchMessage( &msg );
            }
        } while (WM_QUIT != msg.message);

        break;
    }

    //
    // Cleanup
    //
    if (gClient)
    {
        gClient->Shutdown(); // shuts down PhysX for us
        gClient = nil;
    }
    hsAssert(hsgResMgr::ResMgr()->RefCnt()==1, "resMgr has too many refs, expect mem leaks");
    hsgResMgr::Shutdown();  // deletes fResMgr
    DeInitNetClientComm();

    // Uninstall our unhandled exception filter, if we installed one
#ifndef HS_DEBUGGING
    SetUnhandledExceptionFilter( oldFilter );
#endif

    // Exit WinMain and terminate the app....
//    return msg.wParam;
    return PARABLE_NORMAL_EXIT;
}
Esempio n. 27
0
Bool
winCreateBoundingWindowWindowed(ScreenPtr pScreen)
{
    winScreenPriv(pScreen);
    winScreenInfo *pScreenInfo = pScreenPriv->pScreenInfo;
    int iWidth = pScreenInfo->dwUserWidth;
    int iHeight = pScreenInfo->dwUserHeight;
    int iPosX;
    int iPosY;
    HWND *phwnd = &pScreenPriv->hwndScreen;
    WNDCLASSEX wc;
    RECT rcClient, rcWorkArea;
    DWORD dwWindowStyle;
    BOOL fForceShowWindow = FALSE;
    char szTitle[256];

    winDebug("winCreateBoundingWindowWindowed - User w: %d h: %d\n",
             (int) pScreenInfo->dwUserWidth, (int) pScreenInfo->dwUserHeight);
    winDebug("winCreateBoundingWindowWindowed - Current w: %d h: %d\n",
             (int) pScreenInfo->dwWidth, (int) pScreenInfo->dwHeight);

    /* Set the common window style flags */
    dwWindowStyle = WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX;

    /* Decorated or undecorated window */
    if (pScreenInfo->fDecoration
#ifdef XWIN_MULTIWINDOWEXTWM
        && !pScreenInfo->fMWExtWM
#endif
        && !pScreenInfo->fRootless
#ifdef XWIN_MULTIWINDOW
        && !pScreenInfo->fMultiWindow
#endif
        ) {
        /* Try to handle startup via run.exe. run.exe instructs Windows to
         * hide all created windows. Detect this case and make sure the
         * window is shown nevertheless */
        STARTUPINFO startupInfo;

        GetStartupInfo(&startupInfo);
        if (startupInfo.dwFlags & STARTF_USESHOWWINDOW &&
            startupInfo.wShowWindow == SW_HIDE) {
            fForceShowWindow = TRUE;
        }
        dwWindowStyle |= WS_CAPTION;
        if (pScreenInfo->iResizeMode != notAllowed)
            dwWindowStyle |= WS_THICKFRAME | WS_MAXIMIZEBOX;
    }
    else
        dwWindowStyle |= WS_POPUP;

    /* Setup our window class */
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = winWindowProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = g_hInstance;
    wc.hIcon =
        (HICON) LoadImage(g_hInstance, MAKEINTRESOURCE(IDI_XWIN), IMAGE_ICON,
                          GetSystemMetrics(SM_CXICON),
                          GetSystemMetrics(SM_CYICON), 0);
    wc.hCursor = 0;
    wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = WINDOW_CLASS;
    wc.hIconSm =
        (HICON) LoadImage(g_hInstance, MAKEINTRESOURCE(IDI_XWIN), IMAGE_ICON,
                          GetSystemMetrics(SM_CXSMICON),
                          GetSystemMetrics(SM_CYSMICON), LR_DEFAULTSIZE);
    RegisterClassEx(&wc);

    /* Get size of work area */
    winGetWorkArea(&rcWorkArea, pScreenInfo);

    /* Adjust for auto-hide taskbars */
    winAdjustForAutoHide(&rcWorkArea, pScreenInfo);

    /* Did the user specify a position? */
    if (pScreenInfo->fUserGavePosition) {
        iPosX = pScreenInfo->dwInitialX;
        iPosY = pScreenInfo->dwInitialY;
    }
    else {
        iPosX = rcWorkArea.left;
        iPosY = rcWorkArea.top;
    }

    /* Clean up the scrollbars flag, if necessary */
    if ((!pScreenInfo->fDecoration
#ifdef XWIN_MULTIWINDOWEXTWM
         || pScreenInfo->fMWExtWM
#endif
         || pScreenInfo->fRootless
#ifdef XWIN_MULTIWINDOW
         || pScreenInfo->fMultiWindow
#endif
        )
        && (pScreenInfo->iResizeMode == resizeWithScrollbars)) {
        /* We cannot have scrollbars if we do not have a window border */
        pScreenInfo->iResizeMode = notAllowed;
    }

    /* Did the user specify a height and width? */
    if (pScreenInfo->fUserGaveHeightAndWidth) {
        /* User gave a desired height and width, try to accomodate */
#if CYGDEBUG
        winDebug("winCreateBoundingWindowWindowed - User gave height "
                 "and width\n");
#endif

        /* Adjust the window width and height for borders and title bar */
        if (pScreenInfo->fDecoration
#ifdef XWIN_MULTIWINDOWEXTWM
            && !pScreenInfo->fMWExtWM
#endif
            && !pScreenInfo->fRootless
#ifdef XWIN_MULTIWINDOW
            && !pScreenInfo->fMultiWindow
#endif
            ) {
#if CYGDEBUG
            winDebug
                ("winCreateBoundingWindowWindowed - Window has decoration\n");
#endif

            /* Are we resizable */
            if (pScreenInfo->iResizeMode != notAllowed) {
#if CYGDEBUG
                winDebug
                    ("winCreateBoundingWindowWindowed - Window is resizable\n");
#endif

                iWidth += 2 * GetSystemMetrics(SM_CXSIZEFRAME);
                iHeight += 2 * GetSystemMetrics(SM_CYSIZEFRAME)
                    + GetSystemMetrics(SM_CYCAPTION);
            }
            else {
#if CYGDEBUG
                winDebug
                    ("winCreateBoundingWindowWindowed - Window is not resizable\n");
#endif

                iWidth += 2 * GetSystemMetrics(SM_CXFIXEDFRAME);
                iHeight += 2 * GetSystemMetrics(SM_CYFIXEDFRAME)
                    + GetSystemMetrics(SM_CYCAPTION);
            }
        }
    }
    else {
        /* By default, we are creating a window that is as large as possible */
#if CYGDEBUG
        winDebug("winCreateBoundingWindowWindowed - User did not give "
                 "height and width\n");
#endif
        /* Defaults are wrong if we have multiple monitors */
        if (pScreenInfo->fMultipleMonitors) {
            iWidth = GetSystemMetrics(SM_CXVIRTUALSCREEN);
            iHeight = GetSystemMetrics(SM_CYVIRTUALSCREEN);
        }
    }

    /* Make sure window is no bigger than work area */
    if (TRUE
#ifdef XWIN_MULTIWINDOWEXTWM
        && !pScreenInfo->fMWExtWM
#endif
#ifdef XWIN_MULTIWINDOW
        && !pScreenInfo->fMultiWindow
#endif
        ) {
        /* Trim window width to fit work area */
        if (iWidth > (rcWorkArea.right - rcWorkArea.left))
            iWidth = rcWorkArea.right - rcWorkArea.left;

        /* Trim window height to fit work area */
        if (iHeight >= (rcWorkArea.bottom - rcWorkArea.top))
            iHeight = rcWorkArea.bottom - rcWorkArea.top;

#if CYGDEBUG
        winDebug("winCreateBoundingWindowWindowed - Adjusted width: %d "
                 "height: %d\n", iWidth, iHeight);
#endif
    }

    /* Set display and screen-specific tooltip text */
    if (g_pszQueryHost != NULL)
        snprintf(szTitle,
                 sizeof(szTitle),
                 WINDOW_TITLE_XDMCP,
                 g_pszQueryHost, display, (int) pScreenInfo->dwScreen);
    else
        snprintf(szTitle,
                 sizeof(szTitle),
                 WINDOW_TITLE, display, (int) pScreenInfo->dwScreen);

    /* Create the window */
    *phwnd = CreateWindowExA(0, /* Extended styles */
                             WINDOW_CLASS,      /* Class name */
                             szTitle,   /* Window name */
                             dwWindowStyle, iPosX,      /* Horizontal position */
                             iPosY,     /* Vertical position */
                             iWidth,    /* Right edge */
                             iHeight,   /* Bottom edge */
                             (HWND) NULL,       /* No parent or owner window */
                             (HMENU) NULL,      /* No menu */
                             GetModuleHandle(NULL),     /* Instance handle */
                             pScreenPriv);      /* ScreenPrivates */
    if (*phwnd == NULL) {
        ErrorF("winCreateBoundingWindowWindowed - CreateWindowEx () failed\n");
        return FALSE;
    }

#if CYGDEBUG
    winDebug("winCreateBoundingWindowWindowed - CreateWindowEx () returned\n");
#endif

    if (fForceShowWindow) {
        ErrorF
            ("winCreateBoundingWindowWindowed - Setting normal windowstyle\n");
        ShowWindow(*phwnd, SW_SHOW);
    }

    /* Get the client area coordinates */
    if (!GetClientRect(*phwnd, &rcClient)) {
        ErrorF("winCreateBoundingWindowWindowed - GetClientRect () "
               "failed\n");
        return FALSE;
    }

    winDebug("winCreateBoundingWindowWindowed - WindowClient "
             "w %ld h %ld r %ld l %ld b %ld t %ld\n",
             rcClient.right - rcClient.left,
             rcClient.bottom - rcClient.top,
             rcClient.right, rcClient.left, rcClient.bottom, rcClient.top);

    /* We adjust the visual size if the user did not specify it */
    if (!
        ((pScreenInfo->iResizeMode == resizeWithScrollbars) &&
         pScreenInfo->fUserGaveHeightAndWidth)) {
        /*
         * User did not give a height and width with scrollbars enabled,
         * so we will resize the underlying visual to be as large as
         * the initial view port (page size).  This way scrollbars will
         * not appear until the user shrinks the window, if they ever do.
         *
         * NOTE: We have to store the viewport size here because
         * the user may have an autohide taskbar, which would
         * cause the viewport size to be one less in one dimension
         * than the viewport size that we calculated by subtracting
         * the size of the borders and caption.
         */
        pScreenInfo->dwWidth = rcClient.right - rcClient.left;
        pScreenInfo->dwHeight = rcClient.bottom - rcClient.top;
    }

#if 0
    /*
     * NOTE: For the uninitiated, the page size is the number of pixels
     * that we can display in the x or y direction at a time and the
     * range is the total number of pixels in the x or y direction that we
     * have available to display.  In other words, the page size is the
     * size of the window area minus the space the caption, borders, and
     * scrollbars (if any) occupy, and the range is the size of the
     * underlying X visual.  Notice that, contrary to what some of the
     * MSDN Library arcticles lead you to believe, the windows
     * ``client area'' size does not include the scrollbars.  In other words,
     * the whole client area size that is reported to you is drawable by
     * you; you do not have to subtract the size of the scrollbars from
     * the client area size, and if you did it would result in the size
     * of the scrollbars being double counted.
     */

    /* Setup scrollbar page and range, if scrollbars are enabled */
    if (pScreenInfo->fScrollbars) {
        SCROLLINFO si;

        /* Initialize the scrollbar info structure */
        si.cbSize = sizeof(si);
        si.fMask = SIF_RANGE | SIF_PAGE;
        si.nMin = 0;

        /* Setup the width range and page size */
        si.nMax = pScreenInfo->dwWidth - 1;
        si.nPage = rcClient.right - rcClient.left;
        winDebug("winCreateBoundingWindowWindowed - HORZ nMax: %d nPage :%d\n",
                 si.nMax, si.nPage);
        SetScrollInfo(*phwnd, SB_HORZ, &si, TRUE);

        /* Setup the height range and page size */
        si.nMax = pScreenInfo->dwHeight - 1;
        si.nPage = rcClient.bottom - rcClient.top;
        winDebug("winCreateBoundingWindowWindowed - VERT nMax: %d nPage :%d\n",
                 si.nMax, si.nPage);
        SetScrollInfo(*phwnd, SB_VERT, &si, TRUE);
    }
#endif

    /* Show the window */
    if (FALSE
#ifdef XWIN_MULTIWINDOWEXTWM
        || pScreenInfo->fMWExtWM
#endif
#ifdef XWIN_MULTIWINDOW
        || pScreenInfo->fMultiWindow
#endif
        ) {
#if defined(XWIN_MULTIWINDOW) || defined(XWIN_MULTIWINDOWEXTWM)
        pScreenPriv->fRootWindowShown = FALSE;
#endif
        ShowWindow(*phwnd, SW_HIDE);
    }
    else
        ShowWindow(*phwnd, SW_SHOWNORMAL);
    if (!UpdateWindow(*phwnd)) {
        ErrorF("winCreateBoundingWindowWindowed - UpdateWindow () failed\n");
        return FALSE;
    }

    /* Attempt to bring our window to the top of the display */
    if (TRUE
#ifdef XWIN_MULTIWINDOWEXTWM
        && !pScreenInfo->fMWExtWM
#endif
        && !pScreenInfo->fRootless
#ifdef XWIN_MULTIWINDOW
        && !pScreenInfo->fMultiWindow
#endif
        ) {
        if (!BringWindowToTop(*phwnd)) {
            ErrorF("winCreateBoundingWindowWindowed - BringWindowToTop () "
                   "failed\n");
            return FALSE;
        }
    }

    winDebug("winCreateBoundingWindowWindowed -  Returning\n");

    return TRUE;
}
Esempio n. 28
0
BOOL CRunTestsSheet::OnInitDialog() 
{
  if(!m_bHideTarget){
    m_prop.Add(_T("Platform"),m_strTarget);
  }
  m_prop.Add(_T("Active timeout"),m_nTimeout);
  m_prop.Add(_T("Download timeout"),m_nDownloadTimeout);
  m_prop.Add(_T("Active timeout type"),m_nTimeoutType);
  m_prop.Add(_T("Download timeout type"),m_nDownloadTimeoutType);
  m_prop.Add(_T("Remote"),m_bRemote);
  m_prop.Add(_T("Serial"),m_bSerial);
  m_prop.Add(_T("Port"),m_strPort);
  m_prop.Add(_T("Baud"),m_nBaud);
  m_prop.Add(_T("Local TCPIP Host"),m_strLocalTCPIPHost);
  m_prop.Add(_T("Local TCPIP Port"),m_nLocalTCPIPPort);
  m_prop.Add(_T("Reset Type"),m_nReset);
  m_prop.Add(_T("Reset String"),m_strReset);
  m_prop.Add(_T("Resource Host"),m_strResourceHost);
  m_prop.Add(_T("Resource Port"),m_nResourcePort);
  m_prop.Add(_T("Remote Host"),m_strRemoteHost);
  m_prop.Add(_T("Remote Port"),m_nRemotePort);
  m_prop.Add(_T("Recurse"),executionpage.m_bRecurse);
  //m_prop.Add(_T("Loadfromdir"),executionpage.m_strLoaddir);
  m_prop.Add(_T("Farmed"),m_bFarmed);
  m_prop.Add(_T("Extension"),executionpage.m_strExtension);
  
  CeCosTrace::SetOutput(TestOutputCallback,this);
  CeCosTrace::SetError (TestOutputCallback,this);
  
  // m_psh can only be used to set the small icon.  Set the large one here.
  m_psh.hIcon=AfxGetApp()->LoadIcon(IDR_TT_MAINFRAME);
  //sheet.m_psh.dwFlags|=PSH_USEHICON/*|PSH_HASHELP*/;
  if(m_psh.hIcon){
    SetIcon(m_psh.hIcon,FALSE);
    SetIcon(m_psh.hIcon,TRUE);
  }
  GetWindowRect(m_rcPrev);
#ifdef _DEBUG
  CeCosTrace::EnableTracing(CeCosTrace::TRACE_LEVEL_TRACE);
#endif
  CeCosTrace::SetInteractive(true);
  
  if(m_pInitFunc){
    m_pInitFunc(&m_prop,false);
  }
  
  GetDlgItem(IDCANCEL)->SetWindowText(_T("&Close"));
  
  m_nTestsToComplete=0;
  BOOL bResult = CeCosPropertySheet::OnInitDialog();
  SetDlgItemText(IDOK,_T("&Run"));
  SetDlgItemText(ID_APPLY_NOW,_T("&Properties"));
  GetDlgItem(ID_APPLY_NOW)->EnableWindow(TRUE);
  GetDlgItem(IDCANCEL)->EnableWindow(TRUE); // required for modeless case
  
  SetActivePage(&outputpage);
  SetActivePage(&summarypage);
  SetActivePage(&executionpage);
 	
  if(m_pInitFunc){
    m_pInitFunc(&m_prop,false);
    outputpage.UpdateData(FALSE);
    summarypage.UpdateData(FALSE);
    executionpage.UpdateData(FALSE);
  }
  /*
  CString strCaption = _T("Output");
  TC_ITEM tcItem;
  tcItem.mask = TCIF_TEXT;
  tcItem.pszText = (LPTSTR)((LPCTSTR)strCaption);
  GetTabControl()->SetItem(2, &tcItem );
  strCaption=_T("Summary");
  GetTabControl()->SetItem(3, &tcItem );
  */
  // Allow resizing
  
  // WS_OVERLAPPEDWINDOW would preclude caption bar help button
  ModifyStyle(0,WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME ,0);
  
  CRect rect;
  GetWindowRect(rect);
  m_rcPrev=rect;
  
  m_cxMin=rect.Width();
  m_cyMin=rect.Height();
  
  m_bAllowResizing=true;
  
  WINDOWPLACEMENT wndpl;
  if (5==_stscanf(m_strPlacement,_T("%d %d %d %d %d"),&rect.left,&rect.top,&rect.right,&rect.bottom,&wndpl.showCmd)){
    CRect rcMax;
    SystemParametersInfo(SPI_GETWORKAREA, 0, (PVOID)(RECT *)rcMax, 0);
    
    if(rect.Width()<100 || rect.Height()<100 || rect.Width()>rcMax.Width() || rect.Height()>rcMax.Height()){
      rect=CFrameWnd::rectDefault;
    }
    
    wndpl.length = sizeof(WINDOWPLACEMENT);
    wndpl.flags = 0;
    
    wndpl.ptMinPosition = CPoint(0, 0);
    wndpl.ptMaxPosition =CPoint(-::GetSystemMetrics(SM_CXBORDER),-::GetSystemMetrics(SM_CYBORDER));
    wndpl.rcNormalPosition = rect;
    
    // sets window's position and iconized/maximized status
    SetWindowPlacement(&wndpl);
  }
  
  // Hack: force an initial sizing (without which the tab control is badly sized)
  m_rcOffset.left=m_rcOffset.right=m_rcOffset.top=0;
  
  m_rcOffset.bottom=m_bModal?50:-50;
  MoveWindow(GetTabControl(),Stretch);
  for(int i=0;i<GetPageCount();i++){
    MoveWindow(GetPage(i),Stretch);
  }
#ifdef _DEBUG
    for(CWnd *p=GetWindow(GW_CHILD);p;p=p->GetWindow(GW_HWNDNEXT)){
      TCHAR buf[256];
      ::GetClassName(p->m_hWnd,buf,sizeof buf);
      TRACE(_T("Window %x id=%d class=%s\n"),p,p->GetDlgCtrlID(),buf);
    }
#endif
  for(i=0;i<sizeof(arIds)/sizeof(arIds[0]);i++){
    CWnd *pWnd=GetDlgItem(arIds[i]);
    if(pWnd){
      MoveWindow(pWnd,BottomRight);
      pWnd->ShowWindow(SW_SHOW); // necessary in the modeless case
    } else {
      TRACE(_T("Failed to find window id=%x\n"),arIds[i]);
    }
  }

  // hack to lay buttons out correctly in application case
  if(this==AfxGetMainWnd()){
    CRect rect1,rect2;
    GetDlgItem(IDOK)->GetWindowRect(rect1);
    GetDlgItem(IDCANCEL)->GetWindowRect(rect2);
    CRect rect(rect1);
    rect.left-=(rect2.left-rect1.left);
    rect.right-=(rect2.right-rect1.right);
    ScreenToClient(rect);
    GetDlgItem(ID_APPLY_NOW)->MoveWindow(rect);
    GetDlgItem(ID_APPLY_NOW)->ShowWindow(SW_SHOW);
  }

  if(!m_bModal){
    SetTimer(0,100,0);
  }
  BringWindowToTop();
  return bResult;
}
Esempio n. 29
0
//---------------------------------------------------------------------------
// capture window as FIBITMAP - caller must FIP->FI_Unload(dib)
FIBITMAP* CaptureWindow(HWND hCapture, BOOL bClientArea, BOOL bIndirectCapture)
{
	FIBITMAP* dib;
	HWND hForegroundWin;
	RECT rect;//cropping rect

	if (!hCapture || !IsWindow(hCapture))
		return NULL;
	hForegroundWin = GetForegroundWindow();	// old foreground window
	SetForegroundWindow(hCapture);			// force target foreground
	BringWindowToTop(hCapture);				// bring it to top as well
	/// redraw window to prevent runtime artifacts in picture
	UpdateWindow(hCapture);

	HWND hParent = GetAncestor(hCapture, GA_PARENT);
	if (hParent && !IsChild(hParent, hCapture))
		hParent = NULL;
	if (bIndirectCapture) {
		intptr_t wastopmost = GetWindowLongPtr(hCapture, GWL_EXSTYLE)&WS_EX_TOPMOST;
		if (!wastopmost)
			SetWindowPos(hCapture, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
		if (bClientArea) {
			GetClientRect(hCapture, &rect);
			ClientToScreen(hCapture, (POINT*)&rect);
			rect.right += rect.left; rect.bottom += rect.top;
		}
		else
			GetWindowRect(hCapture, &rect);
		dib = CaptureMonitor(NULL, &rect);
		if (!wastopmost)
			SetWindowPos(hCapture, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
	}
	else {
		HDC hDCsrc;
		GetWindowRect(hCapture, &rect);
		if (hParent)
			hDCsrc = GetDC(hCapture);//hCapture is part of a window, capture that
		else
			hDCsrc = GetWindowDC(hCapture);//entire window w/ title bar
		rect.right = ABS(rect.right - rect.left);
		rect.bottom = ABS(rect.bottom - rect.top);
		rect.left = rect.top = 0;
		/// capture window and get FIBITMAP
		dib = CreateDIBFromDC(hDCsrc, &rect, hCapture);
		ReleaseDC(hCapture, hDCsrc);
		if (bClientArea) {//we could capture directly, but doing so breaks GetWindowRgn() and also includes artifacts...
			GetWindowRect(hCapture, &rect);
			RECT rectCA; GetClientRect(hCapture, &rectCA);
			ClientToScreen(hCapture, (POINT*)&rectCA);
			rectCA.left = ABS(rectCA.left - rect.left);
			rectCA.top = ABS(rectCA.top - rect.top);
			rectCA.right += rectCA.left; rectCA.bottom += rectCA.top;
			/// crop the window to ClientArea
			FIBITMAP* dibClient = FIP->FI_Copy(dib, rectCA.left, rectCA.top, rectCA.right, rectCA.bottom);
			FIP->FI_Unload(dib);
			dib = dibClient;
		}
	}
	if (hForegroundWin) {//restore previous foreground window
		SetForegroundWindow(hForegroundWin);
		BringWindowToTop(hForegroundWin);
	}
	return dib;
}
Esempio n. 30
0
/*
 * imgEditInit - initialization
 */
static BOOL imgEditInit( HANDLE currinst, HANDLE previnst, int cmdshow )
{
    WNDCLASS    wc;
    HMENU       menu;
    HDC         hdc;
    BOOL        maximized;
    int         show_state;

    hdc = GetDC( NULL );
    ColorPlanes = GetDeviceCaps( hdc, PLANES );
    BitsPerPixel = GetDeviceCaps( hdc, BITSPIXEL );
    ReleaseDC( NULL, hdc );

    Instance = currinst;
    IEInitErrors( currinst );
    IEInitGlobalStrings();

    if( ImgedIsDDE ) {
        menu = LoadMenu( Instance, "IMGEDDDEMENU" );
    } else {
        menu = LoadMenu( Instance, "IMGEDMENU" );
    }

    hBitmapIcon = LoadIcon( Instance, "BitmapIcon" );
    hIconIcon = LoadIcon( Instance, "IconIcon" );
    hCursorIcon = LoadIcon( Instance, "CursorIcon" );
    hAccel = LoadAccelerators( Instance, "Accelerators" );

    IECtl3dInit( Instance );

#if defined( __NT__ )
    hBkBrush = CreateSolidBrush( GetSysColor( COLOR_BTNFACE ) );
#endif

    /*
     * set up window class
     */
    if( !previnst ) {
        wc.style = 0L;
        wc.lpfnWndProc = (LPVOID)ImgEdFrameProc;
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = LoadIcon( Instance, "APPLICON" );
        wc.hCursor = LoadCursor( (HANDLE)NULL, IDC_ARROW );
        wc.hbrBackground = NULL;
        wc.lpszMenuName = NULL;
        wc.lpszClassName = className;
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    /*
     * This is the child of the MDI frame window (of it's client window actually).
     */
    if( !previnst ) {
        wc.style = CS_BYTEALIGNWINDOW | CS_CLASSDC | CS_DBLCLKS;
        wc.lpfnWndProc = (LPVOID)DrawAreaWinProc;
        wc.cbClsExtra = sizeof( HCURSOR );
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = hBitmapIcon;
        wc.hCursor = LoadCursor( (HANDLE)NULL, IDC_ARROW );
        wc.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH );
        wc.lpszMenuName = NULL;
        wc.lpszClassName = DrawAreaClassB;
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    if( !previnst ) {
        wc.style = CS_BYTEALIGNWINDOW | CS_CLASSDC | CS_DBLCLKS;
        wc.lpfnWndProc = (LPVOID)DrawAreaWinProc;
        wc.cbClsExtra = sizeof( HCURSOR );
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = hIconIcon;
        wc.hCursor = LoadCursor( (HANDLE)NULL, IDC_ARROW );
        wc.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH );
        wc.lpszMenuName = NULL;
        wc.lpszClassName = DrawAreaClassI;
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    if( !previnst ) {
        wc.style = CS_BYTEALIGNWINDOW | CS_CLASSDC | CS_DBLCLKS;
        wc.lpfnWndProc = (LPVOID)DrawAreaWinProc;
        wc.cbClsExtra = sizeof( HCURSOR );
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = hCursorIcon;
        wc.hCursor = LoadCursor( (HANDLE)NULL, IDC_ARROW );
        wc.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH );
        wc.lpszMenuName = NULL;
        wc.lpszClassName = DrawAreaClassC;
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    if( !previnst ) {
        wc.style = 0L;
        wc.lpfnWndProc = (LPVOID)ViewWindowProc;
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = LoadIcon( NULL, IDI_APPLICATION );
        wc.hCursor = LoadCursor( (HANDLE)NULL, IDC_ARROW );
        wc.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH );
        wc.lpszMenuName = NULL;
        wc.lpszClassName = ViewWinClass;
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    if( !previnst ) {
        wc.style = 0L;
        wc.lpfnWndProc = (LPVOID)ColorPalWinProc;
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = NULL;
        wc.hCursor = LoadCursor( (HANDLE)NULL, IDC_ARROW );
#if defined( __NT__ )
        wc.hbrBackground = hBkBrush;
#else
        wc.hbrBackground = (HBRUSH)GetStockObject( LTGRAY_BRUSH );
#endif
        wc.lpszMenuName = NULL;
        wc.lpszClassName = PaletteClass;
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    handCursor = LoadCursor( Instance, "HandCursor" );
    if( !previnst ) {
        wc.style = CS_DBLCLKS;
        wc.lpfnWndProc = (LPVOID)ColorsWndProc;
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = NULL;
        wc.hCursor = handCursor;
#if defined( __NT__ )
        wc.hbrBackground = hBkBrush;
#else
        wc.hbrBackground = (HBRUSH)GetStockObject( LTGRAY_BRUSH );
#endif
        wc.lpszMenuName = NULL;
        wc.lpszClassName = "ColorsClass";
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    if( !previnst ) {
        wc.style = CS_DBLCLKS;
        wc.lpfnWndProc = (LPVOID)ScreenWndProc;
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = NULL;
        wc.hCursor = handCursor;
#if defined( __NT__ )
        wc.hbrBackground = hBkBrush;
#else
        wc.hbrBackground = (HBRUSH)GetStockObject( LTGRAY_BRUSH );
#endif
        wc.lpszMenuName = NULL;
        wc.lpszClassName = "ScreenClass";
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    if( !previnst ) {
        wc.style = 0L;
        wc.lpfnWndProc = (LPVOID)CurrentWndProc;
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = NULL;
        wc.hCursor = LoadCursor( (HANDLE)NULL, IDC_ARROW );
#if defined( __NT__ )
        wc.hbrBackground = hBkBrush;
#else
        wc.hbrBackground = (HBRUSH)GetStockObject( LTGRAY_BRUSH );
#endif
        wc.lpszMenuName = NULL;
        wc.lpszClassName = "CurrentClass";
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    if( !previnst ) {
        wc.style = 0L;
        wc.lpfnWndProc = (LPVOID)BitmapPickProc;
        wc.cbClsExtra = 0;
        wc.cbWndExtra = 0;
        wc.hInstance = Instance;
        wc.hIcon = NULL;
        wc.hCursor = NULL;
#if defined( __NT__ )
        wc.hbrBackground = hBkBrush;
#else
        wc.hbrBackground = (HBRUSH)GetStockObject( LTGRAY_BRUSH );
#endif
        wc.lpszMenuName = NULL;
        wc.lpszClassName = BitmapPickClass;
        if( !RegisterClass( &wc ) ) {
            return( FALSE );
        }
    }

    /*
     * Now make the main window.
     */
    LoadImgedConfig();
    maximized = ImgedConfigInfo.ismaximized;

    InitPalette();
    HMainWindow = CreateWindow(
        className,                              /* Window class name */
        IEAppTitle,                             /* Window caption */
        WS_OVERLAPPEDWINDOW | WS_BORDER | WS_CLIPCHILDREN | WS_CLIPSIBLINGS
        | WS_DLGFRAME,                          /* Window style */
        ImgedConfigInfo.x_pos,                  /* Initial X position */
        ImgedConfigInfo.y_pos,                  /* Initial Y position */
        ImgedConfigInfo.width,                  /* Initial X size */
        ImgedConfigInfo.height,                 /* Initial Y size */
        (HWND)NULL,                             /* Parent window handle */
        (HMENU)menu,                            /* Window menu handle */
        Instance,                               /* Program instance handle */
        NULL );                                 /* Create parameters */

    if( HMainWindow == NULL ) {
        return( FALSE );
    }

    if( maximized ) {
        if( cmdshow == SW_SHOW || cmdshow == SW_SHOWNORMAL ) {
            show_state = SW_SHOWMAXIMIZED;
        } else {
            show_state = cmdshow;
        }
    } else {
        show_state = cmdshow;
    }
    ShowWindow( HMainWindow, show_state );
    UpdateWindow( HMainWindow );

    if( !ImgedIsDDE && !NoTitleScreen ) {
        DisplayTitleScreen( Instance, HMainWindow, 2000, IEAppTitle );
    }

    CreateColorPal();
    InitTools( HMainWindow );
    GrayEditOptions();

#ifdef __NT__
    DragAcceptFiles( HMainWindow, TRUE );
#endif
    //SetActiveWindow( HMainWindow );
    BringWindowToTop( HMainWindow );
    return( TRUE );

} /* imgEditInit */