/* This file is part of the KDE project
   Copyright (C) 2004 Cedric Pasteur <cedric.pasteur@free.fr>
   Copyright (C) 2004 Alexander Dymo <cloudtemple@mskat.net>
   Copyright (C) 2005 Jaroslaw Staniek <js@iidea.pl>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
*/

#include "pixmapedit.h"
#include "editoritem.h"
#include "property.h"

#include <tqlayout.h>
#include <tqpainter.h>
#include <tqlabel.h>
#include <tqcursor.h>
#include <tqpushbutton.h>
#include <tqfont.h>
#include <tqfontmetrics.h>
#include <tqimage.h>
#include <tqfiledialog.h>
#include <tqtooltip.h>
#include <tqapplication.h>

#include <kdebug.h>
#include <kimageio.h>

#ifdef TQ_WS_WIN
#include <win32_utils.h>
#include <tderecentdirs.h>
#endif

#ifndef PURE_QT
#include <tdefiledialog.h>
#include <tdelocale.h>
#include <tdefiledialog.h>
#endif

using namespace KoProperty;

PixmapEdit::PixmapEdit(Property *property, TQWidget *parent, const char *name)
 : Widget(property, parent, name)
{
	setHasBorders(false);

	m_edit = new TQLabel(this, "m_edit");
	TQToolTip::add(m_edit, i18n("Click to show image preview"));
	m_edit->setAlignment(TQt::AlignLeft | TQt::AlignVCenter);
	m_edit->setMinimumHeight(5);
	m_edit->setSizePolicy(TQSizePolicy::Expanding, TQSizePolicy::Fixed);
	m_edit->setBackgroundMode(TQt::PaletteBase);
	m_edit->setMouseTracking(true);
	setBackgroundMode(TQt::PaletteBase);

	m_button = new TQPushButton(i18n("..."), this, "m_button");
	TQToolTip::add(m_button, i18n("Insert image from file"));
	m_button->setSizePolicy(TQSizePolicy::Fixed, TQSizePolicy::Fixed);
	TQFontMetrics fm(m_button->font());
	m_button->setFixedWidth(fm.width(m_button->text()+' '));
	m_button->setFocusPolicy(TQ_NoFocus);

	m_popup = new TQLabel(0, "m_popup", TQt::WStyle_Customize|TQt::WStyle_NoBorder|TQt::WX11BypassWM|WStyle_StaysOnTop);
	m_popup->setPaletteBackgroundColor(m_popup->palette().active().base());
	m_popup->setFrameStyle(TQFrame::Plain|TQFrame::Box);
	m_popup->setMargin(2);
	m_popup->setLineWidth(1);
	m_popup->hide();

	setFocusWidget(m_edit);
	connect(m_button, TQT_SIGNAL(clicked()), this, TQT_SLOT(selectPixmap()));
}

PixmapEdit::~PixmapEdit()
{
	delete m_popup;
}

TQVariant
PixmapEdit::value() const
{
	return m_pixmap;
}

void
PixmapEdit::setValue(const TQVariant &value, bool emitChange)
{
	m_pixmap = value.toPixmap();
	if (m_pixmap.isNull() || (m_pixmap.height()<=height())) {
		m_edit->setPixmap(m_pixmap);
		m_previewPixmap = m_pixmap;
	}
	else {
		TQImage img(m_pixmap.convertToImage());
		if (!TQRect(TQPoint(0,0), m_edit->size()*3).contains(m_pixmap.rect())) {
			img = img.smoothScale(m_edit->size()*3, TQ_ScaleMin);
			m_previewPixmap.convertFromImage(img);//preview pixmap is a bit larger
		}
		else {
			m_previewPixmap = m_pixmap;
		}
		img = img.smoothScale(m_edit->size(), TQ_ScaleMin);
		TQPixmap pm;
		pm.convertFromImage(img);
		m_edit->setPixmap(pm);
	}
	if (emitChange)
		emit valueChanged(this);
}

