Exemple #1
0
void CGraphics_OpenGL::QuadsEnd()
{
	dbg_assert(m_Drawing == DRAWING_QUADS, "called quads_end without begin");
	Flush();
	m_Drawing = 0;
}
Exemple #2
0
// return 0 if error or no. of bytes writte if success
int Cvfgk::EndByteCompression(){
  if(Encode(fByteOut,ctEndChar)) return 0;
  if(Flush(fByteOut)) return 0;
  fByteOut = NULL;
  return iBytesWritten;
}
Exemple #3
0
void WriteFileStream::Put(char c)
{
    *current_++ = c;
    if (current_ == bufferLast_)
        Flush();
}
Exemple #4
0
static HRESULT StreamFlush( aout_stream_t *s )
{
    return Flush( s->sys );
}
		void GLSoftSpriteRenderer::Render() {
			SPADES_MARK_FUNCTION();
			lastImage = NULL;
			program->Use();

			device->Enable(IGLDevice::Blend, true);
			device->BlendFunc(IGLDevice::One, IGLDevice::OneMinusSrcAlpha);

			projectionViewMatrix(program);
			rightVector(program);
			frontVector(program);
			viewOriginVector(program);
			upVector(program);
			texture(program);
			depthTexture(program);
			viewMatrix(program);
			fogDistance(program);
			fogColor(program);
			zNearFar(program);

			positionAttribute(program);
			spritePosAttribute(program);
			colorAttribute(program);

			projectionViewMatrix.SetValue(renderer->GetProjectionViewMatrix());
			viewMatrix.SetValue(renderer->GetViewMatrix());

			fogDistance.SetValue(renderer->GetFogDistance());

			Vector3 fogCol = renderer->GetFogColor();
			fogCol *= fogCol; // linearize
			fogColor.SetValue(fogCol.x, fogCol.y, fogCol.z);

			const client::SceneDefinition &def = renderer->GetSceneDef();
			rightVector.SetValue(def.viewAxis[0].x, def.viewAxis[0].y, def.viewAxis[0].z);
			upVector.SetValue(def.viewAxis[1].x, def.viewAxis[1].y, def.viewAxis[1].z);
			frontVector.SetValue(def.viewAxis[2].x, def.viewAxis[2].y, def.viewAxis[2].z);

			viewOriginVector.SetValue(def.viewOrigin.x, def.viewOrigin.y, def.viewOrigin.z);
			texture.SetValue(0);
			depthTexture.SetValue(1);
			zNearFar.SetValue(def.zNear, def.zFar);

			device->ActiveTexture(1);
			device->BindTexture(IGLDevice::Texture2D,
			                    renderer->GetFramebufferManager()->GetDepthTexture());
			device->ActiveTexture(0);

			device->EnableVertexAttribArray(positionAttribute(), true);
			device->EnableVertexAttribArray(spritePosAttribute(), true);
			device->EnableVertexAttribArray(colorAttribute(), true);

			thresLow = tanf(def.fovX * .5f) * tanf(def.fovY * .5f) * 1.8f;
			thresRange = thresLow * .5f;

			// full-resolution sprites
			{
				GLProfiler::Context measure(renderer->GetGLProfiler(), "Full Resolution");
				for (size_t i = 0; i < sprites.size(); i++) {
					Sprite &spr = sprites[i];
					float layer = LayerForSprite(spr);
					if (layer == 1.f)
						continue;
					if (spr.image != lastImage) {
						Flush();
						lastImage = spr.image;
						SPAssert(vertices.empty());
					}

					Vertex v;
					v.x = spr.center.x;
					v.y = spr.center.y;
					v.z = spr.center.z;
					v.radius = spr.radius;
					v.angle = spr.angle;
					v.r = spr.color.x;
					v.g = spr.color.y;
					v.b = spr.color.z;
					v.a = spr.color.w;

					float fade = 1.f - layer;
					v.r *= fade;
					v.g *= fade;
					v.b *= fade;
					v.a *= fade;

					uint32_t idx = (uint32_t)vertices.size();
					v.sx = -1;
					v.sy = -1;
					vertices.push_back(v);
					v.sx = 1;
					v.sy = -1;
					vertices.push_back(v);
					v.sx = -1;
					v.sy = 1;
					vertices.push_back(v);
					v.sx = 1;
					v.sy = 1;
					vertices.push_back(v);

					indices.push_back(idx);
					indices.push_back(idx + 1);
					indices.push_back(idx + 2);
					indices.push_back(idx + 1);
					indices.push_back(idx + 3);
					indices.push_back(idx + 2);
				}

				Flush();
			}

			// low-res sprites
			IGLDevice::UInteger lastFb = device->GetInteger(IGLDevice::FramebufferBinding);
			int sW = device->ScreenWidth(), sH = device->ScreenHeight();
			int lW = (sW + 3) / 4, lH = (sH + 3) / 4;
			int numLowResSprites = 0;
			GLColorBuffer buf = renderer->GetFramebufferManager()->CreateBufferHandle(lW, lH, true);
			device->BindFramebuffer(IGLDevice::Framebuffer, buf.GetFramebuffer());
			device->ClearColor(0.f, 0.f, 0.f, 0.f);
			device->Clear(IGLDevice::ColorBufferBit);
			device->BlendFunc(IGLDevice::One, IGLDevice::OneMinusSrcAlpha);
			device->Viewport(0, 0, lW, lH);
			{
				GLProfiler::Context measure(renderer->GetGLProfiler(), "Low Resolution");
				for (size_t i = 0; i < sprites.size(); i++) {
					Sprite &spr = sprites[i];
					float layer = LayerForSprite(spr);
					if (layer == 0.f)
						continue;
					if (spr.image != lastImage) {
						Flush();
						lastImage = spr.image;
						SPAssert(vertices.empty());
					}

					numLowResSprites++;

					Vertex v;
					v.x = spr.center.x;
					v.y = spr.center.y;
					v.z = spr.center.z;
					v.radius = spr.radius;
					v.angle = spr.angle;
					v.r = spr.color.x;
					v.g = spr.color.y;
					v.b = spr.color.z;
					v.a = spr.color.w;

					float fade = layer;
					v.r *= fade;
					v.g *= fade;
					v.b *= fade;
					v.a *= fade;

					uint32_t idx = (uint32_t)vertices.size();
					v.sx = -1;
					v.sy = -1;
					vertices.push_back(v);
					v.sx = 1;
					v.sy = -1;
					vertices.push_back(v);
					v.sx = -1;
					v.sy = 1;
					vertices.push_back(v);
					v.sx = 1;
					v.sy = 1;
					vertices.push_back(v);

					indices.push_back(idx);
					indices.push_back(idx + 1);
					indices.push_back(idx + 2);
					indices.push_back(idx + 1);
					indices.push_back(idx + 3);
					indices.push_back(idx + 2);
				}
				Flush();
			}

			// finalize

			device->ActiveTexture(1);
			device->BindTexture(IGLDevice::Texture2D, 0);
			device->ActiveTexture(0);
			device->BindTexture(IGLDevice::Texture2D, 0);
			device->EnableVertexAttribArray(positionAttribute(), false);
			device->EnableVertexAttribArray(spritePosAttribute(), false);
			device->EnableVertexAttribArray(colorAttribute(), false);

			// composite downsampled sprite
			device->BlendFunc(IGLDevice::One, IGLDevice::OneMinusSrcAlpha);
			if (numLowResSprites > 0) {
				GLProfiler::Context measure(renderer->GetGLProfiler(), "Finalize");
				GLQuadRenderer qr(device);

				// do gaussian blur
				GLProgram *program =
				  renderer->RegisterProgram("Shaders/PostFilters/Gauss1D.program");
				static GLProgramAttribute blur_positionAttribute("positionAttribute");
				static GLProgramUniform blur_textureUniform("mainTexture");
				static GLProgramUniform blur_unitShift("unitShift");
				program->Use();
				blur_positionAttribute(program);
				blur_textureUniform(program);
				blur_unitShift(program);
				blur_textureUniform.SetValue(0);
				device->ActiveTexture(0);
				qr.SetCoordAttributeIndex(blur_positionAttribute());
				device->Enable(IGLDevice::Blend, false);

				// x-direction
				GLColorBuffer buf2 =
				  renderer->GetFramebufferManager()->CreateBufferHandle(lW, lH, true);
				device->BindTexture(IGLDevice::Texture2D, buf.GetTexture());
				device->BindFramebuffer(IGLDevice::Framebuffer, buf2.GetFramebuffer());
				blur_unitShift.SetValue(1.f / lW, 0.f);
				qr.Draw();
				buf.Release();

				// x-direction
				GLColorBuffer buf3 =
				  renderer->GetFramebufferManager()->CreateBufferHandle(lW, lH, true);
				device->BindTexture(IGLDevice::Texture2D, buf2.GetTexture());
				device->BindFramebuffer(IGLDevice::Framebuffer, buf3.GetFramebuffer());
				blur_unitShift.SetValue(0.f, 1.f / lH);
				qr.Draw();
				buf2.Release();

				buf = buf3;

				device->Enable(IGLDevice::Blend, true);

				// composite
				program = renderer->RegisterProgram("Shaders/PostFilters/PassThrough.program");
				static GLProgramAttribute positionAttribute("positionAttribute");
				static GLProgramUniform colorUniform("colorUniform");
				static GLProgramUniform textureUniform("mainTexture");
				static GLProgramUniform texCoordRange("texCoordRange");

				positionAttribute(program);
				textureUniform(program);
				texCoordRange(program);
				colorUniform(program);

				program->Use();

				textureUniform.SetValue(0);
				texCoordRange.SetValue(0.f, 0.f, 1.f, 1.f);
				colorUniform.SetValue(1.f, 1.f, 1.f, 1.f);

				qr.SetCoordAttributeIndex(positionAttribute());
				device->BindFramebuffer(IGLDevice::Framebuffer, lastFb);
				device->BindTexture(IGLDevice::Texture2D, buf.GetTexture());
				device->Viewport(0, 0, sW, sH);
				qr.Draw();
				device->BindTexture(IGLDevice::Texture2D, 0);

			} else {
				device->Viewport(0, 0, sW, sH);

				device->BindFramebuffer(IGLDevice::Framebuffer, lastFb);
			}

			buf.Release();
		}
