Exemplo n.º 1
0
void Memo_WriteLen(char* cp, UInt len) {
	Long newsize, newalloc;
	Ptr  RecPointer;

	if (!s_pMemoDb || !cp)
		return;
	newsize = s_iOffset + len + 1;

	if (newsize > s_iAllocSize) {
		// If we need more room, round up to next multiple of diAllocSize.
		// This idiom only works if diAllocSize is a power of 2.
		newalloc = (newsize + diAllocSize-1) & ~(diAllocSize-1);
		if (newalloc > diMaxSize) {	// If we are nearly maxed out,
			newalloc = diMaxSize; // use what we've got.
			if (newsize > diMaxSize) // If we are maxed out, give it up.
				return;
		}
		if (s_RecHandle)
			(void) DmReleaseRecord(s_pMemoDb, s_iRecNum, true);
		s_RecHandle = DmResizeRecord(s_pMemoDb, s_iRecNum, newalloc);
		if (s_RecHandle)
			s_iAllocSize = newalloc;
	}
	if (s_RecHandle) {
		if ((RecPointer = MemHandleLock(s_RecHandle))) {
			// Write extra char at end, often it will be null termination...
			if (!DmWrite(RecPointer, s_iOffset, cp, len+1))	// if no error...
				s_iOffset += len;
			(void) MemPtrUnlock(RecPointer);
		}
	}
}
Exemplo n.º 2
0
void CloseTransliterations( void )
{
    UInt16     i;

    if ( 0 < numXlits ) {
        for ( i = 0 ; i < numXlits ; i++ ) {
            MemHandleUnlock( xlitData[ i ].handle );
            DmReleaseRecord( xlitData[ i ].dbRef, xlitData[ i ].index, false );
        }
        for ( i = 0 ; i < numXlits ; i++ ) {
            DmOpenRef  dbRef;
            dbRef = xlitData[ i ].dbRef;
            if ( dbRef != NULL ) {
                UInt16 j;
                DmCloseDatabase( dbRef );
                for ( j = i + 1 ; j < numXlits ; j++ ) {
                    if ( xlitData[ j ].dbRef == dbRef )
                        xlitData[ j ].dbRef = NULL;
                }
            }
        }
        SafeMemPtrFree( xlitData );
    }

    for ( i = 0 ; i < numXlits + 1 ; i++ ) {
        SafeMemPtrFree( xlitNames[ i ] );
    }
    SafeMemPtrFree( xlitNames );
    numXlits = 0;
}
Exemplo n.º 3
0
void Memo_WriteClose(void) {
	MemoWriteLen("", 0); // Make sure it is null terminated.

	// Release handle on record, resize to amount used...
	if (s_RecHandle) {
		(void) DmReleaseRecord(s_pMemoDb, s_iRecNum, true);
		if (s_iOffset+1 < s_iAllocSize &&
			(s_RecHandle = DmResizeRecord(s_pMemoDb, s_iRecNum, s_iOffset+1)))
			(void) DmReleaseRecord(s_pMemoDb, s_iRecNum, true);
		s_RecHandle = NULL;
	}

	if (s_pMemoDb)
		(void) DmCloseDatabase(s_pMemoDb);
	s_pMemoDb = NULL;
}
Exemplo n.º 4
0
UInt16 OpenPrefsDatabase(void) {
  JMPalmPrefs = DmOpenDatabaseByTypeCreator(JMPalmPrefsType, JMPalmAppID,
					    dmModeReadWrite);

  // the database doesn't exist
  if (!JMPalmPrefs) {
    MemHandle foo;
    UInt16 position = 1;

    if (DmCreateDatabase(0, JMPalmPrefsName,
			 JMPalmAppID, JMPalmPrefsType, false))
      return true;
    
    JMPalmPrefs = DmOpenDatabaseByTypeCreator(JMPalmPrefsType, JMPalmAppID,
					      dmModeReadWrite);
		 		 
    ResetHeader();
    
    // create dummy record
    foo = DmNewRecord(JMPalmPrefs, &position, sizeof(headerdata));
    DmReleaseRecord(JMPalmPrefs, position, true);
    WriteHeader();

    // Do some special handling for the first run of the application
    HandleFirstRun();
  }

  return false;
}
Exemplo n.º 5
0
void writeRecord(MemPtr ptr, UInt32 size, UInt16 index, UInt16 dbID) {
	Err e;
	
	MemHandle recordH = DmNewRecord(dbP[dbID], &index, size);
	MemPtr save = MemHandleLock(recordH);
	e = DmWrite(save, 0, ptr, size);
	MemHandleUnlock(recordH);
	DmReleaseRecord (dbP[dbID], index, 0);
}
Exemplo n.º 6
0
static void
SaveButtonClick (void)
{
  DmOpenRef openRef;
  UInt16 recIndex;
  MemHandle recH;
  Err err;

  if (EditorMidi.dbID == 0) {

    debugPrintf("dbID==0, create a new record in Palmano DB\n");
    /* create new record in palmano DB */
 
    err = getPalmanoDatabase(&openRef, dmModeReadWrite | dmModeExclusive);
    if (err != 0) {
      ErrAlert(err);
      return;
    }

    /* allocate new record in DB */
    recIndex = dmMaxRecordIndex;
    recH = DmNewRecord(openRef, &recIndex, 5); /* initial size is 5 bytes */
    ErrFatalDisplayIf(!recH, "SaveButtonClick(): can't get new record by index!");
  }
  else {
    /* replace old song in-place */

    openRef = DmOpenDatabase (EditorMidi.cardNo, EditorMidi.dbID,
			      dmModeReadWrite | dmModeExclusive);

    ErrFatalDisplayIf(!openRef, "SaveButtonClick(): "
		      "Can't open old song database for record");

    err = DmFindRecordByID(openRef, EditorMidi.uniqueRecID, &recIndex);

    ErrFatalDisplayIf(err, "Can't find record by ID");

    recH = DmGetRecord(openRef, recIndex);

    ErrFatalDisplayIf(!recH, "SaveButtonClick(): "
		      "Can't get old song record for writing");
  }

  // save midi to recH
  GetFieldTextToStr(EditorMidi.name, ID_EditorNameField, sndMidiNameLength);

  debugPrintf("SaveButtonClick(): smfutils_save(recH=%lx, name=%s\n",
	      recH, EditorMidi.name);
  smfutils_save(recH, EditorMidi.name, &notelist);
  debugPrintf("SaveButtonClick(): return from smfutils_save()\n");

  DmReleaseRecord (openRef, recIndex, 1);
  DmCloseDatabase (openRef);
  
  FrmGotoForm(ID_MainForm);
}
Exemplo n.º 7
0
// Write the header
void WriteHeader(void) {
  MemHandle headerMH = NULL;
  MemPtr headerMP = NULL;

  headerMH = DmGetRecord(JMPalmPrefs, 0);

  if (headerMH != NULL)
    headerMP = MemHandleLock(headerMH);

  // write new data
  if (headerMH != NULL) {
    //hd.record_count = record_count;
    DmWrite(headerMP, 0, &hd, sizeof(hd));
    MemHandleUnlock(headerMH);
    DmReleaseRecord(JMPalmPrefs, 0, true);
  }
}
Exemplo n.º 8
0
// Read the header data
UInt16 ReadHeader(void) {
  UInt16 err;
  MemHandle headerMH = NULL;
  MemPtr    headerMP = NULL;
  headerdata* foo;

  err = false;

  headerMH = DmGetRecord(JMPalmPrefs, 0);
  
  if (headerMH != NULL)
    headerMP = MemHandleLock(headerMH);

  foo = (headerdata*)headerMP;

  // copy the object
  if (foo != NULL) {
    memcpy(&hd, foo, sizeof(headerdata));

    // Header version incompatible?
    if (hd.version <= INCOMPATIBILITY_LEVEL) { 
      FrmCustomAlert(ErrorMessageForm, "Installation error: You must"\
		     " delete old JMPalm versions before installing"\
		     " this version. Please delete and reinstall.",
		     0, 0);
      err = true;
    }
    else if (hd.version < CURRENT_SETTINGS_VERSION) {
      FrmCustomAlert(ErrorMessageForm, "New (incompatible) version of "\
		     "JMPalm installed, "\
		     "your settings are lost!", 0, 0);
      drawSplash();
      ResetHeader();
    }
  }

  if (headerMH != NULL) {
    MemHandleUnlock(headerMH);
    DmReleaseRecord(JMPalmPrefs, 0, true);
  }

  return err;
}
Exemplo n.º 9
0
/* Create new item in app database */
static UInt16
DoTheBoogie(KleenexPtr kleenexP, DmOpenRef dbR, UInt16 *index)
{
    MemHandle hnd;
    MemPtr recordP;
    UInt16 strLen;

    *index = dmMaxRecordIndex;
    if (!(hnd = DmNewRecord(dbR, index, 3360)))
        return (1);
    recordP = MemHandleLock(hnd);
    DmWrite(recordP, 0, kleenexP->data, 3200);
    DmSet(recordP, 3200, 160, 0);
    if ((strLen = StrLen(kleenexP->text)) > 31)
        strLen = 31;
    DmWrite(recordP, 3200, kleenexP->text, strLen);
    MemHandleUnlock(hnd);
    DmReleaseRecord(dbR, *index, true);

    return (errNone);
}
Exemplo n.º 10
0
NCSError NCSFileClose(NCS_FILE_HANDLE hFile)
{
#ifdef WIN32

	if( CloseHandle(  hFile ) )
		return(NCS_FILE_CLOSE_ERROR);
	else
		return(NCS_SUCCESS);

#elif defined MACINTOSH

	FSClose((short)hFile);
	hFile = NULL;
	return NCS_SUCCESS;
			
#elif defined PALM

	if(hFile && hFile->dbRef) {
		if(hFile->hRecord) {
			if(hFile->pData) {
				MemHandleUnlock(hFile->hRecord);
			}
			DmReleaseRecord(hFile->dbRef, hFile->iRecord, false);
		}
		DmCloseDatabase(hFile->dbRef);
	}
	NCSFree((void*)hFile);
	
#elif defined(POSIX)

	if(close(hFile) == 0) {
		return(NCS_SUCCESS);
	} else {
		return(NCS_FILE_CLOSE_ERROR);
	}

#else	/* SOLARIS||IRIX */
#error ERROR: EcwFileOpen() routine is not defined for this platform
#endif	/* WIN32 */
}
Exemplo n.º 11
0
static void MusicFormSave(UInt16 index) {
	if (index != dmMaxRecordIndex) {
		MemHandle recordH;
		GameInfoType *ogameInfoP;

		if (!MusicTabSave()) return;
		if (!AudioCDTabSave()) return;
		VolumeTabSave();

		recordH = DmGetRecord(gameDB, index);
		ogameInfoP = (GameInfoType *)MemHandleLock(recordH);
		DmWrite(ogameInfoP, 0, gameInfoP, sizeof(GameInfoType));
		MemHandleUnlock(recordH);
		DmReleaseRecord (gameDB, index, 0);
	}

	MemPtrFree(gameInfoP);
	gameInfoP = NULL;

	TabDeleteTabs(myTabP);
	FrmReturnToMain();
}
Exemplo n.º 12
0
/*************************************************************************
 * Function: replaceAccountHash
 * Description: regernate the hash on a single account based on account
 * index
 * ***********************************************************************/ 