void
PixmapEdit::drawViewer(TQPainter *p, const TQColorGroup &, const TQRect &r, const TQVariant &value)
{
	TQRect r2(r);
	r2.setHeight(r2.height()+1);
	p->setClipRect(r2, TQPainter::CoordPainter);
	p->setClipping(true);
	p->eraseRect(r2);
	if (value.toPixmap().isNull())
		return;
	if (m_recentlyPainted!=value) {
		m_recentlyPainted = value;
		m_scaledPixmap = value.toPixmap();
		if (m_scaledPixmap.height() > r2.height() || m_scaledPixmap.width() > r2.width()) { //scale down
			TQImage img(m_scaledPixmap.convertToImage());
			img = img.smoothScale(r2.size()/*+TQSize(0,2)*/, TQ_ScaleMin);
			m_scaledPixmap.convertFromImage(img);
		}
	}
	p->drawPixmap(r2.topLeft().x(), //+KPROPEDITOR_ITEM_MARGIN,
		r2.topLeft().y()+(r2.height()-m_scaledPixmap.height())/2, m_scaledPixmap);
}

TQString
PixmapEdit::selectPixmapFileName()
{
/*#ifdef PURE_QT
	TQString url = TQFileDialog::getOpenFileName();
	if (!url.isEmpty()) {
		m_edit->setPixmap(TQPixmap(url));
		emit valueChanged(this);
	}
#endif*/
	TQString caption( i18n("Insert Image From File (for \"%1\" property)").arg(property()->caption()) );
#ifdef TQ_WS_WIN
	TQString recentDir;
	TQString fileName = TQFileDialog::getOpenFileName(
		KFileDialog::getStartURL(":lastVisitedImagePath", recentDir).path(), 
		convertKFileDialogFilterToTQFileDialogFilter(KImageIO::pattern(KImageIO::Reading)), 
		this, 0, caption);
#else
	KURL url( KFileDialog::getImageOpenURL(
		":lastVisitedImagePath", this, caption) );
	TQString fileName = url.isLocalFile() ? url.path() : url.prettyURL();

	//! @todo download the file if remote, then set fileName properly
#endif
	return fileName;
}

void
PixmapEdit::selectPixmap()
{
	TQString fileName( selectPixmapFileName() );
	if (fileName.isEmpty())
		return;

	TQPixmap pm;
	if (!pm.load(fileName)) {
		//! @todo err msg
		return;
	}
	setValue(pm);

#ifdef TQ_WS_WIN
	//save last visited path
	KURL url(fileName);
	if (url.isLocalFile())
		TDERecentDirs::add(":lastVisitedImagePath", url.directory());
#endif
}

void
PixmapEdit::resizeEvent(TQResizeEvent *e)
{
	Widget::resizeEvent(e);
	m_edit->move(0,0);
	m_edit->resize(e->size()-TQSize(m_button->width(),-1));
	m_button->move(m_edit->width(),0);
	m_button->setFixedSize(m_button->width(), height());
}

bool
PixmapEdit::eventFilter(TQObject *o, TQEvent *ev)
{
	if(TQT_BASE_OBJECT(o) == m_edit) {
		if(ev->type() == TQEvent::MouseButtonPress && TQT_TQMOUSEEVENT(ev)->button()==Qt::LeftButton) {
			if(m_previewPixmap.height() <= m_edit->height()
				&& m_previewPixmap.width() <= m_edit->width())
				return false;

			m_popup->setPixmap(m_previewPixmap.isNull() ? m_pixmap : m_previewPixmap);
			m_popup->resize(m_previewPixmap.size()+TQSize(2*3,2*3));
			TQPoint pos = TQCursor::pos()+TQPoint(3,15);
			TQRect screenRect = TQApplication::desktop()->availableGeometry( this );
			if ((pos.x()+m_popup->width()) > screenRect.width())
				pos.setX(screenRect.width()-m_popup->width());
			if ((pos.y()+m_popup->height()) > screenRect.height())
				pos.setY(mapToGlobal(TQPoint(0,0)).y()-m_popup->height());
			m_popup->move(pos);
			m_popup->show();
		}
		else if(ev->type() == TQEvent::MouseButtonRelease || ev->type() == TQEvent::Hide) {
			if(m_popup->isVisible())
				m_popup->hide();
		}
		else if(ev->type() == TQEvent::KeyPress) {
			TQKeyEvent* e = TQT_TQKEYEVENT(ev);
			if((e->key() == Key_Enter) || (e->key()== Key_Space) || (e->key() == Key_Return)) {
				m_button->animateClick();
				return true;
			}
		}
	}

	return Widget::eventFilter(o, ev);
}

void
PixmapEdit::setReadOnlyInternal(bool readOnly)
{
	m_button->setEnabled(!readOnly);
}

#include "pixmapedit.moc"