Beispiel #1
0
static void LoadPreferencesNoahPro(AppContext* appContext)
{
    DmOpenRef    db;
    UInt         recNo;
    void *       recData;
    MemHandle    recHandle;
    UInt         recsCount;
    Boolean      fRecFound = false;

    appContext->fFirstRun = true;
    db = DmOpenDatabaseByTypeCreator(NOAH_PREF_TYPE, NOAH_PRO_CREATOR, dmModeReadWrite);
    if (!db) return;
    recsCount = DmNumRecords(db);
    for (recNo = 0; (recNo < recsCount) && !fRecFound; recNo++)
    {
        recHandle = DmQueryRecord(db, recNo);
        recData = MemHandleLock(recHandle);
        if ( (MemHandleSize(recHandle)>=PREF_REC_MIN_SIZE) && IsValidPrefRecord( recData ) )
        {
            LogG( "LoadPreferencesNoahPro(), found prefs record" );
            fRecFound = true;
            appContext->fFirstRun = false;
            DeserializePreferencesNoahPro(appContext, (unsigned char*)recData, MemHandleSize(recHandle) );
        }
        MemPtrUnlock(recData);
    }
    DmCloseDatabase(db);
}
void GlbReleaseRecord(UInt16 index, UInt16 id) {
	if (gVars->globals[id]) {
		MemHandle recordH = DmQueryRecord(gVars->globals[id], index);
		if (recordH)
			MemHandleUnlock(recordH);
	}
}
Beispiel #3
0
/*----------------------------------------CIRexxApp::copyScriptFromFindResult-+
|                                                                             |
+----------------------------------------------------------------------------*/
void CIRexxApp::copyScriptFromFindResult(GoToParamsPtr pGoToParams)
{
   Err err;
   LocalID dbID;
   UInt16 cardNo = 0;
   DmOpenRef dbP;
   DmSearchStateType searchState;
   MemHandle hRecord;

   if ((err = DmGetNextDatabaseByTypeCreator(
       true, &searchState, 'data', CREATORID, true, &cardNo, &dbID)) != errNone) {
      return;
   }
   if ((dbP = DmOpenDatabase(cardNo, dbID, dmModeReadOnly)) == 0) {
      return;
   }
   if (!(hRecord = DmQueryRecord(dbP, pGoToParams->recordNum))) {
      DmCloseDatabase(dbP);
      return;
   }
   Char * p = (char *)MemHandleLock(hRecord);
   UInt32 size = MemHandleSize(hRecord);
   if (p[size - 1] == '\0') { --size; }
   emptyScript();
   appendScript(p, size);
   MemHandleUnlock(hRecord);
   DmCloseDatabase(dbP);
   return;
}
Beispiel #4
0
/* Delete a bookmark for a given word in a bookmark database indicated by sortType */
static Err DeleteBookmarkInDB(AppContext* appContext, BookmarkSortType sortType, char *word)
{
    Err          err;
    UInt16       recsCount, i;
    MemHandle    recHandle;
    char *       wordInRecord;

    err = OpenBookmarksDB(appContext, sortType);
    if ( errNone != err )
        return err;

    recsCount = DmNumRecords(appContext->bookmarksDb);
    for (i = 0; i < recsCount; i++)
    {
        recHandle = DmQueryRecord(appContext->bookmarksDb, i);
        if (!recHandle)
        {
            err = DmGetLastErr();
            goto OnError;
        }

        wordInRecord = (char*)MemHandleLock(recHandle);
        Assert(wordInRecord);
        if (0 == StrCompare(wordInRecord, word))
        {
            MemHandleUnlock(recHandle);
            DmRemoveRecord(appContext->bookmarksDb, i);
            break;
        }
        MemHandleUnlock(recHandle);
    }
OnError:
    CloseBookmarksDB(appContext);
    return err;
}
Beispiel #5
0
static void
ExamDelete(void)
{
  MemHandle mex, m;
  ExamDBRecord *ex;
  UInt16 index=0, pressedButton=0;
  Char *courseName, timeTemp[timeStringLength], dateTemp[longDateStrLength];

  DmFindRecordByID(DatabaseGetRefN(DB_MAIN), gExamsLastSelRowUID, &index);
  mex = DmQueryRecord(DatabaseGetRefN(DB_MAIN), index);
  ex = (ExamDBRecord *)MemHandleLock(mex);

  m=MemHandleNew(1);
  CourseGetName(ex->course, &m, true);
  courseName = MemHandleLock(m);

  DateToAscii(ex->date.month, ex->date.day, ex->date.year+MAC_SHIT_YEAR_CONSTANT, PrefGetPreference(prefLongDateFormat), dateTemp);
  TimeToAscii(ex->begin.hours, ex->begin.minutes, PrefGetPreference(prefTimeFormat), timeTemp);

  pressedButton = FrmCustomAlert(ALERT_ex_dodel, courseName, dateTemp, timeTemp);

  MemHandleUnlock(m);
  MemHandleFree(m);
  MemHandleUnlock(mex);

  if (pressedButton == 0) {
    // OK, the user really wants us to delete the record
    NoteDelete(&index);
    DmRemoveRecord(DatabaseGetRefN(DB_MAIN), index);
    gExamsSelRow=0;
    FrmUpdateForm(FORM_exams, frmRedrawUpdateCode);
  }
}
void *GlbGetRecord(UInt16 index, UInt16 id) {
	if (gVars->globals[id]) {
		MemHandle recordH = DmQueryRecord(gVars->globals[id], index);
		if (recordH)
			return MemHandleLock(recordH);
	}
	return NULL;
}
Beispiel #7
0
static void
TableDrawData(void *table, Int16 row, Int16 column, RectangleType *bounds)
{
  UInt16 index=TblGetRowID(table, row);
  ExamDBRecord *ex;
  MemHandle mex;
  RGBColorType fore={0x00, 0x00, 0x00, 0x00}, back={0x00, 0xFF, 0xFF, 0xFF};

  if (! TblRowUsable(table, row)) return;
  
  TNSetBackColorRGB(&back, NULL);
  TNSetForeColorRGB(&back, NULL);
  WinDrawRectangle(bounds, 0);

  mex = DmQueryRecord(DatabaseGetRefN(DB_MAIN), index);
  ex = (ExamDBRecord *)MemHandleLock(mex);

  if (column == EXCOL_COURSE) {
    Char *temp;
    MemHandle m=MemHandleNew(1);
    CourseGetName(ex->course, &m, true);
    temp = MemHandleLock(m);

    TNSetForeColorRGB(&fore, NULL);
    TNDrawCharsToFitWidth(temp, bounds);

    MemHandleUnlock(m);
    MemHandleFree(m);
  } else if (column == EXCOL_NOTE) {
    if (ex->note) {
      Char noteSymb[2] = { GADGET_NOTESYMBOL, 0 };
      FontID oldFont = FntSetFont(symbolFont);

      TNDrawCharsToFitWidth(noteSymb, bounds);
      FntSetFont(oldFont);
    }
  } else if (column == EXCOL_DATE) {
    Char dateTemp[dateStringLength];
    DateToAscii(ex->date.month, ex->date.day, ex->date.year+MAC_SHIT_YEAR_CONSTANT, PrefGetPreference(prefDateFormat), dateTemp);
    TNDrawCharsToFitWidth(dateTemp, bounds);
  } else if (column == EXCOL_TIME) {
    Char timeTemp[timeStringLength];
    TimeToAscii(ex->begin.hours, ex->begin.minutes, PrefGetPreference(prefTimeFormat), timeTemp);
    TNDrawCharsToFitWidth(timeTemp, bounds);
  }


  if (ex->flags & EX_FLAG_DONE) {
    RGBColorType red = {0x00, 0xFF, 0x00, 0x00}, old;
    Int16 yCoord=bounds->topLeft.y+(bounds->extent.y / 2);
    TNSetForeColorRGB(&red, &old);
    WinDrawLine(bounds->topLeft.x, yCoord, bounds->topLeft.x+bounds->extent.x, yCoord);
    TNSetForeColorRGB(&old, NULL);
  }

  MemHandleUnlock(mex);
}
Beispiel #8
0
/* Save a given word in bookmarks database. */
Err AddBookmark(AppContext* appContext, char * word)
{
    Err                 err;
    UInt16              pos;
    Boolean             fWordAlreadyBookmarked;
    MemHandle           recHandle;
    char *              wordInRec;
    BookmarkSortType    currDbOpen;

    currDbOpen = appContext->currBookmarkDbType;

    // 1. See if we already have the record in bookmarks.
    //    We assume that if the record wasn't found in sorted-by-name database, it doesn't exist in the other.
    //    The sorted-by-name database is quicker to scan, because we can use binary search.

    err = OpenBookmarksDB(appContext, bkmSortByName);
    if (errNone != err)
        goto Exit;

    pos = DmFindSortPosition(appContext->bookmarksDb, word, NULL, (DmComparF *) BookmarksByNameCompare, 0);
    
    fWordAlreadyBookmarked = false;
    // DmFindSortPosition returns the position there the new record should be placed
    // so if the record exist its position is (pos - 1)
    recHandle = DmQueryRecord(appContext->bookmarksDb, pos>0 ? pos-1 : pos);
    // it's ok if we don't get handle - this might be an empty database
    if (recHandle)
    {
        wordInRec = (char*)MemHandleLock(recHandle);
        if (0 == StrCompare(word, wordInRec))
            fWordAlreadyBookmarked = true;
        MemHandleUnlock(recHandle);
    }
    
    if (fWordAlreadyBookmarked)
    {
        err = errNone;
        goto Exit;
    }

    // 2. If we haven't found the record, we add it to databases

    WriteWordInRecord(appContext->bookmarksDb, pos, word);
    CloseBookmarksDB(appContext);

    err = OpenBookmarksDB(appContext, bkmSortByTime);
    if (errNone != err)
        goto Exit;
    // the record must be put chronogically, so we add it at the beginning of the database
    WriteWordInRecord(appContext->bookmarksDb, 0, word);
    CloseBookmarksDB(appContext);

Exit:
    if (bkmInvalid != currDbOpen)
        OpenBookmarksDB(appContext, currDbOpen);
    return err;
}
Beispiel #9
0
/**************************************************************************
 * Function: getHashFromAccountIndex
 * Description: returns the unique has for the account located at a given
 * index. Remember that the first few bytes of an account record are the
 * system ID of the account.  Just skip these an pop off the AID.
 * ************************************************************************/ 
