示例#1
0
int stream_socket::readv(mutable_buffer const &b)
{
	static const unsigned max_vec_size = 16;
	mutable_buffer::buffer_data_type data = b.get();
	unsigned size=0;
#ifndef BOOSTER_WIN32
	struct iovec vec[max_vec_size];
	for(;size < max_vec_size && size < data.second;size++) {
		vec[size].iov_base = data.first[size].ptr;
		vec[size].iov_len = data.first[size].size;
	}
	for(;;) {
		int ret = ::readv(native(),vec,size);
		if(ret >= 0)
			return ret;
		if(ret < 0 && errno==EINTR)
			continue;
		return ret;
	}
#else // Win32
	WSABUF vec[max_vec_size];
	for(;size < max_vec_size && size < data.second;size++) {
		vec[size].buf = data.first[size].ptr;
		vec[size].len = data.first[size].size;
	}
	DWORD recved=0;
	DWORD flags=0;
	int res = ::WSARecv(native(),vec,size,&recved,&flags,0,0);
	if(res == 0)
		return recved;
	return -1;
#endif
}
示例#2
0
bool basic_socket::get_option(boolean_option_type opt,system::error_code &e)
{
	int value = 0;
	socklen_t len = sizeof(value);
	#ifdef BOOSTER_WIN32
	char *ptr = reinterpret_cast<char *>(&value);
	#else
	int *ptr = &value;
	#endif
	int res = 0;
	switch(opt) {
	case tcp_no_delay:
		res=::getsockopt(native(),IPPROTO_TCP,TCP_NODELAY,ptr,&len);
		break;
	case keep_alive:
		res=::getsockopt(native(),SOL_SOCKET,SO_KEEPALIVE,ptr,&len);
		break;
	case reuse_address:
		res=::getsockopt(native(),SOL_SOCKET,SO_REUSEADDR,ptr,&len);
		break;
	default:
		;
	}
	if(res < 0) {
		e=geterror();
		return false;
	}
	return value!=0;
}
示例#3
0
bool DropHandler::RegisterHandler(HWND dropWindow, bool revokeOnDtor)
{
	// ensure not already registered
	if (_isRegistered)
		return false;

	// save the IDropTarget of the shell folder of the working directory
	LOG(QString_NT("Drop registered to %1").arg(native(scnManager->getWorkingDirectory())));
	
	IShellFolder2 * shellFolder = winOS->GetShellFolderFromAbsDirPath(
		native(scnManager->getWorkingDirectory()));
	if (shellFolder)
	{
		// try and coerce the drop target interface from the shell folder
		IDropTarget * dropTarget = NULL;
		shellFolder->CreateViewObject(NULL, IID_IDropTarget, (void **) &dropTarget);
		if (dropTarget)
		{
			_workingDirectoryDropTarget = dropTarget;
		}
		shellFolder->Release();
	}

	// register and return status
	_revokeOnDestroy = revokeOnDtor;
	_dropWindow = dropWindow;
	_isRegistered = SUCCEEDED(RegisterDragDrop(_dropWindow, this));
	return _isRegistered;
}
示例#4
0
int stream_socket::writev(const_buffer const &b)
{
	static const unsigned max_vec_size = 16;
	const_buffer::buffer_data_type data = b.get();
	unsigned size=0;
#ifndef BOOSTER_WIN32
	struct iovec vec[max_vec_size];
	for(;size < max_vec_size && size < data.second;size++) {
		vec[size].iov_base = const_cast<char *>(data.first[size].ptr);
		vec[size].iov_len = data.first[size].size;
	}
	for(;;) {
		int ret = ::writev(native(),vec,size);
		if(ret >= 0)
			return ret;
		if(ret < 0 && errno==EINTR)
			continue;
		return ret;
	}
#else // Win32
	WSABUF vec[max_vec_size];
	for(;size < max_vec_size && size < data.second;size++) {
		vec[size].buf = const_cast<char *>(data.first[size].ptr);
		vec[size].len = data.first[size].size;
	}
	DWORD send=0;
	int res = ::WSASend(native(),vec,size,&send,0,0,0);
	if(res == 0)
		return send;
	return -1;
#endif
}
示例#5
0
void CMainWindow::DumpNextFrame()
{
	m_virtualMachine.TriggerFrameDump(
		[&] (const CFrameDump& frameDump)
		{
			try
			{
				auto frameDumpDirectoryPath = GetFrameDumpDirectoryPath();
				Framework::PathUtils::EnsurePathExists(frameDumpDirectoryPath);
				for(unsigned int i = 0; i < UINT_MAX; i++)
				{
					auto frameDumpFileName = string_format("framedump_%0.8d.dmp.zip", i);
					auto frameDumpPath = frameDumpDirectoryPath / boost::filesystem::path(frameDumpFileName);
					if(!boost::filesystem::exists(frameDumpPath))
					{
						auto dumpStream = Framework::CreateOutputStdStream(frameDumpPath.native());
						frameDump.Write(dumpStream);
						PrintStatusTextA("Dumped frame to '%s'.", frameDumpFileName.c_str());
						return;
					}
				}
			}
			catch(...)
			{

			}
			PrintStatusTextA("Failed to dump frame.");
		}
	);
}
示例#6
0
文件: BT_Mesh.cpp 项目: DX94/BumpTop
Mesh::Mesh(LPCWSTR file)
: _mesh(NULL)
, _meshMaterials(NULL)
, _meshTextures(NULL)
, _meshMaterialCount(0)
{
	ID3DXBuffer * meshMaterialBuffer = NULL;
	HRESULT hr = D3DXLoadMeshFromX(file, 0, dxr->device, NULL, &meshMaterialBuffer, NULL, &_meshMaterialCount, &_mesh);
	_ASSERT(SUCCEEDED(hr));
	if (meshMaterialBuffer && _meshMaterialCount > 0)
	{
		D3DXMATERIAL* d3dxMaterials = (D3DXMATERIAL*)meshMaterialBuffer->GetBufferPointer();
		_meshMaterials = new D3DMATERIAL9[_meshMaterialCount];
		_meshTextures = new IDirect3DTexture9 * [_meshMaterialCount];
		for (unsigned long i = 0; i < _meshMaterialCount; i++)
		{
			_meshMaterials[i] = d3dxMaterials[i].MatD3D;
			if (D3DXCOLOR(0xff000000) == _meshMaterials[i].Ambient)
				_meshMaterials[i].Ambient = D3DXCOLOR(0.75,0.75,0.75,0.75);
			_meshTextures[i] = NULL;
			if (d3dxMaterials[i].pTextureFilename)
			{
				QString texturePath = native(QFileInfo(QString::fromUtf16((const ushort *)file)).dir() / QFileInfo(d3dxMaterials[i].pTextureFilename).fileName());
				hr = D3DXCreateTextureFromFileW(dxr->device, (LPCWSTR)texturePath.utf16(), &_meshTextures[i]);
				_ASSERT(SUCCEEDED(hr));
			}
		}
	}
	meshMaterialBuffer->Release();	
}
示例#7
0
/***********************************************************************//**
 * @brief Rotate sky direction by zenith and azimuth angle
 *
 * @param[in] phi Azimuth angle (deg).
 * @param[in] theta Zenith angle (deg).
 *
 * Rotate sky direction by a zenith and azimuth angle given in the system
 * of the sky direction and aligned in celestial coordinates. 
 * The azimuth angle is counted counter clockwise from celestial north
 * (this is identical to the astronomical definition of a position angle).
 ***************************************************************************/
