Load simplifiedUI using the windows launcher and tabs to spaces

This commit is contained in:
luiscuenca 2019-06-11 09:24:27 -07:00
parent 1748d0527f
commit c02df55186
9 changed files with 1302 additions and 1299 deletions

View file

@ -20,7 +20,7 @@
// CLauncherApp // CLauncherApp
BEGIN_MESSAGE_MAP(CLauncherApp, CWinApp) BEGIN_MESSAGE_MAP(CLauncherApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP() END_MESSAGE_MAP()
CLauncherApp::CLauncherApp(){} CLauncherApp::CLauncherApp(){}
@ -32,60 +32,60 @@ CLauncherApp theApp;
// CLauncherApp initialization // CLauncherApp initialization
BOOL CLauncherApp::InitInstance() { BOOL CLauncherApp::InitInstance() {
// don't launch if already running // don't launch if already running
CreateMutex(NULL, TRUE, _T("HQ_Launcher_Mutex")); CreateMutex(NULL, TRUE, _T("HQ_Launcher_Mutex"));
if (GetLastError() == ERROR_ALREADY_EXISTS) { if (GetLastError() == ERROR_ALREADY_EXISTS) {
return FALSE; return FALSE;
} }
int iNumOfArgs; int iNumOfArgs;
LPWSTR* pArgs = CommandLineToArgvW(GetCommandLine(), &iNumOfArgs); LPWSTR* pArgs = CommandLineToArgvW(GetCommandLine(), &iNumOfArgs);
if (iNumOfArgs > 1 && CString(pArgs[1]).Compare(_T("--uninstall")) == 0) { if (iNumOfArgs > 1 && CString(pArgs[1]).Compare(_T("--uninstall")) == 0) {
_manager.uninstall(); _manager.uninstall();
} else { } else {
_manager.init(); _manager.init();
} }
if (!_manager.installLauncher()) { if (!_manager.installLauncher()) {
return FALSE; return FALSE;
} }
installFont(IDR_FONT_REGULAR); installFont(IDR_FONT_REGULAR);
installFont(IDR_FONT_BOLD); installFont(IDR_FONT_BOLD);
CWinApp::InitInstance(); CWinApp::InitInstance();
SetRegistryKey(_T("HQ High Fidelity")); SetRegistryKey(_T("HQ High Fidelity"));
CLauncherDlg dlg; CLauncherDlg dlg;
m_pMainWnd = &dlg; m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal(); INT_PTR nResponse = dlg.DoModal();
#if !defined(_AFXDLL) && !defined(_AFX_NO_MFC_CONTROLS_IN_DIALOGS) #if !defined(_AFXDLL) && !defined(_AFX_NO_MFC_CONTROLS_IN_DIALOGS)
ControlBarCleanUp(); ControlBarCleanUp();
#endif #endif
// Since the dialog has been closed, return FALSE so that we exit the // Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump. // application, rather than start the application's message pump.
return FALSE; return FALSE;
} }
BOOL CLauncherApp::installFont(int fontID) { BOOL CLauncherApp::installFont(int fontID) {
HINSTANCE hResInstance = AfxGetResourceHandle(); HINSTANCE hResInstance = AfxGetResourceHandle();
HRSRC res = FindResource(hResInstance, HRSRC res = FindResource(hResInstance,
MAKEINTRESOURCE(fontID), L"BINARY"); MAKEINTRESOURCE(fontID), L"BINARY");
if (res) { if (res) {
HGLOBAL mem = LoadResource(hResInstance, res); HGLOBAL mem = LoadResource(hResInstance, res);
void *data = LockResource(mem); void *data = LockResource(mem);
DWORD len = (DWORD)SizeofResource(hResInstance, res); DWORD len = (DWORD)SizeofResource(hResInstance, res);
DWORD nFonts; DWORD nFonts;
auto m_fonthandle = AddFontMemResourceEx( auto m_fonthandle = AddFontMemResourceEx(
data, // font resource data, // font resource
len, // number of bytes in font resource len, // number of bytes in font resource
NULL, // Reserved. Must be 0. NULL, // Reserved. Must be 0.
&nFonts // number of fonts installed &nFonts // number of fonts installed
); );
return (m_fonthandle != 0); return (m_fonthandle != 0);
} }
return FALSE; return FALSE;
} }

View file

@ -11,22 +11,22 @@
#pragma once #pragma once
#ifndef __AFXWIN_H__ #ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH" #error "include 'stdafx.h' before including this file for PCH"
#endif #endif
#include "resource.h" // main symbols #include "resource.h" // main symbols
#include "LauncherManager.h" #include "LauncherManager.h"
class CLauncherApp : public CWinApp class CLauncherApp : public CWinApp
{ {
public: public:
CLauncherApp(); CLauncherApp();
virtual BOOL InitInstance(); virtual BOOL InitInstance();
void setDialogOnFront() { SetWindowPos(m_pMainWnd->GetSafeHwnd(), HWND_TOPMOST, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE); } void setDialogOnFront() { SetWindowPos(m_pMainWnd->GetSafeHwnd(), HWND_TOPMOST, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE); }
LauncherManager _manager; LauncherManager _manager;
private: private:
BOOL installFont(int fontID); BOOL installFont(int fontID);
DECLARE_MESSAGE_MAP() DECLARE_MESSAGE_MAP()
}; };
extern CLauncherApp theApp; extern CLauncherApp theApp;

View file

@ -40,10 +40,10 @@ static CString TROUBLE_URL = _T("https://www.highfidelity.com/hq-support");
CLauncherDlg::CLauncherDlg(CWnd* pParent) CLauncherDlg::CLauncherDlg(CWnd* pParent)
: CDialog(IDD_LAUNCHER_DIALOG, pParent) : CDialog(IDD_LAUNCHER_DIALOG, pParent)
{ {
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
EnableD2DSupport(); EnableD2DSupport();
} }
CLauncherDlg::~CLauncherDlg() { CLauncherDlg::~CLauncherDlg() {
@ -52,109 +52,109 @@ CLauncherDlg::~CLauncherDlg() {
void CLauncherDlg::DoDataExchange(CDataExchange* pDX) void CLauncherDlg::DoDataExchange(CDataExchange* pDX)
{ {
DDX_Control(pDX, IDC_BUTTON_NEXT, m_btnNext); DDX_Control(pDX, IDC_BUTTON_NEXT, m_btnNext);
DDX_Control(pDX, IDC_TROUBLE_LINK, m_trouble_link); DDX_Control(pDX, IDC_TROUBLE_LINK, m_trouble_link);
DDX_Control(pDX, IDC_ORGNAME, m_orgname); DDX_Control(pDX, IDC_ORGNAME, m_orgname);
DDX_Control(pDX, IDC_USERNAME, m_username); DDX_Control(pDX, IDC_USERNAME, m_username);
DDX_Control(pDX, IDC_PASSWORD, m_password); DDX_Control(pDX, IDC_PASSWORD, m_password);
CDialog::DoDataExchange(pDX); CDialog::DoDataExchange(pDX);
} }
BEGIN_MESSAGE_MAP(CLauncherDlg, CDialog) BEGIN_MESSAGE_MAP(CLauncherDlg, CDialog)
ON_WM_PAINT() ON_WM_PAINT()
ON_WM_QUERYDRAGICON() ON_WM_QUERYDRAGICON()
ON_WM_TIMER() ON_WM_TIMER()
ON_EN_SETFOCUS(IDC_ORGNAME, &CLauncherDlg::OnOrgEditChangeFocus) ON_EN_SETFOCUS(IDC_ORGNAME, &CLauncherDlg::OnOrgEditChangeFocus)
ON_EN_SETFOCUS(IDC_USERNAME, &CLauncherDlg::OnUserEditChangeFocus) ON_EN_SETFOCUS(IDC_USERNAME, &CLauncherDlg::OnUserEditChangeFocus)
ON_EN_SETFOCUS(IDC_PASSWORD, &CLauncherDlg::OnPassEditChangeFocus) ON_EN_SETFOCUS(IDC_PASSWORD, &CLauncherDlg::OnPassEditChangeFocus)
ON_BN_CLICKED(IDC_BUTTON_NEXT, &CLauncherDlg::OnNextClicked) ON_BN_CLICKED(IDC_BUTTON_NEXT, &CLauncherDlg::OnNextClicked)
ON_BN_CLICKED(IDC_TROUBLE_LINK, &CLauncherDlg::OnTroubleClicked) ON_BN_CLICKED(IDC_TROUBLE_LINK, &CLauncherDlg::OnTroubleClicked)
ON_WM_CTLCOLOR() ON_WM_CTLCOLOR()
ON_WM_DRAWITEM() ON_WM_DRAWITEM()
ON_WM_SETCURSOR() ON_WM_SETCURSOR()
END_MESSAGE_MAP() END_MESSAGE_MAP()
// CLauncherDlg message handlers // CLauncherDlg message handlers
BOOL CLauncherDlg::OnInitDialog() { BOOL CLauncherDlg::OnInitDialog() {
CDialog::OnInitDialog(); CDialog::OnInitDialog();
SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon SetIcon(m_hIcon, FALSE); // Set small icon
CFont editFont; CFont editFont;
if (LauncherUtils::getFont(GRAPHIK_REGULAR, FIELDS_FONT_SIZE, true, editFont)) { if (LauncherUtils::getFont(GRAPHIK_REGULAR, FIELDS_FONT_SIZE, true, editFont)) {
m_orgname.SetFont(&editFont); m_orgname.SetFont(&editFont);
m_username.SetFont(&editFont); m_username.SetFont(&editFont);
m_password.SetFont(&editFont); m_password.SetFont(&editFont);
} }
CFont buttonFont; CFont buttonFont;
if (LauncherUtils::getFont(_T("Graphik-Bold"), BUTTON_FONT_SIZE, true, buttonFont)) { if (LauncherUtils::getFont(_T("Graphik-Bold"), BUTTON_FONT_SIZE, true, buttonFont)) {
m_btnNext.SetFont(&editFont); m_btnNext.SetFont(&editFont);
} }
m_message_label = (CStatic *)GetDlgItem(IDC_MESSAGE_LABEL); m_message_label = (CStatic *)GetDlgItem(IDC_MESSAGE_LABEL);
m_action_label = (CStatic *)GetDlgItem(IDC_ACTION_LABEL); m_action_label = (CStatic *)GetDlgItem(IDC_ACTION_LABEL);
m_message2_label = (CStatic *)GetDlgItem(IDC_MESSAGE2_LABEL); m_message2_label = (CStatic *)GetDlgItem(IDC_MESSAGE2_LABEL);
m_action2_label = (CStatic *)GetDlgItem(IDC_ACTION2_LABEL); m_action2_label = (CStatic *)GetDlgItem(IDC_ACTION2_LABEL);
m_orgname_banner = (CStatic *)GetDlgItem(IDC_ORGNAME_BANNER); m_orgname_banner = (CStatic *)GetDlgItem(IDC_ORGNAME_BANNER);
m_username_banner = (CStatic *)GetDlgItem(IDC_USERNAME_BANNER); m_username_banner = (CStatic *)GetDlgItem(IDC_USERNAME_BANNER);
m_password_banner = (CStatic *)GetDlgItem(IDC_PASSWORD_BANNER); m_password_banner = (CStatic *)GetDlgItem(IDC_PASSWORD_BANNER);
m_terms = (CStatic *)GetDlgItem(IDC_TERMS); m_terms = (CStatic *)GetDlgItem(IDC_TERMS);
m_terms2 = (CStatic *)GetDlgItem(IDC_TERMS2); m_terms2 = (CStatic *)GetDlgItem(IDC_TERMS2);
m_trouble = (CStatic *)GetDlgItem(IDC_TROUBLE); m_trouble = (CStatic *)GetDlgItem(IDC_TROUBLE);
m_voxel = (CStatic *)GetDlgItem(IDC_VOXEL); m_voxel = (CStatic *)GetDlgItem(IDC_VOXEL);
m_voxel->EnableD2DSupport(); m_voxel->EnableD2DSupport();
m_pRenderTarget = GetRenderTarget(); m_pRenderTarget = GetRenderTarget();
SetTimer(1, 2, NULL); SetTimer(1, 2, NULL);
return TRUE; return TRUE;
} }
BOOL CLauncherDlg::PreTranslateMessage(MSG* pMsg) { BOOL CLauncherDlg::PreTranslateMessage(MSG* pMsg) {
if ((pMsg->message == WM_KEYDOWN)) if ((pMsg->message == WM_KEYDOWN))
{ {
if (pMsg->wParam == VK_RETURN) if (pMsg->wParam == VK_RETURN)
{ {
OnNextClicked(); OnNextClicked();
return TRUE; return TRUE;
} }
} }
return CDialog::PreTranslateMessage(pMsg); return CDialog::PreTranslateMessage(pMsg);
} }
void CLauncherDlg::setCustomDialog() { void CLauncherDlg::setCustomDialog() {
LONG lStyle = GetWindowLong(GetSafeHwnd(), GWL_STYLE); LONG lStyle = GetWindowLong(GetSafeHwnd(), GWL_STYLE);
lStyle &= ~(WS_CAPTION | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SYSMENU); lStyle &= ~(WS_CAPTION | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SYSMENU);
SetWindowLong(GetSafeHwnd(), GWL_STYLE, lStyle); SetWindowLong(GetSafeHwnd(), GWL_STYLE, lStyle);
LONG lExStyle = GetWindowLong(GetSafeHwnd(), GWL_EXSTYLE); LONG lExStyle = GetWindowLong(GetSafeHwnd(), GWL_EXSTYLE);
lExStyle &= ~(WS_EX_DLGMODALFRAME | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE); lExStyle &= ~(WS_EX_DLGMODALFRAME | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE);
SetWindowLong(GetSafeHwnd(), GWL_EXSTYLE, lExStyle); SetWindowLong(GetSafeHwnd(), GWL_EXSTYLE, lExStyle);
SetWindowPos(NULL, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER); SetWindowPos(NULL, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
// theApp.setDialogOnFront(); // theApp.setDialogOnFront();
} }
void CLauncherDlg::OnPaint() void CLauncherDlg::OnPaint()
{ {
CPaintDC dc(this); CPaintDC dc(this);
setCustomDialog(); setCustomDialog();
CDialog::OnPaint(); CDialog::OnPaint();
} }
// The system calls this function to obtain the cursor to display while the user drags // The system calls this function to obtain the cursor to display while the user drags
// the minimized window. // the minimized window.
HCURSOR CLauncherDlg::OnQueryDragIcon() HCURSOR CLauncherDlg::OnQueryDragIcon()
{ {
return static_cast<HCURSOR>(m_hIcon); return static_cast<HCURSOR>(m_hIcon);
} }
void CLauncherDlg::startProcess() { void CLauncherDlg::startProcess() {
@ -202,15 +202,15 @@ void CLauncherDlg::startProcess() {
} }
BOOL CLauncherDlg::getHQInfo(const CString& orgname) { BOOL CLauncherDlg::getHQInfo(const CString& orgname) {
CString hash; CString hash;
CString lowerOrgName = orgname; CString lowerOrgName = orgname;
lowerOrgName.MakeLower(); lowerOrgName.MakeLower();
LauncherUtils::hMac256(lowerOrgName, LAUNCHER_HMAC_SECRET, hash); LauncherUtils::hMac256(lowerOrgName, LAUNCHER_HMAC_SECRET, hash);
return theApp._manager.readOrganizationJSON(hash) == LauncherUtils::ResponseError::NoError; return theApp._manager.readOrganizationJSON(hash) == LauncherUtils::ResponseError::NoError;
} }
afx_msg void CLauncherDlg::OnTroubleClicked() { afx_msg void CLauncherDlg::OnTroubleClicked() {
ShellExecute(0, NULL, TROUBLE_URL, NULL, NULL, SW_SHOWDEFAULT); ShellExecute(0, NULL, TROUBLE_URL, NULL, NULL, SW_SHOWDEFAULT);
} }
afx_msg void CLauncherDlg::OnNextClicked() { afx_msg void CLauncherDlg::OnNextClicked() {
@ -255,414 +255,414 @@ afx_msg void CLauncherDlg::OnNextClicked() {
} }
void CLauncherDlg::drawBackground(CHwndRenderTarget* pRenderTarget) { void CLauncherDlg::drawBackground(CHwndRenderTarget* pRenderTarget) {
CD2DBitmap m_pBitmamBackground(pRenderTarget, IDB_PNG1, _T("PNG")); CD2DBitmap m_pBitmamBackground(pRenderTarget, IDB_PNG1, _T("PNG"));
auto size = pRenderTarget->GetSize(); auto size = pRenderTarget->GetSize();
CD2DRectF backRec(0.0f, 0.0f, size.width, size.height); CD2DRectF backRec(0.0f, 0.0f, size.width, size.height);
pRenderTarget->DrawBitmap(&m_pBitmamBackground, backRec); pRenderTarget->DrawBitmap(&m_pBitmamBackground, backRec);
} }
void CLauncherDlg::drawLogo(CHwndRenderTarget* pRenderTarget) { void CLauncherDlg::drawLogo(CHwndRenderTarget* pRenderTarget) {
CD2DBitmap m_pBitmamLogo(pRenderTarget, IDB_PNG2, _T("PNG")); CD2DBitmap m_pBitmamLogo(pRenderTarget, IDB_PNG2, _T("PNG"));
auto size = pRenderTarget->GetSize(); auto size = pRenderTarget->GetSize();
int logoWidth = 231; int logoWidth = 231;
int logoHeight = 181; int logoHeight = 181;
float logoPosX = 0.5f * (size.width - logoWidth); float logoPosX = 0.5f * (size.width - logoWidth);
float logoPosY = 0.95f * (size.height - logoHeight); float logoPosY = 0.95f * (size.height - logoHeight);
CD2DRectF logoRec(logoPosX, logoPosY, logoPosX + logoWidth, logoPosY + logoHeight); CD2DRectF logoRec(logoPosX, logoPosY, logoPosX + logoWidth, logoPosY + logoHeight);
pRenderTarget->DrawBitmap(&m_pBitmamLogo, logoRec); pRenderTarget->DrawBitmap(&m_pBitmamLogo, logoRec);
} }
void CLauncherDlg::drawSmallLogo(CHwndRenderTarget* pRenderTarget) { void CLauncherDlg::drawSmallLogo(CHwndRenderTarget* pRenderTarget) {
CD2DBitmap m_pBitmamLogo(pRenderTarget, IDB_PNG5, _T("PNG")); CD2DBitmap m_pBitmamLogo(pRenderTarget, IDB_PNG5, _T("PNG"));
auto size = pRenderTarget->GetSize(); auto size = pRenderTarget->GetSize();
int padding = 6; int padding = 6;
int logoWidth = 100; int logoWidth = 100;
int logoHeight = 18; int logoHeight = 18;
float logoPosX = size.width - logoWidth - padding; float logoPosX = size.width - logoWidth - padding;
float logoPosY = size.height - logoHeight - padding; float logoPosY = size.height - logoHeight - padding;
CD2DRectF logoRec(logoPosX, logoPosY, logoPosX + logoWidth, logoPosY + logoHeight); CD2DRectF logoRec(logoPosX, logoPosY, logoPosX + logoWidth, logoPosY + logoHeight);
pRenderTarget->DrawBitmap(&m_pBitmamLogo, logoRec); pRenderTarget->DrawBitmap(&m_pBitmamLogo, logoRec);
} }
void CLauncherDlg::drawVoxel(CHwndRenderTarget* pRenderTarget) { void CLauncherDlg::drawVoxel(CHwndRenderTarget* pRenderTarget) {
CD2DBitmap m_pBitmamVoxel(pRenderTarget, IDB_PNG4, _T("PNG")); CD2DBitmap m_pBitmamVoxel(pRenderTarget, IDB_PNG4, _T("PNG"));
auto size = pRenderTarget->GetSize(); auto size = pRenderTarget->GetSize();
int logoWidth = 132; int logoWidth = 132;
int logoHeight = 134; int logoHeight = 134;
float voxelPosX = 0.5f * (size.width - logoWidth); float voxelPosX = 0.5f * (size.width - logoWidth);
float voxelPosY = 0.5f * (size.height - logoHeight); float voxelPosY = 0.5f * (size.height - logoHeight);
CD2DRectF voxelRec(voxelPosX, voxelPosY, voxelPosX + logoWidth, voxelPosY + logoHeight); CD2DRectF voxelRec(voxelPosX, voxelPosY, voxelPosX + logoWidth, voxelPosY + logoHeight);
auto midPoint = D2D1::Point2F(0.5f * size.width, 0.5f * size.height); auto midPoint = D2D1::Point2F(0.5f * size.width, 0.5f * size.height);
_logoRotation += 2.0f; _logoRotation += 2.0f;
CD2DSolidColorBrush brush(pRenderTarget, D2D1::ColorF(0.0f, 0.0f, 0.0f)); CD2DSolidColorBrush brush(pRenderTarget, D2D1::ColorF(0.0f, 0.0f, 0.0f));
pRenderTarget->SetTransform(D2D1::Matrix3x2F::Rotation(_logoRotation - 2.0f, midPoint)); pRenderTarget->SetTransform(D2D1::Matrix3x2F::Rotation(_logoRotation - 2.0f, midPoint));
pRenderTarget->FillRectangle(voxelRec, &brush); pRenderTarget->FillRectangle(voxelRec, &brush);
pRenderTarget->SetTransform(D2D1::Matrix3x2F::Rotation(_logoRotation, midPoint)); pRenderTarget->SetTransform(D2D1::Matrix3x2F::Rotation(_logoRotation, midPoint));
pRenderTarget->DrawBitmap(&m_pBitmamVoxel, voxelRec); pRenderTarget->DrawBitmap(&m_pBitmamVoxel, voxelRec);
pRenderTarget->SetTransform(D2D1::Matrix3x2F::Identity()); pRenderTarget->SetTransform(D2D1::Matrix3x2F::Identity());
} }
void CLauncherDlg::showWindows(std::vector<CStatic*> windows, bool show) { void CLauncherDlg::showWindows(std::vector<CStatic*> windows, bool show) {
for (auto window : windows) { for (auto window : windows) {
window->ShowWindow(show ? SW_SHOW : SW_HIDE); window->ShowWindow(show ? SW_SHOW : SW_HIDE);
} }
} }
void CLauncherDlg::prepareLogin(DrawStep step) { void CLauncherDlg::prepareLogin(DrawStep step) {
m_voxel->ShowWindow(SW_HIDE); m_voxel->ShowWindow(SW_HIDE);
m_orgname_banner->SetWindowTextW(_T("Organization Name")); m_orgname_banner->SetWindowTextW(_T("Organization Name"));
m_username_banner->SetWindowTextW(_T("Username")); m_username_banner->SetWindowTextW(_T("Username"));
m_password_banner->SetWindowTextW(_T("Password")); m_password_banner->SetWindowTextW(_T("Password"));
CString editText; CString editText;
m_orgname.GetWindowTextW(editText); m_orgname.GetWindowTextW(editText);
m_orgname_banner->ShowWindow(editText.GetLength() == 0 ? SW_SHOW : SW_HIDE); m_orgname_banner->ShowWindow(editText.GetLength() == 0 ? SW_SHOW : SW_HIDE);
m_username.GetWindowTextW(editText); m_username.GetWindowTextW(editText);
m_username_banner->ShowWindow(editText.GetLength() == 0 ? SW_SHOW : SW_HIDE); m_username_banner->ShowWindow(editText.GetLength() == 0 ? SW_SHOW : SW_HIDE);
m_password.GetWindowTextW(editText); m_password.GetWindowTextW(editText);
m_password_banner->ShowWindow(editText.GetLength() == 0 ? SW_SHOW : SW_HIDE); m_password_banner->ShowWindow(editText.GetLength() == 0 ? SW_SHOW : SW_HIDE);
m_orgname.ShowWindow(SW_SHOW); m_orgname.ShowWindow(SW_SHOW);
m_username.ShowWindow(SW_SHOW); m_username.ShowWindow(SW_SHOW);
m_password.ShowWindow(SW_SHOW); m_password.ShowWindow(SW_SHOW);
CString actionText = step == DrawStep::DrawLoginLogin ? _T("Please log in") : _T("Uh-oh, we have a problem"); CString actionText = step == DrawStep::DrawLoginLogin ? _T("Please log in") : _T("Uh-oh, we have a problem");
CString messageText = step == DrawStep::DrawLoginLogin ? _T("Be sure you've uploaded your Avatar before signing in.") : CString messageText = step == DrawStep::DrawLoginLogin ? _T("Be sure you've uploaded your Avatar before signing in.") :
step == DrawStep::DrawLoginErrorCred ? _T("There is a problem with your credentials\n please try again.") : _T("There is a problem with your Organization name\n please try again."); step == DrawStep::DrawLoginErrorCred ? _T("There is a problem with your credentials\n please try again.") : _T("There is a problem with your Organization name\n please try again.");
m_action_label->SetWindowTextW(actionText); m_action_label->SetWindowTextW(actionText);
m_message_label->SetWindowTextW(messageText); m_message_label->SetWindowTextW(messageText);
m_action_label->ShowWindow(SW_SHOW); m_action_label->ShowWindow(SW_SHOW);
m_message_label->ShowWindow(SW_SHOW); m_message_label->ShowWindow(SW_SHOW);
m_btnNext.ShowWindow(SW_SHOW); m_btnNext.ShowWindow(SW_SHOW);
m_trouble->SetWindowTextW(_T("Having Trouble?")); m_trouble->SetWindowTextW(_T("Having Trouble?"));
m_trouble->ShowWindow(SW_SHOW); m_trouble->ShowWindow(SW_SHOW);
m_trouble_link.ShowWindow(SW_SHOW); m_trouble_link.ShowWindow(SW_SHOW);
} }
void CLauncherDlg::prepareChoose() { void CLauncherDlg::prepareChoose() {
m_orgname.ShowWindow(SW_HIDE); m_orgname.ShowWindow(SW_HIDE);
m_username.SetWindowTextW(_T("")); m_username.SetWindowTextW(_T(""));
m_username_banner->SetWindowTextW(_T("Display Name")); m_username_banner->SetWindowTextW(_T("Display Name"));
CString editText; CString editText;
m_username.GetWindowTextW(editText); m_username.GetWindowTextW(editText);
m_username_banner->ShowWindow(editText.GetLength() == 0 ? SW_SHOW : SW_HIDE); m_username_banner->ShowWindow(editText.GetLength() == 0 ? SW_SHOW : SW_HIDE);
m_password.ShowWindow(SW_HIDE); m_password.ShowWindow(SW_HIDE);
m_orgname_banner->ShowWindow(SW_HIDE); m_orgname_banner->ShowWindow(SW_HIDE);
m_password_banner->ShowWindow(SW_HIDE); m_password_banner->ShowWindow(SW_HIDE);
m_action_label->SetWindowTextW(_T("Choose a display name")); m_action_label->SetWindowTextW(_T("Choose a display name"));
m_message_label->SetWindowTextW(_T("This is the name that your teammates will see.")); m_message_label->SetWindowTextW(_T("This is the name that your teammates will see."));
m_terms->ShowWindow(SW_SHOW); m_terms->ShowWindow(SW_SHOW);
m_terms2->ShowWindow(SW_SHOW); m_terms2->ShowWindow(SW_SHOW);
m_terms->SetWindowTextW(_T("By signing in, you agree to the High Fidelity")); m_terms->SetWindowTextW(_T("By signing in, you agree to the High Fidelity"));
m_terms2->SetWindowTextW(_T("Terms of Service")); m_terms2->SetWindowTextW(_T("Terms of Service"));
CRect rec; CRect rec;
m_btnNext.GetWindowRect(&rec); m_btnNext.GetWindowRect(&rec);
ScreenToClient(&rec); ScreenToClient(&rec);
if (rec.top > 281) { if (rec.top > 281) {
rec.bottom -= 35; rec.bottom -= 35;
rec.top -= 35; rec.top -= 35;
m_btnNext.MoveWindow(rec, FALSE); m_btnNext.MoveWindow(rec, FALSE);
} }
m_btnNext.ShowWindow(SW_SHOW); m_btnNext.ShowWindow(SW_SHOW);
} }
void CLauncherDlg::prepareProcess(DrawStep step) { void CLauncherDlg::prepareProcess(DrawStep step) {
m_trouble->ShowWindow(SW_HIDE); m_trouble->ShowWindow(SW_HIDE);
m_trouble_link.ShowWindow(SW_HIDE); m_trouble_link.ShowWindow(SW_HIDE);
m_terms->ShowWindow(SW_HIDE); m_terms->ShowWindow(SW_HIDE);
m_terms2->ShowWindow(SW_HIDE); m_terms2->ShowWindow(SW_HIDE);
m_orgname_banner->ShowWindow(SW_HIDE); m_orgname_banner->ShowWindow(SW_HIDE);
m_username_banner->ShowWindow(SW_HIDE); m_username_banner->ShowWindow(SW_HIDE);
m_password_banner->ShowWindow(SW_HIDE); m_password_banner->ShowWindow(SW_HIDE);
m_orgname.ShowWindow(SW_HIDE); m_orgname.ShowWindow(SW_HIDE);
m_username.ShowWindow(SW_HIDE); m_username.ShowWindow(SW_HIDE);
m_password.ShowWindow(SW_HIDE); m_password.ShowWindow(SW_HIDE);
m_action_label->SetWindowTextW(_T("")); m_action_label->SetWindowTextW(_T(""));
m_message_label->SetWindowTextW(_T("")); m_message_label->SetWindowTextW(_T(""));
m_btnNext.ShowWindow(SW_HIDE); m_btnNext.ShowWindow(SW_HIDE);
m_action_label->ShowWindow(SW_HIDE); m_action_label->ShowWindow(SW_HIDE);
m_message_label->ShowWindow(SW_HIDE); m_message_label->ShowWindow(SW_HIDE);
m_voxel->ShowWindow(SW_SHOW); m_voxel->ShowWindow(SW_SHOW);
CString actionText = _T(""); CString actionText = _T("");
CString messageText = _T(""); CString messageText = _T("");
switch (step) { switch (step) {
case DrawStep::DrawProcessSetup: case DrawStep::DrawProcessSetup:
actionText = _T("We're building your virtual HQ"); actionText = _T("We're building your virtual HQ");
messageText = _T("Set up may take several minutes."); messageText = _T("Set up may take several minutes.");
break; break;
case DrawStep::DrawProcessUpdate: case DrawStep::DrawProcessUpdate:
actionText = _T("Getting updates..."); actionText = _T("Getting updates...");
messageText = _T("We're getting the latest and greatest for you, one sec."); messageText = _T("We're getting the latest and greatest for you, one sec.");
break; break;
case DrawStep::DrawProcessFinishHq: case DrawStep::DrawProcessFinishHq:
actionText = _T("Your new HQ is all setup"); actionText = _T("Your new HQ is all setup");
messageText = _T("Thanks for being patient."); messageText = _T("Thanks for being patient.");
break; break;
case DrawStep::DrawProcessFinishUpdate: case DrawStep::DrawProcessFinishUpdate:
actionText = _T("You're good to go!"); actionText = _T("You're good to go!");
messageText = _T("Thanks for being patient."); messageText = _T("Thanks for being patient.");
break; break;
case DrawStep::DrawProcessUninstall: case DrawStep::DrawProcessUninstall:
actionText = _T("Uninstalling..."); actionText = _T("Uninstalling...");
messageText = _T("It'll take one sec."); messageText = _T("It'll take one sec.");
break; break;
} }
m_action2_label->SetWindowTextW(actionText); m_action2_label->SetWindowTextW(actionText);
m_message2_label->SetWindowTextW(messageText); m_message2_label->SetWindowTextW(messageText);
m_action2_label->ShowWindow(SW_SHOW); m_action2_label->ShowWindow(SW_SHOW);
m_message2_label->ShowWindow(SW_SHOW); m_message2_label->ShowWindow(SW_SHOW);
} }
void CLauncherDlg::prepareError() { void CLauncherDlg::prepareError() {
} }
BOOL CLauncherDlg::getTextFormat(int resID, TextFormat& formatOut) { BOOL CLauncherDlg::getTextFormat(int resID, TextFormat& formatOut) {
// Set default values for message // Set default values for message
BOOL isText = TRUE; BOOL isText = TRUE;
formatOut.color = COLOR_LIGHT_GREY; formatOut.color = COLOR_LIGHT_GREY;
formatOut.isBold = false; formatOut.isBold = false;
formatOut.isButton = false; formatOut.isButton = false;
formatOut.size = MESSAGE_FONT_SIZE; formatOut.size = MESSAGE_FONT_SIZE;
formatOut.underlined = false; formatOut.underlined = false;
switch (resID) { switch (resID) {
case IDC_VOXEL: case IDC_VOXEL:
case IDD_LAUNCHER_DIALOG: case IDD_LAUNCHER_DIALOG:
isText = FALSE; isText = FALSE;
case IDC_MESSAGE_LABEL: case IDC_MESSAGE_LABEL:
case IDC_MESSAGE2_LABEL: case IDC_MESSAGE2_LABEL:
// Default values // Default values
break; break;
case IDC_ACTION_LABEL: case IDC_ACTION_LABEL:
case IDC_ACTION2_LABEL: case IDC_ACTION2_LABEL:
formatOut.size = ACTION_FONT_SIZE; formatOut.size = ACTION_FONT_SIZE;
formatOut.isBold = true; formatOut.isBold = true;
formatOut.color = COLOR_LIGHTER_GREY; formatOut.color = COLOR_LIGHTER_GREY;
break; break;
case IDC_USERNAME: case IDC_USERNAME:
case IDC_PASSWORD: case IDC_PASSWORD:
case IDC_ORGNAME: case IDC_ORGNAME:
formatOut.color = COLOR_WHITE; formatOut.color = COLOR_WHITE;
formatOut.size = FIELDS_FONT_SIZE; formatOut.size = FIELDS_FONT_SIZE;
formatOut.underlined = true; formatOut.underlined = true;
break; break;
case IDC_USERNAME_BANNER: case IDC_USERNAME_BANNER:
case IDC_PASSWORD_BANNER: case IDC_PASSWORD_BANNER:
case IDC_ORGNAME_BANNER: case IDC_ORGNAME_BANNER:
formatOut.size = FIELDS_FONT_SIZE; formatOut.size = FIELDS_FONT_SIZE;
formatOut.color = COLOR_GREY; formatOut.color = COLOR_GREY;
break; break;
case IDC_TERMS: case IDC_TERMS:
formatOut.size = TERMS_FONT_SIZE; formatOut.size = TERMS_FONT_SIZE;
break; break;
case IDC_TERMS2: case IDC_TERMS2:
formatOut.size = TERMS_FONT_SIZE; formatOut.size = TERMS_FONT_SIZE;
formatOut.isBold = true; formatOut.isBold = true;
break; break;
case IDC_TROUBLE: case IDC_TROUBLE:
formatOut.size = TROUBLE_FONT_SIZE; formatOut.size = TROUBLE_FONT_SIZE;
formatOut.color = COLOR_BLUE; formatOut.color = COLOR_BLUE;
break; break;
} }
return isText; return isText;
} }
HBRUSH CLauncherDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) HBRUSH CLauncherDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{ {
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
TextFormat textFormat; TextFormat textFormat;
int resId = pWnd->GetDlgCtrlID(); int resId = pWnd->GetDlgCtrlID();
if (getTextFormat(resId, textFormat)) { if (getTextFormat(resId, textFormat)) {
pDC->SetTextColor(textFormat.color); pDC->SetTextColor(textFormat.color);
pDC->SetBkMode(TRANSPARENT); pDC->SetBkMode(TRANSPARENT);
CFont textFont; CFont textFont;
CString fontFamily = textFormat.isBold ? GRAPHIK_SEMIBOLD : GRAPHIK_REGULAR; CString fontFamily = textFormat.isBold ? GRAPHIK_SEMIBOLD : GRAPHIK_REGULAR;
if (LauncherUtils::getFont(fontFamily, textFormat.size, textFormat.isBold, textFont)) { if (LauncherUtils::getFont(fontFamily, textFormat.size, textFormat.isBold, textFont)) {
pDC->SelectObject(&textFont); pDC->SelectObject(&textFont);
} }
if (textFormat.underlined) { if (textFormat.underlined) {
CRect rect; CRect rect;
pWnd->GetClientRect(&rect); pWnd->GetClientRect(&rect);
int borderThick = 1; int borderThick = 1;
int padding = 4; int padding = 4;
CRect lineRect = CRect(rect.left + padding, rect.bottom, rect.right - padding, rect.bottom + borderThick); CRect lineRect = CRect(rect.left + padding, rect.bottom, rect.right - padding, rect.bottom + borderThick);
lineRect.MoveToY(lineRect.bottom + 1); lineRect.MoveToY(lineRect.bottom + 1);
pDC->FillSolidRect(lineRect, COLOR_GREY); pDC->FillSolidRect(lineRect, COLOR_GREY);
} }
} }
return (HBRUSH)GetStockObject(BLACK_BRUSH); return (HBRUSH)GetStockObject(BLACK_BRUSH);
} }
void CLauncherDlg::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct) void CLauncherDlg::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)
{ {
CDC dc; CDC dc;
dc.Attach(lpDrawItemStruct->hDC); dc.Attach(lpDrawItemStruct->hDC);
CRect rect = lpDrawItemStruct->rcItem; CRect rect = lpDrawItemStruct->rcItem;
CRect defrect = rect; CRect defrect = rect;
CString btnName = _T(""); CString btnName = _T("");
int xpan = 0; int xpan = 0;
if (nIDCtl == IDC_BUTTON_NEXT) { if (nIDCtl == IDC_BUTTON_NEXT) {
if (_drawStep == DrawStep::DrawChoose || _drawStep == DrawStep::DrawLoginLogin) { if (_drawStep == DrawStep::DrawChoose || _drawStep == DrawStep::DrawLoginLogin) {
btnName += _drawStep == DrawStep::DrawLoginLogin ? _T("NEXT") : _T("LOG IN"); btnName += _drawStep == DrawStep::DrawLoginLogin ? _T("NEXT") : _T("LOG IN");
int xpan = -20; int xpan = -20;
defrect = CRect(rect.left - xpan, rect.top, rect.right + xpan, rect.bottom); defrect = CRect(rect.left - xpan, rect.top, rect.right + xpan, rect.bottom);
} else { } else {
btnName += _T("TRY AGAIN"); btnName += _T("TRY AGAIN");
} }
int borderThick = 2; int borderThick = 2;
dc.FillSolidRect(rect, COLOR_BLACK); dc.FillSolidRect(rect, COLOR_BLACK);
dc.FillSolidRect(defrect, COLOR_WHITE); dc.FillSolidRect(defrect, COLOR_WHITE);
defrect.DeflateRect(borderThick, borderThick, borderThick, borderThick); defrect.DeflateRect(borderThick, borderThick, borderThick, borderThick);
dc.FillSolidRect(defrect, COLOR_BLACK); dc.FillSolidRect(defrect, COLOR_BLACK);
UINT state = lpDrawItemStruct->itemState; UINT state = lpDrawItemStruct->itemState;
dc.SetTextColor(COLOR_WHITE); dc.SetTextColor(COLOR_WHITE);
CFont buttonFont; CFont buttonFont;
if (LauncherUtils::getFont(GRAPHIK_SEMIBOLD, BUTTON_FONT_SIZE, true, buttonFont)) { if (LauncherUtils::getFont(GRAPHIK_SEMIBOLD, BUTTON_FONT_SIZE, true, buttonFont)) {
dc.SelectObject(buttonFont); dc.SelectObject(buttonFont);
} }
dc.DrawText(btnName, CRect(rect.left, rect.top + 4, rect.right, rect.bottom - 8), DT_CENTER | DT_VCENTER | DT_SINGLELINE); dc.DrawText(btnName, CRect(rect.left, rect.top + 4, rect.right, rect.bottom - 8), DT_CENTER | DT_VCENTER | DT_SINGLELINE);
dc.Detach(); dc.Detach();
} else if (nIDCtl == IDC_TROUBLE_LINK) { } else if (nIDCtl == IDC_TROUBLE_LINK) {
dc.FillSolidRect(rect, COLOR_BLACK); dc.FillSolidRect(rect, COLOR_BLACK);
dc.SetTextColor(COLOR_BLUE); dc.SetTextColor(COLOR_BLUE);
CFont buttonFont; CFont buttonFont;
if (LauncherUtils::getFont(GRAPHIK_SEMIBOLD, TROUBLE_FONT_SIZE, true, buttonFont)) { if (LauncherUtils::getFont(GRAPHIK_SEMIBOLD, TROUBLE_FONT_SIZE, true, buttonFont)) {
dc.SelectObject(buttonFont); dc.SelectObject(buttonFont);
} }
dc.DrawText(_T("Having Trouble"), CRect(rect.left, rect.top, rect.right, rect.bottom), DT_CENTER | DT_VCENTER | DT_SINGLELINE); dc.DrawText(_T("Having Trouble"), CRect(rect.left, rect.top, rect.right, rect.bottom), DT_CENTER | DT_VCENTER | DT_SINGLELINE);
} }
} }
void CLauncherDlg::redrawBanner(const CEdit& edit, CStatic* banner) { void CLauncherDlg::redrawBanner(const CEdit& edit, CStatic* banner) {
CString editText; CString editText;
edit.GetWindowTextW(editText); edit.GetWindowTextW(editText);
if (editText.GetLength() == 0) { if (editText.GetLength() == 0) {
banner->Invalidate(); banner->Invalidate();
} }
} }
void CLauncherDlg::OnOrgEditChangeFocus() { void CLauncherDlg::OnOrgEditChangeFocus() {
redrawBanner(m_username, m_username_banner); redrawBanner(m_username, m_username_banner);
redrawBanner(m_password, m_password_banner); redrawBanner(m_password, m_password_banner);
} }
void CLauncherDlg::OnUserEditChangeFocus() { void CLauncherDlg::OnUserEditChangeFocus() {
redrawBanner(m_orgname, m_orgname_banner); redrawBanner(m_orgname, m_orgname_banner);
redrawBanner(m_password, m_password_banner); redrawBanner(m_password, m_password_banner);
} }
void CLauncherDlg::OnPassEditChangeFocus() { void CLauncherDlg::OnPassEditChangeFocus() {
redrawBanner(m_orgname, m_orgname_banner); redrawBanner(m_orgname, m_orgname_banner);
redrawBanner(m_username, m_username_banner); redrawBanner(m_username, m_username_banner);
} }
BOOL CLauncherDlg::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) BOOL CLauncherDlg::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message)
{ {
if (pWnd->IsKindOf(RUNTIME_CLASS(CButton))) { if (pWnd->IsKindOf(RUNTIME_CLASS(CButton))) {
::SetCursor(AfxGetApp()->LoadStandardCursor(IDC_HAND)); ::SetCursor(AfxGetApp()->LoadStandardCursor(IDC_HAND));
return TRUE; return TRUE;
} }
return CDialog::OnSetCursor(pWnd, nHitTest, message); return CDialog::OnSetCursor(pWnd, nHitTest, message);
} }
void CLauncherDlg::OnTimer(UINT_PTR nIDEvent) { void CLauncherDlg::OnTimer(UINT_PTR nIDEvent) {
const int CONSOLE_MAX_SHUTDOWN_TRY_COUNT = 10; const int CONSOLE_MAX_SHUTDOWN_TRY_COUNT = 10;
const int CONSOLE_DELTATIME_BETWEEN_TRYS = 10; const int CONSOLE_DELTATIME_BETWEEN_TRYS = 10;
if (_drawStep == DrawStep::DrawProcessSetup || if (_drawStep == DrawStep::DrawProcessSetup ||
_drawStep == DrawStep::DrawProcessUpdate || _drawStep == DrawStep::DrawProcessUpdate ||
_drawStep == DrawStep::DrawProcessUninstall) { _drawStep == DrawStep::DrawProcessUninstall) {
// Refresh // Refresh
setDrawDialog(_drawStep, true); setDrawDialog(_drawStep, true);
} }
if (_showSplash) { if (_showSplash) {
if (_splashStep == 0){ if (_splashStep == 0){
if (theApp._manager.needsUninstall()) { if (theApp._manager.needsUninstall()) {
theApp._manager.addToLog(_T("Waiting to uninstall")); theApp._manager.addToLog(_T("Waiting to uninstall"));
setDrawDialog(DrawStep::DrawProcessUninstall); setDrawDialog(DrawStep::DrawProcessUninstall);
} else { } else {
theApp._manager.addToLog(_T("Start splash screen")); theApp._manager.addToLog(_T("Start splash screen"));
setDrawDialog(DrawStep::DrawLogo); setDrawDialog(DrawStep::DrawLogo);
} }
} else if (_splashStep > 100) { } else if (_splashStep > 100) {
_showSplash = false; _showSplash = false;
if (theApp._manager.shouldShutDown()) { if (theApp._manager.shouldShutDown()) {
if (LauncherUtils::IsProcessRunning(L"interface.exe")) { if (LauncherUtils::IsProcessRunning(L"interface.exe")) {
exit(0); exit(0);
} }
} else if (theApp._manager.needsUpdate()) { } else if (theApp._manager.needsUpdate()) {
startProcess(); startProcess();
} else if (theApp._manager.needsUninstall()) { } else if (theApp._manager.needsUninstall()) {
theApp._manager.uninstallApplication(); theApp._manager.uninstallApplication();
exit(0); exit(0);
} else { } else {
theApp._manager.addToLog(_T("Starting login")); theApp._manager.addToLog(_T("Starting login"));
setDrawDialog(DrawStep::DrawLoginLogin); setDrawDialog(DrawStep::DrawLoginLogin);
} }
} }
_splashStep++; _splashStep++;
} else if (theApp._manager.shouldShutDown()) { } else if (theApp._manager.shouldShutDown()) {
if (LauncherUtils::IsProcessRunning(L"interface.exe")) { if (LauncherUtils::IsProcessRunning(L"interface.exe")) {
exit(0); exit(0);
} }
} }
} }
void CLauncherDlg::setDrawDialog(DrawStep step, BOOL isUpdate) { void CLauncherDlg::setDrawDialog(DrawStep step, BOOL isUpdate) {
_drawStep = step; _drawStep = step;
auto m_pRenderTarget = GetRenderTarget(); auto m_pRenderTarget = GetRenderTarget();
auto m_voxelRenderTarget = m_voxel->GetRenderTarget(); auto m_voxelRenderTarget = m_voxel->GetRenderTarget();
switch (_drawStep) { switch (_drawStep) {
case DrawStep::DrawLogo: case DrawStep::DrawLogo:
m_pRenderTarget->BeginDraw(); m_pRenderTarget->BeginDraw();
drawBackground(m_pRenderTarget); drawBackground(m_pRenderTarget);
m_pRenderTarget->EndDraw(); m_pRenderTarget->EndDraw();
m_voxelRenderTarget->BeginDraw(); m_voxelRenderTarget->BeginDraw();
drawLogo(m_voxelRenderTarget); drawLogo(m_voxelRenderTarget);
m_voxelRenderTarget->EndDraw(); m_voxelRenderTarget->EndDraw();
break; break;
case DrawStep::DrawLoginLogin: case DrawStep::DrawLoginLogin:
case DrawStep::DrawLoginErrorOrg: case DrawStep::DrawLoginErrorOrg:
case DrawStep::DrawLoginErrorCred: case DrawStep::DrawLoginErrorCred:
prepareLogin(_drawStep); prepareLogin(_drawStep);
m_pRenderTarget->BeginDraw(); m_pRenderTarget->BeginDraw();
drawBackground(m_pRenderTarget); drawBackground(m_pRenderTarget);
drawSmallLogo(m_pRenderTarget); drawSmallLogo(m_pRenderTarget);
m_pRenderTarget->EndDraw(); m_pRenderTarget->EndDraw();
RedrawWindow(); RedrawWindow();
break; break;
case DrawStep::DrawChoose: case DrawStep::DrawChoose:
prepareChoose(); prepareChoose();
m_pRenderTarget->BeginDraw(); m_pRenderTarget->BeginDraw();
drawBackground(m_pRenderTarget); drawBackground(m_pRenderTarget);
drawSmallLogo(m_pRenderTarget); drawSmallLogo(m_pRenderTarget);
m_pRenderTarget->EndDraw(); m_pRenderTarget->EndDraw();
RedrawWindow(); RedrawWindow();
break; break;
case DrawStep::DrawProcessFinishHq: case DrawStep::DrawProcessFinishHq:
case DrawStep::DrawProcessFinishUpdate: case DrawStep::DrawProcessFinishUpdate:
case DrawStep::DrawProcessUpdate: case DrawStep::DrawProcessUpdate:
case DrawStep::DrawProcessUninstall: case DrawStep::DrawProcessUninstall:
case DrawStep::DrawProcessSetup: case DrawStep::DrawProcessSetup:
if (!isUpdate) { if (!isUpdate) {
m_voxelRenderTarget->BeginDraw(); m_voxelRenderTarget->BeginDraw();
m_voxelRenderTarget->Clear(D2D1::ColorF(0.0f, 0.0f, 0.0f, 1.0f)); m_voxelRenderTarget->Clear(D2D1::ColorF(0.0f, 0.0f, 0.0f, 1.0f));
m_voxelRenderTarget->EndDraw(); m_voxelRenderTarget->EndDraw();
m_pRenderTarget->BeginDraw(); m_pRenderTarget->BeginDraw();
prepareProcess(_drawStep); prepareProcess(_drawStep);
drawBackground(m_pRenderTarget); drawBackground(m_pRenderTarget);
drawSmallLogo(m_pRenderTarget); drawSmallLogo(m_pRenderTarget);
m_pRenderTarget->EndDraw(); m_pRenderTarget->EndDraw();
RedrawWindow(); RedrawWindow();
} }
m_voxelRenderTarget->BeginDraw(); m_voxelRenderTarget->BeginDraw();
drawVoxel(m_voxelRenderTarget); drawVoxel(m_voxelRenderTarget);
m_voxelRenderTarget->EndDraw(); m_voxelRenderTarget->EndDraw();
break; break;
default: default:
break; break;
} }
} }

View file

@ -13,109 +13,109 @@
// CLauncherDlg dialog // CLauncherDlg dialog
class CLauncherDlg : public CDialog class CLauncherDlg : public CDialog
{ {
// Construction // Construction
public: public:
enum DrawStep { enum DrawStep {
DrawLogo = 0, DrawLogo = 0,
DrawLoginLogin, DrawLoginLogin,
DrawLoginErrorOrg, DrawLoginErrorOrg,
DrawLoginErrorCred, DrawLoginErrorCred,
DrawChoose, DrawChoose,
DrawProcessSetup, DrawProcessSetup,
DrawProcessUpdate, DrawProcessUpdate,
DrawProcessFinishHq, DrawProcessFinishHq,
DrawProcessFinishUpdate, DrawProcessFinishUpdate,
DrawProcessUninstall, DrawProcessUninstall,
DrawError DrawError
}; };
struct TextFormat { struct TextFormat {
int size; int size;
COLORREF color; COLORREF color;
bool isButton; bool isButton;
bool isBold; bool isBold;
bool underlined; bool underlined;
}; };
CLauncherDlg(CWnd* pParent = nullptr); CLauncherDlg(CWnd* pParent = nullptr);
~CLauncherDlg(); ~CLauncherDlg();
virtual BOOL PreTranslateMessage(MSG* pMsg); virtual BOOL PreTranslateMessage(MSG* pMsg);
void setDrawDialog(DrawStep step, BOOL isUpdate = FALSE); void setDrawDialog(DrawStep step, BOOL isUpdate = FALSE);
// Dialog Data // Dialog Data
#ifdef AFX_DESIGN_TIME #ifdef AFX_DESIGN_TIME
enum { IDD = IDD_LAUNCHER_DIALOG }; enum { IDD = IDD_LAUNCHER_DIALOG };
#endif #endif
protected: protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
void startProcess(); void startProcess();
void setCustomDialog(); void setCustomDialog();
// Implementation // Implementation
protected: protected:
BOOL getHQInfo(const CString& orgname); BOOL getHQInfo(const CString& orgname);
DrawStep _drawStep { DrawStep::DrawLogo }; DrawStep _drawStep { DrawStep::DrawLogo };
BOOL getTextFormat(int ResID, TextFormat& formatOut); BOOL getTextFormat(int ResID, TextFormat& formatOut);
void showWindows(std::vector<CStatic*> windows, bool show); void showWindows(std::vector<CStatic*> windows, bool show);
bool _isConsoleRunning{ false }; bool _isConsoleRunning{ false };
bool _isInstalling{ false }; bool _isInstalling{ false };
bool _isFirstDraw{ false }; bool _isFirstDraw{ false };
bool _showSplash{ true }; bool _showSplash{ true };
int _splashStep{ 0 }; int _splashStep{ 0 };
float _logoRotation { 0.0f }; float _logoRotation { 0.0f };
HICON m_hIcon; HICON m_hIcon;
CButton m_btnNext; CButton m_btnNext;
CButton m_trouble_link; CButton m_trouble_link;
CStatic* m_message_label; CStatic* m_message_label;
CStatic* m_action_label; CStatic* m_action_label;
CStatic* m_message2_label; CStatic* m_message2_label;
CStatic* m_action2_label; CStatic* m_action2_label;
CStatic* m_terms; CStatic* m_terms;
CStatic* m_terms2; CStatic* m_terms2;
CStatic* m_trouble; CStatic* m_trouble;
CStatic* m_voxel; CStatic* m_voxel;
CEdit m_orgname; CEdit m_orgname;
CEdit m_username; CEdit m_username;
CEdit m_password; CEdit m_password;
CStatic* m_orgname_banner; CStatic* m_orgname_banner;
CStatic* m_username_banner; CStatic* m_username_banner;
CStatic* m_password_banner; CStatic* m_password_banner;
void drawBackground(CHwndRenderTarget* pRenderTarget); void drawBackground(CHwndRenderTarget* pRenderTarget);
void drawLogo(CHwndRenderTarget* pRenderTarget); void drawLogo(CHwndRenderTarget* pRenderTarget);
void drawSmallLogo(CHwndRenderTarget* pRenderTarget); void drawSmallLogo(CHwndRenderTarget* pRenderTarget);
void drawVoxel(CHwndRenderTarget* pRenderTarget); void drawVoxel(CHwndRenderTarget* pRenderTarget);
void prepareLogin(DrawStep step); void prepareLogin(DrawStep step);
void prepareProcess(DrawStep step); void prepareProcess(DrawStep step);
void prepareChoose(); void prepareChoose();
void prepareError(); void prepareError();
void redrawBanner(const CEdit& edit, CStatic* banner); void redrawBanner(const CEdit& edit, CStatic* banner);
// Generated message map functions // Generated message map functions
virtual BOOL OnInitDialog(); virtual BOOL OnInitDialog();
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
afx_msg void OnPaint(); afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon(); afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnNextClicked(); afx_msg void OnNextClicked();
afx_msg void OnTroubleClicked(); afx_msg void OnTroubleClicked();
afx_msg void OnOrgEditChangeFocus(); afx_msg void OnOrgEditChangeFocus();
afx_msg void OnUserEditChangeFocus(); afx_msg void OnUserEditChangeFocus();
afx_msg void OnPassEditChangeFocus(); afx_msg void OnPassEditChangeFocus();
afx_msg void OnTimer(UINT_PTR nIDEvent); afx_msg void OnTimer(UINT_PTR nIDEvent);
DECLARE_MESSAGE_MAP() DECLARE_MESSAGE_MAP()
public: public:
afx_msg void OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct); afx_msg void OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct);
afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message); afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);
}; };

