コード例 #1
0
ファイル: app.cpp プロジェクト: pol51/colobot
ParseArgsStatus CApplication::ParseArguments(int argc, char *argv[])
{
    enum OptionType
    {
        OPT_HELP = 1,
        OPT_DEBUG,
        OPT_DATADIR,
        OPT_LOGLEVEL,
        OPT_LANGUAGE,
        OPT_LANGDIR,
        OPT_VBO
    };

    option options[] =
    {
        { "help", no_argument, nullptr, OPT_HELP },
        { "debug", no_argument, nullptr, OPT_DEBUG },
        { "datadir", required_argument, nullptr, OPT_DATADIR },
        { "loglevel", required_argument, nullptr, OPT_LOGLEVEL },
        { "language", required_argument, nullptr, OPT_LANGUAGE },
        { "langdir", required_argument, nullptr, OPT_LANGDIR },
        { "vbo", required_argument, nullptr, OPT_VBO }
    };

    opterr = 0;

    int c = 0;
    int index = -1;
    while ((c = getopt_long_only(argc, argv, "", options, &index)) != -1)
    {
        if (c == '?')
        {
            if (optopt == 0)
                GetLogger()->Error("Invalid argument: %s\n", argv[optind-1]);
            else
                GetLogger()->Error("Expected argument for option: %s\n", argv[optind-1]);

            m_exitCode = 1;
            return PARSE_ARGS_FAIL;
        }

        index = -1;

        switch (c)
        {
            case OPT_HELP:
            {
                GetLogger()->Message("\n");
                GetLogger()->Message("Colobot %s (%s)\n", COLOBOT_CODENAME, COLOBOT_VERSION);
                GetLogger()->Message("\n");
                GetLogger()->Message("List of available options:\n");
                GetLogger()->Message("  -help            this help\n");
                GetLogger()->Message("  -debug           enable debug mode (more info printed in logs)\n");
                GetLogger()->Message("  -datadir path    set custom data directory path\n");
                GetLogger()->Message("  -loglevel level  set log level to level (one of: trace, debug, info, warn, error, none)\n");
                GetLogger()->Message("  -language lang   set language (one of: en, de, fr, pl)\n");
                GetLogger()->Message("  -langdir path    set custom language directory path\n");
                GetLogger()->Message("  -vbo mode        set OpenGL VBO mode (one of: auto, enable, disable)\n");
                return PARSE_ARGS_HELP;
            }
            case OPT_DEBUG:
            {
                SetDebugMode(true);
                break;
            }
            case OPT_DATADIR:
            {
                m_dataPath = optarg;
                GetLogger()->Info("Using custom data dir: '%s'\n", m_dataPath.c_str());
                break;
            }
            case OPT_LOGLEVEL:
            {
                LogLevel logLevel;
                if (! CLogger::ParseLogLevel(optarg, logLevel))
                {
                    GetLogger()->Error("Invalid log level: \"%s\"\n", optarg);
                    return PARSE_ARGS_FAIL;
                }

                GetLogger()->Message("[*****] Log level changed to %s\n", optarg);
                GetLogger()->SetLogLevel(logLevel);
                break;
            }
            case OPT_LANGUAGE:
            {
                Language language;
                if (! ParseLanguage(optarg, language))
                {
                    GetLogger()->Error("Invalid language: \"%s\"\n", optarg);
                    return PARSE_ARGS_FAIL;
                }

                GetLogger()->Info("Using language %s\n", optarg);
                m_language = language;
                break;
            }
            case OPT_LANGDIR:
            {
                m_langPath = optarg;
                GetLogger()->Info("Using custom language dir: '%s'\n", m_langPath.c_str());
                break;
            }
            case OPT_VBO:
            {
                std::string vbo;
                vbo = optarg;
                if (vbo == "auto")
                    m_deviceConfig.vboMode = Gfx::VBO_MODE_AUTO;
                else if (vbo == "enable")
                    m_deviceConfig.vboMode = Gfx::VBO_MODE_ENABLE;
                else if (vbo == "disable")
                    m_deviceConfig.vboMode = Gfx::VBO_MODE_DISABLE;
                else
                {
                    GetLogger()->Error("Invalid vbo mode: \"%s\"\n", optarg);
                    return PARSE_ARGS_FAIL;
                }

                break;
            }
            default:
                assert(false); // should never get here
        }
    }

    return PARSE_ARGS_OK;
}
コード例 #2
0
void Logger::LogSection(Logger::Level level, Section* section, const WCHAR* message)
{
	const std::wstring source = GetSectionSourceString(section);
	GetLogger().Log(level, source.c_str(), message);
}
コード例 #3
0
/*
** Opens the context menu in given coordinates.
*/
void ContextMenu::ShowMenu(POINT pos, Skin* skin)
{
	static const MenuTemplate s_Menu[] =
	{
		MENU_ITEM(IDM_MANAGE, ID_STR_MANAGE),
		MENU_ITEM(IDM_ABOUT, ID_STR_ABOUT),
		MENU_ITEM(IDM_SHOW_HELP, ID_STR_HELP),
		MENU_SEPARATOR(),
		MENU_SUBMENU(ID_STR_SKINS,
			MENU_ITEM(IDM_OPENSKINSFOLDER, ID_STR_OPENFOLDER),
			MENU_ITEM(IDM_DISABLEDRAG, ID_STR_DISABLEDRAGGING),
			MENU_SEPARATOR(),
			MENU_ITEM_GRAYED(0, ID_STR_NOSKINS)),
		MENU_SUBMENU(ID_STR_FAVORITES,
			MENU_ITEM_GRAYED(0, ID_STR_NOFAVORITES)),
		MENU_SUBMENU(ID_STR_THEMES,
			MENU_ITEM_GRAYED(0, ID_STR_NOTHEMES)),
		MENU_SEPARATOR(),
		MENU_ITEM(IDM_EDITCONFIG, ID_STR_EDITSETTINGS),
		MENU_ITEM(IDM_REFRESH, ID_STR_REFRESHALL),
		MENU_SEPARATOR(),
		MENU_SUBMENU(ID_STR_LOGGING,
			MENU_ITEM(IDM_SHOWLOGFILE, ID_STR_SHOWLOGFILE),
			MENU_SEPARATOR(),
			MENU_ITEM(IDM_STARTLOG, ID_STR_STARTLOGGING),
			MENU_ITEM(IDM_STOPLOG, ID_STR_STOPLOGGING),
			MENU_SEPARATOR(),
			MENU_ITEM(IDM_DELETELOGFILE, ID_STR_DELETELOGFILE),
			MENU_ITEM(IDM_DEBUGLOG, ID_STR_DEBUGMODE)),
		MENU_SEPARATOR(),
		MENU_ITEM(IDM_QUIT, ID_STR_EXIT)
	};

	if (m_MenuActive || (skin && skin->IsClosing())) return;

	// Show context menu, if no actions were executed
	HMENU menu = MenuTemplate::CreateMenu(s_Menu, _countof(s_Menu), GetString);
	if (!menu) return;

	m_MenuActive = true;
	Rainmeter& rainmeter = GetRainmeter();

	SetMenuDefaultItem(menu, IDM_MANAGE, MF_BYCOMMAND);

	if (_waccess(GetLogger().GetLogFilePath().c_str(), 0) == -1)
	{
		EnableMenuItem(menu, IDM_SHOWLOGFILE, MF_BYCOMMAND | MF_GRAYED);
		EnableMenuItem(menu, IDM_DELETELOGFILE, MF_BYCOMMAND | MF_GRAYED);
		EnableMenuItem(menu, IDM_STOPLOG, MF_BYCOMMAND | MF_GRAYED);
	}
	else
	{
		EnableMenuItem(
			menu,
			(GetLogger().IsLogToFile()) ? IDM_STARTLOG : IDM_STOPLOG,
			MF_BYCOMMAND | MF_GRAYED);
	}

	if (rainmeter.m_Debug)
	{
		CheckMenuItem(menu, IDM_DEBUGLOG, MF_BYCOMMAND | MF_CHECKED);
	}

	HMENU allSkinsMenu = GetSubMenu(menu, 4);
	if (allSkinsMenu)
	{
		if (!rainmeter.m_SkinRegistry.IsEmpty())
		{
			// "Open folder" = 0, "Disable dragging" = 1, separator = 2
			DeleteMenu(allSkinsMenu, 3, MF_BYPOSITION);  // "No skins available" menuitem
			CreateAllSkinsMenu(allSkinsMenu);
		}

		if (rainmeter.m_DisableDragging)
		{
			CheckMenuItem(allSkinsMenu, IDM_DISABLEDRAG, MF_BYCOMMAND | MF_CHECKED);
		}
	}

	HMENU favoritesMenu = GetSubMenu(menu, 5);
	if (favoritesMenu)
	{
		if (!rainmeter.m_Favorites.empty())
		{
			DeleteMenu(favoritesMenu, 0, MF_BYPOSITION);  // "No skins available" menuitem
			CreateFavoritesMenu(favoritesMenu);
		}
	}

	HMENU layoutMenu = GetSubMenu(menu, 6);
	if (layoutMenu)
	{
		if (!rainmeter.m_Layouts.empty())
		{
			DeleteMenu(layoutMenu, 0, MF_BYPOSITION);  // "No layouts available" menuitem
			CreateLayoutMenu(layoutMenu);
		}
	}

	if (skin)
	{
		HMENU rainmeterMenu = menu;
		menu = CreateSkinMenu(skin, 0, allSkinsMenu);

		InsertMenu(menu, IDM_CLOSESKIN, MF_BYCOMMAND | MF_POPUP, (UINT_PTR)rainmeterMenu, L"Rainmeter");
		InsertMenu(menu, IDM_CLOSESKIN, MF_BYCOMMAND | MF_SEPARATOR, 0, nullptr);
	}
	else
	{
		InsertMenu(menu, 13, MF_BYPOSITION | MF_SEPARATOR, 0, nullptr);

		// Create a menu for all active skins
		int index = 0;
		std::map<std::wstring, Skin*>::const_iterator iter = rainmeter.m_Skins.begin();
		for (; iter != rainmeter.m_Skins.end(); ++iter)
		{
			Skin* skin = ((*iter).second);
			HMENU skinMenu = CreateSkinMenu(skin, index, allSkinsMenu);
			InsertMenu(menu, 13, MF_BYPOSITION | MF_POPUP, (UINT_PTR)skinMenu, skin->GetFolderPath().c_str());
			++index;
		}

		// Add update notification item
		if (rainmeter.m_NewVersion)
		{
			InsertMenu(menu, 0, MF_BYPOSITION, IDM_NEW_VERSION, GetString(ID_STR_UPDATEAVAILABLE));
			HiliteMenuItem(rainmeter.GetTrayIcon()->GetWindow(), menu, 0, MF_BYPOSITION | MF_HILITE);
			InsertMenu(menu, 1, MF_BYPOSITION | MF_SEPARATOR, 0, nullptr);
		}
	}

	HWND hWnd = WindowFromPoint(pos);
	if (hWnd != nullptr)
	{
		Skin* skin = rainmeter.GetSkin(hWnd);
		if (skin)
		{
			// Cancel the mouse event beforehand
			skin->SetMouseLeaveEvent(true);
		}
	}

	DisplayMenu(pos, menu, skin ? skin->GetWindow() : rainmeter.m_TrayIcon->GetWindow());
	DestroyMenu(menu);

	m_MenuActive = false;
}
コード例 #4
0
AppConfig::AppConfig(std::string& xmlfile) :
	analyticsEnabled(true),
	updateMonitorEnabled(true)
{
	systemProperties = new PropertiesBinding();
	xmlParserCtxtPtr context = xmlNewParserCtxt();
	xmlDocPtr document = xmlCtxtReadFile(context, xmlfile.c_str(), NULL, 0);

	if (!document)
	{
		std::ostringstream error;
		if (context->lastError.code != XML_IO_LOAD_ERROR)
		{
			error << context->lastError.file << "[Line ";
			error << context->lastError.line << "] ";
		}
		error << context->lastError.message;
		GetLogger()->Error(error.str());

		xmlFreeParserCtxt(context);
		xmlCleanupParser();
		return;
	}

	xmlNodePtr root = xmlDocGetRootElement(document);
	xmlNodePtr node = root->children;
	while (node)
	{
		if (node->type != XML_ELEMENT_NODE)
		{
			node = node->next;
			continue;
		}

		// This should always be a UTF-8, so we can just cast
		// the node name here to a char*
		std::string nodeName(reinterpret_cast<char*>(
			const_cast<xmlChar*>(node->name)));

		if (nodeName == "name")
		{
			appName = ConfigUtils::GetNodeValue(node);
		}
		else if (nodeName == "id")
		{
			appID = ConfigUtils::GetNodeValue(node);
		}
		else if (nodeName == "description")
		{
			description = ConfigUtils::GetNodeValue(node);
		}
		else if (nodeName == "copyright")
		{
			copyright = ConfigUtils::GetNodeValue(node);
		}
		else if (nodeName == "url")
		{
			url = ConfigUtils::GetNodeValue(node);
		}
		else if (nodeName == "version")
		{
			version = ConfigUtils::GetNodeValue(node);
		}
		else if (nodeName == "publisher")
		{
			publisher = ConfigUtils::GetNodeValue(node);
		}
		else if (nodeName == "window")
		{
			this->windows.push_back(WindowConfig::FromXMLNode(node));
		}
		else if (nodeName == "analytics")
		{
			std::string nodeValue(ConfigUtils::GetNodeValue(node));
			analyticsEnabled = ConfigUtils::StringToBool(nodeValue);
		}
		else if (nodeName == "update-monitor")
		{
			std::string nodeValue(ConfigUtils::GetNodeValue(node));
			updateMonitorEnabled = ConfigUtils::StringToBool(nodeValue);
		}
		else if (nodeName == "icon")
		{
			icon = ConfigUtils::GetNodeValue(node);
		}
		else if (nodeName == "property")
		{
			ParsePropertyNode(node, systemProperties->GetConfig());
		}
		else if (nodeName == "title")
		  {
			appTitle = ConfigUtils::GetNodeValue(node);
		  }

		node = node->next;
	}

	xmlFreeDoc(document);
	xmlFreeParserCtxt(context);
	xmlCleanupParser();
}
コード例 #5
0
ファイル: main.cpp プロジェクト: Gemini2015/ZFXEngine
/**
 * Create a render device and stuff.
 */
