1/*
2 * Copyright 2009, Ingo Weinhold, ingo_weinhold@gmx.de.
3 * Distributed under the terms of the MIT License.
4 */
5
6
7#include "TableCellValueRendererUtils.h"
8
9#include <Font.h>
10#include <String.h>
11#include <View.h>
12
13
14static const float kTextMargin = 8;
15
16
17/*static*/ void
18TableCellValueRendererUtils::DrawString(BView* view, BRect rect,
19	const char* string, bool valueChanged, enum alignment alignment,
20	bool truncate)
21{
22	// get font height info
23	font_height	fontHeight;
24	view->GetFontHeight(&fontHeight);
25
26	// truncate, if requested
27	BString truncatedString;
28	if (truncate) {
29		truncatedString = string;
30		view->TruncateString(&truncatedString, B_TRUNCATE_END,
31			rect.Width() - 2 * kTextMargin + 2);
32		string = truncatedString.String();
33	}
34
35	// compute horizontal position according to alignment
36	float x;
37	switch (alignment) {
38		default:
39		case B_ALIGN_LEFT:
40			x = rect.left + kTextMargin;
41			break;
42
43		case B_ALIGN_CENTER:
44			x = rect.left + (rect.Width() - view->StringWidth(string)) / 2;
45			break;
46
47		case B_ALIGN_RIGHT:
48			x = rect.right - kTextMargin - view->StringWidth(string);
49			break;
50	}
51
52	// compute vertical position (base line)
53	float y = rect.top
54		+ (rect.Height() - (fontHeight.ascent + fontHeight.descent
55			+ fontHeight.leading)) / 2
56		+ (fontHeight.ascent + fontHeight.descent) - 2;
57		// TODO: This is the computation BColumnListView (respectively
58		// BTitledColumn) is using, which I find somewhat weird.
59
60	if (valueChanged) {
61		view->PushState();
62		view->SetHighColor((rgb_color){255, 0, 0, 255});
63	}
64
65	view->DrawString(string, BPoint(x, y));
66
67	if (valueChanged)
68		view->PopState();
69}
70
71
72/*static*/ float
73TableCellValueRendererUtils::PreferredStringWidth(BView* view,
74	const char* string)
75{
76	return view->StringWidth(string) + 2 * kTextMargin;
77}
78