示例#1
0
void	CROS_impl::update	(IRenderable* O)
{
	// clip & verify
	if					(dwFrame==Device.dwFrame)			return;
	dwFrame				= Device.dwFrame;
	if					(0==O)								return;
	if					(0==O->renderable.visual)			return;
	VERIFY				(dynamic_cast<CROS_impl*>			(O->renderable_ROS()));
	float	dt			=	Device.fTimeDelta;

	CObject*	_object	= dynamic_cast<CObject*>	(O);

	// select sample, randomize position inside object
	Fvector	position;	O->renderable.xform.transform_tiny	(position,O->renderable.visual->vis.sphere.P);
	float	radius;		radius	= O->renderable.visual->vis.sphere.R;
	position.y			+=  .3f * radius;
	Fvector	direction;	direction.random_dir();
//.			position.mad(direction,0.25f*radius);
//.			position.mad(direction,0.025f*radius);

	// sun-tracing
#if RENDER==R_R1
	light*	sun		=		(light*)RImplementation.L_DB->sun_adapted._get()	;
#else
	light*	sun		=		(light*)RImplementation.Lights.sun_adapted._get()	;
#endif
	if	(MODE & IRender_ObjectSpecific::TRACE_SUN)	{
		if  (--result_sun	< 0)	{
			result_sun		+=		::Random.randI(lt_hemisamples/4,lt_hemisamples/2)	;
			Fvector	direction;	direction.set	(sun->direction).invert().normalize	();
			sun_value		=	!(g_pGameLevel->ObjectSpace.RayTest(position,direction,500.f,collide::rqtBoth,&cache_sun,_object))?1.f:0.f;
		}
	}
	
	// hemi-tracing
	bool	bFirstTime	=	(0==result_count);
	if	(MODE & IRender_ObjectSpecific::TRACE_HEMI)	{
		for (u32 it=0; it<(u32)ps_r2_dhemi_count;	it++)		{	// five samples per one frame
			u32	sample		=	0				;
			if	(result_count<lt_hemisamples)	{ sample=result_count; result_count++;							}
			else								{ sample=(result_iterator%lt_hemisamples); result_iterator++;	}

			// take sample
			Fvector	direction;	direction.set	(hdir[sample][0],hdir[sample][1],hdir[sample][2]).normalize	();
//.			result[sample]	=	!g_pGameLevel->ObjectSpace.RayTest(position,direction,50.f,collide::rqtBoth,&cache[sample],_object);
			result[sample]	=	!g_pGameLevel->ObjectSpace.RayTest(position,direction,50.f,collide::rqtStatic,&cache[sample],_object);
			//	Msg				("%d:-- %s",sample,result[sample]?"true":"false");
		}
	}

	// hemi & sun: update and smooth
//	float	l_f				=	dt*lt_smooth;
//	float	l_i				=	1.f-l_f;
	int		_pass			=	0;
	for (int it=0; it<result_count; it++)	if (result[it])	_pass	++;
	hemi_value				=	float	(_pass)/float(result_count?result_count:1);
	hemi_value				*=	ps_r2_dhemi_scale;
	if (bFirstTime)			hemi_smooth		= hemi_value;
	update_smooth			()	;

	// light-tracing
	BOOL	bTraceLights	= MODE & IRender_ObjectSpecific::TRACE_LIGHTS;
	if		((!O->renderable_ShadowGenerate()) && (!O->renderable_ShadowReceive()))	bTraceLights = FALSE;
	if		(bTraceLights)	{
		// Select nearest lights
		Fvector					bb_size	=	{radius,radius,radius};
		g_SpatialSpace->q_box				(RImplementation.lstSpatial,0,STYPE_LIGHTSOURCE,position,bb_size);
		for (u32 o_it=0; o_it<RImplementation.lstSpatial.size(); o_it++)	{
			ISpatial*	spatial		= RImplementation.lstSpatial[o_it];
			light*		source		= (light*)	(spatial->dcast_Light());
			VERIFY		(source);	// sanity check
			float	R				= radius+source->range;
			if (position.distance_to(source->position) < R)		add	(source);
		}

		// Trace visibility
		lights.clear	();
		float traceR	= radius*.5f;
		for (s32 id=0; id<s32(track.size()); id++)
		{
			// remove untouched lights
			xr_vector<CROS_impl::Item>::iterator I	= track.begin()+id;
			if (I->frame_touched!=Device.dwFrame)	{ track.erase(I) ; id--	; continue ; }

			// Trace visibility
			Fvector				P,D;
			float		amount	= 0;
			light*		xrL		= I->source;
			Fvector&	LP		= xrL->position;
			P.mad				(position,P.random_dir(),traceR);		// Random point inside range

			// point/spot
			float	f			=	D.sub(P,LP).magnitude();
			if (g_pGameLevel->ObjectSpace.RayTest(LP,D.div(f),f,collide::rqtStatic,&I->cache,_object))	amount -=	lt_dec;
			else																						amount +=	lt_inc;
			I->test				+=	amount * dt;	clamp	(I->test,-.5f,1.f);
			I->energy			=	.9f*I->energy + .1f*I->test;

			// 
			float	E			=	I->energy * xrL->color.intensity	();
			if (E > EPS)		{
				// Select light
				lights.push_back			(CROS_impl::Light())		;
				CROS_impl::Light&	L		= lights.back()				;
				L.source					= xrL						;
				L.color.mul_rgb				(xrL->color,I->energy/2)	;
				L.energy					= I->energy/2				;
				if (!xrL->flags.bStatic)	{ L.color.mul_rgb(.5f); L.energy *= .5f; }
			}
		}

		// Sun
		float	E			=	sun_smooth * sun->color.intensity	();
		if (E > EPS)		{
			// Select light
			lights.push_back			(CROS_impl::Light())		;
			CROS_impl::Light&	L		= lights.back()				;
			L.source					= sun						;
			L.color.mul_rgb				(sun->color,sun_smooth/2)	;
			L.energy					= sun_smooth				;
		}

		// Sort lights by importance - important for R1-shadows
		std::sort	(lights.begin(),lights.end(), pred_energy);
	}

	// Process ambient lighting and approximate average lighting
	// Process our lights to find average luminiscense
	CEnvDescriptor&	desc	=	g_pGamePersistent->Environment().CurrentEnv;
	Fvector			accum	=	{ desc.ambient.x,		desc.ambient.y,		desc.ambient.z		};
	Fvector			hemi	=	{ desc.hemi_color.x,	desc.hemi_color.y,	desc.hemi_color.z	};
	Fvector			sun_	=	{ desc.sun_color.x,		desc.sun_color.y,	desc.sun_color.z	};
	if (MODE & IRender_ObjectSpecific::TRACE_HEMI	)	hemi.mul(hemi_smooth); else hemi.mul(.2f);
					accum.add	( hemi );
	if (MODE & IRender_ObjectSpecific::TRACE_SUN	)	sun_.mul(sun_smooth); else sun_.mul(.2f);
					accum.add	( sun_ );
	if (MODE & IRender_ObjectSpecific::TRACE_LIGHTS )	{
		Fvector		lacc	=	{ 0,0,0 };
		for (u32 lit=0; lit<lights.size(); lit++)	{
			float	d	=	lights[lit].source->position.distance_to(position);
			float	r	=	lights[lit].source->range;
			float	a	=	clampr(1.f - d/(r+EPS),0.f,1.f)*(lights[lit].source->flags.bStatic?1.f:2.f);
			lacc.x		+=	lights[lit].color.r*a;
			lacc.y		+=	lights[lit].color.g*a;
			lacc.z		+=	lights[lit].color.b*a;
		}
//		lacc.x		*= desc.lmap_color.x;
//		lacc.y		*= desc.lmap_color.y;
//		lacc.z		*= desc.lmap_color.z;
//		Msg				("- rgb[%f,%f,%f]",lacc.x,lacc.y,lacc.z);
		accum.add		(lacc);
	} else 			accum.set	( .1f, .1f, .1f );
	approximate				=	accum;
}
示例#2
0
void CWallmarksEngine::Render()
{
//	if (marks.empty())			return;
	// Projection and xform
	float	_43					= Device.mProject._43;
	Device.mProject._43			-= ps_r__WallmarkSHIFT; 
	RCache.set_xform_world		(Fidentity);
	RCache.set_xform_project	(Device.mProject);

	Fmatrix	mSavedView			= Device.mView;
	Fvector	mViewPos			;
			mViewPos.mad		(Device.vCameraPosition, Device.vCameraDirection,ps_r__WallmarkSHIFT_V);
	Device.mView.build_camera_dir	(mViewPos,Device.vCameraDirection,Device.vCameraTop);
	RCache.set_xform_view		(Device.mView);

	Device.Statistic->RenderDUMP_WM.Begin	();
	Device.Statistic->RenderDUMP_WMS_Count	= 0;
	Device.Statistic->RenderDUMP_WMD_Count	= 0;
	Device.Statistic->RenderDUMP_WMT_Count	= 0;

	float	ssaCLIP				= r_ssaDISCARD/4;

	lock.Enter		();			// Physics may add wallmarks in parallel with rendering

	for (WMSlotVecIt slot_it=marks.begin(); slot_it!=marks.end(); slot_it++){
		u32			w_offset;
		FVF::LIT	*w_verts, *w_start;
		BeginStream	(hGeom,w_offset,w_verts,w_start);
		wm_slot* slot			= *slot_it;	
		// static wallmarks
		for (StaticWMVecIt w_it=slot->static_items.begin(); w_it!=slot->static_items.end(); ){
			static_wallmark* W	= *w_it;
			if (RImplementation.ViewBase.testSphere_dirty(W->bounds.P,W->bounds.R)){
				Device.Statistic->RenderDUMP_WMS_Count++;
				float dst	= Device.vCameraPosition.distance_to_sqr(W->bounds.P);
				float ssa	= W->bounds.R * W->bounds.R / dst;
				if (ssa>=ssaCLIP)	{
					u32 w_count		= u32(w_verts-w_start);
					if ((w_count+W->verts.size())>=(MAX_TRIS*3)){
						FlushStream	(hGeom,slot->shader,w_offset,w_verts,w_start,FALSE);
						BeginStream	(hGeom,w_offset,w_verts,w_start);
					}
					static_wm_render	(W,w_verts);
				}
				W->ttl	-= 0.1f*Device.fTimeDelta;	// visible wallmarks fade much slower
			} else {
				W->ttl	-= Device.fTimeDelta;
			}
			if (W->ttl<=EPS){	
				static_wm_destroy	(W);
				*w_it				= slot->static_items.back();
				slot->static_items.pop_back();
			}else{
				w_it++;
			}
		}
		// Flush stream
		FlushStream				(hGeom,slot->shader,w_offset,w_verts,w_start,FALSE);	//. remove line if !(suppress cull needed)
		BeginStream				(hGeom,w_offset,w_verts,w_start);

		// dynamic wallmarks
		for (xr_vector<intrusive_ptr<CSkeletonWallmark> >::iterator w_it=slot->skeleton_items.begin(); w_it!=slot->skeleton_items.end(); w_it++){
			intrusive_ptr<CSkeletonWallmark> W	= *w_it;
			if (!W){
				continue	;
			}

#ifdef DEBUG
			if(W->used_in_render != Device.dwFrame)			
			{
				Log("W->used_in_render",W->used_in_render);
				Log("Device.dwFrame",Device.dwFrame);
				VERIFY(W->used_in_render == Device.dwFrame);
			}
#endif

			float dst	= Device.vCameraPosition.distance_to_sqr(W->m_Bounds.P);
			float ssa	= W->m_Bounds.R * W->m_Bounds.R / dst;
			if (ssa>=ssaCLIP){
				Device.Statistic->RenderDUMP_WMD_Count++;
				u32 w_count		= u32(w_verts-w_start);
				if ((w_count+W->VCount())>=(MAX_TRIS*3)){
					FlushStream	(hGeom,slot->shader,w_offset,w_verts,w_start,TRUE);
					BeginStream	(hGeom,w_offset,w_verts,w_start);
				}

				FVF::LIT	*w_save = w_verts;
				try {
					W->Parent()->RenderWallmark	(W,w_verts);
				} catch (...)
				{
					Msg		("! Failed to render dynamic wallmark");
					w_verts = w_save;
				}
			}
			#ifdef	DEBUG
			 W->used_in_render	= u32(-1);
			#endif
		}
		slot->skeleton_items.clear();
		// Flush stream
		FlushStream				(hGeom,slot->shader,w_offset,w_verts,w_start,TRUE);
	}

	lock.Leave();				// Physics may add wallmarks in parallel with rendering

	// Level-wmarks
	RImplementation.r_dsgraph_render_wmarks	();
	Device.Statistic->RenderDUMP_WM.End		();

	// Projection
	Device.mView				= mSavedView;
	Device.mProject._43			= _43;
	RCache.set_xform_view		(Device.mView);
	RCache.set_xform_project	(Device.mProject);
}
示例#3
0
wyInt32
EditorBase::OnContextMenuHelper(LPARAM lParam)
{
	wyBool	    nmenuselect;
	LONG	    lstyle=0;
	HMENU	    hmenu, htrackmenu;
	POINT	    pnt;
	wyInt32		pos;
    RECT        rect;
    MDIWindow*  wnd = GetActiveWin();

	VERIFY(hmenu = GetMenu(pGlobals->m_pcmainwin->m_hwndmain));

	//lStyle = GetWindowLongPtr ( m_hwndparent, GWL_STYLE );
	lstyle = GetWindowLongPtr(GetParent(m_hwndparent), GWL_STYLE);

    if ((lstyle & WS_MAXIMIZE) && wyTheme::IsSysmenuEnabled(GetParent(m_hwndparent)))
		VERIFY(htrackmenu =	GetSubMenu(hmenu, 2));
	else
		VERIFY(htrackmenu =	GetSubMenu(hmenu, 1));

	//If we are pressing the context button,then lParam is -1.
	if(lParam == -1)
	{		
		//for getting the current cursor pos.
		pos = SendMessage(m_hwnd, SCI_GETCURRENTPOS, 0, 0);
		pnt.x = SendMessage(m_hwnd, SCI_POINTXFROMPOSITION, 0, pos) ; 
		pnt.y = SendMessage(m_hwnd, SCI_POINTYFROMPOSITION, 0, pos); 
		VERIFY(ClientToScreen(m_hwnd, &pnt));
	}
	else
	{
		pnt.x = GET_X_LPARAM(lParam); 
		pnt.y = GET_Y_LPARAM(lParam); 
	}

    GetClientRect(m_hwnd, &rect);
    MapWindowPoints(m_hwnd, NULL, (LPPOINT)&rect, 2);

    if(!PtInRect(&rect, pnt))
    {
        return -1;
    }

	//VERIFY(ClientToScreen(m_hwnd, &pnt));
    SetFocus(m_hwnd);

	// Now change the menu item.
	ChangeEditMenuItem(htrackmenu);

    pGlobals->m_pcmainwin->m_connection->HandleTagsMenu((HMENU)hmenu);

    if(wnd)
    {
        //FrameWindow::RecursiveMenuEnable(htrackmenu, wyFalse, MF_ENABLED);

        if(wnd->m_executing == wyTrue || wnd->m_pingexecuting == wyTrue)
        {
            FrameWindow::RecursiveMenuEnable(htrackmenu, wyFalse, MF_DISABLED);
        }

        wyTheme::SetMenuItemOwnerDraw(htrackmenu);
	    nmenuselect = (wyBool)TrackPopupMenu(htrackmenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON, pnt.x, pnt.y, 0, pGlobals->m_pcmainwin->m_hwndmain, NULL);
    }
    return 1;
}
示例#4
0
void	CDetailManager::hw_Render_dump		(ref_constant x_array, u32 var_id, u32 lod_id, u32 c_offset)
{
	RDEVICE.Statistic->RenderDUMP_DT_Count	= 0;

	// Matrices and offsets
	u32		vOffset	=	0;
	u32		iOffset	=	0;

	vis_list& list	=	m_visibles	[var_id];

	Fvector					c_sun,c_ambient,c_hemi;
#ifndef _EDITOR
	CEnvDescriptor&	desc	= *g_pGamePersistent->Environment().CurrentEnv;
	c_sun.set				(desc.sun_color.x,	desc.sun_color.y,	desc.sun_color.z);	c_sun.mul(.5f);
	c_ambient.set			(desc.ambient.x,	desc.ambient.y,		desc.ambient.z);
	c_hemi.set				(desc.hemi_color.x, desc.hemi_color.y,	desc.hemi_color.z);
#else
	c_sun.set				(1,1,1);	c_sun.mul(.5f);
	c_ambient.set			(1,1,1);
	c_hemi.set				(1,1,1);
#endif    

	VERIFY(objects.size()<=list.size());

	// Iterate
	for (u32 O=0; O<objects.size(); O++){
		CDetail&	Object				= *objects	[O];
		xr_vector <SlotItemVec* >& vis	= list		[O];
		if (!vis.empty()){
			// Setup matrices + colors (and flush it as nesessary)
			RCache.set_Element				(Object.shader->E[lod_id]);
			RImplementation.apply_lmaterial	();
			u32			c_base				= x_array->vs.index;
			Fvector4*	c_storage			= RCache.get_ConstantCache_Vertex().get_array_f().access(c_base);

			u32 dwBatch	= 0;

			xr_vector <SlotItemVec* >::iterator _vI = vis.begin();
			xr_vector <SlotItemVec* >::iterator _vE = vis.end();
			for (; _vI!=_vE; _vI++){
				SlotItemVec*	items		= *_vI;
				SlotItemVecIt _iI			= items->begin();
				SlotItemVecIt _iE			= items->end();
				for (; _iI!=_iE; _iI++){
					SlotItem&	Instance	= **_iI;
					u32			base		= dwBatch*4;

					// Build matrix ( 3x4 matrix, last row - color )
					float		scale		= Instance.scale_calculated;
					Fmatrix&	M			= Instance.mRotY;
					c_storage[base+0].set	(M._11*scale,	M._21*scale,	M._31*scale,	M._41	);
					c_storage[base+1].set	(M._12*scale,	M._22*scale,	M._32*scale,	M._42	);
					c_storage[base+2].set	(M._13*scale,	M._23*scale,	M._33*scale,	M._43	);

					// Build color
#if RENDER==R_R1
					Fvector C;
					C.set					(c_ambient);
//					C.mad					(c_lmap,Instance.c_rgb);
					C.mad					(c_hemi,Instance.c_hemi);
					C.mad					(c_sun,	Instance.c_sun);
					c_storage[base+3].set	(C.x,			C.y,			C.z,			1.f		);
#else
					// R2 only needs hemisphere
					float		h			= Instance.c_hemi;
					float		s			= Instance.c_sun;
					c_storage[base+3].set	(s,				s,				s,				h		);
#endif
					dwBatch	++;
					if (dwBatch == hw_BatchSize)	{
						// flush
						RDEVICE.Statistic->RenderDUMP_DT_Count					+=	dwBatch;
						u32 dwCNT_verts			= dwBatch * Object.number_vertices;
						u32 dwCNT_prims			= (dwBatch * Object.number_indices)/3;
						RCache.get_ConstantCache_Vertex().b_dirty				=	TRUE;
						RCache.get_ConstantCache_Vertex().get_array_f().dirty	(c_base,c_base+dwBatch*4);
						RCache.Render			(D3DPT_TRIANGLELIST,vOffset, 0, dwCNT_verts,iOffset,dwCNT_prims);
						RCache.stat.r.s_details.add	(dwCNT_verts);

						// restart
						dwBatch					= 0;
					}
				}
			}
			// flush if nessecary
			if (dwBatch)
			{
				RDEVICE.Statistic->RenderDUMP_DT_Count	+= dwBatch;
				u32 dwCNT_verts			= dwBatch * Object.number_vertices;
				u32 dwCNT_prims			= (dwBatch * Object.number_indices)/3;
				RCache.get_ConstantCache_Vertex().b_dirty				=	TRUE;
				RCache.get_ConstantCache_Vertex().get_array_f().dirty	(c_base,c_base+dwBatch*4);
				RCache.Render				(D3DPT_TRIANGLELIST,vOffset,0,dwCNT_verts,iOffset,dwCNT_prims);
				RCache.stat.r.s_details.add	(dwCNT_verts);
			}
			// Clean up
			vis.clear_not_free			();
		}
		vOffset		+=	hw_BatchSize * Object.number_vertices;
		iOffset		+=	hw_BatchSize * Object.number_indices;
	}
}
示例#5
0
/////////////////////////////////////////////////////////////////////////////
// class AgentDisplay
AgentDisplay::AgentDisplay(MesaAgent::AgentIndex agentIndex, void * pFCB, u16 * pDisplayMem) : MesaAgent::Agent(agentIndex, pFCB)
{
    FCB * pDisplayFCB = (FCB *)pFCB;
    memset(pDisplayFCB, 0, sizeof(FCB));

    DawnView * pView = DawnApp::GetDawnView();
    CRect viewRect;
    pView->GetClientRect(&viewRect);

    // set up FCB
    pDisplayFCB->m_nDisplayType =   C_TO_MESA_UNSPECIFIED(kMonochrome);
    pDisplayFCB->m_nDisplayWidth =  C_TO_MESA_UNSPECIFIED(viewRect.Width());
    pDisplayFCB->m_nDisplayHeight = C_TO_MESA_UNSPECIFIED(viewRect.Height());
    pDisplayFCB->m_nInverseVideo =  C_TO_MESA_UNSPECIFIED(0);
    pDisplayFCB->m_n32mpBitmap =    C_TO_MESA_LONG_UNSPECIFIED((u32)pDisplayMem);

    // make sure the width is a multiple of eight
    ASSERT(0 == (viewRect.Width() % 8));
    
    // set up windows bitmap stuff
    //RGBQUAD black = { 96, 96, 96, 0 };
    //RGBQUAD white = { 192, 192, 192, 0 };
    RGBQUAD black = { 255, 0, 0, 0 };
    RGBQUAD white = { 255, 255, 255, 0 };

    m_colorBlack = black;
    m_colorWhite = white;
    m_pDisplayMemory = (u8 *)pDisplayMem;
    m_nDisplayBytesPerLine = viewRect.Width() / 8;

    m_bitmapInfo.bmiHeader.biSize = sizeof(m_bitmapInfo.bmiHeader); 
    m_bitmapInfo.bmiHeader.biWidth = viewRect.Width();
    m_bitmapInfo.bmiHeader.biHeight = -viewRect.Height(); 
    m_bitmapInfo.bmiHeader.biPlanes = 1; 
    m_bitmapInfo.bmiHeader.biBitCount = 1; 
    m_bitmapInfo.bmiHeader.biCompression = BI_RGB; 
    m_bitmapInfo.bmiHeader.biSizeImage = 0; 
    m_bitmapInfo.bmiHeader.biXPelsPerMeter = 0; 
    m_bitmapInfo.bmiHeader.biYPelsPerMeter = 0; 
    m_bitmapInfo.bmiHeader.biClrUsed = 0; 
    m_bitmapInfo.bmiHeader.biClrImportant = 0;
    m_bitmapInfo.bmiColors[0] = m_colorWhite;
    m_bitmapInfo.bmiColors[1] = m_colorBlack;

    // put a nice pattern into our bits
    unsigned char * pBits;
    for (int row = 0; row < viewRect.Height(); row++)
    {
        pBits = m_pDisplayMemory + row * m_nDisplayBytesPerLine;
        unsigned char byte = (row % 2) ? 0xAA : ~0xAA;
        //if (row < 20) byte = 0xFF; else byte = (row % 2) ? 0xFF : 0x00;
        //byte = 0x00;
        for (unsigned int col = 0; col < m_nDisplayBytesPerLine; col++) *pBits++ = byte;
    }

    // load our mp code bitmap for the cursor
    VERIFY(m_bitmapMP.LoadBitmap(IDB_BITMAP_MPCODE));

    m_hCursor = NULL;
    m_hCursorOrig = (HCURSOR)::GetClassLong(pView->GetSafeHwnd(), GCL_HCURSOR);
}
bool TestExtString::test_strnatcasecmp() {
  VERIFY(f_strnatcasecmp("a", "Ab") < 0);
  return Count(true);
}
示例#7
0
int
dmu_objset_open_impl(spa_t *spa, dsl_dataset_t *ds, blkptr_t *bp,
    objset_t **osp)
{
	objset_t *os;
	int i, err;

	ASSERT(ds == NULL || MUTEX_HELD(&ds->ds_opening_lock));

	os = kmem_zalloc(sizeof (objset_t), KM_PUSHPAGE);
	os->os_dsl_dataset = ds;
	os->os_spa = spa;
	os->os_rootbp = bp;
	if (!BP_IS_HOLE(os->os_rootbp)) {
		uint32_t aflags = ARC_WAIT;
		zbookmark_t zb;
		SET_BOOKMARK(&zb, ds ? ds->ds_object : DMU_META_OBJSET,
		    ZB_ROOT_OBJECT, ZB_ROOT_LEVEL, ZB_ROOT_BLKID);

		if (DMU_OS_IS_L2CACHEABLE(os))
			aflags |= ARC_L2CACHE;
		if (DMU_OS_IS_L2COMPRESSIBLE(os))
			aflags |= ARC_L2COMPRESS;

		dprintf_bp(os->os_rootbp, "reading %s", "");
		err = arc_read(NULL, spa, os->os_rootbp,
		    arc_getbuf_func, &os->os_phys_buf,
		    ZIO_PRIORITY_SYNC_READ, ZIO_FLAG_CANFAIL, &aflags, &zb);
		if (err != 0) {
			kmem_free(os, sizeof (objset_t));
			/* convert checksum errors into IO errors */
			if (err == ECKSUM)
				err = SET_ERROR(EIO);
			return (err);
		}

		/* Increase the blocksize if we are permitted. */
		if (spa_version(spa) >= SPA_VERSION_USERSPACE &&
		    arc_buf_size(os->os_phys_buf) < sizeof (objset_phys_t)) {
			arc_buf_t *buf = arc_buf_alloc(spa,
			    sizeof (objset_phys_t), &os->os_phys_buf,
			    ARC_BUFC_METADATA);
			bzero(buf->b_data, sizeof (objset_phys_t));
			bcopy(os->os_phys_buf->b_data, buf->b_data,
			    arc_buf_size(os->os_phys_buf));
			(void) arc_buf_remove_ref(os->os_phys_buf,
			    &os->os_phys_buf);
			os->os_phys_buf = buf;
		}

		os->os_phys = os->os_phys_buf->b_data;
		os->os_flags = os->os_phys->os_flags;
	} else {
		int size = spa_version(spa) >= SPA_VERSION_USERSPACE ?
		    sizeof (objset_phys_t) : OBJSET_OLD_PHYS_SIZE;
		os->os_phys_buf = arc_buf_alloc(spa, size,
		    &os->os_phys_buf, ARC_BUFC_METADATA);
		os->os_phys = os->os_phys_buf->b_data;
		bzero(os->os_phys, size);
	}

	/*
	 * Note: the changed_cb will be called once before the register
	 * func returns, thus changing the checksum/compression from the
	 * default (fletcher2/off).  Snapshots don't need to know about
	 * checksum/compression/copies.
	 */
	if (ds) {
		err = dsl_prop_register(ds,
		    zfs_prop_to_name(ZFS_PROP_PRIMARYCACHE),
		    primary_cache_changed_cb, os);
		if (err == 0) {
			err = dsl_prop_register(ds,
			    zfs_prop_to_name(ZFS_PROP_SECONDARYCACHE),
			    secondary_cache_changed_cb, os);
		}
		if (!dsl_dataset_is_snapshot(ds)) {
			if (err == 0) {
				err = dsl_prop_register(ds,
				    zfs_prop_to_name(ZFS_PROP_CHECKSUM),
				    checksum_changed_cb, os);
			}
			if (err == 0) {
				err = dsl_prop_register(ds,
				    zfs_prop_to_name(ZFS_PROP_COMPRESSION),
				    compression_changed_cb, os);
			}
			if (err == 0) {
				err = dsl_prop_register(ds,
				    zfs_prop_to_name(ZFS_PROP_COPIES),
				    copies_changed_cb, os);
			}
			if (err == 0) {
				err = dsl_prop_register(ds,
				    zfs_prop_to_name(ZFS_PROP_DEDUP),
				    dedup_changed_cb, os);
			}
			if (err == 0) {
				err = dsl_prop_register(ds,
				    zfs_prop_to_name(ZFS_PROP_LOGBIAS),
				    logbias_changed_cb, os);
			}
			if (err == 0) {
				err = dsl_prop_register(ds,
				    zfs_prop_to_name(ZFS_PROP_SYNC),
				    sync_changed_cb, os);
			}
		}
		if (err != 0) {
			VERIFY(arc_buf_remove_ref(os->os_phys_buf,
			    &os->os_phys_buf));
			kmem_free(os, sizeof (objset_t));
			return (err);
		}
	} else if (ds == NULL) {
		/* It's the meta-objset. */
		os->os_checksum = ZIO_CHECKSUM_FLETCHER_4;
		os->os_compress = ZIO_COMPRESS_LZJB;
		os->os_copies = spa_max_replication(spa);
		os->os_dedup_checksum = ZIO_CHECKSUM_OFF;
		os->os_dedup_verify = 0;
		os->os_logbias = 0;
		os->os_sync = 0;
		os->os_primary_cache = ZFS_CACHE_ALL;
		os->os_secondary_cache = ZFS_CACHE_ALL;
	}

	if (ds == NULL || !dsl_dataset_is_snapshot(ds))
		os->os_zil_header = os->os_phys->os_zil_header;
	os->os_zil = zil_alloc(os, &os->os_zil_header);

	for (i = 0; i < TXG_SIZE; i++) {
		list_create(&os->os_dirty_dnodes[i], sizeof (dnode_t),
		    offsetof(dnode_t, dn_dirty_link[i]));
		list_create(&os->os_free_dnodes[i], sizeof (dnode_t),
		    offsetof(dnode_t, dn_dirty_link[i]));
	}
	list_create(&os->os_dnodes, sizeof (dnode_t),
	    offsetof(dnode_t, dn_link));
	list_create(&os->os_downgraded_dbufs, sizeof (dmu_buf_impl_t),
	    offsetof(dmu_buf_impl_t, db_link));

	mutex_init(&os->os_lock, NULL, MUTEX_DEFAULT, NULL);
	mutex_init(&os->os_obj_lock, NULL, MUTEX_DEFAULT, NULL);
	mutex_init(&os->os_user_ptr_lock, NULL, MUTEX_DEFAULT, NULL);

	DMU_META_DNODE(os) = dnode_special_open(os,
	    &os->os_phys->os_meta_dnode, DMU_META_DNODE_OBJECT,
	    &os->os_meta_dnode);
	if (arc_buf_size(os->os_phys_buf) >= sizeof (objset_phys_t)) {
		DMU_USERUSED_DNODE(os) = dnode_special_open(os,
		    &os->os_phys->os_userused_dnode, DMU_USERUSED_OBJECT,
		    &os->os_userused_dnode);
		DMU_GROUPUSED_DNODE(os) = dnode_special_open(os,
		    &os->os_phys->os_groupused_dnode, DMU_GROUPUSED_OBJECT,
		    &os->os_groupused_dnode);
	}

	/*
	 * We should be the only thread trying to do this because we
	 * have ds_opening_lock
	 */
	if (ds) {
		mutex_enter(&ds->ds_lock);
		ASSERT(ds->ds_objset == NULL);
		ds->ds_objset = os;
		mutex_exit(&ds->ds_lock);
	}

	*osp = os;
	return (0);
}
示例#8
0
BOOL CPPageOutput::OnInitDialog()
{
	__super::OnInitDialog();

	AppSettings& s = AfxGetAppSettings();

	m_iDSVideoRendererType	= s.iDSVideoRendererType;
	m_iRMVideoRendererType	= s.iRMVideoRendererType;
	m_iQTVideoRendererType	= s.iQTVideoRendererType;
	m_iAPSurfaceUsage		= s.iAPSurfaceUsage;
	m_fVMRSyncFix			= s.fVMRSyncFix;
	m_iDX9Resizer			= s.iDX9Resizer;
	m_fVMR9MixerMode		= s.fVMR9MixerMode;
	m_fVMR9MixerYUV			= s.fVMR9MixerYUV;
	m_fD3DFullscreen		= s.fD3DFullscreen;
	m_iEvrBuffers			= s.iEvrBuffers-3;

	// Multi-Monitor code
	CString str;
	m_iMonitorType = 0;

	CMonitor monitor;
	CMonitors monitors;

	m_iMonitorTypeCtrl.AddString(ResStr(IDS_FULLSCREENMONITOR_CURRENT));
	m_MonitorDisplayNames.Add(_T("Current"));
	if(s.f_hmonitor == _T("Current"))
	{
		m_iMonitorType = m_iMonitorTypeCtrl.GetCount()-1;
	}

	for ( int i = 0; i < monitors.GetCount(); i++ )
	{
		monitor = monitors.GetMonitor( i );
		monitor.GetName(str);
		
		if(monitor.IsMonitor())
		{
			DISPLAY_DEVICE displayDevice;
			ZeroMemory(&displayDevice, sizeof(displayDevice));
			displayDevice.cb = sizeof(displayDevice);
			VERIFY(EnumDisplayDevices(str, 0,  &displayDevice, 0));
						
			m_iMonitorTypeCtrl.AddString(str+_T(" - ")+displayDevice.DeviceString);
			m_MonitorDisplayNames.Add(str);
			
			if(s.f_hmonitor == str && m_iMonitorType == 0)
			{
				m_iMonitorType = m_iMonitorTypeCtrl.GetCount()-1;
			}
		}
	}

	//(m_iMonitorTypeCtrl.GetCount() > 2)	? {GetDlgItem(IDC_COMBO2)->EnableWindow(TRUE)} : GetDlgItem(IDC_COMBO2)->EnableWindow(FALSE);
	if(m_iMonitorTypeCtrl.GetCount() > 2)
	{
		GetDlgItem(IDC_COMBO2)->EnableWindow(TRUE);
	}
	else
	{
		m_iMonitorType = 0;
		GetDlgItem(IDC_COMBO2)->EnableWindow(FALSE);
	}

	m_AudioRendererDisplayNames.Add(_T(""));
	m_iAudioRendererTypeCtrl.AddString(_T("System Default"));
	m_iAudioRendererType = 0;

	BeginEnumSysDev(CLSID_AudioRendererCategory, pMoniker)
	{
		LPOLESTR olestr = NULL;
		if(FAILED(pMoniker->GetDisplayName(0, 0, &olestr)))
			continue;

		CStringW str(olestr);
		CoTaskMemFree(olestr);

		m_AudioRendererDisplayNames.Add(CString(str));

		CComPtr<IPropertyBag> pPB;
		if(SUCCEEDED(pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void**)&pPB)))
		{
			CComVariant var;
			pPB->Read(CComBSTR(_T("FriendlyName")), &var, NULL);

			CString fstr(var.bstrVal);

			var.Clear();
			if(SUCCEEDED(pPB->Read(CComBSTR(_T("FilterData")), &var, NULL)))
			{			
				BSTR* pbstr;
				if(SUCCEEDED(SafeArrayAccessData(var.parray, (void**)&pbstr)))
				{
					fstr.Format(_T("%s (%08x)"), CString(fstr), *((DWORD*)pbstr + 1));
					SafeArrayUnaccessData(var.parray);
				}
			}

			m_iAudioRendererTypeCtrl.AddString(fstr);
		}
		else
		{
			m_iAudioRendererTypeCtrl.AddString(CString(str));
		}

		if(s.AudioRendererDisplayName == str && m_iAudioRendererType == 0)
		{
			m_iAudioRendererType = m_iAudioRendererTypeCtrl.GetCount()-1;
		}
	}
