Ejemplo n.º 1
0
void CChatMember::addChatWindow()
{
	ADDTOCALLSTACK("CChatMember::addChatWindow");
	// Called from Event_ChatButton

	CClient *pClient = GetClient();
	if ( !pClient || (!pClient->m_UseNewChatSystem && m_bChatActive) )
		return;

	// Open chat window (old chat system only)
	// On new chat system this is not needed because the chat button is hardcoded on client-side, and
	// PacketChatButton packet is sent by client after login complete only to get initial channel list
	if ( !pClient->m_UseNewChatSystem )
		pClient->addChatSystemMessage(CHATCMD_OpenChatWindow, GetChatName());

	// Send channel names
	for ( CChatChannel *pChannel = static_cast<CChatChannel *>(g_Serv.m_Chats.m_Channels.GetHead()); pChannel != NULL; pChannel = pChannel->GetNext() )
	{
		pClient->addChatSystemMessage(CHATCMD_AddChannel, pChannel->m_sName, pClient->m_UseNewChatSystem ? NULL : pChannel->GetPasswordString());
		if ( (g_Cfg.m_iChatFlags & CHATF_AUTOJOIN) && pChannel->m_bStatic && !GetChannel() )
			g_Serv.m_Chats.JoinChannel(pChannel->m_sName, NULL, this);
	}
}
Ejemplo n.º 2
0
	BoxClass::current_tone_list BoxClass::GetCurrentTones()
	{
		ScopedLock lock(mutex);
		current_tone_list retval;
		if (!box) return retval;
		struct mutabor_logic_parsed * file = box->file;
		if (!file) return retval;
		// no file means no logic (implying no current logic)

		int count = box->key_count;
		if (!count) return retval;
		retval.resize(count);

		size_t i = 0;
		for (mutabor_note_type * key = mutabor_find_key_in_box(box,0);
		     key != NULL;
		     key = mutabor_find_key_in_box(box,key->next)) {

			int index = key->number;
			mutabor_tone tone;

			switch (tone=get_frequency(index)) {
			case MUTABOR_NO_KEY:
				break;
			case MUTABOR_INVALID_KEY:
				retval[i].flag=tone_entry::invalid;
				break;
			default:
				retval[i] = current_tone_entry(index,
							       mutabor_convert_tone_to_pitch(tone),
							       key->id,
							       GetChannel(index, key->channel, key->id));
			}
			++i;
		}
		return retval;
	}
void CServerSynchedStorage::ResetChannel(int channelId)
{
	CryAutoCriticalSection lock(m_mutex);

	TChannelQueueMap::iterator cit=m_channelQueue.lower_bound(SChannelQueueEnt(channelId, 0));
	while (cit != m_channelQueue.end() && cit->first.channel == channelId)
	{
		TChannelQueueMap::iterator next = cit;
		++next;
		m_channelQueue.erase(cit);
		cit = next;
	}

	TChannelQueueMap::iterator git=m_globalQueue.lower_bound(SChannelQueueEnt(channelId, 0));
	while (git != m_globalQueue.end() && git->first.channel == channelId)
	{
		TChannelQueueMap::iterator next = git;
		++next;
		m_globalQueue.erase(git);
		git = next;
	}

	TChannelEntityQueueMap::iterator eit=m_entityQueue.lower_bound(SChannelEntityQueueEnt(channelId, 0, 0));
	while (eit != m_entityQueue.end() && eit->first.channel == channelId)
	{
		TChannelEntityQueueMap::iterator next = eit;
		++next;
		m_entityQueue.erase(eit);
		eit = next;
	}

	if (SChannel *pChannel = GetChannel(channelId))
	{
		if (pChannel->pNetChannel)
			pChannel->pNetChannel->AddSendable( new CClientSynchedStorage::CResetMsg(channelId, this), 1, &pChannel->lastOrderedMessage, &pChannel->lastOrderedMessage );
	}
}
Ejemplo n.º 4
0
void CSoundMgr::CleanUp (void)

//	CleanUp
//
//	Clean up sound manager

	{
	if (m_pDS)
		{
		//	Stop and delete all buffers

		for (int i = 0; i < GetChannelCount(); i++)
			{
			SChannel *pChannel = GetChannel(i);
			while (pChannel)
				{
				pChannel->pBuffer->Stop();
				pChannel->pBuffer->Release();

				SChannel *pDelete = pChannel;
				pChannel = pChannel->pNext;
				delete pDelete;
				}

			}

		m_Channels.RemoveAll();

		//	Kill the DirectSound object

		m_pDS->Release();
		m_pDS = NULL;
		}

	if (m_hMusic)
		::DestroyWindow(m_hMusic);
	}
Ejemplo n.º 5
0
static	BOOL	StartSoundChannel( SoundManager *sm, unsigned int Handle, geSound_Cfg *cfg, int loop, unsigned int* sfx)
{
	HRESULT	hres;
	Channel* channel, *dupChannel;
	
	if( Handle == 0 )
		return( FALSE );
	channel = GetChannel( sm, Handle );
	//Clear all non-playing duplicate buffers.
	ClearDupBuffers(channel);
	//If the main buffer is playing and all non-playing dups have been cleared
	//we need a new duplicate.
	if( ChannelPlaying( channel ) )
	{
		if(!DupChannel( sm,channel, &dupChannel ) )
			return( FALSE );
		channel = dupChannel;
	}
	if( !ModifyChannel( channel, cfg ) )
		return( FALSE );
	IDirectSoundBuffer_SetCurrentPosition(channel->buffer, 0);
	hres = IDirectSoundBuffer_Play( channel->buffer,
				  				   0,
				  				   0,
				  				   loop ? DSBPLAY_LOOPING : 0);

	if	(hres == DS_OK)
	{
		if( sfx )
			*sfx = channel->ID;
		return TRUE;
	}
	
	geErrorLog_Add(GE_ERR_DS_ERROR, NULL);
	return FALSE;
}
Ejemplo n.º 6
0
// src=NULL to memset(0)
void* AudioBufferContainer::SetChannel(int fmt, void* src, int chIdx, int nFrames)
{
  Reformat(fmt, true);
  if (nFrames > m_nFrames || chIdx >= m_nCh) 
  {
    int maxframes = (nFrames > m_nFrames ? nFrames : m_nFrames);
    Resize(chIdx+1, maxframes, true);        
  }
  
  int sz = nFrames*(int)fmt;
  void* dest = GetChannel(fmt, chIdx, true);
  if (src)
  {
    memcpy(dest, src, sz);
  }
  else
  {
    memset(dest, 0, sz);
  }
   
  m_interleaved = false;
  m_hasData = true;
  return dest;
}
void FmRadioController_qcom :: handle_tuned_event
(
     void
)
{
     long freq = -1;

     ALOGI("FM handle Tune event\n");
     //memset(&rds_data, 0, sizeof(Final_RDS_data));
     //memset(&CurrentRTPlusData, 0, sizeof(RTPlus_data));
     freq = GetChannel();
     switch(cur_fm_state) {
         case FM_ON:
            if(af_enabled && (freq != prev_freq)
                && (prev_freq > 0)) {
               ALOGI("AF jump happened\n");
               //FDataReceived(freq);
            }
            break;
         case FM_TUNE_IN_PROGRESS:
            pthread_mutex_lock(&mutex_tune_compl_cond);
            set_fm_state(FM_ON);
            pthread_cond_broadcast(&tune_compl_cond);
            pthread_mutex_unlock(&mutex_tune_compl_cond);
            break;
         case SEEK_IN_PROGRESS:
            pthread_mutex_lock(&mutex_seek_compl_cond);
            set_fm_state(FM_ON);
            pthread_cond_broadcast(&seek_compl_cond);
            pthread_mutex_unlock(&mutex_seek_compl_cond);
            break;
         case SCAN_IN_PROGRESS:
            break;
     }
     prev_freq = freq;
}
Ejemplo n.º 8
0
void* AudioBufferContainer::MixChannel(int fmt, void* src, int chIdx, int nFrames, bool addToDest, double wt_start, double wt_end)
{
  Reformat(fmt, true);
  if (nFrames > m_nFrames || chIdx >= m_nCh) 
  {
    int maxframes = (nFrames > m_nFrames ? nFrames : m_nFrames);
    Resize(chIdx+1, maxframes, true);        
  }
  
  void* dest = GetChannel(fmt, chIdx, true);
  
  if (fmt == FMT_32FP)
  {
    BufMixT((float*)dest, (float*)src, nFrames, addToDest, wt_start, wt_end);
  }
  else if (fmt == FMT_64FP)
  {
    BufMixT((double*)dest, (double*)src, nFrames, addToDest, wt_start, wt_end);
  }
  
  m_interleaved = false;
  m_hasData = true;
  return dest;
}
Ejemplo n.º 9
0
	ItemsListModel::ItemsListModel (IIconThemeManager *itm, QObject *parent)
	: QAbstractItemModel (parent)
	, StarredIcon_ (itm->GetIcon ("mail-mark-important"))
	, UnreadIcon_ (itm->GetIcon ("mail-mark-unread"))
	, ReadIcon_ (itm->GetIcon ("mail-mark-read"))
	{
		ItemHeaders_ << tr ("Name") << tr ("Date");

		connect (&StorageBackendManager::Instance (),
				&StorageBackendManager::channelRemoved,
				[this] (IDType_t id)
				{
					if (id == CurrentChannel_)
						Reset (IDNotFound);
				});
		connect (&StorageBackendManager::Instance (),
				&StorageBackendManager::feedRemoved,
				[this] (IDType_t feedId)
				{
					if (CurrentChannel_ == IDNotFound)
						return;

					auto sb = StorageBackendManager::Instance ().MakeStorageBackendForThread ();
					if (feedId == sb->GetChannel (CurrentChannel_).FeedID_)
						Reset (IDNotFound);
				});

		connect (&StorageBackendManager::Instance (),
				&StorageBackendManager::itemsRemoved,
				this,
				&ItemsListModel::handleItemsRemoved);
		connect (&StorageBackendManager::Instance (),
				&StorageBackendManager::itemDataUpdated,
				this,
				&ItemsListModel::handleItemDataUpdated);
	}
Ejemplo n.º 10
0
void Relay::GetDescription(std::ostringstream& desc) const {
  desc << "Relay " << GetChannel();
}
Ejemplo n.º 11
0
void CSoundMgr::Play (int iChannel, int iVolume, int iPan)

