Ejemplo n.º 1
0
void Server::textRead(){
    QTcpSocket *source = dynamic_cast<QTcpSocket*>(sender());
    QByteArray data = source->readAll();

    QByteArray namePrefix = "/Name::";
    QByteArray challengePrefix = "/Challenge::";
    QByteArray challengeAcceptedPrefix = "/ChallengeAccepted::";
    QByteArray settingsPrefix = "/Settings::";
    QByteArray startPrefix = "/Start::";
    QByteArray turnPrefix = "/Turn::";
    QByteArray locationPrefix = "/Location::";
    QByteArray multiplayerMatchPrefix = "/MultiplayerMatch::";

    if (data.startsWith(namePrefix)){
        QString tempNick(data);
        QStringRef name(&tempNick, namePrefix.length(), tempNick.length() - namePrefix.length());
        QString validName = isAvailable(name.toString());
        nickContainer->append(validName);
        if (name != validName){
            source->write("/ValidName::" + validName.toLatin1());
        }
        sendClientList();
    } else if (data.startsWith(challengePrefix)){
        QString tempNick(data);
        QStringRef name(&tempNick, challengePrefix.length(), tempNick.length() - challengePrefix.length());
        sendChallenge(source, name);
    } else if (data.startsWith(challengeAcceptedPrefix)){
        QString tempNick(data);
        QStringRef name(&tempNick, challengeAcceptedPrefix.length(), tempNick.length() - challengeAcceptedPrefix.length());
        sendChallengeAccepted(name);
    } else if (data.startsWith(settingsPrefix)){
        QString tempString(data);
        QStringRef values(&tempString, settingsPrefix.length(), tempString.length() - settingsPrefix.length());
        sendSettingsData(values.toString());
    } else if (data.startsWith(startPrefix)){
        QString tempString(data);
        QStringRef values(&tempString, startPrefix.length(), tempString.length() - startPrefix.length());
        sendStartMessage(values);
    } else if (data.startsWith(turnPrefix)){
        QString tempString(data);
        QStringRef name(&tempString, turnPrefix.length(), tempString.length() - turnPrefix.length());
        sendTurnChangeMessage(name);
    } else if (data.startsWith(locationPrefix)){
        QString tempString(data);
        QStringRef values(&tempString, locationPrefix.length(), tempString.length() - locationPrefix.length());
        sendLocationMessage(values);
    } else if (data.startsWith(multiplayerMatchPrefix)){
        QString tempString(data);
        sendPrivateMessage(tempString, multiplayerMatchPrefix);
    } else {
        QTime time = QTime::currentTime();
        QString timeString = time.toString() + " ";
        for (int i = 0; i < clientContainer->size(); ++i){
            clientContainer->at(i)->write(timeString.toLatin1() + data);
        }
    }
}
Ejemplo n.º 2
0
void UIDropdownBox::addMessageData()
{
    BString	strFalse	= L"False";
    BString	strTrue		= L"True";

    char temp[64];
    sprintf(temp,"%u",mMaxLength);
	std::string tempString(temp);

    gMessageFactory->addUint8(3);
    gMessageFactory->addUint32(1);
    gMessageFactory->addString((mEnabled) ? strTrue : strFalse);
    gMessageFactory->addUint32(2);
    gMessageFactory->addString(mName);
    gMessageFactory->addString(BString("Enabled"));

	gMessageFactory->addUint8(3);
    gMessageFactory->addUint32(1);
    gMessageFactory->addString((mEnabled) ? strTrue : strFalse);
    gMessageFactory->addUint32(2);
    gMessageFactory->addString(mName);
    gMessageFactory->addString(BString("visible"));

	gMessageFactory->addUint8(3);
    gMessageFactory->addUint32(1);
    gMessageFactory->addString(std::wstring(tempString.begin(), tempString.end()));
    gMessageFactory->addUint32(2);
    gMessageFactory->addString(mName);
    gMessageFactory->addString(BString("MaxLength"));
}
Ejemplo n.º 3
0
// return a substring beginning at index and of length subLength
String String::operator()( int index, int subLength ) const
{
   // if index is out of range or substring length < 0, 
   // return an empty String object
   if ( index < 0 || index >= lngth || subLength < 0 )  
      return ""; // converted to a String object automatically

   // determine length of substring
   int len;

   if ( ( subLength == 0 ) || ( index + subLength > lngth ) )
      len = lngth - index;
   else
      len = subLength;

   // allocate temporary array for substring and 
   // terminating null character
   char *tempPtr = new char[ len + 1 ];

   // copy substring into char array and terminate string
   strncpy( tempPtr, &sPtr[ index ], len );
   tempPtr[ len ] = '\0';

   // create temporary String object containing the substring
   String tempString( tempPtr );
   delete [] tempPtr;
   return tempString;
} 
vector<string> ReadFileList(string path)
{
	DIR *dir;
	struct dirent *ent;
	vector<string> _listStringName;
	if ((dir = opendir(path.c_str())) != NULL)
	{
		/* print all the files and directories within directory */
		while ((ent = readdir(dir)) != NULL)
		{
			char *pName = ent->d_name;
			if (strcmp(pName, "..") != 0 && strcmp(pName, ".") != 0)
			{
				string tempString(pName);
				_listStringName.push_back(tempString);

				//printf("%s\n", ent->d_name);
			}
		}
		closedir(dir);
	}
	else
	{
		/* could not open directory */
		cout << "Cannot open directory" << endl;
	}

	return _listStringName;
}
Ejemplo n.º 5
0
  CMyString& operator=(const CMyString &str){
    if(this!=&str){
      CMyString tempString(str);

      char* tempData=tempString.m_pData;
      tempString.m_pData=m_pData;
      m_pData=tempData;
    }
    return *this;
  }
Ejemplo n.º 6
0
char* IntToChar(int init)
{
	String tempString("");
	int tempInt;
	bool negative;
	if(init < 0)			// Negativt tal?
		negative = true;
	else
	   negative = false;

	do
	{
		tempInt = init%10;			// Få fram sista siffran
		init -= tempInt;			// Dra bort sista siffran
		init /= 10;					// Ta bort nollan som blir där

		switch (tempInt)
		{
		 case 0: tempString += "0"; break;
		 case 1: tempString += '1'; break;
		 case 2: tempString += '2'; break;
		 case 3: tempString += '3'; break;
		 case 4: tempString += '4'; break;
		 case 5: tempString += '5'; break;
		 case 6: tempString += '6'; break;
		 case 7: tempString += '7'; break;
		 case 8: tempString += '8'; break;
		 case 9: tempString += '9'; break;
		}
	} while(init != 0);

	char* ret;
	if(negative)
	{
		ret = new char[tempString.getLen()+2];
		ret[0] = '-';
		for(int i = 1, j = tempString.getLen()-1; j >= 0; j--, i++)//tempString.getLen() != 0)
			ret[i] = tempString.getChar(j);

		ret[tempString.getLen()+1] = '\0';
	}
	else
	{
 		ret= new char[tempString.getLen()+1];

		for(int i = 0, j = tempString.getLen()-1; j >= 0; j--, i++)//tempString.getLen() != 0)
			ret[i] = tempString.getChar(j);

		ret[tempString.getLen()] = '\0';
	}
	return ret;
}
Ejemplo n.º 7
0
UC_API_SYMBOL_EXPORT
UniCErrorT UniCStringCreateFromWCharString(
    const wchar_t* wcharString,
    const size_t wcharStringLength,
    UniCStringT* result
)
{
    UC_BEGIN_TRY_BLOCK();
    NULLPTR_ARG_CHECK(result);
    std::wstring tempString(wcharString, wcharStringLength);
    *result = reinterpret_cast<UniCStringT>(new UniCString::Core::String(tempString));
    UC_END_TRY_BLOCK();
}
Ejemplo n.º 8
0
NS_IMETHODIMP nsMsgHeaderParser::ParseHeadersWithArray(const PRUnichar * aLine, PRUnichar *** aEmailAddresses,
        PRUnichar *** aNames, PRUnichar *** aFullNames, PRUint32 * aNumAddresses)
{
    char * names = nsnull;
    char * addresses = nsnull;
    PRUint32 numAddresses = 0;
    nsresult rv = NS_OK;

    // need to convert unicode to UTF-8...
    nsAutoString tempString (aLine);
    char * utf8String = ToNewUTF8String(tempString);

    rv = ParseHeaderAddresses(utf8String, &names, &addresses, &numAddresses);
    NS_Free(utf8String);
    if (NS_SUCCEEDED(rv) && numAddresses)
    {
        // allocate space for our arrays....
        *aEmailAddresses = (PRUnichar **) PR_MALLOC(sizeof(PRUnichar *) * numAddresses);
        *aNames = (PRUnichar **) PR_MALLOC(sizeof(PRUnichar *) * numAddresses);
        *aFullNames = (PRUnichar **) PR_MALLOC(sizeof(PRUnichar *) * numAddresses);

        // for simplicities sake...
        PRUnichar ** outgoingEmailAddresses = *aEmailAddresses;
        PRUnichar ** outgoingNames = *aNames;
        PRUnichar ** outgoingFullNames = *aFullNames;

        // iterate over the results and fill in our arrays....
        PRUint32 index = 0;
        const char * currentName = names;
        const char * currentAddress = addresses;
        char * unquotedName = nsnull;
        while (index < numAddresses)
        {
            if (NS_SUCCEEDED(UnquotePhraseOrAddr(currentName, PR_TRUE, &unquotedName)))
                rv = FillResultsArray(unquotedName, currentAddress, &outgoingEmailAddresses[index], &outgoingNames[index], &outgoingFullNames[index], this);
            else
                rv = FillResultsArray(currentName, currentAddress, &outgoingEmailAddresses[index], &outgoingNames[index], &outgoingFullNames[index], this);

            PR_FREEIF(unquotedName);
            currentName += strlen(currentName) + 1;
            currentAddress += strlen(currentAddress) + 1;
            index++;
        }
    }

    *aNumAddresses = numAddresses;
    PR_FREEIF(names);
    PR_FREEIF(addresses);
    return rv;
}
Ejemplo n.º 9
0
// -----------------------------------------------------------------------------
// CActiveExample::ShowTheListMsgQueryL
// -----------------------------------------------------------------------------
//
void CActiveExample::ShowTheListMsgQueryL()
    {
    
    _LIT( KHead, "Message" );
    _LIT( KText, "Item" ); 
    
    TBufC<20> tempString( KText );
    CDesCArrayFlat* arrayItem = new( ELeave ) CDesCArrayFlat( 20 );
    arrayItem->AppendL( tempString );
    iGlobalListMsgQuery->ShowListMsgQueryL( arrayItem, iStatus, KHead, KText );
    SetActive();
    
    CActiveScheduler::Start();
    
    }
