From 9d3f15c60ec469d37e3f83930c4b36b48b5af294 Mon Sep 17 00:00:00 2001 From: Ingo Weinhold Date: Sat, 20 Oct 2007 20:40:09 +0000 Subject: [PATCH] Style cleanup patch by Vasilis Kaoutsis. Small changes by myself. git-svn-id: file:///srv/svn/repos/haiku/haiku/trunk@22629 a95241bf-73f2-0310-859d-f6bbb57e9c96 --- src/apps/codycam/CodyCam.cpp | 551 ++++++++++---------- src/apps/codycam/CodyCam.h | 192 ++++--- src/apps/codycam/FtpClient.cpp | 648 ++++++++++------------- src/apps/codycam/FtpClient.h | 108 ++-- src/apps/codycam/Settings.cpp | 183 ++++--- src/apps/codycam/Settings.h | 84 +-- src/apps/codycam/SettingsHandler.cpp | 357 +++++++------ src/apps/codycam/SettingsHandler.h | 200 ++++---- src/apps/codycam/VideoConsumer.cpp | 739 ++++++++++++--------------- src/apps/codycam/VideoConsumer.h | 274 +++++----- 10 files changed, 1623 insertions(+), 1713 deletions(-) diff --git a/src/apps/codycam/CodyCam.cpp b/src/apps/codycam/CodyCam.cpp index 8905a38133..353c8d7a8d 100644 --- a/src/apps/codycam/CodyCam.cpp +++ b/src/apps/codycam/CodyCam.cpp @@ -1,23 +1,24 @@ #include "CodyCam.h" -#include #include #include +#include + +#include #include -#include -#include -#include -#include -#include #include #include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include +#include #include +#include #include -#include #define VIDEO_SIZE_X 320 @@ -38,40 +39,93 @@ const int32 kMenuHeight = 15; const int32 kButtonHeight = 15; const int32 kSliderViewRectHeight = 40; -const rgb_color kViewGray = { 216, 216, 216, 255}; +const rgb_color kViewGray = {216, 216, 216, 255}; -static void ErrorAlert(const char * message, status_t err); -static status_t AddTranslationItems( BMenu * intoMenu, uint32 from_type); +static void ErrorAlert(const char* message, status_t err); +static status_t AddTranslationItems(BMenu* intoMenu, uint32 fromType); #define CALL printf #define ERROR printf #define FTPINFO printf #define INFO printf -//--------------------------------------------------------------- -// The Application -//--------------------------------------------------------------- -int main() { - chdir("/boot/home"); - CodyCam app; - app.Run(); - return 0; +// Utility functions + +static void +ErrorAlert(const char* message, status_t err) +{ + (new BAlert("", message, "Quit"))->Go(); + + printf("%s\n%s [%lx]", message, strerror(err), err); + be_app->PostMessage(B_QUIT_REQUESTED); } -//--------------------------------------------------------------- -CodyCam::CodyCam() : - BApplication("application/x-vnd.Be.CodyCam"), +status_t +AddTranslationItems(BMenu* intoMenu, uint32 fromType) +{ + + BTranslatorRoster* use; + char* translatorTypeName; + const char* translatorIdName; + + use = BTranslatorRoster::Default(); + translatorIdName = "be:translator"; + translatorTypeName = "be:type"; + translator_id* ids = NULL; + int32 count = 0; + + status_t err = use->GetAllTranslators(&ids, &count); + if (err < B_OK) + return err; + + for (int tix = 0; tix < count; tix++) { + const translation_format* formats = NULL; + int32 num_formats = 0; + bool ok = false; + err = use->GetInputFormats(ids[tix], &formats, &num_formats); + if (err == B_OK) + for (int iix = 0; iix < num_formats; iix++) { + if (formats[iix].type == fromType) { + ok = true; + break; + } + } + + if (!ok) + continue; + + err = use->GetOutputFormats(ids[tix], &formats, &num_formats); + if (err == B_OK) + for (int oix = 0; oix < num_formats; oix++) { + if (formats[oix].type != fromType) { + BMessage* itemmsg; + itemmsg = new BMessage(msg_translate); + itemmsg->AddInt32(translatorIdName, ids[tix]); + itemmsg->AddInt32(translatorTypeName, formats[oix].type); + intoMenu->AddItem(new BMenuItem(formats[oix].name, itemmsg)); + } + } + } + delete[] ids; + return B_OK; +} + + +// #pragma mark - + + +CodyCam::CodyCam() + : BApplication("application/x-vnd.Be.CodyCam"), fMediaRoster(NULL), fVideoConsumer(NULL), fWindow(NULL), fPort(0), - mVideoControlWindow(NULL) + fVideoControlWindow(NULL) { } -//--------------------------------------------------------------- CodyCam::~CodyCam() { @@ -87,50 +141,47 @@ CodyCam::~CodyCam() CALL("CodyCam::~CodyCam - EXIT\n"); } -//--------------------------------------------------------------- void CodyCam::ReadyToRun() { /* create the window for the app */ - fWindow = new VideoWindow(BRect(28, 28, 28 + (WINDOW_SIZE_X-1), 28 + (WINDOW_SIZE_Y-1)), - (const char *)"CodyCam", B_TITLED_WINDOW, B_NOT_RESIZABLE | B_NOT_ZOOMABLE, &fPort); - + fWindow = new VideoWindow(BRect(28, 28, 28 + (WINDOW_SIZE_X - 1), + 28 + (WINDOW_SIZE_Y - 1)), (const char*)"CodyCam", B_TITLED_WINDOW, + B_NOT_RESIZABLE | B_NOT_ZOOMABLE, &fPort); + /* set up the node connections */ - status_t status = SetUpNodes(); - if (status != B_OK) - { - // This error is not needed because SetUpNodes handles displaying any + status_t status = _SetUpNodes(); + if (status != B_OK) { + // This error is not needed because _SetUpNodes handles displaying any // errors it runs into. // ErrorAlert("Error setting up nodes", status); return; } - - ((VideoWindow *)fWindow)->ApplyControls(); + + ((VideoWindow*)fWindow)->ApplyControls(); } -//--------------------------------------------------------------- + bool CodyCam::QuitRequested() { - TearDownNodes(); + _TearDownNodes(); snooze(100000); return true; } -//--------------------------------------------------------------- void CodyCam::MessageReceived(BMessage *message) { - switch (message->what) - { + switch (message->what) { case msg_start: { - BTimeSource *timeSource = fMediaRoster->MakeTimeSourceFor(fTimeSourceNode); + BTimeSource* timeSource = fMediaRoster->MakeTimeSourceFor(fTimeSourceNode); bigtime_t real = BTimeSource::RealTime(); bigtime_t perf = timeSource->PerformanceTimeFor(real) + 10000; status_t status = fMediaRoster->StartNode(fProducerNode, perf); @@ -139,57 +190,54 @@ CodyCam::MessageReceived(BMessage *message) timeSource->Release(); break; } + case msg_stop: fMediaRoster->StopNode(fProducerNode, 0, true); break; + case msg_video: { - if (mVideoControlWindow) { - mVideoControlWindow->Activate(); + if (fVideoControlWindow) { + fVideoControlWindow->Activate(); break; } - BParameterWeb * web = NULL; - BView * view = NULL; + BParameterWeb* web = NULL; + BView* view = NULL; media_node node = fProducerNode; status_t err = fMediaRoster->GetParameterWebFor(node, &web); - if ((err >= B_OK) && - (web != NULL)) - { + if (err >= B_OK && web != NULL) { view = BMediaTheme::ViewFor(web); - mVideoControlWindow = new ControlWindow( - BRect(2*WINDOW_OFFSET_X + WINDOW_SIZE_X, WINDOW_OFFSET_Y, - 2*WINDOW_OFFSET_X + WINDOW_SIZE_X + view->Bounds().right, WINDOW_OFFSET_Y + view->Bounds().bottom), - view, node); - fMediaRoster->StartWatching(BMessenger(NULL, mVideoControlWindow), node, B_MEDIA_WEB_CHANGED); - mVideoControlWindow->Show(); + fVideoControlWindow = new ControlWindow( + BRect(2 * WINDOW_OFFSET_X + WINDOW_SIZE_X, WINDOW_OFFSET_Y, + 2 * WINDOW_OFFSET_X + WINDOW_SIZE_X + view->Bounds().right, + WINDOW_OFFSET_Y + view->Bounds().bottom), view, node); + fMediaRoster->StartWatching(BMessenger(NULL, fVideoControlWindow), node, + B_MEDIA_WEB_CHANGED); + fVideoControlWindow->Show(); } break; } + case msg_about: - { - (new BAlert("About CodyCam", "CodyCam\n\nThe Original BeOS WebCam", "Close"))->Go(); + (new BAlert("About CodyCam", "CodyCam\n\nThe Original BeOS WebCam", + "Close"))->Go(); break; - } case msg_control_win: - { // our control window is being asked to go away // set our pointer to NULL - mVideoControlWindow = NULL; + fVideoControlWindow = NULL; break; - - } - + default: BApplication::MessageReceived(message); break; } } -//--------------------------------------------------------------- status_t -CodyCam::SetUpNodes() +CodyCam::_SetUpNodes() { status_t status = B_OK; @@ -198,13 +246,15 @@ CodyCam::SetUpNodes() if (status != B_OK) { ErrorAlert("Can't find the media roster", status); return status; - } + } + /* find the time source */ status = fMediaRoster->GetTimeSource(&fTimeSourceNode); if (status != B_OK) { ErrorAlert("Can't get a time source", status); return status; } + /* find a video producer node */ INFO("CodyCam acquiring VideoInput node\n"); status = fMediaRoster->GetVideoInput(&fProducerNode); @@ -214,12 +264,13 @@ CodyCam::SetUpNodes() } /* create the video consumer node */ - fVideoConsumer = new VideoConsumer("CodyCam", ((VideoWindow *)fWindow)->VideoView(), ((VideoWindow *)fWindow)->StatusLine(), NULL, 0); + fVideoConsumer = new VideoConsumer("CodyCam", ((VideoWindow*)fWindow)->VideoView(), + ((VideoWindow*)fWindow)->StatusLine(), NULL, 0); if (!fVideoConsumer) { ErrorAlert("Can't create a video window", B_ERROR); return B_ERROR; } - + /* register the node */ status = fMediaRoster->RegisterNode(fVideoConsumer); if (status != B_OK) { @@ -230,7 +281,8 @@ CodyCam::SetUpNodes() /* find free producer output */ int32 cnt = 0; - status = fMediaRoster->GetFreeOutputsFor(fProducerNode, &fProducerOut, 1, &cnt, B_MEDIA_RAW_VIDEO); + status = fMediaRoster->GetFreeOutputsFor(fProducerNode, &fProducerOut, 1, &cnt, + B_MEDIA_RAW_VIDEO); if (status != B_OK || cnt < 1) { status = B_RESOURCE_UNAVAILABLE; ErrorAlert("Can't find an available video stream", status); @@ -239,7 +291,8 @@ CodyCam::SetUpNodes() /* find free consumer input */ cnt = 0; - status = fMediaRoster->GetFreeInputsFor(fVideoConsumer->Node(), &fConsumerIn, 1, &cnt, B_MEDIA_RAW_VIDEO); + status = fMediaRoster->GetFreeInputsFor(fVideoConsumer->Node(), &fConsumerIn, 1, + &cnt, B_MEDIA_RAW_VIDEO); if (status != B_OK || cnt < 1) { status = B_RESOURCE_UNAVAILABLE; ErrorAlert("Can't find an available connection to the video window", status); @@ -249,10 +302,10 @@ CodyCam::SetUpNodes() /* Connect The Nodes!!! */ media_format format; format.type = B_MEDIA_RAW_VIDEO; - media_raw_video_format vid_format = - { 0, 1, 0, 239, B_VIDEO_TOP_LEFT_RIGHT, 1, 1, {B_RGB32, VIDEO_SIZE_X, VIDEO_SIZE_Y, VIDEO_SIZE_X*4, 0, 0}}; + media_raw_video_format vid_format = {0, 1, 0, 239, B_VIDEO_TOP_LEFT_RIGHT, + 1, 1, {B_RGB32, VIDEO_SIZE_X, VIDEO_SIZE_Y, VIDEO_SIZE_X * 4, 0, 0}}; format.u.raw_video = vid_format; - + /* connect producer to consumer */ status = fMediaRoster->Connect(fProducerOut.source, fConsumerIn.destination, &format, &fProducerOut, &fConsumerIn); @@ -260,20 +313,22 @@ CodyCam::SetUpNodes() ErrorAlert("Can't connect the video source to the video window", status); return status; } - + + /* set time sources */ + status = fMediaRoster->SetTimeSourceFor(fProducerNode.node, fTimeSourceNode.node); if (status != B_OK) { ErrorAlert("Can't set the timesource for the video source", status); return status; } - + status = fMediaRoster->SetTimeSourceFor(fVideoConsumer->ID(), fTimeSourceNode.node); if (status != B_OK) { ErrorAlert("Can't set the timesource for the video window", status); return status; } - + /* figure out what recording delay to use */ bigtime_t latency = 0; status = fMediaRoster->GetLatencyFor(fProducerNode, &latency); @@ -284,17 +339,18 @@ CodyCam::SetUpNodes() status = fMediaRoster->GetInitialLatencyFor(fProducerNode, &initLatency); if (status < B_OK) { ErrorAlert("error getting initial latency for fCaptureNode", status); + return status; } + initLatency += estimate_max_scheduling_latency(); - BTimeSource *timeSource = fMediaRoster->MakeTimeSourceFor(fProducerNode); + BTimeSource* timeSource = fMediaRoster->MakeTimeSourceFor(fProducerNode); bool running = timeSource->IsRunning(); - + /* workaround for people without sound cards */ /* because the system time source won't be running */ bigtime_t real = BTimeSource::RealTime(); - if (!running) - { + if (!running) { status = fMediaRoster->StartTimeSource(fTimeSourceNode, real); if (status != B_OK) { timeSource->Release(); @@ -327,17 +383,15 @@ CodyCam::SetUpNodes() return status; } -//--------------------------------------------------------------- void -CodyCam::TearDownNodes() +CodyCam::_TearDownNodes() { - CALL("CodyCam::TearDownNodes\n"); + CALL("CodyCam::_TearDownNodes\n"); if (!fMediaRoster) return; - if (fVideoConsumer) - { + if (fVideoConsumer) { /* stop */ INFO("stopping nodes!\n"); // fMediaRoster->StopNode(fProducerNode, 0, true); @@ -345,7 +399,7 @@ CodyCam::TearDownNodes() /* disconnect */ fMediaRoster->Disconnect(fProducerOut.node.node, fProducerOut.source, - fConsumerIn.node.node, fConsumerIn.destination); + fConsumerIn.node.node, fConsumerIn.destination); if (fProducerNode != media_node::null) { INFO("CodyCam releasing fProducerNode\n"); @@ -357,71 +411,14 @@ CodyCam::TearDownNodes() } } -//--------------------------------------------------------------- -// Utility functions -//--------------------------------------------------------------- -static void -ErrorAlert(const char * message, status_t err) -{ - (new BAlert("", message, "Quit"))->Go(); - - printf("%s\n%s [%lx]", message, strerror(err), err); - be_app->PostMessage(B_QUIT_REQUESTED); -} +// #pragma mark - Video Window Class -//--------------------------------------------------------------- -status_t -AddTranslationItems( BMenu * intoMenu, uint32 from_type) -{ - - BTranslatorRoster * use; - char * translator_type_name; - const char * translator_id_name; - - use = BTranslatorRoster::Default(); - translator_id_name = "be:translator"; - translator_type_name = "be:type"; - translator_id * ids = NULL; - int32 count = 0; - - status_t err = use->GetAllTranslators(&ids, &count); - if (err < B_OK) return err; - for (int tix=0; tixGetInputFormats(ids[tix], &formats, &num_formats); - if (err == B_OK) for (int iix=0; iixGetOutputFormats(ids[tix], &formats, &num_formats); - if (err == B_OK) for (int oix=0; oixAddInt32(translator_id_name, ids[tix]); - itemmsg->AddInt32(translator_type_name, formats[oix].type); - intoMenu->AddItem(new BMenuItem(formats[oix].name, itemmsg)); - } - } - } - delete[] ids; - return B_OK; -} - -//--------------------------------------------------------------- -// Video Window Class -//--------------------------------------------------------------- - -VideoWindow::VideoWindow (BRect frame, const char *title, window_type type, uint32 flags, port_id * consumerport) : - BWindow(frame,title,type,flags), - fPortPtr(consumerport), +VideoWindow::VideoWindow (BRect frame, const char* title, window_type type, uint32 flags, + port_id* consumerPort) + : BWindow(frame,title,type,flags), + fPortPtr(consumerPort), fView(NULL), fVideoView(NULL) { @@ -436,9 +433,9 @@ VideoWindow::VideoWindow (BRect frame, const char *title, window_type type, uint strcpy(fFtpInfo.passwordText, "password"); strcpy(fFtpInfo.directoryText, "directory"); - SetUpSettings("codycam", ""); + _SetUpSettings("codycam", ""); - BMenuBar* menuBar = new BMenuBar(BRect(0,0,0,0), "menu bar"); + BMenuBar* menuBar = new BMenuBar(BRect(0, 0, 0, 0), "menu bar"); AddChild(menuBar); BMenuItem* menuItem; @@ -482,11 +479,11 @@ VideoWindow::VideoWindow (BRect frame, const char *title, window_type type, uint AddChild(fView); /* add some controls */ - BuildCaptureControls(fView); + _BuildCaptureControls(fView); /* add another view to hold the video image */ aRect = BRect(0, 0, VIDEO_SIZE_X - 1, VIDEO_SIZE_Y - 1); - aRect.OffsetBy((WINDOW_SIZE_X - VIDEO_SIZE_X)/2, kYBuffer); + aRect.OffsetBy((WINDOW_SIZE_X - VIDEO_SIZE_X) / 2, kYBuffer); fVideoView = new BView(aRect, "Video View", B_FOLLOW_ALL, B_WILL_DRAW); fView->AddChild(fVideoView); @@ -494,14 +491,14 @@ VideoWindow::VideoWindow (BRect frame, const char *title, window_type type, uint Show(); } -//--------------------------------------------------------------- + VideoWindow::~VideoWindow() { - QuitSettings(); + _QuitSettings(); } -//--------------------------------------------------------------- + bool VideoWindow::QuitRequested() @@ -510,171 +507,180 @@ VideoWindow::QuitRequested() return false; } -//--------------------------------------------------------------- void -VideoWindow::MessageReceived(BMessage *message) +VideoWindow::MessageReceived(BMessage* message) { - BControl *p; + BControl* control; - p = NULL; - message->FindPointer((const char *)"source",(void **)&p); - - switch (message->what) - { + control = NULL; + message->FindPointer((const char*)"source", (void **)&control); + + switch (message->what) { case msg_filename: - if (p != NULL) - { - strncpy(fFtpInfo.fileNameText, ((BTextControl *)p)->Text(), 63); + if (control != NULL) { + strncpy(fFtpInfo.fileNameText, ((BTextControl*)control)->Text(), 63); FTPINFO("file is '%s'\n", fFtpInfo.fileNameText); } break; + case msg_rate_15s: FTPINFO("fifteen seconds\n"); fFtpInfo.rate = (bigtime_t)(15 * 1000000); break; + case msg_rate_30s: FTPINFO("thirty seconds\n"); fFtpInfo.rate = (bigtime_t)(30 * 1000000); break; + case msg_rate_1m: FTPINFO("one minute\n"); fFtpInfo.rate = (bigtime_t)(1 * 60 * 1000000); break; + case msg_rate_5m: FTPINFO("five minute\n"); fFtpInfo.rate = (bigtime_t)(5 * 60 * 1000000); break; + case msg_rate_10m: FTPINFO("ten minute\n"); fFtpInfo.rate = (bigtime_t)(10 * 60 * 1000000); break; + case msg_rate_15m: FTPINFO("fifteen minute\n"); fFtpInfo.rate = (bigtime_t)(15 * 60 * 1000000); break; + case msg_rate_30m: FTPINFO("thirty minute\n"); fFtpInfo.rate = (bigtime_t)(30 * 60 * 1000000); break; + case msg_rate_1h: FTPINFO("one hour\n"); fFtpInfo.rate = (bigtime_t)(60LL * 60LL * 1000000LL); break; + case msg_rate_2h: FTPINFO("two hour\n"); fFtpInfo.rate = (bigtime_t)(2LL * 60LL * 60LL * 1000000LL); break; + case msg_rate_4h: FTPINFO("four hour\n"); fFtpInfo.rate = (bigtime_t)(4LL * 60LL * 60LL * 1000000LL); break; + case msg_rate_8h: FTPINFO("eight hour\n"); fFtpInfo.rate = (bigtime_t)(8LL * 60LL * 60LL * 1000000LL); break; + case msg_rate_24h: FTPINFO("24 hour\n"); fFtpInfo.rate = (bigtime_t)(24LL * 60LL * 60LL * 1000000LL); break; + case msg_rate_never: FTPINFO("never\n"); fFtpInfo.rate = (bigtime_t)(B_INFINITE_TIMEOUT); break; + case msg_translate: - message->FindInt32("be:type", (int32 *)&(fFtpInfo.imageFormat)); + message->FindInt32("be:type", (int32*)&(fFtpInfo.imageFormat)); message->FindInt32("be:translator", &(fFtpInfo.translator)); break; + case msg_server: - if (p != NULL) - { - strncpy(fFtpInfo.serverText, ((BTextControl *)p)->Text(), 64); + if (control != NULL) { + strncpy(fFtpInfo.serverText, ((BTextControl*)control)->Text(), 64); FTPINFO("server = '%s'\n", fFtpInfo.serverText); } break; + case msg_login: - if (p != NULL) - { - strncpy(fFtpInfo.loginText, ((BTextControl *)p)->Text(), 64); + if (control != NULL) { + strncpy(fFtpInfo.loginText, ((BTextControl*)control)->Text(), 64); FTPINFO("login = '%s'\n", fFtpInfo.loginText); } break; + case msg_password: - if (p != NULL) - { - strncpy(fFtpInfo.passwordText, ((BTextControl *)p)->Text(), 64); + if (control != NULL) { + strncpy(fFtpInfo.passwordText, ((BTextControl*)control)->Text(), 64); FTPINFO("password = '%s'\n", fFtpInfo.passwordText); - if (Lock()) - { - ((BTextControl *)p)->SetText(""); + if (Lock()) { + ((BTextControl*)control)->SetText(""); Unlock(); } } break; + case msg_directory: - if (p != NULL) - { - strncpy(fFtpInfo.directoryText, ((BTextControl *)p)->Text(), 64); + if (control != NULL) { + strncpy(fFtpInfo.directoryText, ((BTextControl*)control)->Text(), 64); FTPINFO("directory = '%s'\n", fFtpInfo.directoryText); } break; + case msg_passiveftp: - if (p != NULL) - { - fFtpInfo.passiveFtp = ((BCheckBox *)p)->Value(); + if (control != NULL) { + fFtpInfo.passiveFtp = ((BCheckBox*)control)->Value(); if (fFtpInfo.passiveFtp) FTPINFO("using passive ftp\n"); } break; + default: BWindow::MessageReceived(message); return; } if (*fPortPtr) - write_port(*fPortPtr, FTP_INFO, (void *)&fFtpInfo, sizeof(ftp_msg_info)); + write_port(*fPortPtr, FTP_INFO, (void*)&fFtpInfo, sizeof(ftp_msg_info)); } -//--------------------------------------------------------------- -BView * +BView* VideoWindow::VideoView() { return fVideoView; } -//--------------------------------------------------------------- -BStringView * +BStringView* VideoWindow::StatusLine() { return fStatusLine; } -//--------------------------------------------------------------- void -VideoWindow::BuildCaptureControls(BView *theView) +VideoWindow::_BuildCaptureControls(BView* theView) { BRect aFrame, theFrame; theFrame = theView->Bounds(); - theFrame.top += VIDEO_SIZE_Y + 2*kYBuffer + 40; + theFrame.top += VIDEO_SIZE_Y + 2 * kYBuffer + 40; theFrame.left += kXBuffer; - theFrame.right -= (WINDOW_SIZE_X/2 + 5); + theFrame.right -= (WINDOW_SIZE_X / 2 + 5); theFrame.bottom -= kXBuffer; - - fCaptureSetupBox = new BBox( theFrame, "Capture Controls", B_FOLLOW_ALL, B_WILL_DRAW); + + fCaptureSetupBox = new BBox(theFrame, "Capture Controls", B_FOLLOW_ALL, B_WILL_DRAW); fCaptureSetupBox->SetLabel("Capture Controls"); theView->AddChild(fCaptureSetupBox); - + aFrame = fCaptureSetupBox->Bounds(); - aFrame.InsetBy(kXBuffer,kYBuffer); - aFrame.top += kYBuffer/2; + aFrame.InsetBy(kXBuffer, kYBuffer); + aFrame.top += kYBuffer / 2; aFrame.bottom = aFrame.top + kMenuHeight; - - fFileName = new BTextControl(aFrame, "File Name", "File Name:", fFilenameSetting->Value(), new BMessage(msg_filename)); + + fFileName = new BTextControl(aFrame, "File Name", "File Name:", + fFilenameSetting->Value(), new BMessage(msg_filename)); fFileName->SetTarget(BMessenger(NULL, this)); fFileName->SetDivider(fFileName->Divider() - 30); @@ -686,10 +692,12 @@ VideoWindow::BuildCaptureControls(BView *theView) fImageFormatMenu = new BPopUpMenu("Image Format Menu"); AddTranslationItems(fImageFormatMenu, B_TRANSLATOR_BITMAP); fImageFormatMenu->SetTargetForItems(this); + if (fImageFormatMenu->FindItem("JPEG Image") != NULL) fImageFormatMenu->FindItem("JPEG Image")->SetMarked(true); else - fImageFormatMenu->ItemAt(0)->SetMarked(true); + fImageFormatMenu->ItemAt(0)->SetMarked(true); + fImageFormatSelector = new BMenuField(aFrame, "Format", "Format:", fImageFormatMenu); fImageFormatSelector->SetDivider(fImageFormatSelector->Divider() - 30); fCaptureSetupBox->AddChild(fImageFormatSelector); @@ -698,19 +706,19 @@ VideoWindow::BuildCaptureControls(BView *theView) aFrame.bottom = aFrame.top + kMenuHeight; fCaptureRateMenu = new BPopUpMenu("Capture Rate Menu"); - fCaptureRateMenu->AddItem(new BMenuItem("Every 15 seconds",new BMessage(msg_rate_15s))); - fCaptureRateMenu->AddItem(new BMenuItem("Every 30 seconds",new BMessage(msg_rate_30s))); - fCaptureRateMenu->AddItem(new BMenuItem("Every minute",new BMessage(msg_rate_1m))); - fCaptureRateMenu->AddItem(new BMenuItem("Every 5 minutes",new BMessage(msg_rate_5m))); - fCaptureRateMenu->AddItem(new BMenuItem("Every 10 minutes",new BMessage(msg_rate_10m))); - fCaptureRateMenu->AddItem(new BMenuItem("Every 15 minutes",new BMessage(msg_rate_15m))); - fCaptureRateMenu->AddItem(new BMenuItem("Every 30 minutes",new BMessage(msg_rate_30m))); - fCaptureRateMenu->AddItem(new BMenuItem("Every hour",new BMessage(msg_rate_1h))); - fCaptureRateMenu->AddItem(new BMenuItem("Every 2 hours",new BMessage(msg_rate_2h))); - fCaptureRateMenu->AddItem(new BMenuItem("Every 4 hours",new BMessage(msg_rate_4h))); - fCaptureRateMenu->AddItem(new BMenuItem("Every 8 hours",new BMessage(msg_rate_8h))); - fCaptureRateMenu->AddItem(new BMenuItem("Every 24 hours",new BMessage(msg_rate_24h))); - fCaptureRateMenu->AddItem(new BMenuItem("Never",new BMessage(msg_rate_never))); + fCaptureRateMenu->AddItem(new BMenuItem("Every 15 seconds", new BMessage(msg_rate_15s))); + fCaptureRateMenu->AddItem(new BMenuItem("Every 30 seconds", new BMessage(msg_rate_30s))); + fCaptureRateMenu->AddItem(new BMenuItem("Every minute", new BMessage(msg_rate_1m))); + fCaptureRateMenu->AddItem(new BMenuItem("Every 5 minutes", new BMessage(msg_rate_5m))); + fCaptureRateMenu->AddItem(new BMenuItem("Every 10 minutes", new BMessage(msg_rate_10m))); + fCaptureRateMenu->AddItem(new BMenuItem("Every 15 minutes", new BMessage(msg_rate_15m))); + fCaptureRateMenu->AddItem(new BMenuItem("Every 30 minutes", new BMessage(msg_rate_30m))); + fCaptureRateMenu->AddItem(new BMenuItem("Every hour", new BMessage(msg_rate_1h))); + fCaptureRateMenu->AddItem(new BMenuItem("Every 2 hours", new BMessage(msg_rate_2h))); + fCaptureRateMenu->AddItem(new BMenuItem("Every 4 hours", new BMessage(msg_rate_4h))); + fCaptureRateMenu->AddItem(new BMenuItem("Every 8 hours", new BMessage(msg_rate_8h))); + fCaptureRateMenu->AddItem(new BMenuItem("Every 24 hours", new BMessage(msg_rate_24h))); + fCaptureRateMenu->AddItem(new BMenuItem("Never", new BMessage(msg_rate_never))); fCaptureRateMenu->SetTargetForItems(this); fCaptureRateMenu->FindItem(fCaptureRateSetting->Value())->SetMarked(true); fCaptureRateSelector = new BMenuField(aFrame, "Rate", "Rate:", fCaptureRateMenu); @@ -718,76 +726,80 @@ VideoWindow::BuildCaptureControls(BView *theView) fCaptureSetupBox->AddChild(fCaptureRateSelector); aFrame = theView->Bounds(); - aFrame.top += VIDEO_SIZE_Y + 2*kYBuffer + 40; - aFrame.left += WINDOW_SIZE_X/2 + 5; + aFrame.top += VIDEO_SIZE_Y + 2 * kYBuffer + 40; + aFrame.left += WINDOW_SIZE_X / 2 + 5; aFrame.right -= kXBuffer; aFrame.bottom -= kYBuffer; - - fFtpSetupBox = new BBox( aFrame, "Ftp Setup", B_FOLLOW_ALL, B_WILL_DRAW); + + fFtpSetupBox = new BBox(aFrame, "Ftp Setup", B_FOLLOW_ALL, B_WILL_DRAW); fFtpSetupBox->SetLabel("Ftp Setup"); theView->AddChild(fFtpSetupBox); - + aFrame = fFtpSetupBox->Bounds(); aFrame.InsetBy(kXBuffer,kYBuffer); aFrame.top += kYBuffer/2; aFrame.bottom = aFrame.top + kMenuHeight; aFrame.right = aFrame.left + 160; - - fServerName = new BTextControl(aFrame, "Server", "Server:", fServerSetting->Value(), new BMessage(msg_server)); + + fServerName = new BTextControl(aFrame, "Server", "Server:", fServerSetting->Value(), + new BMessage(msg_server)); fServerName->SetTarget(this); fServerName->SetDivider(fServerName->Divider() - 30); fFtpSetupBox->AddChild(fServerName); aFrame.top = aFrame.bottom + kYBuffer; aFrame.bottom = aFrame.top + kMenuHeight; - - fLoginId = new BTextControl(aFrame, "Login", "Login:", fLoginSetting->Value(), new BMessage(msg_login)); + + fLoginId = new BTextControl(aFrame, "Login", "Login:", fLoginSetting->Value(), + new BMessage(msg_login)); fLoginId->SetTarget(this); fLoginId->SetDivider(fLoginId->Divider() - 30); fFtpSetupBox->AddChild(fLoginId); aFrame.top = aFrame.bottom + kYBuffer; aFrame.bottom = aFrame.top + kMenuHeight; - - fPassword = new BTextControl(aFrame, "Password", "Password:", fPasswordSetting->Value(), new BMessage(msg_password)); + + fPassword = new BTextControl(aFrame, "Password", "Password:", + fPasswordSetting->Value(), new BMessage(msg_password)); fPassword->SetTarget(this); fPassword->SetDivider(fPassword->Divider() - 30); fFtpSetupBox->AddChild(fPassword); aFrame.top = aFrame.bottom + kYBuffer; aFrame.bottom = aFrame.top + kMenuHeight; - - fDirectory = new BTextControl(aFrame, "Directory", "Directory:", fDirectorySetting->Value(), new BMessage(msg_directory)); + + fDirectory = new BTextControl(aFrame, "Directory", "Directory:", + fDirectorySetting->Value(), new BMessage(msg_directory)); fDirectory->SetTarget(this); fDirectory->SetDivider(fDirectory->Divider() - 30); fFtpSetupBox->AddChild(fDirectory); aFrame.top = aFrame.bottom + kYBuffer; aFrame.bottom = aFrame.top + kMenuHeight; - - fPassiveFtp = new BCheckBox(aFrame, "Passive ftp", "Passive ftp", new BMessage(msg_passiveftp)); + + fPassiveFtp = new BCheckBox(aFrame, "Passive ftp", "Passive ftp", + new BMessage(msg_passiveftp)); fPassiveFtp->SetTarget(this); fPassiveFtp->SetValue(fPassiveFtpSetting->Value()); fFtpSetupBox->AddChild(fPassiveFtp); - + aFrame = theView->Bounds(); - aFrame.top += VIDEO_SIZE_Y + 2*kYBuffer; + aFrame.top += VIDEO_SIZE_Y + 2 * kYBuffer; aFrame.left += kXBuffer; aFrame.right -= kXBuffer; - aFrame.bottom = aFrame.top + kMenuHeight + 2*kYBuffer; - - fStatusBox = new BBox( aFrame, "Status", B_FOLLOW_ALL, B_WILL_DRAW); + aFrame.bottom = aFrame.top + kMenuHeight + 2 * kYBuffer; + + fStatusBox = new BBox(aFrame, "Status", B_FOLLOW_ALL, B_WILL_DRAW); fStatusBox->SetLabel("Status"); theView->AddChild(fStatusBox); - + aFrame = fStatusBox->Bounds(); - aFrame.InsetBy(kXBuffer,kYBuffer); - - fStatusLine = new BStringView(aFrame,"Status Line","Waiting ..."); + aFrame.InsetBy(kXBuffer, kYBuffer); + + fStatusLine = new BStringView(aFrame, "Status Line", "Waiting ..."); fStatusBox->AddChild(fStatusLine); } -//--------------------------------------------------------------- void VideoWindow::ApplyControls() @@ -803,10 +815,9 @@ VideoWindow::ApplyControls() fPassiveFtp->Invoke(); } -//--------------------------------------------------------------- void -VideoWindow::SetUpSettings(const char *filename, const char *dirname) +VideoWindow::_SetUpSettings(const char* filename, const char* dirname) { fSettings = new Settings(filename, dirname); @@ -819,18 +830,18 @@ VideoWindow::SetUpSettings(const char *filename, const char *dirname) fSettings->Add(fDirectorySetting = new StringValueSetting("Directory", "web/images", "destination directory expected", "")); fSettings->Add(fPassiveFtpSetting = new BooleanValueSetting("PassiveFtp", 1)); - fSettings->Add(fFilenameSetting = new StringValueSetting("StillImageFilename", "codycam.jpg", - "still image filename expected", "")); - fSettings->Add(fCaptureRateSetting = new EnumeratedStringValueSetting("CaptureRate", "Every 5 minutes", kCaptureRate, - "capture rate expected", "unrecognized capture rate specified")); + fSettings->Add(fFilenameSetting = new StringValueSetting("StillImageFilename", + "codycam.jpg", "still image filename expected", "")); + fSettings->Add(fCaptureRateSetting = new EnumeratedStringValueSetting("CaptureRate", + "Every 5 minutes", kCaptureRate, "capture rate expected", + "unrecognized capture rate specified")); fSettings->TryReadingSettings(); } -//--------------------------------------------------------------- void -VideoWindow::QuitSettings() +VideoWindow::_QuitSettings() { fServerSetting->ValueChanged(fServerName->Text()); fLoginSetting->ValueChanged(fLoginId->Text()); @@ -844,13 +855,12 @@ VideoWindow::QuitSettings() delete fSettings; } -//--------------------------------------------------------------- -ControlWindow::ControlWindow( - const BRect & frame, - BView * controls, - media_node node) : - BWindow(frame, "Video Preferences", B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS) +// #pragma mark - + + +ControlWindow::ControlWindow(const BRect& frame, BView* controls, media_node node) + : BWindow(frame, "Video Preferences", B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS) { fView = controls; fNode = node; @@ -858,52 +868,47 @@ ControlWindow::ControlWindow( AddChild(fView); } -//--------------------------------------------------------------- void -ControlWindow::MessageReceived(BMessage * message) +ControlWindow::MessageReceived(BMessage* message) { - BParameterWeb * web = NULL; + BParameterWeb* web = NULL; status_t err; - switch (message->what) - { + switch (message->what) { case B_MEDIA_WEB_CHANGED: { // If this is a tab view, find out which tab // is selected - BTabView *tabView = dynamic_cast(fView); + BTabView* tabView = dynamic_cast(fView); int32 tabNum = -1; if (tabView) tabNum = tabView->Selection(); RemoveChild(fView); delete fView; - + err = BMediaRoster::Roster()->GetParameterWebFor(fNode, &web); - - if ((err >= B_OK) && - (web != NULL)) - { + + if (err >= B_OK && web != NULL) { fView = BMediaTheme::ViewFor(web); AddChild(fView); // Another tab view? Restore previous selection - if (tabNum > 0) - { - BTabView *newTabView = dynamic_cast(fView); + if (tabNum > 0) { + BTabView* newTabView = dynamic_cast(fView); if (newTabView) newTabView->Select(tabNum); } } break; } + default: BWindow::MessageReceived(message); } } -//--------------------------------------------------------------- bool ControlWindow::QuitRequested() @@ -913,4 +918,12 @@ ControlWindow::QuitRequested() } +// #pragma mark - + +int main() { + chdir("/boot/home"); + CodyCam app; + app.Run(); + return 0; +} diff --git a/src/apps/codycam/CodyCam.h b/src/apps/codycam/CodyCam.h index c05155e0f4..4612ec92c8 100644 --- a/src/apps/codycam/CodyCam.h +++ b/src/apps/codycam/CodyCam.h @@ -1,20 +1,22 @@ /* CodyCam.h */ - #ifndef CODYCAM_H #define CODYCAM_H -#include -#include -#include -#include -#include -#include -#include -#include -#include #include "Settings.h" -#include"VideoConsumer.h" +#include "VideoConsumer.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + class BMediaRoster; @@ -56,7 +58,8 @@ enum { msg_control_win = 'ctlw' }; -const char *kCaptureRate[] = { + +const char* kCaptureRate[] = { "Every 15 seconds", "Every 30 seconds", "Every minute", @@ -73,113 +76,96 @@ const char *kCaptureRate[] = { 0 }; + class CodyCam : public BApplication { public: - CodyCam(); - virtual ~CodyCam(); - - void ReadyToRun(); - virtual bool QuitRequested(); - virtual void MessageReceived( - BMessage *message); + CodyCam(); + virtual ~CodyCam(); + + void ReadyToRun(); + virtual bool QuitRequested(); + virtual void MessageReceived(BMessage* message); private: - status_t SetUpNodes(); - void TearDownNodes(); - - BMediaRoster * fMediaRoster; + status_t _SetUpNodes(); + void _TearDownNodes(); - media_node fTimeSourceNode; - media_node fProducerNode; - - VideoConsumer * fVideoConsumer; - - media_output fProducerOut; - media_input fConsumerIn; - - BWindow * fWindow; - - port_id fPort; - - BWindow *mVideoControlWindow; + BMediaRoster* fMediaRoster; + media_node fTimeSourceNode; + media_node fProducerNode; + VideoConsumer* fVideoConsumer; + media_output fProducerOut; + media_input fConsumerIn; + BWindow* fWindow; + port_id fPort; + BWindow* fVideoControlWindow; }; -class VideoWindow : public BWindow -{ -public: - VideoWindow ( - BRect frame, - const char * title, - window_type type, - uint32 flags, - port_id * consumerport); - ~VideoWindow(); - virtual bool QuitRequested(); - virtual void MessageReceived( - BMessage *message); +class VideoWindow : public BWindow { + public: + VideoWindow(BRect frame, const char* title, window_type type, + uint32 flags, port_id* consumerport); + ~VideoWindow(); - void ApplyControls(); - - BView * VideoView(); - BStringView * StatusLine(); - -private: - void BuildCaptureControls( - BView *theView); + virtual bool QuitRequested(); + virtual void MessageReceived(BMessage* message); - void SetUpSettings( - const char *filename, - const char *dirname); - void QuitSettings(); - + void ApplyControls(); -private: - media_node * fProducer; - port_id * fPortPtr; - - - BView * fView; - BView * fVideoView; - - BTextControl * fFileName; - BBox * fCaptureSetupBox; - BMenu * fCaptureRateMenu; - BMenuField * fCaptureRateSelector; - BMenu * fImageFormatMenu; - BMenuField * fImageFormatSelector; - BBox * fFtpSetupBox; - BTextControl * fServerName; - BTextControl * fLoginId; - BTextControl * fPassword; - BTextControl * fDirectory; - BCheckBox * fPassiveFtp; - BBox * fStatusBox; - BStringView * fStatusLine; - - ftp_msg_info fFtpInfo; - + BView* VideoView(); + BStringView* StatusLine(); - Settings * fSettings; - StringValueSetting * fServerSetting; - StringValueSetting * fLoginSetting; - StringValueSetting * fPasswordSetting; - StringValueSetting * fDirectorySetting; - BooleanValueSetting * fPassiveFtpSetting; - StringValueSetting * fFilenameSetting; - EnumeratedStringValueSetting *fCaptureRateSetting; + private: + void _BuildCaptureControls(BView* theView); + + void _SetUpSettings(const char* filename, const char* dirname); + void _QuitSettings(); + + private: + media_node* fProducer; + port_id* fPortPtr; + + BView* fView; + BView* fVideoView; + + BTextControl* fFileName; + BBox* fCaptureSetupBox; + BMenu* fCaptureRateMenu; + BMenuField* fCaptureRateSelector; + BMenu* fImageFormatMenu; + BMenuField* fImageFormatSelector; + BBox* fFtpSetupBox; + BTextControl* fServerName; + BTextControl* fLoginId; + BTextControl* fPassword; + BTextControl* fDirectory; + BCheckBox* fPassiveFtp; + BBox* fStatusBox; + BStringView* fStatusLine; + + ftp_msg_info fFtpInfo; + + Settings* fSettings; + StringValueSetting* fServerSetting; + StringValueSetting* fLoginSetting; + StringValueSetting* fPasswordSetting; + StringValueSetting* fDirectorySetting; + BooleanValueSetting* fPassiveFtpSetting; + StringValueSetting* fFilenameSetting; + EnumeratedStringValueSetting* fCaptureRateSetting; }; + class ControlWindow : public BWindow { - -public: - ControlWindow(const BRect & frame, BView * controls, media_node node); - void MessageReceived(BMessage * message); + public: + ControlWindow(const BRect& frame, BView* controls, media_node node); + void MessageReceived(BMessage* message); bool QuitRequested(); -private: - BView * fView; - media_node fNode; + private: + BView* fView; + media_node fNode; }; -#endif +#endif // CODYCAM_H diff --git a/src/apps/codycam/FtpClient.cpp b/src/apps/codycam/FtpClient.cpp index aa2b203aab..0441eb2fca 100644 --- a/src/apps/codycam/FtpClient.cpp +++ b/src/apps/codycam/FtpClient.cpp @@ -1,38 +1,36 @@ #include "FtpClient.h" FtpClient::FtpClient() + : + fState(0), + fControl(NULL), + fData(NULL) { - m_control = 0; - m_state = 0; - m_data = 0; } - FtpClient::~FtpClient() { - delete m_control; - delete m_data; + delete fControl; + delete fData; } -bool FtpClient::cd(const string &dir) +bool +FtpClient::ChangeDir(const string& dir) { bool rc = false; - int code, codetype; - string cmd = "CWD ", replystr; + int code, codeType; + string cmd = "CWD ", replyString; - cmd += dir; - if(dir.length() == 0) + if (dir.length() == 0) cmd += '/'; - - if(p_sendRequest(cmd) == true) - { - if(p_getReply(replystr, code, codetype) == true) - { - if(codetype == 2) + + if (_SendRequest(cmd) == true) { + if (_GetReply(replyString, code, codeType) == true) { + if (codeType == 2) rc = true; } } @@ -40,44 +38,36 @@ bool FtpClient::cd(const string &dir) } -bool FtpClient::ls(string &listing) +bool +FtpClient::ListDirContents(string& listing) { bool rc = false; - string cmd, replystr; - int code, codetype, numread; + string cmd, replyString; + int code, codeType, numRead; char buf[513]; cmd = "TYPE A"; - if(p_sendRequest(cmd)) - p_getReply(replystr, code, codetype); + if (_SendRequest(cmd)) + _GetReply(replyString, code, codeType); - if(p_openDataConnection()) - { + if (_OpenDataConnection()) { cmd = "LIST"; - - if(p_sendRequest(cmd)) - { - if(p_getReply(replystr, code, codetype)) - { - if(codetype <= 2) - { - if(p_acceptDataConnection()) - { - numread = 1; - while(numread > 0) - { + + if (_SendRequest(cmd)) { + if (_GetReply(replyString, code, codeType)) { + if (codeType <= 2) { + if (_AcceptDataConnection()) { + numRead = 1; + while (numRead > 0) { memset(buf, 0, sizeof(buf)); - numread = m_data->Receive(buf, sizeof(buf) - 1); + numRead = fData->Receive(buf, sizeof(buf) - 1); listing += buf; printf(buf); } - if(p_getReply(replystr, code, codetype)) - { - if(codetype <= 2) - { + if (_GetReply(replyString, code, codeType)) { + if (codeType <= 2) rc = true; - } } } } @@ -85,31 +75,28 @@ bool FtpClient::ls(string &listing) } } - delete m_data; - m_data = 0; + delete fData; + fData = 0; return rc; } -bool FtpClient::pwd(string &dir) +bool +FtpClient::PrintWorkingDir(string& dir) { bool rc = false; - int code, codetype; - string cmd = "PWD", replystr; + int code, codeType; + string cmd = "PWD", replyString; long i; - if(p_sendRequest(cmd) == true) - { - if(p_getReply(replystr, code, codetype) == true) - { - if(codetype == 2) - { - i = replystr.find('"'); - if(i != -1) - { + if (_SendRequest(cmd) == true) { + if (_GetReply(replyString, code, codeType) == true) { + if (codeType == 2) { + i = replyString.find('"'); + if (i != -1) { i++; - dir = replystr.substr(i, replystr.find('"') - i); + dir = replyString.substr(i, replyString.find('"') - i); rc = true; } } @@ -120,129 +107,110 @@ bool FtpClient::pwd(string &dir) } -bool FtpClient::connect(const string &server, const string &login, const string &passwd) +bool +FtpClient::Connect(const string& server, const string& login, const string& passwd) { bool rc = false; - int code, codetype; - string cmd, replystr; + int code, codeType; + string cmd, replyString; BNetAddress addr; - delete m_control; - delete m_data; + delete fControl; + delete fData; - - m_control = new BNetEndpoint; - - if(m_control->InitCheck() != B_NO_ERROR) + fControl = new BNetEndpoint; + + if (fControl->InitCheck() != B_NO_ERROR) return false; - + addr.SetTo(server.c_str(), "tcp", "ftp"); - if(m_control->Connect(addr) == B_NO_ERROR) - { - // + if (fControl->Connect(addr) == B_NO_ERROR) { // read the welcome message, do the login - // - if(p_getReply(replystr, code, codetype)) - { - if(code != 421 && codetype != 5) - { - cmd = "USER "; cmd += login; - p_sendRequest(cmd); - if(p_getReply(replystr, code, codetype)) - { - switch(code) - { + if (_GetReply(replyString, code, codeType)) { + if (code != 421 && codeType != 5) { + cmd = "USER "; + cmd += login; + _SendRequest(cmd); + + if (_GetReply(replyString, code, codeType)) { + switch (code) { case 230: case 202: rc = true; - break; - + break; + case 331: // password needed - cmd = "PASS "; cmd += passwd; - p_sendRequest(cmd); - if(p_getReply(replystr, code, codetype)) - { - if(codetype == 2) - { + cmd = "PASS "; + cmd += passwd; + _SendRequest(cmd); + if (_GetReply(replyString, code, codeType)) { + if (codeType == 2) rc = true; - } } - break; - + break; + default: - break; + break; } } } } } - - if(rc == true) - { - p_setState(ftp_connected); - } else { - delete m_control; - m_control = 0; + if (rc == true) + _SetState(ftp_connected); + else { + delete fControl; + fControl = 0; } - + return rc; } - -bool FtpClient::putFile(const string &local, const string &remote, ftp_mode mode) +bool +FtpClient::PutFile(const string& local, const string& remote, ftp_mode mode) { bool rc = false; - string cmd, replystr; - int code, codetype, rlen, slen, i; + string cmd, replyString; + int code, codeType, rlen, slen, i; BFile infile(local.c_str(), B_READ_ONLY); char buf[8192], sbuf[16384], *stmp; - if(infile.InitCheck() != B_NO_ERROR) + if (infile.InitCheck() != B_NO_ERROR) return false; - - if(mode == binary_mode) + + if (mode == binary_mode) cmd = "TYPE I"; else cmd = "TYPE A"; - if(p_sendRequest(cmd)) - p_getReply(replystr, code, codetype); + if (_SendRequest(cmd)) + _GetReply(replyString, code, codeType); - try - { - if(p_openDataConnection()) - { + try { + if (_OpenDataConnection()) { cmd = "STOR "; cmd += remote; - - if(p_sendRequest(cmd)) - { - if(p_getReply(replystr, code, codetype)) - { - if(codetype <= 2) - { - if(p_acceptDataConnection()) - { + + if (_SendRequest(cmd)) { + if (_GetReply(replyString, code, codeType)) { + if (codeType <= 2) { + if (_AcceptDataConnection()) { rlen = 1; - while(rlen > 0) - { + while (rlen > 0) { memset(buf, 0, sizeof(buf)); memset(sbuf, 0, sizeof(sbuf)); - rlen = infile.Read((void *) buf, sizeof(buf)); + rlen = infile.Read((void*)buf, sizeof(buf)); slen = rlen; stmp = buf; - if(mode == ascii_mode) - { + if (mode == ascii_mode) { stmp = sbuf; slen = 0; - for(i=0;i 0) - { - if(m_data->Send(stmp, slen) < 0) + if (slen > 0) { + if (fData->Send(stmp, slen) < 0) throw "bail"; } } @@ -267,143 +234,119 @@ bool FtpClient::putFile(const string &local, const string &remote, ftp_mode mode } } } - - catch(const char *errstr) - { - + + catch(const char* errorString) + { + } + + delete fData; + fData = 0; + + if (rc) { + _GetReply(replyString, code, codeType); + rc = codeType <= 2; } - delete m_data; - m_data = 0; - - if(rc == true) - { - p_getReply(replystr, code, codetype); - rc = (bool) codetype <= 2; - } - return rc; } - -bool FtpClient::getFile(const string &remote, const string &local, ftp_mode mode) +bool +FtpClient::GetFile(const string& remote, const string& local, ftp_mode mode) { bool rc = false; - string cmd, replystr; - int code, codetype, rlen, slen, i; + string cmd, replyString; + int code, codeType, rlen, slen, i; BFile outfile(local.c_str(), B_READ_WRITE | B_CREATE_FILE); char buf[8192], sbuf[16384], *stmp; - bool writeerr = false; - - if(outfile.InitCheck() != B_NO_ERROR) + bool writeError = false; + + if (outfile.InitCheck() != B_NO_ERROR) return false; - - if(mode == binary_mode) + + if (mode == binary_mode) cmd = "TYPE I"; else cmd = "TYPE A"; - - if(p_sendRequest(cmd)) - p_getReply(replystr, code, codetype); - - if(p_openDataConnection()) - { + if (_SendRequest(cmd)) + _GetReply(replyString, code, codeType); + + if (_OpenDataConnection()) { cmd = "RETR "; cmd += remote; - if(p_sendRequest(cmd)) - { - if(p_getReply(replystr, code, codetype)) - { - if(codetype <= 2) - { - if(p_acceptDataConnection()) - { + if (_SendRequest(cmd)) { + if (_GetReply(replyString, code, codeType)) { + if (codeType <= 2) { + if (_AcceptDataConnection()) { rlen = 1; rc = true; - while(rlen > 0) - { + while (rlen > 0) { memset(buf, 0, sizeof(buf)); memset(sbuf, 0, sizeof(sbuf)); - rlen = m_data->Receive(buf, sizeof(buf)); + rlen = fData->Receive(buf, sizeof(buf)); - if(rlen > 0) - { - + if (rlen > 0) { + slen = rlen; stmp = buf; - if(mode == ascii_mode) - { + if (mode == ascii_mode) { stmp = sbuf; slen = 0; - for(i=0;i 0) - { - if(outfile.Write(stmp, slen) < 0) - { - writeerr = true; - } + + if (slen > 0) { + if (outfile.Write(stmp, slen) < 0) + writeError = true; } } } - } } } } } + + delete fData; + fData = 0; - delete m_data; - m_data = 0; - - if(rc == true) - { - p_getReply(replystr, code, codetype); - rc = (bool) ((codetype <= 2) && (writeerr == false)); - } + if (rc) { + _GetReply(replyString, code, codeType); + rc = (codeType <= 2 && writeError == false); + } return rc; } -// + // Note: this only works for local remote moves, cross filesystem moves // will not work -// -bool FtpClient::moveFile(const string &oldpath, const string &newpath) +bool +FtpClient::MoveFile(const string& oldPath, const string& newPath) { bool rc = false; string from = "RNFR "; string to = "RNTO "; - string replystr; - int code, codetype; + string replyString; + int code, codeType; - from += oldpath; - to += newpath; - - if(p_sendRequest(from)) - { - if(p_getReply(replystr, code, codetype)) - { - if(codetype == 3) - { - if(p_sendRequest(to)) - { - if(p_getReply(replystr, code, codetype)) - { - if(codetype == 2) + from += oldPath; + to += newPath; + + if (_SendRequest(from)) { + if (_GetReply(replyString, code, codeType)) { + if (codeType == 3) { + if (_SendRequest(to)) { + if (_GetReply(replyString, code, codeType)) { + if(codeType == 2) rc = true; } } @@ -414,62 +357,60 @@ bool FtpClient::moveFile(const string &oldpath, const string &newpath) } -void FtpClient::setPassive(bool on) +void +FtpClient::SetPassive(bool on) { - if(on) - p_setState(ftp_passive); + if (on) + _SetState(ftp_passive); else - p_clearState(ftp_passive); + _ClearState(ftp_passive); } - -bool FtpClient::p_testState(unsigned long state) +bool +FtpClient::_TestState(unsigned long state) { - return (bool) ((m_state & state) != 0); + return ((fState & state) != 0); } - -void FtpClient::p_setState(unsigned long state) +void +FtpClient::_SetState(unsigned long state) { - m_state |= state; + fState |= state; } - -void FtpClient::p_clearState(unsigned long state) +void +FtpClient::_ClearState(unsigned long state) { - m_state &= ~state; + fState &= ~state; } - - -bool FtpClient::p_sendRequest(const string &cmd) +bool +FtpClient::_SendRequest(const string& cmd) { bool rc = false; string ccmd = cmd; - if(m_control != 0) - { - if(cmd.find("PASS") != string::npos) + if (fControl != 0) { + if (cmd.find("PASS") != string::npos) printf("PASS (real password sent)\n"); else printf("%s\n", ccmd.c_str()); + ccmd += "\r\n"; - if(m_control->Send(ccmd.c_str(), ccmd.length()) >= 0) - { + if (fControl->Send(ccmd.c_str(), ccmd.length()) >= 0) rc = true; - } } return rc; } - -bool FtpClient::p_getReplyLine(string &line) +bool +FtpClient::_GetReplyLine(string& line) { bool rc = false; int c = 0; @@ -477,38 +418,33 @@ bool FtpClient::p_getReplyLine(string &line) line = ""; // Thanks to Stephen van Egmond for catching a bug here - if(m_control != 0) - { + if (fControl != 0) { rc = true; - while(done == false && (m_control->Receive(&c, 1) > 0)) - { - if(c == EOF || c == xEOF || c == '\n') - { + while (done == false && fControl->Receive(&c, 1) > 0) { + if (c == EOF || c == xEOF || c == '\n') { done = true; } else { - if(c == IAC) - { - m_control->Receive(&c, 1); - switch(c) - { + if (c == IAC) { + fControl->Receive(&c, 1); + switch (c) { unsigned char treply[3]; case WILL: case WONT: - m_control->Receive(&c, 1); + fControl->Receive(&c, 1); treply[0] = IAC; treply[1] = DONT; treply[2] = c; - m_control->Send(treply, 3); + fControl->Send(treply, 3); break; - + case DO: case DONT: - m_control->Receive(&c, 1); - m_control->Receive(&c, 1); + fControl->Receive(&c, 1); + fControl->Receive(&c, 1); treply[0] = IAC; treply[1] = WONT; treply[2] = c; - m_control->Send(treply, 3); + fControl->Send(treply, 3); break; case EOF: @@ -521,10 +457,8 @@ bool FtpClient::p_getReplyLine(string &line) break; } } else { - // // normal char - // - if(c != '\r') + if (c != '\r') line += c; } } @@ -535,10 +469,11 @@ bool FtpClient::p_getReplyLine(string &line) } -bool FtpClient::p_getReply(string &outstr, int &outcode, int &codetype) +bool +FtpClient::_GetReply(string& outString, int& outCode, int& codeType) { bool rc = false; - string line, tempstr; + string line, tempString; // // comment from the ncftp source: @@ -556,149 +491,125 @@ bool FtpClient::p_getReply(string &outstr, int &outcode, int &codetype) * 234 A line beginning with numbers * 123 The last line */ - - if((rc = p_getReplyLine(line)) == true) - { - outstr = line; - outstr += '\n'; - printf(outstr.c_str()); - tempstr = line.substr(0, 3); - outcode = atoi(tempstr.c_str()); + + if ((rc = _GetReplyLine(line)) == true) { + outString = line; + outString += '\n'; + printf(outString.c_str()); + tempString = line.substr(0, 3); + outCode = atoi(tempString.c_str()); - if(line[3] == '-') - { - while((rc = p_getReplyLine(line)) == true) - { - outstr += line; - outstr += '\n'; - printf(outstr.c_str()); - // + if (line[3] == '-') { + while ((rc = _GetReplyLine(line)) == true) { + outString += line; + outString += '\n'; + printf(outString.c_str()); // we're done with nnn when we get to a "nnn blahblahblah" - // - if((line.find(tempstr) == 0) && line[3] == ' ') + if ((line.find(tempString) == 0) && line[3] == ' ') break; } } } - if(rc == false && outcode != 421) - { - outstr += "Remote host has closed the connection.\n"; - outcode = 421; + if (!rc && outCode != 421) { + outString += "Remote host has closed the connection.\n"; + outCode = 421; } - if(outcode == 421) - { - delete m_control; - m_control = 0; - p_clearState(ftp_connected); + if (outCode == 421) { + delete fControl; + fControl = 0; + _ClearState(ftp_connected); } - - codetype = outcode / 100; + + codeType = outCode / 100; return rc; } - -bool FtpClient::p_openDataConnection() +bool +FtpClient::_OpenDataConnection() { - string host, cmd, repstr; + string host, cmd, replyString; unsigned short port; BNetAddress addr; - int i, code, codetype; + int i, code, codeType; bool rc = false; struct sockaddr_in sa; - delete m_data; - m_data = 0; + delete fData; + fData = 0; - m_data = new BNetEndpoint; + fData = new BNetEndpoint; - if(p_testState(ftp_passive)) - { - // + if (_TestState(ftp_passive)) { // Here we send a "pasv" command and connect to the remote server // on the port it sends back to us - // cmd = "PASV"; - if(p_sendRequest(cmd)) - { - if(p_getReply(repstr, code, codetype)) - { - - if(codetype == 2) - { + if (_SendRequest(cmd)) { + if (_GetReply(replyString, code, codeType)) { + + if (codeType == 2) { // It should give us something like: // "227 Entering Passive Mode (192,168,1,1,10,187)" int paddr[6]; unsigned char ucaddr[6]; - - i = repstr.find('('); + + i = replyString.find('('); i++; - repstr = repstr.substr(i, repstr.find(')') - i); - if (sscanf(repstr.c_str(), "%d,%d,%d,%d,%d,%d", + replyString = replyString.substr(i, replyString.find(')') - i); + if (sscanf(replyString.c_str(), "%d,%d,%d,%d,%d,%d", &paddr[0], &paddr[1], &paddr[2], &paddr[3], - &paddr[4], &paddr[5]) != 6) - { - // - // cannot do passive. Do a little harmless rercursion here - // - p_clearState(ftp_passive); - return p_openDataConnection(); + &paddr[4], &paddr[5]) != 6) { + // cannot do passive. Do a little harmless rercursion here + _ClearState(ftp_passive); + return _OpenDataConnection(); } - for(i=0;i<6;i++) - { - ucaddr[i] = (unsigned char) (paddr[i] & 0xff); - } + + for (i = 0; i < 6; i++) + ucaddr[i] = (unsigned char)(paddr[i] & 0xff); + memcpy(&sa.sin_addr, &ucaddr[0], (size_t) 4); memcpy(&sa.sin_port, &ucaddr[4], (size_t) 2); addr.SetTo(sa); - if(m_data->Connect(addr) == B_NO_ERROR) - { + if (fData->Connect(addr) == B_NO_ERROR) rc = true; - } + } } } else { - // // cannot do passive. Do a little harmless rercursion here - // - p_clearState(ftp_passive); - rc = p_openDataConnection(); + _ClearState(ftp_passive); + rc = _OpenDataConnection(); } } else { - // // Here we bind to a local port and send a PORT command - // - if(m_data->Bind() == B_NO_ERROR) - { + if (fData->Bind() == B_NO_ERROR) { char buf[255]; - - m_data->Listen(); - addr = m_data->LocalAddr(); + + fData->Listen(); + addr = fData->LocalAddr(); addr.GetAddr(buf, &port); host = buf; - - i=0; - while(i >= 0) - { + + i = 0; + while (i >= 0) { i = host.find('.', i); - if(i >= 0) + if (i >= 0) host[i] = ','; } - + sprintf(buf, ",%d,%d", (port & 0xff00) >> 8, port & 0x00ff); cmd = "PORT "; - cmd += host; cmd += buf; - p_sendRequest(cmd); - p_getReply(repstr, code, codetype); - // + cmd += host; + cmd += buf; + _SendRequest(cmd); + _GetReply(replyString, code, codeType); // PORT failure is in the 500-range - // - if(codetype == 2) + if (codeType == 2) rc = true; } } @@ -707,32 +618,25 @@ bool FtpClient::p_openDataConnection() } -bool FtpClient::p_acceptDataConnection() +bool +FtpClient::_AcceptDataConnection() { - BNetEndpoint *ep; + BNetEndpoint* endPoint; bool rc = false; - if(p_testState(ftp_passive) == false) - { - if(m_data != 0) - { - ep = m_data->Accept(); - if(ep != 0) - { - delete m_data; - m_data = ep; + if (_TestState(ftp_passive) == false) { + if (fData != 0) { + endPoint = fData->Accept(); + if (endPoint != 0) { + delete fData; + fData = endPoint; rc = true; } } - } else { + } + else rc = true; - } - + return rc; } - - - - - diff --git a/src/apps/codycam/FtpClient.h b/src/apps/codycam/FtpClient.h index 7a874fae11..91faeb730e 100644 --- a/src/apps/codycam/FtpClient.h +++ b/src/apps/codycam/FtpClient.h @@ -1,54 +1,15 @@ -#include -#include +#ifndef FTP_CLIENT_H +#define FTP_CLIENT_H + + #include +#include + +#include #include using std::string; -class FtpClient -{ -public: - FtpClient(); - ~FtpClient(); - - enum ftp_mode - { - binary_mode, - ascii_mode - }; - - bool connect(const string &server, const string &login, const string &passwd); - bool putFile(const string &local, const string &remote, ftp_mode mode = binary_mode); - bool getFile(const string &remote, const string &local, ftp_mode mode = binary_mode); - bool moveFile(const string &oldpath, const string &newpath); - bool cd(const string &dir); - bool pwd(string &dir); - bool ls(string &listing); - - void setPassive(bool on); - -protected: - enum { - ftp_complete = 1UL, - ftp_connected = 2, - ftp_passive = 4 - }; - - unsigned long m_state; - bool p_testState(unsigned long state); - void p_setState(unsigned long state); - void p_clearState(unsigned long state); - - bool p_sendRequest(const string &cmd); - bool p_getReply(string &outstr, int &outcode, int &codetype); - bool p_getReplyLine(string &line); - bool p_openDataConnection(); - bool p_acceptDataConnection(); - - BNetEndpoint *m_control; - BNetEndpoint *m_data; - -}; /* * Definitions for the TELNET protocol. Snarfed from the BSD source. @@ -58,5 +19,56 @@ protected: #define DO 253 #define WONT 252 #define WILL 251 -#define xEOF 236 - +#define xEOF 236 + + +class FtpClient { + public: + FtpClient(); + ~FtpClient(); + + enum ftp_mode { + binary_mode, + ascii_mode + }; + + bool Connect(const string& server, const string& login, + const string& passwd); + + bool PutFile(const string& local, const string& remote, + ftp_mode mode = binary_mode); + + bool GetFile(const string& remote, const string& local, + ftp_mode mode = binary_mode); + + bool MoveFile(const string& oldPath, const string& newPath); + bool ChangeDir(const string& dir); + bool PrintWorkingDir(string& dir); + bool ListDirContents(string& listing); + + void SetPassive(bool on); + + protected: + enum { + ftp_complete = 1UL, + ftp_connected = 2, + ftp_passive = 4 + }; + + bool _TestState(unsigned long state); + void _SetState(unsigned long state); + void _ClearState(unsigned long state); + + bool _SendRequest(const string& cmd); + bool _GetReply(string& outString, int& outCode, int& codeType); + bool _GetReplyLine(string& line); + bool _OpenDataConnection(); + bool _AcceptDataConnection(); + + unsigned long fState; + BNetEndpoint* fControl; + BNetEndpoint* fData; + +}; + +#endif // FTP_CLIENT_H diff --git a/src/apps/codycam/Settings.cpp b/src/apps/codycam/Settings.cpp index 015ebc7103..306aff4ef3 100644 --- a/src/apps/codycam/Settings.cpp +++ b/src/apps/codycam/Settings.cpp @@ -1,90 +1,101 @@ -#include -#include -#include -#include - #include "Settings.h" -Settings *settings = NULL; +#include +#include +#include -// generic setting handler classes +#include -StringValueSetting::StringValueSetting(const char *name, const char *defaultValue, - const char *valueExpectedErrorString, const char *wrongValueErrorString) - : SettingsArgvDispatcher(name), - defaultValue(defaultValue), - valueExpectedErrorString(valueExpectedErrorString), - wrongValueErrorString(wrongValueErrorString), - value(strdup(defaultValue)) +Settings* settings = NULL; + + +StringValueSetting::StringValueSetting(const char* name, const char* defaultValue, + const char* valueExpectedErrorString, const char* wrongValueErrorString) + : SettingsArgvDispatcher(name), + fDefaultValue(defaultValue), + fValueExpectedErrorString(valueExpectedErrorString), + fWrongValueErrorString(wrongValueErrorString), + fValue(strdup(defaultValue)) { } StringValueSetting::~StringValueSetting() { - free(value); + free(fValue); } + void -StringValueSetting::ValueChanged(const char *newValue) +StringValueSetting::ValueChanged(const char* newValue) { - if (newValue == value) + if (newValue == fValue) // guard against self assingment return; - free(value); - value = strdup(newValue); + free(fValue); + fValue = strdup(newValue); } -const char * + +const char* StringValueSetting::Value() const { - return value; + return fValue; } + void -StringValueSetting::SaveSettingValue(Settings *settings) +StringValueSetting::SaveSettingValue(Settings* settings) { -printf("-------StringValueSetting::SaveSettingValue %s %s\n", Name(), value); - settings->Write("\"%s\"", value); + printf("-------StringValueSetting::SaveSettingValue %s %s\n", Name(), fValue); + settings->Write("\"%s\"", fValue); } + bool StringValueSetting::NeedsSaving() const { // needs saving if different than default - return strcmp(value, defaultValue) != 0; + return strcmp(fValue, fDefaultValue) != 0; } -const char * + +const char* StringValueSetting::Handle(const char *const *argv) { if (!*++argv) - return valueExpectedErrorString; + return fValueExpectedErrorString; ValueChanged(*argv); return 0; } -EnumeratedStringValueSetting::EnumeratedStringValueSetting(const char *name, - const char *defaultValue, const char *const *values, const char *valueExpectedErrorString, - const char *wrongValueErrorString) - : StringValueSetting(name, defaultValue, valueExpectedErrorString, wrongValueErrorString), - values(values) + +// #pragma mark - + + +EnumeratedStringValueSetting::EnumeratedStringValueSetting(const char* name, + const char* defaultValue, const char *const *values, + const char* valueExpectedErrorString, + const char* wrongValueErrorString) + : StringValueSetting(name, defaultValue, valueExpectedErrorString, wrongValueErrorString), + fValues(values) { } + void -EnumeratedStringValueSetting::ValueChanged(const char *newValue) +EnumeratedStringValueSetting::ValueChanged(const char* newValue) { #if DEBUG // must be one of the enumerated values bool found = false; for (int32 index = 0; ; index++) { - if (!values[index]) + if (!fValues[index]) break; - if (strcmp(values[index], newValue) != 0) + if (strcmp(fValues[index], newValue) != 0) continue; found = true; break; @@ -94,120 +105,136 @@ EnumeratedStringValueSetting::ValueChanged(const char *newValue) StringValueSetting::ValueChanged(newValue); } -const char * + +const char* EnumeratedStringValueSetting::Handle(const char *const *argv) { if (!*++argv) - return valueExpectedErrorString; + return fValueExpectedErrorString; -printf("-----EnumeratedStringValueSetting::Handle %s %s\n", *(argv-1), *argv); + printf("-----EnumeratedStringValueSetting::Handle %s %s\n", *(argv-1), *argv); bool found = false; for (int32 index = 0; ; index++) { - if (!values[index]) + if (!fValues[index]) break; - if (strcmp(values[index], *argv) != 0) + if (strcmp(fValues[index], *argv) != 0) continue; found = true; break; } if (!found) - return wrongValueErrorString; + return fWrongValueErrorString; ValueChanged(*argv); return 0; } -ScalarValueSetting::ScalarValueSetting(const char *name, int32 defaultValue, - const char *valueExpectedErrorString, const char *wrongValueErrorString, + +// #pragma mark - + + +ScalarValueSetting::ScalarValueSetting(const char* name, int32 defaultValue, + const char* valueExpectedErrorString, const char* wrongValueErrorString, int32 min, int32 max) - : SettingsArgvDispatcher(name), - defaultValue(defaultValue), - value(defaultValue), - max(max), - min(min), - valueExpectedErrorString(valueExpectedErrorString), - wrongValueErrorString(wrongValueErrorString) + : SettingsArgvDispatcher(name), + fDefaultValue(defaultValue), + fValue(defaultValue), + fMax(max), + fMin(min), + fValueExpectedErrorString(valueExpectedErrorString), + fWrongValueErrorString(wrongValueErrorString) { } + void ScalarValueSetting::ValueChanged(int32 newValue) { - ASSERT(newValue > min); - ASSERT(newValue < max); - value = newValue; + ASSERT(newValue > fMin); + ASSERT(newValue < fMax); + fValue = newValue; } + int32 ScalarValueSetting::Value() const { - return value; + return fValue; } + void -ScalarValueSetting::GetValueAsString(char *buffer) const +ScalarValueSetting::GetValueAsString(char* buffer) const { - sprintf(buffer, "%ld", value); + sprintf(buffer, "%ld", fValue); } -const char * + +const char* ScalarValueSetting::Handle(const char *const *argv) { if (!*++argv) - return valueExpectedErrorString; + return fValueExpectedErrorString; int32 newValue = atoi(*argv); - if (newValue < min || newValue > max) - return wrongValueErrorString; - - value = newValue; + if (newValue < fMin || newValue > fMax) + return fWrongValueErrorString; + + fValue = newValue; return 0; } + void -ScalarValueSetting::SaveSettingValue(Settings *settings) +ScalarValueSetting::SaveSettingValue(Settings* settings) { - settings->Write("%d", value); + settings->Write("%d", fValue); } + bool ScalarValueSetting::NeedsSaving() const { - return value != defaultValue; + return fValue != fDefaultValue; } -BooleanValueSetting::BooleanValueSetting(const char *name, bool defaultValue ) - : ScalarValueSetting(name, defaultValue, 0, 0) +// #pragma mark - + + +BooleanValueSetting::BooleanValueSetting(const char* name, bool defaultValue) + : ScalarValueSetting(name, defaultValue, 0, 0) { } + bool BooleanValueSetting::Value() const { - return value; + return fValue; } -const char * + +const char* BooleanValueSetting::Handle(const char *const *argv) { if (!*++argv) - return "or or off expected"; + return "on or off expected"; if (strcmp(*argv, "on") == 0) - value = true; + fValue = true; else if (strcmp(*argv, "off") == 0) - value = false; + fValue = false; else - return "or or off expected"; + return "on or off expected"; return 0; } -void -BooleanValueSetting::SaveSettingValue(Settings *settings) -{ - settings->Write(value ? "on" : "off"); -} +void +BooleanValueSetting::SaveSettingValue(Settings* settings) +{ + settings->Write(fValue ? "on" : "off"); +} diff --git a/src/apps/codycam/Settings.h b/src/apps/codycam/Settings.h index 0afa50afea..f06aeff37b 100644 --- a/src/apps/codycam/Settings.h +++ b/src/apps/codycam/Settings.h @@ -1,84 +1,86 @@ -#ifndef __SETTINGS__ -#define __SETTINGS__ +#ifndef SETTINGS_H +#define SETTINGS_H #include "SettingsHandler.h" -void SetUpSettings(char *filename); +void SetUpSettings(char* filename); void QuitSettings(); class StringValueSetting : public SettingsArgvDispatcher { // simple string setting public: - StringValueSetting(const char *name, const char *defaultValue, - const char *valueExpectedErrorString, - const char *wrongValueErrorString); + StringValueSetting(const char* name, const char* defaultValue, + const char* valueExpectedErrorString, + const char* wrongValueErrorString); virtual ~StringValueSetting(); - void ValueChanged(const char *newValue); - const char *Value() const; - virtual const char *Handle(const char *const *argv); + void ValueChanged(const char* newValue); + const char* Value() const; + virtual const char* Handle(const char *const *argv); protected: - virtual void SaveSettingValue(Settings *); + virtual void SaveSettingValue(Settings*); virtual bool NeedsSaving() const; - const char *defaultValue; - const char *valueExpectedErrorString; - const char *wrongValueErrorString; - char *value; + const char* fDefaultValue; + const char* fValueExpectedErrorString; + const char* fWrongValueErrorString; + char* fValue; }; + class EnumeratedStringValueSetting : public StringValueSetting { // string setting, values that do not match string enumeration // are rejected -public: - EnumeratedStringValueSetting(const char *name, const char *defaultValue, - const char *const *values, const char *valueExpectedErrorString, - const char *wrongValueErrorString); + public: + EnumeratedStringValueSetting(const char* name, const char* defaultValue, + const char *const *values, const char* valueExpectedErrorString, + const char* wrongValueErrorString); - void ValueChanged(const char *newValue); - virtual const char *Handle(const char *const *argv); + void ValueChanged(const char* newValue); + virtual const char* Handle(const char *const *argv); -protected: - const char *const *values; - char *value; + protected: + const char *const *fValues; + char* fValue; }; + class ScalarValueSetting : public SettingsArgvDispatcher { // simple int32 setting public: - ScalarValueSetting(const char *name, int32 defaultValue, - const char *valueExpectedErrorString, const char *wrongValueErrorString, + ScalarValueSetting(const char* name, int32 defaultValue, + const char* valueExpectedErrorString, const char* wrongValueErrorString, int32 min = LONG_MIN, int32 max = LONG_MAX); void ValueChanged(int32 newValue); int32 Value() const; - void GetValueAsString(char *) const; - virtual const char *Handle(const char *const *argv); + void GetValueAsString(char*) const; + virtual const char* Handle(const char *const *argv); protected: - virtual void SaveSettingValue(Settings *); + virtual void SaveSettingValue(Settings*); virtual bool NeedsSaving() const; - int32 defaultValue; - int32 value; - int32 max; - int32 min; - const char *valueExpectedErrorString; - const char *wrongValueErrorString; + int32 fDefaultValue; + int32 fValue; + int32 fMax; + int32 fMin; + const char* fValueExpectedErrorString; + const char* fWrongValueErrorString; }; class BooleanValueSetting : public ScalarValueSetting { // on-off setting -public: - BooleanValueSetting(const char *name, bool defaultValue); + public: + BooleanValueSetting(const char* name, bool defaultValue); - bool Value() const; - virtual const char *Handle(const char *const *argv); + bool Value() const; + virtual const char* Handle(const char *const *argv); -protected: - virtual void SaveSettingValue(Settings *); + protected: + virtual void SaveSettingValue(Settings *); }; -#endif +#endif // SETTINGS_H diff --git a/src/apps/codycam/SettingsHandler.cpp b/src/apps/codycam/SettingsHandler.cpp index 02e7379cdd..1d58f247d1 100644 --- a/src/apps/codycam/SettingsHandler.cpp +++ b/src/apps/codycam/SettingsHandler.cpp @@ -1,73 +1,101 @@ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - #include "SettingsHandler.h" -ArgvParser::ArgvParser(const char *name) - : file(0), - buffer(0), - pos(-1), - argc(0), - currentArgv(0), - currentArgsPos(-1), - sawBackslash(false), - eatComment(false), - inDoubleQuote(false), - inSingleQuote(false), - lineNo(0), - fileName(name) +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + + +#if 0 +static int +Compare(const SettingsArgvDispatcher* p1, const SettingsArgvDispatcher* p2) { - file = fopen(fileName, "r"); - if (!file) { - PRINT(("Error opening %s\n", fileName)); + return strcmp(p1->Name(), p2->Name()); +} +#endif + + +#if 0 +static int +CompareByNameOne(const SettingsArgvDispatcher* item1, + const SettingsArgvDispatcher* item2) +{ + return strcmp(item1->Name(), item2->Name()); +} +#endif + + +/*! \class ArgvParser + ArgvParser class opens a text file and passes the context in argv + format to a specified handler +*/ + + +ArgvParser::ArgvParser(const char* name) + : + fFile(0), + fBuffer(0), + fPos(-1), + fArgc(0), + fCurrentArgv(0), + fCurrentArgsPos(-1), + fSawBackslash(false), + fEatComment(false), + fInDoubleQuote(false), + fInSingleQuote(false), + fLineNo(0), + fFileName(name) +{ + fFile = fopen(fFileName, "r"); + if (!fFile) { + PRINT(("Error opening %s\n", fFileName)); return; } - buffer = new char [kBufferSize]; - currentArgv = new char * [1024]; + fBuffer = new char [kBufferSize]; + fCurrentArgv = new char* [1024]; } ArgvParser::~ArgvParser() { - delete [] buffer; + delete[] fBuffer; MakeArgvEmpty(); - delete [] currentArgv; + delete [] fCurrentArgv; - if (file) - fclose(file); + if (fFile) + fclose(fFile); } + void ArgvParser::MakeArgvEmpty() { // done with current argv, free it up - for (int32 index = 0; index < argc; index++) - delete currentArgv[index]; + for (int32 index = 0; index < fArgc; index++) + delete fCurrentArgv[index]; - argc = 0; + fArgc = 0; } + status_t -ArgvParser::SendArgv(ArgvHandler argvHandlerFunc, void *passThru) +ArgvParser::SendArgv(ArgvHandler argvHandlerFunc, void* passThru) { - if (argc) { + if (fArgc) { NextArgv(); - currentArgv[argc] = 0; - const char *result = (argvHandlerFunc)(argc, currentArgv, passThru); + fCurrentArgv[fArgc] = 0; + const char *result = (argvHandlerFunc)(fArgc, fCurrentArgv, passThru); if (result) - printf("File %s; Line %ld # %s", fileName, lineNo, result); + printf("File %s; Line %ld # %s", fFileName, fLineNo, result); MakeArgvEmpty(); if (result) return B_ERROR; @@ -76,54 +104,60 @@ ArgvParser::SendArgv(ArgvHandler argvHandlerFunc, void *passThru) return B_NO_ERROR; } + void ArgvParser::NextArgv() { - if (sawBackslash) { - currentArgs[++currentArgsPos] = '\\'; - sawBackslash = false; + if (fSawBackslash) { + fCurrentArgs[++fCurrentArgsPos] = '\\'; + fSawBackslash = false; } - currentArgs[++currentArgsPos] = '\0'; - // terminate current arg pos + fCurrentArgs[++fCurrentArgsPos] = '\0'; + // terminate current arg pos // copy it as a string to the current argv slot - currentArgv[argc] = new char [strlen(currentArgs) + 1]; - strcpy(currentArgv[argc], currentArgs); - currentArgsPos = -1; - argc++; + fCurrentArgv[fArgc] = new char [strlen(fCurrentArgs) + 1]; + strcpy(fCurrentArgv[fArgc], fCurrentArgs); + fCurrentArgsPos = -1; + fArgc++; } + void ArgvParser::NextArgvIfNotEmpty() { - if (!sawBackslash && currentArgsPos < 0) + if (!fSawBackslash && fCurrentArgsPos < 0) return; NextArgv(); } + char ArgvParser::GetCh() { - if (pos < 0 || buffer[pos] == 0) { - if (file == 0) + if (fPos < 0 || fBuffer[fPos] == 0) { + if (fFile == 0) return EOF; - if (fgets(buffer, kBufferSize, file) == 0) + if (fgets(fBuffer, kBufferSize, fFile) == 0) return EOF; - pos = 0; + fPos = 0; } - return buffer[pos++]; + return fBuffer[fPos++]; } + status_t -ArgvParser::EachArgv(const char *name, ArgvHandler argvHandlerFunc, void *passThru) +ArgvParser::EachArgv(const char* name, ArgvHandler argvHandlerFunc, void* passThru) { ArgvParser parser(name); return parser.EachArgvPrivate(name, argvHandlerFunc, passThru); } + status_t -ArgvParser::EachArgvPrivate(const char *name, ArgvHandler argvHandlerFunc, void *passThru) +ArgvParser::EachArgvPrivate(const char* name, ArgvHandler argvHandlerFunc, + void* passThru) { status_t result; @@ -131,7 +165,7 @@ ArgvParser::EachArgvPrivate(const char *name, ArgvHandler argvHandlerFunc, void char ch = GetCh(); if (ch == EOF) { // done with file - if (inDoubleQuote || inSingleQuote) { + if (fInDoubleQuote || fInSingleQuote) { printf("File %s # unterminated quote at end of file\n", name); result = B_ERROR; break; @@ -142,15 +176,15 @@ ArgvParser::EachArgvPrivate(const char *name, ArgvHandler argvHandlerFunc, void if (ch == '\n' || ch == '\r') { // handle new line - eatComment = false; - if (!sawBackslash && (inDoubleQuote || inSingleQuote)) { - printf("File %s ; Line %ld # unterminated quote\n", name, lineNo); + fEatComment = false; + if (!fSawBackslash && (fInDoubleQuote || fInSingleQuote)) { + printf("File %s ; Line %ld # unterminated quote\n", name, fLineNo); result = B_ERROR; break; } - lineNo++; - if (sawBackslash) { - sawBackslash = false; + fLineNo++; + if (fSawBackslash) { + fSawBackslash = false; continue; } // end of line, flush all argv @@ -160,11 +194,11 @@ ArgvParser::EachArgvPrivate(const char *name, ArgvHandler argvHandlerFunc, void continue; } - if (eatComment) + if (fEatComment) continue; - if (!sawBackslash) { - if (!inDoubleQuote && !inSingleQuote) { + if (!fSawBackslash) { + if (!fInDoubleQuote && !fInSingleQuote) { if (ch == ';') { // semicolon is a command separator, pass on the whole argv result = SendArgv(argvHandlerFunc, passThru); @@ -173,47 +207,52 @@ ArgvParser::EachArgvPrivate(const char *name, ArgvHandler argvHandlerFunc, void continue; } else if (ch == '#') { // ignore everything on this line after this character - eatComment = true; + fEatComment = true; continue; } else if (ch == ' ' || ch == '\t') { // space or tab separates the individual arg strings NextArgvIfNotEmpty(); continue; - } else if (!sawBackslash && ch == '\\') { + } else if (!fSawBackslash && ch == '\\') { // the next character is escaped - sawBackslash = true; + fSawBackslash = true; continue; } } - if (!inSingleQuote && ch == '"') { + if (!fInSingleQuote && ch == '"') { // enter/exit double quote handling - inDoubleQuote = !inDoubleQuote; + fInDoubleQuote = !fInDoubleQuote; continue; } - if (!inDoubleQuote && ch == '\'') { + if (!fInDoubleQuote && ch == '\'') { // enter/exit single quote handling - inSingleQuote = !inSingleQuote; + fInSingleQuote = !fInSingleQuote; continue; } } else { // we just pass through the escape sequence as is - currentArgs[++currentArgsPos] = '\\'; - sawBackslash = false; + fCurrentArgs[++fCurrentArgsPos] = '\\'; + fSawBackslash = false; } - currentArgs[++currentArgsPos] = ch; + fCurrentArgs[++fCurrentArgsPos] = ch; } return result; } -SettingsArgvDispatcher::SettingsArgvDispatcher(const char *name) - : name(name) +// #pragma mark - + + +SettingsArgvDispatcher::SettingsArgvDispatcher(const char* name) + : + fName(name) { } + void -SettingsArgvDispatcher::SaveSettings(Settings *settings, bool onlyIfNonDefault) +SettingsArgvDispatcher::SaveSettings(Settings* settings, bool onlyIfNonDefault) { if (!onlyIfNonDefault || NeedsSaving()) { settings->Write("%s ", Name()); @@ -222,8 +261,9 @@ SettingsArgvDispatcher::SaveSettings(Settings *settings, bool onlyIfNonDefault) } } + bool -SettingsArgvDispatcher::HandleRectValue(BRect &result, const char *const *argv, +SettingsArgvDispatcher::HandleRectValue(BRect &result, const char* const *argv, bool printError) { if (!*argv) { @@ -253,158 +293,165 @@ SettingsArgvDispatcher::HandleRectValue(BRect &result, const char *const *argv, return true; } + void -SettingsArgvDispatcher::WriteRectValue(Settings *setting, BRect rect) +SettingsArgvDispatcher::WriteRectValue(Settings* setting, BRect rect) { setting->Write("%d %d %d %d", (int32)rect.left, (int32)rect.top, (int32)rect.right, (int32)rect.bottom); } -#if 0 -static int -CompareByNameOne(const SettingsArgvDispatcher *item1, const SettingsArgvDispatcher *item2) -{ - return strcmp(item1->Name(), item2->Name()); -} -#endif -Settings::Settings(const char *filename, const char *settingsDirName) - : fileName(filename), - settingsDir(settingsDirName), - list(0), - count(0), - listSize(30), - currentSettings(0) +// #pragma mark - + + +/*! \class Settings + this class represents a list of all the settings handlers, reads and + saves the settings file +*/ + + +Settings::Settings(const char* filename, const char* settingsDirName) + : + fFileName(filename), + fSettingsDir(settingsDirName), + fList(0), + fCount(0), + fListSize(30), + fCurrentSettings(0) { #ifdef SINGLE_SETTING_FILE settingsHandler = this; #endif - list = (SettingsArgvDispatcher **)calloc(listSize, sizeof(SettingsArgvDispatcher *)); + fList = (SettingsArgvDispatcher**)calloc(fListSize, sizeof(SettingsArgvDispatcher *)); } Settings::~Settings() { - for (int32 index = 0; index < count; index++) - delete list[index]; + for (int32 index = 0; index < fCount; index++) + delete fList[index]; - free(list); + free(fList); } -const char * -Settings::ParseUserSettings(int, const char *const *argv, void *castToThis) +const char* +Settings::_ParseUserSettings(int, const char* const *argv, void* castToThis) { if (!*argv) return 0; #ifdef SINGLE_SETTING_FILE - Settings *settings = settingsHandler; + Settings* settings = settingsHandler; #else - Settings *settings = (Settings *)castToThis; + Settings* settings = (Settings*)castToThis; #endif - SettingsArgvDispatcher *handler = settings->Find(*argv); + SettingsArgvDispatcher* handler = settings->_Find(*argv); if (!handler) return "unknown command"; return handler->Handle(argv); } -#if 0 -static int -Compare(const SettingsArgvDispatcher *p1, const SettingsArgvDispatcher *p2) -{ - return strcmp(p1->Name(), p2->Name()); -} -#endif - -bool -Settings::Add(SettingsArgvDispatcher *setting) +/*! + Returns false if argv dispatcher with the same name already + registered +*/ +bool +Settings::Add(SettingsArgvDispatcher* setting) { // check for uniqueness - if (Find(setting->Name())) + if (_Find(setting->Name())) return false; - if (count >= listSize) { - listSize += 30; - list = (SettingsArgvDispatcher **)realloc(list, - listSize * sizeof(SettingsArgvDispatcher *)); + if (fCount >= fListSize) { + fListSize += 30; + fList = (SettingsArgvDispatcher **)realloc(fList, + fListSize * sizeof(SettingsArgvDispatcher *)); } - list[count++] = setting; + fList[fCount++] = setting; return true; } -SettingsArgvDispatcher * -Settings::Find(const char *name) + +SettingsArgvDispatcher* +Settings::_Find(const char* name) { - for (int32 index = 0; index < count; index++) - if (strcmp(name, list[index]->Name()) == 0) - return list[index]; + for (int32 index = 0; index < fCount; index++) + if (strcmp(name, fList[index]->Name()) == 0) + return fList[index]; return 0; } -void + +void Settings::TryReadingSettings() { BPath prefsPath; if (find_directory(B_USER_SETTINGS_DIRECTORY, &prefsPath, true) == B_OK) { - prefsPath.Append(settingsDir); + prefsPath.Append(fSettingsDir); BPath path(prefsPath); - path.Append(fileName); - ArgvParser::EachArgv(path.Path(), Settings::ParseUserSettings, this); + path.Append(fFileName); + ArgvParser::EachArgv(path.Path(), Settings::_ParseUserSettings, this); } } + void Settings::SaveSettings(bool onlyIfNonDefault) { ASSERT(SettingsHandler()); - SettingsHandler()->SaveCurrentSettings(onlyIfNonDefault); + SettingsHandler()->_SaveCurrentSettings(onlyIfNonDefault); } + void -Settings::MakeSettingsDirectory(BDirectory *resultingSettingsDir) +Settings::_MakeSettingsDirectory(BDirectory *resultingSettingsDir) { BPath path; if (find_directory(B_USER_SETTINGS_DIRECTORY, &path, true) != B_OK) return; // make sure there is a directory - path.Append(settingsDir); + path.Append(fSettingsDir); mkdir(path.Path(), 0777); resultingSettingsDir->SetTo(path.Path()); } -void -Settings::SaveCurrentSettings(bool onlyIfNonDefault) -{ - BDirectory settingsDir; - MakeSettingsDirectory(&settingsDir); - if (settingsDir.InitCheck() != B_OK) +void +Settings::_SaveCurrentSettings(bool onlyIfNonDefault) +{ + BDirectory fSettingsDir; + _MakeSettingsDirectory(&fSettingsDir); + + if (fSettingsDir.InitCheck() != B_OK) return; -printf("+++++++++++ Settings::SaveCurrentSettings %s\n", fileName); + + printf("+++++++++++ Settings::_SaveCurrentSettings %s\n", fFileName); // nuke old settings - BEntry entry(&settingsDir, fileName); + BEntry entry(&fSettingsDir, fFileName); entry.Remove(); BFile prefs(&entry, O_RDWR | O_CREAT); if (prefs.InitCheck() != B_OK) return; - currentSettings = &prefs; - for (int32 index = 0; index < count; index++) { - list[index]->SaveSettings(this, onlyIfNonDefault); + fCurrentSettings = &prefs; + for (int32 index = 0; index < fCount; index++) { + fList[index]->SaveSettings(this, onlyIfNonDefault); } - currentSettings = 0; + fCurrentSettings = 0; } + void -Settings::Write(const char *format, ...) +Settings::Write(const char* format, ...) { va_list args; @@ -413,15 +460,17 @@ Settings::Write(const char *format, ...) va_end(args); } + void -Settings::VSWrite(const char *format, va_list arg) +Settings::VSWrite(const char* format, va_list arg) { char buffer[2048]; vsprintf(buffer, format, arg); - ASSERT(currentSettings && currentSettings->InitCheck() == B_OK); - currentSettings->Write(buffer, strlen(buffer)); + ASSERT(fCurrentSettings && fCurrentSettings->InitCheck() == B_OK); + fCurrentSettings->Write(buffer, strlen(buffer)); } + #ifdef SINGLE_SETTING_FILE -Settings *Settings::settingsHandler = 0; +Settings* Settings::settingsHandler = 0; #endif diff --git a/src/apps/codycam/SettingsHandler.h b/src/apps/codycam/SettingsHandler.h index 7a3f7df7d7..5acc0247f8 100644 --- a/src/apps/codycam/SettingsHandler.h +++ b/src/apps/codycam/SettingsHandler.h @@ -1,11 +1,14 @@ -#ifndef __SETTINGS_FILE__ -#define __SETTINGS_FILE__ +#ifndef SETTINGS_HANDLER_H +#define SETTINGS_HANDLER_H + -#include #include +#include #include #include -#include + +#include + class BFile; class BDirectory; @@ -13,136 +16,139 @@ class BRect; class Settings; -typedef const char *(*ArgvHandler)(int argc, const char *const *argv, void *params); +typedef const char* (*ArgvHandler)(int argc, const char *const *argv, void *params); // return 0 or error string if parsing failed - + const int32 kBufferSize = 1024; + class ArgvParser { - // this class opens a text file and passes the context in argv - // format to a specified handler -public: - static status_t EachArgv(const char *name, - ArgvHandler argvHandlerFunc, void *passThru); + public: + static status_t EachArgv(const char* name, + ArgvHandler argvHandlerFunc, void* passThru); -private: - ArgvParser(const char *name); - ~ArgvParser(); + private: + ArgvParser(const char* name); + ~ArgvParser(); - status_t EachArgvPrivate(const char *name, - ArgvHandler argvHandlerFunc, void *passThru); - char GetCh(); - - status_t SendArgv(ArgvHandler argvHandlerFunc, void *passThru); - // done with a whole line of argv, send it off and get ready - // to build a new one + status_t EachArgvPrivate(const char* name, + ArgvHandler argvHandlerFunc, void* passThru); + char GetCh(); - void NextArgv(); - // done with current string, get ready to start building next - void NextArgvIfNotEmpty(); - // as above, don't commint current string if empty + status_t SendArgv(ArgvHandler argvHandlerFunc, void* passThru); + // done with a whole line of argv, send it off and get ready + // to build a new one - void MakeArgvEmpty(); + void NextArgv(); + // done with current string, get ready to start building next + void NextArgvIfNotEmpty(); + // as above, don't commint current string if empty - FILE *file; - char *buffer; - int32 pos; - int32 numAvail; - - int argc; - char **currentArgv; + void MakeArgvEmpty(); - int32 currentArgsPos; - char currentArgs [1024]; + FILE* fFile; + char* fBuffer; + int32 fPos; + int32 fNumAvail; - bool sawBackslash; - bool eatComment; - bool inDoubleQuote; - bool inSingleQuote; + int fArgc; + char** fCurrentArgv; - int32 lineNo; - const char *fileName; + int32 fCurrentArgsPos; + char fCurrentArgs[1024]; + + bool fSawBackslash; + bool fEatComment; + bool fInDoubleQuote; + bool fInSingleQuote; + + int32 fLineNo; + const char* fFileName; }; + class SettingsArgvDispatcher { - // base class for a single setting item -public: - SettingsArgvDispatcher(const char *name); + // base class for a single setting item + public: + SettingsArgvDispatcher(const char* name); - void SaveSettings(Settings *settings, bool onlyIfNonDefault); + void SaveSettings(Settings* settings, bool onlyIfNonDefault); - const char *Name() const - { return name; } - // name as it appears in the settings file - - virtual const char *Handle(const char *const *argv) = 0; - // override this adding an argv parser that reads in the - // values in argv format for this setting - // return a pointer to an error message or null if parsed OK + const char* Name() const + { + return fName; + } + virtual const char* Handle(const char* const *argv) = 0; + // override this adding an argv parser that reads in the + // values in argv format for this setting + // return a pointer to an error message or null if parsed OK - // some handy reader/writer calls - bool HandleRectValue(BRect &, const char *const *argv, bool printError = true); - // static bool HandleColorValue(rgb_color &, const char *const *argv, bool printError = true); - void WriteRectValue(Settings *, BRect); - // void WriteColorValue(BRect); + bool HandleRectValue(BRect&, const char* const *argv, + bool printError = true); -protected: - virtual void SaveSettingValue(Settings *settings) = 0; - // override this to save the current value of this setting in a - // text format - - virtual bool NeedsSaving() const - { return true; } + // static bool HandleColorValue(rgb_color &, const char *const *argv, bool printError = true); + void WriteRectValue(Settings*, BRect); + // void WriteColorValue(BRect); + + protected: + virtual void SaveSettingValue(Settings* settings) = 0; + // override this to save the current value of this setting in a + // text format + + virtual bool NeedsSaving() const + { + return true; + } // override to return false if current value is equal to the default // and does not need saving -private: - const char *name; + private: + const char* fName; }; + class Settings { - // this class is a list of all the settings handlers, reads and - // saves the settings file -public: - Settings(const char *filename, const char *settingsDirName); - ~Settings(); - void TryReadingSettings(); - void SaveSettings(bool onlyIfNonDefault = true); + public: + Settings(const char* filename, const char* settingsDirName); + ~Settings(); + void TryReadingSettings(); + void SaveSettings(bool onlyIfNonDefault = true); #ifdef SINGLE_SETTING_FILE - static Settings *SettingsHandler() - { return settingsHandler; } + static Settings* SettingsHandler() + { + return settingsHandler; + } #else - Settings *SettingsHandler() - { return this; } + Settings* SettingsHandler() + { + return this; + } #endif - bool Add(SettingsArgvDispatcher *); - // return false if argv dispatcher with the same name already - // registered + bool Add(SettingsArgvDispatcher *); - void Write(const char *format, ...); - void VSWrite(const char *, va_list); + void Write(const char* format, ...); + void VSWrite(const char*, va_list); #ifdef SINGLE_SETTING_FILE - static Settings *settingsHandler; + static Settings* settingsHandler; #endif -private: - void MakeSettingsDirectory(BDirectory *); + private: + void _MakeSettingsDirectory(BDirectory*); - SettingsArgvDispatcher *Find(const char *); - static const char *ParseUserSettings(int, const char *const *argv, void *); - void SaveCurrentSettings(bool onlyIfNonDefault); + SettingsArgvDispatcher* _Find(const char*); + static const char* _ParseUserSettings(int, const char *const *argv, void*); + void _SaveCurrentSettings(bool onlyIfNonDefault); - const char *fileName; - const char *settingsDir; - SettingsArgvDispatcher **list; - int32 count; - int32 listSize; - BFile *currentSettings; + const char* fFileName; + const char* fSettingsDir; + SettingsArgvDispatcher** fList; + int32 fCount; + int32 fListSize; + BFile* fCurrentSettings; }; - -#endif +#endif // SETTINGS_HANDLER_H diff --git a/src/apps/codycam/VideoConsumer.cpp b/src/apps/codycam/VideoConsumer.cpp index ebff574f56..4e923e37bc 100644 --- a/src/apps/codycam/VideoConsumer.cpp +++ b/src/apps/codycam/VideoConsumer.cpp @@ -2,23 +2,26 @@ // SMS // VideoConsumer.cpp -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include "FtpClient.h" #include "VideoConsumer.h" +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + #define M1 ((double)1000000.0) #define JITTER 20000 @@ -27,60 +30,51 @@ #define PROGRESS printf #define LOOP printf -static status_t SetFileType(BFile * file, int32 translator, uint32 type); +static status_t SetFileType(BFile* file, int32 translator, uint32 type); -const media_raw_video_format vid_format = { 29.97,1,0,239,B_VIDEO_TOP_LEFT_RIGHT,1,1,{B_RGB16,320,240,320*4,0,0}}; +const media_raw_video_format vid_format = {29.97, 1, 0, 239, B_VIDEO_TOP_LEFT_RIGHT, + 1, 1, {B_RGB16, 320, 240, 320 * 4, 0, 0}}; -//--------------------------------------------------------------- -VideoConsumer::VideoConsumer( - const char * name, - BView *view, - BStringView * statusLine, - BMediaAddOn *addon, - const uint32 internal_id) : - - BMediaNode(name), - BMediaEventLooper(), - BBufferConsumer(B_MEDIA_RAW_VIDEO), - mStatusLine(statusLine), - mInternalID(internal_id), - mAddOn(addon), - mConnectionActive(false), - mMyLatency(20000), - mWindow(NULL), - mView(view), - mOurBuffers(false), - mBuffers(NULL), - mTimeToFtp(false), - mFtpComplete(true), - mRate(1000000), - mImageFormat(0), - mTranslator(0), - mPassiveFtp(true) +VideoConsumer::VideoConsumer(const char* name, BView* view, BStringView* statusLine, + BMediaAddOn* addon, const uint32 internalId) + : BMediaNode(name), BMediaEventLooper(), BBufferConsumer(B_MEDIA_RAW_VIDEO), + fStatusLine(statusLine), + fInternalID(internalId), + fAddOn(addon), + fConnectionActive(false), + fMyLatency(20000), + fWindow(NULL), + fView(view), + fOurBuffers(false), + fBuffers(NULL), + fTimeToFtp(false), + fFtpComplete(true), + fRate(1000000), + fImageFormat(0), + fTranslator(0), + fPassiveFtp(true) { FUNCTION("VideoConsumer::VideoConsumer\n"); AddNodeKind(B_PHYSICAL_OUTPUT); SetEventLatency(0); - mWindow = mView->Window(); + fWindow = fView->Window(); - for (uint32 j = 0; j < 3; j++) - { - mBitmap[j] = NULL; - mBufferMap[j] = 0; + for (uint32 j = 0; j < 3; j++) { + fBitmap[j] = NULL; + fBufferMap[j] = 0; } - - strcpy(mFileNameText, ""); - strcpy(mServerText, ""); - strcpy(mLoginText, ""); - strcpy(mPasswordText, ""); - strcpy(mDirectoryText, ""); + + strcpy(fFileNameText, ""); + strcpy(fServerText, ""); + strcpy(fLoginText, ""); + strcpy(fPasswordText, ""); + strcpy(fDirectoryText, ""); SetPriority(B_DISPLAY_PRIORITY); } -//--------------------------------------------------------------- VideoConsumer::~VideoConsumer() { @@ -88,113 +82,107 @@ VideoConsumer::~VideoConsumer() Quit(); - if (mWindow) - { + if (fWindow) { printf("Locking the window\n"); - if (mWindow->Lock()) - { + if (fWindow->Lock()) { printf("Closing the window\n"); - mWindow->Close(); - mWindow = 0; + fWindow->Close(); + fWindow = 0; } } // clean up ftp thread // wait up to 30 seconds if ftp is in progress int32 count = 0; - while (!mFtpComplete && (count < 30)) - { + while (!fFtpComplete && count < 30) { snooze(1000000); count++; } - if(count == 30) - kill_thread(mFtpThread); + if (count == 30) + kill_thread(fFtpThread); DeleteBuffers(); - } /******************************** From BMediaNode ********************************/ -//--------------------------------------------------------------- -BMediaAddOn * -VideoConsumer::AddOn(long *cookie) const +BMediaAddOn* +VideoConsumer::AddOn(long* cookie) const { FUNCTION("VideoConsumer::AddOn\n"); // do the right thing if we're ever used with an add-on - *cookie = mInternalID; - return mAddOn; + *cookie = fInternalID; + return fAddOn; } -//--------------------------------------------------------------- // This implementation is required to get around a bug in // the ppc compiler. void -VideoConsumer::Start(bigtime_t performance_time) +VideoConsumer::Start(bigtime_t performanceTime) { - BMediaEventLooper::Start(performance_time); + BMediaEventLooper::Start(performanceTime); } -void -VideoConsumer::Stop(bigtime_t performance_time, bool immediate) -{ - BMediaEventLooper::Stop(performance_time, immediate); -} void -VideoConsumer::Seek(bigtime_t media_time, bigtime_t performance_time) +VideoConsumer::Stop(bigtime_t performanceTime, bool immediate) { - BMediaEventLooper::Seek(media_time, performance_time); + BMediaEventLooper::Stop(performanceTime, immediate); } + void -VideoConsumer::TimeWarp(bigtime_t at_real_time, bigtime_t to_performance_time) +VideoConsumer::Seek(bigtime_t mediaTime, bigtime_t performanceTime) { - BMediaEventLooper::TimeWarp(at_real_time, to_performance_time); + BMediaEventLooper::Seek(mediaTime, performanceTime); } + +void +VideoConsumer::TimeWarp(bigtime_t atRealTime, bigtime_t toPerformanceTime) +{ + BMediaEventLooper::TimeWarp(atRealTime, toPerformanceTime); +} + + status_t -VideoConsumer::DeleteHook(BMediaNode *node) +VideoConsumer::DeleteHook(BMediaNode* node) { return BMediaEventLooper::DeleteHook(node); } -//--------------------------------------------------------------- void VideoConsumer::NodeRegistered() { FUNCTION("VideoConsumer::NodeRegistered\n"); - mIn.destination.port = ControlPort(); - mIn.destination.id = 0; - mIn.source = media_source::null; - mIn.format.type = B_MEDIA_RAW_VIDEO; - mIn.format.u.raw_video = vid_format; + fIn.destination.port = ControlPort(); + fIn.destination.id = 0; + fIn.source = media_source::null; + fIn.format.type = B_MEDIA_RAW_VIDEO; + fIn.format.u.raw_video = vid_format; Run(); } -//--------------------------------------------------------------- status_t -VideoConsumer::RequestCompleted(const media_request_info & info) +VideoConsumer::RequestCompleted(const media_request_info& info) { FUNCTION("VideoConsumer::RequestCompleted\n"); - switch(info.what) - { + switch (info.what) { case media_request_info::B_SET_OUTPUT_BUFFERS_FOR: - { - if (info.status != B_OK) + if (info.status != B_OK) ERROR("VideoConsumer::RequestCompleted: Not using our buffers!\n"); - } break; + default: ERROR("VideoConsumer::RequestCompleted: Invalid argument\n"); break; @@ -202,33 +190,34 @@ VideoConsumer::RequestCompleted(const media_request_info & info) return B_OK; } -//--------------------------------------------------------------- status_t -VideoConsumer::HandleMessage(int32 message, const void * data, size_t size) +VideoConsumer::HandleMessage(int32 message, const void* data, size_t size) { //FUNCTION("VideoConsumer::HandleMessage\n"); - ftp_msg_info *info = (ftp_msg_info *)data; + ftp_msg_info* info = (ftp_msg_info*)data; status_t status = B_OK; - - switch (message) - { + + switch (message) { case FTP_INFO: PROGRESS("VideoConsumer::HandleMessage - FTP_INFO message\n"); - mRate = info->rate; - mImageFormat = info->imageFormat; - mTranslator = info->translator; - mPassiveFtp = info->passiveFtp; - strcpy(mFileNameText, info->fileNameText); - strcpy(mServerText, info->serverText); - strcpy(mLoginText, info->loginText); - strcpy(mPasswordText, info->passwordText); - strcpy(mDirectoryText, info->directoryText); + fRate = info->rate; + fImageFormat = info->imageFormat; + fTranslator = info->translator; + fPassiveFtp = info->passiveFtp; + strcpy(fFileNameText, info->fileNameText); + strcpy(fServerText, info->serverText); + strcpy(fLoginText, info->loginText); + strcpy(fPasswordText, info->passwordText); + strcpy(fDirectoryText, info->directoryText); // remove old user events - EventQueue()->FlushEvents(TimeSource()->Now(), BTimedEventQueue::B_ALWAYS, true, BTimedEventQueue::B_USER_EVENT); - if (mRate != B_INFINITE_TIMEOUT) { - // if rate is not "Never," push an event to restart captures 5 seconds from now - media_timed_event event(TimeSource()->Now() + 5000000, BTimedEventQueue::B_USER_EVENT); + EventQueue()->FlushEvents(TimeSource()->Now(), BTimedEventQueue::B_ALWAYS, + true, BTimedEventQueue::B_USER_EVENT); + if (fRate != B_INFINITE_TIMEOUT) { + // if rate is not "Never," push an event + // to restart captures 5 seconds from now + media_timed_event event(TimeSource()->Now() + 5000000, + BTimedEventQueue::B_USER_EVENT); EventQueue()->AddEvent(event); } break; @@ -237,399 +226,349 @@ VideoConsumer::HandleMessage(int32 message, const void * data, size_t size) return status; } -//--------------------------------------------------------------- void -VideoConsumer::BufferReceived(BBuffer * buffer) +VideoConsumer::BufferReceived(BBuffer* buffer) { LOOP("VideoConsumer::Buffer #%ld received\n", buffer->ID()); - if (RunState() == B_STOPPED) - { + if (RunState() == B_STOPPED) { buffer->Recycle(); return; } media_timed_event event(buffer->Header()->start_time, BTimedEventQueue::B_HANDLE_BUFFER, - buffer, BTimedEventQueue::B_RECYCLE_BUFFER); + buffer, BTimedEventQueue::B_RECYCLE_BUFFER); EventQueue()->AddEvent(event); } -//--------------------------------------------------------------- - void -VideoConsumer::ProducerDataStatus( - const media_destination &for_whom, - int32 status, - bigtime_t at_media_time) +VideoConsumer::ProducerDataStatus(const media_destination& forWhom, int32 status, + bigtime_t atMediaTime) { FUNCTION("VideoConsumer::ProducerDataStatus\n"); - if (for_whom != mIn.destination) + if (forWhom != fIn.destination) return; } -//--------------------------------------------------------------- status_t -VideoConsumer::CreateBuffers( - const media_format & with_format) +VideoConsumer::CreateBuffers(const media_format& withFormat) { FUNCTION("VideoConsumer::CreateBuffers\n"); - - // delete any old buffers + DeleteBuffers(); + // delete any old buffers status_t status = B_OK; // create a buffer group - uint32 mXSize = with_format.u.raw_video.display.line_width; - uint32 mYSize = with_format.u.raw_video.display.line_count; - color_space mColorspace = with_format.u.raw_video.display.format; - PROGRESS("VideoConsumer::CreateBuffers - Colorspace = %d\n", mColorspace); + uint32 xSize = withFormat.u.raw_video.display.line_width; + uint32 ySize = withFormat.u.raw_video.display.line_count; + color_space colorspace = withFormat.u.raw_video.display.format; + PROGRESS("VideoConsumer::CreateBuffers - Colorspace = %d\n", colorspace); - mBuffers = new BBufferGroup(); - status = mBuffers->InitCheck(); - if (B_OK != status) - { + fBuffers = new BBufferGroup(); + status = fBuffers->InitCheck(); + if (status != B_OK) { ERROR("VideoConsumer::CreateBuffers - ERROR CREATING BUFFER GROUP\n"); return status; } // and attach the bitmaps to the buffer group - for (uint32 j=0; j < 3; j++) - { - mBitmap[j] = new BBitmap(BRect(0, 0, (mXSize-1), (mYSize - 1)), mColorspace, false, true); - if (mBitmap[j]->IsValid()) - { + for (uint32 j = 0; j < 3; j++) { + fBitmap[j] = new BBitmap(BRect(0, 0, (xSize - 1), (ySize - 1)), colorspace, + false, true); + if (fBitmap[j]->IsValid()) { buffer_clone_info info; - if ((info.area = area_for(mBitmap[j]->Bits())) == B_ERROR) - ERROR("VideoConsumer::CreateBuffers - ERROR IN AREA_FOR\n");; + if ((info.area = area_for(fBitmap[j]->Bits())) == B_ERROR) + ERROR("VideoConsumer::CreateBuffers - ERROR IN AREA_FOR\n"); info.offset = 0; - info.size = (size_t)mBitmap[j]->BitsLength(); + info.size = (size_t)fBitmap[j]->BitsLength(); info.flags = j; info.buffer = 0; - if ((status = mBuffers->AddBuffer(info)) != B_OK) - { + if ((status = fBuffers->AddBuffer(info)) != B_OK) { ERROR("VideoConsumer::CreateBuffers - ERROR ADDING BUFFER TO GROUP\n"); return status; - } else PROGRESS("VideoConsumer::CreateBuffers - SUCCESSFUL ADD BUFFER TO GROUP\n"); - } - else - { - ERROR("VideoConsumer::CreateBuffers - ERROR CREATING VIDEO RING BUFFER: %08lx\n", status); - return B_ERROR; - } - } - - BBuffer ** buffList = new BBuffer * [3]; - for (int j = 0; j < 3; j++) buffList[j] = 0; - - if ((status = mBuffers->GetBufferList(3, buffList)) == B_OK) - for (int j = 0; j < 3; j++) - if (buffList[j] != NULL) - { - mBufferMap[j] = (uint32) buffList[j]; - PROGRESS(" j = %d buffer = %08lx\n", j, mBufferMap[j]); } else - { + PROGRESS("VideoConsumer::CreateBuffers - SUCCESSFUL ADD BUFFER TO GROUP\n"); + } else { + ERROR("VideoConsumer::CreateBuffers - ERROR CREATING VIDEO RING BUFFER: %08lx\n", + status); + return B_ERROR; + } + } + + BBuffer** buffList = new BBuffer * [3]; + for (int j = 0; j < 3; j++) + buffList[j] = 0; + + if ((status = fBuffers->GetBufferList(3, buffList)) == B_OK) + for (int j = 0; j < 3; j++) + if (buffList[j] != NULL) { + fBufferMap[j] = (uint32)buffList[j]; + PROGRESS(" j = %d buffer = %08lx\n", j, fBufferMap[j]); + } else { ERROR("VideoConsumer::CreateBuffers ERROR MAPPING RING BUFFER\n"); return B_ERROR; } else ERROR("VideoConsumer::CreateBuffers ERROR IN GET BUFFER LIST\n"); - + FUNCTION("VideoConsumer::CreateBuffers - EXIT\n"); return status; } -//--------------------------------------------------------------- void VideoConsumer::DeleteBuffers() { FUNCTION("VideoConsumer::DeleteBuffers\n"); - - if (mBuffers) - { - delete mBuffers; - mBuffers = NULL; - + + if (fBuffers) { + delete fBuffers; + fBuffers = NULL; + for (uint32 j = 0; j < 3; j++) - if (mBitmap[j]->IsValid()) - { - delete mBitmap[j]; - mBitmap[j] = NULL; + if (fBitmap[j]->IsValid()) { + delete fBitmap[j]; + fBitmap[j] = NULL; } } FUNCTION("VideoConsumer::DeleteBuffers - EXIT\n"); } -//--------------------------------------------------------------- status_t -VideoConsumer::Connected( - const media_source & producer, - const media_destination & where, - const media_format & with_format, - media_input * out_input) +VideoConsumer::Connected(const media_source& producer, const media_destination& where, + const media_format& withFormat, media_input* outInput) { FUNCTION("VideoConsumer::Connected\n"); - mIn.source = producer; - mIn.format = with_format; - mIn.node = Node(); - sprintf(mIn.name, "Video Consumer"); - *out_input = mIn; + fIn.source = producer; + fIn.format = withFormat; + fIn.node = Node(); + sprintf(fIn.name, "Video Consumer"); + *outInput = fIn; - uint32 user_data = 0; - int32 change_tag = 1; - if (CreateBuffers(with_format) == B_OK) - BBufferConsumer::SetOutputBuffersFor(producer, mDestination, - mBuffers, (void *)&user_data, &change_tag, true); - else - { + uint32 userData = 0; + int32 changeTag = 1; + if (CreateBuffers(withFormat) == B_OK) + BBufferConsumer::SetOutputBuffersFor(producer, fDestination, + fBuffers, (void *)&userData, &changeTag, true); + else { ERROR("VideoConsumer::Connected - COULDN'T CREATE BUFFERS\n"); return B_ERROR; } - mFtpBitmap = new BBitmap(BRect(0, 0, 320-1, 240-1), B_RGB32, false, false); - mConnectionActive = true; - + fFtpBitmap = new BBitmap(BRect(0, 0, 320 - 1, 240 - 1), B_RGB32, false, false); + fConnectionActive = true; + FUNCTION("VideoConsumer::Connected - EXIT\n"); return B_OK; } -//--------------------------------------------------------------- void -VideoConsumer::Disconnected( - const media_source & producer, - const media_destination & where) +VideoConsumer::Disconnected(const media_source& producer, const media_destination& where) { FUNCTION("VideoConsumer::Disconnected\n"); - if (where == mIn.destination && producer == mIn.source) - { + if (where == fIn.destination && producer == fIn.source) { // disconnect the connection - mIn.source = media_source::null; - delete mFtpBitmap; - mConnectionActive = false; + fIn.source = media_source::null; + delete fFtpBitmap; + fConnectionActive = false; } } -//--------------------------------------------------------------- status_t -VideoConsumer::AcceptFormat( - const media_destination & dest, - media_format * format) +VideoConsumer::AcceptFormat(const media_destination& dest, media_format* format) { FUNCTION("VideoConsumer::AcceptFormat\n"); - if (dest != mIn.destination) - { + if (dest != fIn.destination) { ERROR("VideoConsumer::AcceptFormat - BAD DESTINATION\n"); return B_MEDIA_BAD_DESTINATION; } - + if (format->type == B_MEDIA_NO_TYPE) format->type = B_MEDIA_RAW_VIDEO; - if (format->type != B_MEDIA_RAW_VIDEO) - { + if (format->type != B_MEDIA_RAW_VIDEO) { ERROR("VideoConsumer::AcceptFormat - BAD FORMAT\n"); return B_MEDIA_BAD_FORMAT; } - if (format->u.raw_video.display.format != B_RGB32 && - format->u.raw_video.display.format != B_RGB16 && - format->u.raw_video.display.format != B_RGB15 && - format->u.raw_video.display.format != B_GRAY8 && - format->u.raw_video.display.format != media_raw_video_format::wildcard.display.format) - { + if (format->u.raw_video.display.format != B_RGB32 + && format->u.raw_video.display.format != B_RGB16 + && format->u.raw_video.display.format != B_RGB15 + && format->u.raw_video.display.format != B_GRAY8 + && + format->u.raw_video.display.format != media_raw_video_format::wildcard.display.format) { ERROR("AcceptFormat - not a format we know about!\n"); return B_MEDIA_BAD_FORMAT; } - - if (format->u.raw_video.display.format == media_raw_video_format::wildcard.display.format) - { + + if (format->u.raw_video.display.format == media_raw_video_format::wildcard.display.format) { format->u.raw_video.display.format = B_RGB16; } - char format_string[256]; - string_for_format(*format, format_string, 256); - FUNCTION("VideoConsumer::AcceptFormat: %s\n", format_string); + char formatString[256]; + string_for_format(*format, formatString, 256); + FUNCTION("VideoConsumer::AcceptFormat: %s\n", formatString); return B_OK; } -//--------------------------------------------------------------- status_t -VideoConsumer::GetNextInput( - int32 * cookie, - media_input * out_input) +VideoConsumer::GetNextInput(int32* cookie, media_input* outInput) { FUNCTION("VideoConsumer::GetNextInput\n"); // custom build a destination for this connection // put connection number in id - if (*cookie < 1) - { - mIn.node = Node(); - mIn.destination.id = *cookie; - sprintf(mIn.name, "Video Consumer"); - *out_input = mIn; + if (*cookie < 1) { + fIn.node = Node(); + fIn.destination.id = *cookie; + sprintf(fIn.name, "Video Consumer"); + *outInput = fIn; (*cookie)++; return B_OK; - } - else - { + } else { ERROR("VideoConsumer::GetNextInput - - BAD INDEX\n"); return B_MEDIA_BAD_DESTINATION; } } -//--------------------------------------------------------------- void VideoConsumer::DisposeInputCookie(int32 /*cookie*/) { } -//--------------------------------------------------------------- status_t -VideoConsumer::GetLatencyFor( - const media_destination &for_whom, - bigtime_t * out_latency, - media_node_id * out_timesource) +VideoConsumer::GetLatencyFor(const media_destination& forWhom, bigtime_t* outLatency, + media_node_id* out_timesource) { FUNCTION("VideoConsumer::GetLatencyFor\n"); - if (for_whom != mIn.destination) + if (forWhom != fIn.destination) return B_MEDIA_BAD_DESTINATION; - *out_latency = mMyLatency; + *outLatency = fMyLatency; *out_timesource = TimeSource()->ID(); return B_OK; } -//--------------------------------------------------------------- - status_t -VideoConsumer::FormatChanged( - const media_source & producer, - const media_destination & consumer, - int32 from_change_count, - const media_format &format) +VideoConsumer::FormatChanged(const media_source& producer, const media_destination& consumer, + int32 fromChangeCount, const media_format& format) { FUNCTION("VideoConsumer::FormatChanged\n"); - - if (consumer != mIn.destination) + + if (consumer != fIn.destination) return B_MEDIA_BAD_DESTINATION; - if (producer != mIn.source) + if (producer != fIn.source) return B_MEDIA_BAD_SOURCE; - mIn.format = format; - + fIn.format = format; + return CreateBuffers(format); } -//--------------------------------------------------------------- void -VideoConsumer::HandleEvent( - const media_timed_event *event, - bigtime_t lateness, +VideoConsumer::HandleEvent(const media_timed_event* event, bigtime_t lateness, bool realTimeEvent) - { LOOP("VideoConsumer::HandleEvent\n"); - BBuffer *buffer; - - switch (event->type) - { + BBuffer* buffer; + + switch (event->type) { case BTimedEventQueue::B_START: PROGRESS("VideoConsumer::HandleEvent - START\n"); break; + case BTimedEventQueue::B_STOP: PROGRESS("VideoConsumer::HandleEvent - STOP\n"); - EventQueue()->FlushEvents(event->event_time, BTimedEventQueue::B_ALWAYS, true, BTimedEventQueue::B_HANDLE_BUFFER); + EventQueue()->FlushEvents(event->event_time, BTimedEventQueue::B_ALWAYS, + true, BTimedEventQueue::B_HANDLE_BUFFER); break; + case BTimedEventQueue::B_USER_EVENT: PROGRESS("VideoConsumer::HandleEvent - USER EVENT\n"); - if (RunState() == B_STARTED) - { - mTimeToFtp = true; - PROGRESS("Pushing user event for %.4f, time now %.4f\n", (event->event_time + mRate)/M1, event->event_time/M1); - media_timed_event newEvent(event->event_time + mRate, BTimedEventQueue::B_USER_EVENT); + if (RunState() == B_STARTED) { + fTimeToFtp = true; + PROGRESS("Pushing user event for %.4f, time now %.4f\n", + (event->event_time + fRate) / M1, event->event_time/M1); + media_timed_event newEvent(event->event_time + fRate, + BTimedEventQueue::B_USER_EVENT); EventQueue()->AddEvent(newEvent); } - break; + break; + case BTimedEventQueue::B_HANDLE_BUFFER: + { LOOP("VideoConsumer::HandleEvent - HANDLE BUFFER\n"); - buffer = (BBuffer *) event->pointer; - if (RunState() == B_STARTED && mConnectionActive) - { + buffer = (BBuffer *)event->pointer; + if (RunState() == B_STARTED && fConnectionActive) { // see if this is one of our buffers uint32 index = 0; - mOurBuffers = true; - while(index < 3) - if ((uint32)buffer == mBufferMap[index]) + fOurBuffers = true; + while (index < 3) + if ((uint32)buffer == fBufferMap[index]) break; else index++; - - if (index == 3) - { + + if (index == 3) { // no, buffers belong to consumer - mOurBuffers = false; + fOurBuffers = false; index = 0; } - - if (mFtpComplete && mTimeToFtp) - { + + if (fFtpComplete && fTimeToFtp) { PROGRESS("VidConsumer::HandleEvent - SPAWNING FTP THREAD\n"); - mTimeToFtp = false; - mFtpComplete = false; - memcpy(mFtpBitmap->Bits(), buffer->Data(),mFtpBitmap->BitsLength()); - mFtpThread = spawn_thread(FtpRun, "Video Window Ftp", B_NORMAL_PRIORITY, this); - resume_thread(mFtpThread); + fTimeToFtp = false; + fFtpComplete = false; + memcpy(fFtpBitmap->Bits(), buffer->Data(), fFtpBitmap->BitsLength()); + fFtpThread = spawn_thread(FtpRun, "Video Window Ftp", B_NORMAL_PRIORITY, this); + resume_thread(fFtpThread); } - if ( (RunMode() == B_OFFLINE) || - ((TimeSource()->Now() > (buffer->Header()->start_time - JITTER)) && - (TimeSource()->Now() < (buffer->Header()->start_time + JITTER))) ) - { - if (!mOurBuffers) + if ((RunMode() == B_OFFLINE) + || ((TimeSource()->Now() > (buffer->Header()->start_time - JITTER)) + && (TimeSource()->Now() < (buffer->Header()->start_time + JITTER)))) { + if (!fOurBuffers) // not our buffers, so we need to copy - memcpy(mBitmap[index]->Bits(), buffer->Data(),mBitmap[index]->BitsLength()); - - if (mWindow->Lock()) - { + memcpy(fBitmap[index]->Bits(), buffer->Data(), fBitmap[index]->BitsLength()); + + if (fWindow->Lock()) { uint32 flags; - if ((mBitmap[index]->ColorSpace() == B_GRAY8) && - !bitmaps_support_space(mBitmap[index]->ColorSpace(), &flags)) - { + if ((fBitmap[index]->ColorSpace() == B_GRAY8) && + !bitmaps_support_space(fBitmap[index]->ColorSpace(), &flags)) { // handle mapping of GRAY8 until app server knows how - uint32 *start = (uint32 *)mBitmap[index]->Bits(); - int32 size = mBitmap[index]->BitsLength(); - uint32 *end = start + size/4; - for (uint32 *p = start; p < end; p++) + uint32* start = (uint32*)fBitmap[index]->Bits(); + int32 size = fBitmap[index]->BitsLength(); + uint32* end = start + size / 4; + for (uint32* p = start; p < end; p++) *p = (*p >> 3) & 0x1f1f1f1f; } - - mView->DrawBitmap(mBitmap[index]); - mWindow->Unlock(); + + fView->DrawBitmap(fBitmap[index]); + fWindow->Unlock(); } } else @@ -639,16 +578,17 @@ VideoConsumer::HandleEvent( else buffer->Recycle(); break; + } + default: ERROR("VideoConsumer::HandleEvent - BAD EVENT\n"); break; } } -//--------------------------------------------------------------- status_t -VideoConsumer::FtpRun(void * data) +VideoConsumer::FtpRun(void* data) { FUNCTION("VideoConsumer::FtpRun\n"); @@ -657,25 +597,23 @@ VideoConsumer::FtpRun(void * data) return 0; } -//--------------------------------------------------------------- - void VideoConsumer::FtpThread() { FUNCTION("VideoConsumer::FtpThread\n"); - if (LocalSave(mFileNameText, mFtpBitmap) == B_OK) - FtpSave(mFileNameText); - + if (LocalSave(fFileNameText, fFtpBitmap) == B_OK) + FtpSave(fFileNameText); + #if 0 // save a small version, too - BBitmap * b = new BBitmap(BRect(0,0,159,119), B_RGB32, true, false); - BView * v = new BView(BRect(0,0,159,119), "SmallView 1", 0, B_WILL_DRAW); + BBitmap* b = new BBitmap(BRect(0,0,159,119), B_RGB32, true, false); + BView* v = new BView(BRect(0,0,159,119), "SmallView 1", 0, B_WILL_DRAW); b->AddChild(v); b->Lock(); - v->DrawBitmap(mFtpBitmap, v->Frame()); + v->DrawBitmap(fFtpBitmap, v->Frame()); v->Sync(); b->Unlock(); @@ -685,124 +623,125 @@ VideoConsumer::FtpThread() delete b; #endif - mFtpComplete = true; + fFtpComplete = true; } -//--------------------------------------------------------------- void -VideoConsumer::UpdateFtpStatus(char *status) +VideoConsumer::UpdateFtpStatus(char* status) { printf("FTP STATUS: %s\n",status); - if (mView->Window()->Lock()) - { - mStatusLine->SetText(status); - mView->Window()->Unlock(); + if (fView->Window()->Lock()) { + fStatusLine->SetText(status); + fView->Window()->Unlock(); } } -//--------------------------------------------------------------- status_t -VideoConsumer::LocalSave(char *filename, BBitmap *bitmap) +VideoConsumer::LocalSave(char* filename, BBitmap* bitmap) { - BFile *output; - + BFile* output; + UpdateFtpStatus("Capturing Image ..."); /* save a local copy of the image in the requested format */ - output =new BFile(); - if (output->SetTo(filename, B_READ_WRITE | B_CREATE_FILE | B_ERASE_FILE) == B_NO_ERROR) - { + output = new BFile(); + if (output->SetTo(filename, B_READ_WRITE | B_CREATE_FILE | B_ERASE_FILE) == B_NO_ERROR) { BBitmapStream input(bitmap); - status_t err = BTranslatorRoster::Default()->Translate(&input, NULL, NULL, output, mImageFormat); - if (err == B_OK) - { - err = SetFileType(output, mTranslator, mImageFormat); + status_t err = BTranslatorRoster::Default()->Translate(&input, NULL, NULL, + output, fImageFormat); + if (err == B_OK) { + err = SetFileType(output, fTranslator, fImageFormat); if (err != B_OK) UpdateFtpStatus("Error setting type of output file"); } else - { UpdateFtpStatus("Error writing output file"); - } - input.DetachBitmap(&bitmap); - output->Unset(); - delete output; - return B_OK; - } - else - { + + input.DetachBitmap(&bitmap); + output->Unset(); + delete output; + return B_OK; + } else { UpdateFtpStatus("Error creating output file"); return B_ERROR; } } -//--------------------------------------------------------------- status_t -VideoConsumer::FtpSave(char *filename) +VideoConsumer::FtpSave(char* filename) { - FtpClient ftp; + FtpClient ftp; + + ftp.SetPassive(fPassiveFtp); + // ftp the local file to our web site - /* ftp the local file to our web site */ - ftp.setPassive(mPassiveFtp); - UpdateFtpStatus("Logging in ..."); - if (ftp.connect((string)mServerText, (string)mLoginText, (string)mPasswordText)) // connect to server - { + if (ftp.Connect((string)fServerText, (string)fLoginText, (string)fPasswordText)) { + // connect to server UpdateFtpStatus("Connected ..."); - if (ftp.cd((string)mDirectoryText)) - { // cd to the desired directory + + if (ftp.ChangeDir((string)fDirectoryText)) { + // cd to the desired directory UpdateFtpStatus("Transmitting ..."); - if (ftp.putFile((string)filename, (string)"temp")) // send the file to the server - { + + if (ftp.PutFile((string)filename, (string)"temp")) { + // send the file to the server UpdateFtpStatus("Renaming ..."); - if (ftp.moveFile((string)"temp",(string)filename)) // change to the desired name - { + + if (ftp.MoveFile((string)"temp", (string)filename)) { + // change to the desired name uint32 time = real_time_clock(); char s[80]; - strcpy(s,"Last Capture: "); - strcat(s,ctime((const long *)&time)); - s[strlen(s)-1] = 0; + strcpy(s, "Last Capture: "); + strcat(s, ctime((const long*)&time)); + s[strlen(s) - 1] = 0; UpdateFtpStatus(s); return B_OK; - } else UpdateFtpStatus("Rename failed"); - } else UpdateFtpStatus("File transmission failed"); - } else UpdateFtpStatus("Couldn't find requested directory on server"); - } else UpdateFtpStatus("Server login failed"); + } + else + UpdateFtpStatus("Rename failed"); + } + else + UpdateFtpStatus("File transmission failed"); + } + else + UpdateFtpStatus("Couldn't find requested directory on server"); + } + else + UpdateFtpStatus("Server login failed"); + return B_ERROR; } -//--------------------------------------------------------------- status_t -SetFileType(BFile * file, int32 translator, uint32 type) +SetFileType(BFile* file, int32 translator, uint32 type) { - translation_format * formats; - int32 count; - - status_t err = BTranslatorRoster::Default()->GetOutputFormats(translator, (const translation_format **) &formats, &count); - if (err < B_OK) return err; - const char * mime = NULL; - for (int ix=0; ixGetOutputFormats(translator, + (const translation_format **)&formats, &count); + if (err < B_OK) + return err; -//--------------------------------------------------------------- + const char* mime = NULL; + for (int ix = 0; ix < count; ix++) { + if (formats[ix].type == type) { + mime = formats[ix].MIME; + break; + } + } + if (mime == NULL) { + /* this should not happen, but being defensive might be prudent */ + return B_ERROR; + } + /* use BNodeInfo to set the file type */ + BNodeInfo ninfo(file); + return ninfo.SetType(mime); +} diff --git a/src/apps/codycam/VideoConsumer.h b/src/apps/codycam/VideoConsumer.h index faa2270427..d434f1a540 100644 --- a/src/apps/codycam/VideoConsumer.h +++ b/src/apps/codycam/VideoConsumer.h @@ -1,176 +1,148 @@ // Copyright (c) 1998-99, Be Incorporated, All Rights Reserved. // SMS /* VideoConsumer.h */ +#ifndef VIDEO_CONSUMER_H +#define VIDEO_CONSUMER_H -#if !defined(VID_CONSUMER_H) -#define VID_CONSUMER_H -#include #include -#include -#include -#include #include -#include #include +#include +#include +#include +#include +#include -typedef struct -{ - port_id port; - bigtime_t rate; - uint32 imageFormat; - int32 translator; - bool passiveFtp; - char fileNameText[64]; - char serverText[64]; - char loginText[64]; - char passwordText[64]; - char directoryText[64]; + +typedef struct { + port_id port; + bigtime_t rate; + uint32 imageFormat; + int32 translator; + bool passiveFtp; + char fileNameText[64]; + char serverText[64]; + char loginText[64]; + char passwordText[64]; + char directoryText[64]; } ftp_msg_info; -#define FTP_INFO 0x60000001 +#define FTP_INFO 0x60000001 -class VideoConsumer : - public BMediaEventLooper, - public BBufferConsumer -{ -public: - VideoConsumer( - const char * name, - BView * view, - BStringView * statusLine, - BMediaAddOn *addon, - const uint32 internal_id); - ~VideoConsumer(); - -/* BMediaNode */ -public: - - virtual BMediaAddOn *AddOn(long *cookie) const; - -protected: +class BStringView; - virtual void Start(bigtime_t performance_time); - virtual void Stop(bigtime_t performance_time, bool immediate); - virtual void Seek(bigtime_t media_time, bigtime_t performance_time); - virtual void TimeWarp(bigtime_t at_real_time, bigtime_t to_performance_time); - virtual void NodeRegistered(); - virtual status_t RequestCompleted( - const media_request_info & info); + +class VideoConsumer : public BMediaEventLooper, public BBufferConsumer { + public: + VideoConsumer(const char* name, BView* view, BStringView* statusLine, + BMediaAddOn *addon, const uint32 internalId); + ~VideoConsumer(); + + /* BMediaNode */ + public: + virtual BMediaAddOn* AddOn(long* cookie) const; + + protected: + virtual void Start(bigtime_t performanceTime); + virtual void Stop(bigtime_t performanceTime, bool immediate); + virtual void Seek(bigtime_t mediaTime, bigtime_t performanceTime); + virtual void TimeWarp(bigtime_t atRealTime, + bigtime_t toPerformanceTime); + + virtual void NodeRegistered(); + virtual status_t RequestCompleted(const media_request_info& info); + + virtual status_t HandleMessage(int32 message, const void* data, + size_t size); + + virtual status_t DeleteHook(BMediaNode* node); + + /* BMediaEventLooper */ + protected: + virtual void HandleEvent(const media_timed_event* event, + bigtime_t lateness, bool realTimeEvent); + + /* BBufferConsumer */ + public: + virtual status_t AcceptFormat(const media_destination& dest, + media_format* format); + + virtual status_t GetNextInput(int32* cookie, media_input* outInput); + + virtual void DisposeInputCookie(int32 cookie); + + protected: + virtual void BufferReceived(BBuffer* buffer); + + private: + virtual void ProducerDataStatus(const media_destination &forWhom, + int32 status, bigtime_t atMediaTime); + + virtual status_t GetLatencyFor(const media_destination& forWhom, + bigtime_t* outLatency, media_node_id* outId); + + virtual status_t Connected(const media_source& producer, + const media_destination& where, const media_format& withFormat, + media_input* outInput); + + virtual void Disconnected(const media_source& producer, + const media_destination& where); + + virtual status_t FormatChanged(const media_source& producer, + const media_destination& consumer, int32 fromChangeCount, + const media_format& format); + + /* implementation */ + + public: + status_t CreateBuffers(const media_format& withFormat); + + void DeleteBuffers(); + + static status_t FtpRun(void* data); + + void FtpThread(); - virtual status_t HandleMessage( - int32 message, - const void * data, - size_t size); + void UpdateFtpStatus(char* status); - virtual status_t DeleteHook(BMediaNode * node); + status_t LocalSave(char* filename, BBitmap* bitmap); -/* BMediaEventLooper */ -protected: - virtual void HandleEvent( - const media_timed_event *event, - bigtime_t lateness, - bool realTimeEvent); -/* BBufferConsumer */ -public: - - virtual status_t AcceptFormat( - const media_destination &dest, - media_format * format); - virtual status_t GetNextInput( - int32 * cookie, - media_input * out_input); - - virtual void DisposeInputCookie( - int32 cookie); - -protected: + status_t FtpSave(char* filename); - virtual void BufferReceived( - BBuffer * buffer); - -private: + private: + BStringView* fStatusLine; + uint32 fInternalID; + BMediaAddOn* fAddOn; - virtual void ProducerDataStatus( - const media_destination &for_whom, - int32 status, - bigtime_t at_media_time); - virtual status_t GetLatencyFor( - const media_destination &for_whom, - bigtime_t * out_latency, - media_node_id * out_id); - virtual status_t Connected( - const media_source &producer, - const media_destination &where, - const media_format & with_format, - media_input * out_input); - virtual void Disconnected( - const media_source &producer, - const media_destination &where); - virtual status_t FormatChanged( - const media_source & producer, - const media_destination & consumer, - int32 from_change_count, - const media_format & format); - -/* implementation */ + thread_id fFtpThread; -public: - status_t CreateBuffers( - const media_format & with_format); - - void DeleteBuffers(); - - static status_t FtpRun( - void *data); - - void FtpThread( - void); - - void UpdateFtpStatus( - char *status); - - status_t LocalSave( - char *filename, - BBitmap *bitmap); + bool fConnectionActive; + media_input fIn; + media_destination fDestination; + bigtime_t fMyLatency; - status_t FtpSave( - char *filename); + BWindow* fWindow; + BView* fView; + BBitmap* fBitmap[3]; + bool fOurBuffers; + BBufferGroup* fBuffers; + uint32 fBufferMap[3]; -private: + BBitmap* fFtpBitmap; + volatile bool fTimeToFtp; + volatile bool fFtpComplete; - BStringView * mStatusLine; - uint32 mInternalID; - BMediaAddOn *mAddOn; - - thread_id mFtpThread; - - bool mConnectionActive; - media_input mIn; - media_destination mDestination; - bigtime_t mMyLatency; - - BWindow *mWindow; - BView *mView; - BBitmap *mBitmap[3]; - bool mOurBuffers; - BBufferGroup *mBuffers; - uint32 mBufferMap[3]; - - BBitmap *mFtpBitmap; - volatile bool mTimeToFtp; - volatile bool mFtpComplete; - - bigtime_t mRate; - uint32 mImageFormat; - int32 mTranslator; - bool mPassiveFtp; - char mFileNameText[64]; - char mServerText[64]; - char mLoginText[64]; - char mPasswordText[64]; - char mDirectoryText[64]; + bigtime_t fRate; + uint32 fImageFormat; + int32 fTranslator; + bool fPassiveFtp; + char fFileNameText[64]; + char fServerText[64]; + char fLoginText[64]; + char fPasswordText[64]; + char fDirectoryText[64]; }; -#endif +#endif // VIDEO_CONSUMER_H