Example #1
0
void ZWaveBase::Do_Work()
{
#ifdef WIN32
	//prevent OpenZWave locale from taking over
	_configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
#endif
	while (!m_stoprequested)
	{
		sleep_milliseconds(500);
		if (m_stoprequested)
			return;
		if (m_bInitState)
		{
			if (GetInitialDevices())
			{
				m_bInitState=false;
				sOnConnected(this);
			}
		}
		else
		{
			GetUpdates();
			if (m_bControllerCommandInProgress==true)
			{
				time_t atime=mytime(NULL);
				time_t tdiff=atime-m_ControllerCommandStartTime;
				if (tdiff>=CONTROLLER_COMMAND_TIMEOUT)
				{
					_log.Log(LOG_ERROR,"ZWave: Stopping Controller command (Timeout!)");
					CancelControllerCommand();
				}
			}
		}
	}
}
Example #2
0
// Initialization of the dialog
HWND InitVpnWebDlg(VPNWEBDLG_INIT *init)
{
	HWND hWnd;
	// Validate arguments
	if (init == NULL)
	{
		return NULL;
	}

	_configthreadlocale(_DISABLE_PER_THREAD_LOCALE);
	setlocale(LC_ALL, "");

	ZeroMemory(&data, sizeof(data));
	CopyMemory(&data, init, sizeof(data));

	LoadTables(data.LanguageId);

	hWnd = CreateDialog(hDllInstance, MAKEINTRESOURCE(IDD_VPNWEBDLG),
		data.hControlWnd, VpnWebDlgProc);

	data.hWnd = hWnd;

	ShowWindow(hWnd, SW_SHOW);

	return hWnd;
}
Example #3
0
static void __config_locale_override(void)
{
#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) \
  && ! defined(__MINGW32__)

  _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
  setlocale(LC_NUMERIC, "C");

#elif defined(__APPLE__)

  locale_t loc = newlocale(LC_NUMERIC_MASK, "C", NULL);
  uselocale(loc);

#elif ((defined HAVE_NEWLOCALE) && (defined HAVE_USELOCALE))

  locale_t loc = newlocale(LC_NUMERIC, "C", NULL);
  uselocale(loc);

#elif defined(_EE)
  /* do nothing */
#else

#warning "No way to modify calling thread's locale!"

#endif
}
Example #4
0
static void __config_locale_override(void)
{
#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) \
  && ! defined(__MINGW32__)

  _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
  setlocale(LC_NUMERIC, "C");

#elif defined(__APPLE__)

  locale_t loc = newlocale(LC_NUMERIC_MASK, "C", NULL);
  uselocale(loc);

#elif ((defined HAVE_NEWLOCALE) && (defined HAVE_USELOCALE))

  locale_t loc = newlocale(LC_NUMERIC, "C", NULL);
  uselocale(loc);

#else

/* locale overriding is pretty pointless (Hercules doesn't make use of the area that uses locale functionality),
 * but I'm actually removing it because it floods the buildbot with warnings  */
//#warning "No way to modify calling thread's locale!"

#endif
}
Example #5
0
ThreadSafeLocaleHandler::ThreadSafeLocaleHandler() {
#define FILL_IN_CATEGORY_LOCALE_MAP(category) \
  {category, category ## _MASK, #category, ""}
  m_category_locale_map = {
      FILL_IN_CATEGORY_LOCALE_MAP(LC_CTYPE),
      FILL_IN_CATEGORY_LOCALE_MAP(LC_NUMERIC),
      FILL_IN_CATEGORY_LOCALE_MAP(LC_TIME),
      FILL_IN_CATEGORY_LOCALE_MAP(LC_COLLATE),
      FILL_IN_CATEGORY_LOCALE_MAP(LC_MONETARY),
      #ifndef _MSC_VER
      FILL_IN_CATEGORY_LOCALE_MAP(LC_MESSAGES),
      #endif
      FILL_IN_CATEGORY_LOCALE_MAP(LC_ALL),
      #if !defined(__APPLE__) && !defined(_MSC_VER)
      FILL_IN_CATEGORY_LOCALE_MAP(LC_PAPER),
      FILL_IN_CATEGORY_LOCALE_MAP(LC_NAME),
      FILL_IN_CATEGORY_LOCALE_MAP(LC_ADDRESS),
      FILL_IN_CATEGORY_LOCALE_MAP(LC_TELEPHONE),
      FILL_IN_CATEGORY_LOCALE_MAP(LC_MEASUREMENT),
      FILL_IN_CATEGORY_LOCALE_MAP(LC_IDENTIFICATION),
      #endif
  };
#undef FILL_IN_CATEGORY_LOCALE_MAP

#ifdef _MSC_VER
  _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
  ::setlocale(LC_ALL, "C");
#else
  m_locale = s_null_locale;
#endif

  reset();
}
Example #6
0
void CScriptThread::DoExecute()
{
#ifdef _WIN32
	if ( _configthreadlocale(_ENABLE_PER_THREAD_LOCALE) == -1 )
		GenErr("_configthreadlocale failed.");
#endif

	SetAltSigStackEnabled(true);

	CBaseScriptApp::InitCfgTableTlsValue();
	CBaseScriptApp::InitStrIndexTlsValue();
	CBaseScriptApp::InitStr64IndexTlsValue();

#ifdef _WIN32
	_set_se_translator(TransESHFun);
#endif

	AddWatchCpuThreadID("ScriptThread",GetCurTID());
	HTHREADID id = GetCurTID();
	m_pScript->SetRunningThread(id);

#ifndef _WIN32
	SetLogCallBackFunc(CScriptThread::OnErrLogCallBack);
#endif

	RegistThreadCoreServer(*m_pScript);

	TLS_SetValue(m_pThreadMgr->m_tlsThreadKey, this);

	CPkgFile::InitTLSData();

	stringstream strm;

	strm<<"engine_require(\"server/thread/ThreadCoreServer\")\n"
		"ThreadCoreServer.Run(\""<<m_strRunFile.c_str()<<"\")";

	string sError = m_pScript->RunString(strm.str().c_str(),NULL);
	if (!sError.empty())
	{
		LogErr(sError.c_str());
	}

	CPkgFile::UnitTLSData();

	TLS_SetValue(m_pThreadMgr->m_tlsThreadKey, NULL);

	CBaseScriptApp::UnInitCfgTableTlsValue();
	CBaseScriptApp::UnInitStrIndexTlsValue();
	CBaseScriptApp::UnInitStr64IndexTlsValue();

#ifndef _WIN32	
	SetLogCallBackFunc(NULL);
#endif

	m_pScript->DetachRunningThread();

	SetAltSigStackEnabled(false);

}
Example #7
0
DWORD WINAPI Thread::ThreadEntrypoint(LPVOID pParam) {
	Thread* pThis = reinterpret_cast<Thread*>(pParam);
	
	if(Thread::static_bInstallWin32ExceptionHandler_)
		win32_exception::install_handler();

	_configthreadlocale(_DISABLE_PER_THREAD_LOCALE);

	pThis->Run();

	return 0;
}
Example #8
0
  LocaleSwitcherImpl() {
    if (!recurseLocale(CurrentState)) {
#ifdef RDK_THREADSAFE_SSS
      _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
      ::setlocale(LC_ALL, "C"); // thread safe on windows
#else
      std::setlocale(LC_ALL, "C");
#endif // RDK_THREADSAFE_SSS
      recurseLocale(SwitchLocale);
      switched = true;
    }
  }
Example #9
0
CLocalizer::CLocalizer()
{
#ifdef _MSC_VER
    // Avoid multithreading issues caused by setlocale
    _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
#endif
    char* p = std::setlocale(LC_NUMERIC, nullptr);
    if(nullptr != p) {
        saved_locale = p;
    }
    std::setlocale(LC_NUMERIC, "C");
}
Example #10
0
static void __config_locale_restore(void)
{
#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) \
  && ! defined(__MINGW32__)

    _configthreadlocale(_DISABLE_PER_THREAD_LOCALE);

#elif ((defined HAVE_USELOCALE) && (defined HAVE_FREELOCALE))

  locale_t loc = uselocale(LC_GLOBAL_LOCALE);
  freelocale(loc);

#else

#warning "No way to modify calling thread's locale!"

#endif
}
Example #11
0
static void __config_locale_restore(void)
{
#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) \
  && ! defined(__MINGW32__)

    _configthreadlocale(_DISABLE_PER_THREAD_LOCALE);

#elif ((defined HAVE_USELOCALE) && (defined HAVE_FREELOCALE))

  locale_t loc = uselocale(LC_GLOBAL_LOCALE);
  freelocale(loc);

#else

/* locale overriding is pretty pointless (Hercules doesn't make use of the area that uses locale functionality),
 * but I'm actually removing it because it floods the buildbot with warnings  */
//#warning "No way to modify calling thread's locale!"

#endif
}
Example #12
0
SAPI_API void sapi_startup(sapi_module_struct *sf)
{
	sf->ini_entries = NULL;
	sapi_module = *sf;

#ifdef ZTS
	ts_allocate_id(&sapi_globals_id, sizeof(sapi_globals_struct), (ts_allocate_ctor) sapi_globals_ctor, (ts_allocate_dtor) sapi_globals_dtor);
# ifdef PHP_WIN32
	_configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
# endif
#else
	sapi_globals_ctor(&sapi_globals);
#endif

#ifdef PHP_WIN32
	tsrm_win32_startup();
#endif

	reentrancy_startup();
}
void *RPCThread::Entry() {
    int retval = 0;
    CRPCFinishedEvent RPC_done_event( wxEVT_RPC_FINISHED );
    ASYNC_RPC_REQUEST *current_request;
    double startTime = 0;
    wxMutexError mutexErr = wxMUTEX_NO_ERROR;
    wxCondError condErr = wxCOND_NO_ERROR;

#ifndef NO_PER_THREAD_LOCALE
#ifdef __WXMSW__
    // On Windows, set all locales for this thread on a per-thread basis
    _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
    setlocale(LC_ALL, "C");
#else
    // We initialize RPC_Thread_Locale to fix a compiler warning
    locale_t RPC_Thread_Locale = LC_GLOBAL_LOCALE;
#if defined(__APPLE__) && (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4)
    if (uselocale)    // uselocale() is not available in Mac OS 10.3.9
#endif
    {
        // On Mac / Unix / Linux, set "C" locale for this thread only
        RPC_Thread_Locale = newlocale(LC_ALL_MASK, "C", NULL);
        uselocale(RPC_Thread_Locale);
    }
#endif      // ifndef __WXMSW__
#endif      // ifndef NO_PER_THREAD_LOCALE
   
    m_pRPC_Thread_Mutex->Lock();
    m_pDoc->m_bRPCThreadIsReady = true;
    while(true) {
        // Wait for main thread to wake us
        // This does the following:
        // (1) Unlocks the Mutex and puts the RPC thread to sleep as an atomic operation.
        // (2) On Signal from main thread: locks Mutex again and wakes the RPC thread.
        condErr = m_pRPC_Thread_Condition->Wait();
        wxASSERT(condErr == wxCOND_NO_ERROR);
        
        if (m_pDoc->m_bShutDownRPCThread) {
#if !defined(NO_PER_THREAD_LOCALE) && !defined(__WXMSW__)
#if defined(__APPLE__) && (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4)
        if (uselocale)    // uselocale() is not available in Mac OS 10.3.9
#endif
        {
            uselocale(LC_GLOBAL_LOCALE);
            freelocale(RPC_Thread_Locale);
        }
#endif
            m_pRPC_Thread_Mutex->Unlock();  // Just for safety - not really needed
            // Tell CMainDocument that thread has gracefully ended 
            // We do this here because OnExit() is not called on Windows
            m_pDoc->m_RPCThread = NULL;
            return 0;
        }
        
        current_request = m_pDoc->GetCurrentRPCRequest();

        if (!current_request->isActive)  continue;       // Should never happen
        
        if (current_request->RPCExecutionTime) {
            startTime = dtime();
        }
        retval = ProcessRPCRequest();
        if (current_request->RPCExecutionTime) {
            *(current_request->RPCExecutionTime) = dtime() - startTime;
        }
        
        current_request->retval = retval;

        mutexErr = m_pRPC_Request_Mutex->Lock();
        wxASSERT(mutexErr == wxMUTEX_NO_ERROR);

        current_request->isActive = false;
        wxPostEvent( wxTheApp, RPC_done_event );

        // Signal() is ignored / discarded unless the main thread is 
        // currently blocked by m_pRPC_Request_Condition->Wait[Timeout]()
        m_pRPC_Request_Condition->Signal();
        
        mutexErr = m_pRPC_Request_Mutex->Unlock();
        wxASSERT(mutexErr == wxMUTEX_NO_ERROR);
    }

    return NULL;
}
Example #14
0
/* Attaches a signal handler for Ctrl+C or Ctrl+Break signals
 * Returns 1 if successful or -1 on error
 */
int evtxtools_signal_attach(
     void (*signal_handler)( evtxtools_signal_t ),
     libcerror_error_t **error )
{
	static char *function = "evtxtools_signal_attach";

	if( signal_handler == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid signal handler.",
		 function );

		return( -1 );
	}
	evtxtools_signal_signal_handler = signal_handler;

	if( SetConsoleCtrlHandler(
	     evtxtools_signal_handler,
	     TRUE ) == 0 )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_SET_FAILED,
		 "%s: unable to attach signal handler.",
		 function );

		return( -1 );
	}
	if( SetConsoleCtrlHandler(
	     NULL,
	     FALSE ) == 0 )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_SET_FAILED,
		 "%s: unable to attach break signal.",
		 function );

		return( -1 );
	}
