/* This file is part of the KDE project
   Copyright (C) 2001 Holger Freyther <freyther@yahoo.com>
   Icon stroing inspired by Matthias Elters browser_mnu.* (currently not used)

   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; version 2
	 of the License.

   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 <tqiconset.h>
#include <tqdir.h>
#include <tqfileinfo.h>

#include <tdeaction.h>
#include <tdeapplication.h>
#include <kiconloader.h>
#include <tdeio/global.h>
#include <tdelocale.h>
#include <kurl.h>
#include <ksimpleconfig.h>
#include "kdirmenu.h"

#define CICON(a) (*_icons)[a]

TQMap<TQString, TQPixmap> *KDirMenu::_icons = 0;

KDirMenu::KDirMenu ( TQWidget *parent, const KURL &_src,
            const TQString &_path, const TQString &_name, bool /*showfile*/ )
    : TQPopupMenu(parent),
      path(_path),
      name(_name),
      src( _src ),
      action( 0 )
{
    children.setAutoDelete( true );
    initIconMap( );
    connect( this, TQT_SIGNAL( aboutToShow( ) ), this, TQT_SLOT( slotAboutToShow( ) ) );
    connect( this, TQT_SIGNAL( aboutToHide( ) ), this, TQT_SLOT( slotAboutToHide( ) ) );
    children.clear(); // just in case

    TQFileInfo fileInfo(path);
    if (( src.path() != path || !src.isLocalFile()) && fileInfo.isWritable())
        action = new TDEAction(name, 0, TQT_TQOBJECT(this), TQT_SLOT(new_slot( ) ), TQT_TQOBJECT(this));
}
KDirMenu::~KDirMenu( ) {
    delete action;
    clear( );
    children.clear( );
}
void KDirMenu::insert( KDirMenu *submenu, const TQString &_path ) {
    static const TQIconSet folder = SmallIconSet("folder");
    TQString escapedPath = _path;
    TQString completPath=path+'/'+_path;
    // parse .directory if it does exist
    if (TQFile::exists(completPath + "/.directory")) {

        KSimpleConfig c(completPath + "/.directory", true);
        c.setDesktopGroup();
        TQString iconPath = c.readEntry("Icon");

        if ( iconPath.startsWith("./") )
           iconPath = _path + '/' + iconPath.mid(2);
        TQPixmap icon;
        icon = TDEGlobal::iconLoader()->loadIcon(iconPath,
                                               TDEIcon::Small, TDEIcon::SizeSmall,
                                               TDEIcon::DefaultState, 0, true);
        if(icon.isNull())
           icon = CICON("folder");
        insertItem( icon, escapedPath.replace( "&", "&&" ), submenu );
    }
    else
        insertItem( folder, escapedPath.replace( "&", "&&" ), submenu );
    children.append( submenu );
    connect(submenu, TQT_SIGNAL(fileChosen(const TQString &)),
            this, TQT_SLOT(slotFileSelected(const TQString &)));
}

void KDirMenu::slotAboutToShow( ) {

    // ok, prepare the dir: list all dirs and insert the new menus
    if (count() >= 1) return;

    //Precaution: if not a directory, exit, in case some path in KMetaMenu
    //isn't checked right
    if ( !TQFileInfo(path).isDir() )
        return;

    if ( action )
        action->plug( this );
    else
	setItemEnabled( insertItem( name ), false );

    // all dirs writeable and readable
    TQDir dir(path, TQString(),
             TQDir::Name | TQDir::DirsFirst | TQDir::IgnoreCase,
             TQDir::Dirs | TQDir::Readable | TQDir::Executable);

    const TQFileInfoList* dirList = dir.entryInfoList();
    if ( !dirList || dirList->isEmpty() ) {
        if ( action )
            action->setEnabled( false );
	return;
    }

    insertSeparator( );

    if (dirList->count() == 2) {
        insertItem(i18n("No Sub-Folders"), 0);
        setItemEnabled(0, false);
        return;
    }

    static const TQString& dot = TDEGlobal::staticQString( "." );
    static const TQString& dotdot = TDEGlobal::staticQString( ".." );

    for ( TQFileInfoListIterator it( *dirList ); *it; ++it ) {
        TQString fileName = (*it)->fileName();
        if ( fileName == dot || fileName == dotdot )
            continue;
            
        KURL u;
        u.setPath((*it)->absFilePath());
        if (kapp->authorizeURLAction("list", u, u))
        {
           insert(new KDirMenu(this, src, (*it)->absFilePath(), name),
			TDEIO::decodeFileName( fileName ));
	}
    }
}
void KDirMenu::slotAboutToHide( ) {

}
void KDirMenu::initIconMap()
{
    if(_icons) return;

//    kdDebug(90160) << "PanelBrowserMenu::initIconMap" << endl;

    _icons = new TQMap<TQString, TQPixmap>;

    _icons->insert("folder", SmallIcon("folder"));
    _icons->insert("unknown", SmallIcon("mime_empty"));
    _icons->insert("folder_open", SmallIcon("folder_open"));
    _icons->insert("kdisknav", SmallIcon("kdisknav"));
    _icons->insert("kfm", SmallIcon("kfm"));
    _icons->insert("terminal", SmallIcon("terminal"));
    _icons->insert("txt", SmallIcon("text-plain"));
    _icons->insert("exec", SmallIcon("application-x-executable"));
    _icons->insert("chardevice", SmallIcon("chardevice"));
}
void KDirMenu::slotFileSelected(const TQString &_path ){
    emit fileChosen( _path );
}

void KDirMenu::new_slot() {
    emit fileChosen(path );
}

#include "kdirmenu.moc"
