Example #1
0
void
SyslogDaemon::AboutRequested()
{
	BPath path;
	find_directory(B_SYSTEM_LOG_DIRECTORY, &path);
	path.Append("syslog");

	BString name(B_TRANSLATE("Syslog Daemon"));
	BString message;
	snprintf(message.LockBuffer(512), 512,
		B_TRANSLATE("%s\n\nThis daemon is responsible for collecting "
			"all system messages and write them to the system-wide log "
			"at \"%s\".\n\n"), name.String(), path.Path());
	message.UnlockBuffer();

	BAlert *alert = new BAlert(name.String(), message.String(), B_TRANSLATE("OK"));
	BTextView *view = alert->TextView();
	BFont font;

	view->SetStylable(true);

	view->GetFont(&font);
	font.SetSize(21);
	font.SetFace(B_BOLD_FACE); 			
	view->SetFontAndColor(0, name.Length(), &font);

	alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
	alert->Go(NULL);
}
Example #2
0
void
PDFWriter::ToUnicode(const char *string, BString &unicode)
{
	int32 len = strlen(string);
	int32 srcLen = len, destLen = 255;
	int32 state = 0;
	char buffer[256];
	int32 srcStart = 0;
	int i = 0;

	unicode = "";
	if (len == 0) return;

	do {
		convert_from_utf8(B_UNICODE_CONVERSION, &string[srcStart], &srcLen,
			buffer, &destLen, &state);
		srcStart += srcLen;
		len -= srcLen;
		srcLen = len;

		char *b = unicode.LockBuffer(i + destLen);
		memcpy(&b[i], buffer, destLen);
		unicode.UnlockBuffer(i + destLen);
		i += destLen;
		destLen = 255;
	} while (len > 0);
}
Example #3
0
void
PriorityMenu::BuildMenu()
{
	BMenuItem* item;
	BMessage* message;
	long found = false;

	for (long index = 0; ; index++) {
		PriorityRec	*priority = &priorities[index];
		if (priority->priority < 0)
			break;
		if (!found && fPriority < priority->priority && fPriority >= 0) {
			priority = &customPriority;
			priority->priority = fPriority;
			index--;
		}
		message = new BMessage(SET_PRIORITY);
		message->AddInt32("priority", priority->priority);
		BString name;
		const size_t size = B_OS_NAME_LENGTH * 4;
		snprintf(name.LockBuffer(size), size,
			"%s [%d]", priority->name, (int)priority->priority);
		name.UnlockBuffer();
		item = new BMenuItem(name.String(), message);
		item->SetTarget(slayer->mainWindow);
		item->SetEnabled(fEnabled);
		if (fPriority == priority->priority)
			found = true, item->SetMarked(true);
		AddItem(item);
	}
}
Example #4
0
static void
CoerceFormatToAbbreviatedTimezone(BString& format)
{
    char* s = format.LockBuffer(format.Length());
    if (s == NULL)
        return;

    // replace a single 'z' with 'V'
    bool inQuote = false;
    bool lastWasZ = false;
    for (; *s != '\0'; ++s) {
        switch (*s) {
        case '\'':
            inQuote = !inQuote;
            break;
        case 'z':
            if (!inQuote && !lastWasZ && *(s+1) != 'z')
                *s = 'V';
            lastWasZ = true;
            continue;
        }
        lastWasZ = false;
    }
    format.UnlockBuffer(format.Length());
}
Example #5
0
static void
CoerceFormatTo12HourClock(BString& format)
{
    char* s = format.LockBuffer(format.Length());
    if (s == NULL)
        return;

    // change format to use h instead of H, k instead of K, and append an
    // am/pm marker
    bool inQuote = false;
    for (; *s != '\0'; ++s) {
        switch (*s) {
        case '\'':
            inQuote = !inQuote;
            break;
        case 'H':
            if (!inQuote)
                *s = 'h';
            break;
        case 'K':
            if (!inQuote)
                *s = 'k';
            break;
        }
    }
    format.UnlockBuffer(format.Length());

    format.Append(" a");
}
status_t FortuneAccess::GetFortune(BString *target)
{
	if(!target)
		return B_BAD_VALUE;
	
	if(fRefList.CountItems()<1)
		return B_ERROR;
	
	int32 index = int32(float(rand()) / RAND_MAX * fRefList.CountItems());
	
	entry_ref *ref = (entry_ref*)fRefList.ItemAt(index);
	
	BFile file(ref,B_READ_ONLY);
	if(file.InitCheck()!=B_OK)
		return file.InitCheck();
	
	fLastFile = ref->name;
	
	off_t size;
	file.GetSize(&size);
	
	if(size<1)
		return B_ERROR;
	
	BString data;
	
	char *buffer = data.LockBuffer(size + 10);
	file.Read(buffer,size);
	data.UnlockBuffer();
	buffer = NULL;
	
	// We can't depend on a .dat file, so calculate the number of entries manually
	int32 entrycount = 0;
	int32 entrystart = 0;
	
	do
	{
		entrystart = data.FindFirst("%\n",entrystart + 1);
		entrycount++;
	} while(entrystart>0);
	
	int32 entry = int32(float(rand()) / RAND_MAX * (entrycount-1));

	entrystart = 0;
	for(int32 i=0; i<entry; i++)
		entrystart = data.FindFirst("%\n",entrystart + 1);
		
	BString entrydata;
	entrydata = data.String() + entrystart + 2;
	int32 entrylength = entrydata.FindFirst("%\n");
	if(entrylength>0)
		entrydata.Truncate(entrylength);
	
	*target = entrydata;
	return B_OK;
}
Example #7
0
status_t
LinkReceiver::ReadString(BString &string, size_t* _length)
{
	int32 length = 0;
	status_t status = Read<int32>(&length);

	if (status < B_OK)
		return status;

	if (length < 0) {
		status = B_ERROR;
		goto err;
	}

	if (length > 0) {
		char* buffer = string.LockBuffer(length + 1);
		if (buffer == NULL) {
			status = B_NO_MEMORY;
			goto err;
		}

		status = Read(buffer, length);
		if (status < B_OK) {
			string.UnlockBuffer();
			goto err;
		}

		// make sure the string is null terminated
		buffer[length] = '\0';
		string.UnlockBuffer(length);
	} else
		string = "";

	if (_length)
		*_length = length;

	return B_OK;

err:
	fRecvPosition -= sizeof(int32);
		// rewind the transaction
	return status;
}
Example #8
0
static BString
size_string(double size)
{
	BString string;
	char* buffer = string.LockBuffer(256);
	string_for_size(size, buffer, 256);

	string.UnlockBuffer();
	return string;
}
Example #9
0
BString
BUrl::PreferredApplication() const
{
	BString appSignature;
	BMimeType mime(_UrlMimeType().String());
	mime.GetPreferredApp(appSignature.LockBuffer(B_MIME_TYPE_LENGTH));
	appSignature.UnlockBuffer();

	return BString(appSignature);
}
Example #10
0
static void
CoerceFormatTo24HourClock(BString& format)
{
    char* buffer = format.LockBuffer(format.Length());
    char* currentPos = buffer;
    if (currentPos == NULL)
        return;

    // change the format to use H instead of h, K instead of k, and determine
    // and remove the am/pm marker (including leading whitespace)
    bool inQuote = false;
    bool lastWasWhitespace = false;
    uint32 ch;
    const char* amPmStartPos = NULL;
    const char* amPmEndPos = NULL;
    const char* lastWhitespaceStart = NULL;
    for (char* previousPos = currentPos; (ch = BUnicodeChar::FromUTF8(
            (const char**)&currentPos)) != 0; previousPos = currentPos) {
        switch (ch) {
        case '\'':
            inQuote = !inQuote;
            break;
        case 'h':
            if (!inQuote)
                *previousPos = 'H';
            break;
        case 'k':
            if (!inQuote)
                *previousPos = 'K';
            break;
        case 'a':
            if (!inQuote) {
                if (lastWasWhitespace)
                    amPmStartPos = lastWhitespaceStart;
                else
                    amPmStartPos = previousPos;
                amPmEndPos = currentPos;
            }
            break;
        default:
            if (!inQuote && BUnicodeChar::IsWhitespace(ch)) {
                if (!lastWasWhitespace) {
                    lastWhitespaceStart = previousPos;
                    lastWasWhitespace = true;
                }
                continue;
            }
        }
        lastWasWhitespace = false;
    }

    format.UnlockBuffer(format.Length());
    if (amPmStartPos != NULL && amPmEndPos > amPmStartPos)
        format.Remove(amPmStartPos - buffer, amPmEndPos - amPmStartPos);
}
void
DataTranslationsApplication::_InstallError(const char* name, status_t status)
{
	BString text;
	snprintf(text.LockBuffer(512), 512,
			B_TRANSLATE("Could not install %s:\n%s"), name, strerror(status));
	text.UnlockBuffer();
	BAlert* alert = new BAlert(B_TRANSLATE("DataTranslations - Error"),
		text.String(), B_TRANSLATE("OK"));
	alert->Go();
}
static void
refresh_rate_to_string(float refresh, BString &string,
	bool appendUnit = true, bool alwaysWithFraction = false)
{
	snprintf(string.LockBuffer(32), 32, "%.*g", refresh >= 100.0 ? 4 : 3,
		refresh);
	string.UnlockBuffer();

	if (appendUnit)
		string << " " << B_TRANSLATE("Hz");
}
Example #13
0
void
PDFWriter::ToPDFUnicode(const char *string, BString &unicode)
{
	// PDFlib requires BOM at begin and two 0 at end of string
	BString s;
	ToUnicode(string, s);
	unicode << "\xfe\xff";
	int32 len = s.Length()+2;
	char* buf = unicode.LockBuffer(len + 2);
		// reserve space for two additional '\0'
	memcpy(&buf[2], s.String(), s.Length());
	buf[len] = buf[len+1] = 0;
	unicode.UnlockBuffer(len + 2);
}
Example #14
0
	void _NormalizePath(const BString& path, BString& _normalizedPath)
	{
		BString normalizedPath;
		char* buffer = normalizedPath.LockBuffer(path.Length());
		int32 outIndex = 0;
		const char* remaining = path.String();

		while (*remaining != '\0') {
			// collapse repeated slashes
			if (*remaining == '/') {
				buffer[outIndex++] = '/';
				remaining++;
				while (*remaining == '/')
					remaining++;
			}

			if (*remaining == '\0') {
				// remove trailing slash (unless it's "/" only)
				if (outIndex > 1)
					outIndex--;
				break;
			}

			// skip "." components
			if (*remaining == '.') {
				if (remaining[1] == '\0')
					break;

				if (remaining[1] == '/') {
					remaining += 2;
					while (*remaining == '/')
						remaining++;
					continue;
				}
			}

			// copy path component
			while (*remaining != '\0' && *remaining != '/')
				buffer[outIndex++] = *(remaining++);
		}

		// If the path didn't change, use the original path (BString's copy on
		// write mechanism) rather than the new string.
		if (outIndex == path.Length()) {
			_normalizedPath = path;
		} else {
			normalizedPath.UnlockBuffer(outIndex);
			_normalizedPath = normalizedPath;
		}
	}
