/* * Read the only string from one string resource. * Note: The parameter pos is used both for input and output * of the position in the resource data. * @param resID A valid resource id. * @param pos In: The start position. Out: The position * after the string in the resource. * @param output The resulting string. */ bool ScreenImageSwiper::readStringFromResource( MAHandle resID, int& pos, MAUtil::String& output) const { // Get all the characters on one read. // Get the length of the string stored as a .pstring // (Pascal string). The first byte contains the length. byte stringLen = 0; maReadData(resID, (void*) &stringLen, pos, sizeof(byte)); if (stringLen > maGetDataSize(resID) || stringLen <= 0) { return false; } // Read the string. pos += sizeof(byte); output.resize(stringLen); maReadData(resID, (void*) output.c_str(), pos, stringLen); // Update position to the byte after the string. pos += stringLen; return true; }
/** * Read data and initialise the stream. */ void MessageStream::initialize(MAHandle dataHandle) { mData = NULL; // We must have data. if (NULL == dataHandle) { return; } // Get length of the data, it is not zero terminated. int dataSize = maGetDataSize(dataHandle); // Allocate buffer for string data. char* data = (char*) malloc(dataSize + 1); // Get the data. maReadData(dataHandle, data, 0, dataSize); data[dataSize] = 0; // Check that we have the "ms:" prefix. if (data[0] != 'm') { return; } if (data[1] != 's') { return; } if (data[2] != ':') { return; } mData = data; mDataSize = dataSize; mStart = NULL; mEnd = NULL; }
/** * Inherited from HighLevelHttpConnection. * Called when the HTTP connection has finished * downloading data. * Calls onDownloadComplete. * @param data Handle to the data, will be * 0 on error, > 0 on success. * @param result Result code, RES_OK on success, * otherwise an HTTP error code. */ void HighLevelImageDownloader::dataDownloaded(MAHandle data, int result) { // The resulting image. MAHandle image = 0; // Do we have any data? if (data) { // Convert data to image. image = maCreatePlaceholder(); int res = maCreateImageFromData( image, data, 0, maGetDataSize(data)); // Do we have an error? if (RES_OUT_OF_MEMORY == res) { // The image could not be created, set data handle to zero. image = 0; } // Deallocate the data object, we are done with it. maDestroyPlaceholder(data); } // Notify download complete. onDownloadComplete(image); }
/** * Inherited from HighLevelHttpConnection. * Called when the HTTP connection has finished * downloading data. * Calls onDownloadComplete. * @param data Handle to the data, will be * 0 on error, > 0 on success. * @param result Result code, RES_OK on success, * otherwise an HTTP error code. */ void HighLevelTextDownloader::dataDownloaded(MAHandle data, int result) { // The resulting text. char* text = NULL; // Do we have any data? if (data) { // Copy data to string. int size = maGetDataSize(data); text = new char[size + 1]; if (text) { maReadData(data, text, 0, size); text[size] = '\0'; // Zero terminate string } // Deallocate the data object, we are done with it. maDestroyObject(data); } // Notify download complete. onDownloadComplete(text); // Delete myself! delete this; }
/** * Create a text string from a handle. */ MAUtil::String FileUtil::createTextFromHandle(MAHandle handle) { // Get size of data. int size = maGetDataSize(handle); // Allocate space for text plus zero termination character. char* tempText = (char*) malloc(size + 1); if (NULL == tempText) { return ""; } // Read text data from handle. maReadData(handle, tempText, 0, size); // Zero terminate string. tempText[size] = 0; // Create String object. MAUtil::String text = tempText; // Free temporary text. free(tempText); // Return text object. return text; }
void initFontReader(MAHandle file) { sData = new unsigned char[BUFFER_SIZE]; if(!sData) maPanic(0, "Not enough memory for initialization of MAUI::Font"); sFile = file; sFileSize = maGetDataSize(sFile); sBufPos = sFilePos = 0; readMoreData(); }
void CBHttpConnection::writeElement(int index) { CBHttpConnectionParameter param = this->parameters[index]; if (param.isFile) { theConnection.writeFromData(param.fileData, 0, maGetDataSize(param.fileData)); } else { theConnection.write(param.value.c_str(), param.value.length()); } }
static MA_FILE* openReadWrite(const char *filename, int modeFlags) { MA_FILE *file; char sfilename[1024]; MAHandle store; MAHandle data=0; int size = BUFFER_SIZE; int realLength = 0; filterStoreName(sfilename, 1024, filename); store = maOpenStore(sfilename, MAS_CREATE_IF_NECESSARY); if(!store) return NULL; file = (MA_FILE*) malloc(sizeof(MA_FILE)); if(modeFlags&(MODE_READ|MODE_WRITE)) file->type = TYPE_READWRITE; else file->type = TYPE_WRITEONLY; file->modeFlags = modeFlags; if(modeFlags&(MODE_READ|MODE_APPEND)) { data = maCreatePlaceholder(); maReadStore(store, data); realLength = size = maGetDataSize(data); } file->buffer = (unsigned char*) malloc(size); if(!file->buffer) { free(file->buffer); free(file); return NULL; } file->bufferStart = 0; file->bufferSize = size; file->volEntry = (VolumeEntry*) malloc(sizeof(VolumeEntry)); file->filePtr = 0; file->volEntry->dataOffset = 0; file->volEntry->dataLength = realLength; file->resultFlags = 0; if(modeFlags&(MODE_READ|MODE_APPEND)) { maReadData(data, file->buffer, 0, size); maDestroyObject(data); if(modeFlags&MODE_APPEND) { file->filePtr = size; } } file->store = store; file->volEntry->type=VOL_TYPE_FILE; return file; }
/* * Load the images from resources according to the screen resolution. * @param screenWidth The width of the screen. */ void ScreenImageSwiper::loadImages(int screenWidth) { // Set the image indexes inside the resources according to the resolution. int firstImage = RES_FIRST_IMAGE_LARGE; int lastImage = RES_LAST_IMAGE_LARGE; if (screenWidth <= SMALL_SCREEN_RESOLUTION) { firstImage = RES_FIRST_IMAGE_SMALL; lastImage = RES_LAST_IMAGE_SMALL; } else if (screenWidth <= MEDIUM_SCREEN_RESOLUTION) { firstImage = RES_FIRST_IMAGE_MEDIUM; lastImage = RES_LAST_IMAGE_MEDIUM; } // Compute the number of images. mImagesSize = lastImage - firstImage - 1; // Create the image widgets. for (int i = 0; i < mImagesSize; i++) { // Byte index in the resource data. int pos = 0; // Create an image object. mImages[i] = new ScreenImage(); // Get the resource id of the current image. int resID = firstImage + i + 1; // Create a placeholder to store the current image. mImages[i]->setHandle(maCreatePlaceholder()); // Load the image name from resources. MAUtil::String name; // This reads the string into name and updates // the value of pos to the start of the image data. readStringFromResource(resID, pos, name); // Set the image name. mImages[i]->setName(name); // Create the image from ubin. Note that pos is // updated by the call to readStringFromResource // to point at the start of the image data. maCreateImageFromData( mImages[i]->getHandle(), resID, pos, maGetDataSize(resID) - mImages[i]->getName().length() - 1); } }
// This method runs the same commands as the prepareParameters but returns the size of the request // to be set in the httpConnection header int CBHttpConnection::calculateRequestSize() { int bodySize = 0; for (int i = 0; i < this->parameters.size(); i++) { CBHttpConnectionParameter par = this->parameters[i]; if (par.isFile) bodySize += maGetDataSize(par.fileData); else bodySize += par.value.length(); } return bodySize; }
// each record has this format: { // char name[]; // null-terminated // byte data[]; // terminated by end of record. // } void setup_filesystem() { printf("setup_filesystem\n"); // first, we must find a temporary directory which we can work out of. // we'll probably want to chroot() to it, too. char newRoot[MAX_PATH] = ""; MAASSERT(makeDir(newRoot, 0, "mosync_root/", sizeof(newRoot))); int newRootLen = strlen(newRoot); MAASSERT(chdir(newRoot) == 0); MAASSERT(chroot(".") == 0); // now we have the root of a unix file-system. const MAHandle start = maFindLabel("start"); const MAHandle end = maFindLabel("end"); MAASSERT(start > 0 && end > 0); printf("%i files:\n", end - (start+1)); for(MAHandle i=start+1; i<end; i++) { char buf[MAX_PATH]; int size = maGetDataSize(i); int pathlen = MIN(MAX_PATH, size); maReadData(i, buf, 0, pathlen); const char* name = buf; int namelen = strlen(name); MAASSERT(namelen < MAX_PATH); int dataOffset = namelen+1; int dataLen = size - dataOffset; printf("%i: %s (%i bytes)\n", i, name, dataLen); bool isDirectory = name[namelen-1] == '/'; if(isDirectory) { // there can be no data in a directory. MAASSERT(dataLen == 0); MAASSERT(!mkdir(name, 0755)); } else { // Because we want to use maFileWriteFromData(), we can't use open() here. char realName[MAX_PATH]; MAHandle fh; bool res; memcpy(realName, newRoot, newRootLen); // overwrite the slash in newRoot, so we don't get double slashes. memcpy(realName + newRootLen - 1, name, namelen + 1); MAASSERT((fh = maFileOpen(realName, MA_ACCESS_READ_WRITE)) > 0); res = writeFile(fh, i, dataOffset, dataLen); MAASSERT(maFileClose(fh) >= 0); MAASSERT(res); } } }
char *Controller::readSource(const char *fileName) { char *buffer = NULL; bool networkFile = strstr(fileName, "://"); const char *delim = strchr(fileName, '?'); int len = strlen(fileName); int endIndex = delim ? (delim - fileName) : len; if (delim && !networkFile) { strcpy(opt_command, delim + 1); } _mainBas = false; trace("readSource %s %d %s", fileName, endIndex, opt_command); if (networkFile) { buffer = readConnection(fileName); } else if (strncasecmp("main.bas", fileName, endIndex) == 0) { // load as resource int len = maGetDataSize(MAIN_BAS); buffer = (char *)tmp_alloc(len + 1); maReadData(MAIN_BAS, buffer, 0, len); buffer[len] = '\0'; _mainBas = true; } else { // load from file system MAHandle handle = maFileOpen(fileName, MA_ACCESS_READ); if (maFileExists(handle)) { int len = maFileSize(handle); buffer = (char *)tmp_alloc(len + 1); maFileRead(handle, buffer, len); buffer[len] = '\0'; } maFileClose(handle); } if (buffer == NULL) { buffer = (char *)tmp_alloc(strlen(ERROR_BAS) + 1); strcpy(buffer, ERROR_BAS); } delete [] _programSrc; len = strlen(buffer); _programSrc = new char[len + 1]; strncpy(_programSrc, buffer, len); _programSrc[len] = 0; logPrint("Opened: %s %d bytes\n", fileName, len); return buffer; }
/** * \brief GetString, read whole textfile resource in to a string buffer * @param resource, to a text file. * @return char *, return the text buffer */ char* GetString(MAHandle resource) { // Get the length of the string data. int length = maGetDataSize(resource); // Allocate space for the string data plus the // null termination character. char* buffer = new char[length + 1]; // Read data. maReadData(resource, buffer, 0, length); // Null terminate the string. buffer[length] = '\0'; // Return the string. return buffer; }
/** * Write a data object to a file. * @return true on success, false on error. */ bool FileUtil::writeDataToFile( const MAUtil::String& filePath, MAHandle outData) { MAHandle file = openFileForWriting(filePath); if (file < 0) { return false; } int result = maFileWriteFromData( file, outData, 0, maGetDataSize(outData)); maFileClose(file); return result == 0; }
/** * Prints the incoming webview message. Used for debugging. * * To call this method, override HybridMoblet::handleWebViewMessage * in your moblet with the following method: * * void handleWebViewMessage(MAHandle webViewHandle, MAHandle data) * { * printWebViewMessage(data); * HybridMoblet::handleWebViewMessage(webViewHandle, data); * } */ void HybridMoblet::printWebViewMessage(MAHandle dataHandle) { // Get length of the data, it is not zero terminated. int dataSize = maGetDataSize(dataHandle); // Allocate buffer for string data. char* dataBuffer = (char*) malloc(dataSize + 1); // Get the data. maReadData(dataHandle, dataBuffer, 0, dataSize); // Zero terminate. dataBuffer[dataSize] = 0; // Print unparsed message data. maWriteLog("@@@ MOSYNC: WebViewMessage:", 27); maWriteLog(dataBuffer, dataSize); free(dataBuffer); }
void ImageCache::process(bool afterFin) { //Check to see if the cache can process this request at this time if(mIsBusy) return; //Check to see if there are any outstanding requests if(mRequests.size() == 0) return; //Set the mIsBusy flag, so we don't try to do too much at once mIsBusy = true; //Get the next image request from the queue mNextRequest = mRequests[0]; if(mHttp.isOpen()){ mHttp.close(); } if (mNextRequest->getType() == 5) { MAHandle store = maOpenStore((FILE_PREFIX+mNextRequest->getSaveName()).c_str(), 0); if(store != STERR_NONEXISTENT) { MAHandle cacheimage = maCreatePlaceholder(); maReadStore(store, cacheimage); maCloseStore(store, 0); if (maGetDataSize(cacheimage) > 0) { Util::returnImage(mNextRequest->getImage(), cacheimage, 64); } maDestroyObject(cacheimage); cacheimage = -1; } store = -1; finishedDownloading(); } else { mHttp = HttpConnection(this); int res = mHttp.create(mNextRequest->getUrl().c_str(), HTTP_GET); if(res < 0) { finishedDownloading(); } else { mHttp.finish(); } } }
void testPlaceHolder() { maCreateData(RES_PLACEHOLDER, 16); assert("maGetDataSize", (maGetDataSize(RES_PLACEHOLDER) == 16)); for(int i = 0; i < 4; i++) maWriteData(RES_PLACEHOLDER, &i, i*4, 4); bool failed = false; for(int i = 0; i < 4; i++) { int dest; maReadData(RES_PLACEHOLDER, &dest, i*4, 4); if(dest != i) { failed = true; break; } } assert("Placeholder test", !failed); }
void MoSyncCamController::snapshotDisplayRequested() { if ( !isDisplayed(*mImageViewerScreen) ) { if ( mLastSnapshotDataHandle > 0 ) { mDisplayedImageHandle = maCreatePlaceholder(); maCreateImageFromData( mDisplayedImageHandle, mLastSnapshotDataHandle, 0, maGetDataSize(mLastSnapshotDataHandle)); mImageViewerScreen->setImageWithData(mDisplayedImageHandle); mImageViewerScreen->showWithTransition(mForwardTransition, SCREEN_TRANSITION_DURATION); setCurrentScreen(*mImageViewerScreen); } } }
int MAMain() { //MAExtent e = maGetScrSize(); /// play R_MOSO sound maSoundPlay(SOUND_RESOURCE, 0, maGetDataSize(SOUND_RESOURCE)); printf("Press 0/RSK to exit."); while(1) { maWait(0); MAEvent event; while(maGetEvent(&event)) { if(event.type == EVENT_TYPE_CLOSE || (event.type == EVENT_TYPE_KEY_PRESSED && (event.key == MAK_0 || event.key == MAK_SOFTRIGHT || event.key == MAK_BACK))) { maExit(0); } } } }
int NativeScreen::handleImageData(MAHandle myImageData) { printf("handleImageData(%d)", myImageData); int resCode = -1; MAHandle hImage = maCreatePlaceholder(); int dataSize = maGetDataSize(myImageData); int createImageRes = maCreateImageFromData(hImage, myImageData, 0, dataSize); // Used for testing only. MAUtil::String info = "Ready.Size = " + MAUtil::integerToString(dataSize) + " res = " + MAUtil::integerToString(createImageRes); printf("\n%s\n", info.c_str()); if (createImageRes != RES_OK) { // If the Android VM gets an out of memory exception, get the image handle instead. maAlert("Memory Warning", " The image cannot be created. Try again", NULL, NULL, NULL); maWidgetSetProperty(mEventReturnTypeCheckbox, MAW_CHECK_BOX_CHECKED, "false"); maImagePickerOpen(); } else { char imgHandle[256]; sprintf(imgHandle, "%d", hImage); printf("imgHandle=%s---hImage=%d", imgHandle, hImage); // display the preview resCode = maWidgetSetProperty(mPreview, MAW_IMAGE_IMAGE, imgHandle); } // at this point the new selected image is either displayed or non-existent (out of memory) // the former displayed image (if exists) can be now safely deleted and reused if (mLastDisplayedImageHandle != -1) { maDestroyPlaceholder(mLastDisplayedImageHandle); } mLastDisplayedImageHandle = hImage; return resCode; }
//TestCase void start() { assert("maSoundPlay", maSoundPlay(RES_MP3, 0, maGetDataSize(RES_MP3))>=0); suite->runNextCase(); }
/** * Loads an image from a file and returns the handle to it. * * @param imagePath relative path to the image file. */ MAHandle ResourceMessageHandler::loadImageResource(const char* imagePath) { if (!getFileUtil()) { return 0; } // Get the current apllication directory path. String appPath = getFileUtil()->getAppPath(); // Construct image path. char completePath[2048]; sprintf(completePath, "%s%s", appPath.c_str(), imagePath); // Load the image and create a data handle from it. MAHandle imageFile = maFileOpen(completePath, MA_ACCESS_READ); if (imageFile < 0) { return 0; } int fileSize = maFileSize(imageFile); if (fileSize < 1) { return 0; } // Create buffer to hold file data. MAHandle fileData = maCreatePlaceholder(); int result = maCreateData(fileData, fileSize); if (RES_OK != result) { maDestroyPlaceholder(fileData); return 0; } // Read data from file. result = maFileReadToData(imageFile, fileData, 0, fileSize); maFileClose(imageFile); if (result < 0) { maDestroyPlaceholder(fileData); return 0; } // Create image. MAHandle imageHandle = maCreatePlaceholder(); result = maCreateImageFromData( imageHandle, fileData, 0, maGetDataSize(fileData)); maDestroyPlaceholder(fileData); if (RES_OK != result) { maDestroyPlaceholder(imageHandle); return 0; } // Return the handle to the loaded image. return imageHandle; }
/** * Parse the message. This finds the message name and * creates a dictionary with the message parameters. */ void WebViewMessage::parse(MAHandle dataHandle) { // Set message name to empty string as default. mMessageName = ""; // We must have data. if (NULL == dataHandle) { return; } // Get length of the data, it is not zero terminated. int dataSize = maGetDataSize(dataHandle); // Allocate buffer for string data. char* stringData = (char*) malloc(dataSize + 1); // Get the data. maReadData(dataHandle, stringData, 0, dataSize); // Zero terminate. stringData[dataSize] = 0; // Create String object with message. MAUtil::String messageString = stringData; // Find schema. int start = messageString.find("mosync://"); if (0 != start) { return; } // Set start of message name. start = 9; // Find end of message name. int end = messageString.find("?", start); if (MAUtil::String::npos == end) { // No params, set message name to rest of string. mMessageName = messageString.substr(start); return; } // Set message name. mMessageName = messageString.substr(start, end - start); while (1) { // Find param name. start = end + 1; end = messageString.find("=", start); if (MAUtil::String::npos == end) { // No param name found, we are done. break; } // Set param name. MAUtil::String paramName = messageString.substr(start, end - start); MAUtil::String paramValue; // Find end of param value. start = end + 1; end = messageString.find("&", start); if (MAUtil::String::npos == end) { // Last param, set param value to rest of string. paramValue = messageString.substr(start); } else { paramValue = messageString.substr(start, end - start); } // Add param to table. mMessageParams.insert(unescape(paramName), unescape(paramValue)); // If no more params we are done. if (MAUtil::String::npos == end) { break; } } // Free string data. free(stringData); }
/** * Handle widget events. * @param event A MoSync event data structure. */ void NativeScreen::customEvent(const MAEvent& event) { // Get the information sent by the widget. MAWidgetEventData* widgetEventData = (MAWidgetEventData*) event.data; if ( event.type == EVENT_TYPE_IMAGE_PICKER) { if ( event.imagePickerState == 1 ) { // ready, get handle MAHandle myImage = event.imagePickerItem; char checkboxBuffer[BUF_SIZE]; maWidgetGetProperty(mEventReturnTypeCheckbox, MAW_CHECK_BOX_CHECKED, checkboxBuffer, BUF_SIZE); MAUtil::String value = MAUtil::lowerString(checkboxBuffer); if ( strcmp(value.c_str(),"true") == 0 ) { MAHandle hImage = maCreatePlaceholder(); int dataSize = maGetDataSize(event.imagePickerItem); int createImageRes= maCreateImageFromData(hImage, event.imagePickerItem, 0, dataSize); // Used for testing only. MAUtil::String info = "Ready.Size = " + MAUtil::integerToString(dataSize) + "res = " + MAUtil::integerToString(createImageRes) + ", mime type = " + MAUtil::integerToString(event.imagePickerEncodingType); if ( createImageRes != RES_OK ) { maAlert("Memory Warning", " The image cannot be created. Try again", NULL, NULL, NULL); maWidgetSetProperty(mEventReturnTypeCheckbox, MAW_CHECK_BOX_CHECKED, "false"); // If the Android VM gets an out of memory exception, get the image handle instead. maImagePickerOpen(); } else { char imgHandle[256]; sprintf(imgHandle, "%d", hImage); int resCode = maWidgetSetProperty(mPreview, MAW_IMAGE_IMAGE, imgHandle); } maDestroyPlaceholder(hImage); } else { char buffer[256]; sprintf(buffer, "%d", myImage); int resCode = maWidgetSetProperty(mPreview, MAW_IMAGE_IMAGE, buffer); } setLabelText(mLabel, "Preview is available"); } else { setLabelText(mLabel, "The user canceled the image selection"); } } // Check that the event was a click (touch) event. if (widgetEventData->eventType == MAW_EVENT_CLICKED) { // Handle the event emitted by the widget widgetClicked(widgetEventData->widgetHandle); } }