md_hash * getHashFromAccountIndex (DmOpenRef AccountDB, UInt16 index) {
	static md_hash ret;
	MemHandle rec = DmQueryRecord (AccountDB, index);
	if (rec) {
		MemPtr buff = MemHandleLock (rec);
		MemMove (ret, buff+sizeof(UInt16)+sizeof(UInt16), sizeof (ret));
		MemHandleUnlock (rec);
	}
	return &ret;
}
Beispiel #10
0
/**************************************************************************
 * Function: getAIDFromAccountIndex
 * Description: returns the account id for the account located at a given
 * index. Remember that the first few bytes of an account record are the
 * system ID of the account.  Just skip these an pop off the AID.
 * ************************************************************************/ 
UInt16 getAIDFromAccountIndex(DmOpenRef AccountDB, UInt16 index) {
	UInt16 ret = 0;
	MemHandle rec = DmQueryRecord (AccountDB, index);
	if (rec) {
		MemPtr buff = MemHandleLock (rec);
		MemMove (&ret, buff+sizeof(ret), sizeof (ret));
		MemHandleUnlock (rec);
	}
	return ret;
}
Beispiel #11
0
/******************************************************************************
 * Function: getSIDForSystemIndex
 * Description: this will get the system id for a given index in the
 * system database.
 * ****************************************************************************/ 