void replaceAccountHash(UInt16 index, DmOpenRef db, md_hash * SysPass) {
	Account ac;
	MemHandle rH;
	MemPtr pac = NULL, scratch = NULL, scratch2=NULL;
	if ((rH = DmGetRecord (db, index))) {
		pac = MemHandleLock (rH);
		if ((scratch = MemPtrNew (MemPtrSize (pac)))) {
			UnpackAccount (&ac, pac, scratch, SysPass, 
				MemHandleSize (rH), true, true);
			if ((scratch2 = MemPtrNew (MemPtrSize (pac)))) {
				MemMove(ac.hash, 
					generateAccountHash(&ac), 
					sizeof(md_hash)); 
				PackAccount (scratch2, ac, SysPass, true);
				writeRecord(scratch2, rH);
			}
		}
		MemPtrFree(scratch);
		MemPtrFree(scratch2);
		MemHandleUnlock (rH);
		DmReleaseRecord (db, index, true);
	}
}
Exemplo n.º 13
0
/* Create a new record recNum in a databse db that contains given word */
static Err WriteWordInRecord(DmOpenRef db, UInt16 recNum, char *word)
{
    int         wordLen;
    MemHandle   recHandle;
    MemPtr      recData;
    Err         err;

    Assert(db);
    Assert(word);

    wordLen = StrLen(word)+1;

    recHandle = DmNewRecord(db, &recNum, wordLen);
    if (!recHandle)
        return DmGetLastErr();

    recData = MemHandleLock(recHandle);
    Assert( recData );

    err = DmWrite(recData, 0, word, wordLen);
    MemHandleUnlock(recHandle);
    DmReleaseRecord(db, recNum, true);
    return err;
}
Exemplo n.º 14
0
/**
 * @brief Read the happydays information from address db, and insert into Happydays DB
 * @param frm StartForm to display indicator bars
 * @return If success, return true, or return false
 */
