//----------------------------------------------------------------------------------------
// RemovePendingCommandForUIDRef
//----------------------------------------------------------------------------------------
void
AZPAMAssetMonitor::RemovePendingCommandForUIDRef(
	const UIDRef &				inAssetRef)
{
	//LogFunctionEnterExit;
	if( fPendingCommands.size() > 0 )
	{
		K2Vector<ICommand *>::iterator iter = fPendingCommands.begin();
		K2Vector<ICommand *>::iterator endIter = fPendingCommands.end();
		while( iter != endIter )
		{
			ICommand * currVal = *iter;
			const UIDRef & cmdTarget = currVal->GetTarget();
			if( cmdTarget == inAssetRef )
			{
				fPendingCommands.erase( iter );	//Don't increament the iter.
				currVal->Release();
				endIter = fPendingCommands.end();
			}
			else
			{
				++iter;
			}
		}
	}
}
//----------------------------------------------------------------------------------------
// GetHandleChangesCommand
//----------------------------------------------------------------------------------------
ICommand *
AZPAMAssetMonitor::GetHandleChangesCommand()
{
	//LogFunctionEnterExit;
	ICommand * toReturn = nil;
	if( fPendingCommands.size() > 0 )
	{
		K2Vector<ICommand *>::iterator iter = fPendingCommands.begin();
		K2Vector<ICommand *>::iterator endIter = fPendingCommands.end();
		while( iter != endIter )
		{
			ICommand * currVal = *iter;
			if( currVal->GetCommandState() == ICommand::kNotDone )
			{	
				//Keep the command in pending list
				//otherwise we get a crash if release else leak if not released.
				toReturn = currVal;
				break;
			}
			else
			{
				fPendingCommands.erase( iter );	//Don't increament the iter.
				currVal->Release();
				endIter = fPendingCommands.end();
			}
		}
	}
	return toReturn;
}
示例#3
0
bool Dispatcher::dispatchCommand( ICommand& command )
{
    LBASSERT( command.isValid( ));

    LBVERB << "dispatch " << command << " on " << lunchbox::className( this )
           << std::endl;

    const uint32_t which = command.getCommand();
#ifndef NDEBUG
    if( which >= _impl->qTable.size( ))
    {
        LBABORT( "ICommand " << command
                 << " higher than number of registered command handlers ("
                 << _impl->qTable.size() << ") for object of type "
                 << lunchbox::className( this ) << std::endl );
        return false;
    }
#endif

    CommandQueue* queue = _impl->qTable[ which ];
    if( queue )
    {
        command.setDispatchFunction( _impl->fTable[ which ] );
        queue->push( command );
        return true;
    }
    // else

    LBCHECK( _impl->fTable[ which ]( command ));
    return true;
}
示例#4
0
void CInputHandler::process(string command) throw(EQuit)
{
    ICommand* cmd = 0;
    try
    {
        cmd = getCommand(command);
    }
    catch(EInvalidAddress e)
    {
        std::cout << "?" << std::endl;
        return;
    }
    catch(EUnexpectedAddress e)
    {
        std::cout << "?" << std::endl;
        return;
    }

    if(cmd)
    {
        try
        {
            cmd->execute(storageHandler);
        }
        catch(EQuit e)
        {
            throw EQuit();
        }
    }
}
示例#5
0
void wxGISToolBar::Serialize(IApplication* pApp, wxXmlNode* pNode, bool bStore)
{
	if(bStore)
	{
		pNode->AddProperty(wxT("size"), wxString::Format(wxT("%u"), GetToolBitmapSize().GetWidth()));
		pNode->AddProperty(wxT("LeftDockable"), m_bLDock == true ? wxT("t") : wxT("f"));
		pNode->AddProperty(wxT("RightDockable"), m_bRDock == true ? wxT("t") : wxT("f"));
		wxGISCommandBar::Serialize(pApp, pNode, bStore);
	}
	else
	{
		m_bLDock = pNode->GetPropVal(wxT("LeftDockable"), wxT("f")) == wxT("f") ? false : true;
		m_bRDock = pNode->GetPropVal(wxT("RightDockable"), wxT("f")) == wxT("f") ? false : true;
		short iSize = wxAtoi(pNode->GetPropVal(wxT("size"), wxT("16")));
		SetToolBitmapSize(wxSize(iSize,iSize));

		wxAuiToolBarItemArray prepend_items;
		wxAuiToolBarItemArray append_items;
		ICommand* pCmd = pApp->GetCommand(wxT("wxGISCommonCmd"), 2);
		if(pCmd)
		{				
			wxAuiToolBarItem item;
			item.SetKind(wxITEM_SEPARATOR);
			append_items.Add(item);
			item.SetKind(pCmd->GetKind());
			item.SetId(pCmd->GetID());
			item.SetLabel(pCmd->GetCaption());
			append_items.Add(item);
		}
		SetCustomOverflowItems(prepend_items, append_items);
		wxGISCommandBar::Serialize(pApp, pNode, bStore);
		Realize();
	}
}
示例#6
0
/********************************************************************
 SqlCommandExecuteQuery - executes a SQL command and returns the results if desired

 NOTE: ppirs and pcRoes are optional
********************************************************************/
extern "C" HRESULT DAPI SqlCommandExecuteQuery(
    __in IDBCreateCommand* pidbCommand, 
    __in __sql_command LPCWSTR wzSql, 
    __out IRowset** ppirs,
    __out DBROWCOUNT* pcRows
    )
{
    Assert(pidbCommand);

    HRESULT hr = S_OK;
    ICommandText* picmdText = NULL;
    ICommand* picmd = NULL;
    DBROWCOUNT cRows = 0;

    if (pcRows)
    {
        *pcRows = NULL;
    }

    //
    // create the command
    //
    hr = pidbCommand->CreateCommand(NULL, IID_ICommand, (IUnknown**)&picmd);
    ExitOnFailure(hr, "failed to create command to execute session");

    //
    // set the sql text into the command
    //
    hr = picmd->QueryInterface(IID_ICommandText, (LPVOID*)&picmdText);
    ExitOnFailure(hr, "failed to get command text object for command");
    hr = picmdText->SetCommandText(DBGUID_DEFAULT , wzSql);
    ExitOnFailure1(hr, "failed to set SQL string: %ls", wzSql);

    //
    // execute the command
    //
    hr = picmd->Execute(NULL, (ppirs) ? IID_IRowset : IID_NULL, NULL, &cRows, reinterpret_cast<IUnknown**>(ppirs));
    ExitOnFailure1(hr, "failed to execute SQL string: %ls", wzSql);

    if (DB_S_ERRORSOCCURRED == hr)
    {
        hr = E_FAIL;
    }

    if (pcRows)
    {
        *pcRows = cRows;
    }

LExit:
    ReleaseObject(picmd);
    ReleaseObject(picmdText);

    return hr;
}
int main()
{
    Document* document = new Document("Greetings");
    ICommand* paste = new Paste(document);
    ICommand* print = new Print(document);

    clipboard = "hello everyone";
    paste->execute();
    print->execute();
    paste->undo();

    clipboard = "Bonjour, mes asmis";
    paste->execute();
    clipboard = "Guten morgen, meine Fredundo";
    paste->redo();
    print->execute();
    print->undo();

    cout << "Logged " << Log::get_count() << " commands" << endl;

    delete print;
    delete paste;
    delete document;
    return 0;
}
示例#8
0
wxGISAcceleratorTable::wxGISAcceleratorTable(IApplication* pApp, IGISConfig* pConf) : bHasChanges(true)
{
	m_AccelEntryArray.reserve(20);
	m_pConf = pConf;

	wxXmlNode* pAcceleratorsNodeCU = m_pConf->GetConfigNode(enumGISHKCU, wxString(wxT("accelerators")));
	wxXmlNode* pAcceleratorsNodeLM = m_pConf->GetConfigNode(enumGISHKLM, wxString(wxT("accelerators")));
	//merge two tables
	m_pApp = pApp;
	if(!pApp)
		return;

	//merge acc tables
	//if user delete key - it must be mark as deleted to avoid adding it fron LM table

	if(pAcceleratorsNodeCU)
	{
		wxXmlNode *child = pAcceleratorsNodeCU->GetChildren();
		while(child)
		{
			wxString sCmdName = child->GetPropVal(wxT("cmd_name"), NON);
			unsigned char nSubtype = wxAtoi(child->GetPropVal(wxT("subtype"), wxT("0")));
			ICommand* pCmd = m_pApp->GetCommand(sCmdName, nSubtype);
			if(pCmd)
			{
				wxString sFlags = child->GetPropVal(wxT("flags"), wxT("NORMAL"));
				WXDWORD Flags = GetFlags(sFlags);
				wxString sKey = child->GetPropVal(wxT("keycode"), wxT("A"));
				int nKey = GetKeyCode(sKey);
				Add(wxAcceleratorEntry(Flags, nKey, pCmd->GetID()));
			}
			child = child->GetNext();
		}
	}
	if(pAcceleratorsNodeLM)
	{
		wxXmlNode *child = pAcceleratorsNodeLM->GetChildren();
		while(child)
		{
			wxString sCmdName = child->GetPropVal(wxT("cmd_name"), NON);
			unsigned char nSubtype = wxAtoi(child->GetPropVal(wxT("subtype"), wxT("0")));
			ICommand* pCmd = m_pApp->GetCommand(sCmdName, nSubtype);
			if(pCmd)
			{
				wxString sFlags = child->GetPropVal(wxT("flags"), wxT("NORMAL"));
				WXDWORD Flags = GetFlags(sFlags);
				wxString sKey = child->GetPropVal(wxT("keycode"), wxT("A"));
				int nKey = GetKeyCode(sKey);
				Add(wxAcceleratorEntry(Flags, nKey, pCmd->GetID()));
			}
			child = child->GetNext();
		}
	}
}
示例#9
0
void* ThreadPool_run(void* arg)
{
	ThreadPool* threadPool = arg;
	while (!threadPool->isStop)
	{
		ICommand* command = threadPool->blockingQueue->pop(
		    &threadPool->blockingQueue->iqueue);
		command->execute(command);
	}

	return NULL;
}
示例#10
0
void HelpCommand::Execute() {
	IRenderer *pRenderer = GetEngine()->GetRenderer();
	pRenderer->Render("Available commands:\n");
	CommandFactory::CommandMap mapCommands = GetEngine()->GetCommandFactory()->GetCommandMap();

	CommandFactory::CommandMap::iterator itr;
	for (itr = mapCommands.begin(); itr != mapCommands.end(); itr++) {
		std::stringstream s;
		ICommand *pCommand = itr->second(GetEngine(), "");
		s << itr->first << " " << pCommand->GetParamTypes() << " " << pCommand->GetDescription() << "\n";
		pRenderer->Render(s.str());
		delete pCommand;
	}
}
示例#11
0
文件: LibM2.cpp 项目: ElRaulxX/LibM2
void LibM2::interpretCommand(LPCHARACTER ch,const char* data, size_t len) {
    LibM2* self=instance();
    std::istringstream iss(std::string(data,len));
    std::vector<std::string> arguments;
    copy(std::istream_iterator<std::string>(iss),std::istream_iterator<std::string>(),std::back_inserter<std::vector<std::string> >(arguments));
    if (self->m_map_command.find(arguments.front())!=self->m_map_command.end()) {
        ICommand* cmd = self->m_map_command[arguments.front()];
        if (cmd->usableFor(ch)) {
            cmd->use(ch, arguments);
            return;
        } else if(cmd->isReplaced()) {
            ch->ChatPacket(1,locale_find("그런 명령어는 없습니다"));
            return;
        }
    }
    self->detour_interpretCommand->GetOriginalFunction()(ch,data,len);
}
示例#12
0
void ServiceManager::setDataRecived(uint32_t len, uint8_t id)
{
    _Buffer.Lenght = len;
    ICommand *command = getCommandById(id);
    // если есть в списке команд, то проверяем, не финишировал ли? если нет - исполняем, иначе уничтожаем,
    if (command->finished())
    {
        // не может создать файл, и пока хз что с этим делать Ж(
//        if (command->getStatus() < 0)
        _Commands.remove(id);
    } else
        command->invoke();

    // после исполнения проверяем на финиш, если нет, то сигнал о прочитаном буфере
    if (!command->finished()) //сообщаем, что буфер прочитан
        emit bufferReceived(&_Buffer);
}
示例#13
0
void	GameplayEngine::treatPlayersCommands(std::queue<ICommand *>	& cmds)
{
	for (std::deque<IPlayer *>::iterator it = this->players_.begin() ;
				it != this->players_.end() ; ++it)
		{
			IPlayer *fetch = *it;

			ICommand *tmp = dynamic_cast<IClientService *>(fetch->getService())->Zpull();

			if (tmp && tmp->getType() == CommandType::MOVE)
			{
				DEBUG << "MOVE PLAYER" << std::endl;
			}
			else if (tmp && tmp->getType() == CommandType::FIRE)
			{
				DEBUG << "FIRE IN DA F****N HOLE" << std::endl;
			}
		}
}
示例#14
0
文件: edb.cpp 项目: nmred/study_test
void Edb::prompt(void)
{
   int ret = EDB_OK;
   ret = readInput("edb", 0);

   if(ret)
   {
      return;
   }

   // Input string
   std::string textInput = _cmdBuffer;
   // Split the inputing sentence.
   std::vector<std::string> textVec;
   split(textInput, SPACE, textVec);
   int count = 0;
   std::string cmd = "";
   std::vector<std::string> optionVec;

   std::vector<std::string>::iterator iter = textVec.begin();
   // handle different command here.
   ICommand* pCmd = NULL;
   for(;iter != textVec.end(); ++iter)
   {
      std::string str = *iter;
      if(0 == count)
      {
         cmd = str;
         count++;
      }
      else
      {
         optionVec.push_back(str);
      }
   }
   pCmd = _cmdFactory.getCommandProcesser(cmd.c_str());
   if( NULL != pCmd )
   {
      pCmd->execute( _sock, optionVec);
   }
}
int _tmain(int argc, _TCHAR* argv[])
{
    ICommand* doorOpenCmd = new RemoteDoorCommand(new RemoteDoor("open"));
    Result doorOpenResult = doorOpenCmd->Execute();
    assert(Result::CRITICAL == doorOpenResult.getStatus());
    assert(0 == doorOpenResult.getMessage().compare("door open"));
    delete doorOpenCmd;

    ICommand* doorCloseCmd = new RemoteDoorCommand(new RemoteDoor("not open"));
    Result doorCloseResult = doorCloseCmd->Execute();
    assert(Result::OK == doorCloseResult.getStatus());
    assert(true == doorCloseResult.getMessage().empty());
    delete doorCloseCmd;

    Server server;
    doorOpenCmd = new RemoteDoorCommand(new RemoteDoor("open"));
    server.AddCommand(doorOpenCmd);
    server.Monitor();

	return 0;
}
示例#16
0
void Game::Play()
{
  string cmd;
  renderer->Render("Welcome to Fiends'n'Frogs adventure game!\n");
  ostringstream s;
  s << "by " << DEV_NAME << "(c) " << YEAR << ". Licensed under GPLv3.\n";
  renderer->Render(s.str());
  Player::AskInfo(player);
  renderer->Render("\nPlayer statistics:\n\n");
  player.PrintSummary();
  renderer->Render("\nAnd behold, the adventure begins!\n");
  
  player.SetGame(this);

  srand(time(NULL));
  while(running)
  {

    renderer->Render(GetCurrentRoom()->GetDescription());
    renderer->Render("\n> ");

    getline(cin,cmd);

    CommandFactory comm(this);
    ICommand *pCommand = comm.Create( cmd ); 
    if ( pCommand ) pCommand->Execute();

    delete pCommand;

    GetCurrentRoom()->Update();
      
    if ( player.GetHitpoints() <= 0 ) {
      
      renderer->Render("You're dead. Game over.\n");
      running = false;
    }
  }
  // final message to player
  renderer->Render("Exiting, bye!\n");
}
int main()
{
	stack<ICommand*> cmd_stack;
	vector<Shape*> v;

	while (1)
	{
		int cmd;
		cin >> cmd;

		if (cmd == 1)
		{
			ICommand* p = new AddRectCommand(v);
			p->Execute();
			cmd_stack.push(p);
		}
		else if (cmd == 2)
		{
			ICommand* p = new AddCircleCommand(v);
			p->Execute();
			cmd_stack.push(p);
		}
		else if (cmd == 9)
		{
			ICommand* p = new DrawCommand(v);
			p->Execute();
			cmd_stack.push(p);
		}
		else if (cmd == 0)
		{
			ICommand* p = cmd_stack.top();
			if (p->CanUndo())
				p->Undo();
			cmd_stack.pop();
			delete p;
		}
	}
}
示例#18
0
/********************************************************************
 SqlSessionExecuteQuery - executes a query and returns the results if desired

 NOTE: ppirs and pcRoes and pbstrErrorDescription are optional
********************************************************************/
extern "C" HRESULT DAPI SqlSessionExecuteQuery(
    __in IDBCreateSession* pidbSession, 
    __in __sql_command LPCWSTR wzSql, 
    __out_opt IRowset** ppirs,
    __out_opt DBROWCOUNT* pcRows,
    __out_opt BSTR* pbstrErrorDescription
    )
{
    Assert(pidbSession);

    HRESULT hr = S_OK;
    IDBCreateCommand* pidbCommand = NULL;
    ICommandText* picmdText = NULL;
    ICommand* picmd = NULL;
    DBROWCOUNT cRows = 0;

    if (pcRows)
    {
        *pcRows = NULL;
    }

    //
    // create the command
    //
    hr = pidbSession->CreateSession(NULL, IID_IDBCreateCommand, (IUnknown**)&pidbCommand);
    ExitOnFailure(hr, "failed to create database session");
    hr = pidbCommand->CreateCommand(NULL, IID_ICommand, (IUnknown**)&picmd);
    ExitOnFailure(hr, "failed to create command to execute session");

    //
    // set the sql text into the command
    //
    hr = picmd->QueryInterface(IID_ICommandText, (LPVOID*)&picmdText);
    ExitOnFailure(hr, "failed to get command text object for command");
    hr = picmdText->SetCommandText(DBGUID_DEFAULT , wzSql);
    ExitOnFailure1(hr, "failed to set SQL string: %ls", wzSql);

    //
    // execute the command
    //
    hr = picmd->Execute(NULL, (ppirs) ? IID_IRowset : IID_NULL, NULL, &cRows, reinterpret_cast<IUnknown**>(ppirs));
    ExitOnFailure1(hr, "failed to execute SQL string: %ls", wzSql);

    if (DB_S_ERRORSOCCURRED == hr)
    {
        hr = E_FAIL;
    }

    if (pcRows)
    {
        *pcRows = cRows;
    }

LExit:

    if (FAILED(hr) && picmd && pbstrErrorDescription)
    {
        HRESULT hrGetErrors = SqlGetErrorInfo(picmd, IID_ICommandText, 0x409, NULL, pbstrErrorDescription); // TODO: use current locale instead of always American-English
        if (FAILED(hrGetErrors))
        {
            ReleaseBSTR(*pbstrErrorDescription);
        }
    }

    ReleaseObject(picmd);
    ReleaseObject(picmdText);
    ReleaseObject(pidbCommand);

    return hr;
}
示例#19
0
void CommandQueue::pushFront( const ICommand& command )
{
    LBASSERT( command.isValid( ));
    _impl->commands.pushFront( command );
}
示例#20
0
void CCommand::execute (CEntity *entity, const std::string &commandWithArgs, CLog &log, bool quiet, bool human)
{
	if (!quiet)
	{
		ucstring temp;
		temp.fromUtf8(commandWithArgs);
		string disp = temp.toString();
		log.displayNL ("Executing command : '%s'", disp.c_str());
	}

	// convert the buffer into string vector
	vector<pair<string, vector<string> > > commands;
	
	bool firstArg = true;
	uint i = 0;
	while (true)
	{
		// skip whitespace
		while (true)
		{
			if (i == commandWithArgs.size())
			{
				goto end;
			}
			if (commandWithArgs[i] != ' ' && commandWithArgs[i] != '\t' && commandWithArgs[i] != '\n' && commandWithArgs[i] != '\r')
			{
				break;
			}
			i++;
		}
		
		// get param
		string arg;
		if (commandWithArgs[i] == '\"')
		{
			// starting with a quote "
			i++;
			while (true)
			{
				if (i == commandWithArgs.size())
				{
					if (!quiet) log.displayNL ("Missing end quote character \"");
					return;
				}
				if (commandWithArgs[i] == '"')
				{
					i++;
					break;
				}
				if (commandWithArgs[i] == '\\')
				{
					// manage escape char backslash
					i++;
					if (i == commandWithArgs.size())
					{
						if (!quiet) log.displayNL ("Missing character after the backslash \\ character");
						return;
					}
					switch (commandWithArgs[i])
					{
						case '\\':	arg += '\\'; break; // double backslash
						case 'n':	arg += '\n'; break; // new line
						case '"':	arg += '"'; break; // "
						default:
							if (!quiet) log.displayNL ("Unknown escape code '\\%c'", commandWithArgs[i]);
							return;
					}
					i++;
				}
				else
				{
					arg += commandWithArgs[i++];
				}
			}
		}
		else
		{
			// normal word
			while (true)
			{
				if (commandWithArgs[i] == '\\')
				{
					// manage escape char backslash
					i++;
					if (i == commandWithArgs.size())
					{
						if (!quiet) log.displayNL ("Missing character after the backslash \\ character");
						return;
					}
					switch (commandWithArgs[i])
					{
						case '\\':	arg += '\\'; break; // double backslash
						case 'n':	arg += '\n'; break; // new line
						case '"':	arg += '"'; break; // "
						case ';':	arg += ';'; break; // ;
						default:
							if (!quiet) log.displayNL ("Unknown escape code '\\%c'", commandWithArgs[i]);
							return;
					}
				}
				else if (commandWithArgs[i] == ';')
				{
					// command separator
					break;
				}
				else
				{
					arg += commandWithArgs[i];
				}

				i++;

				if (i == commandWithArgs.size() || commandWithArgs[i] == ' ' || commandWithArgs[i] == '\t' || commandWithArgs[i] == '\n' || commandWithArgs[i] == '\r')
				{
					break;
				}
			}
		}

		if (!arg.empty())
		{
			if (firstArg)
			{
				commands.push_back (make_pair(arg, vector<string> () ));
				firstArg = false;
			}
			else
			{
				commands[commands.size()-1].second.push_back (arg);
			}
		}

		// separator
		if (i < commandWithArgs.size() && commandWithArgs[i] == ';')
		{
			firstArg = true;
			i++;
		}
	}
end:

// displays args for debug purpose
/*	for (uint u = 0; u < commands.size (); u++)
	{
		nlinfo ("c '%s'", commands[u].first.c_str());
		for (uint t = 0; t < commands[u].second.size (); t++)
		{
			nlinfo ("p%d '%s'", t, commands[u].second[t].c_str());
		}
	}
*/

	for (uint u = 0; u < commands.size (); u++)
	{
		if(!CCommandRegistry::getInstance().isCommand(commands[u].first))
		{
			// the command doesn't exist
			if (!quiet) log.displayNL("Command '%s' not found, try 'help'", commands[u].first.c_str());
		}
		else
		{
			ICommand *icom = CCommandRegistry::getInstance().getCommand(commands[u].first);
			//ICommand *icom = (*comm).second;
			if(icom->CategoryName=="mtpt_commands")//TODO find a better way, bad macro usage can result in bad cast :(((
			{
				CCommand *ccom = (CCommand *)icom;
				if (!ccom->execute (entity,commands[u].second, log, quiet, human))
				{
					if (!quiet) log.displayNL("Bad ccommand usage, try 'help %s'", commands[u].first.c_str());
				}
			}
			else
			{
				if (!icom->execute(NULL, commands[u].second, log, quiet, human))
				{
					if (!quiet) log.displayNL("Bad icommand usage, try 'help %s'", commands[u].first.c_str());
				}
			}
		}
	}
}
示例#21
0
void wxGISAcceleratorTable::Store(void)
{
	wxXmlNode* pAcceleratorsNodeCU = m_pConf->GetConfigNode(enumGISHKCU, wxString(wxT("accelerators")));
	if(pAcceleratorsNodeCU)
		wxGISConfig::DeleteNodeChildren(pAcceleratorsNodeCU);
	else
		pAcceleratorsNodeCU = m_pConf->CreateConfigNode(enumGISHKCU, wxString(wxT("accelerators")), true);
	for(size_t i = 0; i < m_AccelEntryArray.size(); i++)
	{
		ICommand* pCmd = m_pApp->GetCommand(m_AccelEntryArray[i].GetCommand());
		wxObject* pObj = dynamic_cast<wxObject*>(pCmd);
		if(pObj)
		{
			wxClassInfo* pInfo = pObj->GetClassInfo();
			wxString sClassName = pInfo->GetClassName();
			unsigned char nSubType = pCmd->GetSubType();
			int nKeyCode = m_AccelEntryArray[i].GetKeyCode();
			int nFlags = m_AccelEntryArray[i].GetFlags();
			wxString sFlags;

			if(nFlags & wxMOD_ALT)
				sFlags += wxT("ALT|");
			if(nFlags & wxMOD_CONTROL)
				sFlags += wxT("CTRL|");
			if(nFlags & wxMOD_SHIFT)
				sFlags += wxT("SHIFT|");
			if(nFlags == 0)
				sFlags += wxT("NORMAL");

			wxString sKeyCode;
			if(nKeyCode >= WXK_F1 && nKeyCode <= WXK_F12)
			{
				sKeyCode += wxString::Format(wxT("WXK_F%d"), nKeyCode - WXK_DIVIDE );
			}
			else if((nKeyCode >= (int)'A' && nKeyCode <= (int)'Z') || (nKeyCode >= (int)'0' && nKeyCode <= (int)'9') || (nKeyCode >= WXK_NUMPAD0 && nKeyCode <= WXK_NUMPAD9))
			{
				sKeyCode += wxString(wxChar(nKeyCode));
			}
			else if(nKeyCode == WXK_DELETE )
			{
				sKeyCode += wxString(wxT("WXK_DELETE"));
			}	
			else if(nKeyCode == WXK_NUMPAD_DELETE)
			{
				sKeyCode += wxString(wxT("WXK_NUMPAD_DELETE"));
			}
			else if(nKeyCode == WXK_ESCAPE)
			{
				sKeyCode += wxString(wxT("WXK_ESCAPE"));
			}
			else if(nKeyCode == WXK_SPACE)
			{
				sKeyCode += wxString(wxT("WXK_SPACE"));
			}
			else if(nKeyCode == WXK_NUMPAD_SPACE)
			{
				sKeyCode += wxString(wxT("WXK_NUMPAD_SPACE"));
			}
			else if(nKeyCode == WXK_RETURN)
			{
				sKeyCode += wxString(wxT("WXK_RETURN"));
			}
			else if(nKeyCode == WXK_EXECUTE)
			{
				sKeyCode += wxString(wxT("WXK_EXECUTE"));
			}
			else if(nKeyCode == WXK_PAUSE)
			{
				sKeyCode += wxString(wxT("WXK_PAUSE"));
			}
			else if(nKeyCode == WXK_END)
			{
				sKeyCode += wxString(wxT("WXK_END"));
			}
			else if(nKeyCode == WXK_NUMPAD_END)
			{
				sKeyCode += wxString(wxT("WXK_NUMPAD_END"));
			}
			else if(nKeyCode == WXK_HOME)
			{
				sKeyCode += wxString(wxT("WXK_HOME"));
			}
			else if(nKeyCode == WXK_NUMPAD_HOME)
			{
				sKeyCode += wxString(wxT("WXK_NUMPAD_HOME"));
			}
			else if(nKeyCode == WXK_INSERT)
			{
				sKeyCode += wxString(wxT("WXK_INSERT"));
			}
			else if(nKeyCode == WXK_NUMPAD_INSERT)
			{
				sKeyCode += wxString(wxT("WXK_NUMPAD_INSERT"));
			}

			wxXmlNode* pNewNode = new wxXmlNode(pAcceleratorsNodeCU, wxXML_ELEMENT_NODE, wxString(wxT("Entry")));
			pNewNode->AddProperty(wxT("cmd_name"), sClassName);
			pNewNode->AddProperty(wxT("subtype"), wxString::Format(wxT("%u"), nSubType));
			pNewNode->AddProperty(wxT("flags"), sFlags);
			pNewNode->AddProperty(wxT("keycode"), sKeyCode);
		}
	}
}
示例#22
0
void wxGISCommandBar::Serialize(IApplication* pApp, wxXmlNode* pNode, bool bStore)
{
	if(bStore)
	{
		pNode->AddProperty(wxT("name"), m_sName);
		pNode->AddProperty(wxT("caption"), m_sCaption);
		for(size_t i = m_CommandArray.size(); i > 0; i--)
		{
			ICommand* pCmd = m_CommandArray[i - 1];
			if(pCmd)
			{
				wxXmlNode* pNewNode = new wxXmlNode(pNode, wxXML_ELEMENT_NODE, wxString(wxT("Item")));
				wxGISEnumCommandKind Kind = pCmd->GetKind();
				switch(Kind)
				{
				case enumGISCommandSeparator:
					pNewNode->AddProperty(wxT("type"), wxT("sep"));
					break;
				case enumGISCommandCheck:
				case enumGISCommandRadio:
				case enumGISCommandNormal:
				case enumGISCommandControl:
				{
					pNewNode->AddProperty(wxT("type"), wxT("cmd"));
					wxObject* pObj = dynamic_cast<wxObject*>(pCmd);
					if(pObj)
					{
						wxClassInfo* pInfo = pObj->GetClassInfo();
						wxString sClassName = pInfo->GetClassName();
						pNewNode->AddProperty(wxT("cmd_name"), sClassName);
						pNewNode->AddProperty(wxT("subtype"), wxString::Format(wxT("%u"), pCmd->GetSubType()));
						pNewNode->AddProperty(wxT("name"), pCmd->GetCaption());
					}
					break;
				}
				case enumGISCommandMenu:
				{
					pNewNode->AddProperty(wxT("type"), wxT("menu"));
					IGISCommandBar* pCB = dynamic_cast<IGISCommandBar*>(pCmd);
					if(pCB)
					{
						pNewNode->AddProperty(wxT("cmd_name"), pCB->GetName());
						pNewNode->AddProperty(wxT("name"), pCmd->GetCaption());
					}
					break;
				}
				default:
					break;
				}
			}
		}
	}
	else
	{
		//m_sName = pNode->GetPropVal(wxT("name"), m_sName);
		//m_sCaption = pNode->GetPropVal(wxT("caption"), m_sCaption);
		wxXmlNode *subchild = pNode->GetChildren();
		while(subchild)
		{
			wxString sType = subchild->GetPropVal(wxT("type"), wxT("sep"));
			if(sType == wxT("cmd"))
			{
				wxString sCmdName = subchild->GetPropVal(wxT("cmd_name"), wxT("None"));
				unsigned char nSubtype = wxAtoi(subchild->GetPropVal(wxT("subtype"), wxT("0")));
				//wxString sName = subchild->GetPropVal(wxT("name"), NONAME);
				ICommand* pSubCmd = pApp->GetCommand(sCmdName, nSubtype);
				if(pSubCmd)
					AddCommand(pSubCmd);
			}
			else if(sType == wxT("menu"))
			{
				//the menu description must be exist in xml before using submenu
				wxString sCmdName = subchild->GetPropVal(wxT("cmd_name"), ERR);
				IGISCommandBar* pGISCommandBar = pApp->GetCommandBar(sCmdName);
				if(pGISCommandBar)
				{
					ICommand* pSubCmd = dynamic_cast<ICommand*>(pGISCommandBar);
					if(pSubCmd)
						AddCommand(pSubCmd);
					else
						AddMenu(dynamic_cast<wxMenu*>(pGISCommandBar), pGISCommandBar->GetCaption());
				}
			}
			else
			{
				ICommand* pSubCmd = pApp->GetCommand(wxT("wxGISCommonCmd"), 3);
				if(pSubCmd)
					AddCommand(pSubCmd);
			}			
			subchild = subchild->GetNext();	
		}
	}
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 *
 * NAME : perform 
 *
 * DESCRIPTION : reads from the pipes and execute the command.
 *
 *-----------------------------------------------------------------------------*/
int perform(int bytes)
{
#ifdef CS1_DEBUG
    char debug_buffer[255] = {0};
#endif
    char* buffer = NULL;    // TODO  This buffer scared me ! 
    int read_total = 0;
    ICommand* command  = NULL;
    char previous_command_buffer[MAX_COMMAND_SIZE] = {'\0'};
    unsigned char read = 0;

    for(int i = 0; i != bytes; i++) {
        read = (unsigned char)info_buffer[i];

#ifdef CS1_DEBUG
        std::ostringstream msg;
        msg << "Read from info pipe = " << (unsigned int)read << " bytes";
        Shakespeare::log(Shakespeare::NOTICE, LOGNAME, msg.str());
#endif

        switch (read) 
        {
            case NET2COM_SESSION_ESTABLISHED :
                break;
            case NET2COM_SESSION_END_CMD_CONFIRMATION :
            case NET2COM_SESSION_END_TIMEOUT :
            case NET2COM_SESSION_END_BY_OTHER_HOST :
            {
                int data_bytes = 0;
                while (data_bytes == 0) {
                    data_bytes = commander->ReadFromDataPipe(buffer, read_total);

                    if (data_bytes > 0) {
#ifdef CS1_DEBUG
                          std::ostringstream msg;
                          msg << "Read " << data_bytes << " bytes from ground station: ";
                          memset (debug_buffer,0,255);
                          for(uint8_t z = 0; z < data_bytes; ++z){
                              uint8_t c = buffer[z];
                              snprintf(debug_buffer,5, "0x%02X ", c);
                              msg << debug_buffer;
                          }
                          Shakespeare::log(Shakespeare::NOTICE, LOGNAME, msg.str());
#endif

                        if (data_bytes != read_total) {
                            Shakespeare::log(Shakespeare::ERROR, LOGNAME, "Something went wrong !!");
                            read_total = 0;
                            break;
                        }

                        FILE *fp_last_command = NULL;
                        unsigned int retry = 10000;

                        if (buffer[COMMAND_RESEND_INDEX] == COMMAND_RESEND_CHAR) 
                        {
                            while(retry > 0 && fp_last_command == NULL){
                                fp_last_command = fopen(LAST_COMMAND_FILENAME.c_str(), "r");
                                retry -=1;
                            }

                            if (fp_last_command != NULL) 
                            {
                                fread(previous_command_buffer, sizeof(char), MAX_COMMAND_SIZE, fp_last_command);
                                fclose(fp_last_command);

                                command = CommandFactory::CreateCommand(previous_command_buffer);

                                if (command != NULL) 
                                {
                                    Shakespeare::log(Shakespeare::NOTICE, 
                                                                    LOGNAME, 
                                                                            "Executing command");

                                    size_t size = 0;
                                    char* result  = (char* )command->Execute(&size);
                                    if (result != NULL) 
                                    {
                                        memset(log_buffer,0,MAX_BUFFER_SIZE);
                                        snprintf(log_buffer, MAX_BUFFER_SIZE, "Command output = %s\n", result);
                                        Shakespeare::log(Shakespeare::NOTICE,LOGNAME,log_buffer);

                                        if (size > 0) {
                                            commander->WriteToDataPipe(result, size);
                                        } else { // this branch will be remove as soon as ALL commands returns the SIZE ! TODO
                                                 // Because it is not safe to rely on a NULL terminator in the result buffer.
                                            commander->WriteToDataPipe(result);
                                        }

                                        free(result); // TODO allocate result buffer with new in all icommand subclasses and use delete
                                        result = NULL;
                                    } else {
                                        commander->WriteToInfoPipe(ERROR_EXECUTING_COMMAND);
                                    }

                                    if (command) {
                                        delete command;
                                        command = NULL;
                                    }
                                } else {
                                    commander->WriteToInfoPipe(ERROR_CREATING_COMMAND);
                                }

                                memset(previous_command_buffer, '\0', MAX_COMMAND_SIZE);
                            }
                        } else {

                            while (retry > 0 && fp_last_command == NULL) {
                                fp_last_command = fopen(LAST_COMMAND_FILENAME.c_str(), "w");
                                retry -= 1;
                            }

                            if (fp_last_command != NULL) {
                                fwrite(buffer, sizeof(char), data_bytes, fp_last_command);
                                fclose(fp_last_command);
                            }
                        }

                        free(buffer);
                        buffer = NULL;
                    }

                    sleep(COMMANER_SLEEP_TIME);
                } //end while

                read_total = 0;
                break;
            }
            default:
                    read_total += read;
                    buffer = (char* )realloc(buffer, read_total * sizeof(char)); // todo get rid of this realloc! use new instead
                    memset(buffer, 0, sizeof(char) * read_total);
                break;
        } // end switch
    } // end for

    return 0;
}