HRESULT ProgramStartup(const char *chAPI) 
{
	HWND hWnd3D[4];
	RECT rcWnd;
	int  x = 0, y = 0;

	// no opengl render device yet...
	//if (strcmp(chAPI, "OpenGL") == 0) return S_OK;

	// create a render objekt
	g_pRenderer = new ZFXRenderer(g_hInst);

	// create a device for the chosen api
	if (FAILED(g_pRenderer->CreateDevice(chAPI))) return E_FAIL;

	// get a pointer on that device
	g_pDevice = g_pRenderer->GetDevice();
	if (g_pDevice == NULL) return E_FAIL;

	// build for child windows
	GetClientRect(g_hWnd, &rcWnd);
	g_MAXWND = 0;
	for (int i = 0; i < g_MAXWND; i++) 
	{
		if ((i == 0) || (i == 2)) x = 10;
		else x = rcWnd.right / 2 + 10;

		if ((i == 0) || (i == 1)) y = 10;
		else y = rcWnd.bottom / 2 + 10;

		hWnd3D[i] = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("static"),
			NULL, WS_CHILD | SS_BLACKRECT | WS_VISIBLE,
			x, y, rcWnd.right / 2 - 20, rcWnd.bottom / 2 - 20,
			g_hWnd, NULL, g_hInst, NULL);
	}

	// init render device
	if (FAILED(g_pDevice->Init(g_hWnd, hWnd3D, g_MAXWND, 16, 0, false)))
	{
		GetLogger().Print(LOG_DEBUG,log_file,"Error RenderDevice Init");
		return ZFX_FAIL;
	}

	g_pDevice->UseWindow(0);

	POINT ptRes;
	g_pDevice->GetResolution(&ptRes);
	long lx = 0, ldx = 0, ldy = 0, fs = 0;

	ldx = ptRes.x / 2.666666f;
	ldy = ldx / 1.333333f;
	lx = ptRes.x - ldx - 10;

	fs = ptRes.x / 20;

	ZFXVIEWPORT rc = { lx, 0, ldx, ldy };
	g_pDevice->InitStage(60, NULL, 0);
	g_pDevice->InitStage(60, &rc, 1);

	if (strcmp(chAPI, "Direct3D") == 0)
	{
		if (FAILED(g_pDevice->CreateFont("Arial", 0, false, false,
			false, fs, &g_nFontID)))
		{
			GetLogger().Print(LOG_DEBUG,log_file,"error: ZFXRenderDevice::CreateFont failed\n");
			return ZFX_FAIL;
		}
	}

	IShaderManager* sm = g_pDevice->GetShaderManager();
	std::string str("shader//shader.vert");
	g_vshader = sm->CreateShader((void*)str.c_str(), SHT_VERTEX, true);
	str.assign("shader//shader.frag");
	g_fshader = sm->CreateShader((void*)str.c_str(), SHT_PIXEL, true);


	return ZFX_OK;
} // ProgramStartup
コード例 #6
0
TextCtrlLogger* DebuggerManager::GetLogger()
{
    int index;
    return GetLogger(index);
}
コード例 #7
0
ファイル: StructureElement.cpp プロジェクト: nutofem/nuto
void NuTo::Structure::ElementDelete(int rElementNumber)
{
    Timer timer(__FUNCTION__, GetShowTime(), GetLogger());
    ElementDeleteInternal(rElementNumber);
}
コード例 #8
0
    TCPServerConnectionBinding::TCPServerConnectionBinding(Poco::Net::StreamSocket& s, Poco::Net::SocketReactor & r) :
        StaticBoundObject("Network.TCPServerSocketConnection"),
        socket(s), 
        reactor(r),
        closed(false),
        onRead(0),
        onWrite(0),
        onReadComplete(0),
        currentSendDataOffset(0),
        readStarted(false),
        writeReadyHandlerInstalled(false)
    {
        GetLogger()->Debug("TCPServerConnectionBinding creating");
        
        /**
         * @tiapi(method=True,name=Network.TCPServerSocketConnection.close,since=1.2)
         * Close the Socket object's connection, if it is open.
         * @tiresult[Boolean] true if the connection was successfully close, false if otherwise
         */
        this->SetMethod("close", &TCPServerConnectionBinding::Close);

        /**
         * @tiapi(method=True,name=Network.TCPServerSocketConnection.write,since=1.2)
         * @tiapi Write data to the Socket's connection, if open.
         * @tiarg[String, data] The data to write to the connection.
         * @tiresult[Boolean] True if the write was successful, false otherwise.
         */
        this->SetMethod("write", &TCPServerConnectionBinding::Write);

        /**
         * @tiapi(method=True,name=Network.TCPServerSocketConnection.isClosed,since=1.2)
         * @tiapi Check whether the Socket is closed.
         * @tiresult[Boolean] true if a Socket object is closed, false if otherwise
         */
        this->SetMethod("isClosed",&TCPServerConnectionBinding::IsClosed);

        /**
         * @tiapi(method=True,name=Network.TCPServerSocketConnection.onRead,since=1.2)
         * @tiapi Set a callback that will be fired when data is received on the Socket.
         * @tiarg[Function, onRead] Function to be called when data is received.
         */
        this->SetMethod("onRead",&TCPServerConnectionBinding::SetOnRead);

        /**
         * @tiapi(method=True,name=Network.TCPServerSocketConnection.onWrite,since=1.2)
         * @tiapi Set a callback that will be fired when data is written on the Socket.
         * @tiarg[Function, onWrite] Function to be called when data is written.
         */
        this->SetMethod("onWrite",&TCPServerConnectionBinding::SetOnWrite);

        /**
         * @tiapi(method=True,name=Network.TCPServerSocketConnection.onError,version=1.2)
         * @tiapi Set the callback that will be fired when the Socket encounters an error.
         * @tiarg[Function, onError] Function to be called when an error happens.
         */
        this->SetMethod("onError",&TCPServerConnectionBinding::SetOnError);
        
        /**
         * @tiapi(method=True,name=Network.TCPServerSocketConnection.onReadComplete,since=1.2)
         * @tiapi Set the callback function that will be fired when a read finishes. A read is
         * @tiapi considered finished if some bytes have been read and a subsequent call to read
         * @tiapi returns zero bytes.
         * @tiarg[Function, onReadComplete] Function be called when a read completes.
         */
        this->SetMethod("onReadComplete",&TCPServerConnectionBinding::SetOnReadComplete);

        reactor.addEventHandler(socket, Poco::NObserver<TCPServerConnectionBinding, Poco::Net::ReadableNotification>(*this, &TCPServerConnectionBinding::onReadable));
        reactor.addEventHandler(socket, Poco::NObserver<TCPServerConnectionBinding, Poco::Net::ShutdownNotification>(*this, &TCPServerConnectionBinding::onShutdown));
        reactor.addEventHandler(socket, Poco::NObserver<TCPServerConnectionBinding, Poco::Net::ErrorNotification>(*this, &TCPServerConnectionBinding::onErrored));
    }