UInt16 getSIDForSystemIndex (DmOpenRef SystemDB, UInt16 i) {
	UInt16 ret;
	MemHandle rec = DmQueryRecord (SystemDB, i);
	if (rec) {
		MemPtr buff = MemHandleLock (rec);
		MemMove (&ret, buff, sizeof (ret));
		MemHandleUnlock (rec);
	}
	return ret;
}
/*
** Load the record data (flags, ...) - but not the picture
*/
static void LoadRecordData(void) {
  MemHandle t = NULL;
  MemPtr ptr = NULL;
  UInt16 attr = 0;
  UInt32 highDataOffset = 0;
  Int16 len = 0;

  PRINT("Loading Record Data for %hd", p.dbI);

  /* Clear unmasked flag */
  d.unmaskedCurrentRecord = false;

  /* Open and lock the record */
  t = DmQueryRecord(d.dbR, p.dbI);
  if (!t) abort();
  ptr = MemHandleLock(t);

  /* Is the record private? */
  DmRecordInfo(d.dbR, p.dbI, &attr, NULL, NULL);
  d.record_private = attr & dmRecAttrSecret;

  /* Read the header data */
  MemMove(&d.record, ptr, sizeof(DiddleBugRecordType));

  /* Read the additional alarm info */
  highDataOffset = sketchDataOffset + d.record.sketchLength;

  len = StrLen((Char*)(ptr + highDataOffset)) + 1; /* +1 for null char */
  if (d.record_name) MemHandleFree(d.record_name);
  d.record_name = MemHandleNew(len);
  ASSERT(d.record_name);
  MemMove(MemHandleLock(d.record_name), ptr + highDataOffset, len);
  MemHandleUnlock(d.record_name);

  highDataOffset += len;

  len = StrLen((Char*)(ptr + highDataOffset)) + 1; /* +1 for null char */
  if (d.record_note) MemHandleFree(d.record_note);
  d.record_note = MemHandleNew(len);
  ASSERT(d.record_note);
  MemMove(MemHandleLock(d.record_note), ptr + highDataOffset, len);
  MemHandleUnlock(d.record_note);

  highDataOffset += len;

  /* Clear old data since there may not be an extra-data block yet */
  MemSet(&d.record_sound, sizeof(AlarmSoundInfoType), 0);
  d.record_sound.listIndex = -1; /* default */
  /* Read new extra-data (if it exists and is from a compatible version) */
  if (d.record.extraLength == sizeof(AlarmSoundInfoType))
    MemMove(&d.record_sound, ptr + highDataOffset, d.record.extraLength);

  /* Unlock record */
  MemHandleUnlock(t);
}
Beispiel #13
0
// Open preferences database and find a record that contains preferences.
// Return errNone if opened succesfully, otherwise an error:
//   psErrNoPrefDatabase - pref database couldn't be found
// devnote: it scans through all records even though we only store preferences
// in one record because I want to be able to use preferences database used
// in earlier versions of Noah Pro/Thes.
Err PrefsStoreReader::ErrOpenPrefsDatabase()
{
    if (_db)
    {
        Assert(_recHandle);
        Assert(_recData);
        return errNone;
    }

    // we already tried to open the database but couldn't, so don't try again
    if (_fDbNotFound)
        return psErrNoPrefDatabase;

    LocalID dbId;
    Err err = ErrFindDatabaseByNameTypeCreator(_dbName, _dbType, _dbCreator, &dbId);
    if (dmErrCantFind==err)
    {
        err = psErrNoPrefDatabase;
        goto ExitAndMarkNotFound;
    }
    if (err)
        goto ExitAndMarkNotFound;
    Assert(0!=dbId);

    _db = DmOpenDatabase(0, dbId, dmModeReadWrite);
    if (!_db)
    {
        err = DmGetLastErr();
        Assert(err);
        goto ExitAndMarkNotFound;
    }

    UInt16 recsCount = DmNumRecords(_db);
    for (UInt16 recNo = 0; recNo < recsCount; recNo++)
    {
        _recHandle = DmQueryRecord(_db, recNo);
        _recData = (unsigned char*)MemHandleLock(_recHandle);
        if ( (MemHandleSize(_recHandle)>=4) && FValidPrefsStoreRecord(_recData) )
        {
            // we found the record with prefernces so remember _recData and _recHandle
            // those must be freed in destructor
            return errNone;
        }
        MemHandleUnlock(_recHandle);
        _recHandle = NULL;
    }

    DmCloseDatabase(_db);
    _db = 0;
    err = psErrNoPrefDatabase;
ExitAndMarkNotFound:
    _fDbNotFound = true;
    return err;
}
Beispiel #14
0
static Boolean
CourseListHandleSelection(void)
{
  MemHandle m, mWebsite, mEmail, old;
  CourseDBRecord c;
  FieldType *fldWebsite, *fldEmail;
  Char *buffer;
  
  m = DmQueryRecord(DatabaseGetRefN(DB_MAIN), gCourseInd[LstGetSelection(GetObjectPtr(LIST_courses))]);
  if (! m)  return true;
  UnpackCourse(&c, MemHandleLock(m));
  fldWebsite = GetObjectPtr(FIELD_cl_website);
  fldEmail = GetObjectPtr(FIELD_cl_email);

  if (StrLen(c.website) == 0) {
    mWebsite = MemHandleNew(4);
    buffer=MemHandleLock(mWebsite);
    MemSet(buffer, 4, 0);
    StrCopy(buffer, "-?-");
  } else {
    mWebsite = MemHandleNew(StrLen(c.website)+1);
    buffer = MemHandleLock(mWebsite);
    MemSet(buffer, StrLen(c.website)+1, 0);
    StrCopy(buffer, c.website);
  }
  MemHandleUnlock(mWebsite);
  old = FldGetTextHandle(fldWebsite);
  FldSetTextHandle(fldWebsite, mWebsite);
  if (old != NULL)  MemHandleFree(old); 
  FldDrawField(fldWebsite);

  if (StrLen(c.teacherEmail) == 0) {
    mEmail = MemHandleNew(4);
    buffer = MemHandleLock(mEmail);
    MemSet(buffer, 4, 0);
    StrCopy(buffer, "-?-");
  } else {
    mEmail = MemHandleNew(StrLen(c.teacherEmail)+1);
    buffer = MemHandleLock(mEmail);
    MemSet(buffer, StrLen(c.teacherEmail)+1, 0);
    StrCopy(buffer, c.teacherEmail);
  }
  MemHandleUnlock(mEmail);
  old = FldGetTextHandle(fldEmail);
  FldSetTextHandle(fldEmail, mEmail);
  if (old != NULL)  MemHandleFree(old); 
  FldDrawField(fldEmail);

  MemHandleUnlock(m);

  return false;
}
Beispiel #15
0
static void
ExamBeam(void)
{
  MemHandle mex;
  ExamDBRecord *ex;
  UInt16 index=0;

  DmFindRecordByID(DatabaseGetRefN(DB_MAIN), gExamsLastSelRowUID, &index);
  mex = DmQueryRecord(DatabaseGetRefN(DB_MAIN), index);
  ex = (ExamDBRecord *)MemHandleLock(mex);

  MemHandleUnlock(mex);

  BeamCourseByCID(ex->course);
}
Beispiel #16
0
/**************************************************************************
 * Function: getSystemFromIndex
 * Description: based upon a system database index, this will locate the
 * system for that index, unpack and decrypt it and initialize s
 * ************************************************************************/ 
void getSystemFromIndex (DmOpenRef SystemDB, md_hash * SysPass, UInt16 index, MemHandle tmp, System * s) {
	MemHandle rec = DmQueryRecord (SystemDB, index);
	if (rec) {
		MemPtr scratch, buff = MemHandleLock (rec);
		
			/*	resize the buffer */
		if (MemHandleResize (tmp, MemPtrSize (buff)) == 0) {
			scratch = MemHandleLock (tmp);
			
			/*	unpack and decrypt the account */
			UnpackSystem (s, buff, scratch, SysPass, MemHandleSize (rec), true); 
		}
		MemHandleUnlock (rec);
	}
}
Beispiel #17
0
/**************************************************************************
 * Function: getAccountFromIndex
 * Description: based upon an account index, this will locate the
 * account for that index, unpack and decrypt it and initialize acc
 * ************************************************************************/ 
void getAccountFromIndex (DmOpenRef AccountDB, md_hash * SysPass, UInt16 index, MemHandle tmp, Account * acc) {
	/*	query the record from the database */
	MemHandle rec = DmQueryRecord (AccountDB, index);
	
	if (rec){
		MemPtr scratch, buff = MemHandleLock (rec);
		
		/*	resize buffer */
		if (MemHandleResize (tmp, MemPtrSize (buff)) == 0) {
			scratch = MemHandleLock (tmp);
			
			/*	unpack the account */
			UnpackAccount (acc, buff, scratch, SysPass, MemHandleSize (rec), true, true);
		}
		MemHandleUnlock (rec);
	}
}
Beispiel #18
0
UInt8
CourseGetType(UInt16 courseID)
{
  MemHandle m;
  UInt16 index=0;

  if (CourseGetIndex(DatabaseGetRefN(DB_MAIN), DatabaseGetCat(), courseID, &index)) {      
    // Found it, put it into the string
    CourseDBRecord c;
    MemPtr mp;

    m = DmQueryRecord(DatabaseGetRefN(DB_MAIN), index);
    mp = MemHandleLock(m);
    UnpackCourse(&c, mp);
    MemHandleUnlock(m);
    return c.ctype;
  }

  return 0;
}
Beispiel #19
0
/************************************************************
 *
 *  FUNCTION: ApptGetRecord
 *
 *  DESCRIPTION: Get a record from a Appointment Database
 *
 *  PARAMETERS: database pointer
 *                  database index
 *                  database record
 *
 *  RETURNS: ##0 if successful, errorcode if not
 *
 *  CREATED: 1/25/95 
 *
 *  BY: Roger Flores
 *
 *************************************************************/
