Ejemplo n.º 1
0
int WINAPI _tWinMain( HINSTANCE hInst, HINSTANCE, LPTSTR, int )
{
	_tsetlocale( LC_ALL, _T(".OCP") );

	ATLVERIFY( SUCCEEDED( _Module.Init( NULL, hInst ) ) );
	if( !EnableDebugPrivilege() )
	{
		MessageBoxV( NULL, IDS_NO_DEBUG_PRIVILEGE, MB_OK | MB_ICONHAND );
		return 0;
	}

	InitializeCriticalSection( &g_cs );
	LoadInternalExceptionList();
	LoadSettings();
	DumpInit();

	if( !ProcessCommandLine() )
	{
		AtlInitCommonControls( ICC_BAR_CLASSES );
		LoadLibrary( CRichEditCtrl::GetLibraryName() );

		CMainDlg dlgMain;
		g_pMainWnd = &dlgMain;
		int nRet = dlgMain.DoModal();
		g_pMainWnd = NULL;
	}

	DumpUninit();
	SaveSettings();
	DeleteCriticalSection( &g_cs );

	_Module.Term();
	return 0;
}
Ejemplo n.º 2
0
int main( int argc, char * argv[] )
{
    if ( !ProcessCommandLine( argc, argv ) )
    {
        printf( "%s %d bit build\n%s",argv[0],8*sizeof(void*),g_szHelpSyntax );
        return 1;
    }

    MODULE_DEPENDENCY_LIST depends( g_pszPrimaryFile );

    if ( !depends.IsValid() )
    {
        printf( "Error: %s %s\n", g_pszPrimaryFile, depends.GetErrorString() );
        return 1;
    }

    PMODULE_FILE_INFO pModInfo = 0;

    while ( pModInfo = depends.GetNextModule( pModInfo ) )
    {
        DisplayFileInformation( pModInfo,g_fQuiet );

        PMODULE_FILE_INFO pNotFound = 0;

        while ( pNotFound = pModInfo->GetNextNotFoundModule(pNotFound) )
        {
            LPCTSTR base = getModuleBase(pNotFound,g_fQuiet) ;
            if ( base ) printf( "  Not found: %s\n", base );
        }
    }

    return 0;
}
Ejemplo n.º 3
0
bool CFileZillaApp::OnInit()
{
	AddStartupProfileRecord(_T("CFileZillaApp::OnInit()"));

	fz::set_translators(translator, translator_pf);

#ifdef __WXMSW__
	if (!InitWinsock()) {
		return false;
	}

	SetAppId();
#endif

	//wxSystemOptions is slow, if a value is not set, it keeps querying the environment
	//each and every time...
	wxSystemOptions::SetOption(_T("filesys.no-mimetypesmanager"), 0);
	wxSystemOptions::SetOption(_T("window-default-variant"), _T(""));
#ifdef __WXMSW__
	wxSystemOptions::SetOption(_T("no-maskblt"), 0);
	wxSystemOptions::SetOption(_T("msw.window.no-clip-children"), 0);
	wxSystemOptions::SetOption(_T("msw.font.no-proof-quality"), 0);
	wxSystemOptions::SetOption(_T("msw.remap"), 0);
	wxSystemOptions::SetOption(_T("msw.staticbox.optimized-paint"), 0);
#endif
#ifdef __WXMAC__
	wxSystemOptions::SetOption(_T("mac.listctrl.always_use_generic"), 1);
	wxSystemOptions::SetOption(_T("mac.textcontrol-use-spell-checker"), 0);
#endif

	int cmdline_result = ProcessCommandLine();
	if (!cmdline_result)
		return false;

	LoadLocales();

	if (cmdline_result < 0) {
		if (m_pCommandLine) {
			m_pCommandLine->DisplayUsage();
		}
		return false;
	}

	InitDefaultsDir();

	COptions::Init();

	InitLocale();

#ifndef _DEBUG
	const wxString& buildType = CBuildInfo::GetBuildType();
	if (buildType == _T("nightly")) {
		wxMessageBoxEx(_T("You are using a nightly development version of FileZilla 3, do not expect anything to work.\r\nPlease use the official releases instead.\r\n\r\n\
Unless explicitly instructed otherwise,\r\n\
DO NOT post bugreports,\r\n\
DO NOT use it in production environments,\r\n\
DO NOT distribute the binaries,\r\n\
DO NOT complain about it\r\n\
USE AT OWN RISK"), _T("Important Information"));
	}
Ejemplo n.º 4
0
int main(int argc, char* argv[])
{
	ProcessCommandLine(argc, argv);
	FCollada::Initialize(); //Needed for Mac/Linux when FCollada is statically linked.
	// In debug mode, output memory leak information and do periodic memory checks
#ifdef PLUG_CRT
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_CHECK_EVERY_128_DF);
#endif

	FUTestBed testBed(logFilename.c_str(), isVerbose);

#ifndef _DEBUG
	try {
#endif
	// Set the current folder to the folder with the samples DAE files
	_chdir("Samples");

	// FMath tests
	RUN_TESTSUITE(FCTestAll)

#ifndef _DEBUG
	}
	catch (const char* sz) { testBed.GetLogFile().WriteLine(sz); }
#ifdef UNICODE
	catch (const fchar* sz) { testBed.GetLogFile().WriteLine(sz); }
#endif
	catch (...) { testBed.GetLogFile().WriteLine("Exception caught!"); }
#endif

	return 0;
}
Ejemplo n.º 5
0
void main(int argc, char* argv[]) {
  struct Options options;

  SetDefaultOptions(&options, 0, MAX_FFT_ORDER);

  ProcessCommandLine(&options, argc, argv,
                     "Test forward and inverse floating-point FFT\n");

  verbose = options.verbose_;

  if (verbose > 255)
    DumpOptions(stderr, &options);

  if (options.test_mode_) {
    struct TestInfo info;

    info.real_only_ = options.real_only_;
    info.max_fft_order_ = options.max_fft_order_;
    info.min_fft_order_ = options.min_fft_order_;
    info.do_forward_tests_ = options.do_forward_tests_;
    info.do_inverse_tests_ = options.do_inverse_tests_;
    /* No known failures */
    info.known_failures_ = 0;

    info.forward_threshold_ = 138.81;
    info.inverse_threshold_ = 138.81;
    RunAllTests(&info);
  } else {
    TestFloatFFT(options.fft_log_size_,
                 options.signal_type_,
                 options.signal_value_);
  }
}
Ejemplo n.º 6
0
int main(int argc, char **argv)
{
    char infilename[BUFSIZ+1];
    char outfilename[BUFSIZ+1];
    char **doc = NULL;
    float maxval;
    float minval;
    int i;
    int resolution;
    int incols;
    int inrows;

    status = ProcessCommandLine(argc, argv, infilename, outfilename, &resolution);
    if (status != ENOERROR)
        goto error;

    status = ReadDocFile(infilename, &doc, &inrows, &incols);
    if (status != ENOERROR)
        goto error;

    status = ReadWriteSrfFiles(infilename, outfilename, resolution, inrows,
                               incols, &minval, &maxval);
    if (status != ENOERROR)
        goto error;

    status = WriteDocFile(outfilename, doc, inrows, incols, resolution, minval,
                          maxval);
    if (status != ENOERROR)
        goto error;

    if (doc != NULL) {
        i = 0;
        while (doc[i]) {
            free(doc[i]);
            i++;
        }
        free(doc);
    }

    return EXIT_SUCCESS;

error:
    if (doc != NULL) {
        i = 0;
        while (doc[i]) {
            if (doc[i] != NULL)
                free(doc[i]);
            else
                break;
            i++;
        }
        free(doc);
    }
    ProcessError();
    exit(EXIT_FAILURE);
}
Ejemplo n.º 7
0
int main(int argc, char *argv[])
{
	DebugInit();
	
	ProcessEnvVars();

	ProcessCommandLine(argc, argv);
	
	DebugShutdown();
	
	return 0;
}
Ejemplo n.º 8
0
void __fastcall TfmLauncher::ProcessStartupParams()
{
  ProcessCommandLine();
  if (!FileExists(FileName))
    ProcessConfigFile();

  if (!DirectoryExists(RootDirectory))
    RootDirectory = "..\\Data";
  if (!FileExists(FileName))
    FileName = "";
  if ((RootDirectory == "") && (FileName != ""))
    RootDirectory = ExtractFileDir(FileName);
}
Ejemplo n.º 9
0
int
CliDMain()
{
	printf("%s\n", NexToneShellBanner);

	PrintCommandPrompt(stdout);

	while (ProcessCommandLine(stdin))
	{
		PrintCommandPrompt(stdout);
	}
	return(0);
}
Ejemplo n.º 10
0
void Entry(void)
{
	HANDLE hMutex;
	int result=1;
	Options options;

	g_controlMsg=RegisterWindowMessageA(CONTROL_MESSAGE_NAME);

	ZeroFill(&options,sizeof options);
	ProcessCommandLine(&options);

#ifdef _DEBUG
	options.showWindow=TRUE;
#endif

	hMutex=OpenMutexA(MUTEX_ALL_ACCESS,FALSE,MUTEX_NAME);
	if(hMutex)
	{
		// Already running.
		ApplyOptions(&options);
	}
	else
	{
		if(options.nextLayout||options.prevLayout)
		{
			// Don't do anything.
		}
		else
		{
			hMutex=CreateMutexA(0,FALSE,MUTEX_NAME);

			if(!RunHelpers())
				result=1;
			else
			{
				result=Main(&options);

				ReleaseMutex(hMutex);
				hMutex=NULL;
			}

			PostMessage(HWND_BROADCAST,g_controlMsg,CONTROL_QUIT,0);
		}
	}

	LocalFree(options.pLayoutToSet);
	options.pLayoutToSet=NULL;

	ExitProcess(result);
}
Ejemplo n.º 11
0
int main(int argc, char *argv[])
{
    PSTR filename;
    
    if ( argc == 1 )
    {
        printf( HelpText );
        return 1;
    }
    
    filename = ProcessCommandLine(argc, argv);
    if ( filename )
        DumpFile( filename );

    return 0;
}
Ejemplo n.º 12
0
/* For the Windows platform, this is the start of the application. */
int WINAPI
WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpszArg, int nCmdShow)
{
    wchar_t **argw = NULL;
    int	argc, i;

    /* Set this to the default value (windowed mode). */
    video_fullscreen = 0;

    /* We need this later. */
    hinstance = hInst;

    /* Set the application version ID string. */
    sprintf(emu_version, "%s v%s", EMU_NAME, EMU_VERSION);

#ifdef USE_CRASHDUMP
    /* Enable crash dump services. */
    InitCrashDump();
#endif

    /* First, set our (default) language. */
    set_language(0x0409);

    /* Create console window. */
    CreateConsole(1);

    /* Process the command line for options. */
    argc = ProcessCommandLine(&argw);

    /* Pre-initialize the system, this loads the config file. */
    if (! pc_init(argc, argw)) {
	/* Detach from console. */
	CreateConsole(0);
	return(1);
    }

    /* Cleanup: we may no longer need the console. */
    if (! force_debug)
	CreateConsole(0);

    /* Handle our GUI. */
    i = ui_init(nCmdShow);

    return(i);
}
Ejemplo n.º 13
0
int
MDServerMain(int argc, char *argv[])
{
    int retval = 0;

    // Initialize error logging
    VisItInit::SetComponentName("mdserver");
    VisItInit::Initialize(argc, argv);
    InitVTKLite::Initialize();
    avtDatabase::SetOnlyServeUpMetaData(true);

    bool runApp = ProcessCommandLine(argc, argv);

    debug1 << "MDSERVER started." << endl;

    TRY
    {
        // Read the plugin info.
        MDServerApplication::Instance()->InitializePlugins();

        // Connect back to the process that launched the MDServer.
        MDServerApplication::Instance()->AddConnection(&argc, &argv);

        // Enter the program's main loop.
        if(runApp)
            MDServerApplication::Instance()->Execute();
        else
            MDServerApplication::Instance()->ExecuteDebug();

        // Clean up
        delete MDServerApplication::Instance();
    }
    CATCH2(VisItException, e)
    {
        debug1 << "VisIt's mdserver encountered the following uncaught "
               "exception: " << e.GetExceptionType().c_str()
               << " from (" << e.GetFilename().c_str()
               << ":" << e.GetLine() << ")" << endl
               << e.Message().c_str() << endl;
        retval = -1;
    }
Ejemplo n.º 14
0
int main(int argc, char* argv[]) {
  struct Options options;
  struct TestInfo info;
  int failed_count = 0;

  SetDefaultOptions(&options, 1, MAX_FFT_ORDER);

  ProcessCommandLine(&options,
                     argc,
                     argv,
                     UsageMessage());

  verbose = options.verbose_;

  info.real_only_ = options.real_only_;
  info.min_fft_order_ = options.min_fft_order_;
  info.max_fft_order_ = options.max_fft_order_;
  info.do_forward_tests_ = options.do_forward_tests_;
  info.do_inverse_tests_ = options.do_inverse_tests_;
  /* No known failures */
  info.known_failures_ = 0;

  SetThresholds(&info);

  if (verbose > 255)
    DumpOptions(stderr, &options);

  if (options.test_mode_) {
    failed_count = RunAllTests(&info);
  } else {
    TestOneFFT(options.fft_log_size_,
               options.signal_type_,
               options.signal_value_,
               &info,
               "Float Real FFT");
  }
  FinishedMessage();

  return failed_count > 0 ? 1 : 0;
}
Ejemplo n.º 15
0
void main(int argc, char* argv[]) {
  struct Options options;

  SetDefaultOptions(&options, 0, MAX_FFT_ORDER);

  ProcessCommandLine(&options, argc, argv,
                     "Test forward and inverse 32-bit fixed-point FFT\n");

  verbose = options.verbose_;
  signal_value = options.signal_value_;

  if (verbose > 255)
    DumpOptions(stderr, &options);

  if (options.test_mode_) {
    struct TestInfo info;

    info.real_only_ = options.real_only_;
    info.max_fft_order_ = options.max_fft_order_;
    info.min_fft_order_ = options.min_fft_order_;
    info.do_forward_tests_ = options.do_forward_tests_;
    info.do_inverse_tests_ = options.do_inverse_tests_;
    info.known_failures_ = 0;
    /*
     * These threshold values assume that we're using the default
     * signal_value set below.
     */
    info.forward_threshold_ = 107.33;
    info.inverse_threshold_ = 79.02;

    if (!options.signal_value_given_) {
      signal_value = 262144;         /* 18 bits */
    }
    RunAllTests(&info);
  } else {
    TestFFT(options.fft_log_size_,
            options.signal_type_,
            options.scale_factor_);
  }
}
Ejemplo n.º 16
0
// wxT('Main program') equivalent: the program execution "starts" here
bool MyApp::OnInit()
{
	SetDefaults();
	wxInitAllImageHandlers();

    // create the main application window
    MyFrame *frame = new MyFrame(wxT("SplashText"),
                                 wxPoint(50, 50), wxSize(500, 500));

	// Reconstruct the command line for future editing by user
	int i;
	for (i = 1; i < argc; i++)
	{
		wxString str(argv[i]);
		if (str.Find(wxT(' ')) != -1)
			str = wxString(wxT('"')) + str + wxString(wxT('"'));
		m_cmdLine += str;
		if (i < (argc - 1))
			m_cmdLine += wxT(" ");
	}

    m_parser.SetCmdLine(argc, argv);
	m_parser.SetDesc(cmdLineDesc);

    Log(wxT("Welcome to MakeSplash, by Julian Smart, 2000."));

	bool success = ProcessCommandLine(frame);

	if (!success || !m_batchMode)
	{
		frame->Show(TRUE);
		return TRUE;
	}
	else
	{
		frame->Destroy();
		return FALSE;
	}
}
Ejemplo n.º 17
0
void main(int argc, char* argv[]) {
  struct Options options;
  struct TestInfo info;

  SetDefaultOptions(&options, 1, MAX_FFT_ORDER);

  ProcessCommandLine(&options, argc, argv,
                     "Test forward and inverse real floating-point FFT\n");

  verbose = options.verbose_;

  if (verbose > 255)
    DumpOptions(stderr, &options);

  info.real_only_ = options.real_only_;
  info.min_fft_order_ = options.min_fft_order_;
  info.max_fft_order_ = options.max_fft_order_;
  info.do_forward_tests_ = options.do_forward_tests_;
  info.do_inverse_tests_ = options.do_inverse_tests_;
  /* No known failures */
  info.known_failures_ = 0;
#ifdef BIG_FFT_TABLE
  info.forward_threshold_ = 136.07;
  info.inverse_threshold_ = 140.76;
#else
  info.forward_threshold_ = 136.07;
  info.inverse_threshold_ = 142.41;
#endif

  if (options.test_mode_) {
    RunAllTests(&info);
  } else {
    TestOneFFT(options.fft_log_size_,
               options.signal_type_,
               options.signal_value_,
               &info,
               "Float Real FFT");
  }
}
Ejemplo n.º 18
0
int main (int argc, char *argv[])
{

  ofstream   tLogFile;
  TScene*    ptScene;
  char       acTimeString [30];
  time_t     tBaseTime, tInitTime, tRenderTime, tPostProcessTime;

  GlobalClassManager = new TClassManager();

  _tProgramName = "render";

  ProcessCommandLine (argc, argv);

  SetPaths();

  if ( !FileExists (_tLocalPath + "config") )
  {
		 cerr << "WARNING: No configuration file in " << _tLocalPath << endl;
  }
  else
  {
    if ( !ProcessConfigFile (_tLocalPath + "config", tConfigData) )
    {
      cerr << "ERROR: Couldn't read configuration file." << endl;
      exit (1);
    }
  }

//  for (multimap<string, string>::const_iterator iter = tConfigData.begin(); ( iter != tConfigData.end() ) ;iter++)
//  {
//    cout << (*iter).first << " = " << (*iter).second << endl;
//  }
  
  multimap<string, string>::const_iterator   iter = tConfigData.find ("PluginConfigFile");
  string   tPluginConfigFile = ( iter != tConfigData.end() ) ? (*iter).second : _tLocalPath + "pluginrc";

  if ( !FileExists (tPluginConfigFile) )
  {
    cerr << "ERROR: Plugin configuration file '" << tPluginConfigFile << "' does not exist." << endl;
    exit (1);
  }

  cout << "Loading plugins..." << endl;
  tPluginManager.initialize (tPluginConfigFile, 0);

  TGradient::_initialize();
  TImageManager::_initialize();
  TSceneManager::_initialize();
  tImageManager.initialize();

  if ( !TSceneManager::_knownFormat (_tInputFileFormat) )
  {
    cout << "ERROR: Scene format not supported" << endl;
    exit (1);
  }
  
  cout << "Parsing..." << endl;
  ptScene = TSceneManager::_load (_tInputFileName, _tInputFileFormat);

  if ( !ptScene )
  {
    cerr << "Error parsing input file" << endl;
    exit (1);
  }

  //
  // Uncomment next line for debug information on the whole scene.
  //
//  ptScene->printDebug();

  tBaseTime = time (NULL);

  cout << "Initializing..." << endl;
  if(!ptScene->initialize())
  {
    cerr << "Initialization failed!" << endl;
    exit (1);
  }    
  tInitTime = time (NULL);

  cout << "Rendering..." << endl;
  ptScene->render (&FinishedLine);
  tRenderTime = time (NULL);
  
  cout << "Postprocessing..." << endl;
  ptScene->postprocess();
  tPostProcessTime = time (NULL);
  
  cout << "Saving..." << endl;
  if ( !ptScene->saveImage() )
  {
    cout << "Could not save image file" << endl;
  }
  
  ptScene->finalize();

  cout << endl;
  cout << " Total ellapsed time : " << difftime (tPostProcessTime, tBaseTime) << " secs" << endl;
  cout << " - Initialization . . . " << difftime (tInitTime, tBaseTime) << " secs" << endl;
  cout << " - Render         . . . " << difftime (tRenderTime, tInitTime) << " secs" << endl;
  cout << " - Postprocessing . . . " << difftime (tPostProcessTime, tRenderTime) << " secs" << endl;
  cout << "";

  if ( _gKeepLog )
  {
    strftime (acTimeString, 30, "%b %d %H:%M:%S", localtime (&tBaseTime));
    
    tLogFile.open (_tLogFileName.c_str(), ios::out | ios::binary | ios::app);

    tLogFile << acTimeString << " " << _tInputFileName << ", " << difftime (tPostProcessTime, tBaseTime) << " seconds" << endl;

    tLogFile.close();
  }

  delete GlobalClassManager;

  return 0;

}  /* main() */
Ejemplo n.º 19
0
BOOL CConsoleGUIApp::InitInstance()
{
	// InitCommonControlsEx() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.
	INITCOMMONCONTROLSEX InitCtrls;
	InitCtrls.dwSize = sizeof(InitCtrls);
	// Set this to include all the common control classes you want to use
	// in your application.
	InitCtrls.dwICC = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	CWinAppEx::InitInstance();

	AfxEnableControlContainer();

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	// of your final executable, you should remove from the following
	// the specific initialization routines you do not need
	// Change the registry key under which our settings are stored
	// TODO: You should modify this string to be something appropriate
	// such as the name of your company or organization
	SetRegistryKey(_T("Local AppWizard-Generated Applications"));

	LPWSTR *szArglist;
	int nArgs;

	szArglist = CommandLineToArgvW (GetCommandLineW(), &nArgs);
	if (szArglist != NULL) {
		if (nArgs == 1) {
			CString strFilePath;
			GetModuleFileName (m_hInstance,  strFilePath.GetBuffer (MAX_PATH), MAX_PATH);
			strFilePath.ReleaseBuffer ();
			strFilePath += _T(" /gui{80F0C7CB-6A50-4441-9985-5A0F4181C1C1}");
			STARTUPINFO startInfo = {0};
			PROCESS_INFORMATION processInfo = {0};

			startInfo.cb = sizeof(STARTUPINFO);

			// relaunch myself in GUI mode
			::CreateProcess (NULL, (LPTSTR)(LPCTSTR)strFilePath, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &startInfo, &processInfo);
			return FALSE;
		} else {
			if (nArgs == 2 && wcscmp (szArglist[1], L"/gui{80F0C7CB-6A50-4441-9985-5A0F4181C1C1}") == 0) {
				::ShowWindow (GetConsoleWindow (), SW_HIDE);
			} else {
				m_bConsoleMode = TRUE;
				ProcessCommandLine (nArgs, szArglist);
				LocalFree (szArglist);
				return FALSE;
			}
		}

		LocalFree (szArglist);
	}	

	m_bConsoleMode = TRUE;

	CConsoleGUIDlg dlg;
	m_pMainWnd = &dlg;
	INT_PTR nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with OK
	}
	else if (nResponse == IDCANCEL)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with Cancel
	}

	// Since the dialog has been closed, return FALSE so that we exit the
	//  application, rather than start the application's message pump.
	return FALSE;
}
Ejemplo n.º 20
0
//================================================================================================
//--------------------------------------------------==-+++--> Entry Point of Program Using WinMain:
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	WNDCLASS wndclass;
	HWND hwndMain;
	MSG msg;
	int updated;
	
	(void)hPrevInstance;
	(void)nCmdShow;
	
	#if defined(__GNUC__) && defined(_DEBUG)
	#	ifdef _WIN64
	#		define LoadExcHndl() LoadLibraryExA("dbg\\64\\exchndl", NULL, LOAD_WITH_ALTERED_SEARCH_PATH)
	#	else
	#		define LoadExcHndl() LoadLibraryExA("dbg\\exchndl", NULL, LOAD_WITH_ALTERED_SEARCH_PATH)
	#	endif
	#else
	#	define LoadExcHndl()
	#endif
	LoadExcHndl(); // LOAD_WITH_ALTERED_SEARCH_PATH works :P At least since Win2k
	
	g_instance = hInstance;
	if(LoadClockAPI("misc/T-Clock" ARCH_SUFFIX, &api)){
		MessageBox(NULL, "Error loading: T-Clock" ARCH_SUFFIX ".dll", "API error", MB_OK|MB_ICONERROR);
		return 2;
	}
	chdir(api.root); // make sure we've got the right working directory
	
	// Make sure we're running Windows 2000 and above
	if(!api.OS) {
		MessageBox(NULL,"T-Clock requires Windows 2000 or newer","old OS",MB_OK|MB_ICONERROR);
		return 1;
	}
	
	// make sure ObjectBar isn't running -> From Original Code/Unclear if This is Still a Conflict. (test suggested not really.. no crash but no clock either :P)
	if(FindWindow("ObjectBar Main","ObjectBar")) {
		MessageBox(NULL,"ObjectBar and T-Clock can't be run together","ObjectBar detected!",MB_OK|MB_ICONERROR);
		return 1;
	}
	
	// Load ALL of the Global Resources
	g_hIconTClock = LoadIcon(api.hInstance, MAKEINTRESOURCE(IDI_MAIN));
	g_hIconPlay = LoadImage(g_instance, MAKEINTRESOURCE(IDI_PLAY), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
	g_hIconStop = LoadImage(g_instance, MAKEINTRESOURCE(IDI_STOP), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
	g_hIconDel  = LoadImage(g_instance, MAKEINTRESOURCE(IDI_DEL), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
	
//	FindTrayServer(hwndMain);
	
	// Make sure we're not running 32bit on 64bit OS / start the other one
	#ifndef _WIN64
	if(IsWow64()){
		hwndMain = FindWindow(g_szClassName, NULL);
		if(hwndMain) { // send commands to existing instance
			ProcessCommandLine(hwndMain,lpCmdLine);
		}else{ // start new instance
			char clock64[MAX_PATH];
			memcpy(clock64, api.root, api.root_len+1);
			add_title(clock64,"Clock" ARCH_SUFFIX_64 ".exe");
			api.Exec(clock64,lpCmdLine,NULL);
		}
		return 0;
	}
	#endif // _WIN64
	
	// Do Not Allow the Program to Execute Twice!
	updated = 25; /**< wait up to 5 sec in 1/5th seconds for other instance */
	do{
		HANDLE processlock=CreateMutex(NULL,FALSE,g_szClassName); // we leak handle here, but Windows closes on process exit anyway (so why do it manually?)
		if(processlock && GetLastError()==ERROR_ALREADY_EXISTS){
			CloseHandle(processlock);
			hwndMain = FindWindow(g_szClassName, NULL);
			if(hwndMain) { // This One Sends Commands to the Instance
				ProcessCommandLine(hwndMain,lpCmdLine); // That is Currently Running.
				return 0;
			}
			Sleep(200);
			continue;
		}
		break;
	}while(updated--);
	
	// Update settings if required and setup defaults
	if((updated=CheckSettings())<0){
		return 1;
	}
	CancelAllTimersOnStartUp();
	
	// Message of the taskbar recreating - Special thanks to Mr.Inuya
	g_WM_TaskbarCreated = RegisterWindowMessage("TaskbarCreated");
	
	// register a window class
	wndclass.style         = 0;
	wndclass.lpfnWndProc   = WndProc;
	wndclass.cbClsExtra    = 0;
	wndclass.cbWndExtra    = 0;
	wndclass.hInstance     = g_instance;
	wndclass.hIcon         = g_hIconTClock;
	wndclass.hCursor       = LoadCursor(NULL, IDC_ARROW);
	wndclass.hbrBackground = (HBRUSH)(intptr_t)(COLOR_WINDOW+1);
	wndclass.lpszMenuName  = NULL;
	wndclass.lpszClassName = g_szClassName;
	g_atomTClock = RegisterClass(&wndclass);
	
	if(api.OS >= TOS_VISTA) { // allow non elevated processes to send control messages (eg, App with admin rights, explorer without)
		#define MSGFLT_ADD 1
		#define MSGFLT_REMOVE 2
		typedef BOOL (WINAPI* ChangeWindowMessageFilter_t)(UINT message,DWORD dwFlag);
		ChangeWindowMessageFilter_t ChangeWindowMessageFilter=(ChangeWindowMessageFilter_t)GetProcAddress(GetModuleHandle("user32"), "ChangeWindowMessageFilter");
		if(ChangeWindowMessageFilter){
			int msgid;
			ChangeWindowMessageFilter(g_WM_TaskbarCreated,MSGFLT_ADD);
			ChangeWindowMessageFilter(WM_COMMAND,MSGFLT_ADD);
			for(msgid=WM_MOUSEFIRST; msgid<=WM_MOUSELAST; ++msgid)
				ChangeWindowMessageFilter(msgid,MSGFLT_ADD);
			for(msgid=MAINMFIRST; msgid<=MAINMLAST; ++msgid)
				ChangeWindowMessageFilter(msgid,MSGFLT_ADD);
		}
	}
	
	// create a hidden window
	g_hwndTClockMain = hwndMain = CreateWindowEx(WS_EX_NOACTIVATE, MAKEINTATOM(g_atomTClock),NULL, 0, 0,0,0,0, NULL,NULL,g_instance,NULL);
	// This Checks for First Instance Startup Options
	ProcessCommandLine(hwndMain,lpCmdLine);
	
	GetHotKeyInfo(hwndMain);
	
	if(api.OS > TOS_2000) {
		if(api.GetInt("Desktop", "MonOffOnLock", 0))
			RegisterSession(hwndMain);
	}
	if(updated==1){
		PostMessage(hwndMain,WM_COMMAND,IDM_SHOWPROP,0);
	}
	while(GetMessage(&msg, NULL, 0, 0)) {
		if(!(g_hwndSheet && IsWindow(g_hwndSheet) && PropSheet_IsDialogMessage(g_hwndSheet,&msg))
		&& !(g_hDlgTimer && IsWindow(g_hDlgTimer) && IsDialogMessage(g_hDlgTimer,&msg))
		&& !(g_hDlgTimerWatch && IsWindow(g_hDlgTimerWatch) && IsDialogMessage(g_hDlgTimerWatch,&msg))
		&& !(g_hDlgStopWatch && IsWindow(g_hDlgStopWatch) && IsDialogStopWatchMessage(g_hDlgStopWatch,&msg))){
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}
	
	UnregisterHotKey(hwndMain, HOT_TIMER);
	UnregisterHotKey(hwndMain, HOT_WATCH);
	UnregisterHotKey(hwndMain, HOT_STOPW);
	UnregisterHotKey(hwndMain, HOT_PROPR);
	UnregisterHotKey(hwndMain, HOT_CALEN);
	UnregisterHotKey(hwndMain, HOT_TSYNC);
	
	UnregisterSession(hwndMain);
	
	EndNewAPI(NULL);
	
	return (int)msg.wParam;
}
Ejemplo n.º 21
0
int WINAPI _tWinMain (HINSTANCE hThisInstance,
                    UNUSED HINSTANCE hPrevInstance,
                    UNUSED LPTSTR lpszArgument,
                    UNUSED int nCmdShow)
{
  MSG messages;            /* Here messages to the application are saved */
  WNDCLASSEX wincl;        /* Data structure for the windowclass */
  DWORD shell32_version;

  /* Initialize handlers for manangement interface notifications */
  mgmt_rtmsg_handler handler[] = {
      { ready,    OnReady },
      { hold,     OnHold },
      { log,      OnLogLine },
      { state,    OnStateChange },
      { password, OnPassword },
      { proxy,    OnProxy },
      { stop,     OnStop },
      { 0,        NULL }
  };
  InitManagement(handler);

  /* initialize options to default state */
  InitOptions(&o);

#ifdef DEBUG
  /* Open debug file for output */
  if (!(o.debug_fp = fopen(DEBUG_FILE, "w")))
    {
      /* can't open debug file */
      ShowLocalizedMsg(IDS_ERR_OPEN_DEBUG_FILE, DEBUG_FILE);
      exit(1);
    }
  PrintDebug(_T("Starting OpenVPN GUI v%S"), PACKAGE_VERSION);
#endif


  o.hInstance = hThisInstance;

  if(!GetModuleHandle(_T("RICHED20.DLL")))
    {
      LoadLibrary(_T("RICHED20.DLL"));
    }
  else
    {
      /* can't load riched20.dll */
      ShowLocalizedMsg(IDS_ERR_LOAD_RICHED20);
      exit(1);
    }

  /* Check version of shell32.dll */
  shell32_version=GetDllVersion(_T("shell32.dll"));
  if (shell32_version < PACKVERSION(5,0))
    {
      /* shell32.dll version to low */
      ShowLocalizedMsg(IDS_ERR_SHELL_DLL_VERSION, shell32_version);
      exit(1);
    }
#ifdef DEBUG
  PrintDebug(_T("Shell32.dll version: 0x%lx"), shell32_version);
#endif


  /* Parse command-line options */
  ProcessCommandLine(&o, GetCommandLine());

  /* Check if a previous instance is already running. */
  if ((FindWindow (szClassName, NULL)) != NULL)
    {
        /* GUI already running */
        ShowLocalizedMsg(IDS_ERR_GUI_ALREADY_RUNNING);
        exit(1);
    }

  if (!GetRegistryKeys()) {
    exit(1);
  }
  if (!CheckVersion()) {
    exit(1);
  }

  if (!EnsureDirExists(o.log_dir))
  {
    ShowLocalizedMsg(IDS_ERR_CREATE_PATH, _T("log_dir"), o.log_dir);
    exit(1);
  }

  BuildFileList();
  if (!VerifyAutoConnections()) {
    exit(1);
  }
  GetProxyRegistrySettings();

#ifndef DISABLE_CHANGE_PASSWORD
  /* Initialize OpenSSL */
  OpenSSL_add_all_algorithms();
  ERR_load_crypto_strings();
#endif

  /* The Window structure */
  wincl.hInstance = hThisInstance;
  wincl.lpszClassName = szClassName;
  wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
  wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
  wincl.cbSize = sizeof (WNDCLASSEX);

  /* Use default icon and mouse-pointer */
  wincl.hIcon = LoadLocalizedIcon(ID_ICO_APP);
  wincl.hIconSm = LoadLocalizedIcon(ID_ICO_APP);
  wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
  wincl.lpszMenuName = NULL;                 /* No menu */
  wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
  wincl.cbWndExtra = 0;                      /* structure or the window instance */
  /* Use Windows's default color as the background of the window */
  wincl.hbrBackground = (HBRUSH) COLOR_3DSHADOW; //COLOR_BACKGROUND;

  /* Register the window class, and if it fails quit the program */
  if (!RegisterClassEx (&wincl))
    return 1;

  /* The class is registered, let's create the program*/
  CreateWindowEx (
           0,                   /* Extended possibilites for variation */
           szClassName,         /* Classname */
           szTitleText,         /* Title Text */
           WS_OVERLAPPEDWINDOW, /* default window */
           (int)CW_USEDEFAULT,  /* Windows decides the position */
           (int)CW_USEDEFAULT,  /* where the window ends up on the screen */
           230,                 /* The programs width */
           200,                 /* and height in pixels */
           HWND_DESKTOP,        /* The window is a child-window to desktop */
           NULL,                /* No menu */
           hThisInstance,       /* Program Instance handler */
           NULL                 /* No Window Creation data */
           );


  /* Run the message loop. It will run until GetMessage() returns 0 */
  while (GetMessage (&messages, NULL, 0, 0))
  {
    TranslateMessage(&messages);
    DispatchMessage(&messages);
  }

  /* The program return-value is 0 - The value that PostQuitMessage() gave */
  return messages.wParam;
}
Ejemplo n.º 22
0
int
main(int argc, char *argv[])
{
    json_object *main_obj = json_object_new_object();
    json_object *parallel_obj = json_object_new_object();
    json_object *problem_obj = 0;
    json_object *clargs_obj = 0;
    MACSIO_TIMING_GroupMask_t main_grp;
    MACSIO_TIMING_TimerId_t main_tid;
    int i, argi, exercise_scr = 0;
    int size = 1, rank = 0;

    /* quick pre-scan for scr cl flag */
    for (i = 0; i < argc && !exercise_scr; i++)
        exercise_scr = !strcmp("exercise_scr", argv[i]);

#warning SHOULD WE BE USING MPI-3 API
#ifdef HAVE_MPI
    MPI_Init(&argc, &argv);
#ifdef HAVE_SCR
#warning SANITY CHECK WITH MIFFPP
    if (exercise_scr)
        SCR_Init();
#endif
    MPI_Comm_dup(MPI_COMM_WORLD, &MACSIO_MAIN_Comm);
    MPI_Errhandler_set(MACSIO_MAIN_Comm, MPI_ERRORS_RETURN);
    MPI_Comm_size(MACSIO_MAIN_Comm, &MACSIO_MAIN_Size);
    MPI_Comm_rank(MACSIO_MAIN_Comm, &MACSIO_MAIN_Rank);
    mpi_errno = MPI_SUCCESS;
#endif
    errno = 0;

    main_grp = MACSIO_TIMING_GroupMask("MACSIO main()");
    main_tid = MT_StartTimer("main", main_grp, MACSIO_TIMING_ITER_AUTO);

    MACSIO_LOG_StdErr = MACSIO_LOG_LogInit(MACSIO_MAIN_Comm, 0, 0, 0, 0);

    /* Process the command line and put the results in the problem */
    clargs_obj = ProcessCommandLine(argc, argv, &argi);
    json_object_object_add(main_obj, "clargs", clargs_obj);

    strncpy(MACSIO_UTILS_UnitsPrefixSystem, JsonGetStr(clargs_obj, "units_prefix_system"),
        sizeof(MACSIO_UTILS_UnitsPrefixSystem));

    MACSIO_LOG_MainLog = MACSIO_LOG_LogInit(MACSIO_MAIN_Comm,
        JsonGetStr(clargs_obj, "log_file_name"),
        JsonGetInt(clargs_obj, "log_line_length"),
        JsonGetInt(clargs_obj, "log_line_cnt/0"),
        JsonGetInt(clargs_obj, "log_line_cnt/1"));

#warning THESE INITIALIZATIONS SHOULD BE IN MACSIO_LOG
    MACSIO_LOG_DebugLevel = JsonGetInt(clargs_obj, "debug_level");

    /* Setup parallel information */
    json_object_object_add(parallel_obj, "mpi_size", json_object_new_int(MACSIO_MAIN_Size));
    json_object_object_add(parallel_obj, "mpi_rank", json_object_new_int(MACSIO_MAIN_Rank));
    json_object_object_add(main_obj, "parallel", parallel_obj);

#warning SHOULD WE INCLUDE TOP-LEVEL INFO ON VAR NAMES AND WHETHER THEYRE RESTRICTED
#warning CREATE AN IO CONTEXT OBJECT
    /* Acquire an I/O context handle from the plugin */

    /* Do a read or write test */
    if (strcmp(JsonGetStr(clargs_obj, "read_path"),"null"))
        main_read(argi, argc, argv, main_obj);
    else
        main_write(argi, argc, argv, main_obj);

    /* stop total timer */
    MT_StopTimer(main_tid);

    /* Write timings data file if requested */
    if (strlen(JsonGetStr(clargs_obj, "timings_file_name")))
        write_timings_file(JsonGetStr(clargs_obj, "timings_file_name"));

    MACSIO_TIMING_ClearTimers(MACSIO_TIMING_ALL_GROUPS);

#warning ATEXIT THESE
    if (json_object_put(main_obj) != 1)
    {
        MACSIO_LOG_MSG(Info, ("Unable to free main JSON object"));
    }
    MACSIO_TIMING_GroupMask(0);
    MACSIO_TIMING_ReduceTimers(MACSIO_MAIN_Comm, -1);
    json_object_apath_get_string(0,0); /* free circ cache */
    MACSIO_LOG_LogFinalize(MACSIO_LOG_MainLog);
    MACSIO_LOG_LogFinalize(MACSIO_LOG_StdErr);

#ifdef HAVE_SCR
    if (exercise_scr)
        SCR_Finalize();
#endif

#ifdef HAVE_MPI
    {   int result;
        if ((MPI_Initialized(&result) == MPI_SUCCESS) && result)
            MPI_Finalize();
    }
#endif

#warning FIX RETVAL OF MAIN TO BE NON-ZERO WHEN ERRORS OCCUR
    return (0);
}
Ejemplo n.º 23
0
//--------------------------------------------------------------------------------
BOOL CNTService::ProcessCommandLine()
	{
	return ProcessCommandLine(::GetCommandLine());
	}
Ejemplo n.º 24
0
int main(int argc, char** argv)
{
	gn_argc = argc; gp_argv = argv;

	int iRc = 0;
	HMODULE hConEmu = NULL;
	wchar_t szErrInfo[200];
	DWORD dwErr;
	typedef int (__stdcall* ConsoleMain2_t)(BOOL abAlternative);
	ConsoleMain2_t lfConsoleMain2;

	#ifdef _DEBUG
	HMODULE hConEmuHk = GetModuleHandle(WIN3264TEST(L"ConEmuHk.dll",L"ConEmuHk64.dll"));
	_ASSERTE(hConEmuHk==NULL && "Hooks must not be loaded into ConEmuC[64].exe!");
	#endif

	#if defined(SHOW_STARTED_MSGBOX)
	if (!IsDebuggerPresent())
	{
		wchar_t szTitle[100]; _wsprintf(szTitle, SKIPLEN(countof(szTitle)) WIN3264TEST(L"ConEmuC",L"ConEmuC64") L" Loaded (PID=%i)", GetCurrentProcessId());
		const wchar_t* pszCmdLine = GetCommandLineW();
		MessageBox(NULL,pszCmdLine,szTitle,0);
	}
	#endif

	// Обязательно, иначе по CtrlC мы свалимся
	SetConsoleCtrlHandler((PHANDLER_ROUTINE)HandlerRoutine, true);

	#ifdef _DEBUG
	UnitTests();
	#endif

	// Some command we can process internally
	if (ProcessCommandLine(iRc, hConEmu))
	{
		// Done, exiting
		goto wrap;
	}

	// Otherwise - do the full cycle
	if (!hConEmu)
		hConEmu = LoadLibrary(WIN3264TEST(L"ConEmuCD.dll",L"ConEmuCD64.dll"));
	dwErr = GetLastError();

	if (!hConEmu)
	{
		_wsprintf(szErrInfo, SKIPLEN(countof(szErrInfo))
		           L"Can't load library \"%s\", ErrorCode=0x%08X\n",
		           WIN3264TEST(L"ConEmuCD.dll",L"ConEmuCD64.dll"),
		           dwErr);
		_wprintf(szErrInfo);
		_ASSERTE(FALSE && "LoadLibrary failed");
		iRc = CERR_CONEMUHK_NOTFOUND;
		goto wrap;
	}

	// Загрузить функи из ConEmuHk
	lfConsoleMain2 = (ConsoleMain2_t)GetProcAddress(hConEmu, "ConsoleMain2");
	gfHandlerRoutine = (PHANDLER_ROUTINE)GetProcAddress(hConEmu, "HandlerRoutine");

	if (!lfConsoleMain2 || !gfHandlerRoutine)
	{
		dwErr = GetLastError();
		_wsprintf(szErrInfo, SKIPLEN(countof(szErrInfo))
		           L"Procedure \"%s\"  not found in library \"%s\"",
		           lfConsoleMain2 ? L"HandlerRoutine" : L"ConsoleMain2",
		           WIN3264TEST(L"ConEmuCD.dll",L"ConEmuCD64.dll"));
		_wprintf(szErrInfo);
		_ASSERTE(FALSE && "GetProcAddress failed");
		FreeLibrary(hConEmu);
		iRc = CERR_CONSOLEMAIN_NOTFOUND;
		goto wrap;
	}

	// Main dll entry point for Server & ComSpec
	iRc = lfConsoleMain2(0/*WorkMode*/);
	// Exiting
	gfHandlerRoutine = NULL;
	//FreeLibrary(hConEmu); -- Shutdown Server/Comspec уже выполнен
wrap:
	//-- bottle neck: relatively long deinitialization
	ExitProcess(iRc);
	return iRc;
}
Ejemplo n.º 25
0
int
main(int argc, char *argv[], char *envp[])
#endif
{
    int i;
    HWEventQueueType alwaysCheckForInput[2];

    display = "0";

    InitRegions();

    CheckUserParameters(argc, argv, envp);

    CheckUserAuthorization();

    InitConnectionLimits();

    ProcessCommandLine(argc, argv);

    alwaysCheckForInput[0] = 0;
    alwaysCheckForInput[1] = 1;
    while (1) {
        serverGeneration++;
        ScreenSaverTime = defaultScreenSaverTime;
        ScreenSaverInterval = defaultScreenSaverInterval;
        ScreenSaverBlanking = defaultScreenSaverBlanking;
        ScreenSaverAllowExposures = defaultScreenSaverAllowExposures;
#ifdef DPMSExtension
        DPMSStandbyTime = DPMSSuspendTime = DPMSOffTime = ScreenSaverTime;
        DPMSEnabled = TRUE;
        DPMSPowerLevel = 0;
#endif
        InitBlockAndWakeupHandlers();
        /* Perform any operating system dependent initializations you'd like */
        OsInit();
        if (serverGeneration == 1) {
            CreateWellKnownSockets();
            for (i = 1; i < MAXCLIENTS; i++)
                clients[i] = NullClient;
            serverClient = calloc(sizeof(ClientRec), 1);
            if (!serverClient)
                FatalError("couldn't create server client");
            InitClient(serverClient, 0, (pointer) NULL);
        }
        else
            ResetWellKnownSockets();
        clients[0] = serverClient;
        currentMaxClients = 1;

        /* Initialize privates before first allocation */
        dixResetPrivates();

        /* Initialize server client devPrivates, to be reallocated as
         * more client privates are registered
         */
        if (!dixAllocatePrivates(&serverClient->devPrivates, PRIVATE_CLIENT))
            FatalError("failed to create server client privates");

        if (!InitClientResources(serverClient)) /* for root resources */
            FatalError("couldn't init server resources");

        SetInputCheck(&alwaysCheckForInput[0], &alwaysCheckForInput[1]);
        screenInfo.numScreens = 0;

        InitAtoms();
        InitEvents();
        InitSelections();
        InitGlyphCaching();
        dixResetRegistry();
        ResetFontPrivateIndex();
        InitCallbackManager();
        InitOutput(&screenInfo, argc, argv);

        if (screenInfo.numScreens < 1)
            FatalError("no screens found");
        InitExtensions(argc, argv);

        for (i = 0; i < screenInfo.numGPUScreens; i++) {
            ScreenPtr pScreen = screenInfo.gpuscreens[i];
            if (!CreateScratchPixmapsForScreen(pScreen))
                FatalError("failed to create scratch pixmaps");
        }

        for (i = 0; i < screenInfo.numScreens; i++) {
            ScreenPtr pScreen = screenInfo.screens[i];

            if (!CreateScratchPixmapsForScreen(pScreen))
                FatalError("failed to create scratch pixmaps");
            if (pScreen->CreateScreenResources &&
                !(*pScreen->CreateScreenResources) (pScreen))
                FatalError("failed to create screen resources");
            if (!CreateGCperDepth(i))
                FatalError("failed to create scratch GCs");
            if (!CreateDefaultStipple(i))
                FatalError("failed to create default stipple");
            if (!CreateRootWindow(pScreen))
                FatalError("failed to create root window");
        }

        InitFonts();
        if (SetDefaultFontPath(defaultFontPath) != Success) {
            ErrorF("[dix] failed to set default font path '%s'",
                   defaultFontPath);
        }
        if (!SetDefaultFont(defaultTextFont)) {
            FatalError("could not open default font '%s'", defaultTextFont);
        }

        if (!(rootCursor = CreateRootCursor(NULL, 0))) {
            FatalError("could not open default cursor font '%s'",
                       defaultCursorFont);
        }

#ifdef DPMSExtension
        /* check all screens, looking for DPMS Capabilities */
        DPMSCapableFlag = DPMSSupported();
        if (!DPMSCapableFlag)
            DPMSEnabled = FALSE;
#endif

#ifdef PANORAMIX
        /*
         * Consolidate window and colourmap information for each screen
         */
        if (!noPanoramiXExtension)
            PanoramiXConsolidate();
#endif

        for (i = 0; i < screenInfo.numScreens; i++)
            InitRootWindow(screenInfo.screens[i]->root);

        InitCoreDevices();
        InitInput(argc, argv);
        InitAndStartDevices();
        ReserveClientIds(serverClient);

        dixSaveScreens(serverClient, SCREEN_SAVER_FORCER, ScreenSaverReset);

#ifdef PANORAMIX
        if (!noPanoramiXExtension) {
            if (!PanoramiXCreateConnectionBlock()) {
                FatalError("could not create connection block info");
            }
        }
        else
#endif
        {
            if (!CreateConnectionBlock()) {
                FatalError("could not create connection block info");
            }
        }

#ifdef XQUARTZ
        /* Let the other threads know the server is done with its init */
        pthread_mutex_lock(&serverRunningMutex);
        serverRunning = TRUE;
        pthread_cond_broadcast(&serverRunningCond);
        pthread_mutex_unlock(&serverRunningMutex);
#endif

        NotifyParentProcess();

        Dispatch();

#ifdef XQUARTZ
        /* Let the other threads know the server is no longer running */
        pthread_mutex_lock(&serverRunningMutex);
        serverRunning = FALSE;
        pthread_mutex_unlock(&serverRunningMutex);
#endif

        UndisplayDevices();
        DisableAllDevices();

        /* Now free up whatever must be freed */
        if (screenIsSaved == SCREEN_SAVER_ON)
            dixSaveScreens(serverClient, SCREEN_SAVER_OFF, ScreenSaverReset);
        FreeScreenSaverTimer();
        CloseDownExtensions();

#ifdef PANORAMIX
        {
            Bool remember_it = noPanoramiXExtension;

            noPanoramiXExtension = TRUE;
            FreeAllResources();
            noPanoramiXExtension = remember_it;
        }
#else
        FreeAllResources();
#endif

        CloseInput();

        for (i = 0; i < screenInfo.numScreens; i++)
            screenInfo.screens[i]->root = NullWindow;

        CloseDownDevices();

        CloseDownEvents();

        for (i = screenInfo.numGPUScreens - 1; i >= 0; i--) {
            ScreenPtr pScreen = screenInfo.gpuscreens[i];
            FreeScratchPixmapsForScreen(pScreen);
            (*pScreen->CloseScreen) (pScreen);
            dixFreePrivates(pScreen->devPrivates, PRIVATE_SCREEN);
            free(pScreen);
            screenInfo.numGPUScreens = i;
        }

        for (i = screenInfo.numScreens - 1; i >= 0; i--) {
            FreeScratchPixmapsForScreen(screenInfo.screens[i]);
            FreeGCperDepth(i);
            FreeDefaultStipple(i);
            dixFreeScreenSpecificPrivates(screenInfo.screens[i]);
            (*screenInfo.screens[i]->CloseScreen) (screenInfo.screens[i]);
            dixFreePrivates(screenInfo.screens[i]->devPrivates, PRIVATE_SCREEN);
            free(screenInfo.screens[i]);
            screenInfo.numScreens = i;
        }

        ReleaseClientIds(serverClient);
        dixFreePrivates(serverClient->devPrivates, PRIVATE_CLIENT);
        serverClient->devPrivates = NULL;

        FreeFonts();

        FreeAuditTimer();

        if (dispatchException & DE_TERMINATE) {
            CloseWellKnownConnections();
        }

        OsCleanup((dispatchException & DE_TERMINATE) != 0);

        if (dispatchException & DE_TERMINATE) {
            ddxGiveUp(EXIT_NO_ERROR);
            break;
        }

        free(ConnectionInfo);
        ConnectionInfo = NULL;
    }
    return 0;
}
Ejemplo n.º 26
0
/**
 * Application entry point
 * Params:
 *   -Test test if the pak file is healthy
 *   -Extract extracts pak file contents (followed by a path, i.e.: -extract D:\ExtractedPak)
 *   -Create=filename response file to create a pak file with
 *   -Sign=filename use the key pair in filename to sign a pak file, or: -sign=key_hex_values_separated_with_+, i.e: -sign=0x123456789abcdef+0x1234567+0x12345abc
 *    where the first number is the private key exponend, the second one is modulus and the third one is the public key exponent.
 *   -Signed use with -extract and -test to let the code know this is a signed pak
 *   -GenerateKeys=filename generates encryption key pair for signing a pak file
 *   -P=prime will use a predefined prime number for generating encryption key file
 *   -Q=prime same as above, P != Q, GCD(P, Q) = 1 (which is always true if they're both prime)
 *   -GeneratePrimeTable=filename generates a prime table for faster prime number generation (.inl file)
 *   -TableMax=number maximum prime number in the generated table (default is 10000)
 *
 * @param	ArgC	Command-line argument count
 * @param	ArgV	Argument strings
 */
INT32_MAIN_INT32_ARGC_TCHAR_ARGV()
{
	// start up the main loop
	GEngineLoop.PreInit(ArgC, ArgV);

	if (ArgC < 2)
	{
		UE_LOG(LogPakFile, Error, TEXT("No pak file name specified. Usage:"));
		UE_LOG(LogPakFile, Error, TEXT("  UnrealPak <PakFilename> -Test"));
		UE_LOG(LogPakFile, Error, TEXT("  UnrealPak <PakFilename> -List"));
		UE_LOG(LogPakFile, Error, TEXT("  UnrealPak <PakFilename> -Extract <ExtractDir>"));
		UE_LOG(LogPakFile, Error, TEXT("  UnrealPak <PakFilename> -Create=<ResponseFile> [Options]"));
		UE_LOG(LogPakFile, Error, TEXT("  UnrealPak <PakFilename> -Dest=<MountPoint>"));
		UE_LOG(LogPakFile, Error, TEXT("  UnrealPak GenerateKeys=<KeyFilename>"));
		UE_LOG(LogPakFile, Error, TEXT("  UnrealPak GeneratePrimeTable=<KeyFilename> [-TableMax=<N>]"));
		UE_LOG(LogPakFile, Error, TEXT("  Options:"));
		UE_LOG(LogPakFile, Error, TEXT("    -blocksize=<BlockSize>"));
		UE_LOG(LogPakFile, Error, TEXT("    -compress"));
		UE_LOG(LogPakFile, Error, TEXT("    -encrypt"));
		UE_LOG(LogPakFile, Error, TEXT("    -order=<OrderingFile>"));
		return 1;
	}

	FPakCommandLineParameters CmdLineParameters;
	int32 Result = 0;
	FString KeyFilename;
	if (FParse::Value(FCommandLine::Get(), TEXT("GenerateKeys="), KeyFilename, false))
	{
		Result = GenerateKeys(*KeyFilename) ? 0 : 1;
	}
	else if (FParse::Value(FCommandLine::Get(), TEXT("GeneratePrimeTable="), KeyFilename, false))
	{
		int64 MaxPrimeValue = 10000;
		FParse::Value(FCommandLine::Get(), TEXT("TableMax="), MaxPrimeValue);
		GeneratePrimeNumberTable(MaxPrimeValue, *KeyFilename);
	}
	else 
	{
		if (FParse::Param(FCommandLine::Get(), TEXT("Test")))
		{
			FString PakFilename = GetPakPath(ArgV[1], false);
			Result = TestPakFile(*PakFilename) ? 0 : 1;
		}
		else if (FParse::Param(FCommandLine::Get(), TEXT("List")))
		{
			FString PakFilename = GetPakPath(ArgV[1], false);
			Result = ListFilesInPak(*PakFilename);
		}
		else if (FParse::Param(FCommandLine::Get(), TEXT("Extract")))
		{
			FString PakFilename = GetPakPath(ArgV[1], false);
			if (ArgC < 4)
			{
				UE_LOG(LogPakFile, Error, TEXT("No extraction path specified."));
				Result = 1;
			}
			else
			{
				FString DestPath = (ArgV[2][0] == '-') ? ArgV[3] : ArgV[2];
				Result = ExtractFilesFromPak(*PakFilename, *DestPath) ? 0 : 1;
			}
		}
		else
		{
			// since this is for creation, we pass true to make it not look in LaunchDir
			FString PakFilename = GetPakPath(ArgV[1], true);

			// List of all items to add to pak file
			TArray<FPakInputPair> Entries;
			ProcessCommandLine(ArgC, ArgV, Entries, CmdLineParameters);
			TMap<FString, uint64> OrderMap;
			ProcessOrderFile(ArgC, ArgV, OrderMap);

			if (Entries.Num() == 0)
			{
				UE_LOG(LogPakFile, Error, TEXT("No files specified to add to pak file."));
				Result = 1;
			}
			else
			{
				if ( CmdLineParameters.GeneratePatch )
				{
					FString OutputPath = FPaths::GetPath(PakFilename) / FString(TEXT("TempFiles"));

					IFileManager::Get().DeleteDirectory(*OutputPath);

					UE_LOG(LogPakFile, Display, TEXT("Generating patch from %s."), *CmdLineParameters.SourcePatchPakFilename );

					if ( ExtractFilesFromPak( *CmdLineParameters.SourcePatchPakFilename, *OutputPath, true ) == false )
					{
						UE_LOG(LogPakFile, Error, TEXT("Unable to extract files from source pak file for patch") );
					}
					CmdLineParameters.SourcePatchDiffDirectory = OutputPath;
				}


				// Start collecting files
				TArray<FPakInputPair> FilesToAdd;
				CollectFilesToAdd(FilesToAdd, Entries, OrderMap);

				if ( CmdLineParameters.GeneratePatch )
				{
					// if we are generating a patch here we remove files which are already shipped...
					RemoveIdenticalFiles(FilesToAdd, CmdLineParameters.SourcePatchDiffDirectory);
				}


				Result = CreatePakFile(*PakFilename, FilesToAdd, CmdLineParameters) ? 0 : 1;
			}
		}
	}

	return Result;
}
Ejemplo n.º 27
0
INT_PTR CALLBACK DialogProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) {
  switch (msg) {
    case WM_INITDIALOG:
    {
      g_sdata.hwnd=hwndDlg;
      HICON hIcon = LoadIcon(g_sdata.hInstance,MAKEINTRESOURCE(IDI_ICON));
      SetClassLongPtr(hwndDlg,GCLP_HICON,(LONG_PTR)hIcon);
      // Altered by Darren Owen (DrO) on 29/9/2003
      // Added in receiving of mouse and key events from the richedit control
      SendMessage(GetDlgItem(hwndDlg,IDC_LOGWIN),EM_SETEVENTMASK,(WPARAM)NULL,ENM_SELCHANGE|ENM_MOUSEEVENTS|ENM_KEYEVENTS);
      DragAcceptFiles(g_sdata.hwnd,FALSE);
      g_sdata.menu = GetMenu(g_sdata.hwnd);
      g_sdata.fileSubmenu = FindSubMenu(g_sdata.menu, IDM_FILE);
      g_sdata.editSubmenu = FindSubMenu(g_sdata.menu, IDM_EDIT);
      g_sdata.toolsSubmenu = FindSubMenu(g_sdata.menu, IDM_TOOLS);
      RestoreMRUList();
      CreateToolBar();
      InitTooltips(g_sdata.hwnd);
      SetDlgItemText(g_sdata.hwnd,IDC_VERSION,g_sdata.branding);
      HFONT hFont = CreateFont(14,FW_NORMAL,FIXED_PITCH|FF_DONTCARE,_T("Courier New"));
      SendDlgItemMessage(hwndDlg,IDC_LOGWIN,WM_SETFONT,(WPARAM)hFont,0);
      RestoreWindowPos(g_sdata.hwnd);
      RestoreCompressor();
      SetScript(_T(""));
      g_sdata.compressor = COMPRESSOR_NONE_SELECTED;
      g_sdata.userSelectCompressor = FALSE;

      ProcessCommandLine();

      if(g_sdata.compressor == COMPRESSOR_NONE_SELECTED) {
        SetCompressor(g_sdata.default_compressor);
      }

      if(g_sdata.userSelectCompressor) {
        if (DialogBox(g_sdata.hInstance,MAKEINTRESOURCE(DLG_COMPRESSOR),g_sdata.hwnd,(DLGPROC)CompressorProc)) {
          EnableItems(g_sdata.hwnd);
          return TRUE;
        }
      }

      CompileNSISScript();
      return TRUE;
    }
    case WM_PAINT:
    {
      PAINTSTRUCT ps;
      GetGripperPos(hwndDlg, g_resize.griprect);
      HDC hdc = BeginPaint(hwndDlg, &ps);
      DrawFrameControl(hdc, &g_resize.griprect, DFC_SCROLL, DFCS_SCROLLSIZEGRIP);
      EndPaint(hwndDlg, &ps);
      return TRUE;
    }
    case WM_DESTROY:
    {
      DragAcceptFiles(g_sdata.hwnd,FALSE);
      SaveSymbols();
      SaveCompressor();
      SaveMRUList();
      SaveWindowPos(g_sdata.hwnd);
      ImageList_Destroy(g_toolbar.imagelist);
      ImageList_Destroy(g_toolbar.imagelistd);
      ImageList_Destroy(g_toolbar.imagelisth);
      DestroyTooltips();
      PostQuitMessage(0);
      return TRUE;
    }
    case WM_CLOSE:
    {
      if (!g_sdata.thread) {
        DestroyWindow(hwndDlg);
      }
      return TRUE;
    }
    case WM_DROPFILES: {
      int num;
      TCHAR szTmp[MAX_PATH];
      num = DragQueryFile((HDROP)wParam,(UINT)-1,NULL,0);
      if (num==1) {
        DragQueryFile((HDROP)wParam,0,szTmp,MAX_PATH);
        if (lstrlen(szTmp)>0) {
          SetScript(szTmp);
          PushMRUFile(g_sdata.script);
          ResetObjects();
          CompileNSISScript();
        }
      } else {
        MessageBox(hwndDlg,MULTIDROPERROR,ERRBOXTITLE,MB_OK|MB_ICONSTOP);
      }
      DragFinish((HDROP)wParam);
      break;
    }
    case WM_GETMINMAXINFO:
    {
      ((MINMAXINFO*)lParam)->ptMinTrackSize.x=MINWIDTH;
      ((MINMAXINFO*)lParam)->ptMinTrackSize.y=MINHEIGHT;
    }
    case WM_ENTERSIZEMOVE:
    {
      GetClientRect(g_sdata.hwnd, &g_resize.resizeRect);
      return TRUE;
    }
    case WM_SIZE:
    {
      if ((wParam == SIZE_MAXHIDE)||(wParam == SIZE_MAXSHOW)) return TRUE;
      RECT rSize;
      if (hwndDlg == g_sdata.hwnd) {
        GetClientRect(g_sdata.hwnd, &rSize);
        if (((rSize.right==0)&&(rSize.bottom==0))||((g_resize.resizeRect.right==0)&&(g_resize.resizeRect.bottom==0)))  return TRUE;
        g_resize.dx = rSize.right - g_resize.resizeRect.right;
        g_resize.dy = rSize.bottom - g_resize.resizeRect.bottom;
        EnumChildWindows(g_sdata.hwnd, DialogResize, (LPARAM)0);
        g_resize.resizeRect = rSize;
      }
      return TRUE;
    }
    case WM_SIZING:
    {
      InvalidateRect(hwndDlg, &g_resize.griprect, TRUE);
      GetGripperPos(hwndDlg, g_resize.griprect);
      return TRUE;
    }
    case WM_NCHITTEST:
    {
      RECT r = g_resize.griprect;
      MapWindowPoints(hwndDlg, 0, (POINT*)&r, 2);
      POINT pt = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
      if (PtInRect(&r, pt))
      {
        SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, HTBOTTOMRIGHT);
        return TRUE;
      }
      return FALSE;
    }
    case WM_MAKENSIS_PROCESSCOMPLETE:
    {
      if (g_sdata.thread) {
        CloseHandle(g_sdata.thread);
        g_sdata.thread=0;
      }
      if(g_sdata.compressor == COMPRESSOR_BEST) {
        if (g_sdata.retcode==0 && FileExists(g_sdata.output_exe)) {
          TCHAR temp_file_name[1024]; // BUGBUG: Hardcoded buffer size
          wsprintf(temp_file_name,_T("%s_makensisw_temp"),g_sdata.output_exe);
          if(!lstrcmpi(g_sdata.compressor_name,compressor_names[(int)COMPRESSOR_SCRIPT+1])) {
            SetCompressorStats();
            CopyFile(g_sdata.output_exe,temp_file_name,false);
            g_sdata.best_compressor_name = g_sdata.compressor_name;
            g_sdata.compressor_name = compressor_names[(int)COMPRESSOR_SCRIPT+2];
            ResetObjects();

            CompileNSISScript();
            return TRUE;
          }
          else {
            int this_compressor=0;
            int i;
            HANDLE hPrev, hThis;
            DWORD prevSize=0, thisSize=0;


            for(i=(int)COMPRESSOR_SCRIPT+2; i<(int)COMPRESSOR_BEST; i++) {
              if(!lstrcmpi(g_sdata.compressor_name,compressor_names[i])) {
                this_compressor = i;
                break;
              }
            }

            if(FileExists(temp_file_name)) {
              hPrev = CreateFile(temp_file_name,GENERIC_READ, FILE_SHARE_READ,
                                 NULL, OPEN_EXISTING, (DWORD)NULL, NULL);
              if(hPrev != INVALID_HANDLE_VALUE) {
                prevSize = GetFileSize(hPrev, 0);
                CloseHandle(hPrev);

                if(prevSize != INVALID_FILE_SIZE) {
                  hThis = CreateFile(g_sdata.output_exe,GENERIC_READ, FILE_SHARE_READ,
                                     NULL, OPEN_EXISTING, (DWORD)NULL, NULL);
                  if(hThis != INVALID_HANDLE_VALUE) {
                    thisSize = GetFileSize(hThis, 0);
                    CloseHandle(hThis);

                    if(thisSize != INVALID_FILE_SIZE) {
                      if(prevSize > thisSize) {
                        CopyFile(g_sdata.output_exe,temp_file_name,false);
                        SetCompressorStats();
                        g_sdata.best_compressor_name = g_sdata.compressor_name;
                      }
                    }
                  }
                }
              }
            }

            if(this_compressor == ((int)COMPRESSOR_BEST - 1)) {
              TCHAR buf[1024];

              g_sdata.compressor_name = compressor_names[(int)COMPRESSOR_SCRIPT+1];

              if(!lstrcmpi(g_sdata.best_compressor_name,compressor_names[this_compressor])) {
                wsprintf(buf,COMPRESSOR_MESSAGE,g_sdata.best_compressor_name,thisSize);
                LogMessage(g_sdata.hwnd,buf);
              }
              else {
                CopyFile(temp_file_name,g_sdata.output_exe,false);
                wsprintf(buf,RESTORED_COMPRESSOR_MESSAGE,g_sdata.best_compressor_name,prevSize);
                LogMessage(g_sdata.hwnd,buf);
                LogMessage(g_sdata.hwnd, g_sdata.compressor_stats);
              }
              DeleteFile(temp_file_name);
              lstrcpy(g_sdata.compressor_stats,_T(""));
            }
            else {
              g_sdata.compressor_name = compressor_names[this_compressor+1];
              ResetObjects();

              CompileNSISScript();
              return TRUE;
            }
          }
        }
      }
      EnableItems(g_sdata.hwnd);
      if (!g_sdata.retcode) {
        MessageBeep(MB_ICONASTERISK);
        if (g_sdata.warnings)
          SetTitle(g_sdata.hwnd,_T("Finished with Warnings"));
        else
          SetTitle(g_sdata.hwnd,_T("Finished Sucessfully"));
        // Added by Darren Owen (DrO) on 1/10/2003
        if(g_sdata.recompile_test)
          PostMessage(g_sdata.hwnd, WM_COMMAND, LOWORD(IDC_TEST), 0);
      }
      else {
        MessageBeep(MB_ICONEXCLAMATION);
        SetTitle(g_sdata.hwnd,_T("Compile Error: See Log for Details"));
      }

      // Added by Darren Owen (DrO) on 1/10/2003
      // ensures the recompile and run state is reset after use
      g_sdata.recompile_test = 0;
      DragAcceptFiles(g_sdata.hwnd,TRUE);
      return TRUE;
    }
    case MakensisAPI::QUERYHOST: {
      if (MakensisAPI::QH_OUTPUTCHARSET) {
        const UINT reqcp = 1200; // We want UTF-16LE
        SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, (LONG_PTR)(1+reqcp));
        return TRUE;
      }
      return FALSE;
    }
    case WM_NOTIFY:
      switch (((NMHDR*)lParam)->code ) {
        case EN_SELCHANGE:
          SendDlgItemMessage(hwndDlg,IDC_LOGWIN, EM_EXGETSEL, 0, (LPARAM) &g_sdata.textrange);
          {
            BOOL enabled = (g_sdata.textrange.cpMax-g_sdata.textrange.cpMin<=0?FALSE:TRUE);
            EnableMenuItem(g_sdata.menu,IDM_COPYSELECTED,(enabled?MF_ENABLED:MF_GRAYED));
            EnableToolBarButton(IDM_COPY,enabled);
          }
        // Altered by Darren Owen (DrO) on 6/10/2003
        // Allows the detection of the right-click menu when running on OSes below Windows 2000
        // and will then simulate the effective WM_CONTEXTMENU message that would be received
        // note: removed the WM_CONTEXTMENU handling to prevent a duplicate menu appearing on
        // Windows 2000 and higher
        case EN_MSGFILTER:
          #define lpnmMsg ((MSGFILTER*)lParam)
          if(WM_RBUTTONUP == lpnmMsg->msg || (WM_KEYUP == lpnmMsg->msg && lpnmMsg->wParam == VK_APPS)){
          POINT pt;
          HWND edit = GetDlgItem(g_sdata.hwnd,IDC_LOGWIN);
          RECT r;
            GetCursorPos(&pt);

            // Added and altered by Darren Owen (DrO) on 29/9/2003
            // Will place the right-click menu in the top left corner of the window
            // if the application key is pressed and the mouse is not in the window
            // from here...
            ScreenToClient(edit, &pt);
            GetClientRect(edit, &r);
            if(!PtInRect(&r, pt))
              pt.x = pt.y = 0;
            MapWindowPoints(edit, HWND_DESKTOP, &pt, 1);
            TrackPopupMenu(g_sdata.editSubmenu, TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, pt.x, pt.y, 0, g_sdata.hwnd, 0);
          }
        case TBN_DROPDOWN:
        {
          LPNMTOOLBAR pToolBar = (LPNMTOOLBAR) lParam;
          if(pToolBar->hdr.hwndFrom == g_toolbar.hwnd && pToolBar->iItem == IDM_COMPRESSOR) {
            ShowToolbarDropdownMenu();
            return TBDDRET_DEFAULT;
          }
          else {
            return TBDDRET_NODEFAULT;
          }
        }
      }
      return TRUE;
    case WM_COPYDATA:
    {
      PCOPYDATASTRUCT cds = PCOPYDATASTRUCT(lParam);
      switch (cds->dwData) {
        case MakensisAPI::NOTIFY_SCRIPT:
          MemSafeFree(g_sdata.input_script);
          g_sdata.input_script = (TCHAR*) MemAlloc(cds->cbData * sizeof(TCHAR));
          lstrcpy(g_sdata.input_script, (TCHAR *)cds->lpData);
          break;
        case MakensisAPI::NOTIFY_WARNING:
          g_sdata.warnings++;
          break;
        case MakensisAPI::NOTIFY_ERROR:
          break;
        case MakensisAPI::NOTIFY_OUTPUT:
          MemSafeFree(g_sdata.output_exe);
          g_sdata.output_exe = (TCHAR*) MemAlloc(cds->cbData * sizeof(TCHAR));
          lstrcpy(g_sdata.output_exe, (TCHAR *)cds->lpData);
          break;
      }
      return TRUE;
    }
    case WM_COMMAND:
    {
      switch (LOWORD(wParam)) {
        case IDM_BROWSESCR: {
          if (g_sdata.input_script) {
            TCHAR str[MAX_PATH],*str2;
            lstrcpy(str,g_sdata.input_script);
            str2=_tcsrchr(str,_T('\\'));
            if(str2!=NULL) *(str2+1)=0;
            ShellExecute(g_sdata.hwnd,_T("open"),str,NULL,NULL,SW_SHOWNORMAL);
          }
          return TRUE;
        }
        case IDM_ABOUT:
        {
          return DialogBox(g_sdata.hInstance,MAKEINTRESOURCE(DLG_ABOUT),hwndDlg,(DLGPROC)AboutProc);
        }
        case IDM_NSISHOME:
        {
          ShellExecuteA(g_sdata.hwnd,"open",NSIS_URL,NULL,NULL,SW_SHOWNORMAL);
          return TRUE;
        }
        case IDM_FORUM:
        {
          ShellExecuteA(g_sdata.hwnd,"open",NSIS_FOR,NULL,NULL,SW_SHOWNORMAL);
          return TRUE;
        }
        case IDM_NSISUPDATE:
        {
          Update();
          return TRUE;
        }
        case IDM_SELECTALL:
        {
          SendDlgItemMessage(g_sdata.hwnd, IDC_LOGWIN, EM_SETSEL, 0, -1);
          return TRUE;
        }
        case IDM_DOCS:
        {
          ShowDocs();
          return TRUE;
        }
        case IDM_LOADSCRIPT:
        {
          if (!g_sdata.thread) {
            OPENFILENAME l={sizeof(l),};
            TCHAR buf[MAX_PATH];
            l.hwndOwner = hwndDlg;
            l.lpstrFilter = _T("NSIS Script (*.nsi)\0*.nsi\0All Files (*.*)\0*.*\0");
            l.lpstrFile = buf;
            l.nMaxFile = MAX_STRING-1;
            l.lpstrTitle = _T("Load Script");
            l.lpstrDefExt = _T("log");
            l.lpstrFileTitle = NULL;
            l.lpstrInitialDir = NULL;
            l.Flags = OFN_HIDEREADONLY|OFN_EXPLORER|OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST;
            lstrcpy(buf,_T(""));
            if (GetOpenFileName(&l)) {
              SetScript(buf);
              PushMRUFile(g_sdata.script);
              ResetObjects();
              CompileNSISScript();
            }
          }
          return TRUE;
        }
        case IDM_MRU_FILE:
        case IDM_MRU_FILE+1:
        case IDM_MRU_FILE+2:
        case IDM_MRU_FILE+3:
        case IDM_MRU_FILE+4:
          LoadMRUFile(LOWORD(wParam)-IDM_MRU_FILE);
          return TRUE;
        case IDM_CLEAR_MRU_LIST:
          ClearMRUList();
          return TRUE;
        case IDM_COMPRESSOR:
        {
          SetCompressor((NCOMPRESSOR)(g_sdata.compressor+1));
          return TRUE;
        }
        case IDM_CLEARLOG:
        {
          if (!g_sdata.thread) {
            ClearLog(g_sdata.hwnd);
          }
          return TRUE;
        }
        case IDM_RECOMPILE:
        {
          CompileNSISScript();
          return TRUE;
        }
        // Added by Darren Owen (DrO) on 1/10/2003
        case IDM_RECOMPILE_TEST:
        {
          g_sdata.recompile_test = 1;
          CompileNSISScript();
          return TRUE;
        }
        case IDM_SETTINGS:
        {
          DialogBox(g_sdata.hInstance,MAKEINTRESOURCE(DLG_SETTINGS),g_sdata.hwnd,(DLGPROC)SettingsProc);
          return TRUE;
        }
        case IDM_TEST:
        case IDC_TEST:
        {
          if (g_sdata.output_exe) {
            ShellExecute(g_sdata.hwnd,_T("open"),g_sdata.output_exe,NULL,NULL,SW_SHOWNORMAL);
          }
          return TRUE;
        }
        case IDM_EDITSCRIPT:
        {
          if (g_sdata.input_script) {
            LPCTSTR verb = _T("open"); // BUGBUG: Should not force the open verb?
            HINSTANCE hi = ShellExecute(g_sdata.hwnd,verb,g_sdata.input_script,NULL,NULL,SW_SHOWNORMAL);
            if ((UINT_PTR)hi <= 32) {
              TCHAR path[MAX_PATH];
              if (GetWindowsDirectory(path,sizeof(path))) {
                lstrcat(path,_T("\\notepad.exe"));
                ShellExecute(g_sdata.hwnd,verb,path,g_sdata.input_script,NULL,SW_SHOWNORMAL);
              }
            }
          }
          return TRUE;
        }
        case IDCANCEL:
        case IDM_EXIT:
        {
          if (!g_sdata.thread) {
            DestroyWindow(g_sdata.hwnd);
          }
          return TRUE;
        }
        case IDM_CANCEL:
        {
          SetEvent(g_sdata.sigint_event);
          SetEvent(g_sdata.sigint_event_legacy);
          return TRUE;
        }
        case IDM_COPY:
        {
          CopyToClipboard(g_sdata.hwnd);
          return TRUE;
        }
        case IDM_COPYSELECTED:
        {
          SendDlgItemMessage(g_sdata.hwnd,IDC_LOGWIN, WM_COPY, 0, 0);
          return TRUE;
        }
        case IDM_SAVE:
        {
          OPENFILENAME l={sizeof(l),};
          TCHAR buf[MAX_STRING];
          l.hwndOwner = hwndDlg;
          l.lpstrFilter = _T("Log Files (*.log)\0*.log\0Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0");
          l.lpstrFile = buf;
          l.nMaxFile = MAX_STRING-1;
          l.lpstrTitle = _T("Save Output");
          l.lpstrDefExt = _T("log");
          l.lpstrInitialDir = NULL;
          l.Flags = OFN_HIDEREADONLY|OFN_EXPLORER|OFN_PATHMUSTEXIST;
          lstrcpy(buf,_T("output"));
          if (GetSaveFileName(&l)) {
            HANDLE hFile = CreateFile(buf,GENERIC_WRITE,0,0,CREATE_ALWAYS,0,0);
            if (INVALID_HANDLE_VALUE != hFile) {
              int len=SendDlgItemMessage(g_sdata.hwnd,IDC_LOGWIN,WM_GETTEXTLENGTH,0,0);
              TCHAR *existing_text=(TCHAR*) MemAlloc(len * sizeof(TCHAR));
              if (existing_text) { // BUGBUG:TODO: Error message for bad hFile and existing_text?
                existing_text[0]=0;
                GetDlgItemText(g_sdata.hwnd, IDC_LOGWIN, existing_text, len);
                DWORD dwWritten = 0;
                WriteFile(hFile,existing_text,len,&dwWritten,0);
                MemFree(existing_text);
              }
              CloseHandle(hFile);
            }
          }
          return TRUE;
        }
        case IDM_FIND:
        {
          if (!g_find.uFindReplaceMsg) g_find.uFindReplaceMsg = RegisterWindowMessage(FINDMSGSTRING);
          memset(&g_find.fr, 0, sizeof(FINDREPLACE));
          g_find.fr.lStructSize = sizeof(FINDREPLACE);
          g_find.fr.hwndOwner = hwndDlg;
          g_find.fr.Flags = FR_NOUPDOWN;
          g_find.fr.lpstrFindWhat = g_findbuf;
          g_find.fr.wFindWhatLen = COUNTOF(g_findbuf);
          g_find.hwndFind = FindText(&g_find.fr);
          return TRUE;
        }
        default:
          {
            int i;
            DWORD command = LOWORD(wParam);
            for(i=(int)COMPRESSOR_SCRIPT; i<=(int)COMPRESSOR_BEST; i++) {
              if(command == compressor_commands[i]) {
                SetCompressor((NCOMPRESSOR)i);
                return TRUE;
              }
            }
          }
      }
    }
  }
  if (g_find.uFindReplaceMsg && msg == g_find.uFindReplaceMsg) {
    LPFINDREPLACE lpfr = (LPFINDREPLACE)lParam;
    if (lpfr->Flags & FR_FINDNEXT) {
      WPARAM flags = FR_DOWN;
      if (lpfr->Flags & FR_MATCHCASE) flags |= FR_MATCHCASE;
      if (lpfr->Flags & FR_WHOLEWORD) flags |= FR_WHOLEWORD;
      FINDTEXTEX ft;
      SendDlgItemMessage(hwndDlg, IDC_LOGWIN, EM_EXGETSEL, 0, (LPARAM)&ft.chrg);
      if (ft.chrg.cpMax == ft.chrg.cpMin) ft.chrg.cpMin = 0;
      else ft.chrg.cpMin = ft.chrg.cpMax;
      ft.chrg.cpMax = SendDlgItemMessage(hwndDlg, IDC_LOGWIN, WM_GETTEXTLENGTH, 0, 0);
      ft.lpstrText = lpfr->lpstrFindWhat;
      ft.chrg.cpMin = SendDlgItemMessage(hwndDlg, IDC_LOGWIN, EM_FINDTEXTEX, flags, (LPARAM)&ft);
      if (ft.chrg.cpMin != -1) SendDlgItemMessage(hwndDlg, IDC_LOGWIN, EM_SETSEL, ft.chrgText.cpMin, ft.chrgText.cpMax);
      else MessageBeep(MB_ICONASTERISK);
    }
    if (lpfr->Flags & FR_DIALOGTERM) g_find.hwndFind = 0;
    return TRUE;
  }
  return 0;
}
Ejemplo n.º 28
0
int WINAPI wWinMain(
    __in HINSTANCE hInstance,
    __in_opt HINSTANCE /* hPrevInstance */,
    __in_z_opt LPWSTR lpCmdLine,
    __in int /*nCmdShow*/
    )
{
    ::HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);

    HRESULT hr = S_OK;
    BOOL fComInitialized = FALSE;
    LPWSTR sczThemeFile = NULL;
    ATOM atom = 0;
    HWND hWnd = NULL;

    HANDLE hDisplayThread = NULL;
    HANDLE hLoadThread = NULL;

    BOOL fRet = FALSE;
    MSG msg = { };

    hr = ::CoInitialize(NULL);
    ExitOnFailure(hr, "Failed to initialize COM.");
    fComInitialized = TRUE;

    hr = ProcessCommandLine(lpCmdLine, &sczThemeFile);
    ExitOnFailure(hr, "Failed to process command line.");

    hr = CreateTheme(hInstance, &vpTheme);
    ExitOnFailure(hr, "Failed to create theme.");

    hr = CreateMainWindowClass(hInstance, vpTheme, &atom);
    ExitOnFailure(hr, "Failed to create main window.");

    hWnd = ::CreateWindowExW(0, reinterpret_cast<LPCWSTR>(atom), vpTheme->sczCaption, vpTheme->dwStyle, CW_USEDEFAULT, CW_USEDEFAULT, vpTheme->nWidth, vpTheme->nHeight, HWND_DESKTOP, NULL, hInstance, NULL);
    ExitOnNullWithLastError(hWnd, hr, "Failed to create window.");

    if (!sczThemeFile)
    {
        // Prompt for a path to the theme file.
        OPENFILENAMEW ofn = { };
        WCHAR wzFile[MAX_PATH] = { };

        ofn.lStructSize = sizeof(ofn);
        ofn.hwndOwner = hWnd;
        ofn.lpstrFile = wzFile;
        ofn.nMaxFile = countof(wzFile);
        ofn.lpstrFilter = L"Theme Files\0*.thm\0XML Files\0*.xml\0All Files\0*.*\0";
        ofn.nFilterIndex = 1;
        ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
        ofn.lpstrTitle = vpTheme->sczCaption;

        if (::GetOpenFileNameW(&ofn))
        {
            hr = StrAllocString(&sczThemeFile, wzFile, 0);
            ExitOnFailure(hr, "Failed to copy opened file to theme file.");
        }
        else
        {
            ::MessageBoxW(hWnd, L"Must specify a path to theme file.", vpTheme->sczCaption, MB_OK | MB_ICONERROR);
            ExitFunction1(hr = E_INVALIDARG);
        }
    }

    hr = DisplayStart(hInstance, hWnd, &hDisplayThread, &vdwDisplayThreadId);
    ExitOnFailure(hr, "Failed to start display.");

    hr = LoadStart(sczThemeFile, hWnd, &hLoadThread);
    ExitOnFailure(hr, "Failed to start load.");

    // message pump
    while (0 != (fRet = ::GetMessageW(&msg, NULL, 0, 0)))
    {
        if (-1 == fRet)
        {
            hr = E_UNEXPECTED;
            ExitOnFailure(hr, "Unexpected return value from message pump.");
        }
        else if (!ThemeHandleKeyboardMessage(vpTheme, msg.hwnd, &msg))
        {
            ::TranslateMessage(&msg);
            ::DispatchMessageW(&msg);
        }
    }

