label.cpp (2397B)
1 // Copyright (c) 2003 - 2009 Anselm R Garbe <anselm@garbe.us> 2 // See LICENSE for license details. 3 4 #include <sstream> 5 6 #include "label.h" 7 8 #include "draw.h" 9 #include "font.h" 10 #include "logger.h" 11 #include "kernel.h" 12 #include "monitor.h" 13 #include "xcore.h" 14 15 Label::Label(Monitor *monitor, Window window, Alignment align, GC gc) 16 : Rectangle() 17 { 18 19 LOGDEBUG("initializing label"); 20 align_ = align; 21 font_ = monitor->font(); 22 monitor_ = monitor; 23 gc_ = gc; 24 window_ = window; 25 } 26 27 Label::~Label() { 28 } 29 30 unsigned int Label::adjustWidth() { 31 setWidth(textWidth()); 32 return width(); 33 } 34 35 unsigned int Label::textWidth() { 36 return font_->textWidth(text_) + 2 * font_->height(); 37 } 38 39 void Label::update(unsigned long background, unsigned long text, 40 unsigned long shine, unsigned long shadow, 41 bool shineBorder, bool shadowBorder) 42 43 { 44 45 LOGDEBUG("label update"); 46 47 // draw background 48 XCORE->setForeground(gc_, background); 49 XCORE->fillRectangle(window_, gc_, this); 50 51 // draw border if neccessary 52 if (shadowBorder) { 53 Draw::drawShadowBorder(window_, gc_, this, shadow); 54 } 55 56 if (shineBorder) { 57 58 Draw::drawShineBorder(window_, gc_, this, shine); 59 } 60 61 // draw text 62 if (text_ == "") { 63 return; // nothing to draw 64 } 65 XCORE->setForeground(gc_, text); 66 int textWidth = this->textWidth(); 67 68 if (textWidth > (int)width()) { 69 int matchLength = (int)((text_.length() * width() / textWidth) - 3); 70 if (matchLength < 0) { 71 matchLength = 0; 72 } 73 text_ = Util::shortenString(text_, matchLength); 74 textWidth = this->textWidth(); 75 } 76 77 unsigned int fontBaseLine = 0; 78 fontBaseLine = font_->ascent(); 79 unsigned int fontY = y() + height() / 2 - font_->height() / 2 + fontBaseLine; 80 81 unsigned int fontX = 0; 82 switch (align_) { 83 case LEFT: 84 fontX = x() + font_->height(); 85 break; 86 case CENTER: 87 fontX = x() + (width() / 2 - (textWidth - 2 * font_->height()) / 2); 88 break; 89 case RIGHT: 90 fontX = x() + width() - textWidth + font_->height(); 91 break; 92 } 93 94 font_->drawText(window_, gc_, fontX, fontY, text_); 95 } 96 97 98 void Label::setText(string text) { 99 text_ = text; 100 } 101 102 string Label::text() const { 103 return text_; 104 } 105 106 void Label::setAlignment(const Alignment align) { 107 align_ = align; 108 }