Err ApptGetRecord (DmOpenRef dbP, UInt16 index, ApptDBRecordPtr r,
                   MemHandle * handleP) {
    MemHandle handle;
    ApptPackedDBRecordPtr src;

    handle = DmQueryRecord(dbP, index);
    ErrFatalDisplayIf(DmGetLastErr(), "Error Querying record");

    src = (ApptPackedDBRecordPtr) MemHandleLock (handle);

    if (DmGetLastErr()) {
        *handleP = 0;
        return DmGetLastErr();
    }

    ApptUnpack(src, r);

    *handleP = handle;
    return 0;
}
Beispiel #20
0
static Int16
LoadSMF(SndMidiListItemType midi, NoteListPtr list)
{
  Err err = false;
  DmOpenRef dbP;
  UInt16 recIndex;
  MemHandle midiH;

  debugPrintf("LoadSMF: open db cardNo=%d dbID=%d for readOnly\n",
	      midi.cardNo, midi.dbID);

  dbP = DmOpenDatabase (midi.cardNo, midi.dbID, dmModeReadOnly);
  if (!dbP)
    err = true;

  if (!err)
    err = DmFindRecordByID(dbP, midi.uniqueRecID, &recIndex);

  debugPrintf("LoadSMF: find record with uniqueRecID=%ld\n",
	      midi.uniqueRecID);

  if (!err) {
    midiH = DmQueryRecord (dbP, recIndex);
    if (!midiH)
      err = true;
  }

  debugPrintf("LoadSMF: midiH=%lx size=%ld\n",
	      midiH, MemHandleSize(midiH));

  if (!err)
    smfutils_load(midiH, list);

  if (dbP)
    DmCloseDatabase (dbP);

  if (err)
    ErrDisplay ("LoadSMF(): error occure in function.");
  return true;
}
static void MusicFormInit(UInt16 index) {
	TabType *tabP;
	FormType *frmP = FrmGetActiveForm();

	if (index != dmMaxRecordIndex) {
		MemHandle recordH = NULL;
		GameInfoType *ogameInfoP;

		recordH = DmQueryRecord(gameDB, index);
		ogameInfoP = (GameInfoType *)MemHandleLock(recordH);
		
		if (!ogameInfoP) {
			FrmCustomAlert(FrmErrorAlert, "An error occured.",0,0);
			return;
		}

		gameInfoP = (GameInfoType *)MemPtrNew(sizeof(GameInfoType));
		MemMove(gameInfoP, ogameInfoP, sizeof(GameInfoType));
		MemHandleUnlock(recordH);

	} else {
		FrmCustomAlert(FrmWarnAlert, "Select an entry first.",0,0);
		FrmReturnToMain();
		return;
	}

	tabP = TabNewTabs(3);
	TabAddContent(&frmP, tabP, "Sound", TabMusicForm);
	TabAddContent(&frmP, tabP, "Volume", TabVolumeForm);
	TabAddContent(&frmP, tabP, "Audio CD", TabAudioCDForm);

	MusicTabInit();
	AudioCDTabInit();
	VolumeTabInit();

	FrmDrawForm(frmP);
	TabSetActive(frmP, tabP, lastTab);

	myTabP = tabP;
}
Beispiel #22
0
static void BookmarksListDrawFunc(Int16 itemNum, RectangleType * bounds, char **data)
{
    Int16       stringWidthP = 160; // max width of the string in the list selection window
    Int16       stringLenP;
    Boolean     truncatedP = false;
    MemHandle   recHandle;
    char *      str;
    AppContext* appContext=GetAppContext();

    Assert(itemNum >= 0);
    
    recHandle = DmQueryRecord(appContext->bookmarksDb, itemNum);
    Assert(recHandle); // no reason it shouldn't work
    if (recHandle)
    {
        str = (char*)MemHandleLock(recHandle);
        stringLenP = StrLen(str);
        FntCharsInWidth(str, &stringWidthP, &stringLenP, &truncatedP);
        WinDrawChars(str, stringLenP, bounds->topLeft.x, bounds->topLeft.y);
        MemHandleUnlock(recHandle);
    }
}
Beispiel #23
0
static void
ExamDetailsFormInit(FormType *frm)
{
  UInt16 selectedCourse=0;
  ListType *course;
  ControlType *course_tr, *date_tr, *time_tr;

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

  gExamDetailsNumCourses = CountCourses();

  gExamDetailsItemList = (Char **) MemPtrNew(gExamDetailsNumCourses * sizeof(Char *));
  gExamDetailsItemIDs = (UInt16 *) MemPtrNew(gExamDetailsNumCourses * sizeof(UInt16));
  gExamDetailsItemInd = (UInt16 *) MemPtrNew(gExamDetailsNumCourses * sizeof(UInt16));

  if (gExamsLastSelRowUID == 0) {
    // ADD
    DateTimeType dt;

    selectedCourse = CourseListGen(gExamDetailsItemList, gExamDetailsItemIDs, gExamDetailsItemInd, gExamDetailsNumCourses, 0, CLIST_SEARCH_INDEX);

    TimSecondsToDateTime(TimGetSeconds(), &dt);
    gExamDetailsDate.year=dt.year-MAC_SHIT_YEAR_CONSTANT;

    gExamDetailsDate.month=dt.month;
    gExamDetailsDate.day=dt.day;

    gExamDetailsBegin.hours=14;
    gExamDetailsBegin.minutes=0;

    gExamDetailsEnd.hours=15;
    gExamDetailsEnd.minutes=30;

  } else {
    MemHandle mex, mRoom, old;
    ExamDBRecord *ex;
    UInt16 index=0;
    Char *buffer;
    FieldType *fldRoom;

    fldRoom=GetObjectPtr(FIELD_exd_room);

    DmFindRecordByID(DatabaseGetRefN(DB_MAIN), gExamsLastSelRowUID, &index);

    mex = DmQueryRecord(DatabaseGetRefN(DB_MAIN), index);
    ex = (ExamDBRecord *)MemHandleLock(mex);

    selectedCourse = CourseListGen(gExamDetailsItemList, gExamDetailsItemIDs, gExamDetailsItemInd, gExamDetailsNumCourses, ex->course, CLIST_SEARCH_ID);

    gExamDetailsDate.year=ex->date.year;
    gExamDetailsDate.month=ex->date.month;
    gExamDetailsDate.day=ex->date.day;

    gExamDetailsBegin.hours=ex->begin.hours;
    gExamDetailsBegin.minutes=ex->begin.minutes;

    gExamDetailsEnd.hours=ex->end.hours;
    gExamDetailsEnd.minutes=ex->end.minutes;

    // Copy contents to the memory handle
    mRoom=MemHandleNew(StrLen(ex->room)+1);
    buffer=(Char *)MemHandleLock(mRoom);
    MemSet(buffer, MemPtrSize(buffer), 0);
    StrNCopy(buffer, ex->room, StrLen(ex->room));
    MemHandleUnlock(mRoom);

    // Load fields
    old = FldGetTextHandle(fldRoom);
    FldSetTextHandle(fldRoom, mRoom);
    if (old != NULL)    MemHandleFree(old); 

    MemHandleUnlock(mex);
  }


  LstSetListChoices(course, gExamDetailsItemList, gExamDetailsNumCourses);
  if (gExamDetailsNumCourses < 5)  LstSetHeight(course, gExamDetailsNumCourses);
  else                 LstSetHeight(course, 5);
  LstSetSelection(course, selectedCourse);
  CtlSetLabel(course_tr, LstGetSelectionText(course, selectedCourse));

  ExamDetailsSetTriggers(date_tr, time_tr);
  EditTimeSetSelectorText(time_tr, &gExamDetailsBegin, &gExamDetailsEnd, gExamDetailsTimeTrigger);

}
Beispiel #24
0
Boolean StartScummVM() {
	Char **argvP;
	UInt8 lightspeed, argc	= 0;
	UInt32 stackSize;
	Boolean toLauncher, direct, isARM;
	UInt8 engine;
	Char num[6];

	UInt16 index = GamGetSelected();

	argvP = ArgsInit();
	direct = false;

	// start command line (exec name)
	ArgsAdd(&argvP[argc], "-", NULL, &argc);

	// no game selected
	if (index == dmMaxRecordIndex) {
		ListPtr listP;
		UInt16 whichButton;
		
		// init form
		FormPtr frmP = FrmInitForm(EngineForm);
		listP = (ListType *)FrmGetObjectPtr(frmP, FrmGetObjectIndex(frmP, EngineListList));
		itemsText = (Char **)MemPtrNew(ENGINE_COUNT * sizeof(Char *));
		
		for (int i = 0; i < ENGINE_COUNT; i++)
			itemsText[i] = (Char *)engines[i].nameP;
			
		LstSetListChoices (listP, itemsText, ENGINE_COUNT);
		LstSetSelection(listP, 0);	
		
		whichButton = FrmDoDialog(frmP);
		engine = LstGetSelection(listP);

		FrmDeleteForm(frmP);
		MemPtrFree(itemsText);
		itemsText = NULL;
		
		if (whichButton == EngineCancelButton) {
			if (bDirectMode) {
				// and force exit if nothing selected
				EventType event;
				event.eType = keyDownEvent;
				event.data.keyDown.chr = vchrLaunch;
				event.data.keyDown.modifiers = commandKeyMask;
				EvtAddUniqueEventToQueue(&event, 0, true);
			}
			// free args
			ArgsFree(argvP);
			return false;
		}

		// default values
		if (bDirectMode)
			gPrefs->card.volRefNum = parseCards();	// always use the first removable card available (?)
		gVars->filter		= true;
		gVars->palmVolume	= 50;
		gVars->fmQuality	= FM_QUALITY_INI;
		direct = true;

	// somthing selected
	} else {
		Char pathP[256];
		MemHandle recordH;
		GameInfoType *gameInfoP;

		recordH = DmQueryRecord(gameDB,index);
		gameInfoP = (GameInfoType *)MemHandleLock(recordH);
		engine = gameInfoP->engine;

		// build path
		StrCopy(pathP,"/Palm/Programs/ScummVM/Games/");
		if (gameInfoP->pathP[0] == '/')
			StrCopy(pathP, gameInfoP->pathP);
		else if (!(gameInfoP->pathP[0] == '.' && StrLen(gameInfoP->pathP) == 1))
			StrCat(pathP, gameInfoP->pathP);

		// path
		ArgsAdd(&argvP[argc], "-p", pathP, &argc);

		// language
		if (gameInfoP->language > 0) {
			const Char *lang = "zh\0cz\0gb\0en\0fr\0de\0hb\0it\0jp\0kr\0pl\0pt\0ru\0es\0se\0";
			ArgsAdd(&argvP[argc], "-q", (lang + (gameInfoP->language - 1) * 3), &argc);
		}

		// fullscreen ?
		if (gameInfoP->fullscreen)
			ArgsAdd(&argvP[argc], "-f", NULL, &argc);

		// aspect-ratio ?
		ArgsAdd(&argvP[argc], (gameInfoP->aspectRatio ? "--aspect-ratio" : "--no-aspect-ratio"), NULL, &argc);

		// gfx mode
		gVars->filter = gameInfoP->filter;

		switch (gameInfoP->renderMode) {
			case 1:
				ArgsAdd(&argvP[argc], "--render-mode=", "amiga", &argc);
				break;
			case 2:
				ArgsAdd(&argvP[argc], "--render-mode=", "cga", &argc);
				break;
			case 3:
				ArgsAdd(&argvP[argc], "--render-mode=", "ega", &argc);
				break;
			case 4:
				ArgsAdd(&argvP[argc], "--render-mode=", "hercAmber", &argc);
				break;
			case 5:
				ArgsAdd(&argvP[argc], "--render-mode=", "hercGreen", &argc);
				break;
		}		

		switch (gameInfoP->gfxMode)	{
			case 1:
				ArgsAdd(&argvP[argc], "-g", "wide", &argc);
				break;
			default:
				ArgsAdd(&argvP[argc], "-g", "1x", &argc);
				break;
		}

		// load state
		if (gameInfoP->autoLoad) {
			StrIToA(num, gameInfoP->loadSlot);
			ArgsAdd(&argvP[argc], "-x", num, &argc);
		}
		// boot script parameter
		if (gameInfoP->bootParam) {
			StrIToA(num, gameInfoP->bootValue);
			ArgsAdd(&argvP[argc], "-b", num, &argc);
		}
		// not a PC version
		if (gameInfoP->setPlatform) {
			static const char *platform[] = {
				"3do",
				"acorn",
				"amiga",
				"atari",
				"c64",
				"pc",
				"fmtowns",
				"linux",
				"mac",
				"nes",
				"segacd",
				"windows"
			};
			ArgsAdd(&argvP[argc], "--platform=", platform[gameInfoP->platform], &argc);	
		}

		// subtitles
		if (gameInfoP->subtitles)
			ArgsAdd(&argvP[argc],  "-n", NULL, &argc);

		// multi midi ?
		if (gameInfoP->musicInfo.sound.multiMidi)
			ArgsAdd(&argvP[argc], "--multi-midi", NULL, &argc);

		if (engine == ENGINE_SCUMM) {
			// music tempo
			StrIToA(num, gameInfoP->musicInfo.sound.tempo);
			ArgsAdd(&argvP[argc], "--tempo=", num, &argc);
		}

		// talk speed
		if (gameInfoP->talkSpeed) {
			StrIToA(num, gameInfoP->talkValue);
			ArgsAdd(&argvP[argc], "--talkspeed=", num, &argc);
		}

		// music driver
		if (gameInfoP->musicInfo.sound.music) {
			static char *drv[] = {
				"auto",
				"null",
				"adlib",
				"towns",
				"pcjr",
				"native",
				"pcspk"
			};

			if (StrCompare(drv[gameInfoP->musicInfo.sound.drvMusic], "native") == 0) {
				if (OPTIONS_TST(kOptDeviceZodiac))
					ArgsAdd(&argvP[argc], "-e", "zodiac", &argc);	// Tapwave Zodiac
				else if (OPTIONS_TST(kOptSonyPa1LibAPI))
					ArgsAdd(&argvP[argc], "-e", "ypa1", &argc);		// Pa1Lib devices
				else
					ArgsAdd(&argvP[argc], "-e", "auto", &argc);		// no driver, switch to auto
			} else {
				ArgsAdd(&argvP[argc], "-e", drv[gameInfoP->musicInfo.sound.drvMusic], &argc);	
			}

			// output rate
			UInt32 rates[] = {4000, 8000, 11025, 22050, 44100};
			StrIToA(num, rates[gameInfoP->musicInfo.sound.rate]);
			ArgsAdd(&argvP[argc], "--output-rate=", num, &argc);

			// FM quality
			gVars->fmQuality = gameInfoP->fmQuality;

		} else {
			ArgsAdd(&argvP[argc], "-e", "null", &argc);
		}

		// volume control
		StrIToA(num, gameInfoP->musicInfo.volume.sfx);
		ArgsAdd(&argvP[argc], "-s", num, &argc);
		StrIToA(num, gameInfoP->musicInfo.volume.music);
		ArgsAdd(&argvP[argc], "-m", num, &argc);
		StrIToA(num, gameInfoP->musicInfo.volume.speech);
		ArgsAdd(&argvP[argc], "-r", num, &argc);

		// game name
		ArgsAdd(&argvP[argc], gameInfoP->gameP, NULL, &argc);

		// others globals data
		gVars->CD.enable = gameInfoP->musicInfo.sound.CD;
		gVars->CD.driver = gameInfoP->musicInfo.sound.drvCD;
		gVars->CD.format = gameInfoP->musicInfo.sound.frtCD;
		gVars->CD.volume = gameInfoP->musicInfo.volume.audiocd;
		gVars->CD.defaultTrackLength = gameInfoP->musicInfo.sound.defaultTrackLength;
		gVars->CD.firstTrack = gameInfoP->musicInfo.sound.firstTrack;
		gVars->palmVolume = gameInfoP->musicInfo.sound.music ? gameInfoP->musicInfo.volume.palm : 0;

		MemHandleUnlock(recordH);
	} // end no game / game selected

	// common command line options

	// debug level
	if (gPrefs->debug) {
		StrIToA(num, gPrefs->debugLevel);
		ArgsAdd(&argvP[argc], "-d", num, &argc);
	}

	if (engine == ENGINE_QUEEN || engine == ENGINE_SKY) {
		// alternative intro ?
		if (gPrefs->altIntro)
			ArgsAdd(&argvP[argc], "--alt-intro", NULL, &argc);
	}
		
	if (engine == ENGINE_SCUMM) {
		// demo mode ?
		if (gPrefs->demoMode)
			ArgsAdd(&argvP[argc], "--demo-mode", NULL, &argc);
	}

	// copy protection ?
	if (gPrefs->copyProtection)
		ArgsAdd(&argvP[argc], "--copy-protection", NULL, &argc);

	// exceed max args ?
	if (argc > MAX_ARG)
		FrmCustomAlert(FrmErrorAlert, "Too many parameters.",0,0);

	// set some common options
	stackSize = (gPrefs->setStack ? STACK_LARGER : STACK_DEFAULT);
	lightspeed= (gPrefs->lightspeed.enable ? gPrefs->lightspeed.mode : 255);
	toLauncher= (gPrefs->exitLauncher);

	// gVars values 
	// (gVars->HRrefNum defined in checkHRmode on Clié)
	gVars->VFS.volRefNum	= gPrefs->card.volRefNum;
	gVars->vibrator			= gPrefs->vibrator;
	gVars->stdPalette		= gPrefs->stdPalette;
	gVars->VFS.cacheSize	= (gPrefs->card.useCache ? gPrefs->card.cacheSize : 0);
	gVars->indicator.showLED= gPrefs->card.showLED;
	gVars->stylusClick		= gPrefs->stylusClick;
	gVars->autoSave			= (gPrefs->autoSave ? gPrefs->autoSavePeriod : -1);
	gVars->advancedMode		= gPrefs->advancedMode;
	gVars->arrowKeys		= gPrefs->arrowKeys;

	// user params
	HWR_RSTALL();
	
	if (gPrefs->goLCD)
		HWR_SET(INIT_GOLCD);
	else
		OPTIONS_RST(kOptGoLcdAPI);
	
	if (!gPrefs->autoOff)
		HWR_SET(INIT_AUTOOFF);

	if (gVars->vibrator)
		HWR_SET(INIT_VIBRATOR);
/* ????
	if (	musicDriver == 1 ||
			musicDriver == 3 ||
			musicDriver == 4 ||
			musicDriver == sysInvalidRefNum) {
		HWR_SET(INIT_PA1LIB);
	}
*/
	if (ModImport(gVars->VFS.volRefNum, engine, &isARM) != errNone) {
		if (bDirectMode) {
			// and force exit if nothing selected
			EventType event;
			event.eType = keyDownEvent;
			event.data.keyDown.chr = vchrLaunch;
			event.data.keyDown.modifiers = commandKeyMask;
			EvtAddUniqueEventToQueue(&event, 0, true);
		}
		ArgsFree(argvP);
		return false;
	}

	// reset mode if screen rotation occured (DIA only)
	if (!direct && OPTIONS_TST(kOptCollapsible)) {
		UInt8 mode = PalmScreenSize(0,0, &(gVars->screenFullWidth), &(gVars->screenFullHeight));
		OPTIONS_RST(kOptModeLandscape);
		OPTIONS_SET((mode == PALM_LANDSCAPE) ? kOptModeLandscape : kOptNone);
	}

	// free and save globals pref memory
	GamCloseDatabase(false);
	FrmCloseAllForms();
	SavePrefs();

	{
		UInt16 cardNo;
		UInt32 dbID;

		LaunchParamType *cmdPBP = (LaunchParamType *)MemPtrNew(sizeof(LaunchParamType));

		MemPtrSetOwner(cmdPBP, 0);
		MemPtrSetOwner(gVars, 0);
		ArgsSetOwner(argvP, 0);

		cardNo = 0;
		dbID = DmFindDatabase(0, "ScummVM-Engine");

		if (isARM)
			FtrSet(appFileCreator, ftrStack , (stackSize * 4));
		else
			ModSetStack(stackSize, cardNo, dbID);

		cmdPBP->args.argc = argc;
		cmdPBP->args.argv = argvP;
		cmdPBP->gVars = gVars;
		cmdPBP->lightspeed = lightspeed;
		cmdPBP->exitLauncher = toLauncher;

		SysUIAppSwitch(cardNo, dbID, sysAppLaunchCmdNormalLaunch, cmdPBP);
		bLaunched = true;
	}

	return false;
}
Beispiel #25
0
/********************************************************************************
 * Description: this is the function responsible for checking the 
 * input password value of the authentication form. 
 * ******************************************************************************/ 
