Ejemplo n.º 1
0
void LogUnixServer::Log(const LogType Type, const std::string &str) {
	char *msg = NULL;

	time_t current = time(NULL);
	struct tm timeinfo;
	char buf[128];

	localtime_r(&current, &timeinfo);
	strftime(buf, sizeof(buf), "%F %T", &timeinfo);

	if (asprintf(&msg, "%s - %s [PID: %d] - %s\n", buf, LogTypeToStr(Type).c_str(), getpid(), str.c_str()) < 0)
	{
		std::stringstream ss;
		ss << "asprintf failed error:" << strerror(errno);
		throw(LogException(ss.str()));
	}
	else
	{
		std::list<int> broken;
		int len = strlen(msg);

		Lock();

		for(auto fd : m_list)
		{
			ssize_t offset = 0;
			ssize_t ret = 0;
			do
			{
				ret = write(fd, msg + offset, len - offset);
				if (ret < 0)
				{
					switch(errno)
					{
						case EINTR:
							ret = 0; //Fudge this as if we didn't write anything
							break;
						default:
							break;
					}
				}
				else
				{
					offset += len;
				}
			} while(offset < len);

			if (ret < len || ret == 0)
			{
				broken.push_back(fd);
			}
		}

		//Kick any broken clients
		for(auto fd : broken)
		{
			if (close(fd) < 0)
			{
				abort();
			}
			m_list.remove(fd);
		}

		Unlock();

	}
	free(msg);
}
Ejemplo n.º 2
0
void cProtocol125::SendUnloadChunk(int a_ChunkX, int a_ChunkZ)
{
	cCSLock Lock(m_CSPacket);
	SendPreChunk(a_ChunkX, a_ChunkZ, false);
}
Ejemplo n.º 3
0
bool CGPSController::IsKnownPosition() {
	Lock();
	bool ret = m_knownPosition;
	Unlock();
	return ret;
}
Ejemplo n.º 4
0
// VPN Azure client main thread
void AcMainThread(THREAD *thread, void *param)
{
	AZURE_CLIENT *ac = (AZURE_CLIENT *)param;
	UINT last_ip_revision = INFINITE;
	UINT64 last_reconnect_tick = 0;
	UINT64 next_reconnect_interval = AZURE_CONNECT_INITIAL_RETRY_INTERVAL;
	UINT num_reconnect_retry = 0;
	UINT64 next_ddns_retry_tick = 0;
	bool last_connect_ok = false;
	// Validate arguments
	if (ac == NULL || thread == NULL)
	{
		return;
	}

	while (ac->Halt == false)
	{
		UINT64 now = Tick64();
		bool connect_was_ok = false;
		// Wait for enabling VPN Azure function
		if (ac->IsEnabled)
		{
			// VPN Azure is enabled
			DDNS_CLIENT_STATUS st;
			bool connect_now = false;
			bool azure_ip_changed = false;

			Lock(ac->Lock);
			{
				Copy(&st, &ac->DDnsStatus, sizeof(DDNS_CLIENT_STATUS));

				if (StrCmpi(st.CurrentAzureIp, ac->DDnsStatusCopy.CurrentAzureIp) != 0)
				{
					if (IsEmptyStr(st.CurrentAzureIp) == false)
					{
						// Destination IP address is changed
						connect_now = true;
						num_reconnect_retry = 0;
					}
				}

				if (StrCmpi(st.CurrentHostName, ac->DDnsStatusCopy.CurrentHostName) != 0)
				{
					// DDNS host name is changed
					connect_now = true;
					num_reconnect_retry = 0;
				}

				Copy(&ac->DDnsStatusCopy, &st, sizeof(DDNS_CLIENT_STATUS));
			}
			Unlock(ac->Lock);

			if (last_ip_revision != ac->IpStatusRevision)
			{
				last_ip_revision = ac->IpStatusRevision;

				connect_now = true;

				num_reconnect_retry = 0;
			}

			if (last_reconnect_tick == 0 || (now >= (last_reconnect_tick + next_reconnect_interval)))
			{
				UINT r;

				last_reconnect_tick = now;
				num_reconnect_retry++;
				next_reconnect_interval = (UINT64)num_reconnect_retry * AZURE_CONNECT_INITIAL_RETRY_INTERVAL;
				next_reconnect_interval = MIN(next_reconnect_interval, AZURE_CONNECT_MAX_RETRY_INTERVAL);

				r = (UINT)next_reconnect_interval;

				r = GenRandInterval(r / 2, r);

				next_reconnect_interval = r;

				connect_now = true;
			}

			if (IsEmptyStr(st.CurrentAzureIp) == false && IsEmptyStr(st.CurrentHostName) == false)
			{
				if (connect_now)
				{
					SOCK *s;
					char *host = NULL;
					UINT port = AZURE_SERVER_PORT;

					Debug("VPN Azure: Connecting to %s...\n", st.CurrentAzureIp);

					if (ParseHostPort(st.CurrentAzureIp, &host, &port, AZURE_SERVER_PORT))
					{
						if (st.InternetSetting.ProxyType == PROXY_DIRECT)
						{
							s = ConnectEx2(host, port, 0, (bool *)&ac->Halt);
						}
						else
						{
							s = WpcSockConnect2(host, port, &st.InternetSetting, NULL, AZURE_VIA_PROXY_TIMEOUT);
						}

						if (s != NULL)
						{
							PACK *p;
							UINT64 established_tick = 0;

							Debug("VPN Azure: Connected.\n");

							SetTimeout(s, AZURE_PROTOCOL_CONTROL_TIMEOUT_DEFAULT);

							Lock(ac->Lock);
							{
								ac->CurrentSock = s;
								ac->IsConnected = true;
								StrCpy(ac->ConnectingAzureIp, sizeof(ac->ConnectingAzureIp), st.CurrentAzureIp);
							}
							Unlock(ac->Lock);

							SendAll(s, AZURE_PROTOCOL_CONTROL_SIGNATURE, StrLen(AZURE_PROTOCOL_CONTROL_SIGNATURE), false);

							// Receive parameter
							p = RecvPackWithHash(s);
							if (p != NULL)
							{
								UCHAR c;
								AZURE_PARAM param;
								bool hostname_changed = false;

								Zero(&param, sizeof(param));

								param.ControlKeepAlive = PackGetInt(p, "ControlKeepAlive");
								param.ControlTimeout = PackGetInt(p, "ControlTimeout");
								param.DataTimeout = PackGetInt(p, "DataTimeout");
								param.SslTimeout = PackGetInt(p, "SslTimeout");

								FreePack(p);

								param.ControlKeepAlive = MAKESURE(param.ControlKeepAlive, 1000, AZURE_SERVER_MAX_KEEPALIVE);
								param.ControlTimeout = MAKESURE(param.ControlTimeout, 1000, AZURE_SERVER_MAX_TIMEOUT);
								param.DataTimeout = MAKESURE(param.DataTimeout, 1000, AZURE_SERVER_MAX_TIMEOUT);
								param.SslTimeout = MAKESURE(param.SslTimeout, 1000, AZURE_SERVER_MAX_TIMEOUT);

								Lock(ac->Lock);
								{
									Copy(&ac->AzureParam, &param, sizeof(AZURE_PARAM));
								}
								Unlock(ac->Lock);

								SetTimeout(s, param.ControlTimeout);

								// Send parameter
								p = NewPack();
								PackAddStr(p, "CurrentHostName", st.CurrentHostName);
								PackAddStr(p, "CurrentAzureIp", st.CurrentAzureIp);
								PackAddInt64(p, "CurrentAzureTimestamp", st.CurrentAzureTimestamp);
								PackAddStr(p, "CurrentAzureSignature", st.CurrentAzureSignature);

								Lock(ac->Lock);
								{
									if (StrCmpi(st.CurrentHostName, ac->DDnsStatus.CurrentHostName) != 0)
									{
										hostname_changed = true;
									}
								}
								Unlock(ac->Lock);

								if (hostname_changed == false)
								{
									if (SendPackWithHash(s, p))
									{
										// Receive result
										if (RecvAll(s, &c, 1, false))
										{
											if (c && ac->Halt == false)
											{
												connect_was_ok = true;

												established_tick = Tick64();

												AcWaitForRequest(ac, s, &param);
											}
										}
									}
								}

								FreePack(p);
							}
							else
							{
								WHERE;
							}

							Debug("VPN Azure: Disconnected.\n");

							Lock(ac->Lock);
							{
								ac->IsConnected = false;
								ac->CurrentSock = NULL;
								ClearStr(ac->ConnectingAzureIp, sizeof(ac->ConnectingAzureIp));
							}
							Unlock(ac->Lock);

							if (established_tick != 0)
							{
								if ((established_tick + (UINT64)AZURE_CONNECT_MAX_RETRY_INTERVAL) <= Tick64())
								{
									// If the connected time exceeds the AZURE_CONNECT_MAX_RETRY_INTERVAL, reset the retry counter.
									last_reconnect_tick = 0;
									num_reconnect_retry = 0;
									next_reconnect_interval = AZURE_CONNECT_INITIAL_RETRY_INTERVAL;
								}
							}

							Disconnect(s);
							ReleaseSock(s);
						}
						else
						{
							Debug("VPN Azure: Error: Connect Failed.\n");
						}

						Free(host);
					}
				}
			}
		}
		else
		{
			last_reconnect_tick = 0;
			num_reconnect_retry = 0;
			next_reconnect_interval = AZURE_CONNECT_INITIAL_RETRY_INTERVAL;
		}

		if (ac->Halt)
		{
			break;
		}

		if (connect_was_ok)
		{
			// If connection goes out after connected, increment connection success count to urge DDNS client query
			next_ddns_retry_tick = Tick64() + MIN((UINT64)DDNS_VPN_AZURE_CONNECT_ERROR_DDNS_RETRY_TIME_DIFF * (UINT64)(num_reconnect_retry + 1), (UINT64)DDNS_VPN_AZURE_CONNECT_ERROR_DDNS_RETRY_TIME_DIFF_MAX);
		}

		if ((next_ddns_retry_tick != 0) && (Tick64() >= next_ddns_retry_tick))
		{
			next_ddns_retry_tick = 0;

			ac->DDnsTriggerInt++;
		}

		Wait(ac->Event, rand() % 1000);
	}
}
Ejemplo n.º 5
0
OMXPacket *OMXReader::Read()
{
  assert(!IsEof());
  
  AVPacket  pkt;
  OMXPacket *m_omx_pkt = NULL;
  int       result = -1;

  if(!m_pFormatContext)
    return NULL;

  Lock();

  // assume we are not eof
  if(m_pFormatContext->pb)
    m_pFormatContext->pb->eof_reached = 0;

  // keep track if ffmpeg doesn't always set these
  pkt.size = 0;
  pkt.data = NULL;
  pkt.stream_index = MAX_OMX_STREAMS;

  result = m_dllAvFormat.av_read_frame(m_pFormatContext, &pkt);
  if (result < 0)
  {
    m_eof = true;
    //FlushRead();
    //m_dllAvCodec.av_free_packet(&pkt);
    UnLock();
    return NULL;
  }
  else if (pkt.size < 0 || pkt.stream_index >= MAX_OMX_STREAMS)
  {
    // XXX, in some cases ffmpeg returns a negative packet size
    if(m_pFormatContext->pb && !m_pFormatContext->pb->eof_reached)
    {
      CLog::Log(LOGERROR, "OMXReader::Read no valid packet");
      //FlushRead();
    }

    m_dllAvCodec.av_free_packet(&pkt);

    m_eof = true;
    UnLock();
    return NULL;
  }

  AVStream *pStream = m_pFormatContext->streams[pkt.stream_index];

  /* only read packets for active streams */
  /*
  if(!IsActive(pkt.stream_index))
  {
    m_dllAvCodec.av_free_packet(&pkt);
    UnLock();
    return NULL;
  }
  */

  // lavf sometimes bugs out and gives 0 dts/pts instead of no dts/pts
  // since this could only happens on initial frame under normal
  // circomstances, let's assume it is wrong all the time
  if(pkt.dts == 0)
    pkt.dts = AV_NOPTS_VALUE;
  if(pkt.pts == 0)
    pkt.pts = AV_NOPTS_VALUE;

  if(m_bMatroska && pStream->codec && pStream->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  { // matroska can store different timestamps
    // for different formats, for native stored
    // stuff it is pts, but for ms compatibility
    // tracks, it is really dts. sadly ffmpeg
    // sets these two timestamps equal all the
    // time, so we select it here instead
    if(pStream->codec->codec_tag == 0)
      pkt.dts = AV_NOPTS_VALUE;
    else
      pkt.pts = AV_NOPTS_VALUE;
  }
  // we need to get duration slightly different for matroska embedded text subtitels
  if(m_bMatroska && pStream->codec->codec_id == AV_CODEC_ID_SUBRIP && pkt.convergence_duration != 0)
    pkt.duration = pkt.convergence_duration;

  if(m_bAVI && pStream->codec && pStream->codec->codec_type == AVMEDIA_TYPE_VIDEO)
  {
    // AVI's always have borked pts, specially if m_pFormatContext->flags includes
    // AVFMT_FLAG_GENPTS so always use dts
    pkt.pts = AV_NOPTS_VALUE;
  }

  m_omx_pkt = AllocPacket(pkt.size);
  /* oom error allocation av packet */
  if(!m_omx_pkt)
  {
    m_eof = true;
    m_dllAvCodec.av_free_packet(&pkt);
    UnLock();
    return NULL;
  }

  m_omx_pkt->codec_type = pStream->codec->codec_type;

  /* copy content into our own packet */
  m_omx_pkt->size = pkt.size;

  if (pkt.data)
    memcpy(m_omx_pkt->data, pkt.data, m_omx_pkt->size);

  m_omx_pkt->stream_index = pkt.stream_index;
  GetHints(pStream, &m_omx_pkt->hints);

  //m_omx_pkt->dts = ConvertTimestamp(pkt.dts, pStream->time_base.den, pStream->time_base.num);
  //m_omx_pkt->pts = ConvertTimestamp(pkt.pts, pStream->time_base.den, pStream->time_base.num);
  m_omx_pkt->dts = ConvertTimestamp(pkt.dts, &pStream->time_base);
  m_omx_pkt->pts = ConvertTimestamp(pkt.pts, &pStream->time_base);
  m_omx_pkt->duration = DVD_SEC_TO_TIME((double)pkt.duration * pStream->time_base.num / pStream->time_base.den);

  // used to guess streamlength
  if (m_omx_pkt->dts != DVD_NOPTS_VALUE && (m_omx_pkt->dts > m_iCurrentPts || m_iCurrentPts == DVD_NOPTS_VALUE))
    m_iCurrentPts = m_omx_pkt->dts;

  // check if stream has passed full duration, needed for live streams
  if(pkt.dts != (int64_t)AV_NOPTS_VALUE)
  {
    int64_t duration;
    duration = pkt.dts;
    if(pStream->start_time != (int64_t)AV_NOPTS_VALUE)
      duration -= pStream->start_time;

    if(duration > pStream->duration)
    {
      pStream->duration = duration;
      duration = m_dllAvUtil.av_rescale_rnd(pStream->duration, (int64_t)pStream->time_base.num * AV_TIME_BASE, 
                                            pStream->time_base.den, AV_ROUND_NEAR_INF);
      if ((m_pFormatContext->duration == (int64_t)AV_NOPTS_VALUE)
          ||  (m_pFormatContext->duration != (int64_t)AV_NOPTS_VALUE && duration > m_pFormatContext->duration))
        m_pFormatContext->duration = duration;
    }
  }

  m_dllAvCodec.av_free_packet(&pkt);

  UnLock();
  return m_omx_pkt;
}
int CFileLoaderThread::DoThreadWork()
{
	int i;
	// Check for shutdown event
	if ( WAIT_OBJECT_0 == WaitForSingleObject( GetShutdownHandle(), 0 ) )
	{
		return 0;
	}

	// No changes to list right now
	Lock();
	// Move new items to work list
	int newItems = m_FileList.Count();
	for ( i = 0; i < newItems; i++ )
	{
		// Move to pending and issue async i/o calls
		m_Pending.AddToTail( m_FileList[ i ] );

		m_nTotalPending++;
	}
	m_FileList.RemoveAll();
	// Done adding new work items
	Unlock();

	int remaining = m_Pending.Count();
	if ( !remaining )
		return 1;

	int workitems = remaining; // min( remaining, 1000 );

	CUtlVector< SentenceRequest * > transfer;

	for ( i = 0; i < workitems; i++ )
	{
		SentenceRequest *r = m_Pending[ 0 ];
		m_Pending.Remove( 0 );

		transfer.AddToTail( r );
		// Do the work
		
		m_nTotalProcessed++;

		r->valid = SceneManager_LoadSentenceFromWavFileUsingIO( r->filename, r->sentence, m_ThreadIO );
	}

	// Now move to completed list
	Lock();
	for ( i = 0; i < workitems; i++ )
	{
		SentenceRequest *r = transfer[ i ];
		if ( r->valid )
		{
			m_nTotalCompleted++;

			m_Completed.AddToTail( r );
		}
		else
		{
			delete r;
		}
	}
	Unlock();
	return 1;
}
Ejemplo n.º 7
0
//-----------------------------------------------------------------------------
// Purpose: Input handler that locks the door.
//-----------------------------------------------------------------------------
void CBaseDoor::InputLock( inputdata_t &inputdata )
{
	Lock();
}
Ejemplo n.º 8
0
void CDVDPerformanceCounter::DeInitialize()
{
  Lock();
  
  Unlock();
}
Ejemplo n.º 9
0
inline void Factory::run()
{
	DeviceParamMap paramMap;
	/* Create the thread to update the Disk status */
	while (1)
	{
		paramMap.clear();
		{
			/* Got all the device param */
			Lock();
			DeviceMap::iterator it = m_DeviceMap.begin(); 
			for(; it!=m_DeviceMap.end(); ++it)
			{	
				s32 nIndex = (*it).first;
				DeviceParam pParam;
				Device *pDevice = m_DeviceMap[nIndex];
				if (pDevice == NULL)
				{
					continue;//TODO
				}
				pDevice->GetDeviceParam(pParam);
				paramMap[nIndex] = pParam;
			}
			UnLock();
		}
		{
			/* Loop all the deviceparam */
			DeviceParamMap::iterator it = paramMap.begin(); 
			for(; it!=paramMap.end(); ++it)
			{	
				/* Loop to check the device and update the url */
				s32 nIndex = (*it).first;
				(*it).second.m_wipOnline = (*it).second.CheckOnline();
				if ((*it).second.m_OnlineUrl == FALSE)
				{
					(*it).second.m_wipOnlineUrl = (*it).second.UpdateUrl();
				}
			}
		}
		{
			/* Loop all the deviceparam result and set to device */
			DeviceParamMap::iterator it = paramMap.begin(); 
			for(; it!=paramMap.end(); ++it)
			{	
				/* Loop to check the device and update the url */
				s32 nIndex = (*it).first;
				Lock();
				DeviceMap::iterator it1 = m_DeviceMap.find(nIndex), 
							ite1 = m_DeviceMap.end();

				if (it1 == ite1) 
				{
					/* the id may be delete */
					UnLock();
					continue;
				}

				DeviceStatus bCheck = m_DeviceMap[nIndex]->CheckDevice(
					(*it).second.m_strUrl, (*it).second.m_strUrlSubStream, 
					(*it).second.m_bHasSubStream, 
					(*it).second.m_wipOnline, (*it).second.m_wipOnlineUrl);
				
				FactoryDeviceChangeData change;
				change.id = nIndex;
				switch (bCheck)
				{
					case DEV_OFF2ON:
					{
						change.type = FACTORY_DEVICE_ONLINE;
						m_DeviceOnlineMap[nIndex] = 1;
						UnLock(); 
						CallDeviceChange(change);
						Lock();
						break;
					}
					case DEV_ON2OFF:
					{
						change.type = FACTORY_DEVICE_OFFLINE;
						m_DeviceOnlineMap[nIndex] = 0;
						UnLock(); 
						CallDeviceChange(change);
						Lock();
						break;
					}
					default:
					{

						break;
					}
				}
				UnLock();
			}
		}
		ve_sleep(1000 * 20);
	}
	
}
Ejemplo n.º 10
0
ECRESULT ECSessionGroup::AddNotificationTable(ECSESSIONID ulSessionId, unsigned int ulType, unsigned int ulObjType, unsigned int ulTableId,
											  sObjectTableKey* lpsChildRow, sObjectTableKey* lpsPrevRow, struct propValArray *lpRow)
{
	ECRESULT hr = erSuccess;

	Lock();

	struct notification *lpNotify = new struct notification;
	memset(lpNotify, 0, sizeof(notification));

	lpNotify->tab = new notificationTable;
	memset(lpNotify->tab, 0, sizeof(notificationTable));
	
	lpNotify->ulEventType			= fnevTableModified;
	lpNotify->tab->ulTableEvent		= ulType;


	if(lpsChildRow && (lpsChildRow->ulObjId > 0 || lpsChildRow->ulOrderId > 0)) {
		lpNotify->tab->propIndex.ulPropTag = PR_INSTANCE_KEY;
		lpNotify->tab->propIndex.__union = SOAP_UNION_propValData_bin;
		lpNotify->tab->propIndex.Value.bin = new struct xsd__base64Binary;
		lpNotify->tab->propIndex.Value.bin->__ptr = new unsigned char[sizeof(ULONG)*2];
		lpNotify->tab->propIndex.Value.bin->__size = sizeof(ULONG)*2;

		memcpy(lpNotify->tab->propIndex.Value.bin->__ptr, &lpsChildRow->ulObjId, sizeof(ULONG));
		memcpy(lpNotify->tab->propIndex.Value.bin->__ptr+sizeof(ULONG), &lpsChildRow->ulOrderId, sizeof(ULONG));
	}else {
		lpNotify->tab->propIndex.ulPropTag = PR_NULL;
		lpNotify->tab->propIndex.__union = SOAP_UNION_propValData_ul;
	}

	if(lpsPrevRow && (lpsPrevRow->ulObjId > 0 || lpsPrevRow->ulOrderId > 0))
	{
		lpNotify->tab->propPrior.ulPropTag = PR_INSTANCE_KEY;
		lpNotify->tab->propPrior.__union = SOAP_UNION_propValData_bin;
		lpNotify->tab->propPrior.Value.bin = new struct xsd__base64Binary;
		lpNotify->tab->propPrior.Value.bin->__ptr = new unsigned char[sizeof(ULONG)*2];
		lpNotify->tab->propPrior.Value.bin->__size = sizeof(ULONG)*2;

		memcpy(lpNotify->tab->propPrior.Value.bin->__ptr, &lpsPrevRow->ulObjId, sizeof(ULONG));
		memcpy(lpNotify->tab->propPrior.Value.bin->__ptr+sizeof(ULONG), &lpsPrevRow->ulOrderId, sizeof(ULONG));

	}else {
		lpNotify->tab->propPrior.__union = SOAP_UNION_propValData_ul;
		lpNotify->tab->propPrior.ulPropTag = PR_NULL;
	}
	
	lpNotify->tab->ulObjType = ulObjType;

	if(lpRow) {
		lpNotify->tab->pRow = new struct propValArray;
		lpNotify->tab->pRow->__ptr = lpRow->__ptr;
		lpNotify->tab->pRow->__size = lpRow->__size;
	}

	AddNotification(lpNotify, ulTableId, 0, ulSessionId);

	//Free by lpRow
	if(lpNotify->tab->pRow){
		lpNotify->tab->pRow->__ptr = NULL;
		lpNotify->tab->pRow->__size = 0;
	}

	//Free struct
	FreeNotificationStruct(lpNotify);

	Unlock();

	return hr;
}
Ejemplo n.º 11
0
void CStringz::Refresh() {
	if (mh) {
		Lock();
		UnLock();
	}
}
Ejemplo n.º 12
0
STDMETHODIMP CGfxTitanII::CreateSurfaces()
{
	HRESULT hr;
	int i;
	DWORD height,width,buffers,hpad,wpad;

	if(m_dwWidth==0 || m_dwHeight==0 /*|| m_hwnd==0*/)
		return E_FAIL;
	if(m_pVr && m_dwWidth==m_dwOldWidth && m_dwHeight==m_dwOldHeight && m_hwnd==m_Oldhwnd)
		return S_OK;

	if(m_bBSMMode == TRUE)
	{
		m_BSM_Init(m_pVr);
	}

	m_dwOldWidth = m_dwWidth;
	m_dwOldHeight = m_dwHeight;

	m_Oldhwnd = m_hwnd;

	//VR_LAYER_OVERLAY:VR_LAYER_PRIMARY
#if defined(SIRF_NOTEBOOK	) || defined(RTK_TITAN_II)
	hr = m_CVR_SetRenderLayer(m_pVr, VR_LAYER_PRIMARY,0.0f);
#else
	hr = m_CVR_SetRenderLayer(m_pVr, VR_LAYER_OVERLAY,0.0f);
#endif
	//[optional] it will change settings in renderer. 
	//TITAN_BITMAP_ORDER: this is the set the bitmap data order 
	//inputted. 
	//pInBuf: the pointer of input data block  
	//data_size: the size of input data block 
	//pOutBuf: the pointer of output data block. 
	//CVR_EscapeCtrl(m_pVr, TITAN_BITMAP_ORDER, pInBuf, data_size, 	pOutBuf); 
	  
	//[optional] it will set the display mode 
	//mode: the display mode to be set 
	hr = m_CVR_SetDisplayMode(m_pVr, m_dispmode); 
  
	//if(m_dwHeight<480)
	//	m_sy = 2;		// double the height!
	//else
		m_sy = 1;
	//if(m_bUseDSP)
	//{	// DSP renderer
	//	alignx = 16;	// 16 is required (spec doesn't specify)
	//	aligny = 4;
	//	hr = CVR_EscapeCtrl(m_pVr,TITAN_DSP_RENDERER,0,0,0);
	//	if(hr!=VR_OK)
	//	{
	//		// do something here.
	//	}
	//}
	//else
	{
//		alignx = 2; /* actually 2, but we prefer this for our averaging ops */
//		aligny = 2;

	}
	buffers = m_dwMaxBuffers+1;
	wpad = ~(m_dwWidth-1) & (ALIGNX-1);
	width = m_dwWidth+wpad;
	height = m_dwHeight*m_sy;
	hpad = ~(height-1) & (ALIGNY-1);
	height = height+hpad;
	//width = width + (width&0xf);
	//height = height + (height&0xf);
	//SetDisplayMode(1);


	m_iYPitch = width;
	m_iUVPitch = m_iYPitch>>1;
	//hr = CVR_SetVideoFormat(m_pVr, 0, width, height, 0, &m_iYPitch, &m_iUVPitch);
		//Set the Video parameters. 
	//VR_FORMAT_I420: set the input data format as I420  
	//width: width of source frame 
	//height: height of source frame 
	//rect: the source rect 
	//LumPitch: pitch of lum 
	//ChromPitch: pitch of chrom 

	width = ROOF(m_dwWidth, ALIGNX);

	if(m_bBSMMode == TRUE)
		height = ROOF(m_dwHeight, ALIGNY);
	else
		height = m_dwHeight;

	VR_SRCRECT rect;
	rect.left= 0;
	rect.right = m_dwWidth;
	rect.top = 0;
	rect.bottom= m_dwHeight;

	hr = m_CVR_SetVideoFormat(m_pVr, VR_FORMAT_I420, width, height, &rect,  &m_iYPitch, &m_iUVPitch);

	SetDeinterlaceMode(m_deinterlace_mode);

    if(!m_bBSMMode)
    {
	    m_pBackBuffer = new LPVR_FRAME_SURFACE[buffers];
	    ZeroMemory(m_pBackBuffer,sizeof(m_pBackBuffer[0])*buffers);

	    for(i=0;i<(signed)buffers;i++)
	    {
		    hr = m_CVR_CreateSurface(m_pVr,&m_pBackBuffer[i],1);
		    if(hr!=VR_OK)
			    break;
	    }
	    if(i==0)
	    {
		    delete[] m_pBackBuffer;
		    m_pBackBuffer = 0;
		    //CVR_DeleteVideoRender(m_pVr);
		    //m_pVr = 0;
		    return E_FAIL;
	    }

	    if(i>1)
	    {		// make sure we have at least one surface available for background scratch, otherwise hang.
		    m_CVR_DestroySurface(m_pVr,m_pBackBuffer[--i]);
		    ZeroMemory(&m_pBackBuffer[i],sizeof(m_pBackBuffer[i]));
	    }

	    m_dwBackBuffers = i;

	    // clear out buffers
	    unsigned char *pb;
	    LONG lstride;
	    int xl,xr,yt,yb,ht;

	    yt = hpad>>1&~1;
	    yb = hpad - yt;
	    xl = 0; // (wpad>>1)&~3;
	    xr = wpad -xl;
	    ht = m_dwHeight*m_sy;

	    for(i=0;i<(signed)m_dwBackBuffers;i++)
	    {
		    if(SUCCEEDED(Lock(i, (LPVOID *)&pb, &lstride, 0)))
		    {
			    clearoutsiderect(pb,m_dwWidth,ht,lstride,0,xl,xr,yt,yb);
			    clearoutsiderect(pb+height*width,m_dwWidth>>1,ht>>1,lstride>>1,128,xl>>1,xr>>1,yt>>1,yb>>1);
			    clearoutsiderect(pb+height*width+(height*width>>2),m_dwWidth>>1,ht>>1,lstride>>1,128,xl>>1,xr>>1,yt>>1,yb>>1);
			    Unlock(i);
		    }
	    }
Ejemplo n.º 13
0
TInt DPowerManager::PowerDown()
	{ // called by ExecHandler 
	__KTRACE_OPT(KPOWER,Kern::Printf(">PowerManger::PowerDown(0x%x) Enter", iPowerController->iTargetState));
	__ASSERT_CRITICAL;

	Lock();


	if (iPowerController->iTargetState == EPwActive)
		{
		Unlock();
		return KErrNotReady;
		}

    __PM_ASSERT(iHandlers);
	NFastSemaphore shutdownSem(0);
	NTimer ntimer;
	TDfc dfc(ShutDownTimeoutFn, &shutdownSem);
#ifndef _DEBUG_POWER	
	iPendingShutdownCount = 0;
#endif	
	DPowerHandler* ph = iHandlers;
	//Power down in reverse order of handle registration.
	do
		{
#ifdef _DEBUG_POWER
		__PM_ASSERT(!(ph->iStatus & DPowerHandler::EDone));
#endif
		ph->iSem = &shutdownSem; 
		ph->PowerDown(iPowerController->iTargetState);
#ifndef _DEBUG_POWER		
		iPendingShutdownCount++; 
#else
		if(iPslShutdownTimeoutMs>0)
			{
		    // Fire shut down timeout timer			
			ntimer.OneShot(iPslShutdownTimeoutMs, dfc);
			}

		NKern::FSWait(&shutdownSem);	// power down drivers one after another to simplify debug
		__e32_atomic_and_ord32(&(ph->iStatus), ~DPowerHandler::EDone);

		// timeout condition
		if(iPslShutdownTimeoutMs>0 && ph->iSem)
			{
			__e32_atomic_store_ord_ptr(&ph->iSem, 0);
			}
		ntimer.Cancel();
#endif		
		ph = ph->iPrev;
		}while(ph != iHandlers);

#ifndef _DEBUG_POWER
	if(iPslShutdownTimeoutMs>0)
		{
		// Fire shut down timeout timer
		ntimer.OneShot(iPslShutdownTimeoutMs, dfc);
		}

	ph = iHandlers;
	do
		{
		NKern::FSWait(&shutdownSem);
		if(__e32_atomic_load_acq32(&iPendingShutdownCount)==ESHUTDOWN_TIMEOUT)
			{
			iPendingShutdownCount = 0;
			NKern::Lock();
			shutdownSem.Reset(); // iPendingShutdownCount could be altered while ShutDownTimeoutFn is running
		       			     // reset it to make sure shutdownSem is completely clean.	
			NKern::Unlock();
			break;
			}
		__e32_atomic_add_ord32(&iPendingShutdownCount, (TUint)(~0x0)); // iPendingShutDownCount--;
		ph = ph->iPrev;
		}while(ph != iHandlers);

	ntimer.Cancel();
	
#endif

	TTickQ::Wait();

	iPowerController->PowerDown(K::SecondQ->WakeupTime());
	__PM_ASSERT(iPowerController->iTargetState != EPwOff);
	iPowerController->iTargetState = EPwActive;

	K::SecondQ->WakeUp();
	TTickQ::Signal();

	NFastSemaphore powerupSem(0);

	ph = iHandlers->iNext;
	//Power up in same order of handle registration.
	do
		{
#ifdef _DEBUG_POWER
		__PM_ASSERT(!(ph->iStatus & DPowerHandler::EDone));
#endif
		ph->iSem = &powerupSem;
		ph->PowerUp();
#ifdef _DEBUG_POWER
		NKern::FSWait(&powerupSem);	// power down drivers one after another to simplify debug
		__PM_ASSERT(!ph->iSem);
		__PM_ASSERT(ph->iStatus & DPowerHandler::EDone);
		ph->iStatus &= ~DPowerHandler::EDone;
#endif
		ph = ph->iNext;
		}while(ph != iHandlers->iNext);

#ifndef _DEBUG_POWER
	ph = iHandlers->iNext;
	do
		{
		NKern::FSWait(&powerupSem);
		ph = ph->iNext;
		}while(ph != iHandlers->iNext);
#endif

	// complete wakeup notification request if any
	NotifyWakeupEvent(KErrNone); 

	Unlock();

	__KTRACE_OPT(KPOWER,Kern::Printf("<PowerManger::PowerDown() Leave"));

	return KErrNone;
	}	
Ejemplo n.º 14
0
/***
	Open a file. If the file exists it is openned "rb+" else
	it is openned "wb+".
	Parameters:
		- szNameFile: Name of file (just the name or full path)
		- szMode
		- iShFlag
	Return:
		E_NOTOPEN or OK (errno e' setado)
***/
int
C_File::Open( const char *szNameFile, const char *szModePar, int iShFlagPar, BOOL bWait )
{
	C_FileCritSect	cCS0( this, CRITSECT0 );
	int		iMode;
	DWORD	dwShMode;
	DWORD	dwCreateMode;

	if( (_bIs32s && iFile != -1) || (!_bIs32s && hFile != INVALID_HANDLE_VALUE) ){
		return( !OK );
	}
	strcpy( szFileName, szNameFile ? szNameFile : "" );
	strcpy( szMode, szModePar ? szModePar : "" );
	iShFlag = iShFlagPar;
	do{
		iMode = Mode16( szModePar );
		dwAccess = Mode( szModePar );
		dwShMode = ShMode( iShFlagPar );
		dwCreateMode = szModePar ? CreateMode( szModePar ) : Exist( szFileName ) ? OPEN_EXISTING : CREATE_ALWAYS;
		if( _bIs32s ){
			if( szModePar != NULL ){
				if( iMode & O_CREAT ){
					iFile = sopen( szNameFile, iMode, iShFlagPar, S_IREAD | S_IWRITE );
				} else {
					iFile = sopen( szNameFile, iMode, iShFlagPar );
				}
			} else {
				if( Exist( szNameFile ) ){
					iFile = sopen( szNameFile, O_BINARY | O_RDWR, iShFlagPar );
				} else {
					iFile = sopen( szNameFile, O_BINARY | O_RDWR | O_CREAT, iShFlagPar, S_IREAD | S_IWRITE );
				}
			}
		} else {
			saSecurity.nLength = sizeof( SECURITY_ATTRIBUTES );
			saSecurity.lpSecurityDescriptor = NULL;
			saSecurity.bInheritHandle = TRUE;
			hFile = CreateFile( szNameFile, dwAccess, dwShMode, &saSecurity, dwCreateMode, 
						(DWORD) (FILE_ATTRIBUTE_ARCHIVE | FILE_FLAG_SEQUENTIAL_SCAN),
						NULL );
		}
		if( (_bIs32s && iFile == -1) || (!_bIs32s && hFile == INVALID_HANDLE_VALUE) ){
			if( _bIs32s ){
				if( errno == EEXIST && (iMode & O_EXCL) ){
					// ************************************************************
					// ATENCAO:
					// ************************************************************
					// nao tentar fechar outro arquivo para re-abrir este se 
					// errno == EEXIST && (iMode & O_EXCL)
					// ************************************************************
					iFile = -1;
					return( !OK );
				}
				if( errno == EACCES && bWait ){
					// o arquivo nao foi aberto porque estah sendo
					// usado por outro processo em modo exclusivo.
					// esperar um pouco e tentar novamente
					Sleep( 1000 );	// 1 segundo
					hFile = INVALID_HANDLE_VALUE;
					iFile = -1;

					// antes de continuar o loop, sair e entrar
					// novamente em regiao critica, para possibilitar
					// outros threads rodarem
					cCS0.LeaveCriticalSection();
					cCS0.EnterCriticalSection();
					continue;
				}
				if( errno != EMFILE ){
					iFile = -1;
					return( !OK );
				}
			} else {
				if( GetLastError() == ERROR_ALREADY_EXISTS && (dwCreateMode == CREATE_NEW) ){
					// ************************************************************
					// ATENCAO:
					// ************************************************************
					// nao tentar fechar outro arquivo para reabrir este se 
					// GetLastError() == ERROR_ALREADY_EXISTS && (dwCreateMode == CREATE_NEW)
					// ************************************************************
					return( !OK );
				}
				if( GetLastError() == ERROR_SHARING_VIOLATION && bWait ){
					// o arquivo nao foi aberto porque estah sendo
					// usado por outro processo em modo exclusivo.
					// esperar um pouco e tentar novamente
					Sleep( 1000 );	// 1 segundo
					hFile = INVALID_HANDLE_VALUE;
					iFile = -1;

					// antes de continuar o loop, sair e entrar
					// novamente em regiao critica, para possibilitar
					// outros threads rodarem
					cCS0.LeaveCriticalSection();
					cCS0.EnterCriticalSection();
					continue;
				}
				if( GetLastError() != ERROR_TOO_MANY_OPEN_FILES ){
#ifdef _USE_PRINTF_
					Printf( "C_File: Deu um erro doidao no Open." );
					Printf( "C_File: Fudeu em <%s>", szNameFile );
#endif
					hFile = INVALID_HANDLE_VALUE;
					iFile = -1;
					return( !OK );
				}
			}
#ifdef _USE_PRINTF_
			Printf( "C_File: Muitos arquivos abertos. Vou terminar." );
#endif
			return( !OK );
		}
	} while ( (_bIs32s && iFile == -1) || (!_bIs32s && hFile == INVALID_HANDLE_VALUE) );
	if( this == _xFile ){
		Seek( 0, SEEK_SET );
		char	szCaca[ 50 ];
		sprintf( szCaca, "%d", ++_iNumXDat );
		Write( szCaca, strlen( szCaca ) );
		Seek( 0, SEEK_SET );
		Lock( strlen( szCaca ) );
#ifdef _USE_PRINTF_
		Printf( "C_File: Abri o _xFile****************************" );
#endif
	}
	if( strstr( szMode, "a" ) != NULL ){
		Seek( 0L, SEEK_END );
	}
	Hash();
	_iNumOpenFiles++;
#ifdef _USE_PRINTF_
	Printf( "C_File: Abri o arquivo <%d> (nome = <%s> - handle = <%d>)", _iNumOpenFiles, szNameFile ? szNameFile : "NULL", _bIs32s ? iFile : (int) hFile );
#endif

	// MMF: apenas se nao for 32s e se iHeadSize estiver setado para um valor maior que 0
	if( !_bIs32s && iHeadSize > 0 ){
		// pegar o tamanho da janela no .ini
		char	szFullIniName[ MAXPATH ];

		GetAppFullPath( szFullIniName, MAXPATH );


		iMMFWinSize = GetPrivateProfileInt( CONFIG_SESSION, WINDOWSIZE_KEY, 
											WINDOWSIZE_DEFAULT, szFullIniName );

		// se o tamanho da janela for <= 0, significa que o usuario nao quer usar MMF
		hMMF = NULL;
		if( iMMFWinSize > 0 ){
			hMMF = CreateFileMapping( hFile, NULL,
				(dwAccess & GENERIC_WRITE) ? PAGE_READWRITE : PAGE_READONLY,
				0, 0, NULL );
		}
		pHeadView = NULL;
		pWinView = NULL;
		iWinNum = 0;
		iSeekWin = 0;
	}

	bRealLock = _bStaticRealLock;

	return( OK );
}
Ejemplo n.º 15
0
void cRoot::QueueExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallback & a_Output)
{
	// Put the command into a queue (Alleviates FS #363):
	cCSLock Lock(m_CSPendingCommands);
	m_PendingCommands.emplace_back(a_Cmd, &a_Output);
}
Ejemplo n.º 16
0
status_t
OHCI::CancelQueuedTransfers(Pipe *pipe, bool force)
{
	if (pipe->Type() & USB_OBJECT_ISO_PIPE)
		return _CancelQueuedIsochronousTransfers(pipe, force);

	if (!Lock())
		return B_ERROR;

	struct transfer_entry {
		Transfer *			transfer;
		transfer_entry *	next;
	};

	transfer_entry *list = NULL;
	transfer_data *current = fFirstTransfer;
	while (current) {
		if (current->transfer && current->transfer->TransferPipe() == pipe) {
			// Check if the skip bit is already set
			if (!(current->endpoint->flags & OHCI_ENDPOINT_SKIP)) {
				current->endpoint->flags |= OHCI_ENDPOINT_SKIP;
				// In case the controller is processing
				// this endpoint, wait for it to finish
				snooze(1000);
			}

			// Clear the endpoint
			current->endpoint->head_physical_descriptor
				= current->endpoint->tail_physical_descriptor;

			if (!force) {
				// If the transfer is canceled by force, the one causing the
				// cancel is probably not the one who initiated the transfer
				// and the callback is likely not safe anymore
				transfer_entry *entry
					= (transfer_entry *)malloc(sizeof(transfer_entry));
				if (entry != NULL) {
					entry->transfer = current->transfer;
					current->transfer = NULL;
					entry->next = list;
					list = entry;
				}
			}
			current->canceled = true;
		}
		current = current->link;
	}

	Unlock();

	while (list != NULL) {
		transfer_entry *next = list->next;
		list->transfer->Finished(B_CANCELED, 0);
		delete list->transfer;
		free(list);
		list = next;
	}

	// wait for any transfers that might have made it before canceling
	while (fProcessingPipe == pipe)
		snooze(1000);

	// notify the finisher so it can clean up the canceled transfers
	release_sem_etc(fFinishTransfersSem, 1, B_DO_NOT_RESCHEDULE);
	return B_OK;
}
Ejemplo n.º 17
0
void cRoot::QueueExecuteConsoleCommand(const AString & a_Cmd)
{
	// Put the command into a queue (Alleviates FS #363):
	cCSLock Lock(m_CSPendingCommands);
	m_PendingCommands.push_back(cCommand(a_Cmd, new cLogCommandDeleteSelfOutputCallback));
}
Ejemplo n.º 18
0
void
OHCI::_FinishTransfers()
{
	while (!fStopFinishThread) {
		if (acquire_sem(fFinishTransfersSem) < B_OK)
			continue;

		// eat up sems that have been released by multiple interrupts
		int32 semCount = 0;
		get_sem_count(fFinishTransfersSem, &semCount);
		if (semCount > 0)
			acquire_sem_etc(fFinishTransfersSem, semCount, B_RELATIVE_TIMEOUT, 0);

		if (!Lock())
			continue;

		TRACE("finishing transfers (first transfer: %p; last"
			" transfer: %p)\n", fFirstTransfer, fLastTransfer);
		transfer_data *lastTransfer = NULL;
		transfer_data *transfer = fFirstTransfer;
		Unlock();

		while (transfer) {
			bool transferDone = false;
			ohci_general_td *descriptor = transfer->first_descriptor;
			ohci_endpoint_descriptor *endpoint = transfer->endpoint;
			status_t callbackStatus = B_OK;

			MutexLocker endpointLocker(endpoint->lock);

			if ((endpoint->head_physical_descriptor & OHCI_ENDPOINT_HEAD_MASK)
				!= endpoint->tail_physical_descriptor) {
				// there are still active transfers on this endpoint, we need
				// to wait for all of them to complete, otherwise we'd read
				// a potentially bogus data toggle value below
				TRACE("endpoint %p still has active tds\n", endpoint);
				lastTransfer = transfer;
				transfer = transfer->link;
				continue;
			}

			endpointLocker.Unlock();

			while (descriptor && !transfer->canceled) {
				uint32 status = OHCI_TD_GET_CONDITION_CODE(descriptor->flags);
				if (status == OHCI_TD_CONDITION_NOT_ACCESSED) {
					// td is still active
					TRACE("td %p still active\n", descriptor);
					break;
				}

				if (status != OHCI_TD_CONDITION_NO_ERROR) {
					// an error occured, but we must ensure that the td
					// was actually done
					if (endpoint->head_physical_descriptor & OHCI_ENDPOINT_HALTED) {
						// the endpoint is halted, this guaratees us that this
						// descriptor has passed (we don't know if the endpoint
						// was halted because of this td, but we do not need
						// to know, as when it was halted by another td this
						// still ensures that this td was handled before).
						TRACE_ERROR("td error: 0x%08lx\n", status);

						switch (status) {
							case OHCI_TD_CONDITION_CRC_ERROR:
							case OHCI_TD_CONDITION_BIT_STUFFING:
							case OHCI_TD_CONDITION_TOGGLE_MISMATCH:
								callbackStatus = B_DEV_CRC_ERROR;
								break;

							case OHCI_TD_CONDITION_STALL:
								callbackStatus = B_DEV_STALLED;
								break;

							case OHCI_TD_CONDITION_NO_RESPONSE:
								callbackStatus = B_TIMED_OUT;
								break;

							case OHCI_TD_CONDITION_PID_CHECK_FAILURE:
								callbackStatus = B_DEV_BAD_PID;
								break;

							case OHCI_TD_CONDITION_UNEXPECTED_PID:
								callbackStatus = B_DEV_UNEXPECTED_PID;
								break;

							case OHCI_TD_CONDITION_DATA_OVERRUN:
								callbackStatus = B_DEV_DATA_OVERRUN;
								break;

							case OHCI_TD_CONDITION_DATA_UNDERRUN:
								callbackStatus = B_DEV_DATA_UNDERRUN;
								break;

							case OHCI_TD_CONDITION_BUFFER_OVERRUN:
								callbackStatus = B_DEV_FIFO_OVERRUN;
								break;

							case OHCI_TD_CONDITION_BUFFER_UNDERRUN:
								callbackStatus = B_DEV_FIFO_UNDERRUN;
								break;

							default:
								callbackStatus = B_ERROR;
								break;
						}

						transferDone = true;
						break;
					} else {
						// an error occured but the endpoint is not halted so
						// the td is in fact still active
						TRACE("td %p active with error\n", descriptor);
						break;
					}
				}

				// the td has completed without an error
				TRACE("td %p done\n", descriptor);

				if (descriptor == transfer->last_descriptor
					|| descriptor->buffer_physical != 0) {
					// this is the last td of the transfer or a short packet
					callbackStatus = B_OK;
					transferDone = true;
					break;
				}

				descriptor
					= (ohci_general_td *)descriptor->next_logical_descriptor;
			}

			if (transfer->canceled) {
				// when a transfer is canceled, all transfers to that endpoint
				// are canceled by setting the head pointer to the tail pointer
				// which causes all of the tds to become "free" (as they are
				// inaccessible and not accessed anymore (as setting the head
				// pointer required disabling the endpoint))
				callbackStatus = B_OK;
				transferDone = true;
			}

			if (!transferDone) {
				lastTransfer = transfer;
				transfer = transfer->link;
				continue;
			}

			// remove the transfer from the list first so we are sure
			// it doesn't get canceled while we still process it
			transfer_data *next = transfer->link;
			if (Lock()) {
				if (lastTransfer)
					lastTransfer->link = transfer->link;

				if (transfer == fFirstTransfer)
					fFirstTransfer = transfer->link;
				if (transfer == fLastTransfer)
					fLastTransfer = lastTransfer;

				// store the currently processing pipe here so we can wait
				// in cancel if we are processing something on the target pipe
				if (!transfer->canceled)
					fProcessingPipe = transfer->transfer->TransferPipe();

				transfer->link = NULL;
				Unlock();
			}

			// break the descriptor chain on the last descriptor
			transfer->last_descriptor->next_logical_descriptor = NULL;
			TRACE("transfer %p done with status 0x%08lx\n",
				transfer, callbackStatus);

			// if canceled the callback has already been called
			if (!transfer->canceled) {
				size_t actualLength = 0;
				if (callbackStatus == B_OK) {
					if (transfer->data_descriptor && transfer->incoming) {
						// data to read out
						iovec *vector = transfer->transfer->Vector();
						size_t vectorCount = transfer->transfer->VectorCount();

						transfer->transfer->PrepareKernelAccess();
						actualLength = _ReadDescriptorChain(
							transfer->data_descriptor,
							vector, vectorCount);
					} else if (transfer->data_descriptor) {
						// read the actual length that was sent
						actualLength = _ReadActualLength(
							transfer->data_descriptor);
					}

					// get the last data toggle and store it for next time
					transfer->transfer->TransferPipe()->SetDataToggle(
						(endpoint->head_physical_descriptor
							& OHCI_ENDPOINT_TOGGLE_CARRY) != 0);

					if (transfer->transfer->IsFragmented()) {
						// this transfer may still have data left
						TRACE("advancing fragmented transfer\n");
						transfer->transfer->AdvanceByFragment(actualLength);
						if (transfer->transfer->VectorLength() > 0) {
							TRACE("still %ld bytes left on transfer\n",
								transfer->transfer->VectorLength());
							// TODO actually resubmit the transfer
						}

						// the transfer is done, but we already set the
						// actualLength with AdvanceByFragment()
						actualLength = 0;
					}
				}

				transfer->transfer->Finished(callbackStatus, actualLength);
				fProcessingPipe = NULL;
			}

			if (callbackStatus != B_OK) {
				// remove the transfer and make the head pointer valid again
				// (including clearing the halt state)
				_RemoveTransferFromEndpoint(transfer);
			}

			// free the descriptors
			_FreeDescriptorChain(transfer->first_descriptor);

			delete transfer->transfer;
			delete transfer;
			transfer = next;
		}
	}
}
Ejemplo n.º 19
0
int main (void)
{
  IPTR args[ARG_NUM] = { (IPTR) NULL, (IPTR) NULL, (IPTR) NULL, FALSE, FALSE};
  struct RDArgs *rda;
  ULONG error = 0;

  locale = OpenLocale(NULL);
  if (!locale)
  {
    PutStr("Could not open locale!\n");
    return -1;
  }

  rda = ReadArgs(TEMPLATE, args, NULL);
  if (rda)
  {
    BPTR lock_in;
    lock_in = Lock((STRPTR)args[ARG_FROM], ACCESS_READ);

    if (lock_in)
    {
       BPTR file_out = Open((STRPTR)args[ARG_TO], MODE_NEWFILE);

       if (NULL != file_out)
       {
          struct FileInfoBlock fib;
          UBYTE * data = NULL;
          BOOL success = Examine(lock_in, &fib);

          /*
          ** Read  the input file into memory
          */
          if (fib.fib_Size && DOSTRUE == success)
            data = AllocVec(fib.fib_Size, MEMF_ANY);

          if (data)
          {
            ULONG read = Read(lock_in, data, fib.fib_Size);

            if (-1 != read)
            {
              struct sorted_data * sd;
              sd = sort(data, 
                        fib.fib_Size, 
                        (STRPTR)args[ARG_COLSTART],
                        (BOOL)args[ARG_CASE],
                        (BOOL)args[ARG_NUMERIC]);

              error = write_data(sd, file_out);
            }
            FreeVec(data);
          }/*  if (data) */

          Close(file_out);  
       } /* if (file_out) */
       UnLock(lock_in);
    } /* if (lock_in) */
    FreeArgs(rda);
  }
  else
    error=RETURN_FAIL;
    
  if (error)
    PrintFault(IoErr(), "Sort");
  
  return error; 
}
Ejemplo n.º 20
0
KeymapWindow::KeymapWindow()
	:
	BWindow(BRect(80, 50, 880, 380), B_TRANSLATE_SYSTEM_NAME("Keymap"),
		B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS)
{
	SetLayout(new BGroupLayout(B_VERTICAL));

	fKeyboardLayoutView = new KeyboardLayoutView("layout");
	fKeyboardLayoutView->SetKeymap(&fCurrentMap);

	fTextControl = new BTextControl(B_TRANSLATE("Sample and clipboard:"),
		"", NULL);

	fSwitchShortcutsButton = new BButton("switch", "",
		new BMessage(kMsgSwitchShortcuts));

	fRevertButton = new BButton("revertButton", B_TRANSLATE("Revert"),
		new BMessage(kMsgRevertKeymap));

	// controls pane
	AddChild(BGroupLayoutBuilder(B_VERTICAL)
		.Add(_CreateMenu())
		.Add(BGroupLayoutBuilder(B_HORIZONTAL, 10)
			.Add(_CreateMapLists(), 0.25)
			.Add(BGroupLayoutBuilder(B_VERTICAL, 10)
				.Add(fKeyboardLayoutView)
				//.Add(new BStringView("text label", "Sample and clipboard:"))
				.Add(BGroupLayoutBuilder(B_HORIZONTAL, 10)
					.Add(_CreateDeadKeyMenuField(), 0.0)
					.AddGlue()
					.Add(fSwitchShortcutsButton))
				.Add(fTextControl)
				.AddGlue(0.0)
				.Add(BGroupLayoutBuilder(B_HORIZONTAL, 10)
					.AddGlue(0.0)
					.Add(fRevertButton)))
			.SetInsets(10, 10, 10, 10)));

	fKeyboardLayoutView->SetTarget(fTextControl->TextView());
	fTextControl->MakeFocus();

	// Make sure the user keymap directory exists
	BPath path;
	find_directory(B_USER_SETTINGS_DIRECTORY, &path);
	path.Append("Keymap");

	entry_ref ref;
	get_ref_for_path(path.Path(), &ref);

	BDirectory userKeymapsDir(&ref);
	if (userKeymapsDir.InitCheck() != B_OK)
		create_directory(path.Path(), S_IRWXU | S_IRWXG | S_IRWXO);

	BMessenger messenger(this);
	fOpenPanel = new BFilePanel(B_OPEN_PANEL, &messenger, &ref,
		B_FILE_NODE, false, NULL);
	fSavePanel = new BFilePanel(B_SAVE_PANEL, &messenger, &ref,
		B_FILE_NODE, false, NULL);

	BRect windowFrame;
	BString keyboardLayout;
	_LoadSettings(windowFrame, keyboardLayout);
	_SetKeyboardLayout(keyboardLayout.String());

	ResizeTo(windowFrame.Width(), windowFrame.Height());
	MoveTo(windowFrame.LeftTop());

	// TODO: this might be a bug in the interface kit, but scrolling to
	// selection does not correctly work unless the window is shown.
	Show();
	Lock();

	// Try and find the current map name in the two list views (if the name
	// was read at all)
	_SelectCurrentMap();

	KeymapListItem* current
		= static_cast<KeymapListItem*>(fUserListView->FirstItem());

	fCurrentMap.Load(current->EntryRef());
	fPreviousMap = fCurrentMap;
	fAppliedMap = fCurrentMap;
	fCurrentMap.SetTarget(this, new BMessage(kMsgKeymapUpdated));

	_UpdateButtons();

	_UpdateDeadKeyMenu();
	_UpdateSwitchShortcutButton();

	Unlock();
}
Ejemplo n.º 21
0
//-----------------------------------------------------------------------------
// Purpose: Locks the button. If locked, the button will play the locked sound
//			when the player tries to use it.
//-----------------------------------------------------------------------------
void CBaseButton::InputLock( inputdata_t &inputdata )
{
	Lock();
}
Ejemplo n.º 22
0
bool ServerSideScripting::EvaluatePage( QTextStream *pOutStream, const QString &sFileName )
{
    try
    {
        bool       bFound( false     );
        ScriptInfo *pInfo = NULL;

        // ------------------------------------------------------------------
        // See if page has already been loaded
        // ------------------------------------------------------------------

        Lock();

        if ( (bFound = m_mapScripts.contains( sFileName )) == true )
            pInfo = m_mapScripts[ sFileName ];

        Unlock();

        // ------------------------------------------------------------------
        // Load Script File and Create Function
        // ------------------------------------------------------------------

        QFileInfo  fileInfo ( sFileName );
        QDateTime  dtLastModified = fileInfo.lastModified();

        if ((pInfo == NULL) || (pInfo->m_dtTimeStamp != dtLastModified ))
        {
            QString      sCode = CreateMethodFromFile( sFileName );

            QScriptValue func  = m_engine.evaluate( sCode, sFileName );

            if ( m_engine.hasUncaughtException() )
            {
                VERBOSE( VB_IMPORTANT, QString( "Error Loading QSP File: %1 - (%2)%3" )
                                          .arg( sFileName )
                                          .arg( m_engine.uncaughtExceptionLineNumber() )
                                          .arg( m_engine.uncaughtException().toString() ));

                return false;
            }

            if (pInfo != NULL)
            {
                pInfo->m_oFunc       = func;
                pInfo->m_dtTimeStamp = dtLastModified;
            }
            else
            {
                pInfo = new ScriptInfo( func, dtLastModified );
                Lock();
                m_mapScripts[ sFileName ] = pInfo;
                Unlock();
            }
        }

        // ------------------------------------------------------------------
        // Execute function to render output
        // ------------------------------------------------------------------

        OutputStream outStream( pOutStream );

        QScriptValueList args;
        args << m_engine.newQObject( &outStream );

        pInfo->m_oFunc.call( QScriptValue(), args );

        if (m_engine.hasUncaughtException())
        {
            VERBOSE( VB_IMPORTANT, QString( "Error calling QSP File: %1 - %2" )
                                      .arg( sFileName )
                                      .arg( m_engine.uncaughtException().toString() ));
            return false;
        }

    }
    catch( ... )
    {
        VERBOSE( VB_IMPORTANT, QString( "Exception while evaluating QSP File: %1" )
                                  .arg( sFileName ));

        return false;
    }

    return true;
}
Ejemplo n.º 23
0
SparseVector *StructuredSVM::GetCurrentWeights(bool lock) {
  if(lock) Lock();
  SparseVector *retval = sum_w->mult_scalar(sum_w_scale ? 1.0/(sum_w_scale) : 0, NULL).ptr();
  if(lock) Unlock();
  return retval;
}
Ejemplo n.º 24
0
HRESULT CMSPThread::Stop()
/*++

Routine Description:

    Stop the thread.

Arguments:
    
Return Value:

    HRESULT.

--*/
{
    LOG((MSP_TRACE, "CMSPThread::Stop - enter"));

    CLock Lock(m_CountLock);

    //
    // Complain if we get more Stops than Starts.
    //

    if ( m_iStartCount == 0 )
    {
        LOG((MSP_ERROR, "CMSPThread::Stop - thread already stopped - "
            "exit E_FAIL"));
        return E_FAIL;
    }

    //
    // Decrement the start count. Due to the above check we should
    // never go below zero.
    //

    m_iStartCount--;

    _ASSERTE( m_iStartCount >= 0 );

    //
    // If there have now been just as many stops as starts, it's time to stop
    // the thread.
    //

    if ( m_iStartCount == 0 )
    {
        //
        // Our state should be cleaned up from before.
        //

        _ASSERTE(m_hCommandEvent != NULL);
        _ASSERTE(m_hThread != NULL);

        //
        // Allocate a command queue item which we will pass to the thread.
        //

        COMMAND_QUEUE_ITEM * pItem = new COMMAND_QUEUE_ITEM;

        if ( ! pItem )
        {
            LOG((MSP_ERROR, "CMSPThread::Stop - allocate new queue item"));

            return E_OUTOFMEMORY;
        }

        pItem->node.cmd = STOP;

        //
        // Put the command queue item in the command queue.
        //

        m_QueueLock.Lock();
        InsertTailList(&m_CommandQueue, &(pItem->link));
        m_QueueLock.Unlock();

        //
        // Signal thread to process this stop command.
        //

        if (SignalThreadProc() == 0)
        {
            LOG((MSP_ERROR, "CMSPThread::Stop - can't signal the thread - "
                "exit E_FAIL"));

            return E_FAIL;
        }

        //
        // Wait until the thread stops
        //

        if (::WaitForSingleObject(m_hThread, INFINITE) != WAIT_OBJECT_0)
        {
            LOG((MSP_ERROR, "CMSPThread::Stop - timeout while waiting for the "
                "thread to stop"));
        }

        //
        // Clean up our state.
        //

        ::CloseHandle(m_hCommandEvent);
        ::CloseHandle(m_hThread);

        m_hCommandEvent     = NULL;
        m_hThread           = NULL;

    }

    LOG((MSP_TRACE, "CMSPThread::Stop - exit S_OK"));
    return S_OK;
}
bool FVisualStudioSourceCodeAccessor::OpenVisualStudioFilesInternalViaDTE(const TArray<FileOpenRequest>& Requests, bool& bWasDeferred)
{
	ISourceCodeAccessModule& SourceCodeAccessModule = FModuleManager::LoadModuleChecked<ISourceCodeAccessModule>(TEXT("SourceCodeAccess"));

	// Initialize the com library, if not already by this thread
	if (!FWindowsPlatformMisc::CoInitialize())
	{
		UE_LOG(LogVSAccessor, Error, TEXT( "ERROR - Could not initialize COM library!" ));
		return false;
	}
	
	bool bDefer = false, bSuccess = false;
	TComPtr<EnvDTE::_DTE> DTE;
	const FString SolutionPath = GetSolutionPath();
	switch (AccessVisualStudioViaDTE(DTE, SolutionPath, GetPrioritizedVisualStudioVersions(SolutionPath)))
	{
	case EAccessVisualStudioResult::VSInstanceIsOpen:
		{
			// Set Focus on Visual Studio
			TComPtr<EnvDTE::Window> MainWindow;
			if (SUCCEEDED(DTE->get_MainWindow(&MainWindow)) &&
				SUCCEEDED(MainWindow->Activate()))
			{
				// Get ItemOperations
				TComPtr<EnvDTE::ItemOperations> ItemOperations;
				if (SUCCEEDED(DTE->get_ItemOperations(&ItemOperations)))
				{
					for ( const FileOpenRequest& Request : Requests )
					{
						// Check that the file actually exists first
						if ( !FPaths::FileExists(Request.FullPath) )
						{
							SourceCodeAccessModule.OnOpenFileFailed().Broadcast(Request.FullPath);
							bSuccess |= false;
							continue;
						}

						// Open File
						auto ANSIPath = StringCast<ANSICHAR>(*Request.FullPath);
						FComBSTR COMStrFileName(ANSIPath.Get());
						FComBSTR COMStrKind(EnvDTE::vsViewKindTextView);
						TComPtr<EnvDTE::Window> Window;
						if ( SUCCEEDED(ItemOperations->OpenFile(COMStrFileName, COMStrKind, &Window)) )
						{
							// If we've made it this far - we've opened the file.  it doesn't matter if
							// we successfully get to the line number.  Everything else is gravy.
							bSuccess |= true;

							// Scroll to Line Number
							TComPtr<EnvDTE::Document> Document;
							TComPtr<IDispatch> SelectionDispatch;
							TComPtr<EnvDTE::TextSelection> Selection;
							if ( SUCCEEDED(DTE->get_ActiveDocument(&Document)) &&
								 SUCCEEDED(Document->get_Selection(&SelectionDispatch)) &&
								 SelectionDispatch && SUCCEEDED(SelectionDispatch->QueryInterface(&Selection)) &&
								 SUCCEEDED(Selection->GotoLine(Request.LineNumber, VARIANT_TRUE)) )
							{
								if ( !SUCCEEDED(Selection->MoveToLineAndOffset(Request.LineNumber, Request.ColumnNumber, false)) )
								{
									UE_LOG(LogVSAccessor, Warning, TEXT("Couldn't goto column number '%i' of line '%i' in '%s'"), Request.ColumnNumber, Request.LineNumber, *Request.FullPath);
								}
							}
							else
							{
								UE_LOG(LogVSAccessor, Warning, TEXT("Couldn't goto line number '%i' in '%s'"), Request.LineNumber, *Request.FullPath);
							}
						}
						else
						{
							UE_LOG(LogVSAccessor, Warning, TEXT("Couldn't open file '%s'."), *Request.FullPath);
						}
					}

					VSLaunchFinished( true );
				}
				else
				{
					UE_LOG(LogVSAccessor, Log, TEXT("Couldn't get item operations. Visual Studio may still be initializing."));
					bDefer = true;
				}
			}
			else
			{
				UE_LOG(LogVSAccessor, Warning, TEXT("Couldn't set focus on Visual Studio."));
			}
		}
		break;

	case EAccessVisualStudioResult::VSInstanceIsNotOpen:
		{
			bDefer = true;

			// We can't process until we're in the main thread, if we aren't initially defer until we are
			if ( IsInGameThread() )
			{
				// If we haven't already attempted to launch VS do so now
				if ( !IsVSLaunchInProgress() )
				{
					// If there's no valid instance of VS running, run one if we have it installed
					if ( !RunVisualStudioAndOpenSolution() )
					{
						bDefer = false;
					}
					else
					{
						VSLaunchStarted();
					}
				}
			}
		}
		break;

	case EAccessVisualStudioResult::VSInstanceIsBlocked:
		{
			// VS may be open for the solution we want, but we can't query it right now as it's blocked for some reason
			// Defer this operation so we can try it again later should VS become unblocked
			bDefer = true;
		}
		break;

	default:
		// Do nothing if we failed the VS detection, otherwise we could get stuck in a loop of constantly 
		// trying to open a VS instance since we can't detect that one is already running
		bDefer = false;
		break;
	}
	
	if ( !bSuccess )
	{
		// If we have attempted to launch VS, and it's taken too long, timeout so the user can try again
		if ( IsVSLaunchInProgress() && ( FPlatformTime::Seconds() - VSLaunchTime ) > 300 )
		{
			// We need todo this in case the process died or was kill prior to the code gaining focus of it
			bDefer = false;
			VSLaunchFinished(false);

			// We failed to open the solution and file, so lets just use the platforms default opener.
			for ( const FileOpenRequest& Request : Requests )
			{
				FPlatformProcess::LaunchFileInDefaultExternalApplication(*Request.FullPath);
			}
		}

		// Defer the request until VS is available to take hold of
		if ( bDefer )
		{
			FScopeLock Lock(&DeferredRequestsCriticalSection);
			DeferredRequests.Append(Requests);
		}
		else if ( !bSuccess )
		{
			UE_LOG(LogVSAccessor, Warning, TEXT("Couldn't access Visual Studio"));
		}
	}

	// Uninitialize the com library, if we initialized it above (don't call if S_FALSE)
	FWindowsPlatformMisc::CoUninitialize();

	bWasDeferred = bDefer;
	return bSuccess;
}
Ejemplo n.º 26
0
HRESULT CMSPThread::Start()
/*++

Routine Description:

    Create the thread if it has not already been created. Otherwise, just
    keep track of how many times the thread start was performed so that
    we only stop the thread when all of these have been paired with a stop.

Arguments:
    
Return Value:

    HRESULT.

--*/
{
    LOG((MSP_TRACE, "CMSPThread::Start - enter"));

    CLock Lock(m_CountLock);

    if ( m_iStartCount == 0 )
    {

        _ASSERTE(m_hCommandEvent == NULL);
        _ASSERTE(m_hThread == NULL);


        TCHAR *ptczEventName = NULL;

#if DBG

        //
        // in debug build, use named events
        //

        TCHAR tszEventName[MAX_PATH];

        _stprintf_s(tszEventName,
            _T("CMSPThread_CommandEvent_pid[0x%lx]CMSPThread[%p]"),
            GetCurrentProcessId(), this);

        LOG((MSP_TRACE, "CMSPThread::Start - creating event[%S]", tszEventName));

        ptczEventName = &tszEventName[0];

#endif


        if ((m_hCommandEvent = ::CreateEvent(
            NULL, 
            FALSE,          // flag for manual-reset event
            FALSE,          // initial state is not set.
            ptczEventName   // No name in release builds, named in debug builds
            )) == NULL)
        {
            LOG((MSP_ERROR, "Can't create the command event"));
            return E_FAIL;
        }

        DWORD dwThreadID;
        m_hThread = ::CreateThread(NULL, 0, gfThreadProc, this, 0, &dwThreadID);

        if (m_hThread == NULL)
        {
            LOG((MSP_ERROR, "Can't create thread.  %ld", GetLastError()));
            return E_FAIL;
        }
    }

    m_iStartCount++;

    LOG((MSP_TRACE, "CMSPThread::Start - exit S_OK"));
    return S_OK;
}
Ejemplo n.º 27
0
void cProtocol125::SendPlayerPosition(void)
{
	cCSLock Lock(m_CSPacket);
	LOGD("Ignore send PlayerPos");  // PlayerPos is a C->S packet only now
}
Ejemplo n.º 28
0
int main(int argc, char* argv[]) {
	try {
		// initialize QMiner environment
		TQm::TEnv::Init();

		// create app environment
		Env = TEnv(argc, argv, TNotify::StdNotify);
		Env.SetNoLine(); // making output prettier
		// command line parameters
		Env.PrepArgs("QMiner " + TQm::TEnv::GetVersion(), 0);
		// read the action
		const bool ConfigP = Env.IsArgStr("config");
		const bool CreateP = Env.IsArgStr("create");
		const bool StartP = Env.IsArgStr("start");
		const bool StopP = Env.IsArgStr("stop");
		const bool ReloadP = Env.IsArgStr("reload");
		const bool DebugP = Env.IsArgStr("debug");
		// stop if no action given
		const bool ActionP = (ConfigP || CreateP || StartP || StopP || ReloadP || DebugP);
		// provide basic instruction when no action given
		if (!ActionP) {
			printf("\n");
			printf("Usage: qm ACTION [OPTION]...\n");
			printf("\n");
			printf("Actions: config, create, start, stop, reload, debug\n");			
		} else {
			Env.SetSilent();
		}
		// configuration file
		const TStr ConfFNm = Env.GetIfArgPrefixStr("-conf=", "qm.conf", "Configration file");
		// read config-specific parameters
		if (!Env.IsSilent()) { printf("\nConfiguration parameters:\n"); }
		const int PortN = Env.GetIfArgPrefixInt("-port=", 8080, "Port number");
		const int CacheSizeMB = Env.GetIfArgPrefixInt("-cache=", 1024, "Cache size");
		const bool OverwriteP = Env.IsArgStr("-overwrite", "Overwrite existing configuration file");
		// read create-specific parameters
		if (!Env.IsSilent()) { printf("\nCreate parameters:\n"); }
		const TStr StoreDefFNm = Env.GetIfArgPrefixStr("-def=", "", "Store definition file");
		// read start-specific parameters
		if (!Env.IsSilent()) { printf("\nStart parameters:\n"); }
		const bool RdOnlyP = Env.IsArgStr("-rdonly", "Open database in Read-only mode");
		const bool NoLoopP = Env.IsArgStr("-noserver", "Do not start server after script execution");
		// read stop-specific parameters
		if (!Env.IsSilent()) { printf("\nStop parameters:\n"); }
		const int ReturnCode = Env.GetIfArgPrefixInt("-return=", 0, "Return code");
		// read reload-specific parameters
		if (!Env.IsSilent()) { printf("\nReload parameters:\n"); }
		TStrV ReloadNmV = Env.GetIfArgPrefixStrV("-name=", "Script name");
		// read debug request parameters
		if (!Env.IsSilent()) { printf("\nDebug parameters:\n"); }
		TStr DebugFNm = Env.GetIfArgPrefixStr("-prefix=", "Debug-", "Prefix of debug output files");
		TStrV DebugTaskV = Env.GetIfArgPrefixStrV("-task=", "Debug tasks [indexvoc, index, stores, <store>, <store>_ALL]");
		// read logging specific parameters
		if (!Env.IsSilent()) { printf("\nLogging parameters:\n"); }
		TStr LogFPath = Env.GetIfArgPrefixStr("-log=", "std", "Log Folder (std for standard output, null for silent)");
		const bool Verbose = Env.IsArgStr("-v", "Verbose output (used for debugging)");
		if (!Env.IsSilent()) { printf("\n"); }

		// stop if no action specified
		if (!ActionP) { return 0; }

		// initialize notifier
		TQm::TEnv::InitLogger(Verbose ? 2 : 1, LogFPath, true);
		printf("\n");

		// Create directory structure with basic qm.conf file
		if (ConfigP) {
			// check so we don't overwrite any existing configuration file
			if (TFile::Exists(ConfFNm) && ! OverwriteP) {
				TQm::TEnv::Logger->OnStatus("Configuration file already exists (" + ConfFNm + ")");
				TQm::TEnv::Logger->OnStatus("Use -overwrite to force overwrite");
				return 2;
			}
			// create configuration file
			PJsonVal ConfigVal = TJsonVal::NewObj();
			ConfigVal->AddToObj("port", PortN);
			PJsonVal CacheVal = TJsonVal::NewObj();
			CacheVal->AddToObj("index", CacheSizeMB);
			CacheVal->AddToObj("store", CacheSizeMB);
			ConfigVal->AddToObj("cache", CacheVal);
			// save configuration file
			ConfigVal->SaveStr().SaveTxt(ConfFNm);
			// make folders if needed
			if (!TFile::Exists("db")) { TDir::GenDir("db"); }
			if (!TFile::Exists("src")) { TDir::GenDir("src"); }
			if (!TFile::Exists("src/lib")) { TDir::GenDir("src/lib"); }
			if (!TFile::Exists("sandbox")) { TDir::GenDir("sandbox"); }			
		}

		// parse configuration file
		TQmParam Param(ConfFNm);
		// prepare lock
		TFileLock Lock(Param.LockFNm);

		// Initialize empty database
		if (CreateP) {
			// do not mess with folders with existing running qminer instance
			Lock.Lock();
			// initialize base
			TQm::PGenericBase GenericBase = TQm::TGenericBase::New(Param.DbFPath, 16, 16);
			// initialize stores
			if (!StoreDefFNm.Empty()) {
				PJsonVal StoreDefVal = TJsonVal::GetValFromStr(TStr::LoadTxt(StoreDefFNm));
				GenericBase->CreateSchema(StoreDefVal);
			}
			// remove lock
			Lock.Unlock();
		}

		// Start QMiner engine
		if (StartP) {
			// do not mess with folders with running qminer instance
			Lock.Lock();
			// load database and start the server
			{
				// generate execution ID
				TStr ExecId = TGuid::GenGuid();
				// resolve access type
				TFAccess FAccess = RdOnlyP ? faRdOnly : faUpdate;
				// load base
				TQm::PGenericBase GenericBase = TQm::TGenericBase::Load(Param.DbFPath, FAccess,
					Param.IndexCacheSize, Param.StoreCacheSize, Param.StoreCacheSizes);
				// prepare server functions 
				TSAppSrvFunV SrvFunV;
				// used to stop the server
				SrvFunV.Add(TSASFunExit::New());
				// admin webservices
				TQm::TGenericStoreSrvFun::RegDefFun(GenericBase, SrvFunV);
				// initialize static content serving thingies
				for (int WwwRootN = 0; WwwRootN < Param.WwwRootV.Len(); WwwRootN++) {
					const TStrPr& WwwRoot = Param.WwwRootV[WwwRootN];
					const TStr& UrlPath = WwwRoot.Val1, FPath = WwwRoot.Val2;
					TQm::TEnv::Logger->OnStatusFmt("Registering '%s' at '/%s/'", FPath.CStr(), UrlPath.CStr());
					SrvFunV.Add(TSASFunFPath::New(UrlPath, FPath));
				}
				// initialize javascript contexts
				TVec<TQm::PScript> ScriptV; InitJs(Param, GenericBase, ScriptV);
				// start server
				if (!NoLoopP) {
					// register javascript contexts
					for (int ScriptN = 0; ScriptN < ScriptV.Len(); ScriptN++) {
						// register server function
						ScriptV[ScriptN]->RegSrvFun(SrvFunV);
					}
					// start server
					PWebSrv WebSrv = TSAppSrv::New(Param.PortN, SrvFunV, TQm::TEnv::Logger, true, true);
					// report we started
					TQm::TEnv::Logger->OnStatusFmt("Server started on port %d", Param.PortN);
					// wait for the end
					TLoop::Run();
				}
			}
			// remove lock
			Lock.Unlock();
		}

		// Stop QMiner engine
		if (StopP) {
			ExecUrl(
				TStr::Fmt("http://127.0.0.1:%d/exit?return=%d", Param.PortN, ReturnCode),
				"Server stop procedure initiated", "Error stopping server: ");
		}

		// Reload QMiner script
		if (ReloadP) {
			for (int ReloadNmN = 0; ReloadNmN < ReloadNmV.Len(); ReloadNmN++) {
				TStr ScriptNm = ReloadNmV[ReloadNmN];
				ExecUrl(TStr::Fmt("http://127.0.0.1:%d/%s/admin/reload", Param.PortN, ScriptNm.CStr()), 
					"Initializing reload of script '" + ScriptNm + "'", 
					"Error reloading script '" + ScriptNm + "': ");
			}
		}

		// Debug dumps of database and index
		if (DebugP) {
			// do not mess with folders with existing running qminer instance
			Lock.Lock();
			// load base
			TQm::PGenericBase GenericBase = TQm::TGenericBase::Load(Param.DbFPath, faRdOnly, 
				Param.IndexCacheSize, Param.StoreCacheSize, Param.StoreCacheSizes);
			TQm::PBase Base = GenericBase->Base;
			// go over task lists and prepare outputs
			for (int TaskN = 0; TaskN < DebugTaskV.Len(); TaskN++) {
				TStr Task = DebugTaskV[TaskN];
				if (Task == "index") {
					Base->PrintIndex(DebugFNm + "index.txt", true);
				} else if (Task == "indexvoc") {
					Base->PrintIndexVoc(DebugFNm + "indexvoc.txt");
				} else if (Task == "stores") {
					Base->PrintStores(DebugFNm + "stores.txt");
				} else if (Task.IsSuffix("_ALL")) {
					TStr StoreNm = Task.LeftOfLast('_');
					Base->GetStoreByStoreNm(StoreNm)->PrintAll(Base, DebugFNm + Task + ".txt");
				} else if (Base->IsStoreNm(Task)) {
					Base->GetStoreByStoreNm(Task)->PrintTypes(Base, DebugFNm + Task + ".txt");
				} else {
					TQm::InfoLog("Unkown debug task '" + Task + "'");
				}
			}
			// remove lock
			Lock.Unlock();
		}		
	} catch (const PExcept& Except) {
		// GLib exception
		TQm::ErrorLog("Error: " + Except->GetMsgStr());
		return 2;
	} catch (...) {
		// other exceptions
		TQm::ErrorLog("Unknown error");
		return 1;
	}
	return TQm::TEnv::ReturnCode.Val;
}
Ejemplo n.º 29
0
double CGPSController::GetLongitude() {
	Lock();
	double ret = m_longitude;
	Unlock();
	return ret;
}
Ejemplo n.º 30
0
// Got a notify message from PutDiskObject()
BOOL backdrop_check_notify(
	BackdropInfo *info,
	DOpusNotify *notify,
	Lister *lister)
{
	char *name_buf;
	BOOL disk=0,ret=0;
	struct List *search;
	BackdropObject *object;

	if (!(name_buf=AllocVec(256,0)))
		return 0;

	// Disk icon?
	if (notify->dn_Name[strlen(notify->dn_Name)-1]==':')
	{
		char *ptr;

		// Get volume name
		if ((ptr=strchr(notify->dn_Name,':')))
		{
			stccpy(name_buf,notify->dn_Name,ptr-notify->dn_Name+1);
			disk=1;
		}
	}

	// Otherwise copy name and clear it
	else
	{
		// Get name pointer
		char *name=FilePart(notify->dn_Name);

		// Copy name
		strcpy(name_buf,name);
		*name=0;

		// Strip trailing '/'
		if (*(name-1)=='/') *(name-1)=0;
	}

	// Is this a lister?
	if (lister)
	{
		short len;
		BOOL ok=0;

		// Match length
		len=strlen(notify->dn_Name);

		// See if strings match
		if (strnicmp(lister->cur_buffer->buf_Path,notify->dn_Name,len)==0)
		{
			// Check termination
			if (lister->cur_buffer->buf_Path[len]=='\0') ok=1;

			// / can terminate too
			else
			if (lister->cur_buffer->buf_Path[len]=='/' &&
				lister->cur_buffer->buf_Path[len+1]=='\0') ok=1;
		}

		// Didn't match?
		if (!ok)
		{
			// Free message
			ReplyFreeMsg(notify);	
			FreeVec(name_buf);
			return 0;
		}
	}

	// Lock backdrop list
	lock_listlock(&info->objects,1);

	// See if there's an icon of this name
	search=&info->objects.list;
	while ((object=(BackdropObject *)FindNameI(search,name_buf)))
	{
		// Disk?
		if (object->type==BDO_DISK && disk)
		{
			// Matched
			break;
		}

		// Valid object?
		else
		if (object->type!=BDO_APP_ICON &&
			object->type!=BDO_BAD_DISK &&
			object->path)
		{
			char *path=0;
			BPTR lock;

			// If no lister, get full path of object
			if (!lister && (path=AllocVec(512,0)))
			{
				// Lock path
				if ((lock=Lock(object->path,ACCESS_READ)))
				{
					// Get full path
					DevNameFromLockDopus(lock,path,512);
					UnLock(lock);
				}

				// Failed
				else strcpy(path,object->path);
			}
					
			// Objects in same directory?
			if (lister || stricmp(notify->dn_Name,(path)?path:object->path)==0)
			{
				// Free path
				if (path) FreeVec(path);

				// Matched
				break;
			}

			// Free path
			if (path) FreeVec(path);
		}

		// If this is a lister, there could only be one
		if (lister)
		{
			object=0;
			break;
		}

		// Keep searching from this object
		search=(struct List *)object;
	}

	// Got object?
	if (object)
	{
		ULONG old_image1=0,old_image2=0,new_image1,new_image2,old_flags=0,new_flags;
		BOOL redraw=0;
		struct DiskObject *old;

		// Save old icon
		old=object->icon;
		object->icon=0;

		// Not deleted?
		if (!notify->dn_Flags)
		{
			// Get image checksums
			old_image1=IconCheckSum(old,0);
			old_image2=IconCheckSum(old,1);
			old_flags=GetIconFlags(old);

			// Get new icon
			backdrop_get_icon(info,object,GETICON_CD|GETICON_NO_POS|GETICON_FAIL);
		}

		// No icon now?
		if (!object->icon)
		{
			// Replace old icon
			object->icon=old;

			// Erase old object
			backdrop_erase_icon(info,object,BDSF_RECALC);

			// Is object a disk?
			if (object->type==BDO_DISK)
			{
				// Signal to refresh drives
				IPC_Command(info->ipc,MAINCMD_REFRESH_DRIVES,0,0,0,0);
			}

			// Remove object from list
			backdrop_remove_object(info,object);
		}

		// Ok to keep going
		else
		{
			// Get image checksums
			new_image1=IconCheckSum(object->icon,0);
			new_image2=IconCheckSum(object->icon,1);
			new_flags=GetIconFlags(object->icon);

			// Mask out uninteresting flag bits
			old_flags&=ICONF_BORDER_OFF|ICONF_BORDER_ON|ICONF_NO_LABEL;
			new_flags&=ICONF_BORDER_OFF|ICONF_BORDER_ON|ICONF_NO_LABEL;

			// Need to redraw?
			if (old_image1!=new_image1 ||
				old_image2!=new_image2 ||
				old_flags!=new_flags)
			{
				// Erase old object
				backdrop_erase_icon(info,object,0);
				redraw=1;
			}

			// Free old icon
			if (old)
			{
				// Free icon remapping
				RemapIcon(old,(info->window)?info->window->WScreen:0,1);

				// Free icon
				FreeCachedDiskObject(old);
			}

			// Fix new icon size
			backdrop_get_icon(info,object,GETICON_POS_ONLY|GETICON_SAVE_POS|GETICON_KEEP);

			// Need to get masks?
			if (!backdrop_icon_border(object))
			{
				// Get masks for this icon
				backdrop_get_masks(object);
			}
			
			// Show new icon
			if (redraw) backdrop_render_object(info,object,BRENDERF_CLIP);
		}

		ret=1;
	}

	// Otherwise, got lister?
	else
	if (lister)
	{
		// Tell lister to get icons
		IPC_Command(lister->ipc,LISTER_GET_ICONS,0,0,0,0);
		ret=1;
	}

	// Or, on the desktop?
	else
	if (info->flags&BDIF_MAIN_DESKTOP)
	{
		BPTR lock1,lock2;

		// Lock the desktop folder and the changed directory
		if ((lock1=Lock(environment->env->desktop_location,ACCESS_READ)) &&
			(lock2=Lock(notify->dn_Name,ACCESS_READ)))
		{
			// Same directory?
			if (SameLock(lock1,lock2)==LOCK_SAME)
			{
				// Update the desktop folder
				misc_startup("dopus_desktop_update",MENU_UPDATE_DESKTOP,GUI->window,0,TRUE);
			}

			// Unlock second lock
			UnLock(lock2);
		}

		// Unlock first lock
		UnLock(lock1);
	}

	// Unlock list
	unlock_listlock(&info->objects);

	// Free message
	ReplyFreeMsg(notify);	
	FreeVec(name_buf);
	return ret;
}