/***************************************************************************
 * $Id: tork.h,v 1.115 2009/08/12 19:41:23 hoganrobert Exp $
 *   Copyright (C) 2006 - 2008 Robert Hogan                                *
 *   robert@roberthogan.net                                                *
 *                                                                         *
 *   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 General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.              *
 ***************************************************************************/


#ifndef _TORK_H_
#define _TORK_H_

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <kapplication.h>
#include <kmainwindow.h>
#include <ktempfile.h>

#include "torkview.h"
#include "torclient.h"
#include "statgraph.h"
#include "popupMessage.h"
#include "torkconfig.h"
#include "version.h"
#include "dcoptork.h"
#include "testprivacyproxy.h"

#include <kconfigskeleton.h>
#include <kwinmodule.h>
#include <kpopupmenu.h>
#include <qvaluevector.h>

#include "update.h"
#include "trayicon.h"
#include "upnpmanager.h"
#include "hiddensrvs.h"

class KPrinter;
class KToggleAction;
class KPopupMenu;
class KActionMenu;
class KURL;
class TrayIcon;
class QLabel;
class KProcIO;
class TorClient;
class QPoint;
class StatGraph;
class TorkConfig;
class KConfigSkeleton;
class KConfigSkeletonItem;
class KTempFile;
class KWindModule;
class UPnPManager;
class SetMaxRate;
class MyHidden;
class TestProxy;

//class QValueVector;

/** Enumeration of types which option values can take */
typedef enum display_status_t {
  DISPLAY_NONE = 0,   /**< An arbitrary string. */
  DISPLAY_QUEUED,         /**< A non-negative integer less than MAX_INT */
} display_status_t;



/**
 * This class serves as the main window for tork.  It handles the
 * menus, toolbars, and status bars.
 *
 * @short Main window class
 * @author Robert Hogan <robert@roberthogan.net>
 * @version 0.03
 */
class tork : public KMainWindow, virtual public DCOPTork
{
    Q_OBJECT
public:
    /**
     * Default Constructor
     */
    tork();

    /**
     * Default Destructor
     */
    virtual ~tork();

    torkView *m_view;

    TrayIcon *_tray;
    QDict<QListViewItem> inodes;
    bool connectedToTor(){return (client!=0) ? true : false;};
    KPopupMenu* m_LaunchMenu;
    void anonymousFirefox(){m_view->anonymousFirefox();};
    void anonymousOpera(){m_view->anonymousOpera();};
    void anonymousEmail(){m_view->sendAnonymousEmail(); hide();};
    void anonymizedFirefox(const QString & url){m_view->anonymizedFirefox(url);};
    void anonymizedOpera(const QString & url){m_view->anonymizedOpera(url);};
    void anonymousKonversation(){torkify( 0 );};
    void anonymousKopete(){torkify( 1 );};
    void anonymousGaim(){torkify( 2 );};
    void anonymousPidgin(){torkify( 3 );};
    void anonymousKonsole(){torkify( 4 );};
    bool getKDESetting();
    bool routerDiscovered(){ return m_routerDiscovered;};
    void setRouterDiscovered(bool discovered){ m_routerDiscovered = discovered;};

    QStringList getDiscoveredRouters(){ return discoveredRouters;};
    void setBandwidthFromSysTray(int rate );
    void enableKDEAndLaunchKonqWithUrl(const QString &);
    int upnpORPort(){ return orPort; };
    int upnpDirPort(){ return dirPort; };
    void setUpnpDirPort(int port){ dirPort=port; };
    void setUpnpORPort(int port){ orPort=port; };

private slots:
    void fileNew();
    void optionsShowToolbar();
    void optionsShowStatusbar();
    void optionsConfigureKeys();
    void optionsConfigureToolbars();
    void optionsPreferences();
    void newToolbarConfig();
    void startTor();
    void startNetStat();
    void stopNetStat();
    void updatePrivoxy();
    void childExited();
    void privoxyExited();
    void netStatExited();
    void filterExited();
    void startFromBeginning();
    void isControllerWorking( );
    void checkRouterDiscovered( );

    
    void changeStatusbar(const QString& in,const QString& out);
    void changeCaption(const QString& text);
    void startController();
    void stopController();
    void receivedOutput(KProcIO *);
    void processFilter(KProcIO *filterproc);
    void receivedNetStatOutput(KProcIO *);
    void toggleKDESetting();
    void enableKDE(bool enable);
    void toggleKDESettingAndLaunchKonq();
    void setKDE(bool set);
    void turnOffKDE();
    void sayWhatImDoing(const QString& );
    void slotOnItem( int, QListViewItem *, const QPoint &, int );
    void slotOnORItem( QListViewItem * );
    void slotOffItem( );
    void openConfig(const QCString& page);

