コード例 #1
0
ファイル: protocol.c プロジェクト: begoon/stuff
int serveconnection(int sockfd)
{
	FILE *in;
	char tempdata[8192], *ptr, *ptr2, *host_ptr1, *host_ptr2;
	char tempstring[8192], mimetype[50];
	char filename[255];
	unsigned int loop=0, flag=0;
	int numbytes=0;
	struct sockaddr_in sa;
	int addrlen = sizeof(struct sockaddr_in);
	t_vhost *thehost;
	
	thehost = &defaulthost;

// tempdata is the full header, tempstring is just the command

	while(!strstr(tempdata, "\r\n\r\n") && !strstr(tempdata, "\n\n"))
	{	
		if((numbytes=recv(sockfd, tempdata+numbytes, 4096-numbytes, 0))==-1)
			return -1;
	}
	for(loop=0; loop<4096 && tempdata[loop]!='\n' && tempdata[loop]!='\r'; loop++)
		tempstring[loop] = tempdata[loop];
	
	tempstring[loop] = '\0';
	ptr = strtok(tempstring, " ");
	if(ptr == 0) return -1;
	if(strcmp(ptr, "GET")) 
	{
		strcpy(filename, SERVERROOT);
		strcat(filename, "/cmderror.html");
		goto sendpage;
	}
	ptr = strtok(NULL, " ");
	if(ptr == NULL)
	{
		strcpy(filename, SERVERROOT);
		strcat(filename, "/cmderror.html");
		goto sendpage;
	}

	host_ptr1 = strstr(tempdata, "Host:");
	if(host_ptr1)
	{
		host_ptr2 = strtok(host_ptr1+6, " \r\n\t");
		
		for(loop=0; loop<no_vhosts; loop++)
                        if(!gstricmp(vhosts[loop].host, host_ptr2))
				thehost = &vhosts[loop];
	}	
	else
		thehost = &defaulthost;
	if(strstr(ptr, "/.."))
	{
		strcpy(filename, SERVERROOT);
		strcat(filename, "/404.html");
		goto sendpage;
	}

	getpeername(sockfd, (struct sockaddr *)&sa, &addrlen);
	Log("Connection from %s, request = \"GET %s\"", inet_ntoa(sa.sin_addr), ptr);

	if(!strncmp(ptr, thehost->CGIBINDIR, strlen(thehost->CGIBINDIR)))
	{/* Trying to execute a cgi-bin file ? lets check */
		ptr2 = strstr(ptr, "?");
		if(ptr2!=NULL) { ptr2[0] = '\0'; flag = 1; }

		strcpy(filename, thehost->CGIBINROOT);
		ptr += strlen(thehost->CGIBINDIR);
		strcat(filename, ptr);

		// Filename = program to execute
		// ptr = filename in cgi-bin dir
		// ptr2+1 = parameters

		if(does_file_exist(filename)==TRUE && isDirectory(filename)==FALSE)
		{
			if(send(sockfd, "HTTP/1.1 200 OK\n", 16, 0)==-1)
			{
				fclose(in);
				return -1;
			}
			if(send(sockfd, "Server: "SERVERNAME"\n", strlen("Server: "SERVERNAME"\n"), 0)==-1)
			{
				fclose(in);
				return -1;
			}
			
			// Is a CGI-program that needs executing
                       //if(0 != dup2(sockfd, 0) || 1 != dup2(sockfd, 1))
                       //      return -1;

			setbuf(stdin, 0);
			setbuf(stdout, 0);
                        if(flag==1) SetEnvironmentVariable("QUERY_STRING", ptr2+1);
			
                        SetCurrentDirectory(thehost->CGIBINROOT);
			
                        WinExec(filename, SW_HIDE);
		}
		strcpy(filename, SERVERROOT);
		strcat(filename, "/cgierror.html");
		goto sendpage;
	}	

	strcpy(filename, thehost->DOCUMENTROOT);
	strcat(filename, ptr);
	      
	if(does_file_exist(filename)==FALSE)
	{		
		if(filename[strlen(filename)-1] == '/')
			strcat(filename, thehost->DEFAULTPAGE);
		else
		{
			strcat(filename, "/");
			strcat(filename, thehost->DEFAULTPAGE);
		}
		if(does_file_exist(filename) == FALSE)
		{
			filename[strlen(filename)-strlen(thehost->DEFAULTPAGE)-1] = '\0'; // Get rid of the /index.. 
                        if(isDirectory(filename) == TRUE) { showdir(filename, sockfd, thehost, ptr); return 0; }
	
			// File does not exist, so we need to display the 404 error page..
			strcpy(filename, SERVERROOT);
			strcat(filename, "/404.html");
		}	
	
	}
sendpage:
	if((in = fopen(filename, "rb"))==NULL)
		return -1;
	
	fseek(in, 0, SEEK_END);
	
	if(send(sockfd, "HTTP/1.1 200 OK\n", 16, 0)==-1)
	{
		fclose(in);
		return -1;
	}
	if(send(sockfd, "Server: "SERVERNAME"\n", strlen("Server: "SERVERNAME"\n"), 0)==-1)
	{
		fclose(in);
		return -1;
	}
	sprintf(tempstring, "Content-Length: %d\n", ftell(in));
	if(send(sockfd, tempstring, strlen(tempstring), 0)==-1)
	{
		fclose(in);
		return -1;
	}

	getmimetype(filename, mimetype);
	sprintf(tempstring, "Content-Type: %s\n\n", mimetype);
	if(send(sockfd, tempstring, strlen(tempstring), 0)==-1)
	{
		fclose(in);
		return -1;
	}
	
	fseek(in, 0, SEEK_SET);

	while(!feof(in))
	{
		numbytes = fread(tempdata, 1, 1024, in);
		if(send(sockfd, tempdata, numbytes, 0)==-1)
		{
			fclose(in);
			return -1;
		}
	}
	fclose(in);

        closesocket(sockfd); 
	return 0;
}
コード例 #2
0
ファイル: WipeFree.cpp プロジェクト: xfxf123444/japan
void CWipeFree::OnDmWipe() 
{
	LVITEM				lvitem;
	int					nSel;
	int					i;
	YG_PARTITION_INFO	*pTargetParInfo = NULL;
	CWipeProc			WipeProcDlg;
	BOOL				bSel = FALSE;
	CString				cstr,csCaption;
	TCHAR				szCurDir[MAX_PATH];
	TCHAR				szDir[32];

	UpdateData(TRUE);
	g_bBeepOff = m_BeepOff.GetCheck();

	nSel = m_SelMothed.GetCurSel ();
	g_nWipeMothed = nSel;

	csCaption.LoadString (IDS_DM_ERROR);

	lvitem.mask = LVIF_IMAGE;
	lvitem.iSubItem = 0;
	
	for(i = 0; i < m_WipeParList.GetItemCount (); i++) 
	{
		lvitem.iItem = i;
		m_WipeParList.GetItem(&lvitem);
		if(lvitem.iImage == IMG_LIST_SELECT) 
		{
			pTargetParInfo		= (YG_PARTITION_INFO*)m_WipeParList.GetItemData (i);
			g_pTargetParInfo	= pTargetParInfo;
			bSel				= TRUE;
			break;
		}
	}
	if(bSel)
	{
		if(g_pTargetParInfo->DriveLetter == _T('*'))
		{
			cstr.LoadString (IDS_Q_FORMAT_PARTITION);
			csCaption.LoadString (IDS_DM_INFO);
			MessageBox(cstr,csCaption,MB_OK);
			return ;
		}
		ZeroMemory(szDir, 32  * sizeof(TCHAR));
		_tcscpy(szDir,_T("C:\\"));
		szDir[0] = g_pTargetParInfo->DriveLetter;
		GetCurrentDirectory(MAX_PATH,szCurDir);
		if(!SetCurrentDirectory(szDir))
		{
			cstr.LoadString (IDS_Q_FORMAT_PARTITION);
			csCaption.LoadString (IDS_DM_INFO);
			MessageBox(cstr,csCaption,MB_OK);
			return ;
		}
		SetCurrentDirectory(szCurDir);
		cstr.Format (IDS_CONFIRM_WIPE_FREE,g_pTargetParInfo->DriveLetter);
		csCaption.LoadString (IDS_DM_CONFIRM_CAPTITION);
		if(IDYES == MessageBox (cstr,csCaption,MB_YESNO))
		{
			WipeProcDlg.m_DriveLetter = g_pTargetParInfo->DriveLetter;
			if (!g_bBeepOff) Beep(1000,100);
			WipeProcDlg.DoModal ();
		}

	}
}
コード例 #3
0
////////////////////////////
// Unpack plugins to 0.csx, 1.csx etc.
bool CRuntime::UnpackPlugins(int startresource)
{
	// Store the old current directory, but look for DLLs for plugin loading etc in the temp directory
	char oldCurrentDirectory[MAX_PATH];
	GetCurrentDirectory(MAX_PATH, oldCurrentDirectory);
	SetCurrentDirectory(tempDir);

	// Get number of plugins
	char strbuf[256];

	if (LoadString(GetModuleHandle(NULL), IDS_numPlugins, strbuf, 256) == 0)
		throw runtime_error("Error unpacking resources (1)");

	numPlugins = atoi(strbuf);

	// If over 1000 plugins or negative, probably undefined string - show error
	if (numPlugins < 0 || numPlugins > 1000)
		throw runtime_error("Error unpacking resources (2)");

	// Loop all plugin resources
	for (int i = 0; i < numPlugins; i++) 
	{
		CString curFile;
		curFile.Format("%s%d.csx", tempDir, i);

		// Create the file for writing
		FILE* f = fopen(CSTR(curFile), "wb");

		if (f == NULL) {
			CString msg;
			msg.Format("Error unpacking resources (3): could not create file %s (%d)", curFile, errno);
			throw runtime_error((const char*)msg);
		}

		// Get the resource data
		HRSRC resLoad = FindResource(NULL, MAKEINTRESOURCE(startresource + i), "DLLBLOCK");

		int e = GetLastError();
		CString s; s.Format("Error unpacking resources (4): %d", e);

		if (resLoad == NULL) throw runtime_error((const char*)s);

		HGLOBAL resData = LoadResource(NULL, resLoad);
		LPCSTR dllData = (LPCSTR)LockResource(resData);

		// Write the resource data to disk
		fwrite(dllData, 1, SizeofResource(NULL, resLoad), f);
		fclose(f);
		FreeResource(resData);

		// Load up this module
		PluginModule plugin;
		plugin.module = LoadLibrary(CSTR(curFile));

		if (plugin.module == NULL) {
			CString msg;
			msg.Format("Failed to load plugin %s (%d)", curFile, GetLastError());
			throw runtime_error((const char*)msg);
		}

		//DWORD e = GetLastError();

		// Get proc addresses
		plugin.RTCreateObject = (LPRTCREATEOBJECT)GetProcAddress(plugin.module, "RTCreateObject");
		plugin.RTDestroyObject = (LPRTDESTROYOBJECT)GetProcAddress(plugin.module, "RTDestroyObject");
		plugin.RTWindowProc = (PLUGINWNDPROC)GetProcAddress(plugin.module, "RTWindowProc");

		// Initialise
		LPRTDLLLOAD RTDllLoad = (LPRTDLLLOAD)GetProcAddress(plugin.module, "RTDllLoad");

		// Handle vectors
		PluginModuleVectors emv;
		pluginvecs.push_back(emv);
		PluginModuleVectors* pv = &(pluginvecs.back());

		MicroAceTool mat(&(pv->CndRoutines), &(pv->ActRoutines), &(pv->ExpRoutines), &(pv->ExpNames));
	
		// Load vectors
		plugin.ideFlags = RTDllLoad(&mat);

		// Get the plugin routine tables
		plugin.pvCndRoutines = &(pv->CndRoutines);
		plugin.pvActRoutines = &(pv->ActRoutines);
		plugin.pvExpRoutines = &(pv->ExpRoutines);
		plugin.pvExpNames = &(pv->ExpNames);

		// Make all expression names lowercase
		vector<CString>::iterator j;
		for (j = plugin.pvExpNames->begin(); j != plugin.pvExpNames->end(); j++)
			j->MakeLower();
		
		// Add to plugins list
		plugins.push_back(plugin);
	}

	// Restore current directory
	SetCurrentDirectory(oldCurrentDirectory);

	return true;
}
コード例 #4
0
ファイル: pioctl_nt.c プロジェクト: bagdxk/openafs
/* take a path with a drive letter, possibly relative, and return a full path
 * without the drive letter.  This is the full path relative to the working
 * dir for that drive letter.  The input and output paths can be the same.
 */