Example #15
0
status_t 
PoorManWindow::SaveConsole(BMessage* message, bool selection)
{
	entry_ref	ref;
	const char* name;
	BPath		path;
	BEntry		entry;
	status_t	err = B_OK;
	FILE*		f;
	
	err = message->FindRef("directory", &ref);
	if (err != B_OK)
		return err;
	
	err = message->FindString("name", &name);
	if (err != B_OK)
		return err;
	
	err = entry.SetTo(&ref);
	if (err != B_OK)
		return err;
	
	entry.GetPath(&path);
	path.Append(name);
	
	if (!(f = fopen(path.Path(), "w")))
		return B_ERROR;
	
	if (!selection) {
		// write the data to the file
		err = fwrite(fLoggingView->Text(), 1, fLoggingView->TextLength(), f);
	} else {
		// find the selected text and write it to a file
		int32 start = 0, end = 0;
		fLoggingView->GetSelection(&start, &end);

		BString buffer;
		char * buffData = buffer.LockBuffer(end - start + 1);
		// copy the selected text from the TextView to the buffer
		fLoggingView->GetText(start, end - start, buffData);
		buffer.UnlockBuffer(end - start + 1);

		err = fwrite(buffer.String(), 1, end - start + 1, f);
	}

	fclose(f);

	return err;
}
Example #16
0
_EXPORT status_t
extract_from_header(const BString& header, const BString& field,
	BString& target)
{
	int32 headerLength = header.Length();
	int32 fieldEndPos = 0;
	while (true) {
		int32 pos = header.IFindFirst(field, fieldEndPos);
		if (pos < 0)
			return B_BAD_VALUE;
		fieldEndPos = pos + field.Length();
		
		if (pos != 0 && header.ByteAt(pos - 1) != '\n')
			continue;
		if (header.ByteAt(fieldEndPos) == ':')
			break;
	}
	fieldEndPos++;

	int32 crPos = fieldEndPos;
	while (true) {
		fieldEndPos = crPos;
		crPos = header.FindFirst('\n', crPos);
		if (crPos < 0)
			crPos = headerLength;
		BString temp;
		header.CopyInto(temp, fieldEndPos, crPos - fieldEndPos);
		if (header.ByteAt(crPos - 1) == '\r') {
			temp.Truncate(temp.Length() - 1);
			temp += " ";
		}
		target += temp;
		crPos++;
		if (crPos >= headerLength)
			break;
		char nextByte = header.ByteAt(crPos);
		if (nextByte != ' ' && nextByte != '\t')
			break;
		crPos++;
	}

	size_t bufferSize = target.Length();
	char* buffer = target.LockBuffer(bufferSize);
	size_t length = rfc2047_to_utf8(&buffer, &bufferSize, bufferSize);
	target.UnlockBuffer(length);

	return B_OK;
}
Example #17
0
		// Convert the word from UTF-8 to the desired character set.  The
		// converted version also includes the escape codes to return to ASCII
		// mode, if relevant.  Also note if it uses unprintable characters,
		// which means it will need that special encoding treatment later.
		void ConvertWordToCharset (uint32 charset) {
			int32 state = 0;
			int32 originalLength = originalWord.Length();
			int32 convertedLength = originalLength * 5 + 1;
			char *convertedBuffer = convertedWord.LockBuffer (convertedLength);
			mail_convert_from_utf8 (charset, originalWord.String(),
				&originalLength, convertedBuffer, &convertedLength, &state);
			for (int i = 0; i < convertedLength; i++) {
				if ((convertedBuffer[i] & (1 << 7)) ||
					(convertedBuffer[i] >= 0 && convertedBuffer[i] < 32)) {
					needsEncoding = true;
					break;
				}
			}
			convertedWord.UnlockBuffer (convertedLength);
		};