static void 
checkPassword (void) 
{
	MemPtr pass1, scratch = NULL;
	char *input;

	UInt16 index = 0;
	MemHandle rec;
	mdKey in;
	ListType *list;
	
		// compact text and get a pointer.
		FldCompactText (GetObjectFromActiveForm (PasswordField));
	input = FldGetTextPtr (GetObjectFromActiveForm (PasswordField));
	list = GetObjectFromActiveForm (selPopupList);
	
		// if SysPass is defined, free it. this happens when Strip locks
		// itself after the timeout.
		if (SysPass)
		MemPtrFree (SysPass);
	
		// if its the first time the user has used the program we need 
		// to set some things up. 
		if (input && StrLen (input))
		
	{
		
			// read the password from the database, decrypt with the input text.
			if ((rec = DmQueryRecord (PasswordDB, index)))
			
		{
			pass1 = MemHandleLock (rec);
			if ((scratch = MemPtrNew (24)))
				
			{
				UInt16 chk = LstGetSelection (list);
				
					//printf("%d\n", LstGetSelection(list)); 
					switch (chk)
					
				{
					case 0:
						UnpackPassword_old (pass1, scratch, input, 1);
						break;
					case 1:
						UnpackPassword_old (pass1, scratch, input, 2);
						break;
					case 2:
						UnpackPassword_old (pass1, scratch, input, 0);
						break;
				}
			}
			MemHandleUnlock (rec);
		}
		
			// the message digest of the password they provided should be exactly the
			// same as the message digest that was just decrypted out of the password
			// database. Do a MemCmp to make sure they are the same.
		md5_string (input, in);

		if ((!MemCmp (in, scratch, 16)) && input)
			
		{
			
				// if so, copy the password onto the system-password
		if ((SysPass = MemPtrNew (StrLen (input) + 1)))
				StrCopy (SysPass, input);
		if (scratch)
				MemPtrFree (scratch);
		md_string(SysPass, NewSysPass);
		cryptSwitch (LstGetSelection (list));
		}
		
		else
			
		{
			
				// FAILURE!!!!!!
				// free the memory and tell the user they entered the wrong password.
				FieldType *fld = GetObjectFromActiveForm (PasswordField);
			FrmCustomAlert (GenericError,
							  "The password you entered is incorrect", NULL,
							  NULL);
				FldSetSelection (fld, 0, FldGetTextLength (fld));
			LstDrawList (list);
			if (scratch)
				
			{
				MemPtrFree (scratch);
				SysPass = NULL;
			}
		}
	}
	
		// null string is always wrong!!!
		else
		
	{
		FrmCustomAlert (GenericError, "You forgot to enter a password!!",
						 NULL, NULL);
		LstDrawList (list);
	}
}
Beispiel #26
0
Boolean BookmarksFormHandleEvent(EventType * event)
{
    Boolean     handled = false;
    FormType *  frm;
    ListType *  bkmList, * sortTypeList;
    char *      listTxt;
    UInt16      bookmarksCount;
    AppContext* appContext = GetAppContext();

    frm = FrmGetActiveForm();
    switch (event->eType)
    {
        case frmOpenEvent:
            OpenBookmarksDB(appContext, appContext->prefs.bookmarksSortType);
            bkmList = (ListType *) FrmGetObjectPtr(frm,  FrmGetObjectIndex(frm, listBookmarks));
            bookmarksCount = BookmarksWordCount(appContext);
            Assert( 0 != bookmarksCount );

            LstSetDrawFunction(bkmList, BookmarksListDrawFunc);
            LstSetListChoices(bkmList, NULL, bookmarksCount);

            sortTypeList = (ListType *) FrmGetObjectPtr(frm,  FrmGetObjectIndex(frm, listSortBy));
            // list position matches enums for simplicity
            LstSetSelection(sortTypeList, (Int16)appContext->prefs.bookmarksSortType);

            listTxt = LstGetSelectionText(sortTypeList, appContext->prefs.bookmarksSortType);
            CtlSetLabel((ControlType *)FrmGetObjectPtr(frm,FrmGetObjectIndex(frm,popupSortBy)), listTxt);

            FrmDrawForm(frm);

            handled = true;
            break;

        case winDisplayChangedEvent:
            handled= BookmarksFormDisplayChanged(appContext, frm);
            break;

        case ctlSelectEvent:
            switch (event->data.ctlSelect.controlID)
            {
                case buttonCancel:
                    CloseBookmarksDB(appContext);
                    FrmReturnToForm(0);
                    handled = true;
                    break;

                case popupSortBy:
                    // do nothing
                    break;

                default:
                    Assert(false);
                    break;
            }
            break;

        case popSelectEvent:
            switch (event->data.popSelect.listID)
            {
                case listSortBy:
                    Assert( appContext->currBookmarkDbType == appContext->prefs.bookmarksSortType );
                    if ((BookmarkSortType) event->data.popSelect.selection != appContext->prefs.bookmarksSortType)
                    {
                        // we changed sorting type
                        sortTypeList = (ListType *) FrmGetObjectPtr(frm,  FrmGetObjectIndex(frm, listSortBy));
                        listTxt = LstGetSelectionText(sortTypeList, event->data.popSelect.selection);
                        CtlSetLabel((ControlType *)FrmGetObjectPtr(frm,FrmGetObjectIndex(frm,popupSortBy)), listTxt);

                        // list position matches enums for simplicity
                        OpenBookmarksDB(appContext, (BookmarkSortType) event->data.popSelect.selection);
                        appContext->prefs.bookmarksSortType = (BookmarkSortType) event->data.popSelect.selection;
#ifdef DEBUG
                        // word count shouldn't change
                        bookmarksCount = BookmarksWordCount(appContext);
                        bkmList = (ListType *) FrmGetObjectPtr(frm,  FrmGetObjectIndex(frm, listBookmarks));
                        Assert( LstGetNumberOfItems(bkmList) == bookmarksCount );
#endif
                        FrmDrawForm(frm);
                    }
                    handled = true;
                    break;

                default:
                    Assert(false);
                    break;
            }
            break;

        case lstSelectEvent:
        {
            MemHandle recHandle;
            char *    word;
            recHandle = DmQueryRecord(appContext->bookmarksDb, event->data.lstSelect.selection);
            Assert( recHandle ); // no reason it shouldn't work
            if (recHandle)
            {
                word = (char*)MemHandleLock(recHandle);
                Assert(word);
#ifndef I_NOAH                
                appContext->currentWord = dictGetFirstMatching(GetCurrentFile(appContext), word);
                MemHandleUnlock(recHandle);
                SendEvtWithType(evtNewWordSelected);
#else
                FrmReturnToForm(0);
                StartWordLookup(appContext, word);
                MemHandleUnlock(recHandle);
#endif                
            }
            CloseBookmarksDB(appContext);
#ifndef I_NOAH
            FrmReturnToForm(0);
#endif            
            handled = true;
        }

        default:
            break;
    }
    return handled;
}
Beispiel #27
0
/***********************************************************************
 *
 * FUNCTION:    ApptGetAppointments
 *
 * DESCRIPTION: This routine returns a list of appointments that are on 
 *              the date specified
 *
 * PARAMETERS:  dbP    - pointer to the database
 *              date   - date to search for
 *              countP - number of appointments on the specified 
 *                       day (returned value)
 *
 * RETURNED:    handle of the appointment list (ApptInfoType)
 *
 * REVISION HISTORY:
 *          Name    Date        Description
 *          ----    ----        -----------
 *          art     6/15/95     Initial Revision
 *
 ***********************************************************************/
