/*
    kiconedit - a small graphics drawing program for the KDE
    Copyright (C) 1998  Thomas Tanghus (tanghus@kde.org)

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

    This program 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
    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., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/  

#include <qregexp.h>
#include <qwhatsthis.h>
#include <qtooltip.h>

#include <kaction.h>
#include <kstdaction.h>
#include <kconfig.h>
#include <kruler.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <ktoolbarbutton.h>
#include <kdebug.h>

#include "kiconedit.h"
#include "kiconcolors.h"
#include <kpopupmenu.h>

WindowList KIconEdit::windowList;

KIconEdit::KIconEdit(const QImage image, const char *name)
 : KMainWindow(0, name)
{
    init();
    img = image;
    img.detach();
    grid->load(&img);
    preview->setPixmap(grid->pixmap());
}

KIconEdit::KIconEdit(const QString &xpm, const char *name)
 : KMainWindow(0, name)
{
    init();
    icon->open(&img, xpm);
    preview->setPixmap(grid->pixmap());
}

void KIconEdit::init()
{
  windowList.append(this);
  setCaption(kapp->caption());

  Properties *pprops = KIconEditProperties::self()->properties();

  menubar = 0L;
  toolbar = 0L;
  drawtoolbar = 0L;
  palettetoolbar = 0L;
  statusbar = 0L;

  msgtimer = new QTimer(this);
  connect( msgtimer, SIGNAL(timeout()), SLOT(slotClearStatusMessage()));

  gridview = new KGridView(&img, this);
  grid = gridview->grid();
  icon = new KIconEditIcon(this, &grid->image());

  setAcceptDrops(true);

  setupStatusBar();
  setupMenuBar();
  setupToolBar();
  setupPaletteToolBar();
  setupWhatsThis();

  connect( icon, SIGNAL( saved()),
           SLOT(slotSaved()));
  connect( icon, SIGNAL( loaded(QImage *)),
     grid, SLOT(load(QImage *)));
  connect( icon, SIGNAL(opennewwin(const QString &)),
           SLOT(slotNewWin(const QString &)));
  connect(icon, SIGNAL(newname(const QString &)),
           SLOT( slotUpdateStatusName(const QString &)));
  connect(icon, SIGNAL(newmessage(const QString &)),
           SLOT( slotUpdateStatusMessage(const QString &)));

  connect( syscolors, SIGNAL( newcolor(uint)),
     grid, SLOT(setColorSelection(uint)));
  connect( customcolors, SIGNAL( newcolor(uint)),
     grid, SLOT(setColorSelection(uint)));

  connect( grid, SIGNAL( changed(const QPixmap &)),
    preview, SLOT(setPixmap(const QPixmap &)));
  connect( grid, SIGNAL( addingcolor(uint) ),
           SLOT(addColor(uint)));
  connect( grid, SIGNAL( colorschanged(uint, uint*) ),
           SLOT(addColors(uint, uint*)));

  connect(grid, SIGNAL(sizechanged(int, int)),
           SLOT( slotUpdateStatusSize(int, int)));
  connect(grid, SIGNAL(poschanged(int, int)),
           SLOT( slotUpdateStatusPos(int, int)));
  connect(grid, SIGNAL(scalingchanged(int, bool)),
           SLOT( slotUpdateStatusScaling(int, bool)));
  connect( grid, SIGNAL( addingcolor(uint) ),
           SLOT(slotUpdateStatusColors(uint)));
  connect(grid, SIGNAL(colorschanged(uint, uint*)),
           SLOT( slotUpdateStatusColors(uint, uint*)));
  connect(grid, SIGNAL(newmessage(const QString &)),
           SLOT( slotUpdateStatusMessage(const QString &)));
  connect(grid, SIGNAL(clipboarddata(bool)),
           SLOT( slotUpdatePaste(bool)));
  connect(grid, SIGNAL(selecteddata(bool)),
           SLOT( slotUpdateCopy(bool)));

  kdDebug() << "Updating statusbar" << endl;
  slotUpdateStatusSize(grid->cols(), grid->rows());

  slotUpdateStatusScaling(grid->scaling(), true);

  if(icon->url().length())
    slotUpdateStatusName(icon->url());

  slotUpdateCopy(false);

  uint *c = 0, n = 0;
  n = grid->getColors(c);
  slotUpdateStatusColors(n, c);

  setCentralWidget(gridview);

  if((pprops->winwidth > 0) && (pprops->winheight > 0))
    resize( pprops->winwidth, pprops->winheight );

  updateAccels();
  show();
}

KIconEdit::~KIconEdit()
{
    kdDebug() << "Deleting KIconEdit: " << (int)this << endl;
    windowList.remove(this);

    if (windowList.count() < 1)
    {
        kapp->quit();
    }
}

bool KIconEdit::queryClose()
{
    bool cancel = false;
    if (grid->isModified())
    {
        int r = KMessageBox::warningYesNoCancel(this,
	    i18n("The current file has been modified.\nDo you want to save it?"));

        switch(r)
        {
            case KMessageBox::Yes:
                icon->save(&grid->image());
                break;
            case KMessageBox::No:
                break;
            case KMessageBox::Cancel:
                cancel = true;
                break;
            default:
                break;
        }
    }

    if(!cancel)
    {
        writeConfig();
    }
    return (!cancel);
}

/*
    save size of the application window
*/
void KIconEdit::resizeEvent( QResizeEvent *ev )
{
  KMainWindow::resizeEvent(ev);
  //kdDebug() << "KIconEdit::resizeEvent()" << endl;

  KIconEditProperties::self()->properties()->winwidth = geometry().width();
  KIconEditProperties::self()->properties()->winheight = geometry().height();

  //viewport->updateScrollBars();
}