示例#9
0
文件: dsl_pool.c 项目: RJVB/zfs
dsl_pool_t *
dsl_pool_create(spa_t *spa, nvlist_t *zplprops, uint64_t txg)
{
	int err;
	dsl_pool_t *dp = dsl_pool_open_impl(spa, txg);
	dmu_tx_t *tx = dmu_tx_create_assigned(dp, txg);
	objset_t *os;
	dsl_dataset_t *ds;
	uint64_t obj;

	rrw_enter(&dp->dp_config_rwlock, RW_WRITER, FTAG);

	/* create and open the MOS (meta-objset) */
	dp->dp_meta_objset = dmu_objset_create_impl(spa,
	    NULL, &dp->dp_meta_rootbp, DMU_OST_META, tx);

	/* create the pool directory */
	err = zap_create_claim(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
	    DMU_OT_OBJECT_DIRECTORY, DMU_OT_NONE, 0, tx);
	ASSERT0(err);

	/* Initialize scan structures */
	VERIFY0(dsl_scan_init(dp, txg));

	/* create and open the root dir */
	dp->dp_root_dir_obj = dsl_dir_create_sync(dp, NULL, NULL, tx);
	VERIFY0(dsl_dir_hold_obj(dp, dp->dp_root_dir_obj,
	    NULL, dp, &dp->dp_root_dir));

	/* create and open the meta-objset dir */
	(void) dsl_dir_create_sync(dp, dp->dp_root_dir, MOS_DIR_NAME, tx);
	VERIFY0(dsl_pool_open_special_dir(dp,
	    MOS_DIR_NAME, &dp->dp_mos_dir));

	if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
		/* create and open the free dir */
		(void) dsl_dir_create_sync(dp, dp->dp_root_dir,
		    FREE_DIR_NAME, tx);
		VERIFY0(dsl_pool_open_special_dir(dp,
		    FREE_DIR_NAME, &dp->dp_free_dir));

		/* create and open the free_bplist */
		obj = bpobj_alloc(dp->dp_meta_objset, SPA_MAXBLOCKSIZE, tx);
		VERIFY(zap_add(dp->dp_meta_objset, DMU_POOL_DIRECTORY_OBJECT,
		    DMU_POOL_FREE_BPOBJ, sizeof (uint64_t), 1, &obj, tx) == 0);
		VERIFY0(bpobj_open(&dp->dp_free_bpobj,
		    dp->dp_meta_objset, obj));
	}

	if (spa_version(spa) >= SPA_VERSION_DSL_SCRUB)
		dsl_pool_create_origin(dp, tx);

	/* create the root dataset */
	obj = dsl_dataset_create_sync_dd(dp->dp_root_dir, NULL, 0, tx);

	/* create the root objset */
	VERIFY0(dsl_dataset_hold_obj(dp, obj, FTAG, &ds));
	VERIFY(NULL != (os = dmu_objset_create_impl(dp->dp_spa, ds,
	    dsl_dataset_get_blkptr(ds), DMU_OST_ZFS, tx)));
