Example #1
0
Magic3D::XMLElement* Magic3D::ObjectInstance::load(XMLElement* root)
{
    if (root)
    {
        spawnOnLoad = loadBool(root,   M3D_OBJECT_INSTANCE_SPAWN);
        Object::load(root);
    }
    return root;
}
Example #2
0
Magic3D::XMLElement* Magic3D::Object::load(XMLElement* root)
{
    if (root)
    {
        script   = loadString(root, M3D_OBJECT_XML_SCRIPT);
        parentPosition = loadBool(root,   M3D_OBJECT_XML_PARENT_POSITION);
        parentRotation = loadBool(root,   M3D_OBJECT_XML_PARENT_ROTATION);
        parentScale    = loadBool(root,   M3D_OBJECT_XML_PARENT_SCALE);
        flag      = loadInt(root, M3D_OBJECT_XML_FLAG);
        billboard = (BILLBOARD)loadInt(root, M3D_OBJECT_XML_BILLBOARD);
        enabled  = loadBool(root, M3D_OBJECT_XML_ENABLED);
        visible  = loadBool(root, M3D_OBJECT_XML_VISIBLE);
        zOrder   = loadBool(root, M3D_OBJECT_XML_ZORDER);
        pick     = loadBool(root, M3D_OBJECT_XML_PICK);
        position = loadVector3(root, M3D_OBJECT_XML_POSITION);
        setRotation(Quaternion(loadVector4(root, M3D_OBJECT_XML_ROTATION)));
        scale    = loadVector3(root, M3D_OBJECT_XML_SCALE);
        bool sc = loadBool(root, M3D_OBJECT_XML_SCRIPTED);
        if (sc)
        {
            setScripted(true);
        }
        else
        {
            this->scripted = false;
        }

        XMLElement* xml = root->FirstChildElement(M3D_MESH_XML);
        unsigned int meshIndex = 0;
        while (xml)
        {
            Mesh* mesh = NULL;
            if (meshIndex < meshes.size())
            {
                mesh = meshes[meshIndex++];
            }

            if (mesh)
            {
                mesh->load(xml);
            }
            xml = xml->NextSiblingElement(M3D_MESH_XML);
        }

        PhysicsObject::load(root);
    }
    return root;
}
Example #3
0
int MetaConfig::reload()
{
	
	FILE *fp = fopen(fname.c_str(), "r");
	if(!fp){
		log(Warn, "reload file %s error", fname.c_str());
		return -1;
	}

	TiXmlDocument doc;
	doc.LoadFile(fp);

	TiXmlHandle docH( &doc );
	TiXmlHandle meta = docH.FirstChildElement( "conf" ).FirstChildElement( "servers" ).FirstChildElement("meta");
	if(meta.Element()){
		loadBool(&meta, "sync", bsync, false);
		TiXmlHandle daemon = meta.FirstChildElement("daemon");
		int ret = flushNodeSrvs(&daemon);
		return ret;
	}else{
		fclose(fp);
		return -1;
	}
}
Example #4
0
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow) {

	int result = prepare(lpCmdLine);
	debug("prepare() result %d\n", result);

	if (result == ERROR_ALREADY_EXISTS) {
		HWND handle = getInstanceWindow();
		ShowWindow(handle, SW_SHOW);
		SetForegroundWindow(handle);
		closeLogFile();
		return 2;
	}

	if (result != TRUE) {
		signalError();
		return 1;
	}

	splash = loadBool(SHOW_SPLASH)
			&& strstr(lpCmdLine, "--l4j-no-splash") == NULL;
	stayAlive = loadBool(GUI_HEADER_STAYS_ALIVE)
			&& strstr(lpCmdLine, "--l4j-dont-wait") == NULL;
	if (splash || stayAlive) {
		hWnd = CreateWindowEx(WS_EX_TOOLWINDOW, "STATIC", "",
				WS_POPUP | SS_BITMAP,
				0, 0, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);
		if (splash) {
			char timeout[10] = {0};
			if (loadString(SPLASH_TIMEOUT, timeout)) {
				splashTimeout = atoi(timeout);
				if (splashTimeout <= 0 || splashTimeout > MAX_SPLASH_TIMEOUT) {
					splashTimeout = DEFAULT_SPLASH_TIMEOUT;
				}
			}
			splashTimeoutErr = loadBool(SPLASH_TIMEOUT_ERR)
					&& strstr(lpCmdLine, "--l4j-no-splash-err") == NULL;
			waitForWindow = loadBool(SPLASH_WAITS_FOR_WINDOW);
			HANDLE hImage = LoadImage(hInstance,	// handle of the instance containing the image
					MAKEINTRESOURCE(SPLASH_BITMAP),	// name or identifier of image
					IMAGE_BITMAP,					// type of image
					0,								// desired width
					0,								// desired height
					LR_DEFAULTSIZE);
			if (hImage == NULL) {
				debug("hImage was NULL signalError(), exiting\n");
				signalError();
				return 1;
			}
			SendMessage(hWnd, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM) hImage);
			RECT rect;
			GetWindowRect(hWnd, &rect);
			int x = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
			int y = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
			SetWindowPos(hWnd, HWND_TOP, x, y, 0, 0, SWP_NOSIZE);
			ShowWindow(hWnd, nCmdShow);

			UpdateWindow (hWnd);
		}
		if (!SetTimer (hWnd, ID_TIMER, 1000 /* 1s */, TimerProc)) {
			debug("SetTimer() signalError(), exiting\n");
			signalError();
			return 1;
		}
	}
	if (execute(FALSE) == -1) {
		debug("execute(FALSE) signalError(), exiting\n");
		signalError();
		return 1;
	}
	if (!(splash || stayAlive)) {
		debug("Exit code:\t0\n");
		closeHandles();
		return 0;
	}

	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	debug("Exit code:\t%d\n", dwExitCode);
	closeHandles();
	return dwExitCode;
}
Example #5
0
void Segments::makeSegments(QImage &imageProcessed, SegmentSettings seg)
{
    segments.clear(); // autoDelete is on

    // statistics that show up in debug spew
    int madeLines = 0;
    int shortLines = 0; // lines rejected since their segments are too short
    int foldedLines = 0; // lines rejected since they could be into other lines

    // debugging with modal progress dialog box is problematic so make switchable
    const bool useDlg = true;

    // for each new column of pixels, loop through the runs. a run is defined as
    // one or more colored pixels that are all touching, with one uncolored pixel or the
    // image boundary at each end of the set. for each set in the current column, count
    // the number of runs it touches in the adjacent (left and right) columns. here is
    // the pseudocode:
    //   if ((L > 1) || (R > 1))
    //     "this run is at a branch point so ignore the set"
    //   else
    //     if (L == 0)
    //       "this run is the start of a new segment"
    //     else
    //       "this run is appended to the segment on the left
    int width = imageProcessed.width();
    int height = imageProcessed.height();

    QProgressDialog* dlg;
    if (useDlg)
    {

        dlg = new QProgressDialog("Scanning segments in image", "Cancel", 0, width);
        CHECK_PTR_ENGAUGE(dlg);
        dlg->setCaption(QString("Progress"));
        dlg->show();
    }

    bool* lastBool = new bool [height];
    CHECK_PTR_ENGAUGE(lastBool);
    bool* currBool = new bool [height];
    CHECK_PTR_ENGAUGE(currBool);
    bool* nextBool = new bool [height];
    CHECK_PTR_ENGAUGE(nextBool);
    Segment** lastSegment = new Segment* [height];
    CHECK_PTR_ENGAUGE(lastSegment);
    Segment** currSegment = new Segment* [height];
    CHECK_PTR_ENGAUGE(currSegment);

    Discretize discretize;
    loadBool(&discretize, lastBool, &imageProcessed, -1);
    loadBool(&discretize, currBool, &imageProcessed, 0);
    loadBool(&discretize, nextBool, &imageProcessed, 1);
    loadSegment(lastSegment, height);

    for (int x = 0; x < width; x++)
    {
        if (useDlg)
        {
            // update progress bar
            dlg->setValue(x);
            qApp->processEvents();

            if (dlg->wasCanceled())
                // quit scanning. only existing segments will be available
                break;
        }

        matchRunsToSegments(x, height, lastBool, lastSegment, currBool, currSegment, nextBool, seg,
                            &madeLines, &foldedLines, &shortLines);

        // get ready for next column
        scrollBool(lastBool, currBool, height);
        scrollBool(currBool, nextBool, height);
        if (x + 1 < width)
            loadBool(&discretize, nextBool, &imageProcessed, x + 1);
        scrollSegment(lastSegment, currSegment, height);
    }

    if (useDlg)
    {
        dlg->setValue(width);
        delete dlg;
    }

    DigitDebug::scanning(QString("segment lines created ") + QString::number(madeLines) +
                         QString(", too short so removed ") + QString::number(shortLines) +
                         QString(", folded together ") + QString::number(foldedLines));

    delete[] lastBool;
    delete[] currBool;
    delete[] nextBool;
    delete[] lastSegment;
    delete[] currSegment;
}
Example #6
0
int prepare(const char *lpCmdLine) {
	char tmp[MAX_ARGS] = {0};
	hModule = GetModuleHandle(NULL);
	if (hModule == NULL) {
		return FALSE;
	}

	// Get executable path
	char exePath[_MAX_PATH] = {0};
	int pathLen = getExePath(exePath);
	if (pathLen == -1) {
		return FALSE;
	}

	// Initialize logging
    if (strstr(lpCmdLine, "--l4j-debug") != NULL) {
		hLog = openLogFile(exePath, pathLen);
		if (hLog == NULL) {
			return FALSE;
		}
		debug("\n\nCmdLine:\t%s %s\n", exePath, lpCmdLine);
	}

    setWow64Flag();

	// Set default error message, title and optional support web site url.
	loadString(SUPPORT_URL, errUrl);
	loadString(ERR_TITLE, errTitle);
	if (!loadString(STARTUP_ERR, errMsg)) {
		return FALSE;
	}

	// Single instance
	loadString(MUTEX_NAME, mutexName);
	if (*mutexName) {
		SECURITY_ATTRIBUTES security;
		security.nLength = sizeof(SECURITY_ATTRIBUTES);
		security.bInheritHandle = TRUE;
		security.lpSecurityDescriptor = NULL;
		CreateMutexA(&security, FALSE, mutexName);
		if (GetLastError() == ERROR_ALREADY_EXISTS) {
			debug("Instance already exists.");
			return ERROR_ALREADY_EXISTS;
		}
	}

	// Working dir
	char tmp_path[_MAX_PATH] = {0};
	GetCurrentDirectory(_MAX_PATH, oldPwd);
	if (loadString(CHDIR, tmp_path)) {
		strncpy(workingDir, exePath, pathLen);
		appendPath(workingDir, tmp_path);
		_chdir(workingDir);
		debug("Working dir:\t%s\n", workingDir);
	}

	// Use bundled jre or find java
	if (loadString(JRE_PATH, tmp_path)) {
		char jrePath[MAX_ARGS] = {0};
		expandVars(jrePath, tmp_path, exePath, pathLen);
		debug("Bundled JRE:\t%s\n", jrePath);
		if (jrePath[0] == '\\' || jrePath[1] == ':') {
			// Absolute
			strcpy(cmd, jrePath);
		} else {
			// Relative
			strncpy(cmd, exePath, pathLen);
			appendPath(cmd, jrePath);
		}
    }
	if (!isJrePathOk(cmd)) {
		if (!loadString(JAVA_MIN_VER, javaMinVer)) {
			loadString(BUNDLED_JRE_ERR, errMsg);
			return FALSE;
		}
		loadString(JAVA_MAX_VER, javaMaxVer);
		if (!findJavaHome(cmd, loadInt(JDK_PREFERENCE))) {
			loadString(JRE_VERSION_ERR, errMsg);
			strcat(errMsg, " ");
			strcat(errMsg, javaMinVer);
			if (*javaMaxVer) {
				strcat(errMsg, " - ");
				strcat(errMsg, javaMaxVer);
			}
			loadString(DOWNLOAD_URL, errUrl);
			return FALSE;
		}
		if (!isJrePathOk(cmd)) {
			loadString(LAUNCHER_ERR, errMsg);
			return FALSE;
		}
	}

    // Append a path to the Path environment variable
	char jreBinPath[_MAX_PATH];
	strcpy(jreBinPath, cmd);
	strcat(jreBinPath, "\\bin");
	if (!appendToPathVar(jreBinPath)) {
		return FALSE;
	}

	// Set environment variables
	char envVars[MAX_VAR_SIZE] = {0};
	loadString(ENV_VARIABLES, envVars);
	char *var = strtok(envVars, "\t");
	while (var != NULL) {
		char *varValue = strchr(var, '=');
		*varValue++ = 0;
		*tmp = 0;
		expandVars(tmp, varValue, exePath, pathLen);
		debug("Set var:\t%s = %s\n", var, tmp);
		SetEnvironmentVariable(var, tmp);
		var = strtok(NULL, "\t");
	}
	*tmp = 0;

	// Process priority
	priority = loadInt(PRIORITY_CLASS);

	// Custom process name
	const BOOL setProcName = loadBool(SET_PROC_NAME)
			&& strstr(lpCmdLine, "--l4j-default-proc") == NULL;
	const BOOL wrapper = loadBool(WRAPPER);

    char jdk_path[_MAX_PATH] = {0};  // fry
    strcpy(jdk_path, cmd);
    //msgBox(jdk_path);

	appendLauncher(setProcName, exePath, pathLen, cmd);

	// Heap sizes
	appendHeapSizes(args);

    // JVM options
	if (loadString(JVM_OPTIONS, tmp)) {
		strcat(tmp, " ");
	} else {
        *tmp = 0;
    }
	/*
	 * Load additional JVM options from .l4j.ini file
	 * Options are separated by spaces or CRLF
	 * # starts an inline comment
	 */
	strncpy(tmp_path, exePath, strlen(exePath) - 3);
	strcat(tmp_path, "l4j.ini");
	long hFile;
	if ((hFile = _open(tmp_path, _O_RDONLY)) != -1) {
		const int jvmOptLen = strlen(tmp);
		char* src = tmp + jvmOptLen;
		char* dst = src;
		const int len = _read(hFile, src, MAX_ARGS - jvmOptLen - BIG_STR);
		BOOL copy = TRUE;
		int i;
		for (i = 0; i < len; i++, src++) {
			if (*src == '#') {
				copy = FALSE;
			} else if (*src == 13 || *src == 10) {
				copy = TRUE;
				if (dst > tmp && *(dst - 1) != ' ') {
					*dst++ = ' ';
				}
			} else if (copy) {
				*dst++ = *src;
			}
		}
		*dst = 0;
		if (len > 0 && *(dst - 1) != ' ') {
			strcat(tmp, " ");
		}
		_close(hFile);
	}

    // Expand environment %variables%
	expandVars(args, tmp, exePath, pathLen);

	// MainClass + Classpath or Jar
	char mainClass[STR] = {0};
	char jar[_MAX_PATH] = {0};
	loadString(JAR, jar);
	if (loadString(MAIN_CLASS, mainClass)) {
		if (!loadString(CLASSPATH, tmp)) {
			return FALSE;
		}
		char exp[MAX_ARGS] = {0};
		expandVars(exp, tmp, exePath, pathLen);
		strcat(args, "-classpath \"");
		if (wrapper) {
			appendAppClasspath(args, exePath, exp);
		} else if (*jar) {
			appendAppClasspath(args, jar, exp);
		}

	// add tools.jar for JDK  [fry]
	char tools[_MAX_PATH] = { 0 };
	sprintf(tools, "%s\\lib\\tools.jar", jdk_path);
	appendAppClasspath(args, tools, exp);

		// Deal with wildcards or >> strcat(args, exp); <<
		char* cp = strtok(exp, ";");
		while(cp != NULL) {
			debug("Add classpath:\t%s\n", cp);
			if (strpbrk(cp, "*?") != NULL) {
				int len = strrchr(cp, '\\') - cp + 1;
				strncpy(tmp_path, cp, len);
				char* filename = tmp_path + len;
				*filename = 0;
				struct _finddata_t c_file;
				long hFile;
				if ((hFile = _findfirst(cp, &c_file)) != -1L) {
					do {
						strcpy(filename, c_file.name);
						strcat(args, tmp_path);
						strcat(args, ";");
						debug("      \"      :\t%s\n", tmp_path);
					} while (_findnext(hFile, &c_file) == 0);
				}
				_findclose(hFile);
			} else {
				strcat(args, cp);
				strcat(args, ";");
			}
			cp = strtok(NULL, ";");
		}
		*(args + strlen(args) - 1) = 0;

		strcat(args, "\" ");
		strcat(args, mainClass);
	} else if (wrapper) {
       	strcat(args, "-jar \"");
		strcat(args, exePath);
   		strcat(args, "\"");
    } else {
       	strcat(args, "-jar \"");
        strncat(args, exePath, pathLen);
        appendPath(args, jar);
       	strcat(args, "\"");
    }

	// Constant command line args
	if (loadString(CMD_LINE, tmp)) {
		strcat(args, " ");
		strcat(args, tmp);
	}

	// Command line args
	if (*lpCmdLine) {
		strcpy(tmp, lpCmdLine);
		char* dst;
		while ((dst = strstr(tmp, "--l4j-")) != NULL) {
			char* src = strchr(dst, ' ');
			if (src == NULL || *(src + 1) == 0) {
				*dst = 0;
			} else {
				strcpy(dst, src + 1);
			}
		}
		if (*tmp) {
			strcat(args, " ");
			strcat(args, tmp);
		}
	}

	debug("Launcher:\t%s\n", cmd);
	debug("Launcher args:\t%s\n", args);
	debug("Args length:\t%d/32768 chars\n", strlen(args));
	return TRUE;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
		LPSTR lpCmdLine_, int nCmdShow_) {

	mainThreadId = GetCurrentThreadId();
	hInst = hInstance; // Store instance handle in our global variable
	nCmdShow = nCmdShow_;
	lpCmdLine = lpCmdLine_;

	// if we should restart on crash, we must also stay alive to check for crashes
	BOOL restartOnCrash = FALSE;

	stayAlive = restartOnCrash
			|| (loadBool(GUI_HEADER_STAYS_ALIVE)
					&& strstr(lpCmdLine, "--l4j-dont-wait") == NULL);

	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);
	wcex.style = CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc = WndProc;
	wcex.cbClsExtra = 0;
	wcex.cbWndExtra = 0;
	wcex.hInstance = hInst;
	wcex.hIcon = LoadIcon(hInst, IDI_APPLICATION);
	wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
	wcex.lpszMenuName = NULL;
	wcex.lpszClassName = szWindowClass;
	wcex.hIconSm = LoadIcon(wcex.hInstance, IDI_APPLICATION);

	if (!RegisterClassEx(&wcex)) {
		MessageBox(NULL, _T("Call to RegisterClassEx failed!"),
				_T("Glasscubes File Helper Installer"), 0);

		return 1;
	}

	//compute window position (center on screen)
	int windowWidth = 500;
	int windowHeight = 100;
	int screenX = GetSystemMetrics(SM_CXSCREEN);
	int screenY = GetSystemMetrics(SM_CYSCREEN);

	int windowPosX = (screenX / 2) - (windowWidth / 2);
	int windowPosY = (screenY / 2) - (windowHeight / 2);

	// The parameters to CreateWindow explained:
	// szWindowClass: the name of the application
	// szTitle: the text that appears in the title bar
	// WS_OVERLAPPEDWINDOW: the type of window to create
	// CW_USEDEFAULT, CW_USEDEFAULT: initial position (x, y)
	// 500, 100: initial size (width, length)
	// NULL: the parent of this window
	// NULL: this application does not have a menu bar
	// hInstance: the first parameter from WinMain
	// NULL: not used in this application
	hWnd = CreateWindow(
			szWindowClass,
			szTitle,
			WS_OVERLAPPEDWINDOW&~WS_MAXIMIZEBOX,
			windowPosX, windowPosY,
			windowWidth, windowHeight,
			NULL,
			NULL,
			hInst,
			NULL
	);

	if (!hWnd) {
		MessageBox(NULL, _T("Call to CreateWindow failed!"),
				_T("Glasscubes File Helper Installer"), 0);

		return 1;
	}

	int cyVScroll = GetSystemMetrics(SM_CYVSCROLL);

	RECT client_rectangle;
	GetClientRect(hWnd, &client_rectangle);

	//create progress bar

	progressBar = CreateWindowEx(
	WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE, PROGRESS_CLASS, NULL,
	WS_CHILD | WS_VISIBLE | PBS_MARQUEE, client_rectangle.left,
			client_rectangle.bottom - cyVScroll, client_rectangle.right,
			cyVScroll, hWnd, NULL, hInst, NULL);

	//SetWindowLong(progressBar, GWL_STYLE,
	//GetWindowLong(progressBar, GWL_STYLE) | PBS_MARQUEE);
	LONG_PTR style = GetWindowLongPtr(progressBar, GWL_STYLE);
	SetWindowLongPtr(progressBar, GWL_STYLE, style | PBS_MARQUEE);

	//label will fill the whole window except the part where progress bar will reside
	textLabel =
	CreateWindow("STATIC", "Initializing...", WS_VISIBLE | WS_CHILD | SS_CENTER,
			client_rectangle.left,client_rectangle.top,client_rectangle.right,
			client_rectangle.bottom - cyVScroll, hWnd, NULL, hInst, NULL);

	//SendMessage(progressBar, PBM_SETRANGE, 0, (LPARAM) MAKELPARAM(0, 599));
	//SendMessage(progressBar, PBM_SETPOS, 0, 0);
	//SetTimer(hWnd, 0, 100, NULL);

	// The parameters to ShowWindow explained:
	// hWnd: the value returned from CreateWindow
	// nCmdShow: the fourth parameter from WinMain
	ShowWindow(hWnd, nCmdShow);
	//UpdateWindow(hWnd);
	setJreDownloadProgressCallback(progressBarUpdateCallback);
	setDisplayMessageCallback(showMessage);

	//MessageBox(hWnd, "execute()", "Debug", MB_OK);

	HANDLE workerThreadHandle = CreateThread( NULL, 0,
			workerThread, NULL, 0, NULL);
	if (workerThreadHandle == NULL) {
		ExitProcess(5);
	}

	// Wait until all threads have terminated.
	// WaitForMultipleObjects( 3,
	//   Array_Of_Thread_Handles, TRUE, INFINITE);
	//MessageBox(NULL, "GUI Exiting", "Debug", MB_OK);

	// Main message loop:
	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	return (int) msg.wParam;
}
Example #8
0
int prepare(const char *lpCmdLine)
{
    char tmp[MAX_ARGS] = {0};
    hModule = GetModuleHandle(NULL);
    if (hModule == NULL)
    {
        return FALSE;
    }

    // Get executable path
    char exePath[_MAX_PATH] = {0};
    int pathLen = getExePath(exePath);
    if (pathLen == -1)
    {
        return FALSE;
    }

    if (!initializeLogging(lpCmdLine, exePath, pathLen))
    {
        return FALSE;
    }

    debug("\n\nVersion:\t%s\n", VERSION);
    debug("CmdLine:\t%s %s\n", exePath, lpCmdLine);
    setWow64Flag();

    // Set default error message, title and optional support web site url.
    loadString(SUPPORT_URL, errUrl);
    loadString(ERR_TITLE, errTitle);
    if (!loadString(STARTUP_ERR, errMsg))
    {
        debug(ERROR_FORMAT, "Startup error message not defined.");
        return FALSE;
    }

    // Single instance
    loadString(MUTEX_NAME, mutexName);
    if (*mutexName)
    {
        SECURITY_ATTRIBUTES security;
        security.nLength = sizeof(SECURITY_ATTRIBUTES);
        security.bInheritHandle = TRUE;
        security.lpSecurityDescriptor = NULL;
        CreateMutexA(&security, FALSE, mutexName);
        if (GetLastError() == ERROR_ALREADY_EXISTS)
        {
            debug(ERROR_FORMAT, "Instance already exists.");
            return ERROR_ALREADY_EXISTS;
        }
    }

    // Working dir
    char tmp_path[_MAX_PATH] = {0};
    GetCurrentDirectory(_MAX_PATH, oldPwd);
    if (loadString(CHDIR, tmp_path))
    {
        strncpy(workingDir, exePath, pathLen);
        appendPath(workingDir, tmp_path);
        _chdir(workingDir);
        debug("Working dir:\t%s\n", workingDir);
    }

    // Use bundled jre or find java
    if (loadString(JRE_PATH, tmp_path))
    {
        char jrePath[MAX_ARGS] = {0};
        expandVars(jrePath, tmp_path, exePath, pathLen);
        debug("Bundled JRE:\t%s\n", jrePath);
        if (jrePath[0] == '\\' || jrePath[1] == ':')
        {
            // Absolute
            strcpy(cmd, jrePath);
        }
        else
        {
            // Relative
            strncpy(cmd, exePath, pathLen);
            appendPath(cmd, jrePath);
        }

        if (isLauncherPathValid(cmd))
        {
            foundJava = (wow64 && loadBool(BUNDLED_JRE_64_BIT))
                        ? FOUND_BUNDLED | KEY_WOW64_64KEY
                        : FOUND_BUNDLED;
        }
    }

    if (foundJava == NO_JAVA_FOUND)
    {
        if (!loadString(JAVA_MIN_VER, javaMinVer))
        {
            loadString(BUNDLED_JRE_ERR, errMsg);
            return FALSE;
        }

        loadString(JAVA_MAX_VER, javaMaxVer);
        if (!findJavaHome(cmd, loadInt(JDK_PREFERENCE)))
        {
            loadString(JRE_VERSION_ERR, errMsg);
            strcat(errMsg, " ");
            strcat(errMsg, javaMinVer);

            if (*javaMaxVer)
            {
                strcat(errMsg, " - ");
                strcat(errMsg, javaMaxVer);
            }

            if (runtimeBits == USE_64_BIT_RUNTIME
                    || runtimeBits == USE_32_BIT_RUNTIME)
            {
                strcat(errMsg, " (");
                strcat(errMsg, runtimeBits == USE_64_BIT_RUNTIME ? "64" : "32");
                strcat(errMsg, "-bit)");
            }

            if (corruptedJreFound)
            {
                char launcherErrMsg[BIG_STR] = {0};

                if (loadString(LAUNCHER_ERR, launcherErrMsg))
                {
                    strcat(errMsg, "\n");
                    strcat(errMsg, launcherErrMsg);
                }
            }

            loadString(DOWNLOAD_URL, errUrl);
            return FALSE;
        }
    }

    // Store the JRE Home Dir
    strcpy(jreHomeDir, cmd);

    // Append a path to the Path environment variable
    char jreBinPath[_MAX_PATH] = {0};
    strcpy(jreBinPath, cmd);
    strcat(jreBinPath, "\\bin");
    if (!appendToPathVar(jreBinPath))
    {
        debug(ERROR_FORMAT, "appendToPathVar failed.");
        return FALSE;
    }

    // Set environment variables
    char envVars[MAX_VAR_SIZE] = {0};
    loadString(ENV_VARIABLES, envVars);
    char *var = strtok(envVars, "\t");
    while (var != NULL)
    {
        char *varValue = strchr(var, '=');
        *varValue++ = 0;
        *tmp = 0;
        expandVars(tmp, varValue, exePath, pathLen);
        debug("Set var:\t%s = %s\n", var, tmp);
        SetEnvironmentVariable(var, tmp);
        var = strtok(NULL, "\t");
    }
    *tmp = 0;

    // Process priority
    priority = loadInt(PRIORITY_CLASS);

    // Launcher
    appendJavaw(cmd);

    // Heap sizes
    appendHeapSizes(args);

    // JVM options
    char jvmOptions[MAX_ARGS] = {0};
    setJvmOptions(jvmOptions, exePath);

    // Expand environment %variables%
    expandVars(args, jvmOptions, exePath, pathLen);

    // MainClass + Classpath or Jar
    char mainClass[STR] = {0};
    char jar[_MAX_PATH] = {0};

    const BOOL wrapper = loadBool(WRAPPER);
    loadString(JAR, jar);

    if (loadString(MAIN_CLASS, mainClass))
    {
        if (!loadString(CLASSPATH, tmp))
        {
            debug("Info:\t\tClasspath not defined.\n");
        }
        char exp[MAX_ARGS] = {0};
        expandVars(exp, tmp, exePath, pathLen);
        strcat(args, "-classpath \"");
        if (wrapper)
        {
            appendAppClasspath(args, exePath);
        }
        else if (*jar)
        {
            appendAppClasspath(args, jar);
        }

        // Deal with wildcards or >> strcat(args, exp); <<
        char* cp = strtok(exp, ";");
        while(cp != NULL)
        {
            debug("Add classpath:\t%s\n", cp);
            if (strpbrk(cp, "*?") != NULL)
            {
                int len = strrchr(cp, '\\') - cp + 1;
                strncpy(tmp_path, cp, len);
                char* filename = tmp_path + len;
                *filename = 0;
                struct _finddata_t c_file;
                long hFile;
                if ((hFile = _findfirst(cp, &c_file)) != -1L)
                {
                    do
                    {
                        strcpy(filename, c_file.name);
                        appendAppClasspath(args, tmp_path);
                        debug("      \"      :\t%s\n", tmp_path);
                    } while (_findnext(hFile, &c_file) == 0);
                }
                _findclose(hFile);
            }
            else
            {
                appendAppClasspath(args, cp);
            }
            cp = strtok(NULL, ";");
        }
        *(args + strlen(args) - 1) = 0;

        strcat(args, "\" ");
        strcat(args, mainClass);
    }
    else if (wrapper)
    {
        strcat(args, "-jar \"");
        strcat(args, exePath);
        strcat(args, "\"");
    }
    else
    {
        strcat(args, "-jar \"");
        strncat(args, exePath, pathLen);
        appendPath(args, jar);
        strcat(args, "\"");
    }

    // Constant command line args
    if (loadString(CMD_LINE, tmp))
    {
        strcat(args, " ");
        strcat(args, tmp);
    }

    // Command line args
    if (*lpCmdLine)
    {
        strcpy(tmp, lpCmdLine);
        char* dst;
        while ((dst = strstr(tmp, "--l4j-")) != NULL)
        {
            char* src = strchr(dst, ' ');
            if (src == NULL || *(src + 1) == 0)
            {
                *dst = 0;
            }
            else
            {
                strcpy(dst, src + 1);
            }
        }
        if (*tmp)
        {
            strcat(args, " ");
            strcat(args, tmp);
        }
    }

    debug("Launcher:\t%s\n", cmd);
    debug("Launcher args:\t%s\n", args);
    debug("Args length:\t%d/32768 chars\n", strlen(args));
    return TRUE;
}
Example #9
0
int MetaConfig::parse()
{
	FILE *fp = fopen(fname.c_str(), "r");
	if(!fp){
		std::cerr << "load file " << fname << " error" << std::endl;
		return -1;
	}

	TiXmlDocument doc;
	doc.LoadFile(fp);

	TiXmlHandle docH( &doc );
	TiXmlHandle meta = docH.FirstChildElement( "conf" ).FirstChildElement( "servers" ).FirstChildElement("meta");
	if(meta.Element()){
		std::string lip;
		loadString(&meta, "ip", lip, "");
		if(lip.empty())
		{
			ip = 0;
		}
		else
		{
			ip = sox::aton_addr(lip.c_str());
			if (ip == INADDR_NONE)
			{
				log(Error, "invalid ip:%s", lip.c_str());
				return -1;
			}
		}
		loadInt(&meta, "session_port", sessionPort, 2001);
		loadInt(&meta, "lostcheck_port", lostCheckPort, 2010);
		loadInt(&meta, "snap_port", snapPort, 2014);
		loadInt(&meta, "sys_port", sysPort, 2018);
		loadInt(&meta, "thread", threadNum, 10);
		loadInt(&meta, "psync_limit", pSyncLogLimit, 10);
		pSyncLogLimit *= 1024;    // kbyte-> byte
		loadBool(&meta, "sync", bsync, false);
		loadBool(&meta, "session_on",isSessionOn, false);
		loadString(&meta, "type", type, "");

		if(type == "daemon")
		{
			// do nothing
		}
		else if(type == "localDaemon")
		{
			// do nothing
		}
		else
		{
			std::cerr << "invalid type" << type << std::endl;
			fclose(fp);
			return -1;
		}
		
		if(!isLocalDaemon()) // daemon
		{
			TiXmlHandle daemon = meta.FirstChildElement("daemon");
			TiXmlHandle node = daemon.FirstChildElement("node");
			if(node.Element())
			{
				loadInt(&node, "gid", gid, -1);
				loadInt(&node, "lid", lid, -1);

				if(gid == -1 || lid == -1){
					std::cerr << "read from config gid:" << gid << " lid:" << lid << " must be set" << std::endl;
					fclose(fp);
					return -1;
				}
			}
			else
			{
				std::cerr << "xml path conf.servers.meta.node not found" << std::endl;
				fclose(fp);
				return -1;
			}
			TiXmlHandle db = daemon.FirstChildElement("db").FirstChildElement("mysql");
			if(db.Element()){
				loadString(&db, "host", config.host, "localhost");
				loadInt(&db, "port", config.port, 3306);
				loadString(&db, "user", config.user, "root");
				loadString(&db, "passwd", config.passwd, "");
				loadString(&db, "database", config.database, "daemon");
				loadString(&db, "charset", config.charset, "utf8");
			}else{
				config.host = "localhost";
				config.port = 3306;
				config.user = "******";
				config.passwd = "";
				config.database = "daemon";
				config.charset = "utf8";
				log(Debug, "use default mysql config setting");
			}
			
			int ret = flushNodeSrvs(&daemon);
			if(ret != 0){
				fclose(fp);
				return ret;
			}
		}
		else // localDaemon
		{
			TiXmlHandle localdaemon = meta.FirstChildElement("localdaemon");
			if(localdaemon.Element()){
				loadString(&localdaemon,"luser", luser,"");
				loadString(&localdaemon,"lpasswd", lpasswd,"");
				loadString(&localdaemon,"chost", chost,"meta.yy.com");
				loadString(&localdaemon,"lname",lname,"");
				loadInt(&localdaemon, "csession_port", cSessionPort, 2001);
				loadInt(&localdaemon, "csnap_port", cSnapPort, 2014);
				loadInt(&localdaemon, "groupid", groupId, -1);
				loadString(&localdaemon,"db_path", dbPath, "");
				if(groupId == -1 || lname.empty() || dbPath.empty())
				{
					std::cerr << "read from config ,lname, dbPath and groupId:" << groupId <<" must be set at localDaemon" << std::endl;
					fclose(fp);
					return -1;
				}
			}
		}
	}
	fclose(fp);
	return 0;
}