// this is for exit by request of the session manager
void KIconEdit::saveProperties(KConfig *config )
{
    kdDebug() << "KIconEdit::saveProperties" << endl;

    config->writeEntry("Name", icon->url());
}

// this is for instances opened by the session manager
void KIconEdit::readProperties(KConfig *config)
{
    kdDebug() << "KIconEdit::readProperties" << endl;

    QString entry = config->readEntry("Name", ""); // no default
    if (entry.isEmpty())  return;
    icon->open(&grid->image(), entry);
}

/*
    this is for normal exits or request from "Options->Save options".
*/

void KIconEdit::writeConfig()
{
    KConfig *config = kapp->config();
    config->setGroup( "Appearance" );
    config->writeEntry("ShowMainToolBar", toolbar->isVisible());
    config->writeEntry("ShowDrawToolBar", drawtoolbar->isVisible());
    config->writeEntry("ShowStatusBar", statusbar->isVisible());

    config->writeEntry("MainToolBarPos", (int)toolbar->barPos());
    config->writeEntry("DrawToolBarPos", (int)drawtoolbar->barPos());

    KRecentFilesAction* recent = dynamic_cast<KRecentFilesAction*>
                                                    (actionCollection()->action(KStdAction::stdName(KStdAction::OpenRecent)));

    if (recent)
    {
        recent->saveEntries(config);
    }

    KIconEditProperties::self()->saveProperties();
}

QSize KIconEdit::sizeHint() const
{
    if(gridview)
        return gridview->sizeHint();
    else
        return QSize(-1, -1);
}