Ejemplo n.º 10
0
void ossim::defaultTileSize(ossimIpt& tileSize)
{
   const char* tileSizeKw = ossimPreferences::instance()->
      findPreference("tile_size");

   if(tileSizeKw)
   {
      std::vector<ossimString> splitArray;
      ossimString tempString(tileSizeKw);
      tempString.split(splitArray, " ");
      bool hasX = true;
    if(splitArray.size() == 2)
      {
         tileSize.x = splitArray[0].toInt32();
         tileSize.y = splitArray[1].toInt32();
      }
      else if(splitArray.size() == 1)
      {
         tileSize.x = splitArray[0].toInt32();
         tileSize.y = splitArray[0].toInt32();
      }
      else
      {
         tileSize = ossimIpt(0,0);
      }
      if(tileSize.x < 1)
      {
         tileSize.x = OSSIM_DEFAULT_TILE_WIDTH;
         hasX = false;
      }
      if(tileSize.y < 1)
      {
         if(!hasX)
         {
            tileSize.y = OSSIM_DEFAULT_TILE_HEIGHT;
         }
         else
         {
            tileSize.y = tileSize.x;
         }
      }
   }
   else
   {
      tileSize.x = OSSIM_DEFAULT_TILE_WIDTH;
      tileSize.y = OSSIM_DEFAULT_TILE_HEIGHT;
   }
}
Ejemplo n.º 11
0
UC_API_SYMBOL_EXPORT
UniCErrorT UniCStringCreateFromCharString(
    const char* charString,
    const size_t charStringLength,
    UniCEncodingT encoding,
    UniCStringT* result
)
{
    UC_BEGIN_TRY_BLOCK();
    NULLPTR_ARG_CHECK(result);
    std::string tempString(charString, charStringLength);
    *result = reinterpret_cast<UniCStringT>(
        new UniCString::Core::String(tempString, GET_CORE_STRING_ENCODING(encoding))
    );
    UC_END_TRY_BLOCK();
}
Ejemplo n.º 12
0
//*****************************************************************************
//  METHOD: 
//*****************************************************************************
bool ossim2dTo2dTransform::loadState(const ossimKeywordlist& kwl,
               const char* prefix)
{
  bool result = true;

   const char* buf;

   buf= kwl.find(prefix, ossimKeywordNames::CONVERGENCE_THRESHOLD_KW);

   if (buf)
   {
      theConvergenceThreshold = atof(buf);
   }
   else
   {
      theConvergenceThreshold = .00000000000002;
   }
   
   buf= kwl.find(prefix, ossimKeywordNames::MAX_ITERATIONS_KW);
   if(buf)
   {
      theMaxIterations = atoi(buf);
   }
   else
   {
      theMaxIterations = 10;
   }
   const char* dxdy = kwl.find(prefix, "dxdy");
   if(dxdy)
   {
      ossimString tempString(dxdy);
      std::vector<ossimString> splitArray;
      tempString = tempString.trim();
      tempString.split(splitArray, " ");
      if(splitArray.size()==2)
      {
         theDxDy.x = splitArray[0].toDouble();
         theDxDy.y = splitArray[1].toDouble();
      }
   }
   if(result)
   {
      ossimObject::loadState(kwl, prefix);
   }
   
   return result;
}
Ejemplo n.º 13
0
void RunnableWrapper::pushToThreadPull(shared_ptr<Runnable> r )
{
	if(availableThreads == 0 && threadCount < maxThreadCount) {
		threadCount++;
		shared_ptr<Runnable> r;
		shared_ptr<RunnableWrapper> wrapper = new  RunnableWrapper(r, 4);
		String tempString(L"invokeAndBlock");
		shared_ptr<String>id = new String((tempString + System::getString(threadCount)));
		shared_ptr<Thread> poolThread = new Thread(wrapper, id);
		poolThread->start();
	}
	THREADPOOL_LOCK->lock();
	{
		threadPool->addElement(r);
		THREADPOOL_LOCK->notify();
	}
	THREADPOOL_LOCK->unlock();
}
Ejemplo n.º 14
0
void ClientAgent::CTCPAction(BString theTarget, BString theMsg)
{
	BString theCTCP(GetWord(theMsg.String(), 1).ToUpper()),
		theRest(RestOfString(theMsg.String(), 2)), tempString("[CTCP->");

	tempString += theTarget;
	tempString += "] ";
	tempString += theCTCP;

	if (theRest != "-9z99") {
		tempString += " ";
		tempString += theRest;
		tempString += '\n';
	} else
		tempString += '\n';

	Display(tempString.String(), C_CTCP_REQ, C_BACKGROUND, F_SERVER);
}
Ejemplo n.º 15
0
/**********************************************************************************
* AUTHOR		: Thanigai Murugan K
* DATE			: 30-AUG-2005
* NAME			: main
* DESCRIPTION	: Main function. Process the command line options and invoke the
*				  train/test methods after instantiating LipiEngine module.
* ARGUMENTS		: Command line arguments, refer to PrintUsage() function for syntax
* RETURNS		: -1 on error 0 on success
* NOTES			:
* CHANGE HISTROY
* Author			Date				Description of change
*************************************************************************************/
int main(int argc, char** argv)
{
	//char *envstring = NULL;
	char lipienginepath[MAX_PATH]="";
	int iErrorCode;
    LTKOSUtil* utilPtr = LTKOSUtilFactory::getInstance();
    void *functionHandle = NULL;
	
	globalArg = argv;
	globalArgCount = argc;

	utilPtr->recordStartTime();
	
	// Assume the default log file, if user did not specify one...
	if(LTKSTRCMP(strLogFile, "") == 0)
	{
		strcpy(strLogFile, DEFAULT_LOG_FILE);
	}

	if(processCommandLineArgs() != 0)
	{
		printUsage();
		delete utilPtr;
		return -1;
	}

	if(bVersionRequest) /* Then display version and exit */
	{
		cout << "\n Version of runwordrec tool: " << SUPPORTED_MIN_VERSION << endl;
		delete utilPtr;
		return 0;
	}

	/* Get the LIPI_ROOT environment variable if the user has not provided in the command line */


	if(strlen(strLipiRootPath)==0)
	{
		char *tempStr=NULL;

		/* Get the LIPI_ROOT environment variable */
		tempStr=getenv(LIPIROOT_ENV_STRING);
		

		if(tempStr == NULL)
		{
			cout << "Error,LIPI_ROOT is neither provided in the command line nor set as an environment variable\n" << endl;
			delete utilPtr;
			return -1;
		}
		strcpy(strLipiRootPath,tempStr);
	}


	// Load the LipiEngine.DLL
	hLipiEngine = NULL;

    iErrorCode = utilPtr->loadSharedLib(strLipiRootPath, 
                                        LIPIENGINE_MODULE_STR, 
                                        &hLipiEngine);

	if(iErrorCode != SUCCESS)
	{
		cout << "Error loading LipiEngine module" << endl;
		delete utilPtr;
		return -1;
	}
	

	int iMajor_lipiEngine=0, iMinor_lipiEngine=0, iBugfix_lipiEngine=0;

    iErrorCode = utilPtr->getFunctionAddress(hLipiEngine, 
                                             "getToolkitVersion", 
                                             &functionHandle);

    if(iErrorCode != SUCCESS)
	{
		cout << "Error mapping the getToolkitVersion function" << endl;
		delete utilPtr;
		return -1;
	}

    LipiEngine_getCurrentVersion = (FN_PTR_GETCURRENTVERSION) functionHandle;

	LipiEngine_getCurrentVersion(&iMajor_lipiEngine, &iMinor_lipiEngine, &iBugfix_lipiEngine);

	// Version comparison START
	char toolkitVer[MAX_STRLEN];
	sprintf(toolkitVer, "%d.%d.%d",iMajor_lipiEngine,iMinor_lipiEngine,iBugfix_lipiEngine);

	LTKVersionCompatibilityCheck verTempObj;
	string supportedMinVersion(SUPPORTED_MIN_VERSION);
	string toolkitVersion(toolkitVer);

	bool compatibilityResults = verTempObj.isFirstVersionHigher(toolkitVersion, supportedMinVersion);

	if(compatibilityResults == false)
	{
		cout<< "\nIncompatible version of LipiEngine(ver: " << toolkitVersion << ") with runwordrec(ver: " << supportedMinVersion << ")" << endl;
		
		// Unload the DLL from memory
		utilPtr->unloadSharedLib(hLipiEngine);
		delete utilPtr;
		return FAILURE;
	}
	// Version comparison END

	// without reserving memory, it gives an error at the end...
	strLogFileName.reserve(MAX_PATH); 

	/* Get the function address of "createLTKLipiEngine" function from the DLL module */
    functionHandle = NULL;
    iErrorCode = utilPtr->getFunctionAddress(hLipiEngine, 
                                            "createLTKLipiEngine", 
                                            &functionHandle);

    if(iErrorCode != SUCCESS)
	{
		cout << "Error mapping the createLTKLipiEngine function" << endl;
		delete utilPtr;
		return -1;
	}

    createLTKLipiEngine = (FN_PTR_CREATELTKLIPIENGINE) functionHandle;

    functionHandle = NULL;
    
	// Create an instance of LipiEngine
	ptrObj = createLTKLipiEngine();

	// set the LIPI_ROOT path in Lipiengine module instance
	ptrObj->setLipiRootPath(strLipiRootPath);

	// set the Log File Path
	if (strlen(strLogFile) != 0 )
	{
		string tempString(strLogFile);
		ptrObj->setLipiLogFileName(tempString);
	}

	if(strlen(strLogLevel) != 0)
	{
		string tempStringLogLevel(strLogLevel);
		ptrObj->setLipiLogLevel(tempStringLogLevel);
	}


	// Initialize the LipiEngine 
	iErrorCode = ptrObj->initializeLipiEngine();
	if(iErrorCode != 0)
	{
		cout << "Error initializing lipiengine: " << getErrorMessage(iErrorCode) << endl;
		cout << "For more details, please see the log file" << endl;
		// Unload the DLL from memory
		utilPtr->unloadSharedLib(hLipiEngine);
		delete utilPtr;
		return -1;
	}

	string strProjName(strProjectName), strProfName(strProfileName);

	// Now create the word recognizer instance using the project/profile name strings
	LTKWordRecognizer *pReco;
	iErrorCode = ptrObj->createWordRecognizer(strProjName, strProfName, &pReco);

	if(iErrorCode != SUCCESS)
	{
		cout << "Error creating word recognizer: " << getErrorMessage(iErrorCode) << endl;
		cout << "For more details, please see the log file" << endl;

		// Unload the DLL from memory
		utilPtr->unloadSharedLib(hLipiEngine);
		delete utilPtr;
		return -1;
	}

	if(bComputePerformance)
    {
        utilPtr->recordStartTime();
    }
	
	iErrorCode = evaluateWordRecognizer(pReco, strTestLstFile);
	if(iErrorCode != SUCCESS)
	{

		cout << "Error during testing the word recognizer: " << getErrorMessage(iErrorCode) << endl;
		cout << "For more details, please see the log file" << endl;

		ptrObj->deleteWordRecognizer(&pReco);

		// Unload the DLL from memory
		utilPtr->unloadSharedLib(hLipiEngine);
		delete utilPtr;
		return -1;
	}

	if(bComputePerformance)
	{
		utilPtr->recordEndTime();

        string timeTaken = "";
        utilPtr->diffTime(timeTaken);
        cout << "Time taken:" << timeTaken << endl;
	}

	// Delete the word recognizer which was created...
	ptrObj->deleteWordRecognizer(&pReco);

	// Unload the DLL from memory
	utilPtr->unloadSharedLib(hLipiEngine);

    delete utilPtr;


	return 0;
}
Ejemplo n.º 16
0
NS_IMETHODIMP
XRemoteService::ParseCommand(const char *aCommand, nsIDOMWindow* aWindow)
{
  NS_ASSERTION(aCommand, "Tell me what to do, or shut up!");

  // begin our parse
  nsCString tempString(aCommand);

  // find the () in the command
  PRInt32 begin_arg = tempString.FindChar('(');
  PRInt32 end_arg = tempString.RFindChar(')');

  // make sure that both were found, the string doesn't start with '('
  // and that the ')' follows the '('
  if (begin_arg == kNotFound || end_arg == kNotFound ||
      begin_arg == 0 || end_arg < begin_arg)
    return NS_ERROR_INVALID_ARG;

  // truncate the closing paren and anything following it
  tempString.Truncate(end_arg);

  // save the argument and trim whitespace off of it
  nsCString argument(tempString);
  argument.Cut(0, begin_arg + 1);
  argument.Trim(" ", PR_TRUE, PR_TRUE);

  // remove the argument
  tempString.Truncate(begin_arg);

  // get the action, strip off whitespace and convert to lower case
  nsCString action(tempString);
  action.Trim(" ", PR_TRUE, PR_TRUE);
  ToLowerCase(action);

  // pull off the noraise argument if it's there.
  PRUint32  index = 0;
  PRBool    raiseWindow = PR_TRUE;
  nsCString lastArgument;

  FindLastInList(argument, lastArgument, &index);
  if (lastArgument.LowerCaseEqualsLiteral("noraise")) {
    argument.Truncate(index);
    raiseWindow = PR_FALSE;
  }

  nsresult rv = NS_OK;
  
  /*   
      openURL ( ) 
            Prompts for a URL with a dialog box. 
      openURL (URL) 
            Opens the specified document without prompting. 
      openURL (URL, new-window) 
            Create a new window displaying the the specified document. 
  */

  /*
      openFile ( ) 
            Prompts for a file with a dialog box. 
      openFile (File) 
            Opens the specified file without prompting. 

  */

  if (action.Equals("openurl") || action.Equals("openfile")) {
    rv = OpenURL(argument, aWindow, PR_TRUE);
  }

  /*
      saveAs ( ) 
            Prompts for a file with a dialog box (like the menu item). 
      saveAs (Output-File) 
            Writes HTML to the specified file without prompting. 
      saveAs (Output-File, Type) 
            Writes to the specified file with the type specified -
	    the type may be HTML, Text, or PostScript. 

  */

  else if (action.Equals("saveas")) {
    if (argument.IsEmpty()) {
      rv = NS_ERROR_NOT_IMPLEMENTED;
    }
    else {
      // check to see if it has a type on it
      index = 0;
      FindLastInList(argument, lastArgument, &index);
      if (lastArgument.LowerCaseEqualsLiteral("html")) {
	argument.Truncate(index);
	rv = NS_ERROR_NOT_IMPLEMENTED;
      }
      else if (lastArgument.EqualsIgnoreCase("text", PR_TRUE)) {
	argument.Truncate(index);
	rv = NS_ERROR_NOT_IMPLEMENTED;
      }
      else if (lastArgument.EqualsIgnoreCase("postscript", PR_TRUE)) {
	argument.Truncate(index);
	rv = NS_ERROR_NOT_IMPLEMENTED;
      }
      else {
	rv = NS_ERROR_NOT_IMPLEMENTED;
      }
    }
   
  }

  /*
      mailto ( ) 
            pops up the mail dialog with the To: field empty. 
      mailto (a, b, c) 
            Puts the addresses "a, b, c" in the default To: field. 

  */

  else if (action.Equals("mailto")) {
    // if you prepend mailto: to the string it will be a mailto: url
    // and openurl should work fine.
    nsCString tempArg("mailto:");
    tempArg.Append(argument);
    rv = OpenURL(tempArg, aWindow, PR_FALSE);
  }

  /*
      addBookmark ( ) 
            Adds the current document to the bookmark list. 
      addBookmark (URL) 
            Adds the given document to the bookmark list. 
      addBookmark (URL, Title) 
            Adds the given document to the bookmark list,
	    with the given title. 
  */

  else if (action.Equals("addbookmark")) {
    rv = NS_ERROR_NOT_IMPLEMENTED;
  }

  /* some extensions! */
  
  /*
      ping()
         Just responds with an OK to let a client know that we are here.
  */

  else if (action.Equals("ping")) {
    // the 200 will get filled in below
    rv = NS_OK;
  }

  /*
      xfeDoCommand()
       This is an interface to make the xfe "do stuff."  Lifted from
       the old Netscape 4.x interface.
  */

  else if (action.Equals("xfedocommand")) {
    rv = XfeDoCommand(argument, aWindow);
  }

  // bad command
  else {
    rv = NS_ERROR_FAILURE;
  }

  return rv;
}
Ejemplo n.º 17
0
char* DoubleToChar(double init)
{
	String tempString("");
	double tempInit = init;
	int tempInt;
	bool negative;
	if(init < 0)			// Negativt tal?
		negative = true;
	else
	   negative = false;

	int dot = 0;
	if((init - int(init)) == 0)			// Finns det någon decimal?
		dot = -1;						// Så kan inte for loopen sätta decimalen sen
	else
	{	// Räkna ut var decimalen är
		int i = 0;
		for(; int(tempInit) > 0 && i < 100; i++)
			tempInit /= 10;

		dot = i;

	
		// Gör om talet till int liknande
		do
		{
			tempInt = int(init);	
			tempInit = init - double(tempInt);
			init *= 10;
		} while(tempInit > 0);
	}
	do
	{
		tempInt = int(init)%10;			// Få fram sista siffran
		init -= tempInt;			// Dra bort sista siffran
		init /= 10;					// Ta bort nollan som blir där

		switch (tempInt)
		{
		 case 0: tempString += "0"; break;
		 case 1: tempString += '1'; break;
		 case 2: tempString += '2'; break;
		 case 3: tempString += '3'; break;
		 case 4: tempString += '4'; break;
		 case 5: tempString += '5'; break;
		 case 6: tempString += '6'; break;
		 case 7: tempString += '7'; break;
		 case 8: tempString += '8'; break;
		 case 9: tempString += '9'; break;
		}
	} while(init != 0);

	char* ret;
	if(negative)
	{
		ret = new char[tempString.getLen()+2];
		ret[0] = '-';
		for(int i = 1, j = tempString.getLen()-1; j >= 0; j--, i++)
		{
			if(i-1 == dot)
			{
				ret[i] = '.';
				j++;
			}
			else
				ret[i] = tempString.getChar(j);
		}

		ret[tempString.getLen()+1] = '\0';
	}
	else
	{
 		ret= new char[tempString.getLen()+1];

		for(int i = 0, j = tempString.getLen()-1; j >= 0; j--, i++)
		{
			if(i == dot)
			{
				ret[i] = '.';
				j++;
			}
			else
				ret[i] = tempString.getChar(j);
		}

		ret[tempString.getLen()] = '\0';
	}
	return ret;
}
Ejemplo n.º 18
0
std::vector<std::string> split(const char*& string, char delimeter)
{
    std::string tempString(string);

    return split(tempString, delimeter);
}
Ejemplo n.º 19
0
void ChannelAgent::UpdateMode(char theSign, char theMode)
{
	char modeString[2]; // necessary C-style string
	memset(modeString, 0, sizeof(modeString));
	sprintf(modeString, "%c", theMode);
	BString myTemp;

	if (theSign == '-') {
		switch (theMode) {
		case 'l': {
			myTemp = fChanLimit;
			myTemp.Append(" ");
			fChanMode.RemoveLast(myTemp);
			myTemp = fChanLimit;
			myTemp.Prepend(" ");
			fChanMode.RemoveLast(myTemp);
			fChanMode.RemoveLast(fChanLimit);
		} break;

		case 'k': {
			myTemp = fChanKey;
			myTemp.Append(" ");
			fChanMode.RemoveLast(myTemp);
			myTemp = fChanKey;
			myTemp.Prepend(" ");
			fChanMode.RemoveLast(myTemp);
			fChanMode.RemoveLast(fChanKey);
		} break;
		}

		fChanMode.RemoveFirst(modeString);
	} else {
		BString theReal(GetWord(fChanMode.String(), 1)),
			theRest(RestOfString(fChanMode.String(), 2));
		theReal.RemoveFirst(modeString);
		theReal.Append(modeString);
		BString tempString(theReal);
		if (theRest != "-9z99") {
			tempString += " ";
			tempString += theRest;
		}

		if (theMode == 'l') {
			if (fChanLimitOld != "") {
				BString theOld(" ");
				theOld += fChanLimitOld;
				tempString.RemoveFirst(theOld);
			}

			tempString.Append(" ");
			tempString.Append(fChanLimit);
			fChanLimitOld = fChanLimit;
		} else if (theMode == 'k') {
			if (fChanKeyOld != "") {
				BString theOld(" ");
				theOld += fChanKeyOld;
				tempString.RemoveFirst(theOld);
			}

			tempString.Append(" ");
			tempString.Append(fChanKey);
			fChanKeyOld = fChanKey;
		}

		fChanMode = tempString;
	}

	if (!IsHidden())
		vision_app->pClientWin()->pStatusView()->SetItemValue(STATUS_MODES, fChanMode.String());
}
Ejemplo n.º 20
0
bool rspfApplanixEcefModel::loadState(const rspfKeywordlist& kwl,
                                       const char* prefix)
{
   if(traceDebug())
   {
      std::cout << "rspfApplanixEcefModel::loadState: ......... entered" << std::endl;
   }

   theImageClipRect = rspfDrect(0,0,4076,4091);
   theRefImgPt      = rspfDpt(2046.0, 2038.5);

   rspfSensorModel::loadState(kwl, prefix);
   if(getNumberOfAdjustableParameters() < 1)
   {
      initAdjustableParameters();
   }
   theEcefPlatformPosition    = rspfGpt(0.0,0.0,1000.0);
   theAdjEcefPlatformPosition = rspfGpt(0.0,0.0,1000.0);
   theRoll    = 0.0;
   thePitch   = 0.0;
   theHeading = 0.0;
   // bool computeGsdFlag = false;
   const char* roll              = kwl.find(prefix, "roll");
   const char* pitch             = kwl.find(prefix, "pitch");
   const char* heading           = kwl.find(prefix, "heading");
   const char* principal_point   = kwl.find(prefix, "principal_point");
   const char* pixel_size        = kwl.find(prefix, "pixel_size");
   const char* focal_length      = kwl.find(prefix, "focal_length");
   const char* ecef_platform_position = kwl.find(prefix, "ecef_platform_position");
   const char* latlonh_platform_position = kwl.find(prefix, "latlonh_platform_position");
   const char* compute_gsd_flag  = kwl.find(prefix, "compute_gsd_flag");
   const char* eo_file           = kwl.find(prefix, "eo_file");
   const char* camera_file       = kwl.find(prefix, "camera_file");
   const char* eo_id             = kwl.find(prefix, "eo_id");
   bool result = true;
   if(eo_id)
   {
      theImageID = eo_id;
   }
   if(eo_file)
   {
      rspfApplanixEOFile eoFile;
      if(eoFile.parseFile(rspfFilename(eo_file)))
      {
         rspfRefPtr<rspfApplanixEORecord> record = eoFile.getRecordGivenId(theImageID);
         if(record.valid())
         {
            rspf_int32 rollIdx    = eoFile.getFieldIdx("ROLL");
            rspf_int32 pitchIdx   = eoFile.getFieldIdx("PITCH");
            rspf_int32 headingIdx = eoFile.getFieldIdx("HEADING");
            rspf_int32 xIdx       = eoFile.getFieldIdx("X");
            rspf_int32 yIdx       = eoFile.getFieldIdx("Y");
            rspf_int32 zIdx       = eoFile.getFieldIdx("Z");

            if((rollIdx >= 0)&&
               (pitchIdx >= 0)&&
               (headingIdx >= 0)&&
               (xIdx >= 0)&&
               (yIdx >= 0)&&
               (zIdx >= 0))
            {
               theRoll    = (*record)[rollIdx].toDouble();
               thePitch   = (*record)[pitchIdx].toDouble();
               theHeading = (*record)[headingIdx].toDouble();
               theEcefPlatformPosition = rspfEcefPoint((*record)[xIdx].toDouble(),
                                                        (*record)[yIdx].toDouble(),
                                                        (*record)[zIdx].toDouble());
               theAdjEcefPlatformPosition = theEcefPlatformPosition;
            }
            else
            {
               return false;
            }
         }
         else
         {
            rspfNotify(rspfNotifyLevel_WARN) << "rspfApplanixEcefModel::loadState()  Image id " << theImageID << " not found in eo file " << eo_file << std::endl;
            
            return false;
         }
      }
      else
      {
         return false;
      }
      // computeGsdFlag = true;
   }
   else
   {
      if(roll)
      {
         theRoll = rspfString(roll).toDouble();
      }
      if(pitch)
      {
         thePitch = rspfString(pitch).toDouble();
      }
      if(heading)
      {
         theHeading = rspfString(heading).toDouble();
      }
      if(ecef_platform_position)
      {
         std::vector<rspfString> splitString;
         rspfString tempString(ecef_platform_position);
         tempString.split(splitString, rspfString(" "));
         if(splitString.size() > 2)
         {
            theEcefPlatformPosition  = rspfEcefPoint(splitString[0].toDouble(),
                                                      splitString[1].toDouble(),
                                                      splitString[2].toDouble());
         }
      }
      else if(latlonh_platform_position)
      {
         std::vector<rspfString> splitString;
         rspfString tempString(latlonh_platform_position);
         tempString.split(splitString, rspfString(" "));
         std::string datumString;
         double lat=0.0, lon=0.0, h=0.0;
         if(splitString.size() > 2)
         {
            lat = splitString[0].toDouble();
            lon = splitString[1].toDouble();
            h = splitString[2].toDouble();
         }
         
         theEcefPlatformPosition = rspfGpt(lat,lon,h);
      }
   }

   if(camera_file)
   {
      rspfKeywordlist cameraKwl;
      rspfKeywordlist lensKwl;
      cameraKwl.add(camera_file);
      const char* sensor = cameraKwl.find("sensor");
      const char* image_size      = cameraKwl.find(prefix, "image_size");
      principal_point = cameraKwl.find("principal_point");
      focal_length    = cameraKwl.find("focal_length");
      pixel_size      = cameraKwl.find(prefix, "pixel_size");
      focal_length    = cameraKwl.find(prefix, "focal_length");
      const char* distortion_units = cameraKwl.find(prefix, "distortion_units");
      rspfUnitConversionTool tool;
      rspfUnitType unitType = RSPF_MILLIMETERS;

      if(distortion_units)
      {
         unitType = (rspfUnitType)rspfUnitTypeLut::instance()->getEntryNumber(distortion_units);

         if(unitType == RSPF_UNIT_UNKNOWN)
         {
            unitType = RSPF_MILLIMETERS;
         }
      }
      if(image_size)
      {
         std::vector<rspfString> splitString;
         rspfString tempString(image_size);
         tempString.split(splitString, rspfString(" "));
         double w=1, h=1;
         if(splitString.size() == 2)
         {
            w = splitString[0].toDouble();
            h = splitString[1].toDouble();
         }
         theImageClipRect = rspfDrect(0,0,w-1,h-1);
         theRefImgPt      = rspfDpt(w/2.0, h/2.0);
      }
      if(sensor)
      {
         theSensorID = sensor;
      }
      if(principal_point)
      {
         std::vector<rspfString> splitString;
         rspfString tempString(principal_point);
         tempString.split(splitString, rspfString(" "));
         if(splitString.size() == 2)
         {
            thePrincipalPoint.x = splitString[0].toDouble();
            thePrincipalPoint.y = splitString[1].toDouble();
         }
      }
      if(pixel_size)
      {
         std::vector<rspfString> splitString;
         rspfString tempString(pixel_size);
         tempString.split(splitString, rspfString(" "));
         if(splitString.size() == 1)
         {
            thePixelSize.x = splitString[0].toDouble();
            thePixelSize.y = thePixelSize.x;
         }
         else if(splitString.size() == 2)
         {
            thePixelSize.x = splitString[0].toDouble();
            thePixelSize.y = splitString[1].toDouble();
         }
      }
      if(focal_length)
      {
         theFocalLength = rspfString(focal_length).toDouble();
      }

      cameraKwl.trimAllValues();
      
      
      rspfString regExpression =  rspfString("^(") + "d[0-9]+)";
      vector<rspfString> keys;
      cameraKwl.getSubstringKeyList( keys, regExpression );
      long numberOfDistortions = (long)keys.size();
      int offset = (int)rspfString("d").size();
      rspf_uint32 idx = 0;
      std::vector<int> numberList(numberOfDistortions);
      for(idx = 0; idx < (int)numberList.size();++idx)
      {
         rspfString numberStr(keys[idx].begin() + offset,
                               keys[idx].end());
         numberList[idx] = numberStr.toInt();
      }
      std::sort(numberList.begin(), numberList.end());
      double distance=0.0, distortion=0.0;

      for(idx = 0; idx < numberList.size(); ++idx)
      {
         rspfString value = cameraKwl.find(rspfString("d")+rspfString::toString(numberList[idx]));

         if(!value.empty())
         {
            std::istringstream inStr(value.c_str());
            inStr >> distance;
            rspf::skipws(inStr);
            inStr >> distortion;
#if 0
            std::vector<rspfString> splitString;
            rspfString tempString(value);
            tempString = tempString.trim();
            tempString.split(splitString, " ");
            std::cout << splitString.size() << std::endl;
            if(splitString.size() >= 2)
            {
               distance = splitString[0].toDouble();
               distortion = splitString[1].toDouble();
            }
#endif
            
            tool.setValue(distortion, unitType);
            lensKwl.add(rspfString("distance") + rspfString::toString(idx),
                        distance,
                        true);
            lensKwl.add(rspfString("distortion") + rspfString::toString(idx),
                        tool.getMillimeters(),
                        true);
         }
         lensKwl.add("convergence_threshold",
                     .00001,
                     true);
         if(pixel_size)
         {
            lensKwl.add("dxdy",
                        rspfString(pixel_size) + " " + rspfString(pixel_size),
                        true);
         }
         else
         {
            lensKwl.add("dxdy",
                        ".009 .009",
                        true);
         }
      }
      if(theLensDistortion.valid())
      {
         theLensDistortion->loadState(lensKwl,"");
      }
   }
Ejemplo n.º 21
0
void mitk::ClaronTrackingDevice::TrackTools()
{
  try
  {
    /* lock the TrackingFinishedMutex to signal that the execution rights are now transfered to the tracking thread */
    MutexLockHolder trackingFinishedLockHolder(*m_TrackingFinishedMutex); // keep lock until end of scope

    bool localStopTracking;       // Because m_StopTracking is used by two threads, access has to be guarded by a mutex. To minimize thread locking, a local copy is used here
    this->m_StopTrackingMutex->Lock();  // update the local copy of m_StopTracking
    localStopTracking = this->m_StopTracking;
    this->m_StopTrackingMutex->Unlock();

    while ((this->GetState() == Tracking) && (localStopTracking == false))
    {
      this->GetDevice()->GrabFrame();

      std::vector<mitk::ClaronTool::Pointer> detectedTools = this->DetectTools();
      std::vector<mitk::ClaronTool::Pointer> allTools = this->GetAllTools();
      std::vector<mitk::ClaronTool::Pointer>::iterator itAllTools;
      for(itAllTools = allTools.begin(); itAllTools != allTools.end(); itAllTools++)
      {
        mitk::ClaronTool::Pointer currentTool = *itAllTools;
        //test if current tool was detected
        std::vector<mitk::ClaronTool::Pointer>::iterator itDetectedTools;
        bool foundTool = false;
        for(itDetectedTools = detectedTools.begin(); itDetectedTools != detectedTools.end(); itDetectedTools++)
        {
          mitk::ClaronTool::Pointer aktuDet = *itDetectedTools;
          std::string tempString(currentTool->GetCalibrationName());
          if (tempString.compare(aktuDet->GetCalibrationName())==0)
          {
            currentTool->SetToolHandle(aktuDet->GetToolHandle());
            foundTool = true;
          }
        }
        if (!foundTool)
        {
          currentTool->SetToolHandle(0);
        }

        if (currentTool->GetToolHandle() != 0)
        {
          currentTool->SetDataValid(true);
          //get tip position of tool:
          std::vector<double> pos_vector = this->GetDevice()->GetTipPosition(currentTool->GetToolHandle());
          //write tip position into tool:
          mitk::Point3D pos;
          pos[0] = pos_vector[0];
          pos[1] = pos_vector[1];
          pos[2] = pos_vector[2];
          currentTool->SetPosition(pos);
          //get tip quaternion of tool
          std::vector<double> quat = this->GetDevice()->GetTipQuaternions(currentTool->GetToolHandle());
          //write tip quaternion into tool
          mitk::Quaternion orientation(quat[1], quat[2], quat[3], quat[0]);
          currentTool->SetOrientation(orientation);
        }
        else
        {
          mitk::Point3D origin;
          origin.Fill(0);
          currentTool->SetPosition(origin);
          currentTool->SetOrientation(mitk::Quaternion(0,0,0,0));
          currentTool->SetDataValid(false);
        }
      }
      /* Update the local copy of m_StopTracking */
      this->m_StopTrackingMutex->Lock();
      localStopTracking = m_StopTracking;
      this->m_StopTrackingMutex->Unlock();
    }
  }
  catch(...)
  {
    this->StopTracking();
    this->SetErrorMessage("Error while trying to track tools. Thread stopped.");
  }
}
bool ossimSpectraboticsRedEdgeModel::loadState(const ossimKeywordlist& kwl,
                                       const char* prefix)
{
   if(traceDebug())
   {
      std::cout << "ossimSpectraboticsRedEdgeModel::loadState: ......... entered" << std::endl;
   }
   //ossimSensorModel::loadState(kwl,prefix);

   ossimSensorModel::loadState(kwl, prefix);
   if(getNumberOfAdjustableParameters() < 1)
   {

      initAdjustableParameters();
   }
   m_ecefPlatformPosition    = ossimGpt(0.0,0.0,1000.0);
   m_adjEcefPlatformPosition = ossimGpt(0.0,0.0,1000.0);
   m_roll    = 0.0;
   m_pitch   = 0.0;
   m_heading = 0.0;


   // bool computeGsdFlag = false;
   const char* roll              = kwl.find(prefix, "Roll");
   const char* pitch             = kwl.find(prefix, "Pitch");
   const char* heading           = kwl.find(prefix, "Yaw");
   const char* focalLength       = kwl.find(prefix, "Focal Length");
   const char* imageWidth        = kwl.find(prefix, "Image Width");
   const char* imageHeight       = kwl.find(prefix, "Image Height");
   const char* fov               = kwl.find(prefix, "Field Of View");
   const char* gpsPos            = kwl.find(prefix, "GPS Position");
   const char* gpsAlt            = kwl.find(prefix, "GPS Altitude");
   const char* imageCenter       = kwl.find(prefix, "Image Center");
   const char* fx                = kwl.find(prefix, "fx");
   const char* fy                = kwl.find(prefix, "fy");
   const char* cx                = kwl.find(prefix, "cx");
   const char* cy                = kwl.find(prefix, "cy");
   const char* k                 = kwl.find(prefix, "k");
   const char* p                 = kwl.find(prefix, "p");

   bool result = true;

#if 0
   std::cout << "roll: " << roll << "\n";
   std::cout << "pitch: " << pitch << "\n";
   std::cout << "heading: " << heading << "\n";
   std::cout << "focalLength: " << focalLength << "\n";
   std::cout << "imageWidth: " << imageWidth << "\n";
   std::cout << "imageHeight: " << imageHeight << "\n";
  // std::cout << "fov: " << fov << "\n";
   std::cout << "gpsPos: " << gpsPos << "\n";
   std::cout << "gpsAlt: " << gpsAlt << "\n";
   #endif
   //
  if(k&&p)
  {
    m_lensDistortion = new ossimTangentialRadialLensDistortion();
    m_lensDistortion->loadState(kwl, prefix);
  }

   if(roll&&
      pitch&&
      heading&&
      focalLength&&
      imageWidth&&
      imageHeight&&
      gpsPos&&
      gpsAlt)
   {
      theSensorID = "MicaSense RedEdge";
      m_roll = ossimString(roll).toDouble();
      m_pitch = ossimString(pitch).toDouble();
      m_heading = ossimString(heading).toDouble();
      m_focalLength = ossimString(focalLength).toDouble();
      m_fov = fov?ossimString(fov).toDouble():48.8;
      theImageSize.x = ossimString(imageWidth).toDouble();
      theImageSize.y = ossimString(imageHeight).toDouble();


      theImageClipRect = ossimDrect(0,0,theImageSize.x-1,theImageSize.y-1);
      theRefImgPt      = ossimDpt(theImageSize.x/2.0, theImageSize.y/2.0);
     
     m_calibratedCenter = theImageClipRect.midPoint();
      // now lets use the field of view and the focal length to 
      // calculate the pixel size on the ccd in millimeters
      double d = tan((m_fov*0.5)*M_PI/180.0)*m_focalLength;
      d*=2.0;
      double tempRadiusPixel = theImageSize.length();
      m_pixelSize.x = (d)/tempRadiusPixel;
      m_pixelSize.y = m_pixelSize.x;
      if(imageCenter)
      {
         std::vector<ossimString> splitString;
         ossimString tempString(imageCenter);
         tempString.split(splitString, ossimString(" "));
         if(splitString.size() == 2)
         {
            theRefImgPt = ossimDpt(splitString[0].toDouble(), splitString[1].toDouble());
         }
      }
      else
      {
         if(traceDebug())
         {
            ossimNotify(ossimNotifyLevel_DEBUG) << "No Image Center found" << std::endl;
        //    result = false;
         }
      }

      // now extract the GPS position and shift it to the ellipsoidal height.
      std::vector<ossimString> splitArray;

      ossimString(gpsPos).split(splitArray, ",");
      splitArray[0] = splitArray[0].replaceAllThatMatch("deg", " ");
      splitArray[1] = splitArray[1].replaceAllThatMatch("deg", " ");

      ossimDms dmsLat;
      ossimDms dmsLon;
      double h = ossimString(gpsAlt).toDouble();
      dmsLat.setDegrees(splitArray[0]);
      dmsLon.setDegrees(splitArray[1]);
      double lat = dmsLat.getDegrees();
      double lon = dmsLon.getDegrees();

      h = h+ossimGeoidManager::instance()->offsetFromEllipsoid(ossimGpt(lat,lon));
      m_ecefPlatformPosition = ossimGpt(lat,lon,h);
      // double height1 = ossimElevManager::instance()->getHeightAboveEllipsoid(ossimGpt(lat, lon));
     
//std::cout << "PLATFORM HEIGHT: " << h << "\n" 
//          << "ELEVATION: " << height1 << "\n";
     // std::cout << m_ecefPlatformPosition << std::endl;
     // std::cout << "POINT: " << ossimGpt(lat,lon,h) << std::endl;
     // std::cout << "MSL:   " << height1 << "\n";

      theRefGndPt = m_ecefPlatformPosition;
      theRefGndPt.height(0.0);

     m_norm = ossim::nan();

    // lens parameters
    if(m_lensDistortion.valid()&&cx&&cy&&fx&&fy)
    {
      m_focalX = ossimString(fx).toDouble();
      m_focalY = ossimString(fy).toDouble();

      // our lens distorion assume center point.  So
      // lets shift to center and then set calibrated relative to 
      // image center.  We will then normalize.
      //
      ossimDpt focal(m_focalX,m_focalY);
      m_norm = focal.length()*0.5; // convert from diameter to radial
      m_calibratedCenter = ossimDpt(ossimString(cx).toDouble(), ossimString(cy).toDouble());
      m_principalPoint = m_calibratedCenter-theImageClipRect.midPoint();
      m_principalPoint.x /= m_norm;
      m_principalPoint.y /= m_norm;

      // lets initialize the root to be about one pixel norm along the diagonal
      // and the convergence will be approximately 100th of a pixel.
      //
      double temp = m_norm;
      if(temp < FLT_EPSILON) temp = 1.0;
      else temp = 1.0/temp;
      m_lensDistortion->setCenter(m_principalPoint);
      m_lensDistortion->setDxDy(ossimDpt(temp,temp));
      m_lensDistortion->setConvergenceThreshold(temp*0.001);
    }
    else
    {
      m_lensDistortion = 0;
      m_calibratedCenter = theImageClipRect.midPoint();
      m_norm = theImageSize.length()*0.5;
      m_principalPoint = ossimDpt(0,0);
    }
     updateModel();
   }
   else // load from regular save state
   {
      const char* principal_point   = kwl.find(prefix, "principal_point");
      const char* pixel_size        = kwl.find(prefix, "pixel_size");
      const char* ecef_platform_position = kwl.find(prefix, "ecef_platform_position");
      const char* latlonh_platform_position = kwl.find(prefix, "latlonh_platform_position");
      // const char* compute_gsd_flag  = kwl.find(prefix, "compute_gsd_flag");
      roll              = kwl.find(prefix, "roll");
      pitch             = kwl.find(prefix, "pitch");
      heading           = kwl.find(prefix, "heading");
      fov               = kwl.find(prefix, "field_of_view");
      focalLength       = kwl.find(prefix, "focal_length");

      if(roll)
      {
         m_roll = ossimString(roll).toDouble();
      }
      if(pitch)
      {
         m_pitch = ossimString(pitch).toDouble();
      }
      if(heading)
      {
         m_heading = ossimString(heading).toDouble();
      }

      if(cx&&cy)
      {
         m_calibratedCenter = ossimDpt(ossimString(cx).toDouble(), ossimString(cy).toDouble());
      }
      if(principal_point)
      {
         std::vector<ossimString> splitString;
         ossimString tempString(principal_point);
         tempString.split(splitString, ossimString(" "));
         if(splitString.size() == 2)
         {
            m_principalPoint.x = splitString[0].toDouble();
            m_principalPoint.y = splitString[1].toDouble();
         }
      }
      else
      {
         if(traceDebug())
         {
            ossimNotify(ossimNotifyLevel_DEBUG) << "No principal_point found" << std::endl;
           // result = false;
         }
      }

      if(pixel_size)
      {
         std::vector<ossimString> splitString;
         ossimString tempString(pixel_size);
         tempString.split(splitString, ossimString(" "));
         if(splitString.size() == 1)
         {
            m_pixelSize.x = splitString[0].toDouble();
            m_pixelSize.y = m_pixelSize.x;
         }
         else if(splitString.size() == 2)
         {
            m_pixelSize.x = splitString[0].toDouble();
            m_pixelSize.y = splitString[1].toDouble();
         }
      }
      else
      {
         if(traceDebug())
         {
            ossimNotify(ossimNotifyLevel_DEBUG) << "No pixel size found" << std::endl;
           // result = false;
         }
      }
      if(ecef_platform_position)
      {
         std::vector<ossimString> splitString;
         ossimString tempString(ecef_platform_position);
         tempString.split(splitString, ossimString(" "));
         if(splitString.size() > 2)
         {
            m_ecefPlatformPosition  = ossimEcefPoint(splitString[0].toDouble(),
                                                      splitString[1].toDouble(),
                                                      splitString[2].toDouble());
         }
      }
      else if(latlonh_platform_position)
      {
         std::vector<ossimString> splitString;
         ossimString tempString(latlonh_platform_position);
         tempString.split(splitString, ossimString(" "));
         std::string datumString;
         double lat=0.0, lon=0.0, h=0.0;
         if(splitString.size() > 2)
         {
            lat = splitString[0].toDouble();
            lon = splitString[1].toDouble();
            h = splitString[2].toDouble();
         }
         
         m_ecefPlatformPosition = ossimGpt(lat,lon,h);
      }
      if(focalLength)
      {
         m_focalLength = ossimString(focalLength).toDouble();
      }
      else
      {
         if(traceDebug())
         {
            ossimNotify(ossimNotifyLevel_DEBUG) << "No focal length found" << std::endl;
            result = false;
         }
      }
      if(fov)
      {
         m_fov = ossimString(fov).toDouble();
      }
      else
      {
         if(traceDebug())
         {
            ossimNotify(ossimNotifyLevel_DEBUG) << "No field of view found" << std::endl;
            result = false;
         }
      }
      theRefGndPt = m_ecefPlatformPosition;
    if(m_lensDistortion.valid()&&cx&&cy&&fx&&fy)
    {
      m_focalX = ossimString(fx).toDouble();
      m_focalY = ossimString(fy).toDouble();

      // our lens distorion assume center point.  So
      // lets shift to center and then set calibrated relative to 
      // image center.  We will then normalize.
      //
      ossimDpt focal(m_focalX,m_focalY);
      m_norm = focal.length()*0.5;
      m_calibratedCenter = ossimDpt(ossimString(cx).toDouble(), ossimString(cy).toDouble());
     // m_principalPoint = m_calibratedCenter-theImageClipRect.midPoint();
     // m_principalPoint.x /= m_norm;
     // m_principalPoint.y /= m_norm;

      // lets initialize the root to be about one pixel norm along the diagonal
      // and the convergence will be approximately 100th of a pixel.
      //
      double temp = m_norm;
      if(temp < FLT_EPSILON) temp = 1.0;
      else temp = 1.0/temp;
      m_lensDistortion->setCenter(m_principalPoint);
      m_lensDistortion->setDxDy(ossimDpt(temp,temp));
      m_lensDistortion->setConvergenceThreshold(temp*0.001);
    }
    else
    {
      m_lensDistortion = 0;
    }
      updateModel();
   }
    try
    {
       //---
       // This will set theGSD and theMeanGSD. Method throws
       // ossimException.
       //---
       computeGsd();
    }
    catch (const ossimException& e)
    {
       ossimNotify(ossimNotifyLevel_WARN)
          << "ossimSpectraboticsRedEdgeModel::loadState Caught Exception:\n"
          << e.what() << std::endl;
    }
   // std::cout << "METERS PER PIXEL :    " << getMetersPerPixel() << std::endl;
   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << std::setprecision(15) << std::endl;
      ossimNotify(ossimNotifyLevel_DEBUG) << "roll:     " << m_roll << std::endl
                                          << "pitch:    " << m_pitch << std::endl
                                          << "heading:  " << m_heading << std::endl
                                          << "platform: " << m_ecefPlatformPosition << std::endl
                                          << "latlon Platform: " << ossimGpt(m_ecefPlatformPosition) << std::endl
                                          << "focal len: " << m_focalLength << std::endl
                                          << "FOV      : " << m_fov << std::endl
                                          << "principal: " << m_principalPoint << std::endl
                                          << "Ground:    " << ossimGpt(m_ecefPlatformPosition) << std::endl;
   }

   // ossimGpt wpt;
   // ossimDpt dpt(100,100);
   // lineSampleToWorld(dpt, wpt);
   // std::cout << "dpt: " << dpt << "\n"
   //           << "wpt: " << wpt << "\n";
   // worldToLineSample(wpt,dpt);
   // std::cout << "dpt: " << dpt << "\n"
   //           << "wpt: " << wpt << "\n";
   return result;
}
Ejemplo n.º 23
0
bool ossimApplanixUtmModel::loadState(const ossimKeywordlist& kwl,
                                   const char* prefix)
{
   if(traceDebug())
   {
      std::cout << "ossimApplanixUtmModel::loadState: ......... entered" << std::endl;
   }
   theImageClipRect = ossimDrect(0,0,4076,4091);
   theRefImgPt      = ossimDpt(2046.0, 2038.5);
   
   ossimSensorModel::loadState(kwl, prefix);

   if(getNumberOfAdjustableParameters() < 1)
   {
      initAdjustableParameters();
   }

   const char* eo_file           = kwl.find(prefix, "eo_file");
   const char* eo_id             = kwl.find(prefix, "eo_id");
   const char* omega             = kwl.find(prefix, "omega");
   const char* phi               = kwl.find(prefix, "phi");
   const char* kappa             = kwl.find(prefix, "kappa");
   const char* bore_sight_tx     = kwl.find(prefix, "bore_sight_tx");
   const char* bore_sight_ty     = kwl.find(prefix, "bore_sight_ty");
   const char* bore_sight_tz     = kwl.find(prefix, "bore_sight_tz");
   
   const char* principal_point   = kwl.find(prefix, "principal_point");
   const char* pixel_size        = kwl.find(prefix, "pixel_size");
   const char* focal_length      = kwl.find(prefix, "focal_length");
   const char* latlonh_platform_position = kwl.find(prefix, "latlonh_platform_position");
   const char* utm_platform_position = kwl.find(prefix, "utm_platform_position");
   const char* compute_gsd_flag  = kwl.find(prefix, "compute_gsd_flag");
   const char* utm_zone          = kwl.find(prefix, "utm_zone");
   const char* utm_hemisphere    = kwl.find(prefix, "utm_hemisphere");
   const char* camera_file       = kwl.find(prefix, "camera_file");
   const char* shift_values      = kwl.find(prefix, "shift_values");
   
   theCompositeMatrix          = ossimMatrix3x3::createIdentity();
   theCompositeMatrixInverse   = ossimMatrix3x3::createIdentity();
   theOmega                    = 0.0;
   thePhi                      = 0.0;
   theKappa                    = 0.0;
   theBoreSightTx              = 0.0;
   theBoreSightTy              = 0.0;
   theBoreSightTz              = 0.0;
   theFocalLength              = 55.0;
   thePixelSize = ossimDpt(.009, .009);
   theEcefPlatformPosition = ossimGpt(0.0,0.0, 1000.0);

   bool loadedFromEoFile = false;

   if(eo_id)
   {
      theImageID = eo_id;
   }
   // loading from standard eo file with given record id
   //
   if(eo_file)
   {
      ossimApplanixEOFile eoFile;
      
      if(eoFile.parseFile(ossimFilename(eo_file)))
      {
         ossimRefPtr<ossimApplanixEORecord> record = eoFile.getRecordGivenId(theImageID);

         if(record.valid())
         {
            loadedFromEoFile = true;
            theBoreSightTx = eoFile.getBoreSightTx()/60.0;
            theBoreSightTy = eoFile.getBoreSightTy()/60.0;
            theBoreSightTz = eoFile.getBoreSightTz()/60.0;
            theShiftValues = ossimEcefVector(eoFile.getShiftValuesX(),
                                             eoFile.getShiftValuesY(),
                                             eoFile.getShiftValuesZ());
            ossim_int32 easting  = eoFile.getFieldIdxLike("EASTING");
            ossim_int32 northing = eoFile.getFieldIdxLike("NORTHING");
            ossim_int32 height   = eoFile.getFieldIdxLike("HEIGHT");
            ossim_int32 omega    = eoFile.getFieldIdxLike("OMEGA");
            ossim_int32 phi      = eoFile.getFieldIdxLike("PHI");
            ossim_int32 kappa    = eoFile.getFieldIdxLike("KAPPA");

            if((omega>=0)&&
               (phi>=0)&&
               (kappa>=0)&&
               (height>=0)&&
               (easting>=0)&&
               (northing>=0))
            {
               theOmega = (*record)[omega].toDouble();
               thePhi   = (*record)[phi].toDouble();
               theKappa = (*record)[kappa].toDouble();
               double h = (*record)[height].toDouble();
               ossimString heightType = kwl.find(prefix, "height_type");
               if(eoFile.isUtmFrame())
               {
                  theUtmZone = eoFile.getUtmZone();
                  theUtmHemisphere = eoFile.getUtmHemisphere()=="North"?'N':'S';
                  ossimUtmProjection utmProj;
                  utmProj.setZone(theUtmZone);
                  utmProj.setHemisphere((char)theUtmHemisphere);
                  theUtmPlatformPosition.x = (*record)[easting].toDouble();
                  theUtmPlatformPosition.y = (*record)[northing].toDouble();
                  theUtmPlatformPosition.z = h;
                  thePlatformPosition = utmProj.inverse(ossimDpt(theUtmPlatformPosition.x,
                                                                 theUtmPlatformPosition.y));
                  thePlatformPosition.height(h);

                  if(eoFile.isHeightAboveMSL())
                  {
                     double offset = ossimGeoidManager::instance()->offsetFromEllipsoid(thePlatformPosition);
                     if(!ossim::isnan(offset))
                     {
                        thePlatformPosition.height(h + offset);
                        theUtmPlatformPosition.z = h + offset;
                     }
                  }
               }
               else
               {
                  return false;
               }
            }
            theEcefPlatformPosition = thePlatformPosition;
         }
         else
         {
            return false;
         }
      }
   }
   if(!loadedFromEoFile)
   {
      if(shift_values)
      {
         std::vector<ossimString> splitString;
         ossimString tempString(shift_values);
         tempString = tempString.trim();
         tempString.split(splitString, " " );
         if(splitString.size() == 3)
         {
            theShiftValues = ossimEcefVector(splitString[0].toDouble(),
                                             splitString[1].toDouble(),
                                             splitString[2].toDouble());
         }
      }
      if(omega&&phi&&kappa)
      {
         theOmega = ossimString(omega).toDouble();
         thePhi   = ossimString(phi).toDouble();
         theKappa = ossimString(kappa).toDouble();
      }
      if(bore_sight_tx&&bore_sight_ty&&bore_sight_tz)
      {
         theBoreSightTx = ossimString(bore_sight_tx).toDouble()/60.0;
         theBoreSightTy = ossimString(bore_sight_ty).toDouble()/60.0;
         theBoreSightTz = ossimString(bore_sight_tz).toDouble()/60.0;
      }
      double lat=0.0, lon=0.0, h=0.0;
      if(utm_zone)
      {
         theUtmZone = ossimString(utm_zone).toInt32();
      }
      if(utm_hemisphere)
      {
         ossimString hem = utm_hemisphere;
         hem = hem.trim();
         hem = hem.upcase();
         theUtmHemisphere = *(hem.begin());
      }
      if(utm_platform_position)
      {
         ossimUtmProjection utmProj;
         std::vector<ossimString> splitString;
         ossimString tempString(utm_platform_position);
         tempString = tempString.trim();
         ossimString datumString;
         utmProj.setZone(theUtmZone);
         utmProj.setHemisphere((char)theUtmHemisphere);
         tempString.split(splitString, " ");
         if(splitString.size() > 2)
         {
            theUtmPlatformPosition.x = splitString[0].toDouble();
            theUtmPlatformPosition.y = splitString[1].toDouble();
            theUtmPlatformPosition.z = splitString[2].toDouble();
         }
         if(splitString.size() > 3)
         {
            datumString = splitString[3];
         }
         const ossimDatum* datum = ossimDatumFactory::instance()->create(datumString);
         if(datum)
         {
            utmProj.setDatum(datum);
         }
         
         thePlatformPosition = utmProj.inverse(ossimDpt(theUtmPlatformPosition.x,
                                                        theUtmPlatformPosition.y));
         thePlatformPosition.height(theUtmPlatformPosition.z);
         
         ossimString heightType = kwl.find(prefix, "height_type");
         if(heightType == "msl")
         {
            double offset = ossimGeoidManager::instance()->offsetFromEllipsoid(thePlatformPosition);
            if(ossim::isnan(offset) == false)
            {
               thePlatformPosition.height(thePlatformPosition.height() + offset);
               theUtmPlatformPosition.z = thePlatformPosition.height();
            }
         }
         theEcefPlatformPosition = thePlatformPosition;
      }
      else if(latlonh_platform_position)
      {
         std::vector<ossimString> splitString;
         ossimString tempString(latlonh_platform_position);
         std::string datumString;
         tempString = tempString.trim();
         tempString.split(splitString, " ");
         if(splitString.size() > 2)
         {
            lat = splitString[0].toDouble();
            lon = splitString[1].toDouble();
            h = splitString[2].toDouble();
         }
         if(splitString.size() > 3)
         {
            datumString = splitString[3];
         }
         thePlatformPosition.latd(lat);
         thePlatformPosition.lond(lon);
         thePlatformPosition.height(h);
         const ossimDatum* datum = ossimDatumFactory::instance()->create(datumString);
         if(datum)
         {
            thePlatformPosition.datum(datum);
         }
         ossimString heightType = kwl.find(prefix, "height_type");
         if(heightType == "msl")
         {
            double offset = ossimGeoidManager::instance()->offsetFromEllipsoid(thePlatformPosition);
            if(ossim::isnan(offset) == false)
            {
               thePlatformPosition.height(thePlatformPosition.height() + offset);
            }
         }
         theEcefPlatformPosition = thePlatformPosition;
      }
   }
   if(principal_point)
   {
      std::vector<ossimString> splitString;
      ossimString tempString(principal_point);
      tempString = tempString.trim();
      tempString.split(splitString, " ");
      if(splitString.size() == 2)
      {
         thePrincipalPoint.x = splitString[0].toDouble();
         thePrincipalPoint.y = splitString[1].toDouble();
      }
   }
   if(pixel_size)
   {
      std::vector<ossimString> splitString;
      ossimString tempString(principal_point);
      tempString = tempString.trim();
      tempString.split(splitString, " ");
      if(splitString.size() == 2)
      {
         thePixelSize.x = splitString[0].toDouble();
         thePixelSize.y = splitString[1].toDouble();
      }
   }
   if(focal_length)
   {
      theFocalLength = ossimString(focal_length).toDouble();
   }

   if(camera_file)
   {
      ossimKeywordlist cameraKwl;
      ossimKeywordlist lensKwl;
      cameraKwl.add(camera_file);
      const char* sensor = cameraKwl.find("sensor");
      const char* image_size      = cameraKwl.find(prefix, "image_size");
      principal_point = cameraKwl.find("principal_point");
      focal_length    = cameraKwl.find("focal_length");
      pixel_size      = cameraKwl.find(prefix, "pixel_size");
      focal_length    = cameraKwl.find(prefix, "focal_length");
      const char* distortion_units = cameraKwl.find(prefix, "distortion_units");
      ossimUnitConversionTool tool;
      ossimUnitType unitType = OSSIM_MILLIMETERS;

      if(distortion_units)
      {
         unitType = (ossimUnitType)ossimUnitTypeLut::instance()->getEntryNumber(distortion_units);

         if(unitType == OSSIM_UNIT_UNKNOWN)
         {
            unitType = OSSIM_MILLIMETERS;
         }
      }
      if(image_size)
      {
         std::vector<ossimString> splitString;
         ossimString tempString(image_size);
         tempString = tempString.trim();
         tempString.split(splitString, " ");
         double w=1, h=1;
         if(splitString.size() == 2)
         {
            w = splitString[0].toDouble();
            h = splitString[1].toDouble();
         }
         theImageClipRect = ossimDrect(0,0,w-1,h-1);
         theRefImgPt      = ossimDpt(w/2.0, h/2.0);
      }
      if(sensor)
      {
         theSensorID = sensor;
      }
      if(principal_point)
      {
         std::vector<ossimString> splitString;
         ossimString tempString(principal_point);
         tempString = tempString.trim();
         tempString.split(splitString, " ");
         if(splitString.size() == 2)
         {
            thePrincipalPoint.x = splitString[0].toDouble();
            thePrincipalPoint.y = splitString[1].toDouble();
         }
      }
      if(pixel_size)
      {
         std::vector<ossimString> splitString;
         ossimString tempString(pixel_size);
         tempString = tempString.trim();
         tempString.split(splitString, " ");
         if(splitString.size() == 1)
         {
            thePixelSize.x = splitString[0].toDouble();
            thePixelSize.y = thePixelSize.x;
         }
         else if(splitString.size() == 2)
         {
            thePixelSize.x = splitString[0].toDouble();
            thePixelSize.y = splitString[1].toDouble();
         }
      }
      if(focal_length)
      {
         theFocalLength = ossimString(focal_length).toDouble();
      }

      ossim_uint32 idx = 0;
      for(idx = 0; idx < 26; ++idx)
      {
         const char* value = cameraKwl.find(ossimString("d")+ossimString::toString(idx));

         if(value)
         {
            std::vector<ossimString> splitString;
            ossimString tempString(value);
            double distance=0.0, distortion=0.0;
            tempString = tempString.trim();
            tempString.split(splitString, " ");
            if(splitString.size() == 2)
            {
               distance = splitString[0].toDouble();
               distortion = splitString[1].toDouble();
            }
            
            tool.setValue(distortion, unitType);
            lensKwl.add(ossimString("distance") + ossimString::toString(idx),
                        distance,
                        true);
            lensKwl.add(ossimString("distortion") + ossimString::toString(idx),
                        tool.getMillimeters(),
                        true);
         }
         lensKwl.add("convergence_threshold",
                     .00001,
                     true);
         if(pixel_size)
         {
            lensKwl.add("dxdy",
                        ossimString(pixel_size) + " " + ossimString(pixel_size),
                        true);
         }
         else
         {
            lensKwl.add("dxdy",
                        ".009 .009",
                        true);
         }
      }
      if(theLensDistortion.valid())
      {
         theLensDistortion->loadState(lensKwl,"");
      }
   }
   else
   {
      
      if(principal_point)
      {
         std::vector<ossimString> splitString;
         ossimString tempString(principal_point);
         tempString = tempString.trim();
         tempString.split(splitString, " ");
         if(splitString.size() == 2)
         {
            thePrincipalPoint.x = splitString[0].toDouble();
            thePrincipalPoint.y = splitString[1].toDouble();
         }
      }
      else
      {
         if(traceDebug())
         {
            ossimNotify(ossimNotifyLevel_DEBUG) << "No principal_point found" << std::endl;
            return false;
         }
      }
      if(pixel_size)
      {
         std::vector<ossimString> splitString;
         ossimString tempString(pixel_size);
         tempString = tempString.trim();
         tempString.split(splitString, " ");
         if(splitString.size() == 1)
         {
            thePixelSize.x = splitString[0].toDouble();
            thePixelSize.y = thePixelSize.x;
         }
         else if(splitString.size() == 2)
         {
            thePixelSize.x = splitString[0].toDouble();
            thePixelSize.y = splitString[1].toDouble();
         }
      }
      else
      {
         if(traceDebug())
         {
            ossimNotify(ossimNotifyLevel_DEBUG) << "No pixel size found" << std::endl;
            return false;
         }
      }
      if(focal_length)
      {
         theFocalLength = ossimString(focal_length).toDouble();
      }
      else
      {
         if(traceDebug())
         {
            ossimNotify(ossimNotifyLevel_DEBUG) << "No focal length found" << std::endl;
            return false;
         }
      }
      
      if(theLensDistortion.valid())
      {
         ossimString lensPrefix = ossimString(prefix)+"distortion.";
         theLensDistortion->loadState(kwl,
                                      lensPrefix.c_str());
      }
   }
   theRefGndPt = thePlatformPosition;
   
   updateModel();

   lineSampleToWorld(theRefImgPt, theRefGndPt);
   if(compute_gsd_flag)
   {
      if(ossimString(compute_gsd_flag).toBool())
      {
         ossimGpt right;
         ossimGpt top;
         lineSampleToWorld(theRefImgPt + ossimDpt(1.0, 0.0),
                           right);
         lineSampleToWorld(theRefImgPt + ossimDpt(1.0, 0.0),
                           top);

         ossimEcefVector horizontal = ossimEcefPoint(theRefGndPt)-ossimEcefPoint(right);
         ossimEcefVector vertical   = ossimEcefPoint(theRefGndPt)-ossimEcefPoint(top);

         theGSD.x = horizontal.length();
         theGSD.y = vertical.length();
         theMeanGSD = (theGSD.x+theGSD.y)*.5;
      }
   }
   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << "theOmega:              " << theOmega << std::endl
                                          << "thePhi:                " << thePhi   << std::endl
                                          << "theKappa:              " << theKappa << std::endl;
      std::cout << "platform position:     " << thePlatformPosition << std::endl;
      std::cout << "platform position ECF: " << theEcefPlatformPosition << std::endl;
      std::cout << "ossimApplanixModel::loadState: ......... leaving" << std::endl;
   }

   return true;
}
Ejemplo n.º 24
0
ossimString  ossimString::trim(const ossimString& valueToTrim) const
{
   ossimString tempString(*this);
   
   return tempString.trim(valueToTrim);
}
Ejemplo n.º 25
0
ModelItem ModelItem::fromEditPacket(const unsigned char* data, int length, int& processedBytes, ModelTree* tree, bool& valid) {
    ModelItem newModelItem; // id and _lastUpdated will get set here...
    const unsigned char* dataAt = data;
    processedBytes = 0;

    // the first part of the data is our octcode...
    int octets = numberOfThreeBitSectionsInCode(data);
    int lengthOfOctcode = bytesRequiredForCodeLength(octets);

    // we don't actually do anything with this octcode...
    dataAt += lengthOfOctcode;
    processedBytes += lengthOfOctcode;

    // id
    uint32_t editID;
    memcpy(&editID, dataAt, sizeof(editID));
    dataAt += sizeof(editID);
    processedBytes += sizeof(editID);

    bool isNewModelItem = (editID == NEW_MODEL);

    // special case for handling "new" modelItems
    if (isNewModelItem) {
        // If this is a NEW_MODEL, then we assume that there's an additional uint32_t creatorToken, that
        // we want to send back to the creator as an map to the actual id
        uint32_t creatorTokenID;
        memcpy(&creatorTokenID, dataAt, sizeof(creatorTokenID));
        dataAt += sizeof(creatorTokenID);
        processedBytes += sizeof(creatorTokenID);

        newModelItem.setCreatorTokenID(creatorTokenID);
        newModelItem._newlyCreated = true;
        valid = true;

    } else {
        // look up the existing modelItem
        const ModelItem* existingModelItem = tree->findModelByID(editID, true);

        // copy existing properties before over-writing with new properties
        if (existingModelItem) {
            newModelItem = *existingModelItem;
            valid = true;
        } else {
            // the user attempted to edit a modelItem that doesn't exist
            qDebug() << "user attempted to edit a modelItem that doesn't exist... editID=" << editID;

            // NOTE: even though this is a bad editID, we have to consume the edit details, so that
            // the buffer doesn't get corrupted for further processing...
            valid = false;
        }
        newModelItem._id = editID;
        newModelItem._newlyCreated = false;
    }
    
    // lastEdited
    memcpy(&newModelItem._lastEdited, dataAt, sizeof(newModelItem._lastEdited));
    dataAt += sizeof(newModelItem._lastEdited);
    processedBytes += sizeof(newModelItem._lastEdited);

    // All of the remaining items are optional, and may or may not be included based on their included values in the
    // properties included bits
    uint16_t packetContainsBits = 0;
    if (!isNewModelItem) {
        memcpy(&packetContainsBits, dataAt, sizeof(packetContainsBits));
        dataAt += sizeof(packetContainsBits);
        processedBytes += sizeof(packetContainsBits);
    }


    // radius
    if (isNewModelItem || ((packetContainsBits & MODEL_PACKET_CONTAINS_RADIUS) == MODEL_PACKET_CONTAINS_RADIUS)) {
        memcpy(&newModelItem._radius, dataAt, sizeof(newModelItem._radius));
        dataAt += sizeof(newModelItem._radius);
        processedBytes += sizeof(newModelItem._radius);
    }

    // position
    if (isNewModelItem || ((packetContainsBits & MODEL_PACKET_CONTAINS_POSITION) == MODEL_PACKET_CONTAINS_POSITION)) {
        memcpy(&newModelItem._position, dataAt, sizeof(newModelItem._position));
        dataAt += sizeof(newModelItem._position);
        processedBytes += sizeof(newModelItem._position);
    }

    // color
    if (isNewModelItem || ((packetContainsBits & MODEL_PACKET_CONTAINS_COLOR) == MODEL_PACKET_CONTAINS_COLOR)) {
        memcpy(newModelItem._color, dataAt, sizeof(newModelItem._color));
        dataAt += sizeof(newModelItem._color);
        processedBytes += sizeof(newModelItem._color);
    }

    // shouldDie
    if (isNewModelItem || ((packetContainsBits & MODEL_PACKET_CONTAINS_SHOULDDIE) == MODEL_PACKET_CONTAINS_SHOULDDIE)) {
        memcpy(&newModelItem._shouldDie, dataAt, sizeof(newModelItem._shouldDie));
        dataAt += sizeof(newModelItem._shouldDie);
        processedBytes += sizeof(newModelItem._shouldDie);
    }

    // modelURL
    if (isNewModelItem || ((packetContainsBits & MODEL_PACKET_CONTAINS_MODEL_URL) == MODEL_PACKET_CONTAINS_MODEL_URL)) {
        uint16_t modelURLLength;
        memcpy(&modelURLLength, dataAt, sizeof(modelURLLength));
        dataAt += sizeof(modelURLLength);
        processedBytes += sizeof(modelURLLength);
        QString tempString((const char*)dataAt);
        newModelItem._modelURL = tempString;
        dataAt += modelURLLength;
        processedBytes += modelURLLength;
    }

    // modelRotation
    if (isNewModelItem || ((packetContainsBits & 
                    MODEL_PACKET_CONTAINS_MODEL_ROTATION) == MODEL_PACKET_CONTAINS_MODEL_ROTATION)) {
        int bytes = unpackOrientationQuatFromBytes(dataAt, newModelItem._modelRotation);
        dataAt += bytes;
        processedBytes += bytes;
    }

    // animationURL
    if (isNewModelItem || ((packetContainsBits & MODEL_PACKET_CONTAINS_ANIMATION_URL) == MODEL_PACKET_CONTAINS_ANIMATION_URL)) {
        uint16_t animationURLLength;
        memcpy(&animationURLLength, dataAt, sizeof(animationURLLength));
        dataAt += sizeof(animationURLLength);
        processedBytes += sizeof(animationURLLength);
        QString tempString((const char*)dataAt);
        newModelItem._animationURL = tempString;
        dataAt += animationURLLength;
        processedBytes += animationURLLength;
    }

    // animationIsPlaying
    if (isNewModelItem || ((packetContainsBits & 
                    MODEL_PACKET_CONTAINS_ANIMATION_PLAYING) == MODEL_PACKET_CONTAINS_ANIMATION_PLAYING)) {
                    
        memcpy(&newModelItem._animationIsPlaying, dataAt, sizeof(newModelItem._animationIsPlaying));
        dataAt += sizeof(newModelItem._animationIsPlaying);
        processedBytes += sizeof(newModelItem._animationIsPlaying);
    }

    // animationFrameIndex
    if (isNewModelItem || ((packetContainsBits & 
                    MODEL_PACKET_CONTAINS_ANIMATION_FRAME) == MODEL_PACKET_CONTAINS_ANIMATION_FRAME)) {
                    
        memcpy(&newModelItem._animationFrameIndex, dataAt, sizeof(newModelItem._animationFrameIndex));
        dataAt += sizeof(newModelItem._animationFrameIndex);
        processedBytes += sizeof(newModelItem._animationFrameIndex);
    }

    // animationFPS
    if (isNewModelItem || ((packetContainsBits & 
                    MODEL_PACKET_CONTAINS_ANIMATION_FPS) == MODEL_PACKET_CONTAINS_ANIMATION_FPS)) {
                    
        memcpy(&newModelItem._animationFPS, dataAt, sizeof(newModelItem._animationFPS));
        dataAt += sizeof(newModelItem._animationFPS);
        processedBytes += sizeof(newModelItem._animationFPS);
    }

    const bool wantDebugging = false;
    if (wantDebugging) {
        qDebug("ModelItem::fromEditPacket()...");
        qDebug() << "   ModelItem id in packet:" << editID;
        newModelItem.debugDump();
    }

    return newModelItem;
}
Ejemplo n.º 26
0
Archivo: internal.cpp Proyecto: KDE/kjs
//#ifndef NDEBUG
void printInfo(ExecState *exec, const char *s, JSValue *o, int lineno)
{
    UString vString;
    if (!o) {
        fprintf(stderr, "KJS: %s: (null)", s);
    } else {
        JSValue *v = o;

        unsigned int arrayLength = 0;
        bool hadExcep = exec->hadException();

        UString name;
        switch (v->type()) {
        case UnspecifiedType:
            name = "Unspecified";
            break;
        case UndefinedType:
            name = "Undefined";
            break;
        case NullType:
            name = "Null";
            break;
        case BooleanType:
            name = "Boolean";
            break;
        case StringType:
            name = "String";
            break;
        case NumberType:
            name = "Number";
            break;
        case ObjectType: {
            JSObject *obj = static_cast<JSObject *>(v);
            name = obj->className();
            if (name.isNull()) {
                name = "(unknown class)";
            }

            if (obj->inherits(&ArrayInstance::info)) {
                arrayLength = obj->get(exec, exec->propertyNames().length)->toUInt32(exec);
            }
            vString = "[object " + name + "]"; // krazy:exclude=doublequote_chars
            break;
        }
        case GetterSetterType:
            name = "GetterSetter";
            break;
        }

        // Avoid calling toString on a huge array (e.g. 4 billion elements, in mozilla/js/js1_5/Array/array-001.js)
        if (arrayLength > 100) {
            vString = UString("[ Array with ") + UString::from(arrayLength) + " elements ]";
        } else if (v->type() != ObjectType) { // Don't want to call a user toString function!
            vString = v->toString(exec);
        }
        if (!hadExcep) {
            exec->clearException();
        }

        if (vString.size() > 350) {
            vString = vString.substr(0, 350) + "...";
        }

        // Can't use two UString::ascii() in the same fprintf call
        CString tempString(vString.cstring());

        fprintf(stderr, "KJS: %s: %s : %s (%p)",
                s, tempString.c_str(), name.ascii(), (void *)v);

        if (lineno >= 0) {
            fprintf(stderr, ", line %d\n", lineno);
        } else {
            fprintf(stderr, "\n");
        }
    }
}
Ejemplo n.º 27
0
rspfString  rspfString::trim(const rspfString& valueToTrim) const
{
   rspfString tempString(*this);
   
   return tempString.trim(valueToTrim);
}
Ejemplo n.º 28
0
bool ossimBuckeyeSensor::loadState(const ossimKeywordlist& kwl,
	const char* prefix)
{
	if (traceDebug())  ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::loadState: entering..." << std::endl;

	theImageClipRect = ossimDrect(0,0,8984,6732);
	theRefImgPt      = ossimDpt(4492, 3366);

	ossimSensorModel::loadState(kwl, prefix);
	if(getNumberOfAdjustableParameters() < 1)
	{
		initAdjustableParameters();
	}
	theEcefPlatformPosition    = ossimGpt(0.0,0.0,1000.0);
	theAdjEcefPlatformPosition = ossimGpt(0.0,0.0,1000.0);
	theRoll    = 0.0;
	thePitch   = 0.0;
	theHeading = 0.0;

	ossimString framemeta_gsti = kwl.find(prefix, "framemeta_gsti");
	ossimString framemeta = kwl.find(prefix,"framemeta");
	ossimString frame_number = kwl.find(prefix, "frame_number");
	ossimString pixel_size = kwl.find(prefix, "pixel_size");
	ossimString principal_point = kwl.find(prefix, "principal_point");
	ossimString focal_length = kwl.find(prefix, "focal_length");
	ossimString smac_radial = kwl.find(prefix, "smac_radial");
	ossimString smac_decent = kwl.find(prefix, "smac_decent");
	ossimString roll;
	ossimString pitch;
	ossimString yaw;
	ossimString platform_position;
	ossimFilename file_to_load;

	ossimString FRAME_STRING	= "Frame#";
	ossimString ROLL_STRING		= "Roll(deg)";
	ossimString PITCH_STRING	= "Pitch(deg)";
	ossimString YAW_STRING		= "Yaw(deg)";
	ossimString LAT_STRING		= "Lat(deg)";
	ossimString LON_STRING		= "Lon(deg)";
	ossimString HAE_STRING		= "HAE(m)";

	// Deal with the fact that there are 3 different types of 'FrameMeta' file
	if (framemeta_gsti.empty() && !framemeta.empty() && !frame_number.empty())
	{
		file_to_load.setFile(framemeta);
		YAW_STRING	= "Azimuth(deg)";
	}
	else if (!framemeta_gsti.empty() && framemeta.empty() && !frame_number.empty())
	{
		file_to_load.setFile(framemeta_gsti);
	}

	if (file_to_load.exists() && !frame_number.empty())
	{
		ossimCsvFile csv(" \t"); // we will use tab or spaces as seaparator
		if(csv.open(file_to_load))
		{
			if(csv.readHeader())
			{
				ossimCsvFile::StringListType heads = csv.fieldHeaderList();
				// Try to see if you can find the first header item, if not, then you either have a file that doesn't work in this case, or it's uppercase
				if (std::find(heads.begin(), heads.end(), FRAME_STRING) == heads.end())
				{
					FRAME_STRING	= FRAME_STRING.upcase();
					ROLL_STRING		= ROLL_STRING.upcase();
					PITCH_STRING	= PITCH_STRING.upcase();
					YAW_STRING		= YAW_STRING.upcase();
					LAT_STRING		= LAT_STRING.upcase();
					LON_STRING		= LON_STRING.upcase();
					HAE_STRING		= HAE_STRING.upcase();
				}

				ossimRefPtr<ossimCsvFile::Record> record;
				bool foundFrameNumber = false;
				while( ((record = csv.nextRecord()).valid()) && !foundFrameNumber)
				{
					if( (*record)[FRAME_STRING] == frame_number)
					{
						foundFrameNumber = true;
						roll = (*record)[ROLL_STRING];
						pitch = (*record)[PITCH_STRING];
						yaw = (*record)[YAW_STRING];
						platform_position = (*record)[LAT_STRING] + " " 
							+ (*record)[LON_STRING]+ " "
							+ (*record)[HAE_STRING] + " WGE";
					}
				}
			}
		}
		csv.close();
	}
	else
	{
		roll = kwl.find(prefix, "roll"); 
		pitch = kwl.find(prefix, "pitch"); 
		yaw = kwl.find(prefix, "heading"); 
		platform_position = kwl.find(prefix, "ecef_platform_position");
	}

	bool result = (!pixel_size.empty()&&
		!principal_point.empty()&&
		!focal_length.empty()&&
		!platform_position.empty());

	if(!focal_length.empty())
	{
		theFocalLength = focal_length.toDouble();
	}
	if(!pixel_size.empty())
	{
		thePixelSize.toPoint(pixel_size);
	}
	if(!roll.empty())
	{
		theRoll = roll.toDouble();
	}
	if(!pitch.empty())
	{
		thePitch = pitch.toDouble();
	}
	if(!yaw.empty())
	{
		theHeading   = yaw.toDouble();
	}
	if(!principal_point.empty())
	{
		thePrincipalPoint.toPoint(principal_point);
	}
	if(platform_position.contains("WGE"))
	{
		std::vector<ossimString> splitString;
		ossimString tempString(platform_position);
		tempString.split(splitString, ossimString(" "));
		std::string datumString;
		double lat=0.0, lon=0.0, h=0.0;
		if(splitString.size() > 2)
		{
			lat = splitString[0].toDouble();
			lon = splitString[1].toDouble();
			h = splitString[2].toDouble();
		}

		theEcefPlatformPosition = ossimGpt(lat,lon,h);
	} else {
		std::vector<ossimString> splitString;
		ossimString tempString(platform_position);
		tempString.split(splitString, ossimString(" "));
		std::string datumString;
		double x=0.0, y=0.0, z=0.0;
		if(splitString.size() > 2)
		{
			x = splitString[0].toDouble();
			y = splitString[1].toDouble();
			z = splitString[2].toDouble();
		}
		theEcefPlatformPosition = ossimEcefPoint(x, y, z);
	}
	theLensDistortion = 0;
	if(!smac_radial.empty()&&
		!smac_decent.empty())
	{
		std::vector<ossimString> radial;
		std::vector<ossimString> decent;
		smac_radial.split(radial, " ");
		smac_decent.split(decent, " ");
		if((radial.size() == 5)&&
			(decent.size() == 4))
		{
			// Just for debugging really.. optomization will make this sleeker
			double k0 = radial[0].toDouble();
			double k1 = radial[1].toDouble();
			double k2 = radial[2].toDouble();
			double k3 = radial[3].toDouble();
			double k4 = radial[4].toDouble();

			double p0 = decent[0].toDouble();
			double p1 = decent[1].toDouble();
			double p2 = decent[2].toDouble();
			double p3 = decent[3].toDouble();

			//theLensDistortion = new ossimSmacCallibrationSystem(radial[0].toDouble(),
			//	radial[1].toDouble(),
			//	radial[2].toDouble(),
			//	radial[3].toDouble(),
			//	radial[4].toDouble(),
			//	decent[0].toDouble(),
			//	decent[1].toDouble(),
			//	decent[2].toDouble(),
			//	decent[3].toDouble());

			theLensDistortion = new ossimSmacCallibrationSystem(k0,k1,k2,k3,k4,p0,p1,p2,p3);
		}
	}
	theImageSize = ossimDpt(theImageClipRect.width(),
		theImageClipRect.height());

	updateModel();

	if(theGSD.isNan())
	{
		try
		{
			// This will set theGSD and theMeanGSD. Method throws ossimException.
			computeGsd();
		}
		catch (const ossimException& e)
		{
			if (traceDebug())
			{
				ossimNotify(ossimNotifyLevel_DEBUG)
					<< "ossimBuckeyeSensor::loadState Caught Exception:\n"
					<< e.what() << std::endl;
			}
		}
	}
	if (traceDebug())  ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimBuckeyeSensor::loadState: returning..." << std::endl;
	return result;
}
Ejemplo n.º 29
0
bool
ServerAgent::ParseENums (const char *data, const char *sWord)
{
	int num (atoi (sWord));

	switch (num)
	{
		case ZERO:								 // 0
			{
				// wasn't a numeric, or the server is playing tricks on us
			}
			return false;

		case ERR_UNKNOWNCOMMAND:	 // 421
			{
				BString tempString (RestOfString (data, 4)),
								badCmd (GetWord (data, 4));

				if (badCmd == "VISION_LAG_CHECK")
				{
					int32 difference (system_time() - fLagCheck);
					if (difference > 0)
					{
						int32 secs (difference / 1000000);
						int32 milli (difference / 1000 - secs * 1000);
						char lag[15] = "";
						sprintf (lag, "%0" B_PRId32 ".%03" B_PRId32, secs, milli);
						fMyLag = lag;
						fLagCount = 0;
						fCheckingLag = false;
						fMsgr.SendMessage (M_LAG_CHANGED);
					}
				}
				else
				{
					tempString.RemoveFirst (":");
					tempString.Append ("\n");
					Display (tempString.String());
				}
			}
			return true;


		case RPL_WELCOME:					// 001
		case RPL_YOURHOST:				 // 002
		case RPL_CREATED:					// 003
		case RPL_MYINFO:					 // 004
			{
				fConnected = true;
				fIsConnecting = false;
				fInitialMotd = true;
				fRetry = 0;

				if (num == RPL_WELCOME)
				{
					BString message = B_TRANSLATE("Established");
					message.Prepend("[@] ").Append("\n");
					Display(message.String(), C_ERROR, C_BACKGROUND, F_SERVER);
				}

				if (fNetworkData.FindBool ("lagCheck"))
				{
					fMyLag = "0.000";
					fMsgr.SendMessage (M_LAG_CHANGED);
				}
				BString theNick (GetWord (data, 3));
				fMyNick = theNick;

				if (!IsHidden())
					vision_app->pClientWin()->pStatusView()->SetItemValue (STATUS_NICK,
						theNick.String());

				BString theMsg (RestOfString (data, 4));
				theMsg.RemoveFirst (":");
				theMsg.Prepend ("* ");
				theMsg.Append ("\n");
				Display (theMsg.String());


				if (num == RPL_MYINFO)
				{
					// set "real" hostname
					fServerHostName = (GetWord (data, 1));
					fServerHostName.RemoveFirst (":");
					BString hostName (fId.String());
					hostName += " - [";
					hostName += fServerHostName.String();
					hostName += "]";
					fAgentWinItem->SetName (hostName.String());

					// detect IRCd
					fIrcdtype = IRCD_STANDARD;

					if (theMsg.FindFirst("hybrid") > 0)
						fIrcdtype = IRCD_HYBRID;
					// ultimate and unreal share the same numerics, so treat them with the same
					// identifier for now
					else if ((theMsg.FindFirst("UltimateIRCd") > 0) || (theMsg.FindFirst("Unreal") > 0))
						fIrcdtype = IRCD_ULTIMATE;
					else if (theMsg.FindFirst("comstud") > 0)
						fIrcdtype = IRCD_COMSTUD;
					else if (theMsg.FindFirst("u2.") > 0)
						fIrcdtype = IRCD_UNDERNET;
					else if (theMsg.FindFirst("PTlink") > 0)
						fIrcdtype = IRCD_PTLINK;
					else if (theMsg.FindFirst ("CR") > 0)
						fIrcdtype = IRCD_CONFERENCEROOM;
					else if (theMsg.FindFirst ("nn-") > 0)
						fIrcdtype = IRCD_NEWNET;
				}
			}
			return true;


		case RPL_PROTOCTL:				 // 005
			{
				// this numeric also serves as RPL_NNMAP on Newnet

				BString theMsg (RestOfString (data, 4));
				theMsg.RemoveFirst (":");
				theMsg.Append ("\n");

				switch (fIrcdtype)
				{
					case IRCD_NEWNET:
						{
							// RPL_NNMAP
							Display (theMsg.String());
						}
						break;

					default:
						{
							// RPL_PROTOCTL
							theMsg.Prepend ("* ");
							Display (theMsg.String());
						}
				}
			}
			return true;



		case RPL_LUSERHIGHESTCONN: // 250
		case RPL_LUSERCLIENT:			// 251
		case RPL_LUSEROP:					// 252
		case RPL_LUSERUNKNOWN:		 // 253
		case RPL_LUSERCHANNELS:		// 254
		case RPL_LUSERME:					// 255
		case RPL_LUSERLOCAL:			 // 265
		case RPL_LUSERGLOBAL:			// 266
			{
				BString theMsg (RestOfString (data, 4));
				theMsg.RemoveFirst (":");
				theMsg.Prepend ("* ");
				theMsg.Append ("\n");
				Display (theMsg.String());
			}
			return true;


		/// strip and send to server agent	///
		case RPL_ULMAP:						 // 006
		case RPL_ULMAPEND:					// 007
		case RPL_U2MAP:						 // 015
		case RPL_U2MAPEND:					// 017
		case RPL_TRACELINK:				 // 200
		case RPL_TRACECONNECTING:	 // 201
		case RPL_TRACEHANDSHAKE:		// 202
		case RPL_TRACEUNKNOWN:			// 203
		case RPL_TRACEOPERATOR:		 // 204
		case RPL_TRACEUSER:				 // 205
		case RPL_TRACESERVER:			 // 206
		case RPL_TRACENEWTYPE:			// 208
		case RPL_TRACECLASS:				// 209
		case RPL_STATSLINKINFO:		 // 211
		case RPL_STATSCOMMANDS:		 // 212
		case RPL_STATSCLINE:				// 213
		case RPL_STATSNLINE:				// 214
		case RPL_STATSILINE:				// 215
		case RPL_STATSKLINE:				// 216
		case RPL_STATSQLINE:				// 217
		case RPL_STATSYLINE:				// 218
		case RPL_ENDOFSTATS:				// 219
		case RPL_STATSBLINE:				// 220
		case RPL_DALSTATSE:				 // 223
		case RPL_DALSTATSF:				 // 224
		case RPL_DALSTATSZ:				 // 225
		case RPL_DALSTATSN:				 // 226
		case RPL_DALSTATSG:				 // 227
		case RPL_STATSLLINE:				// 241
		case RPL_STATSUPTIME:			 // 242
		case RPL_STATSOLINE:				// 243
		case RPL_STATSHLINE:				// 244
		case RPL_STATSSLINE:				// 245
		case RPL_DALSTATSX:				 // 246
		case RPL_STATSXLINE:				// 247
		case RPL_STATSPLINE:				// 249
		case RPL_ADMINME:					 // 256
		case RPL_ADMINLOC1:				 // 257
		case RPL_ADMINLOC2:				 // 258
		case RPL_ADMINEMAIL:				// 259
		case RPL_TRACELOG:					// 261
		case RPL_ENDOFTRACE:				// 262
		case RPL_SILELIST:					// 271
		case RPL_ENDOFSILELIST:		 // 272
		case RPL_ENDOFWHO:					// 315
		case RPL_CHANSERVURL:			 // 328
		case RPL_COMMANDSYNTAX:		 // 334
		case RPL_VERSION:					 // 351
		case RPL_WHOREPLY:					// 352
		case RPL_BANLIST:					 // 367
		case RPL_ENDOFBANLIST:			// 368
		case RPL_INFO:							// 371
		case RPL_ENDOFINFO:				 // 374
		case RPL_YOUREOPER:				 // 381
		case RPL_REHASHING:				 // 382
		case RPL_TIME:							// 391
		case ERR_NOORIGIN:					// 409
		case ERR_NOTEXTTOSEND:			// 412
		case ERR_TOOMANYAWAY:			 // 429
		case ERR_NICKCHANGETOOFAST: // 438
		case ERR_TARGETCHANGETOOFAST: // 439
		case ERR_SUMMONDISABLED:		// 445
		case ERR_USERSDISABLED:		 // 446
		case ERR_NOTREGISTERED:		 // 451
		case ERR_NEEDMOREPARMS:		 // 461
		case ERR_PASSWDMISMATCH:		// 464
		case ERR_YOUREBANNEDCREEP:	// 465
		case ERR_NOPRIVILEGES:			// 481
		case ERR_NOOPERHOST:				// 491
		case ERR_USERSDONTMATCH:		// 502
		case ERR_SILELISTFULL:			// 511
		case ERR_TOOMANYWATCH:			// 512
		case ERR_TOOMANYDCC:				// 514
		case ERR_CANTINVITE:				// 518
		case ERR_LISTSYNTAX:				// 521
		case ERR_WHOSYNTAX:				 // 522
		case ERR_WHOLIMEXCEED:			// 523
		case RPL_LOGON:						 // 600
		case RPL_LOGOFF:						// 601
		case RPL_WATCHOFF:					// 602
		case RPL_WATCHSTAT:				 // 603
		case RPL_NOWON:						 // 604
		case RPL_NOWOFF:						// 605
		case RPL_WATCHLIST:				 // 606
		case RPL_ENDOFWATCHLIST:		// 607
		case RPL_DCCALLOWLIST:			// 618
		case RPL_DCCALLOWEND:			 // 619
		case RPL_DCCALLOW:					// 620
			{
				BString tempString (RestOfString (data, 4));
				tempString.RemoveFirst (":");
				tempString.Append ("\n");
				Display (tempString.String());
			}
			return true;

		case RPL_UMODEIS:					 // 221
			{
				BString theMode (GetWord (data, 4));

				BString tempString = B_TRANSLATE("Your current mode is %1");
				tempString.ReplaceFirst("%1", theMode);
				tempString += '\n';

				BMessage msg (M_DISPLAY);
				PackDisplay (&msg, tempString.String(), C_WHOIS);
				PostActive (&msg);
			}
			return true;

		/// strip and send to active agent	///
		case RPL_TRYAGAIN:					// 263
		case RPL_UNAWAY:						// 305
		case RPL_NOWAWAY:					 // 306
		case ERR_NOSUCHNICK:				// 401
		case ERR_NOSUCHSERVER:			// 402
		case ERR_NOSUCHCHANNEL:		 // 403
		case ERR_CANNOTSENDTOCHAN:	// 404
		case ERR_TOOMANYCHANNELS:	 // 405
		case ERR_WASNOSUCHNICK:		 // 406
		case ERR_TOOMANYTARGETS:		// 407
		case ERR_NOCOLORSONCHAN:		// 408
		case ERR_YOUCANTDOTHAT:		 // 460
		case ERR_CHANOPRIVSNEEDED:	// 482
			{
				BString tempString ("[x] ");
				if (num == ERR_CHANOPRIVSNEEDED)
					tempString += RestOfString (data, 5);
				else
					tempString += RestOfString (data, 4);
				tempString.RemoveFirst (":");
				tempString.Append ("\n");

				BMessage msg (M_DISPLAY);
				PackDisplay (&msg, tempString.String(), C_WHOIS, C_BACKGROUND, F_SERVER);
				PostActive (&msg);
			}
			return true;

		case RPL_AWAY:						 // 301
			{
				BString theNick (GetWord(data, 4));
				BString tempString ("[x] "),
							theReason (RestOfString(data, 5));
				theReason.RemoveFirst(":");
				tempString += "Away: ";
				tempString += theReason;
				tempString += '\n';

				if (fRemoteAwayMessages.find(theNick) != fRemoteAwayMessages.end())
				{
					if (fRemoteAwayMessages[theNick] == theReason)
					{
						return true;
					}
				}
				fRemoteAwayMessages[theNick] = theReason;
				BMessage msg (M_DISPLAY);
				PackDisplay (&msg, tempString.String(), C_WHOIS, C_BACKGROUND, F_SERVER);
				PostActive (&msg);
			}
			return true;

		case RPL_USERHOST:				// 302
			{
				BString theHost (GetWord (data, 4)),
								theHostname (GetAddress (theHost.String()));
				theHost.RemoveFirst (":");

				BString tempString (RestOfString (data, 4));
				tempString.RemoveFirst (":");
				tempString.Append ("\n");
				Display (tempString.String());

				if (fGetLocalIP && (tempString.IFindFirst (fMyNick.String()) == 0))
				{
					fGetLocalIP = false;
					struct addrinfo *info;
					struct addrinfo hints;
					memset(&hints, 0, sizeof(addrinfo));
					hints.ai_family = AF_UNSPEC;
					hints.ai_socktype = SOCK_STREAM;
					hints.ai_protocol = IPPROTO_TCP;
					int result = getaddrinfo(theHostname.String(), NULL, &hints, &info);
					if (result == 0)
					{
						char addr_buf[INET6_ADDRSTRLEN];
						getnameinfo(info->ai_addr, info->ai_addrlen, addr_buf, sizeof(addr_buf),
						NULL, 0, NI_NUMERICHOST);
						fLocalip = addr_buf;
						printf("Got address: %s\n", fLocalip.String());
						freeaddrinfo(info);
						return true;
					}
				}
			}
			return true;

		case RPL_ISON:					 // 303
			{
				BString nicks (RestOfString (data, 4));
				BString onlined, offlined;

				nicks.RemoveFirst (":");

				int hasChanged (0);

				BMessage msg (M_NOTIFYLIST_UPDATE);

				for (int32 i = 0; i < fNotifyNicks.CountItems(); i++)
				{
					NotifyListItem *item (((NotifyListItem *)fNotifyNicks.ItemAt(i)));

					int32 nickidx (nicks.IFindFirst(item->Text()));

					// make sure that the nick isn't a partial match.
					if ((nickidx >= 0) &&
						((nicks[nickidx + strlen(item->Text())] == ' ') || (nicks[nickidx + strlen(item->Text())] == '\0')))
					{
						if (item->GetState() != true)
						{
							item->SetState (true);
							hasChanged = 1;

							if (onlined.Length())
								onlined << ", ";
							onlined << item->Text();
#ifdef USE_INFOPOPPER
							if (be_roster->IsRunning(InfoPopperAppSig) == true) {
								entry_ref ref = vision_app->AppRef();
								BMessage infoMsg(InfoPopper::AddMessage);
								infoMsg.AddString("appTitle", S_INFOPOPPER_TITLE);
								infoMsg.AddString("title", fId.String());
								infoMsg.AddInt8("type", (int8)InfoPopper::Information);

								infoMsg.AddInt32("iconType", InfoPopper::Attribute);
								infoMsg.AddRef("iconRef", &ref);

								BString content;
								content << item->Text() << " is online";
								infoMsg.AddString("content", content);

								BMessenger(InfoPopperAppSig).SendMessage(&infoMsg);
							};
#endif

						}
					}
					else
					{
						if (item->GetState() == true)
						{
							item->SetState (false);
							hasChanged = 2;

							if (offlined.Length())
								offlined << ", ";
							offlined << item->Text();
#ifdef USE_INFOPOPPER
							if (be_roster->IsRunning(InfoPopperAppSig) == true) {
				entry_ref ref = vision_app->AppRef();
								BMessage infoMsg(InfoPopper::AddMessage);
								infoMsg.AddString("appTitle", S_INFOPOPPER_TITLE);
								infoMsg.AddString("title", fId.String());
								infoMsg.AddInt8("type", (int8)InfoPopper::Information);

								infoMsg.AddInt32("iconType", InfoPopper::Attribute);
								infoMsg.AddRef("iconRef", &ref);

								BString content;
								content << item->Text() << " is offline";
								infoMsg.AddString("content", content);

								BMessenger(InfoPopperAppSig).SendMessage(&infoMsg);
							};
#endif

						}
					}
#ifdef __HAIKU__
					if (offlined.Length())
					{
						BNotification notification(B_INFORMATION_NOTIFICATION);
						notification.SetGroup(BString("Vision"));
						entry_ref ref = vision_app->AppRef();
						notification.SetOnClickFile(&ref);
						notification.SetTitle(fServerName.String());
						BString content;
						content << offlined;
						if (offlined.FindFirst(' ') > -1)
							content << " are offline";
						else
							content << " is offline";


						notification.SetContent(content);
						notification.Send();
					}
					if (onlined.Length())
					{
						BNotification notification(B_INFORMATION_NOTIFICATION);
						notification.SetGroup(BString("Vision"));
						entry_ref ref = vision_app->AppRef();
						notification.SetOnClickFile(&ref);
						notification.SetTitle(fServerName.String());
						BString content;
						content << onlined;
						if (onlined.FindFirst(' ') > -1)
							content << " are online";
						else
							content << " is online";


						notification.SetContent(content);
						notification.Send();
					}
#endif
				}
				fNotifyNicks.SortItems(SortNotifyItems);
				msg.AddPointer ("list", &fNotifyNicks);
				msg.AddPointer ("source", this);
				msg.AddInt32 ("change", hasChanged);
				Window()->PostMessage (&msg);
			}
			return true;

		case RPL_WHOISIDENTIFIED:	 // 307
			{
				BString theInfo (RestOfString (data, 5));
				theInfo.RemoveFirst (":");

				if (theInfo == "-9z99")
				{
					// USERIP reply? (RPL_U2USERIP)
					BString tempString (RestOfString (data, 4));
					tempString.RemoveFirst (":");
					tempString.Append ("\n");
					Display (tempString.String());
					return true;
				}

				BMessage display (M_DISPLAY);
				BString buffer;

				buffer += "[x] ";
				buffer += theInfo;
				buffer += "\n";
				PackDisplay (&display, buffer.String(), C_WHOIS, C_BACKGROUND, F_SERVER);
				PostActive (&display);
			}
			return true;

		case RPL_WHOISADMIN:					// 308
		case RPL_WHOISSERVICESADMIN:	// 309
		case RPL_WHOISHELPOP:				 // 310
		case RPL_WHOISOPERATOR:			 // 313
		case RPL_WHOISREGNICK:				// 320
		case RPL_WHOISACTUALLY:			 // 338
		case RPL_WHOISMASK:					 // 550
		case RPL_WHOWASIP:						// 612
		case RPL_WHOISUSERMODESALT:	 // 614
		case RPL_WHOISUSERMODES:			// 615
		case RPL_WHOISREALHOSTNAME:	 // 616
			{
				BString theInfo (RestOfString (data, 5));
				theInfo.RemoveFirst (":");

				BMessage display (M_DISPLAY);
				BString buffer;

				buffer += "[x] ";
				buffer += theInfo;
				buffer += "\n";
				PackDisplay (&display, buffer.String(), C_WHOIS, C_BACKGROUND, F_SERVER);
				PostActive (&display);
			}
			return true;

		case RPL_WHOISUSER:				// 311
			{
				BString theNick (GetWord (data, 4)),
								theIdent (GetWord (data, 5)),
								theAddress (GetWord (data, 6)),
								theName (RestOfString (data, 8));
				theName.RemoveFirst (":");

				BMessage display (M_DISPLAY);
				BString buffer;

				buffer += "[x] ";
				buffer += theNick;
				buffer += " (";
				buffer += theIdent;
				buffer += "@";
				buffer += theAddress;
				buffer += ")\n";
				buffer += "[x] ";
				buffer += theName;
				buffer += "\n";

				PackDisplay (&display, buffer.String(), C_WHOIS, C_BACKGROUND, F_SERVER);
				PostActive (&display);
			}
		return true;

		case RPL_WHOISSERVER:	 // 312
			{
				BString theNick (GetWord (data, 4)),
								theServer (GetWord (data, 5)),
								theInfo (RestOfString (data, 6));
				theInfo.RemoveFirst (":");

				BMessage display (M_DISPLAY);
				BString buffer;

				buffer += "[x] Server: ";
				buffer += theServer;
				buffer += " (";
				buffer += theInfo;
				buffer += ")\n";
				PackDisplay (&display, buffer.String(), C_WHOIS, C_BACKGROUND, F_SERVER);
				PostActive (&display);
			}
			return true;

		case RPL_WHOWASUSER:		 // 314
			{
				BString theNick (GetWord (data, 4)),
								theIdent (GetWord (data, 5)),
								theAddress (GetWord (data, 6)),
								theName (RestOfString (data, 8)),
								tempString ("[x] ");
				theName.RemoveFirst (":");
				tempString += B_TRANSLATE("%1 was (%2)");
				tempString.ReplaceFirst("%1", theNick);
				BString nickString = theIdent << "@" << theAddress;
				tempString.ReplaceFirst("%2", nickString.String());
				tempString += "\n";

				BMessage msg (M_DISPLAY);
				PackDisplay (&msg, tempString.String(), C_WHOIS, C_BACKGROUND, F_SERVER);
				PostActive (&msg);
			}
			return true;

		case RPL_WHOISIDLE:			 // 317
			{
				BString theNick (GetWord (data, 4)),
								tempString ("[x] "),
								tempString2 ("[x] "),
								theTime (GetWord (data, 5)),
								signOnTime (GetWord (data, 6));

				int64 idleTime (strtoul(theTime.String(), NULL, 0));
				tempString += B_TRANSLATE("Idle");
				tempString += ": ";
				tempString += DurationString(idleTime * 1000 * 1000);
				tempString += "\n";

				int32 serverTime = strtoul(signOnTime.String(), NULL, 0);
				struct tm ptr;
				time_t st;
				char str[80];
				st = serverTime;
				localtime_r (&st, &ptr);
				strftime (str,80,"%A %b %d %Y %I:%M %p %Z", &ptr);
				BString signOnTimeParsed (str);
				signOnTimeParsed.RemoveAll ("\n");

				tempString2 += B_TRANSLATE("Signon");
				tempString2 += ": ";
				tempString2 += signOnTimeParsed;
				tempString2 += "\n";

				BMessage msg (M_DISPLAY);
				PackDisplay (&msg, tempString.String(), C_WHOIS, C_BACKGROUND, F_SERVER);
				PostActive (&msg);
				PackDisplay (&msg, tempString2.String(), C_WHOIS, C_BACKGROUND, F_SERVER);
				PostActive (&msg);
			}
			return true;

		case RPL_ENDOFWHOIS:	 // 318
		case RPL_ENDOFNAMES:	 // 366
		case RPL_ENDOFWHOWAS:	// 369
			{
				// nothing
			}
			return true;

		case RPL_WHOISCHANNELS:	 // 319
			{
				BString theChannels (RestOfString (data, 5));
				theChannels.RemoveFirst(":");

				BMessage display (M_DISPLAY);
				BString buffer = "[x] ";

				buffer += B_TRANSLATE("Channels");
				buffer += ": ";
				buffer += theChannels;
				buffer += "\n";
				PackDisplay (&display, buffer.String(), C_WHOIS, C_BACKGROUND, F_SERVER);
				PostActive (&display);
			}
			return true;

		case RPL_LISTSTART:			 // 321
			{
				BMessage msg (M_LIST_BEGIN);
				if (fListAgent)
					vision_app->pClientWin()->DispatchMessage(&msg, (BView *)fListAgent);
			}
			return true;

		case RPL_LIST:						// 322
			{
				BMessage msg (M_LIST_EVENT);
				BString channel (GetWord (data, 4)),
								users (GetWord (data, 5)),
								topic (RestOfString (data, 6));
				topic.RemoveFirst (":");

				msg.AddString ("channel", channel.String());
				msg.AddString ("users", users.String());
				msg.AddString ("topic", topic.String());

				if (fListAgent)
					vision_app->pClientWin()->DispatchMessage(&msg, (BView *)fListAgent);
			}
			return true;

		case RPL_LISTEND:				 // 323
			{
				BMessage msg (M_LIST_DONE);

				if (fListAgent)
					vision_app->pClientWin()->DispatchMessage(&msg, (BView *)fListAgent);
			}
			return true;

		case RPL_CHANNELMODEIS:	 // 324
			{
				BString theChan (GetWord (data, 4)),
								theMode (GetWord (data, 5)),
								tempStuff (RestOfString (data, 6));

				if (tempStuff != "-9z99")
				{
					theMode.Append(" ");
					theMode.Append(tempStuff); // avoid extra space w/o params
				}

				ClientAgent *aClient (ActiveClient()),
										*theClient (Client (theChan.String()));

				BString tempString("*** ");
				tempString += B_TRANSLATE("Channel mode for %1: %2");
				tempString.ReplaceFirst("%1", theChan.String());
				tempString.ReplaceFirst("%2", theMode.String());
				tempString += '\n';

				BMessage msg (M_CHANNEL_MODES);

				msg.AddString ("msgz", tempString.String());
				msg.AddString ("chan", theChan.String());
				msg.AddString ("mode", theMode.String());

				if (theClient)
					theClient->fMsgr.SendMessage (&msg);
				else if (aClient)
					aClient->fMsgr.SendMessage (&msg);
				else
					Display (tempString.String(), C_OP);
			}
			return true;

		case RPL_CHANNELMLOCK:		// 325
			{
				BString theChan (GetWord (data, 4)),
								mLock (GetWord (data, 8)),
								lockMessage ("*** ");
				lockMessage += B_TRANSLATE("Channel mode lock for %1: %2");
				lockMessage.ReplaceFirst("%1", theChan);
				lockMessage.ReplaceFirst("%2", mLock);
				lockMessage += "\n";

				BMessage display (M_DISPLAY);

				PackDisplay (&display, lockMessage.String(), C_OP, C_BACKGROUND, F_TEXT);
				ClientAgent *theClient (Client (theChan.String()));
				if (theClient)
					theClient->fMsgr.SendMessage (&display);
				else
					fMsgr.SendMessage (&display);
			}
			return true;

		case RPL_CHANNELCREATED:			 // 329
			{
				BString theChan (GetWord (data, 4)),
								theTime (GetWord (data, 5)),
								tempString;

				int32 serverTime (strtoul(theTime.String(), NULL, 0));
				struct tm ptr;
				time_t st;
				char str[80];
				st = serverTime;
				localtime_r (&st, &ptr);
				strftime (str,80,"%a %b %d %Y %I:%M %p %Z",&ptr);
				BString theTimeParsed (str);
				theTimeParsed.RemoveAll ("\n");

			tempString = B_TRANSLATE("Channel %1 was created at %2");
			tempString.ReplaceFirst("%1", theChan);
			tempString.ReplaceFirst("%2", theTimeParsed);
				tempString += '\n';
				Display (tempString.String());
			}
			return true;

		case RPL_NOTOPIC:						 // 331
			{
				BString theChan (GetWord (data, 4)),
								tempString ("[x] ");
				tempString += B_TRANSLATE("No topic set in %1");
				tempString.ReplaceFirst("%1", theChan);
				tempString += '\n';

				BMessage msg (M_DISPLAY);
				PackDisplay (&msg, tempString.String(), C_ERROR);
				PostActive (&msg);
			}
			return true;

		case RPL_TOPIC:							 // 332
			{
				BString theChannel (GetWord (data, 4)),
								theTopic (RestOfString (data, 5));
				ClientAgent *client (Client (theChannel.String()));

				theTopic.RemoveFirst (":");

				if (client)
				{
					BMessage display (M_DISPLAY);
					BString buffer;

					buffer += "*** ";
					buffer += B_TRANSLATE("Topic: %1");
					buffer.ReplaceFirst("%1", theTopic);
					buffer += '\n';
					PackDisplay (&display, buffer.String(), C_WHOIS);

					BMessage msg (M_CHANNEL_TOPIC);
					msg.AddString ("topic", theTopic.String());
					msg.AddMessage ("display", &display);

					if (client->fMsgr.IsValid())
						client->fMsgr.SendMessage (&msg);
				}
			}
			return true;

		case RPL_TOPICSET:						// 333
			{
				BString channel (GetWord (data, 4)),
								user (GetWord (data, 5)),
								theTime (GetWord (data, 6));

				int32 serverTime (strtoul(theTime.String(), NULL, 0));
				struct tm ptr;
				time_t st;
				char str[80];
				st = serverTime;
				localtime_r (&st, &ptr);
				strftime (str,80,"%A %b %d %Y %I:%M %p %Z",&ptr);
				BString theTimeParsed (str);
				theTimeParsed.RemoveAll ("\n");

				ClientAgent *client (Client (channel.String()));

				if (client)
				{
					BMessage display (M_DISPLAY);
					BString buffer = "*** ";

					buffer += B_TRANSLATE("Topic set by %1 at %2");
					buffer.ReplaceFirst("%1", user);
					buffer.ReplaceFirst("%2", theTimeParsed);
					buffer += '\n';
					PackDisplay (&display, buffer.String(), C_WHOIS);
					if (client->fMsgr.IsValid())
						client->fMsgr.SendMessage (&display);
				}
			}
			return true;

		case RPL_INVITING:						 // 341
			{
				BString channel (GetWord (data, 5)),
								theNick (GetWord (data, 4)),
								tempString;

				tempString += "*** ";
				tempString += B_TRANSLATE("%1 has been invited to %2.");
				tempString.ReplaceFirst("%1", theNick);
				tempString.ReplaceFirst("%2", channel);
				tempString += "\n";

				BMessage display (M_DISPLAY);

				PackDisplay (&display, tempString.String(), C_WHOIS);
				PostActive (&display);
			}
			return true;


		case RPL_NAMEREPLY:						 // 353
			{
				BString channel (GetWord (data, 5)),
								names (RestOfString (data, 6));
				ClientAgent *client (Client (channel.String()));
				names.RemoveFirst (":");

					BString tempString ("*** ");
					tempString += B_TRANSLATE("Users in %1: %2");
					tempString.ReplaceFirst("%1", channel);
					tempString.ReplaceFirst("%2", names);
					tempString += '\n';
					Display (tempString.String(), C_TEXT);

				if (client) // in the channel
				{
					BMessage msg (M_CHANNEL_NAMES);
					BString nick;
					int32 place (1);

					while ((nick = GetWord (names.String(), place)) != "-9z99")
					{
						const char *sNick (nick.String());
						bool founder (false),
								 protect (false),
								 op (false),
								 voice (false),
								 helper (false),
							 ignored;

						if (nick[0] == '*')
						{
							++sNick;
							founder = true;
						}
						else if (nick[0] == '!')
						{
							++sNick;
							protect = true;
						}
						else if (nick[0] == '@')
						{
							++sNick;
							op = true;
						}
						else if (nick[0] == '+')
						{
							++sNick;
							voice = true;
						}
						else if (nick[0] == '%')
						{
							++sNick;
							helper = true;
						}

						ignored = false;
						// BMessage aMsg (M_IS_IGNORED), reply;
						// aMsg.AddString ("server", fServerName.String());
						// aMsg.AddString ("nick", sNick);

						// be_app_messenger.SendMessage (&aMsg, &reply);
						// reply.FindBool ("ignored", &ignored);

						msg.AddString ("nick", nick.String());
						msg.AddBool ("founder", founder);
						msg.AddBool ("protect", protect);
						msg.AddBool ("op", op);
						msg.AddBool ("voice", voice);
						msg.AddBool ("helper", helper);
						msg.AddBool ("ignored", ignored);
						++place;
					}

					if (client->fMsgr.IsValid())
						client->fMsgr.SendMessage (&msg);
				}
			}
			return true;

		case RPL_MOTD:						// 372
		case RPL_MOTDALT:				 // 378
		case RPL_OPERMOTDSTART:	 // 609
		case RPL_OPERMOTD:				// 610
		case RPL_OPERENDOFMOTD:	 // 611
			{
				BString tempString (RestOfString(data, 4));
				tempString.RemoveFirst (":");
				tempString.Append ("\n");
				Display (tempString.String(), C_SERVER, C_BACKGROUND, F_SERVER);
			}
			return true;

		case RPL_MOTDSTART:				// 375
			{

				BString tempString ("- ");
				tempString += B_TRANSLATE("Server Message Of the Day");
				tempString += ":\n";
				Display (tempString.String(), C_SERVER, C_BACKGROUND, F_SERVER);
			}
			return true;

		case RPL_ENDOFMOTD:				// 376
		case ERR_NOMOTD:					 // 422
			{
				BString tempString (RestOfString (data, 4));
			tempString.RemoveFirst (":");
			tempString.Append ("\n");

				Display (tempString.String(), C_SERVER, C_BACKGROUND, F_SERVER);

				if (fInitialMotd && fCmds.Length())
				{
					BMessage msg (M_SUBMIT_INPUT);
					const char *place (fCmds.String()), *eol;

					msg.AddInt32 ("which", PASTE_MULTI_NODELAY);

					while ((eol = strchr (place, '\n')) != 0)
					{
						BString line;

						line.Append (place, eol - place);
						msg.AddString ("data", line.String());
						ParseAutoexecChans (line);
						place = eol + 1;
					}

					if (*place)
					{
						// check in case this was the only line
						ParseAutoexecChans (BString(place));
						msg.AddString ("data", place);
					}

					msg.AddInt32 ("which", 3);
					msg.AddBool ("autoexec", true);
					fMsgr.SendMessage (&msg);
				}

				BString IPCommand ("/userhost ");
				IPCommand += fMyNick;
				ParseCmd (IPCommand.String());

				if (fReconnecting)
				{
					BString reString = "[@] ";
					reString += B_TRANSLATE("Successful reconnect");
					reString += "\n";
					Display (reString.String(), C_ERROR);
					DisplayAll (reString.String(), C_ERROR, C_BACKGROUND, F_SERVER);
					fMsgr.SendMessage (M_REJOIN_ALL);
					fReconnecting = false;
				}

				fInitialMotd = false;
			}
			return true;

		case RPL_USERSSTART:			 // 392
			{
				// empty for now
		}
			return true;

		case RPL_USERS:						// 393
			{
				// empty for now
			}
			return true;

		case ERR_ERRONEOUSNICKNAME:		// 432
		case ERR_NICKNAMEINUSE:				// 433
		case ERR_RESOURCEUNAVAILABLE:	// 437
			{
				BString theNick (GetWord (data, 4));

				if (fIsConnecting)
				{
					BString nextNick (GetNextNick());
					if (nextNick != "")
					{
						BString tempString = "* ";
						tempString += B_TRANSLATE("Nickname \"%1\" in use or unavailable, trying \"%2\"");
						tempString.ReplaceFirst("%1", theNick.String());
						tempString.ReplaceFirst("%2", nextNick.String());
						tempString += "\n";
						Display (tempString.String());

						tempString = "NICK ";
						tempString += nextNick;
						SendData (tempString.String());
						return true;
					}
					else
					{
						BString tempString = "* ";
						tempString += B_TRANSLATE("All your pre-selected nicknames are in use.");
						tempString += "\n";
						Display (tempString.String());
						tempString = "* ";
						tempString += B_TRANSLATE("Please type /NICK <NEWNICK> to try another.");
						tempString += "\n";
						Display (tempString.String());
						return true;
					}
				}
				BString tempString = "[x] ";
				tempString += B_TRANSLATE("Nickname/Channel \"%1\" is already in use or unavailable.");
				tempString.ReplaceFirst("%1", theNick);
				tempString += "\n";

				BMessage display (M_DISPLAY);
				PackDisplay (&display, tempString.String(), C_NICK);
				PostActive (&display);
			}
			return true;

		case ERR_USERNOTINCHANNEL:		// 441
			{
				BString theChannel (GetWord (data, 5)),
								theNick (GetWord (data, 4)),
								tempString ("[x] ");
				tempString += B_TRANSLATE("%1 not in %2.");
				tempString.ReplaceFirst("%1", theNick);
				tempString.ReplaceFirst("%2", theChannel);
				tempString += "\n";

				BMessage msg (M_DISPLAY);
				PackDisplay (&msg, tempString.String(), C_ERROR);
				PostActive (&msg);
			}
			return true;

		case ERR_NOTONCHANNEL:			 // 442
			{
				BString theChannel (GetWord (data, 4)),
								tempString ("[x] ");
				tempString += B_TRANSLATE("You're not in %1.");
				tempString.ReplaceFirst("%1", theChannel);
				tempString += "\n";

				BMessage msg (M_DISPLAY);
				PackDisplay (&msg, tempString.String(), C_ERROR);
				PostActive (&msg);
			}
			return true;

		case ERR_USERONCHANNEL:		 // 443
			{
				BString theChannel (GetWord (data, 5)),
								theNick (GetWord (data, 4)),
				tempString ("[x] ");
				tempString += B_TRANSLATE("%1 is already in %2.");
				tempString.ReplaceFirst("%1", theNick);
				tempString.ReplaceFirst("%2", theChannel);
				tempString += "\n";

				BMessage msg (M_DISPLAY);
				PackDisplay (&msg, tempString.String(), C_ERROR);
				PostActive (&msg);
			}
			return true;

		case ERR_KEYSET:						// 467
			{
				BString theChannel (GetWord (data, 4)),
								tempString ("[x] ");
				tempString += B_TRANSLATE("Channel key already set in %1.");
				tempString.ReplaceFirst("%1", theChannel);
				tempString += "\n";

				BMessage msg (M_DISPLAY);
				PackDisplay (&msg, tempString.String(), C_ERROR);
				PostActive (&msg);
			}
			return true;

		case ERR_UNKNOWNMODE:				// 472
			{
				BString theMode (GetWord (data, 4)),
								tempString ("[x] ");
				tempString += B_TRANSLATE("Unknown channel mode: '%1'.");
				tempString.ReplaceFirst("%1", theMode);
				tempString += "\n";

				BMessage msg (M_DISPLAY);
				PackDisplay (&msg, tempString.String(), C_QUIT);
				PostActive (&msg);
			}
			return true;

		case ERR_INVITEONLYCHAN:		 // 473
			{
				BString theChan (GetWord (data, 4)),
								tempString ("[x] "),
								theReason (RestOfString (data, 5));
				theReason.RemoveFirst(":");
				theReason.ReplaceLast("channel", theChan.String());
				tempString << theReason < " ";
				tempString += B_TRANSLATE("(invite only)");
				tempString += "\n";

				BMessage msg (M_DISPLAY);
				PackDisplay (&msg, tempString.String(), C_QUIT, C_BACKGROUND, F_SERVER);
				PostActive (&msg);
				RemoveAutoexecChan (theChan);
			}
			return true;

		case ERR_BANNEDFROMCHAN:		 // 474
			{
				BString theChan (GetWord (data, 4)),
								tempString ("[x] "),
								theReason (RestOfString (data, 5));
				theReason.RemoveFirst(":");
				theReason.ReplaceLast("channel", theChan.String());

				tempString << theReason < " ";
				tempString += B_TRANSLATE("(you're banned)");
				tempString += "\n";

				BMessage msg (M_DISPLAY);
				PackDisplay (&msg, tempString.String(), C_QUIT, C_BACKGROUND, F_SERVER);
				PostActive (&msg);
				RemoveAutoexecChan (theChan);
			}
			return true;

		case ERR_BADCHANNELKEY:			// 475
			{
				BString theChan (GetWord(data, 4)),
								theReason (RestOfString(data, 5)),
								tempString("[x] ");
				theReason.RemoveFirst(":");
				theReason.ReplaceLast("channel", theChan.String());
				tempString << theReason << " ";
				tempString += B_TRANSLATE("(bad channel key)");
				tempString += "\n";

				BMessage msg (M_DISPLAY);
				PackDisplay (&msg, tempString.String(), C_QUIT, C_BACKGROUND, F_SERVER);
				PostActive (&msg);
				RemoveAutoexecChan (theChan);
			}
			return true;

		case ERR_UMODEUNKNOWNFLAG:		// 501
			{
				BMessage msg (M_DISPLAY);
				BString buffer = "[x] ";

		buffer += B_TRANSLATE("Unknown mode flag.");
				buffer += "\n";
				PackDisplay (&msg, buffer.String(), C_QUIT);
				PostActive (&msg);
			}
			return true;

		// not sure what these numerics are,
		// but they are usually on-connect messages
		case RPL_290:								 // 290
		case RPL_291:								 // 291
		case RPL_292:								 // 292
			{
				BString tempString (RestOfString(data, 4));
				tempString.RemoveFirst (":");
				tempString.Append ("\n");
				tempString.Prepend ("- ");
				Display (tempString.String());
			}
			return true;

		case RPL_WHOISREGISTEREDBOT:	// 617
			{
				// conflicts with RPL_DCCALLOWCHANGE
				BString theNick (GetWord (data, 4)),
								theMessage (RestOfString (data, 5)),
								tempString;
				theNick.RemoveFirst (":");
				theMessage.RemoveFirst (":");
				theMessage.Append ("\n");

				switch (fIrcdtype)
				{
					case IRCD_ULTIMATE:
						{
							tempString += "[@] ";
							tempString += theMessage;
							BMessage msg (M_DISPLAY);
							PackDisplay (&msg, tempString.String(), C_WHOIS, C_BACKGROUND, F_SERVER);
							PostActive (&msg);
						}
						break;

					default:
						{
							tempString += theNick;
							tempString += " ";
							tempString += theMessage;
							Display (tempString.String());
						}
				}
			}
			return true;

		default:
			break;
	}

	return false;
}
Ejemplo n.º 30
0
void ResourceContainer::sendAttributes(PlayerObject* playerObject)
{
    if(!(playerObject->isConnected()))
        return;

    Message*	newMessage;
    BString		value;

    gMessageFactory->StartMessage();
    gMessageFactory->addUint32(opAttributeListMessage);
    gMessageFactory->addUint64(mId);

    uint32 attrCount = 4;

    for(uint8 i = 0; i < 11; i++)
    {
        if(mResource->getAttribute(i))
            ++attrCount;
    }

    gMessageFactory->addUint32(attrCount + mAttributeMap.size());

    wchar_t temp[64];
    swprintf(temp,20,L"%u/%u",mMaxCondition-mDamage,mMaxCondition);
    gMessageFactory->addString(BString("condition"));
    gMessageFactory->addString(temp);

    AttributeMap::iterator			mapIt;
    AttributeOrderList::iterator	orderIt = mAttributeOrderList.begin();

    while(orderIt != mAttributeOrderList.end())
    {
        mapIt = mAttributeMap.find(*orderIt);

        gMessageFactory->addString(gWorldManager->getAttributeKey((*mapIt).first));

        value = (*mapIt).second.c_str();
        value.convert(BSTRType_Unicode16);

        gMessageFactory->addString(value);

        ++orderIt;
    }

    swprintf(temp,20,L"%u/%u",mAmount,mMaxAmount);
    gMessageFactory->addString(BString("resource_contents"));
    gMessageFactory->addString(temp);

    std::string tempString(mResource->getName().getAnsi());
    gMessageFactory->addString(BString("resource_name"));
    gMessageFactory->addString(std::wstring(tempString.begin(), tempString.end()).c_str());

    tempString.clear();
    tempString = ((mResource->getType())->getName()).getAnsi();
    gMessageFactory->addString(BString("resource_class"));
    gMessageFactory->addString(std::wstring(tempString.begin(), tempString.end()).c_str());

    for(uint8 i = 0; i < 11; i++)
    {
        uint16	attrValue = 0;
        BString	attrName;

        if((attrValue = mResource->getAttribute(i)) != 0)
        {
            switch(i)
            {
            case ResAttr_OQ:
                attrName = "res_quality";
                break;
            case ResAttr_CR:
                attrName = "res_cold_resist";
                break;
            case ResAttr_CD:
                attrName = "res_conductivity";
                break;
            case ResAttr_DR:
                attrName = "res_decay_resist";
                break;
            case ResAttr_HR:
                attrName = "res_heat_resist";
                break;
            case ResAttr_MA:
                attrName = "res_malleability";
                break;
            case ResAttr_SR:
                attrName = "res_shock_resistance";
                break;
            case ResAttr_UT:
                attrName = "res_toughness";
                break;
            case ResAttr_ER:
                attrName = "entangle_resistance";
                break;
            case ResAttr_PE:
                attrName = "res_potential_energy";
                break;
            case ResAttr_FL:
                attrName = "res_flavor";
                break;
            }

            swprintf(temp,10,L"%u",attrValue);

            gMessageFactory->addString(attrName);
            gMessageFactory->addString(temp);
        }
    }

    //gMessageFactory->addUint32(0);

    newMessage = gMessageFactory->EndMessage();

    (playerObject->getClient())->SendChannelAUnreliable(newMessage, playerObject->getAccountId(),  CR_Client, 9);
}