void
BrowserApp::ReadyToRun()
{
	// Since we will essentially run the GUI...
	set_thread_priority(Thread(), B_DISPLAY_PRIORITY);

	BWebPage::InitializeOnce();
	BWebPage::SetCacheModel(B_WEBKIT_CACHE_MODEL_WEB_BROWSER);

	BPath path;
	if (find_directory(B_USER_SETTINGS_DIRECTORY, &path) == B_OK
		&& path.Append(kApplicationName) == B_OK
		&& create_directory(path.Path(), 0777) == B_OK) {

		BWebSettings::SetPersistentStoragePath(path.Path());
	}

	BString mainSettingsPath(kApplicationName);
	mainSettingsPath << "/Application";
	fSettings = new SettingsMessage(B_USER_SETTINGS_DIRECTORY,
		mainSettingsPath.String());
#if ENABLE_NATIVE_COOKIES
	mainSettingsPath = kApplicationName;
	mainSettingsPath << "/Cookies";
	fCookies = new SettingsMessage(B_USER_SETTINGS_DIRECTORY,
		mainSettingsPath.String());
	BMessage cookieArchive;
	cookieArchive = fCookies->GetValue("cookies", cookieArchive);
	fCookieJar = new BNetworkCookieJar(cookieArchive);
	BWebPage::SetCookieJar(fCookieJar);
#endif

	fLastWindowFrame = fSettings->GetValue("window frame", fLastWindowFrame);
	BRect defaultDownloadWindowFrame(-10, -10, 365, 265);
	BRect downloadWindowFrame = fSettings->GetValue("downloads window frame",
		defaultDownloadWindowFrame);
	BRect settingsWindowFrame = fSettings->GetValue("settings window frame",
		BRect());
	bool showDownloads = fSettings->GetValue("show downloads", false);

	fDownloadWindow = new DownloadWindow(downloadWindowFrame, showDownloads,
		fSettings);
	if (downloadWindowFrame == defaultDownloadWindowFrame) {
		// Initially put download window in lower right of screen.
		BRect screenFrame = BScreen().Frame();
		BMessage decoratorSettings;
		fDownloadWindow->GetDecoratorSettings(&decoratorSettings);
		float borderWidth = 0;
		if (decoratorSettings.FindFloat("border width", &borderWidth) != B_OK)
			borderWidth = 5;
		fDownloadWindow->MoveTo(screenFrame.Width()
			- fDownloadWindow->Frame().Width() - borderWidth,
			screenFrame.Height() - fDownloadWindow->Frame().Height()
			- borderWidth);
	}
	fSettingsWindow = new SettingsWindow(settingsWindowFrame, fSettings);

	BWebPage::SetDownloadListener(BMessenger(fDownloadWindow));

	fInitialized = true;

	int32 pagesCreated = 0;
	bool fullscreen = false;
	if (fLaunchRefsMessage) {
		_RefsReceived(fLaunchRefsMessage, &pagesCreated, &fullscreen);
		delete fLaunchRefsMessage;
		fLaunchRefsMessage = NULL;
	}
	if (pagesCreated == 0)
		_CreateNewWindow("", fullscreen);

	PostMessage(PRELOAD_BROWSING_HISTORY);
}
Exemplo n.º 2
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.
}
Exemplo n.º 3
0
ProjectWindow::ProjectWindow(BRect frame, Project *project)
	:	DWindow(frame, "Paladin", B_DOCUMENT_WINDOW, B_NOT_ZOOMABLE |
													B_WILL_ACCEPT_FIRST_CLICK),
		fErrorWindow(NULL),
		fFilePanel(NULL),
		fProject(project),
		fSourceControl(NULL),
		fShowingLibs(false),
		fMenusLocked(false),
		fBuilder(BMessenger(this))
{
	AddCommonFilter(new AltTabFilter());
	SetSizeLimits(200,30000,200,30000);
	RegisterWindow();
	
	// This is for our in-program debug menu which comes in handy now and then.
	// Paladin -d doesn't always get the job done
	AddShortcut('9', B_COMMAND_KEY | B_SHIFT_KEY | B_CONTROL_KEY,
				new BMessage(M_TOGGLE_DEBUG_MENU));
	
	if (fProject)
	{
		fSourceControl = GetSCM(fProject->SourceControl());
		if (fSourceControl)
		{
			if (gPrintDebugMode > 0)
				fSourceControl->SetDebugMode(true);
			
			fSourceControl->SetUpdateCallback(SCMOutputCallback);
			fSourceControl->SetWorkingDirectory(fProject->GetPath().GetFolder());
			
			if (fSourceControl->NeedsInit(fProject->GetPath().GetFolder()))
				fSourceControl->CreateRepository(fProject->GetPath().GetFolder());
		}
	}
	
	BView *top = GetBackgroundView();
	
	BRect bounds(Bounds());
	BRect r(bounds);
	
	r.bottom = 16;
	fMenuBar = new BMenuBar(r,"documentbar");
	top->AddChild(fMenuBar);
	
	r = bounds;
	r.top = fMenuBar->Frame().bottom + 1;
	r.right -= B_V_SCROLL_BAR_WIDTH;
	r.bottom -= B_H_SCROLL_BAR_HEIGHT;
	
	fProjectList = new ProjectList(fProject, r,"filelist",B_FOLLOW_ALL);
	fProjectList->SetInvocationMessage(new BMessage(M_EDIT_FILE));
	
	BScrollView *scrollView = new BScrollView("scrollView",fProjectList,
											B_FOLLOW_ALL,0,false,true);
	top->AddChild(scrollView);
	fProjectList->SetTarget(this);
	
	r.top = r.bottom + 1;
	r.bottom = Bounds().bottom;
	fStatusBar = new BStringView(r,"statusbar", NULL, B_FOLLOW_LEFT_RIGHT |
														B_FOLLOW_BOTTOM);
	top->AddChild(fStatusBar);
	
	fStatusBar->SetViewColor(235,235,235);
	fStatusBar->SetFontSize(10.0);
	
	SetupMenus();
	
	if (project)
	{
		BString title("Paladin: ");
		title << project->GetName();
		SetTitle(title.String());
		
		for (int32 i = 0; i < project->CountGroups(); i++)
		{
			SourceGroup *group = project->GroupAt(i);
			SourceGroupItem *groupitem = new SourceGroupItem(group);
			fProjectList->AddItem(groupitem);
			groupitem->SetExpanded(group->expanded);
			
			for (int32 j = 0; j < group->filelist.CountItems(); j++)
			{
				SourceFile *file = group->filelist.ItemAt(j);
				SourceFileItem *fileitem = new SourceFileItem(file,1);
				
//				fProjectList->AddUnder(fileitem,groupitem);
				fProjectList->AddItem(fileitem);
				
				BString abspath = file->GetPath().GetFullPath();
				if (abspath[0] != '/')
				{
					abspath.Prepend("/");
					abspath.Prepend(project->GetPath().GetFolder());
				}
				BEntry entry(abspath.String());
				if (entry.Exists())
				{
					if (project->CheckNeedsBuild(file,false))
					{
						fileitem->SetDisplayState(SFITEM_NEEDS_BUILD);
						fProjectList->InvalidateItem(fProjectList->IndexOf(fileitem));
					}
					else
						file->SetBuildFlag(BUILD_NO);
				}
				else
				{
					fileitem->SetDisplayState(SFITEM_MISSING);
					fProjectList->InvalidateItem(fProjectList->IndexOf(fileitem));
				}
			}
		}
	}
	
	BNode node(fProject->GetPath().GetFullPath());
	if (node.ReadAttr("project_frame",B_RECT_TYPE,0,&r,sizeof(BRect)) == sizeof(BRect))
	{
		if (r.Width() < 200)
			r.right = r.left + 200;
		if (r.Height() < 200)
			r.top = r.bottom + 200;
		MoveTo(r.left,r.top);
		ResizeTo(r.Width(),r.Height());
	}
	
	fProjectList->MakeFocus(true);
	
	if (gShowFolderOnOpen)
	{
		// Duplicated code from MessageReceived::M_SHOW_PROJECT_FOLDER. Doing
		// it here in combo with snooze() makes it much more likely that the
		// opened project window is frontmost instead of the project folder's window
		entry_ref ref;
		BEntry(fProject->GetPath().GetFolder()).GetRef(&ref);
		BMessenger msgr("application/x-vnd.Be-TRAK");
		
		BMessage reply;
		BMessage openmsg(B_REFS_RECEIVED);
		openmsg.AddRef("refs",&ref);
		msgr.SendMessage(&openmsg);
		snooze(50000);
	}
	
	if (gAutoSyncModules)
		PostMessage(M_SYNC_MODULES);
}
Exemplo n.º 4
0
void MSNManager::MessageReceived(BMessage *msg) {
	switch (msg->what) {
		case msnMessageRecveived: {
			BString passport = msg->FindString("passport");
			BString message = msg->FindString("message");

			fHandler->MessageFromUser(passport.String(), message.String());
		} break;
		
		case msnmsgStatusChanged: {
			uint8 status = msg->FindInt8("status");
			BString passport = msg->FindString("passport");
			fHandler->StatusChanged(passport.String(), (online_types)status);
		} break;
		
		case msnmsgOurStatusChanged: {
			uint8 status = msg->FindInt8("status");
			fHandler->StatusChanged(fPassport.String(), (online_types)status);
			fConnectionState = status;
		} break;
		
		case msnmsgNewConnection: {
			int16 port = 0;
			char *host = NULL;
			const char *type = NULL;

			if (msg->FindString("host", (const char **)&host) != B_OK) {
				LOG(kProtocolName, liLow, "Got a malformed new connection message"
					" (Host)");
				return;
			};
			if (msg->FindInt16("port", &port) != B_OK) {
				LOG(kProtocolName, liLow, "Got a malformed new connection message"
					" (Port)");
				return;
			};
			
			msg->FindString("type", &type);
			
			LOG(kProtocolName, liDebug, "Got a new connection to \"%s\":%i of type \"%s\"", host,
				port, type);
			
			if (strcmp(type, "NS") == 0) {
				//MSNConnection *con = new MSNConnection(host, port, this);
				MSNConnection *con = *fConnectionPool.begin();
				fConnectionPool.pop_front();
				fConnectionPool.push_back( new MSNConnection() );
				con->SetTo( host, port, this );
				//con->Lock();
				
				Command *command = new Command("VER");
				command->AddParam(kProtocolsVers);
					
				con->Send(command);
				
				fNoticeCon = con;
					
				LOG(kProtocolName, liDebug, "  Set fNoticeCon");
				
				return;
			}
			
			if (strcmp(type, "RNG") == 0) {
				MSNSBConnection *con = new MSNSBConnection(host, port, this);
				//con->Run();
				
				const char *auth = msg->FindString("authString");
				const char *sessionID = msg->FindString("sessionID");
				//const char *inviter = msg->FindString("inviterPassport");
				
				Command *command = new Command("ANS");
				command->AddParam(fPassport.String());
				command->AddParam(auth);
				command->AddParam(sessionID);
				
				con->Send(command);
				
				fConnections.push_back( con );
				
				return;
			};
			
			if (strcmp(type, "SB") == 0) {
				MSNSBConnection *con = new MSNSBConnection(host, port, this);
				//con->Run();
				
				const char *authString = msg->FindString("authString");
				
				Command *command = new Command("USR");
				command->AddParam(Passport());
				command->AddParam(authString);
				
				con->Send(command);
				
				waitingmsgmap::iterator it = fWaitingSBs.begin();
				
				if (it != fWaitingSBs.end()) {
					BString passport = (*it).second.first;
					Command *message = (*it).second.second;
					
					Command *cal = new Command("CAL");
					cal->AddParam(passport.String());
					
					con->Send(cal, qsOnline);
					con->SendMessage(message);
					
					// assume it's a MSG here..
					fConnections.push_back( con );
					
					fWaitingSBs.erase( (*it).first );
				};
			};
		} break;

		case msnmsgCloseConnection: {
			MSNConnection *con = NULL;
			msg->FindPointer("connection", (void **)&con);
			
			if (con != NULL) {
				LOG(kProtocolName, liLow, "Connection (%lX) closed", con);
				
				std::list<thread_id> threads;
				
				if (con == fNoticeCon) {
					LOG(kProtocolName, liLow, "  Notice connection closed, go offline");
					connectionlist::iterator i;
					for (i = fConnections.begin(); i != fConnections.end(); i++) {
						threads.push_back( (*i)->Thread() );
						Command * bye = new Command("OUT");
						bye->UseTrID(false);
						(*i)->Send(bye, qsImmediate);
						BMessenger(*i).SendMessage(B_QUIT_REQUESTED);
					};
					
					fHandler->StatusChanged(Passport(), otOffline);
					
					fNoticeCon = NULL;
					fConnectionState = otOffline;
					LOG(kProtocolName, liDebug, "  Unset fNoticeCon");
				};
				
				threads.push_back( con->Thread() );
				BMessenger(con).SendMessage(B_QUIT_REQUESTED);
				
				connectionlist::iterator i = find(fConnections.begin(), fConnections.end(), con);
				
				if ( i != fConnections.end() )
					fConnections.erase( i );
				
				wait_for_threads( threads );
			};
		} break;
		
		case msnmsgRemoveConnection: {
			MSNConnection *con = NULL;
			msg->FindPointer("connection", (void **)&con);
			
			if (con != NULL) {
				connectionlist::iterator i = find(fConnections.begin(), fConnections.end(), con);
				
				LOG(kProtocolName, liLow, "Connection (%lX) removed", con);
				
				if ( i != fConnections.end() )
				{ // don't call anything in con, it's already deleted.
					fConnections.erase( i );
				}
				
				if ( con == fNoticeCon ) {
					std::list<thread_id> threads;
					
					LOG(kProtocolName, liLow, "  Notice connection closed, going offline");
					connectionlist::iterator i;
					for (i = fConnections.begin(); i != fConnections.end(); i++) {
						threads.push_back( (*i)->Thread() );
						Command * bye = new Command("OUT");
						bye->UseTrID(false);
						(*i)->Send(bye, qsImmediate);
						BMessenger(*i).SendMessage(B_QUIT_REQUESTED);
					}
					
					wait_for_threads( threads );
					
					fHandler->StatusChanged(Passport(), otOffline);
					
					fNoticeCon = NULL;
					fConnectionState = otOffline;
					
					LOG(kProtocolName, liDebug, "  Unset fNoticeCon");
				}
			};
		} break;
		
		case msnAuthRequest: {
			// check if that person is already in our AL before asking.
			BString display = msg->FindString("displayname");
			BString passport = msg->FindString("passport");
			list_types listType = (list_types)msg->FindInt8("list");
			
			Buddy *bud = new Buddy(passport.String());
			bud->Lists(listType);
			fWaitingAuth[passport] = bud;
			
			fHandler->AuthRequest(listType, passport.String(), display.String());
		} break;
		
		case msnContactInfo: {
			UpdateContactInfo( msg );
		} break;
		
		case msnmsgError: {
			fHandler->Error( msg->FindString("error") );
		} break;
		
		case msnmsgProgress: {
			float progress=0.0;
			if ( msg->FindFloat("progress", &progress) != B_OK )
			{
				LOG(kProtocolName, liHigh, "Malformed msnmsgProgress message received by MSNManager");
				break;
			}
			
			fHandler->Progress( msg->FindString("id"), msg->FindString("message"), progress );
		} break;
		
		default: {
			BLooper::MessageReceived(msg);
		};
	};
}
Exemplo n.º 5
0
void
ChatWindow::MessageReceived( BMessage * msg )
{
	switch ( msg->what )
	{
		case IM::SETTINGS_UPDATED: {
			if (msg->FindString("people_handler", &fPeopleHandler) != B_OK) {
				fPeopleHandler = kDefaultPeopleHandler;
			};
			
			RebuildDisplay();
		} break;
		case IM::USER_STOPPED_TYPING: {
			BMessage im_msg(IM::MESSAGE);
			im_msg.AddInt32("im_what",IM::USER_STOPPED_TYPING);
			im_msg.AddRef("contact",&fEntry);
			fMan->SendMessage(&im_msg);
			
			stopSelfTypingTimer();
		} break;
		case IM::USER_STARTED_TYPING: {
			BMessage im_msg(IM::MESSAGE);
			im_msg.AddInt32("im_what", IM::USER_STARTED_TYPING);
			im_msg.AddRef("contact", &fEntry);
			fMan->SendMessage(&im_msg);
			
			startSelfTypingTimer();
		} break;
		case IM::DESKBAR_ICON_CLICKED:
		{ // deskbar icon clicked, move to current workspace and activate
			SetWorkspaces( 1 << current_workspace() );
			Activate();
		}	break;
		
		case IM::ERROR:
		case IM::MESSAGE:
		{
			entry_ref contact;
			
			if ( msg->FindRef("contact",&contact) != B_OK )
				return;
				
			if ( contact != fEntry )
				// message not for us, skip it.
				return;
			
			int32 im_what=IM::ERROR;
			
			if ( msg->FindInt32("im_what",&im_what) != B_OK )
				im_what = IM::ERROR;
			
//			int32 old_sel_start, old_sel_end;
			
			char timestr[10];
			time_t now = time(NULL);
			strftime(timestr, sizeof(timestr),"[%H:%M]: ", localtime(&now) );
				
			switch ( im_what )
			{
				case IM::STATUS_CHANGED:
				{
					// This means we're rebuilding menus we don't rally need to rebuild..
					BuildProtocolMenu();
				}	break;
				
				case IM::MESSAGE_SENT:
				{
					fText->Append(timestr, C_TIMESTAMP, C_TIMESTAMP, F_TIMESTAMP);

					BString message;
					msg->FindString("message", &message);
					if (message.Compare("/me ", 4) == 0) {
						fText->Append(_T("* You "), C_ACTION, C_ACTION, F_ACTION);
						message.Remove(0, 4);
						fText->Append(message.String(), C_ACTION, C_ACTION, F_ACTION);
					} else {
						fText->Append(_T("You say: "), C_OWNNICK, C_OWNNICK, F_TEXT);
						//fText->Append(msg->FindString("message"), C_TEXT, C_TEXT, F_TEXT);
					    emoticor->AddText(fText,msg->FindString("message"), C_TEXT, F_TEXT,C_TEXT,F_EMOTICON); //by xeD

					}
					fText->Append("\n", C_TEXT, C_TEXT, F_TEXT);
					fText->ScrollToSelection();
				}	break;
				
				case IM::ERROR:
				{
					BMessage error;
					msg->FindMessage("message", &error);
					
					int32 error_what = -1;
					
					error.FindInt32("im_what", &error_what );
					
					if ( error_what != IM::USER_STARTED_TYPING && 
						 error_what != IM::USER_STOPPED_TYPING )
					{ // ignore messages du to typing
						fText->Append(timestr, C_TIMESTAMP, C_TIMESTAMP, F_TIMESTAMP);
						fText->Append("Error: ", C_TEXT, C_TEXT, F_TEXT);
						fText->Append(msg->FindString("error"), C_TEXT, C_TEXT, F_TEXT);
						fText->Append("\n", C_TEXT, C_TEXT, F_TEXT);
					
						if (!IsActive()) startNotify();
					}
				}	break;
				
				case IM::MESSAGE_RECEIVED:
				{
					if ( msg->FindString("message") == NULL )
					{ // no message to display, probably opened by user
						return;
					}
					
					fText->Append(timestr, C_TIMESTAMP, C_TIMESTAMP, F_TIMESTAMP);
					
					BString protocol = msg->FindString("protocol");
					BString message = msg->FindString("message");
					
					
										
					if (protocol.Length() > 0) {
						fName.ReplaceAll("$protocol$",protocol.String());
					} else {
						fName.ReplaceAll("$protocol$"," ");
					};
					
					if (message.Compare("/me ", 4) == 0) {
						fText->Append("* ", C_ACTION, C_ACTION, F_ACTION);
						fText->Append(fName.String(), C_ACTION, C_ACTION, F_ACTION);
						fText->Append(" ", C_ACTION, C_ACTION, F_ACTION);
						message.Remove(0, 4);
						fText->Append(message.String(), C_ACTION, C_ACTION, F_ACTION);
					} else {
						fText->Append(fName.String(), C_OTHERNICK, C_OTHERNICK, F_TEXT);
						fText->Append(": ", C_OTHERNICK, C_OTHERNICK, F_TEXT);
						emoticor->AddText(fText,msg->FindString("message"), C_TEXT, F_TEXT,C_TEXT,F_EMOTICON); //by xeD

					}
					fText->Append("\n", C_TEXT, C_TEXT, F_TEXT);
					fText->ScrollToSelection();

					if (!IsActive()) startNotify();
					
					stopTypingTimer();
				}	break;
				
				case IM::CONTACT_STARTED_TYPING: {	
					startTypingTimer();
				} break;
				
				case IM::CONTACT_STOPPED_TYPING: {
					stopTypingTimer();
				} break;
				
			}
			
			fText->ScrollToSelection();
			
		}	break;
		
		case SEND_MESSAGE:
		{
			if (fInput->TextLength() == 0) return;
			BMessage im_msg(IM::MESSAGE);
			im_msg.AddInt32("im_what",IM::SEND_MESSAGE);
			im_msg.AddRef("contact",&fEntry);
			im_msg.AddString("message", fInput->Text() );
			
			BMenu *menu = fProtocolMenu->Menu();
			if (menu) {
				IconMenuItem *item = dynamic_cast<IconMenuItem*>(menu->FindMarked());
				if ( item )
				{
					BString connection = item->Extra();
					if (connection.Length() > 0) 
					{
						IM::Connection conn(connection.String());
						
						im_msg.AddString("protocol", conn.Protocol());
						im_msg.AddString("id", conn.ID());
					}
				}	
			};
			
			if ( fMan->SendMessage(&im_msg) == B_OK ) {
				fInput->SetText("");
			} else {
				LOG("im_emoclient", liHigh, "Error sending message to im_server");

				fText->Append(_T("Error: im_server not running, can't send message\n"), C_TEXT, C_TEXT, F_TEXT);
					
				fText->ScrollToSelection();
			};
		}	break;
		
		case SHOW_INFO:
		{
			BMessage open_msg(B_REFS_RECEIVED);
			open_msg.AddRef("refs", &fEntry);
			
			be_roster->Launch(fPeopleHandler.String(), &open_msg);
		}	break;
		
		case VIEW_LOG: {
			BMessage open(B_REFS_RECEIVED);
			open.AddRef("refs", &fEntry);
			be_roster->Launch("application/x-vnd.BeClan.im_binlog_viewer", &open);
		} break;
		
		case VIEW_WEBPAGE: {
			entry_ref htmlRef;
			be_roster->FindApp("application/x-vnd.Be.URL.http", &htmlRef);
			BPath htmlPath(&htmlRef);

			BMessage argv(B_ARGV_RECEIVED);
			argv.AddString("argv", htmlPath.Path());

			int32 length = -1;
			char *url = ReadAttribute(BNode(&fEntry), "META:url", &length);
			if ((url != NULL) && (length > 1)) {
				url = (char *)realloc(url, (length + 1) * sizeof(char));
				url[length] = '\0';
				
				argv.AddString("argv", url);	
				argv.AddInt32("argc", 2);
	
				be_roster->Launch(&htmlRef, &argv);
			} else {
				LOG("im_emoclient", liMedium, "Contact had no homepage");
			};
			
			if (url) free(url);
		} break;
		case VIEW_EMOTICONS: {
			//find emoticon button
 			BView* button = FindView("Emoticons");
 			BRect buttonBounds = button->Bounds();
 			//move emoticon window to just below the button
 			BPoint emotLeftBottom = button->ConvertToScreen(buttonBounds.LeftBottom());
 				
 			popup->SetTargetForItems(this);	
			popup->Go(emotLeftBottom,true,true);
			
		} break;
		case ADD_EMOTICON:
		{
			
			int32 index=msg->FindInt32("index");
			BString txt;
			emoticor->config->menu.FindString("face",index,&txt);
			txt << " ";
			fInput->Insert(txt.String());
		} break;
		case EMAIL:
		{
			BMessage open_msg(B_REFS_RECEIVED);
			open_msg.AddRef("refs", &fEntry);
			// "application/x-vnd.Be-MAIL"
			be_roster->Launch("text/x-email", &open_msg );
		}	break;
		
		case BLOCK:
		{
			IM::Contact contact(fEntry);
			
			char status[256];
			
			if ( contact.GetStatus( status, sizeof(status) ) != B_OK )
				status[0] = 0;
			
			if ( strcmp(status, BLOCKED_TEXT) == 0 )
			{ // already blocked, unblocked
				contact.SetStatus(OFFLINE_TEXT);
				
				BMessage update_msg(IM::UPDATE_CONTACT_STATUS);
				update_msg.AddRef("contact", &fEntry);
				
				fMan->SendMessage( &update_msg );
			} else
			{
				if ( contact.SetStatus(BLOCKED_TEXT) != B_OK )
				{
					LOG("im_emoclient", liHigh, "Block: Error setting contact status");
				}
			}
		}	break;
		
		case AUTH:
		{
			BMessage auth_msg(IM::MESSAGE);
			auth_msg.AddInt32("im_what", IM::REQUEST_AUTH);
			auth_msg.AddRef("contact", &fEntry);
			
			fMan->SendMessage( &auth_msg );
		}	break;
		
		case B_NODE_MONITOR:
		{
			int32 opcode=0;
			
			if ( msg->FindInt32("opcode",&opcode) != B_OK )
				return;
			
			switch ( opcode )
			{
				case B_ENTRY_REMOVED: {
					// oops. should we close down this window now?
					// Nah, we'll just disable everything.
					fInput->MakeEditable(false);
					fInput->SetViewColor( 198,198,198 );
					fInput->Invalidate();
					
					BString title( Title() );
					title += " - DELETED!";
					SetTitle( title.String() );
				}	break;
				case B_ENTRY_MOVED:
				{
					entry_ref ref;
					
					msg->FindInt32("device", &ref.device);
					msg->FindInt64("to directory", &ref.directory);
					ref.set_name( msg->FindString("name") );
					
					fEntry = ref;
					
					BEntry entry(&fEntry);
					if ( !entry.Exists() )
					{
						LOG("im_emoclient", liHigh, "Entry moved: New entry invalid");
					}
				}	break;
				case B_STAT_CHANGED:
				case B_ATTR_CHANGED:
					reloadContact();
					BuildProtocolMenu();
					break;
			}
		}	break;
		
		case kResizeMessage: {
			BView *view = NULL;
			msg->FindPointer("view", reinterpret_cast<void**>(&view));
			if (dynamic_cast<BScrollView *>(view)) {
				BPoint point;
				msg->FindPoint("loc", &point);
				
				fResize->MoveTo(fResize->Frame().left, point.y);
				
				fTextScroll->ResizeTo(fTextScroll->Frame().Width(), point.y - 1 - fDock->Frame().Height() - 1);
				
				fInputScroll->MoveTo(fInputScroll->Frame().left, point.y + 3);
				fInputScroll->ResizeTo( 
					fInputScroll->Bounds().Width(),
					fStatusBar->Frame().top - fInputScroll->Frame().top
				);
				fInput->SetTextRect(fInput->Bounds());
				fInput->ScrollToSelection();
				
				if ( fSendButton )
				{
					fSendButton->MoveTo(fSendButton->Frame().left, point.y + 3);
					fSendButton->ResizeTo( 
						fSendButton->Bounds().Width(),
						fStatusBar->Frame().top - fSendButton->Frame().top
					);
				}
			};
		} break;
		
		case B_MOUSE_WHEEL_CHANGED: {
			fText->MessageReceived(msg);
		} break;
		
		case B_COPY: {
			int32 start = 0;
			int32 end = 0;
			
			fInput->GetSelection(&start, &end);
			
			//printf("%ld - > %ld\n", start, end);
		} break;
		
		case B_SIMPLE_DATA: {
			entry_ref ref;
			BNode node;
//			attr_info info;
			
			for (int i = 0; msg->FindRef("refs", i, &ref) == B_OK; i++) {
				node = BNode(&ref);
				
				char *type = ReadAttribute(node, "BEOS:TYPE");
				if (strcmp(type, "application/x-person") == 0) {
					char *name = ReadAttribute(node, "META:name");
					char *nickname = ReadAttribute(node, "META:nickname");
					char connection[100];
					IM::Contact con(ref);
					con.ConnectionAt(0, connection);

					if (fInput->TextLength() > 0) fInput->Insert("\n");
					fInput->Insert(name);
					fInput->Insert(" (");
					fInput->Insert(nickname);
					fInput->Insert("): ");
					fInput->Insert(connection);

					free(name);
					free(nickname);
				};
				free(type);
			};
			fInput->ScrollToOffset(fInput->TextLength());
		} break;
		
		case CLEAR_TYPING:
			stopTypingTimer();
			break;
		
		case PROTOCOL_SELECTED: {
			// a protocol has been selected. Since BMenuField doesn't resize until later,
			// we have to wait 1000us before actually responding to the change, see below
			if ( fProtocolHack )
				delete fProtocolHack;
			BMessage protoHack(PROTOCOL_SELECTED2);
			fProtocolHack = new BMessageRunner( BMessenger(this), &protoHack, 1000, 1 );
		}	break;
		
		case PROTOCOL_SELECTED2:
			// do what should be done on protocol change
			fStatusBar->PositionViews();
			fInfoView->ResizeTo(
				fStatusBar->Bounds().Width() - fInfoView->Frame().left,
				fInfoView->Bounds().Height()
			);
			break;
		
		default:
			BWindow::MessageReceived(msg);
	}
}
Exemplo n.º 6
0
void
UrlWrapper::ArgvReceived(int32 argc, char** argv)
{
    if (argc <= 1)
        return;

    const char* failc = " || read -p 'Press any key'";
    const char* pausec = " ; read -p 'Press any key'";
    char* args[] = { (char *)"/bin/sh", (char *)"-c", NULL, NULL};
    status_t err;

    BUrl url(argv[1]);

    BString full = BUrl(url).SetProtocol(BString()).UrlString();
    BString proto = url.Protocol();
    BString host = url.Host();
    BString port = BString() << url.Port();
    BString user = url.UserInfo();
    BString pass = url.Password();
    BString path = url.Path();

    if (!url.IsValid()) {
        fprintf(stderr, "malformed url: '%s'\n", url.UrlString().String());
        return;
    }

    // XXX: debug
    PRINT(("PROTO='%s'\n", proto.String()));
    PRINT(("HOST='%s'\n", host.String()));
    PRINT(("PORT='%s'\n", port.String()));
    PRINT(("USER='******'\n", user.String()));
    PRINT(("PASS='******'\n", pass.String()));
    PRINT(("PATH='%s'\n", path.String()));

    if (proto == "about") {
        app_info info;
        BString sig;
        // BUrl could get an accessor for the full - proto part...
        sig = host << "/" << path;
        BMessage msg(B_ABOUT_REQUESTED);
        if (be_roster->GetAppInfo(sig.String(), &info) == B_OK) {
            BMessenger msgr(sig.String());
            msgr.SendMessage(&msg);
            return;
        }
        if (be_roster->Launch(sig.String(), &msg) == B_OK)
            return;
        be_roster->Launch("application/x-vnd.Haiku-About");
        return;
    }

    if (proto == "telnet") {
        BString cmd("telnet ");
        if (url.HasUserInfo())
            cmd << "-l " << user << " ";
        cmd << host;
        if (url.HasPort())
            cmd << " " << port;
        PRINT(("CMD='%s'\n", cmd.String()));
        cmd << failc;
        args[2] = (char*)cmd.String();
        be_roster->Launch(kTerminalSig, 3, args);
        return;
    }

    // see draft:
    // http://tools.ietf.org/wg/secsh/draft-ietf-secsh-scp-sftp-ssh-uri/
    if (proto == "ssh") {
        BString cmd("ssh ");

        if (url.HasUserInfo())
            cmd << "-l " << user << " ";
        if (url.HasPort())
            cmd << "-oPort=" << port << " ";
        cmd << host;
        PRINT(("CMD='%s'\n", cmd.String()));
        cmd << failc;
        args[2] = (char*)cmd.String();
        be_roster->Launch(kTerminalSig, 3, args);
        // TODO: handle errors
        return;
    }

    if (proto == "ftp") {
        BString cmd("ftp ");

        cmd << proto << "://";
        /*
        if (user.Length())
        	cmd << "-l " << user << " ";
        cmd << host;
        */
        cmd << full;
        PRINT(("CMD='%s'\n", cmd.String()));
        cmd << failc;
        args[2] = (char*)cmd.String();
        be_roster->Launch(kTerminalSig, 3, args);
        // TODO: handle errors
        return;
    }

    if (proto == "sftp") {
        BString cmd("sftp ");

        //cmd << url;
        if (url.HasPort())
            cmd << "-oPort=" << port << " ";
        if (url.HasUserInfo())
            cmd << user << "@";
        cmd << host;
        if (url.HasPath())
            cmd << ":" << path;
        PRINT(("CMD='%s'\n", cmd.String()));
        cmd << failc;
        args[2] = (char*)cmd.String();
        be_roster->Launch(kTerminalSig, 3, args);
        // TODO: handle errors
        return;
    }

    if (proto == "finger") {
        BString cmd("/bin/finger ");

        if (url.HasUserInfo())
            cmd << user;
        if (url.HasHost() == 0)
            host = "127.0.0.1";
        cmd << "@" << host;
        PRINT(("CMD='%s'\n", cmd.String()));
        cmd << pausec;
        args[2] = (char*)cmd.String();
        be_roster->Launch(kTerminalSig, 3, args);
        // TODO: handle errors
        return;
    }

    if (proto == "http" || proto == "https" /*|| proto == "ftp"*/) {
        BString cmd("/bin/wget ");

        //cmd << url;
        cmd << proto << "://";
        if (url.HasUserInfo())
            cmd << user << "@";
        cmd << full;
        PRINT(("CMD='%s'\n", cmd.String()));
        cmd << pausec;
        args[2] = (char*)cmd.String();
        be_roster->Launch(kTerminalSig, 3, args);
        // TODO: handle errors
        return;
    }

    if (proto == "file") {
        BMessage m(B_REFS_RECEIVED);
        entry_ref ref;
        _DecodeUrlString(path);
        if (get_ref_for_path(path.String(), &ref) < B_OK)
            return;
        m.AddRef("refs", &ref);
        be_roster->Launch(kTrackerSig, &m);
        return;
    }

    // XXX:TODO: split options
    if (proto == "query") {
        // mktemp ?
        BString qname("/tmp/query-url-temp-");
        qname << getpid() << "-" << system_time();
        BFile query(qname.String(), O_CREAT|O_EXCL);
        // XXX: should check for failure

        BString s;
        int32 v;

        _DecodeUrlString(full);
        // TODO: handle options (list of attrs in the column, ...)

        v = 'qybF'; // QuerY By Formula XXX: any #define for that ?
        query.WriteAttr("_trk/qryinitmode", B_INT32_TYPE, 0LL, &v, sizeof(v));
        s = "TextControl";
        query.WriteAttr("_trk/focusedView", B_STRING_TYPE, 0LL, s.String(),
                        s.Length()+1);
        s = full;
        PRINT(("QUERY='%s'\n", s.String()));
        query.WriteAttr("_trk/qryinitstr", B_STRING_TYPE, 0LL, s.String(),
                        s.Length()+1);
        query.WriteAttr("_trk/qrystr", B_STRING_TYPE, 0LL, s.String(),
                        s.Length()+1);
        s = "application/x-vnd.Be-query";
        query.WriteAttr("BEOS:TYPE", 'MIMS', 0LL, s.String(), s.Length()+1);


        BEntry e(qname.String());
        entry_ref er;
        if (e.GetRef(&er) >= B_OK)
            be_roster->Launch(&er);
        return;
    }

    if (proto == "sh") {
        BString cmd(full);
        if (_Warn(url.UrlString()) != B_OK)
            return;
        PRINT(("CMD='%s'\n", cmd.String()));
        cmd << pausec;
        args[2] = (char*)cmd.String();
        be_roster->Launch(kTerminalSig, 3, args);
        // TODO: handle errors
        return;
    }

    if (proto == "beshare") {
        team_id team;
        BMessenger msgr(kBeShareSig);
        // if no instance is running, or we want a specific server, start it.
        if (!msgr.IsValid() || url.HasHost()) {
            be_roster->Launch(kBeShareSig, (BMessage*)NULL, &team);
            msgr = BMessenger(NULL, team);
        }
        if (url.HasHost()) {
            BMessage mserver('serv');
            mserver.AddString("server", host);
            msgr.SendMessage(&mserver);

        }
        if (url.HasPath()) {
            BMessage mquery('quer');
            mquery.AddString("query", path);
            msgr.SendMessage(&mquery);
        }
        // TODO: handle errors
        return;
    }

    if (proto == "icq" || proto == "msn") {
        // TODO
        team_id team;
        be_roster->Launch(kIMSig, (BMessage*)NULL, &team);
        BMessenger msgr(NULL, team);
        if (url.HasHost()) {
            BMessage mserver(B_REFS_RECEIVED);
            mserver.AddString("server", host);
            msgr.SendMessage(&mserver);

        }
        // TODO: handle errors
        return;
    }

    if (proto == "mms" || proto == "rtp" || proto == "rtsp") {
        args[0] = (char*)url.UrlString().String();
        be_roster->Launch(kVLCSig, 1, args);
        return;
    }

    if (proto == "nfs") {
        BString parameter(host);
        _DecodeUrlString(path);
        if (url.HasPort())
            parameter << ":" << port;
        //XXX: should not always be absolute! FIXME
        parameter << ":/" << path;
        BString prettyPath(path);
        prettyPath.Remove(0, prettyPath.FindLast("/") + 1);
        if (path == "" || path == "/")
            prettyPath = "root";
        prettyPath << " on " << host;
        prettyPath.Prepend("/");
        if (mkdir(prettyPath.String(), 0755) < 0) {
            perror("mkdir");
            return;
        }
        dev_t volume;
        uint32 flags = 0;
        fprintf(stderr, "parms:'%s'\n", parameter.String());
        volume = fs_mount_volume(prettyPath.String(), NULL, "nfs4", flags,
                                 parameter.String());
        if (volume < B_OK) {
            fprintf(stderr, "fs_mount_volume: %s\n", strerror(volume));
            return;
        }

        BMessage m(B_REFS_RECEIVED);
        entry_ref ref;
        if (get_ref_for_path(prettyPath.String(), &ref) < B_OK)
            return;
        m.AddRef("refs", &ref);
        be_roster->Launch(kTrackerSig, &m);
        return;
    }

    if (proto == "doi") {
        BString url("http://dx.doi.org/");
        BString mimetype;

        url << full;
        BUrl u(url.String());
        args[0] = const_cast<char*>("urlwrapper"); //XXX
        args[1] = (char*)u.UrlString().String();
        args[2] = NULL;
        mimetype = kURLHandlerSigBase;
        mimetype += u.Protocol();

        err = be_roster->Launch(mimetype.String(), 1, args + 1);
        if (err != B_OK && err != B_ALREADY_RUNNING)
            err = be_roster->Launch(kAppSig, 1, args + 1);
        // TODO: handle errors
        return;
    }

    /*

    More ?
    cf. http://en.wikipedia.org/wiki/URI_scheme
    cf. http://www.iana.org/assignments/uri-schemes.html

    Audio: (SoundPlay specific, identical to http:// to a shoutcast server)

    vnc: ?
    irc: ?
    im: http://tools.ietf.org/html/rfc3860

    svn: handled by checkitout
    cvs: handled by checkitout
    git: handled by checkitout
    rsync: handled by checkitout - http://tools.ietf.org/html/rfc5781

    smb: cifsmount ?
    nfs: mount_nfs ? http://tools.ietf.org/html/rfc2224
    ipp: http://tools.ietf.org/html/rfc3510

    mailto: ? Mail & Beam both handle it already (not fully though).
    imap: to describe mail accounts ? http://tools.ietf.org/html/rfc5092
    pop: http://tools.ietf.org/html/rfc2384
    mid: cid: as per RFC 2392
    http://www.rfc-editor.org/rfc/rfc2392.txt query MAIL:cid
    message:<MID> http://daringfireball.net/2007/12/message_urls_leopard_mail

    itps: pcast: podcast: s//http/ + parse xml to get url to mp3 stream...
    audio: s//http:/ + default MediaPlayer
    -- see http://forums.winamp.com/showthread.php?threadid=233130

    gps: ? I should submit an RFC for that one :)

    webcal: (is http: to .ics file)

    data: (but it's dangerous)

    */


}
Exemplo n.º 7
0
/*------------------------------------------------------------------------------*\
	MessageReceived( msg)
		-	
\*------------------------------------------------------------------------------*/
void BmPrefsFilterView::MessageReceived( BMessage* msg) {
	try {
		switch( msg->what) {
			case BM_SELECTION_CHANGED: {
				int32 index = mFilterListView->CurrentSelection( 0);
				ShowFilter( index);
				break;
			}
			case BM_TEXTFIELD_MODIFIED: {
				BView* srcView = NULL;
				msg->FindPointer( "source", (void**)&srcView);
				BmTextControl* source = dynamic_cast<BmTextControl*>( srcView);
				if ( mCurrFilter && source == mFilterControl) {
					// rename filter:
					TheFilterList->RenameItem( 
						mCurrFilter->Name(), mFilterControl->Text()
					);
					NoticeChange();
				}
				break;
			}
			case BM_ADD_FILTER: {
				BMenuItem* item = mAddPopup->Menu()->FindMarked();
				if (item) {
					BmString filterKind( item->Label());
					BmString defaultKey 
						= TheFilterList->DefaultNameForFilterKind( filterKind);
					BmString key = defaultKey;
					for( int32 i=1; TheFilterList->FindItemByKey( key); ++i) {
						key = defaultKey;
						key << "_" << i;
					}
					BmFilter* newFilter = new BmFilter( key.String(), filterKind, 
																   TheFilterList.Get());
					TheFilterList->AddItemToList( newFilter);
					mFilterControl->MakeFocus( true);
					mFilterControl->TextView()->SelectAll();
					if (mAddToChainControl->Value()) {
						// add new filter to default chain:
						BmRef< BmListModelItem> chainItem;
						chainItem = TheFilterChainList->FindItemByKey( 
							BM_DefaultItemLabel
						);
						BmFilterChain* chain = dynamic_cast< BmFilterChain*>( 
							chainItem.Get()
						);
						if (chain) {
							BmChainedFilter* chainedFilter 
								= new BmChainedFilter( newFilter->Key().String(), 
															  chain->ChainedFilters());
							chain->ChainedFilters()->AddItemToList( chainedFilter);
						}
					}
					NoticeChange();
				}
				break;
			}
			case BMM_CREATE_FILTER: {
				BmMailRefVect* refVect = NULL;
				msg->FindPointer( BeamApplication::MSG_MAILREF_VECT, 
									  (void**)&refVect);
				if (!refVect || refVect->empty())
					break;
				BmMailRef* ref = refVect->front().Get();
				BmString key( "new filter");
				for( int32 i=1; TheFilterList->FindItemByKey( key); ++i) {
					key = BmString("new filter_")<<i;
				}
				BmString sieveKind( "SIEVE");
				BmFilter* newFilter = new BmFilter( key.String(), sieveKind, 
															   TheFilterList.Get());
				BmFilterAddon* addon = newFilter->Addon();
				if (ref && addon) {
					addon->SetupFromMailData( 
						ref->Subject(), ref->From(), ref->To()
					);
					TheFilterList->AddItemToList( newFilter);
					mFilterControl->MakeFocus( true);
					mFilterControl->TextView()->SelectAll();
					if (mAddToChainControl->Value()) {
						// add new filter to default chain:
						BmRef< BmListModelItem> chainItem;
						chainItem = TheFilterChainList->FindItemByKey( 
							BM_DefaultItemLabel
						);
						BmFilterChain* chain = dynamic_cast< BmFilterChain*>( 
							chainItem.Get()
						);
						if (chain) {
							BmChainedFilter* chainedFilter 
								= new BmChainedFilter( newFilter->Key().String(), 
															  chain->ChainedFilters());
							chain->ChainedFilters()->AddItemToList( chainedFilter);
						}
					}
					NoticeChange();
				}
				delete refVect;
				break;
			}
			case BM_REMOVE_FILTER: {
				int32 buttonPressed;
				if (msg->FindInt32( "which", &buttonPressed) != B_OK) {
					// first step, ask user about it:
					BAlert* alert = new BAlert( 
						"Remove Filter", 
						(BmString("Are you sure about removing the filter\n\n\t<") 
							<< mCurrFilter->Name() << ">?").String(),
						"Remove", "Cancel", NULL, B_WIDTH_AS_USUAL,
						B_WARNING_ALERT
					);
					alert->SetShortcut( 1, B_ESCAPE);
					alert->Go( new BInvoker( 
						new BMessage(BM_REMOVE_FILTER), 
						BMessenger( this)
					));
				} else {
					// second step, do it if user said ok:
					if (buttonPressed == 0) {
						TheFilterChainList->RemoveFilterFromAllChains( 
							mCurrFilter->Key()
						);
						TheFilterList->RemoveItemFromList( mCurrFilter.Get());
						mCurrFilter = NULL;
						NoticeChange();
					}
				}
				break;
			}
			case B_OBSERVER_NOTICE_CHANGE: {
				switch( msg->FindInt32( B_OBSERVE_WHAT_CHANGE)) {
					case BM_NTFY_FILTER_ADDON_MODIFIED: {
						NoticeChange();
						break;
					}
				}
				break;
			}
			case BM_COMPLAIN_ABOUT_FIELD: {
				int32 buttonPressed;
				if (msg->FindInt32( "which", &buttonPressed) != B_OK) {
					BmString complaint;
					complaint = msg->FindString( MSG_COMPLAINT);
					// first step, tell user about complaint:
					BAlert* alert = new BAlert( "Sanity Check Failed", 
														 complaint.String(),
													 	 "OK", NULL, NULL, B_WIDTH_AS_USUAL,
													 	 B_WARNING_ALERT);
					alert->SetShortcut( 0, B_ESCAPE);
					alert->Go( new BInvoker( new BMessage(*msg), BMessenger( this)));
					BmFilter* filter=NULL;
					msg->FindPointer( MSG_ITEM, (void**)&filter);
					BmListViewItem* filterItem 
						= mFilterListView->FindViewItemFor( filter);
					if (filterItem)
						mFilterListView->Select( 
							mFilterListView->IndexOf( filterItem)
						);
				} else {
					// second step, set corresponding focus:
					BmString fieldName;
					fieldName = msg->FindString( MSG_FIELD_NAME);
				}
				break;
			}
			default:
				inherited::MessageReceived( msg);
		}
	}
	catch( BM_error &err) {
		// a problem occurred, we tell the user:
		BM_SHOWERR( BmString("PrefsView_") << Name() << ":\n\t" << err.what());
	}
}
Exemplo n.º 8
0
void
UrlWrapper::ArgvReceived(int32 argc, char** argv)
{
	if (argc <= 1)
		return;
	
	const char* failc = " || read -p 'Press any key'";
	const char* pausec = " ; read -p 'Press any key'";
	char* args[] = { (char *)"/bin/sh", (char *)"-c", NULL, NULL};

	BPrivate::Support::BUrl url(argv[1]);

	BString full = url.Full();
	BString proto = url.Proto();
	BString host = url.Host();
	BString port = url.Port();
	BString user = url.User();
	BString pass = url.Pass();
	BString path = url.Path();

	if (url.InitCheck() < 0) {
		fprintf(stderr, "malformed url: '%s'\n", url.String());
		return;
	}
	
	// XXX: debug
	PRINT(("PROTO='%s'\n", proto.String()));
	PRINT(("HOST='%s'\n", host.String()));
	PRINT(("PORT='%s'\n", port.String()));
	PRINT(("USER='******'\n", user.String()));
	PRINT(("PASS='******'\n", pass.String()));
	PRINT(("PATH='%s'\n", path.String()));

	if (proto == "telnet") {
		BString cmd("telnet ");
		if (url.HasUser())
			cmd << "-l " << user << " ";
		cmd << host;
		if (url.HasPort())
			cmd << " " << port;
		PRINT(("CMD='%s'\n", cmd.String()));
		cmd << failc;
		args[2] = (char*)cmd.String();
		be_roster->Launch(kTerminalSig, 3, args);
		return;
	}
	
	// see draft:
	// http://tools.ietf.org/wg/secsh/draft-ietf-secsh-scp-sftp-ssh-uri/
	if (proto == "ssh") {
		BString cmd("ssh ");
		
		if (url.HasUser())
			cmd << "-l " << user << " ";
		if (url.HasPort())
			cmd << "-oPort=" << port << " ";
		cmd << host;
		PRINT(("CMD='%s'\n", cmd.String()));
		cmd << failc;
		args[2] = (char*)cmd.String();
		be_roster->Launch(kTerminalSig, 3, args);
		// TODO: handle errors
		return;
	}

	if (proto == "ftp") {
		BString cmd("ftp ");
		
		/*
		if (user.Length())
			cmd << "-l " << user << " ";
		cmd << host;
		*/
		cmd << full;
		PRINT(("CMD='%s'\n", cmd.String()));
		cmd << failc;
		args[2] = (char*)cmd.String();
		be_roster->Launch(kTerminalSig, 3, args);
		// TODO: handle errors
		return;
	}
	
	if (proto == "sftp") {
		BString cmd("sftp ");
		
		//cmd << url;
		if (url.HasPort())
			cmd << "-oPort=" << port << " ";
		if (url.HasUser())
			cmd << user << "@";
		cmd << host;
		if (url.HasPath())
			cmd << ":" << path;
		PRINT(("CMD='%s'\n", cmd.String()));
		cmd << failc;
		args[2] = (char*)cmd.String();
		be_roster->Launch(kTerminalSig, 3, args);
		// TODO: handle errors
		return;
	}

	if (proto == "finger") {
		BString cmd("/bin/finger ");
		
		if (url.HasUser())
			cmd << user;
		if (url.HasHost() == 0)
			host = "127.0.0.1";
		cmd << "@" << host;
		PRINT(("CMD='%s'\n", cmd.String()));
		cmd << pausec;
		args[2] = (char*)cmd.String();
		be_roster->Launch(kTerminalSig, 3, args);
		// TODO: handle errors
		return;
	}

	if (proto == "http") {
		BString cmd("/bin/wget ");
		
		//cmd << url;
		if (url.HasUser())
			cmd << user << "@";
		cmd << full;
		PRINT(("CMD='%s'\n", cmd.String()));
		cmd << pausec;
		args[2] = (char*)cmd.String();
		be_roster->Launch(kTerminalSig, 3, args);
		// TODO: handle errors
		return;
	}

	if (proto == "file") {
		BMessage m(B_REFS_RECEIVED);
		entry_ref ref;
		_DecodeUrlString(path);
		if (get_ref_for_path(path.String(), &ref) < B_OK)
			return;
		m.AddRef("refs", &ref);
		be_roster->Launch(kTrackerSig, &m);
		return;
	}

	// XXX:TODO: split options
	if (proto == "query") {
		// mktemp ?
		BString qname("/tmp/query-url-temp-");
		qname << getpid() << "-" << system_time();
		BFile query(qname.String(), O_CREAT|O_EXCL);
		// XXX: should check for failure
		
		BString s;
		int32 v;
		
		_DecodeUrlString(full);
		// TODO: handle options (list of attrs in the column, ...)

		v = 'qybF'; // QuerY By Formula XXX: any #define for that ?
		query.WriteAttr("_trk/qryinitmode", B_INT32_TYPE, 0LL, &v, sizeof(v));
		s = "TextControl";
		query.WriteAttr("_trk/focusedView", B_STRING_TYPE, 0LL, s.String(),
			s.Length()+1);
		s = full;
		PRINT(("QUERY='%s'\n", s.String()));
		query.WriteAttr("_trk/qryinitstr", B_STRING_TYPE, 0LL, s.String(),
			s.Length()+1);
		query.WriteAttr("_trk/qrystr", B_STRING_TYPE, 0LL, s.String(),
			s.Length()+1);
		s = "application/x-vnd.Be-query";
		query.WriteAttr("BEOS:TYPE", 'MIMS', 0LL, s.String(), s.Length()+1);
		

		BEntry e(qname.String());
		entry_ref er;
		if (e.GetRef(&er) >= B_OK)
			be_roster->Launch(&er);
		return;
	}

	if (proto == "sh") {
		BString cmd(full);
		if (_Warn(url.String()) != B_OK)
			return;
		PRINT(("CMD='%s'\n", cmd.String()));
		cmd << pausec;
		args[2] = (char*)cmd.String();
		be_roster->Launch(kTerminalSig, 3, args);
		// TODO: handle errors
		return;
	}

	if (proto == "beshare") {
		team_id team;
		BMessenger msgr(kBeShareSig);
		// if no instance is running, or we want a specific server, start it.
		if (!msgr.IsValid() || url.HasHost()) {
			be_roster->Launch(kBeShareSig, (BMessage*)NULL, &team);
			msgr = BMessenger(NULL, team);
		}
		if (url.HasHost()) {
			BMessage mserver('serv');
			mserver.AddString("server", host);
			msgr.SendMessage(&mserver);
			
		}
		if (url.HasPath()) {
			BMessage mquery('quer');
			mquery.AddString("query", path);
			msgr.SendMessage(&mquery);
		}
		// TODO: handle errors
		return;
	}

	if (proto == "icq" || proto == "msn") {
		// TODO
		team_id team;
		be_roster->Launch(kIMSig, (BMessage*)NULL, &team);
		BMessenger msgr(NULL, team);
		if (url.HasHost()) {
			BMessage mserver(B_REFS_RECEIVED);
			mserver.AddString("server", host);
			msgr.SendMessage(&mserver);
			
		}
		// TODO: handle errors
		return;
	}

	if (proto == "mms" || proto == "rtp" || proto == "rtsp") {
		args[0] = (char*)url.String();
		be_roster->Launch(kVLCSig, 1, args);
		return;
	}

	// Audio: ?

	// vnc: ?
	// irc: ?
	// 
	// svn: ?
	// cvs: ?
	// smb: cifsmount ?
	// nfs: mount_nfs ?
	//
	// mailto: ? Mail & Beam both handle it already (not fully though).
	//
	// mid: cid: as per RFC 2392
	// http://www.rfc-editor.org/rfc/rfc2392.txt query MAIL:cid
	//
	// itps: pcast: podcast: s//http/ + parse xml to get url to mp3 stream...
	// audio: s//http:/ + default MediaPlayer
	// -- see http://forums.winamp.com/showthread.php?threadid=233130
	//
	// gps: ? I should submit an RFC for that one :)

}
Exemplo n.º 9
0
BMessenger
TTracker::MountServer() const
{
	return BMessenger(kMountServerSignature);
}
Exemplo n.º 10
0
DownloadWindow::DownloadWindow(BRect frame, bool visible,
		SettingsMessage* settings)
	: BWindow(frame, B_TRANSLATE("Downloads"),
		B_TITLED_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL,
		B_AUTO_UPDATE_SIZE_LIMITS | B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE),
	fMinimizeOnClose(false)
{
	SetPulseRate(1000000);

	settings->AddListener(BMessenger(this));
	BPath downloadPath;
	if (find_directory(B_DESKTOP_DIRECTORY, &downloadPath) != B_OK)
		downloadPath.SetTo("/boot/home/Desktop");
	fDownloadPath = settings->GetValue(kSettingsKeyDownloadPath,
		downloadPath.Path());
	settings->SetValue(kSettingsKeyDownloadPath, fDownloadPath);

	SetLayout(new BGroupLayout(B_VERTICAL, 0.0));

	DownloadsContainerView* downloadsGroupView = new DownloadsContainerView();
	fDownloadViewsLayout = downloadsGroupView->GroupLayout();

	BMenuBar* menuBar = new BMenuBar("Menu bar");
	BMenu* menu = new BMenu(B_TRANSLATE("Downloads"));
	menu->AddItem(new BMenuItem(B_TRANSLATE("Open downloads folder"),
		new BMessage(OPEN_DOWNLOADS_FOLDER)));
	BMessage* newWindowMessage = new BMessage(NEW_WINDOW);
	newWindowMessage->AddString("url", "");
	BMenuItem* newWindowItem = new BMenuItem(B_TRANSLATE("New browser window"),
		newWindowMessage, 'N');
	menu->AddItem(newWindowItem);
	newWindowItem->SetTarget(be_app);
	menu->AddSeparatorItem();
	menu->AddItem(new BMenuItem(B_TRANSLATE("Hide"),
		new BMessage(B_QUIT_REQUESTED), 'D'));
	menuBar->AddItem(menu);

	fDownloadsScrollView = new DownloadContainerScrollView(downloadsGroupView);

	fRemoveFinishedButton = new BButton(B_TRANSLATE("Remove finished"),
		new BMessage(REMOVE_FINISHED_DOWNLOADS));
	fRemoveFinishedButton->SetEnabled(false);

	fRemoveMissingButton = new BButton(B_TRANSLATE("Remove missing"),
		new BMessage(REMOVE_MISSING_DOWNLOADS));
	fRemoveMissingButton->SetEnabled(false);

	const float spacing = be_control_look->DefaultItemSpacing();

	AddChild(BGroupLayoutBuilder(B_VERTICAL, 0.0)
		.Add(menuBar)
		.Add(fDownloadsScrollView)
		.Add(new BSeparatorView(B_HORIZONTAL, B_PLAIN_BORDER))
		.Add(BGroupLayoutBuilder(B_HORIZONTAL, spacing)
			.AddGlue()
			.Add(fRemoveMissingButton)
			.Add(fRemoveFinishedButton)
			.SetInsets(12, 5, 12, 5)
		)
	);

	PostMessage(INIT);

	if (!visible)
		Hide();
	Show();
}
Exemplo n.º 11
0
MainWindow::MainWindow(BRect frame)
	:
	BWindow(frame, B_TRANSLATE_SYSTEM_NAME("DriveSetup"), B_DOCUMENT_WINDOW,
		B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE),
	fCurrentDisk(NULL),
	fCurrentPartitionID(-1),
	fSpaceIDMap()
{
	BMenuBar* menuBar = new BMenuBar(Bounds(), "root menu");

	// create all the menu items
	fWipeMI = new BMenuItem(B_TRANSLATE("Wipe (not implemented)"),
		new BMessage(MSG_FORMAT));
	fEjectMI = new BMenuItem(B_TRANSLATE("Eject"),
		new BMessage(MSG_EJECT), 'E');
	fSurfaceTestMI = new BMenuItem(
		B_TRANSLATE("Surface test (not implemented)"),
		new BMessage(MSG_SURFACE_TEST));
	fRescanMI = new BMenuItem(B_TRANSLATE("Rescan"), new BMessage(MSG_RESCAN));

	fCreateMI = new BMenuItem(B_TRANSLATE("Create" B_UTF8_ELLIPSIS),
		new BMessage(MSG_CREATE), 'C');
	fDeleteMI = new BMenuItem(B_TRANSLATE("Delete"),
		new BMessage(MSG_DELETE), 'D');

	fMountMI = new BMenuItem(B_TRANSLATE("Mount"),
		new BMessage(MSG_MOUNT), 'M');
	fUnmountMI = new BMenuItem(B_TRANSLATE("Unmount"),
		new BMessage(MSG_UNMOUNT), 'U');
	fMountAllMI = new BMenuItem(B_TRANSLATE("Mount all"),
		new BMessage(MSG_MOUNT_ALL), 'M', B_SHIFT_KEY);

	// Disk menu
	fDiskMenu = new BMenu(B_TRANSLATE("Disk"));

	// fDiskMenu->AddItem(fWipeMI);
	fDiskInitMenu = new BMenu(B_TRANSLATE("Initialize"));
	fDiskMenu->AddItem(fDiskInitMenu);

	fDiskMenu->AddSeparatorItem();

	fDiskMenu->AddItem(fEjectMI);
	// fDiskMenu->AddItem(fSurfaceTestMI);
	fDiskMenu->AddItem(fRescanMI);

	menuBar->AddItem(fDiskMenu);

	// Parition menu
	fPartitionMenu = new BMenu(B_TRANSLATE("Partition"));
	fPartitionMenu->AddItem(fCreateMI);

	fFormatMenu = new BMenu(B_TRANSLATE("Format"));
	fPartitionMenu->AddItem(fFormatMenu);

	fPartitionMenu->AddItem(fDeleteMI);

	fPartitionMenu->AddSeparatorItem();

	fPartitionMenu->AddItem(fMountMI);
	fPartitionMenu->AddItem(fUnmountMI);

	fPartitionMenu->AddSeparatorItem();

	fPartitionMenu->AddItem(fMountAllMI);
	menuBar->AddItem(fPartitionMenu);

	AddChild(menuBar);

	// add DiskView
	BRect r(Bounds());
	r.top = menuBar->Frame().bottom + 1;
	r.bottom = floorf(r.top + r.Height() * 0.33);
	fDiskView = new DiskView(r, B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP,
		fSpaceIDMap);
	AddChild(fDiskView);

	// add PartitionListView
	r.top = r.bottom + 2;
	r.bottom = Bounds().bottom;
	r.InsetBy(-1, -1);
	fListView = new PartitionListView(r, B_FOLLOW_ALL);
	AddChild(fListView);

	// configure PartitionListView
	fListView->SetSelectionMode(B_SINGLE_SELECTION_LIST);
	fListView->SetSelectionMessage(new BMessage(MSG_PARTITION_ROW_SELECTED));
	fListView->SetTarget(this);
	fListView->MakeFocus(true);

	status_t ret = fDDRoster.StartWatching(BMessenger(this));
	if (ret != B_OK) {
		fprintf(stderr, "Failed to start watching for device changes: %s\n",
			strerror(ret));
	}

	// visit all disks in the system and show their contents
	_ScanDrives();

	if (!be_roster->IsRunning(kDeskbarSignature))
		SetFlags(Flags() | B_NOT_MINIMIZABLE);
}
Exemplo n.º 12
0
AboutWindow::AboutWindow (void)
	: BWindow (
			BRect (0.0, 0.0, 420.0, 266.0),
			"About Vision",
			B_TITLED_WINDOW,
			B_WILL_DRAW | B_NOT_RESIZABLE | B_NOT_ZOOMABLE)
{
	/*
	 * Function purpose: Construct
	 */

	
	BRect bounds (Bounds());
	BBitmap *bmp (NULL);

	fBackground = new BView (
										 bounds,
										 "background",
										 B_FOLLOW_ALL_SIDES,
										 B_WILL_DRAW);
	fBackground->SetViewColor (255, 255, 255);
	AddChild (fBackground);


	if ((bmp = BTranslationUtils::GetBitmap ('bits', "vision")) != 0)
	{
		//BRect logo_bounds (bmp->Bounds());

		fLogo = new ClickView (
										bmp->Bounds().OffsetByCopy (16, 16),
										"image",
										B_FOLLOW_LEFT | B_FOLLOW_TOP,
										B_WILL_DRAW,
										"http://vision.sourceforge.net");
		fBackground->AddChild (fLogo);
		fLogo->SetViewBitmap (bmp);
		delete bmp;

		bounds.Set (
			0.0,
			fLogo->Frame().bottom + 12, 
			Bounds().right,
			Bounds().bottom);
	}

	fCredits = new BTextView (
									bounds,
									"credits",
									bounds.OffsetToCopy (B_ORIGIN).InsetByCopy (20, 0),
									B_FOLLOW_LEFT | B_FOLLOW_TOP,
									B_WILL_DRAW); 

	fCredits->MakeSelectable (false);
	fCredits->MakeEditable (false);
	fCredits->SetStylable (true);
	fCredits->SetAlignment (B_ALIGN_CENTER);
	fBackground->AddChild (fCredits);


	fCreditsText =
		"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
		"Unit A\n[Vision]\n"
		"{A-Z}\n"
		"Alan Ellis (voidref)\n"
		"Rene Gollent (AnEvilYak)\n"
		"Todd Lair (tlair)\n"
		"Wade Majors (kurros)\n\n\n\n"

		"\n\n\n\nUnit B\n[Bowser]\n"
		"{A-Z}\n"
		"Andrew Bazan (Hiisi)\n"
		"Rene Gollent (AnEvilYak)\n"
		"Todd Lair (tlair)\n"
		"Brian Luft (Electroly)\n"
		"Wade Majors (kurros)\n"
		"Jamie Wilkinson (project)\n\n\n\n"
	
		"\n\n\n\nBrought To You In Part By Contributions From\n"
		"{A-Z}\n"
		"Seth Flaxman (Flax)\n"
		"Joshua Jensen\n"
		"Gord McLeod (G_McLeod)\n"
		"John Robinson ([geo])\n"
		"Bjorn Oksholen (GuinnessM)\n"
		"Jean-Baptiste M. Quéru (jbq)\n"
		"\n\n\n"

		"\n\n\n\nUnit C\n[Support Crew]\n"
		"Assistant to Wade Majors: Patches\n"
		"Music Supervisor: Baron Arnold\n"
		"Assistant to Baron Arnold: Ficus Kirkpatrick\n"
		"Stunt Coordinator: Gilligan\n"
		"Nude Scenes: Natalie Portman\n"
		"Counselors: regurg and helix\n\n\n"
		"No animals were injured during the production of this IRC client\n\n\n"
		"Soundtrack available on Catastrophe Records\n\n\n\n"
		
		"\n\n\n\nSpecial Thanks\n\n"
		"Olathe\n"
		"Terminus\n"
		"Bob Maple\n"
		"Ted Stodgell\n"
		"Seth Flaxman\n"
		"David Aquilina\n"
		"Kurt von Finck\n"
		"Kristine Gouveia\n"
		"Jessica Tallon\n"
		"Be, Inc., Menlo Park, CA\n"
		"Pizza Hut, Winter Haven, FL (now give me that free pizza Mike)\n\n\n"
		
		"send all complaints and nipple pictures to kaye\n\n\n"

		"\n\n\n\n\n"
		"\"A human being should be able to change "
		"a diaper, plan an invasion, butcher a "
		"hog, conn a ship, design a building, "
		"write a sonnet, balance accounts, build "
		"a wall, set a bone, comfort the dying, "
		"take orders, give orders, cooperate, act "
		"alone, solve equations, analyze a new "
		"problem, pitch manure, program a com"
		"puter, cook a tasty meal, fight effi"
		"ciently, die gallantly. Specialization "
		"is for insects.\" -- Robert A. Heinlein"
	;

	rgb_color myBlack = {0,0,0,255};
	fTextRun.count					= 1;
	fTextRun.runs[0].offset = 0;
	fTextRun.runs[0].font	 = *be_fixed_font;
	fTextRun.runs[0].color	= myBlack;

	fCredits->Insert (fCreditsText, &fTextRun);

	// Center window
	BRect frame (BScreen().Frame());
	MoveTo (
		frame.Width()/2 - Frame().Width()/2,
		frame.Height()/2 - Frame().Height()/2);
	fScrollRunner = new BMessageRunner (BMessenger (this), new BMessage (M_ABOUT_SCROLL),
		 50000);
}
Exemplo n.º 13
0
void HaikuDirectWindow::StartMessageRunner() {
	update_runner = new BMessageRunner(BMessenger(this),
			new BMessage(REDRAW_MSG), 1000000 / 30 /* 30 fps */);
}
Exemplo n.º 14
0
void
RatePackageWindow::_SendRatingThread()
{
	if (!Lock()) {
		fprintf(stderr, "upload rating: Failed to lock window\n");
		return;
	}

	BString package = fPackage->Name();
	BString architecture = fPackage->Architecture();
	BString repositoryCode;
	int rating = (int)fRating;
	BString stability = fStability;
	BString comment = fRatingText->Text();
	BString languageCode = fCommentLanguage;
	BString ratingID = fRatingID;
	bool active = fRatingActive;

	const DepotInfo* depot = fModel.DepotForName(fPackage->DepotName());

	if (depot != NULL)
		repositoryCode = depot->WebAppRepositoryCode();

	WebAppInterface interface = fModel.GetWebAppInterface();

	Unlock();

	if (repositoryCode.Length() == 0) {
		printf("unable to find the web app repository code for the local "
			"depot %s\n",
			fPackage->DepotName().String());
		return;
	}

	if (stability == "unspecified")
		stability = "";

	status_t status;
	BMessage info;
	if (ratingID.Length() > 0) {
		status = interface.UpdateUserRating(ratingID,
		languageCode, comment, stability, rating, active, info);
	} else {
		status = interface.CreateUserRating(package, architecture,
			repositoryCode, languageCode, comment, stability, rating, info);
	}

	BString error = B_TRANSLATE(
		"There was a puzzling response from the web service.");

	BMessage result;
	if (status == B_OK) {
		if (info.FindMessage("result", &result) == B_OK) {
			error = "";
		} else if (info.FindMessage("error", &result) == B_OK) {
			result.PrintToStream();
			BString message;
			if (result.FindString("message", &message) == B_OK) {
				if (message == "objectnotfound") {
					error = B_TRANSLATE("The package was not found by the "
						"web service. This probably means that it comes "
						"from a depot which is not tracked there. Rating "
						"such packages is unfortunately not supported.");
				} else {
					error << B_TRANSLATE(" It responded with: ");
					error << message;
				}
			}
		}
	} else {
		error = B_TRANSLATE(
			"It was not possible to contact the web service.");
	}

	if (!error.IsEmpty()) {
		BString failedTitle;
		if (ratingID.Length() > 0)
			failedTitle = B_TRANSLATE("Failed to update rating");
		else
			failedTitle = B_TRANSLATE("Failed to rate package");

		BAlert* alert = new(std::nothrow) BAlert(
			failedTitle,
			error,
			B_TRANSLATE("Close"), NULL, NULL,
			B_WIDTH_AS_USUAL, B_WARNING_ALERT);

		if (alert != NULL)
			alert->Go();

		fprintf(stderr,
			B_TRANSLATE("Failed to create or update rating: %s\n"),
			error.String());
		if (!info.IsEmpty())
			info.PrintToStream();

		_SetWorkerThread(-1);
	} else {
		_SetWorkerThread(-1);

		fModel.PopulatePackage(fPackage,
			Model::POPULATE_FORCE | Model::POPULATE_USER_RATINGS);

		BMessenger(this).SendMessage(B_QUIT_REQUESTED);

		BString message;
		if (ratingID.Length() > 0) {
			message = B_TRANSLATE("Your rating was updated successfully.");
		} else {
			message = B_TRANSLATE("Your rating was uploaded successfully. "
				"You can update or remove it at any time by rating the "
				"package again.");
		}

		BAlert* alert = new(std::nothrow) BAlert(
			B_TRANSLATE("Success"),
			message,
			B_TRANSLATE("Close"));

		if (alert != NULL)
			alert->Go();
	}
}
Exemplo n.º 15
0
SetupWindow::SetupWindow(void)
	: BWindow(BRect(108.0, 88.0, 500.0, 320.0), S_SETUP_TITLE, B_TITLED_WINDOW,
			  B_ASYNCHRONOUS_CONTROLS | B_NOT_RESIZABLE | B_NOT_ZOOMABLE)
{

	AddShortcut('/', B_SHIFT_KEY, new BMessage(M_PREFS_SHOW));

	bgView = new BView(Bounds(), "background", B_FOLLOW_ALL, B_WILL_DRAW);
	AddChild(bgView);
	bgView->SetViewUIColor(B_PANEL_BACKGROUND_COLOR);

	BRect rect = Bounds();
	LogoView* logo = new LogoView(rect);

	rect.top = logo->PreferredHeight();
	rect.bottom = Bounds().bottom;
	rect.left = kItemSpacing;

	BMenu* netMenu(new NetworkMenu(S_SETUP_CHOOSENET, M_SETUP_CHOOSE_NETWORK, BMessenger(this)));
	netMenu->SetLabelFromMarked(true);
	netList = new BMenuField(rect, "Network List", S_SETUP_CHOOSELABEL, netMenu);
	netList->ResizeToPreferred();
	netList->SetDivider(be_plain_font->StringWidth(S_SETUP_CHOOSELABEL) + 5);

	rect = netList->Frame();
	rect.OffsetBy(0, rect.Height() + kItemSpacing);
	connectButton = new BButton(rect, "connect", S_SETUP_CONNECT_BUTTON,
								new BMessage(M_CONNECT_NETWORK));
	connectButton->ResizeToPreferred();

	rect = connectButton->Frame();
	rect.OffsetBy(rect.Width() + kItemSpacing, 0);

	netPrefsButton = new BButton(rect, "netprefs", S_SETUP_NETPREFS B_UTF8_ELLIPSIS,
								 new BMessage(M_NETWORK_SHOW));
	netPrefsButton->ResizeToPreferred();
	netPrefsButton->SetTarget(vision_app);

	rect = netPrefsButton->Frame();
	rect.OffsetBy(rect.Width() + kItemSpacing, 0);

	prefsButton = new BButton(rect, "prefs", S_SETUP_GENPREFS B_UTF8_ELLIPSIS,
							  new BMessage(M_PREFS_SHOW));
	prefsButton->ResizeToPreferred();
	prefsButton->SetTarget(vision_app);

	rect = prefsButton->Frame();
	float newWidth = rect.right + kItemSpacing;
	float newHeight = rect.bottom + kItemSpacing;

	ResizeTo(newWidth, newHeight);

	bgView->AddChild(logo);
	bgView->AddChild(netList);
	bgView->AddChild(prefsButton);
	bgView->AddChild(netPrefsButton);
	bgView->AddChild(connectButton);

	rect = Bounds();
	rect.bottom = netList->Frame().bottom - (kItemSpacing * 2);
	logo->ResizeTo(newWidth, rect.Height());

	connectButton->SetEnabled(false);

	rect = vision_app->GetRect("SetupWinRect");
	if (rect.Width() > 0)
		MoveTo(rect.LeftTop());
}
Exemplo n.º 16
0
	virtual status_t WatchNode(const node_ref* node, uint32 flags,
		const BHandler* handler, const BLooper* looper = NULL)
	{
		return TTracker::WatchNode(node, flags, BMessenger(handler, looper));
	}