bool KIconEdit::setupMenuBar()
{
  kdDebug() << "setupMenuBar" << endl;

  struct Properties *pprops = KIconEditProperties::self()->properties();
  menubar = menuBar();
  KAccel *keys = pprops->keys;

  kdDebug() << "setupMenuBar - read settings" << endl;

  int id;

  file = new QPopupMenu(menubar);
  toolbar = toolBar();

  KAction* action = new KAction(i18n("New &Window"), "newwin", KShortcut(),
                                                   this,  SLOT(slotNewWin()), this, "newwin");
  action->setWhatsThis(i18n("New window\n\nOpens a new Icon Editor window."));
  action->setToolTip(action->text().replace(QRegExp("\\&"), ""));
  action->plug(file);
  action->plug(toolbar);

  file->insertSeparator();

  action = KStdAction::openNew(this, SLOT(slotNew()), actionCollection());
  action->setWhatsThis(i18n("New\n\nCreate a new icon, either from a template or by specifying the size"));
  action->setToolTip(action->text().replace(QRegExp("\\&"), ""));
  action->plug(file);
  action->plug(toolbar);

  action = KStdAction::open(this, SLOT(slotOpen()), actionCollection());
  action->setWhatsThis(i18n("Open\n\nOpen an existing icon"));
  action->setToolTip(action->text().replace(QRegExp("\\&"), ""));
  action->plug(file);
  action->plug(toolbar);

  KRecentFilesAction* recent = KStdAction::openRecent(this, SLOT(slotOpenRecent(const KURL&)),
                                                                                         actionCollection());
  recent->setMaxItems(15); // FIXME should be configurable!
  recent->loadEntries(kapp->config());
  recent->plug(file);

  file->insertSeparator();

  action = KStdAction::save(this, SLOT(slotSave()), actionCollection());
  action->setWhatsThis(i18n("Save\n\nSave the current icon"));
  action->setToolTip(action->text().replace(QRegExp("\\&"), ""));
  action->plug(file);
  action->plug(toolbar);

  action = KStdAction::saveAs(this, SLOT(slotSaveAs()), actionCollection());
  action->plug(file);

  file->insertSeparator();

  action = KStdAction::print(this, SLOT(slotPrint()), actionCollection());
  action->setWhatsThis(i18n("Print\n\nOpens a print dialog to let you print the current icon."));
  action->plug(file);
  action->plug(toolbar);

  file->insertSeparator();

  action = KStdAction::close(this, SLOT(slotClose()), actionCollection());
  action->plug(file);

  menubar->insertItem(i18n("&File"), file);

  edit = new QPopupMenu(menubar);

  action = KStdAction::cut(this, SLOT(slotCut()), actionCollection());
  action->setWhatsThis(i18n("Cut\n\nCut the current selection out of the icon\n\n"
             "(Tip: You can make both rectangular and circular selections)"));
  action->setToolTip(action->text().replace(QRegExp("\\&"), ""));
  action->plug(edit);
  action->plug(toolbar);

  action = KStdAction::copy(this, SLOT(slotCopy()), actionCollection());
  action->setWhatsThis(i18n("Copy\n\nCopy the current selection out of the icon\n\n"
             "(Tip: You can make both rectangular and circular selections)"));
  action->setToolTip(action->text().replace(QRegExp("\\&"), ""));
  action->plug(edit);
  action->plug(toolbar);

  action = KStdAction::paste(this, SLOT(slotPaste()), actionCollection());
  action->setWhatsThis(i18n("Paste\n\nPaste the contents of the clipboard into the current icon.\n\n"
             "If the contents are larger than the current icon you can paste them"
             " in a new window.\n\n"
             "(Tip: Select \"Paste transparent pixels\" in the configuration dialog"
             " if you also want to paste transparency.)"));
  action->setToolTip(action->text().replace(QRegExp("\\&"), ""));
  action->plug(edit);
  action->plug(toolbar);

  id = edit->insertItem(i18n("Paste as &New"), ID_EDIT_PASTE_AS_NEW);
  edit->connectItem(ID_EDIT_PASTE_AS_NEW, grid, SLOT(editPasteAsNew()));

  id = edit->insertItem(i18n("Clea&r"),  this, SLOT(slotClear()));

  edit->insertSeparator();

  action = new KAction(i18n("Rectangular Selection"), "selectrect", KShortcut(),
                                     this,  SLOT(slotToolSelectRect()), this, "newwin");
  action->setWhatsThis(i18n("Select\n\nSelect a rectangular section of the icon using the mouse."));
  action->setToolTip(action->text().replace(QRegExp("\\&"), ""));
  action->plug(edit);
  action->plug(toolbar);

  action = new KAction(i18n("Circular Selection"), "selectcircle", KShortcut(),
                                     this,  SLOT(slotToolSelectCircle()), this, "newwin");
  action->setWhatsThis(i18n("Select\n\nSelect a circular section of the icon using the mouse."));
  action->setToolTip(action->text().replace(QRegExp("\\&"), ""));
  action->plug(edit);
  action->plug(toolbar);

  action = KStdAction::selectAll(this, SLOT(slotSelectAll()), actionCollection());
  action->plug(edit);

  edit->insertSeparator();

  action = new KAction(i18n("&Resize"), "transform", KShortcut(),
                                                   grid,  SLOT(editResize()), this, "newwin");
  action->setWhatsThis(i18n("Resize\n\nSmoothly resizes the icon while trying to preserve the contents"));
  action->setToolTip(action->plainText());
  action->plug(edit);
  action->plug(toolbar);

  action = new KAction(i18n("&GrayScale"), "grayscale", KShortcut(),
                                                   grid,  SLOT(grayScale()), this, "newwin");
  action->setWhatsThis(i18n("Gray scale\n\nGray scale the current icon.\n"
             "(Warning: The result is likely to contain colors not in the icon palette"));
  action->setToolTip(action->text().replace(QRegExp("\\&"), ""));
  action->plug(edit);
  action->plug(toolbar);

  //id = image->insertItem(SmallIcon("kdepalette"), i18n("&Map to KDE palette"), ID_IMAGE_MAPTOKDE);

  menubar->insertItem(i18n("&Edit"), edit);

  zoom = new QPopupMenu(menubar);
  id = zoom->insertItem(i18n("1:1"), ID_VIEW_ZOOM_1TO1);
  id = zoom->insertItem(i18n("1:5"), ID_VIEW_ZOOM_1TO5);
  id = zoom->insertItem(i18n("1:10"), ID_VIEW_ZOOM_1TO10);
  connect( zoom, SIGNAL(activated(int)), SLOT(slotView(int)));

  view = new QPopupMenu(menubar);

  action = KStdAction::zoomIn(this, SLOT(slotZoomIn()), actionCollection());
  action->setWhatsThis(i18n("Zoom in\n\nZoom in by one."));
  action->setToolTip(action->text().replace(QRegExp("\\&"), ""));
  action->plug(view);

  action = KStdAction::zoomOut(this, SLOT(slotZoomOut()), actionCollection());
  action->setWhatsThis(i18n("Zoom out\n\nZoom out by one."));
  action->setToolTip(action->text().replace(QRegExp("\\&"), ""));
  action->plug(view);

  id = view->insertItem(SmallIcon("viewmag"), i18n("Zoom Factor"), zoom);
  menubar->insertItem(i18n("&View"), view);

  setupTools();

  options = new QPopupMenu(menubar);
  action = KStdAction::keyBindings(this, SLOT(slotConfigureKeys()), actionCollection());
  action->plug(options);
  action = KStdAction::preferences(this, SLOT(slotConfigureSettings()), actionCollection());
  action->plug(options);
  options->insertSeparator();
  options->insertItem(i18n("Show &Grid"), ID_OPTIONS_TOGGLE_GRID);
  if(pprops->showgrid)
    options->setItemChecked(ID_OPTIONS_TOGGLE_GRID, true);
  options->insertItem(i18n("Show &Toolbar"), ID_OPTIONS_TOGGLE_TOOL1);
  if(pprops->maintoolbarstat)
    options->setItemChecked(ID_OPTIONS_TOGGLE_TOOL1, true);
  options->insertItem(i18n("Show &Drawing Tools"), ID_OPTIONS_TOGGLE_TOOL2);
  if(pprops->drawtoolbarstat)
    options->setItemChecked(ID_OPTIONS_TOGGLE_TOOL2, true);
  options->insertItem(i18n("Show &Statusbar"), ID_OPTIONS_TOGGLE_STATS);
  if(pprops->statusbarstat)
    options->setItemChecked(ID_OPTIONS_TOGGLE_STATS, true);
  options->insertSeparator();
  options->insertItem(SmallIcon("filesave"), i18n("&Save Options"), ID_OPTIONS_SAVE);
  connect( options, SIGNAL(activated(int)), SLOT(slotConfigure(int)));
  menubar->insertItem(i18n("&Settings"), options);

  menubar->insertSeparator();

  help = helpMenu();

  menubar->insertItem(i18n("&Help"), help);

  menubar->show();
  //connect( menubar, SIGNAL(activated(int)), SLOT(slotActions(int)));
  //file->setItemEnabled(ID_FILE_RECENT, recentExist);
  kdDebug() << "setupMenuBar - done" << endl;
  return true;
}

