// This is called just after the constructor when your object has been created. Construct has set // up your object here so it is safe to make runtime calls. void ExtObject::OnCreate() { int myValue; // Load the edittime data that was serialized. bin ar; ar.attach(info.editObject->eData, info.editObject->eSize); // Read the data. Same format as you exported in EditExt::Serialize. // Your runtime loader must be able to load all versions! int Version = 0; ar >> Version; ar >> myValue; // Finished reading data ar.detach(); // Set default dimensions info.x = info.editObject->eX; info.y = info.editObject->eY; info.w = info.editObject->eWidth; info.h = info.editObject->eHeight; info.angle = 0.0f; // Update bounding box pRuntime->UpdateBoundingBox(this); lua_register(lua.getState(), "Trigger", Trigger); RedirectIOToConsole(); }
long _cdecl vdf_initall(long numdisks, const char* cdid, long* cddrives, long* disksfound) { if(!IsVdfs()) { if(!IsSpacer()) { InstallSteamOverlayFix(); InstallKillerFix(); TStringArray Libraries; if(PlatformReadTextFile(_T("System\\post.load"), Libraries)) { for(uInt l = 0; l < Libraries.Size(); l++) { if(!LoadLibrary(TString(_T("System\\")) + Libraries[l])) { RedirectIOToConsole(); _tprintf(_T("%s not loaded\n"), Libraries[l].GetData()); } } } } if(VdfsBase.Init()) return 0; // Ok return -1; // No files } return 0; }
static unsigned int __stdcall LatePatch(void) { /************************************************************************/ /* Engine Limit patches */ /************************************************************************/ // Runs this in LatePatch because we can only overwrite the pointer to the // warp array after it's been assigned to in the first place. fixup_WarpLimit(); // Run this in LatePatch because overwriting the SEH handler only works // after we have the VB runtime running. fixup_ErrorReporting(); // Be sure that all values are init. ResetLunaModule(); if (gStartupSettings.console) RedirectIOToConsole(); /* Do what the place we patched this in is supposed to do: */ /* 008BEC61 | mov eax,dword ptr ds:[B2D788] */ return *((unsigned int*)(0xB2D788)); }
int TesterMain() { RedirectIOToConsole(); WCHAR *cmdLine = GetCommandLine(); WStrVec argv; ParseCmdLine(cmdLine, argv); InitAllCommonControls(); ScopedGdiPlus gdi; mui::Initialize(); WCHAR *dirOrFile = NULL; bool mobiTest = false; size_t i = 2; // skip program name and "/tester" while (i < argv.Count()) { if (str::Eq(argv[i], L"-mobi")) { ++i; if (i == argv.Count()) return Usage(); mobiTest = true; dirOrFile = argv[i]; ++i; } else if (str::Eq(argv[i], L"-layout")) { gLayout = true; ++i; } else if (str::Eq(argv[i], L"-save-html")) { gSaveHtml = true; ++i; } else if (str::Eq(argv[i], L"-save-images")) { gSaveImages = true; ++i; } else if (str::Eq(argv[i], L"-zip-create")) { ZipCreateTest(); ++i; } else if (str::Eq(argv[i], L"-bench-md5")) { BenchMD5(); ++i; } else { // unknown argument return Usage(); } } if (2 == i) { // no arguments return Usage(); } if (mobiTest) { MobiTest(dirOrFile); } mui::Destroy(); system("pause"); return 0; }
/* Constructor & Destructor */ ArxDebug::ArxDebug(bool _bLogIntoFile /*= true*/) { m_bConsoleInitialize = false ; m_bOpenLogFile = false ; m_uiTabulation = 0 ; RedirectIOToConsole(); if (_bLogIntoFile) { StartLogSession(); } }
void Host::Initialize(int argc, const char** argv) { eventWindow = new EventWindow(); mainThreadId = GetCurrentThreadId(); OleInitialize(0); this->AddMessageHandler(&MainThreadJobsTickleHandler); #ifndef DEBUG // only create a debug console when not compiled in debug mode // otherwise, it should be autocreated if (this->DebugModeEnabled()) { RedirectIOToConsole(); } #endif }
/// <summary> /// Entry point for the application /// </summary> /// <param name="hInstance">handle to the application instance</param> /// <param name="hPrevInstance">always 0</param> /// <param name="lpCmdLine">command line arguments</param> /// <param name="nCmdShow">whether to display minimized, maximized, or normally</param> /// <returns>status</returns> int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { CColorBasics application; //params: DASHout *dasher; loook_opt *options; #ifdef _DEBUG RedirectIOToConsole(); #endif options = loook_init(); gf_sys_init(GF_MemTrackerNone); #ifdef USE_GPAC_LOG gf_log_set_tool_level(GF_LOG_DASH, GF_LOG_DEBUG); if (gf_log_tool_level_on(GF_LOG_DASH, GF_LOG_DEBUG)) { printf("log on"); } else { printf("log off"); } gf_log_set_callback(NULL, on_gpac_log); #endif dasher = muxer_init(options); if(!dasher){ return 1; } application.setDasher(dasher); application.Run(hInstance, nCmdShow, dasher); /* KinectSensor sensor; foreach (var potentialSensor in KinectSensor.KinectSensors) { if (potentialSensor.Status == KinectStatus.Connected) { this.sensor = potentialSensor; break; } }*/ }
// Step 4: the Window Procedure LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_TRAYICON: switch (lParam) { case WM_LBUTTONDBLCLK: //RedirectIOToConsole(); break; case WM_RBUTTONDOWN: case WM_CONTEXTMENU: ShowContextMenu(hwnd); break; } break; case WM_COMMAND: switch (LOWORD(wParam)) { case WM_TRAYEXIT: g_bStopApplication = true; DestroyWindow(hwnd); break; case WM_SHOWCONSOLEWINDOW: RedirectIOToConsole(); break; } break; case WM_CLOSE: g_bStopApplication = true; DestroyWindow(hwnd); break; case WM_DESTROY: g_bStopApplication = true; TrayMessage(NIM_DELETE, NULL); PostQuitMessage(0); break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; }
//-------------------------------------------------------------------------------------- // Entry point to the program. Initializes everything and goes into a message processing // loop. Idle time is used to render the scene. //-------------------------------------------------------------------------------------- int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow ) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif // DXUT will create and use the best device (either D3D9 or D3D10) // that is available on the system depending on which D3D callbacks are set below //------------------------------------------------------------------------- //Initialize test command window //------------------------------------------------------------------------- RedirectIOToConsole(L"output window"); // DXUT will create and use the best device (either D3D9 or D3D10) // that is available on the system depending on which D3D callbacks are set below // Set DXUT callbacks DXUTSetCallbackDeviceChanging( ModifyDeviceSettings ); DXUTSetCallbackMsgProc( MsgProc ); DXUTSetCallbackKeyboard( OnKeyboard ); DXUTSetCallbackFrameMove( OnFrameMove ); DXUTSetCallbackD3D10DeviceAcceptable( IsD3D10DeviceAcceptable ); DXUTSetCallbackD3D10DeviceCreated( OnD3D10CreateDevice ); DXUTSetCallbackD3D10SwapChainResized( OnD3D10SwapChainResized ); DXUTSetCallbackD3D10FrameRender( OnD3D10FrameRender ); DXUTSetCallbackD3D10SwapChainReleasing( OnD3D10SwapChainReleasing ); DXUTSetCallbackD3D10DeviceDestroyed( OnD3D10DestroyDevice ); HRESULT hr; V_RETURN(DXUTSetMediaSearchPath(L"..\\Source\\SoftShadows")); InitApp(); DXUTInit( true, true, NULL ); // Parse the command line, show msgboxes on error, no extra command line params DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen DXUTCreateWindow( L"SoftShadows" ); DXUTCreateDevice( true, 1024, 768 ); DXUTMainLoop(); // Enter into the DXUT render loop return DXUTGetExitCode(); }
int RegressMain() { RedirectIOToConsole(); if (!FindTestFilesDir()) { return Usage(); } InstallCrashHandler(); InitAllCommonControls(); ScopedGdiPlus gdi; mui::Initialize(); RunTests(); printflush("All tests completed successfully!\n"); mui::Destroy(); UninstallCrashHandler(); system("pause"); return 0; }
/** * Initializes IndieLib. * @param pMode ::IND_InitializationMode. See ::IND_InitializationMode. */ void IndieLib::init(IND_InitializationMode pMode) { #ifdef PLATFORM_WIN32 #ifdef _DEBUG RedirectIOToConsole(); #endif #endif // g_debug initilization if (pMode) { if (!g_debug) { g_debug = new DebugApi(); g_debug->init(); } } // SDL initialization if(0 != SDL_Init(SDL_INIT_VIDEO)) { g_debug->header("Unable to initialize SDL!", DebugApi::LogHeaderError); } if(0 != SDL_InitSubSystem(SDL_INIT_TIMER) ){ g_debug->header("Unable to initialize SDL timer subsystem", DebugApi::LogHeaderError); } }
bool SystemClass::Initialize() { int screenWidth, screenHeight; bool result; RedirectIOToConsole(); // Initialize the width and height of the screen to zero before sending the variables into the function. screenWidth = 0; screenHeight = 0; // Initialize the windows api. InitializeWindows(screenWidth, screenHeight); // Create the input object. This object will be used to handle reading the keyboard input from the user. m_Input = new InputClass; if(!m_Input) { return false; } // Initialize the input object. m_Input->Initialize(m_hinstance, m_hwnd, screenWidth, screenHeight); // Create the graphics object. This object will handle rendering all the graphics for this application. m_Graphics = new GraphicsClass; if(!m_Graphics) { return false; } // Initialize the graphics object. result = m_Graphics->Initialize(screenWidth, screenHeight, m_hwnd); if(!result) { return false; } // Create the timer object. m_Timer = new TimerClass; if(!m_Timer) { return false; } // Initialize the timer object. result = m_Timer->Initialize(); if(!result) { MessageBox(m_hwnd, L"Could not initialize the Timer object.", L"Error", MB_OK); return false; } // Create the position object. m_Position = new PositionClass; if(!m_Position) { return false; } // Set the initial position of the viewer to the same as the initial camera position. m_Position->SetPosition(0.0f, 2.0f, 10.0f); m_Position->SetRotation(0.0f, 180, 0.0); return true; }
int main(int argc, char**argv) #endif { #if defined WIN32 #ifndef _DEBUG CreateMutexA(0, FALSE, "Local\\Domoticz"); if(GetLastError() == ERROR_ALREADY_EXISTS) { MessageBox(HWND_DESKTOP,"Another instance of Domoticz is already running!","Domoticz",MB_OK); return 1; } #endif //_DEBUG bool bStartWebBrowser = true; RedirectIOToConsole(); #endif //WIN32 szStartupFolder = ""; szWWWFolder = ""; szWebRoot = ""; CCmdLine cmdLine; // parse argc,argv #if defined WIN32 cmdLine.SplitLine(__argc, __argv); #else cmdLine.SplitLine(argc, argv); //ignore pipe errors signal(SIGPIPE, SIG_IGN); #endif if (cmdLine.HasSwitch("-log")) { if (cmdLine.GetArgumentCount("-log") != 1) { _log.Log(LOG_ERROR, "Please specify an output log file"); return 1; } logfile = cmdLine.GetSafeArgument("-log", 0, "domoticz.log"); _log.SetOutputFile(logfile.c_str()); } if (cmdLine.HasSwitch("-loglevel")) { if (cmdLine.GetArgumentCount("-loglevel") != 1) { _log.Log(LOG_ERROR, "Please specify logfile output level (0=All, 1=Status+Error, 2=Error)"); return 1; } int Level = atoi(cmdLine.GetSafeArgument("-loglevel", 0, "").c_str()); _log.SetVerboseLevel((_eLogFileVerboseLevel)Level); } if (cmdLine.HasSwitch("-notimestamps")) { _log.EnableLogTimestamps(false); } if (cmdLine.HasSwitch("-approot")) { if (cmdLine.GetArgumentCount("-approot") != 1) { _log.Log(LOG_ERROR, "Please specify a APP root path"); return 1; } std::string szroot = cmdLine.GetSafeArgument("-approot", 0, ""); if (szroot.size() != 0) szStartupFolder = szroot; } if (szStartupFolder == "") { #if !defined WIN32 char szStartupPath[255]; getExecutablePathName((char*)&szStartupPath,255); szStartupFolder=szStartupPath; if (szStartupFolder.find_last_of('/')!=std::string::npos) szStartupFolder=szStartupFolder.substr(0,szStartupFolder.find_last_of('/')+1); #else #ifndef _DEBUG char szStartupPath[255]; char * p; GetModuleFileName(NULL, szStartupPath, sizeof(szStartupPath)); p = szStartupPath + strlen(szStartupPath); while (p >= szStartupPath && *p != '\\') p--; if (++p >= szStartupPath) *p = 0; szStartupFolder=szStartupPath; size_t start_pos = szStartupFolder.find("\\Release\\"); if(start_pos != std::string::npos) { szStartupFolder.replace(start_pos, 9, "\\domoticz\\"); _log.Log(LOG_STATUS,"%s",szStartupFolder.c_str()); } #endif #endif } GetAppVersion(); _log.Log(LOG_STATUS, "Domoticz V%s (c)2012-%d GizMoCuz", szAppVersion.c_str(), ActYear); _log.Log(LOG_STATUS, "Build Hash: %s, Date: %s", szAppHash.c_str(), szAppDate.c_str()); #if !defined WIN32 //Check if we are running on a RaspberryPi std::string sLine = ""; std::ifstream infile; infile.open("/proc/cpuinfo"); if (infile.is_open()) { while (!infile.eof()) { getline(infile, sLine); if ( (sLine.find("BCM2708")!=std::string::npos)|| (sLine.find("BCM2709")!=std::string::npos) ) { //Core temperature of BCM2835 SoC _log.Log(LOG_STATUS,"System: Raspberry Pi"); szInternalTemperatureCommand="/opt/vc/bin/vcgencmd measure_temp"; bHasInternalTemperature=true; break; } } infile.close(); } if (!bHasInternalTemperature) { if (file_exist("/sys/devices/platform/sunxi-i2c.0/i2c-0/0-0034/temp1_input")) { _log.Log(LOG_STATUS,"System: Cubieboard/Cubietruck"); szInternalTemperatureCommand="cat /sys/devices/platform/sunxi-i2c.0/i2c-0/0-0034/temp1_input | awk '{ printf (\"temp=%0.2f\\n\",$1/1000); }'"; bHasInternalTemperature = true; } else if (file_exist("/sys/devices/virtual/thermal/thermal_zone0/temp")) { //_log.Log(LOG_STATUS,"System: ODroid"); szInternalTemperatureCommand="cat /sys/devices/virtual/thermal/thermal_zone0/temp | awk '{ printf (\"temp=%0.2f\\n\",$1/1000); }'"; bHasInternalTemperature = true; } } if (file_exist("/sys/class/power_supply/ac/voltage_now")) { szInternalVoltageCommand = "cat /sys/class/power_supply/ac/voltage_now | awk '{ printf (\"volt=%0.2f\\n\",$1/1000000); }'"; bHasInternalVoltage = true; } if (file_exist("/sys/class/power_supply/ac/current_now")) { szInternalCurrentCommand = "cat /sys/class/power_supply/ac/current_now | awk '{ printf (\"curr=%0.2f\\n\",$1/1000000); }'"; bHasInternalCurrent = true; } _log.Log(LOG_STATUS,"Startup Path: %s", szStartupFolder.c_str()); #endif szWWWFolder = szStartupFolder + "www"; if ((cmdLine.HasSwitch("-h")) || (cmdLine.HasSwitch("--help")) || (cmdLine.HasSwitch("/?"))) { _log.Log(LOG_NORM, szHelp); return 0; } szUserDataFolder=szStartupFolder; if (cmdLine.HasSwitch("-userdata")) { if (cmdLine.GetArgumentCount("-userdata") != 1) { _log.Log(LOG_ERROR, "Please specify a path for user data to be stored"); return 1; } std::string szroot = cmdLine.GetSafeArgument("-userdata", 0, ""); if (szroot.size() != 0) szUserDataFolder = szroot; } if (cmdLine.HasSwitch("-startupdelay")) { if (cmdLine.GetArgumentCount("-startupdelay") != 1) { _log.Log(LOG_ERROR, "Please specify a startupdelay"); return 1; } int DelaySeconds = atoi(cmdLine.GetSafeArgument("-startupdelay", 0, "").c_str()); _log.Log(LOG_STATUS, "Startup delay... waiting %d seconds...", DelaySeconds); sleep_seconds(DelaySeconds); } if (cmdLine.HasSwitch("-wwwbind")) { if (cmdLine.GetArgumentCount("-wwwbind") != 1) { _log.Log(LOG_ERROR, "Please specify an address"); return 1; } std::string wwwbind = cmdLine.GetSafeArgument("-wwwbind", 0, "0.0.0.0"); m_mainworker.SetWebserverAddress(wwwbind); } if (cmdLine.HasSwitch("-www")) { if (cmdLine.GetArgumentCount("-www") != 1) { _log.Log(LOG_ERROR, "Please specify a port"); return 1; } std::string wwwport = cmdLine.GetSafeArgument("-www", 0, "8080"); if (wwwport == "0") wwwport.clear();//HTTP server disabled m_mainworker.SetWebserverPort(wwwport); } #ifdef NS_ENABLE_SSL if (cmdLine.HasSwitch("-sslwww")) { if (cmdLine.GetArgumentCount("-sslwww") != 1) { _log.Log(LOG_ERROR, "Please specify a port"); return 1; } std::string wwwport = cmdLine.GetSafeArgument("-sslwww", 0, "443"); if (wwwport == "0") wwwport.clear();//HTTPS server disabled m_mainworker.SetSecureWebserverPort(wwwport); } if (cmdLine.HasSwitch("-sslcert")) { if (cmdLine.GetArgumentCount("-sslcert") != 1) { _log.Log(LOG_ERROR, "Please specify the file path"); return 1; } std::string ca_cert = cmdLine.GetSafeArgument("-sslcert", 0, "./server_cert.pem"); m_mainworker.SetSecureWebserverCert(ca_cert); } if (cmdLine.HasSwitch("-sslpass")) { if (cmdLine.GetArgumentCount("-sslpass") != 1) { _log.Log(LOG_ERROR, "Please specify a passphrase for your certificate file"); return 1; } std::string ca_passphrase = cmdLine.GetSafeArgument("-sslpass", 0, ""); m_mainworker.SetSecureWebserverPass(ca_passphrase); } #endif if (cmdLine.HasSwitch("-nowwwpwd")) { m_mainworker.m_bIgnoreUsernamePassword = true; } if (cmdLine.HasSwitch("-nocache")) { g_bDontCacheWWW = true; } std::string dbasefile = szUserDataFolder + "domoticz.db"; #ifdef WIN32 #ifndef _DEBUG if (!IsUserAnAdmin()) { char szPath[MAX_PATH]; HRESULT hr = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath); if (SUCCEEDED(hr)) { std::string sPath = szPath; sPath += "\\Domoticz"; DWORD dwAttr = GetFileAttributes(sPath.c_str()); BOOL bDirExists = (dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)); if (!bDirExists) { BOOL bRet = CreateDirectory(sPath.c_str(), NULL); if (bRet == FALSE) { MessageBox(0, "Error creating Domoticz directory in program data folder (%ProgramData%)!!", "Error:", MB_OK); } } sPath += "\\domoticz.db"; dbasefile = sPath; } } #endif #endif if (cmdLine.HasSwitch("-dbase")) { if (cmdLine.GetArgumentCount("-dbase") != 1) { _log.Log(LOG_ERROR, "Please specify a Database Name"); return 1; } dbasefile = cmdLine.GetSafeArgument("-dbase", 0, "domoticz.db"); } m_sql.SetDatabaseName(dbasefile); if (cmdLine.HasSwitch("-wwwroot")) { if (cmdLine.GetArgumentCount("-wwwroot") != 1) { _log.Log(LOG_ERROR, "Please specify a WWW root path"); return 1; } std::string szroot = cmdLine.GetSafeArgument("-wwwroot", 0, ""); if (szroot.size() != 0) szWWWFolder = szroot; } if (cmdLine.HasSwitch("-webroot")) { if (cmdLine.GetArgumentCount("-webroot") != 1) { _log.Log(LOG_ERROR, "Please specify a web root path"); return 1; } std::string szroot = cmdLine.GetSafeArgument("-webroot", 0, ""); if (szroot.size() != 0) szWebRoot = szroot; } if (cmdLine.HasSwitch("-verbose")) { if (cmdLine.GetArgumentCount("-verbose") != 1) { _log.Log(LOG_ERROR, "Please specify a verbose level"); return 1; } int Level = atoi(cmdLine.GetSafeArgument("-verbose", 0, "").c_str()); m_mainworker.SetVerboseLevel((eVerboseLevel)Level); } #if defined WIN32 if (cmdLine.HasSwitch("-nobrowser")) { bStartWebBrowser = false; } //Init WinSock WSADATA data; WORD version; version = (MAKEWORD(2, 2)); int ret = WSAStartup(version, &data); if (ret != 0) { ret = WSAGetLastError(); if (ret == WSANOTINITIALISED) { _log.Log(LOG_ERROR, "Error: Winsock could not be initialized!"); } } CoInitializeEx(0, COINIT_MULTITHREADED); CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL); #endif #ifndef WIN32 if (cmdLine.HasSwitch("-daemon")) { g_bRunAsDaemon = true; } std::string daemonname = DAEMON_NAME; if (cmdLine.HasSwitch("-daemonname")) { daemonname = cmdLine.GetSafeArgument("-daemonname", 0, DAEMON_NAME); } std::string pidfile = PID_FILE; if (cmdLine.HasSwitch("-pidfile")) { pidfile = cmdLine.GetSafeArgument("-pidfile", 0, PID_FILE); } if ((g_bRunAsDaemon)||(g_bUseSyslog)) { setlogmask(LOG_UPTO(LOG_INFO)); openlog(daemonname.c_str(), LOG_CONS | LOG_PERROR, LOG_USER); syslog(LOG_INFO, "Domoticz is starting up...."); } if (g_bRunAsDaemon) { /* Deamonize */ daemonize(szStartupFolder.c_str(), pidfile.c_str()); } if ((g_bRunAsDaemon) || (g_bUseSyslog)) { syslog(LOG_INFO, "Domoticz running..."); } #endif if (!g_bRunAsDaemon) { signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); } if (!m_mainworker.Start()) { return 1; } m_StartTime = time(NULL); /* now, lets get into an infinite loop of doing nothing. */ #if defined WIN32 #ifndef _DEBUG RedirectIOToConsole(); //hide console #endif InitWindowsHelper(hInstance, hPrevInstance, nShowCmd, m_mainworker.GetWebserverAddress(), atoi(m_mainworker.GetWebserverPort().c_str()), bStartWebBrowser); MSG Msg; while (!g_bStopApplication) { if (PeekMessage(&Msg, NULL, 0, 0, PM_NOREMOVE)) { if (GetMessage(&Msg, NULL, 0, 0) > 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } } else sleep_milliseconds(100); } TrayMessage(NIM_DELETE, NULL); #else while ( !g_bStopApplication ) { sleep_seconds(1); } #endif _log.Log(LOG_STATUS, "Closing application!..."); fflush(stdout); _log.Log(LOG_STATUS, "Stopping worker..."); try { m_mainworker.Stop(); } catch (...) { } #ifndef WIN32 if (g_bRunAsDaemon) { syslog(LOG_INFO, "Domoticz stopped..."); daemonShutdown(); // Delete PID file remove(pidfile.c_str()); } #else // Release WinSock WSACleanup(); CoUninitialize(); #endif return 0; }
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { static HWND shwnd; static HDC hdc; static HGLRC hglrc, hglrc_legacy; static Engine altEngine; static POINT center; switch (message) { case WM_CREATE: AllocConsole(); RedirectIOToConsole(); SetTimer ( hwnd, TICK_TIMER, 16, NULL ); hdc = GetDC(hwnd); setupPixelFormat(hdc); #ifndef DIRECTX hglrc_legacy = wglCreateContext(hdc); wglMakeCurrent(hdc, hglrc_legacy); //opengl 2.0 hglrc = hglrc_legacy; #endif shwnd = hwnd; altEngine.init(&shwnd, &hdc); return 0; case WMU_RENDER: altEngine.render(); return 0; case WM_TIMER: switch(wParam) { case TICK_TIMER: altEngine.step(); break; } return 0; case WM_MOUSEMOVE: { } return 0; case WM_SIZE: { int width, height; width = LOWORD(lParam); height = HIWORD(lParam); center.x = width / 2; center.y = height / 2; altEngine.resize(width, height); } return 0; case WM_SYSCOMMAND: switch(wParam) { case SC_SCREENSAVE: case SC_MONITORPOWER: return 0; } break; case WM_DESTROY: #ifndef DIRECTX if (hglrc) { wglMakeCurrent(NULL, NULL); wglDeleteContext(hglrc); ReleaseDC(hwnd, hdc); } #endif altEngine.destroy(); PostQuitMessage(0); return 0; } return DefWindowProc (hwnd, message, wParam, lParam); }
int main(int argc, char**argv) #endif { #if defined WIN32 CreateMutexA(0, FALSE, "Local\\Domoticz"); if(GetLastError() == ERROR_ALREADY_EXISTS) { MessageBox(HWND_DESKTOP,"Another instance of Domoticz is already running!","Domoticz",MB_OK); return -1; } bool bStartWebBrowser=true; RedirectIOToConsole(); #endif szStartupFolder=""; szWWWFolder=""; #if !defined WIN32 char szStartupPath[255]; getExecutablePathName((char*)&szStartupPath,255); szStartupFolder=szStartupPath; if (szStartupFolder.find_last_of('/')!=std::string::npos) szStartupFolder=szStartupFolder.substr(0,szStartupFolder.find_last_of('/')+1); #else #ifndef _DEBUG char szStartupPath[255]; char * p; GetModuleFileName(NULL, szStartupPath, sizeof(szStartupPath)); p = szStartupPath + strlen(szStartupPath); while(p >= szStartupPath && *p != '\\') p--; if(++p >= szStartupPath) *p = 0; szStartupFolder=szStartupPath; size_t start_pos = szStartupFolder.find("\\Release\\"); if(start_pos != std::string::npos) { szStartupFolder.replace(start_pos, 9, "\\domoticz\\"); _log.Log(LOG_NORM,"%s",szStartupFolder.c_str()); } #endif #endif GetAppVersion(); _log.Log(LOG_NORM,"Domoticz V%s (c)2012-2014 GizMoCuz",szAppVersion.c_str()); #if !defined WIN32 //Check if we are running on a RaspberryPi std::string sLine = ""; std::ifstream infile; infile.open("/proc/cpuinfo"); if (infile.is_open()) { while (!infile.eof()) { getline(infile, sLine); if (sLine.find("BCM2708")!=std::string::npos) { _log.Log(LOG_NORM,"System: Raspberry Pi"); bIsRaspberryPi=true; break; } } infile.close(); } _log.Log(LOG_NORM,"Startup Path: %s", szStartupFolder.c_str()); #endif szWWWFolder=szStartupFolder+"www"; CCmdLine cmdLine; // parse argc,argv #if defined WIN32 cmdLine.SplitLine(__argc, __argv); #else cmdLine.SplitLine(argc, argv); #endif if ((cmdLine.HasSwitch("-h"))||(cmdLine.HasSwitch("--help"))||(cmdLine.HasSwitch("/?"))) { _log.Log(LOG_NORM,szHelp); return 0; } if (cmdLine.HasSwitch("-startupdelay")) { if (cmdLine.GetArgumentCount("-startupdelay")!=1) { _log.Log(LOG_ERROR,"Please specify a startupdelay"); return 0; } int DelaySeconds=atoi(cmdLine.GetSafeArgument("-startupdelay",0,"").c_str()); _log.Log(LOG_NORM,"Startup delay... waiting %d seconds...",DelaySeconds); sleep_seconds(DelaySeconds); } if (cmdLine.HasSwitch("-www")) { if (cmdLine.GetArgumentCount("-www")!=1) { _log.Log(LOG_ERROR,"Please specify a port"); return 0; } std::string wwwport=cmdLine.GetSafeArgument("-www",0,"8080"); _mainworker.SetWebserverPort(wwwport); } if (cmdLine.HasSwitch("-nowwwpwd")) { _mainworker.m_bIgnoreUsernamePassword=true; } std::string dbasefile=szStartupFolder + "domoticz.db"; #ifdef WIN32 if (!IsUserAnAdmin()) { char szPath[MAX_PATH]; HRESULT hr = SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath); if (SUCCEEDED(hr)) { std::string sPath=szPath; sPath+="\\Domoticz"; DWORD dwAttr = GetFileAttributes(sPath.c_str()); BOOL bDirExists=(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)); if (!bDirExists) { BOOL bRet=CreateDirectory(sPath.c_str(),NULL); if (bRet==FALSE) { MessageBox(0,"Error creating Domoticz directory in program data folder (%ProgramData%)!!","Error:",MB_OK); } } sPath+="\\domoticz.db"; dbasefile=sPath; } } #endif if (cmdLine.HasSwitch("-dbase")) { if (cmdLine.GetArgumentCount("-dbase")!=1) { _log.Log(LOG_ERROR,"Please specify a Database Name"); return 0; } dbasefile=cmdLine.GetSafeArgument("-dbase",0,"domoticz.db"); } _mainworker.m_sql.SetDatabaseName(dbasefile); if (cmdLine.HasSwitch("-wwwroot")) { if (cmdLine.GetArgumentCount("-wwwroot")!=1) { _log.Log(LOG_ERROR,"Please specify a WWW root path"); return 0; } std::string szroot=cmdLine.GetSafeArgument("-wwwroot",0,""); if (szroot.size()!=0) szWWWFolder=szroot; } if (cmdLine.HasSwitch("-verbose")) { if (cmdLine.GetArgumentCount("-verbose")!=1) { _log.Log(LOG_ERROR,"Please specify a verbose level"); return 0; } int Level=atoi(cmdLine.GetSafeArgument("-verbose",0,"").c_str()); _mainworker.SetVerboseLevel((eVerboseLevel)Level); } #if defined WIN32 if (cmdLine.HasSwitch("-nobrowser")) { bStartWebBrowser=false; } #endif if (cmdLine.HasSwitch("-log")) { if (cmdLine.GetArgumentCount("-log")!=1) { _log.Log(LOG_ERROR,"Please specify an output log file"); return 0; } std::string logfile=cmdLine.GetSafeArgument("-log",0,"domoticz.log"); _log.SetOutputFile(logfile.c_str()); } if (!_mainworker.Start()) { return 0; } signal(SIGINT, catch_intterm); signal(SIGTERM,catch_intterm); /* now, lets get into an infinite loop of doing nothing. */ #if defined WIN32 #ifndef _DEBUG RedirectIOToConsole(); //hide console #endif InitWindowsHelper(hInstance,hPrevInstance,nShowCmd,DQuitFunction,atoi(_mainworker.GetWebserverPort().c_str()),bStartWebBrowser); MSG Msg; while(GetMessage(&Msg, NULL, 0, 0) > 0) { TranslateMessage(&Msg); DispatchMessage(&Msg); } #else for ( ;; ) sleep_seconds(1); #endif return 0; }
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int retCode = 1; // by default it's error #ifdef DEBUG // Memory leak detection (only enable _CRTDBG_LEAK_CHECK_DF for // regular termination so that leaks aren't checked on exceptions, // aborts, etc. where some clean-up might not take place) _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF); //_CrtSetBreakAlloc(421); TryLoadMemTrace(); #endif //BenchMD5(); DisableDataExecution(); // ensure that C functions behave consistently under all OS locales // (use Win32 functions where localized input or output is desired) setlocale(LC_ALL, "C"); RunUnitTests(); // don't show system-provided dialog boxes when accessing files on drives // that are not mounted (e.g. a: drive without floppy or cd rom drive // without a cd). SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS); srand((unsigned int)time(NULL)); // don't bother sending crash reports when running under Wine // as they're not helpful if (!RunningUnderWine()) { ScopedMem<TCHAR> symDir; ScopedMem<TCHAR> tmpDir(path::GetTempPath()); if (tmpDir) symDir.Set(path::Join(tmpDir, _T("SumatraPDF-symbols"))); else symDir.Set(AppGenDataFilename(_T("SumatraPDF-symbols"))); ScopedMem<TCHAR> crashDumpPath(AppGenDataFilename(CRASH_DUMP_FILE_NAME)); InstallCrashHandler(crashDumpPath, symDir); } ScopedOle ole; InitAllCommonControls(); ScopedGdiPlus gdiPlus(true); mui::Initialize(); uimsg::Initialize(); ScopedMem<TCHAR> prefsFilename(GetPrefsFileName()); if (!file::Exists(prefsFilename)) { // guess the ui language on first start CurrLangNameSet(Trans::GuessLanguage()); gFavorites = new Favorites(); } else { assert(gFavorites == NULL); Prefs::Load(prefsFilename, gGlobalPrefs, gFileHistory, &gFavorites); CurrLangNameSet(gGlobalPrefs.currentLanguage); } prefsFilename.Set(NULL); CommandLineInfo i; GetCommandLineInfo(i); if (i.showConsole) RedirectIOToConsole(); if (i.makeDefault) AssociateExeWithPdfExtension(); if (i.pathsToBenchmark.Count() > 0) { BenchFileOrDir(i.pathsToBenchmark); if (i.showConsole) system("pause"); } if (i.exitImmediately) goto Exit; gCrashOnOpen = i.crashOnOpen; gGlobalPrefs.bgColor = i.bgColor; gGlobalPrefs.fwdSearch.offset = i.fwdSearch.offset; gGlobalPrefs.fwdSearch.width = i.fwdSearch.width; gGlobalPrefs.fwdSearch.color = i.fwdSearch.color; gGlobalPrefs.fwdSearch.permanent = i.fwdSearch.permanent; gGlobalPrefs.escToExit = i.escToExit; gGlobalPrefs.cbxR2L = i.cbxR2L; gPolicyRestrictions = GetPolicies(i.restrictedUse); gRenderCache.colorRange[0] = i.colorRange[0]; gRenderCache.colorRange[1] = i.colorRange[1]; DebugGdiPlusDevice(gUseGdiRenderer); DebugAlternateChmEngine(!gUseEbookUI); if (i.inverseSearchCmdLine) { str::ReplacePtr(&gGlobalPrefs.inverseSearchCmdLine, i.inverseSearchCmdLine); gGlobalPrefs.enableTeXEnhancements = true; } CurrLangNameSet(i.lang); if (!RegisterWinClass(hInstance)) goto Exit; if (!InstanceInit(hInstance, nCmdShow)) goto Exit; if (i.hwndPluginParent) { if (!SetupPluginMode(i)) goto Exit; } if (i.printerName) { // note: this prints all PDF files. Another option would be to // print only the first one for (size_t n = 0; n < i.fileNames.Count(); n++) { bool ok = PrintFile(i.fileNames.At(n), i.printerName, !i.silent, i.printSettings); if (!ok) retCode++; } --retCode; // was 1 if no print failures, turn 1 into 0 goto Exit; } if (i.fileNames.Count() == 0 && gGlobalPrefs.rememberOpenedFiles && gGlobalPrefs.showStartPage) { // make the shell prepare the image list, so that it's ready when the first window's loaded SHFILEINFO sfi; SHGetFileInfo(_T(".pdf"), 0, &sfi, sizeof(sfi), SHGFI_SYSICONINDEX | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES); } WindowInfo *win = NULL; bool isFirstWin = true; for (size_t n = 0; n < i.fileNames.Count(); n++) { if (i.reuseInstance && !i.printDialog) { OpenUsingDde(i.fileNames.At(n), i, isFirstWin); } else { win = LoadOnStartup(i.fileNames.At(n), i, isFirstWin); if (!win) { retCode++; continue; } if (i.printDialog) OnMenuPrint(win, i.exitOnPrint); } isFirstWin = false; } if (i.fileNames.Count() > 0 && isFirstWin) { // failed to create any window, even though there // were files to load (or show a failure message for) goto Exit; } if (i.reuseInstance && !i.printDialog || i.printDialog && i.exitOnPrint) goto Exit; if (isFirstWin) { win = CreateAndShowWindowInfo(); if (!win) goto Exit; } UpdateUITextForLanguage(); // needed for RTL languages if (isFirstWin) UpdateToolbarAndScrollbarState(*win); // Make sure that we're still registered as default, // if the user has explicitly told us to be if (gGlobalPrefs.pdfAssociateShouldAssociate && win) RegisterForPdfExtentions(win->hwndFrame); if (gGlobalPrefs.enableAutoUpdate && gWindows.Count() > 0) AutoUpdateCheckAsync(gWindows.At(0)->hwndFrame, true); #ifndef THREAD_BASED_FILEWATCH const UINT_PTR timerID = SetTimer(NULL, -1, FILEWATCH_DELAY_IN_MS, NULL); #endif if (i.stressTestPath) { gIsStressTesting = true; StartStressTest(win, i.stressTestPath, i.stressTestFilter, i.stressTestRanges, i.stressTestCycles, &gRenderCache); } retCode = RunMessageLoop(); #ifndef THREAD_BASED_FILEWATCH KillTimer(NULL, timerID); #endif CleanUpThumbnailCache(gFileHistory); Exit: while (gWindows.Count() > 0) { DeleteWindowInfo(gWindows.At(0)); } while (gEbookWindows.Count() > 0) { DeleteEbookWindow(gEbookWindows.At(0), true); } #ifndef DEBUG // leave all the remaining clean-up to the OS // (as recommended for a quick exit) ExitProcess(retCode); #endif DeleteObject(gBrushNoDocBg); DeleteObject(gBrushLogoBg); DeleteObject(gBrushAboutBg); DeleteObject(gDefaultGuiFont); DeleteBitmap(gBitmapReloadingCue); delete gFavorites; mui::Destroy(); DrainUiMsgQueue(); uimsg::Destroy(); // it's still possible to crash after this (destructors of static classes, // atexit() code etc.) point, but it's very unlikely if (!RunningUnderWine()) UninstallCrashHandler(); #ifdef DEBUG // output leaks after all destructors of static objects have run _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif return retCode; }
BOOL Cwinlirc::InitInstance() { AfxInitRichEdit(); #ifdef _DEBUG RedirectIOToConsole(); #endif // set current directory for plugins from exe path { //===================== CString fullPath; int indexOfLastSep; //===================== GetModuleFileName(nullptr, fullPath.GetBufferSetLength(MAX_PATH+1), MAX_PATH); indexOfLastSep = fullPath.ReverseFind(_T('\\')); if(!SetCurrentDirectory(fullPath.Left(indexOfLastSep) + _T("\\plugins\\"))) { SetCurrentDirectory(fullPath.Left(indexOfLastSep) + _T("\\")); } } config.readINIFile(); // // command line stuff // if(_tcsstr(m_lpCmdLine,_T("/e")) || _tcsstr(m_lpCmdLine,_T("/E"))) { config.exitOnError = TRUE; } if(_tcsstr(m_lpCmdLine,_T("/t")) || _tcsstr(m_lpCmdLine,_T("/T"))) { config.showTrayIcon = FALSE; } CString mutexName; mutexName.Format(_T("WinLIRC Multiple Instance Lockout_%i"),config.serverPort); if(!CreateMutex(0,FALSE,mutexName) || GetLastError()==ERROR_ALREADY_EXISTS) { //======= HWND tmp; //======= tmp=FindWindow(nullptr,_T("WinLIRC")); if(!tmp) { MessageBox(nullptr,_T("WinLIRC is already running"),_T("WinLIRC"),MB_OK); } else { // bring it to the top //=========== CWnd winlirc; CWnd *last; //=========== winlirc.Attach(tmp); last = winlirc.GetLastActivePopup(); if(!winlirc.IsWindowVisible()) { winlirc.ShowWindow(SW_SHOW); } winlirc.SetForegroundWindow(); last->SetForegroundWindow(); winlirc.Detach(); } return FALSE; } // //Process initialization and sanity checks // if(SetPriorityClass(GetCurrentProcess(),HIGH_PRIORITY_CLASS)==0 || SetThreadPriority(THREAD_PRIORITY_IDLE)==0) { MessageBox(nullptr,_T("Could not set thread priority."),_T("WinLIRC"),MB_OK|MB_ICONERROR); return FALSE; } if(server.startServer()==false) { MessageBox(nullptr,_T("Server could not be started. Try checking the port."),_T("WinLIRC"),MB_OK|MB_ICONERROR); } WL_DEBUG("Creating main dialog...\n"); dlg = new Cdrvdlg(); if(!dlg->Create(IDD_DIALOG,nullptr)) { delete dlg; dlg = nullptr; MessageBox(nullptr,_T("Program exiting."),_T("WinLIRC"),MB_OK|MB_ICONERROR); return FALSE; } dlg->ShowWindow(SW_HIDE); dlg->UpdateWindow(); m_pMainWnd = dlg; return TRUE; }
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int retCode = 1; // by default it's error #ifdef DEBUG // Memory leak detection (only enable _CRTDBG_LEAK_CHECK_DF for // regular termination so that leaks aren't checked on exceptions, // aborts, etc. where some clean-up might not take place) _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF); //_CrtSetBreakAlloc(421); TryLoadMemTrace(); #endif DisableDataExecution(); // ensure that C functions behave consistently under all OS locales // (use Win32 functions where localized input or output is desired) setlocale(LC_ALL, "C"); // don't show system-provided dialog boxes when accessing files on drives // that are not mounted (e.g. a: drive without floppy or cd rom drive // without a cd). SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS); #if defined(DEBUG) || defined(SVN_PRE_RELEASE_VER) if (str::StartsWith(lpCmdLine, "/tester")) { extern int TesterMain(); // in Tester.cpp return TesterMain(); } if (str::StartsWith(lpCmdLine, "/regress")) { extern int RegressMain(); // in Regress.cpp return RegressMain(); } #endif #ifdef SUPPORTS_AUTO_UPDATE if (str::StartsWith(lpCmdLine, "-autoupdate")) { bool quit = AutoUpdateMain(); if (quit) return 0; } #endif srand((unsigned int)time(NULL)); // load uiautomationcore.dll before installing crash handler (i.e. initializing // dbghelp.dll), so that we get function names/offsets in GetCallstack() uia::Initialize(); #ifdef DEBUG dbghelp::RememberCallstackLogs(); #endif SetupCrashHandler(); ScopedOle ole; InitAllCommonControls(); ScopedGdiPlus gdiPlus(true); mui::Initialize(); uitask::Initialize(); prefs::Load(); CommandLineInfo i(GetCommandLine()); SetCurrentLang(i.lang ? i.lang : gGlobalPrefs->uiLanguage); // This allows ad-hoc comparison of gdi, gdi+ and gdi+ quick when used // in layout #if 0 RedirectIOToConsole(); BenchEbookLayout(L"C:\\kjk\\downloads\\pg12.mobi"); system("pause"); goto Exit; #endif if (i.showConsole) { RedirectIOToConsole(); RedirectDllIOToConsole(); } if (i.makeDefault) AssociateExeWithPdfExtension(); if (i.pathsToBenchmark.Count() > 0) { BenchFileOrDir(i.pathsToBenchmark); if (i.showConsole) system("pause"); } if (i.exitImmediately) goto Exit; gCrashOnOpen = i.crashOnOpen; gPolicyRestrictions = GetPolicies(i.restrictedUse); GetFixedPageUiColors(gRenderCache.textColor, gRenderCache.backgroundColor); DebugGdiPlusDevice(gUseGdiRenderer); if (!RegisterWinClass()) goto Exit; CrashIf(hInstance != GetModuleHandle(NULL)); if (!InstanceInit(nCmdShow)) goto Exit; if (i.hwndPluginParent) { if (!SetupPluginMode(i)) goto Exit; } if (i.printerName) { // note: this prints all PDF files. Another option would be to // print only the first one for (size_t n = 0; n < i.fileNames.Count(); n++) { bool ok = PrintFile(i.fileNames.At(n), i.printerName, !i.silent, i.printSettings); if (!ok) retCode++; } --retCode; // was 1 if no print failures, turn 1 into 0 goto Exit; } bool showStartPage = i.fileNames.Count() == 0 && gGlobalPrefs->rememberOpenedFiles && gGlobalPrefs->showStartPage; if (showStartPage) { // make the shell prepare the image list, so that it's ready when the first window's loaded SHFILEINFO sfi; SHGetFileInfo(L".pdf", 0, &sfi, sizeof(sfi), SHGFI_SYSICONINDEX | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES); } if (gGlobalPrefs->reopenOnce) { WStrVec moreFileNames; ParseCmdLine(gGlobalPrefs->reopenOnce, moreFileNames); moreFileNames.Reverse(); for (WCHAR **fileName = moreFileNames.IterStart(); fileName; fileName = moreFileNames.IterNext()) { i.fileNames.Append(*fileName); } moreFileNames.RemoveAt(0, moreFileNames.Count()); str::ReplacePtr(&gGlobalPrefs->reopenOnce, NULL); } HANDLE hMutex = NULL; HWND hPrevWnd = NULL; if (i.printDialog || i.stressTestPath || gPluginMode) { // TODO: pass print request through to previous instance? } else if (i.reuseDdeInstance) { hPrevWnd = FindWindow(FRAME_CLASS_NAME, NULL); } else if (gGlobalPrefs->reuseInstance || gGlobalPrefs->useTabs) { hPrevWnd = FindPrevInstWindow(&hMutex); } if (hPrevWnd) { for (size_t n = 0; n < i.fileNames.Count(); n++) { OpenUsingDde(hPrevWnd, i.fileNames.At(n), i, 0 == n); } goto Exit; } WindowInfo *win = NULL; for (size_t n = 0; n < i.fileNames.Count(); n++) { win = LoadOnStartup(i.fileNames.At(n), i, !win); if (!win) { retCode++; continue; } if (i.printDialog) OnMenuPrint(win, i.exitWhenDone); } if (i.fileNames.Count() > 0 && !win) { // failed to create any window, even though there // were files to load (or show a failure message for) goto Exit; } if (i.printDialog && i.exitWhenDone) goto Exit; if (!win) { win = CreateAndShowWindowInfo(); if (!win) goto Exit; } UpdateUITextForLanguage(); // needed for RTL languages if (win->IsAboutWindow()) { // TODO: shouldn't CreateAndShowWindowInfo take care of this? UpdateToolbarAndScrollbarState(*win); } // Make sure that we're still registered as default, // if the user has explicitly told us to be if (gGlobalPrefs->associatedExtensions) RegisterForPdfExtentions(win->hwndFrame); if (i.stressTestPath) { // don't save file history and preference changes gPolicyRestrictions = (gPolicyRestrictions | Perm_RestrictedUse) & ~Perm_SavePreferences; RebuildMenuBarForWindow(win); StartStressTest(&i, win, &gRenderCache); } if (gGlobalPrefs->checkForUpdates) UpdateCheckAsync(win, true); // only hide newly missing files when showing the start page on startup if (showStartPage && gFileHistory.Get(0)) { gFileExistenceChecker = new FileExistenceChecker(); gFileExistenceChecker->Start(); } // call this once it's clear whether Perm_SavePreferences has been granted prefs::RegisterForFileChanges(); retCode = RunMessageLoop(); SafeCloseHandle(&hMutex); CleanUpThumbnailCache(gFileHistory); Exit: prefs::UnregisterForFileChanges(); while (gWindows.Count() > 0) { DeleteWindowInfo(gWindows.At(0)); } #ifndef DEBUG // leave all the remaining clean-up to the OS // (as recommended for a quick exit) ExitProcess(retCode); #else DeleteObject(GetDefaultGuiFont()); DeleteBitmap(gBitmapReloadingCue); DeleteSplitterBrush(); // wait for FileExistenceChecker to terminate // (which should be necessary only very rarely) while (gFileExistenceChecker) { Sleep(10); uitask::DrainQueue(); } mui::Destroy(); uitask::Destroy(); trans::Destroy(); SaveCallstackLogs(); dbghelp::FreeCallstackLogs(); // must be after uitask::Destroy() because we might have queued prefs::Reload() // which crashes if gGlobalPrefs is freed gFileHistory.UpdateStatesSource(NULL); DeleteGlobalPrefs(gGlobalPrefs); // it's still possible to crash after this (destructors of static classes, // atexit() code etc.) point, but it's very unlikely UninstallCrashHandler(); // output leaks after all destructors of static objects have run _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); return retCode; #endif }
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { static HWND shwnd; static HDC hdc; static HGLRC hglrc, hglrc_legacy; static Engine altEngine; static POINT center; static WSADATA wsadata; switch (message) { case WM_CREATE: WSAStartup(MAKEWORD(2, 2), &wsadata); AllocConsole(); RedirectIOToConsole(); SetTimer ( hwnd, TICK_TIMER, 16, NULL ); hdc = GetDC(hwnd); setupPixelFormat(hdc); #ifndef DIRECTX hglrc_legacy = wglCreateContext(hdc); wglMakeCurrent(hdc, hglrc_legacy); glewInit(); if(wglewIsSupported("WGL_ARB_create_context") == TRUE) { const int context[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 1, // WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 }; const int pixelformat[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_COLOR_BITS_ARB, 32, WGL_DEPTH_BITS_ARB, 24, WGL_STENCIL_BITS_ARB, 8, 0, }; int format; unsigned int num_formats; wglChoosePixelFormatARB(hdc, (int *)pixelformat, NULL, 1, &format, &num_formats); hglrc = wglCreateContextAttribsARB(hdc, 0, context); wglMakeCurrent(NULL,NULL); wglDeleteContext(hglrc_legacy); wglMakeCurrent(hdc, hglrc); } else { //opengl 2.0 hglrc = hglrc_legacy; } #endif shwnd = hwnd; altEngine.init(&shwnd, &hdc); return 0; case WMU_RENDER: altEngine.render(); return 0; case WM_TIMER: if (glGetError() != GL_NO_ERROR) { printf("GL_ERROR\n"); } switch(wParam) { case TICK_TIMER: altEngine.step(); break; } return 0; case WM_MOUSEMOVE: { int x, y; x = LOWORD(lParam); y = HIWORD(lParam); if ((x == center.x) && (y == center.y)) return 0; if ( altEngine.mousepos(x, y, x - center.x, y - center.y) ) { POINT screen = center; ClientToScreen(hwnd, &screen); SetCursorPos(screen.x, screen.y); } } return 0; case WM_LBUTTONDOWN: case WM_LBUTTONUP: { bool pressed = (message == WM_LBUTTONDOWN) ? true : false; altEngine.keypress("leftbutton", pressed); return 0; } case WM_MBUTTONDOWN: case WM_MBUTTONUP: { bool pressed = (message == WM_MBUTTONDOWN) ? true : false; altEngine.keypress("middlebutton", pressed); return 0; } case WM_RBUTTONDOWN: case WM_RBUTTONUP: { bool pressed = (message == WM_RBUTTONDOWN) ? true : false; altEngine.keypress("rightbutton", pressed); return 0; } case WM_KEYDOWN: case WM_KEYUP: { bool pressed = (message == WM_KEYDOWN) ? true : false; switch (wParam) { case VK_PAUSE: break; case VK_TAB: break; case VK_RETURN: altEngine.keypress("enter", pressed); break; case VK_SHIFT: altEngine.keypress("shift", pressed); break; case VK_CONTROL: altEngine.keypress("control", pressed); break; case VK_ESCAPE: altEngine.keypress("escape", pressed); break; case VK_UP: altEngine.keypress("up", pressed); break; case VK_LEFT: altEngine.keypress("left", pressed); break; case VK_DOWN: altEngine.keypress("down", pressed); break; case VK_RIGHT: altEngine.keypress("right", pressed); break; } return 0; } case WM_CHAR: altEngine.keystroke((char)wParam); return 0; case WM_SIZE: { int width, height; width = LOWORD(lParam); height = HIWORD(lParam); center.x = width / 2; center.y = height / 2; altEngine.resize(width, height); } return 0; case WM_SYSCOMMAND: switch(wParam) { case SC_SCREENSAVE: case SC_MONITORPOWER: return 0; } break; case WM_DESTROY: #ifndef DIRECTX if (hglrc) { wglMakeCurrent(NULL, NULL); wglDeleteContext(hglrc); ReleaseDC(hwnd, hdc); } #endif altEngine.destroy(); WSACleanup(); PostQuitMessage(0); return 0; } return DefWindowProc(hwnd, message, wParam, lParam); }
// Tests windows native library. // Example C program that ensures the graphic shell works. // This tests the native layer implmentation without golang. int main() { RedirectIOToConsole(); dev_run(); // Does not return. Calls prepRender() and renderFrame(). return 0; }
//================================================================================================================================= /// /// WinMain function for this simple ES app. /// /// \param hInstance instance. /// \param hPrevInstance previous instance. /// \param lpCmdLine command line parameters. /// \param nCmdShow window show state. /// /// \return void //================================================================================================================================= int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { UINT res = WinExec ("C:\\Program Files (x86)\\NVIDIA Corporation\\win_x86_es2emu\\ait\\esTriangle\\copy.bat", SW_SHOWNORMAL); MSG msg; BOOL done=FALSE; g_scene = new msScene(); // redirect stdin/stdout to a console window RedirectIOToConsole(); // unit tests //msBox::unitTest(); //msAnimation::unitTest(); //msAnimationBundle::unitTest(); // msBoxGrid::unitTest(); // return 0; MainFuncInit(); HWND hWnd = CreateWind( SCR_WIDTH, SCR_HEIGHT ) ; if ( !hWnd ) { return 0; } string *uniformsPath = new string("\\data\\uniforms.txt"); msMapDataFileName(*uniformsPath); g_scene->loadData(*uniformsPath); delete uniformsPath; g_scene->init(); #ifdef PERFORMANCE_TUNING SetTimer(hWnd, // handle to main window 43, // timer identifier 2000, (TIMERPROC) NULL); // no timer callback #else SetTimer(hWnd, // handle to main window 43, // timer identifier FRAME_INTERVAL, // 10-second interval (TIMERPROC) NULL); // no timer callback #endif while ( ! done ) { if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) // Is There A Message Waiting? { if ( msg.message == WM_QUIT ) { done=TRUE; } else { TranslateMessage( &msg ); DispatchMessage( &msg ); } } else { #ifdef PERFORMANCE_TUNING if ( ( g_active && !DrawScene() ) || g_keys[VK_ESCAPE] ) { done=TRUE; // ESC or DrawGLScene Signalled A Quit } else { eglSwapBuffers( g_egl.dsp, g_egl.surf ); frameCount ++; } #else if ( ( g_active && FALSE ) || g_keys[VK_ESCAPE] ) { done=TRUE; // ESC or DrawGLScene Signalled A Quit } #endif } } eglDestroyContext( g_egl.dsp, g_egl.cxt ); eglDestroySurface( g_egl.dsp, g_egl.surf ); eglTerminate( g_egl.dsp ); delete g_scene; #ifdef WINDOWS_GL _CrtDumpMemoryLeaks(); #endif return 0; }
int WINAPI WinMain( HINSTANCE hinstance, HINSTANCE hprevinstance, LPSTR lpcmdline, int ncmdshow) { // 3rd processor HANDLE threadId = GetCurrentThread(); DWORD_PTR processAffinityMask = 8; //4; SetThreadAffinityMask(threadId, processAffinityMask); MSG msg; // generic message createWindow(hinstance); RedirectIOToConsole(); createGrid(); // 0. Renderer setup renderer = new Renderer(); renderer->m_connection = &conn; renderer->init(hwnd, 600, 600); // 1. Connection with server setup conn.m_renderer = renderer; conn.setReceiveBuffer((void*)&m_circles); conn.setRopeReceiveBuffer((void*)&m_rope); conn.m_ropePoints = &nRopePoints; conn.m_objectsPerSecond = renderer->getPtrObjectsPerSec(); conn.start(0, 0); conn.m_objectsReceived = &nObjects; // 2. Main Loop double freqGraphics = renderer->getGraphicsFreq(); double delta = 1.0f / (double)freqGraphics; renderer->startTimer(); double d0, d1, elapsedTime=0; int counter = 0; double timer = 0; double currentTime = 0; double avgElapsedTime = 0.0; double baseTime = renderer->getTime(); bool quit = false; while(!quit) { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { if (msg.message == WM_QUIT) quit = true; TranslateMessage(&msg); DispatchMessage(&msg); } else { currentTime = renderer->getTime() - baseTime; if (currentTime >= delta*counter) { d0 = renderer->getTime(); renderer->clear(); renderer->draw(m_rope, nRopePoints); renderer->draw(m_lines, N_LINES); renderer->draw(m_circles, nObjects); renderer->present(); d1 = renderer->getTime(); elapsedTime = d1-d0; counter++; // Things to be checked after execution of each loop ------------ // ... } avgElapsedTime += elapsedTime; timer += renderer->getDeltaTime(); // Things to do per Second ----------------------------- if (timer >= 1.0) { timer = 0.0; //------------------ // average elapsedTime avgElapsedTime /= (double)freqGraphics; // get new value for baseTime baseTime = renderer->getTime(); std::cout << "fps: " << counter << endl; // get current value for frequency and update delta freqGraphics = renderer->getGraphicsFreq(); delta = 1.0f / (double)freqGraphics; avgElapsedTime = 0; counter = 0; } } } // end while // return to Windows like this return(msg.wParam); }
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int retCode = 1; // by default it's error #ifdef DEBUG // Memory leak detection (only enable _CRTDBG_LEAK_CHECK_DF for // regular termination so that leaks aren't checked on exceptions, // aborts, etc. where some clean-up might not take place) _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF); //_CrtSetBreakAlloc(421); TryLoadMemTrace(); #endif DisableDataExecution(); // ensure that C functions behave consistently under all OS locales // (use Win32 functions where localized input or output is desired) setlocale(LC_ALL, "C"); // don't show system-provided dialog boxes when accessing files on drives // that are not mounted (e.g. a: drive without floppy or cd rom drive // without a cd). SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS); #if defined(DEBUG) || defined(SVN_PRE_RELEASE_VER) if (str::StartsWith(lpCmdLine, "/tester")) { extern int TesterMain(); // in Tester.cpp return TesterMain(); } if (str::StartsWith(lpCmdLine, "/regress")) { extern int RegressMain(); // in Regress.cpp return RegressMain(); } #endif #ifdef SUPPORTS_AUTO_UPDATE if (str::StartsWith(lpCmdLine, "-autoupdate")) { bool quit = AutoUpdateMain(); if (quit) return 0; } #endif RunUnitTests(); srand((unsigned int)time(NULL)); { ScopedMem<WCHAR> symDir; ScopedMem<WCHAR> tmpDir(path::GetTempPath()); if (tmpDir) symDir.Set(path::Join(tmpDir, L"SumatraPDF-symbols")); else symDir.Set(AppGenDataFilename(L"SumatraPDF-symbols")); ScopedMem<WCHAR> crashDumpPath(AppGenDataFilename(CRASH_DUMP_FILE_NAME)); InstallCrashHandler(crashDumpPath, symDir); } ScopedOle ole; InitAllCommonControls(); ScopedGdiPlus gdiPlus(true); mui::Initialize(); uitask::Initialize(); LoadPrefs(); CommandLineInfo i; GetCommandLineInfo(i); SetCurrentLang(i.lang ? i.lang : gGlobalPrefs->currLangCode); if (i.showConsole) RedirectIOToConsole(); if (i.makeDefault) AssociateExeWithPdfExtension(); if (i.pathsToBenchmark.Count() > 0) { BenchFileOrDir(i.pathsToBenchmark); if (i.showConsole) system("pause"); } if (i.exitImmediately) goto Exit; gCrashOnOpen = i.crashOnOpen; gUserPrefs->mainWindowBackground = i.bgColor; if (gUserPrefs->forwardSearch.highlightColor != i.forwardSearch.highlightColor || gUserPrefs->forwardSearch.highlightOffset != i.forwardSearch.highlightOffset || gUserPrefs->forwardSearch.highlightPermanent != i.forwardSearch.highlightPermanent || gUserPrefs->forwardSearch.highlightWidth != i.forwardSearch.highlightWidth) { gGlobalPrefs->enableTeXEnhancements = true; } gUserPrefs->forwardSearch = i.forwardSearch; gUserPrefs->escToExit = i.escToExit; gGlobalPrefs->cbxR2L = i.cbxR2L; gPolicyRestrictions = GetPolicies(i.restrictedUse); gRenderCache.colorRange[0] = i.colorRange[0]; gRenderCache.colorRange[1] = i.colorRange[1]; DebugGdiPlusDevice(gUseGdiRenderer); DebugAlternateChmEngine(gUserPrefs->ebookUI.traditionalEbookUI); if (i.inverseSearchCmdLine) { str::ReplacePtr(&gGlobalPrefs->inverseSearchCmdLine, i.inverseSearchCmdLine); gGlobalPrefs->enableTeXEnhancements = true; } if (!RegisterWinClass(hInstance)) goto Exit; if (!InstanceInit(hInstance, nCmdShow)) goto Exit; if (i.hwndPluginParent) { if (!SetupPluginMode(i)) goto Exit; } if (i.printerName) { // note: this prints all PDF files. Another option would be to // print only the first one for (size_t n = 0; n < i.fileNames.Count(); n++) { bool ok = PrintFile(i.fileNames.At(n), i.printerName, !i.silent, i.printSettings); if (!ok) retCode++; } --retCode; // was 1 if no print failures, turn 1 into 0 goto Exit; } if (i.fileNames.Count() == 0 && gGlobalPrefs->rememberOpenedFiles && gGlobalPrefs->showStartPage) { // make the shell prepare the image list, so that it's ready when the first window's loaded SHFILEINFO sfi; SHGetFileInfo(L".pdf", 0, &sfi, sizeof(sfi), SHGFI_SYSICONINDEX | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES); } if (!i.reuseInstance && gUserPrefs->reuseInstance && FindWindow(FRAME_CLASS_NAME, 0)) i.reuseInstance = true; WindowInfo *win = NULL; bool isFirstWin = true; for (size_t n = 0; n < i.fileNames.Count(); n++) { if (i.reuseInstance && !i.printDialog) { OpenUsingDde(i.fileNames.At(n), i, isFirstWin); } else { win = LoadOnStartup(i.fileNames.At(n), i, isFirstWin); if (!win) { retCode++; continue; } if (i.printDialog) OnMenuPrint(win, i.exitWhenDone); } isFirstWin = false; } if (i.fileNames.Count() > 0 && isFirstWin) { // failed to create any window, even though there // were files to load (or show a failure message for) goto Exit; } if (i.reuseInstance && !i.printDialog || i.printDialog && i.exitWhenDone) goto Exit; if (isFirstWin) { win = CreateAndShowWindowInfo(); if (!win) goto Exit; } UpdateUITextForLanguage(); // needed for RTL languages if (isFirstWin) UpdateToolbarAndScrollbarState(*win); // Make sure that we're still registered as default, // if the user has explicitly told us to be if (gGlobalPrefs->pdfAssociateShouldAssociate && win) RegisterForPdfExtentions(win->hwndFrame); if (gGlobalPrefs->enableAutoUpdate && gWindows.Count() > 0) AutoUpdateCheckAsync(gWindows.At(0)->hwndFrame, true); if (i.stressTestPath) StartStressTest(&i, win, &gRenderCache); if (gFileHistory.Get(0)) { gFileExistenceChecker = new FileExistenceChecker(); gFileExistenceChecker->Start(); } retCode = RunMessageLoop(); CleanUpThumbnailCache(gFileHistory); Exit: while (gWindows.Count() > 0) { DeleteWindowInfo(gWindows.At(0)); } while (gEbookWindows.Count() > 0) { DeleteEbookWindow(gEbookWindows.At(0), true); } #ifndef DEBUG // leave all the remaining clean-up to the OS // (as recommended for a quick exit) ExitProcess(retCode); #else CrashIf(gFileExistenceChecker); DeleteObject(gBrushNoDocBg); DeleteObject(gBrushLogoBg); DeleteObject(gBrushAboutBg); DeleteObject(gDefaultGuiFont); DeleteBitmap(gBitmapReloadingCue); gFileHistory.UpdateStatesSource(NULL); DeleteGlobalPrefs(gGlobalPrefs); mui::Destroy(); uitask::Destroy(); trans::Destroy(); // it's still possible to crash after this (destructors of static classes, // atexit() code etc.) point, but it's very unlikely UninstallCrashHandler(); // output leaks after all destructors of static objects have run _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); return retCode; #endif }
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { // Define a class for our main window WNDCLASS WindowClass; WindowClass.style = 0; WindowClass.lpfnWndProc = WndProc; WindowClass.cbClsExtra = 0; WindowClass.cbWndExtra = 0; WindowClass.hInstance = hInstance; WindowClass.hIcon = NULL; WindowClass.hCursor = 0; WindowClass.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BACKGROUND); WindowClass.lpszMenuName = NULL; WindowClass.lpszClassName = L"SFML App"; RegisterClass(&WindowClass); // Let's create the main window HWND Window = CreateWindow(L"SFML App", L"SFML Win32", WS_SYSMENU | WS_VISIBLE, 0, 0, 1280, 720, NULL, NULL, hInstance, NULL); // Let's create two SFML views DWORD Style = WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS; HWND View1 = CreateWindow(L"STATIC", NULL, Style, 0, 0, 200, 720, Window, NULL, hInstance, NULL); HWND View2 = CreateWindow(L"STATIC", NULL, Style, 200, 0, 1080, 720, Window, NULL, hInstance, NULL); // INIT CONSOLE RedirectIOToConsole(); sf::RenderWindow SFMLView1(View1); sf::RenderWindow SFMLView2(View2); // babby's main loop MSG Message; Message.message = ~WM_QUIT; while (Message.message != WM_QUIT) { if (PeekMessage(&Message, NULL, 0, 0, PM_REMOVE)) { // If a message was waiting in the message queue, process it TranslateMessage(&Message); DispatchMessage(&Message); } else { // SFML rendering code goes here // Clear views SFMLView1.clear(sf::Color::Blue); SFMLView2.clear(sf::Color::Red); // Draw sprite 1 on view 1 //SFMLView1.draw(Sprite1); // Draw sprite 2 on view 2 //SFMLView2.Draw(Sprite2); // Display each view on screen SFMLView1.display(); SFMLView2.display(); } } // Destroy the main window DestroyWindow(Window); // Don't forget to unregister the window class UnregisterClass(L"SFML App", hInstance); }
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { bool Ok = true; if(!IsVdfs()) { if(!IsSpacer()) { bool ChangeWorkDir = false; TString WorkPath; if(PlatformGetWorkPath(WorkPath) && WorkPath.TruncateBeforeLast(_T("\\")) && WorkPath.Compare(_T("System"), true)) ChangeWorkDir = (SetCurrentDirectory(_T("..\\")) == TRUE); TStringArray Libraries; if(PlatformReadTextFile(_T("System\\pre.load"), Libraries)) { for(uInt l = 0; l < Libraries.Size(); l++) { if(!LoadLibrary(TString(_T("System\\")) + Libraries[l])) { RedirectIOToConsole(); _tprintf(_T("%s not loaded\n"), Libraries[l].GetData()); } } } if(ChangeWorkDir) SetCurrentDirectory(_T("System\\")); } Ok = Ok && InstallFsHook(VdfsBase); if(!Ok) { RedirectIOToConsole(); printf("InstallFsHook failed\n"); } Ok = Ok && InstallSendMsgFix(); if(!Ok) { RedirectIOToConsole(); printf("InstallSendMsgFix failed\n"); } if(!IsSpacer()) { Ok = Ok && PreInstallKillerFix(); if(!Ok) { RedirectIOToConsole(); printf("InstallKillerFix failed\n"); } Ok = Ok && InstallGUXFix(); if(!Ok) { RedirectIOToConsole(); printf("InstallGUXFix failed\n"); } Ok = Ok && InstallD3DFix(); if(!Ok) { RedirectIOToConsole(); printf("InstallD3DFix failed\n"); } Ok = Ok && InstallIniFix(); if(!Ok) { RedirectIOToConsole(); printf("InstallIniFix failed\n"); } Ok = Ok && InstallBinkFix(); if(!Ok) { RedirectIOToConsole(); printf("InstallBinkFix failed\n"); } Ok = Ok && InstallSplashFix(); if(!Ok) { RedirectIOToConsole(); printf("InstallSplashFix failed\n"); } Ok = Ok && InstallMssFix(); if(!Ok) { RedirectIOToConsole(); printf("InstallMssFix failed\n"); } Ok = Ok && PrepareSteamOverlayFix(); if(!Ok) { RedirectIOToConsole(); printf("PrepareSteamOverlayFix failed\n"); } } } return Ok ? TRUE : FALSE; } break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: { if(!IsVdfs() && !IsSpacer()) { RemoveMssFix(); RemoveSplashFix(); RemoveBinkFix(); RemoveIniFix(); RemoveD3DFix(); RemoveKillerFix(); } } break; } return TRUE; }