void MatrixControl::Run(alNormalWindow *win)
{
//Optimizer Section
int i ,k, x;
int counted_zeros[matrix_dimension];
int bestline,val;
float value;

for (i=0; i < matrix_dimension; ++i)
	{
	counted_zeros[i] = 0;
	for (x=0; x < matrix_dimension; ++x)
		{
		value = float_matrix[i*matrix_dimension +x];
		if (value == 0.0) ++counted_zeros[i];
		}
	}


for (i=0; i < matrix_dimension; ++i)
	{
	bestline = -1;
	val = 0;
	for (k = i; k < matrix_dimension; ++k)
		{
		if (counted_zeros[k] > val) 
			{
			val = counted_zeros[k]; 
			bestline = k;
			}
		}
	if (bestline > i)
		SwitchRows(bestline, i);		
	}
//Optimizer End

oneisrunning = true;

MasterMatrix = this;
loaded_threads = 0;
answers = 0;
MatrixResult = 0.0;

BString nam ("Progress ");
nam += extra::StringOutOf(matrix_dimension);
nam.Append("x");
nam += extra::StringOutOf(matrix_dimension);


alLooper *master_matrix_calculator = new alLooper(&MasterMatrixReceiver,"Master Matrix Calculator",B_LOW_PRIORITY);
theone = new ShowProgressWin(400,100,nam.String(),100);

theone->stat_bar->SetMaxValue( (float) matrix_dimension );
theone->tonotify = win;
theone->toshutLooper = master_matrix_calculator;
theone->Show();



master_matrix_calculator->Parent = (char *) this;
master_matrix_calculator->Run();
master_matrix_calculator->PostMessage(1);
}
Example #2
0
//---------------------------------------------------------------
void ExportWindow::MainLoop()
{
BString fFilePath;
BString fFolderPath;
BString fFileName;
BPath Path;
BEntry Entry("/boot/home");
MSave Load("Load");

find_directory(B_COMMON_SETTINGS_DIRECTORY, &Path);
fFolderPath.SetTo(Path.Path());
fFolderPath.Append(SAVE_NOTE_PATH);

	for (int a = 1; a <= 31; a++)
	{
	fFileName.SetTo("");
	fFileName << a << "-" << fMonth << fYear << "-";
		for (int b = 1; b <= INT_MAXFILES; b++)
		{
		fFileName << b;
		fFilePath.SetTo(fFolderPath);
		fFilePath << fFileName.String();
		Entry.SetTo(fFilePath.String());
			if (Entry.Exists())
			{
			Load.FindString(fFilePath.String(), SAVE_FILE_TYPE, &fType, "M_ERROR");
				
				if (!strcmp(fType.String(), "Note") || !strcmp(fType.String(), "Apointment"))
				{
					//Add the date if it is the first note/apointment of this day
					if (fFirstNoteOfTheDay)
					{
					fContent << "<table width=450 color=\"#FFFFFF\">\n";
					fContent << "<h2>" << a << "." << fMonth << "-" << fYear << "</h2>\n";
					fFirstNoteOfTheDay = false;
					}
					
					//Change the color
					if (!strcmp(TableColor.String(), TableBGColor1.String()))
					{
					TableColor.SetTo(TableBGColor2);
					}
					else
					{
					TableColor.SetTo(TableBGColor1);
					}	
				}
				
				//Its a note
				if (!strcmp(fType.String(), "Note") && _ExportView->mNoteCheckBox->Value())
				{
				Load.FindString(fFilePath.String(), SAVE_FILE_NOTE, &fNote, "M_ERROR");
				Load.FindString(fFilePath.String(), SAVE_FILE_TITLE, &fTitle, "M_ERROR");
				
				fContent << "<tr><td bgcolor=\"" << TableColor.String() << "\" width=430>\n";
				fContent << "<h4>"<< fTitle.String() << "</h4>";
				fNote.ReplaceAll("\n", "<br>");
				fContent << fNote.String() << "\n";
				fContent << "</tr></td>\n";
				}
				
				//Its an apointment
				if (!strcmp(fType.String(), "Apointment") && _ExportView->mApointmentCheckBox->Value())
				{
				Load.FindString(fFilePath.String(), SAVE_FILE_NOTE, &fNote, "M_ERROR");
				Load.FindString(fFilePath.String(), SAVE_FILE_TITLE, &fTitle, "M_ERROR");
				Load.FindString(fFilePath.String(), SAVE_FILE_TIME, &fTime, "M_ERROR");
				
				fContent << "<tr><td bgcolor=\"" << TableColor.String() << "\" width=430>\n";
				fContent << "<h4>"<< fTitle.String() << "";
				
				tmpString.SetTo(fTime);
				tmpString.Remove(0, tmpString.FindFirst(":") + 1);
					if (tmpString.CountChars() == 1)
					{
					fTime.RemoveLast(tmpString.String());
					fTime.Append("0");
					fTime.Append(tmpString.String());
					}
				fContent << "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"<< fTime.String() << "</h4>\n";
				fNote.ReplaceAll("\n", "<br>");
				fContent << fNote.String() << "\n";
				fContent << "</tr></td>\n";
				}
			}
		tmpString.SetTo("");
		tmpString << b;
		fFileName.RemoveLast(tmpString.String());
		}
		if (!fFirstNoteOfTheDay)
		{
		fContent << "</table>\n";
		fContent << "<br>";
		}
	fFirstNoteOfTheDay = true;
	}
}
Example #3
0
status_t LoadStatusses(BPath statFilePath)
{
	status_t error = B_OK;
	//open file
	BFile statFile(statFilePath.Path(), B_READ_ONLY);
	error = statFile.InitCheck();
	if (error != B_ERROR)
	{
		StringList *tokenList = new StringList();
		//read line
		off_t fileSize;
		if (statFile.GetSize(&fileSize) == B_OK)
		{			
			ssize_t bytesRead = 0;
			BString* token = new BString("");
			bool newToken = false;			
			do
			{
				char c[2];				
				bytesRead += statFile.Read(c,1);
				c[1] = '\0';				
				
				if (c[0] == '\t' || c[0] == '\n')
				{
					//clear token
					if (!newToken)
					{
						//add token to list
						tokenList->AddItem(token);						
						token = new BString("");				
						newToken = true;
					}
				}
				else 
				{
					token->Append(c);
					newToken = false;
				}
			}
			while (bytesRead < fileSize);
		}
		
		int32 startIndex = -1;
		int32 endIndex = -1;
		for (int32 i = 0; i < tokenList->CountItems(); i++)
		{
			if ((*tokenList)[i].ICompare("<status>") == 0)
				startIndex = i;
			else if ((*tokenList)[i].ICompare("</status>") == 0)
			{
				endIndex = i;
				break;
			}
		}
		
		if (startIndex != -1 && endIndex != -1)
		{
			//start past the <status> tag
			startIndex++;
			for (int32 i = startIndex; i < endIndex; i++)
			{
				int32 lastLineIndex = i + 4;

				if (lastLineIndex < endIndex)
				{
					//parse lines
					BString bitmapString = (*tokenList)[i];
					BString statusName = (*tokenList)[i+1];
					BString abbreviation = (*tokenList)[i+2];
					bool userChoice = atoi((*tokenList)[i+3].String());				
					BString colourString = (*tokenList)[i+4];
					i += 4;
					//construct bitmap path
					BPath bitmapPath;
					statFilePath.GetParent(&bitmapPath);
					bitmapPath.Append(bitmapString.String());
					BBitmap *icon = BTranslationUtils::GetBitmap(bitmapPath.Path());
					//construct status object
					Status *status = FindStatus(abbreviation);
					if (status != NULL)
					{
						status->AddIcon(icon);
					}
					else
					{
						//remove brackets from colourString
						colourString.RemoveAll("{");						
						colourString.RemoveAll("}");
						
						int32 colours[4];
						int32 startIndex = 0;						
						for (int i = 0; i < 4; i++)
						{
							int32 commaIndex = colourString.FindFirst(",",startIndex);							
							if (commaIndex != B_ERROR)
							{
								BString colourValue;
								colourString.CopyInto(colourValue,startIndex, commaIndex-startIndex);
								colours[i] = atoi(colourValue.String());
								startIndex = commaIndex + 1;
							}
							else if (i < 3)
							{								
								BString colourValue;								
								colourString.CopyInto(colourValue, startIndex, colourString.CountChars() - startIndex);
								colours[i] = atoi(colourValue.String());								
							}		
							else if (i == 3)
							{
								colours[i] = 255;
							}						
						}
						//construct status colour
						rgb_color statusColour;
						statusColour.red = colours[0];
						statusColour.green = colours[1];
						statusColour.blue = colours[2];
						statusColour.alpha = colours[3];
						//construct new status object
						Status *status = new Status(statusName,abbreviation, icon, userChoice, statusColour);
						statLock.Lock();
						statusses[abbreviation] = status;
						statLock.Unlock();	
							
					}		
				}
			}
		}
				
		StringList::deleteStrings(tokenList);
		delete tokenList;
	}	
	else
	{
		error = B_ERROR;
	}	
	return error;
}
Example #4
0
void
TMailApp::RefsReceived(BMessage *msg)
{
	bool		have_names = false;
	BString		names;
	char		type[B_FILE_NAME_LENGTH];
	int32		item = 0;
	BFile		file;
	TMailWindow	*window;
	entry_ref	ref;

	//
	// If a tracker window opened me, get a messenger from it.
	//
	BMessenger messenger;
	if (msg->HasMessenger("TrackerViewToken"))
		msg->FindMessenger("TrackerViewToken", &messenger);

	while (msg->HasRef("refs", item)) {
		msg->FindRef("refs", item++, &ref);
		if ((window = FindWindow(ref)) != NULL)
			window->Activate(true);
		else {
			file.SetTo(&ref, O_RDONLY);
			if (file.InitCheck() == B_NO_ERROR) {
				BNodeInfo	node(&file);
				node.GetType(type);
				if (strcmp(type, B_MAIL_TYPE) == 0
					|| strcmp(type, B_PARTIAL_MAIL_TYPE) == 0) {
					window = NewWindow(&ref, NULL, false, &messenger);
					window->Show();
				} else if(strcmp(type, "application/x-person") == 0) {
					/* Got a People contact info file, see if it has an Email address. */
					BString name;
					BString email;
					attr_info	info;
					char *attrib;

					if (file.GetAttrInfo("META:email", &info) == B_NO_ERROR) {
						attrib = (char *) malloc(info.size + 1);
						file.ReadAttr("META:email", B_STRING_TYPE, 0, attrib, info.size);
						attrib[info.size] = 0; // Just in case it wasn't NUL terminated.
						email << attrib;
						free(attrib);

						/* we got something... */
						if (email.Length() > 0) {
							/* see if we can get a username as well */
							if(file.GetAttrInfo("META:name", &info) == B_NO_ERROR) {
								attrib = (char *) malloc(info.size + 1);
								file.ReadAttr("META:name", B_STRING_TYPE, 0, attrib, info.size);
								attrib[info.size] = 0; // Just in case it wasn't NUL terminated.
								name << "\"" << attrib << "\" ";
								email.Prepend("<");
								email.Append(">");
								free(attrib);
							}

							if (names.Length() == 0) {
								names << name << email;
							} else {
								names << ", " << name << email;
							}
							have_names = true;
							email.SetTo("");
							name.SetTo("");
						}
					}
				}
				else if (strcmp(type, kDraftType) == 0) {
					window = NewWindow();

					// If it's a draft message, open it
					window->OpenMessage(&ref);
					window->Show();
				}
			} /* end of else(file.InitCheck() == B_NO_ERROR */
		}
	}

	if (have_names) {
		window = NewWindow(NULL, names.String());
		window->Show();
	}
}
Example #5
0
File: smtp.cpp Project: DonCN/haiku
status_t
SMTPProtocol::Login(const char *_login, const char *password)
{
	if (fAuthType == 0)
		return B_OK;

	const char *login = _login;
	char hex_digest[33];
	BString out;

	int32 loginlen = ::strlen(login);
	int32 passlen = ::strlen(password);

	if (fAuthType & DIGEST_MD5) {
		//******* DIGEST-MD5 Authentication ( tested. works fine [with Cyrus SASL] )
		// this implements only the subpart of DIGEST-MD5 which is
		// required for authentication to SMTP-servers. Integrity-
		// and confidentiality-protection are not implemented, as
		// they are provided by the use of OpenSSL.
		SendCommand("AUTH DIGEST-MD5"CRLF);
		const char *res = fLog.String();

		if (strncmp(res, "334", 3) != 0)
			return B_ERROR;
		int32 baselen = ::strlen(&res[4]);
		char *base = new char[baselen+1];
		baselen = ::decode_base64(base, &res[4], baselen);
		base[baselen] = '\0';

		D(bug("base: %s\n", base));

		map<BString,BString> challengeMap;
		SplitChallengeIntoMap(base, challengeMap);

		delete[] base;

		BString rawResponse = BString("username="******"' << login << '"';
		rawResponse << ",realm=" << '"' << challengeMap["realm"] << '"';
		rawResponse << ",nonce=" << '"' << challengeMap["nonce"] << '"';
		rawResponse << ",nc=00000001";
		char temp[33];
		for( int i=0; i<32; ++i)
			temp[i] = 1+(rand()%254);
		temp[32] = '\0';
		BString rawCnonce(temp);
		BString cnonce;
		char* cnoncePtr = cnonce.LockBuffer(rawCnonce.Length()*2);
		baselen = ::encode_base64(cnoncePtr, rawCnonce.String(), rawCnonce.Length(), true /* headerMode */);
		cnoncePtr[baselen] = '\0';
		cnonce.UnlockBuffer(baselen);
		rawResponse << ",cnonce=" << '"' << cnonce << '"';
		rawResponse << ",qop=auth";
		BString digestUriValue	= BString("smtp/") << fServerName;
		rawResponse << ",digest-uri=" << '"' << digestUriValue << '"';
		char sum[17], hex_digest2[33];
		BString a1,a2,kd;
		BString t1 = BString(login) << ":"
				<< challengeMap["realm"] << ":"
				<< password;
		MD5Sum(sum, (unsigned char*)t1.String(), t1.Length());
		a1 << sum << ":" << challengeMap["nonce"] << ":" << cnonce;
		MD5Digest(hex_digest, (unsigned char*)a1.String(), a1.Length());
		a2 << "AUTHENTICATE:" << digestUriValue;
		MD5Digest(hex_digest2, (unsigned char*)a2.String(), a2.Length());
		kd << hex_digest << ':' << challengeMap["nonce"]
		   << ":" << "00000001" << ':' << cnonce << ':' << "auth"
		   << ':' << hex_digest2;
		MD5Digest(hex_digest, (unsigned char*)kd.String(), kd.Length());

		rawResponse << ",response=" << hex_digest;
		BString postResponse;
		char *resp = postResponse.LockBuffer(rawResponse.Length() * 2 + 10);
		baselen = ::encode_base64(resp, rawResponse.String(), rawResponse.Length(), true /* headerMode */);
		resp[baselen] = 0;
		postResponse.UnlockBuffer();
		postResponse.Append(CRLF);

		SendCommand(postResponse.String());

		res = fLog.String();
		if (atol(res) >= 500)
			return B_ERROR;
		// actually, we are supposed to check the rspauth sent back
		// by the SMTP-server, but that isn't strictly required,
		// so we skip that for now.
		SendCommand(CRLF);	// finish off authentication
		res = fLog.String();
		if (atol(res) < 500)
			return B_OK;
	}
	if (fAuthType & CRAM_MD5) {
		//******* CRAM-MD5 Authentication ( tested. works fine [with Cyrus SASL] )
		SendCommand("AUTH CRAM-MD5"CRLF);
		const char *res = fLog.String();

		if (strncmp(res, "334", 3) != 0)
			return B_ERROR;
		int32 baselen = ::strlen(&res[4]);
		char *base = new char[baselen+1];
		baselen = ::decode_base64(base, &res[4], baselen);
		base[baselen] = '\0';

		D(bug("base: %s\n", base));

		::MD5HexHmac(hex_digest, (const unsigned char *)base, (int)baselen,
			(const unsigned char *)password, (int)passlen);

		D(bug("%s\n%s\n", base, hex_digest));

		delete[] base;

		BString preResponse, postResponse;
		preResponse = login;
		preResponse << " " << hex_digest << CRLF;
		char *resp = postResponse.LockBuffer(preResponse.Length() * 2 + 10);
		baselen = ::encode_base64(resp, preResponse.String(), preResponse.Length(), true /* headerMode */);
		resp[baselen] = 0;
		postResponse.UnlockBuffer();
		postResponse.Append(CRLF);

		SendCommand(postResponse.String());

		res = fLog.String();
		if (atol(res) < 500)
			return B_OK;
	}
	if (fAuthType & LOGIN) {
		//******* LOGIN Authentication ( tested. works fine)
		ssize_t encodedsize; // required by our base64 implementation

		SendCommand("AUTH LOGIN"CRLF);
		const char *res = fLog.String();

		if (strncmp(res, "334", 3) != 0)
			return B_ERROR;

		// Send login name as base64
		char *login64 = new char[loginlen*3 + 6];
		encodedsize = ::encode_base64(login64, (char *)login, loginlen, true /* headerMode */);
		login64[encodedsize] = 0;
		strcat (login64, CRLF);
		SendCommand(login64);
		delete[] login64;

		res = fLog.String();
		if (strncmp(res,"334",3) != 0)
			return B_ERROR;

		// Send password as base64
		login64 = new char[passlen*3 + 6];
		encodedsize = ::encode_base64(login64, (char *)password, passlen, true /* headerMode */);
		login64[encodedsize] = 0;
		strcat (login64, CRLF);
		SendCommand(login64);
		delete[] login64;

		res = fLog.String();
		if (atol(res) < 500)
			return B_OK;
	}
	if (fAuthType & PLAIN) {
		//******* PLAIN Authentication ( tested. works fine [with Cyrus SASL] )
		// format is:
		// 	authenticateID + \0 + username + \0 + password
		// 	(where authenticateID is always empty !?!)
		BString preResponse, postResponse;
		char *stringPntr;
		ssize_t encodedLength;
		stringPntr = preResponse.LockBuffer(loginlen + passlen + 3);
			// +3 to make room for the two \0-chars between the tokens and
			// the final delimiter added by sprintf().
		sprintf (stringPntr, "%c%s%c%s", 0, login, 0, password);
		preResponse.UnlockBuffer(loginlen + passlen + 2);
			// +2 in order to leave out the final delimiter (which is not part
			// of the string).
		stringPntr = postResponse.LockBuffer(preResponse.Length() * 3);
		encodedLength = ::encode_base64(stringPntr, preResponse.String(),
			preResponse.Length(), true /* headerMode */);
		stringPntr[encodedLength] = 0;
		postResponse.UnlockBuffer();
		postResponse.Prepend("AUTH PLAIN ");
		postResponse << CRLF;

		SendCommand(postResponse.String());

		const char *res = fLog.String();
		if (atol(res) < 500)
			return B_OK;
	}
	return B_ERROR;
}
Example #6
0
void
CalcView::Paste(BMessage* message)
{
	// handle files first
	int32 count;
	if (message->GetInfo("refs", NULL, &count) == B_OK) {
		entry_ref ref;
		ssize_t read;
		BFile file;
		char buffer[256];
		memset(buffer, 0, sizeof(buffer));
		for (int32 i = 0; i < count; i++) {
			if (message->FindRef("refs", i, &ref) == B_OK) {
				if (file.SetTo(&ref, B_READ_ONLY) == B_OK) {
					read = file.Read(buffer, sizeof(buffer) - 1);
					if (read <= 0)
						continue;
					BString expression(buffer);
					int32 j = expression.Length();
					while (j > 0 && expression[j - 1] == '\n')
						j--;
					expression.Truncate(j);
					if (expression.Length() > 0)
						fExpressionTextView->Insert(expression.String());
				}
			}
		}
		return;
	}
	// handle color drops
	// read incoming color
	const rgb_color* dropColor = NULL;
	ssize_t dataSize;
	if (message->FindData("RGBColor", B_RGB_COLOR_TYPE,
			(const void**)&dropColor, &dataSize) == B_OK
		&& dataSize == sizeof(rgb_color)) {

		// calculate view relative drop point
		BPoint dropPoint = ConvertFromScreen(message->DropPoint());

		// calculate current keypad area
		float sizeDisp = fHeight * kDisplayScaleY;
		BRect keypadRect(0.0, sizeDisp, fWidth, fHeight);

		// check location of color drop
		if (keypadRect.Contains(dropPoint) && dropColor != NULL) {
			fBaseColor = *dropColor;
			fHasCustomBaseColor =
				fBaseColor != ui_color(B_PANEL_BACKGROUND_COLOR);
			_Colorize();
			// redraw
			Invalidate();
		}

	} else {
		// look for text/plain MIME data
		const char* text;
		ssize_t numBytes;
		if (message->FindData("text/plain", B_MIME_TYPE,
				(const void**)&text, &numBytes) == B_OK) {
			BString temp;
			temp.Append(text, numBytes);
			fExpressionTextView->Insert(temp.String());
		}
	}
}
Example #7
0
void
TMailApp::ArgvReceived(int32 argc, char **argv)
{
	BEntry entry;
	BString names;
	BString ccNames;
	BString bccNames;
	BString subject;
	BString body;
	BMessage enclosure(B_REFS_RECEIVED);
	// a "mailto:" with no name should open an empty window
	// so remember if we got a "mailto:" even if there isn't a name
	// that goes along with it (this allows deskbar replicant to open
	// an empty message even when Mail is already running)
	bool gotmailto = false;

	for (int32 loop = 1; loop < argc; loop++)
	{
		if (strcmp(argv[loop], "-h") == 0
			|| strcmp(argv[loop], "--help") == 0)
		{
			printf(" usage: %s [ mailto:<address> ] [ -subject \"<text>\" ] [ ccto:<address> ] [ bccto:<address> ] "
				"[ -body \"<body text>\" ] [ enclosure:<path> ] [ <message to read> ...] \n",
				argv[0]);
			fPrintHelpAndExit = true;
			be_app->PostMessage(B_QUIT_REQUESTED);
			return;
		}
		else if (strncmp(argv[loop], "mailto:", 7) == 0)
		{
			if (names.Length())
				names += ", ";
			char *options;
			if ((options = strchr(argv[loop],'?')) != NULL)
			{
				names.Append(argv[loop] + 7, options - argv[loop] - 7);
				if (!strncmp(++options,"subject=",8))
					subject = options + 8;
			}
			else
				names += argv[loop] + 7;
			gotmailto = true;
		}
		else if (strncmp(argv[loop], "ccto:", 5) == 0)
		{
			if (ccNames.Length())
				ccNames += ", ";
			ccNames += argv[loop] + 5;
		}
		else if (strncmp(argv[loop], "bccto:", 6) == 0)
		{
			if (bccNames.Length())
				bccNames += ", ";
			bccNames += argv[loop] + 6;
		}
		else if (strcmp(argv[loop], "-subject") == 0)
			subject = argv[++loop];
		else if (strcmp(argv[loop], "-body") == 0 && argv[loop + 1])
			body = argv[++loop];
		else if (strncmp(argv[loop], "enclosure:", 10) == 0)
		{
			BEntry tmp(argv[loop] + 10, true);
			if (tmp.InitCheck() == B_OK && tmp.Exists())
			{
				entry_ref ref;
				tmp.GetRef(&ref);
				enclosure.AddRef("refs", &ref);
			}
		}
		else if (entry.SetTo(argv[loop]) == B_NO_ERROR)
		{
			BMessage msg(B_REFS_RECEIVED);
			entry_ref ref;
			entry.GetRef(&ref);
			msg.AddRef("refs", &ref);
			RefsReceived(&msg);
		}
	}

	if (gotmailto || names.Length() || ccNames.Length() || bccNames.Length() || subject.Length()
		|| body.Length() || enclosure.HasRef("refs"))
	{
		TMailWindow	*window = NewWindow(NULL, names.String());
		window->SetTo(names.String(), subject.String(), ccNames.String(), bccNames.String(),
			&body, &enclosure);
		window->Show();
	}
}
Example #8
0
void
NotificationView::SetText(const char* app, const char* title, const char* text,
	float newMaxWidth)
{
	if (newMaxWidth < 0)
		newMaxWidth = Bounds().Width() - (kEdgePadding * 2);

	// Delete old lines
	LineInfoList::iterator lIt;
	for (lIt = fLines.begin(); lIt != fLines.end(); lIt++)
		delete (*lIt);
	fLines.clear();

	fApp = app;
	fTitle = title;
	fText = text;

	float iconRight = kEdgePadding + kEdgePadding;
	if (fBitmap != NULL)
		iconRight += fParent->IconSize();

	font_height fh;
	be_bold_font->GetHeight(&fh);
	float fontHeight = ceilf(fh.leading) + ceilf(fh.descent)
		+ ceilf(fh.ascent);
	float y = fontHeight;

	// Title
	LineInfo* titleLine = new LineInfo;
	titleLine->text = fTitle;
	titleLine->font = *be_bold_font;

	if (fParent->Layout() == AllTextRightOfIcon)
		titleLine->location = BPoint(iconRight, y);
	else
		titleLine->location = BPoint(kEdgePadding, y);

	fLines.push_front(titleLine);
	y += fontHeight;

	// Rest of text is rendered with be_plain_font.
	be_plain_font->GetHeight(&fh);
	fontHeight = ceilf(fh.leading) + ceilf(fh.descent)
		+ ceilf(fh.ascent);

	// Split text into chunks between certain characters and compose the lines.
	const char kSeparatorCharacters[] = " \n-\\/";
	BString textBuffer = fText;
	textBuffer.ReplaceAll("\t", "    ");
	const char* chunkStart = textBuffer.String();
	float maxWidth = newMaxWidth - kEdgePadding - iconRight;
	LineInfo* line = NULL;
	ssize_t length = textBuffer.Length();
	while (chunkStart - textBuffer.String() < length) {
		size_t chunkLength = strcspn(chunkStart, kSeparatorCharacters) + 1;

		// Start a new line if either we didn't start one before,
		// the current offset
		BString tempText;
		if (line != NULL)
			tempText.SetTo(line->text);
		tempText.Append(chunkStart, chunkLength);

		if (line == NULL || chunkStart[0] == '\n'
			|| StringWidth(tempText) > maxWidth) {
			line = new LineInfo;
			line->font = *be_plain_font;
			line->location = BPoint(iconRight + kEdgePadding, y);

			fLines.push_front(line);
			y += fontHeight;

			// Skip the eventual new-line character at the beginning of this
			// chunk.
			if (chunkStart[0] == '\n') {
				chunkStart++;
				chunkLength--;
			}
			// Skip more new-line characters and move the line further down.
			while (chunkStart[0] == '\n') {
				chunkStart++;
				chunkLength--;
				line->location.y += fontHeight;
				y += fontHeight;
			}
			// Strip space at beginning of a new line.
			while (chunkStart[0] == ' ') {
				chunkLength--;
				chunkStart++;
			}
		}

		if (chunkStart[0] == '\0')
			break;

		// Append the chunk to the current line, which was either a new
		// line or the one from the previous iteration.
		line->text.Append(chunkStart, chunkLength);

		chunkStart += chunkLength;
	}

	fHeight = y + (kEdgePadding * 2);

	// Make sure icon fits
	if (fBitmap != NULL) {
		float minHeight = 0;
		if (fParent->Layout() == TitleAboveIcon) {
			LineInfo* appLine = fLines.back();
			font_height fh;
			appLine->font.GetHeight(&fh);
			minHeight = appLine->location.y + fh.descent;
		}

		minHeight += fBitmap->Bounds().Height() + 2 * kEdgePadding;
		if (fHeight < minHeight)
			fHeight = minHeight;
	}

	BMessenger messenger(Parent());
	messenger.SendMessage(kResizeToFit);
}
Example #9
0
bool
ServerWindow::ParseEvents (const char *data)
{
	BString firstWord = GetWord(data, 1).ToUpper();
	BString secondWord = GetWord(data, 2).ToUpper();

	if(firstWord == "PING")
	{
		BString tempString,
		        theServer (GetWord(data, 2));
		theServer.RemoveFirst(":");
		
		tempString << "PONG " << myNick << " " << theServer;
		SendData (tempString.String());
		tempString = "";
		tempString << "PONG " << theServer; // fix for some noncompliant servers
		SendData (tempString.String());
		return true;
	}

	if (secondWord == "JOIN")
	{
		BString nick (GetNick (data));
		BString channel (GetWord (data, 3));

		channel.RemoveFirst (":");
		ClientWindow *client (Client (channel.String()));

		if (nick == myNick)
		{
			if (!client)
			{
				client =  new ChannelWindow (
					channel.String(),
					sid,
					serverName.String(),
					sMsgr,
					myNick.String());

				clients.AddItem (client);
				client->Show();
			}
				
			BString tempString ("MODE ");
			tempString << channel;
			SendData (tempString.String());
		}
		else if (client)
		{
			// someone else
			BString ident (GetIdent (data));
			BString address (GetAddress (data));
			const char *expansions[3];
			BString tempString, addy;

			expansions[0] = nick.String();
			expansions[1] = ident.String();
			expansions[2] = address.String();

			tempString = ExpandKeyed (events[E_JOIN], "NIA", expansions);
			BMessage display (M_DISPLAY);
			PackDisplay (
				&display,
				tempString.String(),
				&joinColor,
				0,
				true);

			addy << ident << "@" << address;

			BMessage aMsg (M_IS_IGNORED), reply;
			bool ignored;

			aMsg.AddString ("server", serverName.String());
			aMsg.AddString ("nick", nick.String());
			aMsg.AddString ("address", addy.String());

			be_app_messenger.SendMessage (&aMsg, &reply);
			reply.FindBool ("ignored", &ignored);
			
			BMessage msg (M_USER_ADD);
			msg.AddString ("nick",  nick.String());
			msg.AddBool ("ignore", ignored);
			msg.AddMessage ("display", &display);
			client->PostMessage (&msg);
		}
		return true;
	}
	
	if (secondWord == "PART")
	{
		BString nick (GetNick (data));
		BString channel (GetWord (data, 3));
		ClientWindow *client;

		if ((client = Client (channel.String())) != 0)
		{
			BString ident (GetIdent (data));
			BString address (GetAddress (data));
			const char *expansions[3];
			BString buffer;

			expansions[0] = nick.String();
			expansions[1] = ident.String();
			expansions[2] = address.String();

			buffer = ExpandKeyed (events[E_PART], "NIA", expansions);

			BMessage display (M_DISPLAY);
			PackDisplay (&display, buffer.String(), &joinColor, 0, true);

			BMessage msg (M_USER_QUIT);
			msg.AddString ("nick", nick.String());
			msg.AddMessage ("display", &display);
			client->PostMessage (&msg);
		}

		return true;
	}
	
	if(secondWord == "PRIVMSG")
	{
		BString theNick (GetNick (data)),
			ident (GetIdent (data)),
			address (GetAddress (data)),
			addy;


		addy << ident << "@" << address;
		BMessage aMsg (M_IS_IGNORED), reply;
		bool ignored;

		aMsg.AddString ("server", serverName.String());
		aMsg.AddString ("nick", theNick.String());
		aMsg.AddString ("address", addy.String());

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

		if (ignored)
		{
			BMessage msg (M_IGNORED_PRIVMSG);
			const char *rule;

			reply.FindString ("rule", &rule);
			msg.AddString ("nick", theNick.String());
			msg.AddString ("address", addy.String());
			msg.AddString ("rule", rule);
			Broadcast (&msg);
			return true;
		}

		BString theTarget (GetWord (data, 3).ToUpper()),
		        theTargetOrig (GetWord (data, 3)),
		        theMsg (RestOfString (data, 4));
		ClientWindow *client (0);

		theMsg.RemoveFirst(":");

		if(theMsg[0] == '\1' && GetWord(theMsg.String(), 1) != "\1ACTION") // CTCP
		{
			ParseCTCP (theNick, theTargetOrig, theMsg);
			return true;
		}

		if (theTarget[0] == '#')
			client = Client (theTarget.String());
		else if (!(client = Client (theNick.String())))
		{
			BString ident = GetIdent(data);
			BString address = GetAddress(data);
			BString addyString;
			addyString << ident << "@" << address;

			client = new MessageWindow (
				theNick.String(),
				sid,
				serverName.String(),
				sMsgr,
				myNick.String(),
				addyString.String(),
				false, // not a dcc chat
				true); // initated by server

			clients.AddItem (client);
			client->Show();
		}

		if (client) client->ChannelMessage (
			theMsg.String(),
			theNick.String(),
			ident.String(),
			address.String());

		return true;
	}
	
	if (secondWord == "NICK")
	{
		BString oldNick (GetNick (data)),
		        ident (GetIdent (data)),
		        address (GetAddress (data)),
		        newNick (GetWord (data, 3)),
		        buffer;
		const char *expansions[4];

		newNick.RemoveFirst (":");

		expansions[0] = oldNick.String();
		expansions[1] = newNick.String();
		expansions[2] = ident.String();
		expansions[3] = address.String();

		buffer = ExpandKeyed (events[E_NICK], "NnIA", expansions);
		BMessage display (M_DISPLAY);
		PackDisplay (&display, buffer.String(), &nickColor, 0, bowser_app->GetStampState());

		BMessage msg (M_CHANGE_NICK);
		msg.AddString ("oldnick", oldNick.String());
		msg.AddString ("newnick", newNick.String());
		msg.AddString ("ident", ident.String());
		msg.AddString ("address", address.String());
		msg.AddMessage ("display", &display);

		Broadcast (&msg);

		// Gotta change the server as well!
		if (myNick.ICompare (oldNick) == 0)
		{
			myNick = newNick;
			status->SetItemValue (STATUS_NICK, newNick.String());
		}

		bowser_app->PostMessage (&msg); // for ignores

		return true;
	}

	if (secondWord == "QUIT")
	{
		BString theNick (GetNick (data).String()),
		        theRest (RestOfString (data, 3)),
		        ident (GetIdent (data)),
		        address (GetAddress (data)),
		        theMsg,
		        firstNick;
		const char *expansions[4];

		theRest.RemoveFirst (":");
		
		expansions[0] = theNick.String();
		expansions[1] = theRest.String();
		expansions[2] = ident.String();
		expansions[3] = address.String();

		theMsg = ExpandKeyed (events[E_QUIT], "NRIA", expansions);
		BMessage display (M_DISPLAY);
		PackDisplay (&display, theMsg.String(), &quitColor, 0, true);

		BMessage msg (M_USER_QUIT);
		msg.AddMessage ("display", &display);
		msg.AddString ("nick", theNick.String());

		Broadcast (&msg);
		
		// see if it was our first nickname. if so, change
		firstNick = (const char *)lnicks->ItemAt (0);
		if (theNick == firstNick)
		{
			BString tempCmd ("/nick ");
			tempCmd << firstNick;
			ParseCmd (tempCmd.String());
		}
				
		return true;
	}

	if (secondWord == "KICK")
	{
		BString kicker (GetNick (data)),
		        kickee (GetWord (data, 4)),
		        rest (RestOfString (data, 5)),
		        channel (GetWord (data, 3));
		ClientWindow *client (Client (channel.String()));

		rest.RemoveFirst (":");

		if ((client = Client (channel.String())) != 0
		&&   kickee == myNick)
		{
			BMessage display (M_DISPLAY); // "you were kicked"
			BString buffer;

			buffer << "*** You have been kicked from "
				<< channel << " by " << kicker << " (" << rest << ")\n";
			PackDisplay (&display, buffer.String(), &quitColor, 0, true);

			BMessage display2 (M_DISPLAY); // "attempting auto rejoin"
			buffer = "*** Attempting to automagically rejoin ";
			buffer << channel << "...\n";
			PackDisplay (&display2, buffer.String(), &quitColor, 0, true);
						

			BMessage msg (M_CHANNEL_GOT_KICKED);
			msg.AddString ("channel", channel.String());
			msg.AddMessage ("display", &display);  // "you were kicked"
			msg.AddMessage ("display2", &display2); // "attempting auto rejoin"
			client->PostMessage (&msg);
		}

		if (client && kickee != myNick)
		{
			BMessage display (M_DISPLAY);
			const char *expansions[4];
			BString buffer;

			expansions[0] = kickee.String();
			expansions[1] = channel.String();
			expansions[2] = kicker.String();
			expansions[3] = rest.String();

			buffer = ExpandKeyed (events[E_KICK], "NCnR", expansions);
			PackDisplay (&display, buffer.String(), &quitColor, 0, true);

			BMessage msg (M_USER_QUIT);
			msg.AddString ("nick", kickee.String());
			msg.AddMessage ("display", &display);
			client->PostMessage (&msg);
		}

		return true;
	}

	if(secondWord == "TOPIC")
	{
		BString theNick (GetNick (data)),
		        theChannel (GetWord (data, 3)),
		        theTopic (RestOfString (data, 4));
		ClientWindow *client (Client (theChannel.String()));

		theTopic.RemoveFirst (":");

		if (client && client->Lock())
		{
			BString ident (GetIdent (data));
			BString address (GetAddress (data));
			const char *expansions[5];
			BString buffer;

			expansions[0] = theNick.String();
			expansions[1] = theTopic.String();
			expansions[2] = client->Id().String();
			expansions[3] = ident.String();
			expansions[4] = address.String();

			if(bowser_app->GetShowTopicState())
			{
				buffer << client->Id() << " : " << theTopic;
				client->SetTitle (buffer.String());
				client->Unlock();
			}
			else
			{
				buffer << client->Id();
				client->SetTitle (buffer.String());
				client->Unlock();
			}
			
			BMessage topic (M_CHANNEL_TOPIC);
			
			topic.AddString("topic", theTopic.String());
						
			BMessage display (M_DISPLAY);

			buffer = ExpandKeyed (events[E_TOPIC], "NTCIA", expansions);
			PackDisplay (&display, buffer.String(), &whoisColor, 0, true);
			topic.AddMessage("display", &display);
			client->PostMessage (&topic);
		}
		return true;
	}

	if (secondWord == "MODE")
	{
		BString theNick (GetNick (data)),
		        theChannel (GetWord (data, 3)),
		        theMode (GetWord (data, 4)),
		        theTarget (RestOfString (data, 5));
		ClientWindow *client (Client (theChannel.String()));

		if (client)
		{
			BMessage msg (M_CHANNEL_MODE);

			msg.AddString("nick", theNick.String());
			msg.AddString("mode", theMode.String());
			msg.AddString("target", theTarget.String());

			client->PostMessage (&msg);
		}
		else
		{
			BMessage msg (M_DISPLAY);
			BString buffer;
			
			theMode.RemoveFirst(":");
	
			buffer << "*** User mode changed: " << theMode << "\n";
			PackDisplay (&msg, buffer.String(), 0, 0, true);

			PostActive (&msg);
		}

		return true;
	}

	if(firstWord == "NOTICE") // _server_ notice
	{
		BString theNotice (RestOfString(data, 3));
		const char *expansions[1];

		theNotice.RemoveFirst(":");

		expansions[0] = theNotice.String();
		theNotice = ExpandKeyed (events[E_SNOTICE], "R", expansions);
		Display (theNotice.String(), 0, 0, true);

		return true;
	}

	if (firstWord == "ERROR") // server error (on connect?)
	{
		BString theError (RestOfString (data, 2));

		theError.RemoveAll (":");
		theError.Append ("\n");

		Display (theError.String(), &quitColor);
		isConnecting = false;
		return true;
	}

	if(secondWord == "NOTICE") // _user_ notice
	{
		BString theNick (GetNick (data)),
			ident (GetIdent (data)),
			address (GetAddress (data)),
			addy;

		addy << theNick << "@" << address;

		BMessage aMsg (M_IS_IGNORED), reply;
		bool ignored;

		aMsg.AddString ("server", serverName.String());
		aMsg.AddString ("nick", theNick.String());
		aMsg.AddString ("address", addy.String());

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

		if (ignored) return true;

		BString theNotice = RestOfString(data, 4);

		theNotice.RemoveFirst(":");

		if(theNotice[0] == '\1')
		{
			ParseCTCPResponse(theNick, theNotice);
			return true;
		}

		const char *expansions[4];
		BString tempString;

		expansions[0] = theNick.String();
		expansions[1] = theNotice.String();
		expansions[2] = ident.String();
		expansions[3] = address.String();

		tempString = ExpandKeyed (events[E_UNOTICE], "NRIA", expansions);
		BMessage display (M_DISPLAY);
		PackDisplay (&display, tempString.String(), &noticeColor, 0, true);
		PostActive (&display);
		return true;
	}

	return ParseENums (data, secondWord.String());
}
Example #10
0
BString
BHttpForm::RawData() const
{
	BString result;

	if (fType == B_HTTP_FORM_URL_ENCODED) {
		for (FormStorage::const_iterator it = fFields.begin();
			it != fFields.end(); it++) {
			const BHttpFormData* currentField = &it->second;

			switch (currentField->Type()) {
				case B_HTTPFORM_UNKNOWN:
					break;

				case B_HTTPFORM_STRING:
					result << '&' << BUrl::UrlEncode(currentField->Name())
						<< '=' << BUrl::UrlEncode(currentField->String());
					break;

				case B_HTTPFORM_FILE:
					break;

				case B_HTTPFORM_BUFFER:
					// Send the buffer only if its not marked as a file
					if (!currentField->IsFile()) {
						result << '&' << BUrl::UrlEncode(currentField->Name())
							<< '=';
						result.Append(
							reinterpret_cast<const char*>(currentField->Buffer()),
							currentField->BufferSize());
					}
					break;
			}
		}

		result.Remove(0, 1);
	} else if (fType == B_HTTP_FORM_MULTIPART) {
		//  Very slow and memory consuming method since we're caching the
		// file content, this should be preferably handled by the protocol
		for (FormStorage::const_iterator it = fFields.begin();
			it != fFields.end(); it++) {
			const BHttpFormData* currentField = &it->second;
			result << _GetMultipartHeader(currentField);

			switch (currentField->Type()) {
				case B_HTTPFORM_UNKNOWN:
					break;

				case B_HTTPFORM_STRING:
					result << currentField->String();
					break;

				case B_HTTPFORM_FILE:
				{
					BFile upFile(currentField->File().Path(), B_READ_ONLY);
					char readBuffer[1024];
					ssize_t readSize;

					readSize = upFile.Read(readBuffer, 1024);

					while (readSize > 0) {
						result.Append(readBuffer, readSize);
						readSize = upFile.Read(readBuffer, 1024);
					}
					break;
				}

				case B_HTTPFORM_BUFFER:
					result.Append(
						reinterpret_cast<const char*>(currentField->Buffer()),
						currentField->BufferSize());
					break;
			}

			result << "\r\n";
		}

		result << "--" << fMultipartBoundary << "--\r\n";
	}

	return result;
}
void
NotificationView::SetText(float newMaxWidth)
{
	if (newMaxWidth < 0 && Parent())
		newMaxWidth = Parent()->Bounds().IntegerWidth();
	if (newMaxWidth <= 0)
		newMaxWidth = kDefaultWidth;

	// Delete old lines
	LineInfoList::iterator lIt;
	for (lIt = fLines.begin(); lIt != fLines.end(); lIt++)
		delete (*lIt);
	fLines.clear();

	float iconRight = kIconStripeWidth;
	if (fBitmap != NULL)
		iconRight += fParent->IconSize();
	else
		iconRight += 32;

	font_height fh;
	be_bold_font->GetHeight(&fh);
	float fontHeight = ceilf(fh.leading) + ceilf(fh.descent)
		+ ceilf(fh.ascent);
	float y = 2 * fontHeight;

	// Title
	LineInfo* titleLine = new LineInfo;
	titleLine->text = fNotification->Title();
	titleLine->font = *be_bold_font;

	titleLine->location = BPoint(iconRight + kEdgePadding, y);

	fLines.push_front(titleLine);
	y += fontHeight;

	// Rest of text is rendered with be_plain_font.
	be_plain_font->GetHeight(&fh);
	fontHeight = ceilf(fh.leading) + ceilf(fh.descent)
		+ ceilf(fh.ascent);

	// Split text into chunks between certain characters and compose the lines.
	const char kSeparatorCharacters[] = " \n-\\";
	BString textBuffer = fNotification->Content();
	textBuffer.ReplaceAll("\t", "    ");
	const char* chunkStart = textBuffer.String();
	float maxWidth = newMaxWidth - kEdgePadding - iconRight;
	LineInfo* line = NULL;
	ssize_t length = textBuffer.Length();
	while (chunkStart - textBuffer.String() < length) {
		size_t chunkLength = strcspn(chunkStart, kSeparatorCharacters) + 1;

		// Start a new line if we didn't start one before
		BString tempText;
		if (line != NULL)
			tempText.SetTo(line->text);
		tempText.Append(chunkStart, chunkLength);

		if (line == NULL || chunkStart[0] == '\n'
			|| StringWidth(tempText) > maxWidth) {
			line = new LineInfo;
			line->font = *be_plain_font;
			line->location = BPoint(iconRight + kEdgePadding, y);

			fLines.push_front(line);
			y += fontHeight;

			// Skip the eventual new-line character at the beginning of this chunk
			if (chunkStart[0] == '\n') {
				chunkStart++;
				chunkLength--;
			}

			// Skip more new-line characters and move the line further down
			while (chunkStart[0] == '\n') {
				chunkStart++;
				chunkLength--;
				line->location.y += fontHeight;
				y += fontHeight;
			}

			// Strip space at beginning of a new line
			while (chunkStart[0] == ' ') {
				chunkLength--;
				chunkStart++;
			}
		}

		if (chunkStart[0] == '\0')
			break;

		// Append the chunk to the current line, which was either a new
		// line or the one from the previous iteration
		line->text.Append(chunkStart, chunkLength);

		chunkStart += chunkLength;
	}

	fHeight = y + (kEdgePadding * 2);

	// Make sure icon fits
	if (fBitmap != NULL) {
		float minHeight = fBitmap->Bounds().Height() + 2 * kEdgePadding;

		if (fHeight < minHeight)
			fHeight = minHeight;
	}

	// Make sure the progress bar is below the text, and the window is big
	// enough.
	static_cast<BGroupLayout*>(GetLayout())->SetInsets(kIconStripeWidth + 8,
		fHeight, 8, 8);

	_CalculateSize();
}
bool
fetchStr(const char *&in, BString &str, bool lookForID)
{
	int parLevel = 0;

	while (isspace(*in) || *in == '(') {
		if (*in == '(')
			parLevel++;
		in++;
	}

	if (*in == '"') {
		bool inString = true;
		bool quoted = false;
		in++;
		while (parLevel >= 0 && inString)
		{
			// Collect string content until we find a quote marking end of
			// string (skip escaped quotes)
			while (*in != '"' || quoted)
			{
				str.Append(in,1);
				if (*in == '\\' && !quoted)
					quoted = true;
				else
					quoted = false;
				in++;
			}
			in++;

			inString = false;

			// Strip all whitespace until we find a closing parenthesis, or the
			// beginning of another string
			while (isspace(*in) || *in == ')') {
				if (*in == ')') {
					if (parLevel == 0)
						return true;
					parLevel--;
				}

				in++;
			}

			if (*in == '"') {
				inString = true;
				in++;
			}
		}
	} else {
		if (!memcmp(in, "__null", 6)) {
			// NULL is preprocessed into __null, which we parse as ""
			in += 6;
		} else if (lookForID && (isdigit(*in) || *in == '-' || *in == '+')) {
			// try to parse an ID (a long):
			errno = 0;
			char *next;
			id = strtol(in, &next, 10);
			if (id != 0 || errno == 0) {
				haveID = true;
				in = next;
			}
		} else
			return false;

		while (isspace(*in) || *in == ')') {
			if (*in == ')') {
				if (!parLevel)
					return true;
				parLevel--;
			}
			in++;
		}
	}
	return true;
}
status_t
OptiPNGTranslator::DerivedTranslate(BPositionIO *source,
	const translator_info *info, BMessage *ioExtension,
	uint32 outType, BPositionIO *target, int32 baseType)
{
	if(baseType == 1 && outType == OPTIPNG_PNG_FORMAT) {
		// create temp file
		int tempFileFD;
		BPath tempDir;
		BString tempFilePath;
		if(find_directory(B_SYSTEM_TEMP_DIRECTORY, &tempDir) != B_OK )
			return B_ERROR;
		
		tempFilePath.Append(tempDir.Path())
			.Append("/OptiPNGTranslator.XXXXXX");
		
		tempFileFD = mkstemp(tempFilePath.LockBuffer(0));
		tempFilePath.UnlockBuffer();
		
		if(tempFileFD == -1)
			return B_ERROR;
		close(tempFileFD);
		
		BFile tempFile = BFile(tempFilePath, O_WRONLY);
		
		// write PNG to file
		off_t sourceSize;
		source->GetSize(&sourceSize);
		unsigned char sourceChars[sourceSize];
		
		BTranslatorRoster *roster = BTranslatorRoster::Default();
		roster->Translate(source, NULL, NULL, &tempFile, (uint32)B_PNG_FORMAT);
		
		// optimize file
		BString optipng;
		if(system("optipng &> /dev/null") == 0) {
			optipng = "optipng";
		} else if(system("optipng-x86 &> /dev/null") == 0) {
			optipng = "optipng-x86";
		} else {
			return B_ERROR;
		}
		
		// optipng -clobber -out (file) (file)
		BString command;
		command = optipng;
		if(!fSettings->SetGetBool(OPTIPNG_SETTING_BIT_DEPTH_REDUCTION))
			command += " -nb"; // no bit-depth reduction
		if(!fSettings->SetGetBool(OPTIPNG_SETTING_COLOR_TYPE_REDUCTION))
			command += " -nc";
		if(!fSettings->SetGetBool(OPTIPNG_SETTING_PALETTE_REDUCTION))
			command += " -np";
		
		command.Append(" -o")
			.Append((char)(fSettings->
				SetGetInt32(OPTIPNG_SETTING_OPTIMIZATION_LEVEL)+'0'),1);
		// rest of command
		command.Append(" -clobber -out ")
			.Append(tempFilePath)
			.Append(" ")
			.Append(tempFilePath)
		;
		
		if(system(command) != 0) {
			return B_ERROR;
		}
		
		// read the file
		tempFile = BFile(tempFilePath, O_RDONLY);
		
		off_t fileSize;
		tempFile.GetSize(&fileSize);
		unsigned char *buffer;
		
		buffer = new unsigned char[fileSize];
		if(buffer == NULL)
			return B_ERROR;
		tempFile.ReadAt(0, buffer, fileSize);
		target->Write(buffer, fileSize);
		delete [] buffer;
		
		// delete the file
		BEntry entry = BEntry(tempFilePath);
		entry.Remove();
		
		return B_OK;
	}
	return B_NO_TRANSLATOR;
}
Example #14
0
const char* VersionControl::GetToolVersion(const char* path)
{
	thread_id thread;
	int in, out, err;
	const char** argv;
	int argc = 0;
	const char* threadname = "Helios:GetToolVersion()";
	char buffer[1000];
	size_t bytesread;
	BString version = "";

	buffer[0] = 0;
	argv = (const char**)malloc(sizeof(char*) * (5));
	argv[argc++] = strdup(path);
	argv[argc++] = strdup("--version");
	argv[argc] = NULL;

	thread = pipe_command(argc, argv, in, out, err);
	rename_thread(thread, threadname);
	resume_thread(thread);

	while ((bytesread = read(err, (void*)buffer, 1000)) > 0) {
		buffer[bytesread] = 0;
		version.Append(buffer);
		// printf("%s: %s\n",path, buffer);
		snooze(10000);
	}
	while ((bytesread = read(out, (void*)buffer, 1000)) > 0) {
		buffer[bytesread] = 0;
		version.Append(buffer);
		// printf("%s: %s\n",path, buffer);
		snooze(10000);
	}

	free(argv);
	close(in);
	close(out);
	close(err);

	char str[1024];
	int32 length = 1024;
	int32 state = 0;
	int32 srclen = version.Length();
	convert_to_utf8(B_ISO1_CONVERSION, version.String(), &srclen, str, &length, &state);

	str[length] = 0;
	version = str;

	// --version option not supported?
	if (version.FindFirst("--version") != B_ERROR) {
		version = path;
		version << ": "
				<< _T("(could not get version info)"); // "STR:(could not get version info)"
	} else {
		version.RemoveAll("\n");
		version.RemoveAll("\t");
		// for case-insensitivity replace instead of remove...
		version.IReplaceAll("Copyright ", "");
		version.IReplaceAll("(c) ", B_UTF8_COPYRIGHT);
		version.IReplaceAll("(c)", B_UTF8_COPYRIGHT);
	}
	return strdup(version.String());
}
filter_result ClientAgentInputFilter::Filter(BMessage* msg, BHandler** target)
{
	filter_result result(B_DISPATCH_MESSAGE);
	switch (msg->what) {
	case B_MOUSE_MOVED:
		break;

	case B_COPY: {
		int32 start, finish;
		fWindow->fInput->TextView()->GetSelection(&start, &finish);
		if (start == finish) *target = fWindow->fText;
	} break;

	case B_SELECT_ALL: {
		if (fWindow->fInput->TextView()->TextLength() == 0) *target = fWindow->fText;
	} break;

	case B_KEY_DOWN: {
		result = HandleKeys(msg);
	} break;

	case B_MOUSE_UP: {
		if (fHandledDrop) {
			fHandledDrop = false;
			result = B_SKIP_MESSAGE;
		}
	} break;

	case B_MIME_TYPE: {
		if (msg->HasData("text/plain", B_MIME_TYPE)) {
			const char* buffer;
			ssize_t size;

			msg->FindData("text/plain", B_MIME_TYPE, 0, reinterpret_cast<const void**>(&buffer),
						  &size);

			// We copy it, because B_MIME_TYPE
			// might not be \0 terminated

			BString string;

			string.Append(buffer, size);
			HandleDrop(string.String());

			fHandledDrop = true;
			result = B_SKIP_MESSAGE;
		}
	} break;

	case B_SIMPLE_DATA: {
		if (msg->HasRef("refs")) {
			for (int32 i = 0; msg->HasRef("refs", i); ++i) {
				entry_ref ref;

				msg->FindRef("refs", &ref);

				char mime[B_MIME_TYPE_LENGTH];
				BFile file(&ref, B_READ_ONLY);
				BNodeInfo info(&file);
				off_t size;

				if (file.InitCheck() == B_NO_ERROR && file.GetSize(&size) == B_NO_ERROR &&
					info.InitCheck() == B_NO_ERROR && info.GetType(mime) == B_NO_ERROR &&
					strncasecmp(mime, "text/", 5) == 0) {
					char* buffer(new char[size + 1]);

					if (buffer) {
						// Oh baby!
						file.Read(buffer, size);
						buffer[size] = 0;

						HandleDrop(buffer);
						delete[] buffer;
						break;
					}
				}
			}

			// Give the fWindow a chance to handle non
			// text files.  If it's a message window, it'll
			// kick off a dcc send
			fWindow->DroppedFile(msg);
		}
	} break;

	case B_PASTE: {
		// we have our own pasting code so we can catch multiple lines
		BClipboard clipboard("system");
		const char* fText;
		ssize_t textLen;
		BMessage* clip((BMessage*)NULL);

		if (clipboard.Lock()) {
			if ((clip = clipboard.Data()))
				if (clip->FindData("text/plain", B_MIME_TYPE, (const void**)&fText, &textLen) !=
					B_OK) {
					clipboard.Unlock();
					break;
				}
		}

		clipboard.Unlock();
		BString data(fText, textLen);
		HandleDrop(data.String());
		result = B_SKIP_MESSAGE;
	} break;

	case B_MOUSE_WHEEL_CHANGED: {
		// pass this msg to IRCView
		fWindow->fText->MessageReceived(msg);
		result = B_SKIP_MESSAGE;
	} break;

	default: {
		// printf ("FILTER UNHANDLED: ");
		// msg->PrintToStream();
	}

	break;
	}

	return result;
}
Example #16
0
BView*
AboutView::_CreateCreditsView()
{
	// Begin construction of the credits view
	fCreditsView = new HyperTextView("credits");
	fCreditsView->SetFlags(fCreditsView->Flags() | B_FRAME_EVENTS);
	fCreditsView->SetStylable(true);
	fCreditsView->MakeEditable(false);
	fCreditsView->SetWordWrap(true);
	fCreditsView->SetInsets(5, 5, 5, 5);
	fCreditsView->SetViewColor(ui_color(B_DOCUMENT_BACKGROUND_COLOR));

	BScrollView* creditsScroller = new BScrollView("creditsScroller",
		fCreditsView, B_WILL_DRAW | B_FRAME_EVENTS, false, true,
		B_PLAIN_BORDER);

	// Haiku copyright
	BFont font(be_bold_font);
	font.SetSize(font.Size() + 4);

	fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuGreen);
	fCreditsView->Insert("Haiku\n");

	char string[1024];
	time_t time = ::time(NULL);
	struct tm* tm = localtime(&time);
	int32 year = tm->tm_year + 1900;
	if (year < 2008)
		year = 2008;
	snprintf(string, sizeof(string),
		COPYRIGHT_STRING "2001-%ld The Haiku project. ", year);

	fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey);
	fCreditsView->Insert(string);

	fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey);
	fCreditsView->Insert(B_TRANSLATE("The copyright to the Haiku code is "
		"property of Haiku, Inc. or of the respective authors where expressly "
		"noted in the source. Haiku" B_UTF8_REGISTERED
		" and the HAIKU logo" B_UTF8_REGISTERED
		" are registered trademarks of Haiku, Inc."
		"\n\n"));

	fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kLinkBlue);
	fCreditsView->InsertHyperText("http://www.haiku-os.org",
		new URLAction("http://www.haiku-os.org"));
	fCreditsView->Insert("\n\n");

	font.SetSize(be_bold_font->Size());
	font.SetFace(B_BOLD_FACE | B_ITALIC_FACE);

	fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuOrange);
	fCreditsView->Insert(B_TRANSLATE("Current maintainers:\n"));

	fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey);
	fCreditsView->Insert(
		"Ithamar R. Adema\n"
		"Bruno G. Albuquerque\n"
		"Stephan Aßmus\n"
		"Salvatore Benedetto\n"
		"Stefano Ceccherini\n"
		"Rudolf Cornelissen\n"
		"Alexandre Deckner\n"
		"Adrien Destugues\n"
		"Oliver Ruiz Dorantes\n"
		"Axel Dörfler\n"
		"Jérôme Duval\n"
		"René Gollent\n"
		"Bryce Groff\n"
		"Colin Günther\n"
		"Karsten Heimrich\n"
		"Fredrik Holmqvist\n"
		"Philippe Houdoin\n"
		"Maurice Kalinowski\n"
		"Euan Kirkhope\n"
		"Ryan Leavengood\n"
		"Michael Lotz\n"
		"Brecht Machiels\n"
		"Matt Madia\n"
		"Scott McCreary\n"
		"David McPaul\n"
		"Wim van der Meer\n"
		"Fredrik Modéen\n"
		"Marcus Overhagen\n"
		"Michael Pfeiffer\n"
		"François Revol\n"
		"Philippe Saint-Pierre\n"
		"John Scipione\n"
		"Andrej Spielmann\n"
		"Jonas Sundström\n"
		"Oliver Tappe\n"
		"Gerasim Troeglazov\n"
		"Alexander von Gluck IV\n"
		"Ingo Weinhold\n"
		"Alex Wilson\n"
		"Artur Wyszyński\n"
		"Clemens Zeidler\n"
		"Siarzhuk Zharski\n"
		"\n");

	fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuOrange);
	fCreditsView->Insert(B_TRANSLATE("Past maintainers:\n"));

	fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey);
	fCreditsView->Insert(
		"Andrew Bachmann\n"
		"Tyler Dauwalder\n"
		"Daniel Furrer\n"
		"Andre Alves Garzia\n"
		"Erik Jaesler\n"
		"Marcin Konicki\n"
		"Waldemar Kornewald\n"
		"Thomas Kurschel\n"
		"Frans Van Nispen\n"
		"Adi Oanca\n"
		"Michael Phipps\n"
		"Niels Sascha Reedijk\n"
		"David Reid\n"
		"Hugo Santos\n"
		"Alexander G. M. Smith\n"
		"Bryan Varner\n"
		"Nathan Whitehorn\n"
		"Michael Wilber\n"
		"Jonathan Yoder\n"
		"Gabe Yoder\n"
		"\n");

	fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuOrange);
	fCreditsView->Insert(B_TRANSLATE("Website, marketing & documentation:\n"));

	fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey);
	fCreditsView->Insert(
		"Phil Greenway\n"
		"Gavin James\n"
		"Urias McCullough\n"
		"Niels Sascha Reedijk\n"
		"Joachim Seemer (Humdinger)\n"
		"Jonathan Yoder\n"
		"\n");

	fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuOrange);
	fCreditsView->Insert(B_TRANSLATE("Contributors:\n"));

	fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey);
	fCreditsView->Insert(
		"Andrea Anzani\n"
		"Sean Bartell\n"
		"Andre Braga\n"
		"Michael Bulash\n"
		"Bruce Cameron\n"
		"Jean-Loïc Charroud\n"
		"Greg Crain\n"
		"Michael Davidson\n"
		"David Dengg\n"
		"John Drinkwater\n"
		"Cian Duffy\n"
		"Vincent Duvert\n"
		"Mikael Eiman\n"
		"Fredrik Ekdahl\n"
		"Joshua R. Elsasser\n"
		"Atis Elsts\n"
		"Mark Erben\n"
		"Christian Fasshauer\n"
		"Andreas Färber\n"
		"Janito Ferreira Filho\n"
		"Pier Luigi Fiorini\n"
		"Marc Flerackers\n"
		"Michele Frau (zuMi)\n"
		"Deyan Genovski\n"
		"Pete Goodeve\n"
		"Lucian Adrian Grijincu\n"
		"Sean Healy\n"
		"Matthijs Hollemans\n"
		"Mathew Hounsell\n"
		"Morgan Howe\n"
		"Christophe Huriaux\n"
		"Jian Jiang\n"
		"Ma Jie\n"
		"Carwyn Jones\n"
		"Vasilis Kaoutsis\n"
		"James Kim\n"
		"Shintaro Kinugawa\n"
		"Jan Klötzke\n"
		"Kurtis Kopf\n"
		"Tomáš Kučera\n"
		"Luboš Kulič\n"
		"Elad Lahav\n"
		"Anthony Lee\n"
		"Santiago Lema\n"
		"Raynald Lesieur\n"
		"Oscar Lesta\n"
		"Jerome Leveque\n"
		"Brian Luft\n"
		"Christof Lutteroth\n"
		"Graham MacDonald\n"
		"Jorge G. Mare (Koki)\n"
		"Jan Matějek\n"
		"Brian Matzon\n"
		"Christopher ML Zumwalt May\n"
		"Andrew McCall\n"
		"Nathan Mentley\n"
		"Marius Middelthon\n"
		"Marco Minutoli\n"
		"Misza\n"
		"Hamish Morrison\n"
		"MrSiggler\n"
		"Takashi Murai\n"
		"Alan Murta\n"
		"Raghuram Nagireddy\n"
		"Kazuho Okui\n"
		"Jeroen Oortwijn (idefix)\n"
		"Pahtz\n"
		"Michael Paine\n"
		"Adrian Panasiuk\n"
		"Romain Picard\n"
		"Francesco Piccinno\n"
		"David Powell\n"
		"Jeremy Rand\n"
		"Hartmut Reh\n"
		"Daniel Reinhold\n"
		"Chris Roberts\n"
		"Samuel Rodríguez Pérez\n"
		"Thomas Roell\n"
		"Rafael Romo\n"
		"Ralf Schülke\n"
		"Reznikov Sergei\n"
		"Zousar Shaker\n"
		"Caitlin Shaw\n"
		"Geoffry Song\n"
		"Daniel Switkin\n"
		"Atsushi Takamatsu\n"
		"James Urquhart\n"
		"Jason Vandermark\n"
		"Sandor Vroemisse\n"
		"Denis Washington\n"
		"Ulrich Wimboeck\n"
		"Johannes Wischert\n"
		"James Woodcock\n"
		"Hong Yul Yang\n"
		"Gerald Zajac\n"
		"Łukasz Zemczak\n"
		"JiSheng Zhang\n"
		"Zhao Shuai\n");
	fCreditsView->Insert(
		B_TRANSLATE("\n" B_UTF8_ELLIPSIS
			" and probably some more we forgot to mention (sorry!)"
			"\n\n"));

	fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuOrange);
	fCreditsView->Insert(B_TRANSLATE("Translations:\n"));

	BLanguage* lang;
	BString langName;

	BList sortedTranslations;
	for (uint32 i = 0; i < kNumberOfTranslations; i ++) {
		const Translation* translation = &gTranslations[i];
		sortedTranslations.AddItem((void*)translation);
	}
	sortedTranslations.SortItems(TranslationComparator);

	for (uint32 i = 0; i < kNumberOfTranslations; i ++) {
		const Translation& translation
			= *(const Translation*)sortedTranslations.ItemAt(i);

		langName.Truncate(0);
		if (BLocaleRoster::Default()->GetLanguage(translation.languageCode,
				&lang) == B_OK) {
			lang->GetName(langName);
			delete lang;
		} else {
			// We failed to get the localized readable name,
			// go with what we have.
			langName.Append(translation.languageCode);
		}

		fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuGreen);
		fCreditsView->Insert("\n");
		fCreditsView->Insert(langName);
		fCreditsView->Insert("\n");
		fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey);
		fCreditsView->Insert(translation.names);
	}

	fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuOrange);
	fCreditsView->Insert(B_TRANSLATE("\n\nSpecial thanks to:\n"));

	fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey);
	BString beosCredits(B_TRANSLATE(
		"Be Inc. and its developer team, for having created BeOS!\n\n"));
	int32 beosOffset = beosCredits.FindFirst("BeOS");
	fCreditsView->Insert(beosCredits.String(),
		(beosOffset < 0) ? beosCredits.Length() : beosOffset);
	if (beosOffset > -1) {
		fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kBeOSBlue);
		fCreditsView->Insert("B");
		fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kBeOSRed);
		fCreditsView->Insert("e");
		fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey);
		beosCredits.Remove(0, beosOffset + 2);
		fCreditsView->Insert(beosCredits.String(), beosCredits.Length());
	}
	fCreditsView->Insert(
		B_TRANSLATE("Travis Geiselbrecht (and his NewOS kernel)\n"));
	fCreditsView->Insert(
		B_TRANSLATE("Michael Phipps (project founder)\n\n"));
	fCreditsView->Insert(
		B_TRANSLATE("The Haiku-Ports team\n"));
	fCreditsView->Insert(
		B_TRANSLATE("The Haikuware team and their bounty program\n"));
	fCreditsView->Insert(
		B_TRANSLATE("The BeGeistert team\n"));
	fCreditsView->Insert(
		B_TRANSLATE("Google & their Google Summer of Code program\n"));
	fCreditsView->Insert(
		B_TRANSLATE("The University of Auckland and Christof Lutteroth\n\n"));
	fCreditsView->Insert(
		B_TRANSLATE("... and the many people making donations!\n\n"));

	// copyrights for various projects we use

	BPath mitPath;
	_GetLicensePath("MIT", mitPath);
	BPath lgplPath;
	_GetLicensePath("GNU LGPL v2.1", lgplPath);

	font.SetSize(be_bold_font->Size() + 4);
	font.SetFace(B_BOLD_FACE);
	fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuGreen);
	fCreditsView->Insert(B_TRANSLATE("\nCopyrights\n\n"));

	fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey);
	fCreditsView->Insert(B_TRANSLATE("[Click a license name to read the "
		"respective license.]\n\n"));

	// Haiku license
	BString haikuLicense = B_TRANSLATE_COMMENT("The code that is unique to "
		"Haiku, especially the kernel and all code that applications may link "
		"against, is distributed under the terms of the <MIT license>. "
		"Some system libraries contain third party code distributed under the "
		"<LGPL license>. You can find the copyrights to third party code below."
		"\n\n", "<MIT license> and <LGPL license> aren't variables and can be "
		"translated. However, please, don't remove < and > as they're needed "
		"as placeholders for proper hypertext functionality.");
	int32 licensePart1 = haikuLicense.FindFirst("<");
	int32 licensePart2 = haikuLicense.FindFirst(">");
	int32 licensePart3 = haikuLicense.FindLast("<");
	int32 licensePart4 = haikuLicense.FindLast(">");
	BString part;
	haikuLicense.CopyInto(part, 0, licensePart1);
	fCreditsView->Insert(part);

	part.Truncate(0);
	haikuLicense.CopyInto(part, licensePart1 + 1, licensePart2 - 1
		- licensePart1);
	fCreditsView->InsertHyperText(part, new OpenFileAction(mitPath.Path()));

	part.Truncate(0);
	haikuLicense.CopyInto(part, licensePart2 + 1, licensePart3 - 1
		- licensePart2);
	fCreditsView->Insert(part);

	part.Truncate(0);
	haikuLicense.CopyInto(part, licensePart3 + 1, licensePart4 - 1
		- licensePart3);
	fCreditsView->InsertHyperText(part, new OpenFileAction(lgplPath.Path()));

	part.Truncate(0);
	haikuLicense.CopyInto(part, licensePart4 + 1, haikuLicense.Length() - 1
		- licensePart4);
	fCreditsView->Insert(part);

	// GNU copyrights
	AddCopyrightEntry("The GNU Project",
		B_TRANSLATE("Contains software from the GNU Project, "
		"released under the GPL and LGPL licenses:\n"
		"GNU C Library, "
		"GNU coretools, diffutils, findutils, "
		"sharutils, gawk, bison, m4, make, "
		"gdb, wget, ncurses, termcap, "
		"Bourne Again Shell.\n"
		COPYRIGHT_STRING "The Free Software Foundation."),
		StringVector("GNU LGPL v2.1", "GNU GPL v2", "GNU GPL v3", NULL),
		StringVector(),
		"http://www.gnu.org");

	// FreeBSD copyrights
	AddCopyrightEntry("The FreeBSD Project",
		B_TRANSLATE("Contains software from the FreeBSD Project, "
		"released under the BSD license:\n"
		"cal, ftpd, ping, telnet, "
		"telnetd, traceroute\n"
		COPYRIGHT_STRING "1994-2008 The FreeBSD Project. "
		"All rights reserved."),
		StringVector("BSD (2-clause)", "BSD (3-clause)", "BSD (4-clause)",
			NULL),
		StringVector(),
		"http://www.freebsd.org");

	// NetBSD copyrights
	AddCopyrightEntry("The NetBSD Project",
		B_TRANSLATE("Contains software developed by the NetBSD "
		"Foundation, Inc. and its contributors:\n"
		"ftp, tput\n"
		COPYRIGHT_STRING "1996-2008 The NetBSD Foundation, Inc. "
		"All rights reserved."),
		"http://www.netbsd.org");
			// TODO: License!

	// FFMpeg copyrights
	_AddPackageCredit(PackageCredit("FFMpeg libavcodec")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2000-2007 Fabrice "
			"Bellard, et al."))
		.SetLicenses("GNU LGPL v2.1", "GNU LGPL v2", NULL)
		.SetURL("http://www.ffmpeg.org"));

	// AGG copyrights
	_AddPackageCredit(PackageCredit("AntiGrain Geometry")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2002-2006 Maxim "
			"Shemanarev (McSeem)."))
		.SetLicenses("Anti-Grain Geometry", B_TRANSLATE("BSD (3-clause)"),
			"GPC", NULL)
		.SetURL("http://www.antigrain.com"));

	// PDFLib copyrights
	_AddPackageCredit(PackageCredit("PDFLib")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1997-2006 PDFlib GmbH and "
			"Thomas Merz. All rights reserved.\n"
			"PDFlib and PDFlib logo are registered trademarks of PDFlib GmbH."))
		.SetLicense("PDFlib Lite")
		.SetURL("http://www.pdflib.com"));

	// FreeType copyrights
	_AddPackageCredit(PackageCredit("FreeType2")
		.SetCopyright(B_TRANSLATE("Portions of this software are under "
			"copyright.\n"
			COPYRIGHT_STRING "1996-2006 "
			"The FreeType Project. All rights reserved."))
		.SetLicense("FTL")
		.SetURL("http://www.freetype.org"));

	// Mesa3D (http://www.mesa3d.org) copyrights
	_AddPackageCredit(PackageCredit("Mesa")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1999-2006 Brian Paul. "
			"Mesa3D Project. All rights reserved."))
		.SetLicense("MIT")
		.SetURL("http://www.mesa3d.org"));

	// SGI's GLU implementation copyrights
	_AddPackageCredit(PackageCredit("GLU")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1991-2000 "
			"Silicon Graphics, Inc. All rights reserved."))
		.SetLicense("SGI Free B")
		.SetURL("http://www.sgi.com/products/software/opengl"));

	// GLUT implementation copyrights
	_AddPackageCredit(PackageCredit("GLUT")
		.SetCopyrights(B_TRANSLATE(COPYRIGHT_STRING "1994-1997 Mark Kilgard. "
			"All rights reserved."),
			COPYRIGHT_STRING "1997 Be Inc.",
			COPYRIGHT_STRING "1999 Jake Hamby.",
			NULL)
		.SetLicense("GLUT (Mark Kilgard)")
		.SetURL("http://www.opengl.org/resources/libraries/glut"));

	// OpenGroup & DEC (BRegion backend) copyright
	_AddPackageCredit(PackageCredit("BRegion backend (XFree86)")
		.SetCopyrights(COPYRIGHT_STRING "1987-1988, 1998 The Open Group.",
			B_TRANSLATE(COPYRIGHT_STRING "1987-1988 Digital Equipment "
			"Corporation, Maynard, Massachusetts.\n"
			"All rights reserved."),
			NULL)
		.SetLicenses("OpenGroup", "DEC", NULL));
			// TODO: URL

	// VL-Gothic font
	_AddPackageCredit(PackageCredit("VL-Gothic font")
		.SetCopyrights(B_TRANSLATE(COPYRIGHT_STRING "1990-2003 Wada Laboratory,"
			" the University of Tokyo."), COPYRIGHT_STRING
			"2003-2004 Electronic Font Open Laboratory (/efont/).",
			COPYRIGHT_STRING "2003-2008 M+ FONTS PROJECT.",
			COPYRIGHT_STRING "2006-2009 Daisuke SUZUKI.",
			COPYRIGHT_STRING "2006-2009 Project Vine.",
			B_TRANSLATE("MIT license. All rights reserved."),
			NULL)
		.SetLicense("BSD (3-clause)")
		.SetURL("http://vlgothic.dicey.org/"));

	// expat copyrights
	_AddPackageCredit(PackageCredit("expat")
		.SetCopyrights(B_TRANSLATE(COPYRIGHT_STRING "1998-2000 Thai "
			"Open Source Software Center Ltd and Clark Cooper."),
			B_TRANSLATE(COPYRIGHT_STRING "2001-2003 Expat maintainers."),
			NULL)
		.SetLicense("Expat")
		.SetURL("http://expat.sourceforge.net"));

	// zlib copyrights
	_AddPackageCredit(PackageCredit("zlib")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1995-2004 Jean-loup "
			"Gailly and Mark Adler."))
		.SetLicense("Zlib")
		.SetURL("http://www.zlib.net"));

	// zip copyrights
	_AddPackageCredit(PackageCredit("Info-ZIP")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1990-2002 Info-ZIP. "
			"All rights reserved."))
		.SetLicense("Info-ZIP")
		.SetURL("http://www.info-zip.org"));

	// bzip2 copyrights
	_AddPackageCredit(PackageCredit("bzip2")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1996-2005 Julian R "
			"Seward. All rights reserved."))
		.SetLicense(B_TRANSLATE("BSD (4-clause)"))
		.SetURL("http://bzip.org"));

	// lp_solve copyrights
	_AddPackageCredit(PackageCredit("lp_solve")
		.SetCopyright(COPYRIGHT_STRING
			"Michel Berkelaar, Kjell Eikland, Peter Notebaert")
		.SetLicense("GNU LGPL v2.1")
		.SetURL("http://lpsolve.sourceforge.net/"));

	// OpenEXR copyrights
	_AddPackageCredit(PackageCredit("OpenEXR")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2002-2005 Industrial "
			"Light & Magic, a division of Lucas Digital Ltd. LLC."))
		.SetLicense(B_TRANSLATE("BSD (3-clause)"))
		.SetURL("http://www.openexr.com"));

	// Bullet copyrights
	_AddPackageCredit(PackageCredit("Bullet")
		.SetCopyright(COPYRIGHT_STRING "2003-2008 Erwin Coumans")
		.SetLicense("Bullet")
		.SetURL("http://www.bulletphysics.com"));

	// atftp copyrights
	_AddPackageCredit(PackageCredit("atftp")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2000 Jean-Pierre "
			"ervbefeL and Remi Lefebvre."))
		.SetLicense("GNU GPL v2")
		.SetURL("http://freecode.com/projects/atftp"));

	// Netcat copyrights
	_AddPackageCredit(PackageCredit("Netcat")
		.SetCopyright(COPYRIGHT_STRING "1996 Hobbit.")
		.SetLicense("Public Domain")
		.SetURL("http://nc110.sourceforge.net/"));

	// acpica copyrights
	_AddPackageCredit(PackageCredit("acpica")
		.SetCopyright(COPYRIGHT_STRING "1999-2006 Intel Corp.")
		.SetLicense("Intel (ACPICA)")
		.SetURL("http://www.acpica.org"));

	// unrar copyrights
	_AddPackageCredit(PackageCredit("unrar")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2002-2008 Alexander "
			"L. Roshal. All rights reserved."))
		.SetLicense("UnRAR")
		.SetURL("http://www.rarlab.com"));

	// libpng copyrights
	_AddPackageCredit(PackageCredit("libpng")
		.SetCopyright(COPYRIGHT_STRING "2004, 2006-2008 Glenn "
			"Randers-Pehrson.")
		.SetLicense("LibPNG")
		.SetURL("http://www.libpng.org"));

	// libjpeg copyrights
	_AddPackageCredit(PackageCredit("libjpeg")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1994-2009, Thomas G. "
			"Lane, Guido Vollbeding. This software is based in part on the "
			"work of the Independent JPEG Group."))
		.SetLicense("LibJPEG")
		.SetURL("http://www.ijg.org"));

	// libprint copyrights
	_AddPackageCredit(PackageCredit("libprint")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1999-2000 Y.Takagi. "
			"All rights reserved.")));
			// TODO: License!

	// cortex copyrights
	_AddPackageCredit(PackageCredit("Cortex")
		.SetCopyright(COPYRIGHT_STRING "1999-2000 Eric Moon.")
		.SetLicense(B_TRANSLATE("BSD (3-clause)"))
		.SetURL("http://cortex.sourceforge.net/documentation"));

	// FluidSynth copyrights
	_AddPackageCredit(PackageCredit("FluidSynth")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2003 Peter Hanappe "
			"and others."))
		.SetLicense("GNU LGPL v2")
		.SetURL("http://www.fluidsynth.org"));

	// CannaIM copyrights
	_AddPackageCredit(PackageCredit("CannaIM")
		.SetCopyright(COPYRIGHT_STRING "1999 Masao Kawamura.")
		.SetLicense("MIT"));

	// libxml2, libxslt, libexslt copyrights
	_AddPackageCredit(PackageCredit("libxml2, libxslt")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1998-2003 Daniel Veillard. "
			"All rights reserved."))
		.SetLicense(B_TRANSLATE("MIT (no promotion)"))
		.SetURL("http://xmlsoft.org"));

	_AddPackageCredit(PackageCredit("libexslt")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2001-2002 Thomas Broyer, "
			"Charlie Bozeman and Daniel Veillard. All rights reserved."))
		.SetLicense(B_TRANSLATE("MIT (no promotion)"))
		.SetURL("http://xmlsoft.org"));

	// Xiph.org Foundation copyrights
	_AddPackageCredit(PackageCredit("Xiph.org Foundation")
		.SetCopyrights("libvorbis, libogg, libtheora, libspeex",
			B_TRANSLATE(COPYRIGHT_STRING "1994-2008 Xiph.Org. "
			"All rights reserved."), NULL)
		.SetLicense(B_TRANSLATE("BSD (3-clause)"))
		.SetURL("http://www.xiph.org"));

	// The Tcpdump Group
	_AddPackageCredit(PackageCredit("The Tcpdump Group")
		.SetCopyright("tcpdump, libpcap")
		.SetLicense(B_TRANSLATE("BSD (3-clause)"))
		.SetURL("http://www.tcpdump.org"));

	// Matroska
	_AddPackageCredit(PackageCredit("libmatroska")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2002-2003 Steve Lhomme. "
			"All rights reserved."))
		.SetLicense("GNU LGPL v2.1")
		.SetURL("http://www.matroska.org"));

	// BColorQuantizer (originally CQuantizer code)
	_AddPackageCredit(PackageCredit("CQuantizer")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1996-1997 Jeff Prosise. "
			"All rights reserved."))
		.SetLicense("CQuantizer")
		.SetURL("http://www.xdp.it"));

	// MAPM (Mike's Arbitrary Precision Math Library) used by DeskCalc
	_AddPackageCredit(PackageCredit("MAPM")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1999-2007 Michael C. "
			"Ring. All rights reserved."))
		.SetLicense("MAPM")
		.SetURL("http://tc.umn.edu/~ringx004"));

	// MkDepend 1.7 copyright (Makefile dependency generator)
	_AddPackageCredit(PackageCredit("MkDepend")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1995-2001 Lars Düning. "
			"All rights reserved."))
		.SetLicense("MkDepend")
		.SetURL("http://bearnip.com/lars/be"));

	// libhttpd copyright (used as Poorman backend)
	_AddPackageCredit(PackageCredit("libhttpd")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1995, 1998-2001 "
			"Jef Poskanzer. All rights reserved."))
		.SetLicense("LibHTTPd")
		.SetURL("http://www.acme.com/software/thttpd/"));