//	Play
//
//	Plays a channel.
//
//	iVolume = 0 for maximum volume.
//	iVolume = -10,000 for minimum volume.

	{
	if (m_pDS == NULL || m_iSoundVolume == 0)
		return;

	SChannel *pChannel = GetChannel(iChannel);
	if (pChannel->pBuffer == NULL)
		return;

	//	If the buffer is lost, then we need to restore it

	DWORD dwStatus;
	pChannel->pBuffer->GetStatus(&dwStatus);
	if (dwStatus & DSBSTATUS_BUFFERLOST)
		{
		if (FAILED(pChannel->pBuffer->Restore()))
			return;

		if (pChannel->sFilename.IsBlank())
			return;

		//	Open the file

		MMCKINFO parent, child;
		::ZeroMemory(&parent, sizeof(parent));
		::ZeroMemory(&child, sizeof(child));

		HMMIO hFile = mmioOpen(pChannel->sFilename.GetASCIIZPointer(), NULL, MMIO_READ | MMIO_ALLOCBUF);
		if (hFile == NULL)
			return;

		//	Descend into the RIFF

		parent.fccType = mmioFOURCC('W', 'A', 'V', 'E');
		if (mmioDescend(hFile, &parent, NULL, MMIO_FINDRIFF))
			{
			mmioClose(hFile, 0);
			return;
			}

		child.ckid = mmioFOURCC('d', 'a', 't', 'a');
		if (mmioDescend(hFile, &child, &parent, MMIO_FINDCHUNK))
			{
			mmioClose(hFile, 0);
			return;
			}

		DWORD dwDataSize = child.cksize;

		//	Now read into the buffer

		LPVOID pDest;
		DWORD dwDestSize;
		if (FAILED(pChannel->pBuffer->Lock(0, 0, &pDest, &dwDestSize, NULL, NULL, DSBLOCK_ENTIREBUFFER)))
			{
			mmioClose(hFile, 0);
			return;
			}

		if (mmioRead(hFile, (char *)pDest, dwDestSize) != (LONG)dwDataSize)
			{
			mmioClose(hFile, 0);
			return;
			}

		//	Done with the wave file

		mmioClose(hFile, 0);
		}

	//	Check to see if the channel is busy. If it is, then we may need to create
	//	a second buffer.

	else if (dwStatus & DSBSTATUS_PLAYING)
		{
		SChannel *pLastChannel = pChannel;
		pChannel = pChannel->pNext;
		while (pChannel)
			{
			pChannel->pBuffer->GetStatus(&dwStatus);
			if (!(dwStatus & DSBSTATUS_BUFFERLOST)
					&& !(dwStatus & DSBSTATUS_PLAYING))
				break;

			pLastChannel = pChannel;
			pChannel = pChannel->pNext;
			}

		//	If we couldn't find another channel, then duplicate the original

		if (pChannel == NULL)
			{
			pChannel = GetChannel(iChannel);
			LPDIRECTSOUNDBUFFER pNewBuffer = NULL;

			if (FAILED(m_pDS->DuplicateSoundBuffer(pChannel->pBuffer, &pNewBuffer)))
				return;

			SChannel *pNewChannel = new SChannel;
			pLastChannel->pNext = pNewChannel;
			pNewChannel->pBuffer = pNewBuffer;
			pNewChannel->pNext = NULL;

			pChannel = pNewChannel;
			}
		}

	//	Adjust volume

	int iVolumeAdj = MAX_VOLUME_LEVEL - m_iSoundVolume;
	int iMaxVolume = -(iVolumeAdj * VOLUME_STEP);
	int iVolumeRange = iMaxVolume - MIN_VOLUME;
	iVolume = iMaxVolume - ((iVolumeRange * iVolume) / MIN_VOLUME);

	//	pChannel now points to a valid buffer. Play it!

	pChannel->pBuffer->SetVolume(iVolume);
	pChannel->pBuffer->SetPan(iPan);
	pChannel->pBuffer->Play(0, 0, 0);

	//	Clean-up any channels after us that are done playing

	SChannel *pLastChannel = pChannel;
	pChannel = pChannel->pNext;
	while (pChannel)
		{
		pChannel->pBuffer->GetStatus(&dwStatus);
		if (!(dwStatus & DSBSTATUS_PLAYING))
			{
			pChannel->pBuffer->Release();
			pLastChannel->pNext = pChannel->pNext;
			delete pChannel;
			pChannel = pLastChannel->pNext;
			}
		else
			{
			pLastChannel = pChannel;
			pChannel = pChannel->pNext;
			}
		}
	}
Ejemplo n.º 12
0
ALERROR CSoundMgr::LoadWaveFile (HMMIO hFile, int *retiChannel)

//	LoadWaveFile
//
//	Creates a sound buffer from an open MMIO file

	{
	ASSERT(m_pDS);

	MMCKINFO parent, child;
	::ZeroMemory(&parent, sizeof(parent));
	::ZeroMemory(&child, sizeof(child));

	//	Descend into the RIFF

	parent.fccType = mmioFOURCC('W', 'A', 'V', 'E');
	if (mmioDescend(hFile, &parent, NULL, MMIO_FINDRIFF))
		{
		mmioClose(hFile, 0);
		return ERR_FAIL;
		}

	//	Descend to the wave format

	child.ckid = mmioFOURCC('f', 'm', 't', ' ');
	if (mmioDescend(hFile, &child, &parent, 0))
		{
		mmioClose(hFile, 0);
		return ERR_FAIL;
		}

	//	Allocate a block large enough to hold the format size

	DWORD dwFmtSize = child.cksize;
	DWORD dwAllocSize = max(dwFmtSize, sizeof(WAVEFORMATEX));
	WAVEFORMATEX *pFormat = (WAVEFORMATEX *)new char [dwAllocSize];
	::ZeroMemory(pFormat, dwAllocSize);

	if (mmioRead(hFile, (char *)pFormat, dwFmtSize) != (LONG)dwFmtSize)
		{
		delete [] (char *)pFormat;
		mmioClose(hFile, 0);
		return ERR_FAIL;
		}

	//	Now descend to the data

	if (mmioAscend(hFile, &child, 0))
		{
		delete [] (char *)pFormat;
		mmioClose(hFile, 0);
		return ERR_FAIL;
		}

	child.ckid = mmioFOURCC('d', 'a', 't', 'a');
	if (mmioDescend(hFile, &child, &parent, MMIO_FINDCHUNK))
		{
		delete [] (char *)pFormat;
		mmioClose(hFile, 0);
		return ERR_FAIL;
		}

	DWORD dwDataSize = child.cksize;

	//	Create the DirectSound buffer

	DSBUFFERDESC dsbdesc;
	LPDIRECTSOUNDBUFFER pBuffer;

	::ZeroMemory(&dsbdesc, sizeof(dsbdesc));
	dsbdesc.dwSize = sizeof(dsbdesc);
	dsbdesc.dwFlags = DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLPAN;
	dsbdesc.dwBufferBytes = dwDataSize;
	dsbdesc.lpwfxFormat = pFormat;

	if (FAILED(m_pDS->CreateSoundBuffer(&dsbdesc, &pBuffer, NULL)))
		{
		//	If we can't create the sound buffer, try creating the same buffer
		//	but with no volume or pan controls.

		dsbdesc.dwFlags = 0;
		if (FAILED(m_pDS->CreateSoundBuffer(&dsbdesc, &pBuffer, NULL)))
			{
			delete [] (char *)pFormat;
			return ERR_FAIL;
			}
		}

	delete [] (char *)pFormat;

	//	Now read into the buffer

	LPVOID pDest;
	DWORD dwDestSize;
	if (FAILED(pBuffer->Lock(0, 0, &pDest, &dwDestSize, NULL, NULL, DSBLOCK_ENTIREBUFFER)))
		{
		pBuffer->Release();
		mmioClose(hFile, 0);
		return ERR_FAIL;
		}

	if (mmioRead(hFile, (char *)pDest, dwDestSize) != (LONG)dwDataSize)
		{
		pBuffer->Release();
		mmioClose(hFile, 0);
		return ERR_FAIL;
		}

	//	Done with the wave file

	mmioClose(hFile, 0);

	//	Add to the channel

	int iChannel = AllocChannel();
	SChannel *pChannel = GetChannel(iChannel);
	pChannel->pBuffer = pBuffer;
	pChannel->pNext = NULL;

	//	Done

	if (retiChannel)
		*retiChannel = iChannel;

	return NOERROR;
	}
//------------------------------------------------------------------------
void CServerSynchedStorage::OnClientEnteredGame(int channelId)
{
	SChannel *pChannel=GetChannel(channelId);
 	if (pChannel && pChannel->pNetChannel && !pChannel->pNetChannel->IsLocal())
		FullSynch(channelId, true);
}
Ejemplo n.º 14
0
			///
			/// LDR I/O, only available to LDR images
			void SaveBmp(const std::string& file_name)
			{
				BOOST_STATIC_ASSERT( (boost::is_same<T, UCHAR>::value) );
				BOOST_STATIC_ASSERT( channel == 3 );

				size_t pos = file_name.find_last_of(".");
				std::string file_type = file_name.substr(++pos, std::string::npos);
				boost::to_lower(file_type);
				assert(file_type == "bmp");

				// create output file
				ofstream bmpfile(file_name.c_str(), ios::out | ios::binary);
				if(!bmpfile) 
				{
					assert(0);
					return;
				}

				// save bitmap file header
				BITMAPFILEHEADER fileHeader;
				memset(&fileHeader, 0, sizeof(BITMAPFILEHEADER));
				fileHeader.bfType = 0x4d42;
				fileHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

				if(!bmpfile.write((char*)&fileHeader, sizeof(fileHeader)))
				{
					assert(0);
					bmpfile.close();
					return;
				}

				// save bitmap info header
				BITMAPINFOHEADER infoHeader;
				memset(&infoHeader, 0, sizeof(BITMAPINFOHEADER));
				infoHeader.biSize = sizeof(infoHeader);
				infoHeader.biWidth = GetWidth();
				infoHeader.biHeight = GetHeight();
				infoHeader.biPlanes = 1;
				infoHeader.biBitCount = sizeof(UCHAR)*GetChannel()*8;
				infoHeader.biCompression = BI_RGB;

				if(!bmpfile.write((char*)&infoHeader, sizeof(infoHeader)))
				{
					assert(0);
					bmpfile.close();
					return;
				}

				UCHAR * swap_channel_data = new UCHAR[GetWidth() * GetHeight() * GetChannel()];
				memcpy(swap_channel_data, GetData(), GetWidth() * GetHeight() * GetChannel());
				for (UINT i = 0; i < GetWidth() * GetHeight() * GetChannel(); i += GetChannel())
					swap(swap_channel_data[i], swap_channel_data[i + 2]);

				// save bitmap data
				if(!bmpfile.write((char*)swap_channel_data, GetWidth() * GetHeight() * GetChannel()))
				{
					assert(0);
					bmpfile.close();
					return;
				}

				delete[] swap_channel_data;
				bmpfile.close();
			}