Exemple #6
0
/*******************************************************
Main exe loop
*******************************************************/
Command::Dpt_Error RMWFlash::execute(String_List **output)
{
    ENTER("Command::Dpt_Error RMWFlash::execute(String_List **output)");
    Dpt_Error err;
    bool more_Devs_Left = true;
    DPT_TAG_T hbaTag;

    Init_Engine(1);
    *output = new String_List();

    for (int dev_Index = 0; more_Devs_Left; dev_Index++)
    {
        hbaTag = Get_HBA_by_Index(dev_Index, &more_Devs_Left);
        if (more_Devs_Left == 0)
        {
            break;
        }

        if (( hbaNum == -1 ) || ( hbaNum == dev_Index ))
        {
            unsigned long region_size = 8192;

            switch (region) {
            case 0: region_size = 2 * 1024L * 1024L;        break;
            case 1: region_size = 65536L;                   break;
            case 2: region_size = 512L * 1024L;             break;
            case 3: region_size = 8192;                     break;
            case 4: region_size = 8192;                     break;
            }
            char * original = new char[ region_size ];

            if (original != NULL) {
                // Send the command to the engine to set the region of flash memory to use.
                engine->Reset();
                engine->Insert((uLONG) region);
                err = engine->Send(MSG_FLASH_SET_REGION, hbaTag);
                if (err.Success())
                {
                    // Send the command to the engine to read the flash memory.
                    engine->Reset();
                    engine->Insert((uLONG) 0);
                    engine->Insert((uLONG) region_size);
                    err = engine->Send(MSG_FLASH_READ, hbaTag);

                    // If the read succeeded then copy the data that was read from the flash
                    // memory into the caller's buffer.
                    if (err.Success())
                    {
                        engine->Extract(original, region_size);
#                       if (defined(DEBUG_RMWFlash))
                            {
                                int fd = creat ("before", 0777);
                                write (fd, original, (unsigned)region_size);
                                close (fd);
                            }
#                       endif
                        if (strcmp (data, "-") == 0)
                        {
                            char temp_Buf[ 256 ];
                            sprintf(temp_Buf, "%.*s\r\n", size, original + offset);
                            (**output).add_Item (temp_Buf);
                            continue;
                        }

                        engine->Reset();
                        engine->Insert((uLONG) region);
                        err = engine->Send(MSG_FLASH_SET_REGION, hbaTag);
                        if (err.Success())
                        {
                            /* Ideally we want the caller to specify the checksum handling, but for now ... */
                            switch (region) {
                            case 4:
                                if ((0x14 < offset) && (offset < 0x7F))
                                {
                                    break;
                                }
                                *((unsigned long *)(&original[0x10])) += CheckSum (data, size) - CheckSum (original + offset, size);
                            case 0:
                            case 1:
                            case 2:
                            case 3:
                                break;
                            }

                            memcpy (original + offset, data, size);
#                           if (defined(DEBUG_RMWFlash))
                                {
                                    int fd = creat ("after", 0777);
                                    write (fd, original, (unsigned)region_size);
                                    close (fd);
                                }
#                           endif
                            // Send the command to the engine to write the flash memory.
                            engine->Reset();
                            engine->Insert((void *)original, region_size);
                            err = engine->Send(MSG_FLASH_WR_NO_VERIFY, hbaTag);
                            if (err.Success())
                            {
                                // Send the command to the engine to stop writing flash memory.
                                engine->Reset();
                                err = engine->Send(MSG_FLASH_WRITE_DONE, hbaTag);
                                if (err.Success())
                                {
                                    (**output).add_Item(EventStrings[STR_FLASH_COMPLETE]);
                                }
                            }
                        }
                    }
                }
                delete [] original;
                if (err.Failure())
                {
                    extern void Flush( String_List * );
                    char temp_Buf[ 256 ];
                    sprintf(temp_Buf,
                      EventStrings[STR_FLASH_ERR_MSG],
                      0L, (int)err, (char *)err);

                    (**output).add_Item (temp_Buf);
                    Flush (*output);
                    // Send the command to the engine to stop writing flash memory.
                    engine->Reset();
                    engine->Insert((uCHAR) 1);
                    err = engine->Send(MSG_FLASH_WRITE_DONE, hbaTag);
                    break;
                }
            } else {
                err = Dpt_Error::DPT_ERR_NOT_ENOUGH_MEMORY;
                break;
            }
        }
    }
    (**output).add_Item("\n");
    return (err);
}
Exemple #7
0
// ProcessOne() takes a track, transforms it to bunch of buffer-blocks,
// and calls libsamplerate code on these blocks.
bool EffectChangeSpeed::ProcessOne(WaveTrack * track,
                           sampleCount start, sampleCount end)
{
   if (track == NULL)
      return false;

   // initialization, per examples of Mixer::Mixer and
   // EffectSoundTouch::ProcessOne

   auto outputTrack = mFactory->NewWaveTrack(track->GetSampleFormat(),
                                                    track->GetRate());

   //Get the length of the selection (as double). len is
   //used simple to calculate a progress meter, so it is easier
   //to make it a double now than it is to do it later
   auto len = (end - start).as_double();

   // Initiate processing buffers, most likely shorter than
   // the length of the selection being processed.
   auto inBufferSize = track->GetMaxBlockSize();

   Floats inBuffer{ inBufferSize };

   // mFactor is at most 100-fold so this shouldn't overflow size_t
   auto outBufferSize = size_t( mFactor * inBufferSize + 10 );
   Floats outBuffer{ outBufferSize };

   // Set up the resampling stuff for this track.
   Resample resample(true, mFactor, mFactor); // constant rate resampling

   //Go through the track one buffer at a time. samplePos counts which
   //sample the current buffer starts at.
   bool bResult = true;
   auto samplePos = start;
   while (samplePos < end) {
      //Get a blockSize of samples (smaller than the size of the buffer)
      auto blockSize = limitSampleBufferSize(
         track->GetBestBlockSize(samplePos),
         end - samplePos
      );

      //Get the samples from the track and put them in the buffer
      track->Get((samplePtr) inBuffer.get(), floatSample, samplePos, blockSize);

      const auto results = resample.Process(mFactor,
                                    inBuffer.get(),
                                    blockSize,
                                    ((samplePos + blockSize) >= end),
                                    outBuffer.get(),
                                    outBufferSize);
      const auto outgen = results.second;

      if (outgen > 0)
         outputTrack->Append((samplePtr)outBuffer.get(), floatSample,
                             outgen);

      // Increment samplePos
      samplePos += results.first;

      // Update the Progress meter
      if (TrackProgress(mCurTrackNum, (samplePos - start).as_double() / len)) {
         bResult = false;
         break;
      }
   }

   // Flush the output WaveTrack (since it's buffered, too)
   outputTrack->Flush();

   // Take the output track and insert it in place of the original
   // sample data
   double newLength = outputTrack->GetEndTime();
   if (bResult)
   {
      LinearTimeWarper warper { mCurT0, mCurT0, mCurT1, mCurT0 + newLength };
      bResult = track->ClearAndPaste(
         mCurT0, mCurT1, outputTrack.get(), true, false, &warper);
   }

   if (newLength > mMaxNewLength)
      mMaxNewLength = newLength;

   return bResult;
}
Exemple #8
0
void CJpegEncoder::WriteSOS()
{
	PutByte(0xff);
	PutByte(0xda);

	WORD size = 6 + 2*ColorComponents;
	PutByte(size>>8);
	PutByte(size&0xff);

	PutByte(ColorComponents); // color components: 3

	PutByte(1); // component id
	PutByte(0x00); // DC | AC huff tbl

	PutByte(2); // component id
	PutByte(0x11); // DC | AC huff tbl

	PutByte(3); // component id
	PutByte(0x11); // DC | AC huff tbl

	PutByte(0); // ss, first AC
	PutByte(63); // se, last AC

	PutByte(0); // ah | al

	static float cosuv[8][8][8][8];

	// oh yeah, we don't need no fast dct :)
	for(int v = 0; v < 8; v++) 
		for(int u = 0; u < 8; u++)
			for(int j = 0; j < 8; j++) 
				for(int i = 0; i < 8; i++)
					cosuv[v][u][j][i] = (float)(cos((2*i+1)*u*PI/16) * cos((2*j+1)*v*PI/16));

	int prevDC[3] = {0, 0, 0};

	for(int y = 0; y < m_h; y += 8)
	{
		int jj = min(m_h - y, 8);

		for(int x = 0; x < m_w; x += 8)
		{
			int ii = min(m_w - x, 8);

			for(int c = 0; c < ColorComponents; c++)
			{
				int cc = !!c;

				int ACs = 0;

				static short block[64];

				for(int zigzag = 0; zigzag < 64; zigzag++) 
				{
					BYTE u = zigzagU[zigzag];
					BYTE v = zigzagV[zigzag];

					float F = 0;
/*
					for(int j = 0; j < jj; j++)
						for(int i = 0; i < ii; i++) 
							F += (signed char)m_p[((y+j)*m_w + (x+i))*4 + c] * cosuv[v][u][j][i];
*/
					for(int j = 0; j < jj; j++)
					{
						signed char* p = (signed char*)&m_p[((y+j)*m_w + x)*4 + c];
						for(int i = 0; i < ii; i++, p += 4) 
							F += *p * cosuv[v][u][j][i];
					}

					float cu = !u ? invsq2 : 1.0f;
					float cv = !v ? invsq2 : 1.0f;

					block[zigzag] = short(2.0 / 8.0 * cu * cv * F) / quanttbl[cc][zigzag];
				}

				short DC = block[0] - prevDC[c];
				prevDC[c] = block[0];

				int size = GetBitWidth(DC);
				PutBit(DCVLC[cc][size], DCVLC_Size[cc][size]);

				if(DC < 0) DC = DC - 1;
				PutBit(DC, size);

				int j;
				for(j = 64; j > 1 && !block[j-1]; j--);

				for(int i = 1; i < j; i++)
				{
					short AC = block[i];

					if(AC == 0)
					{
						if(++ACs == 16)
						{
							PutBit(ACVLC[cc][15][0], ACVLC_Size[cc][15][0]);
							ACs = 0;
						}
					}
					else
					{
						int size = GetBitWidth(AC);
						PutBit(ACVLC[cc][ACs][size], ACVLC_Size[cc][ACs][size]);
						
						if(AC < 0) AC--;
						PutBit(AC, size);

						ACs = 0;
					}
				}

				if(j < 64) PutBit(ACVLC[cc][0][0], ACVLC_Size[cc][0][0]);
			}
		}
	}

	Flush();
}
Exemple #9
0
void MainWindow::ShowData()
{
	// Default dropdownmenu entries 
	pcDevice->Clear();
	pcDefaultInput->Clear();
	pcDefaultAudioOut->Clear();
	pcDefaultVideoOut->Clear();
	
	// Add inputs
	os::MediaInput* pcInput;
	uint32 nIndex = 0;
	m_nInputStart = 0;

	while ( ( pcInput = os::MediaManager::GetInstance()->GetInput( nIndex ) ) != NULL )
	{
		pcDevice->AppendItem( pcInput->GetIdentifier() );
		
		if( !pcInput->FileNameRequired() )
		{
			pcDefaultInput->AppendItem( pcInput->GetIdentifier() );
			if( pcInput->GetIdentifier() == cCurrentInput )
				pcDefaultInput->SetSelection( pcDefaultInput->GetItemCount() - 1, false );
		}
		pcInput->Release();
		nIndex++;
	}
	
	// Add codecs
	os::MediaCodec* pcCodec;
	m_nCodecStart = m_nInputStart + nIndex;
	nIndex = 0;

	while ( ( pcCodec = os::MediaManager::GetInstance()->GetCodec( nIndex ) ) != NULL )
	{
		pcDevice->AppendItem( pcCodec->GetIdentifier() );
		pcCodec->Release();
		nIndex++;
	}
	
	// Add outputs
	os::MediaOutput * pcOutput;
	m_nOutputStart = m_nCodecStart + nIndex;
	nIndex = 0;

	while ( ( pcOutput = os::MediaManager::GetInstance()->GetOutput( nIndex ) ) != NULL )
	{
		if( !pcOutput->FileNameRequired() )
		{
			// Add to default dropdown menus 
			for( int i = 0; i < pcOutput->GetOutputFormatCount(); i++ )
			{
				os::MediaFormat_s sFormat = pcOutput->GetOutputFormat( i );
				if( sFormat.nType == os::MEDIA_TYPE_AUDIO ) {
					pcDefaultAudioOut->AppendItem( pcOutput->GetIdentifier() );
					if( pcOutput->GetIdentifier() == cCurrentAudio )
						pcDefaultAudioOut->SetSelection( pcDefaultAudioOut->GetItemCount() - 1, false );
					break;
				}
			}
			for( int i = 0; i < pcOutput->GetOutputFormatCount(); i++ )
			{
				os::MediaFormat_s sFormat = pcOutput->GetOutputFormat( i );
				if( sFormat.nType == os::MEDIA_TYPE_VIDEO ) {
					pcDefaultVideoOut->AppendItem( pcOutput->GetIdentifier() );
					if( pcOutput->GetIdentifier() == cCurrentVideo )
						pcDefaultVideoOut->SetSelection( pcDefaultVideoOut->GetItemCount() - 1, false );

					break;
				}
			}
		}
		pcDevice->AppendItem( pcOutput->GetIdentifier() );
		
		pcOutput->Release();
		nIndex++;
	}
	
	if( m_nDeviceSelect > -1 )
		pcDevice->SetSelection( m_nDeviceSelect, false );

	Flush();
}
Exemple #10
0
RTFStatus RTFReader::Parse(void)
{
	RTFStatus t_status;
	t_status = kRTFStatusSuccess;
			
	while(t_status == kRTFStatusSuccess)
	{
		RTFToken t_token;
		int4 t_value;
		
		if (m_input_skip_count > 0)
		{
			while(m_input_skip_count > 0)
			{
				t_status = ParseToken(t_token, t_value);
				if (t_status != kRTFStatusSuccess)
					break;

				if (t_token == kRTFTokenEnd || t_token == kRTFTokenBeginGroup || t_token == kRTFTokenEndGroup)
				{
					m_input_skip_count = 0;
					break;
				}

				if ((t_token & kRTFTokenMask) == kRTFTokenBin)
					m_input += t_value;

				m_input_skip_count -= 1;
			}
		}

		if (t_status == kRTFStatusSuccess)
			t_status = ParseToken(t_token, t_value);

		if (t_status != kRTFStatusSuccess)
			break;

		if (t_token == kRTFTokenEnd)
			break;
			
		if (t_token == kRTFTokenBeginGroup)
			t_status = m_state . Save();
		else if (t_token == kRTFTokenEndGroup)
		{
			// Take into account implementation of 'destinations'.
			bool t_was_list;
			t_was_list = m_state . GetDestination() == kRTFDestinationLegacyList;

			bool t_was_list_text;
			t_was_list_text = m_state . GetDestination() == kRTFDestinationListText;

			bool t_was_field;
			t_was_field = m_state . GetDestination() == kRTFDestinationFldInst;

			// MW-2014-01-08: [[ Bug 11627 ]] If the paragraph attributes have changed then
			//   force a flush so that a new paragraph with said attributes is created. [ This
			//   isn't 100% correct from my reading of the RTF Spec - really paragraph attrs
			//   should be set on the current paragraph as the paragraph is parsed, rather than
			//   before the first text is emitted - however due to the way LiveCode and Word Processors
			//   generate RTF, this at least makes things roundtrip ].
			if (m_state . HasParagraphChanged())
				Flush(true);

			t_status = m_state . Restore();

			if (t_was_list)
			{
				m_state . SetListStyle(m_list_style);
				m_state . SetListLevel(m_list_level);
			}
			else if (t_was_list_text)
			{
				if (m_list_skip)
					m_state . SetListStyle(kMCTextListStyleSkip);
			}
			else if (t_was_field && m_state . GetDestination() != kRTFDestinationFldInst)
			{
				ProcessField();
			}

			m_attributes_changed = true;
		}
		else if ((t_token & kRTFTokenMask) == kRTFTokenBin)
		{
			m_input_binary_count = t_value;
			m_input_state = kRTFInputStateBinary;
		}
		else switch(m_state . GetDestination())
		{
		case kRTFDestinationSkip:
			// If the skipped destination is in fact the 'list' destination then
			// handle it. We ignore 'pn' destinations if we have a listtable though.
			if (t_token == kRTFTokenLegacyList && m_lists . Count() == 0)
			{
				m_list_style = kMCTextListStyleNone;
				m_list_level = 0;
				m_state . SetDestination(kRTFDestinationLegacyList);
			}
			else if (t_token == kRTFTokenListTable)
				m_state . SetDestination(kRTFDestinationListTable);
			else if (t_token == kRTFTokenListOverrideTable)
				m_state . SetDestination(kRTFDestinationListOverrideTable);
			else if (t_token == kRTFTokenFldInst)
				m_state . SetDestination(kRTFDestinationFldInst);
		break;
		
		case kRTFDestinationNormal:
			t_status = ParseDocument(t_token, t_value);
		break;
		
		case kRTFDestinationFontTable:
			t_status = ParseFontTable(t_token, t_value);
		break;
		
		case kRTFDestinationColorTable:
			t_status = ParseColorTable(t_token, t_value);
		break;

		case kRTFDestinationLegacyList:
			t_status = ParseLegacyList(t_token, t_value);
		break;

		case kRTFDestinationLegacyListPrefix:
			t_status = ParseLegacyListPrefix(t_token, t_value);
		break;
				
		case kRTFDestinationLegacyListSuffix:
			break;
				
		case kRTFDestinationListTable:
			t_status = ParseListTable(t_token, t_value);
		break;
				
		case kRTFDestinationListTableLevelText:
			t_status = ParseListTableLevelText(t_token, t_value);
		break;
				
		case kRTFDestinationListOverrideTable:
			t_status = ParseListOverrideTable(t_token, t_value);
		break;

		case kRTFDestinationListText:
			t_status = ParseListText(t_token, t_value);
		break;

		case kRTFDestinationField:
		break;

		case kRTFDestinationFldInst:
			t_status = ParseFldInst(t_token, t_value);
		break;
		}
	}
	
	return t_status;
}
Exemple #11
0
RTFStatus RTFReader::ParseDocument(RTFToken p_token, int4 p_value)
{
	RTFStatus t_status;
	t_status = kRTFStatusSuccess;

	RTFToken t_token;
	t_token = p_token & kRTFTokenMask;

	bool t_has_parameter;
	t_has_parameter = (p_token & kRTFTokenHasParameter) != 0;

	switch(t_token)
	{
	case kRTFTokenSkipDestination:
		m_state . SetDestination(kRTFDestinationSkip);
	break;
	
	case kRTFTokenFontTable:
		m_state . SetDestination(kRTFDestinationFontTable);
	break;
	
	case kRTFTokenColorTable:
		m_state . SetDestination(kRTFDestinationColorTable);
	break;
	
	case kRTFTokenListTable:
		m_state . SetDestination(kRTFDestinationListTable);
	break;

	case kRTFTokenListText:
		m_list_skip = true;
		m_state . SetDestination(kRTFDestinationListText);
	break;
			
	case kRTFTokenListOverrideTable:
		m_state . SetDestination(kRTFDestinationListOverrideTable);
	break;

	case kRTFTokenFldInst:
		m_state . SetDestination(kRTFDestinationFldInst);
	break;

	case kRTFTokenField:
	break;
			
	case kRTFTokenDefaultFont:
		if (t_has_parameter)
			m_default_font = p_value;
	break;

	case kRTFTokenAnsi:
		m_default_text_encoding = kMCTextEncodingWindows1252;
	break;

	case kRTFTokenMac:
		m_default_text_encoding = kMCTextEncodingMacRoman;
	break;

	case kRTFTokenPC:
		m_default_text_encoding = (MCTextEncoding)(kMCTextEncodingWindowsNative + 437);
	break;

	case kRTFTokenPCA:
		m_default_text_encoding = (MCTextEncoding)(kMCTextEncodingWindowsNative + 850);
	break;

	case kRTFTokenAnsiCodepage:
		if (t_has_parameter)
		{
			if (p_value < 0)
				p_value = 65536 + p_value;
			
			m_default_text_encoding = (MCTextEncoding)(kMCTextEncodingWindowsNative + p_value);
		}
	break;

	case kRTFTokenUnicodeSkip:
		if (t_has_parameter)
			m_state . SetUnicodeSkip(p_value);
	break;

	case kRTFTokenNewLine:
	case kRTFTokenParagraph:
		t_status = Flush(true);
		if (t_status == kRTFStatusSuccess)
		{
			if (m_needs_paragraph)
				Paragraph();
			m_needs_paragraph = true;
		}
	break;

	case kRTFTokenResetParagraphStyle:
		// MW-2012-03-14: [[ RtfParaStyles ]] Reset all the paragraph styles to defaults.
		m_state . SetListStyle(kMCTextListStyleNone);
		m_state . SetListLevel(0);
		m_state . SetListIndex(0);
		m_state . SetBorderWidth(0);
		m_state . SetPadding(0);
		m_state . SetFirstIndent(0);
		m_state . SetLeftIndent(0);
		m_state . SetRightIndent(0);
		m_state . SetSpaceAbove(0);
		m_state . SetSpaceBelow(0);
		m_state . SetParagraphBackgroundColor(0xffffffff);
		m_state . SetBorderColor(0xffffffff);
			
		// MW-2014-01-08: [[ Bug 11627 ]] Make sure the text alignment attribute is reset.
		m_state . SetTextAlign(kMCTextTextAlignLeft);
		break;

	case kRTFTokenRow:
		m_table_cell = false;

		t_status = Flush(true);
		if (t_status == kRTFStatusSuccess)
		{
			if (m_needs_paragraph)
				Paragraph();
			m_needs_paragraph = true;
		}
	break;

	case kRTFTokenCell:
		if (m_table_cell)
		{
			m_table_cell = false;
			t_status = m_text . Output(9, kMCTextEncodingUTF16);
		}
		if (t_status == kRTFStatusSuccess && m_attributes_changed)
			t_status = Flush();
		if (t_status == kRTFStatusSuccess)
			m_table_cell = true;
	break;

	case kRTFTokenColor:
		if (t_has_parameter)
		{
			m_state .  SetForegroundColor(m_colors . Get(p_value));
			m_attributes_changed = true;
		}
	break;

	case kRTFTokenHighlight:
		if (t_has_parameter)
		{
			m_state . SetBackgroundColor(m_colors . Get(p_value));
			m_attributes_changed = true;
		}
	break;

	case kRTFTokenPlain:
		m_state . SetFontName(nil);
		m_state . SetFontStyle(kRTFFontStyleNone);
		m_state . SetFontSize(0);
		m_attributes_changed = true;
	break;

	case kRTFTokenFont:
		if (t_has_parameter)
		{
			static struct { int charset; MCTextEncoding encoding; } s_charset_mapping[] =
			{
				{ ANSI_CHARSET, kMCTextEncodingWindows1252 },
				{ SYMBOL_CHARSET, kMCTextEncodingSymbol },
				{ MAC_CHARSET , kMCTextEncodingMacRoman },
				{ SHIFTJIS_CHARSET, MCTextEncoding(kMCTextEncodingWindowsNative + 932) },
				{ HANGEUL_CHARSET, MCTextEncoding(kMCTextEncodingWindowsNative + 949) },
				{ JOHAB_CHARSET, MCTextEncoding(kMCTextEncodingWindowsNative + 1361) },
				{ GB2312_CHARSET, MCTextEncoding(kMCTextEncodingWindowsNative + 936) },
				{ CHINESEBIG5_CHARSET, MCTextEncoding(kMCTextEncodingWindowsNative + 950) },
				{ GREEK_CHARSET, MCTextEncoding(kMCTextEncodingWindowsNative + 1253) },
				{ TURKISH_CHARSET, MCTextEncoding(kMCTextEncodingWindowsNative + 1254) },
				{ VIETNAMESE_CHARSET, MCTextEncoding(kMCTextEncodingWindowsNative + 1258) },
				{ HEBREW_CHARSET, MCTextEncoding(kMCTextEncodingWindowsNative + 1255) },
				{ ARABIC_CHARSET, MCTextEncoding(kMCTextEncodingWindowsNative + 1256) },
				{ BALTIC_CHARSET, MCTextEncoding(kMCTextEncodingWindowsNative + 1257) },
				{ RUSSIAN_CHARSET, MCTextEncoding(kMCTextEncodingWindowsNative + 1251) },
				{ THAI_CHARSET, MCTextEncoding(kMCTextEncodingWindowsNative + 874) },
				{ EASTEUROPE_CHARSET, MCTextEncoding(kMCTextEncodingWindowsNative + 1250) },
				{ /* PC437_CHARSET */ 254, MCTextEncoding(kMCTextEncodingWindowsNative + 437) },
				{ -1, kMCTextEncodingUndefined }
			};

			const char *t_new_font;
			t_new_font = m_fonts . GetName(p_value);

			uint4 t_new_charset;
			t_new_charset = m_fonts . GetCharset(p_value);

			MCTextEncoding t_new_encoding;
			if (t_new_charset == DEFAULT_CHARSET)
				t_new_encoding = m_default_text_encoding;
			else
			{
				uint4 t_charset_index;
				for(t_charset_index = 0; s_charset_mapping[t_charset_index] . charset != -1; ++t_charset_index)
					if (s_charset_mapping[t_charset_index] . charset == t_new_charset)
						break;
				t_new_encoding = s_charset_mapping[t_charset_index] . encoding;
			}

			m_state . SetTextEncoding(t_new_encoding);
			m_state . SetFontName(t_new_font);
			m_attributes_changed = true;
		}
	break;

	case kRTFTokenFontSize:
		if (t_has_parameter)
		{
			m_state . SetFontSize(p_value);
			m_attributes_changed = true;
		}
	break;

	case kRTFTokenBold:
	case kRTFTokenItalic:
	case kRTFTokenUnderline:
	case kRTFTokenNoUnderline:
	case kRTFTokenStrikethrough:
	case kRTFTokenSuperscript:
	case kRTFTokenSubscript:
	{
		bool t_turn_off;
		t_turn_off = t_has_parameter && p_value == 0;

		RTFFontStyle t_mask = 0;
		if (t_token == kRTFTokenBold)
			t_mask = kRTFFontStyleBold;
		else if (t_token == kRTFTokenItalic)
			t_mask = kRTFFontStyleItalic;
		else if (t_token == kRTFTokenUnderline)
			t_mask = kRTFFontStyleUnderline;
		else if (t_token == kRTFTokenNoUnderline)
		{
			t_mask = kRTFFontStyleUnderline;
			t_turn_off = true;
		}
		else if (t_token == kRTFTokenStrikethrough)
			t_mask = kRTFFontStyleStrikethrough;
		else if (t_token == kRTFTokenSuperscript)
			t_mask = kRTFFontStyleSuperscript;
		else if (t_token == kRTFTokenSubscript)
			t_mask = kRTFFontStyleSubscript;

		RTFFontStyle t_new_style;
		if (t_turn_off)
			t_new_style = m_state . GetFontStyle() & ~t_mask;
		else
			t_new_style = m_state . GetFontStyle() | t_mask;

		m_state . SetFontStyle(t_new_style);
		m_attributes_changed = true;
	}
	break;

	case kRTFTokenTab:
		if (t_status == kRTFStatusSuccess && m_table_cell)
		{
			m_table_cell = false;
			t_status = m_text . Output(9, kMCTextEncodingUTF16);
		}
		if (m_attributes_changed)
			t_status = Flush();
		if (t_status == kRTFStatusSuccess)
			t_status = m_text . Output(9, kMCTextEncodingUTF16);
	break;

	case kRTFTokenUnicode:
	{
		if (t_has_parameter)
		{
			if (t_status == kRTFStatusSuccess && m_table_cell)
			{
				m_table_cell = false;
				t_status = m_text . Output(9, kMCTextEncodingUTF16);
			}
			
			// MW-2014-03-14: [[ Bug 11771 ]] On Mac, HTML on the clipboard is translated
			//   to RTF with LINE SEPARATOR instead of BR. So map both LINE SEPARATOR and
			//   PARAGRAPH SEPARATOR to a new paragraph marker. (This is consistent with the
			//   handling of newline and other related markers in the RTF and means
			//   scripts won't get tripped up).
			if ((p_value & 0xFFFF) == 0x2028 || (p_value & 0xFFFF) == 0x2029)
			{	
				t_status = Flush(true);
				if (t_status == kRTFStatusSuccess)
				{
					if (m_needs_paragraph)
						Paragraph();
					m_needs_paragraph = true;
				}
			}
			else
			{
				if (m_attributes_changed)
					t_status = Flush();
				if (t_status == kRTFStatusSuccess)
					t_status = m_text . Output(p_value & 0xFFFF, kMCTextEncodingUTF16);
				if (t_status == kRTFStatusSuccess)
					m_input_skip_count = m_state . GetUnicodeSkip();
			}
		}
	}
	break;

	case kRTFTokenCharacter:
	{
		MCTextEncoding t_encoding;
		t_encoding = m_state . GetTextEncoding();
		if (t_encoding == kMCTextEncodingUndefined)
			t_encoding = m_default_text_encoding;
		if (t_status == kRTFStatusSuccess && m_table_cell)
		{
			m_table_cell = false;
			t_status = m_text . Output(9, kMCTextEncodingUTF16);
		}
		if (m_attributes_changed)
			t_status = Flush();
		if (t_status == kRTFStatusSuccess)
			t_status = m_text . Output(p_value, t_encoding);
	}
	break;

	// MW-2010-01-08: [[ Bug 8143 ]] Make sure we handle special chars and map then to UTF-16
	case kRTFTokenBullet:
		t_status = m_text . Output(0x2022, kMCTextEncodingUTF16);
		break;
	case kRTFTokenLeftQuote:
		t_status = m_text . Output(0x2018, kMCTextEncodingUTF16);
		break;
	case kRTFTokenRightQuote:
		t_status = m_text . Output(0x2019, kMCTextEncodingUTF16);
		break;
	case kRTFTokenLeftDoubleQuote:
		t_status = m_text . Output(0x201C, kMCTextEncodingUTF16);
		break;
	case kRTFTokenRightDoubleQuote:
		t_status = m_text . Output(0x201D, kMCTextEncodingUTF16);
		break;
			
	// Handle the 'listselect' style lists.
	case kRTFTokenListSelect:
		if (t_has_parameter)
			m_state . SetListIndex(p_value);
	break;

	// MW-2012-03-14: [[ RtfParaStyles ]] Handle the list level select.
	case kRTFTokenListSelectLevel:
		if (t_has_parameter && p_value >= 0 && p_value <= 8)
			m_state . SetListLevel(p_value);
		break;

	// MW-2012-03-14: [[ RtfParaStyles ]] Handle all the paragraph style tags.
	case kRTFTokenParagraphBackgroundColor:
		if (t_has_parameter)
			m_state . SetParagraphBackgroundColor(m_colors . Get(p_value));
		break;
	case kRTFTokenParagraphBorderWidth:
		if (t_has_parameter)
			m_state . SetBorderWidth(p_value);
		break;
	case kRTFTokenParagraphBorderColor:
		if (t_has_parameter)
			m_state . SetBorderColor(m_colors . Get(p_value));
		break;
	case kRTFTokenParagraphPadding:
		if (t_has_parameter)
			m_state . SetPadding(p_value);
		break;
	case kRTFTokenLeftIndent:
		if (t_has_parameter)
			m_state . SetLeftIndent(p_value);
		break;
	case kRTFTokenRightIndent:
		if (t_has_parameter)
			m_state . SetRightIndent(p_value);
		break;
	case kRTFTokenFirstIndent:
		if (t_has_parameter)
			m_state . SetFirstIndent(p_value);
		break;
	case kRTFTokenSpaceAbove:
		if (t_has_parameter)
			m_state . SetSpaceAbove(p_value);
		break;
	case kRTFTokenSpaceBelow:
		if (t_has_parameter)
			m_state . SetSpaceBelow(p_value);
		break;
	case kRTFTokenLeftJustify:
		m_state . SetTextAlign(kMCTextTextAlignLeft);
		break;
	case kRTFTokenRightJustify:
		m_state . SetTextAlign(kMCTextTextAlignRight);
		break;
	case kRTFTokenCenterJustify:
		m_state . SetTextAlign(kMCTextTextAlignCenter);
		break;
	}
	
	return t_status;
}
Exemple #12
0
DSG:: RingBuffer::~RingBuffer(){Flush();}
void CSocketClient::ReleaseBuffers()
{
	Flush();
}
Exemple #14
0
void CGraphics_OpenGL::AddVertices(int Count)
{
	m_NumVertices += Count;
	if((m_NumVertices + Count) >= MAX_VERTICES)
		Flush();
}
Exemple #15
0
void
_SHOWVALUE(
	unsigned long value,
	int size,
	const char *name,
	const char *file,
	int line)
{
	if(__debug_level >= DEBUGLEVEL_Reports)
	{
		char *fmt;

		switch(size)
		{
			case 1:

				fmt = "%s:%ld:%s = %ld, 0x%02lx";
				break;

			case 2:

				fmt = "%s:%ld:%s = %ld, 0x%04lx";
				break;

			default:

				fmt = "%s:%ld:%s = %ld, 0x%08lx";
				break;
		}

		_INDENT();

		if(debug_file == (BPTR)NULL)
			kprintf(fmt,file,line,name,value,value);
		else
			FPrintf(debug_file,fmt,file,line,name,value,value);

		if(size == 1 && value < 256)
		{
			if(debug_file == (BPTR)NULL)
			{
				if(value < ' ' || (value >= 127 && value < 160))
					kprintf(", '\\x%02lx'",value);
				else
					kprintf(", '%lc'",value);
			}
			else
			{
				if(value < ' ' || (value >= 127 && value < 160))
					FPrintf(debug_file,", '\\x%02lx'",value);
				else
					FPrintf(debug_file,", '%lc'",value);
			}
		}

		if(debug_file == (BPTR)NULL)
		{
			kprintf("\n");
		}
		else
		{
			FPrintf(debug_file,"\n");
			Flush(debug_file);
		}
	}
}
void
X86VMTranslationMap64Bit::UnmapPages(VMArea* area, addr_t base, size_t size,
	bool updatePageQueue)
{
	if (size == 0)
		return;

	addr_t start = base;
	addr_t end = base + size - 1;

	TRACE("X86VMTranslationMap64Bit::UnmapPages(%p, %#" B_PRIxADDR ", %#"
		B_PRIxADDR ")\n", area, start, end);

	VMAreaMappings queue;

	RecursiveLocker locker(fLock);
	ThreadCPUPinner pinner(thread_get_current_thread());

	do {
		uint64* pageTable = X86PagingMethod64Bit::PageTableForAddress(
			fPagingStructures->VirtualPML4(), start, fIsKernelMap, false,
			NULL, fPageMapper, fMapCount);
		if (pageTable == NULL) {
			// Move on to the next page table.
			start = ROUNDUP(start + 1, k64BitPageTableRange);
			continue;
		}

		for (uint32 index = start / B_PAGE_SIZE % k64BitTableEntryCount;
				index < k64BitTableEntryCount && start < end;
				index++, start += B_PAGE_SIZE) {
			uint64 oldEntry = X86PagingMethod64Bit::ClearTableEntry(
				&pageTable[index]);
			if ((oldEntry & X86_64_PTE_PRESENT) == 0)
				continue;

			fMapCount--;

			if ((oldEntry & X86_64_PTE_ACCESSED) != 0) {
				// Note, that we only need to invalidate the address, if the
				// accessed flags was set, since only then the entry could have
				// been in any TLB.
				InvalidatePage(start);
			}

			if (area->cache_type != CACHE_TYPE_DEVICE) {
				// get the page
				vm_page* page = vm_lookup_page(
					(oldEntry & X86_64_PTE_ADDRESS_MASK) / B_PAGE_SIZE);
				ASSERT(page != NULL);

				DEBUG_PAGE_ACCESS_START(page);

				// transfer the accessed/dirty flags to the page
				if ((oldEntry & X86_64_PTE_ACCESSED) != 0)
					page->accessed = true;
				if ((oldEntry & X86_64_PTE_DIRTY) != 0)
					page->modified = true;

				// remove the mapping object/decrement the wired_count of the
				// page
				if (area->wiring == B_NO_LOCK) {
					vm_page_mapping* mapping = NULL;
					vm_page_mappings::Iterator iterator
						= page->mappings.GetIterator();
					while ((mapping = iterator.Next()) != NULL) {
						if (mapping->area == area)
							break;
					}

					ASSERT(mapping != NULL);

					area->mappings.Remove(mapping);
					page->mappings.Remove(mapping);
					queue.Add(mapping);
				} else
					page->DecrementWiredCount();

				if (!page->IsMapped()) {
					atomic_add(&gMappedPagesCount, -1);

					if (updatePageQueue) {
						if (page->Cache()->temporary)
							vm_page_set_state(page, PAGE_STATE_INACTIVE);
						else if (page->modified)
							vm_page_set_state(page, PAGE_STATE_MODIFIED);
						else
							vm_page_set_state(page, PAGE_STATE_CACHED);
					}
				}

				DEBUG_PAGE_ACCESS_END(page);
			}
		}

		Flush();
			// flush explicitly, since we directly use the lock
	} while (start != 0 && start < end);

	// TODO: As in UnmapPage() we can lose page dirty flags here. ATM it's not
	// really critical here, as in all cases this method is used, the unmapped
	// area range is unmapped for good (resized/cut) and the pages will likely
	// be freed.

	locker.Unlock();

	// free removed mappings
	bool isKernelSpace = area->address_space == VMAddressSpace::Kernel();
	uint32 freeFlags = CACHE_DONT_WAIT_FOR_MEMORY
		| (isKernelSpace ? CACHE_DONT_LOCK_KERNEL_SPACE : 0);
	while (vm_page_mapping* mapping = queue.RemoveHead())
		object_cache_free(gPageMappingsObjectCache, mapping, freeFlags);
}
Exemple #17
0
clIniFile::~clIniFile() { Flush(); }
void
X86VMTranslationMap64Bit::UnmapArea(VMArea* area, bool deletingAddressSpace,
	bool ignoreTopCachePageFlags)
{
	TRACE("X86VMTranslationMap64Bit::UnmapArea(%p)\n", area);

	if (area->cache_type == CACHE_TYPE_DEVICE || area->wiring != B_NO_LOCK) {
		X86VMTranslationMap64Bit::UnmapPages(area, area->Base(), area->Size(),
			true);
		return;
	}

	bool unmapPages = !deletingAddressSpace || !ignoreTopCachePageFlags;

	RecursiveLocker locker(fLock);
	ThreadCPUPinner pinner(thread_get_current_thread());

	VMAreaMappings mappings;
	mappings.MoveFrom(&area->mappings);

	for (VMAreaMappings::Iterator it = mappings.GetIterator();
			vm_page_mapping* mapping = it.Next();) {
		vm_page* page = mapping->page;
		page->mappings.Remove(mapping);

		VMCache* cache = page->Cache();

		bool pageFullyUnmapped = false;
		if (!page->IsMapped()) {
			atomic_add(&gMappedPagesCount, -1);
			pageFullyUnmapped = true;
		}

		if (unmapPages || cache != area->cache) {
			addr_t address = area->Base()
				+ ((page->cache_offset * B_PAGE_SIZE) - area->cache_offset);

			uint64* entry = X86PagingMethod64Bit::PageTableEntryForAddress(
				fPagingStructures->VirtualPML4(), address, fIsKernelMap,
				false, NULL, fPageMapper, fMapCount);
			if (entry == NULL) {
				panic("page %p has mapping for area %p (%#" B_PRIxADDR "), but "
					"has no page table", page, area, address);
				continue;
			}

			uint64 oldEntry = X86PagingMethod64Bit::ClearTableEntry(entry);

			if ((oldEntry & X86_64_PTE_PRESENT) == 0) {
				panic("page %p has mapping for area %p (%#" B_PRIxADDR "), but "
					"has no page table entry", page, area, address);
				continue;
			}

			// transfer the accessed/dirty flags to the page and invalidate
			// the mapping, if necessary
			if ((oldEntry & X86_64_PTE_ACCESSED) != 0) {
				page->accessed = true;

				if (!deletingAddressSpace)
					InvalidatePage(address);
			}

			if ((oldEntry & X86_64_PTE_DIRTY) != 0)
				page->modified = true;

			if (pageFullyUnmapped) {
				DEBUG_PAGE_ACCESS_START(page);

				if (cache->temporary)
					vm_page_set_state(page, PAGE_STATE_INACTIVE);
				else if (page->modified)
					vm_page_set_state(page, PAGE_STATE_MODIFIED);
				else
					vm_page_set_state(page, PAGE_STATE_CACHED);

				DEBUG_PAGE_ACCESS_END(page);
			}
		}

		fMapCount--;
	}

	Flush();
		// flush explicitely, since we directly use the lock

	locker.Unlock();

	bool isKernelSpace = area->address_space == VMAddressSpace::Kernel();
	uint32 freeFlags = CACHE_DONT_WAIT_FOR_MEMORY
		| (isKernelSpace ? CACHE_DONT_LOCK_KERNEL_SPACE : 0);
	while (vm_page_mapping* mapping = mappings.RemoveHead())
		object_cache_free(gPageMappingsObjectCache, mapping, freeFlags);
}
Exemple #19
0
// close the stream
CS422::FileStream::~FileStream(){
	Flush();
}
bool
X86VMTranslationMap64Bit::ClearAccessedAndModified(VMArea* area, addr_t address,
	bool unmapIfUnaccessed, bool& _modified)
{
	ASSERT(address % B_PAGE_SIZE == 0);

	TRACE("X86VMTranslationMap64Bit::ClearAccessedAndModified(%#" B_PRIxADDR
		")\n", address);

	RecursiveLocker locker(fLock);
	ThreadCPUPinner pinner(thread_get_current_thread());

	uint64* entry = X86PagingMethod64Bit::PageTableEntryForAddress(
		fPagingStructures->VirtualPML4(), address, fIsKernelMap,
		false, NULL, fPageMapper, fMapCount);
	if (entry == NULL)
		return false;

	uint64 oldEntry;

	if (unmapIfUnaccessed) {
		while (true) {
			oldEntry = *entry;
			if ((oldEntry & X86_64_PTE_PRESENT) == 0) {
				// page mapping not valid
				return false;
			}

			if (oldEntry & X86_64_PTE_ACCESSED) {
				// page was accessed -- just clear the flags
				oldEntry = X86PagingMethod64Bit::ClearTableEntryFlags(entry,
					X86_64_PTE_ACCESSED | X86_64_PTE_DIRTY);
				break;
			}

			// page hasn't been accessed -- unmap it
			if (X86PagingMethod64Bit::TestAndSetTableEntry(entry, 0, oldEntry)
					== oldEntry) {
				break;
			}

			// something changed -- check again
		}
	} else {
		oldEntry = X86PagingMethod64Bit::ClearTableEntryFlags(entry,
			X86_64_PTE_ACCESSED | X86_64_PTE_DIRTY);
	}

	pinner.Unlock();

	_modified = (oldEntry & X86_64_PTE_DIRTY) != 0;

	if ((oldEntry & X86_64_PTE_ACCESSED) != 0) {
		// Note, that we only need to invalidate the address, if the
		// accessed flags was set, since only then the entry could have been
		// in any TLB.
		InvalidatePage(address);
		Flush();

		return true;
	}

	if (!unmapIfUnaccessed)
		return false;

	// We have unmapped the address. Do the "high level" stuff.

	fMapCount--;

	locker.Detach();
		// UnaccessedPageUnmapped() will unlock for us

	UnaccessedPageUnmapped(area,
		(oldEntry & X86_64_PTE_ADDRESS_MASK) / B_PAGE_SIZE);

	return false;
}
Exemple #21
0
SqlMassInsert::~SqlMassInsert()
{
	Flush();
}
Exemple #22
0
void GSRenderer::VSync(int field)
{
	GSPerfMonAutoTimer pmat(&m_perfmon);

	m_perfmon.Put(GSPerfMon::Frame);

	Flush();

	if(!m_dev->IsLost(true))
	{
		if(!Merge(field ? 1 : 0))
		{
			return;
		}
	}
	else
	{
		ResetDevice();
	}

	m_dev->AgePool();

	// osd

	if((m_perfmon.GetFrame() & 0x1f) == 0)
	{
		m_perfmon.Update();

		double fps = 1000.0f / m_perfmon.Get(GSPerfMon::Frame);

		string s;

#ifdef GSTITLEINFO_API_FORCE_VERBOSE
		if(1)//force verbose reply
#else
		if(m_wnd->IsManaged())
#endif
		{
			//GSdx owns the window's title, be verbose.

			string s2 = m_regs->SMODE2.INT ? (string("Interlaced ") + (m_regs->SMODE2.FFMD ? "(frame)" : "(field)")) : "Progressive";

			s = format(
				"%lld | %d x %d | %.2f fps (%d%%) | %s - %s | %s | %d S/%d P/%d D | %d%% CPU | %.2f | %.2f",
				m_perfmon.GetFrame(), GetInternalResolution().x, GetInternalResolution().y, fps, (int)(100.0 * fps / GetTvRefreshRate()),
				s2.c_str(),
				theApp.m_gs_interlace[m_interlace].name.c_str(),
				theApp.m_gs_aspectratio[m_aspectratio].name.c_str(),
				(int)m_perfmon.Get(GSPerfMon::SyncPoint),
				(int)m_perfmon.Get(GSPerfMon::Prim),
				(int)m_perfmon.Get(GSPerfMon::Draw),
				m_perfmon.CPU(),
				m_perfmon.Get(GSPerfMon::Swizzle) / 1024,
				m_perfmon.Get(GSPerfMon::Unswizzle) / 1024
			);

			double fillrate = m_perfmon.Get(GSPerfMon::Fillrate);

			if(fillrate > 0)
			{
				s += format(" | %.2f mpps", fps * fillrate / (1024 * 1024));

				int sum = 0;

				for(int i = 0; i < 16; i++)
				{
					sum += m_perfmon.CPU(GSPerfMon::WorkerDraw0 + i);
				}

				s += format(" | %d%% CPU", sum);
			}
		}
		else
		{
			// Satisfy PCSX2's request for title info: minimal verbosity due to more external title text

			s = format("%dx%d | %s", GetInternalResolution().x, GetInternalResolution().y, theApp.m_gs_interlace[m_interlace].name.c_str());
		}

		if(m_capture.IsCapturing())
		{
			s += " | Recording...";
		}

		if(m_wnd->IsManaged())
		{
			m_wnd->SetWindowText(s.c_str());
		}
		else
		{
			// note: do not use TryEnterCriticalSection.  It is unnecessary code complication in
			// an area that absolutely does not matter (even if it were 100 times slower, it wouldn't
			// be noticeable).  Besides, these locks are extremely short -- overhead of conditional
			// is way more expensive than just waiting for the CriticalSection in 1 of 10,000,000 tries. --air

			std::lock_guard<std::mutex> lock(m_pGSsetTitle_Crit);

			strncpy(m_GStitleInfoBuffer, s.c_str(), countof(m_GStitleInfoBuffer) - 1);

			m_GStitleInfoBuffer[sizeof(m_GStitleInfoBuffer) - 1] = 0; // make sure null terminated even if text overflows
		}
	}
	else
	{
		// [TODO]
		// We don't have window title rights, or the window has no title,
		// so let's use actual OSD!
	}

	if(m_frameskip)
	{
		return;
	}

	// present

	m_dev->Present(m_wnd->GetClientRect().fit(m_aspectratio), m_shader);

	// snapshot

	if(!m_snapshot.empty())
	{
		bool shift = false;

		#ifdef _WIN32

		shift = !!(::GetAsyncKeyState(VK_SHIFT) & 0x8000);

		#else

		shift = m_shift_key;

		#endif

		if(!m_dump && shift)
		{
			GSFreezeData fd;
			fd.size = 0;
			fd.data = NULL;
			Freeze(&fd, true);
			fd.data = new uint8[fd.size];
			Freeze(&fd, false);

			m_dump.Open(m_snapshot, m_crc, fd, m_regs);

			delete [] fd.data;
		}

		if(GSTexture* t = m_dev->GetCurrent())
		{
			t->Save(m_snapshot + ".bmp");
		}

		m_snapshot.clear();
	}
	else
	{
		if(m_dump)
		{
            bool control = false;

            #ifdef _WIN32

            control = !!(::GetAsyncKeyState(VK_CONTROL) & 0x8000);

			#else

			control = m_control_key;

            #endif

	    	m_dump.VSync(field, !control, m_regs);
		}
	}

	// capture

	if(m_capture.IsCapturing())
	{
		if(GSTexture* current = m_dev->GetCurrent())
		{
			GSVector2i size = m_capture.GetSize();

			if(GSTexture* offscreen = m_dev->CopyOffscreen(current, GSVector4(0, 0, 1, 1), size.x, size.y))
			{
				GSTexture::GSMap m;

				if(offscreen->Map(m))
				{
					m_capture.DeliverFrame(m.bits, m.pitch, !m_dev->IsRBSwapped());

					offscreen->Unmap();
				}

				m_dev->Recycle(offscreen);
			}
		}
	}
}
Exemple #23
0
static void OutputFlush( audio_output_t *aout )
{
    aout_sys_t *sys = aout->sys;
    Flush( &sys->s );
}
Exemple #24
0
int VSIStdoutHandle::Close()