void KIconEdit::setupTools()
{
  struct Properties *pprops = KIconEditProperties::self()->properties();
  tools = new QPopupMenu(menubar);

  drawtoolbar = toolBar("drawToolBar");
  drawtoolbar->setFullSize();
  drawtoolbar->setIconText((KToolBar::IconText) pprops->drawtoolbartext);
  drawtoolbar->setBarPos(pprops->drawtoolbarpos);

  if(pprops->drawtoolbarstat)
    drawtoolbar->show();
  else
    drawtoolbar->hide();

  KRadioAction* findAction = new KRadioAction(i18n("Find pixel"), "colorpicker", KShortcut(),
                                                                            this, SLOT(slotToolPointer()),  actionCollection(), "pointer");
  findAction->setExclusiveGroup("toolActions");
  findAction->plug(tools);
  findAction->plug(drawtoolbar);
  findAction->setWhatsThis(i18n("Find\n\nThe color of the pixel clicked on will be the current draw color"));
  findAction->setToolTip(findAction->text());

 KRadioAction*  toolAction = new KRadioAction(i18n("Freehand"), "paintbrush", KShortcut(),
                                                                           this, SLOT(slotToolFreehand()),  actionCollection(), "freehand");
  toolAction->setExclusiveGroup("toolActions");
  toolAction->plug(tools);
  toolAction->plug(drawtoolbar);
  toolAction->setWhatsThis(i18n("Free hand\n\nDraw non-linear lines"));
  toolAction->setToolTip(toolAction->text());

  toolAction = new KRadioAction(i18n("Rectangle"), "rectangle", KShortcut(),
                                                    this, SLOT(slotToolRectangle()),  actionCollection(), "rectangle");
  toolAction->setExclusiveGroup("toolActions");
  toolAction->plug(tools);
  toolAction->plug(drawtoolbar);
  toolAction->setWhatsThis(i18n("Rectangle\n\nDraw a rectangle"));
  toolAction->setToolTip(toolAction->text());

  toolAction = new KRadioAction(i18n("Filled Rectangle"), "filledrectangle", KShortcut(),
                                                    this, SLOT(slotToolFilledRectangle()),  actionCollection(), "filledrectangle");
  toolAction->setExclusiveGroup("toolActions");
  toolAction->plug(tools);
  toolAction->plug(drawtoolbar);
  toolAction->setWhatsThis(i18n("Filled rectangle\n\nDraw a filled rectangle"));
  toolAction->setToolTip(toolAction->text());

  toolAction = new KRadioAction(i18n("Circle"), "circle", KShortcut(),
                                                    this, SLOT(slotToolCircle()),  actionCollection(), "circle");
  toolAction->setExclusiveGroup("toolActions");
  toolAction->plug(tools);
  toolAction->plug(drawtoolbar);
  toolAction->setWhatsThis(i18n("Circle\n\nDraw a circle"));
  toolAction->setToolTip(toolAction->text());

  toolAction = new KRadioAction(i18n("Filled Circle"), "filledcircle", KShortcut(),
                                                    this, SLOT(slotToolFilledCircle()),  actionCollection(), "rectangle");
  toolAction->setExclusiveGroup("toolActions");
  toolAction->plug(tools);
  toolAction->plug(drawtoolbar);
  toolAction->setWhatsThis(i18n("Filled circle\n\nDraw a filled circle"));
  toolAction->setToolTip(toolAction->text());

  toolAction = new KRadioAction(i18n("Ellipse"), "ellipse", KShortcut(),
                                                    this, SLOT(slotToolEllipse()),  actionCollection(), "ellipse");
  toolAction->setExclusiveGroup("toolActions");
  toolAction->plug(tools);
  toolAction->plug(drawtoolbar);
  toolAction->setWhatsThis(i18n("Ellipse\n\nDraw an ellipse"));
  toolAction->setToolTip(toolAction->text());

  toolAction = new KRadioAction(i18n("Filled Ellipse"), "filledellipse", KShortcut(),
                                                    this, SLOT(slotToolFilledEllipse()),  actionCollection(), "filledellipse");
  toolAction->setExclusiveGroup("toolActions");
  toolAction->plug(tools);
  toolAction->plug(drawtoolbar);
  toolAction->setWhatsThis(i18n("Filled ellipse\n\nDraw a filled ellipse"));
  toolAction->setToolTip(toolAction->text());

  toolAction = new KRadioAction(i18n("Spray"), "spraycan", KShortcut(),
                                                    this, SLOT(slotToolSpray()),  actionCollection(), "spray");
  toolAction->setExclusiveGroup("toolActions");
  toolAction->plug(tools);
  toolAction->plug(drawtoolbar);
  toolAction->setWhatsThis(i18n("Spray\n\nDraw scattered pixels in the current color"));
  toolAction->setToolTip(toolAction->text());

  toolAction = new KRadioAction(i18n("Flood Fill"), "flood", KShortcut(),
                                                    this, SLOT(slotToolFlood()),  actionCollection(), "flood");
  toolAction->setExclusiveGroup("toolActions");
  toolAction->plug(tools);
  toolAction->plug(drawtoolbar);
  toolAction->setWhatsThis(i18n("Flood fill\n\nFill adjoining pixels with the same color with the current color"));
  toolAction->setToolTip(toolAction->text());

  toolAction = new KRadioAction(i18n("Line"), "line", KShortcut(),
                                                    this, SLOT(slotToolLine()),  actionCollection(), "line");
  toolAction->setExclusiveGroup("toolActions");
  toolAction->plug(tools);
  toolAction->plug(drawtoolbar);
  toolAction->setWhatsThis(i18n("Line\n\nDraw a straight line vertically, horizontally or at 45 deg. angles"));
  toolAction->setToolTip(toolAction->text());

  toolAction = new KRadioAction(i18n("Eraser (Transparent)"), "eraser", KShortcut(),
                                                    this, SLOT(slotToolEraser()),  actionCollection(), "eraser");
  toolAction->setExclusiveGroup("toolActions");
  toolAction->plug(tools);
  toolAction->plug(drawtoolbar);
  toolAction->setWhatsThis(i18n("Erase\n\nErase pixels. Set the pixels to be transparent\n\n"
             "(Tip: If you want to draw transparency with a different tool,"
             " first click on \"Erase\" then on the tool you want to use)"));
  toolAction->setToolTip(toolAction->text());

  findAction->setChecked(true);
  menubar->insertItem(i18n("&Tools"), tools);
}