#ifdef _KERNEL
	zfs_create_fs(os, kcred, zplprops, tx);
	//zfs_create_fs(os, kcred, ZPL_VERSION, tx);// FIXME, should be props
#endif
	dsl_dataset_rele(ds, FTAG);

	dmu_tx_commit(tx);

	rrw_exit(&dp->dp_config_rwlock, FTAG);

	return (dp);
}
	_OX_WINDOWS_VERSION()
	{
		OSVersion.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
		VERIFY(::GetVersionEx(&OSVersion));
	}
示例#11
0
static AuthorizationRef
IdAuthCreateWithFork(void)
{
   int fds[2] = { -1, -1, };
   pid_t child;
   AuthorizationRef auth = NULL;
   struct {
      Bool success;
      AuthorizationExternalForm ext;
   } data;
   uint8 buf;

   /*
    * XXX One more Apple bug related to thread credentials:
    *     AuthorizationCreate() incorrectly uses process instead of thread
    *     credentials. So for this code to properly work in the VMX for
    *     example, we must do this elaborate fork/handshake dance. Fortunately
    *     this function is only called once very early when a process starts.
    */

   if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) {
      Warning("%s: socketpair() failed.\n", __func__);
      goto out;
   }

   child = fork();
   if (child < 0) {
      Warning("%s: fork() failed.\n", __func__);
      goto out;
   }

   if (child) {
      size_t rcvd;
      int status;
      pid_t result;

      // Parent: use fds[0]

      // Wait until the child has created its process ref to the auth session.
      for (rcvd = 0; rcvd < sizeof data; ) {
         ssize_t actual;

         actual = read(fds[0], (void *)&data + rcvd, sizeof data - rcvd);
         ASSERT(actual <= sizeof data - rcvd);
         if (actual < 0) {
            ASSERT(errno == EPIPE);
            Warning("%s: parent read() failed because child died.\n",
                    __func__);
            data.success = FALSE;
            break;
         }

         rcvd += actual;
      }

      if (data.success) {
         if (AuthorizationCreateFromExternalForm(&data.ext, &auth)
             != errAuthorizationSuccess) {
            Warning("%s: parent AuthorizationCreateFromExternalForm() "
                    "failed.\n", __func__);
         }
      }

      // Tell the child it can now destroy its process ref to the auth session.
      write(fds[0], &buf, sizeof buf);

      // Reap the child, looping if we get interrupted by a signal.
      do {
         result = waitpid(child, &status, 0);
      } while (result == -1 && errno == EINTR);

      VERIFY(result == child);
   } else {
      // Child: use fds[1]

      data.success = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,
                                         kAuthorizationFlagDefaults, &auth)
                     == errAuthorizationSuccess;
      if (data.success) {
         data.success = AuthorizationMakeExternalForm(auth, &data.ext)
                        == errAuthorizationSuccess;
         if (!data.success) {
            Warning("%s: child AuthorizationMakeExternalForm() failed.\n",
                    __func__);
         }
      } else {
         Warning("%s: child AuthorizationCreate() failed.\n", __func__);
      }

      // Tell the parent it can now create a process ref to the auth session.
      if (write(fds[1], &data, sizeof data) == sizeof data) {
         /*
          * Wait until the child can destroy its process ref to the auth
          * session.
          */

         for (;;) {
            ssize_t actual = read(fds[1], &buf, sizeof buf);

            ASSERT(actual <= sizeof buf);
            if (actual) {
               break;
            }
         }
      }

      /*
       * This implicitly:
       * o Destroys the child process ref to the Authorization session.
       * o Closes fds[0] and fds[1]
       */

      exit(0);
   }

