Example #1
0
cFile::cFile(const AString & iFileName, eMode iMode) :
	m_File(nullptr)
{
	Open(iFileName, iMode);
}
void RecSlaveEntry(void)
{
  struct AHIAudioCtrlDrv* AudioCtrl;
  struct DriverBase*      AHIsubBase;
  struct FilesaveBase*    FilesaveBase;

  ULONG   signals;
  BPTR    lock = NULL,cd=0,file = NULL;
  Object *o = NULL;
  BYTE   *samples = NULL;
  ULONG   length = NULL;
  ULONG   count = 0,offs = 0,i;

  struct AHIRecordMessage RecordMessage = 
  {
    AHIST_S16S,
    NULL,
    RECBUFFERSIZE
  };

  AudioCtrl    = (struct AHIAudioCtrlDrv*) FindTask( NULL )->tc_UserData;
  AHIsubBase   = (struct DriverBase*) dd->fs_AHIsubBase;
  FilesaveBase = (struct FilesaveBase*) AHIsubBase;

  RecordMessage.ahirm_Buffer = dd->fs_RecBuffer;

  if(!(lock = Lock(dd->fs_RecFileReq->fr_Drawer,ACCESS_READ)))
    goto quit;
  cd = CurrentDir(lock);

  if(DataTypesBase)
  {
    struct TagItem newtags[] =
    {
      { DTA_GroupID, GID_SOUND },
      { TAG_DONE,    0         }
    };
    
    struct TagItem attrtags[] =
    {
      { SDTA_Sample,       (ULONG) &samples },
      { SDTA_SampleLength, (ULONG) &length  },
      { TAG_DONE,          0                }
    };
    
    if (!(o = NewDTObjectA (dd->fs_RecFileReq->fr_File, newtags)))
      goto quit;

    GetDTAttrsA(o, attrtags );
  }
  else // datatypes.library not open. Open the selected file as raw 8 bit signed instead.
  {
    if(!(file = Open(dd->fs_RecFileReq->fr_File,MODE_OLDFILE)))
      goto quit;
    Seek(file,0,OFFSET_END);
    length = Seek(file,0,OFFSET_BEGINNING);
    if(!(samples = AllocVec(length,MEMF_ANY)))
      goto quit;
    if(length != (ULONG) Read(file,samples,length))
      goto quit;
  }

  if(!samples || !length )
    goto quit;

  if((dd->fs_RecSlaveSignal = AllocSignal(-1)) == -1)
    goto quit;

// Everything set up. Tell Master we're alive and healthy.
    Signal((struct Task *)dd->fs_MasterTask,1L<<dd->fs_RecMasterSignal);

    for(;;)
    {
      signals = SetSignal(0L,0L);
      if(signals & (SIGBREAKF_CTRL_C | 1L<<dd->fs_RecSlaveSignal))
        break;

      for(;;)
      {
        if(count+RECBUFFERSIZE-offs < length)
        {
// End of sample will not be reached; just fill to the end of dd->fs_RecBuffer.
          for(i = RECBUFFERSIZE-offs;i>0;i--)
          {
            dd->fs_RecBuffer[(offs)<<1] = 
            dd->fs_RecBuffer[((offs++)<<1)+1] = 
            samples[count++]<<8;
          }
          offs = 0;
          break;
        }
        else
        {
// End of sample will be reached. Fill part of buffer, and iterate (== don't break).
          for(i = length-count;i>0;i--)
          {
            dd->fs_RecBuffer[(offs)<<1] = 
            dd->fs_RecBuffer[((offs++)<<1)+1] = 
            samples[count++]<<8;
          }
          count = 0;
        }

      }

      CallHookPkt(AudioCtrl->ahiac_SamplerFunc,AudioCtrl,&RecordMessage);
      Delay(50*RECBUFFERSIZE/AudioCtrl->ahiac_MixFreq);
    }

quit:
// Get rid of object
  if(DataTypesBase)
  {
    if(o)
      DisposeDTObject (o);
  }
  else // datatypes.library not open.
  {
    if(samples)
      FreeVec(samples);
    if(file)
      Close(file);
  }
  CurrentDir(cd);
  if(lock)
    UnLock(lock);

  Forbid();
  dd->fs_RecSlaveTask = NULL;
  FreeSignal(dd->fs_RecSlaveSignal);
  dd->fs_RecSlaveSignal = -1;
  // Tell the Master we're dying
  Signal((struct Task *)dd->fs_MasterTask,1L<<dd->fs_RecMasterSignal);
  // Multitaking will resume when we are dead.
}
Example #3
0
void DtPrinterIcon::NotifyVisiblity(BaseUI *obj)
{
   if (app_mode == CONFIG_PRINTERS)
      return;

   if (obj == flag)
    {
      boolean show_it = Visible();
      if (show_it)
       {
         if (mainw->setPrefD->ShowStatusFlags() == false)
            show_it = false;
         else
	  {
#ifdef aix
            if (_print_queue_up)
             {
	       show_it = false;
               int i;
               for (i = 0; i < n_devices; i++)
                  if (_print_device_up[i] == false)
	           {
	             show_it = true;
	             break;
	           }
             }
	    else
	       show_it = true;
#else
            if (_print_queue_up && _print_device_up)
               show_it = false;
            else
               show_it = true;
#endif
	  }
       }
      if (flag->Visible() != show_it)
         flag->Visible(show_it);
    }
   else if (obj == details_label)
    {
      boolean show_it = Visible();
      if (show_it)
       {
         if (container && IconView() == DETAILS && Open())
	  {
            if (container->NumChildren() == 0 ||
                (container->Children()[0])->UIClass() == LABEL)
               show_it = false;
            else if (mainw->setPrefD->ShowDetailsLabel())
	     {
	       show_it = false;
	       int i;
	       BaseUI **children = container->Children();
	       for (i = 0; i < container->NumChildren(); i++)
	          if (children[i]->Visible())
	           {
	             show_it = true;
	             break;
	           }
	     }
	    else
               show_it = mainw->setPrefD->ShowDetailsLabel();
	  }
         else
            show_it = false;
       }
      if (details_label->Visible() != show_it)
         details_label->Visible(show_it);
    }
}
Example #4
0
BOOL
ReadConfig ( struct AHIDevUnit *iounit,
             struct AHIBase *AHIBase )
{
  struct IFFHandle *iff;
  struct StoredProperty *prhd,*ahig;
  struct CollectionItem *ci;

  if(iounit)
  {
    /* Internal defaults for device unit */
    iounit->AudioMode       = AHI_INVALID_ID;   // See at the end of the function!
    iounit->Frequency       = 10000;
    iounit->Channels        = 4;
    iounit->MonitorVolume   = ~0;
    iounit->InputGain       = ~0;
    iounit->OutputVolume    = ~0;
    iounit->Input           = ~0;
    iounit->Output          = ~0;
  }
  else
  {
    /* Internal defaults for low-level mode */
    AHIBase->ahib_AudioMode       = AHI_INVALID_ID;
    AHIBase->ahib_Frequency       = 10000;
    AHIBase->ahib_MonitorVolume   = 0x00000;
    AHIBase->ahib_InputGain       = 0x10000;
    AHIBase->ahib_OutputVolume    = 0x10000;
    AHIBase->ahib_Input           = 0;
    AHIBase->ahib_Output          = 0;
  }