void DeskbarPulseView::Remove() {
	// Remove ourselves from the deskbar by name
	BDeskbar *deskbar = new BDeskbar();
	status_t err = deskbar->RemoveItem("DeskbarPulseView");
	if (err != B_OK) {
		BString str;
		snprintf(str.LockBuffer(512), 512,
			B_TRANSLATE("Removing from Deskbar failed.\n%s"), strerror(err));
		str.UnlockBuffer();
		BAlert *alert = new BAlert(B_TRANSLATE("Info"), str.String(),
			B_TRANSLATE("OK"));
		alert->SetShortcut(0, B_ESCAPE);
		alert->Go(NULL);
	}
	delete deskbar;
}
Example #19
0
uint32 DbHandler::CreateDatabase(BString& name, const BString& table)
{
	int err = 0;
	
	err = sqlite3_open(name.LockBuffer(name.Length() + 1), &db);
	name.UnlockBuffer();
	
	if(err) {
		return err;
	}
	else {
		err = AddTable(table);	
	}
	this->db_name = name;
	return 0;
}
Example #20
0
void 
Model::GetPreferredAppForBrokenSymLink(BString &result)
{
	if (!IsSymLink() || LinkTo()) {
		result = "";
		return;
	}

	BModelOpener opener(this);
	BNodeInfo info(fNode);		
	status_t error = info.GetPreferredApp(result.LockBuffer(B_MIME_TYPE_LENGTH));
	result.UnlockBuffer();

	if (error != B_OK)
		// Tracker will have to do
		result = kTrackerSignature;
}
Example #21
0
_EXPORT void
trim_white_space(BString &string)
{
	int32 i;
	int32 length = string.Length();
	char *buffer = string.LockBuffer(length + 1);

	while (length > 0 && isspace(buffer[length - 1]))
		length--;
	buffer[length] = '\0';

	for (i = 0; buffer[i] && isspace(buffer[i]); i++) {}
	if (i != 0) {
		length -= i;
		memmove(buffer,buffer + i,length + 1);
	}
	string.UnlockBuffer(length);
}
Example #22
0
void
parseQuotedChars(BString& stringToParse)
{
	char* in = stringToParse.LockBuffer(0);
	char* out = in;
	int newLength = 0;
	bool quoted = false;

	while (*in != 0 || quoted) {
		if (quoted) {
			if (*in == 'n')
				*out = '\n';
			else if (*in == 't')
				*out = '\t';
			else if (*in == '"')
				*out = '"';
			else if (*in == 'x') {
				// Parse the 2-digit hex integer that follows
				unsigned int hexchar = strtoul(in + 1, NULL, 16);
				*out = hexchar;
				// skip the number
				in += 2;
			} else {
				// dump quote from unknown quoting-sequence:
				*out = *in ;
			}
			quoted = false;
			out++;
			newLength++;
		} else {
			quoted = (*in == '\\');
			if (!quoted) {
				*out = *in;
				out++;
				newLength++;
			}
		}
		in++;
	}
	*out = '\0';
	stringToParse.UnlockBuffer();
}
Preferences::~Preferences()
{
	if (fSavePreferences) {
		BFile file;
		status_t set = B_ERROR;
		if (fSettingsFile)
			file.SetTo(fSettingsFile, B_READ_WRITE | B_CREATE_FILE | B_ERASE_FILE);
		else {
			BPath prefpath;
			if (find_directory(B_USER_SETTINGS_DIRECTORY, &prefpath, true) == B_OK) {
				BDirectory prefdir(prefpath.Path());
				set = prefdir.CreateFile(fName, &file, false);
			}
		}

		if (file.InitCheck () == B_OK) {
			Flatten(&file);
			if (fSignature) {
				file.WriteAttr("BEOS:TYPE", B_MIME_STRING_TYPE, 0, fSignature,
					strlen(fSignature) + 1);
			}
		} else {
			// implement saving somewhere else!
			BString error;
			snprintf(error.LockBuffer(256), 256,
				B_TRANSLATE("Your setting file could not be saved!\n(%s)"),
				strerror(file.InitCheck()));
			error.UnlockBuffer();
			BAlert *alert = new BAlert(B_TRANSLATE("Error saving file"),
				error.String(), B_TRANSLATE("Damned!"), NULL, NULL,
				B_WIDTH_AS_USUAL, B_STOP_ALERT);
			alert->SetShortcut(0, B_ESCAPE);

			alert->Go();
		}
	}
	delete fSettingsFile;
	free(fName);
	free(fSignature);
}
Example #24
0
bool
LoadInDeskbar()
{
	PulseApp *pulseapp = (PulseApp *)be_app;
	BDeskbar *deskbar = new BDeskbar();
	// Don't allow two copies in the Deskbar at once
	if (deskbar->HasItem("DeskbarPulseView")) {
		delete deskbar;
		return false;
	}

	// Must be 16 pixels high, the width is retrieved from the Prefs class
	int width = pulseapp->prefs->deskbar_icon_width;
	int min_width = GetMinimumViewWidth();
	if (width < min_width) {
		pulseapp->prefs->deskbar_icon_width = min_width;
		width = min_width;
	}

	float height = deskbar->MaxItemHeight();
	BRect rect(0, 0, width - 1, height - 1);
	DeskbarPulseView *replicant = new DeskbarPulseView(rect);
	status_t err = deskbar->AddItem(replicant);
	delete replicant;
	delete deskbar;
	if (err != B_OK) {
		BString message;
		snprintf(message.LockBuffer(512), 512,
			B_TRANSLATE("Installing in Deskbar failed\n%s"), strerror(err));
		message.UnlockBuffer();
		BAlert *alert = new BAlert(B_TRANSLATE("Error"),
			message.String(), B_TRANSLATE("OK"));
		alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
		alert->Go(NULL);
		return false;
	}

	return true;
}
void
DataTranslationsWindow::_ShowInfoAlert(int32 id)
{
	const char* name = NULL;
	const char* info = NULL;
	BPath path;
	int32 version = 0;
	_GetTranslatorInfo(id, name, info, version, path);

	BString message;
	// Convert the version number into a readable format
	snprintf(message.LockBuffer(2048), 2048,
		B_TRANSLATE("Name: %s \nVersion: %ld.%ld.%ld\n\n"
			"Info:\n%s\n\nPath:\n%s\n"),
		name, B_TRANSLATION_MAJOR_VERSION(version),
		B_TRANSLATION_MINOR_VERSION(version),
		B_TRANSLATION_REVISION_VERSION(version), info, path.Path());
	message.UnlockBuffer();

	BAlert* alert = new BAlert(B_TRANSLATE("Info"), message.String(),
		B_TRANSLATE("OK"));
	BTextView* view = alert->TextView();
	BFont font;

	view->SetStylable(true);

	view->GetFont(&font);
	font.SetFace(B_BOLD_FACE);

	const char* labels[] = { B_TRANSLATE("Name:"), B_TRANSLATE("Version:"),
		B_TRANSLATE("Info:"), B_TRANSLATE("Path:"), NULL };
	for (int32 i = 0; labels[i]; i++) {
		int32 index = message.FindFirst(labels[i]);
		view->SetFontAndColor(index, index + strlen(labels[i]), &font);
	}

	alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
	alert->Go();
}
//!	Replaces tabs and other white space with spaces, compresses spaces.
void
sanitize_white_space(BString& string)
{
	char* buffer = string.LockBuffer(string.Length() + 1);
	if (buffer == NULL)
		return;

	int32 count = string.Length();
	int32 spaces = 0;
	for (int32 i = 0; buffer[i] != '\0'; i++, count--) {
		if (isspace(buffer[i])) {
			buffer[i] = ' ';
			spaces++;
		} else {
			if (spaces > 1)
				memmove(buffer + i + 1 - spaces, buffer + i, count + 1);
			spaces = 0;
		}
	}

	string.UnlockBuffer();
}
Example #27
0
/* be_joy_init:
 *  Initializes BeOS joystick driver.
 */
