/////////////////////////////////////////////////////////////////////////////// /// Add Attributes to an given element. /// It copies the \c attr array and all values, /// replaces all attribute names by constant literal strings, /// converts the null-terminated array into an array of known size n. /// ///\param el The element. ///\param attr Attributes. ///\returns 0 if there is no error occurred. Otherwise, return 1 to indicate an error. /////////////////////////////////////////////////////////////////////////////// int addAttributes(Element* el, const char** attr) { int n, a; const char** att = NULL; for (n=0; attr[n]; n+=2); printDebug("\n"); printfIntDebug("addAttributes(): n = %d\n", n); if (n>0) { att = calloc(n, sizeof(char*)); if (checkPointer(att)) return 1; } printDebug("addAttributes(): allocated att"); for (n=0; attr[n]; n+=2) { char* value = strdup(attr[n+1]); //duplicate string attr[n+1] printfDebug("addAttributes(): value = %s\n", value); if (checkPointer(value)) return 1; a = checkAttribute(attr[n]); printfIntDebug("addAttributes(): index a = %d\n", a); if (a == -1) { printf("Illegal attribute in"); return 1; // illegal attribute error } att[n ] = attNames[a]; // no heap memory printfDebug("addAttributes(): attNames = %s\n", attNames[a]); att[n+1] = value; // heap memory printfDebug("addAttributes(): att[n+1] = %s\n", att[n+1] ); } el->attributes = att; // NULL if n=0 el->n = n; return 0; // success }
void dictionarySortedPrint(Dictionary* dict) { int i; checkPointer(dict); for(i = 0; i < dict->count; i++) printf("%4i: %s\n", dict->strings[i]->ID, dict->strings[i]->data); }
void ListToPopUpMenu (_List& menuOptions) { lastPopupFactory = new GtkItemFactoryEntry [menuOptions.lLength]; checkPointer (lastPopupFactory); long sepCounter = 0; for (long counter=0; counter<menuOptions.lLength; counter++) { _String *postItem = (_String*)(menuOptions(counter)), * pathID = new _String("/Popup/"), * itemType = new _String; lastPopupFactory[counter].accelerator = NULL; lastPopupFactory[counter].callback_action = counter; lastPopupFactory[counter].callback = G_CALLBACK(hyphy_popup_menu_callback); if (*postItem==_String("SEPARATOR")) { *pathID = *pathID & "sep" & (sepCounter++); *itemType = "<Separator>"; } else { *pathID = *pathID & *postItem; *itemType = "<Item>"; } lastPopupFactory[counter].path = pathID->sData; lastPopupFactory[counter].item_type = itemType->sData; lastPopupMenuItemStrings << pathID; lastPopupMenuItemStrings << itemType; DeleteObject (pathID); DeleteObject (itemType); } }
/////////////////////////////////////////////////////////////////////////////////////// /// Callback functions called by the XML parser. It creates and push a new element node. /// This is the start handler of Parser. XML_Parse() starts from here. /// ///\param context ///\param elm The element ///\param attr The attributes /////////////////////////////////////////////////////////////////////////////////////// static void XMLCALL startElement(void *context, const char *elm, const char **attr) { Elm el; void* e; int size; el = checkElement(elm); //Get the index of element printfDebug("startElement():%s\n", elm); printfDebug("*** starting element %s\n", elmNames[el]); if (el==-1) { printDebug("Error!"); return; // error } skipData = (el != elm_Name); // skip element content for all elements but Name switch(getAstNodeType(el)){ case astElement: size = sizeof(Element); break; case astListElement: size = sizeof(ListElement); break; case astType: size = sizeof(Type); break; case astScalarVariable: size = sizeof(ScalarVariable); break; case astModelDescription: size = sizeof(ModelDescription); break; default: assert(0); // Error message if there is no matching element, } printfIntDebug("Start to created a new element with size: %d\n", size); e = newElement(el, size, attr); // Create a new element printDebug("Created a new element"); if(checkPointer(e)) assert(0); // Check the validity of the new element printDebug("startElement(): Start to stack push."); stackPush(stack, e); // Add the element to stack and grow the stack if necessary }
void test() { for (unsigned x(0); x < buffer_.width(); x+=10) { for (unsigned y(0); y < buffer_.height(); y+=10) { movePointer(x, y); checkFocus(true); checkPointer(x, y); } } movePointer(-1, -1); checkFocus(false); movePointer(5, 5); checkFocus(true); inputKeySend(BTN_LEFT, 1); checkButton(BTN_LEFT, 1); inputKeySend(BTN_LEFT, 0); checkButton(BTN_LEFT, 0); inputKeySend(BTN_RIGHT, 1); checkButton(BTN_RIGHT, 1); inputKeySend(BTN_RIGHT, 0); checkButton(BTN_RIGHT, 0); inputKeySend(BTN_MIDDLE, 1); checkButton(BTN_MIDDLE, 1); inputKeySend(BTN_MIDDLE, 0); checkButton(BTN_MIDDLE, 0); }
//__________________________________________________________________________________ void UpdateChangingFlas (_SimpleList & involvedVariables) { long topLimit = compiledFormulaeParameters.lLength; _SimpleList * toDelete = nil; for (long k = 0; k<topLimit; k++) { long g = ((_SimpleList*)compiledFormulaeParameters.lData[k])->CountCommonElements (involvedVariables,true); if (g>0) { _ElementaryCommand* thisCommand = (_ElementaryCommand*)listOfCompiledFormulae.lData[k]; _Formula *f = (_Formula*)(thisCommand->simpleParameters.lData[1]), *f2 = (_Formula*)(thisCommand->simpleParameters.lData[2]); delete f; delete f2; thisCommand->simpleParameters.Clear(); if (!toDelete) { checkPointer(toDelete = new _SimpleList); } *toDelete << k; } } if (toDelete) { listOfCompiledFormulae.DeleteList (*toDelete); compiledFormulaeParameters.DeleteList (*toDelete); DeleteObject (toDelete); } }
//_______________________________________________________________________ // append operator void _CString::operator << (_String* s) { if ( s && s->sLength) { if (allocatedSpace < sLength + s->sLength) { unsigned long incBy = sLength + s->sLength - nInstances; if (incBy < storageIncrement) { incBy = storageIncrement; } if (incBy < sLength/8) { incBy = sLength/8; } allocatedSpace+=incBy; sData = (char*)MemReallocate((char*)sData, allocatedSpace*sizeof(char)); if (!sData) { checkPointer (sData); } } memcpy(sData+sLength,s->sData,s->sLength); sLength+=s->sLength; } }
int dictionarySaveToFile(Dictionary* dict, char* filename) { FILE* outputFile = fopen(filename, "wb"); int pos, len, retn = 0; checkPointer(dict); checkPointer(filename); if (!outputFile) { fprintf(stderr, "Error[DIC]: could not open \"%s\".\n", filename); return DIC_ERROR; } if (fseek(outputFile, 0, SEEK_SET)) { fprintf(stderr, "Error[DIC]: could not seek \"%s\".\n", filename); retn = DIC_ERROR; goto svexit; } if (sizeof(int) != fwrite(&dict->count, 1, sizeof(int), outputFile)) { fprintf(stderr, "Error[DIC]: could not write to file \"%s\".\n", filename); retn = DIC_ERROR; goto svexit; } for(pos = 0; pos < dict->count; pos++) { len = (int)strlen(dict->index[pos]); if (sizeof(int) != fwrite(&len, 1, sizeof(int), outputFile)) { fprintf(stderr, "Error[DIC]: could not write to file \"%s\".\n", filename); retn = DIC_ERROR; goto svexit; } if (len != fwrite(dict->index[pos], 1, len, outputFile)) { fprintf(stderr, "Error[DIC]: could not write to file \"%s\".\n", filename); retn = DIC_ERROR; goto svexit; } } svexit: if (fclose(outputFile) == EOF) { fprintf(stderr, "Error[DIC]: closing dictionary file \"%s\" failed.\n", filename); retn = DIC_ERROR; } return retn; }
AbstractMatrix *getAbstractMatrixFromSEXP(SEXP s){ checkPointer(s); if (TYPEOF(s) == EXTPTRSXP) { return ((AbstractMatrix*)R_ExternalPtrAddr(s))->castToAbstractMatrix(); } errorLog << "External pointer not valid!" << endl << errorExit ; return NULL; }
_Variable::_Variable (_String&s, bool isG) { theName = (_String*)checkPointer(new _String(s)); varFlags = HY_VARIABLE_NOTSET|(isG?HY_VARIABLE_GLOBAL:0); varValue = nil; varFormula = nil; SetBounds (DEFAULTLOWERBOUND, DEFAULTUPPERBOUND); InsertVar (this); }
// Returns NULL to indicate error Element* newElement(Elm type, int size, const char** attr) { Element* e = (Element*)calloc(1, size); if (!checkPointer(e)) return NULL; e->type = type; e->attributes = NULL; e->n=0; if (!addAttributes(e, attr)) return NULL; return e; }
//__________________________________________________________________ void _HYPlatformGraphicPane::_SlidePane (int dv, int dh) { _HYGraphicPane* theParent = (_HYGraphicPane*)this; Rect r = {0,0,theParent->h,theParent->w}; RgnHandle dummy = NewRgn(); checkPointer (dummy); ScrollRect(&r,dh,dv,dummy); DisposeRgn (dummy); }
//__________________________________________________________________ void _HYSequencePane::CleanUpSequenceNames (void) { bool doSomething = false; _List namesl; _AVLList names (&namesl); for (long k=0; k<speciesIndex.lLength; k++) { _String * thisString = (_String*)rowHeaders (speciesIndex.lData[k]); if (!thisString->IsValidIdentifier(false)) { BufferToConsole ("Changed "); StringToConsole(*thisString); thisString->ConvertToAnIdent(false); BufferToConsole (" to "); StringToConsole(*thisString); NLToConsole(); doSomething = true; } _String * testString = new _String (*thisString); if (!testString) checkPointer (testString); long tryThisSuffix = 2; while (names.Find (testString)>=0) { *testString = *thisString & '_' & tryThisSuffix; tryThisSuffix++; } if (tryThisSuffix>2) { BufferToConsole ("Changed "); StringToConsole(*thisString); BufferToConsole (" to "); StringToConsole(*testString); BufferToConsole (" to avoid duplicate identifiers\n"); doSomething = true; thisString->CopyDynamicString (testString,true); } else DeleteObject (testString); names.Insert(thisString); thisString->nInstances++; } if (doSomething) { SetHeaders (nil,true); _MarkForUpdate(); } }
//_________________________________________________________ _THyPhyMatrix::_THyPhyMatrix(const long r, const long c, const double* d) { checkPointer (mData = (double*)MemAllocate (r*c*sizeof(double))); mRows = r; mCols = c; for (long i = 0; i < r*c; i++,d++) { mData[i] = *d; } }
////////////////////////////////////////////////////////////////////////////////// /// Parse the fmu. The receiver must call freeElement(md) to release AST memory. /// ///\param xmlPath The xml file to be parsed ///\return the root node md of the AST if no error occurred. NULL to indicate failure ///////////////////////////////////////////////////////////////////////////////// ModelDescription* parse(const char* xmlPath) { ModelDescription* md = NULL; FILE *file; int done = 0; stack = stackNew(100, 10); // Allocate stack memory if (checkPointer(stack)) return NULL; // Check if the stack is creatted parser = XML_ParserCreate(NULL); // Create an parser if (checkPointer(parser)) return NULL; // Check if the parser is created XML_SetElementHandler(parser, startElement, endElement); // Set handler for start and end tags XML_SetCharacterDataHandler(parser, handleData); // Set handler for text file = fopen(xmlPath, "rb"); if (file == NULL) { printfError("Cannot open file '%s'\n", xmlPath); XML_ParserFree(parser); // Free the memory for parser return NULL; // Failure } while (!done) { int n = fread(text, sizeof(char), XMLBUFSIZE, file); // Read XMLBUFSIZE characters from file if (n != XMLBUFSIZE) done = 1; // Reach the end of file if (!XML_Parse(parser, text, n, done)){ printf("Parse error in file %s at line %d:\n%s\n", xmlPath, (int)XML_GetCurrentLineNumber(parser), XML_ErrorString(XML_GetErrorCode(parser))); while (!stackIsEmpty(stack)) md = stackPop(stack); if (md) freeElement(md); cleanup(file); return NULL; // failure } } md = stackPop(stack); assert(stackIsEmpty(stack)); cleanup(file); //printElement(1, md); // Print the element for debugging return md; // Success if all refs are valid }
//__________________________________________________________________________________ void _Variable::Initialize (void) { //_Formula::Initialize(); _Constant::Initialize(); theName = (_String*)checkPointer(new _String()); varValue = nil; theIndex = -1; varFlags = HY_VARIABLE_NOTSET; SetBounds (DEFAULTLOWERBOUND, DEFAULTUPPERBOUND); }
SEXP externalptr_is_null(SEXP s) { checkPointer(s); AbstractMatrix * p = (AbstractMatrix*)R_ExternalPtrAddr(s); SEXP ret; PROTECT(ret = allocVector(LGLSXP, 1)); LOGICAL(ret)[0] = FALSE; if (p == NULL) LOGICAL(ret)[0] = TRUE; UNPROTECT(1); return ret; }
int dictionaryRemoveWord(Dictionary* dict, char* word) { int delta = 0, i, count; checkPointer(dict); checkPointer(word); count = dict->count; for(i = 0; i < count; i++) { if (strcmp(dict->strings[i]->data, word) == 0) { delta++; dict->count--; continue; } free(dict->strings[i]->data); free(dict->strings[i]); dict->strings[i - delta] = dict->strings[i]; } return 0; }
// Returns 0 to indicate error // Copies the attr array and all values. // Replaces all attribute names by constant literal strings. // Converts the null-terminated array into an array of known size n. int addAttributes(Element* el, const char** attr) { int n, a; const char** att = NULL; for (n=0; attr[n]; n+=2); if (n>0) { att = calloc(n, sizeof(char*)); if (!checkPointer(att)) return 0; } for (n=0; attr[n]; n+=2) { char* value = strdup(attr[n+1]); if (!checkPointer(value)) return 0; a = checkAttribute(attr[n]); if (a == -1) return 0; // illegal attribute error att[n ] = attNames[a]; // no heap memory att[n+1] = value; // heap memory } el->attributes = att; // NULL if n=0 el->n = n; return 1; // success }
/////////////////////////////////////////////////////////////////////////////// /// Add an new element. /// ///\param type Type of the element. ///\param size Size of the element. ///\param attr Attributes of the element. ///\return The point of the element if ther is no error occurred. /// Otherwise, return NULL to indicate an error. /////////////////////////////////////////////////////////////////////////////// Element* newElement(Elm type, int size, const char** attr) { Element* e = (Element*)calloc(1, size); printfIntDebug("Allocated 1 element with %d bytes of memory in newElement()\n", size); if (checkPointer(e)) return NULL; e->type = type; e->attributes = NULL; e->n=0; printDebug("Start to add new elmement to attr"); if (addAttributes(e, attr)) return NULL; printDebug("Added new elmement to attr"); return e; }
int dictionaryClear(Dictionary* dict) { int i; checkPointer(dict); for(i = 0; i < dict->count; i++) { free(dict->strings[i]->data); free(dict->strings[i]); } dict->count = 0; return 0; }
void FlushConsoleBuffer (void) { if (consoleBufferAdded) { consoleBuffer->Finalize(); hyphyConsoleWindow->PrintString (*consoleBuffer); consoleBufferAdded = 0; DeleteObject (consoleBuffer); consoleBuffer = new _String (CONSOLE_BUFFERING,true); checkPointer (consoleBuffer); } }
BaseRef _CString::makeDynamic (void) { _CString* res = (_CString*)new _CString; checkPointer(res); _String::Duplicate (res); res->compressionType = compressionType; return res; }
//__________________________________________________________________ void _HYPlatformGraphicPane::_SlideRect (_HYRect& rct, int dv, int dh) { _HYGraphicPane* theParent = (_HYGraphicPane*)this; Rect r; r.left = rct.left; r.top = rct.top; r.bottom = rct.bottom; r.right = rct.right; RgnHandle dummy = NewRgn(); checkPointer (dummy); ScrollRect(&r,dh,dv,dummy); DisposeRgn (dummy); }
int dictionaryGetByString(Dictionary* dict, char* word) { int left = 0, right = dict->count; int center = 0, result; checkPointer(dict); checkPointer(word); if (dict->count == 0) return DIC_NO_RECORD; if ((result = strcmp(word, dict->strings[0]->data)) < 0) return DIC_NO_RECORD; else if (result == 0) return dict->strings[0]->ID; while((right - left) > 1) { if ((result = strcmp(word, dict->strings[(center = (left + right) / 2)]->data)) > 0) left = center; else if (result < 0) right = center; else // if (result == 0) return dict->strings[center]->ID; } return DIC_NO_RECORD; // nothing found }
//Assignment operator _SimpleList _SimpleList::operator = (_SimpleList l) { Clear(); lLength = l.lLength; laLength = l.laLength; if (laLength) { checkPointer (lData = (long*)MemAllocate (laLength*sizeof (Ptr))); if (lLength) { memcpy (lData,l.lData,lLength*sizeof (Ptr)); } } return *this; }
//_________________________________________________________ _THyPhyString::_THyPhyString(const char* characters, long length) { if (characters) { if (length == 0) { while (characters[length++]) ; length --; } checkPointer (sData = (char*)MemAllocate (length+1)); memcpy (sData,characters,length+1); } else { sData = nil; } sLength = length; }
// Returns NULL to indicate failure // Otherwise, return the root node md of the AST. // The receiver must call freeElement(md) to release AST memory. ModelDescription* parse(const char* xmlPath) { ModelDescription* md = NULL; FILE *file; int done = 0; stack = stackNew(100, 10); if (!checkPointer(stack)) return NULL; // failure parser = XML_ParserCreate(NULL); if (!checkPointer(parser)) return NULL; // failure XML_SetElementHandler(parser, startElement, endElement); XML_SetCharacterDataHandler(parser, handleData); file = fopen(xmlPath, "rb"); if (file == NULL) { fprintf(stderr,"Cannot open file '%s'\n", xmlPath); XML_ParserFree(parser); return NULL; // failure } while (!done) { int n = fread(text, sizeof(char), XMLBUFSIZE, file); if (n != XMLBUFSIZE) done = 1; if (!XML_Parse(parser, text, n, done)){ fprintf(stderr,"Parse error in file %s at line %d:\n%s\n", xmlPath, (int)XML_GetCurrentLineNumber(parser), XML_ErrorString(XML_GetErrorCode(parser))); while (! stackIsEmpty(stack)) md = stackPop(stack); if (md) freeElement(md); cleanup(file); return NULL; // failure } } md = stackPop(stack); assert(stackIsEmpty(stack)); cleanup(file); //printElement(1, md); // debug return md; // success if all refs are valid }
//_______________________________________________________________________ // append operator void _CString::operator << (char c) { if (allocatedSpace <= sLength) { unsigned long incBy = ((storageIncrement*8 > sLength)? storageIncrement: (sLength/8+1)); allocatedSpace+=incBy; sData = (char*)MemReallocate((char*)sData, allocatedSpace*sizeof(char)); if (!sData) { checkPointer (sData); return; } } sData[sLength++]=c; }
void dictionaryFinalize(Dictionary* dict) { int index; checkPointer(dict); if (dict->strings) { for(index = 0; index < dict->count; index++) if (dict->strings[index]) free(dict->strings[index]); free(dict->strings); } if (dict->index) { for(index = 0; index < dict->count; index++) if (dict->index[index]) free(dict->index[index]); free(dict->index); } }