  if((iff=AllocIFF()))
  {
    iff->iff_Stream=Open("ENV:Sys/ahi.prefs", MODE_OLDFILE);
    if(iff->iff_Stream)
    {
      InitIFFasDOS(iff);
      if(!OpenIFF(iff,IFFF_READ))
      {
        if(!(PropChunk(iff,ID_PREF,ID_PRHD)
          || PropChunk(iff,ID_PREF,ID_AHIG)
          || CollectionChunk(iff,ID_PREF,ID_AHIU)
          || StopOnExit(iff,ID_PREF,ID_FORM)))
        {
          if(ParseIFF(iff,IFFPARSE_SCAN) == IFFERR_EOC)
          {
            prhd=FindProp(iff,ID_PREF,ID_PRHD);
            ahig=FindProp(iff,ID_PREF,ID_AHIG);
            
            if(ahig)
            {
              struct AHIGlobalPrefs *globalprefs;
              
              globalprefs = (struct AHIGlobalPrefs *)ahig->sp_Data;

              AHIBase->ahib_DebugLevel = globalprefs->ahigp_DebugLevel;

              AHIBase->ahib_Flags = 0;

              if(globalprefs->ahigp_DisableSurround)
                AHIBase->ahib_Flags |= AHIBF_NOSURROUND;

              if(globalprefs->ahigp_DisableEcho)
                AHIBase->ahib_Flags |= AHIBF_NOECHO;

              if(globalprefs->ahigp_FastEcho)
                AHIBase->ahib_Flags |= AHIBF_FASTECHO;
                
              if( (ULONG) ahig->sp_Size > offsetof( struct AHIGlobalPrefs,
                                                    ahigp_MaxCPU) )
              {
                AHIBase->ahib_MaxCPU = globalprefs->ahigp_MaxCPU;
              }
              else
              {
                AHIBase->ahib_MaxCPU = 0x10000 * 90 / 100;
              }

              if( (ULONG) ahig->sp_Size > offsetof( struct AHIGlobalPrefs, 
                                                    ahigp_ClipMasterVolume) )
              {
                if(globalprefs->ahigp_ClipMasterVolume)
                  AHIBase->ahib_Flags |= AHIBF_CLIPPING;
              }

              if( (ULONG) ahig->sp_Size > offsetof( struct AHIGlobalPrefs, 
                                                    ahigp_AntiClickTime ) )
              {
                AHIBase->ahib_AntiClickTime = globalprefs->ahigp_AntiClickTime;
              }
              else
              {
                AHIBase->ahib_AntiClickTime = 0;
              }

            }
            ci=FindCollection(iff,ID_PREF,ID_AHIU);
            while(ci)
            {
              struct AHIUnitPrefs *unitprefs;

              unitprefs = (struct AHIUnitPrefs *)ci->ci_Data;

              if(iounit)
              {
                if(unitprefs->ahiup_Unit == iounit->UnitNum)
                {
                  iounit->AudioMode       = unitprefs->ahiup_AudioMode;
                  iounit->Frequency       = unitprefs->ahiup_Frequency;
                  iounit->Channels        = unitprefs->ahiup_Channels;
                  iounit->MonitorVolume   = unitprefs->ahiup_MonitorVolume;
                  iounit->InputGain       = unitprefs->ahiup_InputGain;
                  iounit->OutputVolume    = unitprefs->ahiup_OutputVolume;
                  iounit->Input           = unitprefs->ahiup_Input;
                  iounit->Output          = unitprefs->ahiup_Output;
                }
              }
              else
              {
                if(unitprefs->ahiup_Unit == AHI_NO_UNIT)
                {
                  AHIBase->ahib_AudioMode       = unitprefs->ahiup_AudioMode;
                  AHIBase->ahib_Frequency       = unitprefs->ahiup_Frequency;
                  AHIBase->ahib_MonitorVolume   = unitprefs->ahiup_MonitorVolume;
                  AHIBase->ahib_InputGain       = unitprefs->ahiup_InputGain;
                  AHIBase->ahib_OutputVolume    = unitprefs->ahiup_OutputVolume;
                  AHIBase->ahib_Input           = unitprefs->ahiup_Input;
                  AHIBase->ahib_Output          = unitprefs->ahiup_Output;
                }
              }

              ci=ci->ci_Next;
            }
          }
Example #5
0
void DataStore::ImportDataFromFile(std::string const &file)
{
    std::ifstream infile(file);
    std::string line;
    std::getline(infile, line); //skip first line (assume it's always a header)

    std::vector<std::pair<Record, bool>> vRecordsToAdd; //boolean keeps track if Record already exists in datastore

    //Add all Records from input file to temporary storage
    while (std::getline(infile, line)) {
        std::vector<std::string> const tokens(Utility::Tokenize(line, "|"));

        if (tokens.size() != 6)
            throw std::runtime_error("Bad record in file (found " + std::to_string(tokens.size()) + " fields, expected 6)");

        Record const rec(tokens);
        vRecordsToAdd.emplace_back(std::make_pair(rec, false));
    }

    std::cout << vRecordsToAdd.size() << " record(s) read from file" << std::endl;

    //Read data store (from file) and update existing records
    size_t numUpdated(0);
    Open();
    size_t const size(GetNumRecords());
    for (size_t ii = 0; ii < size; ++ii) {
        Record const oldRec(FetchRecord(ii));

        for (auto &pp : vRecordsToAdd) {
            Record const &rec  (pp.first);
            bool         &added(pp.second);

            if (added)
                continue;

            if (rec == oldRec) {
                UpdateRecord(rec, ii);
                added = true;
                ++numUpdated;
            }
        }
    }

    if (numUpdated > 0)
        std::cout << numUpdated << " record(s) updated in datastore" << std::endl;

    //Finally, add brand new records to datastore
    size_t numAdded(0);
    for (auto const &pp : vRecordsToAdd) {
        Record const &rec(pp.first);
        bool   const &added(pp.second);

        if (!added) {
            AddRecord(rec);
            ++numAdded;
        }
    }

    if (numAdded > 0)
        std::cout << numAdded << " record(s) added to datastore" << std::endl;

    Close();
}
Example #6
0
bool COutFile::Open(LPCWSTR fileName, DWORD creationDisposition)
{
    return Open(fileName, FILE_SHARE_READ,  creationDisposition, FILE_ATTRIBUTE_NORMAL);
}
Example #7
0
bool AFileUnicode::Open(const char* szFolderName, const char * szFileName, ADWORD dwFlags)
{
	char szFullPath[AMAX_PATH];
	af_GetFullPath(szFullPath, szFolderName, szFileName);
	return Open(szFullPath, dwFlags);
}
Example #8
0
CPLErr NTFFileReader::ReadRasterColumn( int iColumn, float *pafElev )

{
/* -------------------------------------------------------------------- */
/*      If we don't already have the scanline offset of the previous    */
/*      line, force reading of previous records to establish it.        */
/* -------------------------------------------------------------------- */
    if( panColumnOffset[iColumn] == 0 )
    {
        int     iPrev;
        
        for( iPrev = 0; iPrev < iColumn-1; iPrev++ )
        {
            if( panColumnOffset[iPrev+1] == 0 )
            {
                CPLErr  eErr;
                
                eErr = ReadRasterColumn( iPrev, NULL );
                if( eErr != CE_None )
                    return eErr;
            }
        }
    }

/* -------------------------------------------------------------------- */
/*      If the dataset isn't open, open it now.                         */
/* -------------------------------------------------------------------- */
    if( GetFP() == NULL )
        Open();
    
/* -------------------------------------------------------------------- */
/*      Read requested record.                                          */
/* -------------------------------------------------------------------- */
    NTFRecord   *poRecord;
    
    SetFPPos( panColumnOffset[iColumn], iColumn );
    poRecord = ReadRecord();

    if( iColumn < nRasterXSize-1 )
    {
        GetFPPos( panColumnOffset+iColumn+1, NULL );
    }
    
/* -------------------------------------------------------------------- */
/*      Handle LANDRANGER DTM columns.                                  */
/* -------------------------------------------------------------------- */
    if( pafElev != NULL && GetProductId() == NPC_LANDRANGER_DTM )
    {
        double  dfVScale, dfVOffset;

        dfVOffset = atoi(poRecord->GetField(56,65));
        dfVScale = atoi(poRecord->GetField(66,75)) * 0.001;

        for( int iPixel = 0; iPixel < nRasterXSize; iPixel++ )
        {
            pafElev[iPixel] = (float) (dfVOffset + dfVScale *
                atoi(poRecord->GetField(84+iPixel*4,87+iPixel*4)));
        }
    }
            
/* -------------------------------------------------------------------- */
/*      Handle PROFILE                                                  */
/* -------------------------------------------------------------------- */
    else if( pafElev != NULL && GetProductId() == NPC_LANDFORM_PROFILE_DTM )
    {
        for( int iPixel = 0; iPixel < nRasterXSize; iPixel++ )
        {
            pafElev[iPixel] = (float) 
           (atoi(poRecord->GetField(19+iPixel*5,23+iPixel*5)) * GetZMult());
        }
    }
    
    delete poRecord;

    return CE_None;
}
Example #9
0
int procan(FILE *outfile) {

   /*filan(0, outfile);*/

   /* controlling terminal */
   fprintf(outfile, "process id = "F_pid"\n", Getpid());
   fprintf(outfile, "process parent id = "F_pid"\n", Getppid());
   {
      int fd;
      if ((fd = Open("/dev/tty", O_NOCTTY, 0)) < 0) {
	 fprintf(outfile, "controlling terminal: -\n");
      } else {
#if 1
	 fprintf(outfile, "controlling terminal: \"%s\"\n", Ttyname(fd));
#else
	 char procpath[PATH_MAX], devpath[PATH_MAX+1];
	 int devlen;
	 sprintf(procpath, "/proc/"F_pid"/fd/%d", Getpid(), 0 /*! fd*/);
	 if ((devlen = Readlink(procpath, devpath, sizeof(devpath))) < 0) {
	    ;
	 } else {
	    devpath[devlen] = '\0';
	    fprintf(outfile, "controlling terminal: \"%s\"\n", devpath);
	 }
#endif
      }
   }
   fprintf(outfile, "process group id = "F_pid"\n", Getpgrp());
#if HAVE_GETSID
   fprintf(outfile, "process session id = "F_pid"\n", Getsid(0));
#endif
   fprintf(outfile, "process group id if fg process / stdin = "F_pid"\n", Tcgetpgrp(0));
   fprintf(outfile, "process group id if fg process / stdout = "F_pid"\n", Tcgetpgrp(1));
   fprintf(outfile, "process group id if fg process / stderr = "F_pid"\n", Tcgetpgrp(2));
   {
      int fd;
      if ((fd = Open("/dev/tty", O_RDWR, 0600)) >= 0) {
	 fprintf(outfile, "process has a controlling terminal\n");
	 Close(fd);
      } else {
	 fprintf(outfile, "process does not have a controlling terminal\n");
      }
   }

   /* process owner, groups */
   fprintf(outfile, "user id  = "F_uid"\n", Getuid());
   fprintf(outfile, "effective user id  = "F_uid"\n", Geteuid());
   fprintf(outfile, "group id = "F_gid"\n", Getgid());
   fprintf(outfile, "effective group id = "F_gid"\n", Getegid());

   {
      struct rlimit rlim;

      fprintf(outfile, "\nRESOURCE LIMITS\n");
      fprintf(outfile, "resource                         current         maximum\n");
      if (getrlimit(RLIMIT_CPU, &rlim) < 0) {
	 Warn2("getrlimit(RLIMIT_CPU, %p): %s", &rlim, strerror(errno));
      } else {
	 fprintf(outfile,
		 "cpu time (seconds)      %16"F_rlim_max"%16"F_rlim_max"\n",
		 rlim.rlim_cur, rlim.rlim_max);
      }
      if (getrlimit(RLIMIT_FSIZE, &rlim) < 0) {
	 Warn2("getrlimit(RLIMIT_FSIZE, %p): %s", &rlim, strerror(errno));
      } else {
	 fprintf(outfile,
		 "file size (blocks)      %16"F_rlim_max"%16"F_rlim_max"\n",
		 rlim.rlim_cur, rlim.rlim_max);
      }
      if (getrlimit(RLIMIT_DATA, &rlim) < 0) {
	 Warn2("getrlimit(RLIMIT_DATA, %p): %s", &rlim, strerror(errno));
      } else {
	 fprintf(outfile,
		 "data seg size (kbytes)  %16"F_rlim_max"%16"F_rlim_max"\n",
		 rlim.rlim_cur, rlim.rlim_max);
      }
      if (getrlimit(RLIMIT_STACK, &rlim) < 0) {
	 Warn2("getrlimit(RLIMIT_STACK, %p): %s", &rlim, strerror(errno));
      } else {
	 fprintf(outfile,
		 "stack size (blocks)     %16"F_rlim_max"%16"F_rlim_max"\n",
		 rlim.rlim_cur, rlim.rlim_max);
      }
      if (getrlimit(RLIMIT_CORE, &rlim) < 0) {
	 Warn2("getrlimit(RLIMIT_CORE, %p): %s", &rlim, strerror(errno));
      } else {
	 fprintf(outfile,
		 "core file size (blocks) %16"F_rlim_max"%16"F_rlim_max"\n",
		 rlim.rlim_cur, rlim.rlim_max);
      }
#ifdef RLIMIT_RSS	/* Linux, AIX; not Cygwin */
      if (getrlimit(RLIMIT_RSS, &rlim) < 0) {
	 Warn2("getrlimit(RLIMIT_RSS, %p): %s", &rlim, strerror(errno));
      } else {
	 fprintf(outfile,
		 "max resident set size   %16"F_rlim_max"%16"F_rlim_max"\n",
		 rlim.rlim_cur, rlim.rlim_max);
      }
#endif
#ifdef RLIMIT_NPROC	/* Linux, not AIX, Cygwin */
      if (getrlimit(RLIMIT_NPROC, &rlim) < 0) {
	 Warn2("getrlimit(RLIMIT_NPROC, %p): %s", &rlim, strerror(errno));
      } else {
	 fprintf(outfile,
		 "max user processes      %16"F_rlim_max"%16"F_rlim_max"\n",
		 rlim.rlim_cur, rlim.rlim_max);
      }
#endif
#ifdef RLIMIT_NOFILE	/* not AIX 4.1 */
      if (getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
	 Warn2("getrlimit(RLIMIT_NOFILE, %p): %s", &rlim, strerror(errno));
      } else {
	 fprintf(outfile,
		 "open files              %16"F_rlim_max"%16"F_rlim_max"\n",
		 rlim.rlim_cur, rlim.rlim_max);
      }
#endif
#ifdef RLIMIT_MEMLOCK	/* Linux, not AIX, Cygwin */
      if (getrlimit(RLIMIT_MEMLOCK, &rlim) < 0) {
	 Warn2("getrlimit(RLIMIT_MEMLOCK, %p): %s", &rlim, strerror(errno));
      } else {
	 fprintf(outfile,
		 "max locked-in-memory address space %16"F_rlim_max"%16"F_rlim_max"\n",
		 rlim.rlim_cur, rlim.rlim_max);
      }
#endif
#ifdef RLIMIT_AS
      if (getrlimit(RLIMIT_AS, &rlim) < 0) {
	 Warn2("getrlimit(RLIMIT_AS, %p): %s", &rlim, strerror(errno));
      } else {
	 fprintf(outfile,
		 "virtual memory (kbytes) %16"F_rlim_max"%16"F_rlim_max"\n",
		 rlim.rlim_cur, rlim.rlim_max);
      }
#endif
   }

   /* file descriptors */

   /* what was this for?? */
   /*Sleep(1);*/
   return 0;
}
Example #10
0
IOFile::IOFile(const std::string& filename, const char openmode[])
	: m_file(NULL), m_good(true)
{
	Open(filename, openmode);
}
Example #11
0
vfsStreamMemory::vfsStreamMemory(u64 addr) : vfsStream()
{
	Open(addr);
}
Example #12
0
/*
--------------------------------------------------------------------------------
open ...
(Standard instances management. Driver specific implementations should be put in Open() function.)
--------------------------------------------------------------------------------
*/
ST_ErrorCode_t STEXTVIN_Open(const ST_DeviceName_t DeviceName, const STEXTVIN_OpenParams_t * const OpenParams_p, STEXTVIN_Handle_t *Handle_p)
{
    S32 DeviceIndex = INVALID_DEVICE_INDEX, UnitIndex, Index;
    U32 OpenedUnitForThisInit;
    ST_ErrorCode_t ErrorCode = ST_NO_ERROR;

    /* Exit now if parameters are bad */
    if ((OpenParams_p == NULL) ||                       /* There must be parameters ! */
        (Handle_p == NULL) ||                           /* Pointer to handle should be valid ! */
        (strlen(DeviceName) > (ST_MAX_DEVICE_NAME - 1)) || /* Device name length should be respected */
        ((((const char *) DeviceName)[0]) == '\0')
       )
    {
        return(ST_ERROR_BAD_PARAMETER);
    }

    EnterCriticalSection();

    if (!FirstInitDone)
    {
        ErrorCode = ST_ERROR_UNKNOWN_DEVICE;
    }
    else
    {
        /* Check if device already initialised and return error if not so */
        DeviceIndex = GetIndexOfDeviceNamed(DeviceName);
        if (DeviceIndex == INVALID_DEVICE_INDEX)
        {
            /* Device name not found */
            ErrorCode = ST_ERROR_UNKNOWN_DEVICE;
        }
        else
        {
            /* Look for a free unit and check all opened units to check if MaxOpen is not reached */
            UnitIndex = STEXTVIN_MAX_UNIT;
            OpenedUnitForThisInit = 0;
            for (Index = 0; Index < STEXTVIN_MAX_UNIT; Index++)
            {
                if ((STEXTVIN_UnitArray[Index].UnitValidity == STEXTVIN_VALID_UNIT) && (STEXTVIN_UnitArray[Index].Device_p == &DeviceArray[DeviceIndex]))
                {
                    OpenedUnitForThisInit ++;
                }
                if (STEXTVIN_UnitArray[Index].UnitValidity != STEXTVIN_VALID_UNIT)
                {
                    /* Found a free handle structure */
                    UnitIndex = Index;
                }
            }
            if ((OpenedUnitForThisInit >= DeviceArray[DeviceIndex].MaxOpen) || (UnitIndex >= STEXTVIN_MAX_UNIT))
            {
                /* None of the units is free or MaxOpen reached */
                ErrorCode = ST_ERROR_NO_FREE_HANDLES;
            }
            else
            {
                *Handle_p = (STEXTVIN_Handle_t) &STEXTVIN_UnitArray[UnitIndex];
                STEXTVIN_UnitArray[UnitIndex].Device_p = &DeviceArray[DeviceIndex];

                /* API specific actions after opening */
                ErrorCode = Open(&STEXTVIN_UnitArray[UnitIndex], OpenParams_p);

                if (ErrorCode == ST_NO_ERROR)
                {
                    /* Register opened handle */
                    STEXTVIN_UnitArray[UnitIndex].UnitValidity = STEXTVIN_VALID_UNIT;

                    STTBX_Report((STTBX_REPORT_LEVEL_INFO, "Handle opened on device '%s'", DeviceName));
                }
            } /* End found unit unused */
        } /* End device valid */
    } /* End FirstInitDone */

    LeaveCriticalSection();

    return(ErrorCode);
} /* End fo STEXTVIN_Open() function */
	long SmtAnnoFclsAdoLayer::AppendFeature(const SmtFeature *pSmtFeature,bool bclone)
	{
		long lRet = SMT_ERR_NONE;
		//////////////////////////////////////////////////////////////////////////
		//db
		if (!IsOpen())
			if (!Open(m_szLayerTableName))
				return SMT_ERR_DB_OPER;

		int nGridID = 0;
		char  szAnnoBuf[TEMP_BUFFER_SIZE];
		int nClr = 0;
		double fAngle = 0.;

		Envelope env;
		const SmtGeometry *pGeom = pSmtFeature->GetGeometryRef();
		const SmtAttribute *pAtt = pSmtFeature->GetAttributeRef();
		const SmtStyle	*pStyle = pSmtFeature->GetStyle();

		pGeom->GetEnvelope(&env);
		
		m_SmtRecordset.AddNew();	
		m_SmtRecordset.PutCollect("ID",_variant_t(pSmtFeature->GetID()));
		m_SmtRecordset.PutCollect("mbr_xmin",_variant_t(env.MinX));
		m_SmtRecordset.PutCollect("mbr_ymin",_variant_t(env.MinY));
		m_SmtRecordset.PutCollect("mbr_xmax",_variant_t(env.MaxX));
		m_SmtRecordset.PutCollect("mbr_ymax",_variant_t(env.MaxY));
		m_SmtRecordset.PutCollect("grid_id",_variant_t(nGridID));
		//////////////////////////////////////////////////////////////////////////
		lRet = AppendStyle(pStyle);

		//////////////////////////////////////////////////////////////////////////
		lRet = AppendGeom(pGeom);

		//////////////////////////////////////////////////////////////////////////
		const SmtField *pFld = NULL;

		pFld = pAtt->GetFieldPtr(pAtt->GetFieldIndex("anno"));
		sprintf(szAnnoBuf,pFld->GetValueAsString());
		m_SmtRecordset.PutCollect("anno",_variant_t(szAnnoBuf));

		pFld = pAtt->GetFieldPtr(pAtt->GetFieldIndex("color"));
		nClr = pFld->GetValueAsInteger();
		m_SmtRecordset.PutCollect("color",_variant_t(nClr));

		pFld = pAtt->GetFieldPtr(pAtt->GetFieldIndex("angle"));
		fAngle = pFld->GetValueAsDouble();
		m_SmtRecordset.PutCollect("angle",_variant_t(fAngle));

		if (!m_SmtRecordset.Update()) 
		{
			SMT_SAFE_DELETE(pSmtFeature);
			return SMT_ERR_DB_OPER;
		}

		//mem
		m_pMemLayer->AppendFeature(pSmtFeature,bclone);
		CalEnvelope();

		return lRet;
	}
bool File::OpenTemporaryFile(const std::wstring &dir)
{
	return Open(tmpnam(NULL), MODE_TEMP);
} 
Example #15
0
cJoystickSDL::cJoystickSDL( const Uint32& index ) :
	cJoystick( index ),
	mJoystick( NULL )
{
	Open();
}
Example #16
0
	void VehicleDoor::isOpen::set(bool value) {
		if (value)
			Open();
		else 
			Close();
	}
Example #17
0
bool CInFile::OpenShared(LPCWSTR fileName, bool shareForWrite)
{
    return Open(fileName, FILE_SHARE_READ | (shareForWrite ? FILE_SHARE_WRITE : 0), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
}
Example #18
0
bool DTVChannel::SetChannelByString(const QString &channum)
{
    QString loc = LOC + QString("SetChannelByString(%1): ").arg(channum);
    LOG(VB_CHANNEL, LOG_INFO, loc);

    ClearDTVInfo();

    if (!IsOpen() && !Open())
    {
        LOG(VB_GENERAL, LOG_ERR, loc + "Channel object "
                "will not open, can not change channels.");

        return false;
    }

    if (!m_inputid)
        return false;

    uint mplexid_restriction;
    uint chanid_restriction;
    if (!IsInputAvailable(mplexid_restriction, chanid_restriction))
    {
        LOG(VB_GENERAL, LOG_INFO, loc +
            QString("Requested channel '%1' is on input '%2' "
                    "which is in a busy input group")
                .arg(channum).arg(m_inputid));

        return false;
    }

    // Fetch tuning data from the database.
    QString tvformat, modulation, freqtable, freqid, si_std;
    int finetune;
    uint64_t frequency;
    int mpeg_prog_num;
    uint atsc_major, atsc_minor, mplexid, chanid, tsid, netid;

    if (!ChannelUtil::GetChannelData(
        m_sourceid, chanid, channum,
        tvformat, modulation, freqtable, freqid,
        finetune, frequency,
        si_std, mpeg_prog_num, atsc_major, atsc_minor, tsid, netid,
        mplexid, m_commfree))
    {
        LOG(VB_GENERAL, LOG_ERR, loc + "Unable to find channel in database.");

        return false;
    }

    if ((mplexid_restriction && (mplexid != mplexid_restriction)) ||
        (!mplexid_restriction &&
         chanid_restriction && (chanid != chanid_restriction)))
    {
        LOG(VB_GENERAL, LOG_ERR, loc +
            QString("Requested channel '%1' is not available because "
                    "the tuner is currently in use on another transport.")
                .arg(channum));

        return false;
    }

    // If the frequency is zeroed out, don't use it directly.
    if (frequency == 0)
    {
        frequency = (freqid.toULongLong() + finetune) * 1000;
        mplexid = 0;
    }
    bool isFrequency = (frequency > 10000000);
    bool hasTuneToChan =
        !m_tuneToChannel.isEmpty() && m_tuneToChannel != "Undefined";

    // If we are tuning to a freqid, rather than an actual frequency,
    // we may need to set the frequency table to use.
    if (!isFrequency || hasTuneToChan)
        SetFreqTable(freqtable);

    // Set NTSC, PAL, ATSC, etc.
    SetFormat(tvformat);

    // If a tuneToChannel is set make sure we're still on it
    if (hasTuneToChan)
        Tune(m_tuneToChannel, 0);

    // Clear out any old PAT or PMT & save version info
    uint version = 0;
    if (genPAT)
    {
        version = (genPAT->Version()+1) & 0x1f;
        delete genPAT; genPAT = NULL;
        delete genPMT; genPMT = NULL;
    }

    bool ok = true;
    if (m_externalChanger.isEmpty())
    {
        if (IsIPTV())
        {
            int chanid = ChannelUtil::GetChanID(m_sourceid, channum);
            IPTVTuningData tuning = ChannelUtil::GetIPTVTuningData(chanid);
            if (!Tune(tuning, false))
            {
                LOG(VB_GENERAL, LOG_ERR, loc + "Tuning to IPTV URL");
                ClearDTVInfo();
                ok = false;
            }
        }
        else if (m_name.contains("composite", Qt::CaseInsensitive) ||
                 m_name.contains("component", Qt::CaseInsensitive) ||
                 m_name.contains("s-video", Qt::CaseInsensitive))
        {
            LOG(VB_GENERAL, LOG_WARNING, loc + "You have not set "
                    "an external channel changing"
                    "\n\t\t\tscript for a component|composite|s-video "
                    "input. Channel changing will do nothing.");
        }
        else if (isFrequency && Tune(frequency))
        {
        }
        else if (isFrequency)
        {
            // Initialize basic the tuning parameters
            DTVMultiplex tuning;
            if (!mplexid || !tuning.FillFromDB(tunerType, mplexid))
            {
                LOG(VB_GENERAL, LOG_ERR, loc +
                        "Failed to initialize multiplex options");
                ok = false;
            }
            else
            {
                // Try to fix any problems with the multiplex
                CheckOptions(tuning);

                // Tune to proper multiplex
                if (!Tune(tuning))
                {
                    LOG(VB_GENERAL, LOG_ERR, loc + "Tuning to frequency.");

                    ClearDTVInfo();
                    ok = false;
                }
            }
        }
        else
        {
            // ExternalChannel justs wants the channum
            ok = freqid.isEmpty() && finetune == 0 ?
                 Tune(channum) : Tune(freqid, finetune);
        }
    }

    LOG(VB_CHANNEL, LOG_INFO, loc + ((ok) ? "success" : "failure"));

    if (!ok)
        return false;

    if (atsc_minor || (mpeg_prog_num>=0))
    {
        SetSIStandard(si_std);
        SetDTVInfo(atsc_major, atsc_minor, netid, tsid, mpeg_prog_num);
    }
    else if (IsPIDTuningSupported())
    {
        // We need to pull the pid_cache since there are no tuning tables
        pid_cache_t pid_cache;
        int chanid = ChannelUtil::GetChanID(m_sourceid, channum);
        ChannelUtil::GetCachedPids(chanid, pid_cache);
        if (pid_cache.empty())
        {
            LOG(VB_GENERAL, LOG_ERR, loc + "PID cache is empty");
            return false;
        }

        // Now we construct the PAT & PMT
        vector<uint> pnum; pnum.push_back(1);
        vector<uint> pid;  pid.push_back(9999);
        genPAT = ProgramAssociationTable::Create(0,version,pnum,pid);

        int pcrpid = -1;
        vector<uint> pids;
        vector<uint> types;
        pid_cache_t::iterator pit = pid_cache.begin();
        for (; pit != pid_cache.end(); ++pit)
        {
            if (!pit->GetStreamID())
                continue;
            pids.push_back(pit->GetPID());
            types.push_back(pit->GetStreamID());
            if (pit->IsPCRPID())
                pcrpid = pit->GetPID();
            if ((pcrpid < 0) && StreamID::IsVideo(pit->GetStreamID()))
                pcrpid = pit->GetPID();
        }
        if (pcrpid < 0)
            pcrpid = pid_cache[0].GetPID();

        genPMT = ProgramMapTable::Create(
            pnum.back(), pid.back(), pcrpid, version, pids, types);

        SetSIStandard("mpeg");
        SetDTVInfo(0,0,0,0,-1);
    }

    // Set the current channum to the new channel's channum
    m_curchannelname = channum;

    // Setup filters & recording picture attributes for framegrabing recorders
    // now that the new curchannelname has been established.
    if (m_pParent)
        m_pParent->SetVideoFiltersForChannel(GetSourceID(), channum);
    InitPictureAttributes();

    HandleScript(freqid);

    return ok;
}
Example #19
0
bool COutFile::Create(LPCWSTR fileName, bool createAlways)
{
    return Open(fileName, GetCreationDisposition(createAlways));
}
Example #20
0
bool
FileDescriptor::OpenReadOnly(const char *pathname)
{
  return Open(pathname, O_RDONLY);
}
Example #21
0
	/** Attaches <code>aCompoundControl</code> to the layout manager.
		Is normally not called manually since <code>CCoeControl::SetLayoutManagerL()</code>
		calls this function.
		Once a compound control is attached to a layout manager, the layout manager owns itself.
		@see Detach
		@see CCoeControl::SetLayoutManagerL
		@param aCompoundControl The compound control.
		@leave KErrOverflow
	*/
void CLayoutTest::AttachL(CCoeControl& aCompoundControl)
	{
	Open();
	iCtrlArray.Append(&aCompoundControl);
	}
Example #22
0
bool
FileDescriptor::OpenNonBlocking(const char *pathname)
{
  return Open(pathname, O_RDWR | O_NONBLOCK);
}
Example #23
0
main( int argc, char **argv )
{
    int colors;
    struct {
	long nplanes;
	long pbytes;
	long across;
	long down;
	long npics;
	long xsize;
	long ysize;
    } pdat;
    long pbytes;	/* Bytes of data in a plane */
    int i, cnt;
    BitMapHeader bmhd;
    struct IFFHandle *iff;
    long camg = HIRES|LACE;
    int tiles=0;
    char **planes;

    if(argc != 3){
	fprintf(stderr, "Usage: %s source destination\n", argv[0]);
	exit(1);
    }

#if defined(_DCC) || defined(__GNUC__)
    IFFParseBase = OpenLibrary( "iffparse.library", 0 );
    if( !IFFParseBase ) {
	error( "unable to open iffparse.library" );
	exit( 1 );
    }
#endif

    /* First, count the files in the file */
    if( fopen_text_file( argv[1], "r" ) != TRUE )
    {
	perror( argv[1] );
	return( 1 );
    }

    nplanes = 0;
    i = colorsinmap-1; /*IFFScreen.Colors - 1; */
    while( i != 0 )
    {
	nplanes++;
	i >>= 1;
    }

    planes = malloc( nplanes * sizeof( char * ) );
    if( planes == 0 )
    {
	error( "can not allocate planes pointer" );
	exit( 1 );
    }

    while( read_text_tile( pixels ) == TRUE )
	++tiles;
    fclose_text_file();

    IFFScreen.Width = COLS * TILE_X;
    IFFScreen.Height = ROWS * TILE_Y;

    pbytes = (COLS * ROWS * TILE_X + 15) / 16 * 2 * TILE_Y;

    for( i = 0; i < nplanes; ++i )
    {
	planes[ i ] = calloc( 1, pbytes );
	if( planes[ i ] == 0 )
	{
	    error( "can not allocate planes pointer" );
	    exit( 1 );
	}
    }

    /* Now, process it */
    if( fopen_text_file( argv[1], "r" ) != TRUE )
    {
	perror( argv[1] );
	return( 1 );
    }

    iff = AllocIFF();
    if( !iff )
    {
	error( "Can not allocate IFFHandle" );
	return( 1 );
    }

    iff->iff_Stream = Open( argv[2], MODE_NEWFILE );
    if( !iff->iff_Stream )
    {
	error( "Can not open output file" );
	return( 1 );
    }

    InitIFFasDOS( iff );
    OpenIFF( iff, IFFF_WRITE );

    PushChunk( iff, ID_BMAP, ID_FORM, IFFSIZE_UNKNOWN );

    bmhd.w = IFFScreen.Width;
    bmhd.h = IFFScreen.Height;
    bmhd.x = 0;
    bmhd.y = 0;
    bmhd.nPlanes = nplanes;
    bmhd.masking = 0;
    bmhd.compression = 0;
    bmhd.reserved1 = 0;
    bmhd.transparentColor = 0;
    bmhd.xAspect = 100;
    bmhd.yAspect = 100;
    bmhd.pageWidth = TILE_X;
    bmhd.pageHeight = TILE_Y;

    PushChunk( iff, ID_BMAP, ID_BMHD, sizeof( bmhd ) );
    WriteChunkBytes( iff, &bmhd, sizeof( bmhd ) );
    PopChunk( iff );

    PushChunk( iff, ID_BMAP, ID_CAMG, sizeof( camg ) );
    WriteChunkBytes( iff, &camg, sizeof( camg ) );
    PopChunk( iff );

    /* We need to reorder the colors to get reasonable default pens but
     * we also need to know where some of the colors are - so go find out.
     */
    map_colors();

    cmap = malloc( (colors = (1L<<nplanes)) * sizeof(AmiColorMap) );
    for( i = 0; i < colors; ++i )
    {
	cmap[ colrmap[ i ] ].r = ColorMap[ CM_RED ][ i ];
	cmap[ colrmap[ i ] ].g = ColorMap[ CM_GREEN ][ i ];
	cmap[ colrmap[ i ] ].b = ColorMap[ CM_BLUE ][ i ];
    }

    PushChunk( iff, ID_BMAP, ID_CMAP, IFFSIZE_UNKNOWN );
    for (i = 0; i < colors; ++i)
	WriteChunkBytes(iff, &cmap[i], 3);
    PopChunk( iff );

    cnt = 0;
    while( read_text_tile( pixels ) == TRUE )
    {
	packwritebody( pixels, planes, cnt );
	if( cnt % 20 == 0 )
	    printf( "%d..", cnt );
	++cnt;
	fflush( stdout );
    }

    pdat.nplanes = nplanes;
    pdat.pbytes = pbytes;
    pdat.xsize = TILE_X;
    pdat.ysize = TILE_Y;
    pdat.across = COLS;
    pdat.down = ROWS;
    pdat.npics = cnt;

    PushChunk( iff, ID_BMAP, ID_PDAT, IFFSIZE_UNKNOWN );
    WriteChunkBytes( iff, &pdat, sizeof( pdat ) );
    PopChunk( iff );

    PushChunk( iff, ID_BMAP, ID_PLNE, IFFSIZE_UNKNOWN );
    for( i = 0; i < nplanes; ++i )
	WriteChunkBytes( iff, planes[i], pbytes );
    PopChunk( iff );

    CloseIFF( iff );
    Close( iff->iff_Stream );
    FreeIFF( iff );

    printf( "\n%d tiles converted\n", cnt );

#if defined(_DCC) || defined(__GNUC__)
    CloseLibrary( IFFParseBase );
#endif
    exit( 0 );
}
Example #24
0
size_t Clipboard::Get(LPTSTR aBuf)
// If aBuf is NULL, it returns the length of the text on the clipboard and leaves the
// clipboard open.  Otherwise, it copies the clipboard text into aBuf and closes
// the clipboard (UPDATE: But only if the clipboard is still open from a prior call
// to determine the length -- see later comments for details).  In both cases, the
// length of the clipboard text is returned (or the value CLIPBOARD_FAILURE if error).
// If the clipboard is still open when the next MsgSleep() is called -- presumably
// because the caller never followed up with a second call to this function, perhaps
// due to having insufficient memory -- MsgSleep() will close it so that our
// app doesn't keep the clipboard tied up.  Note: In all current cases, the caller
// will use MsgBox to display an error, which in turn calls MsgSleep(), which will
// immediately close the clipboard.
{
	// Seems best to always have done this even if we return early due to failure:
	if (aBuf)
		// It should be safe to do this even at its peak capacity, because caller
		// would have then given us the last char in the buffer, which is already
		// a zero terminator, so this would have no effect:
		*aBuf = '\0';

	UINT i, file_count = 0;
	BOOL clipboard_contains_text = IsClipboardFormatAvailable(CF_NATIVETEXT);
	BOOL clipboard_contains_files = IsClipboardFormatAvailable(CF_HDROP);
	if (!(clipboard_contains_text || clipboard_contains_files))
		return 0;

	if (!mIsOpen)
	{
		// As a precaution, don't give the caller anything from the clipboard
		// if the clipboard isn't already open from the caller's previous
		// call to determine the size of what's on the clipboard (no other app
		// can alter its size while we have it open).  The is to prevent a
		// buffer overflow from happening in a scenario such as the following:
		// Caller calls us and we return zero size, either because there's no
		// CF_TEXT on the clipboard or there was a problem opening the clipboard.
		// In these two cases, the clipboard isn't open, so by the time the
		// caller calls us again, there's a chance (vanishingly small perhaps)
		// that another app (if our thread were preempted long enough, or the
		// platform is multiprocessor) will have changed the contents of the
		// clipboard to something larger than zero.  Thus, if we copy that
		// into the caller's buffer, the buffer might overflow:
		if (aBuf)
			return 0;
		if (!Open())
		{
			// Since this should be very rare, a shorter message is now used.  Formerly, it was
			// "Could not open clipboard for reading after many timed attempts. Another program is probably holding it open."
			Close(CANT_OPEN_CLIPBOARD_READ);
			return CLIPBOARD_FAILURE;
		}
		if (   !(mClipMemNow = g_clip.GetClipboardDataTimeout(clipboard_contains_files ? CF_HDROP : CF_NATIVETEXT))   )
		{
			// v1.0.47.04: Commented out the following that had been in effect when clipboard_contains_files==false:
			//    Close("GetClipboardData"); // Short error message since so rare.
			//    return CLIPBOARD_FAILURE;
			// This was done because there are situations when GetClipboardData can fail indefinitely.
			// For example, in Firefox, pulling down the Bookmarks menu then right-clicking "Bookmarks Toolbar
			// Folder" then selecting "Copy" puts one or more formats on the clipboard that cause this problem.
			// For details, search the forum for TYMED_NULL.
			//
			// v1.0.42.03: For the fix below, GetClipboardDataTimeout() knows not to try more than once
			// for CF_HDROP.
			// Fix for v1.0.31.02: When clipboard_contains_files==true, tolerate failure, which happens
			// as a normal/expected outcome when there are files on the clipboard but either:
			// 1) zero of them;
			// 2) the CF_HDROP on the clipboard is somehow misformatted.
			// If you select the parent ".." folder in WinRar then use the following hotkey, the script
			// would previously yield a runtime error:
			//#q::
			//Send, ^c
			//ClipWait, 0.5, 1
			//msgbox %Clipboard%
			//Return
			Close();
			if (aBuf)
				*aBuf = '\0';
			return CLIPBOARD_FAILURE; // Return this because otherwise, Contents() returns mClipMemNowLocked, which is NULL.
		}
		// Although GlobalSize(mClipMemNow) can yield zero in some cases -- in which case GlobalLock() should
		// not be attempted -- it probably can't yield zero for CF_HDROP and CF_TEXT because such a thing has
		// never been reported by anyone.  Therefore, GlobalSize() is currently not called.
		if (   !(mClipMemNowLocked = (LPTSTR)GlobalLock(mClipMemNow))   )
		{
			Close(_T("GlobalLock"));  // Short error message since so rare.
			return CLIPBOARD_FAILURE;
		}
		// Otherwise: Update length after every successful new open&lock:
		// Determine the length (size - 1) of the buffer than would be
		// needed to hold what's on the clipboard:
		if (clipboard_contains_files)
		{
			if (file_count = DragQueryFile((HDROP)mClipMemNowLocked, 0xFFFFFFFF, _T(""), 0))
			{
				mLength = (file_count - 1) * 2;  // Init; -1 if don't want a newline after last file.
				for (i = 0; i < file_count; ++i)
					mLength += DragQueryFile((HDROP)mClipMemNowLocked, i, NULL, 0);
			}
			else
				mLength = 0;
		}
		else // clipboard_contains_text
			mLength = _tcslen(mClipMemNowLocked);
		if (mLength >= CLIPBOARD_FAILURE) // Can't realistically happen, so just indicate silent failure.
			return CLIPBOARD_FAILURE;
	}
	if (!aBuf)
		return mLength;
		// Above: Just return the length; don't close the clipboard because we expect
		// to be called again soon.  If for some reason we aren't called, MsgSleep()
		// will automatically close the clipboard and clean up things.  It's done this
		// way to avoid the chance that the clipboard contents (and thus its length)
		// will change while we don't have it open, possibly resulting in a buffer
		// overflow.  In addition, this approach performs better because it avoids
		// the overhead of having to close and reopen the clipboard.

	// Otherwise:
	if (clipboard_contains_files)
	{
		if (file_count = DragQueryFile((HDROP)mClipMemNowLocked, 0xFFFFFFFF, _T(""), 0))
			for (i = 0; i < file_count; ++i)
			{
				// Caller has already ensured aBuf is large enough to hold them all:
				aBuf += DragQueryFile((HDROP)mClipMemNowLocked, i, aBuf, 999);
				if (i < file_count - 1) // i.e. don't add newline after the last filename.
				{
					*aBuf++ = '\r';  // These two are the proper newline sequence that the OS prefers.
					*aBuf++ = '\n';
				}
				//else DragQueryFile() has ensured that aBuf is terminated.
			}
		// else aBuf has already been terminated upon entrance to this function.
	}
	else
		_tcscpy(aBuf, mClipMemNowLocked);  // Caller has already ensured that aBuf is large enough.
	// Fix for v1.0.37: Close() is no longer called here because it prevents the clipboard variable
	// from being referred to more than once in a line.  For example:
	// Msgbox %Clipboard%%Clipboard%
	// ToolTip % StrLen(Clipboard) . Clipboard
	// Instead, the clipboard is later closed in other places (search on CLOSE_CLIPBOARD_IF_OPEN
	// to find them).  The alternative to fixing it this way would be to let it reopen the clipboard
	// by means getting rid of the following lines above:
	//if (aBuf)
	//	return 0;
	// However, that has the risks described in the comments above those two lines.
	return mLength;
}
Example #25
0
BOOL TaskRegSave( VOID )
{
	STRPTR data;
	ULONG data_len = 0;
	int items = 0;
	BOOL rc = FALSE;
	TaskReg *entry;
	struct DupsLog *d;
	
	ENTER();
	
	// this is executed uSemaLock()'ed or Forbid()'ed
	
	DBG_ASSERT(G && G->MagicID == GLOBAL_MAGIC);
	if(!G || G->MagicID != GLOBAL_MAGIC)
	{
		SetIoErr(ERROR_OBJECT_WRONG_TYPE);
		return FALSE;
	}
	
	if(IsMinListEmpty(G->TaskRegList))
	{
		DBG("The list is empty!\n");
		return TRUE;
	}
	
	NewList((struct List *) &tr_dups );
	
	ITERATE_LIST( G->TaskRegList, TaskReg *, entry)
	{
		if(IsDup(entry->TaskName,entry->AlertFlags,entry->ServerPort))
			continue;
		
		if((d = Malloc(sizeof(struct DupsLog))))
		{
			d->TaskName   = entry->TaskName;
			d->AlertFlags = entry->AlertFlags;
			d->ServerPort = entry->ServerPort;
			AddTail((struct List *)&tr_dups, (struct Node *)d);
		}
		
		items++;
		
		data_len += entry->TaskNameLength;
		#if DATABASE_RESERVED
		data_len += DATABASE_RESERVED;
		#endif
	}
	
	data_len += (sizeof(TaskReg) * items) + (sizeof(ULONG)*3);
	DBG_VALUE(data_len);
	
	if((data = Malloc(data_len)))
	{
		STRPTR ptr=data;
		BPTR fd;
		
		PutV( ptr, ULONG, DATABASE_ID);
		PutV( ptr, ULONG, DATABASE_VERSION);
		
		ITERATE_LIST( G->TaskRegList, TaskReg *, entry)
		{
			DBG_STRING(entry->TaskName);
			
			if(IsDup(entry->TaskName,entry->AlertFlags,entry->ServerPort))
				continue;
			
			PutV( ptr, UWORD, entry->TaskNameLength );
			PutX( ptr, entry->TaskNameLength, entry->TaskName );
			
			PutV( ptr, BYTE, entry->allow );
			PutV( ptr, BYTE, entry->remember );
			
			PutV( ptr, ULONG, entry->RegTime.ds_Days );
			PutV( ptr, ULONG, entry->RegTime.ds_Minute );
			PutV( ptr, ULONG, entry->RegTime.ds_Tick );
			
			PutV( ptr, ULONG, entry->ModTime.ds_Days );
			PutV( ptr, ULONG, entry->ModTime.ds_Minute );
			PutV( ptr, ULONG, entry->ModTime.ds_Tick );
			
			PutV( ptr, ULONG, entry->accesses   );
			PutV( ptr, ULONG, entry->FileCRC    );
			PutV( ptr, UWORD, entry->CRCMods    );
			PutV( ptr, UWORD, entry->AlertFlags );
			PutV( ptr, UWORD, entry->ServerPort );
			
			#if DATABASE_RESERVED
			ptr += DATABASE_RESERVED;
			#endif
		}
		
		PutV( ptr, ULONG, DATABASE_EOFID );
		
		if((fd = Open( DATABASE_FILE, MODE_NEWFILE )))
		{
			LONG len = (LONG)(ptr-data);
			DBG_VALUE(len);
			
			transcode( data, len );
			
			rc = (Write( fd, data, len ) == len);
			Close(fd);
		}
		
		Free(data);
	}
Example #26
0
 /*! \brief constructor */
 StdFile(const char *fname, const char *mode) {
   Open(fname, mode);
 }
Example #27
0
/**
	Handle the requests for this channel.

@param aFunction 	The operation the LDD should perform.
@param a1 			The first argument for the operation.
@param a2 			The second argument for the operation.
@return KErrNone on success or one of the system wide error codes.
*/
TInt DDefragChannel::Request(TInt aFunction, TAny* a1, TAny* a2)
	{
	TInt r = KErrNone;
	NKern::ThreadEnterCS();

	Kern::SemaphoreWait(*iDefragSemaphore);
	if (!iDefragDfcFree && aFunction != RDefragChannel::EControlGeneralDefragDfcComplete)
		{// Only allow a single defrag operation at a time.
		r = KErrInUse;
		goto exit;
		}

	switch (aFunction)
		{
		case RDefragChannel::EControlGeneralDefragDfc:
			// Queue a defrag operation so that on completion it queues a
			// DFC on this driver.
			iRequestThread = &Kern::CurrentThread();
			iRequestThread->Open();

			// Open a reference on this channel to stop the destructor running before
			// the defrag request has completed.
			Open();
			r = iCompleteReq->SetStatus((TRequestStatus*)a1);
			if (r == KErrNone)
				r = iDefragReq.DefragRam(&iDefragCompleteDfc, KDefragRamThreadPriority);
			if (r != KErrNone)
				{// defrag operation didn't start so close all openned handles
				AsyncClose();
				iRequestThread->AsyncClose();
				iRequestThread = NULL;
				}
			else
				iDefragDfcFree = EFalse;
			break;

		case RDefragChannel::EControlGeneralDefragDfcComplete:
			if (iRequestThread != NULL)
				{// The defrag dfc hasn't completed so this shouldn't have been invoked.
				r = KErrGeneral;
				}
			else
				{
				iDefragDfcFree = ETrue;
				}
			break;

		case RDefragChannel::EControlGeneralDefragSem:
			{// Queue a defrag operation so that it will signal a fast mutex once
			// it has completed.
			NFastSemaphore sem;
			NKern::FSSetOwner(&sem, 0);
			r = iDefragReq.DefragRam(&sem, KDefragRamThreadPriority);

			if (r != KErrNone)
				{// Error occurred attempting to queue the defrag operation.
				break;
				}

			// Defrag operation has now been queued so wait for it to finish.
			// Could do some extra kernel side work here before waiting on the 
			// semaphore.
			NKern::FSWait(&sem);
			r = iDefragReq.Result();
			}
			break;

		case RDefragChannel::EControlGeneralDefrag:
			// Synchronously perform a defrag.
			{
			r = iDefragReq.DefragRam(KDefragRamThreadPriority);
			}
			break;

		case RDefragChannel::EControlAllocLowestZone:
			// Allocate from the lowest preference zone
			r = DoAllocLowestZone();
			break;

		case RDefragChannel::EControlClaimLowestZone:
			// Claims the lowest preference zone
			r = DoClaimLowestZone();
			break;
			
		case RDefragChannel::EControlCloseChunk:
			// Have finished with the chunk so close it then free the RAM mapped by it
			r = DoChunkClose();
			TRACE( if (r != KErrNone) {Kern::Printf("ChunkClose returns %d", r);});
			break;

		default:
			r=KErrNotSupported;
			break;
		}
Example #28
0
LuaStateOutFile::LuaStateOutFile(const char* fileName) :
    m_file( NULL ),
    m_fileOwner( false )
{
	Open(fileName);
}
Example #29
0
 int JackAlsaAdapter::SetSampleRate ( jack_nframes_t sample_rate )
 {
     JackAudioAdapterInterface::SetHostSampleRate ( sample_rate );
     Close();
     return Open();
 }
EXPORT_C CMemSpyEngineObject::CMemSpyEngineObject( CMemSpyEngineObject& aParent )
:   iParent( &aParent )
    {
    Open();
    }