//search all valid stations
//ToDo: return value confirm from JNI layer
//and return freq only when we get tune after scan
//complete event
long FmRadioController_qcom :: SearchAll
(
    void
)
{
    int ret;
    long freq = -1;
    struct timespec ts;

    if(cur_fm_state == FM_ON) {
        ALOGI("FM scan started\n");
        set_fm_state(SCAN_IN_PROGRESS);
        ret = QcomFmIoctlsInterface::set_control(fd_driver,
                      V4L2_CID_PRV_SRCHMODE, SCAN_MODE);
        if(ret != FM_SUCCESS) {
            set_fm_state(FM_ON);
            return freq;
        }

        ret = QcomFmIoctlsInterface::set_control(fd_driver,
                      V4L2_CID_PRV_SCANDWELL, SEARCH_DWELL_TIME);
        if(ret != FM_SUCCESS) {
            set_fm_state(FM_ON);
            return freq;
        }

        ret = QcomFmIoctlsInterface::set_control(fd_driver,
                      V4L2_CID_PRV_SRCH_PTY, 0);
        if(ret != FM_SUCCESS) {
            set_fm_state(FM_ON);
            return freq;
        }

        ret = QcomFmIoctlsInterface::set_control(fd_driver,
                      V4L2_CID_PRV_SRCH_PI, 0);
        if(ret != FM_SUCCESS) {
            set_fm_state(FM_ON);
            return freq;
        }

        ret = QcomFmIoctlsInterface::start_search(fd_driver,
                                            SEARCH_UP);
        if(ret != FM_SUCCESS) {
            set_fm_state(FM_ON);
            return freq;
        }
        pthread_mutex_lock(&mutex_scan_compl_cond);
        ts = set_time_out(SCAN_COMPL_TIMEOUT);
        ALOGI("Wait for Scan Timeout or scan complete");
        ret = pthread_cond_timedwait(&scan_compl_cond, &mutex_scan_compl_cond, &ts);
        ALOGI("Scan complete or timedout");
        pthread_mutex_unlock(&mutex_scan_compl_cond);
        if((cur_fm_state != SCAN_IN_PROGRESS)) {

        }else {
        }
        freq = GetChannel();
    }else {
        ALOGE("FM is not in proper state for Scan operation");
    }
    return freq;
}
Ejemplo n.º 16
0
void SafePWM::GetDescription(char *desc)
{
	sprintf(desc, "PWM %ld on module %ld", GetChannel(), GetModuleNumber());
}
Ejemplo n.º 17
0
unsigned long Measurement::GetNextDataBulk()
{
	FILE_LOG(logDEBUG3) << "Measurement::GetNextDataBulk";

	unsigned long i, j, index;
	short *overflow;
	uint32_t traces_asked_for, length_of_trace_fetched;
	// unsigned long length_of_trace_askedfor, length_of_trace_fetched;
	Timing t;

	// std::cerr << "(GetNextDataBulk: " << GetNextIndex() << ", " << GetMaxTracesToFetch() << ")\n";

	// it makes no sense to read any further: we are already at the end
	if(GetNextIndex() >= GetNTraces()) {
		std::cerr << "Stop fetching data from ociloscope." << std::endl;
		return 0UL;
	}

/*
	try {
		for(i=0; i<GetNumberOfChannels(); i++) {
			if(GetChannel(i)->IsEnabled()) {
				delete [] data[i];
				data[i] = new short[GetMaxTracesToFetch()*GetLength()];
			}
		}
	} catch(...) {
		std::cerr << "Unable to allocate memory in Measurement::AllocateMemoryBlock." << std::endl;
		throw;
	}
/**/

	traces_asked_for = GetMaxTracesToFetch();
	if(GetNextIndex() + traces_asked_for > GetNTraces()) {
		traces_asked_for = GetNTraces() - GetNextIndex();
	}
	// allocate buffers
	for(i=0; i<GetNumberOfChannels(); i++) {
		if(GetChannel(i)->IsEnabled()) {
			FILE_LOG(logDEBUG4) << "Measurement::GetNextDataBulk - memset data[i]" << GetLength()*traces_asked_for*sizeof(short);
			memset(data[i], 0, GetLength()*traces_asked_for*sizeof(short));
			FILE_LOG(logDEBUG4) << "done";
		}
		for(j=0; j<traces_asked_for; j++) {
			index = j+GetNextIndex();
			if(GetChannel(i)->IsEnabled()) {
				if(data_allocated[i] == false) {
					throw "Unable to get data. Memory is not allocated.";
				}
				if(GetSeries() == PICO_4000) {
					// GetPicoscope()->SetStatus(ps4000SetDataBufferBulk(
					// 	GetHandle(),                  // handle
					// 	(PS4000_CHANNEL)i,            // channel
					// 	data[i],                      // *buffer
					// 	GetMaxTraceLengthToFetch())); // bufferLength
					GetPicoscope()->SetStatus(ps4000SetDataBufferBulk(
						GetHandle(),                // handle
						(PS4000_CHANNEL)i,          // channel
						&data[i][j*GetLength()],    // *buffer
						GetLength(),                // bufferLength
						index));                    // waveform
				} else {
					// unsigned long dj = (j+GetNextIndex()/GetMaxTracesToFetch())%traces_asked_for;
					// std::cerr << "-- (set data buffer bulk: [" << i << "][" << dj
					// 	<< "], len:" << GetLength() << ", index:" << index
					// 	<< ", from:" << GetNextIndex()
					// 	<< ", to:" << GetNextIndex()+traces_asked_for-1 << "\n";
					GetPicoscope()->SetStatus(ps6000SetDataBufferBulk(
						GetHandle(),                // handle
						(PS6000_CHANNEL)i,          // channel
						&data[i][j*GetLength()],    // *buffer
						GetLength(),                // bufferLength
						index,                      // waveform
						PS6000_RATIO_MODE_NONE));   // downSampleRatioMode
				}
				if(GetPicoscope()->GetStatus() != PICO_OK) {
					std::cerr << "Unable to set memory for channel." << std::endl;
					throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
				}
			}
		}
	}
	// fetch data
	// length_of_trace_fetched = length_of_trace_askedfor;
	std::cerr << "Get data for traces " << GetNextIndex() << "-" << GetNextIndex()+traces_asked_for << " (" << 100.0*(GetNextIndex()+traces_asked_for)/GetNTraces() << "%) ... ";
	overflow = new short[traces_asked_for];
	memset(overflow, 0, traces_asked_for*sizeof(short));
	// std::cerr << "-- x1\n";
	t.Start();
	// std::cerr << "length of buffer: " << data_length[0] << ", length of requested trace: " << length_of_trace_askedfor << " ... ";
	if(GetSeries() == PICO_4000) {
		length_of_trace_fetched = GetLength();
		GetPicoscope()->SetStatus(ps4000GetValuesBulk(
			GetHandle(),                // handle
			&length_of_trace_fetched,   // *noOfSamples
			// TODO: start index
			GetNextIndex(),             // fromSegmentIndex
			GetNextIndex()+traces_asked_for-1, // toSegmentIndex
			// this could also be min(GetMaxTraceLengthToFetch(),wholeLength-startindex)
			overflow));                // *overflow
	} else {
		// TODO: not sure about this ...
		length_of_trace_fetched = GetLength();
		GetPicoscope()->SetStatus(ps6000GetValuesBulk(
			GetHandle(),                // handle
			&length_of_trace_fetched,   // *noOfSamples
			// TODO: start index
			GetNextIndex(),             // fromSegmentIndex
			GetNextIndex()+traces_asked_for-1, // toSegmentIndex
			// this could also be min(GetMaxTraceLengthToFetch(),wholeLength-startindex)
			1,                          // downSampleRatio
			PS6000_RATIO_MODE_NONE,     // downSampleRatioMode
			overflow));                // *overflow
	}
	t.Stop();
	// std::cerr << "-- x2\n";
	if(GetPicoscope()->GetStatus() != PICO_OK) {
		std::cerr << "Unable to set memory for channel." << std::endl;
		throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
	}
	for(i=0; i<traces_asked_for; i++) {
		for(j=0; i<GetNumberOfChannels(); i++) {
			if(overflow[i] & (1<<j)) {
				FILE_LOG(logWARNING) << "Warning: Overflow on channel " << (char)('A'+j) << " of trace " << i+GetNextIndex() << ".\n";
			}
		}
	}
	delete [] overflow;
	// if(length_of_trace_fetched != length_of_trace_askedfor) {
	// 	std::cerr << "Warning: The number of read samples was smaller than requested.\n";
	// }

	// getting timestamps
	int64_t *timestamps;
	PS6000_TIME_UNITS *timeunits;

	timestamps = new int64_t[traces_asked_for];
	timeunits  = new PS6000_TIME_UNITS[traces_asked_for];

	if(GetSeries() == PICO_4000) {
		// NOT YET IMPLEMENTED
	} else {
		FILE_LOG(logDEBUG2) << "ps6000GetValuesTriggerTimeOffsetBulk64(handle=" << GetHandle() << ", *timestamps, *timeunits, fromSegmentIndex=" << GetNextIndex() << ", toSegmentIndex=" << GetNextIndex()+traces_asked_for-1 << ")";
		GetPicoscope()->SetStatus(ps6000GetValuesTriggerTimeOffsetBulk64(
			GetHandle(),                // handle
			timestamps,                 // *times
			timeunits,                  // *timeUnits
			GetNextIndex(),                      // fromSegmentIndex
			GetNextIndex()+traces_asked_for-1)); // toSegmentIndex
	}
	if(GetPicoscope()->GetStatus() != PICO_OK) {
		std::cerr << "Unable to get timestamps." << std::endl;
		throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
	}

	// for(i=0; i<traces_asked_for; i++) {
	// 	std::cerr << "time " << i << ": " << timestamps[i] << "\n";
	// }
	SetRate(traces_asked_for, timestamps[0], timeunits[0], timestamps[traces_asked_for-1], timeunits[traces_asked_for-1]);
	// if(timeunits[0] != timeunits[traces_asked_for-1]) {
	// 	FILE_LOG(logWARNING) << "time unit of the first and last sample differ; rate is not reliable; TIMING seems to be broken anyway";
	// }

	delete [] timestamps;
	delete [] timeunits;


	std::cerr << "OK ("<< t.GetSecondsDouble() <<"s)\n";

	// std::cerr << "length of trace fetched: " << length_of_trace_fetched << "\n";
	// std::cerr << "total length: " << traces_asked_for*length_of_trace_fetched << "\n";

	SetLengthFetched(traces_asked_for*length_of_trace_fetched);
	// std::cerr << "-- next index is now " << GetNextIndex() << ", will be set to " << GetNextIndex() + traces_asked_for << "\n";
	SetNextIndex(GetNextIndex()+traces_asked_for);
	// std::cerr << "-- next index is now " << GetNextIndex() << "\n";
	// std::cerr << "-- return value " << traces_asked_for << "\n";

	return traces_asked_for;
}
Ejemplo n.º 18
0
// TODO: we might want to use multiple buffers at the same time
// returns the length of data
// TODO: the first part only needs to be called once; so we should move the code at the end of RunBlock
//       unless we want to alternate between allocated memory (to enable parallel readouts)
unsigned long Measurement::GetNextData()
{
	FILE_LOG(logDEBUG3) << "Measurement::GetNextData";

	int i;
	short overflow=0;
	uint32_t length_of_trace_askedfor, length_of_trace_fetched;
	Timing t;

	// it makes no sense to read any further: we are already at the end
	if(GetNextIndex() >= GetLength()) {
		std::cerr << "Stop fetching data from osciloscope." << std::endl;
		return 0UL;
	}

	length_of_trace_askedfor = GetMaxTraceLengthToFetch();
	if(GetNextIndex() + length_of_trace_askedfor > GetLength()) {
		length_of_trace_askedfor = GetLength() - GetNextIndex();
	}
	// allocate buffers
	for(i=0; i<GetNumberOfChannels(); i++) {
		if(GetChannel(i)->IsEnabled()) {
			if(data_allocated[i] == false) {
				throw "Unable to get data. Memory is not allocated.";
			}
			if(GetSeries() == PICO_4000) {
				FILE_LOG(logDEBUG2) << "ps4000SetDataBuffer(handle=" << GetHandle() << ", channel=" << i << ", *buffer=<data[i]>, bufferLength=" << GetMaxTraceLengthToFetch() << ")";
				GetPicoscope()->SetStatus(ps4000SetDataBuffer(
					GetHandle(),                  // handle
					(PS4000_CHANNEL)i,            // channel
					data[i],                      // *buffer
					GetMaxTraceLengthToFetch())); // bufferLength
			} else {
				FILE_LOG(logDEBUG2) << "ps6000SetDataBuffer(handle=" << GetHandle() << ", channel=" << i << ", *buffer=<data[i]>, bufferLength=" << GetMaxTraceLengthToFetch() << ", downSampleRatioMode=PS6000_RATIO_MODE_NONE)";
				GetPicoscope()->SetStatus(ps6000SetDataBuffer(
					GetHandle(),                // handle
					(PS6000_CHANNEL)i,          // channel
					data[i],                    // *buffer
					GetMaxTraceLengthToFetch(), // bufferLength
					PS6000_RATIO_MODE_NONE));   // downSampleRatioMode
			}
			if(GetPicoscope()->GetStatus() != PICO_OK) {
				std::cerr << "Unable to set memory for channel." << std::endl;
				throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
			}
		}
	}
	// fetch data
	length_of_trace_fetched = length_of_trace_askedfor;
	std::cerr << "Get data for points " << GetNextIndex() << "-" << GetNextIndex()+length_of_trace_askedfor << " (" << 100.0*(GetNextIndex()+length_of_trace_askedfor)/GetLength() << "%) ... ";
	t.Start();
	// std::cerr << "length of buffer: " << data_length[0] << ", length of requested trace: " << length_of_trace_askedfor << " ... ";
	if(GetSeries() == PICO_4000) {
		FILE_LOG(logDEBUG2) << "ps4000GetValues(handle=" << GetHandle() << ", startIndex=" << GetNextIndex() << ", *noOfSamples=" << length_of_trace_fetched << ", downSampleRatio=1, downSampleRatioMode=PS4000_RATIO_MODE_NONE, segmentIndex=0, *overflow)";
		GetPicoscope()->SetStatus(ps4000GetValues(
			GetHandle(),                // handle
			// TODO: start index
			GetNextIndex(),             // startIndex
			// this could also be min(GetMaxTraceLengthToFetch(),wholeLength-startindex)
			&length_of_trace_fetched,   // *noOfSamples
			1,                          // downSampleRatio
			PS4000_RATIO_MODE_NONE,     // downSampleRatioMode
			0,                          // segmentIndex
			&overflow));                // *overflow
		FILE_LOG(logDEBUG2) << "-> length_of_trace_fetched=" << length_of_trace_fetched << "\n";
	} else {
		FILE_LOG(logDEBUG2) << "ps6000GetValues(handle=" << GetHandle() << ", startIndex=" << GetNextIndex() << ", *noOfSamples=" << length_of_trace_fetched << ", downSampleRatio=1, downSampleRatioMode=PS6000_RATIO_MODE_NONE, segmentIndex=0, *overflow)";
		GetPicoscope()->SetStatus(ps6000GetValues(
			GetHandle(),                // handle
			// TODO: start index
			GetNextIndex(),             // startIndex
			// this could also be min(GetMaxTraceLengthToFetch(),wholeLength-startindex)
			&length_of_trace_fetched,   // *noOfSamples
			1,                          // downSampleRatio
			PS6000_RATIO_MODE_NONE,     // downSampleRatioMode
			0,                          // segmentIndex
			&overflow));                // *overflow
		FILE_LOG(logDEBUG2) << "-> length_of_trace_fetched=" << length_of_trace_fetched << "\n";
	}
	t.Stop();
	if(GetPicoscope()->GetStatus() != PICO_OK) {
		std::cerr << "Unable to set memory for channel." << std::endl;
		throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
	}
	if(overflow) {
		for(i=0; i<GetNumberOfChannels(); i++) {
			if(overflow & (1<<i)) {
				std::cerr << "Warning: Overflow on channel " << (char)('A'+i) << ".\n";
			}
		}
	}
	if(length_of_trace_fetched != length_of_trace_askedfor) {
		std::cerr << "Warning: The number of read samples was smaller than requested.\n";
	}
	std::cerr << "OK ("<< t.GetSecondsDouble() <<"s)\n";
	SetLengthFetched(length_of_trace_fetched);
	SetNextIndex(GetNextIndex()+length_of_trace_fetched);

	return length_of_trace_fetched;
}
Ejemplo n.º 19
0
void Measurement::RunBlock()
{
	FILE_LOG(logDEBUG3) << "Measurement::RunBlock";

	int i;
	Timing t;
	uint32_t max_length=0;

	// we will have to start reading our data from beginning again
	SetNextIndex(0);
	// test if channel settings have already been passed to picoscope
	// and only pass them again if that isn't the case
	FILE_LOG(logDEBUG4) << "Measurement::RunBlock - we have " << GetNumberOfChannels() << " channels";
	for(i=0; i<GetNumberOfChannels(); i++) {
		FILE_LOG(logDEBUG4) << "Measurement::RunBlock - setting channel " << (char)('A'+i) << " (which holds index " << GetChannel(i)->GetIndex() << ")";
		GetChannel(i)->SetChannelInPicoscope();
	}
	// this fixes the timebase if more than a single channel is selected
	FixTimebase();
	// timebase
	SetTimebaseInPicoscope();
	// trigger
	if(IsTriggered()) {
		GetTrigger()->SetTriggerInPicoscope();
	}

	// for rapid block mode
	if(GetNTraces() > 1) {
		// TODO - check that GetLength()*GetNumberOfEnabledChannels()*GetNTraces() doesn't exceed the limit
		if(GetSeries() == PICO_4000) {
			FILE_LOG(logDEBUG2) << "ps4000SetNoOfCaptures(handle=" << GetHandle() << ", nCaptures=" << GetNTraces() << ")";
			GetPicoscope()->SetStatus(ps4000SetNoOfCaptures(
				GetHandle(),    // handle
				GetNTraces())); // nCaptures
		} else {
			FILE_LOG(logDEBUG2) << "ps6000SetNoOfCaptures(handle=" << GetHandle() << ", nCaptures=" << GetNTraces() << ")";
			GetPicoscope()->SetStatus(ps6000SetNoOfCaptures(
				GetHandle(),    // handle
				GetNTraces())); // nCaptures
		}
		if(GetPicoscope()->GetStatus() != PICO_OK) {
			std::cerr << "Unable to set number of captures to " << GetNTraces() << std::endl;
			throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
		}
		if(GetSeries() == PICO_4000) {
			FILE_LOG(logDEBUG2) << "ps4000MemorySegments(handle=" << GetHandle() << ", nSegments=" << GetNTraces() << ", &max_length=" << max_length << ")";
			GetPicoscope()->SetStatus(ps4000MemorySegments(
				GetHandle(),   // handle
				GetNTraces(),  // nSegments
				&max_length));
			FILE_LOG(logDEBUG2) << "->ps4000MemorySegments(... max_length=" << max_length << ")";
		} else {
			FILE_LOG(logDEBUG2) << "ps6000MemorySegments(handle=" << GetHandle() << ", nSegments=" << GetNTraces() << ", &max_length=" << max_length << ")";
			GetPicoscope()->SetStatus(ps6000MemorySegments(
				GetHandle(),   // handle
				GetNTraces(),  // nSegments
				&max_length));
			FILE_LOG(logDEBUG2) << "->ps6000MemorySegments(... max_length=" << max_length << ")";
		}
		if(GetPicoscope()->GetStatus() != PICO_OK) {
			std::cerr << "Unable to set number of segments to " << GetNTraces() << std::endl;
			throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
		}
		if(max_length < GetLength()) { // TODO: times number of enabled channels
			std::cerr << "The maximum length of trace you can get with " << GetNTraces()
			          << " traces is " << max_length << ", but you requested " << GetLength() << "\n";
			throw;
		}
		if(GetSeries() == PICO_4000) {
			FILE_LOG(logDEBUG2) << "ps4000SetNoOfCaptures(handle=" << GetHandle() << ", nCaptures=" << GetNTraces() << ")";
			GetPicoscope()->SetStatus(ps4000SetNoOfCaptures(
				GetHandle(),    // handle
				GetNTraces())); // nCaptures
		} else {
			FILE_LOG(logDEBUG2) << "ps6000SetNoOfCaptures(handle=" << GetHandle() << ", nCaptures=" << GetNTraces() << ")";
			GetPicoscope()->SetStatus(ps6000SetNoOfCaptures(
				GetHandle(),    // handle
				GetNTraces())); // nCaptures
		}
		if(GetPicoscope()->GetStatus() != PICO_OK) {
			std::cerr << "Unable to set number of captures to " << GetNTraces() << std::endl;
			throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
		}
	}

	//std::cerr << "\nPress a key to start fetching the data ...\n";
	//_getch();

	t.Start();
	GetPicoscope()->SetReady(false);
	if(GetSeries() == PICO_4000) {
		FILE_LOG(logDEBUG2) << "ps4000RunBlock(handle=" << GetHandle() << ", noOfPreTriggerSamples=" << GetLengthBeforeTrigger() << ", noOfPostTriggerSamples=" << GetLengthAfterTrigger() << ", timebase=" << timebase << ", oversample=1, *timeIndisposedMs=NULL, segmentIndex=0, lpReady=CallBackBlock, *pParameter=NULL)";
		GetPicoscope()->SetStatus(ps4000RunBlock(
			GetHandle(),              // handle
			GetLengthBeforeTrigger(), // noOfPreTriggerSamples
			GetLengthAfterTrigger(),  // noOfPostTriggerSamples
			timebase,                 // timebase
			1,                        // ovesample
			NULL,                     // *timeIndisposedMs
			0,                        // segmentIndex
			CallBackBlock,            // lpReady
			NULL));                   // *pParameter
	} else {
		FILE_LOG(logDEBUG2) << "ps6000RunBlock(handle=" << GetHandle() << ", noOfPreTriggerSamples=" << GetLengthBeforeTrigger() << ", noOfPostTriggerSamples=" << GetLengthAfterTrigger() << ", timebase=" << timebase << ", oversample=1, *timeIndisposedMs=NULL, segmentIndex=0, lpReady=CallBackBlock, *pParameter=NULL)";
		GetPicoscope()->SetStatus(ps6000RunBlock(
			GetHandle(),              // handle
			GetLengthBeforeTrigger(), // noOfPreTriggerSamples
			GetLengthAfterTrigger(),  // noOfPostTriggerSamples
			timebase,                 // timebase
			1,                        // ovesample
			NULL,                     // *timeIndisposedMs
			0,                        // segmentIndex
			CallBackBlock,            // lpReady
			NULL));                   // *pParameter
	}
	if(GetPicoscope()->GetStatus() != PICO_OK) {
		std::cerr << "Unable to start collecting samples" << std::endl;
		throw Picoscope::PicoscopeException(GetPicoscope()->GetStatus());
	} else {
		std::cerr << "Start collecting samples in "
		          << ((GetNTraces() > 1) ? "rapid " : "") << "block mode ... ";
	}
	// TODO: maybe we want it to be asynchronous
	// TODO: catch the _kbhit event!!!
	// while (!Picoscope::IsReady() && !_kbhit()) {
	while (!Picoscope::IsReady()) {
		Sleep(200);
	}
	t.Stop();
	std::cerr << "OK (" << t.GetSecondsDouble() << "s)\n";

	// sets the index from where we want to start reading data to zero
	SetNextIndex(0UL);
}
Ejemplo n.º 20
0
/**
 * ParseLineArgV
 *
 * Parses and processes a line which was sent by the server.
 *
 * @param argc number of tokens
 * @param argv the tokens
 */