void KIconEdit::updateAccels()
{
    actionCollection()->readShortcutSettings();
}

bool KIconEdit::setupToolBar()
{
  Properties *pprops = KIconEditProperties::self()->properties();
  kdDebug() << "setupToolBar" << endl;

  toolbar->setIconText((KToolBar::IconText) pprops->maintoolbartext);
  toolbar->setBarPos(pprops->maintoolbarpos);
  if(pprops->maintoolbarstat)
    toolbar->show();
  else
    toolbar->hide();

  toolbar->insertSeparator();
  toolbar->insertButton(BarIcon("viewmag-"),ID_VIEW_ZOOM_OUT, TRUE,
			  i18n("Zoom out"));
  toolbar->setDelayedPopup(ID_VIEW_ZOOM_OUT, zoom);
  toolbar->insertButton(BarIcon("viewmag+"),ID_VIEW_ZOOM_IN, TRUE,
			  i18n("Zoom in"));
  toolbar->setDelayedPopup(ID_VIEW_ZOOM_IN, zoom);
  toolbar->insertSeparator();
  toolbar->insertButton(BarIcon("grid"),ID_OPTIONS_TOGGLE_GRID, TRUE,
			  i18n("Toggle grid"));
  toolbar->setToggle(ID_OPTIONS_TOGGLE_GRID, true);
  if(pprops->showgrid)
    ((KToolBarButton*)toolbar->getButton(ID_OPTIONS_TOGGLE_GRID))->on(true);

  toolbar->insertSeparator();

  QToolTip::add(QWhatsThis::whatsThisButton(toolbar), i18n("What is ...?"));
  //toolbar->alignItemRight(btwhat, true);

//  toolbar->insertWidget(ID_HELP_WHATSTHIS, btwhat->sizeHint().width(), btwhat);

  connect( toolbar, SIGNAL(clicked(int)), SLOT(slotView(int)));
  connect( toolbar, SIGNAL(clicked(int)), SLOT(slotConfigure(int)));

  kdDebug() << "setupToolBar - done" << endl;
  return true;
}