#if defined( _MSC_VER )
	evtxtools_signal_initialize_memory_debug();
#endif

	SetErrorMode(
	 SEM_FAILCRITICALERRORS );

#if defined( LOCALE_SUPPORT )
	/* Allow subsequent threads to have their own locale.
	 * If the application is single threaded this call has
	 * no practical effect.
	 */
	_configthreadlocale(
	  _ENABLE_PER_THREAD_LOCALE );

	/* Set the current thread locale to the user default
	 * ANSI code page.
	 */
	setlocale(
	 LC_ALL,
	 "" );

	/* Set the the code page used by multibyte functions
	 * to use the same code page as the previous call to setlocale.
	 */
	_setmbcp(
	  _MB_CP_LOCALE );

#endif /* defined( LOCALE_SUPPORT ) */

	return( 1 );
}
Example #15
0
bool CBOINCGUIApp::OnInit() {
    // Initialize globals
#ifdef SANDBOX
    g_use_sandbox = true;
#else
    g_use_sandbox = false;
#endif

    s_bSkipExitConfirmation = false;
    m_bFilterEvents = false;
    m_bAboutDialogIsOpen = false;

    // Initialize class variables
    m_pLocale = NULL;
    m_pSkinManager = NULL;
    m_pFrame = NULL;
    m_pDocument = NULL;
    m_pTaskBarIcon = NULL;
    m_pEventLog = NULL;
#ifdef __WXMAC__
    m_pMacDockIcon = NULL;
#endif
    m_strBOINCMGRExecutableName = wxEmptyString;
    m_strBOINCMGRRootDirectory = wxEmptyString;
    m_strBOINCMGRDataDirectory = wxEmptyString;
    m_strHostNameArg = wxEmptyString;
    m_strPasswordArg = wxEmptyString;
    m_iRPCPortArg = GUI_RPC_PORT;
    m_strBOINCArguments = wxEmptyString;
    m_bGUIVisible = true;
    m_bDebugSkins = false;
    m_bMultipleInstancesOK = false;
    m_bBOINCMGRAutoStarted = false;
    m_iBOINCMGRDisableAutoStart = 0;
    m_iShutdownCoreClient = 0;
    m_iDisplayExitDialog = 1;
    m_iGUISelected = BOINC_SIMPLEGUI;
    m_bSafeMessageBoxDisplayed = 0;
#ifdef __WXMSW__
    m_hClientLibraryDll = NULL;
#endif

    // Initialize local variables
    int      iErrorCode = 0;
    int      iSelectedLanguage = 0;
    bool     bOpenEventLog = false;
    wxString strDesiredSkinName = wxEmptyString;
    wxString strDialogMessage = wxEmptyString;
    bool     success = false;

    // Configure wxWidgets platform specific code
#ifdef __WXMSW__
    wxSystemOptions::SetOption(wxT("msw.staticbox.optimized-paint"), 0);
#endif
#ifdef __WXMAC__
    // In wxMac-2.8.7, default wxListCtrl::RefreshItem() does not work
    // so use traditional generic implementation.
    // This has been fixed in wxMac-2.8.8, but the Mac native implementation:
    //  - takes 3 times the CPU time as the Mac generic version.
    //  - seems to always redraw entire control even if asked to refresh only one row.
    //  - causes major flicker of progress bars, (probably due to full redraws.)
    wxSystemOptions::SetOption(wxT("mac.listctrl.always_use_generic"), 1);

    AEInstallEventHandler( kCoreEventClass, kAEQuitApplication, NewAEEventHandlerUPP((AEEventHandlerProcPtr)QuitAppleEventHandler), 0, false );

    // Cache the current process serial number
    GetCurrentProcess(&m_psnCurrentProcess);
#endif


    // Commandline parsing is done in wxApp::OnInit()
    if (!wxApp::OnInit()) {
        return false;
    }

    if (g_use_sandbox) {
        wxCHANGE_UMASK(2);  // Set file creation mask to be writable by both user and group
                            // Our umask will be inherited by all our child processes
    }

    // Setup application and company information
    SetAppName(wxT("BOINC Manager"));
    SetVendorName(wxT("Space Sciences Laboratory, U.C. Berkeley"));


    // Initialize the configuration storage module
    m_pConfig = new wxConfig(GetAppName());
    wxConfigBase::Set(m_pConfig);
    wxASSERT(m_pConfig);


    // Restore Application State
    m_pConfig->SetPath(wxT("/"));
    m_pConfig->Read(wxT("AutomaticallyShutdownClient"), &m_iShutdownCoreClient, 0L);
    m_pConfig->Read(wxT("DisplayShutdownClientDialog"), &m_iDisplayExitDialog, 1L);
    m_pConfig->Read(wxT("DisableAutoStart"), &m_iBOINCMGRDisableAutoStart, 0L);
    m_pConfig->Read(wxT("Language"), &iSelectedLanguage, 0L);
    m_pConfig->Read(wxT("GUISelection"), &m_iGUISelected, BOINC_SIMPLEGUI);
    m_pConfig->Read(wxT("EventLogOpen"), &bOpenEventLog);


    // Should we abort the BOINC Manager startup process?
    if (m_bBOINCMGRAutoStarted && m_iBOINCMGRDisableAutoStart) {
        return false;
    }

    // Detect where BOINC Manager executable name.
    DetectExecutableName();

    // Detect where BOINC Manager was installed too.
    DetectRootDirectory();

    // Detect where the BOINC Data files are.
    DetectDataDirectory();


    // Switch the current directory to the BOINC Data directory
    if (!GetDataDirectory().IsEmpty()) {
    	success = wxSetWorkingDirectory(GetDataDirectory());
        if (!success) {
            if (!g_use_sandbox) {
                if (!wxDirExists(GetDataDirectory())) {
                    success = wxMkdir(GetDataDirectory(), 0777);    // Does nothing if dir exists
                }
            }
        }
    }

    if (!success) iErrorCode = -1016;

    // Initialize the BOINC Diagnostics Framework
    int dwDiagnosticsFlags =
        BOINC_DIAG_DUMPCALLSTACKENABLED | 
        BOINC_DIAG_HEAPCHECKENABLED |
        BOINC_DIAG_MEMORYLEAKCHECKENABLED |
#if defined(__WXMSW__) || defined(__WXMAC__)
        BOINC_DIAG_REDIRECTSTDERR |
        BOINC_DIAG_REDIRECTSTDOUT |
#endif
        BOINC_DIAG_TRACETOSTDOUT;

    diagnostics_init(
        dwDiagnosticsFlags,
        "stdoutgui",
        "stderrgui"
    );


    // Enable Logging and Trace Masks
    m_pLog = new wxLogBOINC();
    wxLog::SetActiveTarget(m_pLog);

    m_pLog->AddTraceMask(wxT("Function Start/End"));
    m_pLog->AddTraceMask(wxT("Function Status"));


    // Initialize the internationalization module
#ifdef __WXMSW__
    // On Windows, set all locales for this thread on a per-thread basis
    _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
#endif
    m_pLocale = new wxLocale();
    wxASSERT(m_pLocale);

    // Look for the localization files by absolute and relative locations.
    //   preference given to the absolute location.
    m_pLocale->Init(iSelectedLanguage);
    if (!m_strBOINCMGRRootDirectory.IsEmpty()) {
        m_pLocale->AddCatalogLookupPathPrefix(
            wxString(m_strBOINCMGRRootDirectory + wxT("locale"))
        );
    }
    m_pLocale->AddCatalogLookupPathPrefix(wxT("locale"));
    m_pLocale->AddCatalog(wxT("BOINC-Manager"));
    m_pLocale->AddCatalog(wxT("BOINC-Client"));
    m_pLocale->AddCatalog(wxT("BOINC-Web"));

    InitSupportedLanguages();

	language = m_pLocale->GetCanonicalName();

    // Note: JAWS for Windows will only speak the context-sensitive
    // help if you use this help provider:
    wxHelpProvider::Set(new wxHelpControllerHelpProvider());

    // Enable known image types
    wxInitAllImageHandlers();

    // Initialize the skin manager
    m_pSkinManager = new CSkinManager(m_bDebugSkins);
    wxASSERT(m_pSkinManager);


    // Load desired manager skin
    m_pConfig->Read(wxT("Skin"), &strDesiredSkinName, m_pSkinManager->GetDefaultSkinName());
    m_pSkinManager->ReloadSkin(strDesiredSkinName);


#ifdef SANDBOX
    // Make sure owners, groups and permissions are correct for the current setting of g_use_sandbox
    char path_to_error[MAXPATHLEN];
    path_to_error[0] = '\0';
    
    if (!iErrorCode) {
#if (defined(__WXMAC__) && defined(_DEBUG))     // TODO: implement this for other platforms
        // GDB can't attach to applications which are running as a different user   
        //  or group, so fix up data with current user and group during debugging
        if (check_security(g_use_sandbox, true, NULL, 0)) {
            CreateBOINCUsersAndGroups();
            SetBOINCDataOwnersGroupsAndPermissions();
            SetBOINCAppOwnersGroupsAndPermissions(NULL);
        }
#endif
        iErrorCode = check_security(
            g_use_sandbox, true, path_to_error, sizeof(path_to_error)
        );
    }

    if (iErrorCode) {

        ShowApplication(true);

        if (iErrorCode == -1099) {
            strDialogMessage.Printf(
                _("You currently are not authorized to manage the client.\n\nTo run %s as this user, please:\n  - reinstall %s answering \"Yes\" to the question about\n     non-administrative users\n or\n  - contact your administrator to add you to the 'boinc_master'\n     user group."),
                m_pSkinManager->GetAdvanced()->GetApplicationShortName().c_str(),
                m_pSkinManager->GetAdvanced()->GetApplicationShortName().c_str()
            );
        } else {
            strDialogMessage.Printf(
                _("%s ownership or permissions are not set properly; please reinstall %s.\n(Error code %d"),
                m_pSkinManager->GetAdvanced()->GetApplicationShortName().c_str(),
                m_pSkinManager->GetAdvanced()->GetApplicationShortName().c_str(),
                iErrorCode
            );
            if (path_to_error[0]) {
                strDialogMessage += _(" at ");
                strDialogMessage += wxString::FromUTF8(path_to_error);
            }
            strDialogMessage += _(")");
            
            fprintf(stderr, "%s\n", (const char*)strDialogMessage.utf8_str());
        }

        wxMessageDialog* pDlg = new wxMessageDialog(
                                    NULL, 
                                    strDialogMessage, 
                                    m_pSkinManager->GetAdvanced()->GetApplicationName(), 
                                    wxOK
                                    );

        pDlg->ShowModal();
        if (pDlg)
            pDlg->Destroy();

        return false;
    }
#endif      // SANDBOX


#ifdef __WXMSW__
    // Perform any last minute checks that should keep the manager
    // from starting up.
    wxString strRebootPendingFile = 
        GetRootDirectory() + wxFileName::GetPathSeparator() + wxT("RebootPending.txt");
    
    if (wxFile::Exists(strRebootPendingFile)) {
        wxMessageDialog dialog(
            NULL,
            _("A reboot is required in order for BOINC to run properly.\nPlease reboot your computer and try again."),
            _("BOINC Manager"),
            wxOK|wxICON_ERROR
        );

        dialog.ShowModal();
        return false;
    }
#endif

    // Detect if BOINC Manager is already running, if so, bring it into the
    // foreground and then exit.
    if (!m_bMultipleInstancesOK) {
        if (DetectDuplicateInstance()) {
            return false;
        }
    }

    // Initialize the main document
    m_pDocument = new CMainDocument();
    wxASSERT(m_pDocument);

    m_pDocument->OnInit();


    // Is there a condition in which the Simple GUI should not be used?
    if (BOINC_SIMPLEGUI == m_iGUISelected) {
        // Screen too small?
        if (wxGetDisplaySize().GetHeight() < 600) {
            m_iGUISelected = BOINC_ADVANCEDGUI;
        }
    }


    // Initialize the task bar icon
	m_pTaskBarIcon = new CTaskBarIcon(
        m_pSkinManager->GetAdvanced()->GetApplicationName(), 
        m_pSkinManager->GetAdvanced()->GetApplicationIcon(),
        m_pSkinManager->GetAdvanced()->GetApplicationDisconnectedIcon(),
        m_pSkinManager->GetAdvanced()->GetApplicationSnoozeIcon()
#ifdef __WXMAC__
        , wxTBI_CUSTOM_STATUSITEM
#endif
    );
#ifdef __WXMAC__
    m_pMacDockIcon = new CTaskBarIcon(
        m_pSkinManager->GetAdvanced()->GetApplicationName(), 
        m_pSkinManager->GetAdvanced()->GetApplicationIcon(),
        m_pSkinManager->GetAdvanced()->GetApplicationDisconnectedIcon(),
        m_pSkinManager->GetAdvanced()->GetApplicationSnoozeIcon()
        , wxTBI_DOCK
    );
    wxASSERT(m_pMacDockIcon);
#endif
    wxASSERT(m_pTaskBarIcon);

    // Startup the System Idle Detection code
    IdleTrackerAttach();
    
#ifdef __WXMAC__
    ProcessSerialNumber psn;
    ProcessInfoRec pInfo;
    OSStatus err;
    
    memset(&pInfo, 0, sizeof(pInfo));
    pInfo.processInfoLength = sizeof( ProcessInfoRec );
    err = GetProcessInformation(&m_psnCurrentProcess, &pInfo);
    if (!err) {
        psn = pInfo.processLauncher;
        memset(&pInfo, 0, sizeof(pInfo));
        pInfo.processInfoLength = sizeof( ProcessInfoRec );
        err = GetProcessInformation(&psn, &pInfo);
    }
    // Don't open main window if we were started automatically at login
    if (pInfo.processSignature == 'lgnw') {  // Login Window app
        m_bGUIVisible = false;

        // If the system was just started, we usually get a "Connection 
        // failed" error if we try to connect too soon, so delay a bit.
        sleep(10);
    }
#endif

    // Show the UI
    SetActiveGUI(m_iGUISelected, m_bGUIVisible);

    if (!m_bGUIVisible) {
#ifdef __WXMAC__
        // We don't call Hide() or Show(false) for the main frame
        // under wxCocoa 2.9.5 because it bounces the Dock icon
        // (as in notification.)  We work around this by moving
        // the main window/frame off screen here.
        // The position will be restored in one of these methods:
        // CBOINCGUIApp::OnActivateApp(), CSimpleFrame::SaveState()
        // or CAdvancedFrame::SaveWindowDimensions().
        if (m_pFrame) {
            m_pFrame->MoveFrameOffScreen();
            m_pFrame->Show();
        }
#endif
        ShowApplication(false);
	}

    if (bOpenEventLog) {
        DisplayEventLog(m_bGUIVisible);
        if (m_bGUIVisible && m_pFrame) {
            m_pFrame->Raise();
        }
    }
    
    return true;
}
Example #16
0
BOOL CFdmApp::InitInstance()
{
	g_crashReporter.reset (new vmsAppCrashReporter (
		g_appVersion.getVersion ()->m_tstrProductName,
		L"",
		g_appVersion.getVersion ()->m_tstrFileVersion,
		L"freedownloadmanager.org", L"/dump.php"));

	bool bContinue = true;
	if (g_crashReporter->CheckIfSubmitDumpIsRequestedByCommandLine (bContinue))
	{
		if (!bContinue)
			return FALSE;
	}

	g_crashReporter->InitializeCrashCatcher ();

	AfxEnableControlContainer ();

	{
		_configthreadlocale (_DISABLE_PER_THREAD_LOCALE);
		tstringstream tss;
		tss << _T (".") << GetACP ();
		_tsetlocale(LC_ALL, tss.str ().c_str ());
		_configthreadlocale (_ENABLE_PER_THREAD_LOCALE);
	}

	
	SetRegistryKey (IDS_COMPANY);

	CheckRegistry ();

	fsIECatchMgr::CleanIEPluginKey ();

	
	CString strPath = GetProfileString (_T(""), _T("Path"), _T(""));
	BOOL bNeedLocalRegister = FALSE;
	if (strPath == _T(""))
	{
		CRegKey key;
		if (ERROR_SUCCESS == key.Open (HKEY_CURRENT_USER, _T("Software\\FreeDownloadManager.ORG\\Free Download Manager"), KEY_WRITE))
			vmsSHCopyKey (HKEY_LOCAL_MACHINE, _T("Software\\FreeDownloadManager.ORG\\Free Download Manager"), key);
		strPath = GetProfileString (_T(""), _T("Path"), _T(""));
		bNeedLocalRegister = strPath != "";
	}

	if (GetFileAttributes (strPath + _T("\\fdm.exe")) == DWORD (-1))
	{
		strPath = _T("");
		bNeedLocalRegister = false;
	}

	
	
	if (strPath == _T("") || FALSE == SetCurrentDirectory (strPath))
		_dwAppState |= APPSTATE_PORTABLE_MODE;

	TCHAR tszExeDir [MY_MAX_PATH], tszExeFile [MY_MAX_PATH];
	GetModuleFileName (NULL, tszExeFile, sizeof (tszExeFile));
	fsGetPath (tszExeFile, tszExeDir);

	if (IS_PORTABLE_MODE)
	{
		strPath = tszExeDir;
		SetCurrentDirectory (strPath);
	}

	m_strAppPath = strPath;
	if (m_strAppPath.IsEmpty () == FALSE)
	{
		if (m_strAppPath [m_strAppPath.GetLength ()-1] != '\\' &&
				m_strAppPath [m_strAppPath.GetLength ()-1] != '/')
			m_strAppPath += '\\';
	}

	if (IS_PORTABLE_MODE == false)
	{
		CString strDataFldr = tszExeDir; strDataFldr += _T("Data");
		
		
		
		if (m_strAppPath.CompareNoCase (tszExeDir) &&
			 DWORD (-1) != GetFileAttributes (strDataFldr))
		{
			
			_dwAppState |= APPSTATE_PORTABLE_MODE;
			_dwAppState |= APPSTATE_PORTABLE_MODE_NOREG;
			m_strAppPath = tszExeDir;
		}
	}

	if (IS_PORTABLE_MODE)
	{
		
		vmsAppSettingsStore* pStgs = _App.get_SettingsStore ();
		CString strStgsFile = m_strAppPath + "Data\\settings.dat";
		fsBuildPathToFile (strStgsFile);
		pStgs->LoadSettingsFromFile (strStgsFile);
		_App.ApplySettingsToMutexes ();
	}

	BOOL bNoLng = FALSE;

	if (FALSE == InitLanguage ())
		bNoLng = TRUE;

	if (_tcscmp (m_lpCmdLine, _T("-suis")) == 0 || 
			_tcscmp (m_lpCmdLine, _T("-euis")) == 0 ||
			_tcscmp (m_lpCmdLine, _T("-duis")) == 0)
	{
		IntegrationSettings ();
		return FALSE;
	}

	if (IS_PORTABLE_MODE)
	{
		
		
		
		TCHAR szTmpFile [MY_MAX_PATH];
		CString str = m_strAppPath; str += _T("Data");
		CreateDirectory (str, NULL);
		if (0 == GetTempFileName (str, _T("fdm"), 0, szTmpFile))
			MessageBox (NULL, LS (L_NOWRITEACCESSTODATAFOLDER), vmsFdmAppMgr::getAppName (), MB_ICONWARNING);
		else
			DeleteFile (szTmpFile);
	}

	_SkinMgr.Initialize ();

	_IECatchMgr.ReadSettings ();
	_NOMgr.Initialize ();
	_IECMM.ReadState ();

	
	HRESULT hRes = OleInitialize (NULL);
	
	if (FAILED(hRes))
		return FALSE;
	
	m_bCOMInited = TRUE;

	const tstring currentVersion = vmsFdmAppMgr::getVersion ()->m_fileVersion.ToString ();
	bool currentVersionFirstRun = currentVersion != _App.RecentVersionRun ();
	if (currentVersionFirstRun)
		_App.RecentVersionRun (currentVersion);

	vmsAppGlobalObjects::Create2 (currentVersionFirstRun);

	fsFDMCmdLineParser cmdline;

	cmdline.Parse (fsFDMCmdLineParser::Elevated);

	if (cmdline.isRunAsElevatedTasksProcessor ())
	{
		RunAsElevatedTasksProcessor (cmdline);
		return FALSE;
	}

	if (cmdline.isNeedExit ())
		return FALSE;

	m_bForceSilentSpecified = cmdline.is_ForceSilentSpecified ();

	if (cmdline.isNeedRegisterServer ())
	{
		onNeedRegisterServer ( false );
		return FALSE;
	}
	else if (cmdline.isNeedRegisterServerUserOnly ())
	{
		onNeedRegisterServer ( true );
		return FALSE;
	}
	else if (cmdline.isNeedUnregisterServer ())
	{
		onNeedUnregisterServer ();
		return FALSE;
	}

	if (vmsWinSecurity::os_supports_elevation () && 
		_tcsncmp (m_lpCmdLine, _T("-nelvcheck"), 10) && _tcsicmp (m_lpCmdLine, _T("-autorun")))
	{
		if (vmsWinSecurity::IsProcessElevated ())
		{
			WCHAR wsz [MAX_PATH] = L"";
			GetModuleFileNameW (NULL, wsz, MAX_PATH);
			std::wstring wstr = L"\"";
			wstr += wsz;
			wstr += L"\" -nelvcheck ";
			wstr += CT2WEX<> (m_lpCmdLine);
			_appMutex.CloseMutex ();
			STARTUPINFOW si = {0}; PROCESS_INFORMATION pi = {0};
			si.cb = sizeof (si);
			if (vmsWinSecurity::RunAsDesktopUser (wsz, (LPWSTR)wstr.c_str (), NULL, si, pi))
				return FALSE;
			_appMutex.Create ();
		}
	}

	cmdline.Parse (fsFDMCmdLineParser::Normal);

	if (CheckFdmStartedAlready (m_bForceSilentSpecified == FALSE))
		return FALSE;

	if (!InitATL())
		return FALSE;

	_App.StartCount (_App.StartCount () + 1);

	
	
	if (IS_PORTABLE_MODE && (_dwAppState & APPSTATE_PORTABLE_MODE_NOREG) == 0)
		Install_RegisterServer ();

	
	
	
	
	vmsFilesToDelete::Process ();

	if (bNeedLocalRegister)
		RegisterServer (FALSE);

	

#ifdef _AFXDLL
	Enable3dControls();			
#else
	Enable3dControlsStatic();	
#endif

	CheckLocked ();

	_UpdateMgr.ReadSettings ();
	
	if (_UpdateMgr.IsStartUpdaterNeeded ())
	{
		if (_UpdateMgr.StartUpdater ())	
			return FALSE;	
		else
			::MessageBox (NULL, LS (L_CANTFINDUPDATER), LS (L_ERR), MB_ICONERROR);
	}

	vmsFlvSniffInjector::o ().Enable (_App.FlvMonitoring_Enable () != FALSE);

	LoadHistory ();

	_Snds.ReadSettings ();

	if (!vmsBtSupport::isBtDllValid ())
	{
		MessageBox (NULL, LS (L_INVALID_BT_MODULE), _T ("Free Download Manager"), MB_ICONERROR);
		return FALSE;
	}

	auto ytdllmgr = std::make_shared <vmsYouTubeParserDllMgr> (
		std::make_shared <vmsAppDataFolder> (L"FreeDownloadManager.ORG", L"Free Download Manager"),
		currentVersionFirstRun);
	vmsYouTubeParserDllMgr::reset (ytdllmgr);

	auto avMerger = std::make_shared<vmsAVMergerFFMPEG>();
	auto avAfterMergeAction = std::make_shared<vmsYouTubeAfterMergeAction>();
	auto avYouTubeMergingMgr = std::make_shared <vmsAVMergingMgr>( avMerger, avAfterMergeAction, 1 );	
	_YouTubeDldsMgr.setYouTubeAVMergingMgr( avYouTubeMergingMgr );

	CMainFrame* pFrame = NULL;
	fsnew1 (pFrame, CMainFrame);
	m_pMainWnd = pFrame;

	
	if (FALSE == pFrame->LoadFrame(IDR_MAINFRAME, WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, 
		NULL, NULL))
	{
		return FALSE;
	}

	
	BOOL bHidden = _tcscmp (m_lpCmdLine, _T ("-autorun")) == 0;

	_App.View_ReadWndPlacement (pFrame, _T("MainFrm"), 
		bHidden ? fsAppSettings::RWPA_FORCE_SWHIDE_AND_KEEP_MINIMIZED_MAXIMIZED_STATE : fsAppSettings::RWPA_NONE);

	if (!bHidden)
	{
		if (_App.Prg_StartMinimized ())
		{
			if (IsWindowVisible (pFrame->m_hWnd))
				pFrame->ShowWindow (SW_MINIMIZE);
		}
		else
		{
			pFrame->UpdateWindow();
			if (pFrame->IsWindowVisible ())
				pFrame->SetForegroundWindow ();
		}
	}

	m_bStarting = FALSE;

	
	hRes = _Module.RegisterClassObjects (CLSCTX_LOCAL_SERVER, 
				REGCLS_MULTIPLEUSE);
	if (FAILED (hRes))
	{
		LPVOID lpMsgBuf;
		FormatMessage( 
				FORMAT_MESSAGE_ALLOCATE_BUFFER | 
				FORMAT_MESSAGE_FROM_SYSTEM | 
				FORMAT_MESSAGE_IGNORE_INSERTS,
				NULL,
				hRes,
				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 
				(LPTSTR) &lpMsgBuf,
				0,
				NULL 
				);
			
			
			
			MessageBox( NULL, (LPCTSTR)lpMsgBuf, nullptr, MB_OK | MB_ICONINFORMATION );
			
			LocalFree( lpMsgBuf );
	}
	m_bATLInited2 = SUCCEEDED (hRes);

	return TRUE;
}
Example #17
0
static int __cdecl pre_c_init(void) {
    /*
     * Determine if this is a managed application
     */
    managedapp = check_managed_app();
    /*
     * Set __app_type properly
     */
#ifdef _WINMAIN_
    __set_app_type(_GUI_APP);
#else  /* _WINMAIN_ */
    __set_app_type(_CONSOLE_APP);
#endif  /* _WINMAIN_ */
    /*
     * Mark this module as an EXE file so that atexit/_onexit
     * will do the right thing when called, including for C++
     * d-tors.
     */
    __onexitbegin = __onexitend = (_PVFV*)_encode_pointer((_PVFV*)(-1));
    /*
     * Propogate the _fmode and _commode variables to the DLL
     */
    *_IMP___FMODE = _fmode;
    *_IMP___COMMODE = _commode;
#ifdef _M_IX86
    /*
     * Set the local copy of the Pentium FDIV adjustment flag
     */
    _adjust_fdiv = * _imp___adjust_fdiv;
#endif  /* _M_IX86 */
    /*
     * Run the RTC initialization code for this DLL
     */
#ifdef _RTC
    _RTC_Initialize();
#endif  /* _RTC */
    /*
     * Call _setargv(), which will trigger a call to __setargv() if
     * SETARGV.OBJ is linked with the EXE.  If SETARGV.OBJ is not
     * linked with the EXE, a dummy _setargv() will be called.
     */
#ifdef WPRFLAG
    _wsetargv();
#else  /* WPRFLAG */
    _setargv();
#endif  /* WPRFLAG */

    /*
     * If the user has supplied a _matherr routine then set
     * __pusermatherr to point to it.
     */
    if (!__defaultmatherr) {
        __setusermatherr(_matherr);
    }

#ifdef _M_IX86
    _setdefaultprecision();
#endif  /* _M_IX86 */

    /* Enable per-thread locale if user asked for it */
    if (__globallocalestatus == -1) {
        _configthreadlocale(-1);
    }

    return 0;
}