void MacOpTimer::Start(UINT32 ms) { UnsignedWide ticks; Microseconds(&ticks); long long msecs = ticks.hi; msecs <<= 32; msecs |= ticks.lo; m_startTime = msecs / 1000; m_interval = ms; EventTimerInterval fireDelay = ms * kEventDurationMillisecond; if (m_timerRef) { SetEventLoopTimerNextFireTime(m_timerRef,fireDelay); } else { InstallEventLoopTimer(gMainEventLoop,//GetMainEventLoop(), fireDelay, kEventDurationNoWait, timerUPP, this, &m_timerRef); } }
// ----------------------------------------------------------------------------- OSStatus refr_timer(EventLoopTimerRef * inOutTimer, EventLoopTimerProcPtr inTimerProc, EventTimerInterval inFireDelay, EventTimerInterval inInterval, /* 0 is one-shot */ void * inOutUserData) { OSStatus err = noErr; if (inOutTimer == NULL) { debug0msg0("inOutTimer == NULL"); err = -1; } else if (*inOutTimer == NULL) { EventLoopTimerUPP upp = NewEventLoopTimerUPP(inTimerProc); err = InstallEventLoopTimer(GetMainEventLoop(), inFireDelay, inInterval, upp, inOutUserData, inOutTimer); debug0msg("created new timer, ret code=%ld", err); } else { err = SetEventLoopTimerNextFireTime(*inOutTimer, inInterval); debug0msg("SetEventLoopTimerNextFireTime, ret code=%ld", err); } return err; }
void *OpenURL(char *url) { DWORD c,r; pthread_mutex_lock(&lock); // make sure only 1 thread at a time can do the following r=++req; // increment the request counter for this request pthread_mutex_unlock(&lock); RemoveEventLoopTimer(prebuftimer); // stop prebuffer monitoring BASS_StreamFree(chan); // close old stream PostCustomEvent('open',0,0); c=BASS_StreamCreateURL(url,0,BASS_STREAM_BLOCK|BASS_STREAM_STATUS|BASS_STREAM_AUTOFREE,StatusProc,0); free(url); // free temp URL buffer pthread_mutex_lock(&lock); if (r!=req) { // there is a newer request, discard this stream pthread_mutex_unlock(&lock); if (c) BASS_StreamFree(c); return; } chan=c; // this is now the current stream pthread_mutex_unlock(&lock); if (!chan) { PostCustomEvent('end ',0,0); // Error("Can't play the stream"); } else InstallEventLoopTimer(GetMainEventLoop(),kEventDurationNoWait,kEventDurationSecond/20,NewEventLoopTimerUPP(PrebufTimerProc),0,&prebuftimer); // start prebuffer monitoring return NULL; }
static void Initialize( void ) { EventLoopTimerRef timerRef; EventTypeSpec eventTypeSpec = { kEventClassWindow, kEventWindowClose }; Rect bounds; WindowRef window; InitCursor(); // Create a window and install an event handler to handle the close button. SetRect( &bounds, 50, 50, 600, 200 ); CreateNewWindow( kDocumentWindowClass, kWindowCloseBoxAttribute + kWindowStandardHandlerAttribute, &bounds, &window ); SetWTitle( window, "\pPlugIn Host -- Close Window To Quit" ); InstallWindowEventHandler( window, NewEventHandlerUPP( MyCloseHandler ), 1, &eventTypeSpec, NULL, NULL ); // Create a timer to handle ball-drawing in the window. InstallEventLoopTimer( GetCurrentEventLoop(), kEventDurationSecond, kEventDurationSecond, NewEventLoopTimerUPP( MyTimerHandler ), window, &timerRef ); ShowWindow( window ); }
static void install_mac_timer(void) { EventLoopTimerRef timer; InstallEventLoopTimer(GetMainEventLoop(), .001*kEventDurationSecond,.001*kEventDurationSecond, NewEventLoopTimerUPP(DoRealStuff), NULL, &timer); }
void StartHIDInput (void) { EndHIDInput (); // ensure we are overwriting an earlier set up // setup inputs if (SetupHIDInputs ()) InstallEventLoopTimer (GetCurrentEventLoop(), 0, 0.01, GetHIDTimerUPP (), NULL, &gHIDTimer); // start timer 100 hz else printf ("No 2 DOF device found.\n"); }
bool8 NPServerDialog (void) { OSStatus err; IBNibRef nibRef; npserver.dialogcancel = true; err = CreateNibReference(kMacS9XCFString, &nibRef); if (err == noErr) { WindowRef tWindowRef; err = CreateWindowFromNib(nibRef, CFSTR("ClientList"), &tWindowRef); if (err == noErr) { EventHandlerRef eref; EventLoopTimerRef tref; EventHandlerUPP eventUPP; EventLoopTimerUPP timerUPP; EventTypeSpec windowEvents[] = { { kEventClassCommand, kEventCommandProcess }, { kEventClassCommand, kEventCommandUpdateStatus } }; HIViewRef ctl; HIViewID cid = { 'Chse', 0 }; npserver.dialogprocess = kNPSDialogInit; eventUPP = NewEventHandlerUPP(NPServerDialogEventHandler); err = InstallWindowEventHandler(tWindowRef, eventUPP, GetEventTypeCount(windowEvents), windowEvents, (void *) tWindowRef, &eref); timerUPP = NewEventLoopTimerUPP(NPServerDialogTimerHandler); err = InstallEventLoopTimer(GetCurrentEventLoop(), 0.0f, 0.1f, timerUPP, (void *) tWindowRef, &tref); HIViewFindByID(HIViewGetRoot(tWindowRef), cid, &ctl); HIViewSetVisible(ctl, false); MoveWindowPosition(tWindowRef, kWindowServer, false); ShowWindow(tWindowRef); err = RunAppModalLoopForWindow(tWindowRef); HideWindow(tWindowRef); SaveWindowPosition(tWindowRef, kWindowServer); err = RemoveEventLoopTimer(tref); DisposeEventLoopTimerUPP(timerUPP); err = RemoveEventHandler(eref); DisposeEventHandlerUPP(eventUPP); CFRelease(tWindowRef); } DisposeNibReference(nibRef); } return (!npserver.dialogcancel); }
void InstallTimer( void ) { EventLoopTimerRef timer; InstallEventLoopTimer( GetCurrentEventLoop(), 0, kEventDurationMillisecond * 8, // Roughly 125 times per second NewEventLoopTimerUPP( MyTimerProc ), NULL, &timer ); }
void st_scheduler::start_polling() { assert(m_pTimer == NULL); OSStatus lStatus = InstallEventLoopTimer(GetMainEventLoop(), 0 * kEventDurationSecond, kEventDurationMillisecond, m_uppTask, this, &m_pTimer); // TODO - throw on error assert(lStatus == noErr); }
void InstallTimer( void ) { EventLoopTimerRef timer; InstallEventLoopTimer( GetCurrentEventLoop(), 0, kEventDurationMillisecond * 20, NewEventLoopTimerUPP( MyTimerProc ), gWindow, &timer ); }
int main(int argc, char* argv[]) { IBNibRef nibRef; OSStatus err; InitCursor(); // check the correct BASS was loaded if (HIWORD(BASS_GetVersion())!=BASSVERSION) { Error("An incorrect version of BASS.DLL was loaded (2.4 is required)"); return 0; } // check the correct BASS_FX was loaded if (HIWORD(BASS_FX_GetVersion())!=BASSVERSION) { Error("An incorrect version of BASS_FX.DLL was loaded (2.4 is required)"); return 0; } // initialize default output device if(!BASS_Init(-1,44100,0,NULL,NULL)) { Error("Can't initialize device"); return 0; } // Create Window and Stuff err = CreateNibReference(CFSTR("reverse"), &nibRef); if (err) return err; err = CreateWindowFromNib(nibRef, CFSTR("MainWindow"), &win); if (err) return err; DisposeNibReference(nibRef); SetupControlHandler(10,kEventControlHit,OpenEventHandler); SetControlAction(GetControl(11),NewControlActionUPP(VolEventHandler)); SetControlAction(GetControl(13),NewControlActionUPP(TempoEventHandler)); SetControlAction(GetControl(15),NewControlActionUPP(PosEventHandler)); SetupControlHandler(16,kEventControlHit,DirEventHandler); EventLoopTimerRef timer; InstallEventLoopTimer(GetCurrentEventLoop(),kEventDurationNoWait,kEventDurationSecond/2,TimerProc,0,&timer); // The window was created hidden so show it. ShowWindow(win); // Call the event loop RunApplicationEventLoop(); // Close output BASS_Free(); return 0; }
Timer::Timer( EventLoopRef mainLoop, EventTimerInterval inFireDelay, EventTimerInterval inInterval, void* inTimerData, EventLoopTimerProcPtr userRoutine ) : mTimerUPP( NewEventLoopTimerUPP(userRoutine) ) { InstallEventLoopTimer( mainLoop ,inFireDelay ,inInterval ,mTimerUPP ,inTimerData ,&mTimer); }
void WindowBase::MainLoop() { OSXWindowData *windowData = (OSXWindowData*) GetWRefCon (mWindowHandle); windowData->StartedApplicationLoop = true; windowData->MainLoopEventHandler = NewEventLoopTimerUPP(MainLoopEventHandler); PRCORE_ASSERT_EXCEPTION( noErr != InstallEventLoopTimer (GetCurrentEventLoop(), 0, mMainFreq, windowData->MainLoopEventHandler, (void *) windowData, &windowData->EventMainLoopReference )); RunApplicationEventLoop(); }
int prHIDRunEventLoop(VMGlobals *g, int numArgsPushed) { PyrSlot *a = g->sp - 1; //class PyrSlot *b = g->sp; //num double eventtime; int err = slotDoubleVal(b, &eventtime); if (err) return err; if(gTimer) { RemoveEventLoopTimer(gTimer); gTimer = NULL; } InstallEventLoopTimer (GetCurrentEventLoop(), 0, (EventTimerInterval) eventtime, GetTimerUPP (), 0, &gTimer); //HIDSetQueueCallback(pCurrentHIDDevice, callback); return errNone; }
void windowCaptureFrames(GLWindow *glw) { // This routine is what we'll use to capture frames for building a movie // We need an array of GWorld to hold the image data we're reading out of OpenGL // Then we'll process that buffer with another thread char fBuffer[256], tBuffer[256], frBuffer[256]; Size dataSize; // bail if we're already in the middle of a snapshot sequence if(snapshotTimerUPP) return; // Get the desired frame rate GetControlData(movieFrameRate, kControlEditTextPart, kControlStaticTextTextTag, 256, frBuffer, &dataSize); fps = atoi(frBuffer); if(fps <= 0) fps = 32; if(movieUseTimeLimit) { GetControlData(movieTimeLimit, kControlEditTextPart, kControlStaticTextTextTag, 256, fBuffer, &dataSize); seqTimeInt = atoi(fBuffer); } if(movieUseFrameLimit) { GetControlData(movieFrameCount, kControlEditTextPart, kControlStaticTextTextTag, 256, tBuffer, &dataSize); seqFrameCount = atoi(tBuffer); } if(movTimeLimit <= 0) movTimeLimit = 10; if(movFrameCount <= 0) movFrameCount = 300; // now kick off our sequence timer snapshotTimerUPP = NewEventLoopTimerUPP(MovieCaptureTimedEventProcessor); InstallEventLoopTimer(GetCurrentEventLoop(), 0, kEventDurationSecond / fps, snapshotTimerUPP, NULL, // User Data &snapshotTimer); }
void cutils_test_refr_timer() { int i, fireTimes = 0; const int kNumRefr = 5; const EventTimerInterval kRefrTime = 0.5; // keep this shorter than 1 sec EventLoopTimerRef timer = NULL, rltimer = NULL; OSStatus err; EventLoopTimerUPP upp; LOG0("---- cutils_test_refr_timer ---------------------------------------"); // start timer with long fire delay refr_timer(&timer, &cutils_test_refr_timercb, 2, 0, &fireTimes); for (i = 0; i < kNumRefr; i++) { // refresh timer with shorter fire delay. This should just (1) override // the previous one-shot fire and (2) continuously prolong the // firing time making the timer fire only once refr_timer(&timer, &cutils_test_refr_timercb, kRefrTime, 0, &fireTimes); } // execution flow never blocks, so given the long fire delays our // fireTimes counter must still be 0 LOG("cutils_test_refr_timer:: fireTimes=%d", fireTimes); assert(fireTimes == 0); // install another timer just to get out of the run loop (see below): // we'll make it fire way after the sum of all previous fire delays upp = NewEventLoopTimerUPP(killrl_timercb); err = InstallEventLoopTimer(GetMainEventLoop(), kNumRefr * kRefrTime * 5, 0, upp, NULL, &rltimer); assert(err == 0); // we need to run the app event loop to actually let the `timer' work RunApplicationEventLoop(); LOG("cutils_test_refr_timer:: fireTimes=%d", fireTimes); assert(fireTimes == 1); err = RemoveEventLoopTimer(rltimer); assert(err == 0); err = RemoveEventLoopTimer(timer); assert(err == 0); }
bool AquaGui::run() { double interval = _interval / 1000.0; OSStatus ret = InstallEventLoopTimer (GetMainEventLoop(), 0, interval, DoAdvanceMovie, this, _advance_timer); if (ret != noErr) { return false; } RepositionWindow(myWindow, NULL, kWindowCascadeOnMainScreen); SelectWindow(myWindow); ShowWindow(myWindow); SetWindowModified(myWindow, false); RunApplicationEventLoop(); return true; }
void myTMReset( myTMTaskPtr task) { if (task->primed) { SetEventLoopTimerNextFireTime(task->task, task->time * kDurationMillisecond); } else { task->primed=true; InstallEventLoopTimer(GetMainEventLoop(), task->time * kEventDurationMillisecond, task->time * kEventDurationMillisecond, timer_upp, task, &task->task); } }
pxError pxWindow::setAnimationFPS(long fps) { if (theTimer) { RemoveEventLoopTimer(theTimer); } if (fps > 0) { EventLoopRef mainLoop; EventLoopTimerUPP timerUPP; mainLoop = GetMainEventLoop(); timerUPP = NewEventLoopTimerUPP (doPeriodicTask); InstallEventLoopTimer (mainLoop, 0, (1000/fps) * kEventDurationMillisecond, timerUPP, this, &theTimer); } return PX_OK; }
/* * int nativeCreate(int period) */ JNIEXPORT jint JNICALL Java_com_scriptographer_ai_Timer_nativeCreate( JNIEnv *env, jobject obj, jint period) { try { #ifdef WIN_ENV return (jint) SetTimer(NULL, NULL, period, Dialog_onTimer); #endif // WIN_ENV #ifdef MAC_ENV DEFINE_CALLBACK_PROC(Dialog_onTimer); static EventLoopTimerUPP timerUPP = NewEventLoopTimerUPP( (EventLoopTimerProcPtr) CALLBACK_PROC(Dialog_onTimer)); EventLoopTimerRef timer; InstallEventLoopTimer(GetMainEventLoop(), 0, kEventDurationMillisecond * period, timerUPP, NULL, &timer); return (jint) timer; #endif // MAC_ENV } EXCEPTION_CONVERT(env); return 0; }
void windowSnapshotSequence(GLWindow *glw) { // Get the values from the controls (time and number of frames) // I think we need to pass a count along to the snapshot function // in order to figure out when to remove the damned thing. // There's no other way to do it without creating my own API. char buffer[256]; Size dataSize; // If our UPP is valid, we've already got a timer going if(snapshotTimerUPP) return; GetControlData(sequenceTimeInterval, kControlEditTextPart, kControlStaticTextTextTag, 256, buffer, &dataSize); seqTimeInt = atoi(buffer); GetControlData(sequenceFrameCount, kControlEditTextPart, kControlStaticTextTextTag, 256, buffer, &dataSize); seqFrameCount = atoi(buffer); if(seqTimeInt <= 0) seqTimeInt = 1; if(seqFrameCount <= 0) seqFrameCount = 1; // Now allocate memory for our GWorld buffer if(gwBuffer) { free(gwBuffer); gwBuffer = NULL; } gwBuffer = malloc(seqFrameCount * sizeof(GWorldPtr)); // Remember, we need to use NewGWorldFromPtr() on EACH of these elements as we create them // Now we kick off a new timer to create our snapshots snapshotTimerUPP = NewEventLoopTimerUPP(SnapshotTimedEventProcessor); InstallEventLoopTimer(GetCurrentEventLoop(), 0, kEventDurationMillisecond * seqTimeInt, snapshotTimerUPP, NULL, // User Data &snapshotTimer); }
OSErr createWorkerThread ( WorkerActionRoutine actionRoutine, WorkerCancelRoutine cancelRoutine, WorkerResponseMainThreadCallback responseCallback, void *refcon, WorkerThreadRef *outWorker ) { WorkerThreadRef worker; if ( !actionRoutine || !responseCallback || !outWorker ) return paramErr; worker = calloc( 1, sizeof( WorkerThread ) ); if ( ! worker ) return memFullErr; worker->referenceCount = 1; worker->actionRoutine = actionRoutine; worker->cancelRoutine = cancelRoutine; worker->responseCallback = responseCallback; worker->refcon = refcon; // get the OS version Gestalt(gestaltSystemVersion, &worker->osVersion); // create a one-shot event loop timer worker->responseEventLoopTimerUPP = NewEventLoopTimerUPP( runWorkerResponseEventLoopTimer ); InstallEventLoopTimer( GetMainEventLoop(), kEventDurationForever, kEventDurationForever, worker->responseEventLoopTimerUPP, worker, &worker->responseEventLoopTimer ); // sem_init() not yet implemented as of MacOS X 10.3 - so we're going to use the MP APIs instead // the POSIX calls we could use when sem_init() is supported are clearly marked with the POSIX prefix // Named semaphors are available but not really ideal for our needs in this sample // Reference: http://developer.apple.com/documentation/Carbon/Reference/Multiprocessing_Services/multiproc_ref/function_group_3.html //POSIX sem_init( &worker->requestSemaphore, 0 /* not shared */, 0 /* initial value */ ); //POSIX sem_init( &worker->shutdownSemaphore, 0 /* not shared */, 0 /* initial value */ ); MPCreateSemaphore(1, 0, &worker->requestSemaphore); MPCreateSemaphore(1, 0, &worker->shutdownSemaphore); pthread_create( &worker->workerThread, NULL, runWorkerThread, worker ); *outWorker = worker; return noErr; }
SEXP R_carbonInstallTimer(int interval, R_TimerFunc f, void *userData) { EventLoopRef loop = GetCurrentEventLoop(); EventTimerInterval delay, time; EventLoopTimerUPP proc; EventLoopTimerRef out; OSStatus status; delay = 0; time = interval * kEventDurationSecond; /* Is this milli sceonds */ status = InstallEventLoopTimer(loop, delay, time, NewEventLoopTimerUPP(proc), userData, &out); if(status != noErr) { PROBLEM "Can't register timer task" ERROR; } return(createRCarbonTimer(out)); }
void QEventDispatcherMac::registerTimer(int timerId, int interval, QObject *obj) { #ifndef QT_NO_DEBUG if (timerId < 1 || interval < 0 || !obj) { qWarning("QEventDispatcherUNIX::registerTimer: invalid arguments"); return; } else if (obj->thread() != thread() || thread() != QThread::currentThread()) { qWarning("QObject::startTimer: timers cannot be started from another thread"); return; } #endif Q_D(QEventDispatcherMac); if (!d->macTimerList) d->macTimerList = new MacTimerList; MacTimerInfo t; t.id = timerId; t.interval = interval; t.obj = obj; t.mac_timer = 0; t.pending = true; if (interval) { if (!timerUPP) timerUPP = NewEventLoopTimerUPP(qt_mac_activate_timer); EventTimerInterval mint = (((EventTimerInterval)interval) / 1000); d->macTimerList->append(t); //carbon timers go at the end.. if (InstallEventLoopTimer(GetMainEventLoop(), mint, mint, timerUPP, &d->macTimerList->last(), &d->macTimerList->last().mac_timer)) { qFatal("This cannot really happen, can it!?!"); return; //exceptional error } d->macTimerList->last().pending = false; } else { d->zero_timer_count++; if(d->zero_timer_count == 1) wakeUp(); //if we are blocking we need to come out of that state d->macTimerList->prepend(t); //zero timers come first d->macTimerList->first().pending = false; } }
myTMTaskPtr myTMSetup( int32 time, bool (*func)(void)) { myTMTaskPtr result; result= new myTMTask; if (!result) return result; result->func=func; result->time=time; result->primed=true; InstallEventLoopTimer(GetMainEventLoop(), time * kEventDurationMillisecond, time * kEventDurationMillisecond, timer_upp, result, &result->task); return result; }
bool wxCarbonTimerImpl::Start( int milliseconds, bool mode ) { (void)wxTimerImpl::Start(milliseconds, mode); wxCHECK_MSG( m_milli > 0, false, wxT("invalid value for timer timeout") ); wxCHECK_MSG( m_info->m_timerRef == NULL, false, wxT("attempting to restart a timer") ); m_info->m_timer = this; m_info->m_proc = NewEventLoopTimerUPP( &wxProcessTimer ); OSStatus err = InstallEventLoopTimer( GetMainEventLoop(), m_milli*kEventDurationMillisecond, IsOneShot() ? 0 : m_milli * kEventDurationMillisecond, m_info->m_proc, this, &m_info->m_timerRef ); verify_noerr( err ); return true; }
static OSStatus InstallMovieIdlingEventLoopTimer(MyStatePtr myState) { OSStatus error; mEventLoopTimer = NewEventLoopTimerUPP(MyMovieIdlingTimer); error = InstallEventLoopTimer( GetMainEventLoop(), 0, // firedelay kEventDurationMillisecond * kMinimumIdleDurationInMillis, // interval mEventLoopTimer, myState, // This will be passed to us when // the timer fires &myState->theEventTimer); if (!error) { #ifdef __APPLE_CC__ mTaskNeededSoonerCallback = NewQTNextTaskNeededSoonerCallbackUPP(TaskNeededSoonerCallback); // Install a callback that the Idle Manager will use when // QuickTime needs to wake me up immediately error = QTInstallNextTaskNeededSoonerCallback( mTaskNeededSoonerCallback, 1000, // Millisecond timescale 0, // No flags (void*)myState->theEventTimer); // Our refcon, the // callback will // reschedule it #else mTaskNeededSoonerCallback = mNewQTNextPtr(TaskNeededSoonerCallback); // Install a callback that the Idle Manager will use when // QuickTime needs to wake me up immediately error = mQTInstallNextPtr(mTaskNeededSoonerCallback, 1000, // Millisecond timescale 0, // No flags (void*)myState->theEventTimer); #endif } return error; }
IdleList::IdleList(mdaLooplex *effect, IdleList *next) : effect(effect), next(next), remove(false) { if(effect && !timer) //start timer { #if WIN32 timer = SetTimer(NULL, 0, IDLE_MSEC, TimerCallback); #elif __linux__ timer = 1; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 16 * 1024); int policy; if (pthread_attr_getschedpolicy(&attr, &policy) == 0) { struct sched_param param; param.sched_priority = sched_get_priority_min(policy); pthread_attr_setschedpolicy(&attr, SCHED_OTHER); pthread_attr_setschedparam(&attr, ¶m); } pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0); if (pthread_create(&thread, &attr, &ThreadCallback, 0) != 0) { thread = 0; timer = 0; fprintf(stderr, "Error: mdaLooplex.cpp (line %d)\n", __LINE__); } pthread_attr_destroy(&attr); #else //OSX double ms = kEventDurationMillisecond * (double)IDLE_MSEC; InstallEventLoopTimer(GetCurrentEventLoop(), ms, ms, NewEventLoopTimerUPP(TimerCallback), 0, &timer); #endif } }
void MusicBoxDialog(void) { OSStatus err; IBNibRef nibRef; if (!cartOpen) return; err = CreateNibReference(kMacS9XCFString, &nibRef); if (err == noErr) { CFURLRef iconURL; FSRef iconFSRef; IconRef actIcon; WindowRef tWindowRef; actIcon = nil; if (musicboxmode == kMBXSoundEmulation) iconURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("musicbox_ledoff"), CFSTR("icns"), nil); else iconURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("musicbox_ledon" ), CFSTR("icns"), nil); if (iconURL) { if (CFURLGetFSRef(iconURL, &iconFSRef)) err = RegisterIconRefFromFSRef('~9X~', 'micn', &iconFSRef, &actIcon); CFRelease(iconURL); } err = CreateWindowFromNib(nibRef, CFSTR("MusicBox"), &tWindowRef); if (err == noErr) { EventHandlerRef mboxRef, paneRef; EventHandlerUPP mboxUPP, paneUPP; EventLoopTimerRef timeRef; EventLoopTimerUPP timeUPP; EventTypeSpec mboxEvents[] = { { kEventClassCommand, kEventCommandProcess }, { kEventClassCommand, kEventCommandUpdateStatus } }, paneEvents[] = { { kEventClassControl, kEventControlDraw } }; CFStringRef sref; CGDataProviderRef prov; CGImageRef ipng; CFURLRef iurl; HIViewRef ctl, root, paneView, imageView, contentView; HIViewID cid; HIRect bounds; Rect windowRect, barRect; char drive[_MAX_DRIVE], dir[_MAX_DIR], fname[_MAX_FNAME], ext[_MAX_EXT]; mboxPause = false; mbxFinished = false; showIndicator = false; so.stereo_switch = ~0; for (int i = 0; i < MAC_MAX_PLAYERS; i++) controlPad[i] = 0; switch (drawingMethod) { case kDrawingOpenGL: Settings.OpenGLEnable = true; break; case kDrawingDirect: case kDrawingBlitGL: Settings.OpenGLEnable = false; } // 107's enhanced SPC player root = HIViewGetRoot(tWindowRef); cid.id = 0; if (musicboxmode == kMBXSoundEmulation) { cid.signature = 'HEAD'; HIViewFindByID(root, cid, &ctl); EnableControl(ctl); StoredAPU = new SAPU; StoredAPURegisters = new SAPURegisters; StoredSoundData = new SSoundData; StoredIAPURAM = new uint8 [0x10000]; SPCPlayFreeze(); } else MusicBoxForceFreeze(); cid.signature = 'Kart'; HIViewFindByID(root, cid, &ctl); SetStaticTextTrunc(ctl, truncEnd, false); _splitpath(Memory.ROMFilename, drive, dir, fname, ext); sref = CFStringCreateWithCString(kCFAllocatorDefault, fname, MAC_PATH_ENCODING); if (sref) { SetStaticTextCFString(ctl, sref, false); CFRelease(sref); } ipng = nil; iurl = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("musicbox_indicator"), CFSTR("png"), nil); if (iurl) { prov = CGDataProviderCreateWithURL(iurl); if (prov) { ipng = CGImageCreateWithPNGDataProvider(prov, nil, false, kCGRenderingIntentDefault); CGDataProviderRelease(prov); } CFRelease(iurl); } imageView = nil; if (ipng) { HIViewFindByID(root, kHIViewWindowContentID, &contentView); err = HIImageViewCreate(ipng, &imageView); if (err == noErr) { bounds = CGRectMake(30, 64, CGImageGetWidth(ipng), CGImageGetHeight(ipng)); HIViewSetFrame(imageView, &bounds); HIImageViewSetOpaque(imageView, false); HIViewSetVisible(imageView, true); HIViewAddSubview(contentView, imageView); cid.signature = 'iMaG'; SetControlID(imageView, &cid); } CGImageRelease(ipng); } cid.signature = 'Pane'; HIViewFindByID(root, cid, &paneView); HIViewGetBounds(paneView, &bounds); mbxViewWidth = bounds.size.width; mbxViewHeight = bounds.size.height; mbxMarginY = (mbxViewHeight - mbxBarHeight) / 2.0; mbxMarginX = (mbxViewWidth - ((mbxBarWidth * 8.0 + mbxBarSpace * 7.0) * 2.0 + mbxLRSpace)) / 2.0; if (imageView) { HIViewSetZOrder(imageView, kHIViewZOrderBelow, paneView); HIViewAddSubview(imageView, paneView); } cid.signature = 'Tr_i'; HIViewFindByID(root, cid, &ctl); HIViewGetFrame(ctl, &bounds); GetWindowBounds(tWindowRef, kWindowTitleBarRgn, &barRect); mbxClosedHeight = (short) (bounds.origin.y + bounds.size.height + 7.0) + (barRect.bottom - barRect.top); GetWindowBounds(tWindowRef, kWindowStructureRgn, &windowRect); mbxOpenedHeight = windowRect.bottom - windowRect.top; windowRect.bottom = windowRect.top + mbxClosedHeight; SetWindowBounds(tWindowRef, kWindowStructureRgn, &windowRect); paneUPP = NewEventHandlerUPP(IndicatorEventHandler); err = InstallControlEventHandler(paneView, paneUPP, GetEventTypeCount(paneEvents), paneEvents, (void *) paneView, &paneRef); mboxUPP = NewEventHandlerUPP(MusicBoxEventHandler); err = InstallWindowEventHandler(tWindowRef, mboxUPP, GetEventTypeCount(mboxEvents), mboxEvents, (void *) tWindowRef, &mboxRef); timeUPP = NewEventLoopTimerUPP(MusicBoxTimerHandler); err = InstallEventLoopTimer(GetCurrentEventLoop(), kEventDurationNoWait, kEventDurationSecond * 2.0 / (double) Memory.ROMFramesPerSecond, timeUPP, (void *) paneView, &timeRef); MusicBoxInitIndicator(); stopNow = false; MacStartSound(); pthread_create(&mbxThread, nil, SoundTask, nil); MoveWindowPosition(tWindowRef, kWindowMusicBox, true); GetWindowBounds(tWindowRef, kWindowStructureRgn, &windowRect); if (windowRect.bottom - windowRect.top > mbxClosedHeight) { showIndicator = true; SetControl32BitValue(ctl, 1); // Tr_i } ShowWindow(tWindowRef); err = RunAppModalLoopForWindow(tWindowRef); HideWindow(tWindowRef); SaveWindowPosition(tWindowRef, kWindowMusicBox); stopNow = true; pthread_join(mbxThread, nil); MacStopSound(); err = RemoveEventLoopTimer(timeRef); DisposeEventLoopTimerUPP(timeUPP); err = RemoveEventHandler(mboxRef); DisposeEventHandlerUPP(mboxUPP); err = RemoveEventHandler(paneRef); DisposeEventHandlerUPP(paneUPP); ReleaseWindow(tWindowRef); so.stereo_switch = ~0; mbxFinished = true; if (musicboxmode == kMBXSoundEmulation) { SPCPlayDefrost(); delete StoredAPU; delete StoredAPURegisters; delete StoredSoundData; delete [] StoredIAPURAM; } else MusicBoxForceDefrost(); Settings.OpenGLEnable = false; } if (actIcon) err = UnregisterIconRef('~9X~', 'micn'); DisposeNibReference(nibRef); } }
//------------------------------------------------------------------------ bool platform_support::init(unsigned width, unsigned height, unsigned flags) { if(m_specific->m_sys_format == pix_format_undefined) { return false; } m_window_flags = flags; // application EventTypeSpec eventType; EventHandlerUPP handlerUPP; eventType.eventClass = kEventClassApplication; eventType.eventKind = kEventAppQuit; handlerUPP = NewEventHandlerUPP(DoAppQuit); InstallApplicationEventHandler (handlerUPP, 1, &eventType, nil, nil); eventType.eventClass = kEventClassMouse; eventType.eventKind = kEventMouseDown; handlerUPP = NewEventHandlerUPP(DoMouseDown); InstallApplicationEventHandler (handlerUPP, 1, &eventType, this, nil); eventType.eventKind = kEventMouseUp; handlerUPP = NewEventHandlerUPP(DoMouseUp); InstallApplicationEventHandler (handlerUPP, 1, &eventType, this, nil); eventType.eventKind = kEventMouseDragged; handlerUPP = NewEventHandlerUPP(DoMouseDragged); InstallApplicationEventHandler (handlerUPP, 1, &eventType, this, nil); eventType.eventClass = kEventClassKeyboard; eventType.eventKind = kEventRawKeyDown; handlerUPP = NewEventHandlerUPP(DoKeyDown); InstallApplicationEventHandler (handlerUPP, 1, &eventType, this, nil); eventType.eventKind = kEventRawKeyUp; handlerUPP = NewEventHandlerUPP(DoKeyUp); InstallApplicationEventHandler (handlerUPP, 1, &eventType, this, nil); eventType.eventKind = kEventRawKeyRepeat; handlerUPP = NewEventHandlerUPP(DoKeyDown); // 'key repeat' is translated to 'key down' InstallApplicationEventHandler (handlerUPP, 1, &eventType, this, nil); WindowAttributes windowAttrs; Rect bounds; // window windowAttrs = kWindowCloseBoxAttribute | kWindowCollapseBoxAttribute | kWindowStandardHandlerAttribute; SetRect (&bounds, 0, 0, width, height); OffsetRect (&bounds, 100, 100); CreateNewWindow (kDocumentWindowClass, windowAttrs, &bounds, &m_specific->m_window); if(m_specific->m_window == nil) { return false; } // I assume the text is ASCII. // Change to kCFStringEncodingMacRoman, kCFStringEncodingISOLatin1, kCFStringEncodingUTF8 or what else you need. SetWindowTitleWithCFString (m_specific->m_window, CFStringCreateWithCStringNoCopy (nil, m_caption, kCFStringEncodingASCII, nil)); eventType.eventClass = kEventClassWindow; eventType.eventKind = kEventWindowClose; handlerUPP = NewEventHandlerUPP(DoWindowClose); InstallWindowEventHandler (m_specific->m_window, handlerUPP, 1, &eventType, this, NULL); eventType.eventKind = kEventWindowDrawContent; handlerUPP = NewEventHandlerUPP(DoWindowDrawContent); InstallWindowEventHandler (m_specific->m_window, handlerUPP, 1, &eventType, this, NULL); // Periodic task // Instead of an idle function I use the Carbon event timer. // You may decide to change the wait value which is currently 50 milliseconds. EventLoopRef mainLoop; EventLoopTimerUPP timerUPP; EventLoopTimerRef theTimer; mainLoop = GetMainEventLoop(); timerUPP = NewEventLoopTimerUPP (DoPeriodicTask); InstallEventLoopTimer (mainLoop, 0, 50 * kEventDurationMillisecond, timerUPP, this, &theTimer); m_specific->create_pmap(width, height, &m_rbuf_window); m_initial_width = width; m_initial_height = height; on_init(); on_resize(width, height); m_specific->m_redraw_flag = true; ShowWindow (m_specific->m_window); SetPortWindowPort (m_specific->m_window); return true; }