/* if 0 is returned then the client should not be touched, however if -1 * is returned then the caller is responsible for handling the client */ static int add_listener_to_source (source_t *source, client_t *client) { int loop = 10; do { DEBUG3 ("max on %s is %ld (cur %lu)", source->mount, source->max_listeners, source->listeners); if (source->max_listeners == -1) break; if (source->listeners < (unsigned long)source->max_listeners) break; if (loop && source->fallback_when_full && source->fallback_mount) { source_t *next = source_find_mount (source->fallback_mount); if (!next) { ERROR2("Fallback '%s' for full source '%s' not found", source->mount, source->fallback_mount); return -1; } INFO1 ("stream full trying %s", next->mount); source = next; loop--; continue; } /* now we fail the client */ return -1; } while (1); client->write_to_client = format_generic_write_to_client; client->check_buffer = format_check_http_buffer; client->refbuf->len = PER_CLIENT_REFBUF_SIZE; memset (client->refbuf->data, 0, PER_CLIENT_REFBUF_SIZE); /* lets add the client to the active list */ avl_tree_wlock (source->pending_tree); avl_insert (source->pending_tree, client); avl_tree_unlock (source->pending_tree); if (source->running == 0 && source->on_demand) { /* enable on-demand relay to start, wake up the slave thread */ DEBUG0("kicking off on-demand relay"); source->on_demand_req = 1; } DEBUG1 ("Added client to %s", source->mount); return 0; }
Cursor* CursorStack::SetTop(Cursor* pCursor, INT32 cursorID) { // cursorID will be zero if unmodified code is used. if (cursorID == 0) { ERROR3("CursorStack::SetTop called without a valid cursorID. Please change the offending code.\n"); Cursor* pc; if (nNextFreeSlot > 0) { pc = pcStack[nNextFreeSlot - 1].pCursor; pcStack[nNextFreeSlot - 1].pCursor = pCursor; } else { pc = NULL; Push(pCursor); } SetActive(); return pc; } else { // This is the new case INT32 n=0; // Counter to go through the stack // Find the ID on the stack and replace it with the new cursor while(n<nNextFreeSlot) { if (pcStack[n].UniqueID == cursorID) { Cursor* pc = pcStack[n].pCursor; // for return if (pc == pCursor) return pc; // Don't try and set the cursor if it's the same // Replace this cursor with the new one pcStack[n].pCursor = pCursor; if (nNextFreeSlot > 0) SetActive(); // Finally, return the pointer to the cursor we've just removed from the stack return pc; } n++; } // Oh dear, we seem not to have found this cursorID on the stack. ERROR2(NULL,"cursorID not found on stack in SetTop.\n"); } }
BOOL RIFFFile::GetChunkData(ADDR Block, INT32 BSize, INT32 Offset) { // first of all, check to see if the caller has been a little bit silly if(ObjType != RIFFOBJECTTYPE_CHUNK) { Error = TRUE; // only chunks have getable data ERROR2(FALSE, "RIFFFile::GetChunkData called for a non-chunk object\n"); } // check offset is OK if(Offset >= ObjSize) Offset = ObjSize - 1; // check that we'll be grabbing a nice amount of data if((Offset + BSize) > ObjSize) BSize = ObjSize - Offset; // don't do anything if there's no data to get if(BSize <= 0) return TRUE; // where in the file do we wish to get data from? INT32 TargetLocation = ObjLocation + Offset; // seek to the data we want, but only if it's necessary if(TargetLocation != Location) { if(File->seek(TargetLocation).bad()) RIFFFILE_RETURNERR; Location = TargetLocation; } // and get that data! if(File->read(Block, BSize).bad()) { TRACEUSER( "Ben", _T("RIFFFile: file error when reading chunk data\n")); RIFFFILE_RETURNERR; } // update locations Location += BSize; // and set an essential flag! GotData = TRUE; return TRUE; }
/* handler for curl, checks if successful handling occurred * return 0 for ok, -1 for this entry failed, -2 for server fail. * On failure case, update and process are modified */ static int send_to_yp (const char *cmd, ypdata_t *yp, char *post) { int curlcode; struct yp_server *server = yp->server; /* DEBUG2 ("send YP (%s):%s", cmd, post); */ yp->cmd_ok = 0; curl_easy_setopt (server->curl, CURLOPT_POSTFIELDS, post); curl_easy_setopt (server->curl, CURLOPT_WRITEHEADER, yp); curlcode = curl_easy_perform (server->curl); if (curlcode) { yp->process = do_yp_add; yp_schedule (yp, 1200); ERROR2 ("connection to %s failed with \"%s\"", server->url, server->curl_error); return -2; } if (yp->cmd_ok == 0) { if (yp->error_msg == NULL) yp->error_msg = strdup ("no response from server"); if (yp->process == do_yp_add) { ERROR3 ("YP %s on %s failed: %s", cmd, server->url, yp->error_msg); yp_schedule (yp, 7200); } if (yp->process == do_yp_touch) { /* At this point the touch request failed, either because they rejected our session * or the server isn't accessible. This means we have to wait before doing another * add request. We have a minimum delay but we could allow the directory server to * give us a wait time using the TouchFreq header. This time could be given in such * cases as a firewall block or incorrect listenurl. */ if (yp->touch_interval < 1200) yp_schedule (yp, 1200); else yp_schedule (yp, yp->touch_interval); INFO3 ("YP %s on %s failed: %s", cmd, server->url, yp->error_msg); } yp->process = do_yp_add; free (yp->sid); yp->sid = NULL; return -1; } DEBUG2 ("YP %s at %s succeeded", cmd, server->url); return 0; }
BOOL PSPrintDC::MakeRoomInBuffer(INT32 nBytesRequired) { if (nBytesRequired >= MAX_PSBUF) { // Can't ever do that many bytes! ERROR2(FALSE, "Too many bytes asked for in PSPrintDC::MakeRoomInBuffer()"); } // Do we need to flush? if (nBytesRequired > (MAX_PSBUF - Buffer.nCount)) // Yes return FlushPSBuffer(); // All ok if we get here return TRUE; }
INT32 test2(INT32 which) { if (which==0) { ERROR2RAW( "Simple raw error" ); return 0; } if (which==1) ERROR2( 10, "Simple error" ); if (which==2) ERROR2IF( TRUE, 20, "Simple error if"); if (which==3) ERROR2_PF( 30, ("String (%s)", "blobby") ); if (which==4) ERROR2IF_PF( TRUE, 40, ("Numbers (%d,%d)" , 42,43) ); return 0; }
//Update the Xml File and save changes void QSXML::QUpdate(QList<QShow> MListe) { if(!xml_doc.open(QIODevice::ReadOnly))// Si l'on n'arrive pas à ouvrir le fichier XML. { QNotification ERROR1("Erreur à l'ouverture du document XML","Le document XML n'a pas pu être ouvert. Vérifiez que le nom est le bon et que le document est bien placé"); return; } if (!dom->setContent(&xml_doc)) // Si l'on n'arrive pas à associer le fichier XML à l'objet DOM. { xml_doc.close(); QNotification ERROR2("Erreur à l'ouverture du document XML","Le document XML n'a pas pu être attribué à l'objet QDomDocument."); return; } xml_doc.close(); // Dans tous les cas, on doit fermer le document XML : on n'en a plus besoin, tout est compris dans l'objet DOM. QDomElement root = dom->documentElement();//root for(int i=0;i<MListe.count();i++) { QDomNode n = root.firstChild(); while(!n.isNull()) { QDomElement e = n.toElement(); if(!e.isNull()) { if(e.text() == MListe[i].Name) { e.setAttribute("episode", MListe[i].Episode); break; } } n = n.nextSibling(); } } QFile FinalFile("Series.xml"); if( !FinalFile.open(QIODevice::WriteOnly) ) qDebug() << "Erreur de sauvegarde"; QTextStream out ( &FinalFile); out << dom->toString(); FinalFile.close(); }
// Creates the Gv-Pl interaction, which replaces the Gv-Ss-Pl bend // term. Only do this on the 5' side. static void pam5_groove_phosphate_match(struct patternMatch *match) { struct part *p = match->p; struct atom *aGv = p->atoms[match->atomIndices[0]]; struct atom *aSs = p->atoms[match->atomIndices[1]]; struct atom *aPl = p->atoms[match->atomIndices[2]]; struct bond *b = getBond(p, aPl, aSs); BAIL(); struct bond *bond; struct bend *bend; int reverse; char order; pam5_requires_gromacs(p); BAIL(); switch (b->direction) { case 'F': reverse = (b->a1 == aSs); break; case 'R': reverse = (b->a1 == aPl); break; default: ERROR2("pam5_phosphate_sugar_match: bond between ids %d and %d has no direction", aPl->atomID, aSs->atomID); p->parseError(p->stream); return; } if (reverse) { order = '2'; } else { order = '1'; bend = getBend(p, aGv, aSs, aPl); bend->bendType = bend_Gv_Ss_Pl_5; } bond = makeBond(p, aPl, aGv, order); queueBond(p, bond); trace_makeBond(match, bond); //printMatch(match); }
// returns -1 on error int DAUDIO_Read(void* id, char* data, int byteSize) { AlsaPcmInfo* info = (AlsaPcmInfo*) id; int ret, count; snd_pcm_sframes_t frameSize, readFrames; TRACE1("> DAUDIO_Read %d bytes\n", byteSize); /*TRACE3(" info=%p, data=%p, byteSize=%d\n", (void*) info, (void*) data, (int) byteSize); TRACE2(" info->frameSize=%d, info->handle=%p\n", (int) info->frameSize, (void*) info->handle); */ /* sanity */ if (byteSize <= 0 || info->frameSize <= 0) { ERROR2(" DAUDIO_Read: byteSize=%d, frameSize=%d!\n", (int) byteSize, (int) info->frameSize); TRACE0("< DAUDIO_Read returning -1\n"); return -1; } count = 2; // maximum number of trials to recover from error //frameSize = snd_pcm_bytes_to_frames(info->handle, byteSize); frameSize = (snd_pcm_sframes_t) (byteSize / info->frameSize); do { readFrames = snd_pcm_readi(info->handle, (void*) data, (snd_pcm_uframes_t) frameSize); if (readFrames < 0) { ret = xrun_recovery(info, (int) readFrames); if (ret <= 0) { TRACE1("DAUDIO_Read: xrun recovery returned %d -> return.\n", ret); return ret; } if (count-- <= 0) { ERROR0("DAUDIO_Read: too many attempts to recover from xrun/suspend\n"); return -1; } } else { break; } } while (TRUE); //ret = snd_pcm_frames_to_bytes(info->handle, readFrames); ret = (int) (readFrames * info->frameSize); TRACE1("< DAUDIO_Read: returning %d bytes.\n", ret); return ret; }
BOOL PrintPSRenderRegion::WriteSepFunctions(KernelDC *pDC) { PrintControl *pPrintCtl=NULL; View *pView = GetRenderView(); if (pView) pPrintCtl = pView->GetPrintControl(); if (!pPrintCtl) return TRUE; // Get a pointer to the typeset info structure TypesetInfo *pInfo = pPrintCtl->GetTypesetInfo(); // Is screening off? if (!pInfo->AreScreening()) return TRUE; // Get hold of our PostScript prolog resource... CCResTextFile ScreenFile; // Open the file if (!ScreenFile.open(_R(IDM_PS_SPOTFUNCS), _R(IDT_PS_RES))) { // Failed to open the file... ERROR2(FALSE, "Could not get at PostScript resource!"); } // Read each line from the file and output it to the DC. String_256 LineBuf; TCHAR *pBuf = (TCHAR *) LineBuf; while (!ScreenFile.eof()) { // Copy this line to output. ScreenFile.read(&LineBuf); pDC->OutputTCHARAsChar(pBuf, LineBuf.Length()); pDC->OutputNewLine(); } // All done ScreenFile.close(); return TRUE; }
// returns -1 on error int DAUDIO_Write(void* id, char* data, int byteSize) { AlsaPcmInfo* info = (AlsaPcmInfo*) id; int ret, count; snd_pcm_sframes_t frameSize, writtenFrames; TRACE1("> DAUDIO_Write %d bytes\n", byteSize); /* sanity */ if (byteSize <= 0 || info->frameSize <= 0) { ERROR2(" DAUDIO_Write: byteSize=%d, frameSize=%d!\n", (int) byteSize, (int) info->frameSize); TRACE0("< DAUDIO_Write returning -1\n"); return -1; } count = 2; // maximum number of trials to recover from underrun //frameSize = snd_pcm_bytes_to_frames(info->handle, byteSize); frameSize = (snd_pcm_sframes_t) (byteSize / info->frameSize); do { writtenFrames = snd_pcm_writei(info->handle, (const void*) data, (snd_pcm_uframes_t) frameSize); if (writtenFrames < 0) { ret = xrun_recovery(info, (int) writtenFrames); if (ret <= 0) { TRACE1("DAUDIO_Write: xrun recovery returned %d -> return.\n", ret); return ret; } if (count-- <= 0) { ERROR0("DAUDIO_Write: too many attempts to recover from xrun/suspend\n"); return -1; } } else { break; } } while (TRUE); //ret = snd_pcm_frames_to_bytes(info->handle, writtenFrames); ret = (int) (writtenFrames * info->frameSize); TRACE1("< DAUDIO_Write: returning %d bytes.\n", ret); return ret; }
minipro_handle_t *minipro_open(device_t *device) { int ret; minipro_handle_t *handle = malloc(sizeof(minipro_handle_t)); if(handle == NULL) { ERROR("Couldn't malloc"); } ret = libusb_init(&(handle->ctx)); if(ret < 0) { free(handle); ERROR2("Error initializing libusb: %s", libusb_strerror(ret)); } handle->usb_handle = libusb_open_device_with_vid_pid(handle->ctx, 0x04d8, 0xe11c); if(handle->usb_handle == NULL) { free(handle); ERROR("Error opening device"); } handle->device = device; return(handle); }
extern int fdwatch_update_fd(int idx, unsigned rw) { if (idx < 0 || idx >= fdw_maxcons) { ERROR2("out of bounds idx [{}] (max: {})", idx, fdw_maxcons); return -1; } /* do not allow completly reset the access because then backend codes * can get confused */ if (!rw) { ERROR0("tried to reset rw, not allowed"); return -1; } if (!fdw_rw(fdw_fds + idx)) { ERROR0("found reseted rw"); return -1; } if (fdw->add(idx, rw)) return -1; fdw_rw(&fdw_fds[idx]) = rw; return 0; }
//execute the main fonction void QSXML::exec() { if(!xml_doc.open(QIODevice::ReadOnly))// Si l'on n'arrive pas à ouvrir le fichier XML. { QNotification ERROR1("Erreur à l'ouverture du document XML","Le document XML n'a pas pu être ouvert. Vérifiez que le nom est le bon et que le document est bien placé"); return; } if (!dom->setContent(&xml_doc)) // Si l'on n'arrive pas à associer le fichier XML à l'objet DOM. { xml_doc.close(); QNotification ERROR2("Erreur à l'ouverture du document XML","Le document XML n'a pas pu être attribué à l'objet QDomDocument."); return; } xml_doc.close(); // Dans tous les cas, on doit fermer le document XML : on n'en a plus besoin, tout est compris dans l'objet DOM. QDomElement root = dom->documentElement();//root QDomNode node = root.firstChild();//First child QDomElement element = node.toElement(); Show.clear(); while(!node.isNull()) { QShow elm; elm.url.setUrl(element.attribute("url","NULL")); elm.Name = element.text(); elm.Episode = element.attribute("episode","NULL"); elm.Season = element.attribute("saison","NULL"); Show.append(elm); node = node.nextSibling(); element=node.toElement(); } }
//----------------------------------------------------------------------------- void CStageLaser::updateData( const double dt ) { if ( mFgEnabled ) { // get range data from stage, if the simulation is paused at start up // stage returns NULL, so we store the result in a temporal variable // and store is only if it is any good Stg::ModelRanger::Sensor sensor = mStgLaser->GetSensors()[0]; uint32_t sampleCount = sensor.sample_count; if ( sampleCount != mNumSamples ) { ERROR2( "Got wrong number of laser readings from Stage, "\ "expected %d but got %d", mNumSamples, sampleCount ); } else { if ( !sensor.ranges.empty() ) { //!sample.empty() ) { for ( unsigned int i = 0; i < mNumSamples; i ++ ) { mRangeData[i].range = sensor.ranges[i]; mRangeData[i].reflectance = sensor.intensities[i]; } } } mTimeStamp = mStgLaser->GetWorld()->SimTimeNow() / 1e6; notifyDataUpdateObservers(); } }
CMProperty CM_FIXEDARGS CMRegisterProperty(CMContainer targetContainer, CMconst_CMGlobalName name) { TOCObjectPtr p; GlobalNamePtr g; ContainerPtr container = (ContainerPtr)targetContainer; NOPifNotInitialized(NULL); /* NOP if not initialized! */ g = cmLookupGlobalName(container->globalNameTable, (CM_UCHAR *)name); if (!SessionSuccess) { ERROR2(CM_err_GloblaNameError, name, CONTAINERNAME); return (NULL); } if (g && g->theValue) { p = g->theValue->theValueHdr->theProperty->theObject; if ((p->objectFlags & PropertyObject) == 0) { ERROR4(CM_err_MultTypeProp, "type", name, CONTAINERNAME, (p->objectFlags & TypeObject) ? "type" : "object"); p = NULL; } else ++p->useCount; /* bump this object's use count */ } else { p = cmDefineGlobalNameObject(container, container->nextUserObjectID, CM_StdObjID_GlobalPropName, CM_StdObjID_7BitASCII, (CM_UCHAR *)name, container->generation, 0, PropertyObject); if (p) { p->useCount = 1; /* initial use of this object */ IncrementObjectID(container->nextUserObjectID); } } return ((CMProperty)p); }
/////////////////////////////////////////////////////////////////////// // PrepAndLaunchRedirectedChild // Sets up STARTUPINFO structure, and launches redirected child. /////////////////////////////////////////////////////////////////////// HANDLE System::PrepAndLaunchRedirectedChild( const char *command, HANDLE hChildStdOut, HANDLE hChildStdIn, HANDLE hChildStdErr) { FUNCTION_TRACE; char *file=NULL; int pos=0; bool in_quote=false; for (pos=0;command[pos]!='\0';pos++) { if (command[pos]=='"') in_quote = ! in_quote; if (in_quote) continue; if (command[pos]==' ') break; } file=(char*)MALLOC(pos+1+4); if (command[0]=='"') { // stripping quotes memcpy(file,&command[1],pos-1); for (int i=0;i<pos-1;i++) if (file[i]=='"') file[i]='\0'; } else memcpy(file,command,pos); file[pos]='\0'; const char*extension=".exe"; size_t file_lg=strlen(file); if (file_lg<4 || ! (strcmp(extension,&file[file_lg-4])==0) ) strcat(file,extension); wchar_t actDirBuffer[MAX_PATH]; GetCurrentDirectory(MAX_PATH, actDirBuffer); size_t file_sz=strlen(file); wchar_t *file_w=(wchar_t*)MALLOC((file_sz+1)*sizeof(wchar_t)); wchar_t file_abs_w[MAX_PATH+4]; wchar_t *file_name_w; wchar_t extension_w[50];; mbstowcs(extension_w,extension,sizeof(extension)); mbstowcs(file_w,file,file_sz+1); size_t cmdBuffer_sz=strlen(command); wchar_t *cmdBuffer_w=(wchar_t*)MALLOC((cmdBuffer_sz+1)*sizeof(wchar_t)); mbstowcs(cmdBuffer_w,command,cmdBuffer_sz+1); if (SearchPath(NULL,file_w,extension_w,MAX_PATH,file_abs_w,&file_name_w)==0) { FATAL3("Error: finding path of %s: %u",file,GetLastError()); } STARTUPINFO si; // Set up the start up info struct. ZeroMemory(&si,sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); if (capture_stdout) { si.dwFlags = STARTF_USESTDHANDLES; si.hStdOutput = hChildStdOut; si.hStdInput = hChildStdIn; si.hStdError = hChildStdErr; // Use this if you want to hide the child: // si.wShowWindow = SW_HIDE; // Note that dwFlags must include STARTF_USESHOWWINDOW if you want to // use the wShowWindow flags. } // Launch the process that you want to redirect (in this case, // Child.exe). Make sure Child.exe is in the same directory as // redirect.c launch redirect from a command line to prevent location // confusion. if (!CreateProcess(file_abs_w,cmdBuffer_w,NULL,NULL,TRUE, 0, NULL,NULL,&si,&pi)) { ERROR2("CreateProcess errno:%i\n",GetLastError()); return false; } // Set global child process handle to cause threads to exit. HANDLE hChildProcess = pi.hProcess; // Close any unnecessary handles. //if (!CloseHandle(pi.hThread)) ERROR2("CloseHandle errno:%i\n",GetLastError()); return hChildProcess; }
void DAUDIO_GetFormats(INT32 mixerIndex, INT32 deviceID, int isSource, void* creator) { snd_pcm_t* handle; snd_pcm_format_mask_t* formatMask; snd_pcm_format_t format; snd_pcm_hw_params_t* hwParams; int handledBits[MAX_BIT_INDEX+1]; int ret; int sampleSizeInBytes, significantBits, isSigned, isBigEndian, enc; int origSampleSizeInBytes, origSignificantBits; int channels, minChannels, maxChannels; int rate, bitIndex; for (bitIndex = 0; bitIndex <= MAX_BIT_INDEX; bitIndex++) handledBits[bitIndex] = FALSE; if (openPCMfromDeviceID(deviceID, &handle, isSource, TRUE /*query hardware*/) < 0) { return; } ret = snd_pcm_format_mask_malloc(&formatMask); if (ret != 0) { ERROR1("snd_pcm_format_mask_malloc returned error %d\n", ret); } else { ret = snd_pcm_hw_params_malloc(&hwParams); if (ret != 0) { ERROR1("snd_pcm_hw_params_malloc returned error %d\n", ret); } else { ret = snd_pcm_hw_params_any(handle, hwParams); if (ret != 0) { ERROR1("snd_pcm_hw_params_any returned error %d\n", ret); } } snd_pcm_hw_params_get_format_mask(hwParams, formatMask); #ifdef ALSA_PCM_NEW_HW_PARAMS_API if (ret == 0) { ret = snd_pcm_hw_params_get_channels_min(hwParams, &minChannels); if (ret != 0) { ERROR1("snd_pcm_hw_params_get_channels_min returned error %d\n", ret); } } if (ret == 0) { ret = snd_pcm_hw_params_get_channels_max(hwParams, &maxChannels); if (ret != 0) { ERROR1("snd_pcm_hw_params_get_channels_max returned error %d\n", ret); } } #else minChannels = snd_pcm_hw_params_get_channels_min(hwParams); maxChannels = snd_pcm_hw_params_get_channels_max(hwParams); if (minChannels > maxChannels) { ERROR2("MinChannels=%d, maxChannels=%d\n", minChannels, maxChannels); } #endif // since we queried the hw: device, for many soundcards, it will only // report the maximum number of channels (which is the only way to talk // to the hw: device). Since we will, however, open the plughw: device // when opening the Source/TargetDataLine, we can safely assume that // also the channels 1..maxChannels are available. #ifdef ALSA_PCM_USE_PLUGHW minChannels = 1; #endif if (ret == 0) { // plughw: supports any sample rate rate = -1; for (format = 0; format <= SND_PCM_FORMAT_LAST; format++) { if (snd_pcm_format_mask_test(formatMask, format)) { // format exists if (getFormatFromAlsaFormat(format, &origSampleSizeInBytes, &origSignificantBits, &isSigned, &isBigEndian, &enc)) { // now if we use plughw:, we can use any bit size below the // natively supported ones. Some ALSA drivers only support the maximum // bit size, so we add any sample rates below the reported one. // E.g. this iteration reports support for 16-bit. // getBitIndex will return 2, so it will add entries for // 16-bit (bitIndex=2) and in the next do-while loop iteration, // it will decrease bitIndex and will therefore add 8-bit support. bitIndex = getBitIndex(origSampleSizeInBytes, origSignificantBits); do { if (bitIndex == 0 || bitIndex == MAX_BIT_INDEX || !handledBits[bitIndex]) { handledBits[bitIndex] = TRUE; sampleSizeInBytes = getSampleSizeInBytes(bitIndex, origSampleSizeInBytes); significantBits = getSignificantBits(bitIndex, origSignificantBits); if (maxChannels - minChannels > MAXIMUM_LISTED_CHANNELS) { // avoid too many channels explicitly listed // just add -1, min, and max DAUDIO_AddAudioFormat(creator, significantBits, -1, -1, rate, enc, isSigned, isBigEndian); DAUDIO_AddAudioFormat(creator, significantBits, sampleSizeInBytes * minChannels, minChannels, rate, enc, isSigned, isBigEndian); DAUDIO_AddAudioFormat(creator, significantBits, sampleSizeInBytes * maxChannels, maxChannels, rate, enc, isSigned, isBigEndian); } else { for (channels = minChannels; channels <= maxChannels; channels++) { DAUDIO_AddAudioFormat(creator, significantBits, (channels < 0)?-1:(sampleSizeInBytes * channels), channels, rate, enc, isSigned, isBigEndian); } } } #ifndef ALSA_PCM_USE_PLUGHW // without plugin, do not add fake formats break; #endif } while (--bitIndex > 0); } else { TRACE1("could not get format from alsa for format %d\n", format); } } else { //TRACE1("Format %d not supported\n", format); } } // for loop snd_pcm_hw_params_free(hwParams); } snd_pcm_format_mask_free(formatMask); } snd_pcm_close(handle); }
// returns TRUE if successful int setHWParams(AlsaPcmInfo* info, float sampleRate, int channels, int bufferSizeInFrames, snd_pcm_format_t format) { unsigned int rrate; int ret, dir, periods, periodTime; snd_pcm_uframes_t alsaBufferSizeInFrames = (snd_pcm_uframes_t) bufferSizeInFrames; /* choose all parameters */ ret = snd_pcm_hw_params_any(info->handle, info->hwParams); if (ret < 0) { ERROR1("Broken configuration: no configurations available: %s\n", snd_strerror(ret)); return FALSE; } /* set the interleaved read/write format */ ret = snd_pcm_hw_params_set_access(info->handle, info->hwParams, SND_PCM_ACCESS_RW_INTERLEAVED); if (ret < 0) { ERROR1("SND_PCM_ACCESS_RW_INTERLEAVED access type not available: %s\n", snd_strerror(ret)); return FALSE; } /* set the sample format */ ret = snd_pcm_hw_params_set_format(info->handle, info->hwParams, format); if (ret < 0) { ERROR1("Sample format not available: %s\n", snd_strerror(ret)); return FALSE; } /* set the count of channels */ ret = snd_pcm_hw_params_set_channels(info->handle, info->hwParams, channels); if (ret < 0) { ERROR2("Channels count (%d) not available: %s\n", channels, snd_strerror(ret)); return FALSE; } /* set the stream rate */ rrate = (int) (sampleRate + 0.5f); #ifdef ALSA_PCM_NEW_HW_PARAMS_API dir = 0; ret = snd_pcm_hw_params_set_rate_near(info->handle, info->hwParams, &rrate, &dir); #else ret = snd_pcm_hw_params_set_rate_near(info->handle, info->hwParams, rrate, 0); #endif if (ret < 0) { ERROR2("Rate %dHz not available for playback: %s\n", (int) (sampleRate+0.5f), snd_strerror(ret)); return FALSE; } if ((rrate-sampleRate > 2) || (rrate-sampleRate < - 2)) { ERROR2("Rate doesn't match (requested %2.2fHz, got %dHz)\n", sampleRate, rrate); return FALSE; } /* set the buffer time */ #ifdef ALSA_PCM_NEW_HW_PARAMS_API ret = snd_pcm_hw_params_set_buffer_size_near(info->handle, info->hwParams, &alsaBufferSizeInFrames); #else ret = snd_pcm_hw_params_set_buffer_size_near(info->handle, info->hwParams, alsaBufferSizeInFrames); #endif if (ret < 0) { ERROR2("Unable to set buffer size to %d frames: %s\n", (int) alsaBufferSizeInFrames, snd_strerror(ret)); return FALSE; } bufferSizeInFrames = (int) alsaBufferSizeInFrames; /* set the period time */ if (bufferSizeInFrames > 1024) { dir = 0; periodTime = DEFAULT_PERIOD_TIME; #ifdef ALSA_PCM_NEW_HW_PARAMS_API ret = snd_pcm_hw_params_set_period_time_near(info->handle, info->hwParams, &periodTime, &dir); #else periodTime = snd_pcm_hw_params_set_period_time_near(info->handle, info->hwParams, periodTime, &dir); ret = periodTime; #endif if (ret < 0) { ERROR2("Unable to set period time to %d: %s\n", DEFAULT_PERIOD_TIME, snd_strerror(ret)); return FALSE; } } else { /* set the period count for very small buffer sizes to 2 */ dir = 0; periods = 2; #ifdef ALSA_PCM_NEW_HW_PARAMS_API ret = snd_pcm_hw_params_set_periods_near(info->handle, info->hwParams, &periods, &dir); #else periods = snd_pcm_hw_params_set_periods_near(info->handle, info->hwParams, periods, &dir); ret = periods; #endif if (ret < 0) { ERROR2("Unable to set period count to %d: %s\n", /*periods*/ 2, snd_strerror(ret)); return FALSE; } } /* write the parameters to device */ ret = snd_pcm_hw_params(info->handle, info->hwParams); if (ret < 0) { ERROR1("Unable to set hw params: %s\n", snd_strerror(ret)); return FALSE; } return TRUE; }
bool System::call(const char *command,bool capt_stdout) { hOutputRead=NULL; hInputWrite=NULL; capture_stdout=capt_stdout; hChildProcess = NULL; HANDLE hOutputWrite=GetStdHandle(STD_OUTPUT_HANDLE); HANDLE hInputRead=GetStdHandle(STD_INPUT_HANDLE); SECURITY_ATTRIBUTES sa; // Set up the security attributes struct. sa.nLength= sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; if (capture_stdout) { HANDLE hOutputReadTmp=NULL; HANDLE hInputWriteTmp=NULL; // Create the child output pipe. if (!CreatePipe(&hOutputReadTmp,&hOutputWrite,&sa,0)) { ERROR2("CreatePipe errno:%i\n",GetLastError()); return false; } // Create the child input pipe. if (!CreatePipe(&hInputRead,&hInputWriteTmp,&sa,0)) { ERROR2("CreatePipe errno:%i\n",GetLastError()); return false; } // Create new output read handle and the input write handles. Set // the Properties to FALSE. Otherwise, the child inherits the // properties and, as a result, non-closeable handles to the pipes // are created. if (!DuplicateHandle(GetCurrentProcess(),hOutputReadTmp, GetCurrentProcess(), &hOutputRead, // Address of new handle. 0,FALSE, // Make it uninheritable. DUPLICATE_SAME_ACCESS)) { ERROR2("DupliateHandle errno:%i\n",GetLastError()); return false; } if (!DuplicateHandle(GetCurrentProcess(),hInputWriteTmp, GetCurrentProcess(), &hInputWrite, // Address of new handle. 0,FALSE, // Make it uninheritable. DUPLICATE_SAME_ACCESS)) { ERROR2("DupliateHandle errno:%i\n",GetLastError()); return false; } // Close inheritable copies of the handles you do not want to be // inherited. if (!CloseHandle(hOutputReadTmp)) { ERROR2("CloseHandle errno:%i\n",GetLastError()); return false; } if (!CloseHandle(hInputWriteTmp)) { ERROR2("CloseHandle errno:%i\n",GetLastError()); return false; } } hChildProcess = PrepAndLaunchRedirectedChild(command,hOutputWrite,hInputRead,GetStdHandle(STD_ERROR_HANDLE)); if (capt_stdout) { // Close pipe handles (do not continue to modify the parent). // You need to make sure that no handles to the write end of the // output pipe are maintained in this process or else the pipe will // not close when the child process exits and the ReadFile will hang. if (!CloseHandle(hOutputWrite)) { ERROR2("CloseHandle errno:%i\n",GetLastError()); return false; } if (!CloseHandle(hInputRead )) { ERROR2("CloseHandle errno:%i\n",GetLastError()); return false; } } return true; }
static void test2() { const size32_t recsize = 17; printf("Test DFS\n"); StringBuffer s; unsigned i; unsigned n; unsigned t; queryNamedGroupStore().remove("daregress_group"); queryDistributedFileDirectory().removeEntry("daregress::superfile1"); SocketEndpointArray epa; for (n=0;n<400;n++) { s.clear().append("192.168.").append(n/256).append('.').append(n%256); SocketEndpoint ep(s.str()); epa.append(ep); } Owned<IGroup> group = createIGroup(epa); queryNamedGroupStore().add("daregress_group",group,true); if (!queryNamedGroupStore().find(group,s.clear())) ERROR("Created logical group not found"); if (stricmp(s.str(),"daregress_group")!=0) ERROR("Created logical group found with wrong name"); group.setown(queryNamedGroupStore().lookup("daregress_group")); if (!group) ERROR("named group lookup failed"); printf("Named group created - 400 nodes\n"); for (i=0;i<100;i++) { Owned<IPropertyTree> pp = createPTree("Part"); Owned<IFileDescriptor>fdesc = createFileDescriptor(); fdesc->setDefaultDir("c:\\thordata\\regress"); n = 9; for (unsigned k=0;k<400;k++) { s.clear().append("192.168.").append(n/256).append('.').append(n%256); Owned<INode> node = createINode(s.str()); pp->setPropInt64("@size",(n*777+i)*recsize); s.clear().append("daregress_test").append(i).append("._").append(n+1).append("_of_400"); fdesc->setPart(n,node,s.str(),pp); n = (n+9)%400; } fdesc->queryProperties().setPropInt("@recordSize",17); s.clear().append("daregress::test").append(i); queryDistributedFileDirectory().removeEntry(s.str()); StringBuffer cname; Owned<IDistributedFile> dfile = queryDistributedFileDirectory().createNew(fdesc); if (stricmp(dfile->getClusterName(0,cname),"daregress_group")!=0) ERROR1("Cluster name wrong %d",i); s.clear().append("daregress::test").append(i); dfile->attach(s.str()); } printf("DFile create done - 100 files\n"); unsigned samples = 5; t = 33; for (i=0;i<100;i++) { s.clear().append("daregress::test").append(t); if (!queryDistributedFileDirectory().exists(s.str())) ERROR1("Could not find %s",s.str()); Owned<IDistributedFile> dfile = queryDistributedFileDirectory().lookup(s.str()); if (!dfile) { ERROR1("Could not find %s",s.str()); continue; } offset_t totsz = 0; n = 11; for (unsigned k=0;k<400;k++) { Owned<IDistributedFilePart> part = dfile->getPart(n); if (!part) { ERROR2("part not found %d %d",t,n); continue; } s.clear().append("192.168.").append(n/256).append('.').append(n%256); Owned<INode> node = createINode(s.str()); if (!node->equals(part->queryNode())) ERROR2("part node mismatch %d, %d",t,n); if (part->getFileSize(false,false)!=(n*777+t)*recsize) ERROR4("size node mismatch %d, %d, %d, %d",t,n,(unsigned)part->getFileSize(false,false),(n*777+t)*recsize); s.clear().append("daregress_test").append(t).append("._").append(n+1).append("_of_400"); /* ** TBD if (stricmp(s.str(),part->queryPartName())!=0) ERROR4("part name mismatch %d, %d '%s' '%s'",t,n,s.str(),part->queryPartName()); */ totsz += (n*777+t)*recsize; if ((samples>0)&&(i+n+t==k)) { samples--; RemoteFilename rfn; part->getFilename(rfn,samples%2); StringBuffer fn; rfn.getRemotePath(fn); printf("SAMPLE: %d,%d %s\n",t,n,fn.str()); } n = (n+11)%400; } if (totsz!=dfile->getFileSize(false,false)) ERROR1("total size mismatch %d",t); t = (t+33)%100; } printf("DFile lookup done - 100 files\n"); // check iteration __int64 crctot = 0; unsigned np = 0; unsigned totrows = 0; Owned<IDistributedFileIterator> fiter = queryDistributedFileDirectory().getIterator("daregress::*",false); Owned<IDistributedFilePartIterator> piter; ForEach(*fiter) { piter.setown(fiter->query().getIterator()); ForEach(*piter) { RemoteFilename rfn; StringBuffer s; piter->query().getFilename(rfn,0); rfn.getRemotePath(s); piter->query().getFilename(rfn,1); rfn.getRemotePath(s); crctot += crc32(s.str(),s.length(),0); np++; totrows += (unsigned)(piter->query().getFileSize(false,false)/fiter->query().queryProperties().getPropInt("@recordSize",-1)); } } piter.clear(); fiter.clear(); printf("DFile iterate done - %d parts, %d rows, CRC sum %"I64F"d\n",np,totrows,crctot); Owned<IDistributedSuperFile> sfile; sfile.setown(queryDistributedFileDirectory().createSuperFile("daregress::superfile1",true)); for (i = 0;i<100;i++) { s.clear().append("daregress::test").append(i); sfile->addSubFile(s.str()); } sfile.clear(); sfile.setown(queryDistributedFileDirectory().lookupSuperFile("daregress::superfile1")); if (!sfile) { ERROR("Could not find added superfile"); return; } __int64 savcrc = crctot; crctot = 0; np = 0; totrows = 0; size32_t srs = (size32_t)sfile->queryProperties().getPropInt("@recordSize",-1); if (srs!=17) ERROR1("Superfile does not match subfile row size %d",srs); piter.setown(sfile->getIterator()); ForEach(*piter) { RemoteFilename rfn; StringBuffer s; piter->query().getFilename(rfn,0); rfn.getRemotePath(s); piter->query().getFilename(rfn,1); rfn.getRemotePath(s); crctot += crc32(s.str(),s.length(),0); np++; totrows += (unsigned)(piter->query().getFileSize(false,false)/srs); } piter.clear(); printf("Superfile iterate done - %d parts, %d rows, CRC sum %"I64F"d\n",np,totrows,crctot); if (crctot!=savcrc) ERROR("SuperFile does not match sub files"); unsigned tr = (unsigned)(sfile->getFileSize(false,false)/srs); if (totrows!=tr) ERROR1("Superfile size does not match part sum %d",tr); sfile->detach(); sfile.clear(); sfile.setown(queryDistributedFileDirectory().lookupSuperFile("daregress::superfile1")); if (sfile) ERROR("Superfile deletion failed"); t = 37; for (i=0;i<100;i++) { s.clear().append("daregress::test").append(t); if (i%1) { Owned<IDistributedFile> dfile = queryDistributedFileDirectory().lookup(s.str()); if (!dfile) ERROR1("Could not find %s",s.str()); dfile->detach(); } else queryDistributedFileDirectory().removeEntry(s.str()); t = (t+37)%100; } printf("DFile removal complete\n"); t = 39; for (i=0;i<100;i++) { if (queryDistributedFileDirectory().exists(s.str())) ERROR1("Found %s after deletion",s.str()); Owned<IDistributedFile> dfile = queryDistributedFileDirectory().lookup(s.str()); if (dfile) ERROR1("Found %s after deletion",s.str()); t = (t+39)%100; } printf("DFile removal check complete\n"); queryNamedGroupStore().remove("daregress_group"); if (queryNamedGroupStore().lookup("daregress_group")) ERROR("Named group not removed"); }
BOOL OutputPNG::OutputPNGBits(CCLexFile *File, LPBYTE pBlockStart, BOOL OneBlock, BaseCamelotFilter *pFilter) { ERROR2IF(File==NULL,FALSE,"OutputPNG::OutputPNGHeader File pointer is null"); ERROR2IF(pBlockStart==NULL,FALSE,"OutputPNG::OutputPNGHeader BitmapInfo pointer is null"); // Check we have the PNG related items claimed (NOTE: p at end means pointer and hence implied *) // This would then imply that OutputPNGHeader has been called ERROR2IF(png_ptr == NULL || info_ptr == NULL,FALSE,"OutputPNG::OutputPNGHeader PNG related items not set up"); // Note file in our class variable as used by all the low level routines OutputFile = File; // Must set the exception throwing flag to True and force reporting of errors to False. // This means that the caller must report an error if the function returns False. // Any calls to CCFile::GotError will now throw a file exception and should fall into // the catch handler at the end of the function. // Replaces the goto's that handled this before. BOOL OldThrowingState = File->SetThrowExceptions( TRUE ); BOOL OldReportingState = File->SetReportErrors( FALSE ); try { // It is now ready to go and put that data onto the disc // so wait for the bitmap data to be prepared // turn on interlace handling if you are not using png_write_image() INT32 number_passes = 1; if (Interlace) number_passes = png_set_interlace_handling(png_ptr); // Work out how often we need to update the progress bar INT32 UpdateEvery = 1; if (pFilter == NULL) { if (number_passes > 1) UpdateEvery = (Height/(100*number_passes) + 1); else UpdateEvery = (Height/100 + 1); } INT32 LastProgressUpdate = 0; // Work out the word/byte rounded line width rather than the pixel width INT32 WidthOfLine = DIBUtil::ScanlineSize( Width, BitsPerPixel ); // The pointer to the actual bitmap data LPBYTE pBitsData = pBlockStart; LPBYTE pData = pBitsData; BOOL JobState = TRUE; // Of course being DIBs we need to write the data out upside down! i.e. bottom to top for (INT32 pass = 0; pass < number_passes; pass++) { pBitsData = pBlockStart; LastProgressUpdate = 0; for (INT32 ypos = 0; ypos < Height; ypos++) { // Read in from bottom upwards pData = pBitsData + ((Height - 1 - ypos) * WidthOfLine); // Write that row out to file png_write_row(png_ptr, pData); // Update the progress count, if required if (ypos > (LastProgressUpdate + UpdateEvery)) { // Note the update point so that we know the next one LastProgressUpdate = ypos; // Now update the progress display, started with 100, but only if pFilter is NULL if (pFilter == NULL) ContinueSlowJob( (INT32)(100 * ypos/Height * (pass + 1)/number_passes) ); else { // Ask the pFilter to update the progress bar for us JobState = TRUE; pFilter->IncProgressBarCount(1); } // If JobState is False then the user has probably pressed escape and we should // immediately stop what we are doing. if (!JobState) { File->GotError(_R(IDW_CANCELEXPORT)); // Expects error set on cancel return FALSE; } } } } // write the rest of the file png_write_end(png_ptr, info_ptr); // Call up function to clean up the png structures CleanUpPngStructures(); // Must set the exception throwing and reporting flags back to their entry states File->SetThrowExceptions( OldThrowingState ); File->SetReportErrors( OldReportingState ); // We have finished so reset the PNG exception handling PNGUtil::SetCCFilePointer(NULL); TRACEUSER( "Jonathan", _T("PNG write: Finished\n")); // er, we seem to have finished OK so say so return TRUE; } // CATCH( CFileException, e) catch (...) { // catch our form of a file exception TRACE( _T("OutputPNG::OutputPNGBits CC catch handler\n")); // Call up function to clean up the png structures CleanUpPngStructures(); // Must set the exception throwing and reporting flags back to their entry states File->SetThrowExceptions( OldThrowingState ); File->SetReportErrors( OldReportingState ); // We have finished so reset the PNG exception handling PNGUtil::SetCCFilePointer(NULL); return FALSE; } ERROR2( FALSE, "Escaped exception clause somehow" ); }
// for each ALSA device, call iterator. userData is passed to the iterator // returns total number of iterations int iteratePCMDevices(DeviceIteratorPtr iterator, void* userData) { int count = 0; int subdeviceCount; int card, dev, subDev; char devname[16]; int err; snd_ctl_t *handle; snd_pcm_t *pcm; snd_pcm_info_t* pcminfo; snd_ctl_card_info_t *cardinfo, *defcardinfo = NULL; UINT32 deviceID; int doContinue = TRUE; snd_pcm_info_malloc(&pcminfo); snd_ctl_card_info_malloc(&cardinfo); // 1st try "default" device err = snd_pcm_open(&pcm, ALSA_DEFAULT_DEVICE_NAME, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK); if (err < 0) { // try with the other direction err = snd_pcm_open(&pcm, ALSA_DEFAULT_DEVICE_NAME, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK); } if (err < 0) { ERROR1("ERROR: snd_pcm_open (\"default\"): %s\n", snd_strerror(err)); } else { err = snd_pcm_info(pcm, pcminfo); snd_pcm_close(pcm); if (err < 0) { ERROR1("ERROR: snd_pcm_info (\"default\"): %s\n", snd_strerror(err)); } else { // try to get card info card = snd_pcm_info_get_card(pcminfo); if (card >= 0) { sprintf(devname, ALSA_HARDWARE_CARD, card); if (snd_ctl_open(&handle, devname, SND_CTL_NONBLOCK) >= 0) { if (snd_ctl_card_info(handle, cardinfo) >= 0) { defcardinfo = cardinfo; } snd_ctl_close(handle); } } // call callback function for the device if (iterator != NULL) { doContinue = (*iterator)(ALSA_DEFAULT_DEVICE_ID, pcminfo, defcardinfo, userData); } count++; } } // iterate cards card = -1; while (doContinue) { if (snd_card_next(&card) < 0) { break; } if (card < 0) { break; } sprintf(devname, ALSA_HARDWARE_CARD, card); TRACE1("Opening alsa device \"%s\"...\n", devname); err = snd_ctl_open(&handle, devname, SND_CTL_NONBLOCK); if (err < 0) { ERROR2("ERROR: snd_ctl_open, card=%d: %s\n", card, snd_strerror(err)); } else { err = snd_ctl_card_info(handle, cardinfo); if (err < 0) { ERROR2("ERROR: snd_ctl_card_info, card=%d: %s\n", card, snd_strerror(err)); } else { dev = -1; while (doContinue) { if (snd_ctl_pcm_next_device(handle, &dev) < 0) { ERROR0("snd_ctl_pcm_next_device\n"); } if (dev < 0) { break; } snd_pcm_info_set_device(pcminfo, dev); snd_pcm_info_set_subdevice(pcminfo, 0); snd_pcm_info_set_stream(pcminfo, SND_PCM_STREAM_PLAYBACK); err = snd_ctl_pcm_info(handle, pcminfo); if (err == -ENOENT) { // try with the other direction snd_pcm_info_set_stream(pcminfo, SND_PCM_STREAM_CAPTURE); err = snd_ctl_pcm_info(handle, pcminfo); } if (err < 0) { if (err != -ENOENT) { ERROR2("ERROR: snd_ctl_pcm_info, card=%d: %s", card, snd_strerror(err)); } } else { subdeviceCount = needEnumerateSubdevices(ALSA_PCM) ? snd_pcm_info_get_subdevices_count(pcminfo) : 1; if (iterator!=NULL) { for (subDev = 0; subDev < subdeviceCount; subDev++) { deviceID = encodeDeviceID(card, dev, subDev); doContinue = (*iterator)(deviceID, pcminfo, cardinfo, userData); count++; if (!doContinue) { break; } } } else { count += subdeviceCount; } } } // of while(doContinue) } snd_ctl_close(handle); } } snd_ctl_card_info_free(cardinfo); snd_pcm_info_free(pcminfo); return count; }
BOOL OutputPNG::OutputPNGHeader(CCLexFile *File, LPBITMAPINFOHEADER pInfo, BOOL InterlaceState, INT32 TransparentColour, LPLOGPALETTE pPalette, LPRGBQUAD pQuadPalette) { ERROR2IF(File==NULL,FALSE,"OutputPNG::OutputPNGHeader File pointer is null"); if (pInfo == NULL) pInfo = &(DestBitmapInfo->bmiHeader); ERROR2IF(pInfo==NULL,FALSE,"OutputPNG::OutputPNGHeader BitmapInfo pointer is null"); //ERROR2IF(pPalette==NULL && pQuadPalette==NULL,FALSE,"OutputPNG::OutputPNGHeader Bitmap palette pointer is null"); TRACEUSER( "Jonathan", _T("PNG write: Interlace: %s\n"), InterlaceState ? _T("Yes") : _T("No")); // Note file in our class variable as used by all the low level routines OutputFile = File; // Note the specified transparency and interlace states in our class variables Interlace = InterlaceState; if (TransparentColour != -1) Transparent = TRUE; else Transparent = FALSE; // We are just about to start so set the PNG exception handling up with our CCFile pointer PNGUtil::SetCCFilePointer(File); // Must set the exception throwing flag to True and force reporting of errors to False. // This means that the caller must report an error if the function returns False. // Any calls to CCFile::GotError will now throw a file exception and should fall into // the catch handler at the end of the function. // Replaces the goto's that handled this before. BOOL OldThrowingState = File->SetThrowExceptions( TRUE ); BOOL OldReportingState = File->SetReportErrors( FALSE ); // PNG related items (NOTE: p at end means pointer and hence implied *) png_ptr = NULL; info_ptr = NULL; palette = NULL; try { // Work out the palette size INT32 PalSize = pInfo->biClrUsed; // How many entries in palette TRACEUSER( "Jonathan", _T("PNG write: PalSize = %d\n"),PalSize); // Set up the class variables // First the width/height of the bitmap Width = pInfo->biWidth; Height = pInfo->biHeight; TRACEUSER( "Jonathan", _T("PNG write: Width = %d Height = %d\n"),Width,Height); BitsPerPixel = pInfo->biBitCount; // Start up the PNG writing code // allocate the necessary structures // Use the default handlers png_ptr = png_create_write_struct_2( PNG_LIBPNG_VER_STRING, // libpng version 0, // Optional pointer to be sent with errors camelot_png_error, // Function called in case of error camelot_png_warning, // Function called for warnings 0, // Optional pointer to be sent with mem ops camelot_png_malloc, // Function called to alloc memory camelot_png_free // Function called to free memory ); if (!png_ptr) File->GotError( _R(IDS_OUT_OF_MEMORY) ); info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr, (png_infopp)NULL); File->GotError( _R(IDS_OUT_OF_MEMORY) ); } // set up the input control to the fstream class // If not a disk file then panic for the present moment // Could use the memfile functions for reading and writing as they give us what // we want. Use the io_ptr and iostream* pFStream = File->GetIOFile(); if (pFStream == NULL) { TRACEUSER( "Jonathan", _T("PNG write: OutputPNG::OutputPNGHeader No access to IOStream!")); File->GotError( _R(IDS_UNKNOWN_PNG_ERROR) ); } // Should use our own function png_set_write_fn(png_ptr, pFStream, camelot_png_write_data, camelot_png_flush_data); // png_init_io(png_ptr, pFStream); // You now have the option of modifying how the compression library // will run. The following functions are mainly for testing, but // may be useful in certain special cases, like if you need to // write png files extremely fast and are willing to give up some // compression, or if you want to get the maximum possible compression // at the expense of slower writing. If you have no special needs // in this area, let the library do what it wants, as it has been // carefully tuned to deliver the best speed/compression ratio. // See the compression library for more details. // turn on or off filtering (1 or 0) //png_set_filtering(png_ptr, 1); // compression level (0 - none, 6 - default, 9 - maximum) //png_set_compression_level(png_ptr, Z_BEST_COMPRESSION); //png_set_compression_mem_level(png_ptr, 8); //png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY); //png_set_compression_window_bits(png_ptr, 15); //png_set_compression_method(png_ptr, 8); // - this describes which optional chunks to write to the // file. Note that if you are writing a // PNG_COLOR_TYPE_PALETTE file, the PLTE chunk is not // optional, but must still be marked for writing. To // mark chunks for writing, OR valid with the // appropriate PNG_INFO_<chunk name> define. png_get_valid(png_ptr, info_ptr, 0); // resolution of image png_set_invalid(png_ptr, info_ptr, PNG_INFO_pHYs); png_set_pHYs(png_ptr, info_ptr, pInfo->biXPelsPerMeter, pInfo->biYPelsPerMeter, 1); //meter TRACEUSER( "Jonathan", _T("PNG write: x,y px per cm = %d %d\n"), png_get_x_pixels_per_meter(png_ptr, info_ptr) / 1000, png_get_y_pixels_per_meter(png_ptr, info_ptr) / 1000); BitsPerPixel = pInfo->biBitCount; TRACEUSER( "Jonathan", _T("PNG write: Bitdepth = %d\n"), BitsPerPixel); palette = NULL; num_palette = 0; trans = NULL; // - array of transparent entries for paletted images num_trans = 0; // - number of transparent entries TRACEUSER( "Jonathan", _T("PNG write: TransColour = %d\n"), TransparentColour); if ( BitsPerPixel <= 8 ) { png_set_IHDR(png_ptr, info_ptr, Width, Height, BitsPerPixel, PNG_COLOR_TYPE_PALETTE, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); // set the palette if there is one png_set_invalid(png_ptr, info_ptr, PNG_INFO_PLTE); INT32 PaletteEntries = pInfo->biClrUsed; palette = (png_colorp)png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH * sizeof (png_color)); if (palette == NULL) File->GotError( _R(IDS_OUT_OF_MEMORY) ); png_set_PLTE(png_ptr, info_ptr, palette, num_palette); png_color_struct * pPNGPalette = palette; // ... set palette colors ... if (pQuadPalette && PaletteEntries > 0) { // Palette supplied in RGBQUAD form for (INT32 i = 0; i < PaletteEntries; i++) { pPNGPalette->red = pQuadPalette->rgbRed; pPNGPalette->green = pQuadPalette->rgbGreen; pPNGPalette->blue = pQuadPalette->rgbBlue; // skip to the next palette entry pQuadPalette++; pPNGPalette++; } } else if (pPalette && PaletteEntries > 0) { // Palette supplied in LOGPALETTE form for (INT32 i = 0; i < PaletteEntries; i++) { pPNGPalette->red = pPalette->palPalEntry[i].peRed; pPNGPalette->green = pPalette->palPalEntry[i].peGreen; pPNGPalette->blue = pPalette->palPalEntry[i].peBlue; pPNGPalette++; } } else File->GotError(_R(IDS_PNG_ERR_WRITE_PALETTE)); // Now check to see if transparency is present or not if (TransparentColour >= 0 && TransparentColour <= PaletteEntries ) { // Create the array of transparent entries for this palette // 0 is fully transparent, 255 is fully opaque, regardless of image bit depth // We will only create as many as we require, i.e. up to the transparent colour entry // rather a full palettes worth INT32 NumEntries = TransparentColour + 1; trans = (png_byte*)png_malloc(png_ptr, NumEntries * sizeof (png_byte)); if (trans) { // Set the number of transparent entries num_trans = NumEntries; png_byte * pTransEntry = trans; png_set_invalid(png_ptr, info_ptr, PNG_INFO_tRNS); for (INT32 i = 0; i < TransparentColour; i++) { *pTransEntry = 255; // set it fully opaque pTransEntry++; } // We should now be at the transparent entry so set it fully transparent *pTransEntry = 0; } } } else if (BitsPerPixel == 24) { png_set_IHDR(png_ptr, info_ptr, Width, Height, 8, /* bit_depth */ PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); } else if (BitsPerPixel == 32) { png_set_IHDR(png_ptr, info_ptr, Width, Height, 8, /* bit_depth */ PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); } else ERROR2(FALSE,"OutputPNG::OutputPNGHeader Unknown bit depth"); TRACEUSER( "Jonathan", _T("PNG write: bit_depth = %d color_type = %d\n"), png_get_bit_depth(png_ptr, info_ptr), png_get_color_type(png_ptr, info_ptr)); // Could use:- // if we are dealing with a grayscale image then //info_ptr->sig_bit.gray = true_bit_depth; png_set_hIST(png_ptr, info_ptr, NULL); png_set_text(png_ptr, info_ptr, NULL, 0); // write the file information png_write_info(png_ptr, info_ptr); TRACEUSER( "Jonathan", _T("PNG write: pixel_depth %d channels %d\n"), png_get_bit_depth(png_ptr, info_ptr), png_get_channels(png_ptr, info_ptr)); TRACEUSER( "Jonathan", _T("PNG write: rowbytes %d color_type %d\n"), png_get_rowbytes(png_ptr, info_ptr), png_get_color_type(png_ptr, info_ptr)); // Set up the transformations you want. // Note: that these are all optional. Only call them if you want them // invert monocrome pixels //png_set_invert(png_ptr); // shift the pixels up to a legal bit depth and fill in as appropriate // to correctly scale the image //png_set_shift(png_ptr, &(info_ptr->sig_bit)); // pack pixels into bytes //png_set_packing(png_ptr); png_set_bgr(png_ptr); // swap bytes of 16 bit files to most significant bit first png_set_swap(png_ptr); // Must set the exception throwing and reporting flags back to their entry states File->SetThrowExceptions( OldThrowingState ); File->SetReportErrors( OldReportingState ); // er, we seem to have finished OK so say so return TRUE; } catch (...) { // catch our form of a file exception TRACE( _T("OutputPNG::OutputPNGHeader CC catch handler\n")); // Call up function to clean up the png structures CleanUpPngStructures(); // Must set the exception throwing and reporting flags back to their entry states File->SetThrowExceptions( OldThrowingState ); File->SetReportErrors( OldReportingState ); // We have finished so reset the PNG exception handling PNGUtil::SetCCFilePointer(NULL); return FALSE; } ERROR2( FALSE, "Escaped exception clause somehow" ); }
Sint parsemaxmatoptions(MMcallinfo *mmcallinfo,int argc, char *argv[]) { OptionDescription options[NUMOFOPTIONS]; // store the options Sint optval; // neg. return val. if error, otherwise option number Uint argnum; // pointer to argv signed long readint; // temporary integer to read value from string char leastlengthtext[128+1]; initoptions(&options[0],(Uint) NUMOFOPTIONS); ADDOPTION(OPTMUM,"-mum", "compute maximal matches that are unique in both sequences"); ADDOPTION(OPTMUMREF,"-mumreference", "compute maximal matches that are unique in the reference-\n" "sequence but not necessarily in the query-sequence (default)"); ADDOPTION(OPTMUMCAND,"-mumcand", "same as -mumreference"); ADDOPTION(OPTMAXMATCH,"-maxmatch", "compute all maximal matches regardless of their uniqueness"); ADDOPTION(OPTMATCHNUCLEOTIDESONLY,"-n", "match only the characters a, c, g, or t\n" "they can be in upper or in lower case"); makeleastlengthtext(&leastlengthtext[0]); ADDOPTION(OPTLEASTLENGTH,"-l",&leastlengthtext[0]); ADDOPTION(OPTCOMPUTEBOTHDIRECTIONS,"-b", "compute forward and reverse complement matches"); ADDOPTION(OPTONLYREVERSECOMPLEMENT,"-r", "only compute reverse complement matches"); ADDOPTION(OPTSHOWSTRING,"-s", "show the matching substrings"); ADDOPTION(OPTSHOWREVERSEPOSITIONS,"-c", "report the query-position of a reverse complement match\n" "relative to the original query sequence"); ADDOPTION(OPTFOURCOLUMN,"-F", "force 4 column output format regardless of the number of\n" "reference sequence inputs"); ADDOPTION(OPTSHOWSEQUENCELENGTHS,"-L", "show the length of the query sequences on the header line"); ADDOPTION(OPTCHUNKS,"-C","number of chunks to split query sequence"); ADDOPTION(OPTPREFIXLENGTH,"-P","length of prefix for Direct Access Table"); ADDOPTION(OPTH,"-h", "show possible options"); ADDOPTION(OPTHELP,"-help", "show possible options"); mmcallinfo->showstring = false; mmcallinfo->reversecomplement = false; mmcallinfo->forward = true; mmcallinfo->showreversepositions = false; mmcallinfo->fourcolumn = false; mmcallinfo->showsequencelengths = false; mmcallinfo->matchnucleotidesonly = false; mmcallinfo->cmum = false; mmcallinfo->cmumcand = false; mmcallinfo->cmaxmatch = false; mmcallinfo->minmatchlength = (Uint) DEFAULTMINUNIQUEMATCHLEN; mmcallinfo->chunks = (Uint) DEFAULTCHUNK; if(argc == 1) { showusage(argv[0],&options[0],(Uint) NUMOFOPTIONS); return 1; } for(argnum = UintConst(1); argnum < (Uint) argc && argv[argnum][0] == '-'; argnum++) { optval = procoption(options,(Uint) NUMOFOPTIONS,argv[argnum]); if(optval < 0) { return -1; } switch(optval) { case OPTSHOWSTRING: mmcallinfo->showstring = true; break; case OPTCOMPUTEBOTHDIRECTIONS: mmcallinfo->reversecomplement = true; break; case OPTSHOWREVERSEPOSITIONS: mmcallinfo->showreversepositions = true; break; case OPTLEASTLENGTH: // additionally check the length parameter argnum++; if(argnum > (Uint) (argc-2)) { ERROR1("missing argument for option %s", options[OPTLEASTLENGTH].optname); return -2; } if(sscanf(argv[argnum],"%ld",&readint) != 1 || readint <= 0) { ERROR2("argument %s for option %s is not a positive integer", argv[argnum],options[OPTLEASTLENGTH].optname); return -3; } mmcallinfo->minmatchlength = (Uint) readint; break; case OPTFOURCOLUMN: mmcallinfo->fourcolumn = true; break; case OPTSHOWSEQUENCELENGTHS: mmcallinfo->showsequencelengths = true; break; case OPTMATCHNUCLEOTIDESONLY: mmcallinfo->matchnucleotidesonly = true; break; case OPTONLYREVERSECOMPLEMENT: mmcallinfo->forward = false; mmcallinfo->reversecomplement = true; break; case OPTMAXMATCH: mmcallinfo->cmaxmatch = true; break; case OPTMUMREF: case OPTMUMCAND: mmcallinfo->cmumcand = true; break; case OPTMUM: mmcallinfo->cmum = true; break; case OPTCHUNKS: argnum++; if(argnum > (Uint) (argc-2)) { ERROR1("missing argument for option %s", options[OPTCHUNKS].optname); return -2; } if(sscanf(argv[argnum],"%ld",&readint) != 1 || readint <= 0) { ERROR2("argument %s for option %s is not a positive integer", argv[argnum],options[OPTCHUNKS].optname); return -3; } mmcallinfo->chunks = (Uint) readint; break; case OPTPREFIXLENGTH: argnum++; if(argnum > (Uint) (argc-2)) { ERROR1("missing argument for option %s", options[OPTPREFIXLENGTH].optname); return -2; } if(sscanf(argv[argnum],"%ld",&readint) != 1 || readint <= 0) { ERROR2("argument %s for option %s is not a positive integer", argv[argnum],options[OPTPREFIXLENGTH].optname); return -3; } mmcallinfo->prefix = (Uint) readint; break; case OPTH: case OPTHELP: showusage(argv[0],&options[0],(Uint) NUMOFOPTIONS); return 1; } } if(argnum > (Uint) (argc-2)) { ERROR0("missing file arguments"); return -4; } if(safestringcopy(&mmcallinfo->program[0],argv[0],PATH_MAX) != 0) { return -5; } if(safestringcopy(&mmcallinfo->subjectfile[0],argv[argnum],PATH_MAX) != 0) { return -6; } for(argnum++, mmcallinfo->numofqueryfiles = 0; argnum < (Uint) argc; mmcallinfo->numofqueryfiles++, argnum++) { if(mmcallinfo->numofqueryfiles >= (Uint) MAXNUMOFQUERYFILES) { ERROR1("too many query files, maximal number is %d", (int) MAXNUMOFQUERYFILES); return -7; } if(safestringcopy(&mmcallinfo->queryfilelist [mmcallinfo->numofqueryfiles][0], argv[argnum],PATH_MAX) != 0) { return -8; } } /* verify that mum options are not interchanged */ OPTIONEXCLUDE(OPTMUM,OPTMUMCAND); OPTIONEXCLUDE(OPTMUM,OPTMUMREF); OPTIONEXCLUDE(OPTMUM,OPTMAXMATCH); OPTIONEXCLUDE(OPTMUMCAND,OPTMAXMATCH); OPTIONEXCLUDE(OPTMUMREF,OPTMAXMATCH); if ( mmcallinfo->cmaxmatch ) { mmcallinfo->cmum = false; mmcallinfo->cmumcand = false; } else if ( mmcallinfo->cmum ) { } else /* default to cmumcand */ { mmcallinfo->cmumcand = true; } /* verify that the options -b and -r are not used at the same time */ OPTIONEXCLUDE(OPTCOMPUTEBOTHDIRECTIONS,OPTONLYREVERSECOMPLEMENT); /* verify that -c is only used in combination with either -b or -r */ OPTIONIMPLYEITHER2(OPTSHOWREVERSEPOSITIONS, OPTCOMPUTEBOTHDIRECTIONS,OPTONLYREVERSECOMPLEMENT); return 0; }
int srec_read(FILE *pFile, unsigned char *buf, unsigned int start, unsigned int end) { fseek(pFile, 0, SEEK_SET); unsigned int chunk_len, chunk_addr, chunk_type, i, byte, line_no = 0, greatest_addr = 0; unsigned int number_of_records = 0; bool data_record = false; bool found_S5_rec = false; unsigned int expected_data_records = 0; unsigned int data_len = 0; unsigned char temp = ' '; while(fgets(line, sizeof(line), pFile)) { data_record = true; //Assume that the read data is a data record. Set to false if not. line_no++; // Reading chunk header if(sscanf(line, "S%01x%02x%08x", &chunk_type, &chunk_len, &chunk_addr) != 3) { sscanf(line, "%c",&temp); if(temp != 'S') { continue; } free(buf); ERROR2("Error while parsing SREC at line %d\n", line_no); } if(chunk_type == 0x00 || chunk_type == 0x04) //Header type record or reserved. Skip! { continue; } else if(chunk_type == 0x05) { //This will contain the total expected number of data records. Save for error checking later found_S5_rec = true; if (chunk_len != 3) { // Length field must contain a 3 to be a valid S5 record. ERROR2("Error while parsing S5 Record at line %d\n", line_no); } expected_data_records = chunk_addr; //The expected total number of data records is saved in S503<addr> field. } else if(is_data_type(chunk_type)) { chunk_addr = chunk_addr >> (8*(3-chunk_type)); data_len = chunk_len - chunk_type - 2; // See https://en.wikipedia.org/wiki/SREC_(file_format)#Record_types } else { continue; } // Reading chunk data for(i = 6 + 2*chunk_type; i < 2*data_len + 8; i +=2) { if(sscanf(&(line[i]), "%02x", &byte) != 1) { free(buf); ERROR2("Error while parsing SREC at line %d byte %d\n", line_no, i); } if(!is_data_type(chunk_type)) { // The only data records have to be processed data_record = false; continue; } if((i - 8) / 2 >= chunk_len) { // Respect chunk_len and do not capture checksum as data break; } if(chunk_addr < start) { free(buf); ERROR2("Address %08x is out of range at line %d\n", chunk_addr, line_no); } if(chunk_addr + data_len > end) { free(buf); ERROR2("Address %08x + %d is out of range at line %d\n", chunk_addr, data_len, line_no); } if(chunk_addr + data_len > greatest_addr) { greatest_addr = chunk_addr + data_len; } buf[chunk_addr - start + (i - 8) / 2] = byte; } if(data_record) { //We found a data record. Remember this. number_of_records++; } }
BOOL ContextMenu::BuildOverView(Spread* pSpread, DocCoord ClickPos, ClickModifiers ClickMods) { ERROR2(FALSE,"ContextMenu::BuildOverView called in base class - should be overridden!"); }
BOOL ContextMenu::Build() { ERROR2(FALSE,"ContextMenu::Build called in base class - should be overridden!"); }
INT32 LibraryFile::Init(SuperGallery *ParentGal, PathName *APath, SGLibType Type, BOOL Updated, BOOL DoScroll) { #ifndef EXCLUDE_GALS if(ParentGal == NULL || APath == NULL || !Libraries.IsEmpty()) { ERROR3("LibraryFile::Init - NULL parameters are illegal OR Init called > 1 times"); if(!Libraries.IsEmpty()) return(Libraries.GetCount()); else return 0; } BOOL ok = TRUE; // Tidy up Path a bit String_256 OurPath(APath->GetPath()); LibraryFile::TidyUpSubPath(&OurPath); // Now point Path to the new pathname PathName ModifiedPath(OurPath); PathName *Path = &ModifiedPath; if(!ModifiedPath.IsValid()) { ERROR3("LibraryFile::Init -> Modified library path is invalid"); return 0; } // Remember the pathname and type MyPath = *Path; MyType = Type; ParentGallery = ParentGal; if(ParentGallery->IsKindOf(CC_RUNTIME_CLASS(LibraryGallery))) ParentLibraryGallery = (LibraryGallery *)ParentGal; else { ERROR3("LibraryFile::Init passed a non-library gallery - yikes..."); return 0; } // Need to reset the Quiet status before a stream of Library::Init calls ParentLibraryGallery->SetQuietStatus(FALSE); BOOL Retry = TRUE; while(Retry) { Retry = FALSE; // Would be nice to have a way of adding a file to a path in PathName... Is there one ? if(!SGLibOil::FileExists(Path)) { // We're opening the font gallery, but can't find the font library path - don't warn if(Type == SGLib_Font) return 0; // tell the user that the directory doesn't exist String_256 WarnMsg; String_256 DefaultIndex; String_256 IndexDesc; BOOL CanGenerate; ok = LibraryFile::GetSubIndexDetails(ParentLibraryGallery, &DefaultIndex, &IndexDesc, &CanGenerate); String_256 TmpPath(Path->GetLocation(FALSE)); LibraryFile::TidyUpSubPath(&TmpPath); // Taken out by Graham 30/10/97: If the gallery had no directory specified, //we used to throw a warning which said "do you want to specify another folder?" //We don't do this any more, because the default is to open all galleries empty and //then download stuff from the Xara web site #if 0 WarnMsg.MakeMsg(_R(IDS_BROWSE_OR_SCAN), (TCHAR *)IndexDesc, (TCHAR *)TmpPath); Error::SetError(0, WarnMsg, 0); INT32 ButtonPressed = InformWarning(0, _R(IDS_BROWSE), _R(IDS_RETRY), _R(IDS_CANCEL)/*, _R(IDS_HELP)*/); #else // WEBSTER INT32 ButtonPressed = 3; #endif // WEBSTER TRACEUSER( "Richard", _T("ButtonPressed: %d\n"), ButtonPressed); Error::ClearError(); switch(ButtonPressed) { case 1: { // Open the Browse dialog (or the Add.. dialog as it seems to be called now) PathName ThePath(*Path); // This returns FALSE if Cancel was hit, or an error occurred. if(!SGLibOil::GetLibPath(ParentLibraryGallery, &ThePath, CanGenerate, Type)) { ERROR3("GetLibPath returned FALSE in LF::Init"); return 0; } else { ModifiedPath = ThePath; if(!ModifiedPath.IsValid()) { ERROR3("LibraryFile::Init -> scanned library path is invalid"); return 0; } // Remember the pathname MyPath = ThePath; switch(Type) { case SGLib_ClipArt: case SGLib_Bitmap: LibClipartSGallery::DefaultLibraryPath = MyPath.GetPath(); LibClipartSGallery::ClipartPath = LibClipartSGallery::DefaultLibraryPath; break; case SGLib_ClipArt_WebThemes: LibClipartSGallery::DefaultLibraryPath = MyPath.GetPath(); LibClipartSGallery::WebThemePath = LibClipartSGallery::DefaultLibraryPath; break; #ifndef STANDALONE case SGLib_Texture: case SGLib_Fractal: LibFillsSGallery::DefaultLibraryPath = MyPath.GetPath(); break; case SGLib_Font: // WEBSTER-Martin-09/01/97 - Put back by Ranbir. //#ifndef WEBSTER FontsSGallery::DefaultLibraryPath = MyPath.GetPath(); break; // Not in webster so we get the error below //#endif // WEBSTER #endif default: ERROR2(FALSE,"Library::ScanForLocation Type not present!"); break; } } break; } case 2: Retry = TRUE; #if 0 { // Scan String_256 Result; if(!Library::ScanForLocation(Type, &Result)) { ERROR3("No libraries found..."); return 0; } if(!ModifiedPath.SetPathName(Result)) { ERROR3("LibraryFile::Init -> scanned library path is invalid"); return 0; } // Remember the pathname and type MyPath = *Path; } #endif break; case 3: // Cancel return 0; } } } // Wipe libraries added to gallery for scroll / redraw purposes... InitScrollRedrawSystem(); // Check the actual path exists if(SGLibOil::FileExists(Path)) { // Would be nice to have a way of adding a file to a path in PathName... Is there one ? String_256 IndexFile((const TCHAR *)Path->GetPath(TRUE)); // "%s\\XaraInfo\\index.txt" IndexFile += String_16(_R(IDS_LIBRARIES_XARAINFO_DIRNAME)); IndexFile += TEXT("\\") + String_16(_R(IDS_LIBRARIES_INDEX_FILENAME)); PathName IndexFilePath(IndexFile); if(!IndexFilePath.IsValid()) { ERROR3("LibraryFile::Init indexfilepath is invalid"); return 0; } CCDiskFile MainIndex; if (!MainIndex.InitLexer(FALSE)) { // SetError! ERROR3("LibraryFile::LibraryFile InitLexer failed"); return(0); } if(SGLibOil::FileExists(&IndexFilePath)) { // Count lines in index file INT32 Count = CountLines(&IndexFilePath); TRACEUSER( "Richard", _T("%d lines in index file\n"), Count); // Used for the percentage display INT32 CurrentGroupNumber = 0; // Just in case there's a slow job already going on... SmashSlowJob(); String_64 SlowJob(_R(IDS_LIBRARY_SCANNING)); BeginSlowJob(Count, FALSE, &SlowJob); // Now use the index file to create each group in turn if (MainIndex.open(IndexFilePath, ios::in)) { MainIndex.SetWhitespace(""); // Setting this to blank lets us read non-"'d strings MainIndex.SetDelimiters(","); // ,s delimit our fields MainIndex.SetCommentMarker('#'); // #'d lines are commented out MainIndex.SetStringDelimiters(""); // No string delimiters String_64 Directory; String_64 Description; String_64 SubIndex; String_64 Kind; LexTokenType TT; BOOL EscapePressed = FALSE; while(ok && !EscapePressed) { if(!MainIndex.GetToken()) break; // Get SubLib directory name // Keep reading tokens until we hit a normal one... (skips line ends and // comments for us TT = MainIndex.GetTokenType(); while (TT != TOKEN_NORMAL && ok) { ok = MainIndex.GetToken(); if(!ok) break; TT = MainIndex.GetTokenType(); ok = (TT != TOKEN_EOF); if(!ok) break; } if(!ok) break; Directory = MainIndex.GetTokenBuf(); KillLeadingSpaces(&Directory); if(!MainIndex.GetToken()) break; // Get ',' if(!MainIndex.GetToken()) break; // Get Description String_256 Description256; Description256 = MainIndex.GetTokenBuf(); KillLeadingSpaces(&Description256); Description256.Left(&Description, 60); if(!MainIndex.GetToken()) break; // Get ',' if(!MainIndex.GetToken()) break; // Get Sub Library Index name SubIndex = MainIndex.GetTokenBuf(); KillLeadingSpaces(&SubIndex); if(!MainIndex.GetToken()) break; // Get ',' if(!MainIndex.GetToken()) break; // Get type of files in sublib Kind = MainIndex.GetTokenBuf(); KillLeadingSpaces(&Kind); BOOL Match = FALSE; Match = ParentLibraryGallery->CheckForIndexMatch(&Kind); if(Match) { // Show status of additions EscapePressed = !ContinueSlowJob(CurrentGroupNumber++); // Sort pathname of sublib directory out String_256 SubP(Path->GetPath(TRUE)); SubP += Directory; PathName SubPath(SubP); if(!SubPath.IsValid()) { ERROR3("LibraryFile::Init - invalid subpath"); if(MainIndex.isOpen()) MainIndex.close(); EndSlowJob(); return 0; } // Go ahead and add the new group if(ok) { // Create the sub lib Library *NewSubLib = new Library; if (NewSubLib != NULL) { // Create the new group in the gallery (note the TRUE for create a virtualised one if // we can to save time / memory) if(NewSubLib->Init(ParentGal, &SubPath, &Description, &SubIndex, Type, Updated, TRUE)) { Libraries.AddTail(NewSubLib); // Keep track of libraries added for redraw purposes... AddNewFolderToScrollRedrawSystem(NewSubLib); } else { // This check is new, should be ok... delete NewSubLib; NewSubLib = NULL; ERROR3("Library::Init failed in LibraryFile::Init"); ok = FALSE; } } } } } } else { // Failed to open the index file... // SetError?! ERROR3("LibraryFile::LibraryFile couldn't open index file"); ok = FALSE; } EndSlowJob(); } else { // The directory given had no XaraInfo\index.txt file, maybe it's a sublib, check // For defaults... ok = CheckForSubIndexes(ParentGal, Path, Type, Updated); } // reclaim lexer-buffer memory MainIndex.DeinitLexer(); // And close the file if(MainIndex.isOpen()) MainIndex.close(); // Scroll / redraw the newly added groups... if(DoScroll) DoScrollRedraw(); } else { TRACEUSER( "Richard", _T("Path doesn't exist\n")); } // And return the number of items created return(Libraries.GetCount()); #endif return 0; }
//------------------------------------------------------------------------------ // void main(void) { ERROR2(RBX430_init(_12MHZ)); // init board to 12 MHz ERROR2(lcd_init()); // init LCD ERROR2(port1_init()); // init switches ERROR2(ADC_init()); // init ADC ERROR2(watchdog_init()); // init watchdog ERROR2(timerA_init()); // init TimerA ERROR2(timerB_init()); // init TimerB __bis_SR_register(GIE); // enable interrupts sys_event = NEW_GAME; // start w/new game //----------------------------------------------------------- // play forever while (1) { //----------------------------------------------------------- // event service routine loop //----------------------------------------------------------- while (1) { // disable interrupts while checking sys_event _disable_interrupts(); // if event pending, enable interrupts if (sys_event) _enable_interrupt(); // else enable interrupts and goto sleep else __bis_SR_register(LPM0_bits | GIE); //------------------------------------------------------- // I'm AWAKE!!! What needs service? if (sys_event == SWITCH_1) { sys_event = sys_event & ~SWITCH_1; SWITCH_1_event(); } else if (sys_event == NEW_GAME) // new game event { sys_event &= ~NEW_GAME; // clear new game event NEW_GAME_event(); // process new game } else if (sys_event == MOVE_BALL) // timer A event { sys_event &= ~MOVE_BALL; // clear TimerA event MOVE_BALL_event(ball); // update ball position } else if (sys_event == ADC_READ) // read ADC event { sys_event &= ~ADC_READ; // clear ADC event ADC_READ_event(rightPaddle); // process ADC read ADC_READ_event(leftPaddle); } else if (sys_event == LCD_UPDATE) { LCD_UPDATE_event(); } else if (sys_event == START_GAME) { sys_event = sys_event & ~START_GAME; START_GAME_event(); } else if (sys_event == NEW_RALLY) { sys_event = sys_event & ~ NEW_RALLY; NEW_RALLY_event(); } else if (sys_event == MISSED_BALL) { sys_event = sys_event & ~MISSED_BALL; MISSED_BALL_event(); } else if (sys_event == END_GAME) { sys_event = sys_event | END_GAME; END_GAME_event(); } else // ???? { ERROR2(SYS_ERR_EVENT); // unrecognized event } } } } // end main