void GSkyDir::rotate_deg(const double& phi, const double& theta)
{
    // If we have no equatorial coordinates then get them now
    if (!m_has_radec && m_has_lb)
        gal2equ();

    // Allocate Euler and rotation matrices
    GMatrix ry;
    GMatrix rz;
    GMatrix rot;

    // Set up rotation matrix to rotate from native coordinates to
    // celestial coordinates
    ry.eulery(m_dec*rad2deg - 90.0);
    rz.eulerz(-m_ra*rad2deg);
    rot = transpose(ry * rz);

    // Set up native coordinate vector
    double phi_rad   = phi   * deg2rad;
    double theta_rad = theta * deg2rad;
    double cos_phi   = std::cos(phi_rad);
    double sin_phi   = std::sin(phi_rad);
    double cos_theta = std::cos(theta_rad);
    double sin_theta = std::sin(theta_rad);
    GVector native(-cos_phi*sin_theta, sin_phi*sin_theta, cos_theta);

    // Rotate vector into celestial coordinates
    GVector dir = rot * native;

    // Convert vector into sky position
    celvector(dir);

    // Return
    return;
}
示例#8
0
/***********************************************************************//**
 * @brief Kernel for IRF azimuth angle integration of the diffuse source model
 *
 * @param[in] phi Azimuth angle around observed photon direction (radians).
 *
 * This method provides the kernel for the IRF azimuth angle integration of
 * the diffuse source model.
 *
 * It computes
 *
 * \f[irf = M(\theta, \phi) Aeff(\theta, \phi) Edisp(\theta, \phi)\f]
 *
 * where \f$M(\theta, \phi)\f$ is the spatial component of the diffuse
 * source model, \f$Aeff(\theta, \phi)\f$ is the effective area, and
 * \f$Edisp(\theta, \phi)\f$ is the energy dispersion.
 *
 * As the coordinates \f$(\theta, \phi)\f$ are given in the reference frame
 * of the observed photon direction, some coordinate transformations have
 * to be performed.
 *
 * First, \f$(\theta, \phi)\f$ are transformed into the celestial reference
 * frame using the rotation matrix.
 *
 * Then, the offset angle of the true photon direction is computed in the
 * camera system (so far we do not compute the azimuth angle as we assume an
 * azimuthally symmetric response).
 *
 * @todo Optimize computation of sky direction in native coordinates
 * @todo Implement azimuth angle computation of true photon in camera
 * @todo Replace (theta,phi) by (delta,alpha)
 ***************************************************************************/