out:
   close(fds[0]);
   close(fds[1]);

   return auth;
}
BOOL COXNetBrowseTree::CreateChildren(HTREEITEM hParentItem, NETRESOURCE* pParentNetResources)
// --- In  : hParentItem : Node of which the children nodes have to be created
//			 pParentNetResources : Net resource of this parent node
// --- Out : 
// --- Returns :
// --- Effect : Computes the netresources of the children and creates the child nodes
{
	HANDLE hEnum = NULL;
	DWORD dwScope = pParentNetResources == NULL ? m_nResourceScope : pParentNetResources->dwScope;
	DWORD nResult = WNetOpenEnum(
		dwScope,				// scope of enumeration 
		RESOURCETYPE_ANY,		// resource types to list 
		0,						// resource usage to list 
		pParentNetResources,	// pointer to resource structure 
		&hEnum);				// pointer to enumeration handle buffer 
	if (nResult != NO_ERROR)
	{
		TRACE2("COXNetBrowseTree::CreateChildren : WNetOpenEnum failed with error code %i == 0x%X\n",
			nResult, nResult);
		ReportNetError(nResult, pParentNetResources == NULL ? NULL : pParentNetResources->lpRemoteName);
		return FALSE;
	}

	DWORD nCurrentCount(0);
	DWORD nCurrentSkipCount(0);
	/* =============================================================================== */	

	// The problem with the WNetEnumResoiurce fuction is that allthough you use 
	// 0xFFFFFFFF as requested resource count (this means everything) the function
	// does NOT return ERROR_MORE_DATA if the buffer is too small.  It only returns
	// this value if the buffer supplied is too small even for one value, in this
	// case the space needed to hold the first resource found in the enumeration
	// Normally the size of this resource should be sizeof(NETRESOURCE) which is 
	// 32 bytes but experience learned that this fluctuates between 32 bytes and 
	// more than 1000 bytes.  This is probably due to the fact that WNetEnumResource
	// also needs allocated memory for the strings inside the NETRESOURCE struct.
	// This leads to the conclusion that we cannot calculate with certainty the size
	// of the buffer we need for a certain number of resources.  The most robust
	// solution to this problem is to request a absolute number of resources, make
	// an serious and realistic estimation of the maximum amount of memory needed
	// to hold ALL requested resources and then test to see whether you have retrieved
	// all requested resources.  If this is TRUE then again enumerate the resources
	// to determine whether there aren't any left and so on until the returned
	// number of resources is smaller than the requested number.  This last remark
	// explains why we need to be sure that the requested number of resources 
	// allways fit in the amount of memory we allocated for the buffer.  We could 
	// alocated a very big buffer but we prefer the loop.

	// Also note that we don't use NETRESOURCE* pRes = new NETRESOURCE[Count]
	// because the array allocated will be an array of structs of size sizeof(NETRESOURCE)
	// and that's just not correct to  hold one netresource. That's why we use
	// GlobalAlloc.

	// USERS WHO WANT TO TUNE THE PERFORMANCE OF THIS FUNCTION CAN PLAY WITH THE 
	// NUMBER OF NETRESOURCES VIA THE nCOUNT VARIABLE AND WITH THE SIZE OF THE 
	// ALLOCATED BUFFER VIA THE nBUFFERSIZE VARIABLE BUT KEEP THE REMARKS ABOVE
	// IN MIND.
	/* =============================================================================== */
	// Start with a reasonable buffer size
	DWORD nCount = 5;
	DWORD nBufferSize = 5000;
	LPNETRESOURCE rgpNetResources = (LPNETRESOURCE)GlobalAlloc(GPTR, nBufferSize);

	while (TRUE)
	{
		DWORD nTempCount = nCount;
		DWORD nTempBufferSize = nBufferSize;
		memset(rgpNetResources, 0, nBufferSize);
		DWORD nResult2 = WNetEnumResource(
			hEnum,					// handle to enumeration 
			&nTempCount,				// pointer to entries to list 
			(LPVOID)rgpNetResources, // pointer to buffer for results 
			&nTempBufferSize);			// pointer to buffer size variable 
		TRACE2("COXNetBrowseTree::WNetEnumResource : Number of Netresources (%i), in buffersize (0x%X)\n", nTempCount, nTempBufferSize);

		if ((nResult2 != NO_ERROR) && (nResult2 != ERROR_NO_MORE_ITEMS) &&
			(nResult2 != ERROR_MORE_DATA))
		{
			TRACE2("COXNetBrowseTree::CreateChildren : WNetEnumResource failed with error code %i == 0x%X\n",
				nResult2, nResult2);
			ReportNetError(nResult2, pParentNetResources == NULL ? NULL : pParentNetResources->lpRemoteName);
			// ... Cleanup the handle and memeory allocated
			VERIFY(WNetCloseEnum(hEnum) == NO_ERROR);
			GlobalFree((HGLOBAL)rgpNetResources);
			return FALSE;
		}

		if (nResult2 == ERROR_NO_MORE_ITEMS)
			nTempCount = 0;

		// Loop the requested number of NetResources and make tree item nodes
		{
			HTREEITEM hNewItem;
			NETRESOURCE* pSourceNetResource = NULL;
			NETRESOURCE* pCopyNetResource = NULL;
			DWORD nIndex;
			DWORD nSkipCount = 0;
			for (nIndex = 0; nIndex < nTempCount; nIndex++)
			{
				pSourceNetResource  = &rgpNetResources[nIndex];

				// Check special case for disks and printers
				if ((pSourceNetResource->dwType == RESOURCETYPE_DISK) && !m_bShowDisks)
				{
					// Skip this item
					nSkipCount++;
					continue;
				}
				if ((pSourceNetResource->dwType == RESOURCETYPE_PRINT) && !m_bShowPrinters)
				{
					// Skip this item
					nSkipCount++;
					continue;
				}

				// ... Create a new item
				hNewItem = InsertResourceItem(pSourceNetResource, hParentItem);
				if (hNewItem  == NULL)
				{
					TRACE0("COXNetBrowseTree::InsertResourceItem returned NULL\n");
					// Skip this item
					nSkipCount++;
					continue;
				}

				// Add a copy to the map
				// ... Should not yet be in map
#ifdef _DEBUG
				NETRESOURCE* pCheckNetResource = NULL;
				ASSERT(!m_resourceMap.Lookup(hNewItem, pCheckNetResource));
#endif // _DEBUG
				pCopyNetResource = new NETRESOURCE;
				// ... Copy the struct itself
				memcpy(pCopyNetResource, pSourceNetResource, sizeof(NETRESOURCE));
				// ... Make a copy of all the string members
				if (pSourceNetResource->lpLocalName != NULL)
				{
					size_t len = _tcslen(pSourceNetResource->lpLocalName) + 1;
					pCopyNetResource->lpLocalName = new TCHAR[len];
					UTBStr::tcscpy(pCopyNetResource->lpLocalName, len, pSourceNetResource->lpLocalName);
				}
				else
				{
					pCopyNetResource->lpLocalName = new TCHAR[1];
					*pCopyNetResource->lpLocalName = _T('\0');
				}

				if (pSourceNetResource->lpRemoteName != NULL)
				{
					size_t len = _tcslen(pSourceNetResource->lpRemoteName) + 1;
					pCopyNetResource->lpRemoteName = new TCHAR[len];
					UTBStr::tcscpy(pCopyNetResource->lpRemoteName, len, pSourceNetResource->lpRemoteName);
				}
				else
				{
					pCopyNetResource->lpRemoteName = new TCHAR[1];
					*pCopyNetResource->lpRemoteName = _T('\0');
				}

				if (pSourceNetResource->lpComment != NULL)
				{
					size_t len = _tcslen(pSourceNetResource->lpComment) + 1;
					pCopyNetResource->lpComment = new TCHAR[len];
					UTBStr::tcscpy(pCopyNetResource->lpComment, len, pSourceNetResource->lpComment);
				}
				else
				{
					pCopyNetResource->lpComment = new TCHAR[1];
					*pCopyNetResource->lpComment = _T('\0');
				}

				if (pSourceNetResource->lpProvider != NULL)
				{
					size_t len = _tcslen(pSourceNetResource->lpProvider) + 1;
					pCopyNetResource->lpProvider = new TCHAR[len];
					UTBStr::tcscpy(pCopyNetResource->lpProvider, len, pSourceNetResource->lpProvider);
				}
				else
				{
					pCopyNetResource->lpProvider = new TCHAR[1];
					*pCopyNetResource->lpProvider = _T('\0');
				}

				// ... Add to map
				m_resourceMap.SetAt(hNewItem, pCopyNetResource);
			}

			// we need to keep track of the real number of nodes because we 
			// need it to set the correct treeitem number for the parent node
			nCurrentCount += nTempCount;
			nCurrentSkipCount += nSkipCount;

			if (hParentItem != NULL)
			{
				// Mark the parent node as expanded at least once
				VERIFY(SetItemState(hParentItem, TVIS_EXPANDEDONCE, TVIS_EXPANDEDONCE));

				// Set the number of child items to the correct value
				TV_ITEM item;
				item.hItem = hParentItem;
				item.mask = TVIF_CHILDREN;
				ASSERT(nSkipCount <= nTempCount);
				item.cChildren = nCurrentCount - nCurrentSkipCount;
				VERIFY(SetItem(&item));
			}
		}

		if (nResult2 == ERROR_MORE_DATA  || nTempCount == nCount)
			// Possibly there is more data to retrieve
		{
			nTempCount = nCount;
			continue;
		}
		else
			// There was no error and there isn't anymore data to retrieve
			break;
	}

	// Cleanup the handle and allocated memory
	VERIFY(WNetCloseEnum(hEnum) == NO_ERROR);
	GlobalFree((HGLOBAL)rgpNetResources);
	return TRUE;
}
示例#13
0
文件: pkcs10.cpp 项目: mingpen/OpenNT
HRESULT CPkcs10::put_PublicKey(HCRYPTPROV hprov, DWORD dwKeySpec)
// Store the indicated public key in the subjectPublicKeyInfo field
// of the CertificationRequest. From PKCS #10:
//
//		subjectPublicKeyInfo contains information about the public 
//		key being certified. The information identifies the entity's 
//		public-key algorithm (and any associated parameters); examples 
//		of public-key algorithms include X.509's rsa and PKCS #1's 
//		rsaEncryption. 
//
//		The information also includes a bit-string representation of 
//		the entity's public key. For both public-key algorithms just 
//		mentioned, the bit string contains the BER encoding of a 
//		value of X.509/PKCS #1 type RSAPublicKey
//	
	{
	HRESULT hr = m_pworld->HprovToSubjectPublicKeyInfo(
					hprov, 
                    dwKeySpec,
					m_preq->certificationRequestInfo.subjectPublicKeyInfo
					);
	#if defined(_DEBUG) 
    // Check to to make sure we can read what we wrote
    if (hr==S_OK)
		{
		HCRYPTKEY hkeyuser;
		VERIFY(CryptGetUserKey(hprov, dwKeySpec, &hkeyuser));
		BYTE rgb1[1024];	DWORD cb1 = 1024;
//		BYTE rgb2[1024];	DWORD cb2 = 1024;
		VERIFY(CryptExportKey(hkeyuser, 0, PUBLICKEYBLOB, 0, rgb1, &cb1));
//		VERIFY(CryptExportKey(hkeypub,  0, PUBLICKEYBLOB, 0, rgb2, &cb2));
//			Would like to do the above, but CAPI won't let us export an imported key
//			(*(&(*##$^*&. So, having verified we can successfully fully import, we just
//			go get the raw bits again.
		BLOB b;	m_pworld->Init(b);
		
        HCRYPTKEY hkeypub;
		if (get_PublicKey(hprov, &hkeypub) == S_OK)
            {
		    VERIFY(CryptDestroyKey(hkeypub));
            }
        else
            OutputDebugString("DigSig: Public key retrieval failed\n");

		VERIFY(m_pworld->PublicKeyBlobFromBitString(m_preq->certificationRequestInfo.subjectPublicKeyInfo, dwKeySpec, &b) == S_OK);
		DWORD cb2 = b.cbSize; BYTE* rgb2 = b.pBlobData;
		VERIFY(cb1 == cb2);
		if (cb1 != cb2)
            {
            cb1 = min(cb1,cb2);
            cb2 = cb1;
            }
        ((PUBLICKEYSTRUC*)rgb1)->reserved = 0;
		((PUBLICKEYSTRUC*)rgb2)->reserved = 0;
		VERIFY(memcmp(rgb1, rgb2, cb1) == 0);
		VERIFY(CryptDestroyKey(hkeyuser));

		m_pworld->Free(b);
		}
	#endif

	MakeDirty();
	return hr;
	}
