示例#1
0
文件: bibedt.cpp 项目: stievie/bibedt
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	CWaitCursor wait;
	CString v;
	v.Format(_T("Version %s"), GetAppVersion());
#ifdef _DEBUG
	v += _T("  ***DEBUG***");
#endif
	//{{AFX_DATA_INIT(CAboutDlg)
	m_Version = v;
	//}}AFX_DATA_INIT
	m_Email.SetURL(_T("mailto:") + CString(STIEVIE_MAIL));
	m_NilsEmail.SetURL(_T("mailto:") + CString(NILS_MAIL));
	m_Web.SetURL(CString(BIBEDT_URL) + _T("?version=") + GetAppVersion());
	m_btnDonate.LoadBitmaps(IDB_DONATE);
}
示例#2
0
文件: edapp.cpp 项目: mfloryan/poedit
void PoeditApp::OpenPoeditWeb(const wxString& path)
{
    wxLaunchDefaultBrowser
    (
        wxString::Format("http://poedit.net%s?fromVersion=%s",
                         path,
                         GetAppVersion())
    );
}
示例#3
0
文件: edapp.cpp 项目: mfloryan/poedit
void PoeditApp::SetDefaultCfg(wxConfigBase *cfg)
{
    SetDefaultParsers(cfg);

    if (cfg->Read("version", wxEmptyString) == GetAppVersion()) return;

    if (cfg->Read("TM/search_paths", wxEmptyString).empty())
    {
        wxString paths;
#if defined(__UNIX__)
        paths = wxGetHomeDir() + ":/usr/share/locale:/usr/local/share/locale";
#elif defined(__WXMSW__)
        paths = "C:";
#endif
        cfg->Write("TM/search_paths", paths);
    }

    cfg->Write("version", GetAppVersion());
}
示例#4
0
const char *LoadVersionFromResource()
{
    WORD MajorVersion			=0;
    WORD MinorVersion			=0;
    WORD BuildNumber			=0;
    WORD RevisionNumber			=0;

    GetAppVersion(szModulePath,
                  &MajorVersion,
                  &MinorVersion,
                  &BuildNumber,
                  &RevisionNumber);

    sprintf_s( szBufferVersion, RESOURCE_STRING_BUFFER_SIZE, "%d.%d.%d.%d", MajorVersion, MinorVersion, BuildNumber, RevisionNumber );
    return szBufferVersion;
}
示例#5
0
void ShowHelp()
{
#if defined(_WIN64)
    int platformId = 64;
#else
    int platformId = 32;
#endif

    wstring appVersion = GetAppVersion(g_moduleFilePath.c_str(), NULL, NULL, NULL, NULL);

    OutputConsole(L"ic%d.exe (ver %s)\n", platformId, appVersion.c_str());
    OutputConsole(L"ic%d.exe -h\n", platformId);
    OutputConsole(L"ic%d.exe -key [apikey] -s [hostaddress] -id [agentid] -d [interval-sec,[...]]\n", platformId);
    OutputConsole(L"\n");
    OutputConsole(L"samples:\n");
    OutputConsole(L"    ic%d.exe -key 8CFDDE2478 -s 192.168.0.5\n", platformId);
    OutputConsole(L"        apikey: 8CFDDE2478\n");
    OutputConsole(L"        data server: 192.168.0.5:80\n");
    OutputConsole(L"        (optional: agent id by default - machine name)\n");
    OutputConsole(L"\n");
    OutputConsole(L"    ic%d.exe -key 8CFDDE2478 -s 192.168.0.5 -port 8282\n", platformId);
    OutputConsole(L"        apikey: 8CFDDE2478\n");
    OutputConsole(L"        data server: 192.168.0.5:8282\n");
    OutputConsole(L"        (optional: agent id by default - machine name)\n");
    OutputConsole(L"\n");
    OutputConsole(L"    ic%d.exe -key 8CFDDE2478 -s 192.168.0.5 -id mypc100\n", platformId);
    OutputConsole(L"        apikey: 8CFDDE2478\n");
    OutputConsole(L"        data server: 192.168.0.5:80\n");
    OutputConsole(L"        id: mypc100\n");
    OutputConsole(L"\n");
    OutputConsole(L"    ic%d.exe -key 8CFDDE2478 -s 192.168.0.5 -id mypc100  -regservice\n", platformId);
    OutputConsole(L"        Register as NT Service with this info,\n");
    OutputConsole(L"            apikey: 8CFDDE2478\n");
    OutputConsole(L"            data server: 192.168.0.5:80\n");
    OutputConsole(L"            id: mypc100\n");
    OutputConsole(L"\n");
    OutputConsole(L"    ic%d.exe -unreg\n", platformId);
    OutputConsole(L"        Unregister NT Service\n");
}
示例#6
0
bool InjectorApp::OnInit() {
	::wxInitAllImageHandlers();
    //wxXmlResource::Get()->InitAllHandlers();
    wxFileSystem::AddHandler(new wxArchiveFSHandler);
    wxFileSystem::AddHandler(new wxFilterFSHandler);
    wxFileSystem::AddHandler(new wxMemoryFSHandler);

    m_appdir = wxStandardPaths::Get().GetExecutablePath();
    if (!m_appdir.IsAbsolute())
        m_appdir.MakeAbsolute();

    m_title = GetAppVersion();
	
	m_installdir = "";
	if (!wxApp::OnInit())
		return false;
		
#ifdef _WIN32
	if (m_installdir.IsEmpty()) {
		wxRegKey key("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{907B4640-266B-4A21-92FB-CD1A86CD0F63}");
		if (key.Exists())
			key.QueryValue("InstallLocation", m_installdir);
	}
#endif

	if (m_installdir.IsEmpty() || (!CheckInstallDir())) {
		::wxMessageBox("Could not determine RCT3 installation folder. Please give the correct folder with the command line option '--installdir'.", "Error",wxICON_ERROR|wxOK);
		return false;
	}

    frmMain* main = new frmMain(NULL);
    main->Show(true);
    SetTopWindow(main);

    return true;

}
示例#7
0
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;
}
示例#8
0
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;
}
示例#9
0
文件: edapp.cpp 项目: mfloryan/poedit
bool PoeditApp::IsBetaVersion() const
{
    wxString v = GetAppVersion();
    return  v.Contains("beta") || v.Contains("rc");
}
示例#10
0
文件: edapp.cpp 项目: mfloryan/poedit
void PoeditApp::SetDefaultParsers(wxConfigBase *cfg)
{
    ParsersDB pdb;
    bool changed = false;
    wxString defaultsVersion = cfg->Read("Parsers/DefaultsVersion",
                                         "1.2.x");
    pdb.Read(cfg);

    // Add parsers for languages supported by gettext itself (but only if the
    // user didn't already add language with this name himself):
    static struct
    {
        const char *name;
        const char *exts;
    } s_gettextLangs[] = {
        { "C/C++",    "*.c;*.cpp;*.h;*.hpp;*.cc;*.C;*.cxx;*.hxx" },
        { "C#",       "*.cs" },
        { "Java",     "*.java" },
        { "Perl",     "*.pl" },
        { "PHP",      "*.php" },
        { "Python",   "*.py" },
        { "TCL",      "*.tcl" },
        { NULL, NULL }
    };

    for (size_t i = 0; s_gettextLangs[i].name != NULL; i++)
    {
        // if this lang is already registered, don't overwrite it:
        if (pdb.FindParser(s_gettextLangs[i].name) != -1)
            continue;

        wxString langflag;
        if ( wxStrcmp(s_gettextLangs[i].name, "C/C++") == 0 )
            langflag = " --language=C++";
        else
            langflag = wxString(" --language=") + s_gettextLangs[i].name;

        // otherwise add new parser:
        Parser p;
        p.Name = s_gettextLangs[i].name;
        p.Extensions = s_gettextLangs[i].exts;
        p.Command = wxString("xgettext") + langflag + " --add-comments=TRANSLATORS --force-po -o %o %C %K %F";
        p.KeywordItem = "-k%k";
        p.FileItem = "%f";
        p.CharsetItem = "--from-code=%c";
        pdb.Add(p);
        changed = true;
    }

    // If upgrading Poedit to 1.2.4, add dxgettext parser for Delphi:
#ifdef __WINDOWS__
    if (defaultsVersion == "1.2.x")
    {
        Parser p;
        p.Name = "Delphi (dxgettext)";
        p.Extensions = "*.pas;*.dpr;*.xfm;*.dfm";
        p.Command = "dxgettext --so %o %F";
        p.KeywordItem = wxEmptyString;
        p.FileItem = "%f";
        pdb.Add(p);
        changed = true;
    }
#endif

    // If upgrading Poedit to 1.2.5, update C++ parser to handle --from-code:
    if (defaultsVersion == "1.2.x" || defaultsVersion == "1.2.4")
    {
        int cpp = pdb.FindParser("C/C++");
        if (cpp != -1)
        {
            if (pdb[cpp].Command == "xgettext --force-po -o %o %K %F")
            {
                pdb[cpp].Command = "xgettext --force-po -o %o %C %K %F";
                pdb[cpp].CharsetItem = "--from-code=%c";
                changed = true;
            }
        }
    }

    // Poedit 1.5.6 had a breakage, it add --add-comments without space in front of it.
    // Repair this automatically:
    for (size_t i = 0; i < pdb.GetCount(); i++)
    {
        wxString& cmd = pdb[i].Command;
        if (cmd.Contains("--add-comments=") && !cmd.Contains(" --add-comments="))
        {
            cmd.Replace("--add-comments=", " --add-comments=");
            changed = true;
        }
    }

    if (changed)
    {
        pdb.Write(cfg);
        cfg->Write("Parsers/DefaultsVersion", GetAppVersion());
    }
}
示例#11
0
void ProcessLatestUpdate()
{
    WORD majorVersion = 0;
    WORD minorVersion = 0;
    WORD buildNumber = 0;
    WORD revisionNumber = 0;

    wchar_t szTempFileName[MAX_PATH] { 0 };
    wchar_t lpTempPathBuffer[MAX_PATH] = { 0 };

    wstring thisFileName = g_moduleFilePath;
    wstring currentVersion;

    currentVersion = GetAppVersion(thisFileName.c_str(), &majorVersion, &minorVersion, &buildNumber, &revisionNumber);

    IWinHttpRequest *  pIWinHttpRequest = NULL;
    BSTR            bstrResponse = NULL;

    HRESULT hr = CoInitialize(NULL);

    do
    {
        VARIANT         varFalse;
        VARIANT         varEmpty;

        CLSID           clsid;

        VariantInit(&varFalse);
        V_VT(&varFalse) = VT_BOOL;
        V_BOOL(&varFalse) = VARIANT_FALSE;

        VariantInit(&varEmpty);
        V_VT(&varEmpty) = VT_ERROR;

        hr = CLSIDFromProgID(L"WinHttp.WinHttpRequest.5.1", &clsid);

        if (SUCCEEDED(hr) == FALSE)
        {
            break;
        }
        
        hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER,
            IID_IWinHttpRequest, (void **)&pIWinHttpRequest);
        
        if (SUCCEEDED(hr) == FALSE)
        {
            break;
        }

        BSTR bstrMethod = SysAllocString(L"GET");
        BSTR bstrUrl = SysAllocString(UPDATE_CHECK_URL);
        hr = pIWinHttpRequest->Open(bstrMethod, bstrUrl, varFalse);
        SysFreeString(bstrMethod);
        SysFreeString(bstrUrl);

        if (SUCCEEDED(hr) == FALSE)
        {
            break;
        }

        hr = pIWinHttpRequest->Send(varEmpty);
        if (SUCCEEDED(hr) == FALSE)
        {
            break;
        }

        hr = pIWinHttpRequest->get_ResponseText(&bstrResponse);

        wstring txt = bstrResponse;
        wstring newUpdateVersion = GetNewVersion(txt);
        if (newUpdateVersion.length() == 0)
        {
            break;
        }

        if (newUpdateVersion == currentVersion)
        {
            if (g_isConsoleApp == TRUE)
            {
                OutputConsole(L"This is the latest version (%s)\n", currentVersion.c_str());
            }
            break;
        }

        if (IsNewVersion(majorVersion, minorVersion, buildNumber, revisionNumber, newUpdateVersion) == FALSE)
        {
            if (g_isConsoleApp == TRUE)
            {
                OutputConsole(L"This is the latest version (%s)\n", L"1.0.0.4"); // currentVersion.c_str());
            }
            break;
        }

        // if new, update latest version.
        // if old, roll-back last stable version.

        bool is32bit = sizeof(char *) == 4;
        wstring location = GetUpdateLocation(txt, is32bit);

        VariantInit(&varEmpty);
        V_VT(&varEmpty) = VT_ERROR;

        bstrMethod = SysAllocString(L"GET");
        bstrUrl = SysAllocString(location.c_str());
        pIWinHttpRequest->Open(bstrMethod, bstrUrl, varFalse);
        SysFreeString(bstrMethod);
        SysFreeString(bstrUrl);

        if (SUCCEEDED(hr) == FALSE)
        {
            break;
        }

        hr = pIWinHttpRequest->Send(varEmpty);
        if (SUCCEEDED(hr) == FALSE)
        {
            break;
        }

        VARIANT varResponse;
        VariantInit(&varResponse);
        hr = pIWinHttpRequest->get_ResponseStream(&varResponse);
        if (SUCCEEDED(hr) == FALSE)
        {
            break;
        }

        txt = pIWinHttpRequest->GetResponseHeader(L"Content-Type").operator const wchar_t *();
        if (txt.find(L"text/html") != -1)
        {
            OutputError(L"file not found: %s", location.c_str());
            break;
        }

        IStream*    pStream = NULL;
        BYTE        bBuffer[8192];
        DWORD       cb, cbRead, cbWritten;

        if (VT_UNKNOWN == V_VT(&varResponse) || VT_STREAM == V_VT(&varResponse))
        {
            hr = V_UNKNOWN(&varResponse)->QueryInterface(IID_IStream,
                reinterpret_cast<void**>(&pStream));
        }
        else
        {
            break;
        }

        if (SUCCEEDED(hr) == FALSE)
        {
            break;
        }

        DWORD dwRetVal = GetTempPath(MAX_PATH,          // length of the buffer
            lpTempPathBuffer); // buffer for path 
        if (dwRetVal > MAX_PATH || (dwRetVal == 0))
        {
            OutputError(L"GetTempPath failed (%d)", GetLastError());
            break;
        }

        dwRetVal = GetTempFileName(lpTempPathBuffer, // directory for tmp files
            L"straw",     // temp file name prefix 
            0,                // create unique name 
            szTempFileName);  // buffer for name 
        if (dwRetVal == 0)
        {
            OutputError(L"GetTempFileName failed (%d)", GetLastError());
            break;
        }

        bool succeed = true;

        HANDLE hFile = CreateFile(szTempFileName,
            GENERIC_WRITE,                // Open for writing. 
            0,                            // Do not share. 
            NULL,                         // No security. 
            CREATE_ALWAYS,                // Overwrite existing.
            FILE_ATTRIBUTE_NORMAL,        // Normal file.
            NULL);                        // No attribute template.
        if (hFile == INVALID_HANDLE_VALUE)
        {
            OutputError(L"Can't open a file: %s", szTempFileName);
            break;
        }
        else
        {
            cb = sizeof(bBuffer);
            hr = pStream->Read(bBuffer, cb, &cbRead);
            while (SUCCEEDED(hr) && 0 != cbRead)
            {
                if (!WriteFile(hFile, bBuffer,
                    cbRead, &cbWritten, NULL))
                {
                    OutputError(L"WriteFile fails with 0x%08lx\n", HRESULT_FROM_WIN32(GetLastError()));
                    succeed = false;
                    break;
                }

                hr = pStream->Read(bBuffer, cb, &cbRead);
            }
        }

        CloseHandle(hFile);
        pStream->Release();
        VariantClear(&varResponse);

        if (succeed == true)
        {
            wstring oldFileName = thisFileName;
            oldFileName += currentVersion + L".bak";

            ::DeleteFile(oldFileName.c_str());

            if (MoveFile(thisFileName.c_str(), oldFileName.c_str()) == FALSE)
            {
                OutputError(L"Backup fails (%d)", GetLastError());
                break;
            }

            if (MoveFile(szTempFileName, thisFileName.c_str()) == FALSE)
            {
                OutputError(L"Update fails (%d)", GetLastError());
                break;
            }

            FireRestartCommand();
        }

    } while (false);

    if (::PathFileExists(szTempFileName) == TRUE)
    {
        ::DeleteFile(szTempFileName);
    }

    if (pIWinHttpRequest)
    {
        pIWinHttpRequest->Release();
    }

    if (bstrResponse)
    {
        SysFreeString(bstrResponse);
    }

    CoUninitialize();
}
示例#12
0
DWORD ServiceExecutionThread(LPDWORD param)
{
#if _DEBUG
    ::OutputDebugString(L"ServiceExecutionThread\n");
#endif

    if (IntializeSystemInfo() == FALSE)
    {
        return IC_NO_INITIALIZE;
    }

    WORD wVersionRequested = MAKEWORD(1, 1);
    WSADATA wsaData;
    WSAStartup(wVersionRequested, &wsaData);
    SOCKET udpSocket = INVALID_SOCKET;

    int result = IC_NOERROR;
    bool showHelp = false;

    do
    {
        g_killServiceEvent = CreateEvent(0, TRUE, FALSE, 0);
        if (!g_killServiceEvent)
        {
            OutputError(L"CreateEvent fails! (%d)", GetLastError());
            result = IC_EVENT_CREATE_FAIL;
            break;
        }

        wstring apiKey;
        wstring envInfo;
        vector<int> intervalTimes;
        ConnectionInfo connection;

        g_debugMode = GetDebugMode(g_argc, g_argv);

        if (cmdOptionExists(g_argv, g_argv + g_argc, L"-h") == true
            || cmdOptionExists(g_argv, g_argv + g_argc, L"/h") == true)
        {
            showHelp = true;
            break;
        }

        if (cmdOptionExists(g_argv, g_argv + g_argc, L"-unreg") == true)
        {
            DoUnregistration();
            break;
        }

        if (cmdOptionExists(g_argv, g_argv + g_argc, L"-start") == true)
        {
            DoStartService();
            break;
        }

        if (cmdOptionExists(g_argv, g_argv + g_argc, L"-stop") == true)
        {
            DoStopService();
            break;
        }

        if (cmdOptionExists(g_argv, g_argv + g_argc, L"-update") == true)
        {
            ProcessLatestUpdate();
            break;
        }

        if (cmdOptionExists(g_argv, g_argv + g_argc, L"-restart") == true)
        {
            RestartService();
            break;
        }

        apiKey = GetApiKey(g_argc, g_argv);
        envInfo = GetEnvInfo(g_argc, g_argv);
        intervalTimes = GetIntervalTime(g_argc, g_argv);

        if (apiKey.length() == 0)
        {
            OutputError(L"NO ApiKey\n");
            result = IC_NO_APIKEY;
            showHelp = true;
            break;
        }

        if (envInfo.length() == 0)
        {
            OutputError(L"NO AgentID Info\n");
            result = IC_NO_AGENTIDINFO;
            showHelp = true;
            break;
        }

        string address = GetHostAddress(g_argc, g_argv, connection);
        struct hostent *host = gethostbyname(address.c_str());
        if (host == nullptr)
        {
            OutputError(L"Can't resolve host address: %s\n", address.c_str());
            result = IC_NO_RESOLVE_HOSTADDR;
            break;
        }

        SetupHostPort(g_argc, g_argv, connection);

        if (cmdOptionExists(g_argv, g_argv + g_argc, L"-regservice") == true)
        {
            DoRegistration(apiKey, envInfo, address, connection.Getport(), intervalTimes);
            break;
        }

        struct sockaddr_in remoteServAddr;

        remoteServAddr.sin_family = host->h_addrtype;
        memcpy((char *)&remoteServAddr.sin_addr.s_addr, host->h_addr_list[0], host->h_length);
        remoteServAddr.sin_port = htons((u_short)connection.Getport());

        /* socket creation */
        udpSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        if (udpSocket == INVALID_SOCKET) {
            OutputError(L"socket failed with error: %ld\n", WSAGetLastError());
            break;
        }

        wstring appVersion = GetAppVersion(g_moduleFilePath.c_str(), NULL, NULL, NULL, NULL);
        OutputConsole(L"(%s) ServiceExecutionThread - data collect thread - start\n", appVersion.c_str());

        {
            thread processCpuMemThread([apiKey, envInfo, udpSocket, remoteServAddr, intervalTimes]()
            {
                ProcessCpuMemInfo(apiKey, envInfo, udpSocket, remoteServAddr, intervalTimes[0]);
            });

            thread processDiskThread([apiKey, envInfo, udpSocket, remoteServAddr, intervalTimes]()
            {
                ProcessDiskInfo(apiKey, envInfo, udpSocket, remoteServAddr, intervalTimes[1]);
            });

            thread updateThread([]()
            {
                DWORD oneday = 1000 * 60 * 60 * 24;

                while (true)
                {
                    ProcessLatestUpdate();

                    if (::WaitForSingleObject(g_killServiceEvent, oneday) == WAIT_TIMEOUT)
                    {
                        continue;
                    }

                    break;
                }
            });

            if (g_isConsoleApp == TRUE)
            {
                printf("Press any key to exit...\n");
                getchar();
            }
            else
            {
#if _DEBUG
                ::OutputDebugString(L"Service thread - WaitForSingleObject...\n");
#endif
                WaitForSingleObject(g_killServiceEvent, INFINITE);
            }

#if _DEBUG
            ::OutputDebugString(L"Service thread waiting...\n");
            Sleep(1000);
#endif

            if (processCpuMemThread.joinable() == true)
            {
                processCpuMemThread.join();
            }

            if (processDiskThread.joinable() == true)
            {
                processDiskThread.join();
            }

            if (updateThread.joinable() == true)
            {
                updateThread.join();
            }

#if _DEBUG
            ::OutputDebugString(L"All Service-threads exited...\n");
#endif
        }

        ::SetEvent(g_killSafeExitEvent);

#if _DEBUG
        ::OutputDebugString(L"Service thread detached\n");
#endif

    } while (false);

#if _DEBUG
    ::OutputDebugString(L"ServiceExecutionThread - data collect thread - ending\n");
#endif

    if (udpSocket != INVALID_SOCKET)
    {
        closesocket(udpSocket);
    }

    if (showHelp == true)
    {
        ShowHelp();
    }

    WSACleanup();

#if _DEBUG
    ::OutputDebugString(L"ServiceExecutionThread - data collect thread - ended\n");
#endif

    return result;
}
示例#13
0
int SDLShell::Run(int argc, char *argv[])
{
	printf("*** %s, V%s ***\n", GetAppName(), GetAppVersion());

	int done;
	Uint8 *keys;

	if (SDL_Init(SDL_INIT_VIDEO))
	{
		printf("Unable to initialize SDL: %s\n", SDL_GetError());
		return 0;
	}

	ProcessCommandLine(argc, argv);

	if (!InitApp())
	{
		Exit(EXIT_INIT_APP);
	}

	SDL_Surface *screen;

	if (Verbose(VerboseAll))
	{
		printf("Setting width = %d, height = %d, bpp = %d\n",
			ShellGet(SDLShell::SHELL_WIDTH),
			ShellGet(SDLShell::SHELL_HEIGHT),
			ShellGet(SDLShell::SHELL_BPP));
	}
	screen = SDL_SetVideoMode(ShellGet(SDLShell::SHELL_WIDTH),
				ShellGet(SDLShell::SHELL_HEIGHT),
				ShellGet(SDLShell::SHELL_BPP), Flags());

	if (!screen)
	{
		fprintf(stderr, "Couldn't set %dx%d GL video mode: %s\n", 
			ShellGet(SDLShell::SHELL_WIDTH),
				ShellGet(SDLShell::SHELL_HEIGHT), SDL_GetError());
		
		Exit(EXIT_NO_SCREEN);
	}
	char tempString[100];
	sprintf(tempString, "%s V%s", GetAppName(), GetAppVersion());
	SDL_WM_SetCaption(tempString, GetAppName());

	SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, ShellGet(SHELL_VSYNC));

	if (RequiresOpenGL2())
	{
		// Initialize GLEW and make sure OpenGL 2.0 is supported
		GLenum err = glewInit();
		if(GLEW_OK != err)
		{
		    fprintf(stderr, "[ Fail ] - Error: %s\n", glewGetErrorString(err));
			Exit(EXIT_NO_GL2_SUPPORT);
		}

		if(!GLEW_VERSION_2_0 &&
		   !(GLEW_ARB_shading_language_100 && GLEW_ARB_shader_objects &&
		     GLEW_ARB_vertex_shader && GLEW_ARB_fragment_shader))
		{
		    fprintf(stderr, "[ Fail ] - Shaders not supported\n");
			Exit(EXIT_NO_GL2_SUPPORT);
		}

		if(!GLEW_ARB_vertex_buffer_object)
		{
		    fprintf(stderr, "[ Fail ] - VBO objects are not supported\n");
			Exit(EXIT_NO_GL2_SUPPORT);
		}
	}

	if (RequiresTTF())
	{

		if (TTF_Init() == -1) 
		{
			printf("Unable to initialize SDL_ttf: %s \n", TTF_GetError());
			Exit(EXIT_NO_FONT);
		}
	}

	CreatePointer();
	if (!InitGL())
	{
		Exit(EXIT_INIT_GL);
	}

	done = 0;
	while (!done)
	{
		pPointer->Input();
		ResetPressed();
		ResetMouse();

		SDL_Event event;

		while ( SDL_PollEvent(&event) ) 
		{
			switch(event.type)
			{
			case SDL_VIDEORESIZE:
				if (ShellGet(SDLShell::SHELL_RESIZABLE))
				{				
					screen = SDL_SetVideoMode(event.resize.w, event.resize.h,
								ShellGet(SDLShell::SHELL_BPP),
								Flags());
					if (screen)
					{
						Reshape(screen->w, screen->h);
					}
					else
					{
						/* Uh oh, we couldn't set the new video mode?? */;
					}
				}
				break;
            case SDL_MOUSEMOTION:
				pPointer->UpdateMouseMotion(event.motion);
				/*if (Verbose(VerboseAll))
				{
                	printf("Mouse moved by %d,%d to (%d,%d)\n", 
                       event.motion.xrel, event.motion.yrel,
                       event.motion.x, event.motion.y);
				}*/
                break;
            case SDL_MOUSEBUTTONDOWN:
				if (event.button.button == SDL_BUTTON_WHEELDOWN)
				{
					scrollDown = true;
				}
				pPointer->UpdateMouseButton(event.button);
				/*if (Verbose(VerboseAll))
				{
                	printf("Mouse button %d pressed at (%d,%d)\n",
                       event.button.button, event.button.x, event.button.y);
				}*/
                break;
            case SDL_MOUSEBUTTONUP:
				if (event.button.button == SDL_BUTTON_WHEELUP)
				{
					scrollUp = true;
				}
				if (event.button.button == SDL_BUTTON_LEFT)
				{
					leftClick = true;
				}
				if (event.button.button == SDL_BUTTON_RIGHT)
				{
					rightClick = true;
				}
				pPointer->UpdateMouseButton(event.button);
				/*if (Verbose(VerboseAll))
				{
                	printf("Mouse button %d released at (%d,%d)\n",
                       event.button.button, event.button.x, event.button.y);
				}*/
                break;

			case SDL_KEYUP:
				SetPressed(event.key.keysym.scancode, false);
				SetPressing(event.key.keysym.scancode, false);
				break;
			case SDL_KEYDOWN:
				if (Verbose(VerboseInfo))
				{
					printf("Pressed key %d\n", (int)event.key.keysym.scancode);
				}
				if (!KeyPressing(event.key.keysym.scancode))
				{
					SetPressed(event.key.keysym.scancode, true);
				}
				SetPressing(event.key.keysym.scancode, true);
				break;

			case SDL_QUIT:
				done = 1;
				break;
			}
		}
		keys = SDL_GetKeyState(NULL);

		if (keys[SDLK_ESCAPE])
		{
			done = 1;
		}

		if (!Render())
			break;

		SDL_GL_SwapBuffers();

		shellFrame++;
	}
	ReleaseGL();
	ReleaseApp();

	SDL_Quit();
	return 0;             /* ANSI C requires main to return int. */
}
示例#14
0
unsigned WINAPI BR_SearchObject::StartSearch (void* searchObject)
{
	BR_SearchObject* _this = (BR_SearchObject*)searchObject;
	JNL::open_socketlib();

	BR_Version versionL;
	LineParser lp(false);
	lp.parse(SWS_VERSION_STR);
	versionL.maj   = lp.gettoken_int(0);
	versionL.min   = lp.gettoken_int(1);
	versionL.rev   = lp.gettoken_int(2);
	versionL.build = lp.gettoken_int(3);

	// When searching by user request, lookup both official and beta
	bool searchO = true, searchB = true;
	if (_this->IsStartup())
		GetStartupSearchOptions(&searchO, &searchB, NULL);

	// Get official version and compare
	double runningReaVer = atof(GetAppVersion());

	BR_Version versionO, reaperO;
	int statusO = NO_CONNECTION;
	if (searchO && !_this->GetKillFlag())
	{
		JNL_HTTPGet web;
		web.addheader("User-Agent:SWS (Mozilla)");
		web.addheader("Accept:*/*");
		web.connect(SWS_URL_VERSION_H);
		time_t startTime = time(NULL);
		while (time(NULL) - startTime <= SEARCH_TIMEOUT && !_this->GetKillFlag())
		{
			_this->SetProgress((double)(time(NULL) - startTime) / (SEARCH_TIMEOUT*2));

			// Try to get version.h
			int run = web.run();
			if (run < 0 || web.get_status() < 0 || web.getreplycode() >= 400)
				break;
			if (run == 1 && web.getreplycode() == 200) //  get data only after the connection has closed
			{
				int size = web.bytes_available();
				if (char* buf = new (nothrow) char[size])
				{
					web.get_bytes(buf, size);
					char* token = strtok(buf, "\n");
					while (token != NULL)
					{
						if (sscanf(token, "#define SWS_VERSION %10d,%10d,%10d,%10d", &versionO.maj, &versionO.min, &versionO.rev, &versionO.build) > 0) {}
						else if (sscanf(token, "#define REA_VERSION %10d,%10d,%10d,%10d", &reaperO.maj, &reaperO.min, &reaperO.rev, &reaperO.build) > 0) break;
						token = strtok(NULL, "\n");
					}

					double compatibleReaVerO = (double)reaperO.maj + (double)reaperO.min*0.1 + (double)reaperO.rev*0.01 + (double)reaperO.build*0.001;
					if (runningReaVer >= compatibleReaVerO && _this->CompareVersion(versionO, versionL) == 1)
						statusO = OFFICIAL_AVAILABLE;
					else
						statusO = UP_TO_DATE;

					delete[] buf;
					break;
				}
			}
		}
	}

	// Get beta version and compare
	BR_Version versionB, reaperB;
	int statusB = NO_CONNECTION;
	if (searchB && !_this->GetKillFlag())
	{
		JNL_HTTPGet web;
		web.addheader("User-Agent:SWS (Mozilla)");
		web.addheader("Accept:*/*");
		web.connect(SWS_URL_BETA_VERSION_H);
		time_t startTime = time(NULL);
		while (time(NULL) - startTime <= SEARCH_TIMEOUT && !_this->GetKillFlag())
		{
			_this->SetProgress((double)(time(NULL) - startTime) / (SEARCH_TIMEOUT*2) + 0.5);

			// Try to get version.h
			int run = web.run();
			if (run < 0 || web.get_status() < 0 || web.getreplycode() >= 400)
				break;
			else if (run == 1 && web.getreplycode() == 200) //  get data only after the connection has closed
			{
				int size = web.bytes_available();
				if (char* buf = new (nothrow) char[size])
				{
					web.get_bytes(buf, size);
					char* token = strtok(buf, "\n");
					while (token != NULL)
					{
						if (sscanf(token, "#define SWS_VERSION %10d,%10d,%10d,%10d", &versionB.maj, &versionB.min, &versionB.rev, &versionB.build) > 0) {}
						else if (sscanf(token, "#define REA_VERSION %10d,%10d,%10d,%10d", &reaperB.maj, &reaperB.min, &reaperB.rev, &reaperB.build) > 0) break;
						token = strtok(NULL, "\n");
					}

					double compatibleReaVerB = (double)reaperB.maj + (double)reaperB.min*0.1 + (double)reaperB.rev*0.01 + (double)reaperB.build*0.001;
					if (runningReaVer >= compatibleReaVerB && _this->CompareVersion(versionB, versionL) == 1)
						statusB = BETA_AVAILABLE;
					else
						statusB = UP_TO_DATE;

					delete[] buf;
					break;
				}
			}
		}
	}

	_this->SetProgress(1);

	// Give some breathing space to hwndDlg (i.e. SNM startup action may load screenset that repositions Reaper...)
	if (_this->IsStartup() && !_this->GetKillFlag())
		Sleep(1500);

	// When both versions are available and are identical, ignore beta
	if (statusO == OFFICIAL_AVAILABLE && statusB == BETA_AVAILABLE)
		if (!_this->CompareVersion(versionO, versionB))
			statusB = UP_TO_DATE;

	int status;
	if      (statusO == NO_CONNECTION && statusB == NO_CONNECTION)       status = NO_CONNECTION;
	else if (statusO == OFFICIAL_AVAILABLE && statusB == BETA_AVAILABLE) status = BOTH_AVAILABLE;
	else if (statusO == OFFICIAL_AVAILABLE)                              status = OFFICIAL_AVAILABLE;
	else if (statusB == BETA_AVAILABLE)                                  status = BETA_AVAILABLE;
	else                                                                 status = UP_TO_DATE;

	_this->SetStatus(versionO, versionB, status);
	JNL::close_socketlib();
	return 0;
}
示例#15
0
//++ ------------------------------------------------------------------------------------
// Details:	Check the arguments given on the command line. The main purpose of this
//			function is to check for the presence of the --interpreter option. Having 
//			this option present tells *this manager to set the CMIDriver to do work. If 
//			not use the LLDB driver. The following are options that are only handled by
//			the CMIDriverMgr are: 
//				--help or -h
//				--interpreter
//				--version
//				--versionLong
//				--noLog
//				--executable 
//			The above arguments are not handled by any driver object except for --executable.
//			The options --interpreter and --executable in code act very similar. The
//			--executable is necessary to differentiate whither the MI Driver is being using
//			by a client i.e. Eclipse or from the command line. Eclipse issues the option
//			--interpreter and also passes additional arguments which can be interpreted as an
//			executable if called from the command line. Using --executable tells the MI 
//			Driver is being called the command line and that the executable argument is indeed
//			a specified executable an so actions commands to set up the executable for a 
//			debug session. Using --interpreter on the commnd line does not action additional
//			commands to initialise a debug session and so be able to launch the process.
// Type:	Method.
// Args:	argc		- (R)	An integer that contains the count of arguments that follow in 
//								argv. The argc parameter is always greater than or equal to 1.
//			argv		- (R)	An array of null-terminated strings representing command-line 
//								arguments entered by the user of the program. By convention, 
//								argv[0] is the command with which the program is invoked.
//			vwbExiting	- (W)	True = *this want to exit, Reasons: help, invalid arg(s),
//								version information only.
//								False = Continue to work, start debugger i.e. Command 
//								interpreter. 
// Return:	lldb::SBError - LLDB current error status.
// Throws:	None.
//--
bool CMIDriverMgr::ParseArgs( const int argc, const char * argv[], bool & vwbExiting )
{
	bool bOk = MIstatus::success;

	vwbExiting = false;

	// Print MI application path to the Log file
	const CMIUtilString appPath( CMIUtilString::Format( MIRSRC( IDS_MI_APP_FILEPATHNAME ), argv[ 0 ] ) );
	bOk = m_pLog->Write( appPath, CMICmnLog::eLogVerbosity_Log );
		
	// Print application arguments to the Log file
	const bool bHaveArgs( argc >= 2 );
	CMIUtilString strArgs( MIRSRC( IDS_MI_APP_ARGS ) );
	if( !bHaveArgs )
	{
		strArgs += MIRSRC( IDS_WORD_NONE );
		bOk = bOk && m_pLog->Write( strArgs, CMICmnLog::eLogVerbosity_Log );
	}
	else
	{
		for( MIint i = 1; i < argc; i++ ) 
		{ 
			strArgs += CMIUtilString::Format( "%d:'%s' ", i, argv[ i ] );
		}
		bOk = bOk && m_pLog->Write( strArgs, CMICmnLog::eLogVerbosity_Log );
	}
	
	// Look for the command line options		
	bool bHaveArgInterpret = false;
	bool bHaveArgVersion = false;
	bool bHaveArgVersionLong = false;
	bool bHaveArgNoLog = false;
	bool bHaveArgHelp = false;

	// Hardcode the use of the MI driver
#if MICONFIG_DEFAULT_TO_MI_DRIVER
	bHaveArgInterpret = true;
#endif // MICONFIG_DEFAULT_TO_MI_DRIVER

	if( bHaveArgs )
	{
		// CODETAG_MIDRIVE_CMD_LINE_ARG_HANDLING
		for( MIint i = 1; i < argc; i++ ) 
		{ 
			// *** Add args to help in GetHelpOnCmdLineArgOptions() ***
			const CMIUtilString strArg( argv[ i ] );

			// Argument "--executable" is also check for in CMIDriver::ParseArgs()
			if( (0 == strArg.compare( "--interpreter" )) ||	// Given by the client such as Eclipse
				(0 == strArg.compare( "--executable" )) )	// Used to specify that there is executable argument also on the command line 
			{												// See fn description.
				   bHaveArgInterpret = true;
			}
			if( 0 == strArg.compare( "--version" ) ) 
			{
				   bHaveArgVersion = true;
			}
			if( 0 == strArg.compare( "--versionLong" ) ) 
			{
				   bHaveArgVersionLong = true;
			}
			if( 0 == strArg.compare( "--noLog" ) ) 
			{
				   bHaveArgNoLog = true;
			}
			if( (0 == strArg.compare( "--help" )) || (0 == strArg.compare( "-h" )) )
			{
				bHaveArgHelp = true;
			}
		}
	}

	if( bHaveArgNoLog )
	{
		CMICmnLog::Instance().SetEnabled( false );
	}
	
	// Todo: Remove this output when MI is finished. It is temporary to persuade Ecllipse plugin to work.
	//		 Eclipse reads this literally and will not work unless it gets this exact version text.
	// Handle --version option (ignore the --interpreter option if present)
	if( bHaveArgVersion )
	{
		vwbExiting = true;
		bOk = bOk && CMICmnStreamStdout::Instance().WriteMIResponse( MIRSRC( IDE_MI_VERSION_GDB ) );
		return bOk;
	}

	// Todo: Make this the --version when the the above --version version is removed
	// Handle --versionlong option (ignore the --interpreter option if present)
	if( bHaveArgVersionLong )
	{
		vwbExiting = true;
		bOk = bOk && CMICmnStreamStdout::Instance().WriteMIResponse( GetAppVersion() );
		return bOk;
	}

	// Both '--help' and '--intepreter' means give help for MI only. Without 
	// '--interpreter' help the LLDB driver is working and so help is for that.
	if( bHaveArgHelp && bHaveArgInterpret )
	{
		vwbExiting = true;
		bOk = bOk && CMICmnStreamStdout::Instance().WriteMIResponse( GetHelpOnCmdLineArgOptions() );
		return bOk;
	}
 
	// This makes the assumption that there is at least one MI compatible
	// driver registered and one LLDB driver registerd and the CMIDriver 
	// is the first one found.
	// ToDo: Implement a better solution that handle any order, any number
	// of drivers. Or this 'feature' may be removed if deemed not required.
	IDriver * pLldbDriver = GetFirstNonMIDriver();
	IDriver * pMi2Driver = GetFirstMIDriver();
	if( bHaveArgInterpret && (pMi2Driver != nullptr) )
		bOk = bOk && SetUseThisDriverToDoWork( *pMi2Driver );
	else if( pLldbDriver != nullptr )
		bOk = bOk && SetUseThisDriverToDoWork( *pLldbDriver );
	else
	{
		if( bOk )
		{
			vwbExiting = true;
			const CMIUtilString msg( MIRSRC( IDS_DRIVER_ERR_NON_REGISTERED ) );
			bOk = bOk && CMICmnStreamStdout::Instance().WriteMIResponse( msg );
		}
	}
					
	return bOk;
}
示例#16
0
void SettingsDlg::OnButtonCheckForUpdates(wxCommandEvent& WXUNUSED(event)) {
	CheckForUpdates(m_settings, GetAppVersion(), true);
}