View file

@ -76,396 +76,399 @@ void LauncherManager::closeLog() {
BOOL LauncherManager::installLauncher() { BOOL LauncherManager::installLauncher() {
addToLog(_T("Installing Launcher.")); addToLog(_T("Installing Launcher."));
CString appPath; CString appPath;
BOOL result = getAndCreatePaths(PathType::Running_Path, appPath); BOOL result = getAndCreatePaths(PathType::Running_Path, appPath);
if (!result) { if (!result) {
MessageBox(NULL, L"Error getting app directory", L"Path Error", MB_OK | MB_ICONERROR); MessageBox(NULL, L"Error getting app directory", L"Path Error", MB_OK | MB_ICONERROR);
} }
CString installDirectory; CString installDirectory;
CString appDirectory = appPath.Left(appPath.ReverseFind('\\') + 1); CString appDirectory = appPath.Left(appPath.ReverseFind('\\') + 1);
result = getAndCreatePaths(PathType::Launcher_Directory, installDirectory); result = getAndCreatePaths(PathType::Launcher_Directory, installDirectory);
if (!result) { if (!result) {
MessageBox(NULL, L"Error getting app desired directory", L"Path Error", MB_OK | MB_ICONERROR); MessageBox(NULL, L"Error getting app desired directory", L"Path Error", MB_OK | MB_ICONERROR);
} }
CString instalationPath = installDirectory + LAUNCHER_EXE_FILENAME; CString instalationPath = installDirectory + LAUNCHER_EXE_FILENAME;
if (!installDirectory.Compare(appDirectory) == 0) { if (!installDirectory.Compare(appDirectory) == 0) {
if (!_shouldUninstall) { if (!_shouldUninstall) {
// The installer is not running on the desired location and has to be installed // The installer is not running on the desired location and has to be installed
// Kill of running before self-copy // Kill of running before self-copy
if (LauncherUtils::IsProcessRunning(LAUNCHER_EXE_FILENAME)) { if (LauncherUtils::IsProcessRunning(LAUNCHER_EXE_FILENAME)) {
::ShellExecute(NULL, NULL, L"taskkill", L"/F /T /IM " + LAUNCHER_EXE_FILENAME, NULL, SW_HIDE); ::ShellExecute(NULL, NULL, L"taskkill", L"/F /T /IM " + LAUNCHER_EXE_FILENAME, NULL, SW_HIDE);
} }
CopyFile(appPath, instalationPath, FALSE); CopyFile(appPath, instalationPath, FALSE);
} }
} else if (_shouldUninstall) { } else if (_shouldUninstall) {
addToLog(_T("Launching uninstall mode.")); addToLog(_T("Launching uninstall mode."));
CString tempPath; CString tempPath;
if (getAndCreatePaths(PathType::Temp_Directory, tempPath)) { if (getAndCreatePaths(PathType::Temp_Directory, tempPath)) {
tempPath += _T("\\HQ_uninstaller_tmp.exe"); tempPath += _T("\\HQ_uninstaller_tmp.exe");
CopyFile(instalationPath, tempPath, false); CopyFile(instalationPath, tempPath, false);
LauncherUtils::launchApplication(tempPath, _T(" --uninstall")); LauncherUtils::launchApplication(tempPath, _T(" --uninstall"));
exit(0); exit(0);
} }
} }
return TRUE; return TRUE;
} }
BOOL LauncherManager::createShortcuts() { BOOL LauncherManager::createShortcuts() {
CString desktopLnkPath; CString desktopLnkPath;
addToLog(_T("Creating shortcuts.")); addToLog(_T("Creating shortcuts."));
getAndCreatePaths(PathType::Desktop_Directory, desktopLnkPath); getAndCreatePaths(PathType::Desktop_Directory, desktopLnkPath);
desktopLnkPath += _T("\\HQ Launcher.lnk"); desktopLnkPath += _T("\\HQ Launcher.lnk");
CString installDir; CString installDir;
getAndCreatePaths(PathType::Launcher_Directory, installDir); getAndCreatePaths(PathType::Launcher_Directory, installDir);
CString installPath = installDir + LAUNCHER_EXE_FILENAME; CString installPath = installDir + LAUNCHER_EXE_FILENAME;
if (!LauncherUtils::CreateLink(installPath, (LPCSTR)CStringA(desktopLnkPath), _T("CLick to Setup and Launch HQ."))) { if (!LauncherUtils::CreateLink(installPath, (LPCSTR)CStringA(desktopLnkPath), _T("CLick to Setup and Launch HQ."))) {
return FALSE; return FALSE;
} }
CString startLinkPath; CString startLinkPath;
getAndCreatePaths(PathType::StartMenu_Directory, startLinkPath); getAndCreatePaths(PathType::StartMenu_Directory, startLinkPath);
CString appStartLinkPath = startLinkPath + _T("HQ Launcher.lnk"); CString appStartLinkPath = startLinkPath + _T("HQ Launcher.lnk");
CString uniStartLinkPath = startLinkPath + _T("Uninstall HQ.lnk"); CString uniStartLinkPath = startLinkPath + _T("Uninstall HQ.lnk");
CString uniLinkPath = installDir + _T("Uninstall HQ.lnk"); CString uniLinkPath = installDir + _T("Uninstall HQ.lnk");
if (!LauncherUtils::CreateLink(installPath, (LPCSTR)CStringA(appStartLinkPath), _T("CLick to Setup and Launch HQ."))) { if (!LauncherUtils::CreateLink(installPath, (LPCSTR)CStringA(appStartLinkPath), _T("CLick to Setup and Launch HQ."))) {
return FALSE; return FALSE;
} }
if (!LauncherUtils::CreateLink(installPath, (LPCSTR)CStringA(uniStartLinkPath), _T("CLick to Uninstall HQ."), _T("--uninstall"))) { if (!LauncherUtils::CreateLink(installPath, (LPCSTR)CStringA(uniStartLinkPath), _T("CLick to Uninstall HQ."), _T("--uninstall"))) {
return FALSE; return FALSE;
} }
if (!LauncherUtils::CreateLink(installPath, (LPCSTR)CStringA(uniLinkPath), _T("CLick to Uninstall HQ."), _T("--uninstall"))) { if (!LauncherUtils::CreateLink(installPath, (LPCSTR)CStringA(uniLinkPath), _T("CLick to Uninstall HQ."), _T("--uninstall"))) {
return FALSE; return FALSE;
} }
return TRUE; return TRUE;
} }
BOOL LauncherManager::deleteShortcuts() { BOOL LauncherManager::deleteShortcuts() {
CString desktopLnkPath; CString desktopLnkPath;
addToLog(_T("Deleting shortcuts.")); addToLog(_T("Deleting shortcuts."));
getAndCreatePaths(PathType::Desktop_Directory, desktopLnkPath); getAndCreatePaths(PathType::Desktop_Directory, desktopLnkPath);
desktopLnkPath += _T("\\HQ Launcher.lnk"); desktopLnkPath += _T("\\HQ Launcher.lnk");
BOOL success = LauncherUtils::deleteFileOrDirectory(desktopLnkPath); BOOL success = LauncherUtils::deleteFileOrDirectory(desktopLnkPath);
CString startLinkPath; CString startLinkPath;
getAndCreatePaths(PathType::StartMenu_Directory, startLinkPath); getAndCreatePaths(PathType::StartMenu_Directory, startLinkPath);
return success && LauncherUtils::deleteFileOrDirectory(startLinkPath); return success && LauncherUtils::deleteFileOrDirectory(startLinkPath);
} }
BOOL LauncherManager::isApplicationInstalled(CString& version, CString& domain, BOOL LauncherManager::isApplicationInstalled(CString& version, CString& domain,
CString& content, bool& loggedIn) { CString& content, bool& loggedIn) {
CString applicationDir; CString applicationDir;
getAndCreatePaths(PathType::Launcher_Directory, applicationDir); getAndCreatePaths(PathType::Launcher_Directory, applicationDir);
CString applicationPath = applicationDir + "interface\\interface.exe"; CString applicationPath = applicationDir + "interface\\interface.exe";
BOOL isApplicationInstalled = PathFileExistsW(applicationPath); BOOL isApplicationInstalled = PathFileExistsW(applicationPath);
BOOL configFileExist = PathFileExistsW(applicationDir + _T("interface\\config.json")); BOOL configFileExist = PathFileExistsW(applicationDir + _T("interface\\config.json"));
if (isApplicationInstalled && configFileExist) { if (isApplicationInstalled && configFileExist) {
LauncherUtils::ResponseError status = readConfigJSON(version, domain, content, loggedIn); LauncherUtils::ResponseError status = readConfigJSON(version, domain, content, loggedIn);
return status == LauncherUtils::ResponseError::NoError; return status == LauncherUtils::ResponseError::NoError;
} }
return FALSE; return FALSE;
} }
BOOL LauncherManager::getAndCreatePaths(PathType type, CString& outPath) { BOOL LauncherManager::getAndCreatePaths(PathType type, CString& outPath) {
if (type == PathType::Running_Path) { if (type == PathType::Running_Path) {
char appPath[MAX_PATH]; char appPath[MAX_PATH];
DWORD size = GetModuleFileNameA(NULL, appPath, MAX_PATH); DWORD size = GetModuleFileNameA(NULL, appPath, MAX_PATH);
if (size) { if (size) {
outPath = CString(appPath); outPath = CString(appPath);
return TRUE; return TRUE;
} }
} else if (type == PathType::Desktop_Directory) { } else if (type == PathType::Desktop_Directory) {
TCHAR desktopPath[MAX_PATH]; TCHAR desktopPath[MAX_PATH];
auto success = SUCCEEDED(SHGetFolderPath(NULL, CSIDL_DESKTOP, NULL, 0, desktopPath)); auto success = SUCCEEDED(SHGetFolderPath(NULL, CSIDL_DESKTOP, NULL, 0, desktopPath));
outPath = CString(desktopPath); outPath = CString(desktopPath);
return success; return success;
} else if (type == PathType::Temp_Directory) { } else if (type == PathType::Temp_Directory) {
TCHAR tempPath[MAX_PATH]; TCHAR tempPath[MAX_PATH];
auto success = GetTempPath(MAX_PATH, tempPath); auto success = GetTempPath(MAX_PATH, tempPath);
outPath = CString(tempPath); outPath = CString(tempPath);
return success; return success;
} else { } else {
TCHAR localDataPath[MAX_PATH]; TCHAR localDataPath[MAX_PATH];
if (type == PathType::StartMenu_Directory) { if (type == PathType::StartMenu_Directory) {
TCHAR startMenuPath[MAX_PATH]; TCHAR startMenuPath[MAX_PATH];
auto success = SUCCEEDED(SHGetFolderPath(NULL, CSIDL_STARTMENU, NULL, 0, startMenuPath)); auto success = SUCCEEDED(SHGetFolderPath(NULL, CSIDL_STARTMENU, NULL, 0, startMenuPath));
outPath = CString(startMenuPath) + _T("\\Programs\\HQ\\"); outPath = CString(startMenuPath) + _T("\\Programs\\HQ\\");
success = SHCreateDirectoryEx(NULL, outPath, NULL) || ERROR_ALREADY_EXISTS == GetLastError(); success = SHCreateDirectoryEx(NULL, outPath, NULL) || ERROR_ALREADY_EXISTS == GetLastError();
return success; return success;
} else if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, localDataPath))) { } else if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, localDataPath))) {
_tcscat_s(localDataPath, _T("\\") + DIRECTORY_NAME_APP + _T("\\")); _tcscat_s(localDataPath, _T("\\") + DIRECTORY_NAME_APP + _T("\\"));
outPath = CString(localDataPath); outPath = CString(localDataPath);
if (type == PathType::Download_Directory) { if (type == PathType::Download_Directory) {
outPath += DIRECTORY_NAME_DOWNLOADS + _T("\\"); outPath += DIRECTORY_NAME_DOWNLOADS + _T("\\");
} else if (type == PathType::Interface_Directory) { } else if (type == PathType::Interface_Directory) {
outPath += DIRECTORY_NAME_INTERFACE; outPath += DIRECTORY_NAME_INTERFACE;
} else if (type == PathType::Content_Directory) { } else if (type == PathType::Content_Directory) {
outPath += DIRECTORY_NAME_CONTENT; outPath += DIRECTORY_NAME_CONTENT;
} }
return (CreateDirectory(outPath, NULL) || ERROR_ALREADY_EXISTS == GetLastError()); return (CreateDirectory(outPath, NULL) || ERROR_ALREADY_EXISTS == GetLastError());
} }
} }
return FALSE; return FALSE;
} }
BOOL LauncherManager::getInstalledVersion(const CString& path, CString& version) { BOOL LauncherManager::getInstalledVersion(const CString& path, CString& version) {
CStdioFile cfile; CStdioFile cfile;
BOOL success = cfile.Open(path, CFile::modeRead); BOOL success = cfile.Open(path, CFile::modeRead);
if (success) { if (success) {
cfile.ReadString(version); cfile.ReadString(version);
cfile.Close(); cfile.Close();
} }
return success; return success;
} }
BOOL LauncherManager::launchApplication(const CString& tokensJSON) { BOOL LauncherManager::launchApplication(const CString& tokensJSON) {
CString installDir; CString installDir;
LauncherManager::getAndCreatePaths(PathType::Interface_Directory, installDir); LauncherManager::getAndCreatePaths(PathType::Interface_Directory, installDir);
CString interfaceExe = installDir + _T("\\interface.exe"); CString interfaceExe = installDir + _T("\\interface.exe");
CString params1 = _T("--url \"") + _domainURL + ("\" "); CString params1 = _T("--url \"") + _domainURL + ("\" ");
CString cacheDir; CString scriptsURL = installDir + _T("\\scripts\\simplifiedUI");
LauncherManager::getAndCreatePaths(PathType::Content_Directory, cacheDir); CString params2 = _T("--scripts \"") + scriptsURL + ("\" ");
CString params3 = _T("--cache \"") + cacheDir + ("\" "); CString cacheDir;
CString params4 = !_displayName.IsEmpty() ? _T("--displayName \"") + _displayName + ("\" ") : _T(""); LauncherManager::getAndCreatePaths(PathType::Content_Directory, cacheDir);
CString parsedTokens = tokensJSON; CString params3 = _T("--cache \"") + cacheDir + ("\" ");
parsedTokens.Replace(_T("\""), _T("\\\"")); CString params4 = !_displayName.IsEmpty() ? _T("--displayName \"") + _displayName + ("\" ") : _T("");
CString params5 = !tokensJSON.IsEmpty() ? _T("--tokens \"") + parsedTokens + ("\"") : _T(""); CString parsedTokens = tokensJSON;
CString params = params1 + params3 + params4 + params5 + EXTRA_PARAMETERS; parsedTokens.Replace(_T("\""), _T("\\\""));
auto rs = ShellExecute(NULL, L"open", interfaceExe, params, NULL, SW_SHOW); CString params5 = !tokensJSON.IsEmpty() ? _T("--tokens \"") + parsedTokens + ("\"") : _T("");
return (rs != NULL); CString params = params1 + params2 + params3 + params4 + params5 + EXTRA_PARAMETERS;
auto rs = ShellExecute(NULL, L"open", interfaceExe, params, NULL, SW_SHOW);
return (rs != NULL);
} }
BOOL LauncherManager::createConfigJSON() { BOOL LauncherManager::createConfigJSON() {
CString configPath; CString configPath;
LauncherManager::getAndCreatePaths(PathType::Interface_Directory, configPath); LauncherManager::getAndCreatePaths(PathType::Interface_Directory, configPath);
configPath += "\\config.json"; configPath += "\\config.json";
std::ofstream configFile(configPath, std::ofstream::binary); std::ofstream configFile(configPath, std::ofstream::binary);
if (configFile.fail()) { if (configFile.fail()) {
return FALSE; return FALSE;
} }
Json::Value config; Json::Value config;
CString applicationPath; CString applicationPath;
LauncherManager::getAndCreatePaths(PathType::Launcher_Directory, applicationPath); LauncherManager::getAndCreatePaths(PathType::Launcher_Directory, applicationPath);
applicationPath += LAUNCHER_EXE_FILENAME; applicationPath += LAUNCHER_EXE_FILENAME;
config["loggedIn"] = _loggedIn; config["loggedIn"] = _loggedIn;
config["launcherPath"] = LauncherUtils::cStringToStd(applicationPath); config["launcherPath"] = LauncherUtils::cStringToStd(applicationPath);
config["version"] = LauncherUtils::cStringToStd(_latestVersion); config["version"] = LauncherUtils::cStringToStd(_latestVersion);
config["domain"] = LauncherUtils::cStringToStd(_domainURL); config["domain"] = LauncherUtils::cStringToStd(_domainURL);
CString content; CString content;
getAndCreatePaths(PathType::Content_Directory, content); getAndCreatePaths(PathType::Content_Directory, content);
config["content"] = LauncherUtils::cStringToStd(content); config["content"] = LauncherUtils::cStringToStd(content);
configFile << config; configFile << config;
configFile.close(); configFile.close();
return TRUE; return TRUE;
} }
LauncherUtils::ResponseError LauncherManager::readConfigJSON(CString& version, CString& domain, CString& content, bool& loggedIn) { LauncherUtils::ResponseError LauncherManager::readConfigJSON(CString& version, CString& domain, CString& content, bool& loggedIn) {
CString configPath; CString configPath;
getAndCreatePaths(PathType::Interface_Directory, configPath); getAndCreatePaths(PathType::Interface_Directory, configPath);
configPath += "\\config.json"; configPath += "\\config.json";
std::ifstream configFile(configPath, std::ifstream::binary); std::ifstream configFile(configPath, std::ifstream::binary);
if (configFile.fail()) { if (configFile.fail()) {
return LauncherUtils::ResponseError::Open; return LauncherUtils::ResponseError::Open;
} }
Json::Value config; Json::Value config;
configFile >> config; configFile >> config;
if (config["version"].isString() && config["domain"].isString() && if (config["version"].isString() && config["domain"].isString() &&
config["content"].isString()) { config["content"].isString()) {
loggedIn = config["loggedIn"].asBool(); loggedIn = config["loggedIn"].asBool();
version = config["version"].asCString(); version = config["version"].asCString();
domain = config["domain"].asCString(); domain = config["domain"].asCString();
content = config["content"].asCString(); content = config["content"].asCString();
configFile.close(); configFile.close();
return LauncherUtils::ResponseError::NoError; return LauncherUtils::ResponseError::NoError;
} }
configFile.close(); configFile.close();
return LauncherUtils::ResponseError::ParsingJSON; return LauncherUtils::ResponseError::ParsingJSON;
} }
LauncherUtils::ResponseError LauncherManager::readOrganizationJSON(const CString& hash) { LauncherUtils::ResponseError LauncherManager::readOrganizationJSON(const CString& hash) {
CString contentTypeJson = L"content-type:application/json"; CString contentTypeJson = L"content-type:application/json";
CString response; CString response;
CString url = _T("/hifi-public/huffman/organizations/") + hash + _T(".json"); CString url = _T("/hifi-public/huffman/organizations/") + hash + _T(".json");
LauncherUtils::ResponseError error = LauncherUtils::makeHTTPCall(L"HQ Launcher", L"s3.amazonaws.com", url, LauncherUtils::ResponseError error = LauncherUtils::makeHTTPCall(L"HQ Launcher", L"s3.amazonaws.com", url,
contentTypeJson, CStringA(), response, false); contentTypeJson, CStringA(), response, false);
if (error != LauncherUtils::ResponseError::NoError) { if (error != LauncherUtils::ResponseError::NoError) {
return error; return error;
} }
Json::Value json; Json::Value json;
if (LauncherUtils::parseJSON(response, json)) { if (LauncherUtils::parseJSON(response, json)) {
if (json["content_set_url"].isString() && json["domain"].isString()) { if (json["content_set_url"].isString() && json["domain"].isString()) {
_contentURL = json["content_set_url"].asCString(); _contentURL = json["content_set_url"].asCString();
_domainURL = json["domain"].asCString(); _domainURL = json["domain"].asCString();
return LauncherUtils::ResponseError::NoError; return LauncherUtils::ResponseError::NoError;
} }
} }
return LauncherUtils::ResponseError::ParsingJSON; return LauncherUtils::ResponseError::ParsingJSON;
} }
LauncherUtils::ResponseError LauncherManager::getMostRecentBuild(CString& urlOut, CString& versionOut) { LauncherUtils::ResponseError LauncherManager::getMostRecentBuild(CString& urlOut, CString& versionOut) {
CString contentTypeJson = L"content-type:application/json"; CString contentTypeJson = L"content-type:application/json";
CString response; CString response;
LauncherUtils::ResponseError error = LauncherUtils::makeHTTPCall(L"HQ Launcher", L"thunder.highfidelity.com", L"/builds/api/tags/latest?format=json", LauncherUtils::ResponseError error = LauncherUtils::makeHTTPCall(L"HQ Launcher", L"thunder.highfidelity.com", L"/builds/api/tags/latest?format=json",
contentTypeJson, CStringA(), response, false); contentTypeJson, CStringA(), response, false);
if (error != LauncherUtils::ResponseError::NoError) { if (error != LauncherUtils::ResponseError::NoError) {
return error; return error;
} }
Json::Value json; Json::Value json;
if (LauncherUtils::parseJSON(response, json)) { if (LauncherUtils::parseJSON(response, json)) {
int count = json["count"].isInt() ? json["count"].asInt() : 0; int count = json["count"].isInt() ? json["count"].asInt() : 0;
if (count > 0 && json["results"].isArray()) { if (count > 0 && json["results"].isArray()) {
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
if (json["results"][i].isObject()) { if (json["results"][i].isObject()) {
Json::Value result = json["results"][i]; Json::Value result = json["results"][i];
if (result["latest_version"].isInt()) { if (result["latest_version"].isInt()) {
std::string version = std::to_string(result["latest_version"].asInt()); std::string version = std::to_string(result["latest_version"].asInt());
versionOut = CString(version.c_str()); versionOut = CString(version.c_str());
} }
if (result["installers"].isObject() && if (result["installers"].isObject() &&
result["installers"]["windows"].isObject() && result["installers"]["windows"].isObject() &&
result["installers"]["windows"]["zip_url"].isString()) { result["installers"]["windows"]["zip_url"].isString()) {
urlOut = result["installers"]["windows"]["zip_url"].asCString(); urlOut = result["installers"]["windows"]["zip_url"].asCString();
return LauncherUtils::ResponseError::NoError; return LauncherUtils::ResponseError::NoError;
} }
} }
} }
} }
} }
return LauncherUtils::ResponseError::ParsingJSON; return LauncherUtils::ResponseError::ParsingJSON;
} }
LauncherUtils::ResponseError LauncherManager::getAccessTokenForCredentials(const CString& username, const CString& password) { LauncherUtils::ResponseError LauncherManager::getAccessTokenForCredentials(const CString& username, const CString& password) {
CStringA post = "grant_type=password&username="; CStringA post = "grant_type=password&username=";
post += username; post += username;
post += "&password="; post += "&password=";
post += password; post += password;
post += "&scope=owner"; post += "&scope=owner";
CString contentTypeText = L"content-type:application/x-www-form-urlencoded"; CString contentTypeText = L"content-type:application/x-www-form-urlencoded";
CString response; CString response;
LauncherUtils::ResponseError error = LauncherUtils::makeHTTPCall(L"HQ Launcher", L"metaverse.highfidelity.com", L"/oauth/token", LauncherUtils::ResponseError error = LauncherUtils::makeHTTPCall(L"HQ Launcher", L"metaverse.highfidelity.com", L"/oauth/token",
contentTypeText, post, response, true); contentTypeText, post, response, true);
if (error != LauncherUtils::ResponseError::NoError) { if (error != LauncherUtils::ResponseError::NoError) {
return error; return error;
} }
Json::Value json; Json::Value json;
if (LauncherUtils::parseJSON(response, json)) { if (LauncherUtils::parseJSON(response, json)) {
if (json["error"].isString()) { if (json["error"].isString()) {
return LauncherUtils::ResponseError::BadCredentials; return LauncherUtils::ResponseError::BadCredentials;
} else if (json["access_token"].isString()) { } else if (json["access_token"].isString()) {
_tokensJSON = response; _tokensJSON = response;
return LauncherUtils::ResponseError::NoError; return LauncherUtils::ResponseError::NoError;
} }
} }
return LauncherUtils::ResponseError::ParsingJSON; return LauncherUtils::ResponseError::ParsingJSON;
} }
BOOL LauncherManager::createApplicationRegistryKeys(int size) { BOOL LauncherManager::createApplicationRegistryKeys(int size) {
const std::string REGISTRY_PATH = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\HQ"; const std::string REGISTRY_PATH = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\HQ";
BOOL success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "DisplayName", "HQ"); BOOL success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "DisplayName", "HQ");
CString installDir; CString installDir;
getAndCreatePaths(PathType::Launcher_Directory, installDir); getAndCreatePaths(PathType::Launcher_Directory, installDir);
success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "InstallLocation", LauncherUtils::cStringToStd(installDir)); success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "InstallLocation", LauncherUtils::cStringToStd(installDir));
std::string applicationExe = LauncherUtils::cStringToStd(installDir + LAUNCHER_EXE_FILENAME); std::string applicationExe = LauncherUtils::cStringToStd(installDir + LAUNCHER_EXE_FILENAME);
std::string uninstallPath = '"' + applicationExe + '"' + " --uninstall"; std::string uninstallPath = '"' + applicationExe + '"' + " --uninstall";
success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "UninstallString", uninstallPath); success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "UninstallString", uninstallPath);
success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "DisplayVersion", LauncherUtils::cStringToStd(_latestVersion)); success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "DisplayVersion", LauncherUtils::cStringToStd(_latestVersion));
success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "DisplayIcon", applicationExe); success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "DisplayIcon", applicationExe);
success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "Publisher", "High Fidelity"); success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "Publisher", "High Fidelity");
success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "InstallDate", LauncherUtils::cStringToStd(CTime::GetCurrentTime().Format("%Y%m%d"))); success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "InstallDate", LauncherUtils::cStringToStd(CTime::GetCurrentTime().Format("%Y%m%d")));
success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "EstimatedSize", (DWORD)size); success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "EstimatedSize", (DWORD)size);
success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "NoModify", (DWORD)1); success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "NoModify", (DWORD)1);
success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "NoRepair", (DWORD)1); success = LauncherUtils::insertRegistryKey(REGISTRY_PATH, "NoRepair", (DWORD)1);
return success; return success;
} }
BOOL LauncherManager::deleteApplicationRegistryKeys() { BOOL LauncherManager::deleteApplicationRegistryKeys() {
const CString REGISTRY_PATH = _T("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\HQ"); const CString REGISTRY_PATH = _T("Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\HQ");
return LauncherUtils::deleteRegistryKey(REGISTRY_PATH); return LauncherUtils::deleteRegistryKey(REGISTRY_PATH);
} }
BOOL LauncherManager::uninstallApplication() { BOOL LauncherManager::uninstallApplication() {
CString installDir; CString installDir;
getAndCreatePaths(PathType::Launcher_Directory, installDir); getAndCreatePaths(PathType::Launcher_Directory, installDir);
BOOL success = LauncherUtils::deleteFileOrDirectory(installDir); BOOL success = LauncherUtils::deleteFileOrDirectory(installDir);
success = success && (deleteShortcuts()); success = success && (deleteShortcuts());
success = success && (deleteApplicationRegistryKeys()); success = success && (deleteApplicationRegistryKeys());
return success; return success;
} }
void LauncherManager::onZipExtracted(ZipType type, int size) { void LauncherManager::onZipExtracted(ZipType type, int size) {
if (type == ZipType::ZipContent) { if (type == ZipType::ZipContent) {
addToLog(_T("Downloading application.")); addToLog(_T("Downloading application."));
downloadApplication(); downloadApplication();
} else if (type == ZipType::ZipApplication) { } else if (type == ZipType::ZipApplication) {
createShortcuts(); createShortcuts();
CString versionPath; CString versionPath;
getAndCreatePaths(LauncherManager::PathType::Launcher_Directory, versionPath); getAndCreatePaths(LauncherManager::PathType::Launcher_Directory, versionPath);
addToLog(_T("Creating config.json")); addToLog(_T("Creating config.json"));
createConfigJSON(); createConfigJSON();
addToLog(_T("Launching application.")); addToLog(_T("Launching application."));
launchApplication(_tokensJSON); launchApplication(_tokensJSON);
addToLog(_T("Creating registry keys.")); addToLog(_T("Creating registry keys."));
createApplicationRegistryKeys(size); createApplicationRegistryKeys(size);
_shouldShutdown = TRUE; _shouldShutdown = TRUE;
} }
} }
BOOL LauncherManager::extractApplication() { BOOL LauncherManager::extractApplication() {
CString installPath; CString installPath;
getAndCreatePaths(LauncherManager::PathType::Interface_Directory, installPath); getAndCreatePaths(LauncherManager::PathType::Interface_Directory, installPath);
BOOL success = LauncherUtils::unzipFileOnThread(ZipType::ZipApplication, LauncherUtils::cStringToStd(_applicationZipPath), BOOL success = LauncherUtils::unzipFileOnThread(ZipType::ZipApplication, LauncherUtils::cStringToStd(_applicationZipPath),
LauncherUtils::cStringToStd(installPath), [&](int type, int size) { LauncherUtils::cStringToStd(installPath), [&](int type, int size) {
onZipExtracted((ZipType)type, size); onZipExtracted((ZipType)type, size);
}); });
return success; return success;
} }
void LauncherManager::onFileDownloaded(DownloadType type) { void LauncherManager::onFileDownloaded(DownloadType type) {
if (type == DownloadType::DownloadContent) { if (type == DownloadType::DownloadContent) {
addToLog(_T("Installing content.")); addToLog(_T("Installing content."));
installContent(); installContent();
} else if (type == DownloadType::DownloadApplication) { } else if (type == DownloadType::DownloadApplication) {
addToLog(_T("Installing application.")); addToLog(_T("Installing application."));
extractApplication(); extractApplication();
} }
} }
BOOL LauncherManager::installContent() { BOOL LauncherManager::installContent() {
std::string contentZipFile = LauncherUtils::cStringToStd(_contentZipPath); std::string contentZipFile = LauncherUtils::cStringToStd(_contentZipPath);
CString contentPath; CString contentPath;
getAndCreatePaths(LauncherManager::PathType::Content_Directory, contentPath); getAndCreatePaths(LauncherManager::PathType::Content_Directory, contentPath);
BOOL success = LauncherUtils::unzipFileOnThread(ZipType::ZipContent, contentZipFile, BOOL success = LauncherUtils::unzipFileOnThread(ZipType::ZipContent, contentZipFile,
LauncherUtils::cStringToStd(contentPath), [&](int type, int size) { LauncherUtils::cStringToStd(contentPath), [&](int type, int size) {
onZipExtracted((ZipType)type, size); onZipExtracted((ZipType)type, size);
}); });
return success; return success;
} }
BOOL LauncherManager::downloadFile(DownloadType type, const CString& url, CString& outPath) { BOOL LauncherManager::downloadFile(DownloadType type, const CString& url, CString& outPath) {
CString fileName = url.Mid(url.ReverseFind('/') + 1); CString fileName = url.Mid(url.ReverseFind('/') + 1);
CString downloadDirectory; CString downloadDirectory;
BOOL success = getAndCreatePaths(LauncherManager::PathType::Download_Directory, downloadDirectory); BOOL success = getAndCreatePaths(LauncherManager::PathType::Download_Directory, downloadDirectory);
outPath = downloadDirectory + fileName; outPath = downloadDirectory + fileName;
if (success) { if (success) {
if (!LauncherUtils::downloadFileOnThread(type, url, outPath, [&](int type) { if (!LauncherUtils::downloadFileOnThread(type, url, outPath, [&](int type) {
onFileDownloaded((DownloadType)type); onFileDownloaded((DownloadType)type);
})) { })) {
success = FALSE; success = FALSE;
} }
} }
return success; return success;
} }
BOOL LauncherManager::downloadContent() { BOOL LauncherManager::downloadContent() {
addToLog(_T("Downloading content.")); addToLog(_T("Downloading content."));
CString contentURL = getContentURL(); CString contentURL = getContentURL();
return downloadFile(DownloadType::DownloadContent, contentURL, _contentZipPath); return downloadFile(DownloadType::DownloadContent, contentURL, _contentZipPath);
} }
BOOL LauncherManager::downloadApplication() { BOOL LauncherManager::downloadApplication() {
CString applicationURL = getLatestInterfaceURL(); CString applicationURL = getLatestInterfaceURL();
return downloadFile(DownloadType::DownloadApplication, applicationURL, _applicationZipPath); return downloadFile(DownloadType::DownloadApplication, applicationURL, _applicationZipPath);
} }