bool KIconEdit::setupPaletteToolBar()
{
    QWidget *sysColorsWidget = new QWidget(this);
    QBoxLayout *ml = new QVBoxLayout(sysColorsWidget);
    QLabel *l = new QLabel(i18n("System Colors"), sysColorsWidget);
    syscolors = new KSysColors(sysColorsWidget);
    syscolors->setFixedSize(syscolors->width(), syscolors->height());
    ml->addWidget(l);
    ml->addWidget(syscolors);

    int ow = sysColorsWidget->sizeHint().width();
    int iw = syscolors->width();
    int ih = syscolors->height();

    palettetoolbar = toolBar("paletteToolbar");
    palettetoolbar->show();
    palettetoolbar->setBarPos(KToolBar::Right);

    sysColorsWidget->reparent(palettetoolbar, 0, QPoint(0, 0));

    preview = new QLabel(palettetoolbar);
    preview->setFrameStyle(QFrame::Panel|QFrame::Sunken);
    preview->setFixedSize(iw, 64);
    palettetoolbar->insertWidget(ID_PREVIEW, iw, preview);
    palettetoolbar->insertSeparator();

    palettetoolbar->insertWidget(ID_SYSTEM_COLORS, iw, sysColorsWidget);

    QWidget *customColorsWidget = new QWidget(palettetoolbar);
    ml = new QVBoxLayout(customColorsWidget);
    l = new QLabel(i18n("Custom Colors"), customColorsWidget);
    customcolors = new KCustomColors(customColorsWidget);
    customColorsWidget->setFixedSize(iw, 80);
    ml->addWidget(l);
    ml->addWidget(customcolors);
    palettetoolbar->insertWidget(ID_CUSTOM_COLORS, iw, customColorsWidget);

    return true;
}