#ifdef __INTEL__
	// Udis86 copyrights
	_AddPackageCredit(PackageCredit("Udis86")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2002-2004 "
			"Vivek Mohan. All rights reserved."))
		.SetLicense(B_TRANSLATE("BSD (2-clause)"))
		.SetURL("http://udis86.sourceforge.net"));
#endif

#ifdef __INTEL__
	// Intel PRO/Wireless 2100 Firmware
	_AddPackageCredit(PackageCredit("Intel PRO/Wireless 2100 Firmware")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2003-2006 "
			"Intel Corporation. All rights reserved."))
		.SetLicense("Intel (2xxx firmware)")
		.SetURL("http://ipw2100.sourceforge.net/"));
#endif

#ifdef __INTEL__
	// Intel PRO/Wireless 2200BG Firmware
	_AddPackageCredit(PackageCredit("Intel PRO/Wireless 2200BG Firmware")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2004-2005 "
			"Intel Corporation. All rights reserved."))
		.SetLicense("Intel (2xxx firmware)")
		.SetURL("http://ipw2200.sourceforge.net/"));
#endif

#ifdef __INTEL__
	// Intel PRO/Wireless 3945ABG/BG Network Connection Adapter Firmware
	_AddPackageCredit(
		PackageCredit(
			"Intel PRO/Wireless 3945ABG/BG Network Connection Adapter Firmware")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2006-2007 "
			"Intel Corporation. All rights reserved."))
		.SetLicense("Intel (firmware)")
		.SetURL("http://www.intellinuxwireless.org/"));