View file

@ -23,91 +23,91 @@ const bool INSTALL_ZIP = true;
class LauncherManager class LauncherManager
{ {
public: public:
enum PathType { enum PathType {
Running_Path = 0, Running_Path = 0,
Launcher_Directory, Launcher_Directory,
Download_Directory, Download_Directory,
Interface_Directory, Interface_Directory,
Desktop_Directory, Desktop_Directory,
Content_Directory, Content_Directory,
StartMenu_Directory, StartMenu_Directory,
Temp_Directory Temp_Directory
}; };
enum ZipType { enum ZipType {
ZipContent = 0, ZipContent = 0,
ZipApplication ZipApplication
}; };
enum DownloadType { enum DownloadType {
DownloadContent = 0, DownloadContent = 0,
DownloadApplication DownloadApplication
}; };
enum ErrorType { enum ErrorType {
ErrorNetworkAuth, ErrorNetworkAuth,
ErrorNetworkUpdate, ErrorNetworkUpdate,
ErrorNetworkHq, ErrorNetworkHq,
ErrorDownloading, ErrorDownloading,
ErrorUpdating, ErrorUpdating,
ErrorInstall, ErrorInstall,
ErrorIOFiles ErrorIOFiles
}; };
LauncherManager(); LauncherManager();
~LauncherManager(); ~LauncherManager();
void init(); void init();
BOOL initLog(); BOOL initLog();
BOOL addToLog(const CString& line); BOOL addToLog(const CString& line);
void closeLog(); void closeLog();
BOOL getAndCreatePaths(PathType type, CString& outPath); BOOL getAndCreatePaths(PathType type, CString& outPath);
BOOL getInstalledVersion(const CString& path, CString& version); BOOL getInstalledVersion(const CString& path, CString& version);
BOOL isApplicationInstalled(CString& version, CString& domain, BOOL isApplicationInstalled(CString& version, CString& domain,
CString& content, bool& loggedIn); CString& content, bool& loggedIn);
LauncherUtils::ResponseError getAccessTokenForCredentials(const CString& username, const CString& password); LauncherUtils::ResponseError getAccessTokenForCredentials(const CString& username, const CString& password);
LauncherUtils::ResponseError getMostRecentBuild(CString& urlOut, CString& versionOut); LauncherUtils::ResponseError getMostRecentBuild(CString& urlOut, CString& versionOut);
LauncherUtils::ResponseError readOrganizationJSON(const CString& hash); LauncherUtils::ResponseError readOrganizationJSON(const CString& hash);
LauncherUtils::ResponseError readConfigJSON(CString& version, CString& domain, LauncherUtils::ResponseError readConfigJSON(CString& version, CString& domain,
CString& content, bool& loggedIn); CString& content, bool& loggedIn);
BOOL createConfigJSON(); BOOL createConfigJSON();
BOOL createApplicationRegistryKeys(int size); BOOL createApplicationRegistryKeys(int size);
BOOL deleteApplicationRegistryKeys(); BOOL deleteApplicationRegistryKeys();
BOOL createShortcuts(); BOOL createShortcuts();
BOOL deleteShortcuts(); BOOL deleteShortcuts();
BOOL launchApplication(const CString& tokensJSON = _T("")); BOOL launchApplication(const CString& tokensJSON = _T(""));
BOOL uninstallApplication(); BOOL uninstallApplication();
BOOL installLauncher(); BOOL installLauncher();
// getters // getters
const CString& getContentURL() const { return _contentURL; } const CString& getContentURL() const { return _contentURL; }
const CString& getdomainURL() const { return _domainURL; } const CString& getdomainURL() const { return _domainURL; }
const CString& getVersion() const { return _version; } const CString& getVersion() const { return _version; }
BOOL shouldShutDown() const { return _shouldShutdown; } BOOL shouldShutDown() const { return _shouldShutdown; }
BOOL needsUpdate() { return _shouldUpdate; } BOOL needsUpdate() { return _shouldUpdate; }
BOOL needsUninstall() { return _shouldUninstall; } BOOL needsUninstall() { return _shouldUninstall; }
void setDisplayName(const CString& displayName) { _displayName = displayName; } void setDisplayName(const CString& displayName) { _displayName = displayName; }
bool isLoggedIn() { return _loggedIn; } bool isLoggedIn() { return _loggedIn; }
const CString& getLatestInterfaceURL() const { return _latestApplicationURL; } const CString& getLatestInterfaceURL() const { return _latestApplicationURL; }
void uninstall() { _shouldUninstall = true; }; void uninstall() { _shouldUninstall = true; };
BOOL downloadFile(DownloadType type, const CString& url, CString& localPath); BOOL downloadFile(DownloadType type, const CString& url, CString& localPath);
BOOL downloadContent(); BOOL downloadContent();
BOOL downloadApplication(); BOOL downloadApplication();
BOOL installContent(); BOOL installContent();
BOOL extractApplication(); BOOL extractApplication();
void onZipExtracted(ZipType type, int size); void onZipExtracted(ZipType type, int size);
void onFileDownloaded(DownloadType type); void onFileDownloaded(DownloadType type);
private: private:
CString _latestApplicationURL; CString _latestApplicationURL;
CString _latestVersion; CString _latestVersion;
CString _contentURL; CString _contentURL;
CString _domainURL; CString _domainURL;
CString _version; CString _version;
CString _displayName; CString _displayName;
CString _tokensJSON; CString _tokensJSON;
CString _applicationZipPath; CString _applicationZipPath;
CString _contentZipPath; CString _contentZipPath;
bool _loggedIn{ false }; bool _loggedIn{ false };
BOOL _shouldUpdate{ FALSE }; BOOL _shouldUpdate{ FALSE };
BOOL _shouldUninstall{ FALSE }; BOOL _shouldUninstall{ FALSE };
BOOL _shouldShutdown{ FALSE }; BOOL _shouldShutdown{ FALSE };
CStdioFile _logFile; CStdioFile _logFile;
}; };

