void Webserver::SendJsonResponse(const char* command) { Network *net = reprap.GetNetwork(); RequestState *req = net->GetRequest(NULL); bool keepOpen = false; bool mayKeepOpen; if (numQualKeys == 0) { mayKeepOpen = GetJsonResponse(command, "", "", 0); } else { mayKeepOpen = GetJsonResponse(command, qualifiers[0].key, qualifiers[0].value, qualifiers[1].key - qualifiers[0].value - 1); } if (mayKeepOpen) { // Check that the browser wants to persist the connection too for (size_t i = 0; i < numHeaderKeys; ++i) { if (StringEquals(headers[i].key, "Connection")) { // Comment out the following line to disable persistent connections keepOpen = StringEquals(headers[i].value, "keep-alive"); break; } } } req->Write("HTTP/1.1 200 OK\n"); req->Write("Content-Type: application/json\n"); req->Printf("Content-Length: %u\n", strlen(jsonResponse)); req->Printf("Connection: %s\n\n", keepOpen ? "keep-alive" : "close"); req->Write(jsonResponse); net->SendAndClose(NULL, keepOpen); }
//------------------------------------------------------------------------------------- DXUT_OBJECT CDXUTEffectMap::StringToObject( const char* cstrObject ) { char strObject[MAX_PATH+1] = {0}; RemoveTrailingNumber( strObject, MAX_PATH, cstrObject ); if( StringEquals( strObject, "Geometry" ) ) return DXUT_Geometry; if( StringEquals( strObject, "Light" ) ) return DXUT_Light; if( StringEquals( strObject, "Camera" ) ) return DXUT_Camera; if( StringEquals( strObject, "Frame" ) ) return DXUT_Frame; return DXUT_UNKNOWN_OBJECT; }
inline bool PathIsAbsolute(const std::basic_string<Char>& path) { bool r = false; if(path.length() >= 3) { std::basic_string<Char> sSearch = path.substr(1, 2); if(StringEquals(sSearch, ":/") || StringEquals(sSearch, ":\\")) { r = true; } } return r; }
void ProcessDelete(Arg& a, Version::VersionResource& res) { cout << "Deleting \"" << a.name << "\"..."; int occurrences = 0; // enumerate StringFileInfo (really should only be 1 of these) for(list<Version::StringFileInfo>::iterator itSFI = res.stringFileInfo.begin(); itSFI != res.stringFileInfo.end(); ++ itSFI) { // enumerate string tables for(list<Version::StringTable>::iterator itST = itSFI->items.begin(); itST != itSFI->items.end(); ++ itST) { // enumerate strings for(list<Version::String>::iterator itS = itST->items.begin(); itS != itST->items.end();) { // make sure we don't invalidate this iterator. list<Version::String>::iterator itTemp = itS; ++ itS;// now this is safe. if(StringEquals(itTemp->hdr.key, LibCC::ToUTF16(a.name))) { itST->items.erase(itTemp); occurrences ++; } } } } cout << "Done (" << occurrences << " occurrences deleted)." << endl; }
//---------------------------------------------------------------------------------------------------- // Return the value of the specified key, or nullptr if not present const char* Webserver::GetKeyValue(const char *key) const { for (size_t i = 0; i < numQualKeys; ++i) { if (StringEquals(qualifiers[i].key, key)) { return qualifiers[i].value; } } return nullptr; }
Result ProcessString(Arg& a, Version::VersionResource& res) { cout << "Setting string \"" << a.name << "\"..."; int occurrences = 0; // enumerate StringFileInfo (really should only be 1 of these) for(list<Version::StringFileInfo>::iterator itSFI = res.stringFileInfo.begin(); itSFI != res.stringFileInfo.end(); ++ itSFI) { // enumerate string tables for(list<Version::StringTable>::iterator itST = itSFI->items.begin(); itST != itSFI->items.end(); ++ itST) { // enumerate strings for(list<Version::String>::iterator itS = itST->items.begin(); itS != itST->items.end(); ++ itS) { Version::String& s = *itS; if(StringEquals(s.hdr.key, LibCC::ToUTF16(a.name))) { StringConvert(s.value, a.value); occurrences ++; } } } } if(occurrences) { cout << "Done (" << occurrences << " occurrences replaced)." << endl; } else { // make sure there's a string table to place it. if(!res.stringFileInfo.size()) { cout << endl; return Result::Failure("Error: No string file info block is in the version resource, so I can't add a new string to it.");; } if(!res.stringFileInfo.front().items.size()) { cout << endl; return Result::Failure("Error: No string tables were in the version resource, so I can't add a new string to it.");; } Version::StringTable& st = res.stringFileInfo.front().items.front(); Version::String s; StringConvert(s.value, a.value); StringConvert(s.hdr.key, a.name); s.hdr.type = 1; st.items.push_back(s); cout << "Done (1 new string added)." << endl; } return Result::Success(); }
fresult MedChooseTorsoWoundForm::OnMenu( IMenuItem* mi, bool_t* handled ) { fresult fres; _currentTarget = mwtUnknownTarget; char* hitTargetName; //search menu handler char* miName = mi->GetName(); MenuFactory* mf = _Factories->GetMenuFactory(); FAILIF(mf==NULL); MenuItemSettings* mis = mf->Settings; bool_t found = FALSE; for(ubyte_t i=0; i<MenuItemOriginsLast;i++) { if (StringEquals(miName, mis[i].Name) == TRUE) { switch (i) { case ItemOriginB: _currentTarget = mwtUpTorso; hitTargetName = "Травма верх корпуса"; found = TRUE; break; case ItemOriginY: _currentTarget = mwtUpTorso; hitTargetName = "Травма низа корпуса"; found = TRUE; break; default: found = FALSE; } break; } } if (found != TRUE) { return GENERAL_ERROR; } char* woundDescription = NULL; woundDescription = _App->Logic->MedLogic->GetWoundTargetText(_currentTarget); fres = _App->ShowYNDialogEx(NEW_WOUND_DIALOG_NAME, _TitleText, "добавить\nпроблему", hitTargetName, woundDescription, "добавить проблему"); ENSURESUCCESS(fres); *handled = TRUE; return SUCCESS; }
fresult MedChooseWoundForm::OnAfterDialogShown( IForm* prevFrom, char* dialogName, FormShowResults results, bool* needRedraw ) { fresult fres; if (StringEquals(NEW_WOUND_DIALOG_NAME, dialogName)) { if (results == fsrOK) { fres = _App->Logic->MedLogic->AddNewWound(_currentTarget); ENSURESUCCESS(fres); } } return SUCCESS; }
fresult NewWoundForm::OnAfterShow( IForm* prevFrom, bool_t reActivation, FormShowResults results ) { fresult fres; if (reActivation == TRUE) { //handle msgbox to confirm knockout! if (prevFrom !=NULL) { if(StringEquals(prevFrom->GetName(), _App->Forms->MsgBoxFormName)) { MsgBoxForm* msgBoxForm = (MsgBoxForm*)prevFrom; MessageBoxContent* msgBoxData = msgBoxForm->GetLastYesNoDialog(); if (msgBoxData !=NULL) { if (StringEquals(msgBoxData->title, WOUND_CHECK_TITLE)) { if (results == fsrOK) { //Now it's a target! char* text = _App->Logic->OnNewWound(_target); fres = _txtWoundText->AppendText(text); ENSURESUCCESS(fres); fres = _txtWoundText->Draw(); ENSURESUCCESS(fres); _woundSelected = TRUE; } } } } } } return SUCCESS; }
//------------------------------------------------------------------------------------- DXUT_SEMANTIC CDXUTEffectMap::StringToSemantic( const char* cstrSemantic ) { char strSemantic[MAX_PATH+1] = {0}; RemoveTrailingNumber( strSemantic, MAX_PATH, cstrSemantic ); if( StringEquals( strSemantic, "Diffuse" ) ) return DXUT_Diffuse; if( StringEquals( strSemantic, "Specular" ) ) return DXUT_Specular; if( StringEquals( strSemantic, "Ambient" ) ) return DXUT_Ambient; if( StringEquals( strSemantic, "SpecularPower" ) ) return DXUT_SpecularPower; if( StringEquals( strSemantic, "Emissive" ) ) return DXUT_Emissive; if( StringEquals( strSemantic, "Normal" ) ) return DXUT_Normal; if( StringEquals( strSemantic, "Height" ) ) return DXUT_Height; if( StringEquals( strSemantic, "Refraction" ) ) return DXUT_Refraction; if( StringEquals( strSemantic, "Opacity" ) ) return DXUT_Opacity; if( StringEquals( strSemantic, "Environment" ) ) return DXUT_Environment; if( StringEquals( strSemantic, "EnvironmentNormal" ) ) return DXUT_EnvironmentNormal; if( StringEquals( strSemantic, "Fresnel" ) ) return DXUT_Fresnel; if( StringEquals( strSemantic, "World" ) ) return DXUT_World; if( StringEquals( strSemantic, "WorldInverse" ) ) return DXUT_WorldInverse; if( StringEquals( strSemantic, "WorldInverseTranspose" ) ) return DXUT_WorldInverseTranspose; if( StringEquals( strSemantic, "WorldView" ) ) return DXUT_WorldView; if( StringEquals( strSemantic, "WorldViewInverse" ) ) return DXUT_WorldViewInverse; if( StringEquals( strSemantic, "WorldViewInverseTranspose" ) ) return DXUT_WorldViewInverseTranspose; if( StringEquals( strSemantic, "WorldViewProjection" ) ) return DXUT_WorldViewProjection; if( StringEquals( strSemantic, "WorldViewProjectionInverse" ) ) return DXUT_WorldViewProjectionInverse; if( StringEquals( strSemantic, "WorldViewProjectionInverseTranspose" ) ) return DXUT_WorldViewProjectionInverseTranspose; if( StringEquals( strSemantic, "View" ) ) return DXUT_View; if( StringEquals( strSemantic, "ViewInverse" ) ) return DXUT_ViewInverse; if( StringEquals( strSemantic, "ViewInverseTranspose" ) ) return DXUT_ViewInverseTranspose; if( StringEquals( strSemantic, "ViewProjection" ) ) return DXUT_ViewProjection; if( StringEquals( strSemantic, "ViewProjectionInverse" ) ) return DXUT_ViewProjectionInverse; if( StringEquals( strSemantic, "ViewProjectionInverseTranspose" ) ) return DXUT_ViewProjectionInverseTranspose; if( StringEquals( strSemantic, "Projection" ) ) return DXUT_Projection; if( StringEquals( strSemantic, "ProjectionInverse" ) ) return DXUT_ProjectionInverse; if( StringEquals( strSemantic, "ProjectionInverseTranspose" ) ) return DXUT_ProjectionInverseTranspose; if( StringEquals( strSemantic, "RenderTargetDimensions" ) ) return DXUT_RenderTargetDimensions; if( StringEquals( strSemantic, "RenderTargetClipping" ) ) return DXUT_RenderTargetClipping; if( StringEquals( strSemantic, "Time" ) ) return DXUT_Time; if( StringEquals( strSemantic, "LastTime" ) ) return DXUT_LastTime; if( StringEquals( strSemantic, "ElapsedTime" ) ) return DXUT_ElapsedTime; if( StringEquals( strSemantic, "Position" ) ) return DXUT_Position; if( StringEquals( strSemantic, "Direction" ) ) return DXUT_Direction; if( StringEquals( strSemantic, "BoundingCenter" ) ) return DXUT_BoundingCenter; if( StringEquals( strSemantic, "BoundingSphereSize" ) ) return DXUT_BoundingSphereSize; if( StringEquals( strSemantic, "BoundingSphereMin" ) ) return DXUT_BoundingSphereMin; if( StringEquals( strSemantic, "BoundingSphereMax" ) ) return DXUT_BoundingSphereMax; if( StringEquals( strSemantic, "BoundingBoxSize" ) ) return DXUT_BoundingBoxSize; if( StringEquals( strSemantic, "BoundingBoxMin" ) ) return DXUT_BoundingBoxMin; if( StringEquals( strSemantic, "BoundingBoxMax" ) ) return DXUT_BoundingBoxMax; if( StringEquals( strSemantic, "Attenuation" ) ) return DXUT_Attenuation; if( StringEquals( strSemantic, "RenderColorTarget" ) ) return DXUT_RenderColorTarget; if( StringEquals( strSemantic, "RenderDepthStencilTarget" ) ) return DXUT_RenderDepthStencilTarget; if( StringEquals( strSemantic, "UnitsScale" ) ) return DXUT_UnitsScale; if( StringEquals( strSemantic, "StandardsGlobal" ) ) return DXUT_StandardsGlobal; return DXUT_UNKNOWN_SEMANTIC; }
bool RepRap::CheckPassword(const char *pw) const { return StringEquals(pw, password); }
// Process the first fragment of input from the client. // Return true if the session should be kept open. bool Webserver::ProcessFirstFragment(HttpSession& session, const char* command, bool isOnlyFragment) { // Process connect messages first if (StringEquals(command, "connect") && GetKeyValue("password") != nullptr) { OutputBuffer *response; if (OutputBuffer::Allocate(response)) { if (session.isAuthenticated || reprap.CheckPassword(GetKeyValue("password"))) { // Password is OK, see if we can update the current RTC date and time const char *timeVal = GetKeyValue("time"); if (timeVal != nullptr && !platform->IsDateTimeSet()) { struct tm timeInfo; memset(&timeInfo, 0, sizeof(timeInfo)); if (strptime(timeVal, "%Y-%m-%dT%H:%M:%S", &timeInfo) != nullptr) { time_t newTime = mktime(&timeInfo); platform->SetDateTime(newTime); } } // Client has logged in session.isAuthenticated = true; response->printf("{\"err\":0,\"sessionTimeout\":%u,\"boardType\":\"%s\"}", httpSessionTimeout, platform->GetBoardString()); } else { // Wrong password response->copy("{\"err\":1}"); } network->SendReply(session.ip, 200 | rcJson, response); } else { // If we failed to allocate an output buffer, send back an error string network->SendReply(session.ip, 200 | rcJson, "{\"err\":2}"); } return false; } if (StringEquals(command, "disconnect")) { network->SendReply(session.ip, 200 | rcJson, "{\"err\":0}"); DeleteSession(session.ip); return false; } // Try to authorise the user automatically to retain compatibility with the old web interface if (!session.isAuthenticated && reprap.NoPasswordSet()) { session.isAuthenticated = true; } // If the client is still not authenticated, stop here if (!session.isAuthenticated) { network->SendReply(session.ip, 500, "Not authorized"); return false; } if (StringEquals(command, "reply")) { SendGCodeReply(session); return false; } // rr_configfile sends the config as plain text well if (StringEquals(command, "configfile")) { const char *configPath = platform->GetMassStorage()->CombineName(platform->GetSysDir(), platform->GetConfigFile()); char fileName[FILENAME_LENGTH]; strncpy(fileName, configPath, FILENAME_LENGTH); SendFile(fileName, session); return false; } if (StringEquals(command, "download") && GetKeyValue("name") != nullptr) { SendFile(GetKeyValue("name"), session); return false; } if (StringEquals(command, "upload")) { const char* nameVal = GetKeyValue("name"); const char* lengthVal = GetKeyValue("length"); const char* timeVal = GetKeyValue("time"); if (nameVal != nullptr && lengthVal != nullptr) { // Try to obtain the last modified time time_t fileLastModified = 0; struct tm timeInfo; memset(&timeInfo, 0, sizeof(timeInfo)); if (timeVal != nullptr && strptime(timeVal, "%Y-%m-%dT%H:%M:%S", &timeInfo) != nullptr) { fileLastModified = mktime(&timeInfo); } // Deal with file upload request uint32_t fileLength = atol(lengthVal); StartUpload(session, nameVal, fileLength, fileLastModified); if (session.uploadState == uploading) { if (isOnlyFragment) { FinishUpload(session); return false; } else { network->DiscardMessage(); // no reply needed yet return true; // expecting more data } } } network->SendReply(session.ip, 200 | rcJson, "{\"err\":1}"); // TODO return the cause of the error return false; } if (StringEquals(command, "move")) { const char* response = "{\"err\":1}"; // assume failure const char* const oldVal = GetKeyValue("old"); const char* const newVal = GetKeyValue("new"); if (oldVal != nullptr && newVal != nullptr) { const bool success = platform->GetMassStorage()->Rename(oldVal, newVal); if (success) { response = "{\"err\":0}"; } } network->SendReply(session.ip, 200 | rcJson, response); return false; } if (StringEquals(command, "mkdir")) { const char* response = "{\"err\":1}"; // assume failure const char* dirVal = GetKeyValue("dir"); if (dirVal != nullptr) { bool ok = (platform->GetMassStorage()->MakeDirectory(dirVal)); if (ok) { response = "{\"err\":0}"; } } network->SendReply(session.ip, 200 | rcJson, response); return false; } if (StringEquals(command, "delete")) { const char* response = "{\"err\":1}"; // assume failure const char* nameVal = GetKeyValue("name"); if (nameVal != nullptr) { bool ok = platform->GetMassStorage()->Delete("0:/", nameVal); if (ok) { response = "{\"err\":0}"; } } network->SendReply(session.ip, 200 | rcJson, response); return false; } // The remaining commands use an OutputBuffer for the response OutputBuffer *response = nullptr; if (StringEquals(command, "status")) { const char* typeVal = GetKeyValue("type"); if (typeVal != nullptr) { // New-style JSON status responses int type = atoi(typeVal); if (type < 1 || type > 3) { type = 1; } response = reprap.GetStatusResponse(type, ResponseSource::HTTP); } else { response = reprap.GetLegacyStatusResponse(1, 0); } } else if (StringEquals(command, "gcode")) { const char* gcodeVal = GetKeyValue("gcode"); if (gcodeVal != nullptr) { RegularGCodeInput * const httpInput = reprap.GetGCodes()->GetHTTPInput(); httpInput->Put(HTTP_MESSAGE, gcodeVal); if (OutputBuffer::Allocate(response)) { response->printf("{\"buff\":%u}", httpInput->BufferSpaceLeft()); } } else { network->SendReply(session.ip, 200 | rcJson, "{\"err\":1}"); return false; } } else if (StringEquals(command, "filelist") && GetKeyValue("dir") != nullptr) { response = reprap.GetFilelistResponse(GetKeyValue("dir")); } else if (StringEquals(command, "files")) { const char* dir = GetKeyValue("dir"); if (dir == nullptr) { dir = platform->GetGCodeDir(); } const char* const flagDirsVal = GetKeyValue("flagDirs"); const bool flagDirs = flagDirsVal != nullptr && atoi(flagDirsVal) == 1; response = reprap.GetFilesResponse(dir, flagDirs); } else if (StringEquals(command, "fileinfo")) { const char* const nameVal = GetKeyValue("name"); if (reprap.GetPrintMonitor()->GetFileInfoResponse(nameVal, response)) { processingDeferredRequest = false; } else { processingDeferredRequest = true; } } else if (StringEquals(command, "config")) { response = reprap.GetConfigResponse(); } else { platform->MessageF(HOST_MESSAGE, "KnockOut request: %s not recognised\n", command); network->SendReply(session.ip, 400, "Unknown rr_ command"); return false; } if (response != nullptr) { network->SendReply(session.ip, 200 | rcJson, response); } else if (!processingDeferredRequest) { network->SendReply(session.ip, 500, "No buffer available"); } return processingDeferredRequest; }
// Get the Json response for this command. // 'value' is null-terminated, but we also pass its length in case it contains embedded nulls, which matter when uploading files. bool Webserver::GetJsonResponse(const char* request, const char* key, const char* value, size_t valueLength) { bool found = true; // assume success bool keepOpen = false; // assume we don't want to persist the connection if (StringEquals(request, "status")) // new style status request { GetStatusResponse(1); } else if (StringEquals(request, "poll")) // old style status request { GetStatusResponse(0); } else if (StringEquals(request, "gcode") && StringEquals(key, "gcode")) { LoadGcodeBuffer(value); snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"buff\":%u}", GetReportedGcodeBufferSpace()); } else if (StringEquals(request, "upload_begin") && StringEquals(key, "name")) { CancelUpload(); FileStore *f = platform->GetFileStore("0:/", value, true); if (f != NULL) { fileBeingUploaded.Set(f); uploadState = uploadOK; } else { uploadState = uploadError; } GetJsonUploadResponse(); } else if (StringEquals(request, "upload_data") && StringEquals(key, "data")) { if (uploadState == uploadOK) { uploadPointer = value; uploadLength = valueLength; } GetJsonUploadResponse(); keepOpen = true; } else if (StringEquals(request, "upload_end") && StringEquals(key, "size")) { // Write the remaining data if (uploadLength != 0) { if (!fileBeingUploaded.Write(uploadPointer, uploadLength)) { uploadState = uploadError; } } uploadPointer = NULL; uploadLength = 0; if (uploadState == uploadOK && !fileBeingUploaded.Flush()) { uploadState = uploadError; } // Check the file length is as expected if (uploadState == uploadOK && fileBeingUploaded.Length() != strtoul(value, NULL, 10)) { uploadState = uploadError; } // Close the file if (!fileBeingUploaded.Close()) { uploadState = uploadError; } GetJsonUploadResponse(); if (uploadState != uploadOK && strlen(filenameBeingUploaded) != 0) { platform->GetMassStorage()->Delete("0:/", filenameBeingUploaded); } filenameBeingUploaded[0] = 0; } else if (StringEquals(request, "upload_cancel")) { CancelUpload(); snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"err\":%d}", 0); } else if (StringEquals(request, "delete") && StringEquals(key, "name")) { bool ok = platform->GetMassStorage()->Delete("0:/", value); snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"err\":%d}", (ok) ? 0 : 1); } else if (StringEquals(request, "files")) { const char* dir = (StringEquals(key, "dir")) ? value : platform->GetGCodeDir(); const char* fileList = platform->GetMassStorage()->FileList(dir, false); snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"files\":[%s]}", fileList); } else if (StringEquals(request, "fileinfo") && StringEquals(key, "name")) { unsigned long length; float height, filament, layerHeight; char generatedBy[50]; bool found = GetFileInfo(value, length, height, filament, layerHeight, generatedBy, ARRAY_SIZE(generatedBy)); if (found) { snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"err\":0,\"size\":%lu,\"height\":%.2f,\"filament\":%.1f,\"layerHeight\":%.2f,\"generatedBy\":\"%s\"}", length, height, filament, layerHeight, generatedBy); } else { snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"err\":1}"); } } else if (StringEquals(request, "name")) { snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"myName\":\""); size_t j = strlen(jsonResponse); for (size_t i = 0; i < ARRAY_SIZE(myName) - 1; ++i) { char c = myName[i]; if (c < ' ') // if null terminator or bad character break; if (c == '"' || c == '\\') { // Need to escape the quote-mark or backslash for JSON jsonResponse[j++] = '\\'; } jsonResponse[j++] = c; } jsonResponse[j++] = '"'; jsonResponse[j++] = '}'; jsonResponse[j] = 0; } else if (StringEquals(request, "password") && StringEquals(key, "password")) { CheckPassword(value); snprintf(jsonResponse, ARRAY_UPB(jsonResponse), "{\"password\":\"%s\"}", (gotPassword) ? "right" : "wrong"); } else if (StringEquals(request, "axes")) { strncpy(jsonResponse, "{\"axes\":", ARRAY_UPB(jsonResponse)); char ch = '['; for (int8_t drive = 0; drive < AXES; drive++) { sncatf(jsonResponse, ARRAY_UPB(jsonResponse), "%c%.1f", ch, platform->AxisTotalLength(drive)); ch = ','; } strncat(jsonResponse, "]}", ARRAY_UPB(jsonResponse)); } else if (StringEquals(request, "connect")) { CancelUpload(); GetStatusResponse(1); } else { found = false; } JsonReport(found, request); return keepOpen; }
bool RepRap::NoPasswordSet() const { return (!password[0] || StringEquals(password, DEFAULT_PASSWORD)); }
fresult FormBase::DefaultMenuHandler( IMenuItem* mi ) { fresult fres; //exec virtual OnAnyMenu bool_t found = FALSE; fres = OnMenu(mi, &found); if (found == TRUE) { return fres; } //search menu handler char* miName = mi->GetName(); MenuFactory* mf = _Factories->GetMenuFactory(); FAILIF(mf==NULL); MenuItemSettings* mis = mf->Settings; //function pointer fresult (FormBase::*handler)(IMenuItem* mi); for(ubyte_t i=0; i<MenuItemOriginsLast;i++) { if (StringEquals(miName, mis[i].Name) == TRUE) { switch (i) { case ItemOriginA: handler = &FormBase::OnMenuA; break; case ItemOriginB: handler = &FormBase::OnMenuB; break; case ItemOriginC: handler = &FormBase::OnMenuC; break; case ItemOriginX: handler = &FormBase::OnMenuX; break; case ItemOriginY: handler = &FormBase::OnMenuY; break; case ItemOriginZ: handler = &FormBase::OnMenuZ; break; case ItemOriginL: handler = &FormBase::OnMenuL; break; case ItemOriginE: handler = &FormBase::OnMenuE; break; case ItemOriginR: handler = &FormBase::OnMenuR; break; default: return GENERAL_ERROR; } found = TRUE; break; } } if (found==TRUE) { //Call found handler fres = (this->*handler)(mi); ENSURESUCCESS(fres); } else { //call default fres = OnMenuOther(mi); ENSURESUCCESS(fres); } return SUCCESS; }
void Webserver::CheckPassword(const char *pw) { gotPassword = StringEquals(pw, password); }
// Start sending a file or a JSON response. void Webserver::SendFile(const char* nameOfFileToSend) { if (StringEquals(nameOfFileToSend, "/")) { nameOfFileToSend = INDEX_PAGE; } FileStore *fileToSend = platform->GetFileStore(platform->GetWebDir(), nameOfFileToSend, false); if (fileToSend == NULL) { nameOfFileToSend = FOUR04_FILE; fileToSend = platform->GetFileStore(platform->GetWebDir(), nameOfFileToSend, false); if (fileToSend == NULL) { RejectMessage("not found", 404); return; } } Network *net = reprap.GetNetwork(); RequestState *req = net->GetRequest(NULL); req->Write("HTTP/1.1 200 OK\n"); const char* contentType; bool zip = false; if (StringEndsWith(nameOfFileToSend, ".png")) { contentType = "image/png"; } else if (StringEndsWith(nameOfFileToSend, ".ico")) { contentType = "image/x-icon"; } else if (StringEndsWith(nameOfFileToSend, ".js")) { contentType = "application/javascript"; } else if (StringEndsWith(nameOfFileToSend, ".css")) { contentType = "text/css"; } else if (StringEndsWith(nameOfFileToSend, ".htm") || StringEndsWith(nameOfFileToSend, ".html")) { contentType = "text/html"; } else if (StringEndsWith(nameOfFileToSend, ".zip")) { contentType = "application/zip"; zip = true; } else { contentType = "application/octet-stream"; } req->Printf("Content-Type: %s\n", contentType); if (zip && fileToSend != NULL) { req->Write("Content-Encoding: gzip\n"); req->Printf("Content-Length: %lu", fileToSend->Length()); } req->Write("Connection: close\n\n"); net->SendAndClose(fileToSend); }
fresult ItemsListFormBase::CreateMenu( IMenu** o_mnu ) { fresult fres; MenuFactory* mf = _Factories->GetMenuFactory(); //ready factory mf->CurrentInterlaced = true; mf->CurrentTextFormatHandle = TF_MENU; mf->CurrentEvenTextFormatHandle = TF_MENUEVEN; mf->ClearSettings(); //Set up menu MenuItemSettings* settings = mf->Settings; MenuItemSettings* mis; //ItemOriginX mis = &settings[ItemOriginX]; mis->ImgHandle = scroll_up; mis->Handler = _AutoDispatchMenuHandler; mis->Empty = FALSE; //ItemOriginZ mis = &settings[ItemOriginZ]; mis->ImgHandle = scroll_down; mis->Handler = _AutoDispatchMenuHandler; mis->Empty = FALSE; //ItemOriginL mis = &settings[ItemOriginL]; mis->ImgHandle = small_arrow_bottom; mis->Text = _prevText; mis->Handler = _AutoDispatchMenuHandler; mis->Empty = FALSE; //ItemOriginE mis = &settings[ItemOriginE]; mis->ImgHandle = small_arrow_bottom; mis->Text = "назад"; fres = _FormManager->GetCloseFormHandler(&mis->Handler, fsrCancel); ENSURESUCCESS(fres); mis->Empty = FALSE; //ItemOriginR mis = &settings[ItemOriginR]; mis->ImgHandle = small_arrow_bottom; mis->Text = _nextText; mis->Handler = _AutoDispatchMenuHandler; mis->Empty = FALSE; //call derived update settings UpdateMenuSettings(settings); //create mnu IMenu* mnu = NULL; fres = mf->GetMenu(ABCXYZLER, &mnu); ENSURESUCCESS(fres); for (ubyte_t i=0; i<mnu->GetItemsCount();i++) { MenuItem* mi = (MenuItem*)(mnu->GetItem(i)); if (StringEquals(mi->GetName(), "L") == TRUE) { _mnuBack = mi; } if (StringEquals(mi->GetName(), "R") == TRUE) { _mnuNext = mi; } } //Clean up mf->ClearSettings(); mf->DefaultInterlaced=mf->CurrentInterlaced; mf->DefaultTextFormatHandle=mf->CurrentTextFormatHandle; mf->DefaultEvenTextFormatHandle=mf->CurrentEvenTextFormatHandle; //Get menu Items *o_mnu = mnu; return SUCCESS; }
void Honor2Logic::OnLustraTimer() { //Query current lustraid ubyte_t currLustraId = ArmletApi::GetLustraId(); bool isOutLustra = IsOutLustraId(currLustraId); int currTime = ArmletApi::GetUpTime(); //char strBuff[40]; //ArmletApi::snprintf(strBuff, 40, "t:%d, r:%d", currTime,currLustraId); //AppendLog(LOG_EVENT, strBuff); if(currLustraId == UNKNOWN_ID) { if (_lastKnownLustraIdIsOut) { //zero room, all is ok SetRoom(0); } else { //check if we had a good room no longer that specified time if (currTime - _lastKnownDiscoveryTime > MAX_LUSTRA_WAIT_TIME) { //check not to show msg recursive IForm* frm = _App->GetFormManager()->GetCurrentForm(); bool_t needShowMsg = TRUE; char* title = "Потеря связи!"; if (frm!=NULL) { if (frm->GetName()==_App->Forms->MsgBoxFormName) { MsgBoxForm* msgBoxFrm = (MsgBoxForm*)frm; MessageBoxContent* msgBoxContent = NULL; msgBoxContent = msgBoxFrm->GetCurrentMessage(); if (msgBoxContent != NULL) { if (StringEquals(msgBoxContent->title, title)) { //suppress msg needShowMsg = FALSE; } } } } if ( (_lastLoggedTime ==-1) || (currTime - _lastLoggedTime > MAX_LUSTRA_WAIT_PERIOD) ) { _App->DoVibroAndBeep(); if (needShowMsg == TRUE) { ShowMessage(title, BlueExclamation, "Срочно покажи браслет системе безопасности отсека!", TRUE); } SetRoom(UNKNOWN_ID); _lastLoggedTime = currTime; } } } } else { //good lustra _lastLoggedTime = -1; _lastKnownDiscoveryTime = currTime; SetRoom(currLustraId); _lastKnownLustraId = currLustraId; _lastKnownRoomId = currLustraId; _lastKnownLustraIdIsOut = isOutLustra; } return; }
int main2(int argc, _TCHAR** argv) { CoInitialize(0); { //string file = "F:\\svn.screenie\\root\\bin-release\\screenie.exe"; g_hInstance = GetModuleHandle(0); argc --; argv ++; if(argc < 2) { return Usage(); } // get the filename string file = argv[0]; if(!PathFileExists(file.c_str())) { cout << "File not found: " << file << endl; return 1; } // parse the rest of the command line args argc --; argv ++; vector<Arg> args; Result res; for(int i = 0; i < argc; i ++) { string arg = argv[i]; if(StringEquals(arg, "/xml")) { i ++; if(i >= argc) { cout << "/string command line argument is missing its operand." << endl; return 1; } // this will convert the xml file into a list of arguments. VersionXMLFile f; if(!(res = f.Read(argv[i]))) { cout << res.str() << endl; return 1; } // merge the lists together. for(vector<Arg>::iterator it = f.args.begin(); it != f.args.end(); ++ it) { args.push_back(*it); } } else if(StringEquals(arg, "/string")) { i ++; if(i >= argc) { cout << "/string command line argument is missing its operand." << endl; return 1; } Arg temp; if(!(res = ParseNameValueString(argv[i], temp.name, temp.value))) { res.Prepend("/string command line argument invalid; "); cout << res.str() << endl; return 1; } temp.source = "/string command line argument"; temp.type = Arg::STRING; args.push_back(temp); } else if(StringEquals(arg, "/delete")) { i ++; if(i >= argc) { cout << "/delete command line argument is missing its operand." << endl; return 1; } Arg temp; temp.source = "/delete command line argument"; temp.type = Arg::DELETETYPE; temp.name = argv[i]; args.push_back(temp); } else if(StringEquals(arg, "/fixed")) { i ++; if(i >= argc) { cout << "/fixed command line argument is missing its operand." << endl; return 1; } Arg temp; if(!(res = ParseNameValueString(argv[i], temp.name, temp.value))) { res.Prepend("/fixed command line argument invalid; "); cout << res.str() << endl; return 1; } temp.source = "/fixed command line argument"; temp.type = Arg::FIXED; args.push_back(temp); } else { cout << "Unrecognized command line switch: " << arg << endl; return 1; } } // open version info. Version::VersionResource versionResource; if(!(res = LoadVersionResource(file, versionResource))) { res.Prepend(Format("Failed to read version info from %; ").qs(file).Str()); cout << res.str() << endl; return 1; } // process the arguments sequentially. for(vector<Arg>::iterator it = args.begin(); it != args.end(); ++ it) { Arg& a(*it); switch(a.type) { case Arg::FIXED: if(!(res = ProcessFixed(a, versionResource))) { cout << res.str() << endl; return 1; } break; case Arg::DELETETYPE: ProcessDelete(a, versionResource); break; case Arg::STRING: if(!(res = ProcessString(a, versionResource))) { cout << res.str() << endl; return 1; } break; } } // write it back out in memory BinaryMemory memFinal; if(!(res = versionResource.Write(memFinal))) { res.Prepend(Format("Failed to generate version info; ").Str()); cout << res.str() << endl; return 1; } // update the resource. HANDLE hResource = BeginUpdateResource(file.c_str(), FALSE); if(NULL == hResource) { cout << Format("Error updating resources for %. BeginUpdateResource returned %").qs(file).gle().Str() << endl; return 1; } if(0 == UpdateResource(hResource, RT_VERSION, MAKEINTRESOURCE(VS_VERSION_INFO), versionResource.GetLanguage(), (PVOID)/*const_cast*/memFinal.GetBuffer(), (DWORD)memFinal.GetSize())) { cout << Format("Error updating resources for %. UpdateResource returned %").qs(file).gle().Str() << endl; return 1; } if(0 == EndUpdateResource(hResource, FALSE)) { cout << Format("Error updating resources for %. EndUpdateResource returned %").qs(file).gle().Str() << endl; return 1; } cout << "Version updated successfully." << endl; } CoUninitialize(); return 0; }
bool StringEndsWith(const char* string, const char* ending) { int j = strlen(string); int k = strlen(ending); return k <= j && StringEquals(&string[j - k], ending); }