コード例 #9
0
/*
** Opens the context menu in given coordinates.
*/
void ContextMenu::ShowMenu(POINT pos, MeterWindow* meterWindow)
{
	static const MenuTemplate s_Menu[] =
	{
		MENU_ITEM(IDM_MANAGE, ID_STR_MANAGE),
		MENU_ITEM(IDM_ABOUT, ID_STR_ABOUT),
		MENU_ITEM(IDM_SHOW_HELP, ID_STR_HELP),
		MENU_SEPARATOR(),
		MENU_SUBMENU(ID_STR_SKINS,
			MENU_ITEM_GRAYED(0, ID_STR_NOSKINS),
			MENU_SEPARATOR(),
			MENU_ITEM(IDM_OPENSKINSFOLDER, ID_STR_OPENFOLDER),
			MENU_ITEM(IDM_DISABLEDRAG, ID_STR_DISABLEDRAGGING)),
		MENU_SUBMENU(ID_STR_THEMES,
			MENU_ITEM_GRAYED(0, ID_STR_NOTHEMES)),
		MENU_SEPARATOR(),
		MENU_ITEM(IDM_EDITCONFIG, ID_STR_EDITSETTINGS),
		MENU_ITEM(IDM_REFRESH, ID_STR_REFRESHALL),
		MENU_SEPARATOR(),
		MENU_SUBMENU(ID_STR_LOGGING,
			MENU_ITEM(IDM_SHOWLOGFILE, ID_STR_SHOWLOGFILE),
			MENU_SEPARATOR(),
			MENU_ITEM(IDM_STARTLOG, ID_STR_STARTLOGGING),
			MENU_ITEM(IDM_STOPLOG, ID_STR_STOPLOGGING),
			MENU_SEPARATOR(),
			MENU_ITEM(IDM_DELETELOGFILE, ID_STR_DELETELOGFILE),
			MENU_ITEM(IDM_DEBUGLOG, ID_STR_DEBUGMODE)),
		MENU_SEPARATOR(),
		MENU_ITEM(IDM_QUIT, ID_STR_EXIT)
	};

	if (m_MenuActive || (meterWindow && meterWindow->IsClosing())) return;

	// Show context menu, if no actions were executed
	HMENU menu = MenuTemplate::CreateMenu(s_Menu, _countof(s_Menu), GetString);
	if (!menu) return;

	m_MenuActive = true;
	Rainmeter& rainmeter = GetRainmeter();

	SetMenuDefaultItem(menu, IDM_MANAGE, MF_BYCOMMAND);

	if (_waccess(GetLogger().GetLogFilePath().c_str(), 0) == -1)
	{
		EnableMenuItem(menu, IDM_SHOWLOGFILE, MF_BYCOMMAND | MF_GRAYED);
		EnableMenuItem(menu, IDM_DELETELOGFILE, MF_BYCOMMAND | MF_GRAYED);
		EnableMenuItem(menu, IDM_STOPLOG, MF_BYCOMMAND | MF_GRAYED);
	}
	else
	{
		EnableMenuItem(
			menu,
			(GetLogger().IsLogToFile()) ? IDM_STARTLOG : IDM_STOPLOG,
			MF_BYCOMMAND | MF_GRAYED);
	}

	if (rainmeter.m_Debug)
	{
		CheckMenuItem(menu, IDM_DEBUGLOG, MF_BYCOMMAND | MF_CHECKED);
	}

	HMENU allSkinsMenu = GetSubMenu(menu, 4);
	if (allSkinsMenu)
	{
		if (!rainmeter.m_SkinRegistry.IsEmpty())
		{
			DeleteMenu(allSkinsMenu, 0, MF_BYPOSITION);  // "No skins available" menuitem
			CreateAllSkinsMenu(allSkinsMenu);
		}

		if (rainmeter.m_DisableDragging)
		{
			CheckMenuItem(allSkinsMenu, IDM_DISABLEDRAG, MF_BYCOMMAND | MF_CHECKED);
		}
	}

	HMENU layoutMenu = GetSubMenu(menu, 5);
	if (layoutMenu)
	{
		if (!rainmeter.m_Layouts.empty())
		{
			DeleteMenu(layoutMenu, 0, MF_BYPOSITION);  // "No layouts available" menuitem
			CreateLayoutMenu(layoutMenu);
		}
	}

	if (meterWindow)
	{
		HMENU rainmeterMenu = menu;
		menu = CreateSkinMenu(meterWindow, 0, allSkinsMenu);

		InsertMenu(menu, IDM_CLOSESKIN, MF_BYCOMMAND | MF_POPUP, (UINT_PTR)rainmeterMenu, L"Rainmeter");
		InsertMenu(menu, IDM_CLOSESKIN, MF_BYCOMMAND | MF_SEPARATOR, 0, nullptr);
	}
	else
	{
		InsertMenu(menu, 12, MF_BYPOSITION | MF_SEPARATOR, 0, nullptr);

		// Create a menu for all active skins
		int index = 0;
		std::map<std::wstring, MeterWindow*>::const_iterator iter = rainmeter.m_MeterWindows.begin();
		for (; iter != rainmeter.m_MeterWindows.end(); ++iter)
		{
			MeterWindow* mw = ((*iter).second);
			HMENU skinMenu = CreateSkinMenu(mw, index, allSkinsMenu);
			InsertMenu(menu, 12, MF_BYPOSITION | MF_POPUP, (UINT_PTR)skinMenu, mw->GetFolderPath().c_str());
			++index;
		}

		// Add update notification item
		if (rainmeter.m_NewVersion)
		{
			InsertMenu(menu, 0, MF_BYPOSITION, IDM_NEW_VERSION, GetString(ID_STR_UPDATEAVAILABLE));
			HiliteMenuItem(rainmeter.GetTrayWindow()->GetWindow(), menu, 0, MF_BYPOSITION | MF_HILITE);
			InsertMenu(menu, 1, MF_BYPOSITION | MF_SEPARATOR, 0, nullptr);
		}
	}

	HWND hWnd = WindowFromPoint(pos);
	if (hWnd != nullptr)
	{
		MeterWindow* mw = rainmeter.GetMeterWindow(hWnd);
		if (mw)
		{
			// Cancel the mouse event beforehand
			mw->SetMouseLeaveEvent(true);
		}
	}

	// Set the window to foreground
	hWnd = meterWindow ? meterWindow->GetWindow() : rainmeter.m_TrayWindow->GetWindow();
	HWND hWndForeground = GetForegroundWindow();
	if (hWndForeground != hWnd)
	{
		const DWORD foregroundThreadID = GetWindowThreadProcessId(hWndForeground, nullptr);
		const DWORD currentThreadID = GetCurrentThreadId();
		AttachThreadInput(currentThreadID, foregroundThreadID, TRUE);
		SetForegroundWindow(hWnd);
		AttachThreadInput(currentThreadID, foregroundThreadID, FALSE);
	}

	// Show context menu
	TrackPopupMenu(
		menu,
		TPM_RIGHTBUTTON | TPM_LEFTALIGN | (*GetString(ID_STR_ISRTL) == L'1' ? TPM_LAYOUTRTL : 0),
		pos.x,
		pos.y,
		0,
		hWnd,
		nullptr);

	DestroyMenu(menu);

	m_MenuActive = false;
}
コード例 #10
0
ファイル: FileListener.cpp プロジェクト: Skier/vault_repo
int CFileListener::Run(CThread * thisThread) {
    CString loop = "File Listener loop";
    bool found = true;
    while (!m_stopped) {
        try {
            if ( !found ) {
                LOG_DEBUG(GetLogger(), ATF_DEBUG, "File listener wait for dir changes");
                DWORD result = WaitForMultipleObjects(2,m_handles,false,INFINITE);
                if ( 1 == result - WAIT_OBJECT_0 ) {
                    break;
                }
                if ( 0 != result - WAIT_OBJECT_0 ) {
                    THROW_SYSTEM_EXCEPTION("Problem during wait changes");
                }

                FindNextChangeNotification(m_handles[ATF_WAIT_HANDLE]);
            }
            CString file = GetNextFile();
            if ( file.IsEmpty() ) {
                found = false;
                continue;
            }
            found = true;
            
            LOG_DEBUG(GetLogger(), ATF_DEBUG, "File found ["+file+"]");

            CMessage * msg = new CMessage(file);
            int pos_point = file.ReverseFind('.');
            int pos_slash = file.ReverseFind('\\');
            if ( pos_point < pos_slash || pos_point == -1 ) {
                msg->SetType("$$$");
            } else {
                CString ext = ((const char*)file)[pos_point+1];
                msg->SetType(ext);
            }
            
            CString tranId;
            if ( pos_point < pos_slash || pos_slash == -1) {
                tranId.Format("%0ld", msg->GetID());
                msg->SetTransactionID(tranId);
            } else {
                for ( int i = pos_slash + 1; i < pos_point; i++ ) {
                    tranId += file[i];
                }
                msg->SetTransactionID(tranId);
            }


            IExecutor * executor = m_executors.Get();
            CThread * proc = m_threads.Get();
            executor->SetTask(msg);
            IRunnable& body = proc->GetBody();
            ((CThreadBodyRunnable&)body).SetTask(executor, &m_executors);
            ((CPoolableThread*)proc)->Run();

        } catch (CSystemException &se) {
            CExceptionLogger::Log(GetLogger(), se);
        } catch (CAtfException &te) {
            CExceptionLogger::Log(GetLogger(), te);
        } catch (...) {
            LOG_ERROR(GetLogger(), ATF_ASSERT_ERR, "Unknown Exception was thrown");
        }
        LOG_DEBUG(GetLogger(), ATF_DEBUG, loop);
    }
    return 0;
};
コード例 #11
0
    void TCPServerConnectionBinding::onReadable (const Poco::AutoPtr<Poco::Net::ReadableNotification>& notification)
    {
        if (this->closed)
        {
            return;
        }
        static std::string eprefix("TCPServerConnectionBinding::OnRead: ");
        
        try
        {
            // Always read bytes, so that the tubes get cleared.
            char data[BUFFER_SIZE + 1];
            int size = socket.receiveBytes(&data, BUFFER_SIZE);

            // A read is only complete if we've already read some bytes from the socket.
            bool readComplete = this->readStarted && (size <= 0);
            this->readStarted = (size > 0);

            if (readComplete && !this->onReadComplete.isNull())
            {
                ValueList args;
                RunOnMainThread(this->onReadComplete, args, false);
            }
            else if (size > 0 && !this->onRead.isNull())
            {
                data[size] = '\0';

                BytesRef bytes(new Bytes(data, size));
                ValueList args(Value::NewObject(bytes));
                RunOnMainThread(this->onRead, args, false);
            }
        }
        catch (ValueException& e)
        {
            GetLogger()->Error("Read failed: %s", e.ToString().c_str());
            ValueList args(Value::NewString(e.ToString()));

            if (!this->onError.isNull())
                RunOnMainThread(this->onError, args, false);
        }
        catch (Poco::Exception &e)
        {
            // sometimes we'll get a I/O error (9) after closing during
            // a read, we can safely ignore errors if closed
            if (!this->closed)
            {
                GetLogger()->Error("Read failed: %s", e.displayText().c_str());
                ValueList args(Value::NewString(e.displayText()));

                if (!this->onError.isNull())
                    RunOnMainThread(this->onError, args, false);
            }
        }
        catch (...)
        {
            GetLogger()->Error("Read failed: unknown exception");
            ValueList args(Value::NewString("Unknown exception during read"));

            if (!this->onError.isNull())
                RunOnMainThread(this->onError, args, false);
        }
    }