Exemplo n.º 17
0
void
BrowserApp::ReadyToRun()
{
	// Since we will essentially run the GUI...
	set_thread_priority(Thread(), B_DISPLAY_PRIORITY);

	BWebPage::InitializeOnce();
	BWebPage::SetCacheModel(B_WEBKIT_CACHE_MODEL_WEB_BROWSER);

	BPath path;
	if (find_directory(B_USER_SETTINGS_DIRECTORY, &path) == B_OK
		&& path.Append(kApplicationName) == B_OK
		&& create_directory(path.Path(), 0777) == B_OK) {

		BWebSettings::SetPersistentStoragePath(path.Path());
	}

	BString mainSettingsPath(kApplicationName);
	mainSettingsPath << "/Application";
	fSettings = new SettingsMessage(B_USER_SETTINGS_DIRECTORY,
		mainSettingsPath.String());

	fLastWindowFrame = fSettings->GetValue("window frame", fLastWindowFrame);
	BRect defaultDownloadWindowFrame(-10, -10, 365, 265);
	BRect downloadWindowFrame = fSettings->GetValue("downloads window frame",
		defaultDownloadWindowFrame);
	BRect settingsWindowFrame = fSettings->GetValue("settings window frame",
		BRect());
	BRect consoleWindowFrame = fSettings->GetValue("console window frame",
		BRect(50, 50, 400, 300));
	BRect cookieWindowFrame = fSettings->GetValue("cookie window frame",
		BRect(50, 50, 400, 300));
	bool showDownloads = fSettings->GetValue("show downloads", false);

	fDownloadWindow = new DownloadWindow(downloadWindowFrame, showDownloads,
		fSettings);
	if (downloadWindowFrame == defaultDownloadWindowFrame) {
		// Initially put download window in lower right of screen.
		BRect screenFrame = BScreen().Frame();
		BMessage decoratorSettings;
		fDownloadWindow->GetDecoratorSettings(&decoratorSettings);
		float borderWidth = 0;
		if (decoratorSettings.FindFloat("border width", &borderWidth) != B_OK)
			borderWidth = 5;
		fDownloadWindow->MoveTo(screenFrame.Width()
			- fDownloadWindow->Frame().Width() - borderWidth,
			screenFrame.Height() - fDownloadWindow->Frame().Height()
			- borderWidth);
	}
	fSettingsWindow = new SettingsWindow(settingsWindowFrame, fSettings);

	BWebPage::SetDownloadListener(BMessenger(fDownloadWindow));
	
	fConsoleWindow = new ConsoleWindow(consoleWindowFrame);
	fCookieWindow = new CookieWindow(cookieWindowFrame, fContext->GetCookieJar());

	fInitialized = true;

	int32 pagesCreated = 0;
	bool fullscreen = false;
	if (fLaunchRefsMessage) {
		_RefsReceived(fLaunchRefsMessage, &pagesCreated, &fullscreen);
		delete fLaunchRefsMessage;
		fLaunchRefsMessage = NULL;
	}

	// If no refs led to a new open page, restore previous session.
	if (pagesCreated == 0) {
		BMessage archivedWindow;
		for (int i = 0; fSession->FindMessage("window", i, &archivedWindow) == B_OK;
			i++) {
			BRect frame = archivedWindow.FindRect("window frame");
			BString url;
			archivedWindow.FindString("tab", 0, &url);
			BrowserWindow* window = new(std::nothrow) BrowserWindow(frame,
				fSettings, url, fContext);

			if (window != NULL) {
				window->Show();
				pagesCreated++;

				for (int j = 1; archivedWindow.FindString("tab", j, &url) == B_OK;
					j++) {
					printf("Create %d:%d\n", i, j);
					_CreateNewTab(window, url, false);
					pagesCreated++;
				}
			}
		}
	}

	// If previous session did not contain any window, create a new empty one.
	if (pagesCreated == 0)
		_CreateNewWindow("", fullscreen);

	PostMessage(PRELOAD_BROWSING_HISTORY);
}
Exemplo n.º 18
0
void
PairsWindow::MessageReceived(BMessage* message)
{
	switch (message->what) {
		case MENU_NEW:
			NewGame();
			break;

		case MENU_DIFFICULTY:
		{
			int32 rows;
			int32 cols;
			if (message->FindInt32("rows", &rows) == B_OK
				&& message->FindInt32("cols", &cols) == B_OK) {
				SetGameSize(rows, cols);
			}
			break;
		}

		case MENU_ICON_SIZE:
		{
			int32 size;
			if (message->FindInt32("size", &size) == B_OK) {
				fPairsView->SetIconSize(size);
				_ResizeWindow(fPairsView->Rows(), fPairsView->Cols());
			}

			break;
		}

		case MENU_QUIT:
			be_app->PostMessage(B_QUIT_REQUESTED);
			break;

		case kMsgCardButton:
		{
			if (!fIsPairsActive)
				break;

			int32 buttonNumber;
			if (message->FindInt32("button number", &buttonNumber) != B_OK)
				break;

			BObjectList<PairsButton>* pairsButtonList
				= fPairsView->PairsButtonList();
			if (pairsButtonList == NULL)
				break;

			// look at what icon is behind a button
			int32 buttonCount = pairsButtonList->CountItems();
			for (int32 i = 0; i < buttonCount; i++) {
				int32 iconPosition = fPairsView->GetIconPosition(i);
				if (iconPosition == buttonNumber) {
					fPairCardPosition = i % (buttonCount / 2);
					fButtonPosition = iconPosition;
					break;
				}
			}

			// gameplay
			fButtonClicks++;
			pairsButtonList->ItemAt(fButtonPosition)->Hide();

			if (fIsFirstClick) {
				fPairCardTmpPosition = fPairCardPosition;
				fButtonTmpPosition = fButtonPosition;
			} else {
				delete fPairComparing;
					// message of message runner might not have arrived
					// yet, so it is deleted here to prevent any leaking
					// just in case
				BMessage message(kMsgPairComparing);
				fPairComparing = new BMessageRunner(BMessenger(this),
					&message,  5 * 100000L, 1);
				fIsPairsActive = false;
			}

			fIsFirstClick = !fIsFirstClick;
			break;
		}

		case kMsgPairComparing:
		{
			BObjectList<PairsButton>* pairsButtonList
				= fPairsView->PairsButtonList();
			if (pairsButtonList == NULL)
				break;

			delete fPairComparing;
			fPairComparing = NULL;

			fIsPairsActive = true;

			if (fPairCardPosition == fPairCardTmpPosition)
				fFinishPairs++;
			else {
				pairsButtonList->ItemAt(fButtonPosition)->Show();
				pairsButtonList->ItemAt(fButtonTmpPosition)->Show();
			}

			// game end and results
			if (fFinishPairs == pairsButtonList->CountItems() / 2) {
				BString score;
				score << fButtonClicks;
				BString strAbout = B_TRANSLATE("%app%\n"
					"\twritten by Ralf Schülke\n"
					"\tCopyright 2008-2010, Haiku Inc.\n"
					"\n"
					"You completed the game in %num% clicks.\n");

				strAbout.ReplaceFirst("%app%",
					B_TRANSLATE_SYSTEM_NAME("Pairs"));
				strAbout.ReplaceFirst("%num%", score);

				BAlert* alert = new BAlert("about",
					strAbout.String(),
					B_TRANSLATE("New game"),
					B_TRANSLATE("Quit game"));

				BTextView* view = alert->TextView();
				BFont font;

				view->SetStylable(true);

				view->GetFont(&font);
				font.SetSize(18);
				font.SetFace(B_BOLD_FACE);
				view->SetFontAndColor(0,
					strlen(B_TRANSLATE_SYSTEM_NAME("Pairs")), &font);
				view->ResizeToPreferred();
				alert->SetShortcut(0, B_ESCAPE);

				if (alert->Go() == 0)
					NewGame();
				else
					be_app->PostMessage(B_QUIT_REQUESTED);
			}
			break;
		}

		default:
			BWindow::MessageReceived(message);
	}
}
Exemplo n.º 19
0
void
TeamWindow::_Init()
{
	BScrollView* sourceScrollView;

	const float splitSpacing = 3.0f;

	BLayoutBuilder::Group<>(this, B_VERTICAL, 0.0f)
		.Add(fMenuBar = new BMenuBar("Menu"))
		.AddSplit(B_VERTICAL, splitSpacing)
			.GetSplitView(&fFunctionSplitView)
			.SetInsets(B_USE_SMALL_INSETS)
			.Add(fTabView = new BTabView("tab view"), 0.4f)
			.AddSplit(B_HORIZONTAL, splitSpacing)
				.GetSplitView(&fSourceSplitView)
				.AddGroup(B_VERTICAL, B_USE_SMALL_SPACING)
					.AddGroup(B_HORIZONTAL, B_USE_SMALL_SPACING)
						.Add(fRunButton = new BButton("Run"))
						.Add(fStepOverButton = new BButton("Step over"))
						.Add(fStepIntoButton = new BButton("Step into"))
						.Add(fStepOutButton = new BButton("Step out"))
						.AddGlue()
					.End()
					.Add(fSourcePathView = new BStringView(
						"source path",
						"Source path unavailable."), 4.0f)
					.Add(sourceScrollView = new BScrollView("source scroll",
						NULL, 0, true, true), splitSpacing)
				.End()
				.Add(fLocalsTabView = new BTabView("locals view"))
			.End()
			.AddSplit(B_VERTICAL, splitSpacing)
				.GetSplitView(&fConsoleSplitView)
				.SetInsets(0.0)
				.Add(fConsoleOutputView = ConsoleOutputView::Create())
			.End()
		.End();

	// add source view
	sourceScrollView->SetTarget(fSourceView = SourceView::Create(fTeam, this));

	// add threads tab
	BSplitView* threadGroup = new BSplitView(B_HORIZONTAL, splitSpacing);
	threadGroup->SetName("Threads");
	fTabView->AddTab(threadGroup);
	BLayoutBuilder::Split<>(threadGroup)
		.GetSplitView(&fThreadSplitView)
		.Add(fThreadListView = ThreadListView::Create(fTeam, this))
		.Add(fStackTraceView = StackTraceView::Create(this));

	// add images tab
	BSplitView* imagesGroup = new BSplitView(B_HORIZONTAL, splitSpacing);
	imagesGroup->SetName("Images");
	fTabView->AddTab(imagesGroup);
	BLayoutBuilder::Split<>(imagesGroup)
		.GetSplitView(&fImageSplitView)
		.Add(fImageListView = ImageListView::Create(fTeam, this))
		.Add(fImageFunctionsView = ImageFunctionsView::Create(this));

	// add breakpoints tab
	BGroupView* breakpointsGroup = new BGroupView(B_HORIZONTAL,
		B_USE_SMALL_SPACING);
	breakpointsGroup->SetName("Breakpoints");
	fTabView->AddTab(breakpointsGroup);
	BLayoutBuilder::Group<>(breakpointsGroup)
//		.SetInsets(0.0f)
		.Add(fBreakpointsView = BreakpointsView::Create(fTeam, this));

	// add local variables tab
	BView* tab = fVariablesView = VariablesView::Create(this);
	fLocalsTabView->AddTab(tab);

	// add registers tab
	tab = fRegistersView = RegistersView::Create(fTeam->GetArchitecture());
	fLocalsTabView->AddTab(tab);

	fRunButton->SetMessage(new BMessage(MSG_THREAD_RUN));
	fStepOverButton->SetMessage(new BMessage(MSG_THREAD_STEP_OVER));
	fStepIntoButton->SetMessage(new BMessage(MSG_THREAD_STEP_INTO));
	fStepOutButton->SetMessage(new BMessage(MSG_THREAD_STEP_OUT));
	fRunButton->SetTarget(this);
	fStepOverButton->SetTarget(this);
	fStepIntoButton->SetTarget(this);
	fStepOutButton->SetTarget(this);

	fSourcePathView->SetExplicitMinSize(BSize(100.0, B_SIZE_UNSET));
	fSourcePathView->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET));
	BMessageFilter* filter = new(std::nothrow) PathViewMessageFilter(
		BMessenger(this));
	if (filter != NULL)
		fSourcePathView->AddFilter(filter);

	// add menus and menu items
	BMenu* menu = new BMenu("Team");
	fMenuBar->AddItem(menu);
	BMenuItem* item = new BMenuItem("Restart", new BMessage(
		MSG_TEAM_RESTART_REQUESTED), 'R', B_SHIFT_KEY);
	menu->AddItem(item);
	item->SetTarget(this);
	item = new BMenuItem("Close", new BMessage(B_QUIT_REQUESTED),
		'W');
	menu->AddItem(item);
	item->SetTarget(this);
	menu = new BMenu("Edit");
	fMenuBar->AddItem(menu);
	item = new BMenuItem("Copy", new BMessage(B_COPY), 'C');
	menu->AddItem(item);
	item->SetTarget(this);
	item = new BMenuItem("Select all", new BMessage(B_SELECT_ALL), 'A');
	menu->AddItem(item);
	item->SetTarget(this);
	menu = new BMenu("Tools");
	fMenuBar->AddItem(menu);
	item = new BMenuItem("Save debug report",
		new BMessage(MSG_CHOOSE_DEBUG_REPORT_LOCATION));
	menu->AddItem(item);
	item->SetTarget(this);
	item = new BMenuItem("Inspect memory",
		new BMessage(MSG_SHOW_INSPECTOR_WINDOW), 'I');
	menu->AddItem(item);
	item->SetTarget(this);

	AutoLocker< ::Team> locker(fTeam);
	_UpdateRunButtons();
}
Exemplo n.º 20
0
TFilePanel::TFilePanel(file_panel_mode mode, BMessenger* target,
	const BEntry* startDir, uint32 nodeFlavors, bool multipleSelection,
	BMessage* message, BRefFilter* filter, uint32 containerWindowFlags,
	window_look look, window_feel feel, bool hideWhenDone)
	:
	BContainerWindow(0, containerWindowFlags, look, feel, 0,
		B_CURRENT_WORKSPACE, false),
	fDirMenu(NULL),
	fDirMenuField(NULL),
	fTextControl(NULL),
	fClientObject(NULL),
	fSelectionIterator(0),
	fMessage(NULL),
	fHideWhenDone(hideWhenDone),
	fIsTrackingMenu(false)
{
	InitIconPreloader();

	fIsSavePanel = (mode == B_SAVE_PANEL);

	BRect windRect(85, 50, 568, 296);
	MoveTo(windRect.LeftTop());
	ResizeTo(windRect.Width(), windRect.Height());

	fNodeFlavors = (nodeFlavors == 0) ? B_FILE_NODE : nodeFlavors;

	if (target)
		fTarget = *target;
	else
		fTarget = BMessenger(be_app);

	if (message)
		SetMessage(message);
	else if (fIsSavePanel)
		fMessage = new BMessage(B_SAVE_REQUESTED);
	else
		fMessage = new BMessage(B_REFS_RECEIVED);

	gLocalizedNamePreferred
		= BLocaleRoster::Default()->IsFilesystemTranslationPreferred();

	// check for legal starting directory
	Model* model = new Model();
	bool useRoot = true;

	if (startDir) {
		if (model->SetTo(startDir) == B_OK && model->IsDirectory())
			useRoot = false;
		else {
			delete model;
			model = new Model();
		}
	}

	if (useRoot) {
		BPath path;
		if (find_directory(B_USER_DIRECTORY, &path) == B_OK) {
			BEntry entry(path.Path(), true);
			if (entry.InitCheck() == B_OK && model->SetTo(&entry) == B_OK)
				useRoot = false;
		}
	}

	if (useRoot) {
		BVolume volume;
		BDirectory root;
		BVolumeRoster volumeRoster;
		volumeRoster.GetBootVolume(&volume);
		volume.GetRootDirectory(&root);

		BEntry entry;
		root.GetEntry(&entry);
		model->SetTo(&entry);
	}

	fTaskLoop = new PiggybackTaskLoop;

	AutoLock<BWindow> lock(this);
	fBorderedView = new BorderedView;
	CreatePoseView(model);
	fPoseView->SetRefFilter(filter);
	if (!fIsSavePanel)
		fPoseView->SetMultipleSelection(multipleSelection);

	fPoseView->SetFlags(fPoseView->Flags() | B_NAVIGABLE);
	fPoseView->SetPoseEditing(false);
	AddCommonFilter(new BMessageFilter(B_KEY_DOWN, key_down_filter));
	AddCommonFilter(new BMessageFilter(B_SIMPLE_DATA,
		TFilePanel::MessageDropFilter));
	AddCommonFilter(new BMessageFilter(B_NODE_MONITOR, TFilePanel::FSFilter));

	// inter-application observing
	BMessenger tracker(kTrackerSignature);
	BHandler::StartWatching(tracker, kDesktopFilePanelRootChanged);

	Init();
}
Exemplo n.º 21
0
void
TBarApp::MessageReceived(BMessage* message)
{
	switch (message->what) {
		case 'gloc':
		case 'sloc':
		case 'gexp':
		case 'sexp':
		case 'info':
		case 'exst':
		case 'cwnt':
		case 'icon':
		case 'remv':
		case 'adon':
			// pass any BDeskbar originating messages on to the window
			fBarWindow->PostMessage(message);
			break;

		case kConfigShow:
			ShowPreferencesWindow();
			break;

		case kStateChanged:
			fPreferencesWindow->PostMessage(kStateChanged);
			break;

		case kShowDeskbarMenu:
			if (fBarWindow->Lock()) {
				fBarWindow->ShowDeskbarMenu();
				fBarWindow->Unlock();
			}
			break;

		case kShowTeamMenu:
			if (fBarWindow->Lock()) {
				fBarWindow->ShowTeamMenu();
				fBarWindow->Unlock();
			}
			break;

		case kUpdateRecentCounts:
			int32 count;
			bool enabled;

			if (message->FindInt32("applications", &count) == B_OK)
				fSettings.recentAppsCount = count;
			if (message->FindBool("applicationsEnabled", &enabled) == B_OK)
				fSettings.recentAppsEnabled = enabled && count > 0;

			if (message->FindInt32("folders", &count) == B_OK)
				fSettings.recentFoldersCount = count;
			if (message->FindBool("foldersEnabled", &enabled) == B_OK)
				fSettings.recentFoldersEnabled = enabled && count > 0;

			if (message->FindInt32("documents", &count) == B_OK)
				fSettings.recentDocsCount = count;
			if (message->FindBool("documentsEnabled", &enabled) == B_OK)
				fSettings.recentDocsEnabled = enabled && count > 0;
			break;

		case kConfigClose:
			fPreferencesWindow = NULL;
			break;

		case B_SOME_APP_LAUNCHED:
		{
			team_id team = -1;
			message->FindInt32("be:team", &team);

			uint32 flags = 0;
			message->FindInt32("be:flags", (long*)&flags);

			const char* sig = NULL;
			message->FindString("be:signature", &sig);

			entry_ref ref;
			message->FindRef("be:ref", &ref);

			AddTeam(team, flags, sig, &ref);
			break;
		}

		case B_SOME_APP_QUIT:
		{
			team_id team = -1;
			message->FindInt32("be:team", &team);
			RemoveTeam(team);
			break;
		}

		case B_ARCHIVED_OBJECT:
			// TODO: what's this???
			message->AddString("special", "Alex Osadzinski");
			fStatusViewMessenger.SendMessage(message);
			break;

		case kToggleDraggers:
			if (BDragger::AreDraggersDrawn())
				BDragger::HideAllDraggers();
			else
				BDragger::ShowAllDraggers();
			break;

		case kAlwaysTop:
			fSettings.alwaysOnTop = !fSettings.alwaysOnTop;
			fBarWindow->SetFeel(fSettings.alwaysOnTop ?
				B_FLOATING_ALL_WINDOW_FEEL : B_NORMAL_WINDOW_FEEL);
			fPreferencesWindow->PostMessage(kStateChanged);
			break;

		case kAutoRaise:
			fSettings.autoRaise = fSettings.alwaysOnTop ? false :
				!fSettings.autoRaise;

			fBarWindow->Lock();
			BarView()->UpdateEventMask();
			fBarWindow->Unlock();
			break;

		case kAutoHide:
			fSettings.autoHide = !fSettings.autoHide;

			fBarWindow->Lock();
			BarView()->UpdateEventMask();
			BarView()->HideDeskbar(fSettings.autoHide);
			fBarWindow->Unlock();
			break;

		case kTrackerFirst:
			fSettings.trackerAlwaysFirst = !fSettings.trackerAlwaysFirst;

			fBarWindow->Lock();
			BarView()->UpdatePlacement();
			fBarWindow->Unlock();
			break;

		case kSortRunningApps:
			fSettings.sortRunningApps = !fSettings.sortRunningApps;

			fBarWindow->Lock();
			BarView()->UpdatePlacement();
			fBarWindow->Unlock();
			break;

		case kUnsubscribe:
		{
			BMessenger messenger;
			if (message->FindMessenger("messenger", &messenger) == B_OK)
				Unsubscribe(messenger);
			break;
		}

		case kSuperExpando:
			fSettings.superExpando = !fSettings.superExpando;

			fBarWindow->Lock();
			BarView()->UpdatePlacement();
			fBarWindow->Unlock();
			break;

		case kExpandNewTeams:
			fSettings.expandNewTeams = !fSettings.expandNewTeams;

			fBarWindow->Lock();
			BarView()->UpdatePlacement();
			fBarWindow->Unlock();
			break;

		case 'TASK':
			fSwitcherMessenger.SendMessage(message);
			break;

		case kSuspendSystem:
			// TODO: Call BRoster?
			break;

		case kRebootSystem:
		case kShutdownSystem:
		{
			bool reboot = (message->what == kRebootSystem);
			bool confirm;
			message->FindBool("confirm", &confirm);

			BRoster roster;
			BRoster::Private rosterPrivate(roster);
			status_t error = rosterPrivate.ShutDown(reboot, confirm, false);
			if (error != B_OK)
				fprintf(stderr, "Shutdown failed: %s\n", strerror(error));

			break;
		}

		case kShowSplash:
			run_be_about();
			break;

		case kRestartTracker:
		{
			BRoster roster;
			roster.Launch(kTrackerSignature);
			break;
		}

		case B_LOCALE_CHANGED:
		{
			BLocaleRoster::Default()->Refresh();

			bool localize;
			if (message->FindBool("filesys", &localize) == B_OK)
				gLocalizedNamePreferred = localize;

			BMessenger(fBarWindow->FindView("_deskbar_tv_")).SendMessage(
				message);
				// Notify the TimeView that the format has changed and it should
				// recompute its size
			break;
		}

		default:
			BApplication::MessageReceived(message);
			break;
	}
}
Exemplo n.º 22
0
void
TFilePanel::Init(const BMessage*)
{
	BRect windRect(Bounds());
	fBackView = new BView(Bounds(), "View", B_FOLLOW_ALL, 0);
	fBackView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
	AddChild(fBackView);

	// add poseview menu bar
	fMenuBar = new BMenuBar(BRect(0, 0, windRect.Width(), 1), "MenuBar");
	fMenuBar->SetBorder(B_BORDER_FRAME);
	fBackView->AddChild(fMenuBar);

	// add directory menu and menufield
	fDirMenu = new BDirMenu(0, this, kSwitchDirectory, "refs");

	font_height ht;
	be_plain_font->GetHeight(&ht);
	float f_height = ht.ascent + ht.descent + ht.leading;

	BRect rect;
	rect.top = fMenuBar->Bounds().Height() + 8;
	rect.left = windRect.left + 8;
	rect.right = rect.left + 300;
	rect.bottom = rect.top + (f_height > 22 ? f_height : 22);

	fDirMenuField = new BMenuField(rect, "DirMenuField", "", fDirMenu);
	fDirMenuField->MenuBar()->SetFont(be_plain_font);
	fDirMenuField->SetDivider(0);
	fDirMenuField->MenuBar()->SetMaxContentWidth(rect.Width() - 26.0f);
		// Make room for the icon

	fDirMenuField->MenuBar()->RemoveItem((int32)0);
	fDirMenu->SetMenuBar(fDirMenuField->MenuBar());
		// the above is a weird call from BDirMenu
		// ToDo: clean up

	BEntry entry(TargetModel()->EntryRef());
	if (entry.InitCheck() == B_OK)
		fDirMenu->Populate(&entry, 0, true, true, false, true);
	else
		fDirMenu->Populate(0, 0, true, true, false, true);

	fBackView->AddChild(fDirMenuField);

	// add file name text view
	if (fIsSavePanel) {
		BRect rect(windRect);
		rect.top = rect.bottom - 35;
		rect.left = 8;
		rect.right = rect.left + 170;
		rect.bottom = rect.top + 13;

		fTextControl = new BTextControl(rect, "text view",
			B_TRANSLATE("save text"), "", NULL,
			B_FOLLOW_LEFT | B_FOLLOW_BOTTOM);
		DisallowMetaKeys(fTextControl->TextView());
		DisallowFilenameKeys(fTextControl->TextView());
		fBackView->AddChild(fTextControl);
		fTextControl->SetDivider(0.0f);
		fTextControl->TextView()->SetMaxBytes(B_FILE_NAME_LENGTH - 1);

		fButtonText.SetTo(B_TRANSLATE("Save"));
	} else
		fButtonText.SetTo(B_TRANSLATE("Open"));

	// Add PoseView
	fBorderedView->SetName("PoseView");
	fBorderedView->SetResizingMode(B_FOLLOW_ALL);
	fBorderedView->EnableBorderHighlight(true);

	rect = windRect;
	rect.OffsetTo(10, fDirMenuField->Frame().bottom + 10);
	rect.bottom = windRect.bottom - 60;
	rect.right -= B_V_SCROLL_BAR_WIDTH + 20;
	fBorderedView->MoveTo(rect.LeftTop());
	fBorderedView->ResizeTo(rect.Width(), rect.Height());

	PoseView()->AddScrollBars();
	PoseView()->SetDragEnabled(false);
	PoseView()->SetDropEnabled(false);
	PoseView()->SetSelectionHandler(this);
	PoseView()->SetSelectionChangedHook(true);
	PoseView()->DisableSaveLocation();

	// horizontal
	rect = fBorderedView->Frame();
	rect.top = rect.bottom;
	rect.bottom = rect.top + (float)B_H_SCROLL_BAR_HEIGHT;
	PoseView()->HScrollBar()->MoveTo(rect.LeftTop());
	PoseView()->HScrollBar()->ResizeTo(rect.Size());
	PoseView()->HScrollBar()->SetResizingMode(B_FOLLOW_LEFT_RIGHT | B_FOLLOW_BOTTOM);
	fBackView->AddChild(PoseView()->HScrollBar());

	// vertical
	rect = fBorderedView->Frame();
	rect.left = rect.right;
	rect.right = rect.left + (float)B_V_SCROLL_BAR_WIDTH;
	PoseView()->VScrollBar()->MoveTo(rect.LeftTop());
	PoseView()->VScrollBar()->ResizeTo(rect.Size());
	PoseView()->VScrollBar()->SetResizingMode(B_FOLLOW_TOP_BOTTOM | B_FOLLOW_RIGHT);
	fBackView->AddChild(PoseView()->VScrollBar());

	if (fIsSavePanel)
		fBackView->AddChild(fBorderedView, fTextControl);
	else
		fBackView->AddChild(fBorderedView);

	AddShortcut('W', B_COMMAND_KEY, new BMessage(kCancelButton));
	AddShortcut('H', B_COMMAND_KEY, new BMessage(kSwitchToHome));
	AddShortcut('A', B_COMMAND_KEY | B_SHIFT_KEY,
		new BMessage(kShowSelectionWindow));
	AddShortcut('A', B_COMMAND_KEY, new BMessage(B_SELECT_ALL), PoseView());
	AddShortcut('S', B_COMMAND_KEY, new BMessage(kInvertSelection),
		PoseView());
	AddShortcut('Y', B_COMMAND_KEY, new BMessage(kResizeToFit), PoseView());
	AddShortcut(B_DOWN_ARROW, B_COMMAND_KEY, new BMessage(kOpenDir));
	AddShortcut(B_DOWN_ARROW, B_COMMAND_KEY | B_OPTION_KEY,
		new BMessage(kOpenDir));
	AddShortcut(B_UP_ARROW, B_COMMAND_KEY, new BMessage(kOpenParentDir));
	AddShortcut(B_UP_ARROW, B_COMMAND_KEY | B_OPTION_KEY,
		new BMessage(kOpenParentDir));

	// New code to make buttons font sensitive
	rect = windRect;
	rect.top = rect.bottom - 35;
	rect.bottom -= 10;
	rect.right -= 25;
	float default_width
		= be_plain_font->StringWidth(fButtonText.String()) + 20;
	rect.left = default_width > 75
		? rect.right - default_width : rect.right - 75;

	BButton* default_button = new BButton(rect, "default button",
		fButtonText.String(), new BMessage(kDefaultButton),
		B_FOLLOW_RIGHT + B_FOLLOW_BOTTOM);
	fBackView->AddChild(default_button);

	rect.right = rect.left -= 10;
	float cancel_width
		= be_plain_font->StringWidth(B_TRANSLATE("Cancel")) + 20;
	rect.left = cancel_width > 75
		? rect.right - cancel_width : rect.right - 75;

	BButton* cancel_button = new BButton(rect, "cancel button",
		B_TRANSLATE("Cancel"), new BMessage(kCancelButton),
		B_FOLLOW_RIGHT + B_FOLLOW_BOTTOM);
	fBackView->AddChild(cancel_button);

	if (!fIsSavePanel)
		default_button->SetEnabled(false);

	default_button->MakeDefault(true);

	RestoreState();

	AddMenus();
	AddContextMenus();

	FavoritesMenu* favorites = new FavoritesMenu(B_TRANSLATE("Favorites"),
		new BMessage(kSwitchDirectory), new BMessage(B_REFS_RECEIVED),
		BMessenger(this), IsSavePanel(), fPoseView->RefFilter());
	favorites->AddItem(new BMenuItem(B_TRANSLATE("Add current folder"),
		new BMessage(kAddCurrentDir)));
	favorites->AddItem(new BMenuItem(
		B_TRANSLATE("Edit favorites" B_UTF8_ELLIPSIS),
		new BMessage(kEditFavorites)));

	fMenuBar->AddItem(favorites);

	// configure menus
	BMenuItem* item = fMenuBar->FindItem(B_TRANSLATE("Window"));
	if (item) {
		fMenuBar->RemoveItem(item);
		delete item;
	}

	item = fMenuBar->FindItem(B_TRANSLATE("File"));
	if (item) {
		BMenu* menu = item->Submenu();
		if (menu) {
			item = menu->FindItem(kOpenSelection);
			if (item && menu->RemoveItem(item))
				delete item;

			item = menu->FindItem(kDuplicateSelection);
			if (item && menu->RemoveItem(item))
				delete item;

			// remove add-ons menu, identifier menu, separator
			item = menu->FindItem(B_TRANSLATE("Add-ons"));
			if (item) {
				int32 index = menu->IndexOf(item);
				delete menu->RemoveItem(index);
				delete menu->RemoveItem(--index);
				delete menu->RemoveItem(--index);
			}

			// remove separator
			item = menu->FindItem(B_CUT);
			if (item) {
				item = menu->ItemAt(menu->IndexOf(item)-1);
				if (item && menu->RemoveItem(item))
					delete item;
			}
		}
	}

	PoseView()->ScrollTo(B_ORIGIN);
	PoseView()->UpdateScrollRange();
	PoseView()->ScrollTo(B_ORIGIN);

	if (fTextControl) {
		fTextControl->MakeFocus();
		fTextControl->TextView()->SelectAll();
	} else
		PoseView()->MakeFocus();

	app_info info;
	BString title;
	if (be_app->GetAppInfo(&info) == B_OK) {
		if (!gLocalizedNamePreferred
			|| BLocaleRoster::Default()->GetLocalizedFileName(
				title, info.ref, false) != B_OK)
			title = info.ref.name;
		title << ": ";
	}
	title << fButtonText;	// Open or Save

	SetTitle(title.String());

	SetSizeLimits(370, 10000, 200, 10000);
}
Exemplo n.º 23
0
ChatWindow::ChatWindow(entry_ref & ref)
:	BWindow( 
		BRect(100,100,400,300), 
		"unknown contact - unknown status", 
		B_TITLED_WINDOW,
		B_ASYNCHRONOUS_CONTROLS | B_AVOID_FOCUS
	),
	fEntry(ref),
	fMan( new IM::Manager(BMessenger(this))),
	fChangedNotActivated(false),
	fStatusBar(NULL),
	fSendButton(NULL),
	fProtocolHack(NULL)
{

	bool command, sendButton;
	int32 iconBarSize;
	
	BMessage chatSettings;
	im_load_client_settings("im_emoclient", &chatSettings);
	
	if ( chatSettings.FindBool("command_sends", &command) != B_OK )
		command = true;
	if ( chatSettings.FindBool("show_send_button", &sendButton) != B_OK )
		sendButton = true;
	if ( chatSettings.FindInt32("icon_size", &iconBarSize) != B_OK )
		iconBarSize = kLargeIcon;
	if ( iconBarSize <= 0 )
		iconBarSize = kLargeIcon;
	if (chatSettings.FindString("people_handler", &fPeopleHandler) != B_OK) {
		fPeopleHandler = kDefaultPeopleHandler;
	};
	if (chatSettings.FindString("other", &fOtherText) != B_OK ) {
		fOtherText.SetTo( "$name$ ($nickname$) ($protocol$) ");
	}
	
	// Set window size limits
	SetSizeLimits(
		220, 8000, // width,
		150, 8000  // height
	);
	
	// get the size of various things
	font_height height;
	be_plain_font->GetHeight(&height);
	fFontHeight = height.ascent + height.descent + height.leading;
	
	// default window size
	BRect windowRect(100, 100, 400, 300);
	BPoint inputDivider(0, 150);
	
	// load window size if possible
	if (LoadSettings() == B_OK) {
		bool was_ok = true;
		
		if (fWindowSettings.FindRect("windowrect", &windowRect) != B_OK) {
			was_ok = false;
		}
		if (fWindowSettings.FindPoint("inputdivider", &inputDivider) != B_OK) {
			was_ok = false;
		}
		
		if ( !was_ok )
		{
			windowRect = BRect(100, 100, 400, 300);
			inputDivider = BPoint(0, 200);
		}
	}
	
	// sanity check for divider location
	if ( inputDivider.y > windowRect.Height() - 50 ) {
		LOG("im_emoclient", liLow, "Insane divider, fixed.");
		inputDivider.y = windowRect.Height() - 50;
	};
	
	// set size and position
	MoveTo(windowRect.left, windowRect.top);
	ResizeTo(windowRect.Width(), windowRect.Height());
	
	// create views
	BRect textRect = Bounds();
	BRect inputRect = Bounds();
	BRect dockRect = Bounds();

	dockRect.bottom = iconBarSize + kDockPadding;
	fDock = new IconBar(dockRect);
	
#if B_BEOS_VERSION > B_BEOS_VERSION_5
	fDock->SetViewUIColor(B_UI_PANEL_BACKGROUND_COLOR);
	fDock->SetLowUIColor(B_UI_PANEL_BACKGROUND_COLOR);
	fDock->SetHighUIColor(B_UI_PANEL_TEXT_COLOR);
#else
	fDock->SetViewColor( ui_color(B_PANEL_BACKGROUND_COLOR) );
	fDock->SetLowColor( ui_color(B_PANEL_BACKGROUND_COLOR) );
	fDock->SetHighColor(0, 0, 0, 0);
#endif
	AddChild(fDock);
	
	// add buttons
	ImageButton * btn;
	BBitmap * icon;
//	long err = 0;
	BPath iconDir;
	BPath iconPath;
	BRect buttonRect(0,0,iconBarSize+8,iconBarSize+8);
	find_directory(B_USER_SETTINGS_DIRECTORY, &iconDir, true);
	iconDir.Append("im_kit/icons");
	
//	People Button
	icon = IconForHandler(fPeopleHandler.String(), iconBarSize);
	btn = MakeButton(icon, "Show contact in People", new BMessage(SHOW_INFO), buttonRect);
	fDock->AddItem(btn);
		
//	Email button
	icon = IconForHandler("text/x-email", iconBarSize);
	btn = MakeButton(icon, "Send email to contact", new BMessage(EMAIL), buttonRect);
	fDock->AddItem(btn);
	
//	Block Button
	iconPath = iconDir;
	iconPath.Append("Block");
	icon = ReadNodeIcon(iconPath.Path(), iconBarSize, true);
	btn = MakeButton(icon, "Block messages from contact", new BMessage(BLOCK), buttonRect);
	fDock->AddItem(btn);

//	Log Button
	icon = IconForHandler("application/x-vnd.BeClan.im_binlog_viewer", iconBarSize);
	btn = MakeButton(icon, "View chat history for contact", new BMessage(VIEW_LOG), buttonRect);
	fDock->AddItem(btn);
	
//	Webpage Button
	icon = IconForHandler("text/html", iconBarSize);
	btn = MakeButton(icon, "View contact's web page", new BMessage(VIEW_WEBPAGE), buttonRect);
	fDock->AddItem(btn);
	
// Emoticons	
	iconPath = iconDir;
	iconPath.Append("emoticons");
	icon = ReadNodeIcon(iconPath.Path(), iconBarSize);
	btn = MakeButton(icon, "Emoticons", new BMessage(VIEW_EMOTICONS), buttonRect);
	fDock->AddItem(btn);
	

	textRect.top = fDock->Bounds().bottom+1;
	textRect.InsetBy(2,2);
	textRect.bottom = inputDivider.y;
	textRect.right -= B_V_SCROLL_BAR_WIDTH;
	
	float sendButtonWidth = sendButton ? 50 : 0;
	
	inputRect.InsetBy(2.0, 2.0);
	inputRect.top = inputDivider.y + 7;
	inputRect.right -= B_V_SCROLL_BAR_WIDTH + sendButtonWidth;
	inputRect.bottom -= fFontHeight + (kPadding * 4);
	
	BRect inputTextRect = inputRect;
	inputTextRect.OffsetTo(kPadding, kPadding);
	inputTextRect.InsetBy(kPadding * 2, kPadding * 2);
	
	fInput = new BTextView(inputRect, "input", inputTextRect, B_FOLLOW_ALL,
		B_WILL_DRAW);
	
#if B_BEOS_VERSION > B_BEOS_VERSION_5
	fInput->SetViewUIColor(B_UI_DOCUMENT_BACKGROUND_COLOR);
	fInput->SetLowUIColor(B_UI_DOCUMENT_BACKGROUND_COLOR);
	fInput->SetHighUIColor(B_UI_DOCUMENT_TEXT_COLOR);
#else
	fInput->SetViewColor(245, 245, 245, 0);
	fInput->SetLowColor(245, 245, 245, 0);
	fInput->SetHighColor(0, 0, 0, 0);
#endif

	fInputScroll = new BScrollView(
		"input_scroller", fInput,
		B_FOLLOW_LEFT_RIGHT | B_FOLLOW_BOTTOM, 0,
		false,
		true,
		B_PLAIN_BORDER
	);

	AddChild(fInputScroll);	
	
	fInput->SetWordWrap(true);
	fInput->SetStylable(false);
	fInput->MakeSelectable(true);
	
	if ( sendButton ) {
		BRect sendRect = fInputScroll->Frame();
		sendRect.left = sendRect.right+1;
		sendRect.right = Bounds().right;
		
		fSendButton = new BButton(
			sendRect, "sendButton", _T("Send"), new BMessage(SEND_MESSAGE),
			B_FOLLOW_RIGHT|B_FOLLOW_BOTTOM
		);
	
		AddChild( fSendButton );
	}
	
	BRect statusRect = Bounds();
	statusRect.top = inputRect.bottom + kPadding;
	
	fStatusBar = new StatusBar(statusRect);
	
	AddChild(fStatusBar);
#if B_BEOS_VERSION > B_BEOS_VERSION_5
	fStatusBar->SetViewUIColor(B_UI_PANEL_BACKGROUND_COLOR);
	fStatusBar->SetLowUIColor(B_UI_PANEL_BACKGROUND_COLOR);
	fStatusBar->SetHighUIColor(B_UI_PANEL_TEXT_COLOR);
#else
	fStatusBar->SetViewColor(245, 245, 245, 0);
	fStatusBar->SetLowColor(245, 245, 245, 0);
	fStatusBar->SetHighColor(0, 0, 0, 0);
#endif
	
	BPopUpMenu *pop = new BPopUpMenu("Protocols", true, true);
	fProtocolMenu = new BMenuField(
		BRect(kPadding, kPadding, Bounds().bottom - kPadding, 100),
		"Field", NULL, pop);
	fStatusBar->AddItem(fProtocolMenu);
	
	// fInfoView must be the LAST thing added to fStatusBar, otherwise the
	// resizing of it will be all bonkers.
	fInfoView = new BStringView(BRect(fProtocolMenu->Frame().right+5, 2,
		fStatusBar->Bounds().right - kPadding,
		fStatusBar->Bounds().bottom - kPadding), "infoView",
		"", B_FOLLOW_LEFT_RIGHT | B_FOLLOW_BOTTOM, B_WILL_DRAW);
	fStatusBar->AddItem(fInfoView);
#if B_BEOS_VERSION > B_BEOS_VERSION_5
	fInfoView->SetViewUIColor(B_UI_PANEL_BACKGROUND_COLOR);
	fInfoView->SetLowUIColor(B_UI_PANEL_BACKGROUND_COLOR);
	fInfoView->SetHighUIColor(B_UI_PANEL_TEXT_COLOR);
#else
	fInfoView->SetViewColor(245, 245, 245, 0);
	fInfoView->SetLowColor(245, 245, 245, 0);
	fInfoView->SetHighColor(0, 0, 0, 0);
#endif
	
	// need to build the menu here since it fiddles with fInfoView
	BuildProtocolMenu();
	BMenuItem *first = pop->ItemAt(0);
	if (first) first->SetMarked(true);

	BRect resizeRect = Bounds();
	resizeRect.top = inputDivider.y + 1;
	resizeRect.bottom = inputDivider.y + 4;
	
	fResize = new ResizeView(fInputScroll, resizeRect, "resizer",
		B_FOLLOW_BOTTOM | B_FOLLOW_LEFT_RIGHT);
	AddChild(fResize);
	
	Theme::TimestampFore = C_TIMESTAMP_DUMMY;
	Theme::TimestampBack = C_TIMESTAMP_DUMMY;
	Theme::TimespaceFore = MAX_COLORS;
	Theme::TimespaceBack = MAX_COLORS;
	Theme::TimespaceFont = MAX_FONTS;
	Theme::TimestampFont = F_TIMESTAMP_DUMMY;
	Theme::NormalFore = C_TEXT;
	Theme::NormalBack = C_TEXT;
	Theme::NormalFont = F_TEXT;
	Theme::SelectionBack = C_SELECTION;
	
	fTheme = new Theme("ChatWindow", MAX_COLORS + 1, MAX_COLORS + 1, MAX_FONTS + 1);

	//NormalTextRender *ntr=new NormalTextRender(be_plain_font);
	
	fTheme->WriteLock();
	fTheme->SetForeground(C_URL, 5, 5, 150);
	fTheme->SetBackground(C_URL, 255, 255, 255);
	//fTheme->SetTextRender(C_URL, ntr);
	
	fTheme->SetForeground(C_TIMESTAMP, 130, 130, 130);
	fTheme->SetBackground(C_TIMESTAMP, 255, 255, 255);
	//fTheme->SetTextRender(F_TIMESTAMP, ntr);

	fTheme->SetForeground(C_TEXT, 0, 0, 0);
	fTheme->SetBackground(C_TEXT, 255, 255, 255);
	//fTheme->SetTextRender(F_TEXT, ntr);
	
	fTheme->SetForeground(C_ACTION, 0, 0, 0);
	fTheme->SetBackground(C_ACTION, 255, 255, 255);
	//fTheme->SetTextRender(F_ACTION, ntr);
	
	fTheme->SetForeground(C_SELECTION, 255, 255, 255);
	fTheme->SetBackground(C_SELECTION, 0, 0, 0);

	fTheme->SetForeground(C_OWNNICK, 0, 0, 255);
	fTheme->SetBackground(C_OWNNICK, 255, 255, 255);
	
	fTheme->SetForeground(C_OTHERNICK, 255, 0, 0);
	fTheme->SetBackground(C_OTHERNICK, 255, 255, 255);
	
	//SmileTextRender *str=new SmileTextRender();
	fTheme->SetTextRender(F_EMOTICON,&str);	
	

	fTheme->WriteUnlock();
	
//	IM::Contact con(&fEntry);
//	char id[256];
//	con.ConnectionAt(0, id);

	fText = ((ChatApp *)be_app)->GetRunView(/*id*/ fEntry);
	if (fText == NULL) {
		fText = new RunView(
			textRect, "text", fTheme,
			B_FOLLOW_ALL, B_WILL_DRAW
		);

#if B_BEOS_VERSION > B_BEOS_VERSION_5
		fText->SetViewUIColor(B_UI_DOCUMENT_BACKGROUND_COLOR);
		fText->SetLowUIColor(B_UI_DOCUMENT_BACKGROUND_COLOR);
		fText->SetHighUIColor(B_UI_DOCUMENT_TEXT_COLOR);
#else
		fText->SetViewColor(245, 245, 245, 0);
		fText->SetLowColor(245, 245, 245, 0);
		fText->SetHighColor(0, 0, 0, 0);
#endif

		fText->SetTimeStampFormat(NULL);
	};
	
	fTextScroll = new BScrollView(
		"scroller", fText,
		B_FOLLOW_ALL, 0,
		false, // horiz
		true, // vert
		B_PLAIN_BORDER
	);
	AddChild(fTextScroll);
	fTextScroll->MoveTo(0,fDock->Bounds().bottom+1);
	
	if ( fText->IsHidden() )
		fText->Show();
	fText->ScrollToBottom();
	
	fInput->MakeFocus();
	
	// add input filter that generates "user typing" messages and routes copy-commands
	fFilter = new InputFilter(fInput, new BMessage(SEND_MESSAGE), command, fText,
		kTypingSendRate);
	fInput->AddFilter((BMessageFilter *)fFilter);
	
	// monitor node so we get updates to status etc
	BEntry entry(&ref);
	node_ref node;
	
	entry.GetNodeRef(&node);
	watch_node( &node, B_WATCH_ALL, BMessenger(this) );
	
	// get contact info
	reloadContact();

	// set up timer for clearing typing view
	fTypingTimer = NULL;
	fTypingTimerSelf = NULL;
	
	// this message runner needed to fix a BMenuField bug.
	BMessage protoHack(PROTOCOL_SELECTED2);
	fProtocolHack = new BMessageRunner( BMessenger(this), &protoHack, 10000, 1 );
}
Exemplo n.º 24
0
void ArpIntControl::StartTimer(const BMessage& msg, bigtime_t delay)
{
	StopTimer();
	mEditRunner = new BMessageRunner(BMessenger(this), &msg, delay, 1);
}
Exemplo n.º 25
0
void
MediaConverterWindow::MessageReceived(BMessage* message)
{
	entry_ref inRef;

	char buffer[40];
	BEntry inEntry;

	switch (message->what) {
		#if B_BEOS_VERSION <= B_BEOS_VERSION_6
		case B_LANGUAGE_CHANGED:
			LanguageChanged();
			break;
		#endif

		case INIT_FORMAT_MENUS:
			BuildFormatMenu();
			if (CountSourceFiles() == 0)
				SetEnabled(false, false);
			break;

		case B_SIMPLE_DATA:
			if (message->WasDropped()) {
				DetachCurrentMessage();
				message->what = B_REFS_RECEIVED;
				BMessenger(be_app).SendMessage(message);
				delete message;
			}
			break;

		case FORMAT_SELECT_MESSAGE:
			BuildAudioVideoMenus();
			break;
		case AUDIO_CODEC_SELECT_MESSAGE:
			break;
		case VIDEO_CODEC_SELECT_MESSAGE:
			break;

		case CONVERT_BUTTON_MESSAGE:
			if (!fConverting) {
				fConvertButton->SetLabel(B_TRANSLATE("Cancel"));
				fConverting = true;
				SetStatusMessage(B_TRANSLATE("Convert"));
				SetEnabled(false, true);
				BMessenger(be_app).SendMessage(START_CONVERSION_MESSAGE);
			} else if (!fCancelling) {
				fCancelling = true;
				SetStatusMessage(B_TRANSLATE("Cancelling" B_UTF8_ELLIPSIS));
				BMessenger(be_app).SendMessage(CANCEL_CONVERSION_MESSAGE);
			}
			break;

		case CONVERSION_DONE_MESSAGE:
		{
			SetStatusMessage(fCancelling ? B_TRANSLATE("Conversion cancelled")
				: B_TRANSLATE("Conversion completed"));
			fConverting = false;
			fCancelling = false;
			bool enable = CountSourceFiles() > 0;
			SetEnabled(enable, enable);
			fConvertButton->SetLabel(B_TRANSLATE("Convert"));
			break;
		}

		case OUTPUT_FOLDER_MESSAGE:
			// Execute Save Panel
			if (fSaveFilePanel == NULL) {
				BButton* selectThisDir;

				BMessage folderSelect(FOLDER_SELECT_MESSAGE);
				fSaveFilePanel = new BFilePanel(B_OPEN_PANEL, NULL, NULL,
					B_DIRECTORY_NODE, true, &folderSelect, NULL, false, true);
				fSaveFilePanel->SetButtonLabel(B_DEFAULT_BUTTON,
					B_TRANSLATE("Select"));
				fSaveFilePanel->SetTarget(this);

				fSaveFilePanel->Window()->Lock();
				fSaveFilePanel->Window()->SetTitle(
					B_TRANSLATE("MediaConverter+:SaveDirectory"));
				BRect buttonRect
					= fSaveFilePanel->Window()->ChildAt(0)->FindView(
						"cancel button")->Frame();
				buttonRect.right  = buttonRect.left - 20;
				buttonRect.left = buttonRect.right - 130;
				selectThisDir = new BButton(buttonRect, NULL,
					B_TRANSLATE("Select this folder"),
					new BMessage(SELECT_THIS_DIR_MESSAGE),
					B_FOLLOW_BOTTOM | B_FOLLOW_RIGHT);
				selectThisDir->SetTarget(this);
				fSaveFilePanel->Window()->ChildAt(0)->AddChild(selectThisDir);
				fSaveFilePanel->Window()->Unlock();

				fSaveFilePanel->SetRefFilter(new DirectoryFilter);
			}
			fSaveFilePanel->Show();
			break;

		case FOLDER_SELECT_MESSAGE:
			// "SELECT" Button at Save Panel Pushed
			fSaveFilePanel->GetNextSelectedRef(&inRef);
			inEntry.SetTo(&inRef, true);
			_SetOutputFolder(inEntry);
			fOutputDirSpecified = true;
			fSaveFilePanel->Rewind();
			break;

		case SELECT_THIS_DIR_MESSAGE:
			// "THIS DIR" Button at Save Panel Pushed
			fSaveFilePanel->GetPanelDirectory(&inRef);
			fSaveFilePanel->Hide();
			inEntry.SetTo(&inRef, true);
			_SetOutputFolder(inEntry);
			fOutputDirSpecified = true;
			break;

		case OPEN_FILE_MESSAGE:
			// Execute Open Panel
			if (!fOpenFilePanel) {
				fOpenFilePanel = new BFilePanel(B_OPEN_PANEL, NULL, NULL,
					B_FILE_NODE, true, NULL, NULL, false, true);
				fOpenFilePanel->SetTarget(this);
			}
			fOpenFilePanel->Show();
			break;

		case B_REFS_RECEIVED:
			// Media Files Seleced by Open Panel
			DetachCurrentMessage();
			message->what = B_REFS_RECEIVED;
			BMessenger(be_app).SendMessage(message);
			// fall through

		case B_CANCEL:
			break;

		case QUIT_MESSAGE:
			MediaConverterWindow::QuitRequested();
			break;

		case PREVIEW_MESSAGE:
		{
			// Build the command line to launch the preview application.
			// TODO: Launch the default app instead of hardcoded MediaPlayer!
			int32 srcIndex = fListView->CurrentSelection();
			BMediaFile* inFile = NULL;
			status_t status = GetSourceFileAt(srcIndex, &inFile, &inRef);

			const char* argv[3];
			BString startPosString;
			BPath path;

			if (status == B_OK) {
				argv[0] = "-pos";
					// NOTE: -pos argument is currently not supported by Haiku
					// MediaPlayer.
				startPosString << fStartDurationTC->Text();
				startPosString << "000";
				argv[1] = startPosString.String();

				status = inEntry.SetTo(&inRef);
			}

			if (status == B_OK) {
				status = inEntry.GetPath(&path);
				if (status == B_OK)
					argv[2] = path.Path();
			}

			if (status == B_OK) {
				status = be_roster->Launch(
					"application/x-vnd.Haiku-MediaPlayer",
					3, (char**)argv, NULL);
			}

			if (status != B_OK && status != B_ALREADY_RUNNING) {
				BString errorString(B_TRANSLATE("Error launching: %strError%"));
				errorString.ReplaceFirst("%strError%", strerror(status));
				BAlert* alert = new BAlert(B_TRANSLATE("Error"),
					errorString.String(), B_TRANSLATE("OK"));
				alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
				alert->Go();
			}
			break;
		}

		case VIDEO_QUALITY_CHANGED_MESSAGE:
		{
			int32 value;
			message->FindInt32("be:value", &value);
			snprintf(buffer, sizeof(buffer),
				B_TRANSLATE("Video quality: %3d%%"), (int8)value);
			fVideoQualitySlider->SetLabel(buffer);
			fVideoQuality = value;
			break;
		}

		case AUDIO_QUALITY_CHANGED_MESSAGE:
		{
			int32 value;
			message->FindInt32("be:value", &value);
			snprintf(buffer, sizeof(buffer),
				B_TRANSLATE("Audio quality: %3d%%"), (int8)value);
			fAudioQualitySlider->SetLabel(buffer);
			fAudioQuality = value;
			break;
		}

		default:
			BWindow::MessageReceived(message);
	}
}
Exemplo n.º 26
0
/*------------------------------------------------------------------------------*\
	MessageReceived( msg)
		-	
\*------------------------------------------------------------------------------*/
void BmPrefsIdentityView::MessageReceived( BMessage* msg) {
	try {
		switch( msg->what) {
			case BM_SELECTION_CHANGED: {
				int32 index = mIdentListView->CurrentSelection( 0);
				ShowIdentity( index);
				break;
			}
			case BM_TEXTFIELD_MODIFIED: {
				if (mCurrIdent) {
					BView* srcView = NULL;
					msg->FindPointer( "source", (void**)&srcView);
					BmTextControl* source = dynamic_cast<BmTextControl*>( srcView);
					if ( source == mIdentityControl)
						TheIdentityList->RenameItem( mCurrIdent->Name(), 
															  mIdentityControl->Text());
					else if ( source == mMailAddrControl)
						mCurrIdent->MailAddr( mMailAddrControl->Text());
					else if ( source == mAliasesControl)
						mCurrIdent->MailAliases( mAliasesControl->Text());
					else if ( source == mRealNameControl)
						mCurrIdent->RealName( mRealNameControl->Text());
					else if ( source == mReplyToControl)
						mCurrIdent->ReplyTo( mReplyToControl->Text());
					NoticeChange();
				}
				break;
			}
			case BM_IS_BUCKET_CHANGED: {
				if (mCurrIdent)
					mCurrIdent->MarkedAsBitBucket( mIsBucketControl->Value());
				NoticeChange();
				break;
			}
			case BM_SMTP_SELECTED: {
				BMenuItem* item = mSmtpControl->Menu()->FindMarked();
				if (item && BM_NoItemLabel != item->Label())
					mCurrIdent->SMTPAccount( item->Label());
				else
					mCurrIdent->SMTPAccount( "");
				NoticeChange();
				break;
			}
			case BM_RECV_SELECTED: {
				BMenuItem* item = mRecvControl->Menu()->FindMarked();
				if (item && BM_NoItemLabel != item->Label())
					mCurrIdent->RecvAccount( item->Label());
				else
					mCurrIdent->RecvAccount( "");
				NoticeChange();
				break;
			}
			case BM_SIGNATURE_SELECTED: {
				BMenuItem* item = mSignatureControl->Menu()->FindMarked();
				if (item && BM_NoItemLabel != item->Label())
					mCurrIdent->SignatureName( item->Label());
				else
					mCurrIdent->SignatureName( "");
				NoticeChange();
				break;
			}
			case BM_SET_SPECIAL_HEADERS: {
				if (!mCurrIdent)
					break;
				BmString specialHeaders = mCurrIdent->SpecialHeaders();
				BScreen scr;
				BRect screen( scr.Frame());
				float w=600, h=400;
				BRect alertFrame( (screen.Width()-w)/2,
										(screen.Height()-h)/2,
										(screen.Width()+w)/2,
										(screen.Height()+h)/2);
				TextEntryAlert* alert = 
					new TextEntryAlert( 
						"Edit Special Headers", 
						"Please enter any special headers below, "
						"just as they would appear in a mail.\n\n"
						"Here's an example: \n"
						"    Bcc: maileater <*****@*****.**>\n"
						"    Cc: Jim-Bob <*****@*****.**>\n"
						"        John-Boy <*****@*****.**>\n"
						"    X-Company-Special: grok.dis",
						specialHeaders.String(),
						"Cancel",
						"OK",
						false, 80, 20, B_WIDTH_FROM_LABEL, true,
						&alertFrame
					);
				alert->SetShortcut( 0, B_ESCAPE);
				alert->TextEntryView()->DisallowChar( 27);
				alert->TextEntryView()->SetFontAndColor( be_fixed_font);
				alert->SetShortcut( 0, B_ESCAPE);
				int32 choice = alert->Go( specialHeaders);
				if (choice == 1) {
					if (specialHeaders.Length()
					&& specialHeaders[specialHeaders.Length()-1] != '\n')
						specialHeaders << '\n';
					mCurrIdent->SpecialHeaders( specialHeaders);
				}
				break;
			}
			case BM_ADD_IDENTITY: {
				BmString key( "new identity");
				for( int32 i=1; TheIdentityList->FindItemByKey( key); ++i) {
					key = BmString("new identity_")<<i;
				}
				TheIdentityList->AddItemToList( 
					new BmIdentity( key.String(), 
										 TheIdentityList.Get())
				);
				mIdentityControl->MakeFocus( true);
				mIdentityControl->TextView()->SelectAll();
				NoticeChange();
				break;
			}
			case BM_REMOVE_IDENTITY: {
				int32 buttonPressed;
				if (msg->FindInt32( "which", &buttonPressed) != B_OK) {
					// first step, ask user about it:
					BAlert* alert 
						= new BAlert( "Remove Mail-Identity", 
										  (BmString(
										  		"Are you sure about removing the "
										  		"identity <") << mCurrIdent->Name() 
											   << ">?"
										  ).String(),
										  "Remove", "Cancel", NULL, B_WIDTH_AS_USUAL,
										  B_WARNING_ALERT);
					alert->SetShortcut( 1, B_ESCAPE);
					alert->Go( new BInvoker( new BMessage(BM_REMOVE_IDENTITY), 
													 BMessenger( this)));
				} else {
					// second step, do it if user said ok:
					if (buttonPressed == 0) {
						TheIdentityList->RemoveItemFromList( mCurrIdent.Get());
						mCurrIdent = NULL;
						NoticeChange();
					}
				}
				break;
			}
			case BM_COMPLAIN_ABOUT_FIELD: {
				int32 buttonPressed;
				if (msg->FindInt32( "which", &buttonPressed) != B_OK) {
					BmString complaint;
					complaint = msg->FindString( MSG_COMPLAINT);
					// first step, tell user about complaint:
					BAlert* alert = new BAlert( "Sanity Check Failed", 
														 complaint.String(),
													 	 "OK", NULL, NULL, B_WIDTH_AS_USUAL,
													 	 B_WARNING_ALERT);
					alert->SetShortcut( 0, B_ESCAPE);
					alert->Go( new BInvoker( new BMessage(*msg), BMessenger( this)));
					BmIdentity* ident=NULL;
					msg->FindPointer( MSG_ITEM, (void**)&ident);
					BmListViewItem* accItem 
						= mIdentListView->FindViewItemFor( ident);
					if (accItem)
						mIdentListView->Select( mIdentListView->IndexOf( accItem));
				} else {
					// second step, set corresponding focus:
					BmString fieldName;
					fieldName = msg->FindString( MSG_FIELD_NAME);
					if (fieldName.ICompare( "smtpaccount")==0)
						mSmtpControl->MakeFocus( true);
					else if (fieldName.ICompare( "recvaccount")==0)
						mRecvControl->MakeFocus( true);
				}
				break;
			}
			default:
				inherited::MessageReceived( msg);
		}
	}
	catch( BM_error &err) {
		// a problem occurred, we tell the user:
		BM_SHOWERR( BmString("PrefsView_") << Name() << ":\n\t" << err.what());
	}
}
Exemplo n.º 27
0
void
ProjectWindow::MessageReceived(BMessage *msg)
{
	status_t status;
	
	if ( (msg->WasDropped() && msg->what == B_SIMPLE_DATA) || msg->what == M_ADD_FILES)
	{
		fAddFileStruct.refmsg = *msg;
		fAddFileStruct.parent = this;
		
		uint32 buttons;
		fProjectList->GetMouse(&fAddFileStruct.droppt,&buttons);
		
		thread_id addThread = spawn_thread(AddFileThread,"file adding thread",
											B_NORMAL_PRIORITY, &fAddFileStruct);
		if (addThread >= 0)
			resume_thread(addThread);
	}
	switch (msg->what)
	{
		case M_IMPORT_REFS:
		{
			fImportStruct.refmsg = *msg;
			fImportStruct.parent = this;
			
			thread_id importThread = spawn_thread(ImportFileThread,"file import thread",
												B_NORMAL_PRIORITY, &fImportStruct);
			if (importThread >= 0)
				resume_thread(importThread);
			break;
		}
		case M_BACKUP_PROJECT:
		{
			thread_id backupThread = spawn_thread(BackupThread,"project backup thread",
												B_NORMAL_PRIORITY, this);
			if (backupThread >= 0)
			{
				fStatusBar->SetText(TR("Backing up project"));
				UpdateIfNeeded();
				
				SetMenuLock(true);
				resume_thread(backupThread);
			}
			break;
		}
		case M_GET_CHECK_IN_MSG:
		{
			if (!fSourceControl)
			{
				printf("NULL source control\n");
				break;
			}
			
			BString out;
			fSourceControl->GetCheckinHeader(out);
			
			bool select = false;
			if (out.CountChars() > 1)
				out.Prepend("\n\n");
			else
			{
				out = TR("Enter the description for the changes in this revision.");
				select = true;
			}
			
			GetTextWindow *gtw = new GetTextWindow("Paladin", out.String(),
													BMessage(M_CHECK_IN_PROJECT),
													BMessenger(this));
			if (!select)
				gtw->GetTextView()->Select(0,0);
			gtw->Show();
			break;
		}
		case M_CHECK_IN_PROJECT:
		{
			BString commitstr;
			if (msg->FindString("text", &commitstr) == B_OK && fSourceControl)
			{
				SCMOutputWindow *win = new SCMOutputWindow(TR("Commit"));
				win->Show();
				fSourceControl->Commit(commitstr.String());
			}
			break;
		}
		case M_REVERT_PROJECT:
		{
			if (!fSourceControl)
				break;
			
			int32 result = ShowAlert(TR("This will undo all changes since the last commit. "
										"Continue?"), "Don't Revert", "Revert");
			if (result == 1)
			{
				SCMOutputWindow *win = new SCMOutputWindow(TR("Revert"));
				win->Show();
				fSourceControl->Revert(NULL);
			}
			break;
		}
		case M_REBUILD_FILE:
		case M_ADD_SELECTION_TO_REPO:
		case M_REMOVE_SELECTION_FROM_REPO:
		case M_REVERT_SELECTION:
		case M_DIFF_SELECTION:
		{
			ActOnSelectedFiles(msg->what);
			break;
		}
		case M_DIFF_PROJECT:
		{
			if (fSourceControl)
			{
				SCMOutputWindow *win = new SCMOutputWindow(TR("Differences"));
				win->Show();
				fSourceControl->Diff(NULL);
			}
			break;
		}
		case M_PROJECT_SCM_STATUS:
		{
			if (fSourceControl)
			{
				SCMOutputWindow *win = new SCMOutputWindow(TR("Project Status"));
				BString strstatus;
				fSourceControl->GetChangeStatus(strstatus);
				win->GetTextView()->SetText(strstatus.String());
				win->Show();
			}
			break;
		}
		case M_PUSH_PROJECT:
		{
			if (fSourceControl)
			{
				SCMOutputWindow *win = new SCMOutputWindow(TR("Push"));
				win->Show();
				fSourceControl->Push(NULL);
			}
			break;
		}
		case M_PULL_PROJECT:
		{
			if (fSourceControl)
			{
				SCMOutputWindow *win = new SCMOutputWindow(TR("Pull"));
				win->Show();
				status = fSourceControl->Pull(NULL);
				
				if (!status)
					ShowAlert("Unable to pull from the remote repository. If it "
							"uses a secure connection, please set up the appropriate "
							"SSH keys on the remote server.", "OK");
			}
			break;
		}
		case M_CULL_EMPTY_GROUPS:
		{
			CullEmptyGroups();
			break;
		}
		case M_RUN_FILE_TYPES:
		{
			int32 selection = fProjectList->FullListCurrentSelection();
			if (selection < 0)
				break;
			
			SourceFileItem *item = dynamic_cast<SourceFileItem*>(fProjectList->FullListItemAt(selection));
			if (!item)
				break;
			SpawnFileTypes(item->GetData()->GetPath());
			break;
		}
		case M_OPEN_PARENT_FOLDER:
		{
			BMessage openmsg(B_REFS_RECEIVED);
			int32 selindex = 0;
			int32 selection = fProjectList->FullListCurrentSelection();
			selindex++;
			if (selection >= 0)
			{
				while (selection >= 0)
				{
					SourceFileItem *item = dynamic_cast<SourceFileItem*>(fProjectList->FullListItemAt(selection));
					if (!item)
						break;
					
					SourceFile *file = item->GetData();
					BString abspath = file->GetPath().GetFullPath();
					if (abspath[0] != '/')
					{
						abspath.Prepend("/");
						abspath.Prepend(fProject->GetPath().GetFolder());
					}
					DPath filepath(abspath);
					
					entry_ref ref;
					BEntry(filepath.GetFolder()).GetRef(&ref);
					
					openmsg.AddRef("refs",&ref);
					selection = fProjectList->FullListCurrentSelection(selindex++);
				}
				
				BMessenger msgr("application/x-vnd.Be-TRAK");
				msgr.SendMessage(&openmsg);
			}
			
			break;
		}
		case M_SHOW_PROJECT_FOLDER:
		{
			entry_ref ref;
			BEntry(fProject->GetPath().GetFolder()).GetRef(&ref);
			BMessenger msgr("application/x-vnd.Be-TRAK");
			
			BMessage openmsg(B_REFS_RECEIVED);
			openmsg.AddRef("refs",&ref);
			msgr.SendMessage(&openmsg);
			break;
		}
		case M_SHOW_ASCII_TABLE:
		{
			AsciiWindow *ascwin = new AsciiWindow();
			ascwin->Show();
			break;
		}
		case M_SHOW_VREGEX:
		{
			VRegWindow *vregwin = new VRegWindow();
			vregwin->Show();
			break;
		}
		case M_SHOW_LICENSES:
		{
			LicenseManager *man = new LicenseManager(fProject->GetPath().GetFolder());
			man->Show();
			break;
		}
		case M_RUN_TOOL:
		{
			BString sig;
			if (msg->FindString("signature", &sig) == B_OK)
			{
				LaunchHelper launcher(sig.String());
				launcher.Launch();
			}
			break;
		}
		case M_MAKE_MAKE:
		{
			DPath out(fProject->GetPath().GetFolder());
			out.Append("Makefile");
			if (MakeMake(fProject,out) == B_OK);
			{
				BEntry entry(out.GetFullPath());
				entry_ref ref;
				if (entry.InitCheck() == B_OK)
				{
					entry.GetRef(&ref);
					BMessage refmsg(B_REFS_RECEIVED);
					refmsg.AddRef("refs",&ref);
					be_app->PostMessage(&refmsg);
				}
			}
			break;
		}
		case M_SHOW_CODE_LIBRARY:
		{
			#ifdef BUILD_CODE_LIBRARY
			CodeLibWindow *libwin = CodeLibWindow::GetInstance(BRect(100,100,500,350));
			libwin->Show();
			#endif
			
			break;
		}
		case M_OPEN_PARTNER:
		{
			int32 selection = fProjectList->FullListCurrentSelection();
			if (selection < 0)
				break;
			
			SourceFileItem *item = dynamic_cast<SourceFileItem*>(
									fProjectList->FullListItemAt(selection));
			if (!item)
				break;
			entry_ref ref;
			BEntry(fProject->GetPathForFile(item->GetData()).GetFullPath()).GetRef(&ref);
			BMessage refmsg(M_OPEN_PARTNER);
			refmsg.AddRef("refs",&ref);
			be_app->PostMessage(&refmsg);
			break;
		}
		case M_NEW_GROUP:
		{
			MakeGroup(fProjectList->FullListCurrentSelection());
			PostMessage(M_SHOW_RENAME_GROUP);
			break;
		}
		case M_SHOW_RENAME_GROUP:
		{
			int32 selection = fProjectList->FullListCurrentSelection();
			SourceGroupItem *groupItem = NULL;
			if (selection < 0)
			{
				// Don't need a selection if there is only one group in the project
				if (fProject->CountGroups() == 1)
					groupItem = fProjectList->ItemForGroup(fProject->GroupAt(0));
			}
			else
			{
				BStringItem *strItem = (BStringItem*)fProjectList->FullListItemAt(selection);
				groupItem = fProjectList->GroupForItem(strItem);
			}
			
			if (!groupItem)
				break;
			
			GroupRenameWindow *grwin = new GroupRenameWindow(groupItem->GetData(),
															BMessage(M_RENAME_GROUP),
															BMessenger(this));
			grwin->Show();
			break;
		}
		case M_RENAME_GROUP:
		{
			SourceGroup *group;
			BString newname;
			if (msg->FindPointer("group",(void**)&group) != B_OK ||
				msg->FindString("newname",&newname) != B_OK)
				break;
			
			group->name = newname;
			SourceGroupItem *groupItem = fProjectList->ItemForGroup(group);
			if (!groupItem)
				break;
			
			groupItem->SetText(newname.String());
			fProjectList->InvalidateItem(fProjectList->IndexOf(groupItem));
			
			fProject->Save();
			break;
		}
		case M_SORT_GROUP:
		{
			int32 selection = fProjectList->FullListCurrentSelection();
			
			SourceGroupItem *groupItem = NULL;
			if (selection < 0)
			{
				// Don't need a selection if there is only one group in the project
				if (fProject->CountGroups() == 1)
					groupItem = fProjectList->ItemForGroup(fProject->GroupAt(0));
			}
			else
			{
				BStringItem *strItem = (BStringItem*)fProjectList->FullListItemAt(selection);
				groupItem = fProjectList->GroupForItem(strItem);
			}
			
			if (!groupItem)
				break;
			
			fProjectList->SortItemsUnder(groupItem,true,compare_source_file_items);
			groupItem->GetData()->Sort();
			fProject->Save();
			
			break;
		}
		case M_TOGGLE_ERROR_WINDOW:
		{
			ToggleErrorWindow(fProject->GetErrorList());
			break;
		}
		case M_SHOW_ERROR_WINDOW:
		{
			ShowErrorWindow(fProject->GetErrorList());
			break;
		}
		case M_SHOW_PROJECT_SETTINGS:
		{
			BRect r(0,0,350,300);
			BRect screen(BScreen().Frame());
			
			r.OffsetTo((screen.Width() - r.Width()) / 2.0,
						(screen.Height() - r.Height()) / 2.0);
			
			ProjectSettingsWindow *win = new ProjectSettingsWindow(r,fProject);
			win->Show();
			break;
		}
		case M_SHOW_RUN_ARGS:
		{
			RunArgsWindow *argwin = new RunArgsWindow(fProject);
			argwin->Show();
			break;
		}
		case M_JUMP_TO_MSG:
		{
			entry_ref ref;
			if (msg->FindRef("refs",&ref) == B_OK)
			{
				msg->what = B_REFS_RECEIVED;
				be_app->PostMessage(msg);
			}
			break;
		}
		case B_ABOUT_REQUESTED:
		{
			be_app->PostMessage(B_ABOUT_REQUESTED);
			break;
		}
		case M_SHOW_OPEN_PROJECT:
		{
			be_app->PostMessage(msg);
			break;
		}
		case M_NEW_WINDOW:
		{
			be_app->PostMessage(M_NEW_PROJECT);
			break;
		}
		case M_SHOW_PROGRAM_SETTINGS:
		{
			PrefsWindow *prefwin = new PrefsWindow(BRect(0,0,500,400));
			prefwin->Show();
			break;
		}
		case M_SHOW_FIND_AND_OPEN_PANEL:
		{
			BString text;
			msg->FindString("name",&text);
			
			// Passing a NULL string to this is OK
			FindOpenFileWindow *findwin = new FindOpenFileWindow(text.String());
			findwin->Show();
			break;
		}
		case M_FILE_NEEDS_BUILD:
		{
			SourceFile *file;
			if (msg->FindPointer("file",(void**)&file) == B_OK)
			{
				SourceFileItem *item = fProjectList->ItemForFile(file);
				if (item)
				{
					item->SetDisplayState(SFITEM_NEEDS_BUILD);
					fProjectList->InvalidateItem(fProjectList->IndexOf(item));
				}
			}
			break;
		}
		case M_EDIT_FILE:
		{
			int32 i = 0;
			int32 selection = fProjectList->FullListCurrentSelection(i);
			i++;
			
			BMessage refmsg(B_REFS_RECEIVED);
			while (selection >= 0)
			{
				SourceFileItem *item = dynamic_cast<SourceFileItem*>
										(fProjectList->FullListItemAt(selection));
				if (item && item->GetData())
				{
					BString abspath = item->GetData()->GetPath().GetFullPath();
					if (abspath[0] != '/')
					{
						abspath.Prepend("/");
						abspath.Prepend(fProject->GetPath().GetFolder());
					}
					
					BEntry entry(abspath.String());
					if (entry.InitCheck() == B_OK)
					{
						entry_ref ref;
						entry.GetRef(&ref);
						refmsg.AddRef("refs",&ref);
					}
					else
					{
						if (!entry.Exists())
						{
							BString errmsg = TR("Couldn't find XXXXX. It may have been moved or renamed.");
							errmsg.ReplaceFirst("XXXXX",abspath.String());
							ShowAlert(errmsg.String());
						}
					}
				}
				else
				{
					SourceGroupItem *groupItem = dynamic_cast<SourceGroupItem*>
											(fProjectList->FullListItemAt(selection));
					if (groupItem)
					{
						if (groupItem->IsExpanded())
							fProjectList->Collapse(groupItem);
						else
							fProjectList->Expand(groupItem);
						groupItem->GetData()->expanded = groupItem->IsExpanded();
					}
					
				}
				
				selection = fProjectList->CurrentSelection(i);
				i++;
			}
			be_app->PostMessage(&refmsg);
			break;
		}
		case M_LIBWIN_CLOSED:
		{
			fShowingLibs = false;
			break;
		}
		case M_SHOW_LIBRARIES:
		{
			fShowingLibs = true;
			LibraryWindow *libwin = new LibraryWindow(Frame().OffsetByCopy(15,15),
														BMessenger(this), fProject);
			libwin->Show();
			break;
		}
		case M_SHOW_ADD_NEW_PANEL:
		{
			AddNewFileWindow *anfwin = new AddNewFileWindow(BMessage(M_ADD_NEW_FILE),
														BMessenger(this));
			anfwin->Show();
			break;
		}
		case M_SHOW_FIND_IN_PROJECT_FILES:
		{
			if (!gLuaAvailable)
			{
				ShowAlert("Paladin's multi-file Find window depends on Lua. It will "
						"need to be installed if you wish to use this feature.", "OK",
						NULL, NULL, B_STOP_ALERT);
				break;
			}
			
			FindWindow *findwin = new FindWindow();
			findwin->Show();
			break;
		}
		case M_ADD_NEW_FILE:
		{
			BString name;
			bool makepair;
			if (msg->FindString("name",&name) == B_OK && msg->FindBool("makepair",&makepair) == B_OK)
				AddNewFile(name,makepair);
			break;
		}
		case M_SHOW_ADD_PANEL:
		{
			if (!fFilePanel)
			{
				BMessenger msgr(this);
				BEntry entry(fProject->GetPath().GetFolder());
				entry_ref ref;
				entry.GetRef(&ref);
				fFilePanel = new BFilePanel(B_OPEN_PANEL,&msgr,&ref,B_FILE_NODE,true,
											new BMessage(M_ADD_FILES));
			}
			fFilePanel->Show();
			break;
		}
		case M_REMOVE_FILES:
		{
			bool save = false;
			
			for (int32 i = 0; i < fProjectList->CountItems(); i++)
			{
				SourceFileItem *item = dynamic_cast<SourceFileItem*>(fProjectList->ItemAt(i));
				if (item && item->IsSelected())
				{
					fProjectList->RemoveItem(item);
					fProject->RemoveFile(item->GetData());
					delete item;
					save = true;
					i--;
				}
			}
			CullEmptyGroups();
			if (save)
				fProject->Save();
			break;
		}
		case M_EMPTY_CCACHE:
		{
			// We don't do this when forcing a rebuild of the sources because sometimes it
			// can take quite a while
			if (gUseCCache && gCCacheAvailable)
			{
				fStatusBar->SetText(TR("Emptying build cache"));
				UpdateIfNeeded();
				system("ccache -c > /dev/null");
				fStatusBar->SetText("");
				UpdateIfNeeded();
			}
			break;
		}
		case M_FORCE_REBUILD:
		{
			fProject->ForceRebuild();
			
			for (int32 i = 0; i < fProjectList->FullListCountItems(); i++)
			{
				SourceFileItem *item = dynamic_cast<SourceFileItem*>(fProjectList->FullListItemAt(i));
				if (!item)
					continue;
				
				SourceFile *file = item->GetData();
				if (file->UsesBuild())
				{
					item->SetDisplayState(SFITEM_NEEDS_BUILD);
					fProjectList->InvalidateItem(i);
				}
			}
			// This is necessary because InvalidateItem() uses indices from ItemAt(),
			// not FullListItemAt
			fProjectList->Invalidate();
			break;
		}
		case M_UPDATE_DEPENDENCIES:
		{
			UpdateDependencies();
			break;
		}
		case M_MAKE_PROJECT:
		case M_BUILD_PROJECT:
		{
			fBuildingFile = 0;
			DoBuild(POSTBUILD_NOTHING);
			break;
		}
		case M_RUN_PROJECT:
		{
			DoBuild(POSTBUILD_RUN);
			break;
		}
		case M_RUN_IN_TERMINAL:
		{
			DoBuild(POSTBUILD_RUN_IN_TERMINAL);
			break;
		}
		case M_DEBUG_PROJECT:
		{
			if (!fProject->Debug())
			{
				BString errmsg = TR("Your project does not have debugging information compiled ");
				errmsg << TR("in and will need to be rebuilt to debug. Do you wish to rebuild and ")
					<< TR("run the debugger?");
				int32 result = ShowAlert("Debugging information needs to compiled into "
										"your project. This may take some time for large "
										"projects. Do you wish to rebuild and run "
										"the debugger?",
										"Rebuild","Cancel");
				if (result == 1)
					break;
				
				fProject->SetDebug(true);
				fProject->Save();
				fProject->ForceRebuild();
			}
			
			DoBuild(POSTBUILD_DEBUG);
			break;
		}
		case M_EXAMINING_FILE:
		{
			SourceFile *file;
			if (msg->FindPointer("file",(void**)&file) == B_OK)
			{
				BString out;
				out << TR("Examining ") << file->GetPath().GetFileName();
				fStatusBar->SetText(out.String());
			}
			break;
		}
		case M_BUILDING_FILE:
		{
			SourceFile *file;
			if (msg->FindPointer("sourcefile",(void**)&file) == B_OK)
			{
				SourceFileItem *item = fProjectList->ItemForFile(file);
				if (item)
				{
					item->SetDisplayState(SFITEM_BUILDING);
					fProjectList->InvalidateItem(fProjectList->IndexOf(item));
					
					BString out;
					
					int32 count,total;
					if (msg->FindInt32("count",&count) == B_OK &&
						msg->FindInt32("total",&total) == B_OK)
					{
						fBuildingFile = MAX(fBuildingFile, count);
						out << "(" << fBuildingFile << "/" << total << ") ";
					}
					
					out << TR("Building ") << item->Text();
					fStatusBar->SetText(out.String());
				}
			}
			break;
		}
		case M_BUILDING_DONE:
		{
			SourceFile *file;
			if (msg->FindPointer("sourcefile",(void**)&file) == B_OK)
			{
				SourceFileItem *item = fProjectList->ItemForFile(file);
				if (item)
				{
					item->SetDisplayState(SFITEM_NORMAL);
					fProjectList->InvalidateItem(fProjectList->IndexOf(item));
				}
			}
			break;
		}
		case M_LINKING_PROJECT:
		{
			fStatusBar->SetText(TR("Linking"));
			break;
		}
		case M_UPDATING_RESOURCES:
		{
			fStatusBar->SetText(TR("Updating Resources"));
			break;
		}
		case M_DOING_POSTBUILD:
		{
			fStatusBar->SetText(TR("Performing Post-build tasks"));
			break;
		}
		case M_BUILD_FAILURE:
		{
			SetMenuLock(false);
			
			// fall through
		}
		case M_BUILD_MESSAGES:
		case M_BUILD_WARNINGS:
		{
			if (!fErrorWindow)
			{
				BRect screen(BScreen().Frame());
				BRect r(screen);
				r.left = r.right / 4.0;
				r.right *= .75;
				r.top = r.bottom - 200;
				
				BDeskbar deskbar;
				if (deskbar.Location() == B_DESKBAR_BOTTOM)
					r.OffsetBy(0,-deskbar.Frame().Height());
				
				fErrorWindow = new ErrorWindow(r,this);
				fErrorWindow->Show();
			}
			else
			{
				if (!fErrorWindow->IsFront())
					fErrorWindow->Activate();
			}
			fStatusBar->SetText("");
			
			// Should this be an Unflatten or an Append?
			ErrorList *errorList = fProject->GetErrorList();
			errorList->Unflatten(*msg);
			fErrorWindow->PostMessage(msg);
			break;
		}
		case M_BUILD_SUCCESS:
		{
			SetMenuLock(false);
			fStatusBar->SetText("");
			break;
		}
		case M_ERRORWIN_CLOSED:
		{
			fErrorWindow = NULL;
			break;
		}
		case M_SYNC_MODULES:
		{
			#ifdef BUILD_CODE_LIBRARY
			thread_id syncID = spawn_thread(SyncThread,"module update thread",
												B_NORMAL_PRIORITY, this);
			if (syncID >= 0)
				resume_thread(syncID);
			#endif
			break;
		}
		case M_TOGGLE_DEBUG_MENU:
		{
			ToggleDebugMenu();
			break;
		}
		case M_DEBUG_DUMP_DEPENDENCIES:
		{
			DumpDependencies(fProject);
			break;
		}
		case M_DEBUG_DUMP_INCLUDES:
		{
			DumpIncludes(fProject);
			break;
		}
		default:
		{
			DWindow::MessageReceived(msg);
			break;
		}
	}
}
Exemplo n.º 28
0
BreakConditionConfigWindow::~BreakConditionConfigWindow()
{
	fTeam->RemoveListener(this);
	BMessenger(fTarget).SendMessage(MSG_BREAK_CONDITION_CONFIG_WINDOW_CLOSED);
}
Exemplo n.º 29
0
CharismaWindow::CharismaWindow(BPoint origin):
	BWindow(BRect(origin.x,origin.y,origin.x+200,origin.y+80),
		"Charisma", B_TITLED_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, 
		B_NOT_RESIZABLE|B_NOT_ZOOMABLE|B_WILL_ACCEPT_FIRST_CLICK)
{
	BRect nullrect(0,0,0,0),r;
	BMenu *m;
	BWindow *w;
	char buf[100];
	
	isminim=0;
	
	// le menu
	menubar=new BMenuBar(BRect(0,0,0,0),"menu bar");
	m=new BMenu("File");
	m->AddItem(new BMenuItem("About…",new BMessage(kMsg_About)));
	m->AddSeparatorItem();
	m->AddItem(new BMenuItem("Quit",new BMessage(B_QUIT_REQUESTED),'Q'));
	menubar->AddItem(m);
	m=new BMenu("Settings");
	m->AddItem(new BMenuItem("Select Web Directory…",new BMessage(kMsg_SelectDirectory)));
	m->AddSeparatorItem();
	m->AddItem(extcontrol_item=new BMenuItem("External Control",new BMessage(kMsg_ExternalControl)));
	m->AddItem(netposautoset_item=new BMenuItem("Net+ Autosettings",new BMessage(kMsg_NetposAutosettings)));
	m->AddSeparatorItem();
	m->AddItem(new BMenuItem("Clear Hits",new BMessage(kMsg_ClearHits)));
	menubar->AddItem(m);
	AddChild(menubar);

	// le fond gris
	r=Frame();
	setupview=new BView(
		BRect(0,menubar->Frame().bottom,r.Width(),r.Height()),
		"background",B_FOLLOW_NONE,B_WILL_DRAW);
	setupview->SetViewColor(0xDD,0xDD,0xDD);
	AddChild(setupview);
	
	// "Mode"
	m=new BPopUpMenu("");
	m->AddItem(new BMenuItem("Disabled",MSG));
	m->AddItem(new BMenuItem("Offline",MSG));
	m->AddItem(new BMenuItem("Online",MSG));
	modemenu=new BMenuField(
		BRect(10.0f,10.0f,20.0f,20.0f),"mode",
		"Mode:",
		m);
	BMenuField_resize(modemenu);
	setupview->AddChild(modemenu);

	// "Refresh"
	m=new BPopUpMenu("");
	m->AddItem(new BMenuItem("Dumb",MSG));
	m->AddSeparatorItem();
	m->AddItem(new BMenuItem("Always",MSG));
	m->AddItem(new BMenuItem("Once per session",MSG));
	m->AddSeparatorItem();
	m->AddItem(new BMenuItem("After 1 hour",MSG));
	m->AddItem(new BMenuItem("After 6 hours",MSG));
	m->AddItem(new BMenuItem("After 12 hours",MSG));
	m->AddSeparatorItem();
	m->AddItem(new BMenuItem("After 1 day",MSG));
	m->AddItem(new BMenuItem("After 2 days",MSG));
	m->AddItem(new BMenuItem("After 3 days",MSG));
	m->AddSeparatorItem();
	m->AddItem(new BMenuItem("After 1 week",MSG));
	m->AddItem(new BMenuItem("After 2 weeks",MSG));
	m->AddSeparatorItem();
	m->AddItem(new BMenuItem("After 1 month",MSG));
	m->AddItem(new BMenuItem("After 2 month",MSG));
	m->AddItem(new BMenuItem("After 6 month",MSG));
	m->AddSeparatorItem();
	m->AddItem(new BMenuItem("After 1 year",MSG));
	m->AddItem(new BMenuItem("After 2 years",MSG));
	m->AddSeparatorItem();
	m->AddItem(new BMenuItem("never",MSG));
	smartrefresh=new BMenuField(
		rectunder(modemenu),"refresh",
		"Refresh:",
		m);
	BMenuField_resize(smartrefresh);
	setupview->AddChild(smartrefresh);
	
	// "Hits"
	r.left=10.0f;
	r.top=smartrefresh->Frame().bottom+10.0f;
	r.right=r.left+setupview->StringWidth("hits: 99999");
	r.bottom=r.top+BView_textheight(setupview);
	hits=new BStringView(r,"hits","");
	setupview->AddChild(hits);

	if(!gregistered){
		sprintf(buf,"This copy is not registered");
		r.left=10.0f;
		r.top=hits->Frame().bottom+10.0f;
		r.right=r.left+setupview->StringWidth(buf);
		r.bottom=r.top+BView_textheight(setupview);
		setupview->AddChild(new BStringView(r,NULL,buf));
	}

	r=BView_childrenframe(setupview);
	setupview->ResizeTo(r.right+10,r.bottom+10);
	r=setupview->Frame();
	ResizeTo(r.right,r.bottom);
	
	hitcount=0;
	hitspulser=spawn_thread(pulsehits_,"StaminaWindow::pulsehits",
		B_NORMAL_PRIORITY,this);
	if(hitspulser<B_NO_ERROR)
		fatal(__FILE__,__LINE__,"spawn_thread failed");
	resume_thread(hitspulser);
	
	selectdirpanel=new BFilePanel(
		B_OPEN_PANEL,
		&BMessenger(this),
		NULL,
		B_DIRECTORY_NODE,
		false,
		new BMessage(kMsg_DirSelected));
	w=selectdirpanel->Window();
	w->Lock();
	w->SetTitle("Select Web Directory");
	selectdirpanel->SetButtonLabel(B_DEFAULT_BUTTON,"Select");
	r=w->FindView("cancel button")->Frame();
	r.right=r.left-15.0f;
	r.left=10.0f;
	r.bottom=r.top+BView_textheight(w->ChildAt(0));
	currentdir=new BStringView(r,"current","",B_FOLLOW_LEFT_RIGHT|B_FOLLOW_BOTTOM);
	w->ChildAt(0)->AddChild(currentdir);
	w->Unlock();
	
}
Exemplo n.º 30
0
void
TermApp::ReadyToRun()
{
	// Prevent opeing window when option -h is given.
	if (sUsageRequested)
		return;

	// Install a SIGCHLD signal handler, so that we will be notified, when
	// a shell exits. The handler itself will never be executed, since we block
	// the signal in all threads and handle it with sigwaitinfo() in the child
	// cleanup thread.
	struct sigaction action;
	action.sa_handler = (__sighandler_t)_SigChildHandler;
	sigemptyset(&action.sa_mask);
	action.sa_flags = 0;
	if (sigaction(SIGCHLD, &action, NULL) < 0) {
		fprintf(stderr, "sigaction() failed: %s\n", strerror(errno));
		// continue anyway
	}

	// block SIGCHLD and SIGUSR1 -- we send the latter to wake up the child
	// cleanup thread when quitting.
	sigset_t blockedSignals;
	sigemptyset(&blockedSignals);
	sigaddset(&blockedSignals, SIGCHLD);
	sigaddset(&blockedSignals, SIGUSR1);

	int error = pthread_sigmask(SIG_BLOCK, &blockedSignals, NULL);
	if (error != 0)
		fprintf(stderr, "pthread_sigmask() failed: %s\n", strerror(errno));

	// spawn the child cleanup thread
	fChildCleanupThread = spawn_thread(_ChildCleanupThreadEntry,
		"child cleanup", B_NORMAL_PRIORITY, this);
	if (fChildCleanupThread >= 0) {
		resume_thread(fChildCleanupThread);
	} else {
		fprintf(stderr, "Failed to start child cleanup thread: %s\n",
			strerror(fChildCleanupThread));
	}

	// init the mouse copy'n'paste clipboard
	gMouseClipboard = new BClipboard(MOUSE_CLIPBOARD_NAME, true);

	status_t status = _MakeTermWindow();

	// failed spawn, print stdout and open alert panel
	// TODO: This alert does never show up.
	if (status < B_OK) {
		BAlert* alert = new BAlert("alert",
			B_TRANSLATE("Terminal couldn't start the shell. Sorry."),
			B_TRANSLATE("OK"), NULL, NULL, B_WIDTH_FROM_LABEL,
			B_INFO_ALERT);
		alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
		alert->Go(NULL);
		PostMessage(B_QUIT_REQUESTED);
		return;
	}

	// using BScreen::Frame isn't enough
	if (fStartFullscreen)
		BMessenger(fTermWindow).SendMessage(FULLSCREEN);
}