MemHandle ApptGetAppointments (DmOpenRef dbP, DateType date, UInt16 * countP) {
    Err error;
    Int16 result;
    Int16 count = 0;
    UInt16    recordNum;
    Boolean repeats;
    MemHandle recordH;
    MemHandle apptListH;
    ApptInfoPtr apptList;
    ApptDBRecordType apptRec;
    ApptPackedDBRecordPtr r;

    // Allocated a block to hold the appointment list.
    apptListH = MemHandleNew (sizeof (ApptInfoType) * apptMaxPerDay);
    ErrFatalDisplayIf(!apptListH, "Out of memory");
    if (! apptListH) return (0);

    apptList = MemHandleLock (apptListH);

    // Find the first non-repeating appointment of the day.
    if (ApptFindFirst (dbP, date, &recordNum)) {
        while (count < apptMaxPerDay) {
            // Check if the appointment is on the date passed, if it is
            // add it to the appointment list.
            recordH = DmQueryRecord (dbP, recordNum);
            r = MemHandleLock (recordH);
            result = DateCompare (r->when.date, date);

            if (result == 0) {
                // Add the record to the appoitment list.
                apptList[count].startTime = r->when.startTime;
                apptList[count].endTime = r->when.endTime;
                apptList[count].recordNum = recordNum;
                count++;
            }
            MemHandleUnlock (recordH);
            if (result != 0) break;

            // Get the next record.
            error = DmSeekRecordInCategory (dbP, &recordNum, 1,
                                            dmSeekForward,
                                            dmAllCategories);
            if (error == dmErrSeekFailed) break;
        }
    }

    // Add the repeating appointments to the list.  Repeating appointments
    // are stored at the beginning of the database.
    recordNum = 0;
    while (count < apptMaxPerDay) {
        recordH = DmQueryNextInCategory (dbP, &recordNum, dmAllCategories);
        if (! recordH) break;
        
        r = (ApptPackedDBRecordPtr) MemHandleLock (recordH);
        
        repeats = (r->flags.repeat != 0);
        if (repeats) {
            ApptUnpack (r, &apptRec);
            if (ApptRepeatsOnDate (&apptRec, date)) {
                // Add the record to the appoitment list.
                apptList[count].startTime = r->when.startTime;              
                apptList[count].endTime = r->when.endTime;              
                apptList[count].recordNum = recordNum;  
                count++;
            }
        }
        MemHandleUnlock (recordH);

        // If the record has no repeating info we've reached the end of the 
        // repeating appointments.
        if (! repeats) break;
        
        recordNum++;
    }

    // Sort the list by start time.
    // SysInsertionSort (apptList, count, sizeof (ApptInfoType),
    //          ApptListCompare, 0L);

    // If there are no appointments on the specified day, free the appointment
    // list.
    if (count == 0) {
        MemPtrFree (apptList);
        apptListH = 0;
    }
    // Resize the appointment list block to release any unused space.
    else {
        MemHandleUnlock (apptListH);
        MemHandleResize (apptListH, count * sizeof (ApptInfoType));
    }

    *countP = count;
    return (apptListH);
}
Beispiel #28
0
/************************************************************
 *
 *  FUNCTION: ApptChangeRecord
 *
 *  DESCRIPTION: Change a record in the Appointment Database
 *
 *  PARAMETERS: database pointer
 *                   database index
 *                   database record
 *                   changed fields
 *
 *  RETURNS: ##0 if successful, errorcode if not
 *
 *  CREATED: 1/25/95 
 *
 *  BY: Roger Flores
 *
 *  COMMENTS:   Records are not stored with extra padding - they
 *  are always resized to their exact storage space.  This avoids
 *  a database compression issue.  The code works as follows:
 *  
 *  1)  get the size of the new record
 *  2)  make the new record
 *  3)  pack the packed record plus the changes into the new record
 *  4)  if the sort position is changes move to the new position
 *  5)  attach in position
 *
 *************************************************************/