示例#14
0
template<class T, USHORT default_port> void CHttpAgentT<T, default_port>::DoStartHttp(TAgentSocketObj* pSocketObj)
{
	THttpObj* pHttpObj = m_objPool.PickFreeHttpObj(this, pSocketObj);
	VERIFY(SetConnectionReserved(pSocketObj, pHttpObj));
}
示例#15
0
bool TestExtString::test_strcasecmp() {
  VERIFY(f_strcasecmp("a", "a") == 0);
  VERIFY(f_strcasecmp("a", "A") == 0);
  VERIFY(f_strcasecmp("A", "a") == 0);
  VERIFY(f_strcasecmp("A", "A") == 0);

  VERIFY(f_strcasecmp("a", "b") < 0);
  VERIFY(f_strcasecmp("a", "B") < 0);
  VERIFY(f_strcasecmp("A", "b") < 0);
  VERIFY(f_strcasecmp("A", "B") < 0);
  VERIFY(f_strcasecmp("b", "a") > 0);
  VERIFY(f_strcasecmp("B", "a") > 0);
  VERIFY(f_strcasecmp("b", "A") > 0);
  VERIFY(f_strcasecmp("B", "A") > 0);

  VERIFY(f_strcasecmp("_", "a") < 0);
  VERIFY(f_strcasecmp("_", "A") < 0);
  VERIFY(f_strcasecmp("a", "_") > 0);
  VERIFY(f_strcasecmp("A", "_") > 0);

  VERIFY(f_strcasecmp("@", "`") < 0);
  VERIFY(f_strcasecmp("`", "@") > 0);

  VERIFY(f_strcasecmp("a", "a0") < 0);
  VERIFY(f_strcasecmp("a", "A0") < 0);
  VERIFY(f_strcasecmp("A", "a0") < 0);
  VERIFY(f_strcasecmp("A", "A0") < 0);
  VERIFY(f_strcasecmp("a0", "a") > 0);
  VERIFY(f_strcasecmp("a0", "A") > 0);
  VERIFY(f_strcasecmp("A0", "a") > 0);
  VERIFY(f_strcasecmp("A0", "A") > 0);

  return Count(true);
}
示例#16
0
CRARFile::~CRARFile()
{
	Close();
	if (m_hLibUnRar)
		VERIFY( FreeLibrary(m_hLibUnRar) );
}
示例#17
0
bool TestExtString::test_strncasecmp() {
  VERIFY(f_strncasecmp("a", "Ab", 1).same(0));
  return Count(true);
}
示例#18
0
LONG WINAPI CMiniDump::UnhandledExceptionFilter(_EXCEPTION_POINTERS* lpTopLevelExceptionFilter)
{
    LONG    retval = EXCEPTION_CONTINUE_SEARCH;
    BOOL    bDumpCreated = FALSE;
    HMODULE hDll = nullptr;
    TCHAR   szResult[800];
    szResult[0] = _T('\0');
    CPath   dumpPath;

#if ENABLE_MINIDUMP
    hDll = ::LoadLibrary(_T("dbghelp.dll"));

    if (hDll != nullptr) {
        MINIDUMPWRITEDUMP pMiniDumpWriteDump = (MINIDUMPWRITEDUMP)::GetProcAddress(hDll, "MiniDumpWriteDump");
        if (pMiniDumpWriteDump != nullptr && AfxGetMyApp()->GetAppSavePath(dumpPath)) {
            // Check that the folder actually exists
            if (!FileExists(dumpPath)) {
                VERIFY(CreateDirectory(dumpPath, nullptr));
            }

            CString strDumpName = AfxGetApp()->m_pszExeName;
            strDumpName.Append(_T(".exe.") + VersionInfo::GetVersionString() + _T(".dmp"));
            dumpPath.Append(strDumpName);

            // create the file
            HANDLE hFile = ::CreateFile(dumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, nullptr, CREATE_ALWAYS,
                                        FILE_ATTRIBUTE_NORMAL, nullptr);

            if (hFile != INVALID_HANDLE_VALUE) {
                _MINIDUMP_EXCEPTION_INFORMATION ExInfo;

                ExInfo.ThreadId = ::GetCurrentThreadId();
                ExInfo.ExceptionPointers = lpTopLevelExceptionFilter;
                ExInfo.ClientPointers = FALSE;

                // write the dump
                bDumpCreated = pMiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, &ExInfo, nullptr, nullptr);
                if (bDumpCreated) {
                    _stprintf_s(szResult, _countof(szResult), ResStr(IDS_MPC_CRASH), dumpPath);
                    retval = EXCEPTION_EXECUTE_HANDLER;
                } else {
                    _stprintf_s(szResult, _countof(szResult), ResStr(IDS_MPC_MINIDUMP_FAIL), dumpPath, GetLastError());
                }

                ::CloseHandle(hFile);
            } else {
                _stprintf_s(szResult, _countof(szResult), ResStr(IDS_MPC_MINIDUMP_FAIL), dumpPath, GetLastError());
            }
        }
        FreeLibrary(hDll);
    }

    if (szResult[0]) {
        switch (MessageBox(nullptr, szResult, _T("MPC-HC - Mini Dump"), bDumpCreated ? MB_YESNO : MB_OK)) {
            case IDYES:
                ShellExecute(nullptr, _T("open"), BUGS_URL, nullptr, nullptr, SW_SHOWDEFAULT);
                ExploreToFile(dumpPath);
                break;
            case IDNO:
                retval = EXCEPTION_CONTINUE_SEARCH; // rethrow the exception to make easier attaching a debugger
                break;
        }
    }