{
    return Flush();
}
Exemple #25
0
	void doTouchDown()
	{
		Flush();

	}
Exemple #26
0
static void LoadFileStateData(const std::string& filename, std::vector<u8>& ret_data)
{
  Flush();
  File::IOFile f(filename, "rb");
  if (!f)
  {
    Core::DisplayMessage("State not found", 2000);
    return;
  }

  StateHeader header;
  f.ReadArray(&header, 1);

  if (strncmp(SConfig::GetInstance().GetUniqueID().c_str(), header.gameID, 6))
  {
    Core::DisplayMessage(
        StringFromFormat("State belongs to a different game (ID %.*s)", 6, header.gameID), 2000);
    return;
  }

  std::vector<u8> buffer;

  if (header.size != 0)  // non-zero size means the state is compressed
  {
    Core::DisplayMessage("Decompressing State...", 500);

    buffer.resize(header.size);

    lzo_uint i = 0;
    while (true)
    {
      lzo_uint32 cur_len = 0;  // number of bytes to read
      lzo_uint new_len = 0;    // number of bytes to write

      if (!f.ReadArray(&cur_len, 1))
        break;

      f.ReadBytes(out, cur_len);
      const int res = lzo1x_decompress(out, cur_len, &buffer[i], &new_len, nullptr);
      if (res != LZO_E_OK)
      {
        // This doesn't seem to happen anymore.
        PanicAlertT("Internal LZO Error - decompression failed (%d) (%li, %li) \n"
                    "Try loading the state again",
                    res, i, new_len);
        return;
      }

      i += new_len;
    }
  }
  else  // uncompressed
  {
    const size_t size = (size_t)(f.GetSize() - sizeof(StateHeader));
    buffer.resize(size);

    if (!f.ReadBytes(&buffer[0], size))
    {
      PanicAlert("wtf? reading bytes: %zu", size);
      return;
    }
  }

  // all good
  ret_data.swap(buffer);
}
Exemple #27
0
void EndProgram(void)
{
	Flush();
}
Exemple #28
0
/*
 * this will be called twice:
 * 1) rcfilename = "/etc/screenrc"
 * 2) rcfilename = RcFileName
 */
