void DispatchMessage(BMessage *msg, BHandler *target) { switch(msg->what) { case M_TEMPLATE_SAVE: { EditView *ev; entry_ref dir; const char *filespec; int32 DocID; if ((msg->FindInt32("DocID", &DocID) == B_OK) && (msg->FindRef("directory", &dir) == B_OK) && (msg->FindString("name", &filespec) == B_OK) && (ev = FindEVByDocID(DocID))) { BEntry entry(&dir, true); BPath path; entry.GetPath(&path); path.Append(filespec); const char *filename = path.Path(); if (ev->Save(filename)) { (new BAlert("", "The save operation failed: the file could not be written to the destination.", "Damned!"))->Go(); } } else { (new BAlert("", "The save operation failed.", "Damned!"))->Go(); } if (TemplatePanel) { delete TemplatePanel; TemplatePanel = NULL; } Quit(); } break; case M_TEMPLATE_LOAD: { int i; uint32 type; int32 count; entry_ref ref; EditView *ev = NULL, *firstev = NULL; LockWindow(); msg->GetInfo("refs", &type, &count); for(i=0;i<count;i++) { if (msg->FindRef("refs", i, &ref) == B_OK) { BEntry entry(&ref, true); BPath path; entry.GetPath(&path); // open the template if (ev = CreateEditView((char *)path.Path())) { // take away the template filename: make the file untitled ev->MakeUntitled(); if (!firstev) firstev = ev; } } } // switch to the first template opened if (firstev) TabBar->SetActiveTab(firstev); TabBar->redraw(); UnlockWindow(); if (TemplatePanel) { delete TemplatePanel; TemplatePanel = NULL; } Quit(); } break; case M_TEMPLATE_SELECT: { entry_ref ref; if (msg->FindRef("refs", &ref) == B_OK) { BEntry entry(&ref, true); BPath path; entry.GetPath(&path); BMessenger target; BMessage msg_to_deliver; msg->FindMessage("message", &msg_to_deliver); msg->FindMessenger("target", &target); msg_to_deliver.AddString("template_name", path.Path()); stat("delivering message"); target.SendMessage(&msg_to_deliver); } } break; default: BLooper::DispatchMessage(msg, target); break; } }
bool ShortcutsSpec::_AttemptTabCompletion() { bool result = false; int32 argc; char** argv = ParseArgvFromString(fCommand, argc); if (argc > 0) { // Try to complete the path partially expressed in the last argument! char* arg = argv[argc - 1]; char* fileFragment = strrchr(arg, '/'); if (fileFragment != NULL) { const char* directoryName = (fileFragment == arg) ? "/" : arg; *fileFragment = '\0'; fileFragment++; int fragmentLength = strlen(fileFragment); BDirectory dir(directoryName); if (dir.InitCheck() == B_NO_ERROR) { BEntry nextEnt; BPath nextPath; BList matchList; int maxEntryLen = 0; // Read in all the files in the directory whose names start // with our fragment. while (dir.GetNextEntry(&nextEnt) == B_NO_ERROR) { if (nextEnt.GetPath(&nextPath) == B_NO_ERROR) { char* filePath = strrchr(nextPath.Path(), '/') + 1; if (strncmp(filePath, fileFragment, fragmentLength) == 0) { int len = strlen(filePath); if (len > maxEntryLen) maxEntryLen = len; char* newStr = new char[len + 1]; strcpy(newStr, filePath); matchList.AddItem(newStr); } } } // Now slowly extend our keyword to its full length, counting // numbers of matches at each step. If the match list length // is 1, we can use that whole entry. If it's greater than one, // we can use just the match length. int matchLen = matchList.CountItems(); if (matchLen > 0) { int i; BString result(fileFragment); for (i = fragmentLength; i < maxEntryLen; i++) { // See if all the matching entries have the same letter // in the next position... if so, we can go farther. char commonLetter = '\0'; for (int j = 0; j < matchLen; j++) { char nextLetter = GetLetterAt( (char*)matchList.ItemAt(j), i); if (commonLetter == '\0') commonLetter = nextLetter; if ((commonLetter != '\0') && (commonLetter != nextLetter)) { commonLetter = '\0';// failed; beep(); break; } } if (commonLetter == '\0') break; else result.Append(commonLetter, 1); } // free all the strings we allocated for (int k = 0; k < matchLen; k++) delete [] ((char*)matchList.ItemAt(k)); DoStandardEscapes(result); BString wholeLine; for (int l = 0; l < argc - 1; l++) { wholeLine += argv[l]; wholeLine += " "; } BString file(directoryName); DoStandardEscapes(file); if (directoryName[strlen(directoryName) - 1] != '/') file += "/"; file += result; // Remove any trailing slash... const char* fileStr = file.String(); if (fileStr[strlen(fileStr) - 1] == '/') file.RemoveLast("/"); // and re-append it iff the file is a dir. BDirectory testFileAsDir(file.String()); if ((strcmp(file.String(), "/") != 0) && (testFileAsDir.InitCheck() == B_NO_ERROR)) file.Append("/"); wholeLine += file; SetCommand(wholeLine.String()); result = true; } } *(fileFragment - 1) = '/'; } } FreeArgv(argv); return result; }
void DeskbarView::MessageReceived(BMessage* message) { switch (message->what) { case MD_CHECK_SEND_NOW: // also happens in DeskbarView::MouseUp() with // B_TERTIARY_MOUSE_BUTTON pressed BMailDaemon().CheckAndSendQueuedMail(); break; case MD_CHECK_FOR_MAILS: BMailDaemon().CheckMail(message->FindInt32("account")); break; case MD_SEND_MAILS: BMailDaemon().SendQueuedMail(); break; case MD_OPEN_NEW: { char* argv[] = {(char *)"New Message", (char *)"mailto:"}; be_roster->Launch("text/x-email", 2, argv); break; } case MD_OPEN_PREFS: be_roster->Launch("application/x-vnd.Haiku-Mail"); break; case MD_REFRESH_QUERY: _RefreshMailQuery(); break; case B_QUERY_UPDATE: { int32 what; dev_t device; ino_t directory; const char *name; entry_ref ref; message->FindInt32("opcode", &what); message->FindInt32("device", &device); message->FindInt64("directory", &directory); switch (what) { case B_ENTRY_CREATED: if (message->FindString("name", &name) == B_OK) { ref.device = device; ref.directory = directory; ref.set_name(name); if (!_EntryInTrash(&ref)) fNewMessages++; } break; case B_ENTRY_REMOVED: node_ref node; node.device = device; node.node = directory; BDirectory dir(&node); BEntry entry(&dir, NULL); entry.GetRef(&ref); if (!_EntryInTrash(&ref)) fNewMessages--; break; } fStatus = fNewMessages > 0 ? kStatusNewMail : kStatusNoMail; Invalidate(); break; } case B_QUIT_REQUESTED: BMailDaemon().Quit(); break; // open received files in the standard mail application case B_REFS_RECEIVED: { BMessage argv(B_ARGV_RECEIVED); argv.AddString("argv", "E-mail"); entry_ref ref; BPath path; int i = 0; while (message->FindRef("refs", i++, &ref) == B_OK && path.SetTo(&ref) == B_OK) { //fprintf(stderr,"got %s\n", path.Path()); argv.AddString("argv", path.Path()); } if (i > 1) { argv.AddInt32("argc", i); be_roster->Launch("text/x-email", &argv); } break; } default: BView::MessageReceived(message); } }
status_t CheckCopiable(BEntry *src,BEntry *dest) { // Checks to see if we can copy the src to dest. if(!src || !dest) return B_ERROR; if(!src->Exists()) return B_FILE_NOT_FOUND; // Ensure that when we want the destination directory, that is exactly // what we're working with. If we've been given an entry which is a file, // extract the destination directory. BEntry destdir; if(dest->IsDirectory()) destdir=*dest; else dest->GetParent(&destdir); // check existence of target directory if(!destdir.Exists()) return B_NAME_NOT_FOUND; // check space entry_ref ref; off_t src_bytes; dest->GetRef(&ref); BVolume dvolume(ref.device); src->GetSize(&src_bytes); if(src_bytes>dvolume.FreeBytes()) return B_DEVICE_FULL; // check permissions if(dvolume.IsReadOnly()) return B_READ_ONLY; // check existing name BPath path; destdir.GetPath(&path); char name[B_FILE_NAME_LENGTH]; src->GetName(name); BString newpath=path.Path(); newpath+=name; BFile file; if(file.SetTo(newpath.String(),B_READ_WRITE | B_FAIL_IF_EXISTS)==B_FILE_EXISTS) { // We have an existing file, so query the user what to do. status_t returncode; newpath="The file "; newpath+=name; newpath+=" exists. Do you want to replace it?"; BAlert *alert=new BAlert("Error",newpath.String(),"Replace File", "Skip File", "Stop"); returncode=alert->Go(); switch(returncode) { case 0: return FS_CLOBBER; case 1: return FS_SKIP; default: return B_CANCELED; } } return B_OK; }
void TermWindow::MessageReceived(BMessage *message) { int32 encodingId; bool findresult; switch (message->what) { case B_COPY: _ActiveTermView()->Copy(be_clipboard); break; case B_PASTE: _ActiveTermView()->Paste(be_clipboard); break; #ifdef USE_DEBUG_SNAPSHOTS case SHORTCUT_DEBUG_SNAPSHOTS: _ActiveTermView()->MakeDebugSnapshots(); break; case SHORTCUT_DEBUG_CAPTURE: _ActiveTermView()->StartStopDebugCapture(); break; #endif case B_SELECT_ALL: _ActiveTermView()->SelectAll(); break; case MENU_CLEAR_ALL: _ActiveTermView()->Clear(); break; case MENU_SWITCH_TERM: _SwitchTerminal(); break; case MENU_NEW_TERM: { // Set our current working directory to that of the active tab, so // that the new terminal and its shell inherit it. // Note: That's a bit lame. We should rather fork() and change the // CWD in the child, but since ATM there aren't any side effects of // changing our CWD, we save ourselves the trouble. ActiveProcessInfo activeProcessInfo; if (_ActiveTermView()->GetActiveProcessInfo(activeProcessInfo)) chdir(activeProcessInfo.CurrentDirectory()); app_info info; be_app->GetAppInfo(&info); // try launching two different ways to work around possible problems if (be_roster->Launch(&info.ref) != B_OK) be_roster->Launch(TERM_SIGNATURE); break; } case MENU_PREF_OPEN: if (!fPrefWindow) { fPrefWindow = new PrefWindow(this); } else fPrefWindow->Activate(); break; case MSG_PREF_CLOSED: fPrefWindow = NULL; break; case MSG_WINDOW_TITLE_SETTING_CHANGED: case MSG_TAB_TITLE_SETTING_CHANGED: _TitleSettingsChanged(); break; case MENU_FIND_STRING: if (fFindPanel == NULL) { fFindPanel = new FindWindow(this, fFindString, fFindSelection, fMatchWord, fMatchCase, fForwardSearch); fFindPanel->CenterIn(Frame()); _MoveWindowInScreen(fFindPanel); fFindPanel->Show(); } else fFindPanel->Activate(); break; case MSG_FIND: { fFindPanel->PostMessage(B_QUIT_REQUESTED); message->FindBool("findselection", &fFindSelection); if (!fFindSelection) message->FindString("findstring", &fFindString); else _ActiveTermView()->GetSelection(fFindString); if (fFindString.Length() == 0) { const char* errorMsg = !fFindSelection ? B_TRANSLATE("No search string was entered.") : B_TRANSLATE("Nothing is selected."); BAlert* alert = new BAlert(B_TRANSLATE("Find failed"), errorMsg, B_TRANSLATE("OK"), NULL, NULL, B_WIDTH_AS_USUAL, B_WARNING_ALERT); alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(); fFindPreviousMenuItem->SetEnabled(false); fFindNextMenuItem->SetEnabled(false); break; } message->FindBool("forwardsearch", &fForwardSearch); message->FindBool("matchcase", &fMatchCase); message->FindBool("matchword", &fMatchWord); findresult = _ActiveTermView()->Find(fFindString, fForwardSearch, fMatchCase, fMatchWord); if (!findresult) { BAlert* alert = new BAlert(B_TRANSLATE("Find failed"), B_TRANSLATE("Text not found."), B_TRANSLATE("OK"), NULL, NULL, B_WIDTH_AS_USUAL, B_WARNING_ALERT); alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(); fFindPreviousMenuItem->SetEnabled(false); fFindNextMenuItem->SetEnabled(false); break; } // Enable the menu items Find Next and Find Previous fFindPreviousMenuItem->SetEnabled(true); fFindNextMenuItem->SetEnabled(true); break; } case MENU_FIND_NEXT: case MENU_FIND_PREVIOUS: findresult = _ActiveTermView()->Find(fFindString, (message->what == MENU_FIND_NEXT) == fForwardSearch, fMatchCase, fMatchWord); if (!findresult) { BAlert* alert = new BAlert(B_TRANSLATE("Find failed"), B_TRANSLATE("Not found."), B_TRANSLATE("OK"), NULL, NULL, B_WIDTH_AS_USUAL, B_WARNING_ALERT); alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(); } break; case MSG_FIND_CLOSED: fFindPanel = NULL; break; case MENU_ENCODING: if (message->FindInt32("op", &encodingId) == B_OK) _ActiveTermView()->SetEncoding(encodingId); break; case MSG_COLS_CHANGED: { int32 columns, rows; if (message->FindInt32("columns", &columns) != B_OK || message->FindInt32("rows", &rows) != B_OK) { break; } for (int32 i = 0; i < fTabView->CountTabs(); i++) { TermView* view = _TermViewAt(i); view->SetTermSize(rows, columns, true); _ResizeView(view); } break; } case MSG_HALF_FONT_CHANGED: case MSG_FULL_FONT_CHANGED: { BFont font; _GetPreferredFont(font); for (int32 i = 0; i < fTabView->CountTabs(); i++) { TermView* view = _TermViewAt(i); view->SetTermFont(&font); _ResizeView(view); } break; } case MSG_HALF_SIZE_CHANGED: case MSG_FULL_SIZE_CHANGED: { const char* size = NULL; if (message->FindString("font_size", &size) != B_OK) break; // mark the font size menu item for (int32 i = 0; i < fFontSizeMenu->CountItems(); i++) { BMenuItem* item = fFontSizeMenu->ItemAt(i); if (item == NULL) continue; item->SetMarked(false); if (strcmp(item->Label(), size) == 0) item->SetMarked(true); } BFont font; _ActiveTermView()->GetTermFont(&font); font.SetSize(atoi(size)); PrefHandler::Default()->setInt32(PREF_HALF_FONT_SIZE, (int32)atoi(size)); for (int32 i = 0; i < fTabView->CountTabs(); i++) { TermView* view = _TermViewAt(i); _TermViewAt(i)->SetTermFont(&font); _ResizeView(view); } break; } case FULLSCREEN: if (!fSavedFrame.IsValid()) { // go fullscreen _ActiveTermView()->DisableResizeView(); float mbHeight = fMenuBar->Bounds().Height() + 1; fSavedFrame = Frame(); BScreen screen(this); for (int32 i = fTabView->CountTabs() - 1; i >= 0 ; i--) _TermViewAt(i)->ScrollBar()->ResizeBy(0, (B_H_SCROLL_BAR_HEIGHT - 1)); fMenuBar->Hide(); fTabView->ResizeBy(0, mbHeight); fTabView->MoveBy(0, -mbHeight); fSavedLook = Look(); // done before ResizeTo to work around a Dano bug // (not erasing the decor) SetLook(B_NO_BORDER_WINDOW_LOOK); ResizeTo(screen.Frame().Width() + 1, screen.Frame().Height() + 1); MoveTo(screen.Frame().left, screen.Frame().top); SetFlags(Flags() | (B_NOT_RESIZABLE | B_NOT_MOVABLE)); fFullScreen = true; } else { // exit fullscreen _ActiveTermView()->DisableResizeView(); float mbHeight = fMenuBar->Bounds().Height() + 1; fMenuBar->Show(); for (int32 i = fTabView->CountTabs() - 1; i >= 0 ; i--) _TermViewAt(i)->ScrollBar()->ResizeBy(0, -(B_H_SCROLL_BAR_HEIGHT - 1)); ResizeTo(fSavedFrame.Width(), fSavedFrame.Height()); MoveTo(fSavedFrame.left, fSavedFrame.top); fTabView->ResizeBy(0, -mbHeight); fTabView->MoveBy(0, mbHeight); SetLook(fSavedLook); fSavedFrame = BRect(0, 0, -1, -1); SetFlags(Flags() & ~(B_NOT_RESIZABLE | B_NOT_MOVABLE)); fFullScreen = false; } break; case MSG_FONT_CHANGED: PostMessage(MSG_HALF_FONT_CHANGED); break; case MSG_COLOR_CHANGED: case MSG_COLOR_SCHEME_CHANGED: { _SetTermColors(_ActiveTermViewContainerView()); _ActiveTermViewContainerView()->Invalidate(); _ActiveTermView()->Invalidate(); break; } case SAVE_AS_DEFAULT: { BPath path; if (PrefHandler::GetDefaultPath(path) == B_OK) PrefHandler::Default()->SaveAsText(path.Path(), PREFFILE_MIMETYPE); break; } case MENU_PAGE_SETUP: _DoPageSetup(); break; case MENU_PRINT: _DoPrint(); break; case MSG_CHECK_CHILDREN: _CheckChildren(); break; case MSG_MOVE_TAB_LEFT: case MSG_MOVE_TAB_RIGHT: _NavigateTab(_IndexOfTermView(_ActiveTermView()), message->what == MSG_MOVE_TAB_LEFT ? -1 : 1, true); break; case kTabTitleChanged: { // tab title changed message from SetTitleDialog SessionID sessionID(*message, "session"); if (Session* session = _SessionForID(sessionID)) { BString title; if (message->FindString("title", &title) == B_OK) { session->title.pattern = title; session->title.patternUserDefined = true; } else { session->title.pattern.Truncate(0); session->title.patternUserDefined = false; } _UpdateSessionTitle(_IndexOfSession(session)); } break; } case kWindowTitleChanged: { // window title changed message from SetTitleDialog BString title; if (message->FindString("title", &title) == B_OK) { fTitle.pattern = title; fTitle.patternUserDefined = true; } else { fTitle.pattern = PrefHandler::Default()->getString(PREF_WINDOW_TITLE); fTitle.patternUserDefined = false; } _UpdateSessionTitle(fTabView->Selection()); // updates the window title as a side effect break; } case kSetActiveTab: { int32 index; if (message->FindInt32("index", &index) == B_OK && index >= 0 && index < fSessions.CountItems()) { fTabView->Select(index); } break; } case kNewTab: _NewTab(); break; case kCloseView: { int32 index = -1; SessionID sessionID(*message, "session"); if (sessionID.IsValid()) { if (Session* session = _SessionForID(sessionID)) index = _IndexOfSession(session); } else index = _IndexOfTermView(_ActiveTermView()); if (index >= 0) _RemoveTab(index); break; } case kCloseOtherViews: { Session* session = _SessionForID(SessionID(*message, "session")); if (session == NULL) break; int32 count = fSessions.CountItems(); for (int32 i = count - 1; i >= 0; i--) { if (_SessionAt(i) != session) _RemoveTab(i); } break; } case kIncreaseFontSize: case kDecreaseFontSize: { BFont font; _ActiveTermView()->GetTermFont(&font); float size = font.Size(); if (message->what == kIncreaseFontSize) { if (size < 12) size += 1; else if (size < 24) size += 2; else size += 4; } else { if (size <= 12) size -= 1; else if (size <= 24) size -= 2; else size -= 4; } // constrain the font size if (size < kMinimumFontSize) size = kMinimumFontSize; if (size > kMaximumFontSize) size = kMaximumFontSize; // mark the font size menu item for (int32 i = 0; i < fFontSizeMenu->CountItems(); i++) { BMenuItem* item = fFontSizeMenu->ItemAt(i); if (item == NULL) continue; item->SetMarked(false); if (atoi(item->Label()) == size) item->SetMarked(true); } font.SetSize(size); PrefHandler::Default()->setInt32(PREF_HALF_FONT_SIZE, (int32)size); for (int32 i = 0; i < fTabView->CountTabs(); i++) { TermView* view = _TermViewAt(i); _TermViewAt(i)->SetTermFont(&font); _ResizeView(view); } break; } case kUpdateTitles: _UpdateTitles(); break; case kEditTabTitle: { SessionID sessionID(*message, "session"); if (Session* session = _SessionForID(sessionID)) _OpenSetTabTitleDialog(_IndexOfSession(session)); break; } case kEditWindowTitle: _OpenSetWindowTitleDialog(); break; case kUpdateSwitchTerminalsMenuItem: _UpdateSwitchTerminalsMenuItem(); break; default: BWindow::MessageReceived(message); break; } }
status_t CopyEngine::_CopyFolder(const char* _source, const char* _destination, int32& level, sem_id cancelSemaphore) { level++; fCurrentTargetFolder = _destination; BDirectory source(_source); status_t ret = source.InitCheck(); if (ret < B_OK) return ret; ret = create_directory(_destination, 0777); if (ret < B_OK && ret != B_FILE_EXISTS) { fprintf(stderr, "Could not create '%s': %s\n", _destination, strerror(ret)); return ret; } BDirectory destination(_destination); ret = destination.InitCheck(); if (ret < B_OK) return ret; BEntry entry; while (source.GetNextEntry(&entry) == B_OK) { SemaphoreLocker lock(cancelSemaphore); if (cancelSemaphore >= 0 && !lock.IsLocked()) { // We are supposed to quit return B_CANCELED; } char name[B_FILE_NAME_LENGTH]; status_t ret = entry.GetName(name); if (ret < B_OK) return ret; struct stat statInfo; entry.GetStat(&statInfo); if (!_ShouldCopyEntry(entry, name, statInfo, level)) continue; fItemsCopied++; fCurrentItem = name; _UpdateProgress(); BEntry copy(&destination, name); bool copyAttributes = true; if (S_ISDIR(statInfo.st_mode)) { // handle recursive directory copy if (copy.Exists()) { ret = B_OK; if (copy.IsDirectory()) { if (_ShouldClobberFolder(name, statInfo, level)) ret = _RemoveFolder(copy); else { // Do not overwrite attributes on folders that exist. // This should work better when the install target // already contains a Haiku installation. copyAttributes = false; } } else ret = copy.Remove(); if (ret != B_OK) { fprintf(stderr, "Failed to make room for folder '%s': " "%s\n", name, strerror(ret)); return ret; } } BPath srcFolder; ret = entry.GetPath(&srcFolder); if (ret < B_OK) return ret; BPath dstFolder; ret = copy.GetPath(&dstFolder); if (ret < B_OK) return ret; if (cancelSemaphore >= 0) lock.Unlock(); ret = _CopyFolder(srcFolder.Path(), dstFolder.Path(), level, cancelSemaphore); if (ret < B_OK) return ret; if (cancelSemaphore >= 0 && !lock.Lock()) { // We are supposed to quit return B_CANCELED; } } else { if (copy.Exists()) { if (copy.IsDirectory()) ret = _RemoveFolder(copy); else ret = copy.Remove(); if (ret != B_OK) { fprintf(stderr, "Failed to make room for entry '%s': " "%s\n", name, strerror(ret)); return ret; } } if (S_ISLNK(statInfo.st_mode)) { // copy symbolic links BSymLink srcLink(&entry); if (ret < B_OK) return ret; char linkPath[B_PATH_NAME_LENGTH]; ssize_t read = srcLink.ReadLink(linkPath, B_PATH_NAME_LENGTH - 1); if (read < 0) return (status_t)read; // just in case it already exists... copy.Remove(); BSymLink dstLink; ret = destination.CreateSymLink(name, linkPath, &dstLink); if (ret < B_OK) return ret; } else { // copy file data // NOTE: Do not pass the locker, we simply keep holding the lock! ret = CopyFile(entry, copy); if (ret < B_OK) return ret; } } if (!copyAttributes) continue; ret = copy.SetTo(&destination, name); if (ret != B_OK) return ret; // copy attributes BNode sourceNode(&entry); BNode targetNode(©); char attrName[B_ATTR_NAME_LENGTH]; while (sourceNode.GetNextAttrName(attrName) == B_OK) { attr_info info; if (sourceNode.GetAttrInfo(attrName, &info) < B_OK) continue; size_t size = 4096; uint8 buffer[size]; off_t offset = 0; ssize_t read = sourceNode.ReadAttr(attrName, info.type, offset, buffer, min_c(size, info.size)); // NOTE: It's important to still write the attribute even if // we have read 0 bytes! while (read >= 0) { targetNode.WriteAttr(attrName, info.type, offset, buffer, read); offset += read; read = sourceNode.ReadAttr(attrName, info.type, offset, buffer, min_c(size, info.size - offset)); if (read == 0) break; } } // copy basic attributes copy.SetPermissions(statInfo.st_mode); copy.SetOwner(statInfo.st_uid); copy.SetGroup(statInfo.st_gid); copy.SetModificationTime(statInfo.st_mtime); copy.SetCreationTime(statInfo.st_crtime); } level--; return B_OK; }
void BApplication::_InitData(const char* signature, bool initGUI, status_t* _error) { DBG(OUT("BApplication::InitData(`%s', %p)\n", signature, _error)); // check whether there exists already an application if (be_app) debugger("2 BApplication objects were created. Only one is allowed."); fServerLink = new BPrivate::PortLink(-1, -1); fServerAllocator = NULL; fInitialWorkspace = 0; //fDraggedMessage = NULL; fReadyToRunCalled = false; // initially, there is no pulse fPulseRunner = NULL; fPulseRate = 0; // check signature fInitError = check_app_signature(signature); fAppName = signature; #ifndef RUN_WITHOUT_REGISTRAR bool isRegistrar = signature && strcasecmp(signature, kRegistrarSignature) == 0; // get team and thread team_id team = Team(); thread_id thread = BPrivate::main_thread_for(team); #endif // get app executable ref entry_ref ref; if (fInitError == B_OK) { fInitError = BPrivate::get_app_ref(&ref); if (fInitError != B_OK) { DBG(OUT("BApplication::InitData(): Failed to get app ref: %s\n", strerror(fInitError))); } } // get the BAppFileInfo and extract the information we need uint32 appFlags = B_REG_DEFAULT_APP_FLAGS; if (fInitError == B_OK) { BAppFileInfo fileInfo; BFile file(&ref, B_READ_ONLY); fInitError = fileInfo.SetTo(&file); if (fInitError == B_OK) { fileInfo.GetAppFlags(&appFlags); char appFileSignature[B_MIME_TYPE_LENGTH]; // compare the file signature and the supplied signature if (fileInfo.GetSignature(appFileSignature) == B_OK && strcasecmp(appFileSignature, signature) != 0) { printf("Signature in rsrc doesn't match constructor arg. (%s, %s)\n", signature, appFileSignature); } } else { DBG(OUT("BApplication::InitData(): Failed to get info from: " "BAppFileInfo: %s\n", strerror(fInitError))); } } #ifndef RUN_WITHOUT_REGISTRAR // check whether be_roster is valid if (fInitError == B_OK && !isRegistrar && !BRoster::Private().IsMessengerValid(false)) { printf("FATAL: be_roster is not valid. Is the registrar running?\n"); fInitError = B_NO_INIT; } // check whether or not we are pre-registered bool preRegistered = false; app_info appInfo; if (fInitError == B_OK && !isRegistrar) { if (BRoster::Private().IsAppRegistered(&ref, team, 0, &preRegistered, &appInfo) != B_OK) { preRegistered = false; } } if (preRegistered) { // we are pre-registered => the app info has been filled in // Check whether we need to replace the looper port with a port // created by the roster. if (appInfo.port >= 0 && appInfo.port != fMsgPort) { delete_port(fMsgPort); fMsgPort = appInfo.port; } else appInfo.port = fMsgPort; // check the signature and correct it, if necessary, also the case if (strcmp(appInfo.signature, fAppName)) BRoster::Private().SetSignature(team, fAppName); // complete the registration fInitError = BRoster::Private().CompleteRegistration(team, thread, appInfo.port); } else if (fInitError == B_OK) { // not pre-registered -- try to register the application team_id otherTeam = -1; // the registrar must not register if (!isRegistrar) { fInitError = BRoster::Private().AddApplication(signature, &ref, appFlags, team, thread, fMsgPort, true, NULL, &otherTeam); if (fInitError != B_OK) { DBG(OUT("BApplication::InitData(): Failed to add app: %s\n", strerror(fInitError))); } } if (fInitError == B_ALREADY_RUNNING) { // An instance is already running and we asked for // single/exclusive launch. Send our argv to the running app. // Do that only, if the app is NOT B_ARGV_ONLY. if (otherTeam >= 0) { BMessenger otherApp(NULL, otherTeam); app_info otherAppInfo; if (__libc_argc > 1 && be_roster->GetRunningAppInfo(otherTeam, &otherAppInfo) == B_OK && (otherAppInfo.flags & B_ARGV_ONLY) != 0) { // create an B_ARGV_RECEIVED message BMessage argvMessage(B_ARGV_RECEIVED); fill_argv_message(argvMessage); // replace the first argv string with the path of the // other application BPath path; if (path.SetTo(&otherAppInfo.ref) == B_OK) argvMessage.ReplaceString("argv", 0, path.Path()); // send the message otherApp.SendMessage(&argvMessage); } else otherApp.SendMessage(B_SILENT_RELAUNCH); } } else if (fInitError == B_OK) { // the registrations was successful // Create a B_ARGV_RECEIVED message and send it to ourselves. // Do that even, if we are B_ARGV_ONLY. // TODO: When BLooper::AddMessage() is done, use that instead of // PostMessage(). DBG(OUT("info: BApplication successfully registered.\n")); if (__libc_argc > 1) { BMessage argvMessage(B_ARGV_RECEIVED); fill_argv_message(argvMessage); PostMessage(&argvMessage, this); } // send a B_READY_TO_RUN message as well PostMessage(B_READY_TO_RUN, this); } else if (fInitError > B_ERRORS_END) { // Registrar internal errors shouldn't fall into the user's hands. fInitError = B_ERROR; } } #else // We need to have ReadyToRun called even when we're not using the registrar PostMessage(B_READY_TO_RUN, this); #endif // ifndef RUN_WITHOUT_REGISTRAR if (fInitError == B_OK) { // TODO: Not completely sure about the order, but this should be close. // init be_app and be_app_messenger be_app = this; be_app_messenger = BMessenger(NULL, this); // set the BHandler's name SetName(ref.name); // create meta MIME BPath path; if (path.SetTo(&ref) == B_OK) create_app_meta_mime(path.Path(), false, true, false); #ifndef RUN_WITHOUT_APP_SERVER // app server connection and IK initialization if (initGUI) fInitError = _InitGUIContext(); #endif // RUN_WITHOUT_APP_SERVER } // Return the error or exit, if there was an error and no error variable // has been supplied. if (_error) { *_error = fInitError; } else if (fInitError != B_OK) { DBG(OUT("BApplication::InitData() failed: %s\n", strerror(fInitError))); exit(0); } DBG(OUT("BApplication::InitData() done\n")); }
BView* AboutView::_CreateCreditsView() { // Begin construction of the credits view fCreditsView = new HyperTextView("credits"); fCreditsView->SetFlags(fCreditsView->Flags() | B_FRAME_EVENTS); fCreditsView->SetStylable(true); fCreditsView->MakeEditable(false); fCreditsView->SetWordWrap(true); fCreditsView->SetInsets(5, 5, 5, 5); fCreditsView->SetViewColor(ui_color(B_DOCUMENT_BACKGROUND_COLOR)); BScrollView* creditsScroller = new BScrollView("creditsScroller", fCreditsView, B_WILL_DRAW | B_FRAME_EVENTS, false, true, B_PLAIN_BORDER); // Haiku copyright BFont font(be_bold_font); font.SetSize(font.Size() + 4); fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuGreen); fCreditsView->Insert("Haiku\n"); char string[1024]; time_t time = ::time(NULL); struct tm* tm = localtime(&time); int32 year = tm->tm_year + 1900; if (year < 2008) year = 2008; snprintf(string, sizeof(string), COPYRIGHT_STRING "2001-%ld The Haiku project. ", year); fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey); fCreditsView->Insert(string); fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey); fCreditsView->Insert(B_TRANSLATE("The copyright to the Haiku code is " "property of Haiku, Inc. or of the respective authors where expressly " "noted in the source. Haiku" B_UTF8_REGISTERED " and the HAIKU logo" B_UTF8_REGISTERED " are registered trademarks of Haiku, Inc." "\n\n")); fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kLinkBlue); fCreditsView->InsertHyperText("http://www.haiku-os.org", new URLAction("http://www.haiku-os.org")); fCreditsView->Insert("\n\n"); font.SetSize(be_bold_font->Size()); font.SetFace(B_BOLD_FACE | B_ITALIC_FACE); fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuOrange); fCreditsView->Insert(B_TRANSLATE("Current maintainers:\n")); fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey); fCreditsView->Insert( "Ithamar R. Adema\n" "Bruno G. Albuquerque\n" "Stephan Aßmus\n" "Salvatore Benedetto\n" "Stefano Ceccherini\n" "Rudolf Cornelissen\n" "Alexandre Deckner\n" "Adrien Destugues\n" "Oliver Ruiz Dorantes\n" "Axel Dörfler\n" "Jérôme Duval\n" "René Gollent\n" "Bryce Groff\n" "Colin Günther\n" "Karsten Heimrich\n" "Fredrik Holmqvist\n" "Philippe Houdoin\n" "Maurice Kalinowski\n" "Euan Kirkhope\n" "Ryan Leavengood\n" "Michael Lotz\n" "Brecht Machiels\n" "Matt Madia\n" "Scott McCreary\n" "David McPaul\n" "Wim van der Meer\n" "Fredrik Modéen\n" "Marcus Overhagen\n" "Michael Pfeiffer\n" "François Revol\n" "Philippe Saint-Pierre\n" "John Scipione\n" "Andrej Spielmann\n" "Jonas Sundström\n" "Oliver Tappe\n" "Gerasim Troeglazov\n" "Alexander von Gluck IV\n" "Ingo Weinhold\n" "Alex Wilson\n" "Artur Wyszyński\n" "Clemens Zeidler\n" "Siarzhuk Zharski\n" "\n"); fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuOrange); fCreditsView->Insert(B_TRANSLATE("Past maintainers:\n")); fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey); fCreditsView->Insert( "Andrew Bachmann\n" "Tyler Dauwalder\n" "Daniel Furrer\n" "Andre Alves Garzia\n" "Erik Jaesler\n" "Marcin Konicki\n" "Waldemar Kornewald\n" "Thomas Kurschel\n" "Frans Van Nispen\n" "Adi Oanca\n" "Michael Phipps\n" "Niels Sascha Reedijk\n" "David Reid\n" "Hugo Santos\n" "Alexander G. M. Smith\n" "Bryan Varner\n" "Nathan Whitehorn\n" "Michael Wilber\n" "Jonathan Yoder\n" "Gabe Yoder\n" "\n"); fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuOrange); fCreditsView->Insert(B_TRANSLATE("Website, marketing & documentation:\n")); fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey); fCreditsView->Insert( "Phil Greenway\n" "Gavin James\n" "Urias McCullough\n" "Niels Sascha Reedijk\n" "Joachim Seemer (Humdinger)\n" "Jonathan Yoder\n" "\n"); fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuOrange); fCreditsView->Insert(B_TRANSLATE("Contributors:\n")); fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey); fCreditsView->Insert( "Andrea Anzani\n" "Sean Bartell\n" "Andre Braga\n" "Michael Bulash\n" "Bruce Cameron\n" "Jean-Loïc Charroud\n" "Greg Crain\n" "Michael Davidson\n" "David Dengg\n" "John Drinkwater\n" "Cian Duffy\n" "Vincent Duvert\n" "Mikael Eiman\n" "Fredrik Ekdahl\n" "Joshua R. Elsasser\n" "Atis Elsts\n" "Mark Erben\n" "Christian Fasshauer\n" "Andreas Färber\n" "Janito Ferreira Filho\n" "Pier Luigi Fiorini\n" "Marc Flerackers\n" "Michele Frau (zuMi)\n" "Deyan Genovski\n" "Pete Goodeve\n" "Lucian Adrian Grijincu\n" "Sean Healy\n" "Matthijs Hollemans\n" "Mathew Hounsell\n" "Morgan Howe\n" "Christophe Huriaux\n" "Jian Jiang\n" "Ma Jie\n" "Carwyn Jones\n" "Vasilis Kaoutsis\n" "James Kim\n" "Shintaro Kinugawa\n" "Jan Klötzke\n" "Kurtis Kopf\n" "Tomáš Kučera\n" "Luboš Kulič\n" "Elad Lahav\n" "Anthony Lee\n" "Santiago Lema\n" "Raynald Lesieur\n" "Oscar Lesta\n" "Jerome Leveque\n" "Brian Luft\n" "Christof Lutteroth\n" "Graham MacDonald\n" "Jorge G. Mare (Koki)\n" "Jan Matějek\n" "Brian Matzon\n" "Christopher ML Zumwalt May\n" "Andrew McCall\n" "Nathan Mentley\n" "Marius Middelthon\n" "Marco Minutoli\n" "Misza\n" "Hamish Morrison\n" "MrSiggler\n" "Takashi Murai\n" "Alan Murta\n" "Raghuram Nagireddy\n" "Kazuho Okui\n" "Jeroen Oortwijn (idefix)\n" "Pahtz\n" "Michael Paine\n" "Adrian Panasiuk\n" "Romain Picard\n" "Francesco Piccinno\n" "David Powell\n" "Jeremy Rand\n" "Hartmut Reh\n" "Daniel Reinhold\n" "Chris Roberts\n" "Samuel Rodríguez Pérez\n" "Thomas Roell\n" "Rafael Romo\n" "Ralf Schülke\n" "Reznikov Sergei\n" "Zousar Shaker\n" "Caitlin Shaw\n" "Geoffry Song\n" "Daniel Switkin\n" "Atsushi Takamatsu\n" "James Urquhart\n" "Jason Vandermark\n" "Sandor Vroemisse\n" "Denis Washington\n" "Ulrich Wimboeck\n" "Johannes Wischert\n" "James Woodcock\n" "Hong Yul Yang\n" "Gerald Zajac\n" "Łukasz Zemczak\n" "JiSheng Zhang\n" "Zhao Shuai\n"); fCreditsView->Insert( B_TRANSLATE("\n" B_UTF8_ELLIPSIS " and probably some more we forgot to mention (sorry!)" "\n\n")); fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuOrange); fCreditsView->Insert(B_TRANSLATE("Translations:\n")); BLanguage* lang; BString langName; BList sortedTranslations; for (uint32 i = 0; i < kNumberOfTranslations; i ++) { const Translation* translation = &gTranslations[i]; sortedTranslations.AddItem((void*)translation); } sortedTranslations.SortItems(TranslationComparator); for (uint32 i = 0; i < kNumberOfTranslations; i ++) { const Translation& translation = *(const Translation*)sortedTranslations.ItemAt(i); langName.Truncate(0); if (BLocaleRoster::Default()->GetLanguage(translation.languageCode, &lang) == B_OK) { lang->GetName(langName); delete lang; } else { // We failed to get the localized readable name, // go with what we have. langName.Append(translation.languageCode); } fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuGreen); fCreditsView->Insert("\n"); fCreditsView->Insert(langName); fCreditsView->Insert("\n"); fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey); fCreditsView->Insert(translation.names); } fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuOrange); fCreditsView->Insert(B_TRANSLATE("\n\nSpecial thanks to:\n")); fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey); BString beosCredits(B_TRANSLATE( "Be Inc. and its developer team, for having created BeOS!\n\n")); int32 beosOffset = beosCredits.FindFirst("BeOS"); fCreditsView->Insert(beosCredits.String(), (beosOffset < 0) ? beosCredits.Length() : beosOffset); if (beosOffset > -1) { fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kBeOSBlue); fCreditsView->Insert("B"); fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kBeOSRed); fCreditsView->Insert("e"); fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey); beosCredits.Remove(0, beosOffset + 2); fCreditsView->Insert(beosCredits.String(), beosCredits.Length()); } fCreditsView->Insert( B_TRANSLATE("Travis Geiselbrecht (and his NewOS kernel)\n")); fCreditsView->Insert( B_TRANSLATE("Michael Phipps (project founder)\n\n")); fCreditsView->Insert( B_TRANSLATE("The Haiku-Ports team\n")); fCreditsView->Insert( B_TRANSLATE("The Haikuware team and their bounty program\n")); fCreditsView->Insert( B_TRANSLATE("The BeGeistert team\n")); fCreditsView->Insert( B_TRANSLATE("Google & their Google Summer of Code program\n")); fCreditsView->Insert( B_TRANSLATE("The University of Auckland and Christof Lutteroth\n\n")); fCreditsView->Insert( B_TRANSLATE("... and the many people making donations!\n\n")); // copyrights for various projects we use BPath mitPath; _GetLicensePath("MIT", mitPath); BPath lgplPath; _GetLicensePath("GNU LGPL v2.1", lgplPath); font.SetSize(be_bold_font->Size() + 4); font.SetFace(B_BOLD_FACE); fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuGreen); fCreditsView->Insert(B_TRANSLATE("\nCopyrights\n\n")); fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey); fCreditsView->Insert(B_TRANSLATE("[Click a license name to read the " "respective license.]\n\n")); // Haiku license BString haikuLicense = B_TRANSLATE_COMMENT("The code that is unique to " "Haiku, especially the kernel and all code that applications may link " "against, is distributed under the terms of the <MIT license>. " "Some system libraries contain third party code distributed under the " "<LGPL license>. You can find the copyrights to third party code below." "\n\n", "<MIT license> and <LGPL license> aren't variables and can be " "translated. However, please, don't remove < and > as they're needed " "as placeholders for proper hypertext functionality."); int32 licensePart1 = haikuLicense.FindFirst("<"); int32 licensePart2 = haikuLicense.FindFirst(">"); int32 licensePart3 = haikuLicense.FindLast("<"); int32 licensePart4 = haikuLicense.FindLast(">"); BString part; haikuLicense.CopyInto(part, 0, licensePart1); fCreditsView->Insert(part); part.Truncate(0); haikuLicense.CopyInto(part, licensePart1 + 1, licensePart2 - 1 - licensePart1); fCreditsView->InsertHyperText(part, new OpenFileAction(mitPath.Path())); part.Truncate(0); haikuLicense.CopyInto(part, licensePart2 + 1, licensePart3 - 1 - licensePart2); fCreditsView->Insert(part); part.Truncate(0); haikuLicense.CopyInto(part, licensePart3 + 1, licensePart4 - 1 - licensePart3); fCreditsView->InsertHyperText(part, new OpenFileAction(lgplPath.Path())); part.Truncate(0); haikuLicense.CopyInto(part, licensePart4 + 1, haikuLicense.Length() - 1 - licensePart4); fCreditsView->Insert(part); // GNU copyrights AddCopyrightEntry("The GNU Project", B_TRANSLATE("Contains software from the GNU Project, " "released under the GPL and LGPL licenses:\n" "GNU C Library, " "GNU coretools, diffutils, findutils, " "sharutils, gawk, bison, m4, make, " "gdb, wget, ncurses, termcap, " "Bourne Again Shell.\n" COPYRIGHT_STRING "The Free Software Foundation."), StringVector("GNU LGPL v2.1", "GNU GPL v2", "GNU GPL v3", NULL), StringVector(), "http://www.gnu.org"); // FreeBSD copyrights AddCopyrightEntry("The FreeBSD Project", B_TRANSLATE("Contains software from the FreeBSD Project, " "released under the BSD license:\n" "cal, ftpd, ping, telnet, " "telnetd, traceroute\n" COPYRIGHT_STRING "1994-2008 The FreeBSD Project. " "All rights reserved."), StringVector("BSD (2-clause)", "BSD (3-clause)", "BSD (4-clause)", NULL), StringVector(), "http://www.freebsd.org"); // NetBSD copyrights AddCopyrightEntry("The NetBSD Project", B_TRANSLATE("Contains software developed by the NetBSD " "Foundation, Inc. and its contributors:\n" "ftp, tput\n" COPYRIGHT_STRING "1996-2008 The NetBSD Foundation, Inc. " "All rights reserved."), "http://www.netbsd.org"); // TODO: License! // FFMpeg copyrights _AddPackageCredit(PackageCredit("FFMpeg libavcodec") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2000-2007 Fabrice " "Bellard, et al.")) .SetLicenses("GNU LGPL v2.1", "GNU LGPL v2", NULL) .SetURL("http://www.ffmpeg.org")); // AGG copyrights _AddPackageCredit(PackageCredit("AntiGrain Geometry") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2002-2006 Maxim " "Shemanarev (McSeem).")) .SetLicenses("Anti-Grain Geometry", B_TRANSLATE("BSD (3-clause)"), "GPC", NULL) .SetURL("http://www.antigrain.com")); // PDFLib copyrights _AddPackageCredit(PackageCredit("PDFLib") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1997-2006 PDFlib GmbH and " "Thomas Merz. All rights reserved.\n" "PDFlib and PDFlib logo are registered trademarks of PDFlib GmbH.")) .SetLicense("PDFlib Lite") .SetURL("http://www.pdflib.com")); // FreeType copyrights _AddPackageCredit(PackageCredit("FreeType2") .SetCopyright(B_TRANSLATE("Portions of this software are under " "copyright.\n" COPYRIGHT_STRING "1996-2006 " "The FreeType Project. All rights reserved.")) .SetLicense("FTL") .SetURL("http://www.freetype.org")); // Mesa3D (http://www.mesa3d.org) copyrights _AddPackageCredit(PackageCredit("Mesa") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1999-2006 Brian Paul. " "Mesa3D Project. All rights reserved.")) .SetLicense("MIT") .SetURL("http://www.mesa3d.org")); // SGI's GLU implementation copyrights _AddPackageCredit(PackageCredit("GLU") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1991-2000 " "Silicon Graphics, Inc. All rights reserved.")) .SetLicense("SGI Free B") .SetURL("http://www.sgi.com/products/software/opengl")); // GLUT implementation copyrights _AddPackageCredit(PackageCredit("GLUT") .SetCopyrights(B_TRANSLATE(COPYRIGHT_STRING "1994-1997 Mark Kilgard. " "All rights reserved."), COPYRIGHT_STRING "1997 Be Inc.", COPYRIGHT_STRING "1999 Jake Hamby.", NULL) .SetLicense("GLUT (Mark Kilgard)") .SetURL("http://www.opengl.org/resources/libraries/glut")); // OpenGroup & DEC (BRegion backend) copyright _AddPackageCredit(PackageCredit("BRegion backend (XFree86)") .SetCopyrights(COPYRIGHT_STRING "1987-1988, 1998 The Open Group.", B_TRANSLATE(COPYRIGHT_STRING "1987-1988 Digital Equipment " "Corporation, Maynard, Massachusetts.\n" "All rights reserved."), NULL) .SetLicenses("OpenGroup", "DEC", NULL)); // TODO: URL // VL-Gothic font _AddPackageCredit(PackageCredit("VL-Gothic font") .SetCopyrights(B_TRANSLATE(COPYRIGHT_STRING "1990-2003 Wada Laboratory," " the University of Tokyo."), COPYRIGHT_STRING "2003-2004 Electronic Font Open Laboratory (/efont/).", COPYRIGHT_STRING "2003-2008 M+ FONTS PROJECT.", COPYRIGHT_STRING "2006-2009 Daisuke SUZUKI.", COPYRIGHT_STRING "2006-2009 Project Vine.", B_TRANSLATE("MIT license. All rights reserved."), NULL) .SetLicense("BSD (3-clause)") .SetURL("http://vlgothic.dicey.org/")); // expat copyrights _AddPackageCredit(PackageCredit("expat") .SetCopyrights(B_TRANSLATE(COPYRIGHT_STRING "1998-2000 Thai " "Open Source Software Center Ltd and Clark Cooper."), B_TRANSLATE(COPYRIGHT_STRING "2001-2003 Expat maintainers."), NULL) .SetLicense("Expat") .SetURL("http://expat.sourceforge.net")); // zlib copyrights _AddPackageCredit(PackageCredit("zlib") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1995-2004 Jean-loup " "Gailly and Mark Adler.")) .SetLicense("Zlib") .SetURL("http://www.zlib.net")); // zip copyrights _AddPackageCredit(PackageCredit("Info-ZIP") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1990-2002 Info-ZIP. " "All rights reserved.")) .SetLicense("Info-ZIP") .SetURL("http://www.info-zip.org")); // bzip2 copyrights _AddPackageCredit(PackageCredit("bzip2") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1996-2005 Julian R " "Seward. All rights reserved.")) .SetLicense(B_TRANSLATE("BSD (4-clause)")) .SetURL("http://bzip.org")); // lp_solve copyrights _AddPackageCredit(PackageCredit("lp_solve") .SetCopyright(COPYRIGHT_STRING "Michel Berkelaar, Kjell Eikland, Peter Notebaert") .SetLicense("GNU LGPL v2.1") .SetURL("http://lpsolve.sourceforge.net/")); // OpenEXR copyrights _AddPackageCredit(PackageCredit("OpenEXR") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2002-2005 Industrial " "Light & Magic, a division of Lucas Digital Ltd. LLC.")) .SetLicense(B_TRANSLATE("BSD (3-clause)")) .SetURL("http://www.openexr.com")); // Bullet copyrights _AddPackageCredit(PackageCredit("Bullet") .SetCopyright(COPYRIGHT_STRING "2003-2008 Erwin Coumans") .SetLicense("Bullet") .SetURL("http://www.bulletphysics.com")); // atftp copyrights _AddPackageCredit(PackageCredit("atftp") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2000 Jean-Pierre " "ervbefeL and Remi Lefebvre.")) .SetLicense("GNU GPL v2") .SetURL("http://freecode.com/projects/atftp")); // Netcat copyrights _AddPackageCredit(PackageCredit("Netcat") .SetCopyright(COPYRIGHT_STRING "1996 Hobbit.") .SetLicense("Public Domain") .SetURL("http://nc110.sourceforge.net/")); // acpica copyrights _AddPackageCredit(PackageCredit("acpica") .SetCopyright(COPYRIGHT_STRING "1999-2006 Intel Corp.") .SetLicense("Intel (ACPICA)") .SetURL("http://www.acpica.org")); // unrar copyrights _AddPackageCredit(PackageCredit("unrar") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2002-2008 Alexander " "L. Roshal. All rights reserved.")) .SetLicense("UnRAR") .SetURL("http://www.rarlab.com")); // libpng copyrights _AddPackageCredit(PackageCredit("libpng") .SetCopyright(COPYRIGHT_STRING "2004, 2006-2008 Glenn " "Randers-Pehrson.") .SetLicense("LibPNG") .SetURL("http://www.libpng.org")); // libjpeg copyrights _AddPackageCredit(PackageCredit("libjpeg") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1994-2009, Thomas G. " "Lane, Guido Vollbeding. This software is based in part on the " "work of the Independent JPEG Group.")) .SetLicense("LibJPEG") .SetURL("http://www.ijg.org")); // libprint copyrights _AddPackageCredit(PackageCredit("libprint") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1999-2000 Y.Takagi. " "All rights reserved."))); // TODO: License! // cortex copyrights _AddPackageCredit(PackageCredit("Cortex") .SetCopyright(COPYRIGHT_STRING "1999-2000 Eric Moon.") .SetLicense(B_TRANSLATE("BSD (3-clause)")) .SetURL("http://cortex.sourceforge.net/documentation")); // FluidSynth copyrights _AddPackageCredit(PackageCredit("FluidSynth") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2003 Peter Hanappe " "and others.")) .SetLicense("GNU LGPL v2") .SetURL("http://www.fluidsynth.org")); // CannaIM copyrights _AddPackageCredit(PackageCredit("CannaIM") .SetCopyright(COPYRIGHT_STRING "1999 Masao Kawamura.") .SetLicense("MIT")); // libxml2, libxslt, libexslt copyrights _AddPackageCredit(PackageCredit("libxml2, libxslt") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1998-2003 Daniel Veillard. " "All rights reserved.")) .SetLicense(B_TRANSLATE("MIT (no promotion)")) .SetURL("http://xmlsoft.org")); _AddPackageCredit(PackageCredit("libexslt") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2001-2002 Thomas Broyer, " "Charlie Bozeman and Daniel Veillard. All rights reserved.")) .SetLicense(B_TRANSLATE("MIT (no promotion)")) .SetURL("http://xmlsoft.org")); // Xiph.org Foundation copyrights _AddPackageCredit(PackageCredit("Xiph.org Foundation") .SetCopyrights("libvorbis, libogg, libtheora, libspeex", B_TRANSLATE(COPYRIGHT_STRING "1994-2008 Xiph.Org. " "All rights reserved."), NULL) .SetLicense(B_TRANSLATE("BSD (3-clause)")) .SetURL("http://www.xiph.org")); // The Tcpdump Group _AddPackageCredit(PackageCredit("The Tcpdump Group") .SetCopyright("tcpdump, libpcap") .SetLicense(B_TRANSLATE("BSD (3-clause)")) .SetURL("http://www.tcpdump.org")); // Matroska _AddPackageCredit(PackageCredit("libmatroska") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2002-2003 Steve Lhomme. " "All rights reserved.")) .SetLicense("GNU LGPL v2.1") .SetURL("http://www.matroska.org")); // BColorQuantizer (originally CQuantizer code) _AddPackageCredit(PackageCredit("CQuantizer") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1996-1997 Jeff Prosise. " "All rights reserved.")) .SetLicense("CQuantizer") .SetURL("http://www.xdp.it")); // MAPM (Mike's Arbitrary Precision Math Library) used by DeskCalc _AddPackageCredit(PackageCredit("MAPM") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1999-2007 Michael C. " "Ring. All rights reserved.")) .SetLicense("MAPM") .SetURL("http://tc.umn.edu/~ringx004")); // MkDepend 1.7 copyright (Makefile dependency generator) _AddPackageCredit(PackageCredit("MkDepend") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1995-2001 Lars Düning. " "All rights reserved.")) .SetLicense("MkDepend") .SetURL("http://bearnip.com/lars/be")); // libhttpd copyright (used as Poorman backend) _AddPackageCredit(PackageCredit("libhttpd") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1995, 1998-2001 " "Jef Poskanzer. All rights reserved.")) .SetLicense("LibHTTPd") .SetURL("http://www.acme.com/software/thttpd/")); #ifdef __INTEL__ // Udis86 copyrights _AddPackageCredit(PackageCredit("Udis86") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2002-2004 " "Vivek Mohan. All rights reserved.")) .SetLicense(B_TRANSLATE("BSD (2-clause)")) .SetURL("http://udis86.sourceforge.net")); #endif #ifdef __INTEL__ // Intel PRO/Wireless 2100 Firmware _AddPackageCredit(PackageCredit("Intel PRO/Wireless 2100 Firmware") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2003-2006 " "Intel Corporation. All rights reserved.")) .SetLicense("Intel (2xxx firmware)") .SetURL("http://ipw2100.sourceforge.net/")); #endif #ifdef __INTEL__ // Intel PRO/Wireless 2200BG Firmware _AddPackageCredit(PackageCredit("Intel PRO/Wireless 2200BG Firmware") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2004-2005 " "Intel Corporation. All rights reserved.")) .SetLicense("Intel (2xxx firmware)") .SetURL("http://ipw2200.sourceforge.net/")); #endif #ifdef __INTEL__ // Intel PRO/Wireless 3945ABG/BG Network Connection Adapter Firmware _AddPackageCredit( PackageCredit( "Intel PRO/Wireless 3945ABG/BG Network Connection Adapter Firmware") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2006-2007 " "Intel Corporation. All rights reserved.")) .SetLicense("Intel (firmware)") .SetURL("http://www.intellinuxwireless.org/")); #endif #ifdef __INTEL__ // Intel Wireless WiFi Link 4965AGN Adapter Firmware _AddPackageCredit( PackageCredit("Intel Wireless WiFi Link 4965AGN Adapter Firmware") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2006-2007 " "Intel Corporation. All rights reserved.")) .SetLicense("Intel (firmware)") .SetURL("http://www.intellinuxwireless.org/")); #endif #ifdef __INTEL__ // Marvell 88w8363 _AddPackageCredit(PackageCredit("Marvell 88w8363") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2007-2009 " "Marvell Semiconductor, Inc. All rights reserved.")) .SetLicense("Marvell (firmware)") .SetURL("http://www.marvell.com/")); #endif #ifdef __INTEL__ // Ralink Firmware RT2501/RT2561/RT2661 _AddPackageCredit(PackageCredit("Ralink Firmware RT2501/RT2561/RT2661") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2007 " "Ralink Technology Corporation. All rights reserved.")) .SetLicense("Ralink (firmware)") .SetURL("http://www.ralinktech.com/")); #endif // Gutenprint _AddPackageCredit(PackageCredit("Gutenprint") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "1999-2010 by the authors of Gutenprint. All rights reserved.")) .SetLicense("GNU GPL v2") .SetURL("http://gutenprint.sourceforge.net/")); // libwebp _AddPackageCredit(PackageCredit("libwebp") .SetCopyright(B_TRANSLATE(COPYRIGHT_STRING "2010-2011 Google Inc. All rights reserved.")) .SetLicense(B_TRANSLATE("BSD (3-clause)")) .SetURL("http://www.webmproject.org/code/#libwebp_webp_image_library")); // GTF _AddPackageCredit(PackageCredit("GTF") .SetCopyright(B_TRANSLATE("2001 by Andy Ritger based on the " "Generalized Timing Formula")) .SetLicense(B_TRANSLATE("BSD (3-clause)")) .SetURL("http://gtf.sourceforge.net/")); _AddCopyrightsFromAttribute(); _AddPackageCreditEntries(); return new CropView(creditsScroller, 0, 1, 1, 1); }
status_t WorkerThread::_PerformInstall(partition_id sourcePartitionID, partition_id targetPartitionID) { CALLED(); BPath targetDirectory; BPath srcDirectory; BPath trashPath; BPath testPath; BDirectory targetDir; BDiskDevice device; BPartition* partition; BVolume targetVolume; status_t err = B_OK; int32 entries = 0; entry_ref testRef; const char* mountError = B_TRANSLATE("The disk can't be mounted. Please " "choose a different disk."); if (sourcePartitionID < 0 || targetPartitionID < 0) { ERR("bad source or target partition ID\n"); return _InstallationError(err); } // check if target is initialized // ask if init or mount as is if (fDDRoster.GetPartitionWithID(targetPartitionID, &device, &partition) == B_OK) { if (!partition->IsMounted()) { if ((err = partition->Mount()) < B_OK) { _SetStatusMessage(mountError); ERR("BPartition::Mount"); return _InstallationError(err); } } if ((err = partition->GetVolume(&targetVolume)) != B_OK) { ERR("BPartition::GetVolume"); return _InstallationError(err); } if ((err = partition->GetMountPoint(&targetDirectory)) != B_OK) { ERR("BPartition::GetMountPoint"); return _InstallationError(err); } } else if (fDDRoster.GetDeviceWithID(targetPartitionID, &device) == B_OK) { if (!device.IsMounted()) { if ((err = device.Mount()) < B_OK) { _SetStatusMessage(mountError); ERR("BDiskDevice::Mount"); return _InstallationError(err); } } if ((err = device.GetVolume(&targetVolume)) != B_OK) { ERR("BDiskDevice::GetVolume"); return _InstallationError(err); } if ((err = device.GetMountPoint(&targetDirectory)) != B_OK) { ERR("BDiskDevice::GetMountPoint"); return _InstallationError(err); } } else return _InstallationError(err); // shouldn't happen // check if target has enough space if (fSpaceRequired > 0 && targetVolume.FreeBytes() < fSpaceRequired) { BAlert* alert = new BAlert("", B_TRANSLATE("The destination disk may " "not have enough space. Try choosing a different disk or choose " "to not install optional items."), B_TRANSLATE("Try installing anyway"), B_TRANSLATE("Cancel"), 0, B_WIDTH_AS_USUAL, B_STOP_ALERT); alert->SetShortcut(1, B_ESCAPE); if (alert->Go() != 0) return _InstallationError(err); } if (fDDRoster.GetPartitionWithID(sourcePartitionID, &device, &partition) == B_OK) { if ((err = partition->GetMountPoint(&srcDirectory)) != B_OK) { ERR("BPartition::GetMountPoint"); return _InstallationError(err); } } else if (fDDRoster.GetDeviceWithID(sourcePartitionID, &device) == B_OK) { if ((err = device.GetMountPoint(&srcDirectory)) != B_OK) { ERR("BDiskDevice::GetMountPoint"); return _InstallationError(err); } } else return _InstallationError(err); // shouldn't happen // check not installing on itself if (strcmp(srcDirectory.Path(), targetDirectory.Path()) == 0) { _SetStatusMessage(B_TRANSLATE("You can't install the contents of a " "disk onto itself. Please choose a different disk.")); return _InstallationError(err); } // check not installing on boot volume if (strncmp(BOOT_PATH, targetDirectory.Path(), strlen(BOOT_PATH)) == 0) { BAlert* alert = new BAlert("", B_TRANSLATE("Are you sure you want to " "install onto the current boot disk? The Installer will have to " "reboot your machine if you proceed."), B_TRANSLATE("OK"), B_TRANSLATE("Cancel"), 0, B_WIDTH_AS_USUAL, B_STOP_ALERT); alert->SetShortcut(1, B_ESCAPE); if (alert->Go() != 0) { _SetStatusMessage("Installation stopped."); return _InstallationError(err); } } // check if target volume's trash dir has anything in it // (target volume w/ only an empty trash dir is considered // an empty volume) if (find_directory(B_TRASH_DIRECTORY, &trashPath, false, &targetVolume) == B_OK && targetDir.SetTo(trashPath.Path()) == B_OK) { while (targetDir.GetNextRef(&testRef) == B_OK) { // Something in the Trash entries++; break; } } targetDir.SetTo(targetDirectory.Path()); // check if target volume otherwise has any entries while (entries == 0 && targetDir.GetNextRef(&testRef) == B_OK) { if (testPath.SetTo(&testRef) == B_OK && testPath != trashPath) entries++; } if (entries != 0) { BAlert* alert = new BAlert("", B_TRANSLATE("The target volume is not " "empty. Are you sure you want to install anyway?\n\nNote: The " "'system' folder will be a clean copy from the source volume but " "will retain its settings folder, all other folders will be " "merged, whereas files and links that exist on both the source " "and target volume will be overwritten with the source volume " "version."), B_TRANSLATE("Install anyway"), B_TRANSLATE("Cancel"), 0, B_WIDTH_AS_USUAL, B_STOP_ALERT); alert->SetShortcut(1, B_ESCAPE); if (alert->Go() != 0) { // TODO: Would be cool to offer the option here to clean additional // folders at the user's choice. return _InstallationError(B_CANCELED); } } // Begin actual installation ProgressReporter reporter(fOwner, new BMessage(MSG_STATUS_MESSAGE)); EntryFilter entryFilter(srcDirectory.Path()); CopyEngine engine(&reporter, &entryFilter); BList unzipEngines; err = _LaunchInitScript(targetDirectory); if (err != B_OK) return _InstallationError(err); // Create the default indices which should always be present on a proper // boot volume. We don't care if the source volume does not have them. // After all, the user might be re-installing to another drive and may // want problems fixed along the way... err = _CreateDefaultIndices(targetDirectory); if (err != B_OK) return _InstallationError(err); // Mirror all the indices which are present on the source volume onto // the target volume. err = _MirrorIndices(srcDirectory, targetDirectory); if (err != B_OK) return _InstallationError(err); // Let the engine collect information for the progress bar later on engine.ResetTargets(srcDirectory.Path()); err = engine.CollectTargets(srcDirectory.Path(), fCancelSemaphore); if (err != B_OK) return _InstallationError(err); // Collect selected packages also if (fPackages) { BPath pkgRootDir(srcDirectory.Path(), kPackagesDirectoryPath); int32 count = fPackages->CountItems(); for (int32 i = 0; i < count; i++) { Package *p = static_cast<Package*>(fPackages->ItemAt(i)); BPath packageDir(pkgRootDir.Path(), p->Folder()); err = engine.CollectTargets(packageDir.Path(), fCancelSemaphore); if (err != B_OK) return _InstallationError(err); } } // collect information about all zip packages err = _ProcessZipPackages(srcDirectory.Path(), targetDirectory.Path(), &reporter, unzipEngines); if (err != B_OK) return _InstallationError(err); reporter.StartTimer(); // copy source volume err = engine.CopyFolder(srcDirectory.Path(), targetDirectory.Path(), fCancelSemaphore); if (err != B_OK) return _InstallationError(err); // copy selected packages if (fPackages) { BPath pkgRootDir(srcDirectory.Path(), kPackagesDirectoryPath); int32 count = fPackages->CountItems(); for (int32 i = 0; i < count; i++) { Package *p = static_cast<Package*>(fPackages->ItemAt(i)); BPath packageDir(pkgRootDir.Path(), p->Folder()); err = engine.CopyFolder(packageDir.Path(), targetDirectory.Path(), fCancelSemaphore); if (err != B_OK) return _InstallationError(err); } } // Extract all zip packages. If an error occured, delete the rest of // the engines, but stop extracting. for (int32 i = 0; i < unzipEngines.CountItems(); i++) { UnzipEngine* engine = reinterpret_cast<UnzipEngine*>( unzipEngines.ItemAtFast(i)); if (err == B_OK) err = engine->UnzipPackage(); delete engine; } if (err != B_OK) return _InstallationError(err); err = _LaunchFinishScript(targetDirectory); if (err != B_OK) return _InstallationError(err); fOwner.SendMessage(MSG_INSTALL_FINISHED); return B_OK; }
AboutView::AboutView() : BView("aboutview", B_WILL_DRAW | B_PULSE_NEEDED), fLastActionTime(system_time()), fScrollRunner(NULL) { // Begin Construction of System Information controls system_info systemInfo; get_system_info(&systemInfo); // Create all the various labels for system infomation // OS Version char string[1024]; strlcpy(string, B_TRANSLATE("Unknown"), sizeof(string)); // the version is stored in the BEOS:APP_VERSION attribute of libbe.so BPath path; if (find_directory(B_BEOS_LIB_DIRECTORY, &path) == B_OK) { path.Append("libbe.so"); BAppFileInfo appFileInfo; version_info versionInfo; BFile file; if (file.SetTo(path.Path(), B_READ_ONLY) == B_OK && appFileInfo.SetTo(&file) == B_OK && appFileInfo.GetVersionInfo(&versionInfo, B_APP_VERSION_KIND) == B_OK && versionInfo.short_info[0] != '\0') strlcpy(string, versionInfo.short_info, sizeof(string)); } // Add system revision const char* haikuRevision = __get_haiku_revision(); if (haikuRevision != NULL) { strlcat(string, " (", sizeof(string)); strlcat(string, B_TRANSLATE("Revision"), sizeof(string)); strlcat(string, " ", sizeof(string)); strlcat(string, haikuRevision, sizeof(string)); strlcat(string, ")", sizeof(string)); } BStringView* versionView = new BStringView("ostext", string); versionView->SetExplicitAlignment(BAlignment(B_ALIGN_LEFT, B_ALIGN_VERTICAL_UNSET)); // GCC version BEntry gccFourHybrid("/boot/system/lib/gcc2/libstdc++.r4.so"); BEntry gccTwoHybrid("/boot/system/lib/gcc4/libsupc++.so"); bool isHybrid = gccFourHybrid.Exists() || gccTwoHybrid.Exists(); if (isHybrid) { snprintf(string, sizeof(string), B_TRANSLATE("GCC %d Hybrid"), __GNUC__); } else snprintf(string, sizeof(string), "GCC %d", __GNUC__); BStringView* gccView = new BStringView("gcctext", string); gccView->SetExplicitAlignment(BAlignment(B_ALIGN_LEFT, B_ALIGN_VERTICAL_UNSET)); #if __GNUC__ == 2 if (isHybrid) { // do now show the GCC version if it's the default gccView->Hide(); } #endif // CPU count, type and clock speed char processorLabel[256]; if (systemInfo.cpu_count > 1) { snprintf(processorLabel, sizeof(processorLabel), B_TRANSLATE("%ld Processors:"), systemInfo.cpu_count); } else strlcpy(processorLabel, B_TRANSLATE("Processor:"), sizeof(processorLabel)); BString cpuType; cpuType << get_cpu_vendor_string(systemInfo.cpu_type) << " " << get_cpu_model_string(&systemInfo); BStringView* cpuView = new BStringView("cputext", cpuType.String()); cpuView->SetExplicitAlignment(BAlignment(B_ALIGN_LEFT, B_ALIGN_VERTICAL_UNSET)); int32 clockSpeed = get_rounded_cpu_speed(); if (clockSpeed < 1000) snprintf(string, sizeof(string), B_TRANSLATE("%ld MHz"), clockSpeed); else snprintf(string, sizeof(string), B_TRANSLATE("%.2f GHz"), clockSpeed / 1000.0f); BStringView* frequencyView = new BStringView("frequencytext", string); frequencyView->SetExplicitAlignment(BAlignment(B_ALIGN_LEFT, B_ALIGN_VERTICAL_UNSET)); // RAM BStringView *memSizeView = new BStringView("ramsizetext", MemSizeToString(string, sizeof(string), &systemInfo)); memSizeView->SetExplicitAlignment(BAlignment(B_ALIGN_LEFT, B_ALIGN_VERTICAL_UNSET)); fMemView = new BStringView("ramtext", MemUsageToString(string, sizeof(string), &systemInfo)); fMemView->SetExplicitAlignment(BAlignment(B_ALIGN_LEFT, B_ALIGN_VERTICAL_UNSET)); // Kernel build time/date snprintf(string, sizeof(string), "%s %s", systemInfo.kernel_build_date, systemInfo.kernel_build_time); BStringView* kernelView = new BStringView("kerneltext", string); kernelView->SetExplicitAlignment(BAlignment(B_ALIGN_LEFT, B_ALIGN_VERTICAL_UNSET)); // Uptime fUptimeView = new BTextView("uptimetext"); fUptimeView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); fUptimeView->MakeEditable(false); fUptimeView->MakeSelectable(false); fUptimeView->SetWordWrap(true); fUptimeView->SetText(UptimeToString(string, sizeof(string))); const float offset = 5; SetLayout(new BGroupLayout(B_HORIZONTAL, 0)); SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); BLayoutBuilder::Group<>((BGroupLayout*)GetLayout()) .AddGroup(B_VERTICAL, 0) .Add(new LogoView()) .AddGroup(B_VERTICAL, 0) .Add(_CreateLabel("oslabel", B_TRANSLATE("Version:"))) .Add(versionView) .Add(gccView) .AddStrut(offset) .Add(_CreateLabel("cpulabel", processorLabel)) .Add(cpuView) .Add(frequencyView) .AddStrut(offset) .Add(_CreateLabel("memlabel", B_TRANSLATE("Memory:"))) .Add(memSizeView) .Add(fMemView) .AddStrut(offset) .Add(_CreateLabel("kernellabel", B_TRANSLATE("Kernel:"))) .Add(kernelView) .AddStrut(offset) .Add(_CreateLabel("uptimelabel", B_TRANSLATE("Time running:"))) .Add(fUptimeView) .SetInsets(5, 5, 5, 5) .End() // TODO: investigate: adding this causes the time to be cut //.AddGlue() .End() .Add(_CreateCreditsView()); float min = fMemView->MinSize().width * 1.1f; fCreditsView->SetExplicitMinSize(BSize(min, min)); }
void AboutView::AddCopyrightEntry(const char* name, const char* text, const StringVector& licenses, const StringVector& sources, const char* url) { BFont font(be_bold_font); //font.SetSize(be_bold_font->Size()); font.SetFace(B_BOLD_FACE | B_ITALIC_FACE); fCreditsView->SetFontAndColor(&font, B_FONT_ALL, &kHaikuYellow); fCreditsView->Insert(name); fCreditsView->Insert("\n"); fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kDarkGrey); fCreditsView->Insert(text); fCreditsView->Insert("\n"); if (licenses.CountStrings() > 0) { if (licenses.CountStrings() > 1) fCreditsView->Insert(B_TRANSLATE("Licenses: ")); else fCreditsView->Insert(B_TRANSLATE("License: ")); for (int32 i = 0; i < licenses.CountStrings(); i++) { const char* license = licenses.StringAt(i); if (i > 0) fCreditsView->Insert(", "); BString licenseName; BString licenseURL; parse_named_url(license, licenseName, licenseURL); BPath licensePath; if (_GetLicensePath(licenseURL, licensePath) == B_OK) { fCreditsView->InsertHyperText(licenseName, new OpenFileAction(licensePath.Path())); } else fCreditsView->Insert(licenseName); } fCreditsView->Insert("\n"); } if (sources.CountStrings() > 0) { fCreditsView->Insert(B_TRANSLATE("Source Code: ")); for (int32 i = 0; i < sources.CountStrings(); i++) { const char* source = sources.StringAt(i); if (i > 0) fCreditsView->Insert(", "); BString urlName; BString urlAddress; parse_named_url(source, urlName, urlAddress); fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kLinkBlue); fCreditsView->InsertHyperText(urlName, new URLAction(urlAddress)); } fCreditsView->Insert("\n"); } if (url) { BString urlName; BString urlAddress; parse_named_url(url, urlName, urlAddress); fCreditsView->SetFontAndColor(be_plain_font, B_FONT_ALL, &kLinkBlue); fCreditsView->InsertHyperText(urlName, new URLAction(urlAddress)); fCreditsView->Insert("\n"); } fCreditsView->Insert("\n"); }
KeymapWindow::KeymapWindow() : BWindow(BRect(80, 50, 880, 380), B_TRANSLATE_SYSTEM_NAME("Keymap"), B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS) { SetLayout(new BGroupLayout(B_VERTICAL)); fKeyboardLayoutView = new KeyboardLayoutView("layout"); fKeyboardLayoutView->SetKeymap(&fCurrentMap); fTextControl = new BTextControl(B_TRANSLATE("Sample and clipboard:"), "", NULL); fSwitchShortcutsButton = new BButton("switch", "", new BMessage(kMsgSwitchShortcuts)); fRevertButton = new BButton("revertButton", B_TRANSLATE("Revert"), new BMessage(kMsgRevertKeymap)); // controls pane AddChild(BGroupLayoutBuilder(B_VERTICAL) .Add(_CreateMenu()) .Add(BGroupLayoutBuilder(B_HORIZONTAL, 10) .Add(_CreateMapLists(), 0.25) .Add(BGroupLayoutBuilder(B_VERTICAL, 10) .Add(fKeyboardLayoutView) //.Add(new BStringView("text label", "Sample and clipboard:")) .Add(BGroupLayoutBuilder(B_HORIZONTAL, 10) .Add(_CreateDeadKeyMenuField(), 0.0) .AddGlue() .Add(fSwitchShortcutsButton)) .Add(fTextControl) .AddGlue(0.0) .Add(BGroupLayoutBuilder(B_HORIZONTAL, 10) .AddGlue(0.0) .Add(fRevertButton))) .SetInsets(10, 10, 10, 10))); fKeyboardLayoutView->SetTarget(fTextControl->TextView()); fTextControl->MakeFocus(); // Make sure the user keymap directory exists BPath path; find_directory(B_USER_SETTINGS_DIRECTORY, &path); path.Append("Keymap"); entry_ref ref; get_ref_for_path(path.Path(), &ref); BDirectory userKeymapsDir(&ref); if (userKeymapsDir.InitCheck() != B_OK) create_directory(path.Path(), S_IRWXU | S_IRWXG | S_IRWXO); BMessenger messenger(this); fOpenPanel = new BFilePanel(B_OPEN_PANEL, &messenger, &ref, B_FILE_NODE, false, NULL); fSavePanel = new BFilePanel(B_SAVE_PANEL, &messenger, &ref, B_FILE_NODE, false, NULL); BRect windowFrame; BString keyboardLayout; _LoadSettings(windowFrame, keyboardLayout); _SetKeyboardLayout(keyboardLayout.String()); ResizeTo(windowFrame.Width(), windowFrame.Height()); MoveTo(windowFrame.LeftTop()); // TODO: this might be a bug in the interface kit, but scrolling to // selection does not correctly work unless the window is shown. Show(); Lock(); // Try and find the current map name in the two list views (if the name // was read at all) _SelectCurrentMap(); KeymapListItem* current = static_cast<KeymapListItem*>(fUserListView->FirstItem()); fCurrentMap.Load(current->EntryRef()); fPreviousMap = fCurrentMap; fAppliedMap = fCurrentMap; fCurrentMap.SetTarget(this, new BMessage(kMsgKeymapUpdated)); _UpdateButtons(); _UpdateDeadKeyMenu(); _UpdateSwitchShortcutButton(); Unlock(); }
void KeymapWindow::MessageReceived(BMessage* message) { switch (message->what) { case B_SIMPLE_DATA: case B_REFS_RECEIVED: { entry_ref ref; int32 i = 0; while (message->FindRef("refs", i++, &ref) == B_OK) { fCurrentMap.Load(ref); fAppliedMap = fCurrentMap; } fKeyboardLayoutView->SetKeymap(&fCurrentMap); fSystemListView->DeselectAll(); fUserListView->DeselectAll(); break; } case B_SAVE_REQUESTED: { entry_ref ref; const char *name; if (message->FindRef("directory", &ref) == B_OK && message->FindString("name", &name) == B_OK) { BDirectory directory(&ref); BEntry entry(&directory, name); entry.GetRef(&ref); fCurrentMap.SetName(name); fCurrentMap.Save(ref); fAppliedMap = fCurrentMap; _FillUserMaps(); fCurrentMapName = name; _SelectCurrentMap(); } break; } case kMsgMenuFileOpen: fOpenPanel->Show(); break; case kMsgMenuFileSaveAs: fSavePanel->Show(); break; case kMsgShowModifierKeysWindow: be_app->PostMessage(kMsgShowModifierKeysWindow); break; case kChangeKeyboardLayout: { entry_ref ref; BPath path; if (message->FindRef("ref", &ref) == B_OK) path.SetTo(&ref); _SetKeyboardLayout(path.Path()); break; } case kMsgSwitchShortcuts: _SwitchShortcutKeys(); break; case kMsgMenuFontChanged: { BMenuItem *item = fFontMenu->FindMarked(); if (item != NULL) { BFont font; font.SetFamilyAndStyle(item->Label(), NULL); fKeyboardLayoutView->SetBaseFont(font); fTextControl->TextView()->SetFontAndColor(&font); } break; } case kMsgSystemMapSelected: case kMsgUserMapSelected: { BListView* listView; BListView* otherListView; if (message->what == kMsgSystemMapSelected) { listView = fSystemListView; otherListView = fUserListView; } else { listView = fUserListView; otherListView = fSystemListView; } int32 index = listView->CurrentSelection(); if (index < 0) break; // Deselect item in other BListView otherListView->DeselectAll(); if (index == 0 && listView == fUserListView) { // we can safely ignore the "(Current)" item break; } KeymapListItem* item = static_cast<KeymapListItem*>(listView->ItemAt(index)); if (item != NULL) { fCurrentMap.Load(item->EntryRef()); fAppliedMap = fCurrentMap; fKeyboardLayoutView->SetKeymap(&fCurrentMap); _UseKeymap(); _UpdateButtons(); } break; } case kMsgRevertKeymap: _RevertKeymap(); _UpdateButtons(); break; case kMsgUpdateModifiers: { uint32 keycode; if (message->FindUInt32("caps_key", &keycode) == B_OK) fCurrentMap.Map().caps_key = keycode; if (message->FindUInt32("left_control_key", &keycode) == B_OK) fCurrentMap.Map().left_control_key = keycode; if (message->FindUInt32("right_control_key", &keycode) == B_OK) fCurrentMap.Map().right_control_key = keycode; if (message->FindUInt32("left_option_key", &keycode) == B_OK) fCurrentMap.Map().left_option_key = keycode; if (message->FindUInt32("right_option_key", &keycode) == B_OK) fCurrentMap.Map().right_option_key = keycode; if (message->FindUInt32("left_command_key", &keycode) == B_OK) fCurrentMap.Map().left_command_key = keycode; if (message->FindUInt32("right_command_key", &keycode) == B_OK) fCurrentMap.Map().right_command_key = keycode; _UpdateButtons(); fKeyboardLayoutView->SetKeymap(&fCurrentMap); break; } case kMsgKeymapUpdated: _UpdateButtons(); fSystemListView->DeselectAll(); fUserListView->Select(0L); break; case kMsgDeadKeyAcuteChanged: { BMenuItem* item = fAcuteMenu->FindMarked(); if (item != NULL) { const char* trigger = item->Label(); if (strcmp(trigger, kDeadKeyTriggerNone) == 0) trigger = NULL; fCurrentMap.SetDeadKeyTrigger(kDeadKeyAcute, trigger); fKeyboardLayoutView->Invalidate(); } break; } case kMsgDeadKeyCircumflexChanged: { BMenuItem* item = fCircumflexMenu->FindMarked(); if (item != NULL) { const char* trigger = item->Label(); if (strcmp(trigger, kDeadKeyTriggerNone) == 0) trigger = NULL; fCurrentMap.SetDeadKeyTrigger(kDeadKeyCircumflex, trigger); fKeyboardLayoutView->Invalidate(); } break; } case kMsgDeadKeyDiaeresisChanged: { BMenuItem* item = fDiaeresisMenu->FindMarked(); if (item != NULL) { const char* trigger = item->Label(); if (strcmp(trigger, kDeadKeyTriggerNone) == 0) trigger = NULL; fCurrentMap.SetDeadKeyTrigger(kDeadKeyDiaeresis, trigger); fKeyboardLayoutView->Invalidate(); } break; } case kMsgDeadKeyGraveChanged: { BMenuItem* item = fGraveMenu->FindMarked(); if (item != NULL) { const char* trigger = item->Label(); if (strcmp(trigger, kDeadKeyTriggerNone) == 0) trigger = NULL; fCurrentMap.SetDeadKeyTrigger(kDeadKeyGrave, trigger); fKeyboardLayoutView->Invalidate(); } break; } case kMsgDeadKeyTildeChanged: { BMenuItem* item = fTildeMenu->FindMarked(); if (item != NULL) { const char* trigger = item->Label(); if (strcmp(trigger, kDeadKeyTriggerNone) == 0) trigger = NULL; fCurrentMap.SetDeadKeyTrigger(kDeadKeyTilde, trigger); fKeyboardLayoutView->Invalidate(); } break; } default: BWindow::MessageReceived(message); break; } }
void TBarApp::InitSettings() { desk_settings settings; settings.vertical = true; settings.left = false; settings.top = true; settings.ampmMode = true; settings.showTime = true; settings.state = kExpandoState; settings.width = 0; settings.switcherLoc = BPoint(5000, 5000); settings.recentAppsCount = 10; settings.recentDocsCount = 10; settings.timeShowSeconds = false; settings.recentFoldersCount = 10; settings.alwaysOnTop = false; settings.timeFullDate = false; settings.trackerAlwaysFirst = false; settings.sortRunningApps = false; settings.superExpando = false; settings.expandNewTeams = false; settings.autoRaise = false; settings.autoHide = false; settings.recentAppsEnabled = true; settings.recentDocsEnabled = true; settings.recentFoldersEnabled = true; BPath dirPath; const char* settingsFileName = "Deskbar_settings"; find_directory(B_USER_DESKBAR_DIRECTORY, &dirPath, true); // just make it if (find_directory (B_USER_SETTINGS_DIRECTORY, &dirPath, true) == B_OK) { BPath filePath = dirPath; filePath.Append(settingsFileName); fSettingsFile = new BFile(filePath.Path(), O_RDWR); if (fSettingsFile->InitCheck() != B_OK) { BDirectory theDir(dirPath.Path()); if (theDir.InitCheck() == B_OK) theDir.CreateFile(settingsFileName, fSettingsFile); } BMessage storedSettings; if (fSettingsFile->InitCheck() == B_OK && storedSettings.Unflatten(fSettingsFile) == B_OK) { storedSettings.FindBool("vertical", &settings.vertical); storedSettings.FindBool("left", &settings.left); storedSettings.FindBool("top", &settings.top); storedSettings.FindBool("ampmMode", &settings.ampmMode); storedSettings.FindInt32("state", (int32*)&settings.state); storedSettings.FindFloat("width", &settings.width); storedSettings.FindBool("showTime", &settings.showTime); storedSettings.FindPoint("switcherLoc", &settings.switcherLoc); storedSettings.FindInt32("recentAppsCount", &settings.recentAppsCount); storedSettings.FindInt32("recentDocsCount", &settings.recentDocsCount); storedSettings.FindBool("timeShowSeconds", &settings.timeShowSeconds); storedSettings.FindInt32("recentFoldersCount", &settings.recentFoldersCount); storedSettings.FindBool("alwaysOnTop", &settings.alwaysOnTop); storedSettings.FindBool("timeFullDate", &settings.timeFullDate); storedSettings.FindBool("trackerAlwaysFirst", &settings.trackerAlwaysFirst); storedSettings.FindBool("sortRunningApps", &settings.sortRunningApps); storedSettings.FindBool("superExpando", &settings.superExpando); storedSettings.FindBool("expandNewTeams", &settings.expandNewTeams); storedSettings.FindBool("autoRaise", &settings.autoRaise); storedSettings.FindBool("autoHide", &settings.autoHide); storedSettings.FindBool("recentAppsEnabled", &settings.recentAppsEnabled); storedSettings.FindBool("recentDocsEnabled", &settings.recentDocsEnabled); storedSettings.FindBool("recentFoldersEnabled", &settings.recentFoldersEnabled); } } fSettings = settings; }
/*! \brief Constructor for the ActivityWindow class. * \param[in] data The data to be displayed. * \param[in] target The process to be notified about user's choise. * \param[in] name Name of the Event. * \param[in] category Category of the Event. * \param[in] templateMessage The message to be sent to the target. * If \c NULL is passed, then a new message is constructed * with \c kActivityWindowRepsonceMessage value in \c what. * \param[in] reminder \c true if the window is constructed for a reminder, else * \c false. Actually, it matters only for explanation to user. * Default is \c false (it's not a reminder). * \note A note on memory management: * \c data (the ActionData) belongs to the caller, but it's used only for * initialization of this window. I. e., if the user makes changes to the * data while an ActivityWindow is open, the changes won't be reflected. * However, \c target and \c templateMessage belong to this object. User * shouldn't free them or do anything else. */ ActivityWindow::ActivityWindow( ActivityData* data, BMessenger* target, BString name, Category* category, BMessage* templateMessage, bool reminder ) : BWindow( BRect( 0, 0, 400, 500 ), "Event occurred", B_FLOATING_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, B_NOT_MINIMIZABLE | B_NOT_ZOOMABLE | B_ASYNCHRONOUS_CONTROLS ), fTarget( target ), fData( data ), fTemplateMessage( templateMessage ), bIsReminder( reminder ), fLastError( B_OK ), fEventName( name ), fCategory( category ), fTitle( NULL ), fEventNameView( NULL ), fCategoryView( NULL ), fTextScroller( NULL ), fSnoozeTime( NULL ), fNoteText( NULL ), fSnooze( NULL ), fOk( NULL ) { BFont boldFont( be_bold_font ); BFont plainFont( be_plain_font ); BFont font; // For various font-related activities font_height fh; // For setting the height of the Text View with notification text plainFont.GetHeight( &fh ); int numberOfColumnsInLayout = 2; // Sanity check if ( !data || !target ) { /* Panic! */ fLastError = B_BAD_VALUE; return; } if ( ! fData->GetNotification( NULL ) && ! fData->GetSound( NULL ) && ! fData->GetProgram( NULL, NULL ) ) { // Nothing to do! This is not an error! fLastError = B_NO_INIT; return; } BView* background = new BView( Bounds(), "Background view", B_FOLLOW_ALL_SIDES, B_WILL_DRAW ); if ( !background ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } this->AddChild( background ); BGridLayout* gridLayout = new BGridLayout(); if ( !gridLayout ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } background->SetLayout( gridLayout ); background->SetViewColor( ui_color( B_PANEL_BACKGROUND_COLOR ) ); gridLayout->SetInsets( 5, 5, 5, 5 ); /*------------------------------------------------- * First line - explaining what's happening here *------------------------------------------------*/ BStringView* exp = new BStringView( BRect( 0, 0, 1, 1 ), "Explanation 1", ( bIsReminder ? "A Reminder has occured!" : "An Event has occured!" ) ); if ( ! exp ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } exp->SetFont( &boldFont ); exp->ResizeToPreferred(); BLayoutItem* layoutItem = gridLayout->AddView( exp, 0, 0, numberOfColumnsInLayout, 1 ); if ( layoutItem ) { layoutItem->SetExplicitAlignment( BAlignment( B_ALIGN_CENTER, B_ALIGN_TOP ) ); } /*----------------------------------------------------------------- * Second line - event's name on category's color as background *----------------------------------------------------------------*/ // Create background // Note: the pulse is requested for this Window to receive Pulse notifications. fBackground = new BView( BRect( 0, 0, 1, 1 ), "Background", B_FOLLOW_LEFT_RIGHT | B_FOLLOW_V_CENTER | B_PULSE_NEEDED, B_WILL_DRAW ); if ( !fBackground ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } fBackground->SetViewColor( ui_color( B_PANEL_BACKGROUND_COLOR ) ); layoutItem = gridLayout->AddView( fBackground, 0, 1, numberOfColumnsInLayout, 1 ); if ( layoutItem ) { layoutItem->SetExplicitAlignment( BAlignment( B_ALIGN_USE_FULL_WIDTH, B_ALIGN_USE_FULL_HEIGHT ) ); } BGroupLayout* bgLayout = new BGroupLayout( B_VERTICAL ); if ( !bgLayout ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } fBackground->SetLayout( bgLayout ); bgLayout->SetInsets( 15, 10, 15, 10 ); fBackground->SetViewColor( fCategory.categoryColor ); BString sb = "Category:\n"; sb << fCategory.categoryName; fBackground->SetToolTip( sb.String() ); // Create Event's name view fTitle = new BStringView( BRect( 0, 0, 1, 1 ), "Event name", fEventName.String(), B_FOLLOW_H_CENTER | B_FOLLOW_V_CENTER ); if ( !fTitle ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } // Use big bold font for Event's name fTitle->SetFont( be_bold_font ); fTitle->GetFont( &font ); font.SetSize( font.Size() + 2 ); fTitle->SetFont( &font, B_FONT_SIZE ); // Add the title and set its tooltip fTitle->ResizeToPreferred(); fTitle->SetToolTip( sb.String() ); bgLayout->AddView( fTitle ); fTitle->SetViewColor( ui_color( B_PANEL_BACKGROUND_COLOR ) ); fTitle->SetToolTip( fEventName.String() ); int nextLineInLayout = 2; /*================================================================ * If the notification was set by the user, display it. *================================================================*/ BString tempString; BPath path; float rectHeight = fh.leading + fh.ascent + fh.descent; float rectWidth = this->Bounds().Width() - 10; // Layout insets BSize size( rectWidth, rectHeight ); if ( fData->GetNotification( &tempString ) ) { /*----------------------------------------------------------------- * Line of explanation *----------------------------------------------------------------*/ exp = new BStringView( BRect( 0, 0, 1, 1 ), "Text view explanation", "You set the following notification:" ); if ( !exp ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } exp->ResizeToPreferred(); layoutItem = gridLayout->AddView( exp, 0, nextLineInLayout++, numberOfColumnsInLayout, 1 ); /*----------------------------------------------------------------- * Text view with notification text *----------------------------------------------------------------*/ BRect tempRect( BPoint( 0, 0 ), size ); tempRect.right -= B_V_SCROLL_BAR_WIDTH; fNoteText = new BTextView( tempRect, "Notification text container", tempRect.InsetByCopy( 1, 1 ), B_FOLLOW_ALL_SIDES, B_WILL_DRAW ); if ( !fNoteText ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } fNoteText->MakeEditable( false ); fNoteText->SetText( tempString.String() ); /*----------------------------------------------------------------- * Scroll view to scroll the notification text *----------------------------------------------------------------*/ fTextScroller = new BScrollView( "Notification text scroller", fNoteText, B_FOLLOW_ALL_SIDES, 0, false, true ); if ( !fTextScroller ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } layoutItem = gridLayout->AddView( fTextScroller, 0, nextLineInLayout++, numberOfColumnsInLayout, 1 ); if ( layoutItem ) { // layoutItem->SetExplicitMaxSize( size ); layoutItem->SetExplicitMinSize( size ); layoutItem->SetExplicitPreferredSize( size ); layoutItem->SetExplicitAlignment( BAlignment( B_ALIGN_USE_FULL_WIDTH, B_ALIGN_USE_FULL_HEIGHT ) ); } } // <-- end of adding information about the notification /*================================================================ * If user wanted to play a sound file, notify him about it. *================================================================*/ if ( fData->GetSound( &path ) ) { /*----------------------------------------------------------------- * Line of explanation *----------------------------------------------------------------*/ exp = new BStringView( BRect( 0, 0, 1, 1 ), "Sound file explanation", "You wanted to play the file:", B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP ); if ( !exp ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } exp->ResizeToPreferred(); layoutItem = gridLayout->AddView( exp, 0, nextLineInLayout++, numberOfColumnsInLayout, 1 ); if ( layoutItem ) { layoutItem->SetExplicitAlignment( BAlignment( B_ALIGN_CENTER, B_ALIGN_MIDDLE ) ); } /*----------------------------------------------------------------- * Display sound file name *----------------------------------------------------------------*/ // What should we display - full path or just the leaf? if ( ( size.width - 10 ) > plainFont.StringWidth( path.Path() ) ) { tempString.SetTo( path.Path() ); } else { tempString.SetTo( path.Leaf() ); } exp = new BStringView( BRect( 0, 0, 1, 1 ), "Sound file name", tempString.String() ); if ( !exp ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } exp->ResizeToPreferred(); layoutItem = gridLayout->AddView( exp, 0, nextLineInLayout++, numberOfColumnsInLayout, 1 ); if ( layoutItem ) { layoutItem->SetExplicitAlignment( BAlignment( B_ALIGN_CENTER, B_ALIGN_MIDDLE ) ); } } // <-- end of displaying information about the sound file /*================================================================ * If user wanted to run a program, notify him about it. *================================================================*/ if ( fData->GetProgram( &path, &tempString ) ) { /*----------------------------------------------------------------- * Line of explanation *----------------------------------------------------------------*/ exp = new BStringView( BRect( 0, 0, 1, 1 ), "Program explanation", "You wanted to run a program:" ); if ( !exp ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } exp->ResizeToPreferred(); layoutItem = gridLayout->AddView( exp, 0, nextLineInLayout++, numberOfColumnsInLayout, 1 ); if ( layoutItem ) { layoutItem->SetExplicitAlignment( BAlignment( B_ALIGN_CENTER, B_ALIGN_MIDDLE ) ); } /*----------------------------------------------------------------- * Display path to program file *----------------------------------------------------------------*/ // What should we display - full path or just the leaf? exp = new BStringView( BRect( 0, 0, 1, 1 ), "Program file name", ( ( size.width - 10 ) > plainFont.StringWidth( path.Path() ) ) ? path.Path() : path.Leaf() ); if ( !exp ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } exp->ResizeToPreferred(); layoutItem = gridLayout->AddView( exp, 0, nextLineInLayout++, numberOfColumnsInLayout, 1 ); if ( layoutItem ) { layoutItem->SetExplicitAlignment( BAlignment( B_ALIGN_CENTER, B_ALIGN_MIDDLE ) ); } /*----------------------------------------------------------------- * Explanation about the program options *----------------------------------------------------------------*/ if ( tempString.Length() > 0 ) { exp = new BStringView( BRect( 0, 0, 1, 1 ), "Program file options explanation", "With the following parameters:" ); if ( !exp ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } exp->ResizeToPreferred(); layoutItem = gridLayout->AddView( exp, 0, nextLineInLayout++, numberOfColumnsInLayout, 1 ); if ( layoutItem ) { layoutItem->SetExplicitAlignment( BAlignment( B_ALIGN_CENTER, B_ALIGN_MIDDLE ) ); } /*----------------------------------------------------------------- * Display the program options *----------------------------------------------------------------*/ // What should we display - full path or just the leaf? exp = new BStringView( BRect( 0, 0, 1, 1 ), "Program file options", tempString.String() ); if ( !exp ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } exp->ResizeToPreferred(); layoutItem = gridLayout->AddView( exp, 0, nextLineInLayout++, numberOfColumnsInLayout, 1 ); if ( layoutItem ) { layoutItem->SetExplicitAlignment( BAlignment( B_ALIGN_CENTER, B_ALIGN_MIDDLE ) ); } } // <-- end of diplaying CLI options } // <-- end of displaying information about the program to run /*================================================================ * Now it's time to display the Snooze time selector *================================================================*/ TimePreferences* prefs = pref_GetTimePreferences(); if ( prefs ) { prefs->GetDefaultSnoozeTime( ( int* )&fSnoozeHours, ( int* )&fSnoozeMins ); } else { fSnoozeHours = 0; fSnoozeMins = 10; } BMessage* toSend = new BMessage( kSnoozeTimeControlMessage ); if ( ! toSend ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } fSnoozeTime = new GeneralHourMinControl( BRect( 0, 0, 1, 1 ), "Snooze time selector", "Snooze this Activtiy for:", BString( "" ), // No check box toSend ); if ( !fSnoozeTime ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } fSnoozeTime->SetHoursLimit( 23 ); // Max reminder time delay is 23 hours 55 minutes fSnoozeTime->SetMinutesLimit( 55 ); fSnoozeTime->SetCurrentTime( fSnoozeHours, fSnoozeMins ); layoutItem = gridLayout->AddView( fSnoozeTime, 0, nextLineInLayout++, numberOfColumnsInLayout, 1 ); if ( layoutItem ) { layoutItem->SetExplicitAlignment( BAlignment( B_ALIGN_CENTER, B_ALIGN_MIDDLE ) ); } /*================================================================ * Snooze button *================================================================*/ toSend = new BMessage( kSnoozeButtonPressed ); if ( !toSend ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } fSnooze = new BButton( BRect( 0, 0, 1, 1 ), "Snooze button", "Snooze", toSend, B_FOLLOW_LEFT | B_FOLLOW_TOP ); if ( !fSnooze ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } fSnooze->ResizeToPreferred(); layoutItem = gridLayout->AddView( fSnooze, 0, nextLineInLayout ); if ( layoutItem ) { layoutItem->SetExplicitAlignment( BAlignment( B_ALIGN_LEFT, B_ALIGN_TOP ) ); } /*================================================================ * Ok button *================================================================*/ toSend = new BMessage( kDismissButtonPressed ); if ( !toSend ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } fOk = new BButton( BRect( 0, 0, 1, 1 ), "Dismiss button", "Dismiss", toSend, B_FOLLOW_RIGHT | B_FOLLOW_TOP ); if ( !fOk ) { /* Panic! */ fLastError = B_NO_MEMORY; return; } fSnooze->ResizeToPreferred(); layoutItem = gridLayout->AddView( fOk, 1, nextLineInLayout ); if ( layoutItem ) { layoutItem->SetExplicitAlignment( BAlignment( B_ALIGN_RIGHT, B_ALIGN_TOP ) ); } this->CenterOnScreen(); } // <-- end of constructor for ActivityWindow
void Snapshot::ProcessRefs (BMessage * msg) { // init BString command = "/bin/zip -ry "; BString snapshot_name = m_snapshot_dir_path.Path(); BString file_list; status_t status = B_OK; entry_ref ref; entry_ref last_ref; bool same_folder = true; /* entry_ref dir_ref; status = msg->FindRef("dir_ref", &dir_ref); if (status == B_OK) { BPath path (& dir_ref); // when used as Tracker addon chdir(path.Path()); // telling zip where to work } */ type_code ref_type = B_REF_TYPE; int32 ref_count = 0; status = msg->GetInfo("refs", & ref_type, & ref_count); if (status != B_OK) return; if (ref_count < 1) return; for (int index = 0; index < ref_count ; index++) { msg->FindRef("refs", index, & ref); if (index > 0) { if (last_ref.directory != ref.directory) { same_folder = false; break; } } last_ref = ref; } // change dir to avoid full paths in zip archive if (same_folder) { BEntry entry (& ref); entry.GetParent(& entry); BPath path (& entry); chdir (path.Path()); } // snapshost_name if (ref_count == 1) { snapshot_name += "/"; snapshot_name += ref.name; snapshot_name += ".zip"; } if (ref_count > 1) snapshot_name += "/multiple_files.zip"; // create timestamp time_t current_time = time(NULL); char * timestamp = new char [100]; strftime(timestamp, 99, "%Y.%m.%d_%H:%M:%S", localtime(& current_time)); snapshot_name += " ("; snapshot_name += timestamp; snapshot_name += ")"; MakeShellSafe(& snapshot_name); // files to zip for (int index = 0; index < ref_count ; index++) { msg->FindRef("refs", index, & ref); // BPath path (& ref); if (same_folder) // just the file name { BString file = ref.name; MakeShellSafe (& file); file_list += " "; file_list += file; } else // full path { BString file; BPath path (& ref); file = path.Path(); MakeShellSafe (& file); file_list += " "; file_list += file; } } // make command command += snapshot_name; command += " "; command += file_list; command += " &"; // run command printf("command: %s\n", command.String()); system(command.String()); }
ConfigWindow::ConfigWindow() : BWindow(BRect(100, 100, 600, 540), B_TRANSLATE_SYSTEM_NAME("E-mail"), B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_NOT_ZOOMABLE | B_NOT_RESIZABLE), fLastSelectedAccount(NULL), fSaveSettings(false) { // create controls BRect rect(Bounds()); BView *top = new BView(rect, NULL, B_FOLLOW_ALL, 0); top->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); AddChild(top); // determine font height font_height fontHeight; top->GetFontHeight(&fontHeight); int32 height = (int32)(fontHeight.ascent + fontHeight.descent + fontHeight.leading) + 5; rect.InsetBy(10, 10); rect.bottom -= 18 + height; BTabView *tabView = new BTabView(rect, NULL); BView *view; rect = tabView->Bounds(); rect.bottom -= tabView->TabHeight() + 4; tabView->AddTab(view = new BView(rect, NULL, B_FOLLOW_ALL, 0)); tabView->TabAt(0)->SetLabel(B_TRANSLATE("Accounts")); view->SetViewColor(top->ViewColor()); // accounts listview rect = view->Bounds().InsetByCopy(10, 10); rect.right = 190 - B_V_SCROLL_BAR_WIDTH; rect.bottom -= height + 18; fAccountsListView = new AccountsListView(rect, this); view->AddChild(new BScrollView(NULL, fAccountsListView, B_FOLLOW_ALL, 0, false, true)); rect.right += B_V_SCROLL_BAR_WIDTH; rect.left -= 2; rect.top = rect.bottom + 10; rect.bottom = rect.top + height; BRect sizeRect = rect; sizeRect.right = sizeRect.left + 30 + view->StringWidth( B_TRANSLATE("Add")); view->AddChild(new BButton(sizeRect, NULL, B_TRANSLATE("Add"), new BMessage(kMsgAddAccount), B_FOLLOW_BOTTOM)); sizeRect.left = sizeRect.right + 5; sizeRect.right = sizeRect.left + 30 + view->StringWidth( B_TRANSLATE("Remove")); view->AddChild(fRemoveButton = new BButton( sizeRect, NULL, B_TRANSLATE("Remove"), new BMessage(kMsgRemoveAccount), B_FOLLOW_BOTTOM)); // accounts config view rect = view->Bounds(); rect.left = fAccountsListView->Frame().right + B_V_SCROLL_BAR_WIDTH + 16; rect.right -= 10; fConfigView = new CenterContainer(rect); view->AddChild(fConfigView); _MakeHowToView(); // general settings rect = tabView->ContainerView()->Bounds(); tabView->AddTab(view = new CenterContainer(rect)); tabView->TabAt(1)->SetLabel(B_TRANSLATE("Settings")); rect = view->Bounds().InsetByCopy(10, 10); rect.bottom = rect.top + height * 5 + 15; BBox *box = new BBox(rect); box->SetLabel(B_TRANSLATE("Mail checking")); view->AddChild(box); rect = box->Bounds().InsetByCopy(10, 10); rect.top += 7; rect.bottom = rect.top + height; BRect tile = rect.OffsetByCopy(0, 1); int32 labelWidth = (int32)view->StringWidth(B_TRANSLATE("Check every")) + 6; tile.right = 80 + labelWidth; fIntervalControl = new BTextControl(tile, "time", B_TRANSLATE("Check every"), NULL, NULL); fIntervalControl->SetDivider(labelWidth); box->AddChild(fIntervalControl); BPopUpMenu* frequencyPopUp = new BPopUpMenu(B_EMPTY_STRING); const char* frequencyStrings[] = { B_TRANSLATE_COMMENT("never", "mail checking frequency"), B_TRANSLATE("minutes"), B_TRANSLATE("hours"), B_TRANSLATE("days")}; for (int32 i = 0; i < 4; i++) { BMenuItem* item = new BMenuItem(frequencyStrings[i], new BMessage(kMsgIntervalUnitChanged)); frequencyPopUp->AddItem(item); } tile.left = tile.right + 5; tile.right = rect.right; tile.OffsetBy(0,-1); fIntervalUnitField = new BMenuField(tile, "frequency", B_EMPTY_STRING, frequencyPopUp); fIntervalUnitField->SetDivider(0.0); box->AddChild(fIntervalUnitField); rect.OffsetBy(0,height + 9); rect.bottom -= 2; fPPPActiveCheckBox = new BCheckBox(rect, "ppp active", B_TRANSLATE("Only when dial-up is connected"), NULL); box->AddChild(fPPPActiveCheckBox); rect.OffsetBy(0,height + 9); rect.bottom -= 2; fPPPActiveSendCheckBox = new BCheckBox(rect, "ppp activesend", B_TRANSLATE("Schedule outgoing mail when dial-up is disconnected"), NULL); box->AddChild(fPPPActiveSendCheckBox); // Miscellaneous settings box rect = box->Frame(); rect.bottom = rect.top + 3 * height + 33; box = new BBox(rect); box->SetLabel(B_TRANSLATE("Miscellaneous")); view->AddChild(box); BPopUpMenu *statusPopUp = new BPopUpMenu(B_EMPTY_STRING); const char *statusModes[] = { B_TRANSLATE_COMMENT("Never", "show status window"), B_TRANSLATE("While sending"), B_TRANSLATE("While sending and receiving"), B_TRANSLATE("Always")}; for (int32 i = 0; i < 4; i++) { BMessage* msg = new BMessage(kMsgShowStatusWindowChanged); BMenuItem* item = new BMenuItem(statusModes[i], msg); statusPopUp->AddItem(item); msg->AddInt32("ShowStatusWindow", i); } rect = box->Bounds().InsetByCopy(10, 10); rect.top += 7; rect.bottom = rect.top + height + 5; labelWidth = (int32)view->StringWidth( B_TRANSLATE("Show connection status window:")) + 8; fStatusModeField = new BMenuField(rect, "show status", B_TRANSLATE("Show connection status window:"), statusPopUp); fStatusModeField->SetDivider(labelWidth); box->AddChild(fStatusModeField); rect = fStatusModeField->Frame();; rect.OffsetBy(0, rect.Height() + 10); BMessage* msg = new BMessage(B_REFS_RECEIVED); BButton *button = new BButton(rect, B_EMPTY_STRING, B_TRANSLATE("Edit mailbox menu…"), msg); button->ResizeToPreferred(); box->AddChild(button); button->SetTarget(BMessenger("application/x-vnd.Be-TRAK")); BPath path; find_directory(B_USER_SETTINGS_DIRECTORY, &path); path.Append("Mail/Menu Links"); BEntry entry(path.Path()); if (entry.InitCheck() == B_OK && entry.Exists()) { entry_ref ref; entry.GetRef(&ref); msg->AddRef("refs", &ref); } else button->SetEnabled(false); rect = button->Frame(); rect.OffsetBy(rect.Width() + 30,0); fAutoStartCheckBox = new BCheckBox(rect, "start daemon", B_TRANSLATE("Start mail services on startup"), NULL); fAutoStartCheckBox->ResizeToPreferred(); box->AddChild(fAutoStartCheckBox); // save/revert buttons top->AddChild(tabView); rect = tabView->Frame(); rect.top = rect.bottom + 10; rect.bottom = rect.top + height + 5; BButton *saveButton = new BButton(rect, "apply", B_TRANSLATE("Apply"), new BMessage(kMsgSaveSettings)); float w,h; saveButton->GetPreferredSize(&w, &h); saveButton->ResizeTo(w, h); saveButton->MoveTo(rect.right - w, rect.top); top->AddChild(saveButton); BButton *revertButton = new BButton(rect, "revert", B_TRANSLATE("Revert"), new BMessage(kMsgRevertSettings)); revertButton->GetPreferredSize(&w, &h); revertButton->ResizeTo(w, h); revertButton->MoveTo(rect.left, rect.top); top->AddChild(revertButton); _LoadSettings(); // this will also move our window to the stored position fAccountsListView->SetSelectionMessage(new BMessage(kMsgAccountSelected)); fAccountsListView->MakeFocus(true); }
void HWindow::_SetupMenuField() { BMenuField* menufield = dynamic_cast<BMenuField*>(FindView("filemenu")); if (menufield == NULL) return; BMenu* menu = menufield->Menu(); int32 count = fEventList->CountRows(); for (int32 i = 0; i < count; i++) { HEventRow* row = (HEventRow*)fEventList->RowAt(i); if (row == NULL) continue; BPath path(row->Path()); if (path.InitCheck() != B_OK) continue; if (menu->FindItem(path.Leaf())) continue; BMessage* msg = new BMessage(M_ITEM_MESSAGE); entry_ref ref; ::get_ref_for_path(path.Path(), &ref); msg->AddRef("refs", &ref); menu->AddItem(new BMenuItem(path.Leaf(), msg), 0); } directory_which whichDirectories[] = { B_SYSTEM_SOUNDS_DIRECTORY, B_SYSTEM_NONPACKAGED_SOUNDS_DIRECTORY, B_USER_SOUNDS_DIRECTORY, B_USER_NONPACKAGED_SOUNDS_DIRECTORY, }; for (size_t i = 0; i < sizeof(whichDirectories) / sizeof(whichDirectories[0]); i++) { BPath path; BDirectory dir; BEntry entry; BPath item_path; status_t err = find_directory(whichDirectories[i], &path); if (err == B_OK) err = dir.SetTo(path.Path()); while (err == B_OK) { err = dir.GetNextEntry(&entry, true); if (entry.InitCheck() != B_NO_ERROR) break; entry.GetPath(&item_path); if (menu->FindItem(item_path.Leaf())) continue; BMessage* msg = new BMessage(M_ITEM_MESSAGE); entry_ref ref; ::get_ref_for_path(item_path.Path(), &ref); msg->AddRef("refs", &ref); menu->AddItem(new BMenuItem(item_path.Leaf(), msg), 0); } } }
void DataTranslationsApplication::RefsReceived(BMessage* message) { BTranslatorRoster* roster = BTranslatorRoster::Default(); BPath path; status_t status = find_directory(B_USER_ADDONS_DIRECTORY, &path, true); if (status != B_OK) { _InstallError("translator", status); return; } BDirectory target; status = target.SetTo(path.Path()); if (status == B_OK) { if (!target.Contains("Translators")) status = target.CreateDirectory("Translators", &target); else status = target.SetTo(&target, "Translators"); } if (status != B_OK) { _InstallError("translator", status); return; } int32 i = 0; entry_ref ref; while (message->FindRef("refs", i++, &ref) == B_OK) { if (!roster->IsTranslator(&ref)) { _NoTranslatorError(ref.name); continue; } BEntry entry(&ref, true); status = entry.InitCheck(); if (status != B_OK) { _InstallError(ref.name, status); continue; } if (target.Contains(ref.name)) { BString string( B_TRANSLATE("An item named '%name' already exists in the " "Translators folder! Shall the existing translator be " "overwritten?")); string.ReplaceAll("%name", ref.name); BAlert* alert = new BAlert(B_TRANSLATE("DataTranslations - Note"), string.String(), B_TRANSLATE("Cancel"), B_TRANSLATE("Overwrite")); alert->SetShortcut(0, B_ESCAPE); if (alert->Go() != 1) continue; // the original file will be replaced } // find out whether we need to copy it or not status = _Install(target, entry); if (status == B_OK) { BAlert* alert = new BAlert(B_TRANSLATE("DataTranslations - Note"), B_TRANSLATE("The new translator has been installed " "successfully."), B_TRANSLATE("OK")); alert->Go(NULL); } else _InstallError(ref.name, status); } }
void TBarApp::InitSettings() { desk_settings settings; settings.vertical = fDefaultSettings.vertical = true; settings.left = fDefaultSettings.left = false; settings.top = fDefaultSettings.top = true; settings.state = fDefaultSettings.state = kExpandoState; settings.width = fDefaultSettings.width = 0; settings.switcherLoc = fDefaultSettings.switcherLoc = BPoint(5000, 5000); settings.showClock = fDefaultSettings.showClock = true; // applications settings.trackerAlwaysFirst = fDefaultSettings.trackerAlwaysFirst = false; settings.sortRunningApps = fDefaultSettings.sortRunningApps = false; settings.superExpando = fDefaultSettings.superExpando = false; settings.expandNewTeams = fDefaultSettings.expandNewTeams = false; settings.hideLabels = fDefaultSettings.hideLabels = false; settings.iconSize = fDefaultSettings.iconSize = kMinimumIconSize; // recent items settings.recentDocsEnabled = fDefaultSettings.recentDocsEnabled = true; settings.recentFoldersEnabled = fDefaultSettings.recentFoldersEnabled = true; settings.recentAppsEnabled = fDefaultSettings.recentAppsEnabled = true; settings.recentDocsCount = fDefaultSettings.recentDocsCount = 10; settings.recentFoldersCount = fDefaultSettings.recentFoldersCount = 10; settings.recentAppsCount = fDefaultSettings.recentAppsCount = 10; // window settings.alwaysOnTop = fDefaultSettings.alwaysOnTop = false; settings.autoRaise = fDefaultSettings.autoRaise = false; settings.autoHide = fDefaultSettings.autoHide = false; clock_settings clock; clock.showSeconds = false; clock.showDayOfWeek = false; clock.showTimeZone = false; BPath dirPath; const char* settingsFileName = "settings"; const char* clockSettingsFileName = "clock_settings"; find_directory(B_USER_DESKBAR_DIRECTORY, &dirPath, true); // just make it if (GetDeskbarSettingsDirectory(dirPath, true) == B_OK) { BPath filePath = dirPath; filePath.Append(settingsFileName); fSettingsFile = new BFile(filePath.Path(), O_RDWR); if (fSettingsFile->InitCheck() != B_OK) { BDirectory theDir(dirPath.Path()); if (theDir.InitCheck() == B_OK) theDir.CreateFile(settingsFileName, fSettingsFile); } BMessage prefs; if (fSettingsFile->InitCheck() == B_OK && prefs.Unflatten(fSettingsFile) == B_OK) { settings.vertical = prefs.GetBool("vertical", fDefaultSettings.vertical); settings.left = prefs.GetBool("left", fDefaultSettings.left); settings.top = prefs.GetBool("top", fDefaultSettings.top); settings.state = prefs.GetInt32("state", fDefaultSettings.state); settings.width = prefs.GetFloat("width", fDefaultSettings.width); settings.switcherLoc = prefs.GetPoint("switcherLoc", fDefaultSettings.switcherLoc); settings.showClock = prefs.GetBool("showClock", fDefaultSettings.showClock); // applications settings.trackerAlwaysFirst = prefs.GetBool("trackerAlwaysFirst", fDefaultSettings.trackerAlwaysFirst); settings.sortRunningApps = prefs.GetBool("sortRunningApps", fDefaultSettings.sortRunningApps); settings.superExpando = prefs.GetBool("superExpando", fDefaultSettings.superExpando); settings.expandNewTeams = prefs.GetBool("expandNewTeams", fDefaultSettings.expandNewTeams); settings.hideLabels = prefs.GetBool("hideLabels", fDefaultSettings.hideLabels); settings.iconSize = prefs.GetInt32("iconSize", fDefaultSettings.iconSize); // recent items settings.recentDocsEnabled = prefs.GetBool("recentDocsEnabled", fDefaultSettings.recentDocsEnabled); settings.recentFoldersEnabled = prefs.GetBool("recentFoldersEnabled", fDefaultSettings.recentFoldersEnabled); settings.recentAppsEnabled = prefs.GetBool("recentAppsEnabled", fDefaultSettings.recentAppsEnabled); settings.recentDocsCount = prefs.GetInt32("recentDocsCount", fDefaultSettings.recentDocsCount); settings.recentFoldersCount = prefs.GetInt32("recentFoldersCount", fDefaultSettings.recentFoldersCount); settings.recentAppsCount = prefs.GetInt32("recentAppsCount", fDefaultSettings.recentAppsCount); // window settings.alwaysOnTop = prefs.GetBool("alwaysOnTop", fDefaultSettings.alwaysOnTop); settings.autoRaise = prefs.GetBool("autoRaise", fDefaultSettings.autoRaise); settings.autoHide = prefs.GetBool("autoHide", fDefaultSettings.autoHide); } filePath = dirPath; filePath.Append(clockSettingsFileName); fClockSettingsFile = new BFile(filePath.Path(), O_RDWR); if (fClockSettingsFile->InitCheck() != B_OK) { BDirectory theDir(dirPath.Path()); if (theDir.InitCheck() == B_OK) theDir.CreateFile(clockSettingsFileName, fClockSettingsFile); } if (fClockSettingsFile->InitCheck() == B_OK && prefs.Unflatten(fClockSettingsFile) == B_OK) { clock.showSeconds = prefs.GetBool("showSeconds", false); clock.showDayOfWeek = prefs.GetBool("showDayOfWeek", false); clock.showTimeZone = prefs.GetBool("showTimeZone", false); } } fSettings = settings; fClockSettings = clock; }
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. }
bool MSHLanguageMgr::LoadLanguageFiles(const char * pathToFileStub) { if (NULL != fTransFiles) { DeleteAllLanguageFilesAndList(); } fTransFiles = new BList(); // Sanity check. if (NULL == fTransFiles) { return false; } bool loadedAtLeastOne = false; // Create a list of MSHLanguageFiles, one for each file found at // the passed-in location, using the included stub file prefix. fFileNameStub = ""; BString pathAndStub(pathToFileStub); BString pathOnly = ""; // Obtain the path component separately from the file name stub. const int32 posOfLastFolderSlash = pathAndStub.FindLast('/'); if (B_ERROR == posOfLastFolderSlash) { // Must be just a filename. fFileNameStub = pathAndStub; } else { pathAndStub.CopyInto(pathOnly, 0 /*sourceOffset*/, posOfLastFolderSlash); if (pathAndStub.Length() >= (posOfLastFolderSlash + 1)) { pathAndStub.CopyInto(fFileNameStub, (posOfLastFolderSlash + 1), (pathAndStub.Length() - 1)); } } if (fFileNameStub.Length() > 0) { // Check for a relative path. If relative, then add the app directory to the start. if ((pathOnly == "") || (pathOnly.FindFirst('/') > 0)) { app_info ai; be_app->GetAppInfo(&ai); BEntry appEntry(&ai.ref); BPath appPathWithLeafName; appEntry.GetPath(&appPathWithLeafName); BPath appPathOnly; appPathWithLeafName.GetParent(&appPathOnly); appPathWithLeafName.Unset(); if (pathOnly.FindLast('/') != (pathOnly.Length() - 1)) { pathOnly.Prepend("/"); } pathOnly.Prepend(appPathOnly.Path()); appPathOnly.Unset(); appEntry.Unset(); } if (pathOnly.Length() > 0) { // Find all files in the specified directory that have a name beginning // with the specified stub. char nameBuffer[B_FILE_NAME_LENGTH]; BDirectory langDir(pathOnly.String()); BEntry nextEntry; while (langDir.GetNextEntry(&nextEntry) == B_OK) { if (B_OK == nextEntry.GetName(nameBuffer)) { BString nameStr(nameBuffer); if (nameStr.FindFirst(fFileNameStub) == 0) { // We have a winner! Matching stub on filename (after adding on path) nameStr.Prepend("/"); nameStr.Prepend(pathOnly); MSHLanguageFile* newLangFile = new MSHLanguageFile(nameStr.String()); fTransFiles->AddItem(newLangFile); loadedAtLeastOne = true; } } nextEntry.Unset(); } } } if (!loadedAtLeastOne) { DeleteAllLanguageFilesAndList(); } return loadedAtLeastOne; }
bool FavoritesMenu::AddNextItem() { // run the next chunk of code for a given item adding state if (fState == kStart) { fState = kAddingFavorites; fSectionItemCount = 0; fAddedSeparatorForSection = false; // set up adding the GoTo menu items try { BPath path; ThrowOnError(find_directory(B_USER_SETTINGS_DIRECTORY, &path, true)); path.Append(kGoDirectory); mkdir(path.Path(), 0777); BEntry entry(path.Path()); Model startModel(&entry, true); ThrowOnInitCheckError(&startModel); if (!startModel.IsContainer()) throw B_ERROR; if (startModel.IsQuery()) fContainer = new QueryEntryListCollection(&startModel); else if (startModel.IsVirtualDirectory()) fContainer = new VirtualDirectoryEntryList(&startModel); else { fContainer = new DirectoryEntryList(*dynamic_cast<BDirectory*> (startModel.Node())); } ThrowOnInitCheckError(fContainer); ThrowOnError( fContainer->Rewind() ); } catch (...) { delete fContainer; fContainer = NULL; } } if (fState == kAddingFavorites) { entry_ref ref; if (fContainer != NULL && fContainer->GetNextRef(&ref) == B_OK) { Model model(&ref, true); if (model.InitCheck() != B_OK) return true; if (!ShouldShowModel(&model)) return true; BMenuItem* item = BNavMenu::NewModelItem(&model, model.IsDirectory() ? fOpenFolderMessage : fOpenFileMessage, fTarget); if (item == NULL) return true; item->SetLabel(ref.name); // this is the name of the link in the Go dir if (!fAddedSeparatorForSection) { fAddedSeparatorForSection = true; AddItem(new TitledSeparatorItem(B_TRANSLATE("Favorites"))); } fUniqueRefCheck.push_back(*model.EntryRef()); AddItem(item); fSectionItemCount++; return true; } // done with favorites, set up for adding recent files fState = kAddingFiles; fAddedSeparatorForSection = false; app_info info; be_app->GetAppInfo(&info); fItems.MakeEmpty(); int32 apps, docs, folders; TrackerSettings().RecentCounts(&apps, &docs, &folders); BRoster().GetRecentDocuments(&fItems, docs, NULL, info.signature); fIndex = 0; fSectionItemCount = 0; } if (fState == kAddingFiles) { // if this is a Save panel, not an Open panel // then don't add the recent documents if (!fIsSavePanel) { for (;;) { entry_ref ref; if (fItems.FindRef("refs", fIndex++, &ref) != B_OK) break; Model model(&ref, true); if (model.InitCheck() != B_OK) return true; if (!ShouldShowModel(&model)) return true; BMenuItem* item = BNavMenu::NewModelItem(&model, fOpenFileMessage, fTarget); if (item) { if (!fAddedSeparatorForSection) { fAddedSeparatorForSection = true; AddItem(new TitledSeparatorItem( B_TRANSLATE("Recent documents"))); } AddItem(item); fSectionItemCount++; return true; } } } // done with recent files, set up for adding recent folders fState = kAddingFolders; fAddedSeparatorForSection = false; app_info info; be_app->GetAppInfo(&info); fItems.MakeEmpty(); int32 apps, docs, folders; TrackerSettings().RecentCounts(&apps, &docs, &folders); BRoster().GetRecentFolders(&fItems, folders, info.signature); fIndex = 0; } if (fState == kAddingFolders) { for (;;) { entry_ref ref; if (fItems.FindRef("refs", fIndex++, &ref) != B_OK) break; // don't add folders that are already in the GoTo section if (find_if(fUniqueRefCheck.begin(), fUniqueRefCheck.end(), bind2nd(std::equal_to<entry_ref>(), ref)) != fUniqueRefCheck.end()) { continue; } Model model(&ref, true); if (model.InitCheck() != B_OK) return true; if (!ShouldShowModel(&model)) return true; BMenuItem* item = BNavMenu::NewModelItem(&model, fOpenFolderMessage, fTarget, true); if (item != NULL) { if (!fAddedSeparatorForSection) { fAddedSeparatorForSection = true; AddItem(new TitledSeparatorItem( B_TRANSLATE("Recent folders"))); } AddItem(item); item->SetEnabled(true); // BNavMenu::NewModelItem returns a disabled item here - // need to fix this in BNavMenu::NewModelItem return true; } } } return false; }
void ModulesView::MessageReceived(BMessage* message) { switch (message->what) { case kMsgSaverSelected: { int selection = fListView->CurrentSelection(); if (selection < 0) break; ScreenSaverItem* item = (ScreenSaverItem*)fListView->ItemAt(selection); if (item == NULL) break; if (!strcmp(item->Text(), B_TRANSLATE("Blackness"))) fSettings.SetModuleName(""); else fSettings.SetModuleName(item->Text()); SaveState(); _CloseSaver(); _OpenSaver(); fSettings.Save(); break; } case kMsgTestSaver: { SaveState(); fSettings.Save(); _CloseSaver(); be_roster->StartWatching(BMessenger(this, Looper()), B_REQUEST_QUIT); if (be_roster->Launch(SCREEN_BLANKER_SIG, &fSettings.Message(), &fScreenSaverTestTeam) == B_OK) break; // Try really hard to launch it. It's very likely that this fails // when we run from the CD, and there is only an incomplete mime // database for example... BPath path; if (find_directory(B_SYSTEM_BIN_DIRECTORY, &path) != B_OK || path.Append("screen_blanker") != B_OK) path.SetTo("/boot/system/bin/screen_blanker"); BEntry entry(path.Path()); entry_ref ref; if (entry.GetRef(&ref) == B_OK) { be_roster->Launch(&ref, &fSettings.Message(), &fScreenSaverTestTeam); } break; } case kMsgAddSaver: fFilePanel->Show(); break; case B_SOME_APP_QUIT: { team_id team; if (message->FindInt32("be:team", &team) == B_OK && team == fScreenSaverTestTeam) { be_roster->StopWatching(this); _OpenSaver(); } break; } default: BView::MessageReceived(message); } }
CalendarControl::CalendarControl(BPoint p, const char* name, int day=0, int month=0, int year=0, uint32 flags=CC_DD_MM_YYYY_FORMAT | CC_FULL_YEAR, uint32 look=CC_DOT_DIVIDER | CC_AUTO_INTERFACE) :BControl(BRect(100,100,200,200),name, NULL, NULL, B_FOLLOW_LEFT | B_FOLLOW_TOP, B_WILL_DRAW) { version=NULL; // result will be set after first call of Version() function // to save memory; this function will not be used often. uint32 divider=look & CC_ALL_DIVIDERS; #ifdef __UNIVERSAL_INTERFACE // Analysing interface flags. Advantage to universal interface. interface=look & CC_ALL_INTERFACES; if((interface!=CC_BEOS_INTERFACE) && (interface!=CC_ZETA_INTERFACE)) { // CC_AUTO_INTERFACE or flag are not set correctly. // Analysing in which system program has started and setting interface flag. BPath path; if(find_directory(B_BEOS_LIB_DIRECTORY, &path)!=B_OK) interface=CC_BEOS_INTERFACE; else { path.Append("libbe.so"); BString libbe_version; BFile libbe_file(path.Path(), B_READ_ONLY); BAppFileInfo info(&libbe_file); version_info version; info.GetVersionInfo (&version, B_SYSTEM_VERSION_KIND); libbe_version = version.short_info; char n[3]; libbe_version.CopyInto(n,0,1); n[1]='\0'; int i=atoi(n); if(i<6) // BeOS interface=CC_BEOS_INTERFACE; else // Zeta interface=CC_ZETA_INTERFACE; } } #else // __UNIVERSAL_INTERFACE is not defined, so forced setting interface flag #ifdef __ZETA_INTERFACE interface=CC_ZETA_INTERFACE; #else // __BEOS_INTERFACE and no other variants may be. interface=CC_BEOS_INTERFACE; #endif #endif dtvc=new DateTextView(day,month,year,flags,divider|interface); BPicture *pic1=new BPicture(); pb=new BPictureButton(BRect(70,0,85,15),"PictureButtonAViX",pic1,pic1, new BMessage(CalendarControlButtonPressedMessage), B_ONE_STATE_BUTTON, B_FOLLOW_LEFT | B_FOLLOW_TOP, B_WILL_DRAW); LT=p; AddChild(dtvc); dtvc->MoveTo(3,3); ResizeTo(dtvc->Bounds().Width()+6,dtvc->Bounds().Height()+7); AddChild(pb); delete pic1; #ifdef __UNIVERSAL_INTERFACE if(interface==CC_ZETA_INTERFACE) { #endif #ifdef __ZETA_INTERFACE pb->ResizeTo(Bounds().Height()*0.7+1,Bounds().Height()); pb->MoveTo(Bounds().right+2,Bounds().top); ResizeBy(pb->Bounds().Width()+2, 0); #endif #ifdef __UNIVERSAL_INTERFACE } else // interface==CC_BEOS_INTERFACE { #endif #ifdef __BEOS_INTERFACE pb->ResizeTo(Bounds().Height()*0.7,Bounds().Height()-1); pb->MoveTo(Bounds().right+1, Bounds().top); ResizeBy(pb->Bounds().Width()+1, 0); #endif #ifdef __UNIVERSAL_INTERFACE } #endif }
Prefs::Prefs() : fFatalError(false) { BPath path; find_directory(B_USER_SETTINGS_DIRECTORY, &path); path.Append("Pulse_settings"); fFile = new BFile(path.Path(), B_READ_WRITE | B_CREATE_FILE); if (fFile->InitCheck() != B_OK) { // try to open read-only if (fFile->SetTo(path.Path(), B_READ_ONLY) != B_OK) { fFatalError = true; return; } } int i = NORMAL_WINDOW_MODE; if (!GetInt("window_mode", &window_mode, &i)) { fFatalError = true; return; } // These three prefs require a connection to the app_server BRect r = GetNormalWindowRect(); if (!GetRect("normal_window_rect", &normal_window_rect, &r)) { fFatalError = true; return; } // While normal window position is under user control, size is not. // Width is fixed and height must be dynamically computed each time, // as number of CPUs could change since boot. ComputeNormalWindowSize(); r = GetMiniWindowRect(); if (!GetRect("mini_window_rect", &mini_window_rect, &r)) { fFatalError = true; return; } r.Set(100, 100, 415, 329); if (!GetRect("prefs_window_rect", &prefs_window_rect, &r)) { fFatalError = true; return; } i = DEFAULT_NORMAL_BAR_COLOR; if (!GetInt("normal_bar_color", &normal_bar_color, &i)) { fFatalError = true; return; } i = DEFAULT_MINI_ACTIVE_COLOR; if (!GetInt("mini_active_color", &mini_active_color, &i)) { fFatalError = true; return; } i = DEFAULT_MINI_IDLE_COLOR; if (!GetInt("mini_idle_color", &mini_idle_color, &i)) { fFatalError = true; return; } i = DEFAULT_MINI_FRAME_COLOR; if (!GetInt("mini_frame_color", &mini_frame_color, &i)) { fFatalError = true; return; } i = DEFAULT_DESKBAR_ACTIVE_COLOR; if (!GetInt("deskbar_active_color", &deskbar_active_color, &i)) { fFatalError = true; return; } i = DEFAULT_DESKBAR_IDLE_COLOR; if (!GetInt("deskbar_idle_color", &deskbar_idle_color, &i)) { fFatalError = true; return; } i = DEFAULT_DESKBAR_FRAME_COLOR; if (!GetInt("deskbar_frame_color", &deskbar_frame_color, &i)) { fFatalError = true; return; } bool b = DEFAULT_NORMAL_FADE_COLORS; if (!GetBool("normal_fade_colors", &normal_fade_colors, &b)) { fFatalError = true; return; } // Use the default size unless it would prevent having at least // a one pixel wide display per CPU... this will only happen with > quad i = DEFAULT_DESKBAR_ICON_WIDTH; if (i < GetMinimumViewWidth()) i = GetMinimumViewWidth(); if (!GetInt("deskbar_icon_width", &deskbar_icon_width, &i)) { fFatalError = true; return; } }
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, open new session if set if (fSession->InitCheck() == B_OK && pagesCreated == 0) { const char* kSettingsKeyStartUpPolicy = "start up policy"; uint32 fStartUpPolicy = fSettings->GetValue(kSettingsKeyStartUpPolicy, (uint32)ResumePriorSession); if (fStartUpPolicy == StartNewSession) { PostMessage(NEW_WINDOW); } else { // otherwise, restore previous session 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); }
void BeHappy::SearchAddOns() { // on vide les listes { BPath *p; while ((p=(BPath*)addOnsPaths.RemoveItem((int32)0))!=NULL) delete p; BString *s; while ((s=(BString*)addOnsNames.RemoveItem((int32)0))!=NULL) delete s; } // d'abord on cherche le dossier app_info myInfo; be_app->GetAppInfo(&myInfo); BEntry appEntry(&(myInfo.ref)); BDirectory addOnsDir; appEntry.GetParent(&addOnsDir); // parcours de tous les fichiers du dossier if (addOnsDir.SetTo(&addOnsDir,"Add-ons")==B_OK) { BEntry addOn; while (addOnsDir.GetNextEntry(&addOn,true) == B_OK) { BPath *addOnPath = new BPath; addOn.GetPath(addOnPath); // extraction du type MIME { BNode myNode(&addOn); BNodeInfo myNodeInfo(&myNode); char mimeType[256]; myNodeInfo.GetType(mimeType); if (BString("application/x-vnd.Be-elfexecutable") != mimeType) continue; } // on est sûrs que c'est un Add-on BString *projName = new BString; if (CheckAddOn(addOnPath->Path(),true,projName)) { addOnsPaths.AddItem(addOnPath); addOnsNames.AddItem(projName); } else { delete addOnPath; delete projName; } // si c'est la première fois que SearchAddOns est appelé, on doit activer le node monitor if (!addOnsSearched) { addOnsSearched = true; node_ref myRef; addOnsDir.GetNodeRef(&myRef); watch_node(&myRef,B_WATCH_DIRECTORY,be_app_messenger); } } } else { BAlert *myAlert = new BAlert("BeHappy",T("Can't find Add-ons folder"), "Quit",NULL,NULL,B_WIDTH_AS_USUAL,B_STOP_ALERT); myAlert->Go(); PostMessage(B_QUIT_REQUESTED); } }
BPopUpMenu* DeskbarView::_BuildMenu() { BPopUpMenu* menu = new BPopUpMenu(B_EMPTY_STRING, false, false); menu->SetFont(be_plain_font); menu->AddItem(new BMenuItem(B_TRANSLATE("Create new message" B_UTF8_ELLIPSIS), new BMessage(MD_OPEN_NEW))); menu->AddSeparatorItem(); BMessenger tracker(kTrackerSignature); BNavMenu* navMenu; BMenuItem* item; BMessage* msg; entry_ref ref; BPath path; find_directory(B_USER_SETTINGS_DIRECTORY, &path); path.Append("Mail/Menu Links"); BDirectory directory; if (_CreateMenuLinks(directory, path)) { int32 count = 0; while (directory.GetNextRef(&ref) == B_OK) { count++; path.SetTo(&ref); // the true here dereferences the symlinks all the way :) BEntry entry(&ref, true); // do we want to use the NavMenu, or just an ordinary BMenuItem? // we are using the NavMenu only for directories and queries bool useNavMenu = false; if (entry.InitCheck() == B_OK) { if (entry.IsDirectory()) useNavMenu = true; else if (entry.IsFile()) { // Files should use the BMenuItem unless they are queries char mimeString[B_MIME_TYPE_LENGTH]; BNode node(&entry); BNodeInfo info(&node); if (info.GetType(mimeString) == B_OK && strcmp(mimeString, "application/x-vnd.Be-query") == 0) useNavMenu = true; } // clobber the existing ref only if the symlink derefernces // completely, otherwise we'll stick with what we have entry.GetRef(&ref); } msg = new BMessage(B_REFS_RECEIVED); msg->AddRef("refs", &ref); if (useNavMenu) { item = new BMenuItem(navMenu = new BNavMenu(path.Leaf(), B_REFS_RECEIVED, tracker), msg); navMenu->SetNavDir(&ref); } else item = new BMenuItem(path.Leaf(), msg); menu->AddItem(item); if (entry.InitCheck() != B_OK) item->SetEnabled(false); } if (count > 0) menu->AddSeparatorItem(); } // Hack for R5's buggy Query Notification #ifdef HAIKU_TARGET_PLATFORM_BEOS menu->AddItem(new BMenuItem(B_TRANSLATE("Refresh New Mail Count"), new BMessage(MD_REFRESH_QUERY))); #endif // The New E-mail query if (fNewMessages > 0) { static BMessageFormat format(B_TRANSLATE( "{0, plural, one{# new message} other{# new messages}}")); BString string; format.Format(string, fNewMessages); _GetNewQueryRef(ref); item = new BMenuItem(navMenu = new BNavMenu(string.String(), B_REFS_RECEIVED, BMessenger(kTrackerSignature)), msg = new BMessage(B_REFS_RECEIVED)); msg->AddRef("refs", &ref); navMenu->SetNavDir(&ref); menu->AddItem(item); } else { menu->AddItem(item = new BMenuItem(B_TRANSLATE("No new messages"), NULL)); item->SetEnabled(false); } BMailAccounts accounts; if ((modifiers() & B_SHIFT_KEY) != 0) { BMenu *accountMenu = new BMenu(B_TRANSLATE("Check for mails only")); BFont font; menu->GetFont(&font); accountMenu->SetFont(&font); for (int32 i = 0; i < accounts.CountAccounts(); i++) { BMailAccountSettings* account = accounts.AccountAt(i); BMessage* message = new BMessage(MD_CHECK_FOR_MAILS); message->AddInt32("account", account->AccountID()); accountMenu->AddItem(new BMenuItem(account->Name(), message)); } if (accounts.CountAccounts() == 0) { item = new BMenuItem(B_TRANSLATE("<no accounts>"), NULL); item->SetEnabled(false); accountMenu->AddItem(item); } accountMenu->SetTargetForItems(this); menu->AddItem(new BMenuItem(accountMenu, new BMessage(MD_CHECK_FOR_MAILS))); // Not used: // menu->AddItem(new BMenuItem(B_TRANSLATE("Check For Mails Only"), // new BMessage(MD_CHECK_FOR_MAILS))); menu->AddItem(new BMenuItem(B_TRANSLATE("Send pending mails"), new BMessage(MD_SEND_MAILS))); } else { menu->AddItem(item = new BMenuItem(B_TRANSLATE("Check for mail now"), new BMessage(MD_CHECK_SEND_NOW))); if (accounts.CountAccounts() == 0) item->SetEnabled(false); } menu->AddSeparatorItem(); menu->AddItem(new BMenuItem(B_TRANSLATE("Settings" B_UTF8_ELLIPSIS), new BMessage(MD_OPEN_PREFS))); if (modifiers() & B_SHIFT_KEY) { menu->AddItem(new BMenuItem(B_TRANSLATE("Shutdown mail services"), new BMessage(B_QUIT_REQUESTED))); } // Reset Item Targets (only those which aren't already set) for (int32 i = menu->CountItems(); i-- > 0;) { item = menu->ItemAt(i); if (item != NULL && (msg = item->Message()) != NULL) { if (msg->what == B_REFS_RECEIVED) item->SetTarget(tracker); else item->SetTarget(this); } } return menu; }
status_t PackageView::_InstallTypeChanged(int32 index) { if (index < 0) return B_ERROR; // Clear the choice list for (int32 i = fDestination->CountItems() - 1; i >= 0; i--) { BMenuItem* item = fDestination->RemoveItem(i); delete item; } fCurrentType = index; pkg_profile* profile = fInfo.GetProfile(index); if (profile == NULL) return B_ERROR; BString typeDescription = profile->description; if (typeDescription.IsEmpty()) typeDescription = profile->name; fInstallTypeDescriptionView->SetText(typeDescription.String()); BPath path; BVolume volume; if (profile->path_type == P_INSTALL_PATH) { BMenuItem* item = NULL; if (find_directory(B_SYSTEM_NONPACKAGED_DIRECTORY, &path) == B_OK) { dev_t device = dev_for_path(path.Path()); if (volume.SetTo(device) == B_OK && !volume.IsReadOnly() && path.Append("apps") == B_OK) { item = _AddDestinationMenuItem(path.Path(), volume.FreeBytes(), path.Path()); } } if (item != NULL) { item->SetMarked(true); fCurrentPath.SetTo(path.Path()); fDestination->AddSeparatorItem(); } _AddMenuItem(B_TRANSLATE("Other" B_UTF8_ELLIPSIS), new BMessage(P_MSG_OPEN_PANEL), fDestination); fDestField->SetEnabled(true); } else if (profile->path_type == P_USER_PATH) { bool defaultPathSet = false; BVolumeRoster roster; while (roster.GetNextVolume(&volume) != B_BAD_VALUE) { BDirectory mountPoint; if (volume.IsReadOnly() || !volume.IsPersistent() || volume.GetRootDirectory(&mountPoint) != B_OK) { continue; } if (path.SetTo(&mountPoint, NULL) != B_OK) continue; char volumeName[B_FILE_NAME_LENGTH]; volume.GetName(volumeName); BMenuItem* item = _AddDestinationMenuItem(volumeName, volume.FreeBytes(), path.Path()); // The first volume becomes the default element if (!defaultPathSet) { item->SetMarked(true); fCurrentPath.SetTo(path.Path()); defaultPathSet = true; } } fDestField->SetEnabled(true); } else fDestField->SetEnabled(false); return B_OK; }