extern "C" int be_joy_init(void)
{
   const char *device_config;
   char device_name[B_OS_NAME_LENGTH + 1];
   static char desc[30];
   static char name_x[10];
   static char name_y[10];
   static char name_stick[] = "stick";
   static char name_hat[] = "hat";
   static char name_throttle[] = "throttle";
   static char name_hat_lr[] = "left/right";
   static char name_hat_ud[] = "up/down";
   static char *name_b[] =
   {"B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8"};
   int32 i, j, stick;
   BString *temp;
   char *name;
   
   temp = new BString;
   be_joy = new BJoystick;
   num_devices = be_joy->CountDevices();
   
   /* no joysticks available */
   if (num_devices == 0) {
      goto cleanup;
   }
   
   /* Scans if the joystick_device config variable is set */
   device_config = get_config_string("joystick", "joystick_device", "");
   
   /* Let's try to open selected device */
   if ((device_config[0] == '\0') || (be_joy->Open(device_config) < 0)) {
      /* ok, let's try to open first available device */
      if (be_joy->GetDeviceName(0, device_name) != B_OK) {
         goto cleanup;
      }
      if (be_joy->Open(device_name) == B_ERROR) {
         goto cleanup;
      }
   }
   be_joy->GetControllerName(temp);
   name = temp->LockBuffer(0);
   _al_sane_strncpy(desc, name, sizeof(desc));
   temp->UnlockBuffer();
   joystick_beos.desc = desc;

   num_axes = be_joy->CountAxes();
   num_hats = be_joy->CountHats();
   num_buttons = be_joy->CountButtons();
   if (num_axes) {
      axis_value = (int16 *)malloc(sizeof(int16) * num_axes);
      hat_value = (int8 *)malloc(sizeof(int8) * num_axes);
   }
   
   num_joysticks = be_joy->CountSticks();
   for (i = 0; i < num_joysticks; i++) {
      joy[i].flags = JOYFLAG_DIGITAL | JOYFLAG_ANALOGUE;
      
      stick = 0;
      if (num_axes >= 2) {
         joy[i].stick[0].flags = JOYFLAG_DIGITAL | JOYFLAG_ANALOGUE | JOYFLAG_SIGNED;
         joy[i].stick[0].num_axis = 2;
         joy[i].stick[0].name = name_stick;
         be_joy->GetAxisNameAt(0, temp);
         name = temp->LockBuffer(0);
         _al_sane_strncpy(name_x, name, sizeof(name_x));
         temp->UnlockBuffer();
         joy[i].stick[0].axis[0].name = name_x;
         be_joy->GetAxisNameAt(1, temp);
         name = temp->LockBuffer(0);
         _al_sane_strncpy(name_y, name, sizeof(name_y));
         temp->UnlockBuffer();
         joy[i].stick[0].axis[1].name = name_y;
         
         stick++;
         for (j = 2; j < num_axes; j++) {
            joy[i].stick[stick].flags = JOYFLAG_DIGITAL | JOYFLAG_ANALOGUE | JOYFLAG_UNSIGNED;
            joy[i].stick[stick].num_axis = 1;
            joy[i].stick[stick].axis[0].name = "";
            joy[i].stick[stick].name = name_throttle;
            stick++;
         }
         for (j = 0; j < num_hats; j++) {
            joy[i].stick[stick].flags = JOYFLAG_DIGITAL | JOYFLAG_SIGNED;
            joy[i].stick[stick].num_axis = 2;
            joy[i].stick[stick].axis[0].name = name_hat_lr;
            joy[i].stick[stick].axis[1].name = name_hat_ud;
            joy[i].stick[stick].name = name_hat;
            stick++;
         }
      }
      joy[i].num_sticks = stick;
      joy[i].num_buttons = num_buttons;
      
      for (j = 0; j < num_buttons; j++)
         joy[i].button[j].name = name_b[j];
   }
   
   delete temp;
   be_joy_poll();
   return 0;
   
   cleanup: {
       delete temp;
       delete be_joy;
       return -1;
   } 
}
Example #28
0
status_t
RunPopUpMenu(BPoint where, BString &header, BString &fileName, 
	CLanguageInterface *languageInterface)
{
	status_t err;
	BPath path;
	BDirectory dir;
	err = GetSettingsDir(dir, path);
	err = B_ERROR;
	BPopUpMenu *menu = BuildPopUp(dir);
	if (menu == NULL)
		return B_ERROR;
	
	BMenuItem *item = menu->Go(where, false, true);
	//if (item && item->Message())
	//	item->Message()->PrintToStream();

	switch ((item && item->Message()) ? item->Message()->what : 0)
	{
		case 'head':
		{
			if (item->Message()->FindString("template", &header) < B_OK)
				break;
			BString tmp;
			time_t now = time(NULL);
			struct tm *tim = localtime(&now);
			// date
			char *p;
			p = tmp.LockBuffer(100);
			memset(p, 0, 100);
			strftime(p, 100, "%Y-%m-%d", tim);
			tmp.UnlockBuffer();
			header.ReplaceAll("%DATE%", tmp.String());
			tmp.Truncate(0);
			
			p = tmp.LockBuffer(100);
			memset(p, 0, 100);
			strftime(p, 100, "%T", tim);
			tmp.UnlockBuffer();
			header.ReplaceAll("%TIME%", tmp.String());
			tmp.Truncate(0);

			// year
			p = tmp.LockBuffer(10);
			memset(p, 0, 10);
			strftime(p, 10, "%Y", tim);
			tmp.UnlockBuffer();
			header.ReplaceAll("%YEAR%", tmp.String());
			tmp.Truncate(0);

			// fetch from query on META:email==** ?
			p = tmp.LockBuffer(B_PATH_NAME_LENGTH);
			memset(p, 0, B_PATH_NAME_LENGTH);
			err = dir.ReadAttr("pe:author_people", B_STRING_TYPE, 0LL, p, 
				B_PATH_NAME_LENGTH);
			tmp.UnlockBuffer();
			//printf("ppl:%s\n", tmp.String());
			BNode people;
			if (err > 0)
				people.SetTo(tmp.String());
			tmp.Truncate(0);
			
			BString attr;

			static struct {
				const char *tmplName;
				const char *attrName;
			} attrMap[] = {
				{ "%AUTHOR%", "META:name" },
				{ "%AUTHORMAIL%", "META:email" },
				{ "%COMPANY%", "META:company" },
				{ "%AUTHORURL%", "META:url" },
				{ NULL, NULL }
			};
			int i;

			for (i = 0; attrMap[i].tmplName; i++)
			{
				p = attr.LockBuffer(256);
				memset(p, 0, 256);
				err = people.ReadAttr(attrMap[i].attrName, B_ANY_TYPE, 
					0LL, p, 256);
				//printf("ReadAttr: %d, %s\n", err, attr.String());
				attr.UnlockBuffer();

				tmp << attr;
				header.ReplaceAll(attrMap[i].tmplName, tmp.String());
				tmp.Truncate(0);
				attr.Truncate(0);
			}

			BString fileNameNoExt(fileName);
			if (fileNameNoExt.FindLast('.') > -1)
				fileNameNoExt.Truncate(fileNameNoExt.FindLast('.'));
			header.ReplaceAll("%FILENAMENOEXT%", fileNameNoExt.String());
			header.ReplaceAll("%FILENAME%", fileName.String());
			/*
			tmp << "Haiku";
			header.ReplaceAll("%PROJECT%", tmp.String());
			tmp.Truncate(0);
			*/

			// better values for C++
			BString language("C/C++");
			BString commentLineStart("/*");
			BString commentLineEnd("");
			BString commentBlockStart("/*");
			BString commentBlockCont(" *");
			BString commentBlockLazy("");
			BString commentBlockLineEnd("");
			BString commentBlockEnd(" */");
			if (languageInterface)
			{
				// if not C++
				if (language != languageInterface->Name())
				{
					language = languageInterface->Name();
					commentLineStart = languageInterface->LineCommentStart();
					commentLineEnd = languageInterface->LineCommentEnd();
					// I'd miss a CommentCanSpanLines()
					// let's assume line end means can span
					if (commentLineEnd.Length())
					{
						commentBlockStart = commentLineStart;
						commentBlockCont = "";
						commentBlockLazy = "";
						commentBlockLineEnd = "";
						commentBlockEnd = commentLineEnd;
					}
					else
					{
						commentBlockStart = commentLineStart;
						commentBlockCont = commentLineStart;
						commentBlockLazy = commentLineStart;
						commentBlockLineEnd = commentLineEnd;
						commentBlockEnd = commentLineStart;
					}
					/*
					printf("LANG:'%s' CS:'%s' CE:'%s'\n", 
						language.String(), 
						commentLineStart.String(), 
						commentLineEnd.String());
					*/
				}
			}
			// comment start
			header.ReplaceAll("%COMMS%", commentBlockStart.String());
			// comment cont'd
			header.ReplaceAll("%COMMC%", commentBlockCont.String());
			// comment cont'd lazy (blank if possible)
			header.ReplaceAll("%COMML%", commentBlockLazy.String());
			// comment end
			header.ReplaceAll("%COMME%", commentBlockEnd.String());
			// comment line end
			commentBlockLineEnd << "\n";
			header.ReplaceAll("\n", commentBlockLineEnd.String());


			err = B_OK;
			break;
		}
		case 'optf':
		{
			const char *args[] = {path.Path(), NULL};
			err = be_roster->Launch(sTrackerSig, 1, (char **)args);
			//printf("err %s\n", strerror(err));
			err = B_CANCELED;
			break;
		}
		case 'seta':
		{
			MimeRefFilter filter("application/x-person");
			BPath path;
			entry_ref people;

			if (find_directory(B_USER_DIRECTORY, &path) == B_OK)
			{
				path.Append("people");
				get_ref_for_path(path.Path(), &people);
			}

			BFilePanel *panel;
			panel = new BFilePanel(B_OPEN_PANEL, NULL, &people,
				B_FILE_NODE, false, NULL, &filter);
			// trick to synchronously use BFilePanel
			PanelHandler *handler = new PanelHandler;
			if (panel->Window()->Lock())
			{
				panel->Window()->AddHandler(handler);
				panel->Window()->Unlock();
			}
			panel->SetTarget(BMessenger(handler));
			panel->Show();
			if (handler->Wait() < B_OK)
				break;
			if (!handler->Message())
				break;
			if (handler->Message()->what == B_CANCEL)
				break;
			entry_ref ref;
			//panel->Message()->PrintToStream();
			if (panel->GetNextSelectedRef(&ref) == B_OK)
			{
				//printf("ref:%s\n", ref.name);
				path.SetTo(&ref);
				dir.WriteAttr("pe:author_people", B_STRING_TYPE, 0LL, 
					path.Path(), strlen(path.Path()));
			}
			delete panel;
			delete handler;
			err = B_CANCELED;
			break;
		}
		case B_ABOUT_REQUESTED:
		{
			BString tmpPath("/tmp/Pe-HeaderHeader-About-");
			tmpPath << system_time() << "-" << getpid() << ".txt";
			entry_ref ref;
			get_ref_for_path(tmpPath.String(), &ref);
			{
				BFile f(&ref, B_CREATE_FILE | B_WRITE_ONLY);
				err = f.InitCheck();
				if (err < 0)
					break;
				f.Write(sAboutText, strlen(sAboutText));
				f.SetPermissions(0444);
			}
			BMessage msg(B_REFS_RECEIVED);
			msg.AddRef("refs", &ref);
			err = be_app_messenger.SendMessage(&msg);
			err = B_CANCELED;
			break;
		}
		case 0:
			err = B_CANCELED;
			break;
		default:
			break;
	}
	delete menu;
	return err;
}
Example #29
0
BPopUpMenu *
BuildPopUp(BDirectory &dir)
{
	BPopUpMenu *menu = new BPopUpMenu("menu", false);
	//BMenuItem *item;
	//BMessage *msg;
	//status_t err;

	//menu->SetFont(be_plain_font);

	AddTemplateItem(menu, B_UTF8_COPYRIGHT " Haiku", 
		sHaikuHeaderTemplate);

/*
	AddTemplateItem(menu, B_UTF8_COPYRIGHT " Haiku (Add me)", 
		sHaikuAddMeHeaderTemplate, sHaikuAddMeHeaderMatch);
*/

	AddTemplateItem(menu, B_UTF8_COPYRIGHT " Me (Haiku)", 
		sHaikuMeHeaderTemplate);

	AddTemplateItem(menu, B_UTF8_COPYRIGHT " Me (Haiku) + Rights Reserved", 
		sHaikuMeRightsHeaderTemplate);

	AddTemplateItem(menu, "Id + " B_UTF8_COPYRIGHT "Me + MIT + Created", 
		sIdMeMITCreatedHeaderTemplate);

	AddTemplateItem(menu, "Id + " B_UTF8_COPYRIGHT "Me + Full MIT + Created", 
		sIdMeFullMITCreatedHeaderTemplate);

	AddTemplateItem(menu, "Id + " B_UTF8_COPYRIGHT "Me + Full MIT Revised + Created", 
		sIdMeFullMITRevisedCreatedHeaderTemplate);

	if (dir.InitCheck() < B_OK)
		return menu;

	entry_ref ref;
	while (dir.GetNextRef(&ref) == B_OK)
	{
		BFile file(&ref, B_READ_ONLY);
		if (file.InitCheck() < B_OK)
			continue;
		BString str;
		char *p = str.LockBuffer(1024);
		memset(p, 0, 1024);
		if (file.Read(p, 1024) <= 0)
			continue;
		str.UnlockBuffer();
		
		AddTemplateItem(menu, ref.name, str.String());
	}

	menu->AddSeparatorItem();
	menu->AddItem(new BMenuItem("Open template folder"B_UTF8_ELLIPSIS, 
		new BMessage('optf')));
	menu->AddItem(new BMenuItem("Set author"B_UTF8_ELLIPSIS, 
		new BMessage('seta')));
	menu->AddItem(new BMenuItem("About"B_UTF8_ELLIPSIS, 
		new BMessage(B_ABOUT_REQUESTED)));
	return menu;
}
Example #30
0
void
UrlWrapper::RefsReceived(BMessage* msg)
{
	char buff[B_PATH_NAME_LENGTH];
	int32 index = 0;
	entry_ref ref;
	char* args[] = { const_cast<char*>("urlwrapper"), buff, NULL };
	status_t err;

	while (msg->FindRef("refs", index++, &ref) == B_OK) {
		BFile f(&ref, B_READ_ONLY);
		BNodeInfo ni(&f);
		BString mimetype;
		BString extension(ref.name);
		extension.Remove(0, extension.FindLast('.') + 1);
		if (f.InitCheck() == B_OK && ni.InitCheck() == B_OK) {
			ni.GetType(mimetype.LockBuffer(B_MIME_TYPE_LENGTH));
			mimetype.UnlockBuffer();

			// Internet Explorer Shortcut
			if (mimetype == "text/x-url" || extension == "url") {
				// http://filext.com/file-extension/URL
				// http://www.cyanwerks.com/file-format-url.html
				off_t size;
				if (f.GetSize(&size) < B_OK)
					continue;
				BString contents;
				BString url;
				if (f.ReadAt(0LL, contents.LockBuffer(size), size) < B_OK)
					continue;
				contents.UnlockBuffer();
				while (contents.Length()) {
					BString line;
					int32 cr = contents.FindFirst('\n');
					if (cr < 0)
						cr = contents.Length();
					//contents.MoveInto(line, 0, cr);
					contents.CopyInto(line, 0, cr);
					contents.Remove(0, cr+1);
					line.RemoveAll("\r");
					if (!line.Length())
						continue;
					if (!line.ICompare("URL=", 4)) {
						line.MoveInto(url, 4, line.Length());
						break;
					}
				}
				if (url.Length()) {
					BPrivate::Support::BUrl u(url.String());
					args[1] = (char*)u.String();
					mimetype = kURLHandlerSigBase;
					mimetype += u.Proto();
					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);
					continue;
				}
			}
			if (mimetype == "text/x-webloc" || extension == "webloc") {
				// OSX url shortcuts
				// XML file + resource fork
				off_t size;
				if (f.GetSize(&size) < B_OK)
					continue;
				BString contents;
				BString url;
				if (f.ReadAt(0LL, contents.LockBuffer(size), size) < B_OK)
					continue;
				contents.UnlockBuffer();
				int state = 0;
				while (contents.Length()) {
					BString line;
					int32 cr = contents.FindFirst('\n');
					if (cr < 0)
						cr = contents.Length();
					contents.CopyInto(line, 0, cr);
					contents.Remove(0, cr+1);
					line.RemoveAll("\r");
					if (!line.Length())
						continue;
					int32 s, e;
					switch (state) {
						case 0:
							if (!line.ICompare("<?xml", 5))
								state = 1;
							break;
						case 1:
							if (!line.ICompare("<plist", 6))
								state = 2;
							break;
						case 2:
							if (!line.ICompare("<dict>", 6))
								state = 3;
							break;
						case 3:
							if (line.IFindFirst("<key>URL</key>") > -1)
								state = 4;
							break;
						case 4:
							if ((s = line.IFindFirst("<string>")) > -1
								&& (e = line.IFindFirst("</string>")) > s) {
								state = 5;
								s += 8;
								line.MoveInto(url, s, e - s);
								break;
							} else
								state = 3;
							break;
						default:
							break;
					}
					if (state == 5) {
						break;
					}
				}
				if (url.Length()) {
					BPrivate::Support::BUrl u(url.String());
					args[1] = (char*)u.String();
					mimetype = kURLHandlerSigBase;
					mimetype += u.Proto();
					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);
					continue;
				}
			}

			// NetPositive Bookmark or any file with a META:url attribute
			if (f.ReadAttr("META:url", B_STRING_TYPE, 0LL, buff,
				B_PATH_NAME_LENGTH) > 0) {
				BPrivate::Support::BUrl u(buff);
				args[1] = (char*)u.String();
				mimetype = kURLHandlerSigBase;
				mimetype += u.Proto();
				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);
				continue;
			}
		}
	}
}