    void slotHandle(/*TFunctor *functor*/);
    void noClicked(/*TFunctor *functor*/);
    void popUpClosed();
    void processHashProc(KProcIO *hashproc);
    void toggleTorMon();
    void toggleTorMon2();
    void toggleTorBar();
    void hiddenServices();
    void mixminionHome();
    void networkList();
    void infoUpdated(const QString &type, const QString &summary, const QString &data);
    void shuttingDown();
    void showMyServer();
    void showFirewallEvasion();
    void useNewIdentity();
    void showMyKonqueror();
    void showMyHiddenServices();
    void toggleNonTorTraffic(bool state);
    void toggleTorTraffic(bool state);
    void checkForKonqWindow(WId);
    void configurePrivoxy();
    void warnNoServerInfo();
    void startingPeriodOver();
    void needAlphaVersion( );
    void filterServers( int );
    void toggleIP( int );
    void filterLog( int );
    void filterSubnets( int );
    void filterCountries( int );
    void filterTorTraffic( int );
    void filterNonTorTraffic( int );
    void sortByCountry( );
    void toggleTextFilter( int );
    void createSubnetList( );
    void torkify( int );
    void allowNewIdentityRequests();
    void populateSubNetMenu();
    void populatePseudoMenu();
    void populateCountryMenu();
    void applyPseudonymity( int country_id );
    void checkBandwidthSettings();
    void setTorCaption(const QString &caption);
    void configureServer(int);
    void configureSecurity( int id );
    void updateServerButton( );
    void torUsedAfterDNSRequest();
    void updateTrayStats(const QString &,const QString &,const QString &,const QString &);
    void updateTrayIcon(const QString &);
    void resetExited();
    void switchMode();
    void upnpForwardingOK(kt::UPnPRouter*,const QString &, bool);
    void upnpForwardingError(kt::UPnPRouter*,const QString &, bool);
    void routerDiscovered(kt::UPnPRouter* );
    void configureRouter(bool force,bool silent=false);
    void checkForSystemManagedPrivoxy();
    void cannotContactPrivoxy();
    void privacyProxyPassed();

public slots:

    void startPrivoxy();
    void letTorKManagePrivoxy();
    void serverHelp(); 
    void enterContactInfo();
    void fixAddressPort();
    void continueAsClient();
    void updateTorStable();
    void reconnectWithCookie();
    void copyCookie();
    void updateTork();
    void quickConfig();
    void cannotContactTor();
    void showTip();
    void showTipOnStart();
    void runWizard(); 
    void copyOldConfig();
    void shouldIApplySettings();
    void applySettingsToRunningTor();
    bool showUsage();
    bool showSecurityWarnings();
    bool showGuideQuestions();
    bool showApplySettingsQuestions();
    bool contactInfoSet();
    bool showDNSLeaks();
    void readEavesdropping();
    void aboutTorify();
    void aboutTor();
    void showSecurityNotice(const QString &port);
    void showScreamingNotice(const QString &port);
    void torClosedConnection();
    void makeTorkStoppable();
    void createService(const QString& dir,const QString& port);
    void aboutParanoidMode();
    void processWarning(const QString& type, const QString& text);
    void processQuestion(const QString& type, const QString& text);
    void updateTorUnstable(); 
    void currentTabChanged(QWidget* cur );
    void stopTor();
    void resetTor();
    void toggleServerButton( bool on );
    void dummyAction();
    void retryUPnP();
    void allowPlainTextPorts();
    void assignPortToRemove();
    void startEverything();
    void stopTorGracefully();

private:
    void setupAccel();
    void setupActions();
    QString writeConf();
    QString writePrivoxyConf();
    void writeCustomOptions(QTextStream &ts);
    void writeCustomOptions2(QTextStream &ts);
    void showWarning( display_status_t &msg, const QString &headline,const QString &torsaid,const QString &thismeans, const QString &type, const QString &icon, bool always, bool showstopper);
    void askQuestion(display_status_t &msg, const QString &headline,const QString &torsaid,const QString &body,const QString &question,void (tork::*pt2Func)(), const QString &type, const QString &icon, bool persistent, bool showstopper);
    void processQueue();
    bool elementShouldBeUsed(const KConfigSkeletonItem* it);
    bool noSpecialProcessing(const KConfigSkeletonItem* it, QTextStream &ts);
    QString doHashPassword();
    bool queryClose();
    void prepareToShut();
    void filterViewServers( QValueVector<QString> &possibleValues, QListView* &view, KPopupMenu* &menu, int id, int column );
    void filterView( QValueVector<QString> &possibleValues, QListView* &view, KPopupMenu* &menu, int id, int column );
    QString createFailSafeCommand( const QStringList &filterRules, bool set );
    void updateServerClientStatusBar(const QStringList &client, const QStringList &server);
    void updateToolBar();

private:

    KPrinter   *m_printer;
    KToggleAction *m_toolbarAction;
    KToggleAction *m_statusbarAction;
    KAction *torkConfigure;
    KAction *torkStop;
    KAction *torkStart;
    KAction *torkUpdateTork;
    KAction *torkUpdateStable;
    KAction *torkUpdateUnstable;
    KAction *torkUpdatePrivoxy;
    KAction *torkFirstRunWizard;
    KAction *torkTip;
    KAction *enableKonqi;
    KAction *enableTormon;
    //KAction *toggleParanoid;
    KAction *browseHiddenServices;
    KAction *browseNetworkList;
    KAction *toggleTorbar;
    KActionMenu* m_ServerFilterButton;
    KActionMenu* m_LaunchMenuButton;
    KActionMenu* m_LogFilterButton;
    KActionMenu* m_TrafficFilterButton;
    KPopupMenu* m_ServerFilterMenu;
    KPopupMenu* m_LogFilterMenu;
    KPopupMenu* m_TrafficFilterMenu;
    KPopupMenu* m_TorTrafficFilterMenu;
    KPopupMenu* m_NonTorTrafficFilterMenu;
    KPopupMenu* m_IPFilterMenu;
    KPopupMenu* m_PseudoMenu;
    KPopupMenu* m_PseudoMenuEU;
    KPopupMenu* m_PseudoMenuSA;
    KPopupMenu* m_PseudoMenuAS;
    KPopupMenu* m_PseudoMenuNA;
    KPopupMenu* m_PseudoMenuAN;
    KPopupMenu* m_PseudoMenuAF;
    KPopupMenu* m_PseudoMenuNN;
    KPopupMenu* m_PseudoMenuOC;
    KActionMenu* m_PseudoButton;
    KAction* m_IdentityButton;
    KAction* m_ModeButton;
    KAction* m_UnCensorButton;
    KPopupMenu* m_CountryMenu;
    KPopupMenu* m_CountryMenuEU;
    KPopupMenu* m_CountryMenuSA;
    KPopupMenu* m_CountryMenuAS;
    KPopupMenu* m_CountryMenuNA;
    KPopupMenu* m_CountryMenuAN;
    KPopupMenu* m_CountryMenuAF;
    KPopupMenu* m_CountryMenuNN;
    KPopupMenu* m_CountryMenuOC;
    KActionMenu* m_ServerButton;
    KPopupMenu* m_ServerButtonMenu;
    KActionMenu* m_SecurityButton;
    KPopupMenu* m_SecurityButtonMenu;

	QLabel* m_statusInfo;
	QLabel* m_statusTransfer;
	QLabel* m_statusSpeed;
	StatGraph* m_graphIn;
	StatGraph* m_graphOut;
    KProcIO* childproc;
    KProcIO* filterproc;
    KProcIO* netstatproc;
    KProcIO* privoxyproc;
    TorClient* client;
    bool m_servererrornag;
    bool m_contactinfonag;
    bool m_serverworking;
    QListViewItem* m_prevItem;
    QTimer *timer;
    QTimer *bwtimer;
    QTimer *bwLimitTimer;
    void (tork::*m_pt2Func)();
    KDE::PopupMessage *m_tooltip;
    QStringList m_list;
    QString m_body;
    display_status_t* m_msg;
    KProcIO *hashproc;
    QString m_hashedpassword;
    KConfigSkeletonItem::List previtems;
    KConfigSkeleton pcopy;
    PrevConfig::PrevConfigList prevlist;
    TorkUpdate* updater;
    KTempFile* tfTor;
    KTempFile* tfPrivoxy;
    KWinModule* winModule;
    QWidget* prev;

    QValueList<QListViewItem*> ordinaryServerList;
    QMap<QString,KPopupMenu*> continentMap;
    QMap<QString,KPopupMenu*> continentMapList;
    QStringList discoveredRouters;

    int filterId;

    bool m_toolTipShowing;
    bool m_persistent;
    bool filterWasApplied;
    bool geoip_db;
    bool waitingForServers;
    bool stillStarting;
    bool m_DNSTorified;
    bool m_showstopperAlreadyDisplayed;
    bool m_routerDiscovered;
    bool recentNewIdentityRequest;
    bool m_ShutdownRequested;
    bool m_AppliedSettings;
    bool m_CanApplyServerSettingsIfSet;

    QDialog* dialog;
    MyHidden* myHiddenDialog;
    QDialog* serverdialog;

    UPnPManager* upnpmanager;
    ForwardPortList* forwardPortList;

    QString filterError;
    QString torCaption;
    QString m_program;

	SetMaxRate* m_set_max_rate;

    TestPrivoxy *privoxytest;
    int orPort;
    int dirPort;

};


extern tork *kmain;

#endif // _TORK_H_