#else
    if (MessageBox(nullptr, ResStr(IDS_MPC_BUG_REPORT), ResStr(IDS_MPC_BUG_REPORT_TITLE), MB_YESNO) == IDYES) {
        ShellExecute(nullptr, _T("open"), DOWNLOAD_URL, nullptr, nullptr, SW_SHOWDEFAULT);
    }
#endif // DISABLE_MINIDUMP

    return retval;
}
示例#19
0
bool TestExtString::test_strcoll() {
  VERIFY(f_strcoll("a", "b") < 0);
  VERIFY(f_strcoll("a", "A") > 0);
  return Count(true);
}
示例#20
0
bool TestExtString::test_str_shuffle() {
  VERIFY(f_str_shuffle("ABC").size() == 3);
  return Count(true);
}
示例#21
0
void
dmu_objset_evict(objset_t *os)
{
	int t;

	dsl_dataset_t *ds = os->os_dsl_dataset;

	for (t = 0; t < TXG_SIZE; t++)
		ASSERT(!dmu_objset_is_dirty(os, t));

	if (ds) {
		if (!dsl_dataset_is_snapshot(ds)) {
			VERIFY0(dsl_prop_unregister(ds,
			    zfs_prop_to_name(ZFS_PROP_CHECKSUM),
			    checksum_changed_cb, os));
			VERIFY0(dsl_prop_unregister(ds,
			    zfs_prop_to_name(ZFS_PROP_COMPRESSION),
			    compression_changed_cb, os));
			VERIFY0(dsl_prop_unregister(ds,
			    zfs_prop_to_name(ZFS_PROP_COPIES),
			    copies_changed_cb, os));
			VERIFY0(dsl_prop_unregister(ds,
			    zfs_prop_to_name(ZFS_PROP_DEDUP),
			    dedup_changed_cb, os));
			VERIFY0(dsl_prop_unregister(ds,
			    zfs_prop_to_name(ZFS_PROP_LOGBIAS),
			    logbias_changed_cb, os));
			VERIFY0(dsl_prop_unregister(ds,
			    zfs_prop_to_name(ZFS_PROP_SYNC),
			    sync_changed_cb, os));
		}
		VERIFY0(dsl_prop_unregister(ds,
		    zfs_prop_to_name(ZFS_PROP_PRIMARYCACHE),
		    primary_cache_changed_cb, os));
		VERIFY0(dsl_prop_unregister(ds,
		    zfs_prop_to_name(ZFS_PROP_SECONDARYCACHE),
		    secondary_cache_changed_cb, os));
	}

	if (os->os_sa)
		sa_tear_down(os);

	dmu_objset_evict_dbufs(os);

	dnode_special_close(&os->os_meta_dnode);
	if (DMU_USERUSED_DNODE(os)) {
		dnode_special_close(&os->os_userused_dnode);
		dnode_special_close(&os->os_groupused_dnode);
	}
	zil_free(os->os_zil);

	ASSERT3P(list_head(&os->os_dnodes), ==, NULL);

	VERIFY(arc_buf_remove_ref(os->os_phys_buf, &os->os_phys_buf));

	/*
	 * This is a barrier to prevent the objset from going away in
	 * dnode_move() until we can safely ensure that the objset is still in
	 * use. We consider the objset valid before the barrier and invalid
	 * after the barrier.
	 */
	rw_enter(&os_lock, RW_READER);
	rw_exit(&os_lock);

	mutex_destroy(&os->os_lock);
	mutex_destroy(&os->os_obj_lock);
	mutex_destroy(&os->os_user_ptr_lock);
	kmem_free(os, sizeof (objset_t));
}
示例#22
0
bool TestExtString::test_crypt() {
  VERIFY(!f_crypt("mypassword").empty());
  return Count(true);
}
示例#23
0
void CLightProjector::calculate	()
{
	if (receivers.empty())		return;

	// perform validate / markup
	for (u32 r_it=0; r_it<receivers.size(); r_it++)
	{
		// validate
		BOOL				bValid	= TRUE;
		IRenderable*		O		= receivers[r_it];
		CROS_impl*			LT		= (CROS_impl*)O->renderable_ROS();
		int					slot	= LT->shadow_recv_slot;
		if (slot<0 || slot>=P_o_count)								bValid = FALSE;	// invalid slot
		else if (cache[slot].O!=O)									bValid = FALSE;	// not the same object
		else {
			// seems to be valid
			Fbox	bb;		bb.xform		(O->renderable.visual->vis.box,O->renderable.xform);
			if (cache[slot].BB.contains(bb))	{
				// inside, but maybe timelimit exceeded?
				if (Device.dwTimeGlobal > cache[slot].dwTimeValid)	bValid = FALSE;	// timeout
			} else													bValid = FALSE;	// out of bounds
		}

		// 
		if (bValid)			{
			// Ok, use cached version
			cache[slot].dwFrame	= Device.dwFrame;
		} else {
			taskid.push_back	(r_it);
		}
	}
	if (taskid.empty())			return;

	// Begin
	Device.Statistic->RenderDUMP_Pcalc.Begin	();
	RCache.set_RT				(RT->pRT);
	RCache.set_ZB				(RImplementation.Target->pTempZB);
	CHK_DX(HW.pDevice->Clear	(0,0, D3DCLEAR_ZBUFFER | (HW.Caps.bStencil?D3DCLEAR_STENCIL:0), 0,1,0 ));
	RCache.set_xform_world		(Fidentity);

	// reallocate/reassociate structures + perform all the work
	for (u32 c_it=0; c_it<cache.size(); c_it++)
	{
		if (taskid.empty())							break;
		if (Device.dwFrame==cache[c_it].dwFrame)	continue;

		// found not used slot
		int				tid		= taskid.back();	taskid.pop_back();
		recv&			R		= cache		[c_it];
		IRenderable*	O		= receivers	[tid];
		CROS_impl*	LT		= (CROS_impl*)O->renderable_ROS();
		VERIFY2			(_valid(O->renderable.xform),"Invalid object transformation");
		VERIFY2			(_valid(O->renderable.visual->vis.sphere.P),"Invalid object's visual sphere");

		Fvector			C;		O->renderable.xform.transform_tiny		(C,O->renderable.visual->vis.sphere.P);
		R.O						= O;
		R.C						= C;
		R.C.y					+= O->renderable.visual->vis.sphere.R*0.1f;		//. YURA: 0.1 can be more
		R.BB.xform				(O->renderable.visual->vis.box,O->renderable.xform).scale(0.1f);
		R.dwTimeValid			= Device.dwTimeGlobal + ::Random.randI(time_min,time_max);
		LT->shadow_recv_slot	= c_it; 

		// Msg					("[%f,%f,%f]-%f",C.C.x,C.C.y,C.C.z,C.O->renderable.visual->vis.sphere.R);
		// calculate projection-matrix
		Fmatrix		mProject;
		float		p_R			=	R.O->renderable.visual->vis.sphere.R * 1.1f;
		VERIFY2		(p_R>EPS_L,"Object has no physical size");
		float		p_hat		=	p_R/P_cam_dist;
		float		p_asp		=	1.f;
		float		p_near		=	P_cam_dist-EPS_L;									
		float		p_far		=	P_cam_dist+p_R+P_cam_range;	
		mProject.build_projection_HAT	(p_hat,p_asp,p_near,p_far);
		RCache.set_xform_project		(mProject);
		
		// calculate view-matrix
		Fmatrix		mView;
		Fvector		v_C, v_Cs, v_N;
		v_C.set					(R.C);
		v_Cs					= v_C;
		v_C.y					+=	P_cam_dist;
		v_N.set					(0,0,1);
		VERIFY					(_valid(v_C) && _valid(v_Cs) && _valid(v_N));

		// validate
		Fvector		v;
		v.sub		(v_Cs,v_C);;
#ifdef DEBUG
		if ((v.x*v.x+v.y*v.y+v.z*v.z)<=flt_zero)	{
			CObject* OO = dynamic_cast<CObject*>(R.O);
			Msg("Object[%s] Visual[%s] has invalid position. ",*OO->cName(),*OO->cNameVisual());
			Fvector cc;
			OO->Center(cc);
			Log("center=",cc);

			Log("visual_center=",OO->Visual()->vis.sphere.P);
			
			Log("full_matrix=",OO->XFORM());

			Log	("v_N",v_N);
			Log	("v_C",v_C);
			Log	("v_Cs",v_Cs);

			Log("all bones transform:--------");
			CKinematics* K = dynamic_cast<CKinematics*>(OO->Visual());
			
			for(u16 ii=0; ii<K->LL_BoneCount();++ii){
				Fmatrix tr;

				tr = K->LL_GetTransform(ii);
				Log("bone ",K->LL_BoneName_dbg(ii));
				Log("bone_matrix",tr);
			}
			Log("end-------");
		}
#endif
		// handle invalid object-bug
		if ((v.x*v.x+v.y*v.y+v.z*v.z)<=flt_zero)	{
			// invalidate record, so that object will be unshadowed, but doesn't crash
			R.dwTimeValid			= Device.dwTimeGlobal;
			LT->shadow_recv_frame	= Device.dwFrame-1;
			LT->shadow_recv_slot	= -1; 
			continue				;
		}

		mView.build_camera		(v_C,v_Cs,v_N);
		RCache.set_xform_view	(mView);

		// Select slot, set viewport
		int		s_x				=	c_it%P_o_line;
		int		s_y				=	c_it/P_o_line;
		D3DVIEWPORT9 VP			=	{s_x*P_o_size,s_y*P_o_size,P_o_size,P_o_size,0,1 };
		CHK_DX					(HW.pDevice->SetViewport(&VP));

		// Clear color to ambience
		Fvector&	cap			=	LT->get_approximate();
		CHK_DX					(HW.pDevice->Clear(0,0, D3DCLEAR_TARGET, color_rgba_f(cap.x,cap.y,cap.z, (cap.x+cap.y+cap.z)/4.f), 1, 0 ));

		// calculate uv-gen matrix and clamper
		Fmatrix					mCombine;		mCombine.mul	(mProject,mView);
		Fmatrix					mTemp;
		float					fSlotSize		= float(P_o_size)/float(P_rt_size);
		float					fSlotX			= float(s_x*P_o_size)/float(P_rt_size);
		float					fSlotY			= float(s_y*P_o_size)/float(P_rt_size);
		float					fTexelOffs		= (.5f / P_rt_size);
		Fmatrix					m_TexelAdjust	= 
		{
			0.5f/*x-scale*/,	0.0f,							0.0f,				0.0f,
			0.0f,				-0.5f/*y-scale*/,				0.0f,				0.0f,
			0.0f,				0.0f,							1.0f/*z-range*/,	0.0f,
			0.5f/*x-bias*/,		0.5f + fTexelOffs/*y-bias*/,	0.0f/*z-bias*/,		1.0f
		};
		R.UVgen.mul				(m_TexelAdjust,mCombine);
		mTemp.scale				(fSlotSize,fSlotSize,1);
		R.UVgen.mulA_44			(mTemp);
		mTemp.translate			(fSlotX+fTexelOffs,fSlotY+fTexelOffs,0);
		R.UVgen.mulA_44			(mTemp);

		// Build bbox and render
		Fvector					min,max;
		Fbox					BB;
		min.set					(R.C.x-p_R,	R.C.y-(p_R+P_cam_range),	R.C.z-p_R);
		max.set					(R.C.x+p_R,	R.C.y+0,					R.C.z+p_R);
		BB.set					(min,max);
		R.UVclamp_min.set		(min).add	(.05f);	// shrink a little
		R.UVclamp_max.set		(max).sub	(.05f);	// shrink a little
		ISpatial*	spatial		= dynamic_cast<ISpatial*>	(O);
		if (spatial)			{
			spatial->spatial_updatesector			();
			if (spatial->spatial.sector)			RImplementation.r_dsgraph_render_R1_box	(spatial->spatial.sector,BB,SE_R1_LMODELS);
		}
		//if (spatial)		RImplementation.r_dsgraph_render_subspace	(spatial->spatial.sector,mCombine,v_C,FALSE);
	}

	// Blur
	/*
	{
		// Fill vertex buffer
		u32							Offset;
		FVF::TL4uv* pv				= (FVF::TL4uv*) RCache.Vertex.Lock	(4,geom_Blur.stride(),Offset);
		RImplementation.ApplyBlur4	(pv,P_rt_size,P_rt_size,P_blur_kernel);
		RCache.Vertex.Unlock		(4,geom_Blur.stride());

		// Actual rendering (pass0, temp2real)
		RCache.set_RT				(RT->pRT);
		RCache.set_ZB				(NULL);
		RCache.set_Shader			(sh_BlurTR	);
		RCache.set_Geometry			(geom_Blur	);
		RCache.Render				(D3DPT_TRIANGLELIST,Offset,0,4,0,2);
	}
	*/

	// Finita la comedia
	Device.Statistic->RenderDUMP_Pcalc.End	();
	
	RCache.set_xform_project	(Device.mProject);
	RCache.set_xform_view		(Device.mView);
}
示例#24
0
bool TestExtString::test_get_html_translation_table() {
  VERIFY(!f_get_html_translation_table(k_HTML_ENTITIES).empty());
  return Count(true);
}
void CColorRectTracker::Draw(CDC* pDC)
{
	// set initial DC state
	VERIFY(pDC->SaveDC() != 0);
	pDC->SetMapMode(MM_TEXT);
	pDC->SetViewportOrg(0, 0);
	pDC->SetWindowOrg(0, 0);

	// get normalized rectangle
	CRect rect = m_rect;
	rect.NormalizeRect();

	CPen* pOldPen = NULL;
	CBrush* pOldBrush = NULL;
	CGdiObject* pTemp;
	int nOldROP;
	
	CPoint ptCenter = rect.CenterPoint();
	int nCrossHairWH = rect.Width() < rect.Height() ? rect.Width()/4 : rect.Height()/4;
	if (nCrossHairWH > 20) nCrossHairWH = 20;
	if (nCrossHairWH < 4) nCrossHairWH = 0;

	// draw lines
	if ((m_nStyle & (dottedLine|solidLine)) != 0)
	{
		rect.InflateRect(+1, +1);   // borders are one pixel outside
		pOldBrush = (CBrush*)pDC->SelectStockObject(NULL_BRUSH);
		nOldROP = pDC->SetROP2(R2_COPYPEN);

		pOldPen = pDC->SelectObject( &m_WhiteBoldPen );
		pDC->Rectangle(rect.left, rect.top, rect.right, rect.bottom);
		
		if (nCrossHairWH > 0)
		{
			pDC->MoveTo(ptCenter.x-nCrossHairWH/2, ptCenter.y);
			pDC->LineTo(ptCenter.x+nCrossHairWH/2, ptCenter.y);
			pDC->MoveTo(ptCenter.x, ptCenter.y-nCrossHairWH/2);
			pDC->LineTo(ptCenter.x, ptCenter.y+nCrossHairWH/2);
		}
		
		if (m_nStyle & dottedLine)
			pDC->SelectObject(CPen::FromHandle(_afxBlackDottedPen));
		else
			pDC->SelectStockObject(BLACK_PEN);
		pDC->Rectangle(rect.left, rect.top, rect.right, rect.bottom);

		if (nCrossHairWH > 0)
		{
			pDC->MoveTo(ptCenter.x-nCrossHairWH/2, ptCenter.y);
			pDC->LineTo(ptCenter.x+nCrossHairWH/2, ptCenter.y);
			pDC->MoveTo(ptCenter.x, ptCenter.y-nCrossHairWH/2);
			pDC->LineTo(ptCenter.x, ptCenter.y+nCrossHairWH/2);
		}

		pDC->SetROP2(nOldROP);
	}

	// if hatchBrush is going to be used, need to unrealize it
	if ((m_nStyle & (hatchInside|hatchedBorder)) != 0)
		UnrealizeObject(_afxHatchBrush);

	// hatch inside
	if ((m_nStyle & hatchInside) != 0)
	{
		pTemp = pDC->SelectStockObject(NULL_PEN);
		if (pOldPen == NULL)
			pOldPen = (CPen*)pTemp;
		pTemp = pDC->SelectObject(CBrush::FromHandle(_afxHatchBrush));
		if (pOldBrush == NULL)
			pOldBrush = (CBrush*)pTemp;
		pDC->SetBkMode(TRANSPARENT);
		nOldROP = pDC->SetROP2(R2_MASKNOTPEN);
		pDC->Rectangle(rect.left+1, rect.top+1, rect.right, rect.bottom);
		pDC->SetROP2(nOldROP);
	}

	// draw hatched border
	if ((m_nStyle & hatchedBorder) != 0)
	{
		pTemp = pDC->SelectObject(CBrush::FromHandle(_afxHatchBrush));
		if (pOldBrush == NULL)
			pOldBrush = (CBrush*)pTemp;
		pDC->SetBkMode(OPAQUE);
		CRect rectTrue;
		GetTrueRect(&rectTrue);
		pDC->PatBlt(rectTrue.left, rectTrue.top, rectTrue.Width(),
			rect.top-rectTrue.top, 0x000F0001 /* Pn */);
		pDC->PatBlt(rectTrue.left, rect.bottom,
			rectTrue.Width(), rectTrue.bottom-rect.bottom, 0x000F0001 /* Pn */);
		pDC->PatBlt(rectTrue.left, rect.top, rect.left-rectTrue.left,
			rect.Height(), 0x000F0001 /* Pn */);
		pDC->PatBlt(rect.right, rect.top, rectTrue.right-rect.right,
			rect.Height(), 0x000F0001 /* Pn */);
	}

	// draw resize handles
	if ((m_nStyle & (resizeInside|resizeOutside)) != 0)
	{
		UINT mask = GetHandleMask();
		for (int i = 0; i < 8; ++i)
		{
			if (mask & (1<<i))
			{
				GetHandleRect((TrackerHit)i, &rect);
				rect.InflateRect( +1, +1, +1, +1 );
				pDC->FillSolidRect(rect, RGB(0xff, 0xff, 0xff));
				rect.DeflateRect( +1, +1, +1, +1 );
				pDC->FillSolidRect(rect, RGB(0, 0, 0));
			}
		}
	}

	// cleanup pDC state
	if (pOldPen != NULL)
		pDC->SelectObject(pOldPen);
	if (pOldBrush != NULL)
		pDC->SelectObject(pOldBrush);
	VERIFY(pDC->RestoreDC(-1));
}
示例#26
0
bool TestExtString::test_setlocale() {
  VERIFY(!f_setlocale(0, k_LC_ALL, 0).toString().empty());
  return Count(true);
}
示例#27
0
CString CNumericEdit::GetClipboardText(void) const
{
	CString	strClipBrdText;

	// clipboard contains textual data?
	if (::IsClipboardFormatAvailable(CF_TEXT))
	{
		// open the clipboard to get clipboard text
		if (::OpenClipboard(m_hWnd))
		{
			HANDLE	hClipBrdData = NULL;
			if ((hClipBrdData = ::GetClipboardData(CF_TEXT)) != NULL)
			{
				LPTSTR	lpClipBrdText = (LPTSTR)::GlobalLock(hClipBrdData);
				if (lpClipBrdText)
				{
					strClipBrdText = lpClipBrdText;
					::GlobalUnlock(hClipBrdData);
				}
			}

			VERIFY(::CloseClipboard());

			/**
			 *	parse a number out of the retrieved text
			 */
			bool	bHasDecimal = false;	// decimal symbol flag
			int		iStart = 0, iCount = 0;
			LPTSTR	lpsz = strClipBrdText.LockBuffer();

			// skip leading whitespaces (including tabs)
			for (; *lpsz == _T(' ') || *lpsz == _T('\t'); iStart++)
				lpsz = ::_tcsinc(lpsz);

			// is the first character a negative symbol?
			if (*lpsz == DefUserLocale.chNegationSymbol)
			{
				// negative values are not allowed?
				if (!m_bAllowNegativeValues)
					return ((LPCTSTR)NULL);

				++iCount;
				lpsz = ::_tcsinc(lpsz);
			}

			while (*lpsz != _T('\0'))
			{
				if (!::_istdigit(*lpsz))
				{
					if ( (m_chDigitsAfterDecimal) && 
						 (*lpsz != DefUserLocale.chDecimalSymbol) )
						break;

					// a decimal symbol is already there?
					if (bHasDecimal)
						break;
					bHasDecimal = true;
				}

				++iCount;
				lpsz = ::_tcsinc(lpsz);
			}

			strClipBrdText.UnlockBuffer();

			if ( (!iStart) && (!iCount) )
				strClipBrdText.Empty();
			else
				strClipBrdText = strClipBrdText.Mid(iStart, iCount);
		}
	}

	return (strClipBrdText);
}
示例#28
0
bool TestExtString::test_localeconv() {
  VERIFY(!f_localeconv().empty());
  return Count(true);
}
示例#29
0
// Subclass procedure for the edit box.
LRESULT	CALLBACK 
EditorBase::WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) 
{
	EditorBase *ebase = (EditorBase*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
    MDIWindow   *wnd = NULL;
	wyInt32		ret = 0;
		
	static wyChar	keyword[128];
	static wyBool	keyflag;
	static wyInt32  wrdlen = 0;

    VERIFY(wnd = GetActiveWin());
				
    //if message is from find replace dialog - pass it to the right handler
	//forced type cast
	if(message == (wyUInt32)pGlobals->m_pcmainwin->m_findmsg) 
	{		
		if( ebase->m_findreplace->FindReplace(hwnd, lparam) == wyFalse)
		{
            //when we are closing the find dialog, deleting the memory allocated for Find
			delete(ebase->m_findreplace);
			ebase->m_findreplace = NULL;
		}
		return 0;		
	}    
	
	switch(message)	
	{
	    case WM_HELP:
            ShowHelp("SQL%20Window%20SQLyog%20for%20MySQL%20Administration.htm");
		    return wyTrue;

	    case WM_CONTEXTMENU:
            if(wnd->GetActiveTabEditor())
		    {
			    //CustomGrid_ApplyChanges(wnd->GetActiveTabEditor()->m_pctabmgmt->m_insert->m_hwndgrid, wyTrue);
		    }

            if(ebase->OnContextMenu(lparam) == 1)
            {
                return 1;
            }
		    break;

	    case WM_KEYUP:
	        ebase->OnWMKeyUp(hwnd, wparam);
            break;
		
	    case WM_KEYDOWN:
		    {
			    //This needs to work Ctrl+X to be handled in WM_CHAR, if it wont return '0', that wont process as expected

			    if(GetKeyState(VK_CONTROL) & 0x8000)
			    {
				    if(wparam == 'X')
					    return 0;

				    if(wparam == VK_INSERT)
				    {
					    CopyStyledTextToClipBoard(hwnd);
					    return 0;
				    }
			    }
               
			    if(wnd->m_acinterface->HandlerOnWMKeyDown(hwnd, ebase, wparam))
				    return 1;
		    }
		    break;

        case WM_SYSKEYDOWN:
             if(lparam >> 29)
            {
                //check whether it is insert/delete
                if (wparam == 'C' || wparam == 'c')//switch(wparam)
                {
                    ret = ebase->OnWMChar(hwnd, wparam, wnd, ebase);
                }
            }
             break;

        case WM_SETFOCUS:
            if(wnd)
            {
                PostMessage(wnd->m_pctabmodule->m_hwnd, UM_SETSTATUSLINECOL, (WPARAM)hwnd, 1);
            }

            break;

        case WM_KILLFOCUS:
            if(wnd)
            {
                PostMessage(wnd->m_pctabmodule->m_hwnd, UM_SETSTATUSLINECOL, (WPARAM)NULL, 0);
            }

            break;		
		
	    case WM_LBUTTONUP:
		    ebase->OnLButtonUp(wnd,hwnd);
		    break;

	    case UM_FOCUS:
		    ::SendMessage(hwnd, SCI_GRABFOCUS, 0, 0);
		    break;

	    case WM_CHAR:

		    ret = ebase->OnWMChar(hwnd, wparam, wnd, ebase);

		    if(ret == -1)
			    break;

		    return ret;		

        case UM_ADDBACKQUOTEONAC:
            if(lparam & 1)
            {
                SendMessage(hwnd, SCI_INSERTTEXT, wparam, (LPARAM)"`");
            }

            if(lparam & 2)
            {
               SendMessage(hwnd, SCI_REPLACESEL, (WPARAM)0, (LPARAM)"`");
            }

            SendMessage(hwnd, SCI_ENDUNDOACTION, 0, 0);        
	}

	return CallWindowProc(ebase->wpOrigProc, hwnd, message, wparam, lparam);
}
示例#30
0
void CQListCtrl::OnCustomdrawList(NMHDR* pNMHDR, LRESULT* pResult)
{
	NMLVCUSTOMDRAW* pLVCD = reinterpret_cast<NMLVCUSTOMDRAW*>( pNMHDR );
    
    *pResult = 0;
	
    // Request item-specific notifications if this is the
    // beginning of the paint cycle.
    if ( CDDS_PREPAINT == pLVCD->nmcd.dwDrawStage )
	{
        *pResult = CDRF_NOTIFYITEMDRAW;
	}
    else if ( CDDS_ITEMPREPAINT == pLVCD->nmcd.dwDrawStage )
	{
        LVITEM   rItem;
        int      nItem = static_cast<int>( pLVCD->nmcd.dwItemSpec );
        CDC*     pDC   = CDC::FromHandle ( pLVCD->nmcd.hdc );
        COLORREF crBkgnd;
        BOOL     bListHasFocus;
        CRect    rcItem;
		
        bListHasFocus = ( GetSafeHwnd() == ::GetFocus() );
        
        // Get the image index and selected/focused state of the
        // item being drawn.
        ZeroMemory ( &rItem, sizeof(LVITEM) );
        rItem.mask  = LVIF_STATE;
        rItem.iItem = nItem;
        rItem.stateMask = LVIS_SELECTED | LVIS_FOCUSED;
        GetItem(&rItem);
		
        // Get the rect that bounds the text label.
        GetItemRect(nItem, rcItem, LVIR_LABEL);
		rcItem.left -= DUMMY_COL_WIDTH;
		
		COLORREF OldColor = -1;
		int nOldBKMode = -1;
		
		// Draw the background of the list item.  Colors are selected 
		// according to the item's state.
		if(rItem.state & LVIS_SELECTED)
		{
            if(bListHasFocus)
			{
                crBkgnd = g_Opt.m_Theme.ListBoxSelectedBG();
                OldColor = pDC->SetTextColor(g_Opt.m_Theme.ListBoxSelectedText());
			}
            else
			{
                crBkgnd = g_Opt.m_Theme.ListBoxSelectedNoFocusBG();
                OldColor = pDC->SetTextColor(g_Opt.m_Theme.ListBoxSelectedNoFocusText());
			}
		}
        else
		{
            //Shade alternating Rows
			if((nItem % 2) == 0)
			{
				crBkgnd = g_Opt.m_Theme.ListBoxOddRowsBG();
				OldColor = pDC->SetTextColor(g_Opt.m_Theme.ListBoxOddRowsText());
			}
			else
			{
				crBkgnd = g_Opt.m_Theme.ListBoxEvenRowsBG();
				OldColor = pDC->SetTextColor(g_Opt.m_Theme.ListBoxEvenRowsText());
			}
		}
		
        pDC->FillSolidRect(rcItem, crBkgnd);
        nOldBKMode = pDC->SetBkMode(TRANSPARENT);
		
        CRect rcText = rcItem;
        rcText.left += ROW_LEFT_BORDER;
		rcText.top++;
		
        // Draw the text.
        //CString csText = GetItemText(nItem, 0);
		
		CString csText;
		LPTSTR lpszText = csText.GetBufferSetLength(g_Opt.m_bDescTextSize);
		GetItemText(nItem, 0, lpszText, g_Opt.m_bDescTextSize);
		csText.ReleaseBuffer();
		
		// extract symbols
		CString strSymbols;
		int nSymEnd = csText.Find('|');
		if( nSymEnd >= 0 )
		{
			strSymbols = csText.Left(nSymEnd);  
			csText = csText.Mid(nSymEnd+1);
		}
		
		// set firstTenNum to the first ten number (1-10) corresponding to
		//  the current nItem.
		// -1 means that nItem is not in the FirstTen block.
		int firstTenNum = GetFirstTenNum(nItem);
		
		if( m_bShowTextForFirstTenHotKeys && firstTenNum > 0 )
		{
			rcText.left += 12;
		}
		
		// if we are inside a group, don't display the "in group" flag
		if( theApp.m_GroupID > 0 )
		{
			int nFlag = strSymbols.Find(_T("!"));
			if( nFlag >= 0 )
				strSymbols.Delete(nFlag);
		}
		
		DrawBitMap(nItem, rcText, pDC, csText);

		// draw the symbol box
		if( strSymbols.GetLength() > 0 )
		{
			strSymbols = " " + strSymbols + " "; // leave space for box
			// add spaces to leave room for the symbols
			CRect rectSym(rcText.left, rcText.top+1, rcText.left, rcText.top+1);
			CRect rectSpace(0,0,0,0);
			//Get text bounds
			pDC->DrawText(" ", &rectSpace, DT_VCENTER | DT_EXPANDTABS | DT_CALCRECT);
			pDC->DrawText(strSymbols, &rectSym, DT_VCENTER | DT_EXPANDTABS | DT_CALCRECT);
			VERIFY( rectSpace.Width() > 0 );
			
//			int numSpaces = rectSym.Width() / rectSpace.Width();
//			numSpaces++;
//			csText = CString(' ',numSpaces) + csText;
			
			// draw the symbols
			pDC->FillSolidRect( rectSym, GetSysColor(COLOR_ACTIVECAPTION) );
			//pDC->FillSolidRect( rectSym, RGB(0,255,255) );
			pDC->Draw3dRect(rectSym, GetSysColor(COLOR_3DLIGHT), GetSysColor(COLOR_3DDKSHADOW));
			//		COLORREF crOld = pDC->SetTextColor(GetSysColor(COLOR_INFOTEXT));
			COLORREF crOld = pDC->SetTextColor(RGB(255, 255, 255));
			pDC->DrawText(strSymbols, rectSym, DT_VCENTER|DT_EXPANDTABS|DT_NOPREFIX);
			pDC->SetTextColor(crOld);

			rcText.left += rectSym.Width() + 2;
		}
		
		if(DrawRtfText(nItem, rcText, pDC) == FALSE)
		{
			pDC->DrawText(csText, rcText, DT_VCENTER|DT_EXPANDTABS|DT_NOPREFIX);
		}
		
        // Draw a focus rect around the item if necessary.
        if(bListHasFocus && (rItem.state & LVIS_FOCUSED))
			pDC->DrawFocusRect(rcItem);
		
		if( m_bShowTextForFirstTenHotKeys && firstTenNum > 0 )
		{
			CString cs;
			if( firstTenNum == 10 )
				cs = "0";
			else
				cs.Format(_T("%d"), firstTenNum);
			
			CRect crClient;
			
			GetWindowRect(crClient);
			ScreenToClient(crClient);
			
			CRect crHotKey = rcItem;
			
			crHotKey.right = crHotKey.left + 11;
			crHotKey.left += 2;
			crHotKey.top += 2;
			
			HFONT hOldFont = (HFONT)pDC->SelectObject(m_SmallFont);
			
			pDC->DrawText(cs, crHotKey, DT_BOTTOM);
			
			pDC->MoveTo(CPoint(rcItem.left + 11, rcItem.top));
			pDC->LineTo(CPoint(rcItem.left + 11, rcItem.bottom));
			
			pDC->SelectObject(hOldFont);
		}
		
		// restore the previous values		
		if(OldColor > -1)
			pDC->SetTextColor(OldColor);
		
		if(nOldBKMode > -1)
			pDC->SetBkMode(nOldBKMode);
		
        *pResult = CDRF_SKIPDEFAULT;    // We've painted everything.
	}
}