master chld/haikuprg / src / Typist.cpp
 1#include <Application.h>
 2#include <Window.h>
 3
 4#include <vector>
 5
 6class View:public BView
 7{
 8public:View(BRect f):
 9  BView(f, "Text", B_FOLLOW_ALL, B_WILL_DRAW){
10  l.push_back(BString());
11  fnt.SetSize(size);
12}
13
14  void AttachedToWindow()
15  {
16    MakeFocus(true);
17  }
18
19  void Draw(BRect r)
20  {
21    float w=fnt.StringWidth(txt.String());
22    fnt.GetHeight(&f);
23    
24    SetFont(&fnt, B_FONT_ALL);
25    float y=f.ascent+f.descent;
26
27    for (size_t i=0; i<l.size(); i++)
28      {
29	DrawString(l[i], l[i].Length(), BPoint(0, (y)));
30	y+=f.ascent+f.descent;
31      }
32  }
33
34  
35
36  void KeyDown(const char *c, int32 n)
37  {
38    if (c[0]==B_BACKSPACE){
39      if (l.size()>0){
40	l[l.size()-1].Truncate(l[l.size()-1].Length() - 1);
41	if (l[l.size()-1].Length()<1 && l.size()-1>0) l.pop_back();
42      }
43    }else if (c[0]==B_ENTER){
44      l.push_back(BString());
45    }else{
46      l[l.size()-1].Append(c, n);
47    }
48
49    if (fnt.StringWidth(l[l.size()-1])>Bounds().Width()-5){
50	l.push_back(BString());
51      }
52      if (l.size()*(f.ascent+f.descent) > Bounds().Height()){
53	l.erase(l.begin());
54      }
55    Invalidate();
56  }
57public:
58  BFont fnt;
59  BString txt;
60  int32 size=16;
61private:
62  std::vector<BString> l;
63  font_height f;
64};
65
66class Win:public BWindow
67{
68public:Win(BRect f):
69  BWindow(f, "Typist", B_TITLED_WINDOW, B_QUIT_ON_WINDOW_CLOSE)
70  {
71    View *view=new View(Bounds());
72    AddChild(view);
73    view->ForceFontAliasing(false);
74    view->fnt.SetFamilyAndStyle("PxPlus IBM VGA 9x16", "Regular");
75  }
76};
77
78class App:public BApplication
79{
80public:App():BApplication("application/x-vnd.example.typist")
81  {
82    BRect rect(100,100,640,480);
83    Win *w = new Win(rect);
84    w->Show();
85  }
86};
87
88int main(void)
89{
90  App a;
91  a.Run();
92  return 0;
93}