double cta_irf_diffuse_kern_phi::eval(double phi)
{
    // Initialise result
    double irf = 0.0;

    // Compute sine and cosine of azimuth angle
    double sin_phi = std::sin(phi);
    double cos_phi = std::cos(phi);

    // Compute sky direction vector in native coordinates
    GVector native(-cos_phi*m_sin_theta, sin_phi*m_sin_theta, m_cos_theta);

    // Rotate from native into celestial system
    GVector cel = *m_rot * native;

    // Set sky direction
    GSkyDir srcDir;
    srcDir.celvector(cel);

    // Get sky intensity for this sky direction
    double intensity = m_model->eval(srcDir);

    // Continue only if sky intensity is positive
    if (intensity > 0.0) {

        // Compute true photon offset angle in camera system [radians]
        double offset = std::acos(m_cos_ph + m_sin_ph * cos_phi);
    
        //TODO: Compute true photon azimuth angle in camera system [radians]
        double azimuth = 0.0;

        // Evaluate model times the effective area
        irf = intensity *
              m_rsp->aeff(offset, azimuth, m_zenith, m_azimuth, m_srcLogEng);

        // Optionally take energy dispersion into account
        if (m_rsp->hasedisp() && irf > 0.0) {
            irf *= m_rsp->edisp(m_obsLogEng, offset, azimuth, m_zenith, m_azimuth, m_srcLogEng);
        }
    
        // Compile option: Check for NaN/Inf
        #if defined(G_NAN_CHECK)
        if (isnotanumber(irf) || isinfinite(irf)) {
            std::cout << "*** ERROR: cta_irf_diffuse_kern_phi::eval";
            std::cout << "(phi=" << phi << "):";
            std::cout << " NaN/Inf encountered";
            std::cout << " (irf=" << irf;
            std::cout << ", intensity=" << intensity;
            std::cout << ", offset=" << offset;
            std::cout << ", azimuth=" << azimuth;
            std::cout << ")";
            std::cout << std::endl;
        }
        #endif

    } // endif: sky intensity was positive

    // Return
    return irf;
}
示例#9
0
/** Performs early sanity checks on the account and fee fields */
NotTEC
preflight1 (PreflightContext const& ctx)
{
    auto const ret = preflight0(ctx);
    if (!isTesSuccess(ret))
        return ret;

    auto const id = ctx.tx.getAccountID(sfAccount);
    if (id == beast::zero)
    {
        JLOG(ctx.j.warn()) << "preflight1: bad account id";
        return temBAD_SRC_ACCOUNT;
    }

    // No point in going any further if the transaction fee is malformed.
    auto const fee = ctx.tx.getFieldAmount (sfFee);
    if (!fee.native () || fee.negative () || !isLegalAmount (fee.xrp ()))
    {
        JLOG(ctx.j.debug()) << "preflight1: invalid fee";
        return temBAD_FEE;
    }

    auto const spk = ctx.tx.getSigningPubKey();

    if (!spk.empty () && !publicKeyType (makeSlice (spk)))
    {
        JLOG(ctx.j.debug()) << "preflight1: invalid signing key";
        return temBAD_SIGNATURE;
    }

    return tesSUCCESS;
}
示例#10
0
// _110313_054719 Now works for passive, too.
void ShelveInfoNative::Pop(bool active)
{
	HANDLE handle = active ? PANEL_ACTIVE : PANEL_PASSIVE;
	if (Path)
		::SetPanelDirectory(handle, Path);

	array<String^>^ selectedNames = GetSelectedNames();
	if (!Current && !selectedNames && !_modes)
		return;

	PanelInfo pi;
	GetPanelInfo(handle, pi);
	if (0 != (pi.Flags & PFLAGS_PLUGIN) || pi.PanelType != PTYPE_FILEPANEL)
		//! do not throw, sometimes a panel just cannot close
		return;

	Panel1 native(active);

	if (Current)
		native.GoToName(Current);

	native.SelectNames(selectedNames);

	// restore modes
	if (_modes)
	{
		if (_viewMode != (PanelViewMode)pi.ViewMode)
			native.ViewMode = _viewMode;
		
		bool reversed = (pi.Flags & PFLAGS_REVERSESORTORDER) != 0;
		PanelSortMode sortMode = (PanelSortMode)(reversed ? -pi.SortMode : pi.SortMode);
		if (_sortMode != sortMode)
			native.SortMode = _sortMode;
	}
}
示例#11
0
void PrepareTestEnvironment(const CGameTestSheet::EnvironmentActionArray& environment)
{
	//TODO: There's a bug if there's a slash at the end of the path for the memory card
	auto mcPathPreference = Iop::CMcServ::GetMcPathPreference(0);
	auto memoryCardPath = boost::filesystem::path("./memorycard");
	boost::filesystem::remove_all(memoryCardPath);

	CAppConfig::GetInstance().RegisterPreferencePath(mcPathPreference, "");
	CAppConfig::GetInstance().SetPreferencePath(mcPathPreference, memoryCardPath);

	for(const auto& environmentAction : environment)
	{
		if(environmentAction.type == CGameTestSheet::ENVIRONMENT_ACTION_CREATE_DIRECTORY)
		{
			auto folderToCreate = memoryCardPath / boost::filesystem::path(environmentAction.name);
			Framework::PathUtils::EnsurePathExists(folderToCreate);
		}
		else if(environmentAction.type == CGameTestSheet::ENVIRONMENT_ACTION_CREATE_FILE)
		{
			auto fileToCreate = memoryCardPath / boost::filesystem::path(environmentAction.name);
			auto inputStream = Framework::CreateOutputStdStream(fileToCreate.native());
			inputStream.Seek(environmentAction.size - 1, Framework::STREAM_SEEK_SET);
			inputStream.Write8(0x00);
		}
	}
}
示例#12
0
void MemoryCardManagerDialog::on_import_saves_button_clicked()
{
	QFileDialog dialog(this);
	dialog.setDirectory(m_lastpath);
	dialog.setFileMode(QFileDialog::ExistingFiles);
	dialog.setNameFilter(tr("All Supported types (*.psu *.sps *.xps *.max);;EMS Memory Adapter Save Dumps (*.psu);;Sharkport/X-Port Save Dumps (*.sps; *.xps);;Action Replay MAX Save Dumps (*.max);;All files (*.*)"));
	if(dialog.exec())
	{
		QString fileName = dialog.selectedFiles().first();
		m_lastpath = QFileInfo(fileName).path();

		try
		{
			auto filePath = QStringToPath(fileName);
			auto input = Framework::CreateInputStdStream(filePath.native());
			CSaveImporter::ImportSave(input, m_pCurrentMemoryCard->GetBasePath(),
			                          std::bind(&MemoryCardManagerDialog::OnImportOverwrite, this, std::placeholders::_1));
		}
		catch(const std::exception& Exception)
		{
			QString msg("Couldn't import save(s):\n\n%1");
			QMessageBox messageBox;
			messageBox.critical(this, "Error", msg.arg(Exception.what()));
			messageBox.show();
			return;
		}

		m_pCurrentMemoryCard->RefreshContents();
		populateSaveList();
	}
}
示例#13
0
void FileSystemManager::createShortcut(QString shortcutFilePath, QString pathToTarget, QString desc)
{
	HRESULT hres = NULL;
	IShellLink * psl = NULL;
	IPersistFile * ppf = NULL;
	
	QDir workingDirectory = scnManager->getWorkingDirectory();
	QDir linkPath = workingDirectory / shortcutFilePath;

	// Get a pointer to the IShellLink interface.
	hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **) &psl);

	if (SUCCEEDED(hres))
	{
		// Set the path to the shortcut target
		psl->SetPath((LPCWSTR) pathToTarget.utf16());
		psl->SetDescription((LPCWSTR) desc.utf16());

		// Query IShellLink for the IPersistFile interface for
		// saving the shortcut in persistent storage.
		hres = psl->QueryInterface(IID_IPersistFile, (void **) &ppf);

		if (SUCCEEDED(hres))
		{
			// Save the link by calling IPersistFile::Save.
			hres = ppf->Save((LPCOLESTR) native(linkPath).utf16(), TRUE);
			ppf->Release();
		}

		psl->Release();
	}
}
示例#14
0
void VM_GenCollectFullConcurrent::doit_epilogue() {
  Thread* thr = Thread::current();
  assert(thr->is_Java_thread(), "just checking");
  JavaThread* jt = (JavaThread*)thr;
  // Release the Heap_lock first.
  Heap_lock->unlock();
  release_and_notify_pending_list_lock();

  // It is fine to test whether completed collections has
  // exceeded our request count without locking because
  // the completion count is monotonically increasing;
  // this will break for very long-running apps when the
  // count overflows and wraps around. XXX fix me !!!
  // e.g. at the rate of 1 full gc per ms, this could
  // overflow in about 1000 years.
  GenCollectedHeap* gch = GenCollectedHeap::heap();
  if (gch->total_full_collections_completed() <= _full_gc_count_before) {
    // Now, wait for witnessing concurrent gc cycle to complete,
    // but do so in native mode, because we want to lock the
    // FullGCEvent_lock, which may be needed by the VM thread
    // or by the CMS thread, so we do not want to be suspended
    // while holding that lock.
    ThreadToNativeFromVM native(jt);
    MutexLockerEx ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
    // Either a concurrent or a stop-world full gc is sufficient
    // witness to our request.
    while (gch->total_full_collections_completed() <= _full_gc_count_before) {
      FullGCCount_lock->wait(Mutex::_no_safepoint_check_flag);
    }
  }
  // Enable iCMS back.
  CMSCollector::enable_icms();
}
TEST_F(FailureFixture, ExistingDiskMessageOnDestructTest) {
    std::random_device generator;
    std::uniform_int_distribution<unsigned long long> distribution(1, DEFAULT_MAX_MEMORY_SIZE);
    auto number_to_create = distribution(generator);

    {
        PriorityBuffer<PriorityMessage> buffer{get_priority};
        
        // Push DEFAULT_MAX_MEMORY_SIZE messages into the buffer with 0 priority
        for (int i = 0; i < DEFAULT_MAX_MEMORY_SIZE; ++i) {
            auto message = std::unique_ptr<PriorityMessage>{ new PriorityMessage{} };
            message->set_priority(0);
            ASSERT_TRUE(message->IsInitialized());
            buffer.Push(std::move(message));
        }

        std::stringstream stream;
        stream << "SELECT hash FROM "
               << table_name_
               << " ORDER BY priority LIMIT "
               << number_to_create
               << ";";
        auto response = execute_(stream.str());
        ASSERT_EQ(number_to_create, response.size());

        for (auto& record : response) {
            auto file_path = buffer_path_ / fs::path{record["hash"]};
            std::ofstream file_out{file_path.native()};
            file_out << "hello world";
        }
    }

    // Let the buffer drop and try to push memory messages to disk
    EXPECT_EQ(DEFAULT_MAX_MEMORY_SIZE - number_to_create, number_of_files_());
}
示例#16
0
void 
SocketAdapter::handleWrite(const boost::system::error_code& error) {
    Ptr self(shared_from_this());
    // NOTE: this will be called from one of io_service's threads
    AC_TRACE << "  doing write " << this << " with error " << error << " socket is " << native();
    write_in_progress = false;
    if (boost_socket.is_open() && error == 0) {
        int i;
        CURLMcode myStatus = curl_multi_socket_action(_parent->_curlMulti, native(), CURL_CSELECT_OUT, &i);
        MultiAdapter::checkCurlStatus(myStatus, PLUS_FILE_LINE);
        AC_TRACE << "   done write " << this;
    }

    if (boost_socket.is_open() && error == 0) {
        SocketAdapter::handleOperations(self, native());
    } 
};
示例#17
0
void AutomatedJSONTestSuite::PrepareScene::onStateChanged()
{
	// Clear out all files from the training directory 
	StrList dirContents = fsManager->getDirectoryContents(native(winOS->GetTrainingDirectory()));
	for_each(QString filename, dirContents)
	{
		fsManager->deleteFileByName(filename, true); // delete silently
	}
示例#18
0
void UTXOAddressState::serialize(const boost::filesystem::path &path) {
    blocksci::for_each(addressTypeStates, [&](auto &addressTypeState) {
        std::stringstream ss;
        ss << addressName(addressTypeState.type);
        ss << ".dat";
        auto fullPath = path / ss.str();
        addressTypeState.serialize(fullPath.native());
    });
}
示例#19
0
void FlickrPhotoFrameSource::createLocalCacheDirectory()
{
	// use a hash of the feed url as the dir name
	QString dir;
	if (!_tag.isNull() && !_tag.isEmpty())
		dir = _tag;
	else if (!_groupId.isNull() && !_groupId.isEmpty())
		dir = _groupId;
	else
		dir = _userId;
	convertToValidDirectoryName(dir);

	// create this directory if necessary
	QString framesDir = native(winOS->GetFramesDirectory() / "Flickr");
	QDir().mkpath(framesDir);
	_localCacheDirectory = QDir(framesDir) / dir;
	QDir().mkpath(native(_localCacheDirectory));
}
示例#20
0
    unsigned
    Scheduler::minimumPriority(void)
    {
#if defined(DUNE_SYS_HAS_SCHED_GET_PRIORITY_MIN)
      int policy = native();
      return sched_get_priority_min(policy);
#endif

      return 0;
    }
示例#21
0
void stream_socket::connect(endpoint const &ep,system::error_code &e)
{
	endpoint::native_address_type address = ep.raw();
	#ifndef BOOSTER_WIN32
	for(;;) {
		int res = ::connect(native(),address.first,address.second);
		if(res < 0 && errno==EINTR)
			continue;
		if(res < 0) {
			e=geterror();
			return;
		}
		break;
	}
	#else
	if(::connect(native(),address.first,address.second) < 0)
		e=geterror();
	#endif
}
示例#22
0
endpoint basic_socket::remote_endpoint(system::error_code &e)
{
	std::vector<char> endpoint_raw_(1000,0);
	sockaddr *sa = reinterpret_cast<sockaddr *>(&endpoint_raw_.front());
	socklen_t len = endpoint_raw_.size();
	if(::getpeername(native(),sa,&len) < 0)
		e=geterror();
	endpoint ep;
	ep.raw(sa,len);
	return ep;
}
示例#23
0
void 
SocketAdapter::handleRead(const boost::system::error_code& error) {
    Ptr self(shared_from_this());
    // NOTE: this will be called from one of io_service's threads
    AC_TRACE << "  doing read " << this << " on socket " << native() << " with error " << error;
    read_in_progress = false;
    if (error != 0) {
        if (error == boost::asio::error::operation_aborted) {
            AC_TRACE << "Read aborted";
        } else {
            AC_TRACE << "Read aborted with unknown error " << error;
        }
        return;
    }
    int i;
    CURLMcode myStatus = curl_multi_socket_action(_parent->_curlMulti, native(), CURL_CSELECT_IN, &i);
    MultiAdapter::checkCurlStatus(myStatus, PLUS_FILE_LINE);
    AC_TRACE << "   done read " << this << " socket " << native();
    SocketAdapter::handleOperations(self, native());
};
示例#24
0
void basic_socket::set_option(boolean_option_type opt,bool v,system::error_code &e)
{
	int value = v ? 1 : 0;
	char const *p=reinterpret_cast<char const *>(&value);
	int res = 0;
	switch(opt) {
	case tcp_no_delay:
		res=::setsockopt(native(),IPPROTO_TCP,TCP_NODELAY,p,sizeof(value));
		break;
	case keep_alive:
		res=::setsockopt(native(),SOL_SOCKET,SO_KEEPALIVE,p,sizeof(value));
		break;
	case reuse_address:
		res=::setsockopt(native(),SOL_SOCKET,SO_REUSEADDR,p,sizeof(value));
		break;
	default:
		;
	}
	if(res < 0)
		e=geterror();
}
  /// Remove an endpoint to the set used by the acceptor.
  boost::system::error_code bind_remove(implementation_type& impl,
      const endpoint_type& endpoint, boost::system::error_code& ec)
  {
    if (!is_open(impl))
    {
      ec = boost::asio::error::bad_descriptor;
      return ec;
    }

    boost::asio_sctp::detail::sctp_socket_ops::bind_remove(native(impl), endpoint.data(), endpoint.size(), ec);
    return ec;
  }
示例#26
0
void LocalPhotoFrameSource::updateDirectory(QDir dir, vector<PhotoFrameSourceItem>& items)
{
	// assume dir exists
	if (!empty(dir))
	{
		StrList dirListing = fsManager->getDirectoryContents(native(dir));
		for (int i = 0; i < dirListing.size(); ++i)
		{
			QFileInfo file(dirListing[i]);

			if (file.isSymLink()) {
				file = QFile(file.symLinkTarget());
			}

			if (file.isDir())
				// recurse into that directory
				updateDirectory(file.absoluteFilePath(), items);
			else
			{
				// XXX: we can do this smarter with watched directories?!

				// check if this is a valid image file
				QString filename = file.fileName();
				if (filename.size() > 4)
				{
					QString ext = fsManager->getFileExtension(filename);
					bool isValidImage = !ext.isEmpty() && GLOBAL(supportedExtensions).contains(ext + ".");
					if (isValidImage)
					{
						// check if we already have that item in the list
						vector<PhotoFrameSourceItem>::const_iterator itemIter = items.begin();
						vector<PhotoFrameSourceItem>::const_iterator endIter = items.end();
						bool exists = false;
						while (itemIter != endIter)
						{
							if ((*itemIter).getResourceId() == dirListing[i])
								exists = true;
							++itemIter;
						}

						// if not, add it to the list
						if (!exists)
						{
							PhotoFrameSourceItem item(dirListing[i]);
							item.setTexturePath(dirListing[i]);
							items.push_back(item);
						}
					}
				}
			}
		}
	}
}
示例#27
0
		void seek(implementation_type& impl, int64_t offset, int origin,
			boost::system::error_code& err) 
		{
			// setting file pointer here for truncate purposes in async_write_some
			LARGE_INTEGER li;
			li.QuadPart = offset;
			if(HFILE_ERROR==SetFilePointer(native(impl), li.LowPart, &li.HighPart, origin))
			{
				err =  boost::system::error_code(GetLastError(), 
					boost::asio::error::get_system_category());
			}
		}
示例#28
0
bool FileSystemManager::renameFile(QDir old, QString newName, bool confirm)
{
	QString oldPathString(native(old));
	QDir parentPath = parent(old);
	QString newPathString(native((parentPath / newName)));

	TCHAR oldp[MAX_PATH] = {0};
	TCHAR newp[MAX_PATH] = {0};
	lstrcpy(oldp, (LPCTSTR) oldPathString.utf16());
	lstrcpy(newp, (LPCTSTR) newPathString.utf16());

	SHFILEOPSTRUCT fileOperation = { 0 };
	fileOperation.hwnd = winOS->GetWindowsHandle();
	fileOperation.wFunc = FO_RENAME;
	fileOperation.pFrom = oldp;
	fileOperation.pTo = newp;
	fileOperation.fFlags = FOF_ALLOWUNDO | (confirm ? NULL : FOF_NOCONFIRMATION);

	// Do the windows file operations for Rename
	return (SHFileOperation(&fileOperation) == 0) && !fileOperation.fAnyOperationsAborted;
}
示例#29
0
SocketAdapter::SocketAdapter(MultiAdapter * pParent, CURLM * theCurlMultihandle) :
    boost_socket(pParent->io),
    readyState(0),
    read_in_progress(false),
    write_in_progress(false),
    _parent(pParent)
{ 
    AC_DEBUG << "creating socket " << this;
    boost_socket.open(boost::asio::ip::tcp::v4());
    boost::asio::ip::tcp::socket::non_blocking_io non_blocking_io(true);
    boost_socket.io_control(non_blocking_io);
    AC_TRACE << "         socket is " << native();
};
示例#30
0
void acceptor::accept(stream_socket &target,system::error_code &e)
{
	native_type new_fd = invalid_socket;
	#ifndef BOOSTER_WIN32
	for(;;) {
		new_fd = ::accept(native(),0,0);
		if(new_fd < 0 && errno==EINTR)
			continue;
		break;
	}
	#else
	new_fd = ::accept(native(),0,0);
	#endif

	if(new_fd == invalid_socket) {
		e=geterror();
		return;
	}

	target.assign(new_fd);
	return;
}