bool KIconEdit::setupStatusBar()
{
    Properties *pprops = KIconEditProperties::self()->properties();
    statusbar = statusBar();

    statusbar->insertItem("    -1, -1    ", 0);
    statusbar->insertItem("   32 x 32   ", 1);
    statusbar->insertItem(" 1:1000 ", 2);
    statusbar->insertItem("Colors:       ", 3);
    statusbar->insertItem("", 4);

    if(pprops->statusbarstat)
        statusbar->show();
    else
        statusbar->hide();
    return true;
}

bool KIconEdit::setupWhatsThis()
{ 

  kdDebug() << "setupWhatsThis" << endl;

  // Create help for the custom widgets

  QString str = i18n("Icon draw grid\n\nThe icon grid is the area where you draw the icons.\n"
                 "You can zoom in and out using the magnifying glasses on the toolbar.\n"
                 "(Tip: Hold the magnify button down for a few seconds to zoom to a predefined scale");
  QWhatsThis::add(grid, str);

  str = i18n("Rulers\n\nThis is a visual representation of the current cursor position");
  QWhatsThis::add(gridview->hruler(), str);
  QWhatsThis::add(gridview->vruler(), str);

  str = i18n("Statusbar\n\nThe statusbar gives information on the status "
             "of the current icon. The fields are:\n\n"
             "\t- Cursor position\n"
             "\t- Size\n"
             "\t- Zoom factor\n"
             "\t- Number of colors\n"
             "\t- Application messages");

  QWhatsThis::add(statusbar, str);

  str = i18n("Preview\n\nThis is a 1:1 preview of the current icon");
  QWhatsThis::add(preview, str);

  str = i18n("System colors\n\nHere you can select colors from the KDE Icon Palette.");
  QWhatsThis::add(syscolors, str);

  str = i18n("Custom colors\n\nHere you can build a palette of custom colors.\n"
             "Double-click on a box to edit the color");
  QWhatsThis::add(customcolors, str);

  // Create help for the main toolbar

  str = i18n("Zoom out\n\nZoom out by one.\n\n"
             "(Tip: Hold the button down for a few seconds to zoom to a predefined scale");
  QWhatsThis::add(toolbar->getButton(ID_VIEW_ZOOM_OUT), str);

  str = i18n("Zoom in\n\nZoom in by one.\n\n"
             "(Tip: Hold the button down for a few seconds to zoom to a predefined scale");
  QWhatsThis::add(toolbar->getButton(ID_VIEW_ZOOM_IN), str);

  str = i18n("Toggle grid\n\nToggles the grid in the icon edit grid on/off");
  QWhatsThis::add(toolbar->getButton(ID_OPTIONS_TOGGLE_GRID), str);

  kdDebug() << "setupWhatsThis - done" << endl;
  return true;
}

void KIconEdit::addRecent(const QString & path)
{
    KRecentFilesAction* recent = dynamic_cast<KRecentFilesAction*>
                                                    (actionCollection()->action(KStdAction::stdName(KStdAction::OpenRecent)));

    if (recent)
    {
        recent->addURL(path);
    }
    return;
}

#include "kiconedit.moc"