Err ApptChangeRecord(DmOpenRef dbP, UInt16 *index, ApptDBRecordPtr r,
                     ApptDBRecordFlags changedFields) {
    Err result;
    Int16 newIndex;
    UInt16 attributes;
    Boolean dontMove;
    MemHandle oldH;
    MemHandle srcH;
    MemHandle dstH;
    ApptDBRecordType src;
    ApptPackedDBRecordPtr dst = 0;
    ApptPackedDBRecordPtr cmp;

    // We do not assume that r is completely valid so we get a valid
    // ApptDBRecordPtr...
    if ((result = ApptGetRecord(dbP, *index, &src, &srcH)) != 0)
        return result;

    // and we apply the changes to it.
    if (changedFields.when)
        src.when = r->when;

    if (changedFields.alarm)
        src.alarm = r->alarm;

    if (changedFields.repeat)
        src.repeat = r->repeat;

    if (changedFields.exceptions)
        src.exceptions = r->exceptions;

    if (changedFields.description)
        src.description = r->description;

    if (changedFields.note)
        src.note = r->note;

    // Allocate a new chunk with the correct size and pack the data from
    // the unpacked record into it.
    dstH = DmNewHandle(dbP, (UInt32) ApptPackedSize(&src));
    if (dstH) {
        dst = MemHandleLock (dstH);
        ApptPack (&src, dst);
    }

    MemHandleUnlock (srcH);
    if (dstH == NULL)
        return dmErrMemError;

    // If the sort position is changed move to the new position.
    // Check if any of the key fields have changed.
    if ((!changedFields.when) && (! changedFields.repeat))
        goto attachRecord;      // repeating events aren't in sorted order

    // Make sure *index-1 < *index < *index+1, if so it's in sorted
    // order.  Leave it there.
    if (*index > 0) {
        // This record wasn't deleted and deleted records are at the end of the
        // database so the prior record may not be deleted!
        cmp = MemHandleLock (DmQueryRecord(dbP, *index-1));
        dontMove = (ApptComparePackedRecords (cmp, dst, 0, NULL, NULL, 0)
                    <= 0);
        MemPtrUnlock (cmp);
    } else
        dontMove = true;


    if (dontMove && (*index+1 < DmNumRecords (dbP))) {
        DmRecordInfo(dbP, *index+1, &attributes, NULL, NULL);
        if ( ! (attributes & dmRecAttrDelete) ) {
            cmp = MemHandleLock (DmQueryRecord(dbP, *index+1));
            dontMove &= (ApptComparePackedRecords (dst, cmp, 0, NULL, NULL,
                                                   0) <= 0);
            MemPtrUnlock (cmp);
        }
    }

    if (dontMove)
        goto attachRecord;

    // The record isn't in the right position.  Move it.
    newIndex = ApptFindSortPosition (dbP, dst);
    DmMoveRecord (dbP, *index, newIndex);
    if (newIndex > *index) newIndex--;
    *index = newIndex;                      // return new position

 attachRecord:
    // Attach the new record to the old index,  the preserves the
    // category and record id.
    result = DmAttachRecord (dbP, index, dstH, &oldH);

    MemPtrUnlock(dst);

    if (result) return result;

    MemHandleFree(oldH);


    return 0;
}
Beispiel #29
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);

}
Beispiel #30
0
/***********************************************************************
 *
 * FUNCTION:    ApptFindFirst
 *
 * DESCRIPTION: This routine finds the first appointment on the specified
 *              day.
 *
 * PARAMETERS:  dbP    - pointer to the database
 *              date   - date to search for
 *              indexP - pointer to the index of the first record on the 
 *                       specified day (returned value)
 *
 * RETURNED:    true if a record has found
 *
 * REVISION HISTORY:
 *          Name    Date        Description
 *          ----    ----        -----------
 *          art 6/15/95     Initial Revision
 *
 ***********************************************************************/