LExit:
    if (::IsWindow(hWnd))
    {
        ::DestroyWindow(hWnd);
    }

    if (hDisplayThread)
    {
        ::PostThreadMessageW(vdwDisplayThreadId, WM_QUIT, 0, 0);
        ::WaitForSingleObject(hDisplayThread, 10000);
        ::CloseHandle(hDisplayThread);
    }

    // TODO: come up with a good way to kill the load thread, probably need to switch
    // the ReadDirectoryW() to overlapped mode.
    ReleaseHandle(hLoadThread);

    if (atom && !::UnregisterClassW(reinterpret_cast<LPCWSTR>(atom), hInstance))
    {
        DWORD er = ::GetLastError();
        er = er;
    }

    ThemeFree(vpTheme);
    ThemeUninitialize();

    // uninitialize COM
    if (fComInitialized)
    {
        ::CoUninitialize();
    }

    ReleaseStr(sczThemeFile);
    return hr;
}
Ejemplo n.º 29
0
/*
 * WindowProc - main window message handler
 */
LONG CALLBACK MainWindowProc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
{
    WORD                        cmd;
    about_info                  ai;
    HMENU                       mh;
    CommunicationBuffer         *dbginfo;

    switch ( msg ) {
    case WM_CREATE:
        setupSystemMenu( hwnd );
        MainLBox = CreateListBox( hwnd );
        mh = GetMenu( hwnd );
        if( ConfigData.auto_attatch ) {
            CheckMenuItem( mh, MENU_AUTO_ATTATCH, MF_BYCOMMAND | MF_CHECKED );
        }
        if( ConfigData.continue_exception ) {
            CheckMenuItem( mh, MENU_EXCEPTION_CONTINUE,
                                MF_BYCOMMAND | MF_CHECKED );
        }
        LBPrintf( MainLBox, STR_DRNT_STARTED, AppName );
        break;
    case WM_SIZE:
        MoveListBox( MainLBox, 0, 0, LOWORD( lparam ), HIWORD( lparam ) );
        ClearAlert();
        break;
    case WM_SYSCOMMAND:
        switch( wparam ) {
        case MENU_LOG_CURRENT_STATE:
        case MENU_LOG_OPTIONS:
        case MENU_TASK_CTL:
            SendMessage( hwnd, WM_COMMAND, wparam, 0 );
            break;
        default:
            return( DefWindowProc( hwnd, msg, wparam, lparam ) );
        }
        break;
    case WM_COMMAND:
        cmd = LOWORD( wparam );
        switch( cmd ) {
        case LISTBOX_1:
            break;
        case MENU_EXCEPTION_CONTINUE:
            ConfigData.continue_exception = !ConfigData.continue_exception;
            mh = GetMenu( hwnd );
            if( ConfigData.continue_exception ) {
                CheckMenuItem( mh, MENU_EXCEPTION_CONTINUE,
                                   MF_BYCOMMAND | MF_CHECKED );
            } else {
                CheckMenuItem( mh, MENU_EXCEPTION_CONTINUE,
                                   MF_BYCOMMAND | MF_UNCHECKED );
            }
            break;
        case MENU_LOG_VIEW:
            ViewLog();
            break;
        case MENU_NEW_TASK:
            CallProcCtl( MENU_NEW_TASK, NULL, NULL );
            break;
        case MENU_AUTO_ATTATCH:
            ConfigData.auto_attatch = ! ConfigData.auto_attatch;
            mh = GetMenu( hwnd );
            if( ConfigData.auto_attatch ) {
                CheckMenuItem( mh, MENU_AUTO_ATTATCH,
                               MF_BYCOMMAND | MF_CHECKED );
            } else {
                CheckMenuItem( mh, MENU_AUTO_ATTATCH,
                               MF_BYCOMMAND | MF_UNCHECKED );
            }
            break;
        case MENU_SHOW_DIP_STATUS:
            ShowDIPStatus( hwnd );
            break;
        case MENU_CLEAR:
            ClearListBox( MainLBox );
            break;
        case MENU_SAVE_AS:
            SaveListBox( SLB_SAVE_AS, SaveExtra, "", AppName, hwnd,
                         GetListBoxHwnd( MainLBox ) );
            break;
        case MENU_SAVE:
            SaveListBox( SLB_SAVE_TMP, SaveExtra, ".\\drwat.txt", AppName,
                         hwnd, GetListBoxHwnd( MainLBox ) );
            break;
        case MENU_FONT:
            if( ChooseMonoFont( hwnd ) ) {
                SetListBoxFont( MainLBox );
            }
            break;
        case MENU_MARK:
            ProcessMark( hwnd, Instance, MarkPrint );
            break;
        case MENU_ABOUT:
            ai.owner = hwnd;
            ai.inst = Instance;
            ai.name = AllocRCString( STR_ABOUT_NAME );
            ai.version = AllocRCString( STR_ABOUT_VERSION );
            ai.first_cr_year = "1993";
            ai.title = AllocRCString( STR_ABOUT_TITLE );
            DoAbout( &ai );
            FreeRCString( ai.name );
            FreeRCString( ai.version );
            FreeRCString( ai.title );
            break;
        case MENU_HELP_CONTENTS:
            if( !WHtmlHelp( hwnd, DR_CHM_FILE, HELP_CONTENTS, 0 ) ) {
                WWinHelp( hwnd, DR_HELP_FILE, HELP_CONTENTS, 0 );
            }
            break;
        case MENU_HELP_SRCH:
            if( !WHtmlHelp( hwnd, DR_CHM_FILE, HELP_PARTIALKEY, (HELP_DATA)"" ) ) {
                WWinHelp( hwnd, DR_HELP_FILE, HELP_PARTIALKEY, (HELP_DATA)"" );
            }
            break;
        case MENU_HELP_ON_HELP:
            WWinHelp( hwnd, HELP_HELP_FILE, HELP_HELPONHELP, 0 );
            break;
        case MENU_TASK_CTL:
            DisplayProcList();
            break;
        case MENU_LOG_CURRENT_STATE:
            MakeLog( NULL );
            break;
        case MENU_ERASE_LOG_FILE:
            EraseLog();
            break;
        case MENU_LOG_OPTIONS:
            SetLogOptions( hwnd );
            break;
        case MENU_EXIT:
            SendMessage( hwnd, WM_CLOSE, 0, 0L );
            break;
        default:
            MessageBox( hwnd, "This function is not yet available",
                        AppName, MB_OK );
            break;
        }
        break;
    case DR_DEBUG_EVENT:
        dbginfo = (CommunicationBuffer *)lparam;
        dbginfo->action = DebugEventHandler( &dbginfo->dbginfo );
        break;
    case WM_COPYDATA:
        {
            COPYDATASTRUCT      *copydata;

            copydata = (COPYDATASTRUCT *)lparam;
            ProcessCommandLine( copydata->lpData );
        }
        break;
    case WM_CLOSE:
        if( QueryEnd( hwnd ) ) {
            SendMessage( hwnd, WM_DESTROY, 0, 0L );
        }
        break;
    case WM_DESTROY:
        FiniListBox( MainLBox );
        PutProfileInfo();
        DestroyMonoFonts();
        WWinHelp( hwnd, DR_HELP_FILE, HELP_QUIT, 0 );
        PostQuitMessage( 0 );
        break;
    default:
        return( DefWindowProc( hwnd, msg, wparam, lparam ) );
    }
    return( 0L );

} /* WindowProc */
Ejemplo n.º 30
0
int main (int argument_count, char* argument_list[])
{
    struct tsdef_def_error_list def_errors;
    char*                       program_directory;
    char*                       program_path;
    int                         error;
    errno_t                     std_error;

    signal(SIGINT, NullSignalHandler);

    printf(
           "\n"
           "Launching Trigger Script Interpreter\n"
           "------------------------------------\n"
          );

    TSUtil_InitializePathCollection(&tsi_search_paths);

    error = TSUtil_AppendPath(".", &tsi_search_paths);
    if(error != TSUTIL_ERROR_NONE)
    {
        printf("\nAn unexpected error has occurred and the interpretter must now exit\n");

        goto append_path_failed;
    }

    TSDef_InitializeModule(&tsi_module);

    tsi_unit_invocation = NULL;
    tsi_set_variables   = NULL;
    tsi_flags           = 0;

    error = ProcessCommandLine(argument_count, argument_list);
    if(error < 0)
        goto process_command_line_failed;
    else if(error > 0)
        goto exit_gracefully;

    if(tsi_unit_invocation == NULL)
    {
        printf("\nNo function was specified, please invoke the interpretter with a function to be executed\n");

        goto no_unit_specified;
    }

#ifdef PLATFORM_WIN32
    std_error = _get_pgmptr(&program_path);
    if(std_error != 0)
        goto get_program_path_failed;

    program_directory = strdup(program_path);
    if(program_directory == NULL)
    {
        printf("\nAn unexpected error has occurred and the interpretter must now exit\n");

        goto allocate_program_directory_failed;
    }

    program_path = strrchr(program_directory, '\\');
    if(program_path != NULL)
        *program_path = 0;
#else
    #error "Unsupported platform"
#endif

    error = TSI_RegisterFFI(program_directory, &tsi_module);

    free(program_directory);

    if(error != TSI_ERROR_NONE)
    {
        printf("\nAn unexpected error has occurred and the interpretter must now exit\n");

        goto register_ffi_failed;
    }

    printf("\n");

    TSDef_InitializeDefErrorList(&def_errors);

    printf("Compiling trigger script...\n");

    error = TSUtil_CompileUnit(
                               tsi_unit_invocation,
                               0,
                               &tsi_search_paths,
                               TSI_SOURCE_EXTENSION,
                               &NotifyLookup,
                               &def_errors,
                               &tsi_module
                              );
    if(error != TSDEF_ERROR_NONE)
    {
        if(error == TSUTIL_ERROR_COMPILATION_ERROR || error == TSUTIL_ERROR_COMPILATION_WARNING)
            TSI_ReportDefErrors(&def_errors);
        else
            printf("An unexpected error has while trying to parse the unit\n");

        if(error != TSUTIL_ERROR_COMPILATION_WARNING)
            goto compilation_failed;
    }

    TSDef_DestroyDefErrorList(&def_errors);

    printf("Compilation successful\n");

    if(!(tsi_flags&TSI_FLAG_COMPILE_ONLY))
    {
        printf("\n");

        if(error == TSUTIL_ERROR_COMPILATION_WARNING)
        {
            int pressed_char;

            printf("Warnings were encountered, run anyways? (y/n)> ");

            do
            {
                pressed_char = getch();
                pressed_char = tolower(pressed_char);

                if(isalpha(pressed_char))
                    putchar(pressed_char);
            }while(pressed_char != 'y' && pressed_char != 'n');

            printf("\n");

            if(pressed_char == 'y')
                error = TSUTIL_ERROR_NONE;
        }

        if(error == TSUTIL_ERROR_NONE)
        {
            struct tsint_controller_data controller;
            struct tsint_execif_data     execif;

            controller.function  = &TSI_Controller;
            controller.user_data = NULL;

            execif.execif    = &tsi_execif;
            execif.user_data = NULL;

            printf("Executing trigger script...\n");

            error = TSInt_AllocAbortSignal(&abort_signal);
            if(error != TSINT_ERROR_NONE)
            {
                printf("\nAn unexpected error has occurred and the interpretter must now exit\n");

                goto alloc_abort_signal_failed;
            }

            signal(SIGINT, AbortSignalHandler);

            error = TSInt_InterpretModule(
                                          &tsi_module,
                                          NULL,
                                          NULL,
                                          &controller,
                                          &execif,
                                          abort_signal
                                         );
            if(error != TSINT_ERROR_NONE)
                printf("Trigger script halted due to exception\n");

            signal(SIGINT, NullSignalHandler);

            TSInt_FreeAbortSignal(abort_signal);
        }
    }

exit_gracefully:
    DestroyVariables();
    TSDef_DestroyModule(&tsi_module);
    TSUtil_DestroyPathCollection(&tsi_search_paths);

    return 0;

compilation_failed:
    TSDef_DestroyDefErrorList(&def_errors);
alloc_abort_signal_failed:
register_ffi_failed:
allocate_program_directory_failed:
get_program_path_failed:
process_command_line_failed:
    DestroyVariables();
no_unit_specified:
    TSDef_DestroyModule(&tsi_module);
append_path_failed:
    TSUtil_DestroyPathCollection(&tsi_search_paths);

    return -1;
}