1 /*
2 * Copyright 2007, Ingo Weinhold <bonefish@cs.tu-berlin.de>.
3 * All rights reserved. Distributed under the terms of the MIT License.
4 */
5
6 #include "StringView.h"
7
8 #include <math.h>
9
10 #include <View.h>
11
12
StringView(const char * string)13 StringView::StringView(const char* string)
14 : View(),
15 fString(string),
16 fAlignment(B_ALIGN_LEFT),
17 fStringAscent(0),
18 fStringDescent(0),
19 fStringWidth(0),
20 fExplicitMinSize(B_SIZE_UNSET, B_SIZE_UNSET)
21 {
22 SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
23 fTextColor = (rgb_color){ 0, 0, 0, 255 };
24 }
25
26
27 void
SetString(const char * string)28 StringView::SetString(const char* string)
29 {
30 fString = string;
31
32 _UpdateStringMetrics();
33 Invalidate();
34 InvalidateLayout();
35 }
36
37
38 void
SetAlignment(alignment align)39 StringView::SetAlignment(alignment align)
40 {
41 if (align != fAlignment) {
42 fAlignment = align;
43 Invalidate();
44 }
45 }
46
47
48 void
SetTextColor(rgb_color color)49 StringView::SetTextColor(rgb_color color)
50 {
51 fTextColor = color;
52 Invalidate();
53 }
54
55
56 BSize
MinSize()57 StringView::MinSize()
58 {
59 BSize size(fExplicitMinSize);
60 if (!size.IsWidthSet())
61 size.width = fStringWidth - 1;
62 if (!size.IsHeightSet())
63 size.height = fStringAscent + fStringDescent - 1;
64 return size;
65 }
66
67
68 void
SetExplicitMinSize(BSize size)69 StringView::SetExplicitMinSize(BSize size)
70 {
71 fExplicitMinSize = size;
72 }
73
74
75 void
AddedToContainer()76 StringView::AddedToContainer()
77 {
78 _UpdateStringMetrics();
79 }
80
81
82 void
Draw(BView * container,BRect updateRect)83 StringView::Draw(BView* container, BRect updateRect)
84 {
85 BSize size(Size());
86 int widthDiff = (int)size.width + 1 - (int)fStringWidth;
87 int heightDiff = (int)size.height + 1
88 - (int)(fStringAscent + (int)fStringDescent);
89 BPoint base;
90
91 // horizontal alignment
92 switch (fAlignment) {
93 case B_ALIGN_RIGHT:
94 base.x = widthDiff;
95 break;
96 case B_ALIGN_LEFT:
97 default:
98 base.x = 0;
99 break;
100 }
101
102 base.y = heightDiff / 2 + fStringAscent;
103
104 container->SetHighColor(fTextColor);
105 container->DrawString(fString.String(), base);
106 }
107
108
109 void
_UpdateStringMetrics()110 StringView::_UpdateStringMetrics()
111 {
112 BView* container = Container();
113 if (!container)
114 return;
115
116 BFont font;
117 container->GetFont(&font);
118
119 font_height fh;
120 font.GetHeight(&fh);
121
122 fStringAscent = ceilf(fh.ascent);
123 fStringDescent = ceilf(fh.descent);
124 fStringWidth = font.StringWidth(fString.String());
125 }
126