int StartRc(char *rcfilename, int nopanic)
{
	int argc, len;
	char *p, *cp;
	char buf[2048];
	char *args[MAXARGS];
	int argl[MAXARGS];
	FILE *fp;
	char *oldrc_name = rc_name;

	/* always fix termcap/info capabilities */
	extra_incap = CatExtra("TF", extra_incap);

	/* Special settings for vt100 and others */
	if (display && (!strncmp(D_termname, "vt", 2) || !strncmp(D_termname, "xterm", 5)))
		extra_incap =
		    CatExtra
		    ("xn:f0=\033Op:f1=\033Oq:f2=\033Or:f3=\033Os:f4=\033Ot:f5=\033Ou:f6=\033Ov:f7=\033Ow:f8=\033Ox:f9=\033Oy:f.=\033On:f,=\033Ol:fe=\033OM:f+=\033Ok:f-=\033Om:f*=\033Oj:f/=\033Oo:fq=\033OX",
		     extra_incap);

	rc_name = findrcfile(rcfilename);

	if (rc_name == NULL || (fp = secfopen(rc_name, "r")) == NULL) {
		const char *rc_nonnull = rc_name ? rc_name : rcfilename;
		if (!rc_recursion && RcFileName && !strcmp(RcFileName, rc_nonnull)) {
			/*
			 * User explicitly gave us that name,
			 * this is the only case, where we get angry, if we can't read
			 * the file.
			 */
			if (!nopanic)
				Panic(0, "Unable to open \"%s\".", rc_nonnull);
			/* possibly NOTREACHED */
		}
		if (rc_name)
			Free(rc_name);
		rc_name = oldrc_name;
		return 1;
	}
	while (fgets(buf, sizeof buf, fp) != NULL) {
		if ((p = strrchr(buf, '\n')) != NULL)
			*p = '\0';
		if ((argc = Parse(buf, sizeof buf, args, argl)) == 0)
			continue;
		if (strcmp(args[0], "echo") == 0) {
			if (!display)
				continue;
			if (argc < 2 || (argc == 3 && strcmp(args[1], "-n")) || argc > 3) {
				Msg(0, "%s: 'echo [-n] \"string\"' expected.", rc_name);
				continue;
			}
			AddStr(args[argc - 1]);
			if (argc != 3) {
				AddStr("\r\n");
				Flush(0);
			}
		} else if (strcmp(args[0], "sleep") == 0) {
			if (!display)
				continue;
			if (argc != 2) {
				Msg(0, "%s: sleep: one numeric argument expected.", rc_name);
				continue;
			}
			DisplaySleep1000(1000 * atoi(args[1]), 1);
		}
		else if (!strcmp(args[0], "termcapinfo") || !strcmp(args[0], "terminfo"))
		{
			if (!display)
				continue;
			if (argc < 3 || argc > 4) {
				Msg(0, "%s: %s: incorrect number of arguments.", rc_name, args[0]);
				continue;
			}
			for (p = args[1]; p && *p; p = cp) {
				if ((cp = strchr(p, '|')) != 0)
					*cp++ = '\0';
				len = strlen(p);
				if (p[len - 1] == '*') {
					if (!(len - 1) || !strncmp(p, D_termname, len - 1))
						break;
				} else if (!strcmp(p, D_termname))
					break;
			}
			if (!(p && *p))
				continue;
			extra_incap = CatExtra(args[2], extra_incap);
			if (argc == 4)
				extra_outcap = CatExtra(args[3], extra_outcap);
		} else if (!strcmp(args[0], "source")) {
			if (rc_recursion <= 10) {
				rc_recursion++;
				(void)StartRc(args[1], 0);
				rc_recursion--;
			}
		}
	}
	fclose(fp);
	Free(rc_name);
	rc_name = oldrc_name;
	return 0;
}
Exemple #29
0
void SocketWBuffer::WriteChar(char ch) {
    buffer_[pos_++] = ch;
    if (pos_ == buffer_.size()) {
        Flush();
    }
}
Exemple #30
0
void CGraphics_OpenGL::LinesEnd()
{
	dbg_assert(m_Drawing == DRAWING_LINES, "called end without begin");
	Flush();
	m_Drawing = 0;
}