static long
fs_GetFullPath(char *pathp, char *outPathp, long outSize)
{
    char tpath[1000];
    char origPath[1000];
    char *firstp;
    long code;
    int pathHasDrive;
    int doSwitch;
    char newPath[3];
    char * p;
    int save;

    if (pathp[0] != 0 && pathp[1] == ':') {
	/* there's a drive letter there */
	firstp = pathp + 2;
	pathHasDrive = 1;
    } else {
	firstp = pathp;
	pathHasDrive = 0;
    }

    if ( firstp[0] == '\\' && firstp[1] == '\\' ||
	 firstp[0] == '/' && firstp[1] == '/') {
        /* UNC path - strip off the server and sharename */
        int i, count;
        for ( i=2,count=2; count < 4 && firstp[i]; i++ ) {
            if ( firstp[i] == '\\' || firstp[i] == '/' ) {
                count++;
            }
        }
        if ( firstp[i] == 0 ) {
            strcpy(outPathp,"\\");
        } else {
            strcpy(outPathp,&firstp[--i]);
        }
	for (p=outPathp ;*p; p++) {
	    if (*p == '/')
		*p = '\\';
	}
        return 0;
    } else if (firstp[0] == '\\' || firstp[0] == '/') {
        /* already an absolute pathname, just copy it back */
        strcpy(outPathp, firstp);
	for (p=outPathp ;*p; p++) {
	    if (*p == '/')
		*p = '\\';
	}
        return 0;
    }

    GetCurrentDirectory(sizeof(origPath), origPath);

    doSwitch = 0;
    if (pathHasDrive && (*pathp & ~0x20) != (origPath[0] & ~0x20)) {
	/* a drive has been specified and it isn't our current drive.
	 * to get path, switch to it first.  Must case-fold drive letters
	 * for user convenience.
	 */
	doSwitch = 1;
	newPath[0] = *pathp;
	newPath[1] = ':';
	newPath[2] = 0;
	if (!SetCurrentDirectory(newPath)) {
	    code = GetLastError();

            if ( IoctlDebug() ) {
                save = errno;
                fprintf(stderr, "pioctl fs_GetFullPath SetCurrentDirectory(%s) failed: 0x%X\r\n",
                         newPath, code);
                errno = save;
            }
	    return code;
	}
    }

    /* now get the absolute path to the current wdir in this drive */
    GetCurrentDirectory(sizeof(tpath), tpath);
    if (tpath[1] == ':')
        strcpy(outPathp, tpath + 2);	/* skip drive letter */
    else if ( tpath[0] == '\\' && tpath[1] == '\\'||
	      tpath[0] == '/' && tpath[1] == '/') {
        /* UNC path - strip off the server and sharename */
        int i, count;
        for ( i=2,count=2; count < 4 && tpath[i]; i++ ) {
            if ( tpath[i] == '\\' || tpath[i] == '/' ) {
                count++;
            }
        }
        if ( tpath[i] == 0 ) {
            strcpy(outPathp,"\\");
        } else {
            strcpy(outPathp,&tpath[--i]);
        }
    } else {
        /* this should never happen */
        strcpy(outPathp, tpath);
    }

    /* if there is a non-null name after the drive, append it */
    if (*firstp != 0) {
        int len = (int)strlen(outPathp);
        if (outPathp[len-1] != '\\' && outPathp[len-1] != '/')
            strcat(outPathp, "\\");
        strcat(outPathp, firstp);
    }

    /* finally, if necessary, switch back to our home drive letter */
    if (doSwitch) {
	SetCurrentDirectory(origPath);
    }

    for (p=outPathp ;*p; p++) {
	if (*p == '/')
	    *p = '\\';
    }
    return 0;
}
コード例 #5
0
ファイル: sexe.c プロジェクト: buzz26/toyBox
//
//	サービスとして起動したかチェック
//	実行ファイルのディレクトリと、カレントディレクトリを比較
//	out: TRUE .. サービスとして起動したと思われる
//
BOOL check_execute_service(void)
{
	TCHAR current_path[MAX_PATH];
	OSVERSIONINFO ovi;
	SC_HANDLE scm, sc;
	SERVICE_STATUS st;
	DWORD size;
	LPQUERY_SERVICE_CONFIG qsc;

	nt_flag = FALSE;
	service_install_flag = FALSE;
	service_stop_flag = FALSE;
	ovi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
	GetVersionEx(&ovi);
	if(ovi.dwPlatformId == VER_PLATFORM_WIN32_NT) {
		nt_flag = TRUE;
		GetCurrentDirectory(MAX_PATH, current_path);
		// 実行ファイルのパスとカレントパスが違う場合、
		// サービスとして起動されたと判定。
		// 起動ドライブのルートにこのプログラムが置かれてたり、
		// CreateProcess で違うディレクトリで起動されるとまずい
		// ような気がする。まあ大丈夫でしょう。いいかげん。
		if(_tcsicmp(execute_path, current_path)) {
			SetCurrentDirectory(execute_path);
			return TRUE;
		}
		// サービスインストールチェック
		if(scm = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE)) {
			if(sc = OpenService(scm, service_name, SERVICE_ALL_ACCESS)) {
				// サービスインストール済み
				service_install_flag = TRUE;
				// 2004/8/9
				QueryServiceConfig(sc, 0, 0, &size);
				qsc = (LPQUERY_SERVICE_CONFIG)LocalAlloc(LPTR, size);
				QueryServiceConfig(sc, qsc, size, &size);
				if(qsc->dwStartType == SERVICE_AUTO_START) {
					auto_flag = 1;
				} else if(qsc->dwStartType == SERVICE_DEMAND_START) {
					auto_flag = 0;
				}
				if(qsc->dwServiceType & SERVICE_INTERACTIVE_PROCESS) {
					desktop_flag = 1;
				} else {
					desktop_flag = 0;
				}
				LocalFree(qsc);
				if(QueryServiceStatus(sc, &st)) {
					if(st.dwCurrentState != SERVICE_STOPPED) {
						service_stop_flag = TRUE;
					}
					ControlService(sc, SERVICE_CONTROL_STOP, &st);
					Sleep(500);
				} else {
					// サービスを停止できません。\nサービスの権限のあるユーザーでログインしてください。
					MessageBoxResourceText(NULL, IDS_ERROR_STOP_SERVICE, NULL, ERROR_HEADER, MB_OK);
				}
				CloseServiceHandle(sc);
			}
			CloseServiceHandle(scm);
		}
	}
	return FALSE;
}
コード例 #6
0
ファイル: mainwindow.cpp プロジェクト: alexgaiv/lib3d
void MainWindow::OnCreate()
{
	glewInit();

	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);
	glEnable(GL_MULTISAMPLE);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glClearColor(0.82f, 0.85f, 0.96f, 1.0f);

	const char *sides[6] =
	{
		"textures/skybox/ft.tga",
		"textures/skybox/bk.tga",
		"textures/skybox/up.tga",
		"textures/skybox/dn.tga",
		"textures/skybox/lf.tga",
		"textures/skybox/rt.tga",
	};

	skybox = new Skybox(m_rc, sides);
	mainShader = new ProgramObject(m_rc, "shaders/main.vert.glsl", "shaders/main.frag.glsl");
	gun = new Model(m_rc);
	muzzle_flash = new Model(m_rc);
	crosshair = new Model(m_rc);
	sponza = new Model(m_rc);

	Font2D font("fonts/font.fnt");
	font.SetColor(Color4f(1));
	text = new Text2D(m_rc, font);
	
	char dir[MAX_PATH] = "";
	GetCurrentDirectory(MAX_PATH, dir);
	SetCurrentDirectory("sponza_obj");
	sponza->LoadRaw("sponza.raw");
	sponza->shader = *mainShader;
	sponza->scale = Vector3f(0.2f);
	SetCurrentDirectory(dir);

	gun->LoadRaw("models/gun.raw");
	gun->shader = *mainShader;
	gun->location = Vector3f(0.7f, -2.0f, -2.0f);
	gun->scale = Vector3f(-1, 1, -1);

	muzzle_flash->LoadRaw("models/quad.raw");
	muzzle_flash->meshes[0].material = *m_rc->materials("materials.mtl", "muzzle");
	muzzle_flash->shader = *mainShader;
	muzzle_flash->location = Vector3f(0.72f, -0.26f, -3.5f);

	crosshair->AddMesh(muzzle_flash->meshes[0]);
	crosshair->meshes[0].material = *m_rc->materials("materials.mtl", "crosshair");
	crosshair->shader = *mainShader;
	crosshair->scale = Vector3f(4.0f);

	for (int i = 0, n = sponza->meshes.size(); i < n; i++) {
		sponza->meshes[i].ComputeBoundingBox();
	}

	mainShader->Uniform("ColorMap", 0);
	mainShader->Uniform("NormalMap", 1);
	mainShader->Uniform("SpecularMap", 2);
	mainShader->Uniform("OpacityMask", 4);

	camera.SetPosition(0, 20, 0);
	camera.RotateY(90);
	camera.MoveZ(-40);
	camera.SetType(CAM_FREE);
}
コード例 #7
0
ファイル: packetparser.cpp プロジェクト: vden/PacketParser
PacketParser::PacketParser(string path) {
#ifdef WIN32
	//flist list = {0, 0, NULL};
	HANDLE fh;
	HMODULE h;
	WIN32_FIND_DATA info;
	int i;

	SetCurrentDirectory(path.c_str());
	// build a list of files
	fh = FindFirstFile("libparse*.*", &info);
	if (fh != INVALID_HANDLE_VALUE) {
		do {
			h = LoadLibrary(info.cFileName);

			parse_fn fn;
			fn = (parse_fn)GetProcAddress(h, "parse");
			proto_fn proto;
			proto = (proto_fn)GetProcAddress(h, "proto");
			tags_fn tags;
			tags = (tags_fn)GetProcAddress(h, "tags");
			find_fn find;
			find = (find_fn)GetProcAddress(h, "findProto");

#else // WIN32
	void* h;
	DIR *dp;
	struct dirent *dir;
	if((dp = opendir(path.c_str())) == NULL) {
		cerr << "Error opening " << path << endl;
	}

	while ((dir = readdir(dp)) != NULL) {
		if (strncmp(dir->d_name, "libparse", 8))
			continue;

		h = dlopen(dir->d_name, RTLD_LAZY);
		if (!h) {
			cerr << "LOAD ERR: " << dlerror() << endl;
		}

		parse_fn fn;
		fn = (parse_fn)dlsym(h, "parse");
		proto_fn proto;
		proto = (proto_fn)dlsym(h, "proto");
		tags_fn tags;
		tags = (tags_fn)dlsym(h, "tags");
		find_fn find;
		find = (find_fn)dlsym(h, "findProto");

#endif //WIN32

		cout << "Proto loaded: " << proto() << endl;

		vector<string> ds = tags();
		vector<string>::iterator it;

		for (it = ds.begin(); it != ds.end(); it++) {
			Tags::instance().add_tag(proto() + "." + *it);
		};

		parse_fns[proto()] = fn;
		find_fns[proto()] = find;

		handles.push_back(h);

#ifdef WIN32
	} while (FindNextFile(fh, &info));
	FindClose(fh);
}
#else
	}
	closedir(dp);
#endif
	parse_fns["test"] = test_parse_fn;
}
コード例 #8
0
ファイル: cmdproxy.c プロジェクト: aixoss/emacs
int
main (int argc, char ** argv)
{
  int rc;
  int need_shell;
  char * cmdline;
  char * progname;
  int envsize;
  char **pass_through_args;
  int num_pass_through_args;
  char modname[MAX_PATH];
  char path[MAX_PATH];
  char dir[MAX_PATH];
  int status;

  interactive = TRUE;

  SetConsoleCtrlHandler ((PHANDLER_ROUTINE) console_event_handler, TRUE);

  if (!GetCurrentDirectory (sizeof (dir), dir))
    fail ("error: GetCurrentDirectory failed\n");

  /* We serve double duty: we can be called either as a proxy for the
     real shell (that is, because we are defined to be the user shell),
     or in our role as a helper application for running DOS programs.
     In the former case, we interpret the command line options as if we
     were a Unix shell, but in the latter case we simply pass our
     command line to CreateProcess.  We know which case we are dealing
     with by whether argv[0] refers to ourself or to some other program.
     (This relies on an arcane feature of CreateProcess, where we can
     specify cmdproxy as the module to run, but specify a different
     program in the command line - the MSVC startup code sets argv[0]
     from the command line.)  */

  if (!GetModuleFileName (NULL, modname, sizeof (modname)))
    fail ("error: GetModuleFileName failed\n");

  /* Change directory to location of .exe so startup directory can be
     deleted.  */
  progname = strrchr (modname, '\\');
  *progname = '\0';
  SetCurrentDirectory (modname);
  *progname = '\\';

  /* Due to problems with interaction between API functions that use "OEM"
     codepage vs API functions that use the "ANSI" codepage, we need to
     make things consistent by choosing one and sticking with it.  */
  SetConsoleCP (GetACP ());
  SetConsoleOutputCP (GetACP ());

  /* Although Emacs always sets argv[0] to an absolute pathname, we
     might get run in other ways as well, so convert argv[0] to an
     absolute name before comparing to the module name.  */
  path[0] = '\0';
  /* The call to SearchPath will find argv[0] in the current
     directory, append ".exe" to it if needed, and also canonicalize
     it, to resolve references to ".", "..", etc.  */
  status = SearchPath (NULL, argv[0], ".exe", sizeof (path), path,
				  &progname);
  if (!(status > 0 && stricmp (modname, path) == 0))
    {
      if (status <= 0)
	{
	  char *s;

	  /* Make sure we have argv[0] in path[], as the failed
	     SearchPath might not have copied it there.  */
	  strcpy (path, argv[0]);
	  /* argv[0] could include forward slashes; convert them all
	     to backslashes, for strrchr calls below to DTRT.  */
	  for (s = path; *s; s++)
	    if (*s == '/')
	      *s = '\\';
	}
      /* Perhaps MODNAME and PATH use mixed short and long file names.  */
      if (!(GetShortPathName (modname, modname, sizeof (modname))
	    && GetShortPathName (path, path, sizeof (path))
	    && stricmp (modname, path) == 0))
	{
	  /* Sometimes GetShortPathName fails because one or more
	     directories leading to argv[0] have issues with access
	     rights.  In that case, at least we can compare the
	     basenames.  Note: this disregards the improbable case of
	     invoking a program of the same name from another
	     directory, since the chances of that other executable to
	     be both our namesake and a 16-bit DOS application are nil.  */
	  char *p = strrchr (path, '\\');
	  char *q = strrchr (modname, '\\');
	  char *pdot, *qdot;

	  if (!p)
	    p = strchr (path, ':');
	  if (!p)
	    p = path;
	  else
	    p++;
	  if (!q)
	    q = strchr (modname, ':');
	  if (!q)
	    q = modname;
	  else
	    q++;

	  pdot = strrchr (p, '.');
	  if (!pdot || stricmp (pdot, ".exe") != 0)
	    pdot = p + strlen (p);
	  qdot = strrchr (q, '.');
	  if (!qdot || stricmp (qdot, ".exe") != 0)
	    qdot = q + strlen (q);
	  if (pdot - p != qdot - q || strnicmp (p, q, pdot - p) != 0)
	    {
	      /* We are being used as a helper to run a DOS app; just
		 pass command line to DOS app without change.  */
	      /* TODO: fill in progname.  */
	      if (spawn (NULL, GetCommandLine (), dir, &rc))
		return rc;
	      fail ("Could not run %s\n", GetCommandLine ());
	    }
	}
    }

  /* Process command line.  If running interactively (-c or /c not
     specified) then spawn a real command shell, passing it the command
     line arguments.

     If not running interactively, then attempt to execute the specified
     command directly.  If necessary, spawn a real shell to execute the
     command.

  */

  progname = NULL;
  cmdline = NULL;
  /* If no args, spawn real shell for interactive use.  */
  need_shell = TRUE;
  interactive = TRUE;
  /* Ask command.com to create an environment block with a reasonable
     amount of free space.  */
  envsize = get_env_size () + 300;
  pass_through_args = (char **) alloca (argc * sizeof (char *));
  num_pass_through_args = 0;

  while (--argc > 0)
    {
      ++argv;
      /* Act on switches we recognize (mostly single letter switches,
	 except for -e); all unrecognized switches and extra args are
	 passed on to real shell if used (only really of benefit for
	 interactive use, but allow for batch use as well).  Accept / as
	 switch char for compatibility with cmd.exe.  */
      if (((*argv)[0] == '-' || (*argv)[0] == '/') && (*argv)[1] != '\0')
	{
	  if (((*argv)[1] == 'c' || (*argv)[1] == 'C') && ((*argv)[2] == '\0'))
	    {
	      if (--argc == 0)
		fail ("error: expecting arg for %s\n", *argv);
	      cmdline = *(++argv);
	      interactive = FALSE;
	    }
	  else if (((*argv)[1] == 'i' || (*argv)[1] == 'I') && ((*argv)[2] == '\0'))
	    {
	      if (cmdline)
		warn ("warning: %s ignored because of -c\n", *argv);
	    }
	  else if (((*argv)[1] == 'e' || (*argv)[1] == 'E') && ((*argv)[2] == ':'))
	    {
	      int requested_envsize = atoi (*argv + 3);
	      /* Enforce a reasonable minimum size, as above.  */
	      if (requested_envsize > envsize)
		envsize = requested_envsize;
	      /* For sanity, enforce a reasonable maximum.  */
	      if (envsize > 32768)
		envsize = 32768;
	    }
	  else
	    {
	      /* warn ("warning: unknown option %s ignored", *argv); */
	      pass_through_args[num_pass_through_args++] = *argv;
	    }
	}
      else
	break;
    }

#if 0
  /* I think this is probably not useful - cmd.exe ignores extra
     (non-switch) args in interactive mode, and they cannot be passed on
     when -c was given.  */

  /* Collect any remaining args after (initial) switches.  */
  while (argc-- > 0)
    {
      pass_through_args[num_pass_through_args++] = *argv++;
    }
#else
  /* Probably a mistake for there to be extra args; not fatal.  */
  if (argc > 0)
    warn ("warning: extra args ignored after '%s'\n", argv[-1]);
#endif

  pass_through_args[num_pass_through_args] = NULL;

  /* If -c option, determine if we must spawn a real shell, or if we can
     execute the command directly ourself.  */
  if (cmdline)
    {
      const char *args;

      /* The program name is the first token of cmdline.  Since
         filenames cannot legally contain embedded quotes, the value
         of escape_char doesn't matter.  */
      args = cmdline;
      if (!get_next_token (path, &args))
        fail ("error: no program name specified.\n");

      canon_filename (path);
      progname = make_absolute (path);

      /* If we found the program and the rest of the command line does
         not contain unquoted shell metacharacters, run the program
         directly (if not found it might be an internal shell command,
         so don't fail).  */
      if (progname != NULL && try_dequote_cmdline (cmdline))
        need_shell = FALSE;
      else
        progname = NULL;
    }

 pass_to_shell:
  if (need_shell)
    {
      char * p;
      int    extra_arg_space = 0;
      int    maxlen, remlen;
      int    run_command_dot_com;

      progname = getenv ("COMSPEC");
      if (!progname)
	fail ("error: COMSPEC is not set\n");

      canon_filename (progname);
      progname = make_absolute (progname);

      if (progname == NULL || strchr (progname, '\\') == NULL)
	fail ("error: the program %s could not be found.\n", getenv ("COMSPEC"));

      /* Need to set environment size when running command.com.  */
      run_command_dot_com =
	(stricmp (strrchr (progname, '\\'), "command.com") == 0);

      /* Work out how much extra space is required for
         pass_through_args.  */
      for (argv = pass_through_args; *argv != NULL; ++argv)
	/* We don't expect to have to quote switches.  */
	extra_arg_space += strlen (*argv) + 2;

      if (cmdline)
	{
	  char * buf;

	  /* Convert to syntax expected by cmd.exe/command.com for
	     running non-interactively.  Always quote program name in
	     case path contains spaces (fortunately it can't contain
	     quotes, since they are illegal in path names).  */

	  remlen = maxlen =
	    strlen (progname) + extra_arg_space + strlen (cmdline) + 16 + 2;
	  buf = p = alloca (maxlen + 1);

	  /* Quote progname in case it contains spaces.  */
	  p += _snprintf (p, remlen, "\"%s\"", progname);
	  remlen = maxlen - (p - buf);

	  /* Include pass_through_args verbatim; these are just switches
             so should not need quoting.  */
	  for (argv = pass_through_args; *argv != NULL; ++argv)
	    {
	      p += _snprintf (p, remlen, " %s", *argv);
	      remlen = maxlen - (p - buf);
	    }

	  /* Now that we know we will be invoking the shell, quote the
	     command line after the "/c" switch as the shell expects:
	     a single pair of quotes enclosing the entire command
	     tail, no matter whether quotes are used in the command
	     line, and how many of them are there.  See the output of
	     "cmd /?" for how cmd.exe treats quotes.  */
	  if (run_command_dot_com)
	    _snprintf (p, remlen, " /e:%d /c \"%s\"", envsize, cmdline);
	  else
	    _snprintf (p, remlen, " /c \"%s\"", cmdline);
	  cmdline = buf;
	}
      else
	{
	  if (run_command_dot_com)
	    {
	      /* Provide dir arg expected by command.com when first
		 started interactively (the "command search path").  To
		 avoid potential problems with spaces in command dir
		 (which cannot be quoted - command.com doesn't like it),
		 we always use the 8.3 form.  */
	      GetShortPathName (progname, path, sizeof (path));
	      p = strrchr (path, '\\');
	      /* Trailing slash is acceptable, so always leave it.  */
	      *(++p) = '\0';
	    }
	  else
	    path[0] = '\0';

	  remlen = maxlen =
	    strlen (progname) + extra_arg_space + strlen (path) + 13;
	  cmdline = p = alloca (maxlen + 1);

	  /* Quote progname in case it contains spaces.  */
	  p += _snprintf (p, remlen, "\"%s\" %s", progname, path);
	  remlen = maxlen - (p - cmdline);

	  /* Include pass_through_args verbatim; these are just switches
             so should not need quoting.  */
	  for (argv = pass_through_args; *argv != NULL; ++argv)
	    {
	      p += _snprintf (p, remlen, " %s", *argv);
	      remlen = maxlen - (p - cmdline);
	    }

	  if (run_command_dot_com)
	    _snprintf (p, remlen, " /e:%d", envsize);
	}
    }

  if (!progname)
    fail ("Internal error: program name not defined\n");

  if (!cmdline)
    cmdline = progname;

  if (spawn (progname, cmdline, dir, &rc))
    return rc;

  if (!need_shell)
    {
      need_shell = TRUE;
      goto pass_to_shell;
    }

  fail ("Could not run %s\n", progname);

  return 0;
}
コード例 #9
0
BOOL CEditorDoc::OnNewDocument ( )
{
	theApp.m_Debug.Write ( "CEditorDoc::OnNewDocument" );
	
	// create a new document

	// call the base class function
	if ( !COleDocument::OnNewDocument ( ) )
	{
		theApp.m_Debug.Write ( "CEditorDoc::Failed" );
		return FALSE;
	}

	

	// m_NewProject.DoModal ( );

	// string to store executable link
	TCHAR szExecutable [ MAX_PATH ];

	theApp.m_Debug.Write ( "CEditorDoc::SetCurrentDirectory" );
	
	theApp.m_Debug.Write ( theApp.m_szDirectory );
	SetCurrentDirectory ( theApp.m_szDirectory );

	// get the exe to run
	//GetPrivateProfileString ( _T ( "General" ), _T ( "Executable" ), _T ( "" ), szExecutable, MAX_PATH, _T ( "./files/editors/host/editor.ini" ) );
	GetPrivateProfileString ( _T ( "General" ), _T ( "Executable" ), _T ( "" ), szExecutable, MAX_PATH, theApp.m_szLanguage );
	
	// get pointer to frame
	CMainFrame* pFrame = ( CMainFrame* ) theApp.m_pMainWnd;

	// show library window
	pFrame->SetEntityVisible ( TRUE );

	SetTitle ( _T ( "Editor" ) );

	theApp.m_pDocumentA = this;



	if ( theApp.m_bRestart )
	{
		theApp.m_Debug.Write ( "CEditorDoc::m_bRestart" );

		//Sleep ( 250 );

		theApp.m_bAppRunning = true;
		theApp.m_bRestart  = false;

		theApp.m_DBProApplicationLaunched = false;

		SetCurrentDirectory ( theApp.m_szDirectory );

		char szExeANSI [ 255 ] = "";
		char szParamANSI [ 255 ] = "";
		CString szParamUNI;
		CString szExeUNI;

					cIPC* pIPC	= theApp.m_Message.GetIPC ( );
			char  dataA [ 255 ] = "";
			char  dataB [ 255 ] = "";
			
			pIPC->ReceiveBuffer ( &dataA [ 0 ], 1000, sizeof ( dataA ) );
			pIPC->ReceiveBuffer ( &dataB [ 0 ], 1256, sizeof ( dataB ) );

			ConvertANSIToWide ( ( BYTE* ) &dataA [ 0 ], szExeANSI,   &szExeUNI );
			ConvertANSIToWide ( ( BYTE* ) &dataB [ 0 ], szParamANSI, &szParamUNI );

		//ConvertANSIToWide ( &theApp.m_pData [ 1000 ], szExeANSI,   &szExeUNI );
		//ConvertANSIToWide ( &theApp.m_pData [ 1256 ], szParamANSI, &szParamUNI );

		// ORIGINAL WORKING CODE
		// open the exe file
		//HINSTANCE hInstance = ShellExecute ( NULL, _T ( "open" ), szExeUNI, szParamUNI, NULL, SW_HIDE   );
		//theApp.m_hInstance = hInstance;

		// 151204
		theApp.SetFileMapData ( 912, 0 );
		theApp.SetFileMapData ( 916, 0 );

		{
			

			SHELLEXECUTEINFO seinfo;

			ZeroMemory ( &seinfo, sizeof ( seinfo ) );

			seinfo.cbSize       = sizeof ( seinfo );
			seinfo.fMask        = SEE_MASK_NOCLOSEPROCESS;
			seinfo.hwnd         = NULL;
			seinfo.lpVerb       = _T ( "open" );
			seinfo.lpFile       = szExeUNI;
			seinfo.lpParameters = szParamUNI;
			seinfo.lpDirectory  = _T ( "" );
			seinfo.nShow        = SW_HIDE;
			//seinfo.nShow        = SW_SHOW;
			
			char szDebug [ 255 ] = "";

			theApp.m_Debug.Write ( "RESTART EDITOR" );

			sprintf ( szDebug, "Shell execute - executable - %s", szExeANSI   );
			theApp.m_Debug.Write ( szDebug );
			sprintf ( szDebug, "Shell execute - parameters - %s", szParamANSI );
			theApp.m_Debug.Write ( szDebug );

			theApp.m_iRecover = 0;

			cIPC* pIPC	= theApp.m_Message.GetIPC ( );
			
			BYTE dataClear [ 6144 ] = { 0 };
			
			pIPC->SendBuffer ( &dataClear [ 0 ], 0, sizeof ( dataClear ) );

			//memset ( theApp.m_pData, 0, 1024 * 6 );

			theApp.SetFileMapData ( 44, 1 );
			theApp.SetFileMapData ( 486, 1 );

			theApp.m_bDisplayMouse = TRUE;
			theApp.m_lastPoint.x = 0;
			theApp.m_lastPoint.y = 0;
			theApp.m_bEnd = FALSE;
			theApp.m_bDisable = true;
			theApp.m_bFocus = false;
			theApp.m_bEntityFocus = false;
			theApp.m_iRecover = 0;
			theApp.m_bRestart = false;

			////// 221204 ////////////////////////////////////
			/*
			while ( 1 )
			{
				bool bGame = false;

				HANDLE hSnapShot = CreateToolhelp32Snapshot ( TH32CS_SNAPPROCESS, 0 );
				PROCESSENTRY32 processInfo;
				processInfo.dwSize = sizeof ( PROCESSENTRY32 );
				int index = 0;

				while ( Process32Next ( hSnapShot, &processInfo ) != FALSE )
				{
					// 170105
					//if ( wcscmp ( processInfo.szExeFile, _T ( "FPSC-Game.exe" ) ) == 0 )
					if ( strcmp ( processInfo.szExeFile, _T ( "FPSC-Game.exe" ) ) == 0 )
					{
						bGame = true;
					}
				}

				CloseHandle ( hSnapShot );
				
				if ( bGame )
					theApp.m_Debug.Write ( "FPSC-Game.exe - running" );

				if ( !bGame )
					break;
			}
			*/
			////////////////////////////////////////////////

			////////////////////////
			{
				theApp.m_Debug.Write ( "CEditorDoc::Checking running processes" );
				
				// 010205
				while ( 1 )
				{
					CEnumProcess tmp;
					 CString s;

					tmp.SetMethod ( 0x1 );

					CEnumProcess::CProcessEntry entry;

					bool bGame = false;
					
					for (BOOL OK = tmp.GetProcessFirst(&entry); OK; OK = tmp.GetProcessNext(&entry) )
					{
						int image = 0;
						if (entry.hTask16)
						{
							s.Format("%08X (%ld)", entry.dwPID, entry.hTask16);
							image = 1;
						}
						else
							s.Format("%08X", entry.dwPID);

						TRACE(s + " %s\n", entry.lpFilename);
						
						

						{
							_strlwr ( entry.lpFilename );

							CString		process = entry.lpFilename;
							char		szTextANSI [ 255 ]	= "";
							ConvertWideToANSI ( NULL, &process, szTextANSI );

							//theApp.m_Debug.Write ( szTextANSI );

							char  seps[ ] = ".\\//";
							char* token;

							token = strtok ( szTextANSI, seps );

							while ( token != NULL )
							{
								/*
								if ( strcmp ( token, "fpsc-game" ) == 0 )
								{
									bGame = true;
								}
								*/

								if ( _strnicmp ( token, "fpsc-game", strlen ( token ) ) == 0 )
									bGame = true;

								token = strtok ( NULL, seps );
							}
						}
					}

					if ( bGame )
						theApp.m_Debug.Write ( "FPSC-game.exe - running" );

					if ( !bGame )
					{
						theApp.m_Debug.Write ( "FPSC-game.exe - not running - quit" );
						break;
					}
				}
			}
			///////////////////////

			// 170105
			theApp.m_bTestGameCancel = true;


				

			/*
		// 020205 - new
		{

			{
				STARTUPINFO si;
			    PROCESS_INFORMATION pi;
				ZeroMemory( &si, sizeof(si) );
				si.cb = sizeof(si);
				si.dwFlags = STARTF_USESHOWWINDOW;
				//si.wShowWindow = SW_SHOWDEFAULT;
				si.wShowWindow = SW_HIDE;

				DWORD dwPriority = NORMAL_PRIORITY_CLASS;

				if ( CreateProcess ( szExeANSI, szParamANSI, NULL, NULL, FALSE, dwPriority, NULL, theApp.m_szDirectory, &si, &pi ) ) 
				{
					theApp.m_DBProApplicationLaunched = true;
					theApp.m_bAppRunning = true;

					theApp.m_Debug.Write ( "Shell execute - success" );

					memcpy ( &theApp.m_DBProProcess, &pi, sizeof ( PROCESS_INFORMATION ) );

					
					//SAFE_DELETE(pDirectory);
					//CloseHandle ( pi.hThread );
					//CloseHandle ( pi.hProcess );
					//*dwExecuteFileProcess = pi.dwProcessId;
					//return TRUE;
				}
				else
				{
					theApp.m_Debug.Write ( "Shell execute - failed" );
					theApp.m_DBProApplicationLaunched = false;	
				}
			}
		}
		*/

		
			// 020205 - original
			if ( ShellExecuteEx ( &seinfo ) == TRUE )
			{
				theApp.m_DBProApplicationLaunched = true;
				theApp.m_DBProApplication		  = seinfo;

				theApp.m_hInstance = seinfo.hInstApp;
				theApp.m_bAppRunning = true;

				theApp.m_Debug.Write ( "Shell execute - success" );
			}
			else
			{
				theApp.m_Debug.Write ( "Shell execute - failed" );
				theApp.m_DBProApplicationLaunched = false;
			}
			
			if ( seinfo.hInstApp <= ( HINSTANCE ) 32 )
			{
				theApp.m_Debug.Write ( "Shell execute - invalid hinstance" );
				theApp.m_DBProApplicationLaunched = false;
			}
			
		}

		
		
		theApp.SetFileMapData ( 974, 0 );

		theApp.m_bFocus       = false;
		theApp.m_bEntityFocus = false;

	}
	else
	{
		// go to root FPSC folder
		SetCurrentDirectory ( theApp.m_szDirectory );

		// create mapeditor process
		SHELLEXECUTEINFO seinfo;
		ZeroMemory ( &seinfo, sizeof ( seinfo ) );
		seinfo.cbSize       = sizeof ( seinfo );

		// check if editor already exists (for debugging)
		HWND hEditorWnd = FindWindow ( NULL, "FPSC Map Editor" );
		if ( hEditorWnd )
		{
			// debug
			theApp.m_Debug.Write ( "ACQUIRING EDITOR" );

			// fill data from window
			seinfo.hwnd         = hEditorWnd;
			seinfo.hInstApp     = NULL;

			// set application for linkage
			theApp.m_DBProApplicationLaunched = true;
			theApp.m_DBProApplication		  = seinfo;
			theApp.m_hInstance = seinfo.hInstApp;
			theApp.m_bAppRunning = true;
			theApp.m_Debug.Write ( "ACQUIRE - success\n" );
		}
		else
		{
			// debug
			theApp.m_Debug.Write ( "LAUNCH EDITOR" );

			// prepare data for launch
			seinfo.fMask        = SEE_MASK_NOCLOSEPROCESS;
			seinfo.hwnd         = NULL;
			seinfo.lpVerb       = _T ( "open" );
			seinfo.lpFile       = szExecutable;
			seinfo.lpParameters = _T ( "" );
			seinfo.lpDirectory  = _T ( "" );
			seinfo.nShow        = SW_HIDE;

			// shell execute mapeditor
			if ( ShellExecuteEx ( &seinfo ) == TRUE )
			{
				theApp.m_DBProApplicationLaunched = true;
				theApp.m_DBProApplication		  = seinfo;

				theApp.m_hInstance = seinfo.hInstApp;
				theApp.m_bAppRunning = true;

				theApp.m_Debug.Write ( "START - success\n" );
			}
			else
			{
				theApp.m_Debug.Write ( "START - failed\n" );
				theApp.m_DBProApplicationLaunched = false;	
			}
		}
		
		// debug
		theApp.m_Debug.Write ( "FINISHED\n" );
	}

	// debug
	theApp.m_Debug.Write ( "CEditorDoc::End" );

	// complete
	return TRUE;
}
コード例 #10
0
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
	//correct current directory
	SetCurrentDirectory(GetModuleFullDirectory().c_str());

	//std::wstring monoRuntimeFullPath = GetModuleFullDirectory() + _T("\\MonoRuntime");

	std::wstring monoRuntimeLocalPath = _T("NativeDlls\\Windows_x86\\MonoRuntime");

	HMODULE hMonoDllModule = NULL;

	//load mono dll
	{
		//std::wstring dllFullPath = monoRuntimeFullPath + std::wstring(_T("\\bin\\mono.dll"));
		std::wstring dllPath = monoRuntimeLocalPath + std::wstring(_T("\\bin\\mono.dll"));

		hMonoDllModule = LoadLibrary( dllPath.c_str() );

		if(!hMonoDllModule)
		{
			TCHAR error[4096];
			wsprintf(error, _T("Loading \"%s\" failed."), dllPath.c_str());
			MessageBox(0, error,  _T("Mono launcher error"), MB_OK | MB_ICONEXCLAMATION);
			return -1;
		}
	}

	mono_main* monoMainFunction = (mono_main*)GetProcAddress( hMonoDllModule, "mono_main" );
	if(!monoMainFunction)
	{
		MessageBox(0, _T("No \"mono_main\" procedure."), _T("Mono launcher error"), 
			MB_OK | MB_ICONEXCLAMATION);
		return -1;
	}

	mono_set_dirs* monoSetDirsFunction = (mono_set_dirs*)GetProcAddress( 
		hMonoDllModule, "mono_set_dirs" );
	if(!monoSetDirsFunction)
	{
		MessageBox(0, _T("No \"mono_set_dirs\" procedure."), _T("Mono launcher error"), 
			MB_OK | MB_ICONEXCLAMATION);
		return -1;
	}

	std::wstring destinationFileName = GetDestinationFileName();
	if(destinationFileName.empty())
		return -1;
	std::string destinationFileNameAnsi = ToAnsiString(destinationFileName);

	//it's will be modified
	char* lpCmdLineTemp = new char[wcslen(lpCmdLine) + 1];
	memset(lpCmdLineTemp, 0, wcslen(lpCmdLine) + 1);
	wcstombs(lpCmdLineTemp, lpCmdLine, wcslen(lpCmdLine));

	int argc = 0;
	char* argv[256];
	{
		argv[argc] = "none";
		argc++;

		argv[argc] = (char*)destinationFileNameAnsi.c_str();
		argc++;

		//parse windows command line
		char* cmdPointer = lpCmdLineTemp;
		while(*cmdPointer && argc < 256)
		{
			while(*cmdPointer && *cmdPointer <= ' ')
				cmdPointer++;
			if(*cmdPointer)
			{
				argv[argc++] = cmdPointer;
				while(*cmdPointer && *cmdPointer > ' ')
					cmdPointer++;
				if(*cmdPointer) 
					*(cmdPointer++) = 0;
			}
		}
	}

	//run mono

	//std::string monoLibPathAnsi = ToAnsiString(monoRuntimeFullPath + _T("\\lib"));
	//std::string monoEtcPathAnsi = ToAnsiString(monoRuntimeFullPath + _T("\\etc"));
	std::string monoLibPathAnsi = ToAnsiString(monoRuntimeLocalPath + _T("\\lib"));
	std::string monoEtcPathAnsi = ToAnsiString(monoRuntimeLocalPath + _T("\\etc"));
	//1 - path to "lib" directory
	//2 - config file path (by default in the mono path to "etc" directory)
	monoSetDirsFunction(monoLibPathAnsi.c_str(), monoEtcPathAnsi.c_str());

	int result = monoMainFunction(argc, argv);

	delete[] lpCmdLineTemp;

	return result;
}
コード例 #11
0
BOOL
CIipostinstApp::InitInstance()
{
    BOOL    silent;

    /* Standard initialization */
    theInstall.m_DBMSupgrade = FALSE;
    theInstall.m_UseResponseFile = FALSE;
    theInstall.m_bSkipLicenseCheck = FALSE;
    theInstall.m_bEmbeddedRelease = FALSE;
    theInstall.m_commandline = "";
    theInstall.m_SoftwareKey = NULL;

	return_code = 0;
    hSystemPalette = 0;
    theIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

	/*// 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);
	*/
	InitCommonControls();
	CWinApp::InitInstance();

	AfxEnableControlContainer();

    theInstall.Init();
    silent = theInstall.GetRegValueBOOL("SilentInstall", FALSE);
    theInstall.DeleteRegValue("InstalledFeatures");
    theInstall.DeleteRegValue("RemovedFeatures");

    if (silent)
    {
	theInstall.PostInstallation(NULL);
	
	while(theInstall.IsBusy())
	    Sleep(1500);

	/* Start up IVM */
	if (theInstall.m_StartIVM)
	{
	    SetCurrentDirectory(theInstall.m_installPath + "\\ingres\\bin");
	    theInstall.Execute( "\"" + theInstall.m_installPath + "\\ingres\\bin\\ivm.exe\"", FALSE);
	}

	if (!theInstall.m_postInstRet)
	{
	    return_code=1;
	    return TRUE;
	}
	return FALSE;
    }

    CString s;
#ifdef EVALUATION_RELEASE
    s.LoadString(IDS_SDKTITLE);
#else
    if (theInstall.m_DBATools)
    s.Format(IDS_TITLE_DBA, theInstall.m_installationcode);
    else
    s.Format(IDS_TITLE, theInstall.m_installationcode);
#endif /* EVALUATION_RELEASE */

    CPropSheet dlg(s);
    m_pMainWnd = &dlg;
    dlg.DoModal();

    if (theInstall.m_postInstRet)
    {
	if (theInstall.m_win95 && theInstall.m_reboot) 
	{
	    CWaitCursor	wait;

	    if (!theInstall.m_win95)
	    {
		TOKEN_PRIVILEGES    tp;
		LUID		    luid;
		TOKEN_PRIVILEGES    tpPrevious;
		HANDLE		    hToken = NULL;
		DWORD		    cbPrevious = sizeof(TOKEN_PRIVILEGES);

		OpenProcessToken(GetCurrentProcess(),
				 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
				 &hToken);

		if(!LookupPrivilegeValue( NULL, SE_SHUTDOWN_NAME, &luid )) 
		    return FALSE;
		
		/*
		** First pass. Get current privilege setting.
		*/

		tp.PrivilegeCount           = 1;
		tp.Privileges[0].Luid       = luid;
		tp.Privileges[0].Attributes = 0;
		
		AdjustTokenPrivileges(
		    hToken,
		    FALSE,
		    &tp,
		    sizeof(TOKEN_PRIVILEGES),
		    &tpPrevious,
		    &cbPrevious
		    );
		
		/*
		** Second pass. Set privilege based on previous setting.
		*/
		tpPrevious.PrivilegeCount		= 1;
		tpPrevious.Privileges[0].Luid	= luid;
		tpPrevious.Privileges[0].Attributes |= (SE_PRIVILEGE_ENABLED);
		
		AdjustTokenPrivileges(
		    hToken,
		    FALSE,
		    &tpPrevious,
		    cbPrevious,
		    NULL,
		    NULL
		    );
	    }

	    ExitWindowsEx(EWX_REBOOT, 0);
	}
    }
    else
    {
	return_code=1;
	return TRUE;
    }

    if (hSystemPalette)
    {
	HDC hDC=::GetDC(NULL);
	::SelectPalette(hDC,hSystemPalette,FALSE);
	::SelectPalette(hDC,hSystemPalette,TRUE);
	::RealizePalette(hDC);
	::ReleaseDC(NULL,hDC);
    }

    return FALSE;
}
コード例 #12
0
ファイル: registry.cpp プロジェクト: kirillkovalenko/nssm
int get_parameters(nssm_service_t *service, STARTUPINFO *si) {
  unsigned long ret;

  /* Try to open the registry */
  HKEY key = open_registry(service->name, KEY_READ);
  if (! key) return 1;

  /* Don't expand parameters when retrieving for the GUI. */
  bool expand = si ? true : false;

  /* Try to get environment variables - may fail */
  get_environment(service->name, key, NSSM_REG_ENV, &service->env, &service->envlen);
  /* Environment variables to add to existing rather than replace - may fail. */
  get_environment(service->name, key, NSSM_REG_ENV_EXTRA, &service->env_extra, &service->env_extralen);

  /* Set environment if we are starting the service. */
  if (si) set_service_environment(service);

  /* Try to get executable file - MUST succeed */
  if (get_string(key, NSSM_REG_EXE, service->exe, sizeof(service->exe), expand, false, true)) {
    RegCloseKey(key);
    return 3;
  }

  /* Try to get flags - may fail and we don't care */
  if (get_string(key, NSSM_REG_FLAGS, service->flags, sizeof(service->flags), expand, false, true)) {
    log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_NO_FLAGS, NSSM_REG_FLAGS, service->name, service->exe, 0);
    ZeroMemory(service->flags, sizeof(service->flags));
  }

  /* Try to get startup directory - may fail and we fall back to a default */
  if (get_string(key, NSSM_REG_DIR, service->dir, sizeof(service->dir), expand, true, true) || ! service->dir[0]) {
    _sntprintf_s(service->dir, _countof(service->dir), _TRUNCATE, _T("%s"), service->exe);
    strip_basename(service->dir);
    if (service->dir[0] == _T('\0')) {
      /* Help! */
      ret = GetWindowsDirectory(service->dir, sizeof(service->dir));
      if (! ret || ret > sizeof(service->dir)) {
        log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_NO_DIR_AND_NO_FALLBACK, NSSM_REG_DIR, service->name, 0);
        RegCloseKey(key);
        return 4;
      }
    }
    log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_NO_DIR, NSSM_REG_DIR, service->name, service->dir, 0);
  }

  /* Try to get processor affinity - may fail. */
  TCHAR buffer[512];
  if (get_string(key, NSSM_REG_AFFINITY, buffer, sizeof(buffer), false, false, false) || ! buffer[0]) service->affinity = 0LL;
  else if (affinity_string_to_mask(buffer, &service->affinity)) {
    log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_BOGUS_AFFINITY_MASK, service->name, buffer);
    service->affinity = 0LL;
  }
  else {
    DWORD_PTR affinity, system_affinity;

    if (GetProcessAffinityMask(GetCurrentProcess(), &affinity, &system_affinity)) {
      _int64 effective_affinity = service->affinity & system_affinity;
      if (effective_affinity != service->affinity) {
        TCHAR *system = 0;
        if (! affinity_mask_to_string(system_affinity, &system)) {
          TCHAR *effective = 0;
          if (! affinity_mask_to_string(effective_affinity, &effective)) {
            log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_EFFECTIVE_AFFINITY_MASK, service->name, buffer, system, effective, 0);
          }
          HeapFree(GetProcessHeap(), 0, effective);
        }
        HeapFree(GetProcessHeap(), 0, system);
      }
    }
  }

  /* Try to get priority - may fail. */
  unsigned long priority;
  if (get_number(key, NSSM_REG_PRIORITY, &priority, false) == 1) {
    if (priority == (priority & priority_mask())) service->priority = priority;
    else log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_BOGUS_PRIORITY, service->name, NSSM_REG_PRIORITY, 0);
  }

  /* Try to get hook I/O sharing - may fail. */
  unsigned long hook_share_output_handles;
  if (get_number(key, NSSM_REG_HOOK_SHARE_OUTPUT_HANDLES, &hook_share_output_handles, false) == 1) {
    if (hook_share_output_handles) service->hook_share_output_handles = true;
    else service->hook_share_output_handles = false;
  }
  else hook_share_output_handles = false;
  /* Try to get file rotation settings - may fail. */
  unsigned long rotate_files;
  if (get_number(key, NSSM_REG_ROTATE, &rotate_files, false) == 1) {
    if (rotate_files) service->rotate_files = true;
    else service->rotate_files = false;
  }
  else service->rotate_files = false;
  if (get_number(key, NSSM_REG_ROTATE_ONLINE, &rotate_files, false) == 1) {
    if (rotate_files) service->rotate_stdout_online = service->rotate_stderr_online = true;
    else service->rotate_stdout_online = service->rotate_stderr_online = false;
  }
  else service->rotate_stdout_online = service->rotate_stderr_online = false;
  /* Log timestamping requires a logging thread.*/
  unsigned long timestamp_log;
  if (get_number(key, NSSM_REG_TIMESTAMP_LOG, &timestamp_log, false) == 1) {
    if (timestamp_log) service->timestamp_log = true;
    else service->timestamp_log = false;
  }
  else service->timestamp_log = false;

  /* Hook I/O sharing and online rotation need a pipe. */
  service->use_stdout_pipe = service->rotate_stdout_online || service->timestamp_log || hook_share_output_handles;
  service->use_stderr_pipe = service->rotate_stderr_online || service->timestamp_log || hook_share_output_handles;
  if (get_number(key, NSSM_REG_ROTATE_SECONDS, &service->rotate_seconds, false) != 1) service->rotate_seconds = 0;
  if (get_number(key, NSSM_REG_ROTATE_BYTES_LOW, &service->rotate_bytes_low, false) != 1) service->rotate_bytes_low = 0;
  if (get_number(key, NSSM_REG_ROTATE_BYTES_HIGH, &service->rotate_bytes_high, false) != 1) service->rotate_bytes_high = 0;
  override_milliseconds(service->name, key, NSSM_REG_ROTATE_DELAY, &service->rotate_delay, NSSM_ROTATE_DELAY, NSSM_EVENT_BOGUS_THROTTLE);

  /* Try to get force new console setting - may fail. */
  if (get_number(key, NSSM_REG_NO_CONSOLE, &service->no_console, false) != 1) service->no_console = 0;

  /* Change to startup directory in case stdout/stderr are relative paths. */
  TCHAR cwd[PATH_LENGTH];
  GetCurrentDirectory(_countof(cwd), cwd);
  SetCurrentDirectory(service->dir);

  /* Try to get stdout and stderr */
  if (get_io_parameters(service, key)) {
    log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_GET_OUTPUT_HANDLES_FAILED, service->name, 0);
    RegCloseKey(key);
    SetCurrentDirectory(cwd);
    return 5;
  }

  /* Change back in case the startup directory needs to be deleted. */
  SetCurrentDirectory(cwd);

  /* Try to get mandatory restart delay */
  override_milliseconds(service->name, key, NSSM_REG_RESTART_DELAY, &service->restart_delay, 0, NSSM_EVENT_BOGUS_RESTART_DELAY);

  /* Try to get throttle restart delay */
  override_milliseconds(service->name, key, NSSM_REG_THROTTLE, &service->throttle_delay, NSSM_RESET_THROTTLE_RESTART, NSSM_EVENT_BOGUS_THROTTLE);

  /* Try to get service stop flags. */
  unsigned long type = REG_DWORD;
  unsigned long stop_method_skip;
  unsigned long buflen = sizeof(stop_method_skip);
  bool stop_ok = false;
  ret = RegQueryValueEx(key, NSSM_REG_STOP_METHOD_SKIP, 0, &type, (unsigned char *) &stop_method_skip, &buflen);
  if (ret != ERROR_SUCCESS) {
    if (ret != ERROR_FILE_NOT_FOUND) {
      if (type != REG_DWORD) {
        log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_BOGUS_STOP_METHOD_SKIP, service->name, NSSM_REG_STOP_METHOD_SKIP, NSSM, 0);
      }
      else log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_QUERYVALUE_FAILED, NSSM_REG_STOP_METHOD_SKIP, error_string(ret), 0);
    }
  }
  else stop_ok = true;

  /* Try all methods except those requested to be skipped. */
  service->stop_method = ~0;
  if (stop_ok) service->stop_method &= ~stop_method_skip;

  /* Try to get kill delays - may fail. */
  override_milliseconds(service->name, key, NSSM_REG_KILL_CONSOLE_GRACE_PERIOD, &service->kill_console_delay, NSSM_KILL_CONSOLE_GRACE_PERIOD, NSSM_EVENT_BOGUS_KILL_CONSOLE_GRACE_PERIOD);
  override_milliseconds(service->name, key, NSSM_REG_KILL_WINDOW_GRACE_PERIOD, &service->kill_window_delay, NSSM_KILL_WINDOW_GRACE_PERIOD, NSSM_EVENT_BOGUS_KILL_WINDOW_GRACE_PERIOD);
  override_milliseconds(service->name, key, NSSM_REG_KILL_THREADS_GRACE_PERIOD, &service->kill_threads_delay, NSSM_KILL_THREADS_GRACE_PERIOD, NSSM_EVENT_BOGUS_KILL_THREADS_GRACE_PERIOD);

  /* Try to get process tree settings - may fail. */
  unsigned long kill_process_tree;
  if (get_number(key, NSSM_REG_KILL_PROCESS_TREE, &kill_process_tree, false) == 1) {
    if (kill_process_tree) service->kill_process_tree = true;
    else service->kill_process_tree = false;
  }
  else service->kill_process_tree = true;

  /* Try to get default exit action. */
  bool default_action;
  service->default_exit_action = NSSM_EXIT_RESTART;
  TCHAR action_string[ACTION_LEN];
  if (! get_exit_action(service->name, 0, action_string, &default_action)) {
    for (int i = 0; exit_action_strings[i]; i++) {
      if (! _tcsnicmp((const TCHAR *) action_string, exit_action_strings[i], ACTION_LEN)) {
        service->default_exit_action = i;
        break;
      }
    }
  }

  /* Close registry */
  RegCloseKey(key);

  return 0;
}
コード例 #13
0
ファイル: main.cpp プロジェクト: Alwayssnarky/ppsspp
int WINAPI WinMain(HINSTANCE _hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow)
{
	// Windows Vista and above: alert Windows that PPSSPP is DPI aware,
	// so that we don't flicker in fullscreen on some PCs.
	MakePPSSPPDPIAware();

	// FMA3 support in the 2013 CRT is broken on Vista and Windows 7 RTM (fixed in SP1). Just disable it.
#ifdef _M_X64
	_set_FMA3_enable(0);
#endif

	EnableCrashingOnCrashes();

	wchar_t modulePath[MAX_PATH];
	GetModuleFileName(NULL, modulePath, MAX_PATH);
	for (size_t i = wcslen(modulePath) - 1; i > 0; i--) {
		if (modulePath[i] == '\\') {
			modulePath[i] = 0;
			break;
		}
	}
	SetCurrentDirectory(modulePath);
	// GetCurrentDirectory(MAX_PATH, modulePath);  // for checking in the debugger

#ifndef _DEBUG
	bool showLog = false;
#else
	bool showLog = false;
#endif

	VFSRegister("", new DirectoryAssetReader("assets/"));
	VFSRegister("", new DirectoryAssetReader(""));

	wchar_t lcCountry[256];

	// LOCALE_SNAME is only available in WinVista+
	// Really should find a way to do this in XP too :/
	if (0 != GetLocaleInfo(LOCALE_NAME_USER_DEFAULT, LOCALE_SNAME, lcCountry, 256)) {
		langRegion = ConvertWStringToUTF8(lcCountry);
		for (size_t i = 0; i < langRegion.size(); i++) {
			if (langRegion[i] == '-')
				langRegion[i] = '_';
		}
	} else {
		langRegion = "en_US";
	}

	osName = GetWindowsVersion() + " " + GetWindowsSystemArchitecture();

	const char *configFilename = NULL;
	const char *configOption = "--config=";

	const char *controlsConfigFilename = NULL;
	const char *controlsOption = "--controlconfig=";

	for (int i = 1; i < __argc; ++i)
	{
		if (__argv[i][0] == '\0')
			continue;
		if (__argv[i][0] == '-')
		{
			if (!strncmp(__argv[i], configOption, strlen(configOption)) && strlen(__argv[i]) > strlen(configOption)) {
				configFilename = __argv[i] + strlen(configOption);
			}
			if (!strncmp(__argv[i], controlsOption, strlen(controlsOption)) && strlen(__argv[i]) > strlen(controlsOption)) {
				controlsConfigFilename = __argv[i] + strlen(controlsOption);
			}
		}
	}

	// On Win32 it makes more sense to initialize the system directories here 
	// because the next place it was called was in the EmuThread, and it's too late by then.
	InitSysDirectories();

	// Load config up here, because those changes below would be overwritten
	// if it's not loaded here first.
	g_Config.AddSearchPath("");
	g_Config.AddSearchPath(GetSysDirectory(DIRECTORY_SYSTEM));
	g_Config.SetDefaultPath(GetSysDirectory(DIRECTORY_SYSTEM));
	g_Config.Load(configFilename, controlsConfigFilename);

	// The rest is handled in NativeInit().
	for (int i = 1; i < __argc; ++i)
	{
		if (__argv[i][0] == '\0')
			continue;

		if (__argv[i][0] == '-')
		{
			switch (__argv[i][1])
			{
			case 'l':
				showLog = true;
				g_Config.bEnableLogging = true;
				break;
			case 's':
				g_Config.bAutoRun = false;
				g_Config.bSaveSettings = false;
				break;
			}

			if (!strncmp(__argv[i], "--fullscreen", strlen("--fullscreen")))
				g_Config.bFullScreen = true;

			if (!strncmp(__argv[i], "--windowed", strlen("--windowed")))
				g_Config.bFullScreen = false;

			if (!strncmp(__argv[i], "--escapeexitsemu", strlen("--escapeexitsemu")))
				g_Config.bEscapeExitsEmulator = true;
		}
	}
#ifdef _DEBUG
	g_Config.bEnableLogging = true;
#endif

	LogManager::Init();
	// Consider at least the following cases before changing this code:
	//   - By default in Release, the console should be hidden by default even if logging is enabled.
	//   - By default in Debug, the console should be shown by default.
	//   - The -l switch is expected to show the log console, REGARDLESS of config settings.
	//   - It should be possible to log to a file without showing the console.
	LogManager::GetInstance()->GetConsoleListener()->Init(showLog, 150, 120, "PPSSPP Debug Console");


	//Windows, API init stuff
	INITCOMMONCONTROLSEX comm;
	comm.dwSize = sizeof(comm);
	comm.dwICC = ICC_BAR_CLASSES | ICC_LISTVIEW_CLASSES | ICC_TAB_CLASSES;
	InitCommonControlsEx(&comm);
	timeBeginPeriod(1);
	MainWindow::Init(_hInstance);

	g_hPopupMenus = LoadMenu(_hInstance, (LPCWSTR)IDR_POPUPMENUS);

	MainWindow::Show(_hInstance, iCmdShow);

	HWND hwndMain = MainWindow::GetHWND();
	HWND hwndDisplay = MainWindow::GetDisplayHWND();
	
	//initialize custom controls
	CtrlDisAsmView::init();
	CtrlMemView::init();
	CtrlRegisterList::init();
	CGEDebugger::Init();

	DialogManager::AddDlg(vfpudlg = new CVFPUDlg(_hInstance, hwndMain, currentDebugMIPS));

	host = new WindowsHost(hwndMain, hwndDisplay);
	host->SetWindowTitle(0);

	MainWindow::CreateDebugWindows();

	// Emu thread is always running!
	EmuThread_Start();

	HACCEL hAccelTable = LoadAccelerators(_hInstance, (LPCTSTR)IDR_ACCELS);
	HACCEL hDebugAccelTable = LoadAccelerators(_hInstance, (LPCTSTR)IDR_DEBUGACCELS);

	//so.. we're at the message pump of the GUI thread
	for (MSG msg; GetMessage(&msg, NULL, 0, 0); )	// for no quit
	{
		if (msg.message == WM_KEYDOWN)
		{
			//hack to enable/disable menu command accelerate keys
			MainWindow::UpdateCommands();

			//hack to make it possible to get to main window from floating windows with Esc
			if (msg.hwnd != hwndMain && msg.wParam == VK_ESCAPE)
				BringWindowToTop(hwndMain);
		}

		//Translate accelerators and dialog messages...
		HWND wnd;
		HACCEL accel;
		switch (g_activeWindow)
		{
		case WINDOW_MAINWINDOW:
			wnd = hwndMain;
			accel = hAccelTable;
			break;
		case WINDOW_CPUDEBUGGER:
			wnd = disasmWindow[0] ? disasmWindow[0]->GetDlgHandle() : 0;
			accel = hDebugAccelTable;
			break;
		case WINDOW_GEDEBUGGER:
		default:
			wnd = 0;
			accel = 0;
			break;
		}

		if (!TranslateAccelerator(wnd, accel, &msg))
		{
			if (!DialogManager::IsDialogMessage(&msg))
			{
				//and finally translate and dispatch
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}
	}

	VFSShutdown();

	EmuThread_Stop();

	MainWindow::DestroyDebugWindows();
	DialogManager::DestroyAll();
	timeEndPeriod(1);
	delete host;
	g_Config.Save();
	LogManager::Shutdown();
	return 0;
}
コード例 #14
0
void setCurrentDirectory(const char* path)
{
	SetCurrentDirectory(path);
}
コード例 #15
0
ファイル: CopyDlg.cpp プロジェクト: melbcat/DynamoRIO-for-ARM
BOOL CCopyDlg::CopyFiles()
{
    TCHAR msg[MAX_PATH*2];
    TCHAR cmd[MAX_PATH*2];

    UpdateData(TRUE); // get target dir string

    // make the target directory
    // have to build each new directory one at a time
    CString newdir;
    int pos = 0;
    int slash = m_Target.Find('\\', pos);

    // first see if need to clean out existing dir
    if (SetCurrentDirectory(m_Target)) {
        _stprintf(msg, _T("Directory %s already exists.\n")
                  _T("Continuing will delete all its existing files.\nContinue?"), m_Target);
        int res = MessageBox(msg, _T("Confirmation"), MB_OKCANCEL | MYMBFLAGS);
        if (res == IDCANCEL)
            return FALSE;
        // get out of the dir
        BOOL ok = SetCurrentDirectory(m_CWD);
        assert(ok);
        _stprintf(cmd, _T("%s"), m_Target);
        if (!CShellInterface::DeleteFile(cmd, GetParent()->m_hWnd)) {
            _stprintf(msg, _T("Error removing existing directory %s"), m_Target);
            MessageBox(msg, _T("Error Deleting Files"), MB_OK | MYMBFLAGS);
            return FALSE;
        }
    }

    while (TRUE) {
        if (slash == -1)
            newdir = m_Target;
        else
            newdir = m_Target.Mid(0, slash);
        if (!SetCurrentDirectory(newdir)) {
            _stprintf(msg, _T("Create directory %s?"), newdir);
            int res = MessageBox(msg, _T("Confirmation"), MB_OKCANCEL | MYMBFLAGS);
            if (res == IDCANCEL)
                return FALSE;
            if (!CreateDirectory(newdir, NULL)) {
                _stprintf(msg, _T("Could not create directory %s"), newdir);
                MessageBox(msg, _T("Error Copying Files"), MB_OK | MYMBFLAGS);
                return FALSE;
            }
        }
        if (slash == -1)
            break;
        pos = slash + 1;
        slash = m_Target.Find('\\', pos);
    }

    // now copy the files
#if 1 /* CGO 2008 tutorial: create zip file */
    DWORD written;
    BOOL success;
    TCHAR to[MAX_PATH];
    _stprintf(to, _T("%s\\%s"), m_Target, ZIPNAME);
    HANDLE h = CreateFile(to,                    // file to open
                          GENERIC_WRITE,         // no read access needed
                          0,                     // no sharing
                          NULL,                  // default security
                          CREATE_ALWAYS,         // clobber existing file
                          FILE_ATTRIBUTE_NORMAL, // normal file
                          NULL);                 // no attr. template
    if (h == NULL)
        success = FALSE;
    else {
        success = WriteFile(h, zipdata, sizeof(zipdata), &written, NULL);
        CloseHandle(h);
    }
    if (!success || written != sizeof(zipdata)) {
        _stprintf(msg, _T("Error copying file to %s"), to);
        MessageBox(msg, _T("Error Copying Files"), MB_OK | MYMBFLAGS);
        return FALSE;
    }
#else
    TCHAR from[MAX_PATH];
    TCHAR to[MAX_PATH];
# if 0
    _stprintf(from, _T("%s"), _T("c:\\iye\\rio\\install\\DynamoRIO"));
    //_stprintf(from, _T("%s"), _T("d:\\bruening\\dynamo\\install\\DynamoRIO"));
# else
    _stprintf(from, _T("%s\\DynamoRIO"), m_CWD);
# endif
    _stprintf(to, _T("%s"), m_Target);
    if (!CShellInterface::CopyDir(from, to, GetParent()->m_hWnd)) {
        _stprintf(msg, _T("Error copying files from %s to %s"), from, to);
        MessageBox(msg, _T("Error Copying Files"), MB_OK | MYMBFLAGS);
        return FALSE;
    }
#endif

    return TRUE;
}
コード例 #16
0
ファイル: ModelLoader.cpp プロジェクト: HazenBabcock/LDView
void ModelLoader::startup(void)
{
	int width;
	int height;
	int widthDelta = 0;
	bool maximized;
	TCStringArray *commandLine = TCUserDefaults::getProcessedCommandLine();
	HWND hParentWindow = NULL;

	TCUserDefaults::removeValue(HFOV_KEY, false);
	TCUserDefaults::removeValue(CAMERA_GLOBE_KEY, false);
	if (commandLine)
	{
		int i;
		int count = commandLine->getCount();

		for (i = 0; i < count; i++)
		{
			char *command = (*commandLine)[i];
			int num;

			if (stringHasCaseInsensitivePrefix(command, "-ca"))
			{
				float value;

				if (sscanf(command + 3, "%f", &value) == 1)
				{
					TCUserDefaults::setFloatForKey(value, HFOV_KEY, false);
				}
			}
			else if (stringHasCaseInsensitivePrefix(command, "-cg"))
			{
				TCUserDefaults::setStringForKey(command + 3, CAMERA_GLOBE_KEY,
					false);
			}
			else if (strcasecmp(command, "-float") == 0 && i + 1 < count &&
				sscanf((*commandLine)[i + 1], "%i", &num) == 1 && num != 0)
			{
				hParentWindow = (HWND)num;
			}
		}
	}
	width = TCUserDefaults::longForKey(WINDOW_WIDTH_KEY, WIN_WIDTH, false);
	height = TCUserDefaults::longForKey(WINDOW_HEIGHT_KEY, WIN_HEIGHT, false);
	maximized = TCUserDefaults::longForKey(WINDOW_MAXIMIZED_KEY, 0, false) != 0;
	parentWindow = new LDViewWindow(TITLE, hInstance, CW_USEDEFAULT,
		CW_USEDEFAULT, width + widthDelta, height);
	parentWindow->setMinWidth(320);
	parentWindow->setMinHeight(240);
	parentWindow->setScreenSaver(screenSaver);
	if (hParentWindow)
	{
		parentWindow->setHParentWindow(hParentWindow);
	}
	if (parentWindow->initWindow())
	{
		char *commandLineFilename = getCommandLineFilename();
		char *snapshotFilename =
			TCUserDefaults::stringForKey(SAVE_SNAPSHOT_KEY, NULL, false);
		bool savedSnapshot = false;
		bool saveSnapshots = TCUserDefaults::boolForKey(SAVE_SNAPSHOTS_KEY, 0,
			false);

		modelWindow = parentWindow->getModelWindow();
		modelWindow->retain();
		if (snapshotFilename)
		{
			char originalDir[MAX_PATH];
			char fullFilename[MAX_PATH];

			GetCurrentDirectory(sizeof(originalDir), originalDir);
			if (ModelWindow::chDirFromFilename(snapshotFilename, fullFilename))
			{
				delete snapshotFilename;
				snapshotFilename = copyString(fullFilename);
				SetCurrentDirectory(originalDir);
			}
		}
		if (!screenSaver && commandLineFilename &&
			(snapshotFilename || saveSnapshots))
		{
			if (modelWindow->setupOffscreen(1600, 1200,
				TCUserDefaults::longForKey(FSAA_MODE_KEY) > 0))
			{
				// Note: even if the snapshot save fails, we don't want to continue.
				// The user will get an error in the event of a snapshot save
				// failure.
				LDSnapshotTaker::doCommandLine();
				parentWindow->shutdown();
				savedSnapshot = true;
				modelWindow->cleanupOffscreen();
			}
		}
		if (!savedSnapshot)
		{
			parentWindow->showWindow(nCmdShow);
			if (maximized)
			{
				parentWindow->maximize();
			}
			if (!screenSaver)
			{
				if (commandLineFilename && snapshotFilename)
				{
					parentWindow->openModel(commandLineFilename);
					if (modelWindow->saveSnapshot(snapshotFilename, true))
					{
						parentWindow->shutdown();
					}
				}
				else
				{
					std::string stepString =
						TCUserDefaults::commandLineStringForKey(STEP_KEY);
					long step;

					parentWindow->openModel(commandLineFilename);
					if (commandLineFilename != NULL && stepString.size() > 0 &&
						sscanf(stepString.c_str(), "%li", &step) == 1)
					{
						parentWindow->setStep(step);
					}
				}
			}
		}
		delete commandLineFilename;
		delete snapshotFilename;
	}
}
コード例 #17
0
ファイル: makenssi.cpp プロジェクト: kichik/nsis-1
int main(int argc, char **argv)
{
  CEXEBuild build;
  int do_cd=1;
  int outputtried=0;
  int argpos=1;
  int nousage=0;
  int files_processed=0;
  int cmds_processed=0;
  int plugins_processed=0;
  FILE *fp;
  int tmpargpos=1;
  int no_logo=0;

  if (argc > 1 && !stricmp(argv[1], "/VERSION"))
  {
    fprintf(g_output,NSIS_VERSION);
    fflush(g_output);
    return 0;
  }
  if (argc > 1 && argv[1][0]=='/' && (argv[1][1]=='v' || argv[1][1]=='V'))
  {
    tmpargpos++;
    if (argv[1][2] <= '2' && argv[1][2] >= '0')
    {
      no_logo=1;
    }
  }
  
  if (!no_logo)
  {
    if (argc > tmpargpos && argv[tmpargpos][0]=='/' && (argv[tmpargpos][1]=='o' || argv[tmpargpos][1]=='O') && argv[tmpargpos][2])
    {
      g_output=fopen(argv[tmpargpos]+2,"w");
      if (!g_output) 
      {
        printf("Error opening output log for writing. Using stdout.\n");
        g_output=stdout;
      }
      outputtried=1;
    }
    fprintf(g_output,"MakeNSIS %s - Copyright 1999-2003 Nullsoft, Inc.\n"
           "\n"
           "Portions Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler (zlib).\n"
           "Includes portions derived from bzip2 (see documentation for details).\n"
           "Contributors: [email protected], Ryan Geiss, Andras Varga, Drew Davidson, Peter Windridge, Dave Laundon, Robert Rainwater, Yaroslav Faybishenko, Jeff Doozan, Amir Szekely, Ximon Eighteen, et al.\n\n",NSIS_VERSION);
    fflush(g_output);
  }

  atexit(myatexit);
  signal(SIGINT,sigint);

  if (!g_output) g_output=stdout;
  while (argpos < argc)
  {
    if (argv[argpos][0]=='/' && (argv[argpos][1]=='D' || argv[argpos][1]=='d') && argv[argpos][2])
    {
      char *p=argv[argpos]+2;
      if (p[0])
      {
        char *s=strdup(p),*v;
        if (build.display_script) 
        {
          fprintf(g_output,"Command line defined: \"%s\"\n",p);
          fflush(g_output);
        }
        v=strstr(s,"=");
        if (v) *v++=0;
        build.define(s,v?v:"");
        free(s);
      }
      else
      {
        build.warning("command line /D requires argument (i.e. \"/Ddefine\"). ignored.");
      }
    }
    else if (argv[argpos][0]=='/' && (argv[argpos][1]=='X' || argv[argpos][1]=='x') && argv[argpos][2])
    {
      if (build.process_oneline(argv[argpos]+2,"command line",argpos+1) != PS_OK)
      {
        return 1;
      }
      cmds_processed++;
    }
    else if (argv[argpos][0]=='/' && (argv[argpos][1]=='O' || argv[argpos][1]=='o') && argv[argpos][2])
    {
      if (!outputtried)
      {
        g_output=fopen(argv[argpos]+2,"w");
        if (!g_output) 
        {
          if (build.display_errors) printf("Error opening output log for writing. Using stdout.\n");
          g_output=stdout;
        }
        outputtried=1;
      }
    }
    else if (!stricmp(argv[argpos],"/NOCD")) do_cd=0;
    else if (argv[argpos][0] == '/' && (argv[argpos][1] == 'V' || argv[argpos][1] == 'v') && 
             argv[argpos][2] >= '0' && argv[argpos][2] <= '4' && !argv[argpos][3])
    {
      int v=argv[argpos][2]-'0';
      build.display_script=v>3;
      build.display_info=v>2;
      build.display_warnings=v>1;
      build.display_errors=v>0;
      g_display_errors=build.display_errors;
    }
    else if (!stricmp(argv[argpos],"/NOCONFIG")) g_noconfig=1;
    else if (!stricmp(argv[argpos],"/PAUSE")) g_dopause=1;
    else if (!stricmp(argv[argpos],"/LICENSE")) 
    {
      if (build.display_info) 
      {
        fprintf(g_output,"This software is provided 'as-is', without any express or implied warranty.  In\n"
             "no event will the authors be held liable for any damages arising from the use\n"
             "of this software.\n\n"
             "Permission is granted to anyone to use this software for any purpose, including\n"
             "commercial applications, and to alter it and redistribute it freely, subject to\n"
             "the following restrictions:\n"
             "  1. The origin of this software must not be misrepresented; you must not claim\n"
             "     that you wrote the original software. If you use this software in a\n"
             "     product, an acknowledgment in the product documentation would be\n"
             "     appreciated but is not required.\n"
             "  2. Altered source versions must be plainly marked as such, and must not be\n"
             "     misrepresented as being the original software.\n"
             "  3. This notice may not be removed or altered from any source distribution.\n\n");
        fflush(g_output);
      }
      nousage++;
    }
    else if (!stricmp(argv[argpos],"/CMDHELP"))
    {
      if (argpos < argc-1)
        build.print_help(argv[++argpos]);
      else 
        build.print_help(NULL);
      nousage++;
    }
    else if (!stricmp(argv[argpos],"/NOTIFYHWND"))
    {
      build.notify_hwnd=(HWND)atol(argv[++argpos]);
      if (!IsWindow(build.notify_hwnd))
        build.notify_hwnd=0;
    }
    else if (!stricmp(argv[argpos],"/HDRINFO"))
    {
      if (build.display_info) 
      {
        fprintf(g_output,"Size of EXE header is %d bytes for zlib, %d bytes for bzip2.\n", zlib_exeheader_size,bzip2_exeheader_size);
        fprintf(g_output,"Size of info header is %d bytes.\n",sizeof(firstheader));
        fprintf(g_output,"Size of [un]install header is %d bytes,\n",sizeof(header));
        fprintf(g_output,"Size of each section is %d bytes.\n",sizeof(section));
        fprintf(g_output,"Size of each page is %d bytes.\n",sizeof(page));
        fprintf(g_output,"Size of each instruction is %d bytes.\n",sizeof(entry));
        int x=build.definedlist.getnum();
        fprintf(g_output,"\nDefined symbols: ");
        for (int i=0; i<x; i++)
        {
          fprintf(g_output,"%s",build.definedlist.getname(i));
          char *p=build.definedlist.getvalue(i);
          if (*p) fprintf(g_output,"=%s",p);
          if (i<x-1) fprintf(g_output,",");
        }
        if (!x) fprintf(g_output,"none");
        fprintf(g_output,"\n");
        fflush(g_output);
      }
      nousage++;
    }
    else 
    {
      if (argv[argpos][0]=='/') break;
      files_processed++;
      if (!strcmp(argv[argpos],"-")) g_dopause=0;
      if (!g_noconfig)
      {
        g_noconfig=1;
        char exepath[1024];
        GetModuleFileName(NULL,exepath,sizeof(exepath)-1);
        //strncpy(exepath,argv[0],1023);
        exepath[1023]=0;
        char *p=exepath;
        while (*p) p++;
        while (p > exepath && *p != '\\') p=CharPrev(exepath,p);
        if (p>exepath) p++;
        strcpy(p,"nsisconf.nsh");
        FILE *cfg=fopen(exepath,"rt");
        if (cfg)
        {
          if (build.display_script) 
          {
            fprintf(g_output,"\n\nProcessing config: \n");
            fflush(g_output);
          }
          int ret=build.process_script(cfg,exepath);
          fclose(cfg);
          if (ret != PS_OK && ret != PS_EOF)
          {
            if (build.display_errors) 
            {
              fprintf(g_output,"Error in config on line %d -- aborting creation process\n",build.linecnt);
              fflush(g_output);
            }
            return 1;
          }
        }
      }

      {
        char sfile[1024];
        if (!strcmp(argv[argpos],"-"))
        {
          fp=stdin;
          strcpy(sfile,"stdin");
        }
        else
        {
          strcpy(sfile,argv[argpos]);
          fp=fopen(sfile,"rt");
          if (!fp)
          {
            sprintf(sfile,"%s.nsi",argv[argpos]);
            fp=fopen(sfile,"rt");
            if (!fp)
            {
              if (build.display_errors) 
              {
                sfile[strlen(sfile)-4]=0;
                fprintf(g_output,"Can't open script \"%s\"\n",sfile);
                fflush(g_output);
              }
              return 1;
            }
          }
          if (do_cd)
          {
            char dirbuf[1024],*p;
            GetFullPathName(sfile,sizeof(dirbuf),dirbuf,&p);
            p=dirbuf;
            while (*p) p++;
            while (p > dirbuf && *p != '\\') p=CharPrev(dirbuf,p);
            *p=0;
            if (dirbuf[0]) 
            {
              if (build.display_script) 
              {
                fprintf(g_output,"Changing directory to: \"%s\"\n",dirbuf);
                fflush(g_output);
              }
              if (!SetCurrentDirectory(dirbuf))
              {
                if (build.display_errors)
                {
                  fprintf(g_output,"Error changing directory to \"%s\"\n",dirbuf);
                  fflush(g_output);
                }
                return 1;
              }
            }
          }
        }

        #ifdef NSIS_CONFIG_PLUGIN_SUPPORT
        // Added by Ximon Eighteen 5th August 2002
        if (!plugins_processed) {
          build.build_plugin_table();
          plugins_processed=1;
        }
        #endif //NSIS_CONFIG_PLUGIN_SUPPORT

        if (build.display_script) 
        {
          build.notify(MAKENSIS_NOTIFY_SCRIPT,sfile);
          fprintf(g_output,"\n\nProcessing script file: \"%s\"\n",sfile);
          fflush(g_output);
        }
        int ret=build.process_script(fp,sfile);
        if (fp != stdin) fclose(fp);

        if (ret != PS_EOF && ret != PS_OK)
        {
          if (build.display_errors) 
          {
            fprintf(g_output,"Error in script \"%s\" on line %d -- aborting creation process\n",sfile,build.linecnt);
            fflush(g_output);
          }
          return 1;
        }
      }
    }
    argpos++;
  }

  if (argpos<argc || (!files_processed && !cmds_processed))
  {
    if (build.display_errors && !nousage)
    {
      fprintf(g_output,"Usage:\n"
             "  makensis [options] [script.nsi | - [...]]\n"
             "   options are:\n"
             "    /CMDHELP item prints out help for 'item', or lists all commands\n"
             "    /HDRINFO prints information about what options makensis was compiled with\n"
             "    /LICENSE prints the makensis software license\n");
      fprintf(g_output,
             "    /Vx verbosity where x is 4=all,3=no script,2=no info,1=no warnings,0=none\n"
             "    /Ofile specifies a text file to log compiler output (default is stdout)\n"
             "    /PAUSE pauses after execution\n"
             "    /NOCONFIG disables inclusion of <path to makensis.exe>\\nsisconf.nsh\n"
             "    /NOCD disabled the current directory change to that of the .nsi file\n"
             "    /Ddefine[=value] defines the symbol \"define\" for the script [to value]\n"
             "    /Xscriptcmd executes scriptcmd in script (i.e. \"/XOutFile poop.exe\")\n"
             "   for script file name, you can use - to read from the standard input\n");
      fflush(g_output);
    }
    return 1;
  }

  if (build.display_info) 
  {
    fprintf(g_output,"\nProcessed ");
    if (files_processed) fprintf(g_output,"%d file%s, ",files_processed,files_processed==1?"":"s");
    if (cmds_processed) fprintf(g_output,"%d command line command%s, ",cmds_processed,cmds_processed==1?"":"s");
    fprintf(g_output,"writing output:\n");
    fflush(g_output);
  }
  
  if (build.write_output())
  { 
    if (build.display_errors) 
    {
      fprintf(g_output,"Error - aborting creation process\n");
      fflush(g_output);
    }
    return 1;
  }
  return 0; 
}
コード例 #18
0
bool DropCopyCommand::Execute()
{

	CString sDroppath = parser.GetVal(_T("droptarget"));
	if (CTGitPath(sDroppath).IsAdminDir())
	{
		CMessageBox::Show(NULL,_T("Can't drop to .git repository directory\n"),
							   _T("TortoiseGit"),MB_OK|MB_ICONERROR);
		return FALSE;
	}
	unsigned long count = 0;

	CString sNewName;
	pathList.RemoveAdminPaths();
	if ((parser.HasKey(_T("rename")))&&(pathList.GetCount()==1))
	{
		// ask for a new name of the source item
		do
		{
			CRenameDlg renDlg;
			renDlg.m_windowtitle.LoadString(IDS_PROC_COPYRENAME);
			renDlg.m_name = pathList[0].GetFileOrDirectoryName();
			if (renDlg.DoModal() != IDOK)
			{
				return FALSE;
			}
			sNewName = renDlg.m_name;
		} while(sNewName.IsEmpty() || PathFileExists(sDroppath+_T("\\")+sNewName));
	}
	CSysProgressDlg progress;
	progress.SetTitle(IDS_PROC_COPYING);
	progress.SetAnimation(IDR_MOVEANI);
	progress.SetTime(true);
	progress.ShowModeless(CWnd::FromHandle(hwndExplorer));
	for (int nPath = 0; nPath < pathList.GetCount(); ++nPath)
	{
		const CTGitPath& sourcePath = orgPathList[nPath];

		CTGitPath fullDropPath(sDroppath);

		if (sNewName.IsEmpty())
			fullDropPath.AppendPathString(sourcePath.GetFileOrDirectoryName());
		else
			fullDropPath.AppendPathString(sNewName);

		// Check for a drop-on-to-ourselves
		if (sourcePath.IsEquivalentTo(fullDropPath))
		{
			// Offer a rename
			progress.Stop();
			CRenameDlg dlg;
			dlg.m_windowtitle.Format(IDS_PROC_NEWNAMECOPY, (LPCTSTR)sourcePath.GetUIFileOrDirectoryName());
			if (dlg.DoModal() != IDOK)
			{
				return FALSE;
			}
			// rebuild the progress dialog
			progress.EnsureValid();
			progress.SetTitle(IDS_PROC_COPYING);
			progress.SetAnimation(IDR_MOVEANI);
			progress.SetTime(true);
			progress.SetProgress(count, pathList.GetCount());
			progress.ShowModeless(CWnd::FromHandle(hwndExplorer));
			// Rebuild the destination path, with the new name
			fullDropPath.SetFromUnknown(sDroppath);
			fullDropPath.AppendPathString(dlg.m_name);
		}

		if( CopyFile( sourcePath.GetWinPath(), fullDropPath.GetWinPath(), true))
		{
			CString ProjectTopDir;
			if(fullDropPath.HasAdminDir(&ProjectTopDir))
			{
				g_Git.SetCurrentDir(ProjectTopDir);
				SetCurrentDirectory(ProjectTopDir);
				CString cmd;
				cmd = _T("git.exe add \"");

				CString path;
				path=fullDropPath.GetGitPathString().Mid(ProjectTopDir.GetLength());
				if(path.GetLength()>0)
					if(path[0]==_T('\\') || path[0]==_T('/'))
						path=path.Mid(1);
				cmd += path;
				cmd +=_T('\"');

				CString output;
				if (g_Git.Run(cmd, &output, CP_UTF8))
				{
					CMessageBox::Show(NULL, output, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
				}else
					CShellUpdater::Instance().AddPathForUpdate(fullDropPath);
			}

		}else
		{
			CString str;
			str+=_T("Copy file fail:");
			str+=sourcePath.GetWinPath();

			CMessageBox::Show(NULL, str, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
		}

		++count;
		if (progress.IsValid())
		{
			progress.FormatPathLine(1, IDS_PROC_COPYINGPROG, sourcePath.GetWinPath());
			progress.FormatPathLine(2, IDS_PROC_CPYMVPROG2, fullDropPath.GetWinPath());
			progress.SetProgress(count, pathList.GetCount());
		}
		if ((progress.IsValid())&&(progress.HasUserCancelled()))
		{
			CMessageBox::Show(hwndExplorer, IDS_SVN_USERCANCELLED, IDS_APPNAME, MB_ICONINFORMATION);
			return false;
		}
	}

	return true;
}
コード例 #19
0
ファイル: FileMisc.cpp プロジェクト: noindom99/repositorium
void FileMisc::SetCwd(const CString& sCwd)
{
	SetCurrentDirectory(sCwd);
}
コード例 #20
0
ファイル: Main.c プロジェクト: kichik/nsis-1
NSIS_ENTRYPOINT_GUINOCRT
EXTERN_C void NSISWinMainNOCRT()
{
  int ret = 0;
  const TCHAR *m_Err = _LANG_ERRORWRITINGTEMP;

  int cl_flags = 0;

  TCHAR *realcmds;
  TCHAR seekchar=_T(' ');
  TCHAR *cmdline;

  InitCommonControls();

  SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);

#if defined(NSIS_SUPPORT_ACTIVEXREG) || defined(NSIS_SUPPORT_CREATESHORTCUT)
  {
    extern HRESULT g_hres;
    g_hres=OleInitialize(NULL);
  }
#endif

  // load shfolder.dll before any script code is executed to avoid
  // weird situations where SetOutPath or even the extraction of 
  // shfolder.dll will cause unexpected behavior.
  //
  // this also prevents the following:
  //
  //  SetOutPath "C:\Program Files\NSIS" # maybe read from reg
  //  File shfolder.dll
  //  Delete $PROGRAMFILES\shfolder.dll # can't be deleted, as the
  //                                    # new shfolder.dll is used
  //                                    # to find its own path.
  g_SHGetFolderPath = myGetProcAddress(MGA_SHGetFolderPath);

  {
    // workaround for bug #1008632
    // http://sourceforge.net/tracker/index.php?func=detail&aid=1008632&group_id=22049&atid=373085
    //
    // without this, SHGetSpecialFolderLocation doesn't always recognize
    // some special folders, like the desktop folder for all users, on
    // Windows 9x. unlike SHGetSpecialFolderPath, which is not available
    // on all versions of Windows, SHGetSpecialFolderLocation doesn't try
    // too hard to make sure the caller gets what he asked for. so we give
    // it a little push in the right direction by doing part of the work
    // for it.
    //
    // part of what SHGetFileInfo does, is to convert a path into an idl.
    // to do this conversion, it first needs to initialize the list of 
    // special idls, which are exactly the idls we use to get the paths
    // of special folders (CSIDL_*).

    SHFILEINFO shfi;
    SHGetFileInfo(_T(""), 0, &shfi, sizeof(SHFILEINFO), 0);
  }

  mystrcpy(g_caption,_LANG_GENERIC_ERROR);

  mystrcpy(state_command_line, GetCommandLine());

#ifdef NSIS_CONFIG_VISIBLE_SUPPORT
  g_hInstance = GetModuleHandle(NULL);
#endif//NSIS_CONFIG_VISIBLE_SUPPORT

  cmdline = state_command_line;
  if (*cmdline == _T('\"')) seekchar = *cmdline++;

  cmdline=findchar(cmdline, seekchar);
  cmdline=CharNext(cmdline);
  realcmds=cmdline;

  while (*cmdline)
  {
    // skip over any spaces
    while (*cmdline == _T(' ')) cmdline++;
    
    // get char we should look for to get the next parm
    seekchar = _T(' ');
    if (cmdline[0] == _T('\"'))
    {
      cmdline++;
      seekchar = _T('\"');
    }

    // is it a switch?
    if (cmdline[0] == _T('/'))
    {
      cmdline++;

#define END_OF_ARG(c) (c == _T(' ') || c == _T('\0'))

#if defined(NSIS_CONFIG_VISIBLE_SUPPORT) && defined(NSIS_CONFIG_SILENT_SUPPORT)
      if (cmdline[0] == _T('S') && END_OF_ARG(cmdline[1]))
        cl_flags |= FH_FLAGS_SILENT;
#endif//NSIS_CONFIG_SILENT_SUPPORT && NSIS_CONFIG_VISIBLE_SUPPORT
#ifdef NSIS_CONFIG_CRC_SUPPORT
      if (CMP4CHAR(cmdline, _T("NCRC")) && END_OF_ARG(cmdline[4]))
        cl_flags |= FH_FLAGS_NO_CRC;
#endif//NSIS_CONFIG_CRC_SUPPORT

      if (CMP4CHAR(cmdline-2, _T(" /D=")))
      {
        *(cmdline-2)=_T('\0'); // keep this from being passed to uninstaller if necessary
        mystrcpy(state_install_directory,cmdline+2);
        break; // /D= must always be last
      }
    }

    // skip over our parm
    cmdline = findchar(cmdline, seekchar);
    // skip the quote
    if (*cmdline == _T('\"'))
      cmdline++;
  }

  GetTempPath(NSIS_MAX_STRLEN, state_temp_dir);
  if (!ValidateTempDir())
  {
    GetWindowsDirectory(state_temp_dir, NSIS_MAX_STRLEN - 5); // leave space for \Temp
    mystrcat(state_temp_dir, _T("\\Temp"));
    if (!ValidateTempDir())
    {
      // Bug #2909242:
      // When running at <= Low IL we cannot write to %Temp% but we can try the temp folder used by IE.
      // There does not seem to be a API to get the low temp dir directly, so we build the path on our own

      GetTempPath(NSIS_MAX_STRLEN - 4, state_temp_dir); // leave space for \Low
      mystrcat(state_temp_dir, _T("Low"));

      // If we don't call SetEnvironmentVariable 
      // child processes will use %temp% and not %temp%\Low
      // and some apps probably can't handle a read only %temp%
      // Do it before ValidateTempDir() because it appends a backslash.
      // TODO: Should this be moved to ValidateTempDir() so it also updates for %windir%\Temp?
      SetEnvironmentVariable(_T("TEMP"), state_temp_dir);
      SetEnvironmentVariable(_T("TMP"), state_temp_dir);

      if (!ValidateTempDir())
      {
        goto end;
      }
    }
  }
  DeleteFile(state_language);

  m_Err = loadHeaders(cl_flags);
  if (m_Err) goto end;

#ifdef NSIS_CONFIG_UNINSTALL_SUPPORT
  if (g_is_uninstaller)
  {
    TCHAR *p = findchar(state_command_line, 0);

    // state_command_line has state_install_directory right after it in memory, so reading
    // a bit over state_command_line won't do any harm
    while (p >= state_command_line && !CMP4CHAR(p, _T(" _?="))) p--;

    m_Err = _LANG_UNINSTINITERROR;

    if (p >= state_command_line)
    {
      *p=0; // terminate before "_?="
      p+=4; // skip over " _?="
      if (is_valid_instpath(p))
      {
        mystrcpy(state_install_directory, p);
        mystrcpy(state_output_directory, p);
        m_Err = 0;
      }
      else
      {
        goto end;
      }
    }
    else
    {
      int x;

      mystrcat(state_temp_dir,_T("~nsu.tmp"));

      // check if already running from uninstaller temp dir
      // this prevents recursive uninstaller calls
      if (!lstrcmpi(state_temp_dir,state_exe_directory))
        goto end;

      CreateDirectory(state_temp_dir,NULL);
      SetCurrentDirectory(state_temp_dir);

      if (!state_install_directory[0])
        mystrcpy(state_install_directory,state_exe_directory);

      mystrcpy(g_usrvars[0], realcmds);
      SET2CHAR(g_usrvars[1], _T("A\0"));

      for (x = 0; x < 26; x ++)
      {
        static TCHAR buf2[NSIS_MAX_STRLEN];

        GetNSISString(buf2,g_header->str_uninstchild); // $TEMP\$1u_.exe

        DeleteFile(buf2); // clean up after all the other ones if they are there

        if (m_Err) // not done yet
        {
          // copy file
          if (CopyFile(state_exe_path,buf2,TRUE))
          {
            HANDLE hProc;
#ifdef NSIS_SUPPORT_MOVEONREBOOT
            MoveFileOnReboot(buf2,NULL);
#endif
            GetNSISString(buf2,g_header->str_uninstcmd); // '"$TEMP\$1u_.exe" $0 _?=$INSTDIR\'
            hProc=myCreateProcess(buf2);
            if (hProc)
            {
              CloseHandle(hProc);
              // success
              m_Err = 0;
            }
          }
        }
        g_usrvars[1][0]++;
      }

#ifdef NSIS_SUPPORT_MOVEONREBOOT
      MoveFileOnReboot(state_temp_dir,NULL);
#endif

      goto end;
    }
  }
#endif//NSIS_CONFIG_UNINSTALL_SUPPORT

  g_exec_flags.errlvl = -1;
  ret = ui_doinstall();

#ifdef NSIS_CONFIG_LOG
#if !defined(NSIS_CONFIG_LOG_ODS) && !defined(NSIS_CONFIG_LOG_STDOUT)
  log_write(1);
#endif//!NSIS_CONFIG_LOG_ODS && !NSIS_CONFIG_LOG_STDOUT
#endif//NSIS_CONFIG_LOG
end:

  CleanUp();

#if defined(NSIS_SUPPORT_ACTIVEXREG) || defined(NSIS_SUPPORT_CREATESHORTCUT)
  OleUninitialize();
#endif

  if (m_Err)
  {
    my_MessageBox(m_Err, MB_OK | MB_ICONSTOP | (IDOK << 21));
    ExitProcess(2);
  }

#ifdef NSIS_SUPPORT_REBOOT
  if (g_exec_flags.reboot_called)
  {
    BOOL (WINAPI *OPT)(HANDLE, DWORD,PHANDLE);
    BOOL (WINAPI *LPV)(LPCTSTR,LPCTSTR,PLUID);
    BOOL (WINAPI *ATP)(HANDLE,BOOL,PTOKEN_PRIVILEGES,DWORD,PTOKEN_PRIVILEGES,PDWORD);
    OPT=myGetProcAddress(MGA_OpenProcessToken);
    LPV=myGetProcAddress(MGA_LookupPrivilegeValue);
    ATP=myGetProcAddress(MGA_AdjustTokenPrivileges);
    if (OPT && LPV && ATP)
    {
      HANDLE hToken;
      TOKEN_PRIVILEGES tkp;
      if (OPT(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
      {
        LPV(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);
        tkp.PrivilegeCount = 1;
        tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
        ATP(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
      }
    }

    if (!ExitWindowsEx(EWX_REBOOT,0))
      ExecuteCallbackFunction(CB_ONREBOOTFAILED);
  }
#endif//NSIS_SUPPORT_REBOOT

  if (g_exec_flags.errlvl != -1)
    ret = g_exec_flags.errlvl;

  ExitProcess(ret);
}
コード例 #21
0
unsigned int __stdcall InstallAction ( MSIHANDLE hModule )
{
    // store the original path
    char ORIG_PATH[MAX_PATH_SIZE] = {0};  // c:\somewhere
    GetCurrentDirectory(MAX_PATH_SIZE, ORIG_PATH);

    if (InitGlobal() == false)
    {
        return 0;
    }
    
    ExtractBinaryFile(hModule, "JarPack", g_TEMP_INSTALLER_JAR);

    do_extract(g_TEMP_INSTALLER_JAR);

	// get JnlpFileName Property from msi Property table
    char jnlpFileName[256] = {0};
    GetMsiProperty(hModule, jnlpFileName, "JnlpFileName");
    char TEMP_JNLP_FILE[MAX_PATH_SIZE] = {0};  // C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\[javaws4c1.tmp]\draw.jnlp
    sprintf(TEMP_JNLP_FILE, "%s\\%s", g_TEMP_JAVAWS_PATH, jnlpFileName);

	// get Shortcut Property from msi Property table
    char shortcut[256] = {0};
    GetMsiProperty(hModule, shortcut, "Shortcut");
    if(shortcut[0] != '0')
    {
        strncpy(g_SHORTCUT, "-shortcut", strlen("-shortcut"));
    }

	// get CacheType Property from msi Property table
    char cachetype[256] = {0};
    GetMsiProperty(hModule, cachetype, "CacheType");
    if(0 == stricmp(cachetype, "system"))
    {
        strncpy(g_CACHE_TYPE, "-system", strlen("-system"));
    }

	// get Association Property from msi Property table
    char association[256] = {0};
    GetMsiProperty(hModule, association, "Association");
    if(association[0] != '0')
    {
        strncpy(g_ASSOCIATION, "-association", strlen("-association"));
    }

    // install the jnlp software
    STARTUPINFO stinfo = {0}; //info of the window
    stinfo.cb = sizeof(STARTUPINFO);
    PROCESS_INFORMATION procinfo; //info of the process
    char CREATEPROCESS[MAX_PATH_SIZE] = {0};  // javaws -silent -import -system -codebase %s
    sprintf(CREATEPROCESS, "%s\\javaws %s -silent -import %s %s -codebase \"%s\" %s", 
        g_JAVAWS_HOME, g_CACHE_TYPE, g_SHORTCUT, g_ASSOCIATION, g_TEMP_JAVAWS_URL, TEMP_JNLP_FILE);

    if(!CreateProcess(NULL, CREATEPROCESS, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &stinfo, &procinfo))
    {
        return 0;
    }
    
    // wait for the end of the process
    WaitForSingleObject(procinfo.hProcess, INFINITE);
    CloseHandle(procinfo.hProcess);
    CloseHandle(procinfo.hThread);

    // restore to original path & Remove the generated temporary directory
    SetCurrentDirectory(ORIG_PATH);
    RemoveDir(g_TEMP_JAVAWS_PATH);

    return ERROR_SUCCESS;
}
コード例 #22
0
ファイル: browse.c プロジェクト: kichik/nsis-1
void __declspec(dllexport) SelectFileDialog(HWND hwndParent, int string_size, char *variables, stack_t **stacktop, extra_parameters *extra)
{
  OPENFILENAME ofn={0,}; // XXX WTF
  int save;
  char type[5];
  static char path[1024];
  static char filter[1024];
  static char currentDirectory[1024];
  static char initialDir[1024];
  DWORD gfa;

  EXDLL_INIT();

  ofn.lStructSize = sizeof(OPENFILENAME);
  ofn.hwndOwner = hwndParent;
  ofn.lpstrFilter = filter;
  ofn.lpstrFile = path;
  ofn.nMaxFile  = sizeof(path);
  //ofn.Flags = pField->nFlags & (OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_CREATEPROMPT | OFN_EXPLORER);
  ofn.Flags = OFN_CREATEPROMPT | OFN_EXPLORER;

  popstringn(type, sizeof(type));
  popstringn(path, sizeof(path));
  popstringn(filter, sizeof(filter));

  save = !lstrcmpi(type, "save");

  // Check if the path given is a folder. If it is we initialize the 
  // ofn.lpstrInitialDir parameter
  gfa = GetFileAttributes(path);
  if ((gfa != INVALID_FILE_ATTRIBUTES) && (gfa & FILE_ATTRIBUTE_DIRECTORY))
  {
    lstrcpy(initialDir, path);
    ofn.lpstrInitialDir = initialDir;
    path[0] = '\0'; // disable initial file selection as path is actually a directory
  }

  if (!filter[0])
  {
    lstrcpy(filter, "All Files|*.*");
  }

  {
    // Convert the filter to the format required by Windows: NULL after each
    // item followed by a terminating NULL
    char *p = filter;
    while (*p) // XXX take care for 1024
    {
      if (*p == '|')
      {
        *p++ = 0;
      }
      else
      {
        p = CharNext(p);
      }
    }
    p++;
    *p = 0;
  }

  GetCurrentDirectory(sizeof(currentDirectory), currentDirectory); // save working dir

  if ((save ? GetSaveFileName(&ofn) : GetOpenFileName(&ofn)))
  {
    pushstring(path);
  }
  else if (CommDlgExtendedError() == FNERR_INVALIDFILENAME)
  {
    *path = '\0';
    if ((save ? GetSaveFileName(&ofn) : GetOpenFileName(&ofn)))
    {
      pushstring(path);
    }
    else
    {
      pushstring("");
    }
  }
  else
  {
    pushstring("");
  }

  // restore working dir
  // OFN_NOCHANGEDIR doesn't always work (see MSDN)
  SetCurrentDirectory(currentDirectory);
}
コード例 #23
0
ファイル: SceneEditorCommon.cpp プロジェクト: viticm/pap2
BOOL Init3DEngine(unsigned uMode, unsigned int uFlag, HWND hBaseWindow, HWND hRenderWindow, BSTR strEnginePath, BSTR strStartUpPath)
{
	ATLTRACE("#####################3DEngine Initializing!##################\r\n");

	BOOL bRetCode = false;
	KGLOG_PARAM LogParam;
	char szCWD[MAX_PATH];
	getcwd(szCWD, sizeof(szCWD));
	memset(&LogParam, 0, sizeof(LogParam));
	snprintf(LogParam.szPath,sizeof(LogParam.szPath),"%s\\logs",szCWD);
	LogParam.szPath[sizeof(LogParam.szPath) - 1] = '\0';

	strcpy(LogParam.szIdent, "AtlaxKG3D");
	LogParam.nMaxLineEachFile = 65536;
	LogParam.Options = (KGLOG_OPTIONS)KGLOG_OPTION_FILE;
	bRetCode = KGLogInit(LogParam, NULL);
	if (!bRetCode)
	{
		::MessageBox(NULL, "Log文件初始化失败!", NULL, NULL);
		return FALSE;
	}

	TCHAR szCurDir[MAX_PATH];
	sprintf(szCurDir, BSTR_TO_STRING(strStartUpPath));
	strcat(szCurDir, "/3DProxy/");
	g_SetRootPath(szCurDir);
	SetCurrentDirectory(szCurDir);

	KGLogPrintf(KGLOG_DEBUG, "strStartUpPath=%s", BSTR_TO_STRING(strStartUpPath));
	
#ifdef _DEBUG
	strcat(szCurDir, "KG3DEngineD.dll");
#else
	strcat(szCurDir, "KG3DEngine.dll");
#endif
	g_3dEngineDll.Init(szCurDir);
	KGLogPrintf(KGLOG_DEBUG, "%s loaddll成功", szCurDir);

	g_SetRootPath(BSTR_TO_STRING(strEnginePath)); // in Engine_lua5(D).dll
	lstrcpy(g_EnginePath, BSTR_TO_STRING(strEnginePath));
	SetCurrentDirectory(BSTR_TO_STRING(strEnginePath));
	lstrcpy(g_szDefWorkDirectory, g_EnginePath);

	HMODULE h = g_3dEngineDll.GetDllHandle();
	_ASSERTE(h);
	if (!h) return FALSE;
	
	KGLogPrintf(KGLOG_DEBUG, "g_3dEngineDll loaddll成功");	

	if (lstrlen(g_EnginePath) <= 0)
	{
		HMODULE hDll = GetModuleHandle("atlax.dll");
		if (hDll)
		{
			KGLogPrintf(KGLOG_DEBUG, "atlax.dll loaddll成功");
			TCHAR szBuf[MAX_PATH + 1];
			GetModuleFileName(hDll, szBuf, MAX_PATH);
			CString strTemp = szBuf;
			CString strDir = strTemp.Left(strTemp.ReverseFind('\\'));
			SetCurrentDirectory(strDir);
		}
	}
	else //
	{
		SetCurrentDirectory(g_EnginePath);
	}

	typedef HRESULT (*pfnGet3DEngineInterface)(void** pEngineManager);
	pfnGet3DEngineInterface Get3DEngineInterface = (pfnGet3DEngineInterface)GetProcAddress(h, "Get3DEngineInterface");
	_ASSERTE(Get3DEngineInterface);
	if (!Get3DEngineInterface) return FALSE;

	IEKG3DEngineManager* pInterface = NULL;
	HRESULT hret = Get3DEngineInterface((void**)&pInterface);
	if (FAILED(hret))
		return FALSE;
	else
	{
		KGLogPrintf(KGLOG_DEBUG, "pre pInterface->Init");

        if (FAILED(pInterface->Init(uMode, uFlag, hBaseWindow, hRenderWindow)))
        {
            return FALSE;
        }

        pInterface->SetAutoReloadTexture(TRUE);

		InitGlobalVars(pInterface);
		ATLTRACE("=================3DEngine Initialized!==================\r\n");
		return TRUE;
	}
}
コード例 #24
0
ファイル: nt_svc.c プロジェクト: RevanthPar/openldap
/* in ntservice.c */
int main( int argc, LPTSTR *argv )
{
	int		length;
	char	filename[MAX_PATH], *fname_start;

	/*
	 * Because the service was registered as SERVICE_WIN32_OWN_PROCESS,
	 * the lpServiceName element of the SERVICE_TABLE_ENTRY will be
	 * ignored.
	 */

	SERVICE_TABLE_ENTRY		DispatchTable[] = {
		{	"",	(LPSERVICE_MAIN_FUNCTION) ServiceMain	},
		{	NULL,			NULL	}
	};

	/*
	 * set the service's current directory to the installation directory
	 * for the service. this way we don't have to write absolute paths
	 * in the configuration files
	 */
	GetModuleFileName( NULL, filename, sizeof( filename ) );
	fname_start = strrchr( filename, *LDAP_DIRSEP );

	if ( argc > 1 ) {
		if ( _stricmp( "install", argv[1] ) == 0 ) 
		{
			char *svcName = SERVICE_NAME;
			char *displayName = "OpenLDAP Directory Service";
			BOOL auto_start = FALSE;

			if ( (argc > 2) && (argv[2] != NULL) )
				svcName = argv[2];

			if ( argc > 3 && argv[3])
				displayName = argv[3];

			if ( argc > 4 && stricmp(argv[4], "auto") == 0)
				auto_start = TRUE;

			strcat(filename, " service");
			if ( !lutil_srv_install(svcName, displayName, filename, auto_start) ) 
			{
				fputs( "service failed installation ...\n", stderr  );
				return EXIT_FAILURE;
			}
			fputs( "service has been installed ...\n", stderr  );
			return EXIT_SUCCESS;
		}

		if ( _stricmp( "remove", argv[1] ) == 0 ) 
		{
			char *svcName = SERVICE_NAME;
			if ( (argc > 2) && (argv[2] != NULL) )
				svcName = argv[2];
			if ( !lutil_srv_remove(svcName, filename) ) 
			{
				fputs( "failed to remove the service ...\n", stderr  );
				return EXIT_FAILURE;
			}
			fputs( "service has been removed ...\n", stderr );
			return EXIT_SUCCESS;
		}
		if ( _stricmp( "service", argv[1] ) == 0 )
		{
			is_NT_Service = 1;
			*fname_start = '\0';
			SetCurrentDirectory( filename );
		}
	}

	if (is_NT_Service)
	{
		StartServiceCtrlDispatcher(DispatchTable);
	} else
	{
		ServiceMain( argc, argv );
	}

	return EXIT_SUCCESS;
}
コード例 #25
0
TEST(libgit, Mailmap)
{
	CAutoTempDir tempdir;
	g_Git.m_CurrentDir = tempdir.GetTempDir();
	// libgit relies on CWD being set to working tree
	SetCurrentDirectory(g_Git.m_CurrentDir);

	GIT_MAILMAP mailmap = (void*)0x12345678;
	git_read_mailmap(&mailmap);
	EXPECT_EQ(nullptr, mailmap);

	CString mailmapFile = tempdir.GetTempDir() + L"\\.mailmap";
	EXPECT_TRUE(CStringUtils::WriteStringToTextFile(mailmapFile, L""));

	mailmap = (void*)0x12345678;
	git_read_mailmap(&mailmap);
	EXPECT_EQ(nullptr, mailmap);

	EXPECT_TRUE(CStringUtils::WriteStringToTextFile(mailmapFile, L"Sven Strickroth <*****@*****.**>"));
	git_read_mailmap(&mailmap);
	EXPECT_NE(nullptr, mailmap);
	const char* email1 = nullptr;
	const char* author1 = nullptr;
	EXPECT_EQ(-1, git_lookup_mailmap(mailmap, &email1, &author1, "*****@*****.**", nullptr, [](void*) { return "Sven S."; }));
	EXPECT_EQ(0, git_lookup_mailmap(mailmap, &email1, &author1, "*****@*****.**", nullptr, [](void*) { return "Sven S."; }));
	EXPECT_EQ(nullptr, email1);
	EXPECT_STREQ("Sven Strickroth", author1);

	email1 = nullptr;
	author1 = nullptr;
	EXPECT_EQ(0, git_lookup_mailmap(mailmap, &email1, &author1, "*****@*****.**", nullptr, [](void*) { return "Sven S."; }));
	EXPECT_EQ(nullptr, email1);
	EXPECT_STREQ("Sven Strickroth", author1);

	git_free_mailmap(mailmap);
	CString content;
	for (auto& entry : { L"", L"1", L"2", L"A", L"4", L"5", L"b", L"7" })
		content.AppendFormat(L"Sven%s Strickroth <*****@*****.**> <*****@*****.**>\n", entry, entry, entry);
	EXPECT_TRUE(CStringUtils::WriteStringToTextFile(mailmapFile, content));
	git_read_mailmap(&mailmap);
	EXPECT_NE(nullptr, mailmap);
	email1 = nullptr;
	author1 = nullptr;
	EXPECT_EQ(-1, git_lookup_mailmap(mailmap, &email1, &author1, "*****@*****.**", nullptr, [](void*) { return "Sven S."; }));
	EXPECT_EQ(-1, git_lookup_mailmap(mailmap, &email1, &author1, "*****@*****.**", nullptr, [](void*) { return "Sven S."; }));
	EXPECT_EQ(-1, git_lookup_mailmap(mailmap, &email1, &author1, "*****@*****.**", nullptr, [](void*) { return "Sven S."; }));
	for (auto& entry : { "", "1", "2", "A", "4", "5", "b", "7" })
	{
		CStringA maillookup, mail, name;
		maillookup.Format("*****@*****.**", entry);
		mail.Format("*****@*****.**", entry);
		name.Format("Sven%s Strickroth", entry);
		email1 = nullptr;
		author1 = nullptr;
		EXPECT_EQ(0, git_lookup_mailmap(mailmap, &email1, &author1, maillookup, nullptr, [](void*) { return "Sven S."; }));
		EXPECT_STREQ(mail, email1);
		EXPECT_STREQ(name, author1);
	}

	email1 = nullptr;
	author1 = nullptr;
	EXPECT_EQ(0, git_lookup_mailmap(mailmap, &email1, &author1, "*****@*****.**", nullptr, [](void*) { return "Sven Strickroth"; }));
	EXPECT_STREQ("*****@*****.**", email1);
	EXPECT_STREQ("Sven Strickroth", author1);

	git_free_mailmap(mailmap);
	EXPECT_TRUE(CStringUtils::WriteStringToTextFile(mailmapFile, L"<*****@*****.**> <*****@*****.**>\nSven S. <*****@*****.**> Sven Strickroth <*****@*****.**>"));
	git_read_mailmap(&mailmap);
	EXPECT_NE(nullptr, mailmap);
	email1 = nullptr;
	author1 = nullptr;
	EXPECT_EQ(-1, git_lookup_mailmap(mailmap, &email1, &author1, "*****@*****.**", nullptr, [](void*) { return "Sven S."; }));
	EXPECT_EQ(-1, git_lookup_mailmap(mailmap, &email1, &author1, "*****@*****.**", nullptr, [](void*) { return "Sven S."; }));
	EXPECT_EQ(-1, git_lookup_mailmap(mailmap, &email1, &author1, "*****@*****.**", nullptr, [](void*) { return "Sven S."; }));
	EXPECT_EQ(0, git_lookup_mailmap(mailmap, &email1, &author1, "*****@*****.**", nullptr, [](void*) { return "Sven S."; }));
	EXPECT_STREQ("*****@*****.**", email1);
	EXPECT_STREQ(nullptr, author1);
	email1 = nullptr;
	author1 = nullptr;
	EXPECT_EQ(0, git_lookup_mailmap(mailmap, &email1, &author1, "*****@*****.**", nullptr, [](void*) { return "Sven Strickroth"; }));
	EXPECT_STREQ("*****@*****.**", email1);
	EXPECT_STREQ("Sven S.", author1);
}
コード例 #26
0
ファイル: GamePlace.cpp プロジェクト: lincoln56/robinerp
//初始化函数
BOOL CGamePlaceApp::InitInstance()
{
//TODO: call AfxInitRichEdit2() to initialize richedit2 library.
	Glb().m_release=false;//是否发布版
	Glb().m_weblogon=false;	//是否互联星空登录
	Glb().m_autoreg=false;	//不用设置,此变量程序自动改变


#ifndef MY_DEBUG
	Glb().m_release=true;//是否发布版
//	try
#endif
	{
		//定义变量
#ifndef MY_DEBUG
		CBcfFile _f(CBcfFile::GetAppPath()+"bzgame.bcf");
		CString _mutexId = _f.GetKeyVal("BZW","mutexid","GamePlaceChangeed10001000");

		CMutex Mutex(FALSE, _mutexId, NULL);////互斥
		if (Mutex.Lock(0)==FALSE)
			return FALSE;
		SetUnhandledExceptionFilter(ExceptionFilter);
#endif		


#ifdef BZ_ZLIB
		///<读取资源文件
		///<先获取密码  add by wxx 
		CBcfFile fMsg(CBcfFile::GetAppPath()+"bzgame.bcf");
		CString strPassWord;
		strPassWord = fMsg.GetKeyVal("BZW","LoginIP1","www.szbzw.com");
		char *password = strPassWord.GetBuffer(strPassWord.GetLength()+1);

		///<读取文件
		CUnZipRes unZipRes;
		char * pPW=new char[strlen(password)+1];
		memcpy(pPW,password,strlen(password)+1);
		unZipRes.SetPassWord(pPW);

		if(!CBcfFile::IsFileExist("image.r"))///add by wxx 0712
		{
			MessageBox(NULL,"资源文件有损!","提示",MB_OK);
			return FALSE;
		}

		CString strPackage = CBcfFile::GetAppPath() + "image.r";
		BzDui::CPaintManagerUI::SetResourcePackage(strPackage.GetBuffer(),password);

		unZipRes.ReadFile("image.r",(unsigned char*)pPW);
        delete []pPW;
#endif
		//初始化
		InitCommonControls();
		CWinApp::InitInstance();

#ifndef MY_DEV

		// 初始BzCrashRpt
		BzCrash_Initiation();
		BzCrash_DisableSetUnhandledExceptionFilter();
		BzCrash_SetProjectName("D平台大厅");
		BzCrash_SetEmailSender("*****@*****.**");
		BzCrash_SetEmailReceiver("*****@*****.**");
		BzCrash_SetSmtpServer("smtp.sina.com");
		BzCrash_SetSmtpUser("bzbugrev");
		BzCrash_SetSmtpPassword("1122334455");
		BzCrash_DeleteSended(false);
#endif

		//初始化 SOCKET
		if (!AfxSocketInit())
		{
			AfxMessageBox(IDP_SOCKETS_INIT_FAILED);
			return FALSE;
		}
		AfxEnableControlContainer();
		SetRegistryKey(IDS_REG_KEY);

		//设置程序路径
		TCHAR szModuleName[MAX_PATH];
		DWORD dwLength=GetModuleFileName(AfxGetInstanceHandle(),szModuleName,sizeof(szModuleName));
		szModuleName[dwLength-lstrlen(m_pszExeName)-lstrlen(TEXT(".EXE"))-1]=0;
		SetCurrentDirectory(szModuleName);
		CreateDirectory("CustomFace",NULL);

		CString str;
		int len=strlen(szModuleName);
		szModuleName[len]='\\';
		szModuleName[len+1]='\0';
		AfxGetApp()->WriteProfileString(TEXT("LogonInfo"),TEXT("Path"),szModuleName);
		Glb().m_Path=szModuleName;

		//初始化全局资源
		AfxInitRichEdit();
		CGameImageLink::InitResource();

		// 加载钩子
		DetourFunctionWithTrampoline((PBYTE)SetScrollInfoT, (PBYTE)SetScrollInfoD);
		DetourFunctionWithTrampoline((PBYTE)GetScrollInfoT, (PBYTE)GetScrollInfoD);
		DetourFunctionWithTrampoline((PBYTE)SetScrollPosT, (PBYTE)SetScrollPosD);
		DetourFunctionWithTrampoline((PBYTE)GetScrollPosT, (PBYTE)GetScrollPosD);
		DetourFunctionWithTrampoline((PBYTE)SetScrollRangeT, (PBYTE)SetScrollRangeD);
		DetourFunctionWithTrampoline((PBYTE)GetScrollRangeT, (PBYTE)GetScrollRangeD);
		DetourFunctionWithTrampoline((PBYTE)ShowScrollBarT, (PBYTE)ShowScrollBarD);
		DetourFunctionWithTrampoline((PBYTE)EnableScrollBarT, (PBYTE)EnableScrollBarD);


		//引入DirectUI支持,初始化DirectUI
		BzDui::CPaintManagerUI::SetInstance(m_hInstance);

		CString s = CBcfFile::GetAppPath ();/////本地路径
		CString strSkin = m_skinmgr.GetSkinBcfFileName();
		CBcfFile f(s + strSkin);
		TCHAR szUIPath[MAX_PATH];
		CString skinfolder = f.GetKeyVal(m_skinmgr.GetKeyVal(strSkin),"skinfolder",m_skinmgr.GetSkinPath());
		wsprintf(szUIPath,"%s",skinfolder);

		BzDui::CPaintManagerUI::SetResourcePath(szUIPath);

		//建立对话框 
		CGamePlaceDlg dlg;
		m_pMainWnd=&dlg;
		//BZUIInitial();
		dlg.DoModal();
		///////////////////////////////////////////////////////////
		///Kylin 20090107  添加最近游戏列表

		//CString s=CBcfFile::GetAppPath (false);/////本地路径
		//CBcfFile f( s + "bzgame.bcf");
		//CString temp="";


		//try
		//{
		//	for(int i=0;i<Glb().m_baFavorSave.GetCount();i++)
		//	{
		//		temp.Format("%s%i;",temp,Glb().m_baFavorSave[i]);
		//	}
		//	f.SetKeyValString(Glb().m_key,"Favor",temp);
		//}
		//catch (...)
		//{
		//	return FALSE;
		//}
		///////////////////////////////////////////////////////////
		//BZUIShutDown();
	}
#ifndef MY_DEBUG
	//catch (...)
	//{
	//	//重新启动游戏
	//	STARTUPINFO StartInfo;
	//	PROCESS_INFORMATION Info;
	//	::memset(&Info,0,sizeof(Info));
	//	::memset(&StartInfo,0,sizeof(StartInfo));
	//	StartInfo.cb=sizeof(StartInfo);
	//	StartInfo.wShowWindow=SW_SHOWMAXIMIZED;
	//	CreateProcess(NULL,TEXT("BZW.exe"),NULL,NULL,TRUE,CREATE_DEFAULT_ERROR_MODE,NULL,NULL,&StartInfo,&Info);
	//}
#endif

	return FALSE;
}
コード例 #27
0
INT_PTR CALLBACK ConfigureBitmapTransitionProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch(message)
    {
        case WM_INITDIALOG:
            {
                ConfigBitmapInfo *configInfo = (ConfigBitmapInfo*)lParam;
                SetWindowLongPtr(hwnd, DWLP_USER, (LONG_PTR)configInfo);
                LocalizeWindow(hwnd);

                //--------------------------

                HWND hwndTemp = GetDlgItem(hwnd, IDC_BITMAPS);

                StringList bitmapList;
                configInfo->data->GetStringList(TEXT("bitmap"), bitmapList);
                for(UINT i=0; i<bitmapList.Num(); i++)
                {
                    CTSTR lpBitmap = bitmapList[i];

                    if(OSFileExists(lpBitmap))
                        SendMessage(hwndTemp, LB_ADDSTRING, 0, (LPARAM)lpBitmap);
                }

                //--------------------------

                hwndTemp = GetDlgItem(hwnd, IDC_TRANSITIONTIME);

                UINT transitionTime = configInfo->data->GetInt(TEXT("transitionTime"));
                SendMessage(hwndTemp, UDM_SETRANGE32, MIN_TRANSITION_TIME, MAX_TRANSITION_TIME);

                if(!transitionTime)
                    transitionTime = 10;

                SendMessage(hwndTemp, UDM_SETPOS32, 0, transitionTime);

                EnableWindow(GetDlgItem(hwnd, IDC_REPLACE), FALSE);
                EnableWindow(GetDlgItem(hwnd, IDC_REMOVE), FALSE);
                EnableWindow(GetDlgItem(hwnd, IDC_MOVEUPWARD), FALSE);
                EnableWindow(GetDlgItem(hwnd, IDC_MOVEDOWNWARD), FALSE);

                //--------------------------

                BOOL bFadeInOnly = configInfo->data->GetInt(TEXT("fadeInOnly"), 1);
                BOOL bDisableFading = configInfo->data->GetInt(TEXT("disableFading"));
                BOOL bRandomize = configInfo->data->GetInt(TEXT("randomize"));
                SendMessage(GetDlgItem(hwnd, IDC_FADEINONLY), BM_SETCHECK, bFadeInOnly ? BST_CHECKED : BST_UNCHECKED, 0);
                SendMessage(GetDlgItem(hwnd, IDC_DISABLEFADING), BM_SETCHECK, bDisableFading ? BST_CHECKED : BST_UNCHECKED, 0);
                SendMessage(GetDlgItem(hwnd, IDC_RANDOMIZE), BM_SETCHECK, bRandomize ? BST_CHECKED : BST_UNCHECKED, 0);
                
                
                EnableWindow(GetDlgItem(hwnd, IDC_FADEINONLY), !bDisableFading);

                return TRUE;
            }

        case WM_COMMAND:
            switch(LOWORD(wParam))
            {
                case IDC_ADD:
                    {
                        TSTR lpFile = (TSTR)Allocate(32*1024*sizeof(TCHAR));
                        zero(lpFile, 32*1024*sizeof(TCHAR));

                        OPENFILENAME ofn;
                        zero(&ofn, sizeof(ofn));
                        ofn.lStructSize = sizeof(ofn);
                        ofn.lpstrFile = lpFile;
                        ofn.hwndOwner = hwnd;
                        ofn.nMaxFile = 32*1024*sizeof(TCHAR);
                        ofn.lpstrFilter = TEXT("All Formats (*.bmp;*.dds;*.jpg;*.png;*.gif)\0*.bmp;*.dds;*.jpg;*.png;*.gif\0");
                        ofn.nFilterIndex = 1;
                        ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_ALLOWMULTISELECT | OFN_EXPLORER;

                        TCHAR curDirectory[MAX_PATH+1];
                        GetCurrentDirectory(MAX_PATH, curDirectory);

                        BOOL bOpenFile = GetOpenFileName(&ofn);

                        TCHAR newDirectory[MAX_PATH+1];
                        GetCurrentDirectory(MAX_PATH, newDirectory);

                        SetCurrentDirectory(curDirectory);

                        if(bOpenFile)
                        {
                            TSTR lpCurFile = lpFile+ofn.nFileOffset;

                            while(lpCurFile && *lpCurFile)
                            {
                                String strPath;
                                strPath << newDirectory << TEXT("\\") << lpCurFile;

                                SendMessage(GetDlgItem(hwnd, IDC_BITMAPS), LB_ADDSTRING, 0, (LPARAM)strPath.Array());

                                lpCurFile += slen(lpCurFile)+1;
                            }
                        }

                        Free(lpFile);

                        break;
                    }

                case IDC_BITMAPS:
                    if(HIWORD(wParam) == LBN_SELCHANGE)
                    {
                        EnableWindow(GetDlgItem(hwnd, IDC_REPLACE), TRUE);
                        EnableWindow(GetDlgItem(hwnd, IDC_REMOVE), TRUE);
                        EnableWindow(GetDlgItem(hwnd, IDC_MOVEUPWARD), TRUE);
                        EnableWindow(GetDlgItem(hwnd, IDC_MOVEDOWNWARD), TRUE);
                    }
                    break;

                case IDC_REMOVE:
                    {
                        UINT curSel = (UINT)SendMessage(GetDlgItem(hwnd, IDC_BITMAPS), LB_GETCURSEL, 0, 0);
                        if(curSel != LB_ERR)
                        {
                            SendMessage(GetDlgItem(hwnd, IDC_BITMAPS), LB_DELETESTRING, curSel, 0);
                            EnableWindow(GetDlgItem(hwnd, IDC_REPLACE), FALSE);
                            EnableWindow(GetDlgItem(hwnd, IDC_REMOVE), FALSE);
                            EnableWindow(GetDlgItem(hwnd, IDC_MOVEUPWARD), FALSE);
                            EnableWindow(GetDlgItem(hwnd, IDC_MOVEDOWNWARD), FALSE);
                        }
                    }
                    break;

                case IDC_MOVEUPWARD:
                    {
                        HWND hwndBitmaps = GetDlgItem(hwnd, IDC_BITMAPS);
                        UINT curSel = (UINT)SendMessage(hwndBitmaps, LB_GETCURSEL, 0, 0);
                        if(curSel != LB_ERR)
                        {
                            if(curSel > 0)
                            {
                                String strText = GetLBText(hwndBitmaps, curSel);

                                SendMessage(hwndBitmaps, LB_DELETESTRING, curSel, 0);
                                SendMessage(hwndBitmaps, LB_INSERTSTRING, --curSel, (LPARAM)strText.Array());
                                PostMessage(hwndBitmaps, LB_SETCURSEL, curSel, 0);
                            }
                        }
                    }
                    break;

                case IDC_MOVEDOWNWARD:
                    {
                        HWND hwndBitmaps = GetDlgItem(hwnd, IDC_BITMAPS);

                        UINT numBitmaps = (UINT)SendMessage(hwndBitmaps, LB_GETCOUNT, 0, 0);
                        UINT curSel = (UINT)SendMessage(hwndBitmaps, LB_GETCURSEL, 0, 0);
                        if(curSel != LB_ERR)
                        {
                            if(curSel < (numBitmaps-1))
                            {
                                String strText = GetLBText(hwndBitmaps, curSel);

                                SendMessage(hwndBitmaps, LB_DELETESTRING, curSel, 0);
                                SendMessage(hwndBitmaps, LB_INSERTSTRING, ++curSel, (LPARAM)strText.Array());
                                PostMessage(hwndBitmaps, LB_SETCURSEL, curSel, 0);
                            }
                        }
                    }
                    break;

                case IDC_DISABLEFADING:
                    {
                        BOOL bDisableFading = SendMessage(GetDlgItem(hwnd, IDC_DISABLEFADING), BM_GETCHECK, 0, 0) == BST_CHECKED;
                        EnableWindow(GetDlgItem(hwnd, IDC_FADEINONLY), !bDisableFading);
                    }
                    break;

                case IDOK:
                    {
                        HWND hwndBitmaps = GetDlgItem(hwnd, IDC_BITMAPS);

                        UINT numBitmaps = (UINT)SendMessage(hwndBitmaps, LB_GETCOUNT, 0, 0);
                        if(!numBitmaps)
                        {
                            OBSMessageBox(hwnd, Str("Sources.TransitionSource.Empty"), NULL, 0);
                            break;
                        }

                        //---------------------------

                        StringList bitmapList;
                        for(UINT i=0; i<numBitmaps; i++)
                            bitmapList << GetLBText(hwndBitmaps, i);

                        ConfigBitmapInfo *configInfo = (ConfigBitmapInfo*)GetWindowLongPtr(hwnd, DWLP_USER);

                        D3DX10_IMAGE_INFO ii;
                        if(SUCCEEDED(D3DX10GetImageInfoFromFile(bitmapList[0], NULL, &ii, NULL)))
                        {
                            configInfo->cx = ii.Width;
                            configInfo->cy = ii.Height;
                        }
                        else
                        {
                            configInfo->cx = configInfo->cy = 32;
                            AppWarning(TEXT("ConfigureBitmapTransitionSource: could not get image info for bitmap '%s'"), bitmapList[0].Array());
                        }

                        configInfo->data->SetStringList(TEXT("bitmap"), bitmapList);

                        UINT transitionTime = (UINT)SendMessage(GetDlgItem(hwnd, IDC_TRANSITIONTIME), UDM_GETPOS32, 0, 0);
                        configInfo->data->SetInt(TEXT("transitionTime"), transitionTime);

                        BOOL bFadeInOnly = SendMessage(GetDlgItem(hwnd, IDC_FADEINONLY), BM_GETCHECK, 0, 0) == BST_CHECKED;
                        BOOL bDisableFading = SendMessage(GetDlgItem(hwnd, IDC_DISABLEFADING), BM_GETCHECK, 0, 0) == BST_CHECKED;
                        BOOL bRandomize = SendMessage(GetDlgItem(hwnd, IDC_RANDOMIZE), BM_GETCHECK, 0, 0) == BST_CHECKED;
                        configInfo->data->SetInt(TEXT("fadeInOnly"), bFadeInOnly);
                        configInfo->data->SetInt(TEXT("disableFading"), bDisableFading);
                        configInfo->data->SetInt(TEXT("randomize"), bRandomize);
                    }

                case IDCANCEL:
                    EndDialog(hwnd, LOWORD(wParam));
                    break;
            }
            break;
    }

    return 0;
}
コード例 #28
0
LRESULT FileChildWindow::WndProc(UINT nmsg, WPARAM wparam, LPARAM lparam)
{
	switch(nmsg) {
		case WM_DRAWITEM: {
			LPDRAWITEMSTRUCT dis = (LPDRAWITEMSTRUCT)lparam;
			Entry* entry = (Entry*) dis->itemData;

			if (dis->CtlID == IDW_TREE_LEFT) {
				_left->draw_item(dis, entry);
				return TRUE;
			} else if (dis->CtlID == IDW_TREE_RIGHT) {
				_right->draw_item(dis, entry);
				return TRUE;
			}

			goto def;}

		case WM_SIZE:
			if (wparam != SIZE_MINIMIZED)
				resize_children(LOWORD(lparam), HIWORD(lparam));
			return DefMDIChildProc(_hwnd, nmsg, wparam, lparam);

		case PM_GET_FILEWND_PTR:
			return (LRESULT)this;

		case WM_SETFOCUS: {
			TCHAR path[MAX_PATH];

			if (_left && _left->_cur) {
				_left->_cur->get_path(path, COUNTOF(path));
				SetCurrentDirectory(path);
			}

			SetFocus(_focus_pane? _right_hwnd: _left_hwnd);
			goto def;}

		case PM_DISPATCH_COMMAND: {
			Pane* pane = GetFocus()==_left_hwnd? _left: _right;

			switch(LOWORD(wparam)) {
			  case ID_WINDOW_NEW: {CONTEXT("FileChildWindow PM_DISPATCH_COMMAND ID_WINDOW_NEW");
				if (_root._entry->_etype == ET_SHELL)
					FileChildWindow::create(ShellChildWndInfo(GetParent(_hwnd)/*_hmdiclient*/, _path, DesktopFolderPath()));
				else
					FileChildWindow::create(FileChildWndInfo(GetParent(_hwnd)/*_hmdiclient*/, _path));
				break;}

			  case ID_REFRESH: {CONTEXT("ID_REFRESH");
				refresh();
				break;}

			  case ID_ACTIVATE: {CONTEXT("ID_ACTIVATE");
				activate_entry(pane);
				break;}

			  default:
				if (pane->command(LOWORD(wparam)))
					return TRUE;
				else
					return super::WndProc(nmsg, wparam, lparam);
			}

			return TRUE;}

		case WM_CONTEXTMENU: {
			 // first select the current item in the listbox
			HWND hpanel = (HWND) wparam;
			POINT pt;
			pt.x = LOWORD(lparam);
			pt.y = HIWORD(lparam);
			POINT pt_screen = pt;
			ScreenToClient(hpanel, &pt);
			SendMessage(hpanel, WM_LBUTTONDOWN, 0, MAKELONG(pt.x, pt.y));
			SendMessage(hpanel, WM_LBUTTONUP, 0, MAKELONG(pt.x, pt.y));

			 // now create the popup menu using shell namespace and IContextMenu
			Pane* pane = GetFocus()==_left_hwnd? _left: _right;
			int idx = ListBox_GetCurSel(*pane);
			if (idx != -1) {
				Entry* entry = (Entry*) ListBox_GetItemData(*pane, idx);

				HRESULT hr = entry->do_context_menu(_hwnd, pt_screen, _cm_ifs);

				if (SUCCEEDED(hr))
					refresh();
				else
					CHECKERROR(hr);
			}
			break;}

		default: def:
			return super::WndProc(nmsg, wparam, lparam);
	}

	return 0;
}
コード例 #29
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPSTR /*lpCmdLine*/, int /*nShowCmd*/)
{
    LPCTSTR lpCmdLine = GetCommandLine(); /* this line necessary for _ATL_MIN_CRT */

    /*
     * Need to parse the command line before initializing the VBox runtime.
     */
    TCHAR szTokens[] = _T("-/");
    LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens);
    while (lpszToken != NULL)
    {
        if (WordCmpI(lpszToken, _T("Embedding")) == 0)
        {
            /* %HOMEDRIVE%%HOMEPATH% */
            wchar_t wszHome[RTPATH_MAX];
            DWORD cEnv = GetEnvironmentVariable(L"HOMEDRIVE", &wszHome[0], RTPATH_MAX);
            if (cEnv && cEnv < RTPATH_MAX)
            {
                DWORD cwc = cEnv; /* doesn't include NUL */
                cEnv = GetEnvironmentVariable(L"HOMEPATH", &wszHome[cEnv], RTPATH_MAX - cwc);
                if (cEnv && cEnv < RTPATH_MAX - cwc)
                {
                    /* If this fails there is nothing we can do. Ignore. */
                    SetCurrentDirectory(wszHome);
                }
            }
        }

        lpszToken = FindOneOf(lpszToken, szTokens);
    }

    /*
     * Initialize the VBox runtime without loading
     * the support driver.
     */
    int    argc = __argc;
    char **argv = __argv;
    RTR3InitExe(argc, &argv, 0);

    /* Note that all options are given lowercase/camel case/uppercase to
     * approximate case insensitive matching, which RTGetOpt doesn't offer. */
    static const RTGETOPTDEF s_aOptions[] =
    {
        { "--embedding",    'e',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "-embedding",     'e',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "/embedding",     'e',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "--unregserver",  'u',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "-unregserver",   'u',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "/unregserver",   'u',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "--regserver",    'r',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "-regserver",     'r',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "/regserver",     'r',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "--reregserver",  'f',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "-reregserver",   'f',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "/reregserver",   'f',    RTGETOPT_REQ_NOTHING | RTGETOPT_FLAG_ICASE },
        { "--helper",       'H',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
        { "-helper",        'H',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
        { "/helper",        'H',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
        { "--logfile",      'F',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
        { "-logfile",       'F',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
        { "/logfile",       'F',    RTGETOPT_REQ_STRING | RTGETOPT_FLAG_ICASE },
        { "--logrotate",    'R',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
        { "-logrotate",     'R',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
        { "/logrotate",     'R',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
        { "--logsize",      'S',    RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },
        { "-logsize",       'S',    RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },
        { "/logsize",       'S',    RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_ICASE },
        { "--loginterval",  'I',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
        { "-loginterval",   'I',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
        { "/loginterval",   'I',    RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_ICASE },
    };

    bool            fRun = true;
    bool            fRegister = false;
    bool            fUnregister = false;
    const char      *pszPipeName = NULL;
    const char      *pszLogFile = NULL;
    uint32_t        cHistory = 10;                  // enable log rotation, 10 files
    uint32_t        uHistoryFileTime = RT_SEC_1DAY; // max 1 day per file
    uint64_t        uHistoryFileSize = 100 * _1M;   // max 100MB per file

    RTGETOPTSTATE   GetOptState;
    int vrc = RTGetOptInit(&GetOptState, argc, argv, &s_aOptions[0], RT_ELEMENTS(s_aOptions), 1, 0 /*fFlags*/);
    AssertRC(vrc);

    RTGETOPTUNION   ValueUnion;
    while ((vrc = RTGetOpt(&GetOptState, &ValueUnion)))
    {
        switch (vrc)
        {
            case 'e':
                /* already handled above */
                break;

            case 'u':
                fUnregister = true;
                fRun = false;
                break;

            case 'r':
                fRegister = true;
                fRun = false;
                break;

            case 'f':
                fUnregister = true;
                fRegister = true;
                fRun = false;
                break;

            case 'H':
                pszPipeName = ValueUnion.psz;
                if (!pszPipeName)
                    pszPipeName = "";
                fRun = false;
                break;

            case 'F':
                pszLogFile = ValueUnion.psz;
                break;

            case 'R':
                cHistory = ValueUnion.u32;
                break;

            case 'S':
                uHistoryFileSize = ValueUnion.u64;
                break;

            case 'I':
                uHistoryFileTime = ValueUnion.u32;
                break;

            case 'h':
            {
                TCHAR txt[]= L"Options:\n\n"
                             L"/RegServer:\tregister COM out-of-proc server\n"
                             L"/UnregServer:\tunregister COM out-of-proc server\n"
                             L"/ReregServer:\tunregister and register COM server\n"
                             L"no options:\trun the server";
                TCHAR title[]=_T("Usage");
                fRun = false;
                MessageBox(NULL, txt, title, MB_OK);
                return 0;
            }

            case 'V':
            {
                char *psz = NULL;
                RTStrAPrintf(&psz, "%sr%s\n", RTBldCfgVersion(), RTBldCfgRevisionStr());
                PRTUTF16 txt = NULL;
                RTStrToUtf16(psz, &txt);
                TCHAR title[]=_T("Version");
                fRun = false;
                MessageBox(NULL, txt, title, MB_OK);
                RTStrFree(psz);
                RTUtf16Free(txt);
                return 0;
            }

            default:
                /** @todo this assumes that stderr is visible, which is not
                 * true for standard Windows applications. */
                /* continue on command line errors... */
                RTGetOptPrintError(vrc, &ValueUnion);
        }
    }

    /* Only create the log file when running VBoxSVC normally, but not when
     * registering/unregistering or calling the helper functionality. */
    if (fRun)
    {
        if (!pszLogFile)
        {
            char szLogFile[RTPATH_MAX];
            vrc = com::GetVBoxUserHomeDirectory(szLogFile, sizeof(szLogFile));
            if (RT_SUCCESS(vrc))
                vrc = RTPathAppend(szLogFile, sizeof(szLogFile), "VBoxSVC.log");
            if (RT_SUCCESS(vrc))
                pszLogFile = RTStrDup(szLogFile);
        }
        char szError[RTPATH_MAX + 128];
        vrc = com::VBoxLogRelCreate("COM Server", pszLogFile,
                                    RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG,
                                    "all", "VBOXSVC_RELEASE_LOG",
                                    RTLOGDEST_FILE, UINT32_MAX /* cMaxEntriesPerGroup */,
                                    cHistory, uHistoryFileTime, uHistoryFileSize,
                                    szError, sizeof(szError));
        if (RT_FAILURE(vrc))
            return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to open release log (%s, %Rrc)", szError, vrc);
    }

    int nRet = 0;
    HRESULT hRes = com::Initialize();

    _ASSERTE(SUCCEEDED(hRes));
    _Module.Init(ObjectMap, hInstance, &LIBID_VirtualBox);
    _Module.dwThreadID = GetCurrentThreadId();

    if (!fRun)
    {
        if (fUnregister)
        {
            _Module.UpdateRegistryFromResource(IDR_VIRTUALBOX, FALSE);
            nRet = _Module.UnregisterServer(TRUE);
        }
        if (fRegister)
        {
            _Module.UpdateRegistryFromResource(IDR_VIRTUALBOX, TRUE);
            nRet = _Module.RegisterServer(TRUE);
        }
        if (pszPipeName)
        {
            Log(("SVCMAIN: Processing Helper request (cmdline=\"%s\")...\n", pszPipeName));

            if (!*pszPipeName)
                vrc = VERR_INVALID_PARAMETER;

            if (RT_SUCCESS(vrc))
            {
                /* do the helper job */
                SVCHlpServer server;
                vrc = server.open(pszPipeName);
                if (RT_SUCCESS(vrc))
                    vrc = server.run();
            }
            if (RT_FAILURE(vrc))
            {
                Log(("SVCMAIN: Failed to process Helper request (%Rrc).", vrc));
                nRet = 1;
            }
        }
    }
    else
    {
        _Module.StartMonitor();
#if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED)
        hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE | REGCLS_SUSPENDED);
        _ASSERTE(SUCCEEDED(hRes));
        hRes = CoResumeClassObjects();
#else
        hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE);
#endif
        _ASSERTE(SUCCEEDED(hRes));

        MSG msg;
        while (GetMessage(&msg, 0, 0, 0))
            DispatchMessage(&msg);

        _Module.RevokeClassObjects();
        Sleep(dwPause); //wait for any threads to finish
    }

    _Module.Term();

    com::Shutdown();

    Log(("SVCMAIN: Returning, COM server process ends.\n"));
    return nRet;
}
コード例 #30
0
ファイル: CGLCG.cpp プロジェクト: JohnnyRocketFingers/snes9x
bool CGLCG::LoadShader(const TCHAR *shaderFile)
{
	CCGShader cgShader;
	TCHAR shaderPath[MAX_PATH];
	TCHAR tempPath[MAX_PATH];
	CGprofile vertexProfile, fragmentProfile;
	GLenum error;

	if(!fboFunctionsLoaded) {
		MessageBox(NULL, TEXT("Your OpenGL graphics driver does not support framebuffer objects.\nYou will not be able to use CG shaders in OpenGL mode."), TEXT("CG Error"),
			MB_OK|MB_ICONEXCLAMATION);
        return false;
    }

	vertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);
	fragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);

	cgGLDisableProfile(vertexProfile);
	cgGLDisableProfile(fragmentProfile);

	ClearPasses();

	if (shaderFile == NULL || *shaderFile==TEXT('\0'))
		return true;

	lstrcpy(shaderPath,shaderFile);
	for(int i=lstrlen(shaderPath); i>=0; i--){
		if(IS_SLASH(shaderPath[i])){
			shaderPath[i]=TEXT('\0');
			break;
		}
	}

	SetCurrentDirectory(shaderPath);
	if(!cgShader.LoadShader(_tToChar(shaderFile)))
		return false;

	cgGLSetOptimalOptions(vertexProfile);
	cgGLSetOptimalOptions(fragmentProfile);

	/* insert dummy pass that will contain the original texture
	*/
	shaderPasses.push_back(shaderPass());

	for(CCGShader::passVector::iterator it=cgShader.shaderPasses.begin();
			it!=cgShader.shaderPasses.end();it++) {
		shaderPass pass;

		pass.scaleParams = it->scaleParams;
		/* if this is the last pass (the only one that can have CG_SCALE_NONE)
		   and no filter has been set use the GUI setting
		*/
		if(pass.scaleParams.scaleTypeX==CG_SCALE_NONE && !it->filterSet) {
			pass.linearFilter = GUI.BilinearFilter;
		} else {
			pass.linearFilter = it->linearFilter;
		}

		// paths in the meta file can be relative
		_tfullpath(tempPath,_tFromChar(it->cgShaderFile),MAX_PATH);
		char *fileContents = ReadShaderFileContents(tempPath);
		if(!fileContents)
			return false;

		pass.cgVertexProgram = cgCreateProgram( cgContext, CG_SOURCE, fileContents,
						vertexProfile, "main_vertex", NULL);

		checkForCgError("Compiling vertex program");

		pass.cgFragmentProgram = cgCreateProgram( cgContext, CG_SOURCE, fileContents,
							fragmentProfile, "main_fragment", NULL);

		checkForCgError("Compiling fragment program");

		delete [] fileContents;
		if(!pass.cgVertexProgram || !pass.cgFragmentProgram) {
			return false;
		}
		cgGLLoadProgram(pass.cgVertexProgram);
		cgGLLoadProgram(pass.cgFragmentProgram);

		/* generate framebuffer and texture for this pass and apply
		   default texture settings
		*/
		glGenFramebuffers(1,&pass.fbo);
		glGenTextures(1,&pass.tex);
		glBindTexture(GL_TEXTURE_2D,pass.tex);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

		shaderPasses.push_back(pass);
	}

	for(std::vector<CCGShader::lookupTexture>::iterator it=cgShader.lookupTextures.begin();it!=cgShader.lookupTextures.end();it++) {		
		lookupTexture tex;
		strcpy(tex.id,it->id);

		/* generate texture for the lut and apply specified filter setting
		*/
		glGenTextures(1,&tex.tex);
		glBindTexture(GL_TEXTURE_2D,tex.tex);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, it->linearfilter?GL_LINEAR:GL_NEAREST);
		glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, it->linearfilter?GL_LINEAR:GL_NEAREST);

		_tfullpath(tempPath,_tFromChar(it->texturePath),MAX_PATH);

		// simple file extension png/tga decision
		int strLen = strlen(it->texturePath);
		if(strLen>4) {
			if(!strcasecmp(&it->texturePath[strLen-4],".png")) {
				int width, height;
				bool hasAlpha;
				GLubyte *texData;
				if(loadPngImage(tempPath,width,height,hasAlpha,&texData)) {
					glPixelStorei(GL_UNPACK_ROW_LENGTH, width);
					glTexImage2D(GL_TEXTURE_2D, 0, hasAlpha ? 4 : 3, width,
						height, 0, hasAlpha ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, texData);
					free(texData);
				}
			} else if(!strcasecmp(&it->texturePath[strLen-4],".tga")) {
				STGA stga;
				if(loadTGA(tempPath,stga)) {
					glPixelStorei(GL_UNPACK_ROW_LENGTH, stga.width);
					glTexImage2D(GL_TEXTURE_2D, 0, 4, stga.width,
						stga.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, stga.data);
				}
			}
		}
		lookupTextures.push_back(tex);
	}

	/* enable texture unit 1 for the lookup textures
	*/
	glClientActiveTexture(GL_TEXTURE1);
	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
	glTexCoordPointer(2,GL_FLOAT,0,lut_coords);
	glClientActiveTexture(GL_TEXTURE0);

	/* generate textures and set default values for the pref-filled PREV deque.
	*/
	for(int i=0;i<prevPasses.size();i++) {
		glGenTextures(1,&prevPasses[i].tex);
		glBindTexture(GL_TEXTURE_2D,prevPasses[i].tex);
		glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,512,512,0,GL_RGB,GL_UNSIGNED_SHORT_5_6_5,NULL);
		glBindTexture(GL_TEXTURE_2D,0);
		prevPasses[i].textureSize.x = prevPasses[i].textureSize.y = prevPasses[i].textureSize.x = prevPasses[i].textureSize.y = 0;
		memset(prevPasses[i].texCoords,0,sizeof(prevPasses[i].texCoords));
	}

	shaderLoaded = true;
	
	return true;
}