void ArgvReceived(int32 argc, char **argv) { int i, j; BMessage msg(InfoPopper::AddMessage); InfoPopper::info_type type = InfoPopper::Information; const char *app = "Command Line"; const char *title = "Something Happened"; BString content; float progress = 0.0; const char *messageID = NULL; int32 timeout = 0; const char *iconFile = NULL; const char *onClickApp; entry_ref onClickFile; const char *onClickArgv; entry_ref onClickRef; for (i = 1; i < argc; i++) { //printf("argv[%d] = %s\n", i, argv[i]); if (!strcmp(argv[i], "--help")) { return Usage(); } else if (!strcmp(argv[i], "--type")) { if (++i >= argc) return Usage(); type = (InfoPopper::info_type)atoi(argv[i]); for (j=0; kTypeNames[j]; j++) { if (!strncmp(kTypeNames[j], argv[i], strlen(argv[i]))) { type = (InfoPopper::info_type)j; }; }; } else if (!strcmp(argv[i], "--app")) { if (++i >= argc) return Usage(); app = argv[i]; } else if (!strcmp(argv[i], "--title")) { if (++i >= argc) return Usage(); title = argv[i]; } else if (!strcmp(argv[i], "--messageID")) { if (++i >= argc) return Usage(); messageID = argv[i]; msg.AddString("messageID", messageID); } else if (!strcmp(argv[i], "--progress")) { if (++i >= argc) return Usage(); progress = atof(argv[i]); msg.AddFloat("progress", progress); } else if (!strcmp(argv[i], "--timeout")) { if (++i >= argc) return Usage(); timeout = atol(argv[i]); msg.AddInt32("timeout", timeout); #if 0 } else if (!strcmp(argv[i], "--empty")) { /* like alert's --empty */ iconFile = NULL; } else if (!strcmp(argv[i], "--info")) { iconFile = "info"; } else if (!strcmp(argv[i], "--idea")) { } else if (!strcmp(argv[i], "--warning")) { } else if (!strcmp(argv[i], "--stop")) { #endif } else if (!strcmp(argv[i], "--icon")) { bool isOverlay = false; if (++i >= argc) return Usage(); iconFile = argv[i]; if (!strncmp(iconFile, "overlay:", 8)) { iconFile += 8; isOverlay = true; }; if (!strncmp(iconFile, "attr:", 5)) { iconFile += 5; msg.AddInt32(isOverlay?"overlayIconType":"iconType", InfoPopper::Attribute); } else { msg.AddInt32(isOverlay?"overlayIconType":"iconType", InfoPopper::Contents); }; entry_ref ref; if (get_ref_for_path(iconFile, &ref) < B_OK) { fprintf(stderr, "bad icon path\n"); return Usage(); }; msg.AddRef(isOverlay?"overlayIconRef":"iconRef", &ref); } else if (!strcmp(argv[i], "--onClickApp")) { if (++i >= argc) return Usage(); onClickApp = argv[i]; msg.AddString("onClickApp", onClickApp); } else if (!strcmp(argv[i], "--onClickFile")) { if (++i >= argc) return Usage(); if (get_ref_for_path(argv[i], &onClickFile) < B_OK) { fprintf(stderr, "bad path\n"); return Usage(); }; msg.AddRef("onClickFile", &onClickFile); } else if (!strcmp(argv[i], "--onClickArgv")) { if (++i >= argc) return Usage(); onClickArgv = argv[i]; msg.AddString("onClickArgv", onClickArgv); } else if (!strcmp(argv[i], "--onClickRef")) { if (++i >= argc) return Usage(); if (get_ref_for_path(argv[i], &onClickRef) < B_OK) { fprintf(stderr, "bad path\n"); return Usage(); } msg.AddRef("onClickRef", &onClickRef); } else { if (content.Length()) content << "\n"; content << argv[i]; } } msg.AddInt8("type", (int8)type); msg.AddString("app", app); msg.AddString("title", title); msg.AddString("content", content); be_app_messenger.SendMessage(&msg); }
void TeamWindow::MessageReceived(BMessage* message) { switch (message->what) { case MSG_TEAM_RESTART_REQUESTED: { fListener->TeamRestartRequested(); break; } case MSG_CHOOSE_DEBUG_REPORT_LOCATION: { try { char filename[B_FILE_NAME_LENGTH]; UiUtils::ReportNameForTeam(fTeam, filename, sizeof(filename)); BMessenger msgr(this); fFilePanel = new BFilePanel(B_SAVE_PANEL, &msgr, NULL, 0, false, new BMessage(MSG_GENERATE_DEBUG_REPORT)); fFilePanel->SetSaveText(filename); fFilePanel->Show(); } catch (...) { delete fFilePanel; fFilePanel = NULL; } break; } case MSG_GENERATE_DEBUG_REPORT: { delete fFilePanel; fFilePanel = NULL; BPath path; entry_ref ref; if (message->FindRef("directory", &ref) == B_OK && message->HasString("name")) { path.SetTo(&ref); path.Append(message->FindString("name")); if (get_ref_for_path(path.Path(), &ref) == B_OK) fListener->DebugReportRequested(&ref); } break; } case MSG_DEBUG_REPORT_SAVED: { BString data; data.SetToFormat("Debug report successfully saved to '%s'", message->FindString("path")); BAlert *alert = new(std::nothrow) BAlert("Report saved", data.String(), "Close"); if (alert == NULL) break; alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(); break; } case MSG_SHOW_INSPECTOR_WINDOW: { if (fInspectorWindow) { fInspectorWindow->Activate(true); } else { try { fInspectorWindow = InspectorWindow::Create(fTeam, fListener, this); if (fInspectorWindow != NULL) { BMessage settings; fInspectorWindow->LoadSettings(fUiSettings); fInspectorWindow->Show(); } } catch (...) { // TODO: notify user } } target_addr_t address; if (message->FindUInt64("address", &address) == B_OK) { BMessage addressMessage(MSG_INSPECT_ADDRESS); addressMessage.AddUInt64("address", address); fInspectorWindow->PostMessage(&addressMessage); } break; } case MSG_INSPECTOR_WINDOW_CLOSED: { _SaveInspectorSettings(CurrentMessage()); fInspectorWindow = NULL; break; } case MSG_SHOW_BREAK_CONDITION_CONFIG_WINDOW: { if (fBreakConditionConfigWindow) { fBreakConditionConfigWindow->Activate(true); } else { try { fBreakConditionConfigWindow = BreakConditionConfigWindow::Create( fTeam, fListener, this); if (fBreakConditionConfigWindow != NULL) fBreakConditionConfigWindow->Show(); } catch (...) { // TODO: notify user } } break; } case MSG_BREAK_CONDITION_CONFIG_WINDOW_CLOSED: { fBreakConditionConfigWindow = NULL; break; } case MSG_SHOW_WATCH_VARIABLE_PROMPT: { target_addr_t address; uint32 type; int32 length; if (message->FindUInt64("address", &address) != B_OK || message->FindUInt32("type", &type) != B_OK || message->FindInt32("length", &length) != B_OK) { break; } try { WatchPromptWindow* window = WatchPromptWindow::Create( fTeam->GetArchitecture(), address, type, length, fListener); window->Show(); } catch (...) { // TODO: notify user } break; } case B_REFS_RECEIVED: { entry_ref locatedPath; if (message->FindRef("refs", &locatedPath) != B_OK) break; _HandleResolveMissingSourceFile(locatedPath); break; } case MSG_LOCATE_SOURCE_IF_NEEDED: { _HandleLocateSourceRequest(); break; } case MSG_SOURCE_ENTRY_QUERY_COMPLETE: { BStringList* entries; if (message->FindPointer("entries", (void**)&entries) != B_OK) break; ObjectDeleter<BStringList> entryDeleter(entries); _HandleLocateSourceRequest(entries); fActiveSourceWorker = -1; break; } case MSG_THREAD_RUN: case MSG_THREAD_STOP: case MSG_THREAD_STEP_OVER: case MSG_THREAD_STEP_INTO: case MSG_THREAD_STEP_OUT: if (fActiveThread != NULL && fTraceUpdateRunner == NULL) { fListener->ThreadActionRequested(fActiveThread->ID(), message->what); } break; case MSG_CLEAR_STACK_TRACE: { if (fTraceUpdateRunner != NULL) { _SetActiveStackTrace(NULL); _UpdateRunButtons(); } break; } case MSG_THREAD_STATE_CHANGED: { int32 threadID; if (message->FindInt32("thread", &threadID) != B_OK) break; _HandleThreadStateChanged(threadID); break; } case MSG_THREAD_CPU_STATE_CHANGED: { int32 threadID; if (message->FindInt32("thread", &threadID) != B_OK) break; _HandleCpuStateChanged(threadID); break; } case MSG_THREAD_STACK_TRACE_CHANGED: { int32 threadID; if (message->FindInt32("thread", &threadID) != B_OK) break; _HandleStackTraceChanged(threadID); break; } case MSG_IMAGE_DEBUG_INFO_CHANGED: { int32 imageID; if (message->FindInt32("image", &imageID) != B_OK) break; _HandleImageDebugInfoChanged(imageID); break; } case MSG_CONSOLE_OUTPUT_RECEIVED: { int32 fd; BString output; if (message->FindInt32("fd", &fd) != B_OK || message->FindString("output", &output) != B_OK) { break; } fConsoleOutputView->ConsoleOutputReceived(fd, output); break; } case MSG_USER_BREAKPOINT_CHANGED: { UserBreakpoint* breakpoint; if (message->FindPointer("breakpoint", (void**)&breakpoint) != B_OK) break; BReference<UserBreakpoint> breakpointReference(breakpoint, true); _HandleUserBreakpointChanged(breakpoint); break; } case MSG_WATCHPOINT_CHANGED: { Watchpoint* watchpoint; if (message->FindPointer("watchpoint", (void**)&watchpoint) != B_OK) break; BReference<Watchpoint> watchpointReference(watchpoint, true); _HandleWatchpointChanged(watchpoint); break; } case MSG_FUNCTION_SOURCE_CODE_CHANGED: { _HandleSourceCodeChanged(); break; } default: BWindow::MessageReceived(message); break; } }
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 UrlWrapper::ArgvReceived(int32 argc, char** argv) { if (argc <= 1) return; const char* failc = " || read -p 'Press any key'"; const char* pausec = " ; read -p 'Press any key'"; char* args[] = { (char *)"/bin/sh", (char *)"-c", NULL, NULL}; status_t err; BUrl url(argv[1]); BString full = BUrl(url).SetProtocol(BString()).UrlString(); BString proto = url.Protocol(); BString host = url.Host(); BString port = BString() << url.Port(); BString user = url.UserInfo(); BString pass = url.Password(); BString path = url.Path(); if (!url.IsValid()) { fprintf(stderr, "malformed url: '%s'\n", url.UrlString().String()); return; } // XXX: debug PRINT(("PROTO='%s'\n", proto.String())); PRINT(("HOST='%s'\n", host.String())); PRINT(("PORT='%s'\n", port.String())); PRINT(("USER='******'\n", user.String())); PRINT(("PASS='******'\n", pass.String())); PRINT(("PATH='%s'\n", path.String())); if (proto == "about") { app_info info; BString sig; // BUrl could get an accessor for the full - proto part... sig = host << "/" << path; BMessage msg(B_ABOUT_REQUESTED); if (be_roster->GetAppInfo(sig.String(), &info) == B_OK) { BMessenger msgr(sig.String()); msgr.SendMessage(&msg); return; } if (be_roster->Launch(sig.String(), &msg) == B_OK) return; be_roster->Launch("application/x-vnd.Haiku-About"); return; } if (proto == "telnet") { BString cmd("telnet "); if (url.HasUserInfo()) cmd << "-l " << user << " "; cmd << host; if (url.HasPort()) cmd << " " << port; PRINT(("CMD='%s'\n", cmd.String())); cmd << failc; args[2] = (char*)cmd.String(); be_roster->Launch(kTerminalSig, 3, args); return; } // see draft: // http://tools.ietf.org/wg/secsh/draft-ietf-secsh-scp-sftp-ssh-uri/ if (proto == "ssh") { BString cmd("ssh "); if (url.HasUserInfo()) cmd << "-l " << user << " "; if (url.HasPort()) cmd << "-oPort=" << port << " "; cmd << host; PRINT(("CMD='%s'\n", cmd.String())); cmd << failc; args[2] = (char*)cmd.String(); be_roster->Launch(kTerminalSig, 3, args); // TODO: handle errors return; } if (proto == "ftp") { BString cmd("ftp "); cmd << proto << "://"; /* if (user.Length()) cmd << "-l " << user << " "; cmd << host; */ cmd << full; PRINT(("CMD='%s'\n", cmd.String())); cmd << failc; args[2] = (char*)cmd.String(); be_roster->Launch(kTerminalSig, 3, args); // TODO: handle errors return; } if (proto == "sftp") { BString cmd("sftp "); //cmd << url; if (url.HasPort()) cmd << "-oPort=" << port << " "; if (url.HasUserInfo()) cmd << user << "@"; cmd << host; if (url.HasPath()) cmd << ":" << path; PRINT(("CMD='%s'\n", cmd.String())); cmd << failc; args[2] = (char*)cmd.String(); be_roster->Launch(kTerminalSig, 3, args); // TODO: handle errors return; } if (proto == "finger") { BString cmd("/bin/finger "); if (url.HasUserInfo()) cmd << user; if (url.HasHost() == 0) host = "127.0.0.1"; cmd << "@" << host; PRINT(("CMD='%s'\n", cmd.String())); cmd << pausec; args[2] = (char*)cmd.String(); be_roster->Launch(kTerminalSig, 3, args); // TODO: handle errors return; } if (proto == "http" || proto == "https" /*|| proto == "ftp"*/) { BString cmd("/bin/wget "); //cmd << url; cmd << proto << "://"; if (url.HasUserInfo()) cmd << user << "@"; cmd << full; PRINT(("CMD='%s'\n", cmd.String())); cmd << pausec; args[2] = (char*)cmd.String(); be_roster->Launch(kTerminalSig, 3, args); // TODO: handle errors return; } if (proto == "file") { BMessage m(B_REFS_RECEIVED); entry_ref ref; _DecodeUrlString(path); if (get_ref_for_path(path.String(), &ref) < B_OK) return; m.AddRef("refs", &ref); be_roster->Launch(kTrackerSig, &m); return; } // XXX:TODO: split options if (proto == "query") { // mktemp ? BString qname("/tmp/query-url-temp-"); qname << getpid() << "-" << system_time(); BFile query(qname.String(), O_CREAT|O_EXCL); // XXX: should check for failure BString s; int32 v; _DecodeUrlString(full); // TODO: handle options (list of attrs in the column, ...) v = 'qybF'; // QuerY By Formula XXX: any #define for that ? query.WriteAttr("_trk/qryinitmode", B_INT32_TYPE, 0LL, &v, sizeof(v)); s = "TextControl"; query.WriteAttr("_trk/focusedView", B_STRING_TYPE, 0LL, s.String(), s.Length()+1); s = full; PRINT(("QUERY='%s'\n", s.String())); query.WriteAttr("_trk/qryinitstr", B_STRING_TYPE, 0LL, s.String(), s.Length()+1); query.WriteAttr("_trk/qrystr", B_STRING_TYPE, 0LL, s.String(), s.Length()+1); s = "application/x-vnd.Be-query"; query.WriteAttr("BEOS:TYPE", 'MIMS', 0LL, s.String(), s.Length()+1); BEntry e(qname.String()); entry_ref er; if (e.GetRef(&er) >= B_OK) be_roster->Launch(&er); return; } if (proto == "sh") { BString cmd(full); if (_Warn(url.UrlString()) != B_OK) return; PRINT(("CMD='%s'\n", cmd.String())); cmd << pausec; args[2] = (char*)cmd.String(); be_roster->Launch(kTerminalSig, 3, args); // TODO: handle errors return; } if (proto == "beshare") { team_id team; BMessenger msgr(kBeShareSig); // if no instance is running, or we want a specific server, start it. if (!msgr.IsValid() || url.HasHost()) { be_roster->Launch(kBeShareSig, (BMessage*)NULL, &team); msgr = BMessenger(NULL, team); } if (url.HasHost()) { BMessage mserver('serv'); mserver.AddString("server", host); msgr.SendMessage(&mserver); } if (url.HasPath()) { BMessage mquery('quer'); mquery.AddString("query", path); msgr.SendMessage(&mquery); } // TODO: handle errors return; } if (proto == "icq" || proto == "msn") { // TODO team_id team; be_roster->Launch(kIMSig, (BMessage*)NULL, &team); BMessenger msgr(NULL, team); if (url.HasHost()) { BMessage mserver(B_REFS_RECEIVED); mserver.AddString("server", host); msgr.SendMessage(&mserver); } // TODO: handle errors return; } if (proto == "mms" || proto == "rtp" || proto == "rtsp") { args[0] = (char*)url.UrlString().String(); be_roster->Launch(kVLCSig, 1, args); return; } if (proto == "nfs") { BString parameter(host); _DecodeUrlString(path); if (url.HasPort()) parameter << ":" << port; //XXX: should not always be absolute! FIXME parameter << ":/" << path; BString prettyPath(path); prettyPath.Remove(0, prettyPath.FindLast("/") + 1); if (path == "" || path == "/") prettyPath = "root"; prettyPath << " on " << host; prettyPath.Prepend("/"); if (mkdir(prettyPath.String(), 0755) < 0) { perror("mkdir"); return; } dev_t volume; uint32 flags = 0; fprintf(stderr, "parms:'%s'\n", parameter.String()); volume = fs_mount_volume(prettyPath.String(), NULL, "nfs4", flags, parameter.String()); if (volume < B_OK) { fprintf(stderr, "fs_mount_volume: %s\n", strerror(volume)); return; } BMessage m(B_REFS_RECEIVED); entry_ref ref; if (get_ref_for_path(prettyPath.String(), &ref) < B_OK) return; m.AddRef("refs", &ref); be_roster->Launch(kTrackerSig, &m); return; } if (proto == "doi") { BString url("http://dx.doi.org/"); BString mimetype; url << full; BUrl u(url.String()); args[0] = const_cast<char*>("urlwrapper"); //XXX args[1] = (char*)u.UrlString().String(); args[2] = NULL; mimetype = kURLHandlerSigBase; mimetype += u.Protocol(); err = be_roster->Launch(mimetype.String(), 1, args + 1); if (err != B_OK && err != B_ALREADY_RUNNING) err = be_roster->Launch(kAppSig, 1, args + 1); // TODO: handle errors return; } /* More ? cf. http://en.wikipedia.org/wiki/URI_scheme cf. http://www.iana.org/assignments/uri-schemes.html Audio: (SoundPlay specific, identical to http:// to a shoutcast server) vnc: ? irc: ? im: http://tools.ietf.org/html/rfc3860 svn: handled by checkitout cvs: handled by checkitout git: handled by checkitout rsync: handled by checkitout - http://tools.ietf.org/html/rfc5781 smb: cifsmount ? nfs: mount_nfs ? http://tools.ietf.org/html/rfc2224 ipp: http://tools.ietf.org/html/rfc3510 mailto: ? Mail & Beam both handle it already (not fully though). imap: to describe mail accounts ? http://tools.ietf.org/html/rfc5092 pop: http://tools.ietf.org/html/rfc2384 mid: cid: as per RFC 2392 http://www.rfc-editor.org/rfc/rfc2392.txt query MAIL:cid message:<MID> http://daringfireball.net/2007/12/message_urls_leopard_mail itps: pcast: podcast: s//http/ + parse xml to get url to mp3 stream... audio: s//http:/ + default MediaPlayer -- see http://forums.winamp.com/showthread.php?threadid=233130 gps: ? I should submit an RFC for that one :) webcal: (is http: to .ics file) data: (but it's dangerous) */ }
void TeamWindow::_HandleLocateSourceRequest(BStringList* entries) { if (fActiveFunction == NULL) return; else if (fActiveFunction->GetFunctionDebugInfo()->SourceFile() == NULL) return; else if (fActiveSourceCode == NULL) return; else if (fActiveSourceCode->GetSourceFile() != NULL) return; else if (fActiveFunction->GetFunction()->SourceCodeState() == FUNCTION_SOURCE_NOT_LOADED) { return; } if (entries == NULL) { if (fActiveSourceWorker < 0) { fActiveSourceWorker = spawn_thread(&_RetrieveMatchingSourceWorker, "source file query worker", B_NORMAL_PRIORITY, this); if (fActiveSourceWorker > 0) resume_thread(fActiveSourceWorker); } return; } int32 count = entries->CountStrings(); if (count > 0) { BPopUpMenu* menu = new(std::nothrow) BPopUpMenu(""); if (menu == NULL) return; BPrivate::ObjectDeleter<BPopUpMenu> menuDeleter(menu); BMenuItem* item = NULL; for (int32 i = 0; i < count; i++) { item = new(std::nothrow) BMenuItem(entries->StringAt(i).String(), NULL); if (item == NULL || !menu->AddItem(item)) { delete item; return; } } menu->AddSeparatorItem(); BMenuItem* manualItem = new(std::nothrow) BMenuItem( "Locate manually" B_UTF8_ELLIPSIS, NULL); if (manualItem == NULL || !menu->AddItem(manualItem)) { delete manualItem; return; } BPoint point; fSourcePathView->GetMouse(&point, NULL, false); fSourcePathView->ConvertToScreen(&point); item = menu->Go(point, false, true); if (item == NULL) return; else if (item != manualItem) { // if the user picks to locate the entry manually, // then fall through to the usual file panel logic // as if we'd found no matches at all. entry_ref ref; if (get_ref_for_path(item->Label(), &ref) == B_OK) { _HandleResolveMissingSourceFile(ref); return; } } } try { if (fFilePanel == NULL) { fFilePanel = new BFilePanel(B_OPEN_PANEL, new BMessenger(this)); } fFilePanel->Show(); } catch (...) { delete fFilePanel; fFilePanel = NULL; } }
void PApp::ArgvReceived(int32 argc, char **argv) { try { int i = 1, lineNr = -1; char *p; while (i < argc) { switch (argv[i][0]) { case '-': if (strcmp(argv[i], "-reload_worksheet") == 0) { PDoc *d = OpenWorksheet(); if (d && d->Lock()) d->Quit(); d = OpenWorksheet(); } else { Usage(); } break; case '+': lineNr = strtoul(argv[i] + 1, &p, 10) - 1; if (!p || p == argv[i] + 1) Usage(); break; default: { BPath path; if (argv[i][0] == '/') path.SetTo(argv[i]); else path.SetTo("/boot/home"); FailOSErr (path.InitCheck()); entry_ref doc; CDocWindow *d; FailOSErr (get_ref_for_path(path.Path(), &doc)); BEntry e; FailOSErr(e.SetTo(&doc)); if (e.Exists()) d = dynamic_cast<CDocWindow*>(OpenWindow(doc)); else { d = NewWindow(NULL); d->SetEntryRef(&doc); } if (d && lineNr >= 0) { BMessage m(msg_SelectLines); m.AddInt32("from", lineNr); m.AddInt32("to", lineNr - 1); d->PostMessage(&m, d->PreferredHandler()); } break; } } i++; } } catch (HErr& e) { e.DoError(); } } /* PApp::ArgvReceived */
void TFilePanel::MessageReceived(BMessage* message) { entry_ref ref; switch (message->what) { case B_REFS_RECEIVED: // item was double clicked in file panel (PoseView) if (message->FindRef("refs", &ref) == B_OK) { BEntry entry(&ref, true); if (entry.InitCheck() == B_OK) { // Double-click on dir or link-to-dir ALWAYS opens the // dir. If more than one dir is selected, the first is // entered. if (entry.IsDirectory()) { entry.GetRef(&ref); bool isDesktop = SwitchDirToDesktopIfNeeded(ref); PoseView()->SetIsDesktop(isDesktop); entry.SetTo(&ref); PoseView()->SwitchDir(&ref); SwitchDirMenuTo(&ref); } else { // Otherwise, we have a file or a link to a file. // AdjustButton has already tested the flavor; // all we have to do is see if the button is enabled. BButton* button = dynamic_cast<BButton*>( FindView("default button")); if (button == NULL) break; if (IsSavePanel()) { int32 count = 0; type_code type; message->GetInfo("refs", &type, &count); // Don't allow saves of multiple files if (count > 1) { ShowCenteredAlert( B_TRANSLATE( "Sorry, saving more than one " "item is not allowed."), B_TRANSLATE("Cancel")); } else { // if we are a savepanel, set up the // filepanel correctly then pass control // so we follow the same path as if the user // clicked the save button // set the 'name' fld to the current ref's // name notify the panel that the default // button should be enabled SetSaveText(ref.name); SelectionChanged(); HandleSaveButton(); } break; } // send handler a message and close BMessage openMessage(*fMessage); for (int32 index = 0; ; index++) { if (message->FindRef("refs", index, &ref) != B_OK) break; openMessage.AddRef("refs", &ref); } OpenSelectionCommon(&openMessage); } } } break; case kSwitchDirectory: { entry_ref ref; // this comes from dir menu or nav menu, so switch directories if (message->FindRef("refs", &ref) == B_OK) { BEntry entry(&ref, true); if (entry.GetRef(&ref) == B_OK) SetTo(&ref); } break; } case kSwitchToHome: { BPath homePath; entry_ref ref; if (find_directory(B_USER_DIRECTORY, &homePath) != B_OK || get_ref_for_path(homePath.Path(), &ref) != B_OK) { break; } SetTo(&ref); break; } case kAddCurrentDir: { BPath path; if (find_directory(B_USER_SETTINGS_DIRECTORY, &path, true) != B_OK) { break; } path.Append(kGoDirectory); BDirectory goDirectory(path.Path()); if (goDirectory.InitCheck() == B_OK) { BEntry entry(TargetModel()->EntryRef()); entry.GetPath(&path); BSymLink link; goDirectory.CreateSymLink(TargetModel()->Name(), path.Path(), &link); } break; } case kEditFavorites: { BPath path; if (find_directory (B_USER_SETTINGS_DIRECTORY, &path, true) != B_OK) { break; } path.Append(kGoDirectory); BMessenger msgr(kTrackerSignature); if (msgr.IsValid()) { BMessage message(B_REFS_RECEIVED); entry_ref ref; if (get_ref_for_path(path.Path(), &ref) == B_OK) { message.AddRef("refs", &ref); msgr.SendMessage(&message); } } break; } case kCancelButton: PostMessage(B_QUIT_REQUESTED); break; case kResizeToFit: ResizeToFit(); break; case kOpenDir: OpenDirectory(); break; case kOpenParentDir: OpenParent(); break; case kDefaultButton: if (fIsSavePanel) { if (PoseView()->IsFocus() && PoseView()->SelectionList()->CountItems() == 1) { Model* model = (PoseView()->SelectionList()-> FirstItem())->TargetModel(); if (model->ResolveIfLink()->IsDirectory()) { PoseView()->CommitActivePose(); PoseView()->OpenSelection(); break; } } HandleSaveButton(); } else HandleOpenButton(); break; case B_OBSERVER_NOTICE_CHANGE: { int32 observerWhat; if (message->FindInt32("be:observe_change_what", &observerWhat) == B_OK) { switch (observerWhat) { case kDesktopFilePanelRootChanged: { bool desktopIsRoot = true; if (message->FindBool("DesktopFilePanelRoot", &desktopIsRoot) == B_OK) { TrackerSettings(). SetDesktopFilePanelRoot(desktopIsRoot); } SetTo(TargetModel()->EntryRef()); break; } } } break; } default: _inherited::MessageReceived(message); break; } }
void DownloadWindow::MessageReceived(BMessage* message) { switch (message->what) { case INIT: { _LoadSettings(); // Small trick to get the correct enabled status of the Remove // finished button _DownloadFinished(NULL); break; } case B_DOWNLOAD_ADDED: { BWebDownload* download; if (message->FindPointer("download", reinterpret_cast<void**>( &download)) == B_OK) { _DownloadStarted(download); } break; } case B_DOWNLOAD_REMOVED: { BWebDownload* download; if (message->FindPointer("download", reinterpret_cast<void**>( &download)) == B_OK) { _DownloadFinished(download); } break; } case OPEN_DOWNLOADS_FOLDER: { entry_ref ref; status_t status = get_ref_for_path(fDownloadPath.String(), &ref); if (status == B_OK) status = be_roster->Launch(&ref); if (status != B_OK && status != B_ALREADY_RUNNING) { BString errorString(B_TRANSLATE_COMMENT("The downloads folder could " "not be opened.\n\nError: %error", "Don't translate " "variable %error")); errorString.ReplaceFirst("%error", strerror(status)); BAlert* alert = new BAlert(B_TRANSLATE("Error opening downloads " "folder"), errorString.String(), B_TRANSLATE("OK")); alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(NULL); } break; } case REMOVE_FINISHED_DOWNLOADS: _RemoveFinishedDownloads(); break; case REMOVE_MISSING_DOWNLOADS: _RemoveMissingDownloads(); break; case SAVE_SETTINGS: _ValidateButtonStatus(); _SaveSettings(); break; case SETTINGS_VALUE_CHANGED: { BString string; if (message->FindString("name", &string) == B_OK && string == kSettingsKeyDownloadPath && message->FindString("value", &string) == B_OK) { fDownloadPath = string; } break; } default: BWindow::MessageReceived(message); break; } }
void UrlWrapper::ArgvReceived(int32 argc, char** argv) { if (argc <= 1) return; const char* failc = " || read -p 'Press any key'"; const char* pausec = " ; read -p 'Press any key'"; char* args[] = { (char *)"/bin/sh", (char *)"-c", NULL, NULL}; BPrivate::Support::BUrl url(argv[1]); BString full = url.Full(); BString proto = url.Proto(); BString host = url.Host(); BString port = url.Port(); BString user = url.User(); BString pass = url.Pass(); BString path = url.Path(); if (url.InitCheck() < 0) { fprintf(stderr, "malformed url: '%s'\n", url.String()); return; } // XXX: debug PRINT(("PROTO='%s'\n", proto.String())); PRINT(("HOST='%s'\n", host.String())); PRINT(("PORT='%s'\n", port.String())); PRINT(("USER='******'\n", user.String())); PRINT(("PASS='******'\n", pass.String())); PRINT(("PATH='%s'\n", path.String())); if (proto == "telnet") { BString cmd("telnet "); if (url.HasUser()) cmd << "-l " << user << " "; cmd << host; if (url.HasPort()) cmd << " " << port; PRINT(("CMD='%s'\n", cmd.String())); cmd << failc; args[2] = (char*)cmd.String(); be_roster->Launch(kTerminalSig, 3, args); return; } // see draft: // http://tools.ietf.org/wg/secsh/draft-ietf-secsh-scp-sftp-ssh-uri/ if (proto == "ssh") { BString cmd("ssh "); if (url.HasUser()) cmd << "-l " << user << " "; if (url.HasPort()) cmd << "-oPort=" << port << " "; cmd << host; PRINT(("CMD='%s'\n", cmd.String())); cmd << failc; args[2] = (char*)cmd.String(); be_roster->Launch(kTerminalSig, 3, args); // TODO: handle errors return; } if (proto == "ftp") { BString cmd("ftp "); /* if (user.Length()) cmd << "-l " << user << " "; cmd << host; */ cmd << full; PRINT(("CMD='%s'\n", cmd.String())); cmd << failc; args[2] = (char*)cmd.String(); be_roster->Launch(kTerminalSig, 3, args); // TODO: handle errors return; } if (proto == "sftp") { BString cmd("sftp "); //cmd << url; if (url.HasPort()) cmd << "-oPort=" << port << " "; if (url.HasUser()) cmd << user << "@"; cmd << host; if (url.HasPath()) cmd << ":" << path; PRINT(("CMD='%s'\n", cmd.String())); cmd << failc; args[2] = (char*)cmd.String(); be_roster->Launch(kTerminalSig, 3, args); // TODO: handle errors return; } if (proto == "finger") { BString cmd("/bin/finger "); if (url.HasUser()) cmd << user; if (url.HasHost() == 0) host = "127.0.0.1"; cmd << "@" << host; PRINT(("CMD='%s'\n", cmd.String())); cmd << pausec; args[2] = (char*)cmd.String(); be_roster->Launch(kTerminalSig, 3, args); // TODO: handle errors return; } if (proto == "http") { BString cmd("/bin/wget "); //cmd << url; if (url.HasUser()) cmd << user << "@"; cmd << full; PRINT(("CMD='%s'\n", cmd.String())); cmd << pausec; args[2] = (char*)cmd.String(); be_roster->Launch(kTerminalSig, 3, args); // TODO: handle errors return; } if (proto == "file") { BMessage m(B_REFS_RECEIVED); entry_ref ref; _DecodeUrlString(path); if (get_ref_for_path(path.String(), &ref) < B_OK) return; m.AddRef("refs", &ref); be_roster->Launch(kTrackerSig, &m); return; } // XXX:TODO: split options if (proto == "query") { // mktemp ? BString qname("/tmp/query-url-temp-"); qname << getpid() << "-" << system_time(); BFile query(qname.String(), O_CREAT|O_EXCL); // XXX: should check for failure BString s; int32 v; _DecodeUrlString(full); // TODO: handle options (list of attrs in the column, ...) v = 'qybF'; // QuerY By Formula XXX: any #define for that ? query.WriteAttr("_trk/qryinitmode", B_INT32_TYPE, 0LL, &v, sizeof(v)); s = "TextControl"; query.WriteAttr("_trk/focusedView", B_STRING_TYPE, 0LL, s.String(), s.Length()+1); s = full; PRINT(("QUERY='%s'\n", s.String())); query.WriteAttr("_trk/qryinitstr", B_STRING_TYPE, 0LL, s.String(), s.Length()+1); query.WriteAttr("_trk/qrystr", B_STRING_TYPE, 0LL, s.String(), s.Length()+1); s = "application/x-vnd.Be-query"; query.WriteAttr("BEOS:TYPE", 'MIMS', 0LL, s.String(), s.Length()+1); BEntry e(qname.String()); entry_ref er; if (e.GetRef(&er) >= B_OK) be_roster->Launch(&er); return; } if (proto == "sh") { BString cmd(full); if (_Warn(url.String()) != B_OK) return; PRINT(("CMD='%s'\n", cmd.String())); cmd << pausec; args[2] = (char*)cmd.String(); be_roster->Launch(kTerminalSig, 3, args); // TODO: handle errors return; } if (proto == "beshare") { team_id team; BMessenger msgr(kBeShareSig); // if no instance is running, or we want a specific server, start it. if (!msgr.IsValid() || url.HasHost()) { be_roster->Launch(kBeShareSig, (BMessage*)NULL, &team); msgr = BMessenger(NULL, team); } if (url.HasHost()) { BMessage mserver('serv'); mserver.AddString("server", host); msgr.SendMessage(&mserver); } if (url.HasPath()) { BMessage mquery('quer'); mquery.AddString("query", path); msgr.SendMessage(&mquery); } // TODO: handle errors return; } if (proto == "icq" || proto == "msn") { // TODO team_id team; be_roster->Launch(kIMSig, (BMessage*)NULL, &team); BMessenger msgr(NULL, team); if (url.HasHost()) { BMessage mserver(B_REFS_RECEIVED); mserver.AddString("server", host); msgr.SendMessage(&mserver); } // TODO: handle errors return; } if (proto == "mms" || proto == "rtp" || proto == "rtsp") { args[0] = (char*)url.String(); be_roster->Launch(kVLCSig, 1, args); return; } // Audio: ? // vnc: ? // irc: ? // // svn: ? // cvs: ? // smb: cifsmount ? // nfs: mount_nfs ? // // mailto: ? Mail & Beam both handle it already (not fully though). // // mid: cid: as per RFC 2392 // http://www.rfc-editor.org/rfc/rfc2392.txt query MAIL:cid // // itps: pcast: podcast: s//http/ + parse xml to get url to mp3 stream... // audio: s//http:/ + default MediaPlayer // -- see http://forums.winamp.com/showthread.php?threadid=233130 // // gps: ? I should submit an RFC for that one :) }
char* determineBinaryLocation(const char* launchcmd) { FILE *f; char *path, *delim, *envpath, *testcmd; const char* initial; #ifdef __BEOS__ // Thanks Caz entry_ref ref; BPath bpath; if(get_ref_for_path(launchcmd, &ref) == B_NO_ERROR) { BEntry entry(&ref); if(entry.GetPath(&bpath) == B_NO_ERROR) { // since we dup anything returned, this isn't a problem initial = bpath.Path(); } } #else // not changing the constant, changing what it points to initial = launchcmd; #endif #ifdef _WIN32 #define DIRLISTSEPARATOR ';' #else #define DIRLISTSEPARATOR ':' #endif f = fopen(initial, "rb"); if( f != NULL ) { fclose(f); path = cppstrdup(initial); delim = strrchr(path, '/'); #ifdef _WIN32 delim = (char*)max((unsigned int)delim, (unsigned int)strrchr(path, '\\')); #endif if( delim == NULL ) { delete path; binloc = "."; return cppstrdup("."); } delim[0] = '\0'; binloc = path; return path; } envpath = getenv("PATH"); path = envpath; while( (delim = strchr(envpath, DIRLISTSEPARATOR)) != NULL ) { delim[0] = '\0'; delim++; if( path[strlen(path)-1] != '/' #ifdef _WIN32 && path[strlen(path)-1] != '\\' #endif ) { testcmd = new char[strlen(path)+strlen(initial)+1]; sprintf(testcmd, "%s/%s", path, initial); } else { testcmd = new char[strlen(path)+strlen(initial)]; sprintf(testcmd, "%s%s", path, initial); } if( (f = fopen(testcmd, "rb")) != NULL ) { fclose(f); path = cppstrdup(initial); delim = strrchr(path, '/'); #ifdef _WIN32 delim = (char*)max((unsigned int)delim, (unsigned int)strrchr(path, '\\')); #endif if( delim == NULL ) { delete[] path; delete[] testcmd; binloc = "."; return cppstrdup("."); } delim[0] = '\0'; delete[] testcmd; binloc = path; return path; } path = delim; delete[] testcmd; } binloc = "."; return cppstrdup("."); }
void nsbeos_gui_view_source(struct hlcache_handle *content) { char *temp_name; bool done = false; BPath path; status_t err; size_t size; const char *source = content_get_source_data(content, &size); if (!content || !source) { beos_warn_user("MiscError", "No document source"); return; } /* try to load local files directly. */ temp_name = url_to_path(nsurl_access(hlcache_handle_get_url(content))); if (temp_name) { path.SetTo(temp_name); BEntry entry; if (entry.SetTo(path.Path()) >= B_OK && entry.Exists() && entry.IsFile()) done = true; } if (!done) { /* We cannot release the requested filename until after it * has finished being used. As we can't easily find out when * this is, we simply don't bother releasing it and simply * allow it to be re-used next time NetSurf is started. The * memory overhead from doing this is under 1 byte per * filename. */ const char *filename = filename_request(); if (!filename) { beos_warn_user("NoMemory", 0); return; } path.SetTo(TEMP_FILENAME_PREFIX); path.Append(filename); BFile file(path.Path(), B_WRITE_ONLY | B_CREATE_FILE); err = file.InitCheck(); if (err < B_OK) { beos_warn_user("IOError", strerror(err)); return; } err = file.Write(source, size); if (err < B_OK) { beos_warn_user("IOError", strerror(err)); return; } lwc_string *mime = content_get_mime_type(content); if (mime) { file.WriteAttr("BEOS:TYPE", B_MIME_STRING_TYPE, 0LL, lwc_string_data(mime), lwc_string_length(mime) + 1); lwc_string_unref(mime); } } entry_ref ref; if (get_ref_for_path(path.Path(), &ref) < B_OK) return; BMessage m(B_REFS_RECEIVED); m.AddRef("refs", &ref); // apps to try const char *editorSigs[] = { "application/x-vnd.beunited.pe", "application/x-vnd.XEmacs", "application/x-vnd.Haiku-StyledEdit", "application/x-vnd.Be-STEE", "application/x-vnd.yT-STEE", NULL }; int i; for (i = 0; editorSigs[i]; i++) { team_id team = -1; { BMessenger msgr(editorSigs[i], team); if (msgr.SendMessage(&m) >= B_OK) break; } err = be_roster->Launch(editorSigs[i], (BMessage *)&m, &team); if (err >= B_OK) break; } }
const char *DoInclude(MTextAddOn& ao, const char *incl, const char *start, const char *end) { status_t err = B_NO_ERROR; do { BEntry e; entry_ref ref; if (ao.GetRef(ref) == B_OK) { BDirectory d; if ((err = BEntry(&ref).GetParent(&d)) != B_OK) break; if ((err = d.FindEntry(incl, &e, true)) != B_OK) break; } else { if ((err = get_ref_for_path(incl, &ref)) != B_OK) break; if ((err = e.SetTo(&ref)) != B_OK) break; } int tStart, tEnd; tStart = start - ao.Text(); tEnd = tStart + (end - start); ao.Select(tStart, tEnd); ao.Delete(); string str; BFile file; if ((err = file.SetTo(&e, B_READ_ONLY)) != B_OK) break; size_t size = file.Seek(0, SEEK_END); file.Seek(0, SEEK_SET); char *t = (char *)malloc(size + 3); if (t == NULL) { err = B_ERROR; break; } file.Read(t + 1, size); t[0] = '\n'; if (t[size] == '\n') t[size + 1] = 0; else { t[size + 1] = '\n'; t[size + 2] = 0; } const char *txtp = start, *txt = ao.Text(); char lws[256], *lw = lws; while (--txtp >= txt && *txtp != '\n') ; while (isspace(*++txtp)) *lw++ = *txtp; *lw = 0; str = t; BPath p; if ((err = e.GetPath(&p)) != B_OK) break; ReplaceGlossary(str, p.Path(), lws); ao.Insert(str.c_str()); end = ao.Text() + tStart + str.length(); } while (false); if (err) { char s[PATH_MAX]; sprintf(s, "Error including %s: %s", incl, strerror(err)); beep(); MWarningAlert(s).Go(); } return end; } /* DoInclude */
int main(int argc, char **argv) { int optchar; int verbose = FALSE; int silent = FALSE; int randomize = FALSE; int number_files = 0; int reverb = 4; float synth_volume = 1.0; float sample_volume = 1.0; status_t error; BSynth Synth; BMidiSynthFile mFile; entry_ref file; /* * data for long getopt * * */ static struct option long_options[] = { { "verbose", // name no_argument, // has flag? NULL, // return val 'v' // value to return }, { "silent", // name no_argument, // has flag? NULL, // return val 's' // value to return }, { "version", no_argument, NULL, 'V' }, { "help", no_argument, NULL, 'h' }, { "repeat", no_argument, NULL, 'r' }, { "randomize", no_argument, NULL, 'r' }, { "reverb", required_argument, //requires argument NULL, 'R' }, { "volume", required_argument, NULL, 'V' }, { "sample", required_argument, NULL, 'S' }, { NULL, 0, NULL, 0} //final element MUST be 0-filled }; /* * First, parse the arguments * * * */ while ((optchar = getopt_long(argc, argv, "vshrR:V:S:", long_options, NULL)) != EOF) { switch(optchar) { case 'v': //verbose if (silent) fprintf(stderr, "-v and -s are mutually " "exclusive!\n"); verbose = TRUE; silent = FALSE; break; case 's': //silent if (verbose) fprintf(stderr, "-s and -v are mutually " "exclusive!\n"); silent = TRUE; verbose = FALSE; break; case 'V': // adjust volume synth_volume = atof(optarg); break; case 'S': // adjust volume sample_volume = atof(optarg); break; case 'h': PrintHelp(); exit(0); break; case 'r': // randomize/repeat randomize = TRUE; break; case 'R': //reverb // set reverb by optarg reverb = atoi(optarg); // prevent illegal values if (reverb < 1) reverb = 1; if (reverb > 6) reverb = 6; break; case '?': //unsupported flag!! if (!silent) PrintHelp(); exit(1); break; } } argc -= optind; argv += optind; number_files = argc; if (number_files == 0 && !silent) { PrintHelp(); exit(1); } if (verbose) fprintf(stdout, "Loading synth samples\n"); Synth.LoadSynthData(B_BIG_SYNTH); Synth.SetReverb((reverb_mode)reverb); Synth.SetSynthVolume(synth_volume); Synth.SetSampleVolume(sample_volume); if (randomize) { srand(time(NULL)); while (number_files) { int i; i = number_files > 1 ? rand() % number_files : 0; if (verbose) fprintf(stdout, "File %s\n", argv[i]); //get refs on it error = get_ref_for_path(argv[i], &file); if (error) { if (!silent) fprintf(stderr, "unable to get refs on file %s\n", argv[i]); } else { error = mFile.LoadFile(&file); if (error & !silent) { fprintf(stderr, "Unable to load %s\n", argv[i]); } } /* * error is TRUE if the file couldn't be loaded * or if it couldn't be referenced */ if (error) { // move the argvs number_files--; argv[i] = NULL; if (i != number_files) { memmove(argv+i, argv+i+1, (number_files-i) * sizeof(char *)); } } else { mFile.Start(); while (!mFile.IsFinished()) snooze(100000); mFile.Fade(); } } } else { int i; for (i =0 ; i < number_files; i++) { if (verbose) fprintf(stdout, "File %s\n", argv[i]); //get refs on it error = get_ref_for_path(argv[i], &file); if (error) { if (!silent) fprintf(stderr, "unable to get refs on file %s\n", argv[1]); } else { error = mFile.LoadFile(&file); if (error & !silent) { fprintf(stderr, "Unable to load %s\n", argv[i]); } } if (!error) { mFile.Start(); while (!mFile.IsFinished()) snooze(100000); mFile.Fade(); } } } return 0; }
void PApp::FindAndOpen(const char *file, const char* fromSource) { char *bi = NULL; bool found = false; try { BEntry e; entry_ref doc; BDirectory d; if (!found && fromSource) { BPath path; entry_ref eref; if (get_ref_for_path(fromSource, &eref) == B_OK) { vector<BString> inclPathVect; if (!ProjectRoster->GetIncludePathsForFile(&eref, inclPathVect)) ProjectRoster->GetAllIncludePaths(inclPathVect); for(uint32 i=0; !found && i<inclPathVect.size(); ++i) { if (path.SetTo(inclPathVect[i].String(), file) != B_OK) continue; if (e.SetTo(path.Path(), true) != B_OK) continue; if (e.Exists() && e.IsFile()) { FailOSErr(e.GetRef(&doc)); found = true; } } } } if (!found && gPrefs->GetPrefInt(prf_I_BeIncludes)) { bi = strdup(getenv("BEINCLUDES")); char *ip = bi; char *p = ip; while (p && !found) { char *pe = strchr(p, ';'); if (pe) *pe = 0; FailOSErr(d.SetTo(p)); if (d.Contains(file, B_FILE_NODE | B_SYMLINK_NODE)) { FailOSErr(d.FindEntry(file, &e, true)); if (!e.IsFile()) THROW((0)); FailOSErr(e.GetRef(&doc)); found = true; } p = (pe && pe[1]) ? pe + 1 : NULL; } } if (!found) { const char *p; int i = 0; while ((p = gPrefs->GetIxPrefString(prf_X_IncludePath, i++))!= NULL && !found) { if (e.SetTo(p) != B_OK || !e.Exists()) continue; FailOSErr(d.SetTo(p)); if (d.Contains(file, B_FILE_NODE | B_SYMLINK_NODE)) { FailOSErr(d.FindEntry(file, &e, true)); if (!e.IsFile()) THROW((0)); FailOSErr(e.GetRef(&doc)); found = true; } } } if (found) OpenWindow(doc); else beep(); } catch (HErr& e) { beep(); } if (bi) free(bi); } // PApp::FindAndOpen
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. }
void DownloadProgressView::MessageReceived(BMessage* message) { switch (message->what) { case B_DOWNLOAD_STARTED: { BString path; if (message->FindString("path", &path) != B_OK) break; fPath.SetTo(path); BEntry entry(fPath.Path()); fIconView->SetTo(entry); fStatusBar->Reset(fPath.Leaf()); _StartNodeMonitor(entry); // Immediately switch to speed display whenever a new download // starts. sShowSpeed = true; sLastEstimatedFinishSpeedToggleTime = fProcessStartTime = fLastSpeedReferenceTime = fEstimatedFinishReferenceTime = system_time(); break; } case B_DOWNLOAD_PROGRESS: { int64 currentSize; int64 expectedSize; if (message->FindInt64("current size", ¤tSize) == B_OK && message->FindInt64("expected size", &expectedSize) == B_OK) { _UpdateStatus(currentSize, expectedSize); } break; } case B_DOWNLOAD_REMOVED: // TODO: This is a bit asymetric. The removed notification // arrives here, but it would be nicer if it arrived // at the window... Window()->PostMessage(message); break; case OPEN_DOWNLOAD: { // TODO: In case of executable files, ask the user first! entry_ref ref; status_t status = get_ref_for_path(fPath.Path(), &ref); if (status == B_OK) status = be_roster->Launch(&ref); if (status != B_OK && status != B_ALREADY_RUNNING) { BAlert* alert = new BAlert(B_TRANSLATE("Open download error"), B_TRANSLATE("The download could not be opened."), B_TRANSLATE("OK")); alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(NULL); } break; } case RESTART_DOWNLOAD: BWebPage::RequestDownload(fURL); break; case CANCEL_DOWNLOAD: fDownload->Cancel(); DownloadCanceled(); break; case REMOVE_DOWNLOAD: { Window()->PostMessage(SAVE_SETTINGS); RemoveSelf(); delete this; // TOAST! return; } case B_NODE_MONITOR: { int32 opCode; if (message->FindInt32("opcode", &opCode) != B_OK) break; switch (opCode) { case B_ENTRY_REMOVED: fIconView->SetIconDimmed(true); DownloadCanceled(); break; case B_ENTRY_MOVED: { // Follow the entry to the new location dev_t device; ino_t directory; const char* name; if (message->FindInt32("device", reinterpret_cast<int32*>(&device)) != B_OK || message->FindInt64("to directory", reinterpret_cast<int64*>(&directory)) != B_OK || message->FindString("name", &name) != B_OK || strlen(name) == 0) { break; } // Construct the BEntry and update fPath entry_ref ref(device, directory, name); BEntry entry(&ref); if (entry.GetPath(&fPath) != B_OK) break; // Find out if the directory is the Trash for this // volume char trashPath[B_PATH_NAME_LENGTH]; if (find_directory(B_TRASH_DIRECTORY, device, false, trashPath, B_PATH_NAME_LENGTH) == B_OK) { BPath trashDirectory(trashPath); BPath parentDirectory; fPath.GetParent(&parentDirectory); if (parentDirectory == trashDirectory) { // The entry was moved into the Trash. // If the download is still in progress, // cancel it. if (fDownload) fDownload->Cancel(); fIconView->SetIconDimmed(true); DownloadCanceled(); break; } else if (fIconView->IsIconDimmed()) { // Maybe it was moved out of the trash. fIconView->SetIconDimmed(false); } } // Inform download of the new path if (fDownload) fDownload->HasMovedTo(fPath); float value = fStatusBar->CurrentValue(); fStatusBar->Reset(name); fStatusBar->SetTo(value); Window()->PostMessage(SAVE_SETTINGS); break; } case B_ATTR_CHANGED: { BEntry entry(fPath.Path()); fIconView->SetIconDimmed(false); fIconView->SetTo(entry); break; } } break; } // Context menu messages case COPY_URL_TO_CLIPBOARD: if (be_clipboard->Lock()) { BMessage* data = be_clipboard->Data(); if (data != NULL) { be_clipboard->Clear(); data->AddData("text/plain", B_MIME_TYPE, fURL.String(), fURL.Length()); } be_clipboard->Commit(); be_clipboard->Unlock(); } break; case OPEN_CONTAINING_FOLDER: if (fPath.InitCheck() == B_OK) { BPath containingFolder; if (fPath.GetParent(&containingFolder) != B_OK) break; BEntry entry(containingFolder.Path()); if (!entry.Exists()) break; entry_ref ref; if (entry.GetRef(&ref) != B_OK) break; be_roster->Launch(&ref); // Use Tracker scripting and select the download pose // in the window. // TODO: We should somehow get the window that just openend. // Using the name like this is broken when there are multiple // windows open with this name. Also Tracker does not scroll // to this entry. BString windowName = ref.name; BString fullWindowName = containingFolder.Path(); BMessenger trackerMessenger("application/x-vnd.Be-TRAK"); if (trackerMessenger.IsValid() && get_ref_for_path(fPath.Path(), &ref) == B_OK) { // We need to wait a bit until the folder is open. // TODO: This is also too fragile... we should be able // to wait for the roster message. snooze(250000); int32 tries = 2; while (tries > 0) { BMessage selectionCommand(B_SET_PROPERTY); selectionCommand.AddSpecifier("Selection"); selectionCommand.AddSpecifier("Poses"); selectionCommand.AddSpecifier("Window", windowName.String()); selectionCommand.AddRef("data", &ref); BMessage reply; trackerMessenger.SendMessage(&selectionCommand, &reply); int32 error; if (reply.FindInt32("error", &error) != B_OK || error == B_OK) { break; } windowName = fullWindowName; tries--; } } } break; default: BGroupView::MessageReceived(message); } }
status_t MovieEncoder::Encode() { int32 framesLeft = fFileList->CountItems(); int32 framesWritten = 0; if (framesLeft <= 0) { DisposeData(); BMessage message(kEncodingFinished); message.AddInt32("status", (int32)B_ERROR); fMessenger.SendMessage(&message); return B_ERROR; } // Create movie char movieName[B_FILE_NAME_LENGTH]; MakeUniqueName(fOutputFile.Path(), movieName, B_FILE_NAME_LENGTH); entry_ref movieRef; get_ref_for_path(movieName, &movieRef); media_file_format fileFormat; if (!GetMediaFileFormat(fFamily, fileFormat)) { BMessage message(kEncodingFinished); message.AddInt32("status", (int32)B_ERROR); fMessenger.SendMessage(&message); return B_ERROR; } BBitmap* bitmap = BTranslationUtils::GetBitmapFile((const char*)fFileList->ItemAtFast(0)); BRect sourceFrame = bitmap->Bounds(); delete bitmap; if (!fDestFrame.IsValid()) fDestFrame = sourceFrame.OffsetToCopy(B_ORIGIN); BitmapMovie* movie = new BitmapMovie(fDestFrame.IntegerWidth() + 1, fDestFrame.IntegerHeight() + 1, fColorSpace); status_t error = movie->CreateFile(movieRef, fileFormat, fFormat, fCodecInfo); if (error < B_OK) { delete movie; DisposeData(); BMessage message(kEncodingFinished); message.AddInt32("status", (int32)error); fMessenger.SendMessage(&message); return error; } // Bitmap and view used to convert the source bitmap // to the correct size and depth BBitmap* destBitmap = new BBitmap(fDestFrame, fColorSpace, true); BView* destDrawer = new BView(fDestFrame, "drawing view", B_FOLLOW_NONE, 0); if (destBitmap->Lock()) { destBitmap->AddChild(destDrawer); destBitmap->Unlock(); } const uint32 keyFrameFrequency = 10; BMessage progressMessage(B_UPDATE_STATUS_BAR); progressMessage.AddFloat("delta", 1.0); bool keyFrame = true; for (int32 i = 0; i < fFileList->CountItems(); i++) { if (framesWritten % keyFrameFrequency == 0) keyFrame = true; const char* fileName = reinterpret_cast<const char*>(fFileList->ItemAtFast(i)); BBitmap* frame = BTranslationUtils::GetBitmapFile(fileName); if (frame == NULL) continue; // Draw scaled if (error == B_OK) { destBitmap->Lock(); destDrawer->DrawBitmap(frame, frame->Bounds(), destDrawer->Bounds()); destDrawer->Sync(); destBitmap->Unlock(); } delete frame; if (error == B_OK) error = movie->WriteFrame(destBitmap, keyFrame); if (error == B_OK) { framesWritten++; keyFrame = false; } else { printf("%s\n", strerror(error)); break; } if (fMessenger.IsValid()) fMessenger.SendMessage(new BMessage(progressMessage)); } //printf("%ld frames written\n", framesWritten); delete movie; delete destBitmap; //delete cursor; DisposeData(); BMessage message(kEncodingFinished); message.AddInt32("status", (int32)B_OK); fMessenger.SendMessage(&message); return B_OK; }
bool CStdErrParser::MatchOne(bool flush) { vector<CErrPatInfo>::iterator ri; CMessageItem *item = NULL; entry_ref ref; int m = fErrBuffer.length(); for (ri = fPatterns.begin(); item == NULL && ri != fPatterns.end(); ++ri) { CRegex& rx = *ri->fInfo; const char *text = fErrBuffer.c_str(); int size = fErrBuffer.length(); int r = rx.Match(text, size, 0); if (r) { if (r == krx_NoMatch) continue; else THROW((rx.ErrorStr().String())); } BString file; if (text[rx.MatchStart(ri->fFile)] != kDirectorySeparator && fCWD) file << fCWD << kDirectorySeparator; file << rx.MatchStr(text, ri->fFile); if (get_ref_for_path(file.String(), &ref) == B_OK && BEntry(&ref).Exists()) { int line = strtoul(rx.MatchStr(text, ri->fLine).String(), NULL, 10); bool warning = false; if (ri->fWarning) { BString wstr = rx.MatchStr(text, ri->fWarning); warning = (wstr.ICompare("warning", 7) == 0); } item = new CMessageItem(rx.MatchStr(text, ri->fMsg).String(), rx.MatchLen(ri->fMsg), warning ? CMessageItem::msgWarning : CMessageItem::msgError, &ref, line); fErrBuffer.erase(rx.MatchStart(), rx.MatchLen()); m = rx.MatchStart(); } } int found = false; if (item || flush) { BAutolock lock(fErrList->Window()); if (lock.IsLocked()) { font_height fi; be_plain_font->GetHeight(&fi); float h = fi.ascent + fi.descent + 2; while (m > 0) { int l = (int)fErrBuffer.find('\n'); CMessageItem *i = new CMessageItem(fErrBuffer.c_str(), std::min(m, l), CMessageItem::msgInfo); fErrList->AddItem(i); i->SetHeight(h); fErrBuffer.erase(0, std::min(l + 1, m)); m -= l + 1; found = true; } if (item) { fErrList->AddItem(item); item->SetHeight(h); found = true; } if (found) { fErrList->Select(fErrList->CountItems() - 1); fErrList->ScrollToSelection(); if (fErrList->Window()->IsHidden()) fErrList->Window()->Show(); } } } return found; } // CStdErrParser::MatchOne