Boolean ApptFindFirst (DmOpenRef dbP, DateType date, UInt16 * indexP) {
    Err err;
    Int16 numOfRecords;
    Int16 kmin, probe, i;     // all positions in the database.
    Int16 result = 0;         // result of comparing two records
    UInt16 index;
    MemHandle recordH;
    Boolean found = false;
    ApptPackedDBRecordPtr r;

    kmin = probe = 0;
    numOfRecords = DmNumRecords(dbP);


    while (numOfRecords > 0) {
        i = numOfRecords >> 1;
        probe = kmin + i;

        index = probe;
        recordH = DmQueryNextInCategory (dbP, &index, dmAllCategories);
        if (recordH) {
            r = (ApptPackedDBRecordPtr) MemHandleLock (recordH);
            if (r->flags.repeat)
                result = 1;
            else
                result = DateCompare (date, r->when.date);
            MemHandleUnlock (recordH);
        }

        // If no handle, assume the record is deleted, deleted records
        // are greater.
        else
            result = -1;


        // If the date passed is less than the probe's date, keep searching.
        if (result < 0)
            numOfRecords = i;

        // If the date passed is greater than the probe's date, keep searching.
        else if (result > 0) {
            kmin = probe + 1;
            numOfRecords = numOfRecords - i - 1;
        }

        // If the records are equal find the first record on the day.
        else {
            found = true;
            *indexP = index;
            while (true) {
                err = DmSeekRecordInCategory (dbP, &index, 1, dmSeekBackward,
                                              dmAllCategories);
                if (err == dmErrSeekFailed) break;

                recordH = DmQueryRecord(dbP, index);
                r = (ApptPackedDBRecordPtr) MemHandleLock (recordH);
                if (r->flags.repeat)
                    result = 1;
                else
                    result = DateCompare (date, r->when.date);
                MemHandleUnlock (recordH);
                if (result != 0) break;
                *indexP = index;
            }

            break;
        }
    }


    // If that were no appointments on the specified day, return the
    // index of the next appointment (on a future day).
    if (! found) {
        if (result < 0)
            *indexP = probe;
        else
            *indexP = probe + 1;
    }

    return (found);
}