View file

@ -36,360 +36,360 @@ CString LauncherUtils::urlEncodeString(const CString& url) {
} }
BOOL LauncherUtils::IsProcessRunning(const wchar_t *processName) { BOOL LauncherUtils::IsProcessRunning(const wchar_t *processName) {
bool exists = false; bool exists = false;
PROCESSENTRY32 entry; PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32); entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry)) { if (Process32First(snapshot, &entry)) {
while (Process32Next(snapshot, &entry)) { while (Process32Next(snapshot, &entry)) {
if (!_wcsicmp(entry.szExeFile, processName)) { if (!_wcsicmp(entry.szExeFile, processName)) {
exists = true; exists = true;
break; break;
} }
} }
} }
CloseHandle(snapshot); CloseHandle(snapshot);
return exists; return exists;
} }
HRESULT LauncherUtils::CreateLink(LPCWSTR lpszPathObj, LPCSTR lpszPathLink, LPCWSTR lpszDesc, LPCWSTR lpszArgs) { HRESULT LauncherUtils::CreateLink(LPCWSTR lpszPathObj, LPCSTR lpszPathLink, LPCWSTR lpszDesc, LPCWSTR lpszArgs) {
IShellLink* psl; IShellLink* psl;
// Get a pointer to the IShellLink interface. It is assumed that CoInitialize // Get a pointer to the IShellLink interface. It is assumed that CoInitialize
// has already been called. // has already been called.
CoInitialize(NULL); CoInitialize(NULL);
HRESULT hres = E_INVALIDARG; HRESULT hres = E_INVALIDARG;
if ((lpszPathObj != NULL) && (wcslen(lpszPathObj) > 0) && if ((lpszPathObj != NULL) && (wcslen(lpszPathObj) > 0) &&
(lpszDesc != NULL) && (lpszDesc != NULL) &&
(lpszPathLink != NULL) && (strlen(lpszPathLink) > 0)) { (lpszPathLink != NULL) && (strlen(lpszPathLink) > 0)) {
hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl); hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl);
if (SUCCEEDED(hres)) { if (SUCCEEDED(hres)) {
IPersistFile* ppf; IPersistFile* ppf;
// Set the path to the shortcut target and add the description. // Set the path to the shortcut target and add the description.
psl->SetPath(lpszPathObj); psl->SetPath(lpszPathObj);
psl->SetDescription(lpszDesc); psl->SetDescription(lpszDesc);
psl->SetArguments(lpszArgs); psl->SetArguments(lpszArgs);
// Query IShellLink for the IPersistFile interface, used for saving the // Query IShellLink for the IPersistFile interface, used for saving the
// shortcut in persistent storage. // shortcut in persistent storage.
hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf); hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf);
if (SUCCEEDED(hres)) { if (SUCCEEDED(hres)) {
WCHAR wsz[MAX_PATH]; WCHAR wsz[MAX_PATH];
// Ensure that the string is Unicode. // Ensure that the string is Unicode.
MultiByteToWideChar(CP_ACP, 0, lpszPathLink, -1, wsz, MAX_PATH); MultiByteToWideChar(CP_ACP, 0, lpszPathLink, -1, wsz, MAX_PATH);
// Add code here to check return value from MultiByteWideChar // Add code here to check return value from MultiByteWideChar
// for success. // for success.
// Save the link by calling IPersistFile::Save. // Save the link by calling IPersistFile::Save.
hres = ppf->Save(wsz, TRUE); hres = ppf->Save(wsz, TRUE);
ppf->Release(); ppf->Release();
} }
psl->Release(); psl->Release();
} }
} }
CoUninitialize(); CoUninitialize();
return SUCCEEDED(hres); return SUCCEEDED(hres);
} }
std::string LauncherUtils::cStringToStd(CString cstring) { std::string LauncherUtils::cStringToStd(CString cstring) {
CT2CA convertedString(cstring); CT2CA convertedString(cstring);
std::string strStd(convertedString); std::string strStd(convertedString);
return strStd; return strStd;
} }
BOOL LauncherUtils::launchApplication(LPCWSTR lpApplicationName, LPTSTR cmdArgs) { BOOL LauncherUtils::launchApplication(LPCWSTR lpApplicationName, LPTSTR cmdArgs) {
// additional information // additional information
STARTUPINFO si; STARTUPINFO si;
PROCESS_INFORMATION pi; PROCESS_INFORMATION pi;
// set the size of the structures // set the size of the structures
ZeroMemory(&si, sizeof(si)); ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si); si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi)); ZeroMemory(&pi, sizeof(pi));
// start the program up // start the program up
BOOL success = CreateProcess( BOOL success = CreateProcess(
lpApplicationName, // the path lpApplicationName, // the path
cmdArgs, // Command line cmdArgs, // Command line
NULL, // Process handle not inheritable NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE FALSE, // Set handle inheritance to FALSE
CREATE_NEW_CONSOLE, // Opens file in a separate console CREATE_NEW_CONSOLE, // Opens file in a separate console
NULL, // Use parent's environment block NULL, // Use parent's environment block
NULL, // Use parent's starting directory NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure &si, // Pointer to STARTUPINFO structure
&pi // Pointer to PROCESS_INFORMATION structure &pi // Pointer to PROCESS_INFORMATION structure
); );
// Close process and thread handles. // Close process and thread handles.
CloseHandle(pi.hProcess); CloseHandle(pi.hProcess);
CloseHandle(pi.hThread); CloseHandle(pi.hThread);
return success; return success;
} }
BOOL LauncherUtils::deleteRegistryKey(const CString& registryPath) { BOOL LauncherUtils::deleteRegistryKey(const CString& registryPath) {
TCHAR szDelKey[MAX_PATH * 2]; TCHAR szDelKey[MAX_PATH * 2];
StringCchCopy(szDelKey, MAX_PATH * 2, registryPath); StringCchCopy(szDelKey, MAX_PATH * 2, registryPath);
auto status = RegDeleteKey(HKEY_CURRENT_USER, szDelKey); auto status = RegDeleteKey(HKEY_CURRENT_USER, szDelKey);
if (status == ERROR_SUCCESS) { if (status == ERROR_SUCCESS) {
return TRUE; return TRUE;
} }
return FALSE; return FALSE;
} }
LauncherUtils::ResponseError LauncherUtils::makeHTTPCall(const CString& callerName, LauncherUtils::ResponseError LauncherUtils::makeHTTPCall(const CString& callerName,
const CString& mainUrl, const CString& dirUrl, const CString& mainUrl, const CString& dirUrl,
const CString& contentType, CStringA& postData, const CString& contentType, CStringA& postData,
CString& response, bool isPost = false) { CString& response, bool isPost = false) {
HINTERNET hopen = WinHttpOpen(callerName, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, HINTERNET hopen = WinHttpOpen(callerName, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
if (!hopen) { if (!hopen) {
return ResponseError::Open; return ResponseError::Open;
} }
HINTERNET hconnect = WinHttpConnect(hopen, mainUrl, INTERNET_DEFAULT_HTTPS_PORT, 0); HINTERNET hconnect = WinHttpConnect(hopen, mainUrl, INTERNET_DEFAULT_HTTPS_PORT, 0);
if (!hconnect) { if (!hconnect) {
return ResponseError::Connect; return ResponseError::Connect;
} }
HINTERNET hrequest = WinHttpOpenRequest(hconnect, isPost ? L"POST" : L"GET", dirUrl, HINTERNET hrequest = WinHttpOpenRequest(hconnect, isPost ? L"POST" : L"GET", dirUrl,
NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE); NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_SECURE);
if (!hrequest) { if (!hrequest) {
return ResponseError::OpenRequest; return ResponseError::OpenRequest;
} }
if (isPost) { if (isPost) {
if (!WinHttpSendRequest(hrequest, contentType, -1, if (!WinHttpSendRequest(hrequest, contentType, -1,
postData.GetBuffer(postData.GetLength()), (DWORD)strlen(postData), (DWORD)strlen(postData), NULL)) { postData.GetBuffer(postData.GetLength()), (DWORD)strlen(postData), (DWORD)strlen(postData), NULL)) {
return ResponseError::SendRequest; return ResponseError::SendRequest;
} }
} else { } else {
if (!WinHttpSendRequest(hrequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0)) { if (!WinHttpSendRequest(hrequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0)) {
return ResponseError::SendRequest; return ResponseError::SendRequest;
} }
} }
if (!WinHttpReceiveResponse(hrequest, 0)) { if (!WinHttpReceiveResponse(hrequest, 0)) {
return ResponseError::ReceiveRequest; return ResponseError::ReceiveRequest;
} }
// query remote file size, set haveContentLength on success and dwContentLength to the length // query remote file size, set haveContentLength on success and dwContentLength to the length
wchar_t szContentLength[32]; wchar_t szContentLength[32];
DWORD bufferBytes = 4096; DWORD bufferBytes = 4096;
DWORD dwHeaderIndex = WINHTTP_NO_HEADER_INDEX; DWORD dwHeaderIndex = WINHTTP_NO_HEADER_INDEX;
BOOL haveContentLength = WinHttpQueryHeaders(hrequest, WINHTTP_QUERY_CONTENT_LENGTH, NULL, BOOL haveContentLength = WinHttpQueryHeaders(hrequest, WINHTTP_QUERY_CONTENT_LENGTH, NULL,
&szContentLength, &bufferBytes, &dwHeaderIndex); &szContentLength, &bufferBytes, &dwHeaderIndex);
DWORD dwContentLength; DWORD dwContentLength;
if (haveContentLength) { if (haveContentLength) {
dwContentLength = _wtoi(szContentLength); dwContentLength = _wtoi(szContentLength);
} }
byte p[4096]; byte p[4096];
if (!WinHttpQueryDataAvailable(hrequest, &bufferBytes)) { if (!WinHttpQueryDataAvailable(hrequest, &bufferBytes)) {
return ResponseError::ReadResponse; return ResponseError::ReadResponse;
} }
WinHttpReadData(hrequest, p, bufferBytes, &bufferBytes); WinHttpReadData(hrequest, p, bufferBytes, &bufferBytes);
response = CString((const char*)p, (int)bufferBytes); response = CString((const char*)p, (int)bufferBytes);
return ResponseError::NoError; return ResponseError::NoError;
} }
BOOL LauncherUtils::parseJSON(const CString& jsonTxt, Json::Value& root) { BOOL LauncherUtils::parseJSON(const CString& jsonTxt, Json::Value& root) {
Json::CharReaderBuilder CharBuilder; Json::CharReaderBuilder CharBuilder;
std::string jsonString = cStringToStd(jsonTxt); std::string jsonString = cStringToStd(jsonTxt);
std::string errs; std::string errs;
Json::CharReader* nreader = CharBuilder.newCharReader(); Json::CharReader* nreader = CharBuilder.newCharReader();
bool parsingSuccessful = false; bool parsingSuccessful = false;
if (nreader != NULL) { if (nreader != NULL) {
parsingSuccessful = nreader->parse(jsonString.c_str(), jsonString.c_str() + jsonString.length(), &root, &errs); parsingSuccessful = nreader->parse(jsonString.c_str(), jsonString.c_str() + jsonString.length(), &root, &errs);
delete nreader; delete nreader;
} }
return parsingSuccessful; return parsingSuccessful;
} }
BOOL LauncherUtils::getFont(const CString& fontName, int fontSize, bool isBold, CFont& fontOut) { BOOL LauncherUtils::getFont(const CString& fontName, int fontSize, bool isBold, CFont& fontOut) {
LOGFONT lf; LOGFONT lf;
memset(&lf, 0, sizeof(lf)); memset(&lf, 0, sizeof(lf));
lf.lfHeight = fontSize; lf.lfHeight = fontSize;
lf.lfWeight = isBold ? FW_BOLD : FW_NORMAL; lf.lfWeight = isBold ? FW_BOLD : FW_NORMAL;
lf.lfOutPrecision = OUT_TT_ONLY_PRECIS; lf.lfOutPrecision = OUT_TT_ONLY_PRECIS;
lf.lfQuality = ANTIALIASED_QUALITY; lf.lfQuality = ANTIALIASED_QUALITY;
wcscpy_s(lf.lfFaceName, fontName); wcscpy_s(lf.lfFaceName, fontName);
if (!fontOut.CreateFontIndirect(&lf)) { if (!fontOut.CreateFontIndirect(&lf)) {
return FALSE; return FALSE;
} }
return TRUE; return TRUE;
} }
uint64_t LauncherUtils::extractZip(const std::string& zipFile, const std::string& path, std::vector<std::string>& files) { uint64_t LauncherUtils::extractZip(const std::string& zipFile, const std::string& path, std::vector<std::string>& files) {
mz_zip_archive zip_archive; mz_zip_archive zip_archive;
memset(&zip_archive, 0, sizeof(zip_archive)); memset(&zip_archive, 0, sizeof(zip_archive));
auto status = mz_zip_reader_init_file(&zip_archive, zipFile.c_str(), 0); auto status = mz_zip_reader_init_file(&zip_archive, zipFile.c_str(), 0);
if (!status) return 0; if (!status) return 0;
int fileCount = (int)mz_zip_reader_get_num_files(&zip_archive); int fileCount = (int)mz_zip_reader_get_num_files(&zip_archive);
if (fileCount == 0) { if (fileCount == 0) {
mz_zip_reader_end(&zip_archive); mz_zip_reader_end(&zip_archive);
return 0; return 0;
} }
mz_zip_archive_file_stat file_stat; mz_zip_archive_file_stat file_stat;
if (!mz_zip_reader_file_stat(&zip_archive, 0, &file_stat)) { if (!mz_zip_reader_file_stat(&zip_archive, 0, &file_stat)) {
mz_zip_reader_end(&zip_archive); mz_zip_reader_end(&zip_archive);
return 0; return 0;
} }
// Get root folder // Get root folder
CString lastDir = _T(""); CString lastDir = _T("");
uint64_t totalSize = 0; uint64_t totalSize = 0;
for (int i = 0; i < fileCount; i++) { for (int i = 0; i < fileCount; i++) {
if (!mz_zip_reader_file_stat(&zip_archive, i, &file_stat)) continue; if (!mz_zip_reader_file_stat(&zip_archive, i, &file_stat)) continue;
std::string filename = file_stat.m_filename; std::string filename = file_stat.m_filename;
std::replace(filename.begin(), filename.end(), '/', '\\'); std::replace(filename.begin(), filename.end(), '/', '\\');
CString fullFilename = CString(path.c_str()) + "\\" + CString(filename.c_str()); CString fullFilename = CString(path.c_str()) + "\\" + CString(filename.c_str());
if (mz_zip_reader_is_file_a_directory(&zip_archive, i)) { if (mz_zip_reader_is_file_a_directory(&zip_archive, i)) {
if (SHCreateDirectoryEx(NULL, fullFilename, NULL) || ERROR_ALREADY_EXISTS == GetLastError()) { if (SHCreateDirectoryEx(NULL, fullFilename, NULL) || ERROR_ALREADY_EXISTS == GetLastError()) {
break; break;
} else { } else {
continue; continue;
} }
} }
CT2A destFile(fullFilename); CT2A destFile(fullFilename);
if (mz_zip_reader_extract_to_file(&zip_archive, i, destFile, 0)) { if (mz_zip_reader_extract_to_file(&zip_archive, i, destFile, 0)) {
totalSize += (uint64_t)file_stat.m_uncomp_size; totalSize += (uint64_t)file_stat.m_uncomp_size;
files.emplace_back(destFile); files.emplace_back(destFile);
} }
} }
// Close the archive, freeing any resources it was using // Close the archive, freeing any resources it was using
mz_zip_reader_end(&zip_archive); mz_zip_reader_end(&zip_archive);
return totalSize; return totalSize;
} }
BOOL LauncherUtils::insertRegistryKey(const std::string& regPath, const std::string& name, const std::string& value) { BOOL LauncherUtils::insertRegistryKey(const std::string& regPath, const std::string& name, const std::string& value) {
HKEY key; HKEY key;
auto status = RegCreateKeyExA(HKEY_CURRENT_USER, regPath.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_QUERY_VALUE, NULL, &key, NULL); auto status = RegCreateKeyExA(HKEY_CURRENT_USER, regPath.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_QUERY_VALUE, NULL, &key, NULL);
if (status == ERROR_SUCCESS) { if (status == ERROR_SUCCESS) {
status = RegSetValueExA(key, name.c_str(), 0, REG_SZ, (const BYTE*)value.c_str(), (DWORD)(value.size() + 1)); status = RegSetValueExA(key, name.c_str(), 0, REG_SZ, (const BYTE*)value.c_str(), (DWORD)(value.size() + 1));
return status == ERROR_SUCCESS; return status == ERROR_SUCCESS;
} }
RegCloseKey(key); RegCloseKey(key);
return FALSE; return FALSE;
} }
BOOL LauncherUtils::insertRegistryKey(const std::string& regPath, const std::string& name, DWORD value) { BOOL LauncherUtils::insertRegistryKey(const std::string& regPath, const std::string& name, DWORD value) {
HKEY key; HKEY key;
auto status = RegCreateKeyExA(HKEY_CURRENT_USER, regPath.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_QUERY_VALUE, NULL, &key, NULL); auto status = RegCreateKeyExA(HKEY_CURRENT_USER, regPath.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE | KEY_QUERY_VALUE, NULL, &key, NULL);
if (status == ERROR_SUCCESS) { if (status == ERROR_SUCCESS) {
status = RegSetValueExA(key, name.c_str(), 0, REG_DWORD, (const BYTE*)&value, sizeof(value)); status = RegSetValueExA(key, name.c_str(), 0, REG_DWORD, (const BYTE*)&value, sizeof(value));
return TRUE; return TRUE;
} }
RegCloseKey(key); RegCloseKey(key);
return FALSE; return FALSE;
} }
BOOL LauncherUtils::deleteFileOrDirectory(const CString& dirPath, bool noRecycleBin) { BOOL LauncherUtils::deleteFileOrDirectory(const CString& dirPath, bool noRecycleBin) {
CString dir = dirPath; CString dir = dirPath;
// Add extra null to string // Add extra null to string
dir.AppendChar(0); dir.AppendChar(0);
SHFILEOPSTRUCT fileop; SHFILEOPSTRUCT fileop;
fileop.hwnd = NULL; // no status display fileop.hwnd = NULL; // no status display
fileop.wFunc = FO_DELETE; // delete operation fileop.wFunc = FO_DELETE; // delete operation
fileop.pFrom = dir; // source file name as double null terminated string fileop.pFrom = dir; // source file name as double null terminated string
fileop.pTo = NULL; // no destination needed fileop.pTo = NULL; // no destination needed
fileop.fFlags = FOF_NOCONFIRMATION | FOF_SILENT; // do not prompt the user fileop.fFlags = FOF_NOCONFIRMATION | FOF_SILENT; // do not prompt the user
if (!noRecycleBin) { if (!noRecycleBin) {
fileop.fFlags |= FOF_ALLOWUNDO; fileop.fFlags |= FOF_ALLOWUNDO;
} }
fileop.fAnyOperationsAborted = FALSE; fileop.fAnyOperationsAborted = FALSE;
fileop.lpszProgressTitle = NULL; fileop.lpszProgressTitle = NULL;
fileop.hNameMappings = NULL; fileop.hNameMappings = NULL;
int ret = SHFileOperation(&fileop); int ret = SHFileOperation(&fileop);
return (ret == 0); return (ret == 0);
} }
BOOL LauncherUtils::hMac256(const CString& cmessage, const char* keystr, CString& hashOut) { BOOL LauncherUtils::hMac256(const CString& cmessage, const char* keystr, CString& hashOut) {
char message[256]; char message[256];
strcpy_s(message, CStringA(cmessage).GetString()); strcpy_s(message, CStringA(cmessage).GetString());
char key[256]; char key[256];
strcpy_s(key, keystr); strcpy_s(key, keystr);
HCRYPTPROV hProv = 0; HCRYPTPROV hProv = 0;
HCRYPTHASH hHash = 0; HCRYPTHASH hHash = 0;
HCRYPTKEY hKey = 0; HCRYPTKEY hKey = 0;
HCRYPTHASH hHmacHash = 0; HCRYPTHASH hHmacHash = 0;
BYTE pbHash[32]; BYTE pbHash[32];
HMAC_INFO HmacInfo; HMAC_INFO HmacInfo;
int err = 0; int err = 0;
typedef struct blob { typedef struct blob {
BLOBHEADER header; BLOBHEADER header;
DWORD len; DWORD len;
BYTE key[1]; BYTE key[1];
} m_blob; } m_blob;
ZeroMemory(&HmacInfo, sizeof(HmacInfo)); ZeroMemory(&HmacInfo, sizeof(HmacInfo));
HmacInfo.HashAlgid = CALG_SHA_256; HmacInfo.HashAlgid = CALG_SHA_256;
ZeroMemory(&pbHash, 32); ZeroMemory(&pbHash, 32);
m_blob* kb = NULL; m_blob* kb = NULL;
DWORD kbSize = DWORD(sizeof(m_blob) + strlen(key)); DWORD kbSize = DWORD(sizeof(m_blob) + strlen(key));
kb = (m_blob*)malloc(kbSize); kb = (m_blob*)malloc(kbSize);
kb->header.bType = PLAINTEXTKEYBLOB; kb->header.bType = PLAINTEXTKEYBLOB;
kb->header.bVersion = CUR_BLOB_VERSION; kb->header.bVersion = CUR_BLOB_VERSION;
kb->header.reserved = 0; kb->header.reserved = 0;
kb->header.aiKeyAlg = CALG_RC2; kb->header.aiKeyAlg = CALG_RC2;
memcpy(&kb->key, key, strlen(key)); memcpy(&kb->key, key, strlen(key));
kb->len = (DWORD)strlen(key); kb->len = (DWORD)strlen(key);
BOOL success = false; BOOL success = false;
DWORD datalen = (DWORD)32; DWORD datalen = (DWORD)32;
if (CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_NEWKEYSET) if (CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_NEWKEYSET)
&& CryptImportKey(hProv, (BYTE*)kb, kbSize, 0, CRYPT_IPSEC_HMAC_KEY, &hKey) && CryptImportKey(hProv, (BYTE*)kb, kbSize, 0, CRYPT_IPSEC_HMAC_KEY, &hKey)
&& CryptCreateHash(hProv, CALG_HMAC, hKey, 0, &hHmacHash) && CryptCreateHash(hProv, CALG_HMAC, hKey, 0, &hHmacHash)
&& CryptSetHashParam(hHmacHash, HP_HMAC_INFO, (BYTE*)&HmacInfo, 0) && CryptSetHashParam(hHmacHash, HP_HMAC_INFO, (BYTE*)&HmacInfo, 0)
&& CryptHashData(hHmacHash, (BYTE*)message, (DWORD)strlen(message), 0) && CryptHashData(hHmacHash, (BYTE*)message, (DWORD)strlen(message), 0)
&& CryptGetHashParam(hHmacHash, HP_HASHVAL, pbHash, &datalen, 0)) { && CryptGetHashParam(hHmacHash, HP_HASHVAL, pbHash, &datalen, 0)) {
char *Hex = "0123456789abcdef"; char *Hex = "0123456789abcdef";
char HashString[65] = { 0 }; char HashString[65] = { 0 };
for (int Count = 0; Count < 32; Count++) for (int Count = 0; Count < 32; Count++)
{ {
HashString[Count * 2] = Hex[pbHash[Count] >> 4]; HashString[Count * 2] = Hex[pbHash[Count] >> 4];
HashString[(Count * 2) + 1] = Hex[pbHash[Count] & 0xF]; HashString[(Count * 2) + 1] = Hex[pbHash[Count] & 0xF];
} }
hashOut = CString(HashString); hashOut = CString(HashString);
success = true; success = true;
} }
free(kb); free(kb);
if (hHmacHash) if (hHmacHash)
CryptDestroyHash(hHmacHash); CryptDestroyHash(hHmacHash);
if (hKey) if (hKey)
CryptDestroyKey(hKey); CryptDestroyKey(hKey);
if (hHash) if (hHash)
CryptDestroyHash(hHash); CryptDestroyHash(hHash);
if (hProv) if (hProv)
CryptReleaseContext(hProv, 0); CryptReleaseContext(hProv, 0);
return success; return success;
} }
DWORD WINAPI LauncherUtils::unzipThread(LPVOID lpParameter) { DWORD WINAPI LauncherUtils::unzipThread(LPVOID lpParameter) {
UnzipThreadData& data = *((UnzipThreadData*)lpParameter); UnzipThreadData& data = *((UnzipThreadData*)lpParameter);
uint64_t size = LauncherUtils::extractZip(data._zipFile, data._path, std::vector<std::string>()); uint64_t size = LauncherUtils::extractZip(data._zipFile, data._path, std::vector<std::string>());
int mb_size = (int)(size * 0.001f); int mb_size = (int)(size * 0.001f);
data.callback(data._type, mb_size); data.callback(data._type, mb_size);
delete &data; delete &data;
return 0; return 0;
} }
DWORD WINAPI LauncherUtils::downloadThread(LPVOID lpParameter) DWORD WINAPI LauncherUtils::downloadThread(LPVOID lpParameter)
{ {
DownloadThreadData& data = *((DownloadThreadData*)lpParameter); DownloadThreadData& data = *((DownloadThreadData*)lpParameter);
auto hr = URLDownloadToFile(0, data._url, data._file, 0, NULL); auto hr = URLDownloadToFile(0, data._url, data._file, 0, NULL);
data.callback(data._type); data.callback(data._type);
return 0; return 0;
} }
DWORD WINAPI LauncherUtils::deleteDirectoriesThread(LPVOID lpParameter) { DWORD WINAPI LauncherUtils::deleteDirectoriesThread(LPVOID lpParameter) {
@ -406,33 +406,33 @@ DWORD WINAPI LauncherUtils::deleteDirectoriesThread(LPVOID lpParameter) {
} }
BOOL LauncherUtils::unzipFileOnThread(int type, const std::string& zipFile, const std::string& path, std::function<void(int, int)> callback) { BOOL LauncherUtils::unzipFileOnThread(int type, const std::string& zipFile, const std::string& path, std::function<void(int, int)> callback) {
DWORD myThreadID; DWORD myThreadID;
UnzipThreadData* unzipThreadData = new UnzipThreadData(); UnzipThreadData* unzipThreadData = new UnzipThreadData();
unzipThreadData->_type = type; unzipThreadData->_type = type;
unzipThreadData->_zipFile = zipFile; unzipThreadData->_zipFile = zipFile;
unzipThreadData->_path = path; unzipThreadData->_path = path;
unzipThreadData->setCallback(callback); unzipThreadData->setCallback(callback);
HANDLE myHandle = CreateThread(0, 0, unzipThread, unzipThreadData, 0, &myThreadID); HANDLE myHandle = CreateThread(0, 0, unzipThread, unzipThreadData, 0, &myThreadID);
if (myHandle) { if (myHandle) {
CloseHandle(myHandle); CloseHandle(myHandle);
return TRUE; return TRUE;
} }
return FALSE; return FALSE;
} }
BOOL LauncherUtils::downloadFileOnThread(int type, const CString& url, const CString& file, std::function<void(int)> callback) { BOOL LauncherUtils::downloadFileOnThread(int type, const CString& url, const CString& file, std::function<void(int)> callback) {
DWORD myThreadID; DWORD myThreadID;
DownloadThreadData* downloadThreadData = new DownloadThreadData(); DownloadThreadData* downloadThreadData = new DownloadThreadData();
downloadThreadData->_type = type; downloadThreadData->_type = type;
downloadThreadData->_url = url; downloadThreadData->_url = url;
downloadThreadData->_file = file; downloadThreadData->_file = file;
downloadThreadData->setCallback(callback); downloadThreadData->setCallback(callback);
HANDLE myHandle = CreateThread(0, 0, downloadThread, downloadThreadData, 0, &myThreadID); HANDLE myHandle = CreateThread(0, 0, downloadThread, downloadThreadData, 0, &myThreadID);
if (myHandle) { if (myHandle) {
CloseHandle(myHandle); CloseHandle(myHandle);
return TRUE; return TRUE;
} }
return FALSE; return FALSE;
} }
BOOL LauncherUtils::deleteDirectoriesOnThread(const CString& applicationDir, BOOL LauncherUtils::deleteDirectoriesOnThread(const CString& applicationDir,

View file

@ -18,17 +18,17 @@
class LauncherUtils class LauncherUtils
{ {
public: public:
enum ResponseError { enum ResponseError {
Open = 0, Open = 0,
Connect, Connect,
OpenRequest, OpenRequest,
SendRequest, SendRequest,
ReceiveRequest, ReceiveRequest,
ReadResponse, ReadResponse,
ParsingJSON, ParsingJSON,
BadCredentials, BadCredentials,
NoError NoError
}; };
enum DeleteDirError { enum DeleteDirError {
NoErrorDeleting = 0, NoErrorDeleting = 0,
@ -37,27 +37,27 @@ public:
ErrorDeletingBothDirs ErrorDeletingBothDirs
}; };
struct DownloadThreadData { struct DownloadThreadData {
int _type; int _type;
CString _url; CString _url;
CString _file; CString _file;
std::function<void(int)> callback; std::function<void(int)> callback;
// function(type) // function(type)
void setCallback(std::function<void(int)> fn) { void setCallback(std::function<void(int)> fn) {
callback = std::bind(fn, std::placeholders::_1); callback = std::bind(fn, std::placeholders::_1);
} }
}; };
struct UnzipThreadData { struct UnzipThreadData {
int _type; int _type;
std::string _zipFile; std::string _zipFile;
std::string _path; std::string _path;
// function(type, size) // function(type, size)
std::function<void(int, int)> callback; std::function<void(int, int)> callback;
void setCallback(std::function<void(int, int)> fn) { void setCallback(std::function<void(int, int)> fn) {
callback = std::bind(fn, std::placeholders::_1, std::placeholders::_2); callback = std::bind(fn, std::placeholders::_1, std::placeholders::_2);
} }
}; };
struct DeleteThreadData { struct DeleteThreadData {
CString _applicationDir; CString _applicationDir;
@ -66,31 +66,31 @@ public:
void setCallback(std::function<void(int)> fn) { callback = std::bind(fn, std::placeholders::_1); } void setCallback(std::function<void(int)> fn) { callback = std::bind(fn, std::placeholders::_1); }
}; };
static BOOL parseJSON(const CString& jsonTxt, Json::Value& jsonObject); static BOOL parseJSON(const CString& jsonTxt, Json::Value& jsonObject);
static ResponseError makeHTTPCall(const CString& callerName, const CString& mainUrl, static ResponseError makeHTTPCall(const CString& callerName, const CString& mainUrl,
const CString& dirUrl, const CString& contentType, const CString& dirUrl, const CString& contentType,
CStringA& postData, CString& response, bool isPost); CStringA& postData, CString& response, bool isPost);
static std::string cStringToStd(CString cstring); static std::string cStringToStd(CString cstring);
static BOOL getFont(const CString& fontName, int fontSize, bool isBold, CFont& fontOut); static BOOL getFont(const CString& fontName, int fontSize, bool isBold, CFont& fontOut);
static BOOL launchApplication(LPCWSTR lpApplicationName, LPTSTR cmdArgs = _T("")); static BOOL launchApplication(LPCWSTR lpApplicationName, LPTSTR cmdArgs = _T(""));
static BOOL IsProcessRunning(const wchar_t *processName); static BOOL IsProcessRunning(const wchar_t *processName);
static BOOL insertRegistryKey(const std::string& regPath, const std::string& name, const std::string& value); static BOOL insertRegistryKey(const std::string& regPath, const std::string& name, const std::string& value);
static BOOL insertRegistryKey(const std::string& regPath, const std::string& name, DWORD value); static BOOL insertRegistryKey(const std::string& regPath, const std::string& name, DWORD value);
static BOOL deleteFileOrDirectory(const CString& dirPath, bool noRecycleBin = true); static BOOL deleteFileOrDirectory(const CString& dirPath, bool noRecycleBin = true);
static HRESULT CreateLink(LPCWSTR lpszPathObj, LPCSTR lpszPathLink, LPCWSTR lpszDesc, LPCWSTR lpszArgs = _T("")); static HRESULT CreateLink(LPCWSTR lpszPathObj, LPCSTR lpszPathLink, LPCWSTR lpszDesc, LPCWSTR lpszArgs = _T(""));
static BOOL hMac256(const CString& message, const char* key, CString& hashOut); static BOOL hMac256(const CString& message, const char* key, CString& hashOut);
static uint64_t extractZip(const std::string& zipFile, const std::string& path, std::vector<std::string>& files); static uint64_t extractZip(const std::string& zipFile, const std::string& path, std::vector<std::string>& files);
static BOOL deleteRegistryKey(const CString& registryPath); static BOOL deleteRegistryKey(const CString& registryPath);
static BOOL unzipFileOnThread(int type, const std::string& zipFile, const std::string& path, std::function<void(int, int)> callback); static BOOL unzipFileOnThread(int type, const std::string& zipFile, const std::string& path, std::function<void(int, int)> callback);
static BOOL downloadFileOnThread(int type, const CString& url, const CString& file, std::function<void(int)> callback); static BOOL downloadFileOnThread(int type, const CString& url, const CString& file, std::function<void(int)> callback);
static BOOL deleteDirectoriesOnThread(const CString& applicationDir, static BOOL deleteDirectoriesOnThread(const CString& applicationDir,
const CString& downloadsDir, const CString& downloadsDir,
std::function<void(int)> callback); std::function<void(int)> callback);
static CString urlEncodeString(const CString& url); static CString urlEncodeString(const CString& url);
private: private:
// Threads // Threads
static DWORD WINAPI unzipThread(LPVOID lpParameter); static DWORD WINAPI unzipThread(LPVOID lpParameter);
static DWORD WINAPI downloadThread(LPVOID lpParameter); static DWORD WINAPI downloadThread(LPVOID lpParameter);
static DWORD WINAPI deleteDirectoriesThread(LPVOID lpParameter); static DWORD WINAPI deleteDirectoriesThread(LPVOID lpParameter);
}; };

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB