Example #1
0
void UReporterGraph::DrawData(UCanvas* Canvas)
{
    FVector2D Start, End;

    const FVector2D Min = FVector2D(GraphScreenSize.Min.X * Canvas->SizeX, Canvas->SizeY - GraphScreenSize.Min.Y * Canvas->SizeY);
    const FVector2D Max = FVector2D(GraphScreenSize.Max.X * Canvas->SizeX, Canvas->SizeY - GraphScreenSize.Max.Y * Canvas->SizeY);
    const float Height = GraphScreenSize.Max.Y - GraphScreenSize.Min.Y;
    const float dx = Height / FMath::Abs(Max.Y - Min.Y);
    UFont* Font = GetDefaultFont();
    int32 StringSizeX, StringSizeY;
    // Draw the X axis
    StringSize(Font, StringSizeX, StringSizeY, TEXT("0"));

    float UpOffset = 0;
    float DownOffset = 0;

    if (bDrawCursorOnGraph && DataStyle == EGraphDataStyle::Lines)
    {
        DrawLine(Canvas, DataToNormalized(FVector2D(CursorLocation, GraphMinMaxData.Min.Y)), DataToNormalized(FVector2D(CursorLocation, GraphMinMaxData.Max.Y)), FLinearColor::White, EReporterLineStyle::Line);
    }

    for (int32 i = 0; i < CurrentData.Num(); i++)
    {
        if (IsOffsetForDataSetsEnabled())
        {
            if (i % 2)
            {
                UpOffset += dx;
            }
            else
            {
                DownOffset += dx;
            }
        }

        for (int32 j = 1; j < CurrentData[i].Data.Num(); j++)
        {
            FVector2D DataStart = Start = CurrentData[i].Data[j - 1];
            FVector2D DataEnd = End = CurrentData[i].Data[j];

            Start = DataToNormalized(Start);
            End = DataToNormalized(End);

            if (DataStyle == EGraphDataStyle::Lines)
            {
                const FVector2D DrawOffset = FVector2D(UpOffset, UpOffset) * (i % 2 ? 1.0 : -1.0f);
                DrawLine(Canvas, Start + DrawOffset, End + DrawOffset, CurrentData[i].Color);

                if (bDrawCursorOnGraph && CursorLocation >= DataStart.X && CursorLocation < DataEnd.X)
                {
                    const float t = (CursorLocation - DataStart.X) / (DataEnd.X - DataStart.X);
                    FVector2D Location = FMath::Lerp<FVector2D, float>(DataStart, DataEnd, t);

                    FVector2D TextPos = ToScreenSpace(DataToNormalized(Location), Canvas) + DrawOffset;
                    Canvas->Canvas->DrawShadowedString(StringSizeX + TextPos.X, TextPos.Y, *FString::Printf(TEXT("%1.2f"), Location.Y), Font, CurrentData[i].Color);
                }
            }
            else
            {
                FVector2D Position0, Position1, Position2;

                // draw the top triangle of the quad
                Position0.X = Start.X;
                Position0.Y = (GraphMinMaxData.Min.Y * (GraphScreenSize.Max.Y - GraphScreenSize.Min.Y)) + GraphScreenSize.Min.Y;
                Position1 = End;
                Position2 = Start;
                DrawTriangle(Canvas, Position0, Position1, Position2, CurrentData[i].Color);


                // draw the second triangle of the quad
                Position0.X = Start.X;
                Position0.Y = (GraphMinMaxData.Min.Y * (GraphScreenSize.Max.Y - GraphScreenSize.Min.Y)) + GraphScreenSize.Min.Y;
                Position1.X = End.X;
                Position1.Y = (GraphMinMaxData.Min.Y * (GraphScreenSize.Max.Y - GraphScreenSize.Min.Y)) + GraphScreenSize.Min.Y;
                Position2 = End;

                DrawTriangle(Canvas, Position0, Position1, Position2, CurrentData[i].Color);
            }
        }
    }
}
void
CBShellEditor::HandleKeyPress
	(
	const int				key,
	const JXKeyModifiers&	modifiers
	)
{
	const JBoolean controlOn = modifiers.control();
	const JBoolean metaOn    = modifiers.meta();
	const JBoolean shiftOn   = modifiers.shift();
	if ((key == kJLeftArrow && metaOn && !controlOn && !shiftOn) ||
		(key == JXCtrl('A') && controlOn && !metaOn && !shiftOn))
		{
		const JIndex index            = GetInsertionIndex();
		const JRunArray<Font>& styles = GetStyles();
		if (index > 1 && styles.GetElement(index-1) == GetDefaultFont())
			{
			JIndex runIndex, firstIndexInRun;
			const JBoolean ok = styles.FindRun(index-1, &runIndex, &firstIndexInRun);
			SetCaretLocation(firstIndexInRun);
			return;
			}
		}

	if (key == kJReturnKey)
		{
		SetCurrentFont(itsInsertFont);
		}
	else
		{
		SetCurrentFont(GetDefaultFont());
		}

	JBoolean sentCmd = kJFalse;
	if (key == kJReturnKey && !modifiers.shift() && !HasSelection())
		{
		JIndex index;
		JBoolean ok = GetCaretLocation(&index);
		assert( ok );

		JString cmd;
		const JRunArray<Font>& styles = GetStyles();
		if (index > 1 && styles.GetElement(index-1) == GetDefaultFont())
			{
			JIndex runIndex, firstIndexInRun;
			ok = styles.FindRun(index-1, &runIndex, &firstIndexInRun);

			const JIndex endIndex = firstIndexInRun + styles.GetRunLength(runIndex);
			cmd = (GetText()).GetSubstring(firstIndexInRun, endIndex - 1);
			SetCaretLocation(endIndex);

			if (cmd.BeginsWith("man "))
				{
				cmd.ReplaceSubstring(1, 4, "jcc --man ");
				}
			else if (cmd.BeginsWith("apropos "))
				{
				cmd.ReplaceSubstring(1, 8, "jcc --apropos ");
				}
			else if (cmd.BeginsWith("vi "))
				{
				cmd.ReplaceSubstring(1, 3, "jcc ");
				}
			else if (cmd.BeginsWith("less ") || cmd.BeginsWith("more "))
				{
				cmd.ReplaceSubstring(1, 5, "jcc ");
				}
			else if (cmd == "more" || cmd == "less" || cmd == "vi")
				{
				cmd = "jcc";
				}
			}

		cmd += "\n";
		itsShellDoc->SendCommand(cmd);

		sentCmd = kJTrue;
		}

	CBTextEditor::HandleKeyPress(key, modifiers);

	if (sentCmd)
		{
		itsInsertIndex = GetInsertionIndex();
		}
}
Example #3
0
void UReporterGraph::DrawAxis(UCanvas* Canvas, FVector2D Start, FVector2D End, float NumNotches, bool bIsVerticalAxis)
{
    // Draw the axis line
    DrawLine(Canvas, Start, End, AxesColor);

    // Divide each axis up into the desired notches
    float NotchDelta = (Start - End).Size() / (float)NumNotches;
    FVector2D NotchDataDelta = (GraphMinMaxData.Max - GraphMinMaxData.Min) / NumNotches;
    FVector2D NotchLocation = Start;
    FVector2D NotchLength(0,0);

    FLinearColor NotchColor = AxesColor;

    // if we should just draw notches
    switch(AxisStyle)
    {
    case EGraphAxisStyle::Lines:
    {
        NumNotches = 1;
        FVector2D NotchDataDelta = (GraphMinMaxData.Max - GraphMinMaxData.Min) / NumNotches;
        NotchDelta = (Start - End).Size();
        if(bIsVerticalAxis)
        {
            NotchLength.X = -(End.Y - Start.Y) * 0.05f;
            NotchLocation.X += NotchLength.X * -0.5f;
        }
        else
        {
            NotchLength.Y = -(End.X - Start.X) * 0.05f;
            NotchLocation.Y += NotchLength.Y * -0.5f;
        }
    }
    break;

    case EGraphAxisStyle::Notches:
    {
        if(bIsVerticalAxis)
        {
            NotchLength.X = -(End.Y - Start.Y) * 0.05f;
            NotchLocation.X += NotchLength.X * -0.5f;
        }
        else
        {
            NotchLength.Y = -(End.X - Start.X) * 0.05f;
            NotchLocation.Y += NotchLength.Y * -0.5f;
        }
    }
    break;

    case EGraphAxisStyle::Grid:
    {
        NotchColor *= 0.125f;

        if(bIsVerticalAxis)
        {
            NotchLength.X = End.Y - Start.Y;
        }
        else
        {
            NotchLength.Y = End.X - Start.X;
        }
    }
    break;
    }

    UFont* Font = GetDefaultFont();
    const FVector2D Width = FVector2D((GraphScreenSize.Max.X - GraphScreenSize.Min.X), 0);
    const FVector2D Height = FVector2D(0, (GraphScreenSize.Max.Y - GraphScreenSize.Min.Y));

    for (int Index = 0; Index < NumNotches + 1; Index++)
    {
        FString NotchValue = FString::Printf(TEXT("%1.2f"), (bIsVerticalAxis ? GraphMinMaxData.Min.Y + (NotchDataDelta.Y * (Index /*+ 1*/)) : GraphMinMaxData.Min.X + (NotchDataDelta.X * (Index /*+ 1*/))));

        int32 StringSizeX, StringSizeY;
        StringSize(Font, StringSizeX, StringSizeY, *NotchValue );

        FVector2D ScreenPos = ToScreenSpace(NotchLocation, Canvas);

        if (bIsVerticalAxis)
        {
            Canvas->Canvas->DrawShadowedString(ScreenPos.X - StringSizeX - 4, ScreenPos.Y - StringSizeY * 0.5f, *NotchValue, Font, AxesColor);
            DrawLine(Canvas, NotchLocation, NotchLocation + Width, NotchColor);
        }
        else
        {
            Canvas->Canvas->DrawShadowedString( ScreenPos.X - StringSizeX * 0.5f, ScreenPos.Y + (AxisStyle == EGraphAxisStyle::Grid ? + 5 : -NotchLength.Y * Canvas->SizeY), *NotchValue , Font, AxesColor);
            DrawLine(Canvas, NotchLocation, NotchLocation + Height, NotchColor);
        }

        if(bIsVerticalAxis)
        {
            NotchLocation.Y += NotchDelta;
        }
        else
        {
            NotchLocation.X += NotchDelta;
        }
    }
}
Example #4
0
void AwtMenuItem::MeasureSelf(HDC hDC, MEASUREITEMSTRUCT& measureInfo)
{
    JNIEnv *env =(JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
    if (env->EnsureLocalCapacity(4) < 0) {
        return;
    }

    /* self is a sun.awt.windows.WMenuItemPeer */
    jobject self = GetPeer(env);

    /* font is a java.awt.Font */
    jobject font = GetFont(env);
    jstring text = GetJavaString(env);
    SIZE size = AwtFont::getMFStringSize(hDC, font, text);

    /* 4700350: If the font size is taller than the menubar, change to the
     * default font.  Otherwise, menu text is painted over the title bar and
     * client area.  -bchristi
     */
    if (IsTopMenu() && size.cy > ::GetSystemMetrics(SM_CYMENU)) {
        jobject defFont = GetDefaultFont(env);
        env->DeleteLocalRef(font);
        font = env->NewLocalRef(defFont);
        size = AwtFont::getMFStringSize(hDC, font, text);
    }

    jstring fontName =
        (jstring)JNU_CallMethodByName(env, 0,font, "getName",
                                      "()Ljava/lang/String;").l;
    /* fontMetrics is a Hsun_awt_windows_WFontMetrics */
    jobject fontMetrics =  GetFontMetrics(env, font);


//     int height = env->GetIntField(fontMetrics, AwtFont::heightID);
    int height = (jint)JNU_CallMethodByName(env, 0, fontMetrics, "getHeight",
                                            "()I").i;

    measureInfo.itemHeight = height;
    measureInfo.itemHeight += measureInfo.itemHeight/3;
    // 3 is a heuristic number
    measureInfo.itemWidth = size.cx;
    if (!IsTopMenu()) {
        int checkWidth = ::GetSystemMetrics(SM_CXMENUCHECK);
        // Workaround for CR#6401956
        if (IS_WINVISTA) {
            AdjustCheckWidth(checkWidth);
        }
        measureInfo.itemWidth += checkWidth;

        // Add in shortcut width, if one exists.
        jstring shortcutLabel =
            (jstring)env->GetObjectField(self, AwtMenuItem::shortcutLabelID);
        if (shortcutLabel != NULL) {
            size = AwtFont::getMFStringSize(hDC, font, shortcutLabel);
            measureInfo.itemWidth += size.cx + checkWidth;
            env->DeleteLocalRef(shortcutLabel);
        }
    }
    env->DeleteLocalRef(text);
    env->DeleteLocalRef(font);
    env->DeleteLocalRef(fontName);
    env->DeleteLocalRef(fontMetrics);
}
Example #5
0
PRInt32
nsULE::GetGlyphInfo(const PRUnichar      *aSrcBuf,
                    PRInt32              aSrcLen,
                    PangoliteGlyphString *aGlyphData,
                    const char           *aFontCharset)
{
  int                  ct=0, start=0, i, index, startgid, lastCluster=0;
  PRBool               sameCtlRun=PR_FALSE;
  PangoliteEngineShape *curShaper=NULL, *prevShaper=NULL;
  PangoliteMap         *pngMap=NULL;
  PangoliteAnalysis    pngAnalysis;
  guint                enginetypeId=0, rendertypeId=0;

  pngAnalysis.aDir = PANGO_DIRECTION_LTR;
 
  // Maybe find a better way to handle font encodings
  if (aFontCharset == NULL)
    pngAnalysis.fontCharset = strdup(GetDefaultFont(aSrcBuf[0]));
  else
    pngAnalysis.fontCharset = strdup(aFontCharset);

  enginetypeId = g_quark_from_static_string(PANGO_ENGINE_TYPE_SHAPE);
  rendertypeId = g_quark_from_static_string(PANGO_RENDER_TYPE_X);
  pngMap = pangolite_find_map("en_US", enginetypeId, rendertypeId);

  for (ct=0; ct < aSrcLen;) {
    start = ct;
    curShaper = (PangoliteEngineShape*)
      pangolite_map_get_engine(pngMap, (PRUint32)aSrcBuf[ct++]);
    sameCtlRun = (curShaper != NULL);
    prevShaper = curShaper;

    if (sameCtlRun) {
      while (sameCtlRun && ct < aSrcLen) {
        curShaper = (PangoliteEngineShape*)
          pangolite_map_get_engine(pngMap, (PRUint32)aSrcBuf[ct]);
        sameCtlRun = ((curShaper != NULL) && (curShaper == prevShaper));
        if (sameCtlRun)
          ct++;
      }
      startgid = aGlyphData->num_glyphs;
      pngAnalysis.shape_engine = curShaper;
      prevShaper->script_shape(pngAnalysis.fontCharset,
                               &aSrcBuf[start], (ct-start),
                               &pngAnalysis, aGlyphData);
      if (lastCluster > 0) {
         for (i=startgid; i < aGlyphData->num_glyphs; i++)
           aGlyphData->log_clusters[i] += lastCluster;
      }
    }
    else {
      while (!sameCtlRun && ct < aSrcLen) {
        curShaper = (PangoliteEngineShape*)
          pangolite_map_get_engine(pngMap, (PRUint32)aSrcBuf[ct]);
        sameCtlRun = (curShaper != NULL);
        if (!sameCtlRun)
          ct++;
      }
      index = aGlyphData->num_glyphs;
      for (i=0; i < (ct-start); i++) {
        pangolite_glyph_string_set_size(aGlyphData, index+1);
        aGlyphData->glyphs[index].glyph = aSrcBuf[start+i];
        aGlyphData->glyphs[index].is_cluster_start = (gint)1;
        aGlyphData->log_clusters[index] = i+lastCluster;
        index++;
      }
    }
    lastCluster = aGlyphData->log_clusters[aGlyphData->num_glyphs-1];
  }
  nsMemory::Free(pngAnalysis.fontCharset);
  return aGlyphData->num_glyphs;
}
Example #6
0
void AppLocal::DrawEyeViewsPostDistorted( Matrix4f const & centerViewMatrix, const int numPresents )
{
	const float TEXT_SCALE = 1.0f;

	// update vr lib systems after the app frame, but before rendering anything
	GetGuiSys().Frame( this, vrFrame, GetVRMenuMgr(), GetDefaultFont(), GetMenuFontSurface() );
	GetGazeCursor().Frame( this->lastViewMatrix, vrFrame.DeltaSeconds );

	if ( ShowFPS )
	{
		static double  LastFrameTime = TimeInSeconds();
		static double  AccumulatedFrameInterval = 0.0;
		static int   NumAccumulatedFrames = 0;
		static float LastFrameRate = 60.0f;

		double currentFrameTime = TimeInSeconds();
		double frameInterval = currentFrameTime - LastFrameTime;
		AccumulatedFrameInterval += frameInterval;
		NumAccumulatedFrames++;
		if ( NumAccumulatedFrames > FPS_NUM_FRAMES_TO_AVERAGE ) {
			double interval = ( AccumulatedFrameInterval / NumAccumulatedFrames );  // averaged
			AccumulatedFrameInterval = 0.0;
			NumAccumulatedFrames = 0;
			LastFrameRate = 1.0f / float( interval > 0.000001 ? interval : 0.00001 );
		}    
		fontParms_t fontParms;
		fontParms.CenterHoriz = true;
		fontParms.Billboard = true;
        fontParms.TrackRoll = true;
		const Vector3f viewPos( GetViewMatrixPosition( centerViewMatrix ) );
		const Vector3f viewFwd( GetViewMatrixForward( centerViewMatrix ) );
		const Vector3f textPos( viewPos + viewFwd * 1.5f );
		GetWorldFontSurface().DrawTextBillboarded3Df( GetDefaultFont(), 
                fontParms, textPos, TEXT_SCALE, Vector4f( 1.0f, 0.0f, 0.0f, 1.0f ), "%.1f fps", LastFrameRate );
		LastFrameTime = currentFrameTime;
	}

	if ( InfoTextEndFrame >= vrFrame.FrameNumber )
	{
		fontParms_t fontParms;
		fontParms.CenterHoriz = true;
		fontParms.Billboard = true;
        fontParms.TrackRoll = true;
		const Vector3f viewPos( GetViewMatrixPosition( centerViewMatrix ) );
		const Vector3f viewFwd( GetViewMatrixForward( centerViewMatrix ) );
		const Vector3f textPos( viewPos + viewFwd * 1.5f );
		GetWorldFontSurface().DrawTextBillboarded3Df( GetDefaultFont(), 
                fontParms, textPos, TEXT_SCALE, Vector4f( 1.0f, 1.0f, 1.0f, 1.0f ), InfoText.ToCStr() );
	}

	GetMenuFontSurface().Finish( centerViewMatrix );
	GetWorldFontSurface().Finish( centerViewMatrix );
	GetVRMenuMgr().Finish( centerViewMatrix );

	// Increase the fov by about 10 degrees if we are not holding 60 fps so
	// there is less black pull-in at the edges.
	//
	// Doing this dynamically based just on time causes visible flickering at the
	// periphery when the fov is increased, so only do it if minimumVsyncs is set.
	const float fovDegrees = hmdInfo.SuggestedEyeFov +
			( ( ( SwapParms.MinimumVsyncs > 1 ) || ovr_GetPowerLevelStateThrottled() ) ? 10.0f : 0.0f ) +
			( ( !showVignette ) ? 5.0f : 0.0f );

	// DisplayMonoMode uses a single eye rendering for speed improvement
	// and / or high refresh rate double-scan hardware modes.
	const int numEyes = renderMonoMode ? 1 : 2;

	// Flush out and report any errors
	GL_CheckErrors("FrameStart");

	if ( drawCalibrationLines && calibrationLinesDrawn )
	{
		// doing a time warp test, don't generate new images
		LOG( "drawCalibrationLines && calibrationLinesDrawn" );
	}
	else
	{
		// possibly change the buffer parameters
		EyeTargets->BeginFrame( vrParms );

		for (int eye = 0; eye < numEyes; eye++)
		{
			EyeTargets->BeginRenderingEye( eye );

			// Call back to the app for drawing.
			const Matrix4f mvp = appInterface->DrawEyeView( eye, fovDegrees );

			DrawActivity( mvp );

			DrawPassThroughCamera( fovDegrees, vrFrame.PoseState.Pose.Orientation );

			GetVRMenuMgr().RenderSubmitted( mvp.Transposed() );
			GetMenuFontSurface().Render3D( GetDefaultFont(), mvp.Transposed() );
			GetWorldFontSurface().Render3D( GetDefaultFont(), mvp.Transposed() );

			glDisable( GL_DEPTH_TEST );
			glDisable( GL_CULL_FACE );

			// Optionally draw thick calibration lines into the texture,
			// which will be overlayed by the thinner origin cross when
			// distorted to the window.
			if ( drawCalibrationLines )
			{
				EyeDecorations.DrawEyeCalibrationLines(fovDegrees, eye);
				calibrationLinesDrawn = true;
			}
			else
			{
				calibrationLinesDrawn = false;
			}

			DrawDialog( mvp );

			GetGazeCursor().Render( eye, mvp );

			GetDebugLines().Render( mvp.Transposed() );

			if ( showVignette )
			{
				// Draw a thin vignette at the edges of the view so clamping will give black
				// This will not be reflected correctly in overlay planes.
				// EyeDecorations.DrawEyeVignette();

				EyeDecorations.FillEdge( vrParms.resolution, vrParms.resolution );
			}

			EyeTargets->EndRenderingEye( eye );
		}
	}

	// This eye set is complete, use it now.
	if ( numPresents > 0 )
	{
		const CompletedEyes eyes = EyeTargets->GetCompletedEyes();

		for ( int eye = 0 ; eye < TimeWarpParms::MAX_WARP_EYES ; eye++ )
		{
			SwapParms.Images[eye][0].TexCoordsFromTanAngles = TanAngleMatrixFromFov( fovDegrees );
			SwapParms.Images[eye][0].TexId = eyes.Textures[renderMonoMode ? 0 : eye ];
			SwapParms.Images[eye][0].Pose = SensorForNextWarp.Predicted;
		}

		ovr_WarpSwap( OvrMobile, &SwapParms );
	}
}
Example #7
0
void
AwtMenuItem::DrawSelf(DRAWITEMSTRUCT& drawInfo)
{
    JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
    if (env->EnsureLocalCapacity(4) < 0) {
        return;
    }

    // self is sun.awt.windows.WMenuItemPeer
    jobject self = GetPeer(env);

    //  target is java.awt.MenuItem
    jobject target = env->GetObjectField(self, AwtObject::targetID);

    HDC hDC = drawInfo.hDC;
    RECT rect = drawInfo.rcItem;
    RECT textRect = rect;
    SIZE size;

    DWORD crBack,crText;
    HBRUSH hbrBack;

    jobject font = GetFont(env);
    jstring text = GetJavaString(env);
    size = AwtFont::getMFStringSize(hDC, font, text);

    /* 4700350: If the font size is taller than the menubar, change to the
     * default font.  Otherwise, menu text is painted over the title bar and
     * client area.  -bchristi
     */
    if (IsTopMenu() && size.cy > ::GetSystemMetrics(SM_CYMENU)) {
        env->DeleteLocalRef(font);
        font = env->NewLocalRef(GetDefaultFont(env));
        size = AwtFont::getMFStringSize(hDC, font, text);
    }

    /* Fix for bug 4257944 by [email protected]
    * check state of the parent
    */
    AwtMenu* menu = GetMenuContainer();
    DASSERT(menu != NULL && GetID() >= 0);

    //Check whether the MenuItem is disabled.
    BOOL bEnabled = (jboolean)env->GetBooleanField(target,
                                                   AwtMenuItem::enabledID);
    if (menu != NULL) {
        bEnabled = bEnabled && !menu->IsDisabledAndPopup();
    }

    if ((drawInfo.itemState) & (ODS_SELECTED)) {
        // Set background and text colors for selected item
        crBack = ::GetSysColor (COLOR_HIGHLIGHT);
        // Disabled text must be drawn in gray.
        crText = ::GetSysColor(bEnabled? COLOR_HIGHLIGHTTEXT : COLOR_GRAYTEXT);
    } else {
        // COLOR_MENUBAR is only defined on WindowsXP. Our binaries are
        // built on NT, hence the below ifdef.

#ifndef COLOR_MENUBAR
#define COLOR_MENUBAR 30
#endif
        // Set background and text colors for unselected item
        if (IS_WINXP && IsTopMenu() && AwtDesktopProperties::IsXPStyle()) {
            crBack = ::GetSysColor (COLOR_MENUBAR);
        } else {
            crBack = ::GetSysColor (COLOR_MENU);
        }
        // Disabled text must be drawn in gray.
        crText = ::GetSysColor (bEnabled ? COLOR_MENUTEXT : COLOR_GRAYTEXT);
    }

    // Fill item rectangle with background color
    hbrBack = ::CreateSolidBrush (crBack);
    DASSERT(hbrBack);
    VERIFY(::FillRect (hDC, &rect, hbrBack));
    VERIFY(::DeleteObject (hbrBack));

    // Set current background and text colors
    ::SetBkColor (hDC, crBack);
    ::SetTextColor (hDC, crText);

    int nOldBkMode = ::SetBkMode(hDC, OPAQUE);
    DASSERT(nOldBkMode != 0);

    //draw check mark
    int checkWidth = ::GetSystemMetrics(SM_CXMENUCHECK);
    // Workaround for CR#6401956
    if (IS_WINVISTA) {
        AdjustCheckWidth(checkWidth);
    }

    if (IsCheckbox()) {
        // means that target is a java.awt.CheckboxMenuItem
        jboolean state =
            (jboolean)env->GetBooleanField(target, AwtMenuItem::stateID);
        if (state) {
            DASSERT(drawInfo.itemState & ODS_CHECKED);
            RECT checkRect;
            ::CopyRect(&checkRect, &textRect);
            if (GetRTL())
                checkRect.left = checkRect.right - checkWidth;
            else
                checkRect.right = checkRect.left + checkWidth;

            DrawCheck(hDC, checkRect);
        }
    }

    ::SetBkMode(hDC, TRANSPARENT);
    int x = 0;
    //draw string
    if (!IsTopMenu()){
        textRect.left += checkWidth;
        x = (GetRTL()) ? textRect.right - checkWidth - size.cx : textRect.left;
    } else {
        x = textRect.left = (textRect.left + textRect.right - size.cx) / 2;
    }

    int y = (textRect.top+textRect.bottom-size.cy)/2;

    // Text must be drawn in emboss if the Menu is disabled and not selected.
    BOOL bEmboss = !bEnabled && !(drawInfo.itemState & ODS_SELECTED);
    if (bEmboss) {
        ::SetTextColor(hDC, GetSysColor(COLOR_BTNHILIGHT));
        AwtFont::drawMFString(hDC, font, text, x + 1, y + 1, GetCodePage());
        ::SetTextColor(hDC, GetSysColor(COLOR_BTNSHADOW));
    }
    AwtFont::drawMFString(hDC, font, text, x, y, GetCodePage());

    jstring shortcutLabel =
        (jstring)env->GetObjectField(self, AwtMenuItem::shortcutLabelID);
    if (!IsTopMenu() && shortcutLabel != NULL) {
        UINT oldAlign = 0;
        if (GetRTL()){
            oldAlign = ::SetTextAlign(hDC, TA_LEFT);
            AwtFont::drawMFString(hDC, font, shortcutLabel, textRect.left, y,
                                  GetCodePage());
        } else {
            oldAlign = ::SetTextAlign(hDC, TA_RIGHT);
            AwtFont::drawMFString(hDC, font, shortcutLabel,
                                  textRect.right - checkWidth, y,
                                  GetCodePage());
        }

        ::SetTextAlign(hDC, oldAlign);
    }

    VERIFY(::SetBkMode(hDC,nOldBkMode));

    env->DeleteLocalRef(target);
    env->DeleteLocalRef(text);
    env->DeleteLocalRef(font);
    env->DeleteLocalRef(shortcutLabel);
}
Example #8
0
void AppLocal::DrawEyeViewsPostDistorted( Matrix4f const & centerViewMatrix, const int numPresents )
{
	// update vr lib systems after the app frame, but before rendering anything
	GetGuiSys().Frame( this, vrFrame, GetVRMenuMgr(), GetDefaultFont(), GetMenuFontSurface(), centerViewMatrix );
	GetGazeCursor().Frame( centerViewMatrix, vrFrame.DeltaSeconds );

	GetMenuFontSurface().Finish( centerViewMatrix );
	GetWorldFontSurface().Finish( centerViewMatrix );
	GetVRMenuMgr().Finish( centerViewMatrix );

	// Increase the fov by about 10 degrees if we are not holding 60 fps so
	// there is less black pull-in at the edges.
	//
	// Doing this dynamically based just on time causes visible flickering at the
	// periphery when the fov is increased, so only do it if minimumVsyncs is set.
	const float fovDegrees = hmdInfo.SuggestedEyeFov[0] +
			( ( ( SwapParms.MinimumVsyncs > 1 ) || ovr_GetPowerLevelStateThrottled() ) ? 10.0f : 0.0f ) +
			( ( !showVignette ) ? 5.0f : 0.0f );

	// DisplayMonoMode uses a single eye rendering for speed improvement
	// and / or high refresh rate double-scan hardware modes.
	const int numEyes = renderMonoMode ? 1 : 2;

	// Flush out and report any errors
	GL_CheckErrors("FrameStart");

	if ( drawCalibrationLines && calibrationLinesDrawn )
	{
		// doing a time warp test, don't generate new images
		LOG( "drawCalibrationLines && calibrationLinesDrawn" );
	}
	else
	{
		// possibly change the buffer parameters
		EyeTargets->BeginFrame( vrParms );

		for ( int eye = 0; eye < numEyes; eye++ )
		{
			EyeTargets->BeginRenderingEye( eye );

			// Call back to the app for drawing.
			const Matrix4f mvp = appInterface->DrawEyeView( eye, fovDegrees );

			GetVRMenuMgr().RenderSubmitted( mvp.Transposed(), centerViewMatrix );
			GetMenuFontSurface().Render3D( GetDefaultFont(), mvp.Transposed() );
			GetWorldFontSurface().Render3D( GetDefaultFont(), mvp.Transposed() );

			glDisable( GL_DEPTH_TEST );
			glDisable( GL_CULL_FACE );

			// Optionally draw thick calibration lines into the texture,
			// which will be overlayed by the thinner origin cross when
			// distorted to the window.
			if ( drawCalibrationLines )
			{
				EyeDecorations.DrawEyeCalibrationLines( fovDegrees, eye );
				calibrationLinesDrawn = true;
			}
			else
			{
				calibrationLinesDrawn = false;
			}

			DrawDialog( mvp );

			GetGazeCursor().Render( eye, mvp );

			GetDebugLines().Render( mvp.Transposed() );

			if ( showVignette )
			{
				// Draw a thin vignette at the edges of the view so clamping will give black
				// This will not be reflected correctly in overlay planes.
				// EyeDecorations.DrawEyeVignette();

				EyeDecorations.FillEdge( vrParms.resolution, vrParms.resolution );
			}

			EyeTargets->EndRenderingEye( eye );
		}
	}

	// This eye set is complete, use it now.
	if ( numPresents > 0 )
	{
		const CompletedEyes eyes = EyeTargets->GetCompletedEyes();

		for ( int eye = 0; eye < MAX_WARP_EYES; eye++ )
		{
			SwapParms.Images[eye][0].TexCoordsFromTanAngles = TanAngleMatrixFromFov( fovDegrees );
			SwapParms.Images[eye][0].TexId = eyes.Textures[renderMonoMode ? 0 : eye ];
			SwapParms.Images[eye][0].Pose = SensorForNextWarp.Predicted;
		}

		ovr_WarpSwap( OvrMobile, &SwapParms );
	}
}
STDMETHODIMP
CDirect2DRM::CreateImageFromWrappedTextExt(
				BSTR bstrText,
				IFont *pFont,
				BOOL bShadowed,
				DWORD width, 
				DWORD height,
				DWORD nPoint,
				LPDIRECT2DRMIMAGE *ppImage)
{
	MMASSERT(ppImage);
	if (m_pImageCache == NULL)
		return E_NOTINITIALIZED;

	HRESULT hr;
	LPD2DRMIMAGEPRIVATE pImagePriv = NULL;
	CMFImage *pmfi = NULL;
	SIZE size = {width, height };
	CString strText(bstrText);
	IFont *pIFont = NULL;
	CY ptsize = {nPoint*10000, 0};

	HFONT hFont = NULL;
	if ( pFont != NULL )
	{
		hr = pFont->get_hFont( &hFont);
		if (FAILED(hr))
			goto e_CreateImageFromText;
	} else {
		pIFont = GetDefaultFont();
		hr = pIFont->put_Size(ptsize);
		hr = pIFont->get_hFont( &hFont);
		
		if (FAILED(hr))
			goto e_CreateImageFromText;
	}
	
		// get a reference to the MFImage from the image cache
	if (FAILED(hr = m_pImageCache->GetImageFromText(strText, hFont, 0x00FFFFFF, bShadowed, 0, &size, &pmfi)) ||
		// CoCreate the D2DRMImage object
		FAILED(hr = CoCreateInstance(
						CLSID_CDirect2DRMImage,
						NULL,
						CLSCTX_INPROC_SERVER,
						IID_ID2DRMImagePrivate,
						(LPVOID *) &pImagePriv)) ||
		// initialize the D2DRMImage with the MFImage
		FAILED(hr = pImagePriv->InitFromMFImage(this, pmfi, 0)))
		goto e_CreateImageFromText;

	*ppImage = (LPDIRECT2DRMIMAGE) pImagePriv;

	// release the extra reference we had from the CreateImageFromText
	pmfi->Release();
	MMRELEASE(pIFont);
	return S_OK;

e_CreateImageFromText:
	MMRELEASE(pImagePriv);
	MMRELEASE(pmfi);
	MMRELEASE(pIFont);
	return hr;
}
Example #10
0
 Label::Label()
 {
     Init(std::wstring(), GetDefaultFont());
 }
Example #11
0
 Label::Label(const std::wstring& text)
 {
     Init(text, GetDefaultFont());
 }
void
CBTCLStyler::Scan
	(
	std::istream&			input,
	const TokenExtra&	initData
	)
{
	BeginScan(input);

	const JString& text = GetText();

	JBoolean keepGoing;
	Token token;
	JFontStyle style;
	do
		{
		token = NextToken();
		if (token.type == kEOF)
			{
			break;
			}

		// save token starts

		if (token.type == kPredefinedWord ||
			token.type == kOtherWord ||
			token.type == kVariable ||
			token.type == kString ||
			token.type == kComment)
			{
			SaveTokenStart(TokenExtra());
			}

		// handle special cases

		if (token.type == kString ||
			token.type == kUnterminatedString)
			{
			ExtendCheckRangeForString(token.range);
			}

		// set the style

		const JIndex typeIndex = token.type - kWhitespace;
		if (token.type == kWhitespace)
			{
			style = GetDefaultFont().GetStyle();
			}
		else if (token.type == kComment       ||
				 token.type == kString        ||
				 token.type == kBrace         ||
				 token.type == kSquareBracket ||
				 token.type == kParenthesis)
			{
			style = GetTypeStyle(typeIndex);
			}
		else if (token.type < kWhitespace)
			{
			style = GetTypeStyle(kError - kWhitespace);
			}
		else
			{
			style = GetStyle(typeIndex, text.GetSubstring(token.range));
			}

		keepGoing = SetStyle(token.range, style);

		if (token.type == kString)
			{
			StyleEmbeddedVariables(token);
			}
		}
		while (keepGoing);
}
Example #13
0
static int FrameModulesLoaded(WPARAM, LPARAM)
{
	if (ServiceExists(MS_CLIST_FRAMES_ADDFRAME)) {
		LOGFONT lf;
		/* built-in font module is not available before this hook */
		COLORREF clr = GetDefaultColor(FRAMEELEMENT_TEXT);
		FontService_RegisterFont("AutoShutdown", "CountdownFont", LPGENT("Automatic Shutdown"), LPGENT("Countdown on Frame"), LPGENT("Automatic Shutdown"), LPGENT("Background"), 0, FALSE, GetDefaultFont(&lf), clr);
		clr = GetDefaultColor(FRAMEELEMENT_BKGRND);
		FontService_RegisterColor("AutoShutdown", "BkgColor", LPGENT("Automatic Shutdown"), LPGENT("Background"), clr);
		if (!IsThemeActive()) {
			/* progressbar color can only be changed with classic theme */
			clr = GetDefaultColor(FRAMEELEMENT_BAR);
			FontService_RegisterColor("AutoShutdown", "ProgressColor", TranslateT("Automatic Shutdown"), TranslateT("Progress Bar"), clr);
		}
	}
	return 0;
}
Example #14
0
static LRESULT CALLBACK FrameWndProc(HWND hwndFrame, UINT msg, WPARAM wParam, LPARAM lParam)
{
	CountdownFrameWndData *dat = (CountdownFrameWndData*)GetWindowLongPtr(hwndFrame, GWLP_USERDATA);

	switch (msg) {
	case WM_NCCREATE:  /* init window data */
		dat = (struct CountdownFrameWndData*)mir_calloc(sizeof(*dat));
		SetWindowLongPtr(hwndFrame, GWLP_USERDATA, (LONG_PTR)dat);
		if (dat == NULL) return FALSE; /* creation failed */
		dat->fTimeFlags = *(WORD*)((CREATESTRUCT*)lParam)->lpCreateParams;
		dat->flags = FWPDF_COUNTDOWNINVALID;
		break;

	case WM_CREATE:  /*  create childs */
		{
			CREATESTRUCT *params = (CREATESTRUCT*)lParam;
			dat->hwndIcon = CreateWindowEx(WS_EX_NOPARENTNOTIFY, _T("Static"), NULL, WS_CHILD | WS_VISIBLE | SS_ICON | SS_CENTERIMAGE | SS_NOTIFY,
				3, 0, GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), hwndFrame, NULL, params->hInstance, NULL);
			dat->hwndProgress = CreateWindowEx(WS_EX_NOPARENTNOTIFY, PROGRESS_CLASS, (dat->fTimeFlags&SDWTF_ST_TIME) ? TranslateT("Shutdown at:") : TranslateT("Time left:"),
				WS_CHILD | WS_VISIBLE | PBS_SMOOTH, GetSystemMetrics(SM_CXICON) + 5, 5, 90, (GetSystemMetrics(SM_CXICON) / 2) - 5, hwndFrame, NULL, params->hInstance, NULL);
			if (dat->hwndProgress == NULL) return -1; /* creation failed, calls WM_DESTROY */
			SendMessage(dat->hwndProgress, PBM_SETSTEP, 1, 0);
			mir_subclassWindow(dat->hwndProgress, ProgressBarSubclassProc);
			dat->hwndDesc = CreateWindowEx(WS_EX_NOPARENTNOTIFY, _T("Static"), (dat->fTimeFlags&SDWTF_ST_TIME) ? TranslateT("Shutdown at:") : TranslateT("Time left:"),
				WS_CHILD | WS_VISIBLE | SS_LEFTNOWORDWRAP | SS_NOTIFY, GetSystemMetrics(SM_CXICON) + 5, (GetSystemMetrics(SM_CXICON) / 2), 75,
				(GetSystemMetrics(SM_CXICON) / 2), hwndFrame, NULL, params->hInstance, NULL);
			dat->hwndTime = CreateWindowEx(WS_EX_NOPARENTNOTIFY, _T("Static"), NULL, WS_CHILD | WS_VISIBLE | SS_RIGHT | SS_NOTIFY | SS_ENDELLIPSIS,
				(GetSystemMetrics(SM_CXICON) + 80), (GetSystemMetrics(SM_CXICON) / 2), 35, (GetSystemMetrics(SM_CXICON) / 2), hwndFrame, NULL, params->hInstance, NULL);
			if (dat->hwndTime == NULL)
				return -1; /* creation failed, calls WM_DESTROY */

			// create tooltips
			TTTOOLINFO ti;
			dat->hwndToolTip = CreateWindowEx(WS_EX_TOPMOST, TOOLTIPS_CLASS, NULL, WS_POPUP | TTS_ALWAYSTIP | TTS_NOPREFIX,
				CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hwndFrame, NULL, params->hInstance, NULL);
			if (dat->hwndToolTip != NULL) {
				SetWindowPos(dat->hwndToolTip, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
				memset(&ti, 0, sizeof(ti));
				ti.cbSize = sizeof(ti);
				ti.hwnd = hwndFrame;
				ti.uFlags = TTF_IDISHWND | TTF_SUBCLASS | TTF_TRANSPARENT;
				ti.lpszText = LPSTR_TEXTCALLBACK; /* commctl 4.70+ */
				ti.uId = (UINT_PTR)dat->hwndTime; /* in-place tooltip */
				SendMessage(dat->hwndToolTip, TTM_ADDTOOL, 0, (LPARAM)&ti);
				ti.uFlags &= ~TTF_TRANSPARENT;
				ti.uId = (UINT_PTR)dat->hwndProgress;
				SendMessage(dat->hwndToolTip, TTM_ADDTOOL, 0, (LPARAM)&ti);
				if (dat->hwndDesc != NULL) {
					ti.uId = (UINT_PTR)dat->hwndDesc;
					SendMessage(dat->hwndToolTip, TTM_ADDTOOL, 0, (LPARAM)&ti);
				}
				if (dat->hwndIcon != NULL) {
					ti.uId = (UINT_PTR)dat->hwndIcon;
					SendMessage(dat->hwndToolTip, TTM_ADDTOOL, 0, (LPARAM)&ti);
				}
			}
			/* init layout */
			dat->hHookColorsChanged = HookEventMessage(ME_COLOUR_RELOAD, hwndFrame, M_REFRESH_COLORS);
			dat->hHookFontsChanged = HookEventMessage(ME_FONT_RELOAD, hwndFrame, M_REFRESH_FONTS);
			dat->hHookIconsChanged = HookEventMessage(ME_SKIN2_ICONSCHANGED, hwndFrame, M_REFRESH_ICONS);
			SendMessage(hwndFrame, M_REFRESH_COLORS, 0, 0);
			SendMessage(hwndFrame, M_REFRESH_FONTS, 0, 0);
			SendMessage(hwndFrame, M_REFRESH_ICONS, 0, 0);
			SendMessage(hwndFrame, M_SET_COUNTDOWN, 0, 0);
			SendMessage(hwndFrame, M_UPDATE_COUNTDOWN, 0, 0);
			if (!SetTimer(hwndFrame, 1, 1000, NULL))
				return -1; /* creation failed, calls WM_DESTROY */
		}
		return 0;

	case WM_DESTROY:
		if (dat == NULL) return 0;

		UnhookEvent(dat->hHookColorsChanged);
		UnhookEvent(dat->hHookFontsChanged);
		UnhookEvent(dat->hHookIconsChanged);
		/* other childs are destroyed automatically */
		if (dat->hwndToolTip != NULL)
			DestroyWindow(dat->hwndToolTip);
		break;

	case WM_NCDESTROY:
		if (dat == NULL) return 0;
		if (dat->hFont != NULL) DeleteObject(dat->hFont);
		if (dat->hbrBackground != NULL) DeleteObject(dat->hbrBackground);
		mir_free(dat);
		SetWindowLongPtr(hwndFrame, GWLP_USERDATA, 0);
		break;

	case WM_SIZE:
		{
			RECT rc;
			UINT defflg = SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_NOACTIVATE;
			SetRect(&rc, 0, 0, LOWORD(lParam), HIWORD(lParam)); /* width,height */
			/* workaround: reduce flickering of frame in clist */
			InvalidateRect(hwndFrame, &rc, FALSE);
			HDWP hdwp = BeginDeferWindowPos(3);
			/* progress */
			LONG width = rc.right - GetSystemMetrics(SM_CXICON) - 10;
			LONG height = rc.bottom - (GetSystemMetrics(SM_CYICON) / 2) - 5;
			if (NULL != dat->hwndProgress) /* Wine fix. */
				hdwp = DeferWindowPos(hdwp, dat->hwndProgress, NULL, 0, 0, width, height, SWP_NOMOVE | defflg);
			/* desc */
			if (dat->hwndDesc != NULL) /* Wine fix. */
				hdwp = DeferWindowPos(hdwp, dat->hwndDesc, NULL, GetSystemMetrics(SM_CXICON) + 5, 5 + height, 0, 0, SWP_NOSIZE | defflg);
			/* time */
			if (NULL != dat->hwndTime) /* Wine fix. */
				hdwp = DeferWindowPos(hdwp, dat->hwndTime, NULL, GetSystemMetrics(SM_CXICON) + 85, 5 + height, width - 80, (GetSystemMetrics(SM_CXICON) / 2), defflg);
			EndDeferWindowPos(hdwp);
		}
		PostMessage(hwndFrame, M_CHECK_CLIPPED, 0, 0);
		return 0;

	case M_REFRESH_COLORS:
		COLORREF clrBar;
		if (FontService_GetColor(_T("Automatic Shutdown"), _T("Progress Bar"), &clrBar))
			clrBar = GetDefaultColor(FRAMEELEMENT_BAR);
		if (FontService_GetColor(_T("Automatic Shutdown"), _T("Background"), &dat->clrBackground))
			dat->clrBackground = GetDefaultColor(FRAMEELEMENT_BKGRND);
		if (dat->hbrBackground != NULL) DeleteObject(dat->hbrBackground);
		dat->hbrBackground = CreateSolidBrush(dat->clrBackground);
		SendMessage(dat->hwndProgress, PBM_SETBARCOLOR, 0, (LPARAM)clrBar);
		SendMessage(dat->hwndProgress, PBM_SETBKCOLOR, 0, (LPARAM)dat->clrBackground);
		InvalidateRect(hwndFrame, NULL, TRUE);
		return 0;

	case M_REFRESH_ICONS:
		return 0;

	case M_REFRESH_FONTS:
		{
			LOGFONT lf;
			if (!FontService_GetFont(_T("Automatic Shutdown"), _T("Countdown on Frame"), &dat->clrText, &lf)) {
				if (dat->hFont != NULL) DeleteObject(dat->hFont);
				dat->hFont = CreateFontIndirect(&lf);
			}
			else {
				dat->clrText = GetDefaultColor(FRAMEELEMENT_TEXT);
				if (GetDefaultFont(&lf) != NULL) {
					if (dat->hFont != NULL) DeleteObject(dat->hFont);
					dat->hFont = CreateFontIndirect(&lf);
				}
			}
		}
		if (dat->hwndDesc != NULL)
			SendMessage(dat->hwndDesc, WM_SETFONT, (WPARAM)dat->hFont, FALSE);
		SendMessage(dat->hwndTime, WM_SETFONT, (WPARAM)dat->hFont, FALSE);
		InvalidateRect(hwndFrame, NULL, FALSE);
		return 0;

	case WM_SYSCOLORCHANGE:
		SendMessage(hwndFrame, M_REFRESH_COLORS, 0, 0);
		break;

	case WM_SETTINGCHANGE: /* colors depend on windows settings */
		SendMessage(hwndFrame, M_REFRESH_COLORS, 0, 0);
		SendMessage(hwndFrame, M_REFRESH_FONTS, 0, 0);
		SendMessage(hwndFrame, M_UPDATE_COUNTDOWN, 0, 0);
		RedrawWindow(hwndFrame, NULL, NULL, RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_ERASE);
		break;

	case WM_TIMECHANGE: /* windows system clock changed */
		SendMessage(hwndFrame, M_SET_COUNTDOWN, 0, 0);
		PostMessage(hwndFrame, M_UPDATE_COUNTDOWN, 0, 0);
		break;

	case WM_CTLCOLORDLG:
	case WM_CTLCOLORSTATIC:
		SetTextColor((HDC)wParam, dat->clrText);
		SetBkColor((HDC)wParam, dat->clrBackground);
		return (INT_PTR)dat->hbrBackground;

	case WM_ERASEBKGND:
		{
			RECT rc;
			if (dat->hbrBackground != NULL && GetClientRect(hwndFrame, &rc)) {
				FillRect((HDC)wParam, &rc, dat->hbrBackground);
				return TRUE;
			}
			return FALSE;
		}
	case M_SET_COUNTDOWN:
		if (dat->fTimeFlags&SDWTF_ST_TIME) {
			dat->settingLastTime = (time_t)db_get_dw(NULL, "AutoShutdown", "TimeStamp", SETTING_TIMESTAMP_DEFAULT);
			dat->countdown = time(NULL);
			if (dat->settingLastTime > dat->countdown) dat->countdown = dat->settingLastTime - dat->countdown;
			else dat->countdown = 0;
		}
		else if (dat->flags&FWPDF_COUNTDOWNINVALID) {
			dat->countdown = (time_t)db_get_dw(NULL, "AutoShutdown", "Countdown", SETTING_COUNTDOWN_DEFAULT);
			dat->countdown *= (time_t)db_get_dw(NULL, "AutoShutdown", "CountdownUnit", SETTING_COUNTDOWNUNIT_DEFAULT);
		}
		dat->flags &= ~FWPDF_COUNTDOWNINVALID;
		/* commctl 4.70+, Win95: 1-100 will work fine (wrap around) */
		SendMessage(dat->hwndProgress, PBM_SETRANGE32, 0, (LPARAM)dat->countdown);
		return 0;
	case WM_TIMER:
		if (dat == NULL) return 0;
		if (dat->countdown != 0 && !(dat->flags&FWPDF_COUNTDOWNINVALID) && !(dat->flags&FWPDF_PAUSED)) {
			dat->countdown--;
			PostMessage(dat->hwndProgress, PBM_STEPIT, 0, 0);
		}
		if (IsWindowVisible(hwndFrame)) PostMessage(hwndFrame, M_UPDATE_COUNTDOWN, 0, 0);
		if (dat->countdown == 0) {
			SendMessage(hwndFrame, M_CLOSE_COUNTDOWN, 0, 0);
			ServiceShutdown(0, TRUE);
			ServiceStopWatcher(0, 0);
		}
		return 0;
	case WM_SHOWWINDOW:
		/* the text is kept unchanged while hidden */
		if ((BOOL)wParam) SendMessage(hwndFrame, M_UPDATE_COUNTDOWN, 0, 0);
		break;
	case M_UPDATE_COUNTDOWN:
		if (dat->flags&FWPDF_PAUSED && !(dat->flags&FWPDF_PAUSEDSHOWN)) {
			SetWindowText(dat->hwndTime, TranslateT("Paused"));
			dat->flags |= FWPDF_PAUSEDSHOWN;
		}
		else {
			TCHAR szOutput[256];
			if (dat->fTimeFlags&SDWTF_ST_TIME)
				GetFormatedDateTime(szOutput, _countof(szOutput), dat->settingLastTime, TRUE);
			else GetFormatedCountdown(szOutput, _countof(szOutput), dat->countdown);
			SetWindowText(dat->hwndTime, szOutput);
			PostMessage(hwndFrame, M_CHECK_CLIPPED, 0, 0);
			/* update tooltip text (if shown) */
			if (dat->hwndToolTip != NULL && !(dat->flags&FWPDF_PAUSED)) {
				TTTOOLINFO ti;
				ti.cbSize = sizeof(ti);
				if (SendMessage(dat->hwndToolTip, TTM_GETCURRENTTOOL, 0, (LPARAM)&ti) && (HWND)ti.uId != dat->hwndIcon)
					SendMessage(dat->hwndToolTip, TTM_UPDATE, 0, 0);
			}
			else dat->flags &= ~FWPDF_PAUSEDSHOWN;
		}
		return 0;
	case M_CLOSE_COUNTDOWN:
		KillTimer(hwndFrame, 1);
		dat->countdown = 0;
		dat->flags &= ~FWPDF_PAUSED;
		SendMessage(hwndFrame, M_UPDATE_COUNTDOWN, 0, 0);
		dat->flags |= FWPDF_COUNTDOWNINVALID;
		/* step up to upper range */
		SendMessage(dat->hwndProgress, PBM_SETPOS, SendMessage(dat->hwndProgress, PBM_GETRANGE, FALSE, 0), 0);
		SetWindowLongPtr(dat->hwndProgress, GWL_STYLE, GetWindowLongPtr(dat->hwndProgress, GWL_STYLE) | PBM_SETMARQUEE);
		SendMessage(dat->hwndProgress, PBM_SETMARQUEE, TRUE, 10); /* marquee for rest of time */
		return 0;
	case M_PAUSE_COUNTDOWN:
		if (dat->flags&FWPDF_PAUSED) {
			/* unpause */
			dat->flags &= ~(FWPDF_PAUSED | FWPDF_PAUSEDSHOWN);
			SendMessage(hwndFrame, M_SET_COUNTDOWN, 0, 0);
			SendMessage(dat->hwndProgress, PBM_SETSTATE, PBST_NORMAL, 0); /* WinVista+ */
		}
		else {
			/* pause */
			dat->flags |= FWPDF_PAUSED;
			SendMessage(dat->hwndProgress, PBM_SETSTATE, PBST_PAUSED, 0); /* WinVista+ */
		}
		SendMessage(hwndFrame, M_UPDATE_COUNTDOWN, 0, 0);
		return 0;
	case WM_CONTEXTMENU:
		{
			if (dat->flags & FWPDF_COUNTDOWNINVALID)
				return 0;

			POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
			if (pt.x == -1 && pt.y == -1) { /* invoked by keyboard */
				RECT rc;
				/* position in middle above rect */
				if (!GetWindowRect(hwndFrame, &rc)) return 0;
				pt.x = rc.left + ((int)(rc.right - rc.left) / 2);
				pt.y = rc.top + ((int)(rc.bottom - rc.top) / 2);
			}
			HMENU hContextMenu = CreatePopupMenu();
			if (hContextMenu != NULL) {
				AppendMenu(hContextMenu, MF_STRING, MENUITEM_PAUSECOUNTDOWN, (dat->flags&FWPDF_PAUSED) ? TranslateT("&Unpause Countdown") : TranslateT("&Pause Countdown"));
				SetMenuDefaultItem(hContextMenu, MENUITEM_PAUSECOUNTDOWN, FALSE);
				AppendMenu(hContextMenu, MF_STRING, MENUITEM_STOPCOUNTDOWN, TranslateT("&Cancel Countdown"));
				TrackPopupMenuEx(hContextMenu, TPM_LEFTALIGN | TPM_TOPALIGN | TPM_HORPOSANIMATION | TPM_VERPOSANIMATION | TPM_RIGHTBUTTON, pt.x, pt.y, hwndFrame, NULL);
				DestroyMenu(hContextMenu);
			}
		}
		return 0;
	case WM_LBUTTONDBLCLK:
		if (!(dat->flags&FWPDF_COUNTDOWNINVALID))
			SendMessage(hwndFrame, M_PAUSE_COUNTDOWN, 0, 0);
		return 0;
	case WM_COMMAND:
		switch (LOWORD(wParam)) {
		case MENUITEM_STOPCOUNTDOWN:
			/* close only countdown window when other watcher types running */
			if (dat->fTimeFlags&~(SDWTF_SPECIFICTIME | SDWTF_ST_MASK))
				CloseCountdownFrame(); /* something else is running */
			else ServiceStopWatcher(0, 0); /* calls CloseCountdownFrame() */
			return 0;
		case MENUITEM_PAUSECOUNTDOWN:
			SendMessage(hwndFrame, M_PAUSE_COUNTDOWN, 0, 0);
			return 0;
		}
		break;
	case M_CHECK_CLIPPED: /* for in-place tooltip on dat->hwndTime */
		{
			RECT rc;
			HDC hdc;
			SIZE size;
			HFONT hFontPrev = NULL;
			TCHAR szOutput[256];
			dat->flags &= ~FWPDF_TIMEISCLIPPED;
			if (GetWindowText(dat->hwndTime, szOutput, _countof(szOutput)))
				if (GetClientRect(dat->hwndTime, &rc)) {
					hdc = GetDC(dat->hwndTime);
					if (hdc != NULL) {
						if (dat->hFont != NULL)
							hFontPrev = (HFONT)SelectObject(hdc, dat->hFont);
						if (GetTextExtentPoint32(hdc, szOutput, (int)mir_tstrlen(szOutput), &size))
							if (size.cx >= (rc.right - rc.left))
								dat->flags &= FWPDF_TIMEISCLIPPED;
						if (dat->hFont != NULL)
							SelectObject(hdc, hFontPrev);
						ReleaseDC(dat->hwndTime, hdc);
					}
				}
			return 0;
		}
	case WM_NOTIFY:
		if (((NMHDR*)lParam)->hwndFrom == dat->hwndToolTip)
			switch (((NMHDR*)lParam)->code) {
			case TTN_SHOW: /* 'in-place' tooltip on dat->hwndTime */
				if (dat->flags&FWPDF_TIMEISCLIPPED && (HWND)wParam == dat->hwndTime) {
					RECT rc;
					if (GetWindowRect(dat->hwndTime, &rc)) {
						SetWindowLongPtr(dat->hwndToolTip, GWL_STYLE, GetWindowLongPtr(dat->hwndToolTip, GWL_STYLE) | TTS_NOANIMATE);
						SetWindowLongPtr(dat->hwndToolTip, GWL_EXSTYLE, GetWindowLongPtr(dat->hwndToolTip, GWL_EXSTYLE) | WS_EX_TRANSPARENT);
						SendMessage(dat->hwndToolTip, TTM_ADJUSTRECT, TRUE, (LPARAM)&rc);
						SetWindowPos(dat->hwndToolTip, NULL, rc.left, rc.top, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
						return TRUE; /* self-defined position */
					}
				}
				SetWindowLongPtr(dat->hwndToolTip, GWL_STYLE, GetWindowLongPtr(dat->hwndToolTip, GWL_STYLE) & (~TTS_NOANIMATE));
				SetWindowLongPtr(dat->hwndToolTip, GWL_EXSTYLE, GetWindowLongPtr(dat->hwndToolTip, GWL_EXSTYLE) & (~WS_EX_TRANSPARENT));
				return 0;
			case TTN_POP:
				/* workaround #5: frame does not get redrawn after
				 * in-place tooltip	hidden on dat->hwndTime */
				RedrawWindow(hwndCountdownFrame, NULL, NULL, RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_ERASE);
				return 0;
			case TTN_NEEDTEXT:
				{
					NMTTDISPINFO *ttdi = (NMTTDISPINFO*)lParam;
					if (dat->flags&FWPDF_TIMEISCLIPPED && (HWND)wParam == dat->hwndTime) {
						if (GetWindowText(dat->hwndTime, ttdi->szText, _countof(ttdi->szText)))
							ttdi->lpszText = ttdi->szText;
					}
					else if ((HWND)wParam == dat->hwndIcon)
						ttdi->lpszText = TranslateT("Automatic Shutdown");
					else {
						TCHAR szTime[_countof(ttdi->szText)];
						if (dat->fTimeFlags&SDWTF_ST_TIME)
							GetFormatedDateTime(szTime, _countof(szTime), dat->settingLastTime, FALSE);
						else GetFormatedCountdown(szTime, _countof(szTime), dat->countdown);
						mir_sntprintf(ttdi->szText, _T("%s %s"), (dat->fTimeFlags&SDWTF_ST_TIME) ? TranslateT("Shutdown at:") : TranslateT("Time left:"), szTime);
						ttdi->lpszText = ttdi->szText;
					}
					return 0;
				}
			}
		break;
	}
	return DefWindowProc(hwndFrame, msg, wParam, lParam);
}
Example #15
0
// Load a BMFont file (AngelCode font file)
static SpriteFont LoadBMFont(const char *fileName)
{
    #define MAX_BUFFER_SIZE     256

    SpriteFont font = { 0 };
    font.texture.id = 0;

    char buffer[MAX_BUFFER_SIZE];
    char *searchPoint = NULL;

    int fontSize = 0;
    int texWidth, texHeight;
    char texFileName[128];
    int numChars = 0;

    int base;   // Useless data

    FILE *fntFile;

    fntFile = fopen(fileName, "rt");

    if (fntFile == NULL)
    {
        TraceLog(WARNING, "[%s] FNT file could not be opened", fileName);
        return font;
    }

    // NOTE: We skip first line, it contains no useful information
    fgets(buffer, MAX_BUFFER_SIZE, fntFile);
    //searchPoint = strstr(buffer, "size");
    //sscanf(searchPoint, "size=%i", &fontSize);

    fgets(buffer, MAX_BUFFER_SIZE, fntFile);
    searchPoint = strstr(buffer, "lineHeight");
    sscanf(searchPoint, "lineHeight=%i base=%i scaleW=%i scaleH=%i", &fontSize, &base, &texWidth, &texHeight);

    TraceLog(DEBUG, "[%s] Font size: %i", fileName, fontSize);
    TraceLog(DEBUG, "[%s] Font texture scale: %ix%i", fileName, texWidth, texHeight);

    fgets(buffer, MAX_BUFFER_SIZE, fntFile);
    searchPoint = strstr(buffer, "file");
    sscanf(searchPoint, "file=\"%128[^\"]\"", texFileName);

    TraceLog(DEBUG, "[%s] Font texture filename: %s", fileName, texFileName);

    fgets(buffer, MAX_BUFFER_SIZE, fntFile);
    searchPoint = strstr(buffer, "count");
    sscanf(searchPoint, "count=%i", &numChars);

    TraceLog(DEBUG, "[%s] Font num chars: %i", fileName, numChars);

    // Compose correct path using route of .fnt file (fileName) and texFileName
    char *texPath = NULL;
    char *lastSlash = NULL;

    lastSlash = strrchr(fileName, '/');

    // NOTE: We need some extra space to avoid memory corruption on next allocations!
    texPath = malloc(strlen(fileName) - strlen(lastSlash) + strlen(texFileName) + 4);

    // NOTE: strcat() and strncat() required a '\0' terminated string to work!
    *texPath = '\0';
    strncat(texPath, fileName, strlen(fileName) - strlen(lastSlash) + 1);
    strncat(texPath, texFileName, strlen(texFileName));

    TraceLog(DEBUG, "[%s] Font texture loading path: %s", fileName, texPath);
    
    Image imFont = LoadImage(texPath);
    
    if (imFont.format == UNCOMPRESSED_GRAYSCALE) 
    {
        Image imCopy = ImageCopy(imFont);
        
        for (int i = 0; i < imCopy.width*imCopy.height; i++) ((unsigned char *)imCopy.data)[i] = 0xff;  // WHITE pixel

        ImageAlphaMask(&imCopy, imFont);
        font.texture = LoadTextureFromImage(imCopy);
        UnloadImage(imCopy);
    }
    else font.texture = LoadTextureFromImage(imFont);
    
    font.size = fontSize;
    font.numChars = numChars;
    font.charValues = (int *)malloc(numChars*sizeof(int));
    font.charRecs = (Rectangle *)malloc(numChars*sizeof(Rectangle));
    font.charOffsets = (Vector2 *)malloc(numChars*sizeof(Vector2));
    font.charAdvanceX = (int *)malloc(numChars*sizeof(int));

    UnloadImage(imFont);
    
    free(texPath);

    int charId, charX, charY, charWidth, charHeight, charOffsetX, charOffsetY, charAdvanceX;

    for (int i = 0; i < numChars; i++)
    {
        fgets(buffer, MAX_BUFFER_SIZE, fntFile);
        sscanf(buffer, "char id=%i x=%i y=%i width=%i height=%i xoffset=%i yoffset=%i xadvance=%i",
                       &charId, &charX, &charY, &charWidth, &charHeight, &charOffsetX, &charOffsetY, &charAdvanceX);

        // Save data properly in sprite font
        font.charValues[i] = charId;
        font.charRecs[i] = (Rectangle){ charX, charY, charWidth, charHeight };
        font.charOffsets[i] = (Vector2){ (float)charOffsetX, (float)charOffsetY };
        font.charAdvanceX[i] = charAdvanceX;
    }

    fclose(fntFile);

    if (font.texture.id == 0)
    {
        UnloadSpriteFont(font);
        font = GetDefaultFont();
    }
    else TraceLog(INFO, "[%s] SpriteFont loaded successfully", fileName);

    return font;
}
Example #16
0
// Load a rBMF font file (raylib BitMap Font)
static SpriteFont LoadRBMF(const char *fileName)
{
    // rBMF Info Header (16 bytes)
    typedef struct {
        char id[4];             // rBMF file identifier
        char version;           // rBMF file version
                                //      4 MSB --> main version
                                //      4 LSB --> subversion
        char firstChar;         // First character in the font
                                // NOTE: Depending on charDataType, it could be useless
        short imgWidth;         // Image width - always POT (power-of-two)
        short imgHeight;        // Image height - always POT (power-of-two)
        short numChars;         // Number of characters contained
        short charHeight;       // Characters height - the same for all characters
        char compType;          // Compression type:
                                //      4 MSB --> image data compression
                                //      4 LSB --> chars data compression
        char charsDataType;     // Char data type provided
    } rbmfInfoHeader;

    SpriteFont spriteFont = { 0 };

    rbmfInfoHeader rbmfHeader;
    unsigned int *rbmfFileData = NULL;
    unsigned char *rbmfCharWidthData = NULL;

    int charsDivisor = 1;    // Every char is separated from the consecutive by a 1 pixel divisor, horizontally and vertically

    FILE *rbmfFile = fopen(fileName, "rb");        // Define a pointer to bitmap file and open it in read-binary mode

    if (rbmfFile == NULL)
    {
        TraceLog(WARNING, "[%s] rBMF font file could not be opened, using default font", fileName);

        spriteFont = GetDefaultFont();
    }
    else
    {
        fread(&rbmfHeader, sizeof(rbmfInfoHeader), 1, rbmfFile);

        TraceLog(DEBUG, "[%s] Loading rBMF file, size: %ix%i, numChars: %i, charHeight: %i", fileName, rbmfHeader.imgWidth, rbmfHeader.imgHeight, rbmfHeader.numChars, rbmfHeader.charHeight);

        spriteFont.numChars = (int)rbmfHeader.numChars;

        int numPixelBits = rbmfHeader.imgWidth*rbmfHeader.imgHeight/32;

        rbmfFileData = (unsigned int *)malloc(numPixelBits*sizeof(unsigned int));

        for (int i = 0; i < numPixelBits; i++) fread(&rbmfFileData[i], sizeof(unsigned int), 1, rbmfFile);

        rbmfCharWidthData = (unsigned char *)malloc(spriteFont.numChars*sizeof(unsigned char));

        for (int i = 0; i < spriteFont.numChars; i++) fread(&rbmfCharWidthData[i], sizeof(unsigned char), 1, rbmfFile);

        // Re-construct image from rbmfFileData
        //-----------------------------------------
        Color *imagePixels = (Color *)malloc(rbmfHeader.imgWidth*rbmfHeader.imgHeight*sizeof(Color));

        for (int i = 0; i < rbmfHeader.imgWidth*rbmfHeader.imgHeight; i++) imagePixels[i] = BLANK;        // Initialize array

        int counter = 0;        // Font data elements counter

        // Fill image data (convert from bit to pixel!)
        for (int i = 0; i < rbmfHeader.imgWidth*rbmfHeader.imgHeight; i += 32)
        {
            for (int j = 31; j >= 0; j--)
            {
                if (BIT_CHECK(rbmfFileData[counter], j)) imagePixels[i+j] = WHITE;
            }

            counter++;
        }

        Image image = LoadImageEx(imagePixels, rbmfHeader.imgWidth, rbmfHeader.imgHeight);
        ImageFormat(&image, UNCOMPRESSED_GRAY_ALPHA);

        free(imagePixels);

        TraceLog(DEBUG, "[%s] Image reconstructed correctly, now converting it to texture", fileName);

        // Create spritefont with all data read from rbmf file
        spriteFont.texture = LoadTextureFromImage(image);
        UnloadImage(image);     // Unload image data

        //TraceLog(INFO, "[%s] Starting chars set reconstruction", fileName);

        // Get characters data using rbmfCharWidthData, rbmfHeader.charHeight, charsDivisor, rbmfHeader.numChars
        spriteFont.charValues = (int *)malloc(spriteFont.numChars*sizeof(int));
        spriteFont.charRecs = (Rectangle *)malloc(spriteFont.numChars*sizeof(Rectangle));
        spriteFont.charOffsets = (Vector2 *)malloc(spriteFont.numChars*sizeof(Vector2));
        spriteFont.charAdvanceX = (int *)malloc(spriteFont.numChars*sizeof(int));

        int currentLine = 0;
        int currentPosX = charsDivisor;
        int testPosX = charsDivisor;

        for (int i = 0; i < spriteFont.numChars; i++)
        {
            spriteFont.charValues[i] = (int)rbmfHeader.firstChar + i;

            spriteFont.charRecs[i].x = currentPosX;
            spriteFont.charRecs[i].y = charsDivisor + currentLine*((int)rbmfHeader.charHeight + charsDivisor);
            spriteFont.charRecs[i].width = (int)rbmfCharWidthData[i];
            spriteFont.charRecs[i].height = (int)rbmfHeader.charHeight;

            // NOTE: On image based fonts (XNA style), character offsets and xAdvance are not required (set to 0)
            spriteFont.charOffsets[i] = (Vector2){ 0.0f, 0.0f };
            spriteFont.charAdvanceX[i] = 0;

            testPosX += (spriteFont.charRecs[i].width + charsDivisor);

            if (testPosX > spriteFont.texture.width)
            {
                currentLine++;
                currentPosX = 2*charsDivisor + (int)rbmfCharWidthData[i];
                testPosX = currentPosX;

                spriteFont.charRecs[i].x = charsDivisor;
                spriteFont.charRecs[i].y = charsDivisor + currentLine*(rbmfHeader.charHeight + charsDivisor);
            }
            else currentPosX = testPosX;
        }

        spriteFont.size = spriteFont.charRecs[0].height;

        TraceLog(INFO, "[%s] rBMF file loaded correctly as SpriteFont", fileName);
    }

    fclose(rbmfFile);

    free(rbmfFileData);                // Now we can free loaded data from RAM memory
    free(rbmfCharWidthData);

    return spriteFont;
}