bool CIRCConnection::ParseLineArgV(int argc, const char **argv) {
	CChannel *Channel;
	CClientConnection *Client;

	m_LastResponse = g_CurrentTime;

	if (argc < 2) {
		return true;
	}

	const char *Reply = argv[0];
	const char *Raw = argv[1];
	char *Nick = ::NickFromHostmask(Reply);
	int iRaw = atoi(Raw);

	bool b_Me = false;
	if (m_CurrentNick != NULL && Nick != NULL && strcasecmp(Nick, m_CurrentNick) == 0) {
		b_Me = true;
	}

	free(Nick);

	Client = GetOwner()->GetClientConnectionMultiplexer();

	// HASH values
	CHashCompare hashRaw(argv[1]);
	static CHashCompare hashPrivmsg("PRIVMSG");
	static CHashCompare hashNotice("NOTICE");
	static CHashCompare hashJoin("JOIN");
	static CHashCompare hashPart("PART");
	static CHashCompare hashKick("KICK");
	static CHashCompare hashNick("NICK");
	static CHashCompare hashQuit("QUIT");
	static CHashCompare hashMode("MODE");
	static CHashCompare hashTopic("TOPIC");
	static CHashCompare hashPong("PONG");
	// END of HASH values

	if (argc > 3 && iRaw == 433) {
		bool ReturnValue = ModuleEvent(argc, argv);

		if (ReturnValue) {
			if (GetCurrentNick() == NULL) {
				WriteLine("NICK :%s_", argv[3]);
			}

			if (m_NickCatchTimer == NULL) {
				m_NickCatchTimer = new CTimer(30, false, NickCatchTimer, this);
			}
		}

		return ReturnValue;
	} else if (argc > 3 && hashRaw == hashPrivmsg && Client == NULL) {
		const char *Host;
		const char *Dest = argv[2];
		char *Nick = ::NickFromHostmask(Reply);

		Channel = GetChannel(Dest);

		if (Channel != NULL) {
			CNick *User = Channel->GetNames()->Get(Nick);

			if (User != NULL) {
				User->SetIdleSince(g_CurrentTime);
			}

			Channel->AddBacklogLine(argv[0], argv[3]);
		}

		if (!ModuleEvent(argc, argv)) {
			free(Nick);
			return false;
		}

		/* don't log ctcp requests */
		if (argv[3][0] != '\1' && argv[3][strlen(argv[3]) - 1] != '\1' && Dest != NULL &&
				Nick != NULL && m_CurrentNick != NULL && strcasecmp(Dest, m_CurrentNick) == 0 &&
				strcasecmp(Nick, m_CurrentNick) != 0) {
			char *Dup;
			char *Delim;

			Dup = strdup(Reply);

			if (AllocFailed(Dup)) {
				free(Nick);

				return true;
			}

			Delim = strchr(Dup, '!');

			if (Delim != NULL) {
				*Delim = '\0';

				Host = Delim + 1;
			}

			GetOwner()->Log("%s (%s): %s", Dup, Delim ? Host : "<unknown host>", argv[3]);

			free(Dup);
		}

		free(Nick);

		UpdateHostHelper(Reply);

		return true;
	} else if (argc > 3 && hashRaw == hashPrivmsg && Client != NULL) {
		Channel = GetChannel(argv[2]);

		if (Channel != NULL) {
			Channel->AddBacklogLine(argv[0], argv[3]);
		}
	} else if (argc > 3 && hashRaw == hashNotice && Client == NULL) {
		const char *Dest = argv[2];
		char *Nick;
		
		if (!ModuleEvent(argc, argv)) {
			return false;
		}

		Nick = ::NickFromHostmask(Reply);

		/* don't log ctcp replies */
		if (argv[3][0] != '\1' && argv[3][strlen(argv[3]) - 1] != '\1' && Dest != NULL &&
				Nick != NULL && m_CurrentNick != NULL && strcasecmp(Dest, m_CurrentNick) == 0 &&
				strcasecmp(Nick, m_CurrentNick) != 0) {
			GetOwner()->Log("%s (notice): %s", Reply, argv[3]);
		}

		free(Nick);

		return true;
	} else if (argc > 2 && hashRaw == hashJoin) {
		if (b_Me) {
			AddChannel(argv[2]);

			/* GetOwner() can be NULL if AddChannel failed */
			if (GetOwner() != NULL && Client == NULL) {
				WriteLine("MODE %s", argv[2]);
			}
		}

		Channel = GetChannel(argv[2]);

		if (Channel != NULL) {
			Nick = NickFromHostmask(Reply);

			if (AllocFailed(Nick)) {
				return false;
			}

			Channel->AddUser(Nick, '\0');
			free(Nick);
		}

		UpdateHostHelper(Reply);
	} else if (argc > 2 && hashRaw == hashPart) {
		bool bRet = ModuleEvent(argc, argv);

		if (b_Me) {
			RemoveChannel(argv[2]);
		} else {
			Channel = GetChannel(argv[2]);

			if (Channel != NULL) {
				Nick = ::NickFromHostmask(Reply);

				if (AllocFailed(Nick)) {
					return false;
				}

				Channel->RemoveUser(Nick);

				free(Nick);
			}
		}

		UpdateHostHelper(Reply);

		return bRet;
	} else if (argc > 3 && hashRaw == hashKick) {
		bool bRet = ModuleEvent(argc, argv);

		if (m_CurrentNick != NULL && strcasecmp(argv[3], m_CurrentNick) == 0) {
			RemoveChannel(argv[2]);

			if (Client == NULL) {
				char *Dup = strdup(Reply);

				if (AllocFailed(Dup)) {
					return bRet;
				}

				char *Delim = strchr(Dup, '!');
				const char *Host = NULL;

				if (Delim) {
					*Delim = '\0';

					Host = Delim + 1;
				}

				GetOwner()->Log("%s (%s) kicked you from %s (%s)", Dup, Delim ? Host : "<unknown host>", argv[2], argc > 4 ? argv[4] : "");

				free(Dup);
			}
		} else {
			Channel = GetChannel(argv[2]);

			if (Channel != NULL) {
				Channel->RemoveUser(argv[3]);
			}
		}

		UpdateHostHelper(Reply);

		return bRet;
	} else if (argc > 2 && iRaw == 1) {
		if (Client != NULL) {
			if (strcmp(Client->GetNick(), argv[2]) != 0) {
				Client->WriteLine(":%s!%s NICK :%s", Client->GetNick(), m_Site ? m_Site : "*****@*****.**", argv[2]);
			}
		}

		free(m_CurrentNick);
		m_CurrentNick = strdup(argv[2]);

		free(m_Server);
		m_Server = strdup(Reply);
	} else if (argc > 2 && hashRaw == hashNick) {
		if (b_Me) {
			free(m_CurrentNick);
			m_CurrentNick = strdup(argv[2]);
		}

		Nick = NickFromHostmask(argv[0]);

		int i = 0;

		if (!b_Me && GetOwner()->GetClientConnectionMultiplexer() == NULL) {
			const char *AwayNick = GetOwner()->GetAwayNick();

			if (AwayNick != NULL && strcasecmp(AwayNick, Nick) == 0) {
				WriteLine("NICK %s", AwayNick);
			}
		}

		while (hash_t<CChannel *> *ChannelHash = m_Channels->Iterate(i++)) {
			ChannelHash->Value->RenameUser(Nick, argv[2]);
		}

		free(Nick);
	} else if (argc > 1 && hashRaw == hashQuit) {
		bool bRet = ModuleEvent(argc, argv);

		Nick = NickFromHostmask(argv[0]);

		int i = 0;

		while (hash_t<CChannel *> *ChannelHash = m_Channels->Iterate(i++)) {
			ChannelHash->Value->RemoveUser(Nick);
		}

		free(Nick);

		return bRet;
	} else if (argc > 1 && (iRaw == 422 || iRaw == 376)) {
		int DelayJoin = GetOwner()->GetDelayJoin();
		if (m_State != State_Connected) {
			const CVector<CModule *> *Modules = g_Bouncer->GetModules();

			for (int i = 0; i < Modules->GetLength(); i++) {
				(*Modules)[i]->ServerLogon(GetOwner()->GetUsername());
			}

			const char *ClientNick;

			if (Client != NULL) {
				ClientNick = Client->GetNick();

				if (strcmp(m_CurrentNick, ClientNick) != 0) {
					Client->ChangeNick(m_CurrentNick);
				}
			}

			GetOwner()->Log("You were successfully connected to an IRC server.");
			g_Bouncer->Log("User %s connected to an IRC server.",
				GetOwner()->GetUsername());
		}

		if (DelayJoin == 1) {
			m_DelayJoinTimer = g_Bouncer->CreateTimer(5, false, DelayJoinTimer, this);
		} else if (DelayJoin == 0) {
			JoinChannels();
		}

		if (Client == NULL) {
			bool AppendTS = (GetOwner()->GetConfig()->ReadInteger("user.ts") != 0);
			const char *AwayReason = GetOwner()->GetAwayText();

			if (AwayReason != NULL) {
				WriteLine(AppendTS ? "AWAY :%s (Away since the dawn of time)" : "AWAY :%s", AwayReason);
			}
		}

		const char *AutoModes = GetOwner()->GetAutoModes();
		const char *DropModes = GetOwner()->GetDropModes();

		if (AutoModes != NULL) {
			WriteLine("MODE %s +%s", GetCurrentNick(), AutoModes);
		}

		if (DropModes != NULL && Client == NULL) {
			WriteLine("MODE %s -%s", GetCurrentNick(), DropModes);
		}

		m_State = State_Connected;
	} else if (argc > 1 && strcasecmp(Reply, "ERROR") == 0) {
		if (strstr(Raw, "throttle") != NULL) {
			GetOwner()->ScheduleReconnect(120);
		} else {
			GetOwner()->ScheduleReconnect(5);
		}

		if (GetCurrentNick() != NULL && GetSite() != NULL) {
			g_Bouncer->LogUser(GetUser(), "Error received for user %s [%s!%s]: %s",
				GetOwner()->GetUsername(), GetCurrentNick(), GetSite(), argv[1]);
		} else {
			g_Bouncer->LogUser(GetUser(), "Error received for user %s: %s",
				GetOwner()->GetUsername(), argv[1]);
		}
	} else if (argc > 3 && iRaw == 465) {
		if (GetCurrentNick() != NULL && GetSite() != NULL) {
			g_Bouncer->LogUser(GetUser(), "G/K-line reason for user %s [%s!%s]: %s",
				GetOwner()->GetUsername(), GetCurrentNick(), GetSite(), argv[3]);
		} else {
			g_Bouncer->LogUser(GetUser(), "G/K-line reason for user %s: %s",
				GetOwner()->GetUsername(), argv[3]);
		}
	} else if (argc > 5 && iRaw == 351) {
		free(m_ServerVersion);
		m_ServerVersion = strdup(argv[3]);

		free(m_ServerFeat);
		m_ServerFeat = strdup(argv[5]);
	} else if (argc > 3 && iRaw == 5) {
		for (int i = 3; i < argc - 1; i++) {
			char *Dup = strdup(argv[i]);

			if (AllocFailed(Dup)) {
				return false;
			}

			char *Eq = strchr(Dup, '=');

			if (strcasecmp(Dup, "NAMESX") == 0) {
				WriteLine("PROTOCTL NAMESX");
			}

			char *Value;

			if (Eq) {
				*Eq = '\0';

				Value = strdup(++Eq);
			} else {
				Value = strdup("");
			}

			m_ISupport->Add(Dup, Value);

			free(Dup);
		}
	} else if (argc > 4 && iRaw == 324) {
		Channel = GetChannel(argv[3]);

		if (Channel != NULL) {
			Channel->ClearModes();
			Channel->ParseModeChange(argv[0], argv[4], argc - 5, &argv[5]);
			Channel->SetModesValid(true);
		}
	} else if (argc > 3 && hashRaw == hashMode) {
		Channel = GetChannel(argv[2]);

		if (Channel != NULL) {
			Channel->ParseModeChange(argv[0], argv[3], argc - 4, &argv[4]);
		} else if (strcmp(m_CurrentNick, argv[2]) == 0) {
			bool Flip = true, WasNull;
			const char *Modes = argv[3];
			size_t Length = strlen(Modes) + 1;

			if (m_Usermodes != NULL) {
				Length += strlen(m_Usermodes);
			}

			WasNull = (m_Usermodes != NULL) ? false : true;
			m_Usermodes = (char *)realloc(m_Usermodes, Length);

			if (AllocFailed(m_Usermodes)) {
				return false;
			}

			if (WasNull) {
				m_Usermodes[0] = '\0';
			}

			while (*Modes != '\0') {
				if (*Modes == '+') {
					Flip = true;
				} else if (*Modes == '-') {
					Flip = false;
				} else {
					if (Flip) {
						size_t Position = strlen(m_Usermodes);
						m_Usermodes[Position] = *Modes;
						m_Usermodes[Position + 1] = '\0';
					} else {
						char *CurrentModes = m_Usermodes;
						size_t a = 0;

						while (*CurrentModes != '\0') {
							*CurrentModes = m_Usermodes[a];

							if (*CurrentModes != *Modes) {
								CurrentModes++;
							}

							a++;
						}
					}
				}

				Modes++;
			}
		}

		UpdateHostHelper(Reply);
	} else if (argc > 4 && iRaw == 329) {
		Channel = GetChannel(argv[3]);

		if (Channel != NULL) {
			Channel->SetCreationTime(atoi(argv[4]));
		}
	} else if (argc > 4 && iRaw == 332) {
		Channel = GetChannel(argv[3]);

		if (Channel != NULL) {
			Channel->SetTopic(argv[4]);
		}
	} else if (argc > 5 && iRaw == 333) {
		Channel = GetChannel(argv[3]);

		if (Channel != NULL) {
			Channel->SetTopicNick(argv[4]);
			Channel->SetTopicStamp(atoi(argv[5]));
		}
	} else if (argc > 3 && iRaw == 331) {
		Channel = GetChannel(argv[3]);

		if (Channel != NULL) {
			Channel->SetNoTopic();
		}
	} else if (argc > 3 && hashRaw == hashTopic) {
		Channel = GetChannel(argv[2]);

		if (Channel != NULL) {
			Channel->SetTopic(argv[3]);
			Channel->SetTopicStamp(g_CurrentTime);
			Channel->SetTopicNick(argv[0]);
		}

		UpdateHostHelper(Reply);
	} else if (argc > 5 && iRaw == 353) {
		Channel = GetChannel(argv[4]);

		if (Channel != NULL) {
			const char *nicks;
			const char **nickv;

			nicks = ArgTokenize(argv[5]);

			if (AllocFailed(nicks)) {
				return false;
			}

			nickv = ArgToArray(nicks);

			if (AllocFailed(nickv)) {
				ArgFree(nicks);

				return false;
			}

			int nickc = ArgCount(nicks);

			for (int i = 0; i < nickc; i++) {
				char *Nick = strdup(nickv[i]);
				char *BaseNick = Nick;

				if (AllocFailed(Nick)) {
					ArgFree(nicks);

					return false;
				}

				StrTrim(Nick, ' ');

				while (IsNickPrefix(*Nick)) {
					Nick++;
				}

				char *Modes = NULL;

				if (BaseNick != Nick) {
					Modes = (char *)malloc(Nick - BaseNick + 1);

					if (!AllocFailed(Modes)) {
						strmcpy(Modes, BaseNick, Nick - BaseNick + 1);
					}
				}

				Channel->AddUser(Nick, Modes);

				free(BaseNick);
				free(Modes);
			}

			ArgFreeArray(nickv);
			ArgFree(nicks);
		}
	} else if (argc > 3 && iRaw == 366) {
		Channel = GetChannel(argv[3]);

		if (Channel != NULL) {
			Channel->SetHasNames();
		}
	} else if (argc > 9 && iRaw == 352) {
		const char *Ident = argv[4];
		const char *Host = argv[5];
		const char *Server = argv[6];
		const char *Nick = argv[7];
		const char *Realname = argv[9];
		char *Mask;

		int rc = asprintf(&Mask, "%s!%s@%s", Nick, Ident, Host);

		if (!RcFailed(rc)) {
			UpdateHostHelper(Mask);
			UpdateWhoHelper(Nick, Realname, Server);

			free(Mask);
		}
	} else if (argc > 6 && iRaw == 367) {
		Channel = GetChannel(argv[3]);

		if (Channel != NULL) {
			Channel->GetBanlist()->SetBan(argv[4], argv[5], atoi(argv[6]));
		}
	} else if (argc > 3 && iRaw == 368) {
		Channel = GetChannel(argv[3]);

		if (Channel != NULL) {
			Channel->SetHasBans();
		}
	} else if (argc > 3 && iRaw == 396) {
		free(m_Site);
		m_Site = strdup(argv[3]);

		if (AllocFailed(m_Site)) {}
	} else if (argc > 3 && hashRaw == hashPong && m_Server != NULL && strcasecmp(argv[2], m_Server) == 0 && m_EatPong) {
		m_EatPong = false;

		return false;
	} else if (argc > 3 && iRaw == 421) {
		m_FloodControl->Unplug();

		return false;
	}

	if (GetOwner() != NULL) {
		return ModuleEvent(argc, argv);
	} else {
		return true;
	}
}
Ejemplo n.º 21
0
nsresult
nsHtml5Parser::Parse(const nsAString& aSourceBuffer,
                     void* aKey,
                     const nsACString& aContentType,
                     bool aLastCall,
                     nsDTDMode aMode) // ignored
{
  nsresult rv;
  if (NS_FAILED(rv = mExecutor->IsBroken())) {
    return rv;
  }
  if (aSourceBuffer.Length() > INT32_MAX) {
    return mExecutor->MarkAsBroken(NS_ERROR_OUT_OF_MEMORY);
  }

  // Maintain a reference to ourselves so we don't go away
  // till we're completely done. The old parser grips itself in this method.
  nsCOMPtr<nsIParser> kungFuDeathGrip(this);
  
  // Gripping the other objects just in case, since the other old grip
  // required grips to these, too.
  nsRefPtr<nsHtml5StreamParser> streamKungFuDeathGrip(GetStreamParser());
  nsRefPtr<nsHtml5TreeOpExecutor> treeOpKungFuDeathGrip(mExecutor);

  if (!mExecutor->HasStarted()) {
    NS_ASSERTION(!GetStreamParser(),
                 "Had stream parser but document.write started life cycle.");
    // This is the first document.write() on a document.open()ed document
    mExecutor->SetParser(this);
    mTreeBuilder->setScriptingEnabled(mExecutor->IsScriptEnabled());

    bool isSrcdoc = false;
    nsCOMPtr<nsIChannel> channel;
    rv = GetChannel(getter_AddRefs(channel));
    if (NS_SUCCEEDED(rv)) {
      isSrcdoc = NS_IsSrcdocChannel(channel);
    }
    mTreeBuilder->setIsSrcdocDocument(isSrcdoc);

    mTokenizer->start();
    mExecutor->Start();
    if (!aContentType.EqualsLiteral("text/html")) {
      mTreeBuilder->StartPlainText();
      mTokenizer->StartPlainText();
    }
    /*
     * If you move the following line, be very careful not to cause 
     * WillBuildModel to be called before the document has had its 
     * script global object set.
     */
    rv = mExecutor->WillBuildModel(eDTDMode_unknown);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // Return early if the parser has processed EOF
  if (mExecutor->IsComplete()) {
    return NS_OK;
  }

  if (aLastCall && aSourceBuffer.IsEmpty() && !aKey) {
    // document.close()
    NS_ASSERTION(!GetStreamParser(),
                 "Had stream parser but got document.close().");
    if (mDocumentClosed) {
      // already closed
      return NS_OK;
    }
    mDocumentClosed = true;
    if (!mBlocked && !mInDocumentWrite) {
      return ParseUntilBlocked();
    }
    return NS_OK;
  }

  // If we got this far, we are dealing with a document.write or
  // document.writeln call--not document.close().

  NS_ASSERTION(IsInsertionPointDefined(),
               "Doc.write reached parser with undefined insertion point.");

  NS_ASSERTION(!(GetStreamParser() && !aKey),
               "Got a null key in a non-script-created parser");

  // XXX is this optimization bogus?
  if (aSourceBuffer.IsEmpty()) {
    return NS_OK;
  }

  // This guard is here to prevent document.close from tokenizing synchronously
  // while a document.write (that wrote the script that called document.close!)
  // is still on the call stack.
  mozilla::AutoRestore<bool> guard(mInDocumentWrite);
  mInDocumentWrite = true;

  // The script is identified by aKey. If there's nothing in the buffer
  // chain for that key, we'll insert at the head of the queue.
  // When the script leaves something in the queue, a zero-length
  // key-holder "buffer" is inserted in the queue. If the same script
  // leaves something in the chain again, it will be inserted immediately
  // before the old key holder belonging to the same script.
  //
  // We don't do the actual data insertion yet in the hope that the data gets
  // tokenized and there no data or less data to copy to the heap after
  // tokenization. Also, this way, we avoid inserting one empty data buffer
  // per document.write, which matters for performance when the parser isn't
  // blocked and a badly-authored script calls document.write() once per
  // input character. (As seen in a benchmark!)
  //
  // The insertion into the input stream happens conceptually before anything
  // gets tokenized. To make sure multi-level document.write works right,
  // it's necessary to establish the location of our parser key up front
  // in case this is the first write with this key.
  //
  // In a document.open() case, the first write level has a null key, so that
  // case is handled separately, because normal buffers containing data
  // have null keys.

  // These don't need to be owning references, because they always point to
  // the buffer queue and buffers can't be removed from the buffer queue
  // before document.write() returns. The buffer queue clean-up happens the
  // next time ParseUntilBlocked() is called.
  // However, they are made owning just in case the reasoning above is flawed
  // and a flaw would lead to worse problems with plain pointers. If this
  // turns out to be a perf problem, it's worthwhile to consider making
  // prevSearchbuf a plain pointer again.
  nsRefPtr<nsHtml5OwningUTF16Buffer> prevSearchBuf;
  nsRefPtr<nsHtml5OwningUTF16Buffer> firstLevelMarker;

  if (aKey) {
    if (mFirstBuffer == mLastBuffer) {
      nsHtml5OwningUTF16Buffer* keyHolder = new nsHtml5OwningUTF16Buffer(aKey);
      keyHolder->next = mLastBuffer;
      mFirstBuffer = keyHolder;
    } else if (mFirstBuffer->key != aKey) {
      prevSearchBuf = mFirstBuffer;
      for (;;) {
        if (prevSearchBuf->next == mLastBuffer) {
          // key was not found
          nsHtml5OwningUTF16Buffer* keyHolder =
            new nsHtml5OwningUTF16Buffer(aKey);
          keyHolder->next = mFirstBuffer;
          mFirstBuffer = keyHolder;
          prevSearchBuf = nullptr;
          break;
        }
        if (prevSearchBuf->next->key == aKey) {
          // found a key holder
          break;
        }
        prevSearchBuf = prevSearchBuf->next;
      }
    } // else mFirstBuffer is the keyholder

    // prevSearchBuf is the previous buffer before the keyholder or null if
    // there isn't one.
  } else {
    // We have a first-level write in the document.open() case. We insert before
    // mLastBuffer, effectively, by making mLastBuffer be a new sentinel object
    // and redesignating the previous mLastBuffer as our firstLevelMarker.  We
    // need to put a marker there, because otherwise additional document.writes
    // from nested event loops would insert in the wrong place. Sigh.
    mLastBuffer->next = new nsHtml5OwningUTF16Buffer((void*)nullptr);
    firstLevelMarker = mLastBuffer;
    mLastBuffer = mLastBuffer->next;
  }

  nsHtml5DependentUTF16Buffer stackBuffer(aSourceBuffer);

  while (!mBlocked && stackBuffer.hasMore()) {
    stackBuffer.adjust(mLastWasCR);
    mLastWasCR = false;
    if (stackBuffer.hasMore()) {
      int32_t lineNumberSave;
      bool inRootContext = (!GetStreamParser() && !aKey);
      if (inRootContext) {
        mTokenizer->setLineNumber(mRootContextLineNumber);
      } else {
        // we aren't the root context, so save the line number on the
        // *stack* so that we can restore it.
        lineNumberSave = mTokenizer->getLineNumber();
      }

      mLastWasCR = mTokenizer->tokenizeBuffer(&stackBuffer);

      if (inRootContext) {
        mRootContextLineNumber = mTokenizer->getLineNumber();
      } else {
        mTokenizer->setLineNumber(lineNumberSave);
      }

      if (mTreeBuilder->HasScript()) {
        mTreeBuilder->Flush(); // Move ops to the executor
        rv = mExecutor->FlushDocumentWrite(); // run the ops
        NS_ENSURE_SUCCESS(rv, rv);
        // Flushing tree ops can cause all sorts of things.
        // Return early if the parser got terminated.
        if (mExecutor->IsComplete()) {
          return NS_OK;
        }
      }
      // Ignore suspension requests
    }
  }

  nsRefPtr<nsHtml5OwningUTF16Buffer> heapBuffer;
  if (stackBuffer.hasMore()) {
    // The buffer wasn't tokenized to completion. Create a copy of the tail
    // on the heap.
    heapBuffer = stackBuffer.FalliblyCopyAsOwningBuffer();
    if (!heapBuffer) {
      // Allocation failed. The parser is now broken.
      return mExecutor->MarkAsBroken(NS_ERROR_OUT_OF_MEMORY);
    }
  }

  if (heapBuffer) {
    // We have something to insert before the keyholder holding in the non-null
    // aKey case and we have something to swap into firstLevelMarker in the
    // null aKey case.
    if (aKey) {
      NS_ASSERTION(mFirstBuffer != mLastBuffer,
        "Where's the keyholder?");
      // the key holder is still somewhere further down the list from
      // prevSearchBuf (which may be null)
      if (mFirstBuffer->key == aKey) {
        NS_ASSERTION(!prevSearchBuf,
          "Non-null prevSearchBuf when mFirstBuffer is the key holder?");
        heapBuffer->next = mFirstBuffer;
        mFirstBuffer = heapBuffer;
      } else {
        if (!prevSearchBuf) {
          prevSearchBuf = mFirstBuffer;
        }
        // We created a key holder earlier, so we will find it without walking
        // past the end of the list.
        while (prevSearchBuf->next->key != aKey) {
          prevSearchBuf = prevSearchBuf->next;
        }
        heapBuffer->next = prevSearchBuf->next;
        prevSearchBuf->next = heapBuffer;
      }
    } else {
      NS_ASSERTION(firstLevelMarker, "How come we don't have a marker.");
      firstLevelMarker->Swap(heapBuffer);
    }
  }

  if (!mBlocked) { // buffer was tokenized to completion
    NS_ASSERTION(!stackBuffer.hasMore(),
      "Buffer wasn't tokenized to completion?");
    // Scripting semantics require a forced tree builder flush here
    mTreeBuilder->Flush(); // Move ops to the executor
    rv = mExecutor->FlushDocumentWrite(); // run the ops
    NS_ENSURE_SUCCESS(rv, rv);
  } else if (stackBuffer.hasMore()) {
    // The buffer wasn't tokenized to completion. Tokenize the untokenized
    // content in order to preload stuff. This content will be retokenized
    // later for normal parsing.
    if (!mDocWriteSpeculatorActive) {
      mDocWriteSpeculatorActive = true;
      if (!mDocWriteSpeculativeTreeBuilder) {
        // Lazily initialize if uninitialized
        mDocWriteSpeculativeTreeBuilder =
            new nsHtml5TreeBuilder(nullptr, mExecutor->GetStage());
        mDocWriteSpeculativeTreeBuilder->setScriptingEnabled(
            mTreeBuilder->isScriptingEnabled());
        mDocWriteSpeculativeTokenizer =
            new nsHtml5Tokenizer(mDocWriteSpeculativeTreeBuilder, false);
        mDocWriteSpeculativeTokenizer->setInterner(&mAtomTable);
        mDocWriteSpeculativeTokenizer->start();
      }
      mDocWriteSpeculativeTokenizer->resetToDataState();
      mDocWriteSpeculativeTreeBuilder->loadState(mTreeBuilder, &mAtomTable);
      mDocWriteSpeculativeLastWasCR = false;
    }

    // Note that with multilevel document.write if we didn't just activate the
    // speculator, it's possible that the speculator is now in the wrong state.
    // That's OK for the sake of simplicity. The worst that can happen is
    // that the speculative loads aren't exactly right. The content will be
    // reparsed anyway for non-preload purposes.

    // The buffer position for subsequent non-speculative parsing now lives
    // in heapBuffer, so it's ok to let the buffer position of stackBuffer
    // to be overwritten and not restored below.
    while (stackBuffer.hasMore()) {
      stackBuffer.adjust(mDocWriteSpeculativeLastWasCR);
      if (stackBuffer.hasMore()) {
        mDocWriteSpeculativeLastWasCR =
            mDocWriteSpeculativeTokenizer->tokenizeBuffer(&stackBuffer);
      }
    }

    mDocWriteSpeculativeTreeBuilder->Flush();
    mDocWriteSpeculativeTreeBuilder->DropHandles();
    mExecutor->FlushSpeculativeLoads();
  }

  return NS_OK;
}
Ejemplo n.º 22
0
/**
 * @return The value to be written to the channel field of a routing mux.
 */
uint32_t DigitalInput::GetChannelForRouting()
{
	return DigitalModule::RemapDigitalChannel(GetChannel() - 1);
}
//Seeks strong valid channel in downward direction
//return -1 on failure or valid channel on success
long FmRadioController_qcom :: SeekDown
(
    void
)
{
    long ret;
    long freq = -1;
    struct timespec ts;

    if(cur_fm_state == FM_ON) {
        ALOGI("FM seek down started\n");
        set_fm_state(SEEK_IN_PROGRESS);
        ret = QcomFmIoctlsInterface::set_control(fd_driver,
                      V4L2_CID_PRV_SRCHMODE, SEEK_MODE);
        if(ret != FM_SUCCESS) {
            set_fm_state(FM_ON);
            return freq;
        }

        ret = QcomFmIoctlsInterface::set_control(fd_driver,
                      V4L2_CID_PRV_SCANDWELL, SEEK_DWELL_TIME);
        if(ret != FM_SUCCESS) {
            set_fm_state(FM_ON);
            return freq;
        }

        ret = QcomFmIoctlsInterface::set_control(fd_driver,
                      V4L2_CID_PRV_SRCH_PTY, 0);
        if(ret != FM_SUCCESS) {
            set_fm_state(FM_ON);
            return freq;
        }

        ret = QcomFmIoctlsInterface::set_control(fd_driver,
                      V4L2_CID_PRV_SRCH_PI, 0);
        if(ret != FM_SUCCESS) {
            set_fm_state(FM_ON);
            return freq;
        }

        ret = QcomFmIoctlsInterface::start_search(fd_driver,
                                            SEARCH_DOWN);
        if(ret != FM_SUCCESS) {
            set_fm_state(FM_ON);
            return freq;
        }
        pthread_mutex_lock(&mutex_seek_compl_cond);
        ts = set_time_out(SEEK_COMPL_TIMEOUT);
        ret = pthread_cond_timedwait(&seek_compl_cond, &mutex_seek_compl_cond, &ts);
        pthread_mutex_unlock(&mutex_seek_compl_cond);
        if((cur_fm_state != SEEK_IN_PROGRESS) && !seek_canceled) {
           freq = GetChannel();
        }else {
        }
        seek_canceled = false;
        return freq;
    }else {
        ALOGE("FM is not in proper state to start Seek down operation\n");
        return freq;
    }
}
Ejemplo n.º 24
0
Archivo: hash.c Proyecto: NX-Andro/x3
struct chanNode *
AddChannel(const char *name, time_t time_, const char *modes, char *banlist, char *exemptlist)
{
    struct chanNode *cNode;
    char new_modes[MAXLEN], *argv[MAXNUMPARAMS];
    unsigned int nn;

    if (!IsChannelName(name)) {
        log_module(MAIN_LOG, LOG_ERROR, "Somebody asked to add channel '%s', which isn't a channel name!", name);
        return NULL;
    }
    if (!modes)
        modes = "";

    safestrncpy(new_modes, modes, sizeof(new_modes));
    nn = split_line(new_modes, 0, ArrayLength(argv), argv);
    if (!(cNode = GetChannel(name))) {
        cNode = calloc(1, sizeof(*cNode) + strlen(name));
        strcpy(cNode->name, name);
        banList_init(&cNode->banlist);
        exemptList_init(&cNode->exemptlist);
        modeList_init(&cNode->members);
        mod_chanmode(NULL, cNode, argv, nn, MCP_FROM_SERVER);
        dict_insert(channels, cNode->name, cNode);
        cNode->timestamp = time_;
        rel_age = 1;
    } else if (cNode->timestamp > time_) {
        wipeout_channel(cNode, time_, argv, nn);
        rel_age = 1;
    } else if (cNode->timestamp == time_) {
        mod_chanmode(NULL, cNode, argv, nn, MCP_FROM_SERVER);
        rel_age = 0;
    } else {
        rel_age = -1;
    }

    /* rel_age is the relative ages of our channel data versus what is
     * in a BURST command.  1 means ours is younger, 0 means both are
     * the same age, -1 means ours is older. */

    /* if it's a new or updated channel, make callbacks */
    if (rel_age > 0)
        for (nn=0; nn<ncf_used; nn++)
            ncf_list[nn](cNode, ncf_list_extra[nn]);

    /* go through list of bans and add each one */
    if (banlist && (rel_age >= 0)) {
        for (nn=0; banlist[nn];) {
            char *ban = banlist + nn;
            struct banNode *bn;
            while (banlist[nn] != ' ' && banlist[nn])
                nn++;
            while (banlist[nn] == ' ')
                banlist[nn++] = 0;
            bn = calloc(1, sizeof(*bn));
            safestrncpy(bn->ban, ban, sizeof(bn->ban));
            safestrncpy(bn->who, "<unknown>", sizeof(bn->who));
            bn->set = now;
            banList_append(&cNode->banlist, bn);
        }
    }

    /* go through list of exempts and add each one */
    if (exemptlist && (rel_age >= 0)) {
        for (nn=0; exemptlist[nn];) {
            char *exempt = exemptlist + nn;
            struct exemptNode *en;
            while (exemptlist[nn] != ' ' && exemptlist[nn])
                nn++;
            while (exemptlist[nn] == ' ')
                exemptlist[nn++] = 0;
            en = calloc(1, sizeof(*en));
            safestrncpy(en->exempt, exempt, sizeof(en->exempt));
            safestrncpy(en->who, "<unknown>", sizeof(en->who));
            en->set = now;
            exemptList_append(&cNode->exemptlist, en);
        }
    }

    return cNode;
}
Ejemplo n.º 25
0
void CKadOperation::Process(UINT Tick)
{
	bool bLookupActive = m_LookupState == eLookupActive;

	CKadLookup::Process(Tick); // this looks for more nodes

	if(m_pOperator && m_pOperator->IsValid())
	{
		m_pOperator->RunTimers();

		if(bLookupActive && m_LookupState != eLookupActive)
			m_pOperator->OnClosestNodes();
	}

	if((Tick & E10PerSec) == 0)
		return;

	if(m_LookupState == eLookupActive)
		return; // we are looking for closer nodes right now - just wait a second
	

	// Note: the kad operation mode for this kind of lookups is complicated, there are 3 modes of operation
	//
	//		m_JumpCount > 0
	//	1. Jumping, where we open channels to random nodes and request proxying
	//
	//		m_HopLimit > 1
	//	2. Routing, where we open channels to propabalistically choosen closest nodes
	//				The propabalistically choice is based on the total desired spread area
	//				If we hit a node that is already handling this lookup we need to choose a new one
	//
	//		m_HopLimit == 1
	//	3. Itterative Mode, here we do a normal lookup for closest nodes and than talk to them, not using proxying
	//		
	//
	//		m_HopLimit == 0
	//	4. Target for a operations and messaging, not doing any own spreading
	//

	if(m_HopLimit == 0 || (m_HopLimit == 1 && !(CountCalls() || CountStores() || CountLoads())))
		return; // we are not alowed to do anything - hoop 0 or hoop 1 and we have no hopable jobs just messages

	int FailedCount = 0;
	// Note: if we are in range we will act as one successfull share
	int UsedShares = m_InRange ? 1 : 0;
	int ShareHolders = 0;
	for(TNodeStatusMap::iterator I = m_Nodes.begin(); I != m_Nodes.end(); I++)
	{
		SOpProgress* pProgress = (SOpProgress*)I->second;
		if(pProgress->OpState == eOpFailed)
		{
			FailedCount++;
			continue;
		}
		if(pProgress->Shares == 0)
			continue;
		
		if(!I->first.pChannel)
		{
			ASSERT(0);
			continue;
		}

		UsedShares += pProgress->Shares;
		ShareHolders++;

		bool bStateless;
		if(!((bStateless = (pProgress->OpState == eOpStateless)) || pProgress->OpState == eOpProxy))
			continue;

		// send newly added requests if there are any
		if (pProgress->Calls.size() != CountCalls()
		 || pProgress->Stores.size() != CountStores()
		 || pProgress->Loads.size() != CountLoads())
		{
			SendRequests(I->first.pNode, I->first.pChannel, pProgress, bStateless);
		}
	}
	int FreeShares = GetSpreadShare() - UsedShares;
	//ASSERT(FreeShares >= 0);
	m_ActiveCount = ShareHolders;
	m_FailedCount = FailedCount;


	int TotalDoneJobs = 0;
	int TotalReplys = 0;
	if(m_pOperator)
		CountDone(m_pOperator->GetRequests(), TotalDoneJobs, TotalReplys);
	else
		CountDone(m_CallMap, TotalDoneJobs, TotalReplys);
	CountDone(m_StoreMap, TotalDoneJobs, TotalReplys);
	CountDone(m_LoadMap, TotalDoneJobs, TotalReplys);
	m_TotalDoneJobs = TotalDoneJobs;
	m_TotalReplys = TotalReplys;


	if(m_ManualMode)
		return;

	// Note: if we are in Jump Mode we prep the iterator to give uss randome nodes
	//		If we are in Iterative Mode we prep the iterator to give us the closest node
	//		If we are in Routong Mode it complicated, we want a random node from the m_SpreadCount closest nodes
	CRoutingZone::SIterator Iter(m_JumpCount > 0 ? 0 : (m_HopLimit > 1 ? m_SpreadCount : 1));
	for(CKadNode* pNode = NULL; FreeShares > 0 && (pNode = GetParent<CKademlia>()->Root()->GetClosestNode(Iter, m_ID)) != NULL;)
	{
		if(m_JumpCount == 0 && ((pNode->GetID() ^ m_ID) > GetParent<CKademlia>()->Root()->GetMaxDistance()))
			break; // there are no nodes anymore in list that would be elegable here
		
		CComChannel* pChannel = GetChannel(pNode);
		if(!pChannel)
			continue;

		SOpProgress* pProgress = GetProgress(pNode);
		ASSERT(pProgress); // right after get channel this must work
		if(pProgress->OpState != eNoOp)
			continue; // this node has already been tryed

		if(m_HopLimit > 1)
			RequestProxying(pNode, pChannel, pProgress, FreeShares, ShareHolders, m_InitParam);
		else
			RequestStateless(pNode, pChannel, pProgress);

		if(pProgress->Shares)
		{
			FreeShares -= pProgress->Shares;
			ShareHolders ++;
		}
	}

	// if there are shares left we are out of nodes
	m_OutOfNodes = (FreeShares > 0);
}
Ejemplo n.º 26
0
void MainClientWindow::AddMessageToChannel(IRCData::MessageData *messageData)
{
    ChatWidget *widget = GetChannel(messageData->channelName);
    widget->AddMessage(messageData);
}
Ejemplo n.º 27
0
/** \fn IPTVSignalMonitor::~IPTVSignalMonitor()
 *  \brief Stops signal monitoring and table monitoring threads.
 */
IPTVSignalMonitor::~IPTVSignalMonitor()
{
    GetChannel()->GetFeeder()->RemoveListener(this);
    Stop();
}
Ejemplo n.º 28
0
void PlayField::MessageReceived(void){
	int cnt = GetReceivedCount();
	char *buf = (char*)GetReceivedBuffer();
	for(int n=0; n<cnt; n++){
		switch(GetReceivedCommand(n)){
		case INPUT_DIGITAL_DOWN:{
			if(!buf){
				printf("PlayField::MessageReceived: No buffer!\n");
				break;
			}
			int len = *(int16*)buf;
			buf+=sizeof(int16);
			char *str = new char[len+1];
			for(int n=0; n<len; n++) str[n]=*buf++;
			str[len]='\0';
//			printf("%s down\n",str);

			char *key = &str[1];
			int chan = 0;
			bool done = false;
			do{
				switch(*key++){
				case '0': chan*=10; break;
				case '1': chan*=10; chan+=1; break;
				case '2': chan*=10; chan+=2; break;
				case '3': chan*=10; chan+=3; break;
				case '4': chan*=10; chan+=4; break;
				case '5': chan*=10; chan+=5; break;
				case '6': chan*=10; chan+=6; break;
				case '7': chan*=10; chan+=7; break;
				case '8': chan*=10; chan+=8; break;
				case '9': chan*=10; chan+=9; break;
				default: done=true;
				}
			}while(!done);

if(chan>=channels->GetCount()){
//	printf("PlayField::MessageReceived(): Channel overflow!\n");
	delete str;
	return;
}

//			printf("%s(%d) down\n",key,chan);

			if(!strcmp(key,"!Hook")){
//printf("PlayField: hookof %d\n",chan);
				#ifndef SINGLE_LINE_TEST
				if(GetChannel(chan)) printf("PlayField: Channel allready active (%d)!\n",chan);
				else{
				#endif
					//((Player*)players->GetItem(0))->Logon();
					Player *player = AllocateChannel(chan);
					player->Logon();
				#ifndef SINGLE_LINE_TEST
				}
				#endif
			}
			else if(!strcmp(key,"1")){ if(GetChannel(chan)) ((Player*)GetChannel(chan))->Lock(0); }
			else if(!strcmp(key,"2")){ if(GetChannel(chan)) ((Player*)GetChannel(chan))->Lock(1); }
			else if(!strcmp(key,"3")){ if(GetChannel(chan)) ((Player*)GetChannel(chan))->Lock(2); }
			else if(!strcmp(key,"4")){ if(GetChannel(chan)) ((Player*)GetChannel(chan))->Lock(3); }
			else if(!strcmp(key,"5")){ if(GetChannel(chan)) ((Player*)GetChannel(chan))->Spinn(); }
			if(GetChannel(chan)) ((Player*)GetChannel(chan))->DigitDown(key);

/*
			if(!strcmp(key,"!Hook")) state[chan] = '!';
			if(!strcmp(key,"0"))     state[chan] = '0';
			if(!strcmp(key,"1"))     state[chan] = '1';
			if(!strcmp(key,"2"))     state[chan] = '2';
			if(!strcmp(key,"3"))     state[chan] = '3';
			if(!strcmp(key,"4"))     state[chan] = '4';
			if(!strcmp(key,"5"))     state[chan] = '5';
			if(!strcmp(key,"6"))     state[chan] = '6';
			if(!strcmp(key,"7"))     state[chan] = '7';
			if(!strcmp(key,"8"))     state[chan] = '8';
			if(!strcmp(key,"9"))     state[chan] = '9';
			if(!strcmp(key,"#"))     state[chan] = '#';
			if(!strcmp(key,"*"))     state[chan] = '*';
*/
			delete str;

		}break;
		case INPUT_DIGITAL_UP:{
			if(!buf){
				printf("PlayField::MessageReceived: No buffer!\n");
				break;
			}
			int len = *(int16*)buf;
			buf+=sizeof(int16);
			char *str = new char[len+1];
			for(int n=0; n<len; n++) str[n]=*buf++;
			str[len]='\0';
//			printf("%s up\n",str);

			char *key = &str[1];
			int chan = 0;
			bool done = false;
			do{
				switch(*key++){
				case '0': chan*=10; break;
				case '1': chan*=10; chan+=1; break;
				case '2': chan*=10; chan+=2; break;
				case '3': chan*=10; chan+=3; break;
				case '4': chan*=10; chan+=4; break;
				case '5': chan*=10; chan+=5; break;
				case '6': chan*=10; chan+=6; break;
				case '7': chan*=10; chan+=7; break;
				case '8': chan*=10; chan+=8; break;
				case '9': chan*=10; chan+=9; break;
				default: done=true;
				}
			}while(!done);

if(chan>=channels->GetCount()){
//	printf("PlayField::MessageReceived(): Channel overflow!\n");
	delete str;
	return;
}

//			printf("%s(%d) up\n",key,chan);

//			if(!strcmp(key,"!Hook")) ((Player*)players->GetItem(0))->Logout();
			if(GetChannel(chan)) ((Player*)GetChannel(chan))->DigitUp(key);

			#ifndef SINGLE_LINE_TEST
			if(!strcmp(key,"!Hook")){
//printf("PlayField: hookon %d\n",chan);
				Player *player = GetChannel(chan);
				if(player){
					player->Logout();
					FreeChannel(chan);
				}else printf("PlayField: No player in channel %d!\n",chan);
			}
			#endif

/*
			if(!strcmp(key,"!Hook")) state[chan] = '-';
			else
			if(!strcmp(key,"0"))     state[chan] = '!';
			if(!strcmp(key,"1"))     state[chan] = '!';
			if(!strcmp(key,"2"))     state[chan] = '!';
			if(!strcmp(key,"3"))     state[chan] = '!';
			if(!strcmp(key,"4"))     state[chan] = '!';
			if(!strcmp(key,"5"))     state[chan] = '!';
			if(!strcmp(key,"6"))     state[chan] = '!';
			if(!strcmp(key,"7"))     state[chan] = '!';
			if(!strcmp(key,"8"))     state[chan] = '!';
			if(!strcmp(key,"9"))     state[chan] = '!';
			if(!strcmp(key,"#"))     state[chan] = '!';
			if(!strcmp(key,"*"))     state[chan] = '!';
*/
			delete str;
		}break;
		}
	}
}
Ejemplo n.º 29
0
NS_IMETHODIMP
InterceptedChannelBase::SaveTimeStamps()
{
  MOZ_ASSERT(NS_IsMainThread());

  nsCOMPtr<nsIChannel> underlyingChannel;
  nsresult rv = GetChannel(getter_AddRefs(underlyingChannel));
  MOZ_ASSERT(NS_SUCCEEDED(rv));

  nsCOMPtr<nsITimedChannel> timedChannel =
    do_QueryInterface(underlyingChannel);
  MOZ_ASSERT(timedChannel);

  rv = timedChannel->SetLaunchServiceWorkerStart(mLaunchServiceWorkerStart);
  MOZ_ASSERT(NS_SUCCEEDED(rv));

  rv = timedChannel->SetLaunchServiceWorkerEnd(mLaunchServiceWorkerEnd);
  MOZ_ASSERT(NS_SUCCEEDED(rv));

  rv = timedChannel->SetDispatchFetchEventStart(mDispatchFetchEventStart);
  MOZ_ASSERT(NS_SUCCEEDED(rv));

  rv = timedChannel->SetDispatchFetchEventEnd(mDispatchFetchEventEnd);
  MOZ_ASSERT(NS_SUCCEEDED(rv));

  rv = timedChannel->SetHandleFetchEventStart(mHandleFetchEventStart);
  MOZ_ASSERT(NS_SUCCEEDED(rv));

  rv = timedChannel->SetHandleFetchEventEnd(mHandleFetchEventEnd);
  MOZ_ASSERT(NS_SUCCEEDED(rv));

  nsCOMPtr<nsIChannel> channel;
  GetChannel(getter_AddRefs(channel));
  if (NS_WARN_IF(!channel)) {
    return NS_ERROR_FAILURE;
  }

  bool isNonSubresourceRequest = nsContentUtils::IsNonSubresourceRequest(channel);
  nsCString navigationOrSubresource = isNonSubresourceRequest ?
    NS_LITERAL_CSTRING("navigation") : NS_LITERAL_CSTRING("subresource");

  nsAutoCString subresourceKey(EmptyCString());
  GetSubresourceTimeStampKey(channel, subresourceKey);

  // We may have null timestamps if the fetch dispatch runnable was cancelled
  // and we defaulted to resuming the request.
  if (!mFinishResponseStart.IsNull() && !mFinishResponseEnd.IsNull()) {
    MOZ_ASSERT(mSynthesizedOrReset != Invalid);

    Telemetry::HistogramID id = (mSynthesizedOrReset == Synthesized) ?
      Telemetry::SERVICE_WORKER_FETCH_EVENT_FINISH_SYNTHESIZED_RESPONSE_MS :
      Telemetry::SERVICE_WORKER_FETCH_EVENT_CHANNEL_RESET_MS;
    Telemetry::Accumulate(id, navigationOrSubresource,
      static_cast<uint32_t>((mFinishResponseEnd - mFinishResponseStart).ToMilliseconds()));
    if (!isNonSubresourceRequest && !subresourceKey.IsEmpty()) {
      Telemetry::Accumulate(id, subresourceKey,
        static_cast<uint32_t>((mFinishResponseEnd - mFinishResponseStart).ToMilliseconds()));
    }
  }

  Telemetry::Accumulate(Telemetry::SERVICE_WORKER_FETCH_EVENT_DISPATCH_MS,
    navigationOrSubresource,
    static_cast<uint32_t>((mHandleFetchEventStart - mDispatchFetchEventStart).ToMilliseconds()));

  if (!isNonSubresourceRequest && !subresourceKey.IsEmpty()) {
    Telemetry::Accumulate(Telemetry::SERVICE_WORKER_FETCH_EVENT_DISPATCH_MS,
      subresourceKey,
      static_cast<uint32_t>((mHandleFetchEventStart - mDispatchFetchEventStart).ToMilliseconds()));
  }

  if (!mFinishResponseEnd.IsNull()) {
    Telemetry::Accumulate(Telemetry::SERVICE_WORKER_FETCH_INTERCEPTION_DURATION_MS,
      navigationOrSubresource,
      static_cast<uint32_t>((mFinishResponseEnd - mDispatchFetchEventStart).ToMilliseconds()));
    if (!isNonSubresourceRequest && !subresourceKey.IsEmpty()) {
      Telemetry::Accumulate(Telemetry::SERVICE_WORKER_FETCH_INTERCEPTION_DURATION_MS,
        subresourceKey,
        static_cast<uint32_t>((mFinishResponseEnd - mDispatchFetchEventStart).ToMilliseconds()));
    }
  }

  return rv;
}
Ejemplo n.º 30
0
ChatWidget *MainClientWindow::GetCurrentChannel()
{
    QString name = ((ChatWidget*)tabbedPane->currentWidget())
            ->GetChannelData()->name;
    return GetChannel(name);
}