Boolean NewUpdateHappyDaysDB(FormPtr frm)
{
    UInt16 currIndex = 0;
    PrvAddrPackedDBRecord *rp;
    AddrDBRecordType r;
    MemHandle recordH = 0;
    UInt16 recordNum;
    int i = 0, indicateNext;
    int step;

    // create the happydays cache db
    HappyDays   hd;
    Boolean     ignore = false;         // ignore error record
    Char*       hdField;
    UInt16      addrattr, index;
    Char        *p, *q, *end;
    Int16       err;

    // display collecting information
    //
    FrmDrawForm(frm);

    // clean up old database
    //
    CleanupHappyDaysCache(MainDB);

    recordNum = DmNumRecords(AddressDB);
    indicateNext = step = recordNum / INDICATE_NUM;

    if (recordNum > 50) initIndicate();

    while (1) {
        char *name1, *name2;
        Int8 whichField;        // birthday field or note field?

        recordH = DmQueryNextInCategory(AddressDB, &currIndex,
                                        dmAllCategories);
        if (!recordH) break;
        if (i++ == indicateNext) {
            if (recordNum > 50) displayNextIndicate( (i-1) / step);
            indicateNext += step;
        }

        DmRecordInfo(AddressDB, currIndex, &addrattr, NULL, NULL);
        addrattr &= dmRecAttrCategoryMask;      // get category info

        rp = (PrvAddrPackedDBRecord*)MemHandleLock(recordH);
        /*
         * Build the unpacked structure for an AddressDB record.  It
         * is just a bunch of pointers into the rp structure.
         */
        NewAddrUnpack(rp, &r);

        if ( (gHappyDaysField <= 0 || !r.fields[gHappyDaysField])
                // there is no birthday info(trick. should check flags, but I think it is ok)
                //
                && DateToInt(r.birthdayInfo.birthdayDate) == 0
                && !(gPrefsR.scannote && r.fields[note]
                     && StrStr(r.fields[note], gPrefsR.notifywith) ) ) {

            // If there is not exist Happydays field or note field, or internal birthday field(in NEW PIMS)
            //
            MemHandleUnlock(recordH);
            currIndex++;
            continue;
        }

        MemSet(&hd, sizeof(hd), 0);
        hd.addrRecordNum = currIndex;
        if (DetermineRecordName(&r, gSortByCompany, &hd.name1, &hd.name2)) {
            // name 1 has priority;
            hd.flag.bits.priority_name1 = 1;
        }

        // ===========================================================
        // Process Birthday field first
        // ===========================================================
        if (DateToInt(r.birthdayInfo.birthdayDate) != 0) {
            hd.date = r.birthdayInfo.birthdayDate;
            hd.flag.bits.year = 1;
            hd.flag.bits.solar = 1;

            // maintain address book order(name order)
            //      list order is determined by sort
            err = HDNewRecord(MainDB, &hd, &index);
            if (!err) {
                UInt16 attr;
                // set the category of the new record to the category
                // it belongs in
                DmRecordInfo(MainDB, index, &attr, NULL, NULL);
                attr &= ~dmRecAttrCategoryMask;
                attr |= addrattr;

                DmSetRecordInfo(MainDB, index, &attr, NULL);
                DmReleaseRecord(MainDB, index, true);
            }
        }
        // ===========================================================

        // save the temporary name
        name1 = hd.name1;
        name2 = hd.name2;

        if (gHappyDaysField >= 0 && r.fields[gHappyDaysField]) {
            whichField = gHappyDaysField;
        }
        else if (gPrefsR.scannote     // scanNote & exists
                 && r.fields[note]
                 && StrStr(r.fields[note], gPrefsR.notifywith)) {
            whichField = note;
        }
        else whichField = -1;

        while (whichField >= 0) {

            if (whichField == note) {
                p = StrStr(r.fields[note], gPrefsR.notifywith) + StrLen(gPrefsR.notifywith) + 1;

                if ( StrLen(r.fields[note]) < (p - r.fields[note]) ) break;
            }
            else {
                p = r.fields[whichField];
            }

            hdField = MemPtrNew(StrLen(r.fields[whichField]) - (p - r.fields[whichField])+1);
            SysCopyStringResource(gAppErrStr, NotEnoughMemoryString);
            ErrFatalDisplayIf(!hdField, gAppErrStr);

            p = StrCopy(hdField, p);

            if (whichField == note &&
                    (end = StrStr(p, gPrefsR.notifywith))) {
                // end delimeter
                //
                *end = 0;
            }

            while ((q = StrChr(p, '\n'))) {
                // multiple event
                //

                *q = 0;
                if (AnalizeOneRecord(addrattr, p, &hd, &ignore))
                    goto Update_ErrHandler;
                p = q+1;

                // restore the saved name
                hd.name1 = name1;
                hd.name2 = name2;

                // reset multiple flag
                hd.flag.bits.multiple_event = 0;

                while (*p == ' ' || *p == '\t' || *p == '\n')
                    p++;     // skip white space
            }
            // last record
            if (*p) {
                // check the null '\n'
                if (AnalizeOneRecord(addrattr, p, &hd, &ignore))
                    goto Update_ErrHandler;
            }

            if (whichField == gHappyDaysField  // next is note field
                    && (gPrefsR.scannote     // scanNote & exists
                        && r.fields[note]
                        && StrStr(r.fields[note], gPrefsR.notifywith)) ) {
                whichField = note;
            }
            else whichField = -1;

            MemPtrFree(hdField);
        }
        MemHandleUnlock(recordH);
        currIndex++;
    }
    if (recordNum > 50) displayNextIndicate( INDICATE_NUM -1);

    return true;

Update_ErrHandler:
    MemPtrFree(hdField);
    MemHandleUnlock(recordH);
    return false;
}
Exemplo n.º 15
0
Boolean
ExamsFormHandleEvent(EventPtr event)
{
  FormPtr frm=FrmGetActiveForm();
  Boolean handled = false;
  Boolean categoryEdited, reDraw=false;
  UInt16 category, numRecords;
  ControlType *ctl;
  UInt32 *recordList;

  if (event->eType == ctlSelectEvent) {
    // button handling
    switch (event->data.ctlSelect.controlID) {
      case BUTTON_ex_back:
        handled=true;
        FrmGotoForm(FORM_main);
        break;

      case BUTTON_ex_add:
        handled=true;
        if (CountCourses() > 0) {
          gExamsLastSelRowUID=0;
          FrmPopupForm(FORM_exam_details);
        } else {
          FrmAlert(ALERT_nocourses);
        }
        break;

      case BUTTON_ex_edit:
        handled=true;
        gExamsLastSelRowUID=TblGetRowData(GetObjectPtr(TABLE_exams), gExamsSelRow);
        FrmPopupForm(FORM_exam_details);
        break;

      case BUTTON_ex_note:
      {
        UInt16 index=0;

        handled=true;

        gExamsLastSelRowUID=TblGetRowData(GetObjectPtr(TABLE_exams), gExamsSelRow);
        DmFindRecordByID(DatabaseGetRefN(DB_MAIN), gExamsLastSelRowUID, &index);
        NoteSet(index, FORM_exams);
        FrmPopupForm(NewNoteView);
        break;
      }

      case BUTTON_ex_del:
        handled=true;
        gExamsLastSelRowUID=TblGetRowData(GetObjectPtr(TABLE_exams), gExamsSelRow);
        ExamDelete();
        break;

      case BUTTON_ex_beam:
        handled=true;
        gExamsLastSelRowUID=TblGetRowData(GetObjectPtr(TABLE_exams), gExamsSelRow);
        ExamBeam();
        break;

      case LIST_ex_cat_trigger:
        handled=true;
        category=DatabaseGetCat();
        numRecords=DmNumRecordsInCategory(DatabaseGetRef(), DELETE_CATEGORY);
        recordList=(UInt32 *)MemPtrNew(numRecords * sizeof(UInt32));
        CatPreEdit(numRecords, recordList);
        categoryEdited = CategorySelect(DatabaseGetRef(), frm,
                                        LIST_ex_cat_trigger, LIST_ex_cat, false,
                                        &category, gCategoryName, 0,
                                        STRING_cat_edit); // categoryDefaultEditCategoryString
        if (categoryEdited || (category != DatabaseGetCat())) {
          reDraw=true;
          DatabaseSetCat(category);
          ctl = GetObjectPtr(LIST_ex_cat_trigger);
          CategoryGetName(DatabaseGetRef(), category, gCategoryName); 
          CategorySetTriggerLabel(ctl, gCategoryName);
        }
        CatPostEdit(numRecords, recordList);
        if (reDraw) {
          gExamsOffset=0;
          gExamsSelRow=0;
          FrmUpdateForm(FORM_exams, frmRedrawUpdateCode);
        }
        if (recordList != NULL)  MemPtrFree((MemPtr)recordList);
        break;

      default:
        break;
    }
  } else if (event->eType == tblEnterEvent) {
    UInt16 i;
    
    if (event->data.tblEnter.column == EXCOL_DONE) {
      handled=false;
    } else if (event->data.tblEnter.column == EXCOL_NOTE) {
      MemHandle m;
      Boolean hasNote=false;

      gExamsSelRow=event->data.tblEnter.row;
      for (i=0; i < TblGetNumberOfRows(event->data.tblEnter.pTable); ++i) {
        RectangleType r;
        TblGetItemBounds(event->data.tblEnter.pTable, i, EXCOL_SELI, &r);
        TableDrawSelection(event->data.tblEnter.pTable, i, event->data.tblEnter.column, &r);
      }


      m = DmQueryRecord(DatabaseGetRefN(DB_MAIN), TblGetRowID(event->data.tblEnter.pTable, event->data.tblEnter.row));
      if (m) {
        ExamDBRecord *ex = (ExamDBRecord *)MemHandleLock(m);
        if (ex->note) hasNote = true;
        else          hasNote = false;
        MemHandleUnlock(m);
      }

      if (hasNote) {
        Coord newPointX, newPointY;
        Boolean isPenDown=false, drawn=false;
        RectangleType fieldBounds;
        IndexedColorType curForeColor, curBackColor, curTextColor;
        Char noteSymb[2] = { GADGET_NOTESYMBOL, 0 };
        FontID oldFont;
  
  
        EvtGetPen(&newPointX, &newPointY, &isPenDown);
        TblGetItemBounds(event->data.tblEnter.pTable, event->data.tblEnter.row, EXCOL_NOTE, &fieldBounds);
  
        oldFont = FntSetFont(symbolFont);
        while (isPenDown){
          if (! drawn && RctPtInRectangle(newPointX, newPointY, &fieldBounds)) {
            curForeColor = WinSetForeColor(UIColorGetTableEntryIndex(UIObjectSelectedForeground));
            curBackColor = WinSetBackColor(UIColorGetTableEntryIndex(UIObjectSelectedFill));
            curTextColor = WinSetTextColor(UIColorGetTableEntryIndex(UIObjectSelectedForeground));
            TNDrawCharsToFitWidth(noteSymb, &fieldBounds);
            WinSetForeColor(curForeColor);
            WinSetForeColor(curBackColor);
            WinSetForeColor(curTextColor);
            drawn = true;
          } else if (drawn && ! RctPtInRectangle(newPointX, newPointY, &fieldBounds)) {
            curForeColor = WinSetForeColor(UIColorGetTableEntryIndex(UIObjectForeground));
            curBackColor = WinSetBackColor(UIColorGetTableEntryIndex(UIObjectFill));
            curTextColor = WinSetTextColor(UIColorGetTableEntryIndex(UIObjectForeground));
            TNDrawCharsToFitWidth(noteSymb, &fieldBounds);
            WinSetForeColor(curForeColor);
            WinSetForeColor(curBackColor);
            WinSetForeColor(curTextColor);
            drawn = false;
          }
          EvtGetPen(&newPointX, &newPointY, &isPenDown);
        }
        FntSetFont(oldFont);
      } else {
        handled = true;
      }
    } else {
      gExamsSelRow=event->data.tblEnter.row;
      for (i=0; i < TblGetNumberOfRows(event->data.tblEnter.pTable); ++i) {
        RectangleType r;
        TblGetItemBounds(event->data.tblEnter.pTable, i, EXCOL_SELI, &r);
        TableDrawSelection(event->data.tblEnter.pTable, i, event->data.tblEnter.column, &r);
      }
      handled=true;
    }
  } else if (event->eType == tblSelectEvent) {
    if (event->data.tblEnter.column == EXCOL_DONE) {
      MemHandle mex;
      ExamDBRecord *ex;
      Boolean done=(TblGetItemInt(event->data.tblSelect.pTable, event->data.tblSelect.row, event->data.tblSelect.column) == 0) ? false : true;
      UInt16 flags, index=TblGetRowID(event->data.tblSelect.pTable, event->data.tblSelect.row);

      mex=DmGetRecord(DatabaseGetRefN(DB_MAIN), index);
      ex = MemHandleLock(mex);
      flags = ex->flags;

      if (done) {
        flags |= EX_FLAG_DONE;
      } else {
        flags &= (EX_FLAG_DONE ^ 0xFFFF);
      }

      DmWrite(ex, offsetof(ExamDBRecord, flags), &flags, sizeof(flags));
      DmReleaseRecord(DatabaseGetRefN(DB_MAIN), index, false);

      TblMarkRowInvalid(event->data.tblSelect.pTable, event->data.tblSelect.row);
      TblRedrawTable(event->data.tblSelect.pTable);

      MemHandleUnlock(mex);

    } else if (event->data.tblEnter.column == EXCOL_NOTE) {
      ControlType *ctl=GetObjectPtr(BUTTON_ex_note);
      // Don't need code twice, just read ctlSelect Event for BUTTON_ex_note
      CtlHitControl(ctl);
    }
    handled=true;
  } else if (event->eType == ctlRepeatEvent) {
    // Repeat buttons pressed
    if( event->data.ctlRepeat.controlID == REPEAT_ex_up )
      gExamsOffset -= 1;
    else
      gExamsOffset += 1;

    ExamsTableInit();
    TblMarkTableInvalid(GetObjectPtr(TABLE_exams));
    TblRedrawTable(GetObjectPtr(TABLE_exams));
  } else if (event->eType == keyDownEvent) {
    // We have a hard button assigned and it was pressed
    if (TxtCharIsHardKey(event->data.keyDown.modifiers, event->data.keyDown.chr)) {
      if (! (event->data.keyDown.modifiers & poweredOnKeyMask)) {
        FrmGotoForm(FORM_main);
        handled = true;
      }
    }
  } else if (event->eType == menuOpenEvent) {
    return HandleMenuOpenEvent(event);
  } else if (event->eType == menuEvent) {
    // forwarding of menu events
    return HandleMenuEvent(event->data.menu.itemID);
  } else if (event->eType == frmOpenEvent) {
    // initializes and draws the form
    ControlType *ctl;

    gExamsOffset=0;
    ExamsTableInit();
    FrmDrawForm (frm);

    ctl = GetObjectPtr(LIST_ex_cat_trigger);
    CategoryGetName (DatabaseGetRef(), DatabaseGetCat(), gCategoryName); 
    CategorySetTriggerLabel (ctl, gCategoryName); 

    handled = true;
  } else if (event->eType == frmUpdateEvent) {
    // redraws the form if needed
    gExamsOffset=0;
    ExamsTableInit();
    FrmDrawForm(frm);
    handled = false;
  } else if (event->eType == frmCloseEvent) {
    // this is done if form is closed
    // TblEraseTable(GetObjectPtr(TABLE_exams));
    // ExamsFormFree();
    FrmEraseForm(frm);
  }

  return (handled);

}
Exemplo n.º 16
0
static Boolean
ExamDetailsFormSave(void)
{
  MemHandle newExam=NULL;
  UInt16 index = dmMaxRecordIndex;
  ListType *course;
  ControlType *course_tr, *date_tr, *time_tr;
  Char *room;
  Char empty[1]={'\0'};
  FieldType *fldRoom;

  course = GetObjectPtr(LIST_exd_course);
  course_tr = GetObjectPtr(LIST_exd_course_trigger);
  date_tr = GetObjectPtr(SELECTOR_exd_date);
  time_tr = GetObjectPtr(SELECTOR_exd_time);

  fldRoom = GetObjectPtr(FIELD_exd_room);
  room = FldGetTextPtr(fldRoom);
  if (room == NULL)  room=empty;

  if (gExamsLastSelRowUID == 0) {
    // New record
    newExam = DmNewRecord(DatabaseGetRefN(DB_MAIN), &index, sizeof(ExamDBRecord));
  } else {
    // Load record
    DmFindRecordByID(DatabaseGetRefN(DB_MAIN), gExamsLastSelRowUID, &index);
    newExam = DmGetRecord(DatabaseGetRefN(DB_MAIN), index);
  }
  if (! newExam) {
    // Could not create entry
    FrmAlert(ALERT_nomem);
    return false;
  } else {
    UInt16 attr=0;
    ExamDBRecord ex, *ep;

    ep = (ExamDBRecord *)MemHandleLock(newExam);

    ex.type=TYPE_EXAM;
    ex.course=gExamDetailsItemIDs[LstGetSelection(course)];
    ex.note = (gExamsLastSelRowUID == 0) ? 0 : ep->note;
    ex.date.year = gExamDetailsDate.year;
    ex.date.month = gExamDetailsDate.month;
    ex.date.day = gExamDetailsDate.day;
    ex.begin.hours = gExamDetailsBegin.hours;
    ex.begin.minutes = gExamDetailsBegin.minutes;
    ex.end.hours = gExamDetailsEnd.hours;
    ex.end.minutes = gExamDetailsEnd.minutes;
    ex.flags = 0x0000;
    StrNCopy(ex.room, room, sizeof(ex.room));

    DmWrite(ep, 0, &ex, sizeof(ExamDBRecord));
    MemHandleUnlock(newExam);
    DmReleaseRecord(DatabaseGetRef(), index, false);
    DmRecordInfo(DatabaseGetRef(), index, &attr, NULL, NULL);
    attr |= DatabaseGetCat();
    DmSetRecordInfo(DatabaseGetRef(), index, &attr, NULL);

    DatabaseSort();
  } 

  AlarmReset(DatabaseGetRef());
  return true;
}
Exemplo n.º 17
0
NCSError NCSFileRead(NCS_FILE_HANDLE hFile, void *pBuffer, UINT32 nLength, UINT32* pRead)
{
#ifdef WIN32
	
	BOOLEAN	bError;
	DWORD	nBytesRead;

	bError = (BOOLEAN)ReadFile(  hFile,								// handle of file to read
								pBuffer,							// pointer to buffer that receives data
								nLength,							// number of bytes to read
								&nBytesRead,							// pointer to number of bytes read
								NULL);								// pointer to structure for data
	if(pRead) {
		*pRead = (UINT32)nBytesRead;
	}
	if( bError != 0 && nBytesRead == nLength )
		return( NCS_SUCCESS );
	else
		return( NCS_FILE_IO_ERROR );

#elif defined MACINTOSH
	
	int		iOReturn;
	long	myLength;
			
	UINT32  theOffset;
	BOOLEAN	result;
			
	result = GetFPos((short)hFile, (long *)&theOffset);
			
	myLength = nLength;
	iOReturn = FSRead((short)hFile, (long *)&nLength,pBuffer);
	switch (iOReturn) {
		case noErr:
				return NCS_SUCCESS;
			break;
		case eofErr:
				return ((myLength == nLength)?NCS_FILE_IO_ERROR:NCS_SUCCESS);
			break;
		case rfNumErr:
			    return (NCS_FILE_IO_ERROR);
		    break;
		default:
				return NCS_FILE_IO_ERROR;
			break;
	}

#elif defined PALM

	Err eErr;
	INT16 iStartRecord = hFile->iOffset / hFile->nRecordSize + 1;
	INT16 iEndRecord = (hFile->iOffset + nLength) / hFile->nRecordSize + 1;
	INT16 iRecord = hFile->iOffset / hFile->nRecordSize + 1;
	INT64 nRead = 0;
	INT32 nToRead = nLength;
	
	for(iRecord = iStartRecord; iRecord <= iEndRecord; iRecord++) {
		if(hFile->iRecord != iRecord) {
			if(hFile->hRecord) {
				if(hFile->pData) {
					MemHandleUnlock(hFile->hRecord);
					hFile->pData = NULL;
				}
				DmReleaseRecord(hFile->dbRef, hFile->iRecord, false);
				hFile->iRecord = 0;
				hFile->hRecord = NULL;
			}
			hFile->iRecord = iRecord;
			if(hFile->hRecord = DmGetRecord(hFile->dbRef, hFile->iRecord)) {
				hFile->pData = MemHandleLock(hFile->hRecord);
				if(hFile->pData == NULL) {
					DmReleaseRecord(hFile->dbRef, hFile->iRecord, false);
				}
			}
			if(!hFile->hRecord || !hFile->pData) {
				return(NCS_FILE_IO_ERROR);
			}
		}
		if(hFile->pData) {
			INT32 nThisRead = MIN(nToRead, hFile->nRecordSize - (hFile->iOffset % hFile->nRecordSize));
				 
			memcpy((UINT8*)pBuffer + nRead, 
				   (void*)((UINT8*)hFile->pData + hFile->iOffset % hFile->nRecordSize), 
				   nThisRead);
						   
			hFile->iOffset += nThisRead;
			nToRead -= nThisRead;
			nRead += nThisRead;
		}
	}
	if(nRead == nLength) {
		*pRead = nRead;
		return(NCS_SUCCESS);
	}
/*		
	nRead = FileRead(hFile, pBuffer, (Int32)(nLength & 0x7fffffff) , 1, &eErr);
	
	*pRead = (UINT32)nRead;
	
	return(NCSPalmGetNCSError(eErr));
*/
#elif defined(POSIX)

	int nThisRead = read(hFile, (void*)pBuffer, (unsigned int)nLength);
	if(pRead) {
		*pRead = nThisRead;
	}
	if(nThisRead == nLength) {
		return(NCS_SUCCESS);
	} else {
		return(NCS_FILE_IO_ERROR);
	}

#else	/* SOLARIS||IRIX */
#error ERROR: EcwReadFile() routine is not defined for this platform
#endif	/* WIN32 */
}
Exemplo n.º 18
0
Int16 AnalizeOneRecord(UInt16 addrattr, Char* src,
                  HappyDays* hd, Boolean *ignore)
{
    Char *p, *q;
    UInt16 index;
    Int16 err;
    Int16 year, month, day;
    Int16 nth[20];
    Int16 count = 0;

	while (*src == ' ' || *src == '\t') src++;    // skip white space

    // ignore record with exclamation mark
    if (*src == '!') {
        if (gPrefsR.ignoreexclamation) return 0;
        else src++;
    }


    if ((q = StrChr(src, '['))) {
        // [ 이 있는 경우 duration으로 판단 
        p = q;

        q = StrChr(src, ']');
        if (q) *q = 0;
        else return 0;

        do {
            p++;
            nth[count++] = StrAToI(p);
            if (count >= 20) break;
        } while ((p = StrChr(p, ',')));
    }
    
    if (*src == '*') {
        
        // this is multiple event
        hd->flag.bits.multiple_event = true;
        if ((p = StrChr(src, ' '))) *p = 0;
        else goto ErrHandler;
    
        if ( *(src+1) != 0 ) {                       // if src have 'custom' tag
            hd->custom = src+1;
            UnderscoreToSpace(src+1);
        }
		else hd->custom = 0;

        src = p+1;
        while (*src == ' ' || *src == '\t') src++;     // skip white space

        if ((p = StrChr(src, ' '))) *p = 0;
        else goto ErrHandler;

        if (*src == '.') {
            hd->name1 = src+1;
            hd->name2 = 0;
        }
        else {
            hd->name2 = src;
        }
        
        UnderscoreToSpace(src);
        
        src = p+1;
        while (*src == ' ' || *src == '\t') src++;     // skip white space
    }
    
    if (!AnalysisHappyDays(src, &hd->flag,
                           &year, &month, &day)) goto ErrHandler;

    // convert into date format
    //
    if (hd->flag.bits.year) {
        if ((year < 1904) || (year > 2031) ) goto ErrHandler;
        else hd->date.year = year - 1904; 
    }
    else hd->date.year = 0;
        
    hd->date.month = month;
    hd->date.day = day;

    // maintain address book order(name order)
    //      list order is determined by sort
    err = HDNewRecord(MainDB, hd, &index);
    if (!err) {
        UInt16 attr;
        // set the category of the new record to the category
        // it belongs in
        DmRecordInfo(MainDB, index, &attr, NULL, NULL);
        attr &= ~dmRecAttrCategoryMask;
        attr |= addrattr;

        DmSetRecordInfo(MainDB, index, &attr, NULL);

        DmReleaseRecord(MainDB, index, true);
    }

    if (count > 0) {
        Int16 i;
        HappyDays hdr;

        for (i = 0; i < count; i++) {
            MemMove(&hdr, hd, sizeof(hdr));

            hdr.flag.bits.nthdays = 1;
            hdr.nth = nth[i];

            if (!hdr.flag.bits.year) goto ErrHandler;
            
            err = HDNewRecord(MainDB, &hdr, &index);
            if (!err) {
                UInt16 attr;
                // set the category of the new record to the category
                // it belongs in
                DmRecordInfo(MainDB, index, &attr, NULL, NULL);
                attr &= ~dmRecAttrCategoryMask;
                attr |= addrattr;

                DmSetRecordInfo(MainDB, index, &attr, NULL);

                DmReleaseRecord(MainDB, index, true);
            }
        }
    }
    
    return 0;

 ErrHandler:
    if (*ignore) return 0;
                
    switch (FrmCustomAlert(InvalidFormat,
                           ((!hd->name2) ?
                            ((!hd->name1) ? " " : hd->name1)
                            : hd->name2),
                               " ", " ")) {
    case 0:                 // EDIT
        if (!GotoAddress(hd->addrRecordNum)) return -1;
    case 2:                 // Ignore all
        *ignore = true;
    case 1:  
    	break;              // Ignore
    }
    return 0;
}
Exemplo n.º 19
0
NCSError NCSFileOpen(const NCSTChar *szFilename, int iFlags, NCS_FILE_HANDLE *phFile)
{
#ifdef WIN32
	DWORD dwMode = GENERIC_READ;
	DWORD dwCreate = OPEN_EXISTING;

	if(iFlags & NCS_FILE_READ) dwMode = GENERIC_READ;
	if(iFlags & NCS_FILE_READ_WRITE) dwMode = GENERIC_READ|GENERIC_WRITE;
	if(iFlags & NCS_FILE_CREATE) dwCreate = CREATE_ALWAYS;
	if(iFlags & NCS_FILE_CREATE_UNIQUE) dwCreate = CREATE_NEW;
	if(iFlags & NCS_FILE_APPEND) dwCreate = OPEN_ALWAYS;

	*phFile = CreateFile(szFilename,			        // file name
						 dwMode,						// Generic read mode 
						 FILE_SHARE_READ,				// Let anyone access and share the file
						 NULL,							// No security info (so can't be inherited by child process)
						 dwCreate,						// File must exist to be opened
						 FILE_FLAG_RANDOM_ACCESS,		// Going to be doing lots of random access
						 NULL);							// And no template file for attributes
	if( *phFile == INVALID_HANDLE_VALUE ) {
		return( NCS_FILE_OPEN_FAILED );
	} else {
		return( NCS_SUCCESS );
	}

#elif defined MACINTOSH
#if __POWERPC__
	
	int i,length, result;
	Str255		pascalString;
	FSSpec		fileSpec;
		//	We have a C string, we need a PASCAL string.
	length = strlen(szFilename) + 1;
	for(i = 1; i < length; ++i)
		pascalString[i] = szFilename[i - 1];
	pascalString[0] = strlen(szFilename);
			
	//	Create a File Specification Record, then create a File
	result = FSMakeFSSpec(0,0,pascalString,&fileSpec);	// return is meaningless, since the only possible error doesn't effect processing in this case
			
	switch(result) {
		case noErr:
				// we could dRes pFile here, but we are the only user
				result =FSpOpenDF(&fileSpec, fsRdPerm, (short *)phFile);
				if(result) return NCS_FILE_OPEN_FAILED;
				else return NCS_SUCCESS;
			break;
		default:
			    return NCS_SUCCESS;
		    break;
	}

#else	/* __POWERPC__ */

	int i,length, result;
	Str255		pascalString;
	//	We have a C string, we need a PASCAL string.
	length = strlen(szFilename) + 1;
	for(i = 1; i < length; ++i)
		pascalString[i] = szFilename[i - 1];
	pascalString[0] = strlen(szFilename);
		
	result =FSOpen(pascalString, 0, (short *)phFile);
	if(result) return TRUE;
	else return FALSE;

#endif	/* __POWERPC__ */
#elif defined PALM

	NCS_FILE_HANDLE hFile;
	Err eErr;
	UInt32 nMode = 0;
	
	if(hFile = (NCS_FILE_HANDLE)NCSMalloc(sizeof(NCS_FILE_HANDLE_STRUCT), TRUE)) {
		hFile->dbID = DmFindDatabase(0, szFilename);
		
		if(hFile->dbID) {
	   		Char nameP[dmDBNameLength];
	   		UInt16 attributes;
	   		UInt16 version;
	   		UInt32 crDate;
	   		UInt32 modDate;
	   		UInt32 bckUpDate;
	   		UInt32 modNum;
	   		LocalID appInfoID;
	   		LocalID sortInfoID;
	   		UInt32 type;
	   		UInt32 creator;
					
	   		DmDatabaseInfo(0, hFile->dbID, nameP,
	   					   &attributes, 
	   					   &version,
	   					   &crDate,
	   					   &modDate,
	   					   &bckUpDate,
	   					   &modNum,
	   					   &appInfoID,
	   					   &sortInfoID,
	   					   &type,
	   					   &creator);
	   					   
	   		if(creator == NCS_PALM_CREATOR_ID) {
	   			if(hFile->dbRef = DmOpenDatabase(0, hFile->dbID, dmModeReadOnly|dmModeShowSecret)) {
	   				UInt32 nRecords;
	   				UInt32 nTotalBytes;
	   				UInt32 nDataBytes;
	   				
	   				eErr = DmDatabaseSize(0, hFile->dbID, &nRecords, &nTotalBytes, &nDataBytes);
	   				
	   				if(eErr == errNone) {
	   					MemHandle hRecord;
	   					
	   					hFile->nRecords = nRecords;
	   					hFile->nDBSize = nDataBytes;
#ifdef NOTDEF	   					
	   					if(hRecord = DmGetRecord(hFile->dbRef, 0)) {
	   						MemPtr pData;
	   						
							if(pData = MemHandleLock(hRecord)) {
								hFile->nRecordSize = ((UINT16*)pData)[0];
							
								MemHandleUnlock(hRecord);
							}
							DmReleaseRecord(hFile->dbRef, 0, false);
						}
#endif
						*phFile = hFile;
						return(NCS_SUCCESS);
	   				}
	   				DmCloseDatabase(hFile->dbRef);
	   				return(NCSPalmGetNCSError(eErr));
	   			}
	   		}
		}
	} else {
		return(NCS_COULDNT_ALLOC_MEMORY);
	}
/*	
	if(iFlags & NCS_FILE_READ) nMode = fileModeReadOnly|fileModeAnyTypeCreator;
	if(iFlags & NCS_FILE_READ_WRITE) nMode = fileModeUpdate|fileModeAnyTypeCreator;
	if(iFlags & NCS_FILE_CREATE) nMode = fileModeReadWrite|fileModeAnyTypeCreator;
	if(iFlags & NCS_FILE_CREATE_UNIQUE) nMode = fileModeReadWrite|fileModeDontOverwrite|fileModeAnyTypeCreator;
	if(iFlags & NCS_FILE_APPEND) nMode = fileModeAppend|fileModeAnyTypeCreator;
	
	*phFile = FileOpen(0, (char*)szFilename, 0, 0, nMode, &eErr);
	
	return(NCSPalmGetNCSError(eErr));			   
*/					
#elif defined(POSIX)

	int flags = O_RDONLY;

	if(iFlags & NCS_FILE_READ) flags = O_RDONLY;
	if(iFlags & NCS_FILE_READ_WRITE) flags = O_RDWR;
	if(iFlags & NCS_FILE_CREATE) flags |= O_CREAT;
	if(iFlags & NCS_FILE_CREATE_UNIQUE) flags |= O_CREAT|O_EXCL;
	if(iFlags & NCS_FILE_APPEND) flags |= O_APPEND;

#if defined SOLARIS || (defined(HPUX) && !defined(__LP64__))
	// Enable 64bit!
	flags |= O_LARGEFILE;
#endif

#ifdef HPUX
	*phFile = open64((const char*)CHAR_STRING(szFilename), (int)flags);

#ifdef NOTDEF
	if (*phFile < 0) {
		fprintf(stderr, "Error opening file : %ld\n", errno); 
		if (errno == EOVERFLOW) {
			fprintf(stderr, "The named file is a regular file and the size "
                          "of the file cannot be represented correctly in an object of "
                          "size off_t.");
		}
	}
#endif

#else
	*phFile = open((const char*)CHAR_STRING(szFilename), (int)flags, S_IRUSR|S_IWUSR);
#endif
	if(*phFile != -1) {
		return(NCS_SUCCESS);
	} else {
		return(NCS_FILE_OPEN_FAILED);
	}

#else	/* SOLARIS||IRIX */
#error ERROR  EcwFileCreate() routine is not defined for this platform
#endif	/* WIN32 */
}
Exemplo n.º 20
0
// Save preferences previously set via ErrSet*() calls to a database.
// If something goes wrong, returns an error
// Possible errors:
//   memErrNotEnoughSpace - not enough memory to allocate needed structures
//   errors from Dm*() calls
Err PrefsStoreWriter::ErrSavePreferences()
{
    Err     err = errNone;
    long    blobSize;
    void *  prefsBlob = SerializeItems(_items, _itemsCount, &blobSize);
    if ( NULL == prefsBlob ) 
        return memErrNotEnoughSpace;

    DmOpenRef db = DmOpenDatabaseByTypeCreator(_dbType, _dbCreator, dmModeReadWrite);
    if (!db)
    {
        err = DmCreateDatabase(0, _dbName, _dbCreator, _dbType, false);
        if ( err)
            return err;

        db = DmOpenDatabaseByTypeCreator(_dbType, _dbCreator, dmModeReadWrite);
        if (!db)
            return DmGetLastErr();
    }

    // set backup bit on the database. code adapted from DataStore.cpp
    // DataStore::open()
    if (errNone == err)
    {
        LocalID localId;
        UInt16 cardNo;
        UInt16 attribs;
        err = DmOpenDatabaseInfo(db, &localId, NULL, NULL, &cardNo, NULL);
        if (errNone != err)
            goto Continue;
        err = DmDatabaseInfo(cardNo, localId, NULL, &attribs, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
        if (errNone != err)
            goto Continue;
        if (0 != attribs & dmHdrAttrBackup)
            goto Continue;
        attribs |= dmHdrAttrBackup;
        err = DmSetDatabaseInfo(cardNo, localId, NULL, &attribs, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
Continue:
        err = errNone;
    }

    UInt16    recNo = 0;
    UInt16    recsCount = DmNumRecords(db);
    MemHandle recHandle;
    Boolean   fRecordBusy = false;
    Boolean   fRecFound = false;
    void *    recData;
    long      recSize;
    while (recNo < recsCount)
    {
        recHandle = DmGetRecord(db, recNo);
        fRecordBusy = true;
        recData = MemHandleLock(recHandle);
        recSize = MemHandleSize(recHandle);
        if (IsValidPrefRecord(recData))
        {
            fRecFound = true;
            break;
        }
        MemPtrUnlock(recData);
        DmReleaseRecord(db, recNo, true);
        fRecordBusy = false;
        ++recNo;
    }

    if (fRecFound && blobSize>recSize)
    {
        /* need to resize the record */
        MemPtrUnlock(recData);
        DmReleaseRecord(db,recNo,true);
        fRecordBusy = false;
        recHandle = DmResizeRecord(db, recNo, blobSize);
        if ( NULL == recHandle )
            return DmGetLastErr();
        recData = MemHandleLock(recHandle);
        Assert( MemHandleSize(recHandle) == blobSize );        
    }

    if (!fRecFound)
    {
        recNo = 0;
        recHandle = DmNewRecord(db, &recNo, blobSize);
        if (!recHandle)
        {
            err = DmGetLastErr();
            goto CloseDbExit;
        }
        recData = MemHandleLock(recHandle);
        fRecordBusy = true;
    }

    err = DmWrite(recData, 0, prefsBlob, blobSize);
    MemPtrUnlock(recData);
    if (fRecordBusy)
        DmReleaseRecord(db, recNo, true);
CloseDbExit:
    // if had error before - preserve that error
    // otherwise return error code from DmCloseDatabase()
    if (err)
        DmCloseDatabase(db);
    else
        err = DmCloseDatabase(db);
    new_free( prefsBlob );
    return err;
}
Exemplo n.º 21
0
/***************************************************************************
 * Function: cryptSwitch
 * Description: handles changing the system password based upon the 
 * password change screen. Basically checks that current password is correct,
 * checks that the new password was entered correctly, then re-encrypts the
 * databases based upon the new password.
 * ************************************************************************/ 
static void 
cryptSwitch (int v) 
{
	
		// total number of records to re-write
	UInt16 totalAItems = DmNumRecordsInCategory (AccountDB, dmAllCategories);
	UInt16 totalSItems = DmNumRecordsInCategory (SystemDB, dmAllCategories);
	MemPtr pac = NULL, scratch = NULL, scratch2 = NULL;
	UInt16 i = 0, senc = 0, aenc = 0;
	MemHandle rH;
	char s[5], a[5];
	StripPrefType prefs;	
	UInt16 prefsSize, prefsVersion;

	FormType *preF = FrmGetActiveForm ();
	FormType *f = FrmInitForm (pleaseWait);
	FrmDrawForm (f);
	
		// re-encrypt the password 
	if ((rH = DmGetRecord (PasswordDB, 0)))	
	{
		if ((scratch = MemPtrNew (getSCSize(sizeof(md_hash)))))			
		{
			PackPassword (scratch, &NewSysPass);			
			writeRecord (scratch, rH);
			MemPtrFree (scratch);
		}
		DmReleaseRecord (PasswordDB, 0, true);
	}
	
		// loop through the systems and re-encrypt
	for (i = 0; i < totalSItems; i++)
	{
		System_old sys;
		if ((rH = DmGetRecord (SystemDB, i)))	
		{
			pac = MemHandleLock (rH);
			if ((scratch = MemPtrNew (MemPtrSize (pac))))	
			{	
					// decrypt the system with old password
				switch (v)	
				{
					case 0:
						UnpackSystem_old (&sys, pac, scratch, SysPass,
										MemHandleSize (rH), true, 1);
										
						scratch2 = MemPtrNew (getSystemSize((System *)&sys, true));
						break;
					case 1:
						UnpackSystem_old (&sys, pac, scratch, SysPass,
										MemHandleSize (rH), true, 2);
						scratch2 = MemPtrNew (getSystemSize ((System *)&sys,true) );
						break;
					case 2:
						UnpackSystem_old (&sys, pac, scratch, SysPass,
										MemHandleSize (rH), true, 0);
						scratch2 = MemPtrNew (getSystemSize ((System *)&sys, true ));
						break;
				}
				if (scratch2)				
				{			
					PackSystem(scratch2, *((System *) &sys), &NewSysPass, true);
					MemHandleUnlock (rH);
					writeRecord (scratch2, rH);
					senc++;
					MemPtrFree (scratch2);
				}
				MemPtrFree (scratch);
			}
			DmReleaseRecord (SystemDB, i, true);
		}
	}
	
		// loop through the accounts and re-encrypt
	for (i = 0; i < totalAItems; i++)	
	{
		Account_old ac;
		Account ac_new;
		if ((rH = DmGetRecord (AccountDB, i)))
			
		{
			pac = MemHandleLock (rH);
			if ((scratch = MemPtrNew (MemPtrSize (pac))))
				
			{
				
					// decrypt the system with old password
				switch (v)	
				{
					case 0:
						UnpackAccount_old(&ac, pac, scratch, SysPass,
										 MemHandleSize (rH), true, true, 1);
						ChangeAccountFormat(i, &ac, &ac_new);
						scratch2 = MemPtrNew (getAccountSize(&ac_new, true));
						break; 
					case 1:
						UnpackAccount_old (&ac, pac, scratch, SysPass,
										 MemHandleSize (rH), true, true, 2);
						ChangeAccountFormat(i, &ac, &ac_new);
						scratch2 = MemPtrNew (getAccountSize(&ac_new, true));
						break; 
					case 2:
						UnpackAccount_old(&ac, pac, scratch, SysPass,
										 MemHandleSize (rH), true, true, 0);
						ChangeAccountFormat(i, &ac, &ac_new);
						scratch2 = MemPtrNew (getAccountSize(&ac_new,true));
						break; 
				}

				if (scratch2)
				{
					PackAccount(scratch2, ac_new, &NewSysPass, true);
					MemHandleUnlock (rH);
					writeRecord (scratch2, rH);
					aenc++;
					MemPtrFree (scratch2);
				}
				MemPtrFree (scratch);
			}
			DmReleaseRecord (AccountDB, i, true);
		}
	}
	FrmEraseForm (f);
	FrmDeleteForm (f);
	FrmSetActiveForm (preF);
		// close databases.
	DmCloseDatabase (SystemDB);
	DmCloseDatabase (AccountDB);
	DmCloseDatabase (PasswordDB);

	{
		UInt16 cardNo;
		UInt32 type;
		LocalID dbID;
		DmSearchStateType search;

		type = systemDBType;
		DmGetNextDatabaseByTypeCreator(true, &search, systemDBTypeOld, 
			StripCreator, true, &cardNo, &dbID);
		DmSetDatabaseInfo(cardNo, dbID, NULL, NULL, NULL, NULL, NULL,
			NULL, NULL, NULL, NULL, &type, NULL);
	
		type = accountDBType;
		DmGetNextDatabaseByTypeCreator(true, &search, accountDBTypeOld, 
			StripCreator, true, &cardNo, &dbID);
		DmSetDatabaseInfo(cardNo, dbID, NULL, NULL, NULL, NULL, NULL,
			NULL, NULL, NULL, NULL, &type, NULL);

		type = passwordDBType;
		DmGetNextDatabaseByTypeCreator(true, &search, passwordDBTypeOld, 
			StripCreator, true, &cardNo, &dbID);
		DmSetDatabaseInfo(cardNo, dbID, NULL, NULL, NULL, NULL, NULL,
			NULL, NULL, NULL, NULL,  &type, NULL);

	}

	prefsSize = sizeof (StripPrefType);
	prefsVersion = PrefGetAppPreferences (StripCreator, StripPrefID, &prefs, &prefsSize, true);
    if  (prefsVersion != StripVersionNumber) {
        prefs.smart_beaming = false;
        PrefSetAppPreferences (StripCreator, StripPrefID, StripVersionNumber,
            &prefs, sizeof (StripPrefType), true);
        prefsVersion = PrefGetAppPreferences (StripCreator, StripPrefID,
            &prefs, &prefsSize, true);
	} 

	StrIToA (s, senc);
	StrIToA (a, aenc);
	FrmCustomAlert (infoDialog, s, a, NULL);

	StopApplication ();
	SysReset ();
}