#endif
#ifdef __INTEL__
	// Intel Wireless WiFi Link 4965AGN Adapter Firmware
	_AddPackageCredit(
		PackageCredit("Intel Wireless WiFi Link 4965AGN Adapter Firmware")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2006-2007 "
			"Intel Corporation. All rights reserved."))
		.SetLicense("Intel (firmware)")
		.SetURL("http://www.intellinuxwireless.org/"));
#endif

#ifdef __INTEL__
	// Marvell 88w8363
	_AddPackageCredit(PackageCredit("Marvell 88w8363")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2007-2009 "
			"Marvell Semiconductor, Inc. All rights reserved."))
		.SetLicense("Marvell (firmware)")
		.SetURL("http://www.marvell.com/"));
#endif

#ifdef __INTEL__
	// Ralink Firmware RT2501/RT2561/RT2661
	_AddPackageCredit(PackageCredit("Ralink Firmware RT2501/RT2561/RT2661")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2007 "
			"Ralink Technology Corporation. All rights reserved."))
		.SetLicense("Ralink (firmware)")
		.SetURL("http://www.ralinktech.com/"));
#endif

	// Gutenprint
	_AddPackageCredit(PackageCredit("Gutenprint")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING
			"1999-2010 by the authors of Gutenprint. All rights reserved."))
		.SetLicense("GNU GPL v2")
		.SetURL("http://gutenprint.sourceforge.net/"));

	// libwebp
	_AddPackageCredit(PackageCredit("libwebp")
		.SetCopyright(B_TRANSLATE(COPYRIGHT_STRING
			"2010-2011 Google Inc. All rights reserved."))
		.SetLicense(B_TRANSLATE("BSD (3-clause)"))
		.SetURL("http://www.webmproject.org/code/#libwebp_webp_image_library"));

	// GTF
	_AddPackageCredit(PackageCredit("GTF")
		.SetCopyright(B_TRANSLATE("2001 by Andy Ritger based on the "
			"Generalized Timing Formula"))
		.SetLicense(B_TRANSLATE("BSD (3-clause)"))
		.SetURL("http://gtf.sourceforge.net/"));

	_AddCopyrightsFromAttribute();
	_AddPackageCreditEntries();

	return new CropView(creditsScroller, 0, 1, 1, 1);
}
Example #17
0
void
FileTypes::MessageReceived(BMessage* message)
{
    switch (message->what) {
    case kMsgSettingsChanged:
        fSettings.UpdateFrom(message);
        break;

    case kMsgOpenTypesWindow:
        if (fTypesWindow == NULL) {
            fTypesWindow = new FileTypesWindow(fSettings.Message());
            if (fArgvType.Length() > 0) {
                // Set the window to the type that was requested on the
                // command line (-type), we do this only once, if we
                // ever opened more than one FileTypesWindow.
                fTypesWindow->SelectType(fArgvType.String());
                fArgvType = "";
            }
            fTypesWindow->Show();
            fWindowCount++;
        } else
            fTypesWindow->Activate(true);
        break;
    case kMsgTypesWindowClosed:
        fTypesWindow = NULL;
        _WindowClosed();
        break;

    case kMsgOpenApplicationTypesWindow:
        if (fApplicationTypesWindow == NULL) {
            fApplicationTypesWindow = new ApplicationTypesWindow(
                fSettings.Message());
            fApplicationTypesWindow->Show();
            fWindowCount++;
        } else
            fApplicationTypesWindow->Activate(true);
        break;
    case kMsgApplicationTypesWindowClosed:
        fApplicationTypesWindow = NULL;
        _WindowClosed();
        break;

    case kMsgTypeWindowClosed:
        fTypeWindowCount--;
    // supposed to fall through

    case kMsgWindowClosed:
        _WindowClosed();
        break;


    case kMsgOpenFilePanel:
    {
        // the open file panel sends us a message when it's done
        const char* subTitle;
        if (message->FindString("title", &subTitle) != B_OK)
            subTitle = B_TRANSLATE("Open file");

        int32 what;
        if (message->FindInt32("message", &what) != B_OK)
            what = B_REFS_RECEIVED;

        BMessenger target;
        if (message->FindMessenger("target", &target) != B_OK)
            target = be_app_messenger;

        BString title = B_TRANSLATE("FileTypes");
        if (subTitle != NULL && subTitle[0]) {
            title.Append(": ");
            title.Append(subTitle);
        }

        fFilePanel->SetMessage(new BMessage(what));
        fFilePanel->Window()->SetTitle(title.String());
        fFilePanel->SetTarget(target);

        if (!fFilePanel->IsShowing())
            fFilePanel->Show();
        break;
    }

    case B_SILENT_RELAUNCH:
        // In case we were launched via the add-on, there is no types
        // window yet.
        if (fTypesWindow == NULL)
            PostMessage(kMsgOpenTypesWindow);
        break;

    case B_CANCEL:
        if (fWindowCount == 0)
            PostMessage(B_QUIT_REQUESTED);
        break;

    case B_SIMPLE_DATA:
        RefsReceived(message);
        break;

    default:
        BApplication::MessageReceived(message);
        break;
    }
}
Example #18
0
// CreateNewProject - create all the text files for the new project
void NewProjectWindow::CreateNewProject(void)
{
	// Set Project Name and Various other settings
	char tmp[300];       // this will be removed when all references are gone 
	char cmd[256];
	int x;               // this will be removed when all references are gone
	FILE *f;             // this will be removed when all references are gone
	char FileName[256];
	char AppName[256];   // this will be removed when all references are gone
	BString FileContents;
	BString UpperProjectName;
	
	ProjectName.SetTo(txtNewProject->Text());
	UpperProjectName.SetTo(ProjectName.String());
	UpperProjectName.ToUpper();
	sprintf(AppName,"%s",ProjectName.String());  // this will be removed when all references are gone
		
	// 1) Get Current Directory
	app_info	daInfo;
	be_app->GetAppInfo(&daInfo);
	BEntry	daEntry(&daInfo.ref);
	daEntry.GetParent(&daEntry);
	BPath	pPath(&daEntry);
	char	apath[256];
	::memcpy(apath, pPath.Path(), 256);			
			
	// 2) Create New Directory
	sprintf(cmd,"mkdir %s/projects/%s",apath,ProjectName.String());
	system(cmd);
			
	// 3) Create Basic Files for a Default App
	
	// Application Header
	sprintf(FileName,"%s/projects/%s/%s.h",apath,ProjectName.String(),ProjectName.String());
	FileContents.SetTo("#ifndef __");
	FileContents.Append(UpperProjectName.String());
	FileContents.Append("_H__\n");
	FileContents.Append("#define __");
	FileContents.Append(UpperProjectName.String());
	FileContents.Append("_H__\n\n");
	FileContents.Append("extern const char *APP_SIGNATURE;\n\n");
	FileContents.Append("class ");
	FileContents.Append(ProjectName.String());
	FileContents.Append(" : public BApplication\n{\n\tpublic:\n\t\t");
	FileContents.Append(ProjectName.String());
	FileContents.Append("();\n");
	FileContents.Append("\t\tvirtual void MessageReceived(BMessage *message);\n");
	FileContents.Append("\tprivate:\n\n};\n\n");
	FileContents.Append("#endif\n");
	CreateFile(FileName,"Header",FileContents);
		
	// Application Constants.h
	sprintf(FileName,"%s/projects/%s/%sConstants.h",apath,ProjectName.String(),ProjectName.String());
	FileContents.SetTo("#ifndef __");
	FileContents.Append(UpperProjectName.String());
	FileContents.Append("CONSTANTS_H__\n");
	FileContents.Append("#define __");
	FileContents.Append(UpperProjectName.String());
	FileContents.Append("CONSTANTS_H__\n\n");
	FileContents.Append("// Pointers to BWindows\n");
	FileContents.Append("extern ");
	FileContents.Append(ProjectName.String());
	FileContents.Append("Window* ptr");
	FileContents.Append(ProjectName.String());
	FileContents.Append("Window;\n\n");
	FileContents.Append("// Product Name and Properties\n");
	FileContents.Append("const char projtitle[]=\"");
	FileContents.Append(ProjectName.String());
	FileContents.Append("\";\nconst char projversion[]=\"v0.1\";\nconst char projauthor[]=\"");
	FileContents.Append(txtAuthor->Text());
	FileContents.Append("\";\n\n");
	
	FileContents.Append("#endif\n");
	CreateFile(FileName,"Constants",FileContents);
	
	// Windows Header
	sprintf(FileName,"%s/projects/%s/%sWindows.h",apath,ProjectName.String(),ProjectName.String());
	FileContents.SetTo("#ifndef __");
	FileContents.Append(UpperProjectName.String());
	FileContents.Append("WINDOWS_H__\n");
	FileContents.Append("#define __");
	FileContents.Append(UpperProjectName.String());
	FileContents.Append("WINDOWS_H__\n\n");
	FileContents.Append("#include \"");
	FileContents.Append(ProjectName.String());
	FileContents.Append(".h\"\n");
	FileContents.Append("#include \"");
	FileContents.Append(ProjectName.String());
	FileContents.Append("Views.h\"\n\n");
	FileContents.Append("class ");
	FileContents.Append(ProjectName.String()); 
	FileContents.Append("View;\n\n");
	FileContents.Append("class ");
	FileContents.Append(ProjectName.String()); 
	FileContents.Append("Window : public BWindow\n");
	FileContents.Append("{\n\tpublic:\n\t\t");
	FileContents.Append(ProjectName.String()); 
	FileContents.Append("Window(BRect frame);\n");
	FileContents.Append("\t\t~");
	FileContents.Append(ProjectName.String()); 
	FileContents.Append("Window();\n");
	FileContents.Append("\t\tvirtual bool QuitRequested();\n");
	FileContents.Append("\t\tvirtual void MessageReceived(BMessage *message);\n");
	FileContents.Append("\tprivate:\n");
	FileContents.Append("\t\tvoid InitWindow(void);\n\n");
	if (chkLoadSavePrefs->Value() == B_CONTROL_ON) {
		FileContents.Append("\t\tvoid LoadSettings(BMessage *msg);\n");
		FileContents.Append("\t\tvoid SaveSettings(void);\n");
	}
	FileContents.Append("\t\t");
	FileContents.Append(ProjectName.String());
	FileContents.Append("View*\t\tptr");
	FileContents.Append(ProjectName.String());
	FileContents.Append("View;\n");
	FileContents.Append("};\n\n");
	FileContents.Append("#endif\n");
	CreateFile(FileName,"Windows Header",FileContents);

//	FileContents.Append("");
	
//	f = fopen(FileName,"w");
//	x = fputs("/*\n\n",f);
//	sprintf(tmp,"%s Windows Header\n\n",ProjectName.String());
//	x = fputs(tmp,f);
//	sprintf(tmp,"Author: %s\n\n",txtAuthor->Text());
//	x = fputs(tmp,f);
//	x = fputs("(C)2003 Created using BRIE (http://brie.sf.net/)\n\n",f);
//	x = fputs("*/\n\n",f);
//	sprintf(tmp,"#ifndef __%sWINDOWS_H__\n",ProjectName.String());
//	x = fputs(tmp,f);
//	sprintf(tmp,"#define __%sWINDOWS_H__\n\n",ProjectName.String());
//	x = fputs(tmp,f);
//	sprintf(tmp,"#include \"%s.h\"\n",ProjectName.String());
//	x = fputs(tmp,f);
//	sprintf(tmp,"#include \"%sViews.h\"\n\n",ProjectName.String());
//	x = fputs(tmp,f);
//	sprintf(tmp,"class %sView;\n\n",ProjectName.String());
//	x = fputs(tmp,f);
//	sprintf(tmp,"class %sWindow : public BWindow\n",ProjectName.String());
//	x = fputs(tmp,f);
//	x = fputs("{\n",f);
//	x = fputs("\tpublic:\n",f);
//	sprintf(tmp,"\t\t%sWindow(BRect frame);\n",ProjectName.String());
//	x = fputs(tmp,f);
//	sprintf(tmp,"\t\t~%sWindow();\n",ProjectName.String());
//	x = fputs(tmp,f);
//	x = fputs("\t\tvirtual bool QuitRequested();\n",f);
//	x = fputs("\t\tvirtual void MessageReceived(BMessage *message);\n",f);
//	x = fputs("\tprivate:\n",f);
//	x = fputs("\t\tvoid InitWindow(void);\n\n",f);
	
	// add load/save pref (if checked)
//	if (chkLoadSavePrefs->Value() == B_CONTROL_ON) {
//		x = fputs("\t\tvoid LoadSettings(BMessage *msg);\n",f);
//		x = fputs("\t\tvoid SaveSettings(void); \n",f);
//	}
//	sprintf(tmp,"\t\t%sView*\t\tptr%sView;\n",ProjectName.String(),ProjectName.String());
//	x = fputs(tmp,f);
//	x = fputs("};\n\n",f);
//	x = fputs("#endif\n",f);
//	fclose(f);
	
	// Views Header
	sprintf(FileName,"%s/projects/%s/%sViews.h",apath,ProjectName.String(),ProjectName.String());
	f = fopen(FileName,"w");
	x = fputs("/*\n\n",f);
	sprintf(tmp,"%s Views Header\n\n",ProjectName.String());
	x = fputs(tmp,f);
	sprintf(tmp,"Author: %s\n\n",txtAuthor->Text());
	x = fputs(tmp,f);
	x = fputs("(C)2003 Created using BRIE (http://brie.sf.net/)\n\n",f);
	x = fputs("*/\n\n",f);
	sprintf(tmp,"#ifndef __%sVIEWS_H__\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"#define __%sVIEWS_H__\n\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"#include \"%s.h\"\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"#include \"%sWindows.h\"\n\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"class %sView : public BView\n",AppName);
	x = fputs(tmp,f);
	x = fputs("{\n",f);
	x = fputs("\tpublic:\n",f);
	sprintf(tmp,"\t\t%sView(BRect frame);\n",AppName);
	x = fputs(tmp,f);
	x = fputs("\t\tvirtual void Draw(BRect updateRect);\n",f);
	x = fputs("};\n\n",f);
	x = fputs("#endif\n",f);
	fclose(f);

	// View CPP
	sprintf(FileName,"%s/projects/%s/%sView.cpp",apath,AppName,AppName);
	f = fopen(FileName,"w");
	x = fputs("/*\n\n",f);
	sprintf(tmp,"%s View\n\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"Author: %s\n\n",txtAuthor->Text());
	x = fputs(tmp,f);
	x = fputs("(C)2003 Created using BRIE (http://brie.sf.net/)\n\n",f);
	x = fputs("*/\n\n",f);
	x = fputs("// Includes ------------------------------------------------------------------------------------------ //\n",f);
	x = fputs("#include <Alert.h>\n",f);
	x = fputs("#include <Application.h>\n",f);
	x = fputs("#include <Screen.h>\n",f);
	x = fputs("#include <stdio.h>\n",f);
	x = fputs("#include <Window.h>\n",f);
	x = fputs("#include <View.h>\n\n",f);
	sprintf(tmp,"#include \"%sWindows.h\"\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"#include \"%sViews.h\"\n",AppName);
	x = fputs(tmp,f);
	x = fputs("// -------------------------------------------------------------------------------------------------- //\n\n",f);
	sprintf(tmp,"// %sView - Constructor\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"%sView::%sView (BRect frame) : BView (frame, \"%sView\", B_FOLLOW_ALL_SIDES, B_WILL_DRAW )\n",AppName,AppName,AppName);
	x = fputs(tmp,f);
	x = fputs("{\n",f);
	x = fputs("\tSetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));\n",f);
	x = fputs("}\n",f);
	x = fputs("// ------------------------------------------------------------------------------------------------- //\n\n",f);
	sprintf(tmp,"void %sView::Draw(BRect /*updateRect*/)\n",AppName);
	x = fputs(tmp,f);
	x = fputs("{\n",f);
	x = fputs("\tBRect r;\n",f);
	x = fputs("\tr = Bounds();\n",f);
	x = fputs("}\n",f);
	x = fputs("// ------------------------------------------------------------------------------------------------- //\n",f);
	fclose(f);
	
	// Main CPP
	sprintf(FileName,"%s/projects/%s/%s.cpp",apath,AppName,AppName);
	f = fopen(FileName,"w");
	x = fputs("/*\n\n",f);
	sprintf(tmp,"%s\n\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"Author: %s\n\n",txtAuthor->Text());
	x = fputs(tmp,f);
	x = fputs("(C)2003 Created using BRIE (http://brie.sf.net/)\n\n",f);
	x = fputs("*/\n\n",f);
	x = fputs("// Includes ------------------------------------------------------------------------------------------ //\n",f);
	x = fputs("#include <Alert.h>\n",f);
	x = fputs("#include <Application.h>\n",f);
	x = fputs("#include <Button.h>\n",f);
	x = fputs("#include <Entry.h>\n",f);
	x = fputs("#include <File.h>\n",f);
	x = fputs("#include <FilePanel.h>\n",f);
	x = fputs("#include <ListView.h>\n",f);
	x = fputs("#include <Path.h>\n",f);
	x = fputs("#include <Screen.h>\n",f);
	x = fputs("#include <ScrollView.h>\n",f);
	x = fputs("#include <stdio.h>\n",f);
	x = fputs("#include <string.h>\n",f);
	x = fputs("#include <TextControl.h>\n",f);
	x = fputs("#include <Window.h>\n",f);
	x = fputs("#include <View.h>\n\n",f);
	sprintf(tmp,"#include \"%s.h\"\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"#include \"%sWindows.h\"\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"#include \"%sViews.h\"\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"#include \"%sConstants.h\"\n",AppName);
	x = fputs(tmp,f);
	//x = fputs("// -------------------------------------------------------------------------------------------------- //\n\n",f);
	x = fputs("// Constants ---------------------------------------------------------------------------------------- //\n\n",f);
	sprintf(tmp,"const char *APP_SIGNATURE = \"application/x-vnd.%s.%s\";  // Application Signature and Title\n\n",txtAuthor->Text(),AppName);
	x = fputs(tmp,f);
	x = fputs("// -------------------------------------------------------------------------------------------------- //\n\n",f);
	sprintf(tmp,"%sWindow\t\t*ptr%sWindow;\n\n",AppName,AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"// %s - Constructor\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"%s::%s() : BApplication (APP_SIGNATURE)\n",AppName,AppName);
	x = fputs(tmp,f);
	x = fputs("{\n",f);
	x = fputs("\t// Default Window Size - Position doesn't matter as we centre the form to the current screen size\n",f);
	x = fputs("\tBRect	screenFrame = (BScreen(B_MAIN_SCREEN_ID).Frame());\n\n",f);
	x = fputs("\tfloat FormTopDefault = 0;\n",f);
	x = fputs("\tfloat FormLeftDefault = 0;\n",f);
	x = fputs("\tfloat FormWidthDefault = screenFrame.Width() - 500;\n",f);
	x = fputs("\tfloat FormHeightDefault = screenFrame.Height() - 500;\n",f);
	sprintf(tmp,"\tBRect %sWindowRect(FormTopDefault,FormLeftDefault,FormLeftDefault+FormWidthDefault,FormTopDefault+FormHeightDefault);\n\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"\tptr%sWindow = new %sWindow(%sWindowRect);\n",AppName,AppName,AppName);
	x = fputs(tmp,f);
	x = fputs("}\n",f);
	x = fputs("// ------------------------------------------------------------------------------------------------- //\n\n",f);
	sprintf(tmp,"// %s::MessageReceived -- handles incoming messages\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"void %s::MessageReceived (BMessage *message)\n",AppName);
	x = fputs(tmp,f);
	x = fputs("{\n",f);
	x = fputs("\tswitch(message->what)\n",f);
	x = fputs("\t{\n",f);
	x = fputs("\t\tdefault:\n",f);
	x = fputs("\t\t\tBApplication::MessageReceived(message); // pass it along ... \n",f);
	x = fputs("\t\t\tbreak;\n",f);
	x = fputs("\t}\n",f);
	x = fputs("}\n",f);
	x = fputs("// ------------------------------------------------------------------------------------------------- //\n\n",f);
	sprintf(tmp,"// %s Main\n",AppName);
	x = fputs(tmp,f);
	x = fputs("int main(void)\n",f);
	x = fputs("{\n",f);
	sprintf(tmp,"\t%s theApp;\n",AppName);
	x = fputs(tmp,f);
	x = fputs("\ttheApp.Run();\n",f);
	x = fputs("\treturn 0;\n",f);
	x = fputs("}\n",f);
	x = fputs("// end --------------------------------------------------------------------------------------------- //\n\n",f);
	fclose(f);
	
	// Window CPP
	sprintf(FileName,"%s/projects/%s/%sWindow.cpp",apath,AppName,AppName);
	f = fopen(FileName,"w");
	x = fputs("/*\n\n",f);
	sprintf(tmp,"%sWindow\n\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"Author: %s\n\n",txtAuthor->Text());
	x = fputs(tmp,f);
	x = fputs("(C)2003 Created using BRIE (http://brie.sf.net/)\n\n",f);
	x = fputs("*/\n\n",f);
	x = fputs("// Includes ------------------------------------------------------------------------------------------ //\n",f);
	x = fputs("#include <Alert.h>\n",f);
	x = fputs("#include <Application.h>\n",f);
	x = fputs("#include <Button.h>\n",f);
	
	// add load/save pref (if checked)
	if (chkLoadSavePrefs->Value() == B_CONTROL_ON) {
		x = fputs("#include <File.h>\n",f);
		x = fputs("#include <FindDirectory.h>\n",f);
	}	
	
	// add menubar includes (if checked)
	if (chkMenuBar->Value() == B_CONTROL_ON) {
		x = fputs("#include <MenuBar.h>\n",f);
		x = fputs("#include <Menu.h>\n",f);
		x = fputs("#include <MenuItem.h>\n",f);
	}
	
	x = fputs("#include <Path.h>\n",f);
	x = fputs("#include <Screen.h>\n",f);
	x = fputs("#include <ScrollView.h>\n",f);
	x = fputs("#include <stdio.h>\n",f);
	x = fputs("#include <string.h>\n",f);
	x = fputs("#include <TextControl.h>\n",f);
	x = fputs("#include <Window.h>\n",f);
	x = fputs("#include <View.h>\n\n",f);
	sprintf(tmp,"#include \"%s.h\"\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"#include \"%sWindows.h\"\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"#include \"%sViews.h\"\n",AppName);
	x = fputs(tmp,f);
	x = fputs("// -------------------------------------------------------------------------------------------------- //\n\n",f);
	x = fputs("// CenterWindowOnScreen -- Centers the BWindow to the Current Screen\n",f);
	x = fputs("static void CenterWindowOnScreen(BWindow* w)\n",f);
	x = fputs("{\n",f);
	x = fputs("\tBRect\tscreenFrame = (BScreen(B_MAIN_SCREEN_ID).Frame());",f);
	x = fputs("\tBPoint\tpt;\n",f);
	x = fputs("\tpt.x = screenFrame.Width()/2 - w->Bounds().Width()/2;\n",f);
	x = fputs("\tpt.y = screenFrame.Height()/2 - w->Bounds().Height()/2;\n\n",f);
	x = fputs("\tif (screenFrame.Contains(pt))\n",f);
	x = fputs("\t\tw->MoveTo(pt);\n",f);
	x = fputs("}\n",f);
	x = fputs("// -------------------------------------------------------------------------------------------------- //\n\n",f);
	sprintf(tmp,"// %sWindow - Constructor\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"%sWindow::%sWindow(BRect frame) : BWindow (frame, \"%s v0.1\", B_TITLED_WINDOW, B_NORMAL_WINDOW_FEEL , 0)\n",AppName,AppName,AppName);
	x = fputs(tmp,f);
	x = fputs("{\n",f);
	x = fputs("\tInitWindow();\n",f);
	x = fputs("\tCenterWindowOnScreen(this);\n",f);
	
	// add load/save pref (if checked)
	if (chkLoadSavePrefs->Value() == B_CONTROL_ON) {
		x = fputs("\n",f);
		x = fputs("\t// Load User Settings \n",f);
		x = fputs("\tBPath path;\n",f);
		x = fputs("\tfind_directory(B_USER_SETTINGS_DIRECTORY,&path);\n",f);
		sprintf(tmp,"\tpath.Append(\"%s_Settings\",true);\n",AppName);
		x = fputs(tmp,f);
		x = fputs("\tBFile file(path.Path(),B_READ_ONLY);\n",f);
		x = fputs("\tBMessage msg;\n",f);
		x = fputs("\tmsg.Unflatten(&file);\n",f);
		x = fputs("\tLoadSettings (&msg);\n",f);
		x = fputs("\n",f);
    }
	
	x = fputs("\tShow();\n",f);
	x = fputs("}\n",f);
	x = fputs("// -------------------------------------------------------------------------------------------------- //\n\n",f);
	sprintf(tmp,"// %sWindow - Destructor\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"%sWindow::~%sWindow()\n",AppName,AppName);
	x = fputs(tmp,f);
	x = fputs("{\n",f);
	x = fputs("\texit(0);\n",f);
	x = fputs("}\n",f);
	x = fputs("// -------------------------------------------------------------------------------------------------- //\n\n",f);
	sprintf(tmp,"// %sWindow::InitWindow -- Initialization Commands here\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"void %sWindow::InitWindow(void)\n",AppName);
	x = fputs(tmp,f);
	x = fputs("{\n",f);
	x = fputs("\tBRect r;\n",f);
	x = fputs("\tr = Bounds(); // the whole view\n",f);
		
	// add MenuBar (if checked)
	if (chkMenuBar->Value() == B_CONTROL_ON) {
		ptrMenuCreator = new MenuCreator(BRect(367.0, 268.0, 657.0, 500.0));
		x = fputs("\n",f);
		x = fputs("\t// MenuBar - Created by BRIE Menu Creator\n",f);
		x = fputs("\tBMenu *menu;\n",f);
		x = fputs("\tBRect rMenuBar;\n\n",f);
		x = fputs("\trMenuBar = Bounds();\n",f);
		x = fputs("\trMenuBar.top = 20;\n\n",f);
		x = fputs("\t// Add the menu bar\n",f);
		x = fputs("\trMenuBar.top = 0;\n",f);
		x = fputs("\trMenuBar.bottom = 19;\n",f);
		x = fputs("\tmenubar = new BMenuBar(rMenuBar, \"menu_bar\");\n",f);
		x = fputs("\tAddChild(menubar);\n",f);
		x = fputs("\n",f);
		x = fputs("\t// ### INSERT MENU HERE FROM MENU CREATOR ### \n",f);
		x = fputs("\n",f);
		x = fputs("\t// EndMenuBar (please do not remove this line)\n\n",f);
	}
	
	x = fputs("\t// Create the Views\n",f);
	sprintf(tmp,"\tAddChild(ptr%sView = new %sView(r));\n",AppName,AppName);
	x = fputs(tmp,f);
	x = fputs("}\n",f);
	x = fputs("// -------------------------------------------------------------------------------------------------- //\n\n",f);
	sprintf(tmp,"// %sWindow::QuitRequested -- Post a message to the app to quit\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"bool %sWindow::QuitRequested()\n",AppName);
	x = fputs(tmp,f);
	x = fputs("{\n",f);
	
	if (chkLoadSavePrefs->Value() == B_CONTROL_ON) {
		x = fputs("\tSaveSettings();\n",f);
	}
	
	x = fputs("\tbe_app->PostMessage(B_QUIT_REQUESTED);\n",f);
	x = fputs("\treturn true;\n",f);
	x = fputs("}\n",f);
	x = fputs("// -------------------------------------------------------------------------------------------------- //\n\n",f);	
	
	// add load/save pref (if checked)
	if (chkLoadSavePrefs->Value() == B_CONTROL_ON) {
		sprintf(tmp,"// %sWindow::LoadSettings -- Loads your current settings\n",AppName);
		x = fputs(tmp,f);
		sprintf(tmp,"void %sWindow::LoadSettings(BMessage *msg)\n",AppName);
		x = fputs(tmp,f);
		x = fputs("{\n",f);
		x = fputs("\tBRect frame;\n\n",f);
		x = fputs("\tif (B_OK == msg->FindRect(\"windowframe\",&frame)) {\n",f);
		x = fputs("\t\tMoveTo(frame.left,frame.top);\n",f);
		x = fputs("\t\tResizeTo(frame.right-frame.left,frame.bottom-frame.top);\n",f);
		x = fputs("\t}\n",f);
		x = fputs("}\n",f);
		x = fputs("// -------------------------------------------------------------------------------------------------- //\n\n",f);		

		sprintf(tmp,"// %sWindow::SaveSettings -- Saves the Users settings\n",AppName);
		x = fputs(tmp,f);
		sprintf(tmp,"void %sWindow::SaveSettings(void)\n",AppName);
		x = fputs(tmp,f);
		x = fputs("{\n",f);
		x = fputs("\tBMessage msg;\n",f);
		x = fputs("\tmsg.AddRect(\"windowframe\",Frame());\n\n",f);
		x = fputs("\tBPath path;\n",f);
		x = fputs("\tstatus_t result = find_directory(B_USER_SETTINGS_DIRECTORY,&path);\n",f);
		x = fputs("\tif (result == B_OK) {\n",f);
		sprintf(tmp,"\t\tpath.Append(\"%s_Settings\",true);\n",AppName);
		x = fputs(tmp,f);
		x = fputs("\t\tBFile file(path.Path(),B_READ_WRITE | B_CREATE_FILE | B_ERASE_FILE);\n",f);
		x = fputs("\t\tmsg.Flatten(&file);\n",f);
		
		x = fputs("\t}\n",f);
		x = fputs("}\n",f);
		x = fputs("// -------------------------------------------------------------------------------------------------- //\n\n",f);
	}
		
	sprintf(tmp,"// %sWindow::MessageReceived -- receives messages\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"void %sWindow::MessageReceived (BMessage *message)\n",AppName);
	x = fputs(tmp,f);
	x = fputs("{\n",f);
	x = fputs("\tswitch(message->what)\n",f);
	x = fputs("\t{\n",f);
	x = fputs("\t\tdefault:\n",f);
	x = fputs("\t\t\tBWindow::MessageReceived(message);\n",f);
	x = fputs("\t\t\tbreak;\n",f);
	x = fputs("\t}\n",f);
	x = fputs("}\n",f);
	x = fputs("// -------------------------------------------------------------------------------------------------- //\n\n",f);	
	fclose(f);
	
	// this step doesnt work - would be nice if rsrc files could be made from text
	// 4) Copy newproject.rsrc to our project folder
	//sprintf(cmd,"cp %s/newproject.rsrc %s/projects/%s/",apath,apath,AppName);
	//system(cmd);
	//sprintf(cmd,"mv %s/projects/%s/newproject.rsrc %s/projects/%s/%s.rsrc",apath,AppName,apath,AppName,AppName);
	//system(cmd);
	
	// 5) Create BRIE Project File - this is required for internal use in this application only
	sprintf(FileName,"%s/projects/%s.bprj",apath,AppName);
	f = fopen(FileName,"w");
	sprintf(tmp,"## BRIE Project File for %s ##\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"ProjectName=%s\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"ProjectDir=%s/projects/%s\n",apath,AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"Author=%s\n",txtAuthor->Text());
	x = fputs(tmp,f);
	sprintf(tmp,"Language=%s\n","C/C++"); // might change later ...
	x = fputs(tmp,f);
	x = fputs("### Files\n",f);
	sprintf(tmp,"%s.cpp\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"%sWindow.cpp\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"%sView.cpp\n",AppName);
	x = fputs(tmp,f);
	fclose(f);
	sprintf(tmp,"%s.bprj",AppName);
	//ptrFileWindow->SetProject(FileName,tmp);
	//ptrProjectWindow->SetProjectTitle(AppName);
	
	//msg = new BMessage(SET_PROJECT_NAME);
	//msg.AddString("ProjectName",AppName);
	//msg.AddBool("NotSaved",true);
	//ptrProjectWindow->PostMessage(&msg);
	
	// Create our ProjectFiles BMessage
	BMessage pfmsg(ADD_PROJECT_FILE);
	BString ProgName;
	ProgName.SetTo(AppName);
	ProgName.Append(".cpp");
	pfmsg.AddString(kProjectFile, ProgName.String());
	BMessenger(ptrProjectWindow).SendMessage(&pfmsg);
	
	pfmsg.MakeEmpty();
	ProgName.SetTo(AppName);
	ProgName.Append("Window.cpp");
	pfmsg.AddString(kProjectFile, ProgName.String());
	BMessenger(ptrProjectWindow).SendMessage(&pfmsg);
	
	pfmsg.MakeEmpty();
	ProgName.SetTo(AppName);
	ProgName.Append("View.cpp");
	pfmsg.AddString(kProjectFile, ProgName.String());
	BMessenger(ptrProjectWindow).SendMessage(&pfmsg);
	
	// 6) Create makefile for compilation
	sprintf(FileName,"%s/projects/%s/makefile",apath,AppName);
	f = fopen(FileName,"w");
	sprintf(tmp,"## BeOS Makefile for %s ##\n",AppName);
	x = fputs(tmp,f);
	sprintf(tmp,"## Author: %s\n",txtAuthor->Text());
	x = fputs(tmp,f);
	x = fputs("## Created by BRIE (http://brie.sf.net/)\n\n",f);
	x = fputs("## Application Specific Settings ---------------------------------------------\n\n",f);
	x = fputs("# specify the name of the binary\n",f);
	sprintf(tmp,"NAME= %s\n",AppName);
	x = fputs(tmp,f);
	x = fputs("# specify the type of binary\n",f);
	x = fputs("#	APP:	Application\n",f);
	x = fputs("#	SHARED:	Shared library or add-on\n",f);
	x = fputs("#	STATIC:	Static library archive\n",f);
	x = fputs("#	DRIVER: Kernel Driver\n",f);
	x = fputs("TYPE= APP\n\n",f);
	x = fputs("#	specify the source files to use\n",f);
	x = fputs("#	Note that spaces in folder names do not work well with this makefile.\n",f);
	sprintf(tmp,"SRCS= %s.cpp %sWindow.cpp %sView.cpp\n",AppName,AppName,AppName);
	x = fputs(tmp,f);
	x = fputs("# end of srcs\n\n",f);
	x = fputs("#	specify the resource files to use\n",f);
	//x = fputs("RSRCS= ../../newproject.rsrc\n\n",f);
	x = fputs("RSRCS= \n\n",f);
	x = fputs("#	specify additional libraries to link against\n",f);
	x = fputs("LIBS= be root\n\n",f);
	x = fputs("#	specify additional paths to directories \n",f);
	x = fputs("LIBPATHS=\n\n",f);
	x = fputs("#	additional paths to look for system headers\n",f);
	x = fputs("SYSTEM_INCLUDE_PATHS =\n\n",f);
	x = fputs("#	additional paths to look for local headers\n",f);
	x = fputs("LOCAL_INCLUDE_PATHS =\n\n",f);
	x = fputs("#	specify the level of optimization that you desire - NONE, SOME, FULL\n",f);
	x = fputs("OPTIMIZE=\n\n",f);
	x = fputs("#	specify any preprocessor symbols to be defined.  \n",f);
	x = fputs("DEFINES=\n\n",f);
	x = fputs("#	specify special warning levels - NONE, ALL\n",f);
	x = fputs("WARNINGS = ALL\n\n",f);
	x = fputs("#	specify whether image symbols will be created\n",f);
	x = fputs("SYMBOLS = TRUE\n\n",f);
	x = fputs("#	specify debug settings\n",f);
	x = fputs("DEBUGGER =\n\n",f);
	x = fputs("#	specify additional compiler flags for all files\n",f);	
	x = fputs("COMPILER_FLAGS =\n\n",f);
	x = fputs("#	specify additional linker flags\n",f);
	x = fputs("LINKER_FLAGS =\n\n",f);
	x = fputs("## include the makefile-engine\n",f);
	x = fputs("DEVEL_DIRECTORY := \\\n",f);
	x = fputs("\t$(shell findpaths -r \"makefile_engine\" B_FIND_PATH_DEVELOP_DIRECTORY)",f);
	x = fputs("include $(DEVEL_DIRECTORY)/etc/makefile-engine",f);
	fclose(f);
	
	// 7) Send Messages to other Windows to update
	BMessage msg(SET_PROJECT_TITLE);
	msg.AddString(kProjectName, AppName);
	//msg.AddBool(kNotSaved, true); // make this false later - true for debug purposes
	BMessenger(ptrFileWindow).SendMessage(&msg);
	BMessenger(ptrProjectWindow).SendMessage(&msg);
	ProjectName.SetTo(AppName);
	ProjectPath = apath;
	
	// set properties window to show current Window from New Project
	ptrPropertiesWindow->ShowProperties("Window",ProjectName.String());
		
	// 8) Show Tracker and/or Continue
	ShowTracker(apath,AppName);
}
Example #19
0
void
ListAgent::MessageReceived (BMessage *msg)
{
  switch (msg->what)
  {
    case M_THEME_FONT_CHANGE:
      {
        int32 which (msg->FindInt16 ("which"));
        if (which == F_LISTAGENT)
        {
          activeTheme->ReadLock();
          listView->SetFont (B_FONT_ROW, &activeTheme->FontAt (F_LISTAGENT));
          activeTheme->ReadUnlock();
          listView->Invalidate();
        }
      }
      break;
      
    case M_THEME_FOREGROUND_CHANGE:
      {
        int32 which (msg->FindInt16 ("which"));
        bool refresh (false);
        switch (which)
        {
          case C_BACKGROUND:
            activeTheme->ReadLock();
            listView->SetColor (B_COLOR_BACKGROUND, activeTheme->ForegroundAt (C_BACKGROUND));
            activeTheme->ReadUnlock();
            refresh = true;
            break;
            
          case C_TEXT:
            activeTheme->ReadLock();
            listView->SetColor (B_COLOR_TEXT, activeTheme->ForegroundAt (C_TEXT));
            activeTheme->ReadUnlock();
            refresh = true;
            break;

          case C_SELECTION:             
            activeTheme->ReadLock();
            listView->SetColor (B_COLOR_SELECTION, activeTheme->ForegroundAt (C_SELECTION));
            activeTheme->ReadUnlock();
            refresh = true;
            break;
            
          default:
            break;
        }
        if (refresh)
          Invalidate();
      }
      break;
      
    case M_STATUS_ADDITEMS:
      {
        vision_app->pClientWin()->pStatusView()->AddItem (new StatusItem (S_STATUS_LISTCOUNT, ""), true);
        vision_app->pClientWin()->pStatusView()->AddItem (new StatusItem (S_STATUS_LISTSTAT, ""), true);
        vision_app->pClientWin()->pStatusView()->AddItem (new StatusItem (S_STATUS_LISTFILTER, "", STATUS_ALIGN_LEFT), true);
 
        BString cString;
        cString << listView->CountRows();
        vision_app->pClientWin()->pStatusView()->SetItemValue (0, cString.String(), false);
        vision_app->pClientWin()->pStatusView()->SetItemValue (1, statusStr.String(), false);
        vision_app->pClientWin()->pStatusView()->SetItemValue (2, filter.String(), true);
      }
      break;

    case M_LIST_COMMAND:
      {
        if (!processing)
        {
          BMessage sMsg (M_SERVER_SEND);
          
          BString command ("LIST");
          
          BString params (msg->FindString ("cmd"));
          if (params != "-9z99")
          {
            command.Append (" ");
            command.Append (params);
          }

          sMsg.AddString ("data", command.String());

          fSMsgr->SendMessage (&sMsg);
          processing = true;

          if (!IsHidden())
            vision_app->pClientWin()->pStatusView()->SetItemValue (0, "0", true);
        }
      }
      break;

    case M_LIST_BEGIN:
      {
        BMessage msg (M_LIST_UPDATE);
        listUpdateTrigger = new BMessageRunner (BMessenger(this), &msg, 3000000); 
        statusStr = S_LIST_STATUS_LOADING;
        if (!IsHidden())
          vision_app->pClientWin()->pStatusView()->SetItemValue (1, statusStr.String(), true);
      }
      break;
      
    case M_LIST_DONE:
      {
        if (listUpdateTrigger)
        {
          delete listUpdateTrigger;
          listUpdateTrigger = 0;
        }
        statusStr = S_LIST_STATUS_DONE;

        listView->SetSortingEnabled (true);
        listView->SetSortColumn (channelColumn, true, true);
        
        if (!IsHidden())
          vision_app->pClientWin()->pStatusView()->SetItemValue (1, statusStr.String(), true);

        mFind->SetEnabled (true);
        mFindAgain->SetEnabled (true);
        mFilter->SetEnabled (true);

        processing = false;
        
        // empty out any remaining channels that fell below the batch cut off
        AddBatch();

        BString cString;
        cString << listView->CountRows();
        if (!IsHidden())
          vision_app->pClientWin()->pStatusView()->SetItemValue (0, cString.String(), true);
      }
      break;

    case M_LIST_EVENT:
      {
        const char *channel, *users, *topic;

        msg->FindString ("channel", &channel);
        msg->FindString ("users", &users);
        msg->FindString ("topic", &topic);
        
        BRow *row (new BRow ());
        
        
        BStringField *channelField (new BStringField (channel));
        BIntegerField *userField (new BIntegerField (atoi(users)));
        BStringField *topicField (new BStringField (topic));
        
        row->SetField (channelField, channelColumn->LogicalFieldNum());
        row->SetField (userField, usersColumn->LogicalFieldNum());
        row->SetField (topicField, topicColumn->LogicalFieldNum());

        fBuildList.AddItem (row);
        
        if (fBuildList.CountItems() == LIST_BATCH_SIZE)
          AddBatch();
      }
      break;

#ifdef __INTEL__

		case M_LIST_FILTER:
			if (msg->HasString ("text"))
			{
				const char *buffer;

				msg->FindString ("text", &buffer);
				if (filter != buffer)
				{
					filter = buffer;

					if (!IsHidden())
					  vision_app->pClientWin()->pStatusView()->SetItemValue (2, filter.String(), true);

					regfree (&re);
					memset (&re, 0, sizeof (re));
					regcomp (
						&re,
						filter.String(),
						REG_EXTENDED | REG_ICASE | REG_NOSUB);
					
					BRow *currentRow;	
					BStringField *channel,
					             *topic;

					while (hiddenItems.CountItems() != 0)
					{
					  currentRow = hiddenItems.RemoveItemAt (0L);
					  listView->AddRow (currentRow);
					}

					if (filter != NULL)
					{
  					  int32 k (0);
  					    					  					
					  while (k < listView->CountRows())
					  {
					     currentRow = listView->RowAt (k);
					     channel = (BStringField *)currentRow->GetField (0);
					     topic = (BStringField *)currentRow->GetField (2);
       				  	 if ((regexec (&re, channel->String(), 0, 0, 0) != REG_NOMATCH)
       				  	    || (regexec (&re, topic->String(), 0, 0, 0) != REG_NOMATCH))
       				  	  {
       				  	    k++;
       					    continue;
       					  }
       					 else
       					 {
       					   listView->RemoveRow (currentRow);
       					   hiddenItems.AddItem (currentRow);
       					 }
					  }
					}
					fMsgr.SendMessage (M_LIST_DONE);
					processing = true;
				}
			}
			else
			{
				PromptWindow *prompt (new PromptWindow (
					BPoint ((Window()->Frame().right/2) - 100, (Window()->Frame().bottom/2) - 50),
					"  Filter:",
					"List Filter",
					filter.String(),
					this,
					new BMessage (M_LIST_FILTER),
					new RegExValidate ("Filter"),
					true));
				prompt->Show();
			}

			break;

		case M_LIST_FIND:
			if (msg->HasString ("text"))
			{
				int32 selection (listView->IndexOf(listView->CurrentSelection()));
				const char *buffer;

				msg->FindString ("text", &buffer);

				if (strlen (buffer) == 0)
				{
					find = buffer;
					break;
				}

				if (selection < 0)
				{
					selection = 0;
				}
				else
				{
					++selection;
				}

				if (find != buffer)
				{
					regfree (&fre);
					memset (&fre, 0, sizeof (fre));
					regcomp (
						&fre,
						buffer,
						REG_EXTENDED | REG_ICASE | REG_NOSUB);
					find = buffer;
				}

				BStringField *field;
				int32 i;
				for (i = selection; i < listView->CountRows(); ++i)
				{
					field = (BStringField *)listView->RowAt (i)->GetField (0);

					if (regexec (&fre, field->String(), 0, 0, 0) != REG_NOMATCH)
						break;
				}

				if (i < listView->CountRows())
				{
					BRow* row = listView->RowAt (i);
					listView->DeselectAll();
					listView->AddToSelection (row);
					listView->ScrollTo(row);
					listView->Refresh();
				}
				else
				{
					listView->DeselectAll();
				}
			}
			else
			{
				PromptWindow *prompt (new PromptWindow (
					BPoint ((Window()->Frame().right / 2) - 100, (Window()->Frame().bottom/2) - 50),
					S_LIST_PROMPT_LABEL,
					S_LIST_PROMPT_TITLE,
					find.String(),
					this,
					new BMessage (M_LIST_FIND),
					new RegExValidate ("Find:"),
					true));
				prompt->Show();
			} 
			break;

		case M_LIST_FAGAIN:
			if (find.Length())
			{
				msg->AddString ("text", find.String());
				msg->what = M_LIST_FIND;
				fMsgr.SendMessage (msg);
			}
			break;
#endif

		case M_LIST_INVOKE:
		{
			BMessage msg (M_SUBMIT);
			BString buffer;
				
			BRow *row (listView->CurrentSelection());
				
			if (row)
			{
                 buffer = "/JOIN ";
                 buffer += ((BStringField *)row->GetField(0))->String();
                 msg.AddBool ("history", false);
                 msg.AddBool ("clear", false);
                 msg.AddString ("input", buffer.String());
                 fSMsgr->SendMessage (&msg);
            }
		}
		break;
		
		case M_CLIENT_QUIT:
		{
		  fSMsgr->SendMessage(M_LIST_SHUTDOWN);
		  BMessage deathchant (M_OBITUARY);
          deathchant.AddPointer ("agent", this);
          deathchant.AddPointer ("item", fAgentWinItem);
          vision_app->pClientWin()->PostMessage (&deathchant);
		}
		break;
		
		default:
			BView::MessageReceived (msg);
	}
}
Example #20
0
status_t
AGMSBayesianSpamFilter::ProcessMailMessage (
	BPositionIO** io_message,
	BEntry* io_entry,
	BMessage* io_headers,
	BPath* io_folder,
	const char* io_uid)
{
	ssize_t		 amountRead;
	attr_info	 attributeInfo;
	const char	*classificationString;
	off_t		 dataSize;
	BPositionIO	*dataStreamPntr = *io_message;
	status_t	 errorCode = B_OK;
	int32        headerLength;
	BString      headerString;
	BString		 newSubjectString;
	BNode        nodeForOutputFile;
	bool		 nodeForOutputFileInitialised = false;
	const char	*oldSubjectStringPntr;
	char         percentageString [30];
	BMessage	 replyMessage;
	BMessage	 scriptingMessage;
	team_id		 serverTeam;
	float		 spamRatio;
	char		*stringBuffer = NULL;
	char         tempChar;
	status_t     tempErrorCode;
	const char  *tokenizeModeStringPntr;

	// Set up a BNode to the final output file so that we can write custom
	// attributes to it.  Non-custom attributes are stored separately in
	// io_headers.

	if (io_entry != NULL && B_OK == nodeForOutputFile.SetTo (io_entry))
		nodeForOutputFileInitialised = true;

	// Get a connection to the spam database server.  Launch if needed, should
	// only need it once, unless another e-mail thread shuts down the server
	// inbetween messages.  This code used to be in InitCheck, but apparently
	// that isn't called.

	printf("Checking for Spam Server.\n");
	if (fLaunchAttemptCount == 0 || !fMessengerToServer.IsValid ()) {
		if (fLaunchAttemptCount > 3)
			goto ErrorExit; // Don't try to start the server too many times.
		fLaunchAttemptCount++;

		// Make sure the server is running.
		if (!be_roster->IsRunning (kServerSignature)) {
			errorCode = be_roster->Launch (kServerSignature);
			if (errorCode != B_OK) {
				BPath path;
				entry_ref ref;
				directory_which places[] = {B_COMMON_BIN_DIRECTORY,B_BEOS_BIN_DIRECTORY};
				for (int32 i = 0; i < 2; i++) {
					find_directory(places[i],&path);
					path.Append("spamdbm");
					if (!BEntry(path.Path()).Exists())
						continue;
					get_ref_for_path(path.Path(),&ref);
					if ((errorCode =  be_roster->Launch (&ref)) == B_OK)
						break;
				}
				if (errorCode != B_OK)
					goto ErrorExit;
			}
		}

		// Set up the messenger to the database server.
		serverTeam = be_roster->TeamFor (kServerSignature);
		if (serverTeam < 0)
			goto ErrorExit;
		fMessengerToServer =
			BMessenger (kServerSignature, serverTeam, &errorCode);
		if (!fMessengerToServer.IsValid ())
			goto ErrorExit;

		// Check if the server is running in headers only mode.  If so, we only
		// need to download the header rather than the entire message.
		scriptingMessage.MakeEmpty ();
		scriptingMessage.what = B_GET_PROPERTY;
		scriptingMessage.AddSpecifier ("TokenizeMode");
		replyMessage.MakeEmpty ();
		if ((errorCode = fMessengerToServer.SendMessage (&scriptingMessage,
			&replyMessage)) != B_OK)
			goto ErrorExit;
		if ((errorCode = replyMessage.FindInt32 ("error", &tempErrorCode))
			!= B_OK)
			goto ErrorExit;
		if ((errorCode = tempErrorCode) != B_OK)
			goto ErrorExit;
		if ((errorCode = replyMessage.FindString ("result",
			&tokenizeModeStringPntr)) != B_OK)
			goto ErrorExit;
		fHeaderOnly = (tokenizeModeStringPntr != NULL
			&& strcmp (tokenizeModeStringPntr, "JustHeader") == 0);
	}

	// See if the message has already been classified.  Happens for messages
	// which are partially downloaded when you have auto-training on.  Could
	// untrain the partial part before training on the complete message, but we
	// don't know how big it was, so instead just ignore the message.

	if (nodeForOutputFileInitialised) {
		if (nodeForOutputFile.GetAttrInfo ("MAIL:classification",
			&attributeInfo) == B_OK)
			return B_OK;
	}

	// Copy the message to a string so that we can pass it to the spam database
	// (the even messier alternative is a temporary file).  Do it in a fashion
	// which allows NUL bytes in the string.  This method of course limits the
	// message size to a few hundred megabytes.  If we're using header mode,
	// only read the header rather than the full message.

	if (fHeaderOnly) {
		// Read just the header, it ends with an empty CRLF line.
		dataStreamPntr->Seek (0, SEEK_SET);
		while ((errorCode = dataStreamPntr->Read (&tempChar, 1)) == 1) {
			headerString.Append (tempChar, 1);
			headerLength = headerString.Length();
			if (headerLength >= 4 && strcmp (headerString.String() +
				headerLength - 4, "\r\n\r\n") == 0)
				break;
		}
		if (errorCode < 0)
			goto ErrorExit;

		dataSize = headerString.Length();
		stringBuffer = new char [dataSize + 1];
		memcpy (stringBuffer, headerString.String(), dataSize);
		stringBuffer[dataSize] = 0;
	} else {
		// Read the whole file.  The seek to the end may take a while since
		// that triggers downloading of the entire message (and caching in a
		// slave file - see the MessageIO class).
		dataSize = dataStreamPntr->Seek (0, SEEK_END);
		if (dataSize <= 0)
			goto ErrorExit;

		try {
			stringBuffer = new char [dataSize + 1];
		} catch (...) {
			errorCode = ENOMEM;
			goto ErrorExit;
		}

		dataStreamPntr->Seek (0, SEEK_SET);
		amountRead = dataStreamPntr->Read (stringBuffer, dataSize);
		if (amountRead != dataSize)
			goto ErrorExit;
		stringBuffer[dataSize] = 0; // Add an end of string NUL, just in case.
	}

	// Send off a scripting command to the database server, asking it to
	// evaluate the string for spaminess.  Note that it can return ENOMSG
	// when there are no words (a good indicator of spam which is pure HTML
	// if you are using plain text only tokenization), so we could use that
	// as a spam marker too.  Code copied for the reevaluate stuff below.

	scriptingMessage.MakeEmpty ();
	scriptingMessage.what = B_SET_PROPERTY;
	scriptingMessage.AddSpecifier ("EvaluateString");
	errorCode = scriptingMessage.AddData ("data", B_STRING_TYPE,
		stringBuffer, dataSize + 1, false /* fixed size */);
	if (errorCode != B_OK)
		goto ErrorExit;
	replyMessage.MakeEmpty ();
	errorCode = fMessengerToServer.SendMessage (&scriptingMessage,
		&replyMessage);
	if (errorCode != B_OK
		|| replyMessage.FindInt32 ("error", &errorCode) != B_OK)
		goto ErrorExit; // Unable to read the return code.
	if (errorCode == ENOMSG && fNoWordsMeansSpam)
		spamRatio = fSpamCutoffRatio; // Yes, no words and that means spam.
	else if (errorCode != B_OK
		|| replyMessage.FindFloat ("result", &spamRatio) != B_OK)
		goto ErrorExit; // Classification failed in one of many ways.

	// If we are auto-training, feed back the message to the server as a
	// training example (don't train if it is uncertain).  Also redo the
	// evaluation after training.

	if (fAutoTraining) {
		if (spamRatio >= fSpamCutoffRatio || spamRatio < fGenuineCutoffRatio) {
			scriptingMessage.MakeEmpty ();
			scriptingMessage.what = B_SET_PROPERTY;
			scriptingMessage.AddSpecifier ((spamRatio >= fSpamCutoffRatio)
				? "SpamString" : "GenuineString");
			errorCode = scriptingMessage.AddData ("data", B_STRING_TYPE,
				stringBuffer, dataSize + 1, false /* fixed size */);
			if (errorCode != B_OK)
				goto ErrorExit;
			replyMessage.MakeEmpty ();
			errorCode = fMessengerToServer.SendMessage (&scriptingMessage,
				&replyMessage);
			if (errorCode != B_OK
				|| replyMessage.FindInt32 ("error", &errorCode) != B_OK)
				goto ErrorExit; // Unable to read the return code.
			if (errorCode != B_OK)
				goto ErrorExit; // Failed to set a good example.
		}

		// Note the kind of example made so that the user doesn't reclassify
		// the message twice (the spam server looks for this attribute).

		classificationString =
			(spamRatio >= fSpamCutoffRatio)
			? "Spam"
			: ((spamRatio < fGenuineCutoffRatio) ? "Genuine" : "Uncertain");
		if (nodeForOutputFileInitialised)
			nodeForOutputFile.WriteAttr ("MAIL:classification", B_STRING_TYPE,
				0 /* offset */, classificationString,
				strlen (classificationString) + 1);

		// Now that the database has changed due to training, recompute the
		// spam ratio.  Hopefully it will have become more extreme in the
		// correct direction (not switched from being spam to being genuine).
		// Code copied from above.

		scriptingMessage.MakeEmpty ();
		scriptingMessage.what = B_SET_PROPERTY;
		scriptingMessage.AddSpecifier ("EvaluateString");
		errorCode = scriptingMessage.AddData ("data", B_STRING_TYPE,
			stringBuffer, dataSize + 1, false /* fixed size */);
		if (errorCode != B_OK)
			goto ErrorExit;
		replyMessage.MakeEmpty ();
		errorCode = fMessengerToServer.SendMessage (&scriptingMessage,
			&replyMessage);
		if (errorCode != B_OK
			|| replyMessage.FindInt32 ("error", &errorCode) != B_OK)
			goto ErrorExit; // Unable to read the return code.
		if (errorCode == ENOMSG && fNoWordsMeansSpam)
			spamRatio = fSpamCutoffRatio; // Yes, no words and that means spam.
		else if (errorCode != B_OK
			|| replyMessage.FindFloat ("result", &spamRatio) != B_OK)
			goto ErrorExit; // Classification failed in one of many ways.
	}

	// Store the spam ratio in an attribute called MAIL:ratio_spam,
	// attached to the eventual output file.

	if (nodeForOutputFileInitialised)
		nodeForOutputFile.WriteAttr ("MAIL:ratio_spam",
			B_FLOAT_TYPE, 0 /* offset */, &spamRatio, sizeof (spamRatio));

	// Also add it to the subject, if requested.

	if (fAddSpamToSubject
		&& spamRatio >= fSpamCutoffRatio
		&& io_headers->FindString ("Subject", &oldSubjectStringPntr) == B_OK) {
		newSubjectString.SetTo ("[Spam ");
		sprintf (percentageString, "%05.2f", spamRatio * 100.0);
		newSubjectString << percentageString << "%] ";
		newSubjectString << oldSubjectStringPntr;
		io_headers->ReplaceString ("Subject", newSubjectString);
	}

	// Beep using different sounds for spam and genuine, as Jeremy Friesner
	// nudged me to get around to implementing.  And add uncertain to that, as
	// "BiPolar" suggested.  If the user doesn't want to hear the sound, they
	// can turn it off in the system sound preferences.

	if (spamRatio >= fSpamCutoffRatio) {
		system_beep (kAGMSBayesBeepSpamName);
	} else if (spamRatio < fGenuineCutoffRatio) {
		system_beep (kAGMSBayesBeepGenuineName);
	} else {
		system_beep (kAGMSBayesBeepUncertainName);
	}

	return B_OK;

ErrorExit:
	fprintf (stderr, "Error exit from "
		"SpamFilter::ProcessMailMessage, code maybe %ld (%s).\n",
		errorCode, strerror (errorCode));
	delete [] stringBuffer;
	return B_OK; // Not MD_ERROR so the message doesn't get left on server.
}
Example #21
0
void
TMailApp::ReadyToRun()
{
	// Create needed indices for META:group, META:email, MAIL:draft,
	// INDEX_SIGNATURE, INDEX_STATUS on the boot volume

	BVolume volume;
	BVolumeRoster().GetBootVolume(&volume);

	fs_create_index(volume.Device(), "META:group", B_STRING_TYPE, 0);
	fs_create_index(volume.Device(), "META:email", B_STRING_TYPE, 0);
	fs_create_index(volume.Device(), "MAIL:draft", B_INT32_TYPE, 0);
	fs_create_index(volume.Device(), INDEX_SIGNATURE, B_STRING_TYPE, 0);
	fs_create_index(volume.Device(), INDEX_STATUS, B_STRING_TYPE, 0);
	fs_create_index(volume.Device(), B_MAIL_ATTR_FLAGS, B_INT32_TYPE, 0);

	// Start people queries
	fPeopleQueryList.Init("META:email=**");

	// Load dictionaries
	BPath indexDir;
	BPath dictionaryDir;
	BPath userDictionaryDir;
	BPath userIndexDir;
	BPath dataPath;
	BPath indexPath;
	BDirectory directory;
	BEntry entry;

	// Locate dictionaries directory
	find_directory(B_SYSTEM_DATA_DIRECTORY, &indexDir, true);
	indexDir.Append("spell_check");
	dictionaryDir = indexDir;

	//Locate user dictionary directory
	find_directory(B_USER_CONFIG_DIRECTORY, &userIndexDir, true);
	userIndexDir.Append("data/spell_check");
	userDictionaryDir = userIndexDir;

	// Create directory if needed
	directory.CreateDirectory(userIndexDir.Path(),  NULL);

	// Setup directory paths
	indexDir.Append(kIndexDirectory);
	dictionaryDir.Append(kDictDirectory);
	userIndexDir.Append(kIndexDirectory);
	userDictionaryDir.Append(kDictDirectory);

	// Create directories if needed
	directory.CreateDirectory(indexDir.Path(), NULL);
	directory.CreateDirectory(dictionaryDir.Path(), NULL);
	directory.CreateDirectory(userIndexDir.Path(), NULL);
	directory.CreateDirectory(userDictionaryDir.Path(), NULL);

	dataPath = dictionaryDir;
	dataPath.Append("words");

	// Only Load if Words Dictionary
	if (BEntry(kWordsPath).Exists() || BEntry(dataPath.Path()).Exists()) {
		// If "/boot/optional/goodies/words" exists but there is no
		// system dictionary, copy words
		if (!BEntry(dataPath.Path()).Exists() && BEntry(kWordsPath).Exists()) {
			BFile words(kWordsPath, B_READ_ONLY);
			BFile copy(dataPath.Path(), B_WRITE_ONLY | B_CREATE_FILE);
			char buffer[4096];
			ssize_t size;

			while ((size = words.Read( buffer, 4096)) > 0)
				copy.Write(buffer, size);
			BNodeInfo(&copy).SetType("text/plain");
		}

		// Load dictionaries
		directory.SetTo(dictionaryDir.Path());

		BString leafName;
		gUserDict = -1;

		while (gDictCount < MAX_DICTIONARIES
			&& directory.GetNextEntry(&entry) != B_ENTRY_NOT_FOUND) {
			dataPath.SetTo(&entry);

			indexPath = indexDir;
			leafName.SetTo(dataPath.Leaf());
			leafName.Append(kMetaphone);
			indexPath.Append(leafName.String());
			gWords[gDictCount] = new Words(dataPath.Path(), indexPath.Path(), true);

			indexPath = indexDir;
			leafName.SetTo(dataPath.Leaf());
			leafName.Append(kExact);
			indexPath.Append(leafName.String());
			gExactWords[gDictCount] = new Words(dataPath.Path(), indexPath.Path(), false);
			gDictCount++;
		}

		// Create user dictionary if it does not exist
		dataPath = userDictionaryDir;
		dataPath.Append("user");
		if (!BEntry(dataPath.Path()).Exists()) {
			BFile user(dataPath.Path(), B_WRITE_ONLY | B_CREATE_FILE);
			BNodeInfo(&user).SetType("text/plain");
		}

		// Load user dictionary
		if (BEntry(userDictionaryDir.Path()).Exists()) {
			gUserDictFile = new BFile(dataPath.Path(), B_WRITE_ONLY | B_OPEN_AT_END);
			gUserDict = gDictCount;

			indexPath = userIndexDir;
			leafName.SetTo(dataPath.Leaf());
			leafName.Append(kMetaphone);
			indexPath.Append(leafName.String());
			gWords[gDictCount] = new Words(dataPath.Path(), indexPath.Path(), true);

			indexPath = userIndexDir;
			leafName.SetTo(dataPath.Leaf());
			leafName.Append(kExact);
			indexPath.Append(leafName.String());
			gExactWords[gDictCount] = new Words(dataPath.Path(), indexPath.Path(), false);
			gDictCount++;
		}
	}

	// Create a new window if starting up without any extra arguments.

	if (!fPrintHelpAndExit && !fWindowCount) {
		TMailWindow	*window;
		window = NewWindow();
		window->Show();
	}
}
Example #22
0
status_t
InterfaceHardwareView::Update()
{
	// Populate fields with current settings
	if (fSettings->HasLink()) {
		if (fSettings->IsWireless()) {
			BString network = fSettings->WirelessNetwork();
			network.Prepend(" (");
			network.Prepend(B_TRANSLATE("connected"));
			network.Append(")");
			fStatusField->SetText(network.String());
		} else {
			fStatusField->SetText(B_TRANSLATE("connected"));
		}
	} else
		fStatusField->SetText(B_TRANSLATE("disconnected"));

	fMacAddressField->SetText(fSettings->HardwareAddress());

	// TODO : Find how to get link speed
	fLinkSpeedField->SetText("100 Mb/s");

	// Update Link stats
	ifreq_stats stats;
	char buffer[100];
	fSettings->Stats(&stats);

	string_for_size(stats.send.bytes, buffer, sizeof(buffer));
	fLinkTxField->SetText(buffer);

	string_for_size(stats.receive.bytes, buffer, sizeof(buffer));
	fLinkRxField->SetText(buffer);

	// TODO move the wireless info to a separate tab. We should have a
	// BListView of available networks, rather than a menu, to make them more
	// readable and easier to browse and select.
	if (fNetworkMenuField->IsHidden(fNetworkMenuField)
		&& fSettings->IsWireless()) {
		fNetworkMenuField->Show();
	} else if (!fNetworkMenuField->IsHidden(fNetworkMenuField)
		&& !fSettings->IsWireless()) {
		fNetworkMenuField->Hide();
	}

	if (fSettings->IsWireless()) {
		// Rebuild network menu
		BMenu* menu = fNetworkMenuField->Menu();
		menu->RemoveItems(0, menu->CountItems(), true);

		std::set<BNetworkAddress> associated;
		BNetworkAddress address;
		uint32 cookie = 0;
		while (fSettings->GetNextAssociatedNetwork(cookie, address) == B_OK)
			associated.insert(address);

		wireless_network network;
		int32 count = 0;
		cookie = 0;
		while (fSettings->GetNextNetwork(cookie, network) == B_OK) {
			BMessage* message = new BMessage(kMsgNetwork);

			message->AddString("device", fSettings->Name());
			message->AddString("name", network.name);

			BMenuItem* item = new WirelessNetworkMenuItem(network.name,
				network.signal_strength,
				network.authentication_mode, message);
			if (associated.find(network.address) != associated.end())
				item->SetMarked(true);
			menu->AddItem(item);

			count++;
		}
		if (count == 0) {
			BMenuItem* item = new BMenuItem(
				B_TRANSLATE("<no wireless networks found>"), NULL);
			item->SetEnabled(false);
			menu->AddItem(item);
		} else {
			BMenuItem* item = new BMenuItem(
				B_TRANSLATE("Choose automatically"), NULL);
			if (menu->FindMarked() == NULL)
				item->SetMarked(true);
			menu->AddItem(item, 0);
			menu->AddItem(new BSeparatorItem(), 1);
		}
		menu->SetTargetForItems(this);
	}

	fRenegotiate->SetEnabled(!fSettings->IsDisabled());
	fOnOff->SetLabel(fSettings->IsDisabled() ? "Enable" : "Disable");

	return B_OK;
}
Example #23
0
BUrl&
BUrl::SetPath(const BString& path)
{
	// Implements RFC3986 section 5.2.4, "Remove dot segments"

	// 1.
	BString output;
	BString input(path);

	// 2.
	while(!input.IsEmpty())
	{
		// 2.A.
		if (input.StartsWith("./"))
		{
			input.Remove(0, 2);
			continue;
		}

		if (input.StartsWith("../"))
		{
			input.Remove(0, 3);
			continue;
		}

		// 2.B.
		if (input.StartsWith("/./"))
		{
			input.Remove(0, 2);
			continue;
		}

		if (input == "/.")
		{
			input.Remove(1, 1);
			continue;
		}

		// 2.C.
		if (input.StartsWith("/../"))
		{
			input.Remove(0, 3);
			output.Truncate(output.FindLast('/'));
			continue;
		}

		if (input == "/..")
		{
			input.Remove(1, 2);
			output.Truncate(output.FindLast('/'));
			continue;
		}

		// 2.D.
		if (input == "." || input == "..")
		{
			break;
		}

		if (input == "/.")
		{
			input.Remove(1, 1);
			continue;
		}

		// 2.E.
		int slashpos = input.FindFirst('/', 1);
		if (slashpos > 0) {
			output.Append(input, slashpos);
			input.Remove(0, slashpos);
		} else {
			output.Append(input);
			break;
		}
	}

	_SetPathUnsafe(output);
	return *this;
}
Example #24
0
int32
MessageWindow::DCCOut (void *arg)
{
  MessageWindow *mWin ((MessageWindow *)arg);
  struct sockaddr_in sa;
  int status;
  char *endpoint;
  u_long realIP = strtoul (mWin->dIP.String(), &endpoint, 10);

  if ((mWin->acceptSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  {
    BMessage msg (M_DISPLAY);

    mWin->PackDisplay (&msg, "Error opening socket.\n", 0);
    mWin->PostMessage (&msg);
    return false;
  }
	
  sa.sin_family = AF_INET;
  sa.sin_port = htons (atoi (mWin->dPort.String()));
  sa.sin_addr.s_addr = ntohl (realIP);
  memset (sa.sin_zero, 0, sizeof(sa.sin_zero));

  {
    BMessage msg (M_DISPLAY);
    BString buffer;
    struct in_addr addr;

    addr.s_addr = ntohl (realIP);

    buffer << "Trying to connect to address "
      << inet_ntoa (addr)
      << " port " << mWin->dPort << "\n";
    
    mWin->PackDisplay (&msg, buffer.String(), 0);
    mWin->PostMessage (&msg);
  }

  status = connect (mWin->acceptSocket, (struct sockaddr *)&sa, sizeof(sa));
  if (status < 0)
  {
    BMessage msg (M_DISPLAY);

    mWin->PackDisplay (&msg, "Error connecting socket.\n", 0);
    mWin->PostMessage (&msg);
    close (mWin->mySocket);
    return false;
  }

  mWin->dConnected = true;

  BMessage msg (M_DISPLAY);
  mWin->PackDisplay (&msg, "Connected!\n", 0);
  mWin->PostMessage (&msg);

  char tempBuffer[2];
  BString inputBuffer;
	
  while (mWin->dConnected)
  {
    snooze(10000);
    while (mWin->dConnected && mWin->DataWaiting())
    {
      if (recv (mWin->acceptSocket, tempBuffer, 1, 0) == 0)
      {
        BMessage msg (M_DISPLAY);

         mWin->dConnected = false;
         mWin->PackDisplay (&msg, "DCC chat terminated.\n", 0);
         mWin->PostMessage (&msg);
         goto outta_loop; // I hate goto, but this is a good use.
       }

       if (tempBuffer[0] == '\n')
       {
         mWin->ChannelMessage (inputBuffer.String());
         inputBuffer = "";
       }
       else
         inputBuffer.Append(tempBuffer[0],1);
     }
  }
	
  outta_loop: // GOTO MARKER

  close (mWin->acceptSocket);
  
  return 0;
}
Example #25
0
File: smtp.cpp Project: DonCN/haiku
//! Receives response from server.
int32
SMTPProtocol::ReceiveResponse(BString &out)
{
	out = "";
	int32 len = 0,r;
	char buf[SMTP_RESPONSE_SIZE];
	bigtime_t timeout = 1000000*180; // timeout 180 secs
	bool gotCode = false;
	int32 errCode;
	BString searchStr = "";

	struct timeval tv;
	struct fd_set fds;

	tv.tv_sec = long(timeout / 1e6);
	tv.tv_usec = long(timeout-(tv.tv_sec * 1e6));

	/* Initialize (clear) the socket mask. */
	FD_ZERO(&fds);

	/* Set the socket in the mask. */
	FD_SET(fSocket, &fds);
        int result = -1;
#ifdef USE_SSL
        if ((use_ssl) && (SSL_pending(ssl)))
            result = 1;
        else
#endif
            result = select(1 + fSocket, &fds, NULL, NULL, &tv);
	if (result < 0)
		return errno;

	if (result > 0) {
		while (1) {
                 #ifdef USE_SSL
			if (use_ssl)
				r = SSL_read(ssl,buf,SMTP_RESPONSE_SIZE - 1);
			else
		  #endif
			r = recv(fSocket,buf, SMTP_RESPONSE_SIZE - 1,0);
			if (r <= 0)
				break;

			if (!gotCode)
			{
				if (buf[3] == ' ' || buf[3] == '-')
				{
					errCode = atol(buf);
					gotCode = true;
					searchStr << errCode << ' ';
				}
			}

			len += r;
			out.Append(buf, r);

			if (strstr(buf, CRLF) && (out.FindFirst(searchStr) != B_ERROR))
				break;
		}
	} else
		fLog = "SMTP socket timeout.";

	D(bug("S:%s\n", out.String()));
	return len;
}
Example #26
0
void
QPopupMenu::AddPersonItem(const entry_ref *ref, ino_t node, BString &name,
	BString &email, const char *attr, BMenu *groupMenu, BMenuItem *superItem)
{
	BString	label;
	BString	sortKey;
		// For alphabetical order sorting, usually last name.

	// if we have no Name, just use the email address
	if (name.Length() == 0) {
		label = email;
		sortKey = email;
	} else {
		// otherwise, pretty-format it
		label << name << " (" << email << ")";

		// Extract the last name (last word in the name),
		// removing trailing and leading spaces.
		const char *nameStart = name.String();
		const char *string = nameStart + strlen(nameStart) - 1;
		const char *wordEnd;

		while (string >= nameStart && isspace(*string))
			string--;
		wordEnd = string + 1; // Points to just after last word.
		while (string >= nameStart && !isspace(*string))
			string--;
		string++; // Point to first letter in the word.
		if (wordEnd > string)
			sortKey.SetTo(string, wordEnd - string);
		else // Blank name, pretend that the last name is after it.
			string = nameStart + strlen(nameStart);

		// Append the first names to the end, so that people with the same last
		// name get sorted by first name.  Note no space between the end of the
		// last name and the start of the first names, but that shouldn't
		// matter for sorting.
		sortKey.Append(nameStart, string - nameStart);
	}

	// The target (a TTextControl) will examine all the People files specified
	// and add the emails and names to the string it is displaying (same code
	// is used for drag and drop of People files).
	BMessage *msg = new BMessage(B_SIMPLE_DATA);
	msg->AddRef("refs", ref);
	msg->AddInt64("node", node);
	if (attr) // For nonstandard e-mail attributes, like META:email3
		msg->AddString("attr", attr);
	msg->AddString("sortkey", sortKey);

	BMenuItem *newItem = new BMenuItem(label.String(), msg);
	if (fTargetHandler)
		newItem->SetTarget(fTargetHandler);

	// If no group, just add it to ourself; else add it to group menu
	BMenu *parentMenu = groupMenu ? groupMenu : this;
	if (groupMenu) {
		// Add ref to group super item.
		BMessage *superMsg = superItem->Message();
		superMsg->AddRef("refs", ref);
	}

	// Add it to the appropriate menu.  Use alphabetical order by sortKey to
	// insert it in the right spot (a dumb linear search so this will be slow).
	// Start searching from the end of the menu, since the main menu includes
	// all the groups at the top and we don't want to mix it in with them.
	// Thus the search starts at the bottom and ends when we hit a separator
	// line or the top of the menu.

	int32 index = parentMenu->CountItems();
	while (index-- > 0) {
		BMenuItem *item = parentMenu->ItemAt(index);
		if (item == NULL ||	dynamic_cast<BSeparatorItem *>(item) != NULL)
			break;

		BMessage *message = item->Message();
		BString key;

		// Stop when testKey < sortKey.
		if (message != NULL
			&& message->FindString("sortkey", &key) == B_OK
			&& ICompare(key, sortKey) < 0)
			break;
	}

	if (!parentMenu->AddItem(newItem, index + 1)) {
		fprintf (stderr, "QPopupMenu::AddPersonItem: Unable to add menu "
			"item \"%s\" at index %ld.\n", sortKey.String(), index + 1);
		delete newItem;
	}
}
Example #27
0
int main(int argc, char* argv[])
{
	BApplication mailApp(APP_SIG);

	// No arguments, show usage
	if (argc < 2) {
		fprintf(stdout,"This program can only send mail, not read it.\n");
		fprintf(stdout,"usage: %s [-v] [-s subject] [-c cc-addr] "
			"[-b bcc-addr] to-addr ...\n", argv[0]);
		fflush(stdout);
		return 0;
	}

	char *subject = "No title";
	char *cc = "";
	char *bcc = "";
	BString to = "";
	BString body = "";

	bool verbose =false;
	// Parse arguments
	for (int i = 1; i < argc; i++) {
		if (strcmp(argv[i], "-v") == 0)
			verbose = true;
		else if (strcmp(argv[i], "-s") == 0) {
			subject = argv[i+1];
			i++;
		} else if (strcmp(argv[i], "-c") == 0) {
			cc = argv[i+1];
			i++;
 		} else if (strcmp(argv[i], "-b") == 0) {
 			bcc = argv[i+1];
 			i++;
		} else {
			to.Append(argv[i]);
			if (i < argc - 1)
				to.Append(" ");
  		}
	}

	if (verbose) {
		fprintf(stdout, "\n");
		fprintf(stdout, "To:\t<%s> \n", to.String());
		fprintf(stdout, "Cc:\t<%s> \n", cc);
		fprintf(stdout, "Bcc:\t<%s> \n", bcc);
		fprintf(stdout, "Subj:\t<%s> \n", subject);
		fprintf(stdout, "Body:\t<%s> \n", body.String());
    	fprintf(stdout, "\n");
	}

	// Check if recipients are valid
    if (strcmp(to.String(), "") == 0 &&
    	strcmp(cc, "") == 0 &&
    	strcmp(bcc, "") == 0) {

		fprintf(stdout, "[Error]: You must specify at least one recipient "
			"in to, cc or bcc fields.\n");
		return -1;
	}

	// Read each line until we get a single dot "." on a line
	char line[32768] = "";

	printf("Now type your message.\nType '.' alone on a line to send it.\n");
	do {
	    gets(line);

	    if (strcmp(line, ".") != 0) {
	    	body.Append(line).Append("\n");
		}
	    // fprintf(stdout,"Line: %s \n",line);
	} while (strcmp(line, ".") != 0);


	if (verbose)
   		fprintf(stdout, "\nBody:\n%s\n", body.String());

	if (verbose)
   		fprintf(stdout, "\nSending E-mail...\n");
	fflush(stdout);

	BMailMessage mail;
	mail.AddHeaderField(B_MAIL_TO, to.String());
	mail.AddHeaderField(B_MAIL_CC, cc);
	mail.AddHeaderField(B_MAIL_BCC, bcc);
	mail.AddHeaderField(B_MAIL_SUBJECT, subject);
	mail.AddContent(body.String(), strlen(body.String()));
	status_t result = mail.Send();

	if (result == B_OK) {
		fprintf(stdout, "\nMessage was sent successfully.\n");
		return 0;
	}

	fprintf(stdout, "Message failed to send: %s", strerror(result));
	return result;
}
Example #28
0
void
THeaderView::InitGroupCompletion()
{
	// get boot volume
	BVolume volume;
	BVolumeRoster().GetBootVolume(&volume);

	// Build a list of all unique groups and the addresses they expand to.
	BQuery query;
	query.SetVolume(&volume);
	query.SetPredicate("META:group=**");
	query.Fetch();

	map<BString *, BString *, CompareBStrings> groupMap;
	entry_ref ref;
	BNode file;
	while (query.GetNextRef(&ref) == B_OK) {
		if (file.SetTo(&ref) != B_OK)
			continue;

		BString groups;
		if (file.ReadAttrString("META:group", &groups) < B_OK || groups.Length() == 0)
			continue;

		BString address;
		file.ReadAttrString("META:email", &address);

		// avoid adding an empty address
		if (address.Length() == 0)
			continue;

		char *group = groups.LockBuffer(groups.Length());
		char *next = strchr(group, ',');

		for (;;) {
			if (next)
				*next = 0;

			while (*group && *group == ' ')
				group++;

			BString *groupString = new BString(group);
			BString *addressListString = NULL;

			// nobody is in this group yet, start it off
			if (groupMap[groupString] == NULL) {
				addressListString = new BString(*groupString);
				addressListString->Append(" ");
				groupMap[groupString] = addressListString;
			} else {
				addressListString = groupMap[groupString];
				addressListString->Append(", ");
				delete groupString;
			}

			// Append the user's address to the end of the string with the
			// comma separated list of addresses.  If not present, add the
			// < and > brackets around the address.

			if (address.FindFirst ('<') < 0) {
				address.ReplaceAll ('>', '_');
				address.Prepend ("<");
				address.Append(">");
			}
			addressListString->Append(address);

			if (!next)
				break;

			group = next + 1;
			next = strchr(group, ',');
		}
	}

	map<BString *, BString *, CompareBStrings>::iterator iter;
	for (iter = groupMap.begin(); iter != groupMap.end();) {
		BString *group = iter->first;
		BString *addr = iter->second;
		fEmailList.AddChoice(addr->String());
		++iter;
		groupMap.erase(group);
		delete group;
		delete addr;
	}
}
Example #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;
}
Example #30
0
status_t SSO::SSLSend(const char *host, HTTPFormatter *send, HTTPFormatter **recv) {
	int err = B_OK;
	int sd;
	struct sockaddr_in sa;
	struct hostent *hp;
	SSL_CTX *ctx;
	SSL *ssl;
	char buffer[1024];
	SSL_METHOD *meth;

	SSL_load_error_strings();
	SSLeay_add_ssl_algorithms();
	meth = SSLv23_client_method();
	ctx = SSL_CTX_new (meth);
	CHK_NULL(ctx);
	SSL_CTX_set_options(ctx, SSL_OP_ALL);

	/* ----------------------------------------------- */
	/* Create a socket and connect to server using normal socket calls. */
	sd = socket (AF_INET, SOCK_STREAM, 0);
	CHK_ERR(sd, "socket");

	// clear sa
	memset (&sa, '\0', sizeof(sa));
	
	// get address
	if ((hp= gethostbyname(host)) == NULL) { 
		sa.sin_addr.s_addr = inet_addr (host);   /* Server IP */
	} else {
		memcpy((char *)&sa.sin_addr,hp->h_addr,hp->h_length); /* set address */
	};
	
	sa.sin_family = AF_INET;
	sa.sin_port = htons(443);    /* Server Port number */
	
	err = connect(sd, (struct sockaddr*) &sa, sizeof(sa));
	CHK_ERR(err, "connect");
	
	/* ----------------------------------------------- */
	/* Now we have TCP conncetion. Start SSL negotiation. */
  
	ssl = SSL_new (ctx);                         CHK_NULL(ssl);    
	if (SSL_set_fd(ssl, sd) == 0) {
		LOG(kProtocolName, liDebug, "C %lX: SSL Error setting fd", this);
		return -1;
	};
	
    SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL);
	SSL_set_connect_state(ssl);
	
	err = SSL_connect (ssl);
	CHK_SSL(err);
	
	/* --------------------------------------------------- */
	/* DATA EXCHANGE - Send a message and receive a reply. */

	err = SSL_write(ssl, send->Flatten(), send->Length());
	CHK_SSL(err);
	
	if (err <= 0) {
		LOG(kProtocolName, liDebug, "C %lX: SSL Error writing. Err: %ld", this, SSL_get_error(ssl, err));
	};
	
	BString data;
	int received = 0;
	while (err > 0) {
		err = SSL_read(ssl, buffer, sizeof(buffer));
		CHK_SSL(err);
		if (err > 0) {
			received += err;
			data.Append(buffer, err);
			memset(buffer, 0, sizeof(buffer));
		};
	};

	*recv = new HTTPFormatter(data.String(), data.Length());
	LOG(kProtocolName, liDebug, "C %lX: Got %d chars", this, received);
	SSL_shutdown (ssl);  /* send SSL/TLS close_notify */
	
	/* Clean up. */
	close (sd);
	SSL_free (ssl);
	SSL_CTX_free (ctx);
	
	return received;
};