コード例 #12
0
ファイル: log.cpp プロジェクト: ihlades/ACSRelay
void Log::SetOutputLevel ( const enum OutputLevel level )
{
    GetLogger().mLevel = level;
}
コード例 #13
0
INetTransport::INetTransport()
{
  GetLogger()->Register(STR_NAME_NET_TRANSPORT);
}
コード例 #14
0
ファイル: app.cpp プロジェクト: pol51/colobot
bool CApplication::Create()
{
    GetLogger()->Info("Creating CApplication\n");

    boost::filesystem::path dataPath(m_dataPath);
    if (! (boost::filesystem::exists(dataPath) && boost::filesystem::is_directory(dataPath)) )
    {
        GetLogger()->Error("Data directory '%s' doesn't exist or is not a directory\n", m_dataPath.c_str());
        m_errorMessage = std::string("Could not read from data directory:\n") +
                         std::string("'") + m_dataPath + std::string("'\n") +
                         std::string("Please check your installation, or supply a valid data directory by -datadir option.");
        m_exitCode = 1;
        return false;
    }

    SetLanguage(m_language);

    //Create the sound instance.
    if (!GetProfile().InitCurrentDirectory())
    {
        GetLogger()->Warn("Config not found. Default values will be used!\n");
        m_sound = new CSoundInterface();
    }
    else
    {
        std::string path;
        if (GetProfile().GetLocalProfileString("Resources", "Data", path))
            m_dataPath = path;

        #ifdef OPENAL_SOUND
        m_sound = static_cast<CSoundInterface *>(new ALSound());
        #else
        GetLogger()->Info("No sound support.\n");
        m_sound = new CSoundInterface();
        #endif

        m_sound->Create(true);
        if (GetProfile().GetLocalProfileString("Resources", "Sound", path)) {
            m_sound->CacheAll(path);
        } else {
            m_sound->CacheAll(GetDataSubdirPath(DIR_SOUND));
        }

        if (GetProfile().GetLocalProfileString("Resources", "Music", path)) {
            m_sound->AddMusicFiles(path);
        } else {
            m_sound->AddMusicFiles(GetDataSubdirPath(DIR_MUSIC));
        }
    }

    std::string standardInfoMessage =
      "\nPlease see the console output or log file\n"
      "to get more information on the source of error";

    /* SDL initialization sequence */


    Uint32 initFlags = SDL_INIT_VIDEO | SDL_INIT_TIMER;

    if (SDL_Init(initFlags) < 0)
    {
        m_errorMessage = std::string("SDL initialization error:\n") +
                         std::string(SDL_GetError());
        GetLogger()->Error(m_errorMessage.c_str());
        m_exitCode = 2;
        return false;
    }

    // This is non-fatal and besides seems to fix some memory leaks
    if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0)
    {
        GetLogger()->Warn("Joystick subsystem init failed\nJoystick(s) will not be available\n");
    }

    if ((IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG) == 0)
    {
        m_errorMessage = std::string("SDL_Image initialization error:\n") +
                         std::string(IMG_GetError());
        GetLogger()->Error(m_errorMessage.c_str());
        m_exitCode = 3;
        return false;
    }

    // load settings from profile
    int iValue;
    if ( GetProfile().GetLocalProfileInt("Setup", "Resolution", iValue) )
    {
        std::vector<Math::IntPoint> modes;
        GetVideoResolutionList(modes, true, true);
        if (static_cast<unsigned int>(iValue) < modes.size())
            m_deviceConfig.size = modes.at(iValue);
    }

    if ( GetProfile().GetLocalProfileInt("Setup", "Fullscreen", iValue) )
    {
        m_deviceConfig.fullScreen = (iValue == 1);
    }

    if (! CreateVideoSurface())
        return false; // dialog is in function

    if (m_private->surface == nullptr)
    {
        m_errorMessage = std::string("SDL error while setting video mode:\n") +
                         std::string(SDL_GetError());
        GetLogger()->Error(m_errorMessage.c_str());
        m_exitCode = 4;
        return false;
    }

    SDL_WM_SetCaption(m_windowTitle.c_str(), m_windowTitle.c_str());

    // Enable translating key codes of key press events to unicode chars
    SDL_EnableUNICODE(1);

    // Don't generate joystick events
    SDL_JoystickEventState(SDL_IGNORE);

    // The video is ready, we can create and initalize the graphics device
    m_device = new Gfx::CGLDevice(m_deviceConfig);
    if (! m_device->Create() )
    {
        m_errorMessage = std::string("Error in CDevice::Create()\n") + standardInfoMessage;
        m_exitCode = 5;
        return false;
    }

    // Create the 3D engine
    m_engine = new Gfx::CEngine(this);

    m_engine->SetDevice(m_device);

    if (! m_engine->Create() )
    {
        m_errorMessage = std::string("Error in CEngine::Init()\n") + standardInfoMessage;
        m_exitCode = 6;
        return false;
    }

    // Create model manager
    m_modelManager = new Gfx::CModelManager(m_engine);

    // Create the robot application.
    m_robotMain = new CRobotMain(this);

    m_robotMain->ChangePhase(PHASE_WELCOME1);

    GetLogger()->Info("CApplication created successfully\n");

    return true;
}
コード例 #15
0
void Database::Close(const ValueList& args, KValueRef result)
{
    GetLogger()->Debug("Closing database: %s", name.c_str());
    this->Close();
}
コード例 #16
0
ファイル: alsound.cpp プロジェクト: BTML/colobot
bool ALSound::SearchFreeBuffer(SoundType sound, int &channel, bool &alreadyLoaded)
{
    int priority = GetPriority(sound);

    // Seeks a channel used which sound is stopped.
    for (auto& it : m_channels)
    {
        if (it.second->IsPlaying())
        {
            continue;
        }
        if (it.second->GetSoundType() != sound)
        {
            continue;
        }

        it.second->SetPriority(priority);
        it.second->Reset();
        channel = it.first;
        alreadyLoaded = it.second->IsLoaded();
        return true;
    }

    // just add a new channel if we dont have any
    if (m_channels.size() == 0)
    {
        auto chn = MakeUnique<Channel>();
        // check if we channel ready to play music, if not report error
        if (chn->IsReady())
        {
            chn->SetPriority(priority);
            chn->Reset();
            channel = 1;
            m_channels[channel] = std::move(chn);
            alreadyLoaded = false;
            return true;
        }
        GetLogger()->Error("Could not open channel to play sound!\n");
        return false;
    }

    // Assigns new channel within limit
    if (m_channels.size() < m_channelsLimit)
    {
        auto it = m_channels.end();
        it--;
        int i = (*it).first;
        while (++i)
        {
            if (m_channels.find(i) == m_channels.end())
            {
                auto chn = MakeUnique<Channel>();
                // check if channel is ready to play music, if not destroy it and seek free one
                if (chn->IsReady())
                {
                    chn->SetPriority(priority);
                    chn->Reset();
                    m_channels[i] = std::move(chn);
                    channel = i;
                    alreadyLoaded = false;
                    return true;
                }
                GetLogger()->Debug("Could not open additional channel to play sound!\n");
                break;
            }
        }
    }

    int lowerOrEqual = -1;
    for (auto& it : m_channels)
    {
        if (it.second->GetPriority() < priority)
        {
            GetLogger()->Debug("Sound channel with lower priority will be reused.\n");
            channel = it.first;
            it.second->Reset();
            return true;
        }
        if (it.second->GetPriority() <= priority)
            lowerOrEqual = it.first;
    }

    if (lowerOrEqual != -1)
    {
        channel = lowerOrEqual;
        m_channels[channel]->Reset();
        GetLogger()->Debug("Sound channel with lower or equal priority will be reused.\n");
        return true;
    }

    GetLogger()->Debug("Could not find free buffer to use.\n");
    return false;
}
コード例 #17
0
ファイル: MasterLogic.cpp プロジェクト: 2asoft/MMO-Framework
//---------------------------------------------------------------------------------------------
void TMasterLogic::InitLog()
{
  GetLogger()->Register("Inner");// для логирования внутренних событий
  GetLogger()->Init("Master");
}
コード例 #18
0
ファイル: settings.cpp プロジェクト: Grunaka/colobot
void CSettings::LoadSettings()
{
    CApplication* app = CApplication::GetInstancePointer();
    CRobotMain* main = CRobotMain::GetInstancePointer();
    Gfx::CEngine* engine = Gfx::CEngine::GetInstancePointer();
    Gfx::CCamera* camera = main->GetCamera();
    CSoundInterface* sound = app->GetSound();

    int iValue = 0;
    float fValue = 0.0f;
    bool bValue = false;
    std::string sValue = "";

    GetConfigFile().GetBoolProperty("Setup", "Tooltips", m_tooltips);
    GetConfigFile().GetBoolProperty("Setup", "InterfaceGlint", m_interfaceGlint);
    GetConfigFile().GetBoolProperty("Setup", "InterfaceRain", m_interfaceRain);
    GetConfigFile().GetBoolProperty("Setup", "Soluce4", m_soluce4);
    GetConfigFile().GetBoolProperty("Setup", "Movies", m_movies);
    GetConfigFile().GetBoolProperty("Setup", "FocusLostPause", m_focusLostPause);

    if (GetConfigFile().GetBoolProperty("Setup", "OldCameraScroll", bValue))
        camera->SetOldCameraScroll(bValue);

    if (GetConfigFile().GetBoolProperty("Setup", "CameraInvertX", bValue))
        camera->SetCameraInvertX(bValue);

    if (GetConfigFile().GetBoolProperty("Setup", "CameraInvertY", bValue))
        camera->SetCameraInvertY(bValue);

    if (GetConfigFile().GetBoolProperty("Setup", "InterfaceEffect", bValue))
        camera->SetEffect(bValue);

    if (GetConfigFile().GetBoolProperty("Setup", "Blood", bValue))
        camera->SetBlood(bValue);

    if (GetConfigFile().GetBoolProperty("Setup", "Autosave", bValue))
        main->SetAutosave(bValue);

    if (GetConfigFile().GetIntProperty("Setup", "AutosaveInterval", iValue))
        main->SetAutosaveInterval(iValue);

    if (GetConfigFile().GetIntProperty("Setup", "AutosaveSlots", iValue))
        main->SetAutosaveSlots(iValue);

    if (GetConfigFile().GetBoolProperty("Setup", "ObjectDirty", bValue))
        engine->SetDirty(bValue);

    if (GetConfigFile().GetBoolProperty("Setup", "FogMode", bValue))
    {
        engine->SetFog(bValue);
        camera->SetOverBaseColor(Gfx::Color(0.0f, 0.0f, 0.0f, 0.0f)); // TODO: color ok?
    }

    if (GetConfigFile().GetBoolProperty("Setup", "LightMode", bValue))
        engine->SetLightMode(bValue);

    if (GetConfigFile().GetIntProperty("Setup", "JoystickIndex", iValue))
    {
        if (iValue >= 0)
        {
            auto joysticks = app->GetJoystickList();
            for(const auto& joystick : joysticks)
            {
                if (joystick.index == iValue)
                {
                    app->ChangeJoystick(joystick);
                    app->SetJoystickEnabled(true);
                }
            }
        }
        else
        {
            app->SetJoystickEnabled(false);
        }
    }

    if (GetConfigFile().GetFloatProperty("Setup", "ParticleDensity", fValue))
        engine->SetParticleDensity(fValue);

    if (GetConfigFile().GetFloatProperty("Setup", "ClippingDistance", fValue))
        engine->SetClippingDistance(fValue);

    if (GetConfigFile().GetIntProperty("Setup", "AudioVolume", iValue))
        sound->SetAudioVolume(iValue);

    if (GetConfigFile().GetIntProperty("Setup", "MusicVolume", iValue))
        sound->SetMusicVolume(iValue);

    if (GetConfigFile().GetBoolProperty("Setup", "EditIndentMode", bValue))
        engine->SetEditIndentMode(bValue);

    if (GetConfigFile().GetIntProperty("Setup", "EditIndentValue", iValue))
        engine->SetEditIndentValue(iValue);


    if (GetConfigFile().GetIntProperty("Setup", "MipmapLevel", iValue))
        engine->SetTextureMipmapLevel(iValue);

    if (GetConfigFile().GetIntProperty("Setup", "Anisotropy", iValue))
        engine->SetTextureAnisotropyLevel(iValue);

    if (GetConfigFile().GetFloatProperty("Setup", "ShadowColor", fValue))
        engine->SetShadowColor(fValue);

    if (GetConfigFile().GetFloatProperty("Setup", "ShadowRange", fValue))
        engine->SetShadowRange(fValue);

    if (GetConfigFile().GetIntProperty("Setup", "MSAA", iValue))
        engine->SetMultiSample(iValue);

    if (GetConfigFile().GetIntProperty("Setup", "FilterMode", iValue))
        engine->SetTextureFilterMode(static_cast<Gfx::TexFilter>(iValue));

    if (GetConfigFile().GetBoolProperty("Setup", "ShadowMapping", bValue))
        engine->SetShadowMapping(bValue);

    if (GetConfigFile().GetBoolProperty("Setup", "ShadowMappingQuality", bValue))
        engine->SetShadowMappingQuality(bValue);

    if (GetConfigFile().GetIntProperty("Setup", "ShadowMappingResolution", iValue))
    {
        if (iValue == 0)
        {
            engine->SetShadowMappingOffscreen(false);
        }
        else
        {
            engine->SetShadowMappingOffscreen(true);
            engine->SetShadowMappingOffscreenResolution(iValue);
        }
    }

    if (GetConfigFile().GetBoolProperty("Experimental", "TerrainShadows", bValue))
        engine->SetTerrainShadows(bValue);

    CInput::GetInstancePointer()->LoadKeyBindings();



    GetConfigFile().GetFloatProperty("Edit", "FontSize",    m_fontSize);
    GetConfigFile().GetFloatProperty("Edit", "WindowPosX",  m_windowPos.x);
    GetConfigFile().GetFloatProperty("Edit", "WindowPosY",  m_windowPos.y);
    GetConfigFile().GetFloatProperty("Edit", "WindowDimX",  m_windowDim.x);
    GetConfigFile().GetFloatProperty("Edit", "WindowDimY",  m_windowDim.y);

    GetConfigFile().GetBoolProperty ("Edit", "IOPublic", m_IOPublic);
    GetConfigFile().GetFloatProperty("Edit", "IOPosX",   m_IOPos.x);
    GetConfigFile().GetFloatProperty("Edit", "IOPosY",   m_IOPos.y);
    GetConfigFile().GetFloatProperty("Edit", "IODimX",   m_IODim.x);
    GetConfigFile().GetFloatProperty("Edit", "IODimY",   m_IODim.y);

    m_language = LANGUAGE_ENV;
    if (GetConfigFile().GetStringProperty("Language", "Lang", sValue))
    {
        if (!sValue.empty() && !ParseLanguage(sValue, m_language))
        {
            GetLogger()->Error("Failed to parse language '%s' from config file. Default language will be used.\n",
                               sValue.c_str());
        }
    }
    app->SetLanguage(m_language);
}
コード例 #19
0
ファイル: alsound.cpp プロジェクト: pol51/colobot
bool ALSound::SearchFreeBuffer(Sound sound, int &channel, bool &bAlreadyLoaded)
{
    int priority = GetPriority(sound);

    // Seeks a channel used which sound is stopped.
    for (auto it : mChannels) {
        if (it.second->IsPlaying())
            continue;
        if (it.second->GetSoundType() != sound)
            continue;

        it.second->SetPriority(priority);
        channel = it.first;
        bAlreadyLoaded = it.second->IsLoaded();
        return true;
    }

    // just add a new channel if we dont have any
    if (mChannels.size() == 0) {
        Channel *chn = new Channel();
        // check if we channel ready to play music, if not report error
        if (chn->IsReady()) {
            chn->SetPriority(priority);
            mChannels[1] = chn;
            channel = 1;
            bAlreadyLoaded = false;
            return true;
        }
        delete chn;
        GetLogger()->Error("Could not open channel to play sound!");
        return false;
    }

    // Seeks a channel completely free.
    if (mChannels.size() < 64) {
        auto it = mChannels.end();
        it--;
        int i = (*it).first;
        while (++i) {
            if (mChannels.find(i) == mChannels.end()) {
                Channel *chn = new Channel();
                // check if channel is ready to play music, if not destroy it and seek free one
                if (chn->IsReady()) {
                    chn->SetPriority(priority);
                    mChannels[++i] = chn;
                    channel = i;
                    bAlreadyLoaded = false;
                    return true;
                }
                delete chn;
                GetLogger()->Warn("Could not open additional channel to play sound!");
            }
        }
    }

    int lowerOrEqual = -1;
    for (auto it : mChannels) {
        if (it.second->GetPriority() < priority) {
            GetLogger()->Debug("Sound channel with lower priority will be reused.");
            channel = it.first;
            return true;
        }
        if (it.second->GetPriority() <= priority)
            lowerOrEqual = it.first;
    }

    if (lowerOrEqual != -1) {
        channel = lowerOrEqual;
        GetLogger()->Debug("Sound channel with lower or equal priority will be reused.");
        return true;
    }

    GetLogger()->Warn("Could not find free buffer to use.\n");
    return false;
}
コード例 #20
0
/*----------------------------------------------------------------------
|   NPT_LogManager::GetLogger
+---------------------------------------------------------------------*/
NPT_Logger*
NPT_LogManager::GetLogger(const char* name)
{
    // exit now if the log manager is disabled
    if (!LogManager.m_Enabled) return NULL;

    // auto lock until we return from this method
    NPT_AutoLock lock(LogManager.m_Lock);

    /* check that the manager is initialized */
    if (!LogManager.m_Configured) {
        /* init the manager */
        LogManager.Configure();
        NPT_ASSERT(LogManager.m_Configured);
    }

    /* check if this logger is already configured */
    NPT_Logger* logger = LogManager.FindLogger(name);
    if (logger) return logger;

    /* create a new logger */
    logger = new NPT_Logger(name, LogManager);
    if (logger == NULL) return NULL;

    /* configure the logger */
    LogManager.ConfigureLogger(logger);

    /* find which parent to attach to */
    NPT_Logger* parent = LogManager.m_Root;
    NPT_String  parent_name = name;
    for (;;) {
        NPT_Logger* candidate_parent;

        /* find the last dot */
        int dot = parent_name.ReverseFind('.');
        if (dot < 0) break;
        parent_name.SetLength(dot);
        
        /* see if the parent exists */
        candidate_parent = LogManager.FindLogger(parent_name);
        if (candidate_parent) {
            parent = candidate_parent;
            break;
        }

        /* this parent name does not exist, see if we need to create it */
        if (LogManager.HaveLoggerConfig(parent_name)) {
            LogManager.m_Lock.Unlock();
            parent = GetLogger(parent_name);
            LogManager.m_Lock.Lock();
            break;
        }
    }

    /* attach to the parent */
    logger->SetParent(parent);

    /* add this logger to the list */
    LogManager.m_Loggers.Add(logger);

    return logger;
}
コード例 #21
0
ファイル: StructureElement.cpp プロジェクト: nutofem/nuto
int NuTo::Structure::BoundaryElementsCreate(int rElementGroupId, int rNodeGroupId, NodeBase* rControlNode)
{
    Timer timer(__FUNCTION__, GetShowTime(), GetLogger());

    // find groups
    boost::ptr_map<int, GroupBase>::iterator itGroupElements = mGroupMap.find(rElementGroupId);
    if (itGroupElements == mGroupMap.end())
        throw Exception(__PRETTY_FUNCTION__, "Group with the given identifier does not exist.");
    if (itGroupElements->second->GetType() != NuTo::eGroupId::Elements)
        throw Exception(__PRETTY_FUNCTION__, "Group is not an element group.");

    boost::ptr_map<int, GroupBase>::iterator itGroupBoundaryNodes = mGroupMap.find(rNodeGroupId);
    if (itGroupBoundaryNodes == mGroupMap.end())
        throw Exception(__PRETTY_FUNCTION__, "Group with the given identifier does not exist.");
    if (itGroupBoundaryNodes->second->GetType() != NuTo::eGroupId::Nodes)
        throw Exception(__PRETTY_FUNCTION__, "Group is not a node group.");

    Group<ElementBase>& elementGroup = *(itGroupElements->second->AsGroupElement());
    Group<NodeBase>& nodeGroup = *(itGroupBoundaryNodes->second->AsGroupNode());

    // since the search is done via the id's, the surface nodes are ptr, so make another set with the node ptrs
    std::set<const NodeBase*> nodePtrSet;
    for (auto itNode : nodeGroup)
    {
        nodePtrSet.insert(itNode.second);
    }

    std::vector<int> newBoundaryElementIds;

    // loop over all elements
    for (auto itElement : elementGroup)
    {
        ElementBase* elementPtr = itElement.second;
        const InterpolationType& interpolationType = elementPtr->GetInterpolationType();

        // std::cout << typeid(*elementPtr).name() << "\n";
        // std::cout << typeid(ContinuumElement<1>).name() << std::endl;
        if (typeid(*elementPtr) != typeid(ContinuumElement<1>) && typeid(*elementPtr) != typeid(ContinuumElement<2>) &&
            typeid(*elementPtr) != typeid(ContinuumElement<3>))
            throw Exception(__PRETTY_FUNCTION__, "Element is not a ContinuumElement.");

        // loop over all surfaces
        for (int iSurface = 0; iSurface < interpolationType.GetNumSurfaces(); ++iSurface)
        {
            bool elementSurfaceNodesMatchBoundaryNodes = true;
            Eigen::VectorXi surfaceNodeIndices = interpolationType.GetSurfaceNodeIndices(iSurface);

            int numSurfaceNodes = surfaceNodeIndices.rows();
            std::vector<const NodeBase*> surfaceNodes(numSurfaceNodes);

            for (int iSurfaceNode = 0; iSurfaceNode < numSurfaceNodes; ++iSurfaceNode)
            {
                surfaceNodes[iSurfaceNode] = elementPtr->GetNode(surfaceNodeIndices(iSurfaceNode, 0));
            }

            // check, if all surface nodes are in the node group
            for (auto& surfaceNode : surfaceNodes)
            {
                if (nodePtrSet.find(surfaceNode) == nodePtrSet.end())
                {
                    // this surface has at least one node that is not in the list, continue
                    elementSurfaceNodesMatchBoundaryNodes = false;
                    break;
                }
            }
            if (not elementSurfaceNodesMatchBoundaryNodes)
                continue;

            int surfaceId = iSurface;

            int elementId = GetUnusedId(mElementMap);

            ElementBase* boundaryElement = nullptr;
            ConstitutiveBase& constitutiveLaw = elementPtr->GetConstitutiveLaw(0);

            switch (elementPtr->GetLocalDimension())
            {
            case 1:
            {
                const auto& integrationType = *GetPtrIntegrationType(eIntegrationType::IntegrationType0DBoundary);
                auto& element = dynamic_cast<ContinuumElement<1>&>(*elementPtr);
                if (rControlNode == nullptr)
                    boundaryElement = new ContinuumBoundaryElement<1>(element, integrationType, surfaceId);
                else
                    boundaryElement = new ContinuumBoundaryElementConstrainedControlNode<1>(element, integrationType,
                                                                                            surfaceId, rControlNode);
                break;
            }
            case 2:
            {
                eIntegrationType integrationTypeEnum;
                // check for 2D types
                switch (interpolationType.GetStandardIntegrationType())
                {
                case eIntegrationType::IntegrationType2D3NGauss1Ip:
                case eIntegrationType::IntegrationType2D4NGauss1Ip:
                    integrationTypeEnum = eIntegrationType::IntegrationType1D2NGauss1Ip;
                    break;
                case eIntegrationType::IntegrationType2D3NGauss3Ip:
                case eIntegrationType::IntegrationType2D4NGauss4Ip:
                    integrationTypeEnum = eIntegrationType::IntegrationType1D2NGauss2Ip;
                    break;
                case eIntegrationType::IntegrationType2D3NGauss6Ip:
                case eIntegrationType::IntegrationType2D4NGauss9Ip:
                    integrationTypeEnum = eIntegrationType::IntegrationType1D2NGauss3Ip;
                    break;
                case eIntegrationType::IntegrationType2D3NGauss12Ip:
                    integrationTypeEnum = eIntegrationType::IntegrationType1D2NGauss5Ip;
                    break;

                case eIntegrationType::IntegrationType2D4NLobatto9Ip:
                    integrationTypeEnum = eIntegrationType::IntegrationType1D2NLobatto3Ip;
                    break;

                case eIntegrationType::IntegrationType2D4NLobatto16Ip:
                    integrationTypeEnum = eIntegrationType::IntegrationType1D2NLobatto4Ip;
                    break;

                case eIntegrationType::IntegrationType2D4NLobatto25Ip:
                    integrationTypeEnum = eIntegrationType::IntegrationType1D2NLobatto5Ip;
                    break;

                default:
                    throw Exception(__PRETTY_FUNCTION__,
                                    "Could not automatically determine integration type of the boundary element.");
                }
                const auto& integrationType = *GetPtrIntegrationType(integrationTypeEnum);
                auto& element = dynamic_cast<ContinuumElement<2>&>(*elementPtr);
                if (rControlNode == nullptr)
                    boundaryElement = new ContinuumBoundaryElement<2>(element, integrationType, surfaceId);
                else
                    boundaryElement = new ContinuumBoundaryElementConstrainedControlNode<2>(element, integrationType,
                                                                                            surfaceId, rControlNode);

                break;
            }
            case 3:
            {
                eIntegrationType integrationTypeEnum;
                // check for 3D types
                switch (interpolationType.GetStandardIntegrationType())
                {
                case eIntegrationType::IntegrationType3D4NGauss1Ip:
                    integrationTypeEnum = eIntegrationType::IntegrationType2D3NGauss1Ip;
                    break;

                case eIntegrationType::IntegrationType3D4NGauss4Ip:
                    integrationTypeEnum = eIntegrationType::IntegrationType2D3NGauss3Ip;
                    break;

                case eIntegrationType::IntegrationType3D8NGauss1Ip:
                    integrationTypeEnum = eIntegrationType::IntegrationType2D4NGauss1Ip;
                    break;

                case eIntegrationType::IntegrationType3D8NGauss2x2x2Ip:
                    integrationTypeEnum = eIntegrationType::IntegrationType2D4NGauss4Ip;
                    break;

                case eIntegrationType::IntegrationType3D8NLobatto3x3x3Ip:
                    integrationTypeEnum = eIntegrationType::IntegrationType2D4NLobatto9Ip;
                    break;

                case eIntegrationType::IntegrationType3D8NLobatto4x4x4Ip:
                    integrationTypeEnum = eIntegrationType::IntegrationType2D4NLobatto16Ip;
                    break;

                case eIntegrationType::IntegrationType3D8NLobatto5x5x5Ip:
                    integrationTypeEnum = eIntegrationType::IntegrationType2D4NLobatto16Ip;
                    break;

                default:
                    throw Exception(__PRETTY_FUNCTION__,
                                    "Could not automatically determine integration type of the boundary element.");
                }

                const auto& integrationType = *GetPtrIntegrationType(integrationTypeEnum);
                auto& element = dynamic_cast<ContinuumElement<3>&>(*elementPtr);
                if (rControlNode == nullptr)
                    boundaryElement = new ContinuumBoundaryElement<3>(element, integrationType, surfaceId);
                else
                    boundaryElement = new ContinuumBoundaryElementConstrainedControlNode<3>(element, integrationType,
                                                                                            surfaceId, rControlNode);
                break;
            }
            default:
                throw Exception(__PRETTY_FUNCTION__, "Boundary element for Continuum element with dimension " +
                                                             std::to_string(elementPtr->GetLocalDimension()) +
                                                             "not implemented");
            }

            mElementMap.insert(elementId, boundaryElement);
            newBoundaryElementIds.push_back(elementId);

            boundaryElement->SetConstitutiveLaw(constitutiveLaw);
        }
    }

    int boundaryElementGroup = GroupCreate(eGroupId::Elements);
    for (int boundaryElementId : newBoundaryElementIds)
        GroupAddElement(boundaryElementGroup, boundaryElementId);

    return boundaryElementGroup;
}
コード例 #22
0
ファイル: glframebuffer.cpp プロジェクト: BTML/colobot
void CGLFramebuffer::Create()
{
    if (m_fbo != 0) return;

    m_width = m_params.width;
    m_height = m_params.height;
    m_depth = m_params.depth;
    m_samples = m_params.samples;

    glGenFramebuffers(1, &m_fbo);
    glBindFramebuffer(GL_FRAMEBUFFER, m_fbo);

    // create color texture
    if (m_params.colorTexture)
    {
        GLint previous;
        glGetIntegerv(GL_TEXTURE_BINDING_2D, &previous);

        glGenTextures(1, &m_colorTexture);
        glBindTexture(GL_TEXTURE_2D, m_colorTexture);

        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_params.width, m_params.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

        glBindTexture(GL_TEXTURE_2D, previous);

        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_colorTexture, 0);
    }
    // create color renderbuffer
    else
    {
        glGenRenderbuffers(1, &m_colorRenderbuffer);
        glBindRenderbuffer(GL_RENDERBUFFER, m_colorRenderbuffer);

        if (m_params.samples > 1)
            glRenderbufferStorageMultisample(GL_RENDERBUFFER, m_params.samples, GL_RGBA8, m_params.width, m_params.height);
        else
            glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, m_params.width, m_params.height);

        glBindRenderbuffer(GL_RENDERBUFFER, 0);

        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_colorRenderbuffer);
    }

    GLuint depthFormat = 0;

    switch (m_params.depth)
    {
    case 16: depthFormat = GL_DEPTH_COMPONENT16; break;
    case 24: depthFormat = GL_DEPTH_COMPONENT24; break;
    case 32: depthFormat = GL_DEPTH_COMPONENT32; break;
    default: depthFormat = GL_DEPTH_COMPONENT16; break;
    }

    // create depth texture
    if (m_params.depthTexture)
    {
        GLint previous;
        glGetIntegerv(GL_TEXTURE_BINDING_2D, &previous);

        glGenTextures(1, &m_depthTexture);
        glBindTexture(GL_TEXTURE_2D, m_depthTexture);

        glTexImage2D(GL_TEXTURE_2D, 0, depthFormat, m_params.width, m_params.height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, nullptr);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);

        float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
        glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, color);

        glBindTexture(GL_TEXTURE_2D, previous);

        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthTexture, 0);
    }
    // create depth renderbuffer
    else
    {
        glGenRenderbuffers(1, &m_depthRenderbuffer);
        glBindRenderbuffer(GL_RENDERBUFFER, m_depthRenderbuffer);

        if (m_params.samples > 1)
            glRenderbufferStorageMultisample(GL_RENDERBUFFER, m_params.samples, depthFormat, m_params.width, m_params.height);
        else
            glRenderbufferStorage(GL_RENDERBUFFER, depthFormat, m_params.width, m_params.height);

        glBindRenderbuffer(GL_RENDERBUFFER, 0);

        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depthRenderbuffer);
    }

    GLuint result = glCheckFramebufferStatus(GL_FRAMEBUFFER);
    if (result != GL_FRAMEBUFFER_COMPLETE)
    {
        GetLogger()->Error("Framebuffer incomplete\n");
        assert(false);
    }

    glBindFramebuffer(GL_FRAMEBUFFER, m_currentFBO);
}
コード例 #23
0
ファイル: main.cpp プロジェクト: Gemini2015/ZFXEngine
/**
 * WinMain function to get the thing started.
 */
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInstance,
	LPSTR lpCmdLine, int nCmdShow) {
	WNDCLASSEX	wndclass;
	HRESULT     hr;
	HWND		   hWnd;
	MSG			msg;

	// Set up window attributes
	wndclass.cbSize = sizeof(wndclass);
	wndclass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_DBLCLKS;
	wndclass.lpfnWndProc = MsgProc;
	wndclass.cbClsExtra = 0;
	wndclass.cbWndExtra = 0;
	wndclass.hInstance = hInst;
	wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
	wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW);
	wndclass.lpszMenuName = NULL;
	wndclass.lpszClassName = g_szAppClass;
	wndclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);

	if (RegisterClassEx(&wndclass) == 0)
		return 0;

	// create window
	if (!(hWnd = CreateWindowEx(NULL, g_szAppClass,
		"ZFXEngine - Demo Application",
		WS_OVERLAPPEDWINDOW | WS_VISIBLE,
		GetSystemMetrics(SM_CXSCREEN) / 2 - 400,
		GetSystemMetrics(SM_CYSCREEN) / 2 - 300,
		800, 600, NULL, NULL, hInst, NULL)))
		return 0;

	ShowWindow(hWnd, SW_HIDE);

	g_hWnd = hWnd;
	g_hInst = hInst;


	int SwitchAPI = 1;
	std::string chAPI;
	switch (SwitchAPI)
	{
	case 0:
		chAPI.assign("Direct3D");
		break;
	case 1:
		chAPI.assign("OpenGL");
		break;
	default:
		chAPI.assign("Direct3D");
		break;
	}

	

	// try to start the engine
	if (FAILED(hr = ProgramStartup(chAPI.c_str())))
	{
		GetLogger().Print(LOG_DEBUG,log_file,"error: ProgramStartup() failed\n");
		g_bDone = true;
	}
	else if (hr == ZFX_CANCELED)
	{
		GetLogger().Print(LOG_DEBUG,log_file,"error: ProgramStartup() canceled by user \n");
		g_bDone = true;
	}
	else
	{
		GetLogger().Print(LOG_DEBUG,log_file,"ProgramStartup Success");
		g_pDevice->SetClearColor(1, 1, 1);

		ShowWindow(hWnd, SW_SHOW);

		LoadModel();

	}

	//DrawVertex();

	InitTriangleExam();
	InitFont();
	//InitLightExam();

	InitGlyphTex();

	GetTimer()->Reset();

	while (!g_bDone)
	{
		while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}

		if (g_bIsActive)
		{
			UpdateFPS();


			//DrawGlyphTex();

			//DrawLightExam();


			//ProgramTick();
			
			IShaderManager* sm = g_pDevice->GetShaderManager();
			sm->EnableShader(false);
			//DrawTriangle(sm);
			
			//DrawS3DModel();

			
			DrawString("Life is cool");

			/*if (g_pDevice->IsWindowed())
			{
				g_pDevice->UseWindow(1);
				g_pDevice->SetView3D(vU*-1.0f, vR, vD, vP);
				ProgramTick();

				g_pDevice->UseWindow(2);
				g_pDevice->SetView3D(vR*-1.0f, vU*-1, vD, vP);
				ProgramTick();

				g_pDevice->UseWindow(3);
				g_pDevice->SetView3D(vU, vR*-1, vD, vP);
				ProgramTick();
			}*/
		}
	}

	// cleanup stuff
	ProgramCleanup();

	UnregisterClass(g_szAppClass, hInst);

	// return back to windows
	return (int)msg.wParam;
} // WinMain
コード例 #24
0
ファイル: DialogAbout.cpp プロジェクト: AlonTzarafi/rainmeter
/*
** Called when tab is displayed.
**
*/
void DialogAbout::TabLog::Initialize()
{
	// Add columns to the list view
	HWND item = GetControl(Id_ItemsListView);
	ListView_SetExtendedListViewStyleEx(item, 0, LVS_EX_LABELTIP | LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER);

	// Set folder/.ini icons for tree list
	HIMAGELIST hImageList = ImageList_Create(16, 16, ILC_COLOR32, 3, 1);
	HMODULE hDLL = GetModuleHandle(L"user32");

	HICON hIcon = (HICON)LoadImage(hDLL, MAKEINTRESOURCE(103), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
	ImageList_AddIcon(hImageList, hIcon);
	DeleteObject(hIcon);

	hIcon = (HICON)LoadImage(hDLL, MAKEINTRESOURCE(101), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
	ImageList_AddIcon(hImageList, hIcon);
	DeleteObject(hIcon);

	hIcon = (HICON)LoadImage(hDLL, MAKEINTRESOURCE(104), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR); 
	ImageList_AddIcon(hImageList, hIcon);
	DeleteObject(hIcon);

	ListView_SetImageList(item, (WPARAM)hImageList, LVSIL_SMALL);

	LVCOLUMN lvc;
	lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
	lvc.fmt = LVCFMT_LEFT;  // left-aligned column
	lvc.iSubItem = 0;
	lvc.cx = 75;
	lvc.pszText = GetString(ID_STR_TYPE);
	ListView_InsertColumn(item, 0, &lvc);
	lvc.iSubItem = 1;
	lvc.cx = 85;
	lvc.pszText = GetString(ID_STR_TIME);
	ListView_InsertColumn(item, 1, &lvc);
	lvc.iSubItem = 2;
	lvc.cx = 225;
	lvc.pszText = GetString(ID_STR_SOURCE);
	ListView_InsertColumn(item, 2, &lvc);
	lvc.iSubItem = 4;
	
	// Start 4th column at max width
	RECT rect;
	lvc.cx = GetWindowRect(item, &rect) ? (rect.right - rect.left - 405) : 180;
	lvc.pszText = GetString(ID_STR_MESSAGE);
	ListView_InsertColumn(item, 3, &lvc);

	// Add stored entires
	for (const auto& entry : GetLogger().GetEntries())
	{
		AddItem(entry.level, entry.timestamp.c_str(), entry.source.c_str(), entry.message.c_str());
	}

	item = GetControl(Id_ErrorCheckBox);
	Button_SetCheck(item, BST_CHECKED);

	item = GetControl(Id_WarningCheckBox);
	Button_SetCheck(item, BST_CHECKED);

	item = GetControl(Id_NoticeCheckBox);
	Button_SetCheck(item, BST_CHECKED);

	item = GetControl(Id_DebugCheckBox);
	Button_SetCheck(item, BST_CHECKED);

	m_Initialized = true;
}
コード例 #25
0
ファイル: pathman.cpp プロジェクト: BTML/colobot
void CPathManager::AddMod(std::string modPath)
{
    GetLogger()->Info("Loading mod: '%s'\n", modPath.c_str());
    CResourceManager::AddLocation(modPath, true);
}
コード例 #26
0
//-------------------------------------------------------------------
void TEditorMapLogic::InitLog()
{
  GetLogger()->Register( "Inner" );// для логирования внутренних событий
  GetLogger()->Init( "EditorMap" );
}
コード例 #27
0
void Logger::LogSectionVF(Logger::Level level, Section* section, const WCHAR* format, va_list args)
{
	const std::wstring source = GetSectionSourceString(section);
	GetLogger().LogVF(level, source.c_str(), format, args);
}
コード例 #28
0
void Database::Execute(const ValueList& args, KValueRef result)
{
    args.VerifyException("execute", "s");

    if (!session)
        throw ValueException::FromString("Tried to call execute, but database was closed.");

    std::string sql(args.GetString(0));
    GetLogger()->Debug("Execute called with %s", sql.c_str());
    
    Statement select(*this->session);
    
    try
    {
        ValueBinding binding;
        
        select << sql;
        
        if (args.size()>1)
        {
            
            for (size_t c=1;c<args.size();c++)
            {
                KValueRef anarg = args.at(c);
                if (anarg->IsList())
                {
                    KListRef list = anarg->ToList();
                    for (size_t a=0;a<list->Size();a++)
                    {
                        KValueRef arg = list->At(a);
                        binding.convert(select,arg);
                    }
                }
                else
                {
                    binding.convert(select,anarg);
                }
            }
        }
        Poco::UInt32 count = select.execute();

        GetLogger()->Debug("sql returned: %d rows for result",count);

        this->SetInt("rowsAffected",count);

        // get the row insert id
        Statement ss(*this->session);
        ss << "select last_insert_rowid()", now;
        RecordSet rr(ss);
        Poco::DynamicAny value = rr.value(0);
        int i;
        value.convert(i);
        this->SetInt("lastInsertRowId",i);

        
        if (count > 0)
        {
            RecordSet rs(select);
            KObjectRef r = new ResultSet(rs);
            result->SetObject(r);
        }
        else
        {
            KObjectRef r = new ResultSet();
            result->SetObject(r);
        }
    }
    catch (Poco::Data::DataException &e)
    {
        GetLogger()->Error("Exception executing: %s, Error was: %s", sql.c_str(),
            e.what());
        throw ValueException::FromString(e.what());
    }
}
コード例 #29
0
ファイル: mainClient.cpp プロジェクト: 2asoft/MMO-Framework
int main(int argc, char** argv)
{
  GetLogger()->Register(STR_NAME_MMO_ENGINE);
  GetLogger()->Register(STR_NAME_NET_TRANSPORT);
  GetLogger()->Init("Client_Test");
  GetLogger()->SetPrintf(false);
  GetLogger()->SetEnable(false);

  THandlerMMO_Client handler;

  TInputCmdTestMMO_Client inputCmd;
  bool res = inputCmd.SetArg(argc, argv);
  BL_ASSERT(res);

  TInputCmdTestMMO_Client::TInput inputArg;
  inputCmd.Get(inputArg);

  TMakerTransport makerTransport;
  std::vector<nsMMOEngine::TClient*> pArrClient;
  for( int i = 0 ; i < inputArg.count ; i++ )
  {
    nsMMOEngine::TClient* pClient = new nsMMOEngine::TClient;
    pClient->Init(&makerTransport);
    nsMMOEngine::TDescOpen descOpen;
    descOpen.port = inputArg.begin_port + i;
    pClient->Open(&descOpen); 
    pClient->SetDstObject(&handler);
    pClient->SetSelfID(descOpen.port);
    
    pArrClient.push_back(pClient);
  }

  const char* sLocalHost = inputArg.ip_server.data();
  unsigned int masterIP = boost::asio::ip::address_v4::from_string(sLocalHost).to_ulong();
  int indexClientOnLogin = 0;
  while(true)
  {
    unsigned int startTime = ht_GetMSCount();
    // Login
    int cnt = std::min(inputArg.count, indexClientOnLogin+STEP_LOGIN);
    for( int i = indexClientOnLogin ; i < cnt ; i++ )
    {
      char sLogin[100];
      sprintf(sLogin, "%d", inputArg.begin_id + i);
      pArrClient[i]->Login(masterIP, MASTER_PORT,
        sLogin, strlen(sLogin), (void*)PASSWORD_CLIENT, strlen(PASSWORD_CLIENT));
    }
    indexClientOnLogin = cnt;

    // Work
    for( int i = 0 ; i < indexClientOnLogin ; i++ )
      pArrClient[i]->Work();
    handler.Work();
    // burn rest time
    unsigned int deltaTime = ht_GetMSCount() - startTime;
    static int old_delta_time = -1;
    if((old_delta_time!=deltaTime)&&
       (deltaTime>70))
    {
      printf("dTime=%d\n", deltaTime);
      old_delta_time = deltaTime;
    }
    if(deltaTime < CLIENT_QUANT_TIME)
      ht_msleep(CLIENT_QUANT_TIME-deltaTime);
  }

  return 0;
}
コード例 #30
0
ファイル: app.cpp プロジェクト: pol51/colobot
void CApplication::SetLanguage(Language language)
{
    m_language = language;

    /* Gettext initialization */

    std::string locale = "";
    switch (m_language)
    {
        default:
        case LANGUAGE_ENV:
            locale = "";
            break;

        case LANGUAGE_ENGLISH:
            locale = "en_US.utf8";
            break;

        case LANGUAGE_GERMAN:
            locale = "de_DE.utf8";
            break;

        case LANGUAGE_FRENCH:
            locale = "fr_FR.utf8";
            break;

        case LANGUAGE_POLISH:
            locale = "pl_PL.utf8";
            break;
    }

    if (locale.empty())
    {
        char *envLang = getenv("LANGUAGE");
        if (envLang == NULL)
        {
            envLang = getenv("LANG");
        }
        if (envLang == NULL)
        {
            GetLogger()->Error("Failed to get language from environment, setting default language");
            m_language = LANGUAGE_ENGLISH;
        }
        else if (strncmp(envLang,"en",2) == 0)
        {
           m_language = LANGUAGE_ENGLISH;
        }
        else if (strncmp(envLang,"de",2) == 0)
        {
           m_language = LANGUAGE_GERMAN;
        }
        else if (strncmp(envLang,"fr",2) == 0)
        {
           m_language = LANGUAGE_FRENCH;
        }
        else if (strncmp(envLang,"pl",2) == 0)
        {
           m_language = LANGUAGE_POLISH;
        }
        GetLogger()->Trace("SetLanguage: Inherit LANGUAGE=%s from environment\n", envLang);
    }
    else
    {
        std::string langStr = "LANGUAGE=";
        langStr += locale;
        strcpy(S_LANGUAGE, langStr.c_str());
        putenv(S_LANGUAGE);
        GetLogger()->Trace("SetLanguage: Set LANGUAGE=%s in environment\n", locale.c_str());
    }
    setlocale(LC_ALL, "");

    bindtextdomain("colobot", m_langPath.c_str());
    bind_textdomain_codeset("colobot", "UTF-8");
    textdomain("colobot");

    GetLogger()->Debug("SetLanguage: Test gettext translation: '%s'\n", gettext("Colobot rules!"));
}