#include "clineedit.h"
#include "qad_types.h"


CLineEdit::CLineEdit(QWidget * parent): QLineEdit(parent) {
	cw = new QWidget(this);
	clear_im.load(":/icons/edit-clear-locationbar-rtl.png");
	cw->setCursor(Qt::ArrowCursor);
	cw->setToolTip(tr("Clear"));
	cw->hide();
	cw->installEventFilter(this);
	connect(this, SIGNAL(textChanged(QString)), this, SLOT(textChanged_(QString)));
	int is = fontHeight();
	int m0, m1, m2, m3;
	getTextMargins(&m0, &m1, &m2, &m3);
	setTextMargins(m0, m1, m2 + (is * 1.2), m3);
	//connect(cw, SIGNAL(mouseReleaseEvent(QMouseEvent * )), this, SLOT(clearMouseRelease(QMouseEvent * )));
}


bool CLineEdit::eventFilter(QObject * o, QEvent * e) {
	switch (e->type()) {
	case QEvent::MouseButtonRelease:
		clearMouseRelease((QMouseEvent * )e);
		break;
	case QEvent::Paint:
		cwPaintEvent();
		break;
	default : break;
	}
	return QLineEdit::eventFilter(o, e);
}


void CLineEdit::resizeEvent(QResizeEvent * e) {
	QLineEdit::resizeEvent(e);
	int is = fontHeight(), tm = (height() - is) / 2;
	cw->setGeometry(width() - is - tm, tm, is, is);
}


void CLineEdit::changeEvent(QEvent * e) {
	QLineEdit::changeEvent(e);
	if (e->type() == QEvent::LanguageChange) {
		cw->setToolTip(tr("Clear"));
		return;
	}
}


void CLineEdit::cwPaintEvent() {
	QPainter p(cw);
	p.setRenderHint(QPainter::SmoothPixmapTransform);
	p.drawImage(cw->rect(), clear_im);
}


void CLineEdit::setDefaultText(const QString & t, bool set_text) {
	dt = t;
	if (set_text) {
		setText(t);
		emit textEdited(t);
		cw->hide();
		return;
	}
	textChanged_(text());
}
