/***************************************************************************
                          c6.cpp  -  description
                             -------------------
    begin                : Fri Feb 14 16:20:30 CET 2003
    copyright            : (C) 2003 by Giorgio A.
    email                : openc6@hotmail.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#include <qwidget.h>
#include <qapplication.h>
#include <qmessagebox.h>
#include <qcstring.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qinputdialog.h>
#include <qstring.h>
#include <qdir.h>
#include <qdatetime.h>
#include <qprocess.h>
#include <qtooltip.h>
#include <qfiledialog.h>
#include <qfileinfo.h>
#include <qobjectlist.h>
#include <qsound.h>
#include <qspinbox.h>
#include <qsettings.h>
#include <qlayout.h>
#include <qtimer.h>
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qpopupmenu.h>
#include <qlabel.h>
#include <qcursor.h>
#include <qtimer.h>
#include <qwidgetlist.h>
#include <qdom.h>
#include <qregexp.h>
#include <qevent.h>
#include <qstylesheet.h>
#include "c6.h"
#include "progressindicator.h"
#include "c6_main.h"
#include "c6about.h"
#include "chatview.h"
#include "c6conf.h"
#include "c6button.h"
#include "c6logview.h"
#include "c6login.h"
#include "c6search.h"
#include "c6profile.h"
#include "c6report.h"
#include "c6nicklist.h"
#include "c6smiley.h"
#include "c6roomlist.h"
#include "c6chatroom.h"
#include "c6logger.h"
#include "c6settings.h"
#include "c6tabwidget.h"
#include "c6pixmapcache.h"
#include "c6users.h"
#include "c6chatfactory.h"


#if !defined(Q_OS_MACX) && !defined(Q_OS_DARWIN)
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/scrnsaver.h>
#else
#include <Carbon/Carbon.h>
#endif

#define NICKSTR "nickname"
#define PASSWSTR "password"
#define ERRORSTR "error"
#define OLDNICKSTR "oldnick"
#define NO_NICK_AVAILABLE "Nessun nick disponibile !"
#define IDLE_CHECK_INTERVAL 2000
#define MAXPORTSCAN 1800

#define BLACKANSWMSG "Replied with blackList message"
#define NETFRIENDANWMSG "Replied with only netfriend message"
#define BUSYANSWMSG "Replied with busy message"
#define AWAYANSWMSG "Replied with away message"
#define ACCEPT_DENYMSG QString::fromUtf8("La richiesta di invio file è stata rifiutata");
#define ACCEPT_DENYSERVICEMSG QString::fromUtf8("La richiesta di ricezione file è stata rifiutata")
#define ACCEPT_SERVICEMSG QString::fromUtf8("La richiesta di ricezione file è stata accettata")

#define ENTER_ROOM_MSG(nick) QString("Il netfriend <b>")+nick+QString::fromUtf8("</b> è appena entrato in questa stanza")
#define EXIT_ROOM_MSG(nick) QString("Il netfriend <b>")+nick+QString::fromUtf8("</b> è appena uscito da questa stanza")
#define INVITEMESS(room,mess) QString("ti invita ad entrare nella stanza \"room://")+room+"\" - "+mess
#define KICKBANNED_ROOM_MSG QString::fromUtf8("A causa di un <b>kick</b> o un <b>ban</b> non sei più attivo in questa stanza.")
#define ADD_TO_WHITELIST_MSG(user) QString::fromUtf8("L'utente <b>"+user+"</b> è stato autorizzato!")

#define NO_LISTMSG QString::fromUtf8("Non è stata trovata nessuna lista contatti esistente !")
#define ACCEPT_FILE_STR(nickname) QString("ti sta mandando un file lo accetti ? c6cmd://Accept?Type=FILE&Value=YES c6cmd://Accept?Type=FILE&Value=NO")

static const QString OFFLINESTR = QString::fromUtf8("L'utente non è online.\nPuoi lasciare un messaggio.\n");
static const QString ONOFFLINESTR = QString::fromUtf8("L'utente con cui stavi chattando non è più online.\nPuoi lasciare un messaggio.\n");
static const QString OFFONLINESTR = QString::fromUtf8("L'utente con cui stavi chattando è di nuovo online.\n");
static const QString AUTO_RECEIVE_ENABLED = "Ricezione automatica abilitata";
static const QString MERGE_MSG = "\tLa lista degli amici locale (nick.lst) sta per essere trasferita sul server\n\t\t\t"
                          "     Vuoi procedere ?";
static const QString FIRST_ATTEMPT_STR_BEGIN =QString::fromUtf8("Questo è il primo accesso con il nick selezionato con la nuova versione di OpenC6.\n\n");                          
static const QString FIRST_ATTEMPT_STR_END = QString::fromUtf8("\n\nP.S. l'operazione può essere anche eseguita dopo l'accesso mediante la funzione\n "
        "\"Importa Lista\" dal menu principale.");         
static const QString WARN_NICK_LENGTH = QString::fromUtf8("La lunghezza del nick deve essere più grande di un carattere !");
static const QString WARN_NICK_FORMAT = "Formato del nick non corretto !!\nPuoi usare le lettere dell'alfabeto minuscole\nnumeri e i caratteri speciali . - _";

#if defined(Q_OS_MACX) || defined(Q_OS_DARWIN)

typedef OSStatus (*idleTimerFunctionPtr)(EventLoopRef inEventLoop,
        EventTimerInterval   inFireDelay,
        EventTimerInterval   inInterval,
        EventLoopIdleTimerUPP    inTimerProc,
        void *               inTimerData,
        EventLoopTimerRef *  outTimer);

static unsigned secondsIdle = 0;
static EventLoopTimerRef timerRef;

static OSStatus loadFramework(CFStringRef framework, CFBundleRef *bundlePtr)
{
    if (bundlePtr == nil )
    {
        return(-1);
    }

    FSRef   frameworksFolderRef;
    CFURLRef baseURL = nil;
    CFURLRef bundleURL = nil;
    *bundlePtr = nil;

    OSStatus err = FSFindFolder(kOnAppropriateDisk, kFrameworksFolderType, true, &frameworksFolderRef);

    if (err == noErr)
    {
        baseURL = CFURLCreateFromFSRef(kCFAllocatorSystemDefault, &frameworksFolderRef);
        if (baseURL == nil)
        {
            err = coreFoundationUnknownErr;
        }
    }

    if (err == noErr)
    {
        bundleURL = CFURLCreateCopyAppendingPathComponent(kCFAllocatorSystemDefault, baseURL, framework, false);
        if (bundleURL == nil)
        {
            err = coreFoundationUnknownErr;
        }
    }

    if (err == noErr)
    {
        *bundlePtr = CFBundleCreate(kCFAllocatorSystemDefault, bundleURL);
        if (*bundlePtr == nil)
        {
            err = coreFoundationUnknownErr;
        }
    }

    if (err == noErr)
    {
        if ( ! CFBundleLoadExecutable( *bundlePtr ) )
        {
            err = coreFoundationUnknownErr;
        }
    }

    if (err != noErr && *bundlePtr != nil)
    {
        CFRelease(*bundlePtr);
        *bundlePtr = nil;
    }

    if (bundleURL != nil)
    {
        CFRelease(bundleURL);
    }

    if (baseURL != nil)
    {
        CFRelease(baseURL);
    }

    return err;
}

pascal void idleTimerCheck(EventLoopTimerRef, EventLoopIdleTimerMessage status, void*)
{
    switch (status)
    {
    case kEventLoopIdleTimerStarted:
    case kEventLoopIdleTimerStopped:
        secondsIdle = 0;
        break;
    case kEventLoopIdleTimerIdling:
        secondsIdle++;
        break;
    }
}
#endif

static C6Users* getNetFriendPtr(QString const& name);
static void setNetfriendMessaged(QString const& name);
bool skipThis = false;
bool awayState = false;
bool connected = false;
bool isFirstLogin = false;
int safeInitCounter = 0;
C6Users::C6USER_STATUS previousState = C6Users::U_NOTPRESENT;

static QString getCurrentTimeStr()
{
    QString loc = QTime::currentTime(Qt::LocalTime).toString();
    return(loc);
}

C6* C6::_self = 0;

C6* C6::getInstance()
{
    if( !_self )
    {
        _self = new C6();
    }
    return _self;
}

C6* C6::self()
{
    return _self;
}

C6::C6():
        loginDialog(0),
        _startedApp(false),
        _idleTimer(0),
        _global(0)
{
    _global = static_cast<C6Global*>(&(C6Global::getInstance()));
    C6Settings &settings = C6Settings::getInstance();
    _global->setRoomListPtr((void*)&chatRoomList);
    settings.loadSettings();
    
    calibrateSystemFontSize();     
    _global->initialize();
    
    C6Smiley::loadSmiley();
    C6Logger::getInstance();

    initTabStuff();

    loginDialog = new C6Login();
    connect(loginDialog,SIGNAL(startConnect(bool)),this,SLOT(ConnectClicked(bool)));
    connect(loginDialog,SIGNAL(exitClicked()),this,SLOT(exitClicked()));
    connect(loginDialog,SIGNAL(openConfig()),this,SLOT(openConfig()));
    connect(loginDialog,SIGNAL(showAbout()),this,SLOT(showAbout()));
    connect(loginDialog,SIGNAL(forceClose()),this,SLOT(exitClicked()));

    loadLoginAccounts();

    _c6socket = new C6Proto(this);
    connect(_c6socket,SIGNAL(signalOnline()),this,SLOT(imOnLine()));
    connect(_c6socket,SIGNAL(SignalOffline(bool)),this,SLOT(closeConnection(bool)));
    connect(_c6socket,SIGNAL(signalError(int,const QString&)),this,SLOT(signalError(int,const QString&)));
    connect(_c6socket,SIGNAL(messageReceived(QString&, QString&,C6Proto::C6MessageStyle*)),this,SLOT(receiveChatMessage(QString&,QString&,C6Proto::C6MessageStyle*)));
    connect(_c6socket,SIGNAL(notifyStatus(C6Users::C6UsersVector &,bool)),this,SLOT(updateNetFriendStatus(C6Users::C6UsersVector &,bool)));
    connect(_c6socket,SIGNAL(SysLog(QString)),this,SLOT(WriteOnSystemLog(QString)));
    connect(this,SIGNAL(requestProfile(const QString&)),_c6socket,SLOT(requestProfile(const QString&)));
    connect(_c6socket,SIGNAL(fireConnection(QHostAddress,int,QString,QString)),this,SLOT(fireConnection(QHostAddress,int,QString,QString)));
    connect(_c6socket,SIGNAL(prepareFileReception(QString&,QString&)),this,SLOT(prepareFileReception(QString&,QString&)));
    connect(_c6socket,SIGNAL(nowSelectUser(unsigned char *)),this,SLOT(nowSelectUser(unsigned char *)));
    connect(_c6socket,SIGNAL(roomEnterInfo(const QString&,const QString&,int,int,QMap<QString,int>&)),this,SLOT(roomEnterInfo(const QString&,const QString&,int,int,QMap<QString,int>&)));  
    connect(_c6socket,SIGNAL(eventFromRoom(QString&,QString&,C6Proto::SERVER_COMMAND_ID)),this,SLOT(eventFromRoom(QString&,QString&,C6Proto::SERVER_COMMAND_ID)));
    connect(_c6socket,SIGNAL(messageFromRoom(QString&, QString&, QString&)),this,SLOT(messageFromRoom(QString&, QString&, QString&)));
    connect(_c6socket,SIGNAL(searchResultReady(std::vector<C6Proto::RoomSearchResult>&)),this,SLOT(searchResultReady(std::vector<C6Proto::RoomSearchResult>&)));
    connect(_c6socket,SIGNAL(notifyInfoResult(const QString &,unsigned char*,int,bool)),this,SLOT(getUserInfo(const QString &,unsigned char*,int,bool)));
    connect(_c6socket,SIGNAL(infoLogin(bool)),this,SLOT(infoLogin(bool)));
    connect(_c6socket,SIGNAL(extendedChangeStatus(const C6Users::C6Users &)),
            this,SLOT(extendedChangeStatus(const C6Users::C6Users &)));
    connect(_c6socket,SIGNAL(parseBuddyList(QByteArray&)),this,SLOT(parseBuddyList(QByteArray& )));
    connect(_c6socket,SIGNAL(parseBuddyAuth(QByteArray&)),this,SLOT(parseBuddyAuth(QByteArray& )));
    connect(_c6socket,SIGNAL(parseBuddyConfig(QByteArray&)),this,SLOT(parseBuddyConfig(QByteArray& )));
    connect(_c6socket,SIGNAL(askForPassword(const QString&)),this,SLOT(askForPassword(const QString&)));
    
    mainDialog = new C6_Main();
    connect(mainDialog,SIGNAL(SendClose()),this,SLOT(clientExit()));
    connect(mainDialog,SIGNAL(ForceClose()),this,SLOT(restoreLogin()));
    connect(mainDialog,SIGNAL(userMenuAction(const QString &,USER_MENU_ACTIONS,QString)),this,SLOT(doMainAction(const QString &,USER_MENU_ACTIONS,QString)));
    connect(mainDialog,SIGNAL(buildChat(const QString &)),this,SLOT(buildChat(const QString &)));
    connect(mainDialog,SIGNAL(changeMyStatus(C6Users::C6USER_STATUS,const QString&)),SLOT(changeMyStatus(C6Users::C6USER_STATUS,const QString& )));
    connect(mainDialog,SIGNAL(signalMenuChoice(int)),this,SLOT(HandleMenuCommand(int)));
    connect(mainDialog,SIGNAL(newNickReconnect(int )),this,SLOT(reconnect(int)));
    connect(mainDialog,SIGNAL(showAbout()),this,SLOT(showAbout()));
    connect(_c6socket,SIGNAL(signalServerStats(const QString &)),
            mainDialog,SLOT(updateServerStats(const QString &)));
    
    connect(_c6socket,SIGNAL(progress(int)),SLOT(showMainDialog(int)));    
    aboutDialog = new C6About(loginDialog);
    connect(aboutDialog,SIGNAL(execUrl(QString &)),this,SLOT(execUrl(QString &)));

    reportDialog = new C6Report(loginDialog);
    connect(reportDialog,SIGNAL(execUrl(QString &)),this,SLOT(execUrl(QString &)));
    connect(reportDialog,SIGNAL(showAbout()),this,SLOT(showAbout()));
    connect(_c6socket,SIGNAL(notifyReportMessage(const QString&,const QString&,const QString&)),
            SLOT(showReport(const QString&,const QString&,const QString&))); 

    searchDialog = new C6Search(loginDialog);
    connect(searchDialog,SIGNAL(sendSearchValue(unsigned char *,C6Proto::USER_SEARCH_TYPE)),
            _c6socket,SLOT(sendSearch(unsigned char *,C6Proto::USER_SEARCH_TYPE)));
    connect(_c6socket,SIGNAL(notifySearchList(QStringList*,std::vector<C6Users::C6USER_STATUS>)),
            SLOT(userSearchResultsFound(QStringList*,std::vector<C6Users::C6USER_STATUS>)));
    connect(searchDialog,SIGNAL(searchMenuClicked(const QString &,USER_MENU_ACTIONS)),
            SLOT(userMenuAction(const QString &,USER_MENU_ACTIONS)));
    connect(searchDialog,SIGNAL(showAbout()),this,SLOT(showAbout()));
    connect(searchDialog,SIGNAL(searchByNick(const QString&)),SLOT(searchByNick(const QString&)));  

    roomList = new C6RoomList(_c6socket->getRoomCategoryVector(),0);
    connect(roomList,SIGNAL(enterRoom(const QString&)),this,SLOT(enterRoom(const QString&)));
    connect(roomList,SIGNAL(createRoom(const QString&,const QString&,bool,int,const QString&)),     
            this,SLOT(createRoom(const QString&,const QString&,bool,int,const QString&)));
    connect(roomList,SIGNAL(searchFilteredRoom(int,unsigned char *)),SLOT(searchRoom(int,unsigned char *)));
    connect(roomList,SIGNAL(showAbout()),SLOT(showAbout()));
    connect(roomList,SIGNAL(inviteSelected(const QString &,const QStringList &,const QString &)),
            SLOT(inviteNetfriend(const QString &,const QStringList &,const QString &)));
    
 
    setFontOnWidgets();   
    
    if (settings.getAutoConnect() && (loginDialog->getLogin().length()) > 0 &&
            (loginDialog->getPassword().length() > 0))
    {
        startConnection();
    }
    else
    {
        loginDialog->show();
    }

    _idleTimer = new QTimer(this);
    connect(_idleTimer,SIGNAL(timeout()),this,SLOT(checkIfIdle()));
    
#if defined(Q_OS_MACX) || defined(Q_OS_DARWIN)

    CFBundleRef carbonBundle;
    if (loadFramework(CFSTR("Carbon.framework"), &carbonBundle ) == noErr)
    {
        idleTimerFunctionPtr idleTimer = (idleTimerFunctionPtr)CFBundleGetFunctionPointerForName(carbonBundle, CFSTR("InstallEventLoopIdleTimer"));
        if (idleTimer != nil)
        {
            EventLoopIdleTimerUPP timerUPP = NewEventLoopIdleTimerUPP(idleTimerCheck);
            (*idleTimer)(GetMainEventLoop(),kEventDurationSecond,kEventDurationSecond,timerUPP,0,&timerRef);
        }
    }
#endif
}

C6::~C6()
{
    delete _c6socket;
    delete mainDialog;
    delete loginDialog;
    delete roomList;
    delete tabLayout;
    delete tabbedDialog;

    C6PixmapCache::destroyInstance();
    C6Settings::destroyInstance();
    C6Logger::destroyInstance();
}

QWidget* C6::getMainDialogPtr()
{
    return(mainDialog);
}

void C6::ConnectClicked(bool ok)
{
    if (ok == true)
    {
        startConnection();
    }
    else
    {
        messageBox("Errore","Tutti i campi devono essere compilati !");
    }
}

void C6::startConnection()
{
    const QString loginID = loginDialog->getLogin();
    const QString passw = loginDialog->getPassword();

    ProgressIndicator *Connect = new ProgressIndicator(loginDialog);
    connect(Connect,SIGNAL(forceClose()),this,SLOT(restoreLogin()));
    connect(_c6socket,SIGNAL(progress(int)),Connect,SLOT(setProgress(int)));

    if (loginID.contains("@") == false)                      /* tricky but easy */
    {
        _c6socket->setOldAccountMode(true);
        mainDialog->setOwnerName(loginID);
    }
    else
    {
        _c6socket->setOldAccountMode(false);
    }

    mainDialog->setOnlineStatus(C6Settings::getInstance().getStatus());

    fastReconnect = false;
    loginDialog->hide();                                  /* hide login win */
    Connect->show();                                      /* show connecting win */

    initConnection(loginID,passw);
}

void C6::initConnection(QString const & nick,QString const &passw)
{
    C6Users::C6USER_STATUS initStatus = mainDialog->getOnlineStatus();
    _c6socket->setInitialStatus(initStatus,C6Settings::getInstance().getIpVisible());
    _c6socket->startConnection(nick,passw);
    emit statusChanged(initStatus);
}


/** Display error messages text */
int C6::messageBox(QString const & cap,QString const & text)
{
    qApp->beep();
    QMessageBox box(cap,text,QMessageBox::Warning,
                    QMessageBox::Ok,QMessageBox::NoButton,
                    QMessageBox::NoButton,loginDialog);
    return(box.exec());
}

/** Show the about dialog */
void C6::showAbout()
{
    aboutDialog->show();
}
/** exit the application and save config  */
void C6::exitClicked()
{
    emit exit_main();
}

/** Store login and password  */
void C6::saveCurrentUserDetails()
{
    C6Settings::getInstance().saveLoginIdentity(loginDialog->getLogin());

    if (loginDialog->getLogin() && loginDialog->SavePwdChk->isChecked())
    {
        _global->saveCurrentIdentity(loginDialog->getLogin(),loginDialog->getPassword(),
                                    mainDialog->getMessageODD());   
    }
    else
    {
        _global->saveCurrentIdentity(loginDialog->getLogin(),QString::null,
                                    mainDialog->getMessageODD());   
    }
}
/** Load login accounts */
void C6::loadLoginAccounts()
{
    Q_ASSERT(loginDialog);

    C6Settings &settings = C6Settings::getInstance();
    QString home = QDir::homeDirPath();
    QDir curdir(home+"/"+C6DIR+"/"+C6USERSDIR+"/");

    curdir.setNameFilter("*.rc");
    curdir.setFilter(QDir::Files);
    QStringList fileList(curdir.entryList());

    int count = fileList.count();

    for (int i=0; i < count; i++)
    {
        fileList[i] = fileList[i].left(fileList[i].length()-3);
    }

    loginDialog->nickName->insertStringList(fileList);

    connect(loginDialog->nickName,SIGNAL(activated(const QString &)),this,SLOT(reloadPassword(const QString&)));

    if (count)
    {
        int i = 0;
        bool found=false;

        while (!found && (i < count))
        {
            if (loginDialog->nickName->text(i) == settings.getLastLogin())
            {
                found = true;
            }
            else
            {
                i++;
            }
        }

        if (found == true)
        {
            loginDialog->nickName->setCurrentItem(i);
            loadPassword(loginDialog->nickName->text(i));
        }
    }
}

/** This receive signal from _c6socket and show login error */
void C6::signalError(int err,const QString& error)
{
    QString message;
    QString errorStr = (error == QString::null) ? "" : error;
    
    switch (err)
    {
    case C6Proto::INVALID_NAME:
        message = "Chiave Unica non valida !";
        break;
    case C6Proto::INVALID_LOGIN:
        message = "Chiave unica inesistente o password errata !";
        break;
    case C6Proto::USER_ALREADY_LOGGED:
        message = QString::fromUtf8("Utente già collegato !");
        break;
    case C6Proto::INVALID_USER:
        message = "Nickname inesistente !";
        break;
    case C6Proto::INVALID_PASSWORD:
        message = "Password non valida !" ;
        break;
    case C6Proto::SERVER_ERROR:
        message = "Server fuori servizio o nome non valido !" ;
        break;
    case C6Proto::XFERFAIL:
        message = QString::fromUtf8("L'utente non può accettare il file o non ha attivato la ricezione !");
        break;
    case C6Proto::NONEXISTING_ROOM:
        message = QString::fromUtf8("Stanza inesistente !");
        break;
    case C6Proto::EXISTING_ROOM:
        message = QString::fromUtf8("La stanza esiste già !");
        break;
    case C6Proto::ROOM_ISFULL:
        message = QString::fromUtf8("La stanza è piena !");
        break;
    case C6Proto::ROOM_HASERROR:
        message = QString::fromUtf8("Errore di accesso alla stanza specificata:\n" + error+" !");
        break;
    case C6Proto::PROXY_METHOD_ERROR:
        message = "Metodo di autenticazione del proxy non supportato !";
        break;
    case C6Proto::PROXY_BAD_ANSWER:
        message = "Risposta dal proxy non corretta !";
        break;
    case C6Proto::PROXY_BAD_AUTH:
        message = "Autenticazione presso il proxy fallita !";
        break;
    case C6Proto::KICK_BAN_ERROR:
        message = error;    
        break;          
    }

    messageBox("Errore",message);

    switch(err)
    {
    case C6Proto::XFERFAIL:
    case C6Proto::XFERABORT:
    case C6Proto::XFERERROR:
    case C6Proto::NONEXISTING_ROOM:
    case C6Proto::EXISTING_ROOM:
    case C6Proto::ROOM_ISFULL:
    case C6Proto::ROOM_HASERROR:
    case C6Proto::KICK_BAN_ERROR:      
         break;
    default:
        restoreLogin();
    }
}


/** called when online */
void C6::imOnLine()
{
    saveCurrentUserDetails();
    mainDialog->refreshList();   
    emit online();

    awayState = false;
    previousState = C6Users::U_NOTPRESENT;
    connected = true;

    if (C6Settings::getInstance().getAutoAway() == true)
    {
        _idleTimer->changeInterval(IDLE_CHECK_INTERVAL);
    }
}

void C6::restoreLogin()
{
    _c6socket->closeSocket();
    deleteAllChat();
    deleteAllRooms();
    hideChildrenDialogs(loginDialog);
    tabbedDialog->hide();
    mainDialog->hide();
    loginDialog->show();
    setAllUsersOffline();
    _idleTimer->stop();
    _global->clearUsersList();
    reportDialog->clearReport();    
    roomList->hide();       
    mainDialog->setListType(C6_Main::NETFRIEND_LIST);
    mainDialog->refreshList(true);
    connected = false;
    safeInitCounter = 0;

    emit restoreLoginSession();
}

void setNetfriendMessaged(QString const & name)
{
    C6Users *tmp=getNetFriendPtr(name);

    if (tmp)
    {
        tmp->setMessaged(true);
    }
}

/** set user online/offline */
bool C6::setNetfriendProperty(C6Users const & c6user) //QString const & name,C6Users::C6USER_STATUS status)
{
    bool ret = false;
    C6Users *tmp=getNetFriendPtr(c6user.getNick());

    if (tmp != 0)
    {
        tmp->setStatus(c6user.getStatus());
        tmp->setDailyMessage(c6user.getDailyMessage());    
        ret = true;
    }

    return(ret);
}

/** Initialize the chat  */
ChatView* C6::buildChat(const QString & nick,bool receiveEvent)
{
    ChatView *temp = const_cast<ChatView*>(getChatViewPtr(nick));
    if (temp != 0)                      // chat view already exists
    {
        if (receiveEvent == false)
        {
            if (_global->getTabActivated())
            {
                restoreWidget(*tabbedDialog);
            }
            else
            {
                restoreWidget(*temp);
            }
        }
    }
    else
    {
        C6Settings &settings = C6Settings::getInstance();

        temp = static_cast<ChatView*>(C6ChatFactory::getChat(C6ChatFactory::PRIVATE));

        if (temp != 0)
        {
            temp->setFriendNick(nick);
            temp->setFileTransferReceivePort(getSuitableBindPort());
            _c6socket->requestInfo(nick);

            // check if the user is offline and set the status in case    
            C6Users::C6USER_STATUS status = getNetfriendStatus(nick);     
            if (status != C6Users::U_NOTPRESENT)
            {
                if (status == C6Users::U_OFFLINE)
                {
                    temp->setOnlineStatus(false);      
                    temp->serviceMessage(OFFLINESTR);                         
                }                   
            }                
            
            ChatForm.append(temp);

            connect(temp,SIGNAL(removeChatFromList(const QString&)),
                    this,SLOT(removeChatFromList(const QString &)));
            connect(temp,SIGNAL(sendChatMessage(QString &,bool,QString&)),this,
                    SLOT(sendChatMessage(QString &,bool,QString&))); 
            connect(temp,SIGNAL(AddNickFromChat(QString &,QString &)),
                    this,SLOT(AddNickFromChat(QString & ,QString &)));
            connect(temp,SIGNAL(Append2Log(QString &,QString &,QString &)),
                    this,SLOT(chatWriteOnLog(QString &,QString&,QString&)));
            connect(temp,SIGNAL(showUserProfile(const QString&,bool)),SLOT(showUserProfile(const QString&,bool)));
            connect(temp,SIGNAL(ShowUserLog(QString)),this,SLOT(ShowUserLog(QString)));
            connect(temp,SIGNAL(messageSent()),this,SLOT(messageSent()));
            connect(this,SIGNAL(specialChatNotify(QString,C6Users::C6USER_STATUS)),temp,
                    SLOT(specialChatNotify(QString,C6Users::C6USER_STATUS)));
            connect(temp,SIGNAL(sendFile(QString,QString,int)),this,SLOT(sendFile(QString,QString,int)));
            connect(temp,SIGNAL(chatIsActive(ChatView*)),this,SLOT(chatIsActive(ChatView*)));
            connect(temp,SIGNAL(execUrl(QString &)),this,SLOT(execUrl(QString &)));
            connect(temp,SIGNAL(showAbout()),this,SLOT(showAbout()));
            connect(temp,SIGNAL(signalGateway(const QString&,int,const QString&)),
                    this,SLOT(sendGatewayBind(const QString&,int,const QString&)));
            connect(temp,SIGNAL(acceptReception(bool,const QString &)),this,SLOT(acceptReception(bool,const QString &)));
            connect(temp,SIGNAL(acceptAuthorization(bool,const QString &)),this,SLOT(acceptAuthorization(bool,const QString &)));         

            temp->setMyNick(mainDialog->getIdentityName());

            if (receiveEvent == false)                    // through double click in list view
            {
                if (_global->getTabActivated() == true)
                {
                    addToTab(temp,true);
                    restoreWidget(*tabbedDialog);
                }
                else
                {
                    temp->show();
                }
            }
            else                                           // a message received
            {
                QString nickStar = nick;
                nickStar.prepend("*");

                if (settings.getAutoPopUp() == true)
                {
                    if (_global->getTabActivated() == true)
                    {
                        addToTab(temp);
                        changeTabName(temp,nickStar);
                        temp->setMessaged(true);
                        restoreWidget(*tabbedDialog);
                        tabbedDialog->raise();
                    }
                    else
                    {
                        restoreWidget(*temp);
                        temp->raise();
                    }
                }
                else
                {
                    QString time = getCurrentTimeStr();
                    emit  enqueueIncomingMessage(time,const_cast<QString&>(nick),
                                                 reinterpret_cast<void*>(temp));

                    if (_global->getTabActivated() == true)
                    {
                        addToTab(temp);

                        if ((tabbedDialog->isMinimized() ==  true) || (tabbedDialog->isShown() ==  false))
                        {
                            tabbedDialog->setCaption(nickStar);
                            tabbedDialog->showMinimized();               // this should go here cause
                            temp->setMessaged(true);

                            if (tabbedDialog->isMinimized() ==  true)
                            {
                                changeTabName(temp,nickStar);
                            }
                        }
                        else
                        {
                            changeTabName(temp,nickStar);
                            temp->setMessaged(true);
                        }
                    }
                    else
                    {
                        temp->setCaption(nickStar);
                        temp->setMessaged(true);
                        temp->showMinimized();
                    }
                }
            }

            if (getNetfriendStatus(nick) == C6Users::U_NOTPRESENT)
            {
                skipThis = true;
                _c6socket->sendUserRequest(nick);
            }
        }
    }
    return(temp);
}

/** get a user status  */
C6Users::C6USER_STATUS C6::getNetfriendStatus(QString const & nick)
{
    C6Users::C6USER_STATUS ret = C6Users::U_NOTPRESENT;
    C6Users *tmp= getNetFriendPtr(nick);

    if (tmp != 0)
    {
        ret = tmp->getStatus();
    }

    return(ret);
}

/** remove the chat view from list  */
void C6::removeChatFromList(const QString &nick)
{
    ChatView *temp = const_cast<ChatView*>(getChatViewPtr(nick));

    if (temp != 0)
    {
        freeBindPort(temp->getServerPort());    

        disconnect(this,SIGNAL(specialChatNotify(QString,C6Users::C6USER_STATUS)),temp,
                   SLOT(specialChatNotify(QString,C6Users::C6USER_STATUS)));

        if (_global->getTabActivated())
        {
            removeFromTab(temp);
        }

              
        /*      
        if (temp->isShown() == true)
        {
            temp->close();
    } */

       ChatForm.remove(temp);
    }
    else
    {
#ifdef C6DEBUG
        qWarning("\nCorrupted list %s\n",nick.latin1());
#endif

    }
}

/** receive a message mess from nick
    and update chat view  */
void C6::receiveChatMessage(QString &nick,QString &messStr,C6Proto::C6MessageStyle* inStyle)
{
    C6Settings &settings = C6Settings::getInstance();

    QString mess;
    C6Proto::C6MessageStyle style;

    if (IsInBlackList(nick))
    {
        mess = BLACKANSWMSG;
        _c6socket->sendMessage(nick,true,settings.getBlackListMessage(),style);
        chatWriteOnLog(nick,nick,mess);
        return;
    }

    C6Users::C6USER_STATUS myStatus = mainDialog->getOnlineStatus();

    if (settings.getAutoMessage() && (myStatus == C6Users::U_NETFRIENDONLY) &&
            (getNetfriendStatus(nick) == C6Users::U_NOTPRESENT))
    {
        _c6socket->sendMessage(nick,true,settings.getNetFriendsMessage(),style);
        mess = NETFRIENDANWMSG;
        chatWriteOnLog(nick,nick,mess);
        return;
    }

    mess = messStr;
    ChatView *temp = const_cast<ChatView*>(getChatViewPtr(nick));
    QString loginNick = loginDialog->getLogin();
    bool alreadyOpen = false;

    if (temp != 0)                                    /* a chat view is already open */
    {
        alreadyOpen = true;
        QString nickStar = nick;
        nickStar.prepend("*");

        temp->updateOtherText(nick,mess,inStyle);

        if (_global->getTabActivated() == true)
        {
            if (settings.getAutoRaise() == true)
            {
                restoreWidget(*tabbedDialog);
                changeTabName(temp,nickStar);
                temp->setMessaged(true);
            }
            else
            {
                ChatView *current = reinterpret_cast<ChatView*>(tabHandler->currentPage());

                if (loginNick.compare(nick) != 0)
                {
                    bool minimized = (tabbedDialog->isMinimized() == true) || (current->getFocus() == false);
                    if ((current != temp) || (minimized == true))
                    {
                        emit enqueueIncomingMessage(getCurrentTimeStr(),nick,
                                                    reinterpret_cast<void*>(temp));

                        setNetfriendMessaged(nick);                                             /* message icon in netfriend list */
                        mainDialog->refreshList();

                        changeTabName(temp,nickStar);                  /* notify with * message received but not read */
                        temp->setMessaged(true);

                        if (minimized == true)                                     /* change caption only if not shown */
                        {
                            tabbedDialog->setCaption(nickStar);
                        }
                    }
                }
            }
        }
        else
        {
            if (temp->canRaise())                         /* setfocus or maximize chat win */
            {
                restoreWidget(*temp);
            }
            else
            {
                if (temp->isActiveWindow() == false)
                {
                    emit  enqueueIncomingMessage(getCurrentTimeStr(),nick,
                                                 reinterpret_cast<void*>(temp));

                    if (loginNick.compare(nick) != 0)
                    {
                        setNetfriendMessaged(nick);                                   /* message icon in netfriend list */
                        mainDialog->refreshList();
                        temp->setCaption(nickStar);                                   /* notify with * message received but not read */
                        temp->setMessaged(true);
                    }
                }
            }
        }
    }
    else                                       /* chatview doesn't exist and we need to build a chat view */
    {
        if ((myStatus != C6Users::U_BUSY) && (myStatus != C6Users::U_AWAY))
        {
            ChatView* temp = buildChat(nick,true);
            temp->updateOtherText(nick,mess,inStyle);

            if (loginNick.compare(nick) != 0)
            {
                // message icon in netfriend list
                setNetfriendMessaged(nick);
                mainDialog->refreshList();
            }

            if (settings.getSoundOnce() == true)
            {
                playSoundOnReceivedMessage();
            }
        }
    }

    if (settings.getSoundOnce() == false)
    {
        playSoundOnReceivedMessage();
    }

    chatWriteOnLog(nick,nick,mess);

    if (myStatus == C6Users::U_BUSY)
    {
        if ((settings.getAutoMessage() == true) && (loginNick.compare(nick) != 0)
                && (alreadyOpen == false))
        {
            _c6socket->sendMessage(nick,true,settings.getBusyMessage(),style);
        }

        if (alreadyOpen == false)
        {                                // no opened chat win
            showReport(nick,mess);
        }

        mess = BUSYANSWMSG;
        chatWriteOnLog(nick,nick,mess);
    }

    if (myStatus == C6Users::U_AWAY)
    {
        if ((settings.getAutoMessage() == true) && (loginNick.compare(nick) != 0)
                && (alreadyOpen == false))
        {
            _c6socket->sendMessage(nick,true,settings.getAwayMessage(),style);
        }

        if (alreadyOpen == false)
        {                                // no opened chat win
            showReport(nick,mess);
        }

        mess = AWAYANSWMSG;
        chatWriteOnLog(nick,nick,mess);
    }
}
/** handle root popup menu  */
void C6::doMainAction(const QString &child,USER_MENU_ACTIONS select,QString root)
{
    doMenuAction(child,select,root);
}

/** handle child pop up menu  */
void C6::doMenuAction(QString const & nick,USER_MENU_ACTIONS select,QString const& parent)
{
    switch (select)
    {
        case STARTCHAT:
            openChat();    
            break;            
        case REMOVENICK:
        {      
            removeUser(nick);
            _c6socket->RemoveUser(nick);
            saveNetfriendList();
            mainDialog->refreshList();
        }      
        break;
        case PROFILE:
        {
            showFullUserProfile(nick);    
        }
        break;
        case ALLPROFILE:
        {      
            showShortProfile(nick);
        }      
        break;
        case INITCHAT:
        {      
            buildChat(nick);
        }      
        break;
        case USRLOG:
        {      
            ShowUserLog(nick);
        }      
        break;
        case ADDROOTNICK:
        {      
            if (getNetfriendStatus(nick) == C6Users::U_NOTPRESENT)
            {
                addUser(parent,nick);
                _c6socket->sendUserRequest(nick);
                saveNetfriendList();
                mainDialog->refreshList();
            }
            else
            {
                messageBox("Attenzione",QString::fromUtf8("Nick già presente in lista"));
            }
        }      
        break;
        case TOGGLEONLINE :
        {      
            mainDialog->setShowOnline(!mainDialog->getShowOnline());
            mainDialog->refreshList();
        }      
        break;
        case SORTORDER :
        {      
            C6Settings::getInstance().setSortAscending(!C6Settings::getInstance().getSortAscending());
            mainDialog->refreshList();
        }      
        break;
        case ADDNICK  :
        {      
            addNickDialog(nick);
        }      
        break;
        case ADDGROUP:
        {      
            addGroup(nick);
            saveNetfriendList();
        }      
        break;
        case REMOVEGROUP:
        {      
            removeGroup(nick);
            saveNetfriendList();
        }      
        break;
        case RENAMEGROUP:
        {      
            renameGroup(nick);
            saveNetfriendList();
        }      
        break;
        case REVOKE_AUTH:
        {      
            _c6socket->removeBuddyFromWhiteList(nick);
            _global->removeFromWhiteList(nick);
            mainDialog->refreshList();
        }      
        break;
        case KICK:
        {      
            _c6socket->kickUserFromRoom(parent,nick,10);   
        }      
        break;               
        default:
        {      
            if (select >= MOVE)
            {
                QStringList groups = _global->getAllGroups();
    
                moveUser(nick,parent,groups[select-MOVE]);
                saveNetfriendList();
            }
        }      
        break;
    }
}

void C6::addUser(QString const & root,QString const & nick)
{
    _global->addUser(root,nick);

    if (_global->isTheBlackList(root) == true)
    {
        _c6socket->addBuddyToBlackList(nick);
    }
    else
    {
        _c6socket->addBuddy(root,nick);
    }
}

void C6::addUser(QString const & root,QString const & user,QString const & nick)
{
    _global->addUser(root,user,nick);
}

void C6::removeUser(QString const & nick)
{
    QString group = _global->getUserGroupName(nick);

    if (_global->isTheBlackList(group) == true)
    {
        _c6socket->removeBuddyFromBlackList(nick);
    }
    else
    {
        _c6socket->removeBuddy(group,nick);
    }

    _global->removeUser(nick);
}

/** check if some user went offline during a chat */
void C6::notifyOnOfflineStatus(QString const & nick,int status,bool showMsg)
{
    ChatView *temp = const_cast<ChatView*>(getChatViewPtr(nick));

    if (temp)
    {
        if (status == C6Users::U_OFFLINE)                                                // from ONLINE to OFF
        {
            if (showMsg == true)
            {
                temp->serviceMessage(ONOFFLINESTR);
            }
            temp->setOnlineStatus(false);
        }
        else
        {
            if (showMsg == true)
            {
                temp->serviceMessage(OFFONLINESTR);                                 // from OFFLINE to ON
            }
            temp->setOnlineStatus(true);
        }
    }
}
/** open the configuration dialog */
void C6::openConfig()
{
    C6Conf tmp(loginDialog);
    connect(&tmp,SIGNAL(playWav(QString)),this,SLOT(playWav(QString)));
    connect(&tmp,SIGNAL(apply(C6Conf&)),this,SLOT(applyConfig(C6Conf&)));

    if (connected == true)
    {
        if (_c6socket->isOldAccount() == false)
        {
            tmp.setConfigurationMode(_c6socket->getConfigurationMode());
            tmp.setOfflineMode(_c6socket->getOfflineMessageMode());
        }
    }

    tmp.exec();
#if !defined(Q_OS_MACX) && !defined(Q_OS_DARWIN)

    disconnect(&tmp,0,0,0);
#endif

}

/*!
    \fn C6::applyConfig()
 */
void C6::applyConfig(C6Conf& conf)
{
    C6Settings &settings = C6Settings::getInstance();
    calibrateSystemFontSize();     
    setFontOnWidgets();
    _global->loadSpecialList();
    _global->loadAutoRoomList();    
    postConfigureUpdates();

    if (settings.getStyleSwitch() == true)
    {
        _global->setWidgetStyle(settings.getWidgetStyle());
    }

    if (settings.getAutoAway() == true)
    {
        _idleTimer->changeInterval(IDLE_CHECK_INTERVAL);
    }
    else
    {
        _idleTimer->stop();
    }

    if (connected == true)
    {
        if (_c6socket->isOldAccount() == false)
        {
            if (_c6socket->getConfigurationMode() != conf.getConfigurationMode())
            {
                _c6socket->sendAndSetConfigurationMode(conf.getConfigurationMode());
            }

            if (_c6socket->getOfflineMessageMode() != conf.getOfflineMode())
            {
                _c6socket->sendAndSetOfflineMessageMode(conf.getOfflineMode());
            }
        }
    }
    
    mainDialog->refreshList();   
}


/** check if nick is in black list  */
bool C6::IsInBlackList(QString const & nick)
{
    return(_global->isBlackListed(nick));
}

/** add a nick from chat  */
void C6::AddNickFromChat(QString & nick,QString & list)
{
    if (getNetfriendStatus(nick) == C6Users::U_NOTPRESENT)
    {
        addUser(list,nick);
        _c6socket->sendUserRequest(nick);
        saveNetfriendList();
        mainDialog->refreshList();
    }
    else
    {
        messageBox("Attenzione",QString::fromUtf8("Nick già presente in lista"));
    }
}
/** write log file for each conversation */
void C6::chatWriteOnLog(QString & nick,QString & from,QString & text)
{
    C6Logger::getInstance().logChatOnFile(nick,from,text);
}

/** write log file for each room */
void C6::roomWriteOnLog(QString &room_name,QString &text)
{
    C6Logger::getInstance().logRoomOnFile(room_name,text);
}

/** write on system log file */
void C6::WriteOnSystemLog(QString print)
{
    C6Logger::getInstance().logSystemMessage(print);
}


/** move a nick from a list to another */
void C6::moveUser(QString nick,QString from,QString to)
{
    if (from.compare(to) == 0)
    {
        messageBox("Attenzione","Operazione inutile !");
    }
    else
    {
        C6Users::C6USER_STATUS status = getNetfriendStatus(nick);
        C6Users *c6user= getNetFriendPtr(nick);    
        
        if (c6user != 0)
        {             
            C6Users::C6Users tmp =*c6user;
            removeUser(nick);
            addUser(to,nick);
            setNetfriendProperty(tmp);
            mainDialog->refreshList();
        }      
    }
}

/** handle offline status when signal received
    mode = true connection closes  abnormally
    mode = false connection exited normally  */
void C6::closeConnection(bool mode)
{
    if (mode == true)
    {
        if (C6Settings::getInstance().getReconnect())
        {
            reconnect();
        }
        else
        {
            messageBox("Errore",QString::fromUtf8("La connessione non è piu attiva. Si prega di riprovare più tardi"));
            restoreLogin();
        }
    }
    else
    {
        restoreLogin();
    }
}

/** request closing the connection  */
void C6::clientExit()
{
    _c6socket->ReqClientExit();
}

/** handle menu cases from chatview  */
void C6::HandleMenuCommand(int choice)
{
    switch(choice)
    {
    case FORCE_EXITMAIN   :
        restoreLogin();
        break;
    case EXITMAIN         :
        clientExit() ;
        break;
    case NETSEARCH        :
        showSearchForm();
        break;
    case ROOMLIST         :
        showChatRooms();
        break;
    case CONFIG           :
        openConfig();
        break;
    case ROOMLOG          :
    case USERLOG          :
    case SYSLOG           :
        ShowLogWin(choice);
        break;
    case CREDITS          :
        showAbout();
        break;
    case IMPORTLIST       :
        mergeLocalList();
        break;
    }
}

/** show the log view window */
void C6::ShowLogWin(int choice)
{
    C6LogView *logView = new C6LogView(loginDialog,QDir::homeDirPath()+"/"+C6DIR);
    connect(logView,SIGNAL(showAbout()),this,SLOT(showAbout()));
    logView->show(choice);
}


void C6::postConfigureUpdates()
{
    C6Settings &settings = C6Settings::getInstance();
    QStyleSheet *sh=QStyleSheet::defaultSheet();
    
    sh->item("netfnick")->setColor(settings.getForeNetFriendColor());
    sh->item("netfnick")->setFontFamily(settings.getFontStyle());
    sh->item("netfnick")->setFontSize(settings.getFontSize());
    sh->item("mynick")->setColor(settings.getForegndColor());
    sh->item("mynick")->setFontFamily(settings.getFontStyle());
    sh->item("mynick")->setFontSize(settings.getFontSize());   
    sh->item("smessage")->setColor(settings.getForeMessageColor());
        
    int tmp = _global->getBaseFont().pointSize() -1 ;
        
    sh->item("smessage")->setFontSize(tmp);   
    sh->item("smessage")->setFontFamily(_global->getBaseFont().family());    
    sh->item("text")->setFontSize(tmp);   
    sh->item("text")->setFontFamily(_global->getBaseFont().family());       
    
    for (ChatView *temp = ChatForm.first(); temp; temp = ChatForm.next())
    {
        temp->setCustomFont();
        temp->rebuildFontAndColor();
        temp->setReceive(settings.getAutoAccept());
    }

    for (C6ChatRoom *temp = chatRoomList.first(); temp; temp = chatRoomList.next())
    {
        temp->setCustomFont();
        temp->updateColorFont();
    }
   
    mainDialog->setShowOnline(settings.getShowOnline());
}

void C6::hideChildrenDialogs(QWidget *dis)
{
    Q_ASSERT(dis != 0);

    QObjectList *l = dis->topLevelWidget()->queryList();
    QObjectListIt it(*l);
    QObject *obj=0;
    QDialog *dialog = 0;

    while ((obj = it.current()) != 0)
    {
        if ((dialog = dynamic_cast<QDialog*>(obj)) != 0)
        {
            if (dialog->isShown())
            {
                dialog->hide();
            }
        }
        ++it;
    }
}

void C6::ShowUserLog(QString user)
{
    C6LogView *logView = new C6LogView(loginDialog,QDir::homeDirPath()+"/"+C6DIR);
    connect(logView,SIGNAL(showAbout()),this,SLOT(showAbout()));
    logView->show(SINGLEUSERLOG,user);
}

void C6::setAllUsersOffline()
{
    _global->setAllUsersOffline();
}

void C6::playWav(QString path)
{
    if (path.stripWhiteSpace().length() > 0)
    {
        if (C6Settings::getInstance().getSoundSwitch() && QFile::exists(path))
        {
            if (QSound::isAvailable() == true)
            {
                QSound::play(path);
            }
            else
            {
                QProcess exe;
                exe.addArgument(C6Settings::getInstance().getSoundPlayer());
                exe.addArgument(path);

                if(exe.start() == true)
                {
                   wait3(NULL,WNOHANG,NULL);
                }
            }
        }
    }
}

void C6::messageSent()
{
    if (C6Settings::getInstance().getOutMessageSwitch())
    {
        playWav(C6Settings::getInstance().getOutMessageWav());
    }
}

void C6::showSearchForm()
{
    searchDialog->raise();
    searchDialog->setActiveWindow();

    if (searchDialog->isMinimized())
    {
        searchDialog->showNormal();
    }
    else
    {
        searchDialog->show();
    }
}

void C6::showShortProfile(QString const & nick)
{
    emit requestProfile(nick);
}

void C6::userMenuAction(const QString & nick,USER_MENU_ACTIONS select)
{
    QStringList groups = _global->getAllGroups();
    if (select >=MOVE)
    {
        doMenuAction(nick,ADDROOTNICK,groups[select-MOVE]);
    }
    else
    {
        doMenuAction(nick,select);
    }
}

void C6::getUserInfo(const QString &nick,unsigned char *data,int packL,bool toGUI)
{
    if (toGUI == true)
    {
        C6Profile *profileDialog = new C6Profile(loginDialog);
        connect(profileDialog,SIGNAL(showAbout()),this,SLOT(showAbout()));
        profileDialog->updateUserProfile(data,packL);
        profileDialog->show();
    }
    else
    {
        ChatView *chatPtr = const_cast<ChatView*>(getChatViewPtr(nick));
        if (chatPtr != 0)
        {
            chatPtr->setOtherClientInfo(data,packL);
        }
    }
}

void C6::sendFile(QString s,QString nick,int clientVersion)
{
    _c6socket->requestFileTransfer(nick,s,clientVersion);
}

void C6::fireConnection(QHostAddress ip,int port,QString fileName,QString sendNick)
{
    ChatView *temp = const_cast<ChatView*>(getChatViewPtr(sendNick));

    if (temp)
    {
        temp->startTransfer(ip,port,fileName);
    }
}

void C6::chatIsActive(ChatView* chat)
{
    markAsRead(chat);
    emit chatHasFocus(chat);
}

void C6::markAsRead(ChatView *pchat)
{
    C6Settings &settings = C6Settings::getInstance();

    if (pchat != 0)
    {
        QString nick = pchat->getOtherNick();
        pchat->setMessaged(false);

        if (settings.getTabbedChat() == true)
        {
            changeTabName(pchat,nick);
            tabbedDialog->setCaption(nick);
        }
        else
        {
            pchat->setCaption(nick);
        }

        C6Users *userPtr= getNetFriendPtr(nick);
        if ((userPtr != 0) && (userPtr->isMessaged() == true))
        {
            userPtr->setMessaged(false);
            mainDialog->refreshList();
        }
    }
}

void C6::sendGatewayBind(const QString &ip,int port,const QString &nickToGrant)
{
    _c6socket->grantIP(ip,port,nickToGrant);
}


/*!
    \fn C6::prepareFileReception(QString&)
 */
void C6::prepareFileReception(QString& from,QString& mess)
{
    bool isReceiveOn = false;
    
    ChatView *temp = const_cast<ChatView*>(getChatViewPtr(from));

    if (temp != 0)
    {
        isReceiveOn = temp->isReceiveOn();
    }
    else // chat is still not open, take property value from config
    {
        isReceiveOn = C6Settings::getInstance().getAutoAccept();
    }

    if (isReceiveOn == true)
    {
        receiveChatMessage(from,const_cast<QString&>(AUTO_RECEIVE_ENABLED));

        ChatView *chat = const_cast<ChatView*>(getChatViewPtr(from));

        if (_c6socket->hasNAT() == true)
        {
            int port = 0;
            QString ip;

            _c6socket->getGateway(ip,port);
            chat->activateFileServer(ip,port);
        }
        else
        {
            _c6socket->activateFileReception(from,chat->getServerPort());
            chat->activateFileServer();
        }
    }
    else
    {
        if (_c6socket->hasNAT() == true)
        {
            QString receiveMessage(ACCEPT_FILE_STR(from));    
            receiveChatMessage(from,receiveMessage);
        }
        else
        {
            _c6socket->activateFileReception(from,0);               // server not available
        }
    }
}



/*!
    \fn C6::getSuitableBindPort()
 */
int C6::getSuitableBindPort()
{
    std::vector<int>::iterator it;
    int start = C6Settings::getInstance().getStartPort().toInt();
    bool broken,assigned=false;

    if (_portBindChatVector.size())
    {
        while ((start < MAXPORTSCAN) && !assigned)
        {
            broken = false;
            for (it = _portBindChatVector.begin(); it != _portBindChatVector.end(); it++)
                if (start == *it)
                {
                    start++;
                    broken=true;
                    break;
                }

            if (!broken)
            {
                _portBindChatVector.push_back(start);
                assigned = true;
            }
        }
    }
    else
        _portBindChatVector.push_back(start);

    return(start);
}

void C6::freeBindPort(int port)
{
    std::vector<int>::iterator it;
    for (it = _portBindChatVector.begin(); it != _portBindChatVector.end(); it++)
    {
        if (*it == port)
        {
            _portBindChatVector.erase(it);
            break;
        }
    }
}       

C6Users* getNetFriendPtr(QString const & name)
{
    return(C6Global::getInstance().getC6UserPtr(name));
}

/*!
    \fn C6::updateNetFriendStatus(C6Users::C6UsersVector & usrVector,bool boot)
 */
void C6::updateNetFriendStatus(C6Users::C6UsersVector & usrVector,bool boot)
{
    C6Settings &settings = C6Settings::getInstance();
    C6Users::C6USER_STATUS status = C6Users::U_NOTPRESENT;
    QString userNick;

    for(unsigned int i=0; i < usrVector.size(); i++)
    {
        status = usrVector[i].getStatus();
        userNick = usrVector[i].getNick();

        if(setNetfriendProperty(usrVector[i]) == true)        // the user in the list
        {
            if (boot == false)
            {
                Q_ASSERT(usrVector.size() == 1);
                if (C6Users::isStatusOnline(status))
                {
                    if (_global->isInSpecialList(userNick))
                    {
                        if(settings.getSpecialFriendSwitch())
                        {
                            playWav(settings.getSpecialFriendWav());
                        }

                        if (settings.getSpecialNotifySwitch())
                        {
                            emit specialChatNotify(userNick,status);
                        }
                    }
                    else
                    {
                        if (settings.getOnlineMessageSwitch() && !IsInBlackList(userNick))
                        {
                            playWav(settings.getOnlineMessageWav());
                        }
                    }
                }
                else
                {
                    if (settings.getSpecialNotifySwitch() && _global->isInSpecialList(userNick))
                    {
                        emit specialChatNotify(userNick,status);
                    }

                    if (settings.getOfflineMessageSwitch() && !IsInBlackList(userNick))
                    {
                        playWav(settings.getOfflineMessageWav());
                    }
                }
                notifyOnOfflineStatus(userNick,status);
            }
        }
        else
        {
            bool showMsg = false;
            ChatView const *temp = getChatViewPtr(userNick);
            if (temp != 0)
            {
                showMsg =  skipThis;
            }
            notifyOnOfflineStatus(userNick,status,!showMsg);
            skipThis = false;
        }
    }

    if (_global->getTabActivated())
    {
        QWidget *temp = const_cast<ChatView*>(getChatViewPtr(userNick));

        if(temp !=0)
        {
            tabHandler->updateTabIcon(*temp,status);
        }
    }
    mainDialog->refreshList();
}

static bool findIndexInUserList(QStringList &userList,int *j)
{
    unsigned int i=0;
    bool found = false;

    if (C6Settings::getInstance().getLastIdentity() != "NONE")
    {
        while ((i < userList.count()) && !found)
        {
            if (userList[i].compare(C6Settings::getInstance().getLastIdentity()) == 0)
            {
                found = true;
            }
            else
            {
                i++;
            }
        }
    }

    if (found)
    {
        *j=i;
    }

    return(found);
}

void C6::nowSelectUser(unsigned char *data)
{
    QString xml_str;
    QString nick;
    QString passw;
    int pos=0,pos1=0,ret=0;

    bool done=false;
    bool found=false;
    bool old_account=false;

    if (fastReconnect == false)
    {
        userList.clear();
        passwList.clear();

        xml_str.setLatin1((const char*)data);

        if (xml_str.find(ERRORSTR,0) > 0)
        {
            signalError(C6Proto::INVALID_LOGIN);
            return;
        }

        C6NickList *nickList = new C6NickList(loginDialog);

        while (!done)
        {
            old_account = (xml_str.find(OLDNICKSTR,0) > 0);
            pos = xml_str.find(NICKSTR,pos1);
            if (pos > 0)
            {
                pos+=strlen(NICKSTR)+1;
                pos1 = xml_str.find(QChar('<'),pos);
                nick = xml_str.mid(pos,pos1-pos);

                pos = xml_str.find(PASSWSTR,pos1);
                pos+=strlen(PASSWSTR)+1;
                pos1 = xml_str.find(QChar('<'),pos);
                passw = xml_str.mid(pos,pos1-pos);

                userList+=nick;
                passwList+=passw.left(10);
                nickList->addNick(nick);
            }
            else
            {            
                done = true;
            }            
        }

        int i=0;
        found = findIndexInUserList(userList,&i);

        if (done && found)
        {
            nickList->setDefaultIdentity(i);
        }
        else
        {
            nickList->setDefaultIdentity(0);
        }

        ret = 0;

        if (userList.count() == 0)
        {
            messageBox("Attenzione",NO_NICK_AVAILABLE);
            restoreLogin();
            return;
        }

        if (!old_account)
        {
            if (userList.count() == 0)
            {
                messageBox("Attenzione",NO_NICK_AVAILABLE);
                restoreLogin();
                return;
            }

            if (userList.count() > 1)               // if there's only 1 nick no need to choose..
            {
                ret = nickList->exec();

                if (ret == NORESULT)
                {
                    restoreLogin();
                    return;               
                }
            }
        }

        mainDialog->setOwnerName(userList[ret]);
        mainDialog->addUser2Menu(userList);      // remove the menu entry userList.count < 2
        _c6socket->loginAs(userList[ret],passwList[ret]);
        C6Settings::getInstance().setCurrentIdentity(userList[ret]);
        
        const QString message = _global->getCurrentMessageODDay(loginDialog->getLogin(),userList[ret]);
        _c6socket->setMessageOfTheDay(message);    
        mainDialog->setMessageODD(message);    
    }
    else
    {
        int i=0;
        findIndexInUserList(userList,&i);

        fastReconnect = false;
        mainDialog->setOwnerName(userList[fastNickID]);
        mainDialog->addUser2Menu(userList);

        C6Users::C6USER_STATUS initStatus = mainDialog->getOnlineStatus();
        _c6socket->setInitialStatus(initStatus,C6Settings::getInstance().getIpVisible());
        emit statusChanged(initStatus);
        _c6socket->loginAs(userList[fastNickID],passwList[fastNickID]);
        C6Settings::getInstance().setCurrentIdentity(userList[fastNickID]);
        
        const QString message = _global->getCurrentMessageODDay(loginDialog->getLogin(),userList[fastNickID]);
        _c6socket->setMessageOfTheDay(message);     
        mainDialog->setMessageODD(message);              
    }
}


/*!
    \fn C6::reloadPassword(const QString & text)
 */
void C6::reloadPassword(const QString & text)
{
    loadPassword(text);
}


/*!
    \fn C6::loadPassword(QString login)
 */
void C6::loadPassword(QString login)
{
    login = _global->getCurrentIdentityPassword(login); 
    
    if (login.isNull() == false)
    {
        loginDialog->Password->setText(login);
    }
    else
    {
        loginDialog->Password->setText("");
    }

    loginDialog->SavePwdChk->setChecked(login ? true : false);
}

/*!
    \fn C6::execUrl(QString url)
 */
void C6::execUrl(QString & url)
{
    if (url.contains("room://"))      // open the browser
    {
        url = url.right(url.length()-7);
        enterRoom(url);
    }
    else
        if (url.contains("nick://"))      // open the browser
        {
            url = url.mid(7,url.length());
            buildChat(url);
        }
        else
        {
            QProcess *exe = new QProcess(this);
            if (exe)
            {
                exe->addArgument(C6Settings::getInstance().getBrowser());
                exe->addArgument(url);
                exe->start();
                delete exe;
            }
        }
}

/*!
    \fn C6::showChatRooms()
 */
void C6::showChatRooms()
{
    roomList->raise();
    roomList->setActiveWindow();
    roomList->loadCategoryList(_c6socket->getRoomCategoryVector());
   
    if (roomList->isMinimized())
    {
        roomList->showNormal();
    }
    else
    {
        roomList->show();
    }
}


/*!
    \fn C6::enterRoom(QString & room_name)
 */
void C6::enterRoom(const QString& room_name,const QString& password)
{
    C6ChatRoom *tmp = const_cast<C6ChatRoom*>(getPtrRoom(room_name));

    if (tmp == 0)                                                // new room
    {
        _c6socket->enterRoom(room_name,password);    
    }
    else
    {
        restoreWidget(static_cast<QWidget&>(*tmp));
    }
}


/*!
    \fn C6::roomEnterInfo(const QString& roomName,const QString& roomTopic,int roomAttribute,int allowedUserRole,QMap<QString,int>& users);  
    
 
    update the nick list for room room_name
 
 */
void C6::roomEnterInfo(const QString& roomName,const QString& roomTopic,int roomAttribute,int allowedUserRole,QMap<QString,int>& users)
{
    C6ChatRoom const *tmp = getPtrRoom(roomName);
    QString nick = mainDialog->getIdentityName();

    if (tmp == 0)   // should be always this way
    {
        C6ChatRoom *room =  reinterpret_cast< C6ChatRoom *>(C6ChatFactory::getChat(C6ChatFactory::ROOM));

        if (room != 0)
        {
            chatRoomList.append(room);
            room->setMyNick(nick);
            room->setRoomName(roomName,roomTopic);
            room->setRoomCaption(roomName,roomAttribute);    
            
            connect(room,SIGNAL(sendToRoom(QString&,QString&,int)),SLOT(sendToRoom(QString&,QString&,int)));
            connect(room,SIGNAL(exitFromRoom(QString &)),SLOT(exitFromRoom(QString &)));
            connect(room,SIGNAL(menuUserAction(const QString &,const QString &,USER_MENU_ACTIONS)),
                    SLOT(roomMenuUserAction(const QString &,const QString &, USER_MENU_ACTIONS)));
            connect(room,SIGNAL(execUrl(QString&)),SLOT(execUrl(QString&)));
            connect(room,SIGNAL(append2Log(QString&,QString&)),SLOT(roomWriteOnLog(QString&, QString& )));
            connect(room,SIGNAL(signalRoomLog(QString&)),SLOT(showRoomLog(QString&)));
            connect(room,SIGNAL(switchToRoom(QString&)),SLOT(switchToRoom(QString&)));
            connect(room,SIGNAL(inviteSelected(const QString &,const QStringList &,const QString &)),SLOT(inviteNetfriend(const QString &,const QStringList &,const QString &)));
            connect(room,SIGNAL(showAbout()),SLOT(showAbout()));

            room->show();
            room->updateUserList(users);
        }
    }
}


/*!
    \fn C6::getPtrRoom(QString room)
 
    return the pointer to room or 0 if it doesn't exists
 */
C6ChatRoom const* C6::getPtrRoom(QString const & room)
{
    C6ChatRoom *tmp=0;

    for(tmp = chatRoomList.first(); tmp; tmp = chatRoomList.next())
    {
        if (tmp->getRoomName() == room)
        {
            break;
        }
    }

    return(tmp);
}


/*!
    \fn C6::eventFromRoom(QString &room_name,QString &nick,SERVER_COMMAND_ID action)
 
    this handles when a user exit or enter the room room_name
 */
void C6::eventFromRoom(QString &roomName,QString &nick,C6Proto::SERVER_COMMAND_ID action)
{
    QString nickname = nick;

    C6ChatRoom *tmp =  const_cast<C6ChatRoom*>(getPtrRoom(roomName));

    if (tmp !=0)
    {
        if (action == C6Proto::EXIT_FROMROOM)
        {
            if (nickname.compare(mainDialog->getIdentityName()) == 0)    // maybe banned or kicked
            {
                tmp->serviceMessage(KICKBANNED_ROOM_MSG);
                tmp->setKicked();
            }
            else
            {
                tmp->serviceMessage(EXIT_ROOM_MSG(nickname));
                tmp->updateTheList(nickname,true);
            }
        }
        else
        {
            tmp->serviceMessage(ENTER_ROOM_MSG(nickname));
            tmp->updateTheList(nickname,false);
        }
    }
}


/*!
    \fn C6::messageFromRoom(QString &room_name,QString &nickfrom,QString &msg)
 
    this handles incoming message to room room_name
 */
void C6::messageFromRoom(QString &room_name,QString &nickfrom,QString &msg)
{
    C6ChatRoom *tmp =  const_cast<C6ChatRoom*>(getPtrRoom(room_name));

    if (tmp)
    {
        tmp->updateOtherText(nickfrom,msg);
    }
}


/*!
    \fn C6::sendToRoom(QString& nick,QString &msg,int type)
 */
void C6::sendToRoom(QString &channel,QString &msg,int type)
{
    _c6socket->sendMessageToRoom(channel,msg,type);
}


/*!
    \fn C6::exitFromRoom(QString &)
 */
void C6::exitFromRoom(QString & roomName)
{
    _c6socket->exitFromRoom(roomName);
    C6ChatRoom const *tmp =  getPtrRoom(roomName);

    if (tmp != 0)
    {
        // disconnect(tmp,0,0,0);  crash on mac
        chatRoomList.remove(tmp);
    }
}

/*!
    \fn C6::createRoom(const QString& roomName,const QString& caption,bool isPublic,int index,const QString& password)      
       
    create a room room_name with caption and if present properties property set
 */
void C6::createRoom(const QString& roomName,const QString& caption,bool isPublic,int index,const QString& password)     
{
    C6Proto::RoomAttribute roomAttr;   
    const int enterMode = 0;    
      
    roomAttr.setPublic(isPublic);
    if (password.length() > 0)
    {
        roomAttr.setPasswordProtected(true);     
    }                  
    
    _c6socket->createRoom(roomName,caption,roomAttr.pack(),index,enterMode,password);
}


/*!
    \fn C6::searchRoom(unsigned char *property)
    
    search for room
 */
void C6::searchRoom(int roomSearchAttribute,unsigned char *property)
{
    roomList->setWaitResult();
    _c6socket->roomSearch(roomSearchAttribute,property);
}


/*!
    \fn C6::searchResultReady(std::vector<RoomSearchResult>&)
 */
void C6::searchResultReady(std::vector<C6Proto::RoomSearchResult>& result)
{
    roomList->updateResults(result);     
}

/*!
    \fn C6::sendUserList()
 */
void C6::sendUserList()
{
    QStringList& autoRoom = const_cast<QStringList &>(_global->getAutoRoomList());
    QStringList tmp = getNickStringList();
    _c6socket->sendUserRequest(tmp);

    if (C6Settings::getInstance().getAutoRoomEnter() == true)
    {
        for(unsigned int i=0; i < autoRoom.count(); i++)
        {
            _c6socket->enterRoom(autoRoom[i]);
        }
    }
}

/*!
    \fn C6::getNickStringList()
 */
QStringList C6::getNickStringList()
{
    return(_global->getAllUsers());
}


/*!
    \fn C6::showRoomLog(QString name)
 */
void C6::showRoomLog(QString & name)
{
    C6LogView *logView = new C6LogView(loginDialog,QDir::homeDirPath()+"/"+C6DIR);
    connect(logView,SIGNAL(showAbout()),this,SLOT(showAbout()));
    logView->show(SINGLEROOMLOG,name);
}


/*!
    \fn C6::newNickReconnect(int nick)
 */
void C6::reconnect(int nick)
{
    const QString tmp_reconnect("Riconnessione in corso...");

    _idleTimer->stop();
    _c6socket->closeSocket();
    deleteAllChat();
    deleteAllRooms();
    setAllUsersOffline();
    tabbedDialog->hide();
    mainDialog->setListType(C6_Main::NETFRIEND_LIST);
    mainDialog->setOwnerName(tmp_reconnect);
    mainDialog->updateServerStats("");
    _global->clearUsersList();
    reportDialog->clearReport();    
    roomList->hide();    
    mainDialog->refreshList(true);
    connected = false;
    safeInitCounter = 0;

    if (nick >= 0)
    {
        fastReconnect = true;
        fastNickID = nick;
    }
    else
    {
        fastReconnect = false;
    }

    ProgressIndicator *progressWin = new ProgressIndicator(loginDialog);
    connect(progressWin,SIGNAL(forceClose()),this,SLOT(restoreLogin()));
    connect(_c6socket,SIGNAL(progress(int)),progressWin,SLOT(setProgress(int)));
    progressWin->show();

    mainDialog->setOnlineStatus(C6Settings::getInstance().getStatus());
    initConnection(loginDialog->getLogin(),loginDialog->getPassword());
}

/*!
    \fn C6::switchToRoom(QString & room)
    
    given a room, give the focus 
 */
void C6::switchToRoom(QString & room)
{
    C6ChatRoom* ptr =  const_cast<C6ChatRoom*>(getPtrRoom(room));

    if (ptr)
    {
        if (ptr->isMinimized())
        {
            ptr->hide();
            ptr->showNormal();
            ptr->setFocus();
        }

        ptr->raise();
        ptr->setActiveWindow();
        ptr->takeFocus();
    }
}

/*!
    \fn C6::showReport()
 */
void C6::showReport(const QString & nick,const QString& mess,const QString& timeString)
{
    reportDialog->notify(nick,mess,timeString);
}

/*!
    \fn C6::addToTab(ChatView const * chat)
 */
void C6::addToTab(ChatView const *chat,bool setCurrent)
{
    if (chat != 0)
    {
        int count = tabHandler->count();

        C6Users::C6USER_STATUS status =  getNetfriendStatus(chat->getOtherNick());
        // disconnect to avoid SIGNAL
        tabHandler->disconnect(SIGNAL(currentChanged(QWidget*)));
        tabHandler->addTabAndSetCurrent(*chat,status,chat->getOtherNick(),setCurrent);
        connect(tabHandler,SIGNAL(currentChanged(QWidget*)),this,SLOT(currentTabChanged(QWidget*)));

        if (count == 0)
        {
            QSize tabSize(chat->baseSize().width(),chat->baseSize().height());
            tabHandler->resize(tabSize);
            tabbedDialog->resize(tabSize);
        }

        const_cast<ChatView*>(chat)->takeFocus();
    }
}


/*!
    \fn C6::getChatViewPtr(QString & nick)
 */
ChatView const * C6::getChatViewPtr(QString const & nick)
{
    ChatView *tmp=0;

    for(tmp = ChatForm.first(); tmp; tmp = ChatForm.next())
    {
        if (tmp->getOtherNick().compare(nick) == 0)
        {
            break;
        }
    }
    return(tmp);
}


/*!
    \fn C6::removeFromTab(ChatView const *chat)
 */
void C6::removeFromTab(ChatView const *chat)
{
    int count = tabHandler->count();
    Q_ASSERT(count);

    if (chat == 0)
    {
        return;
    }

    if (count == 1)
    {
        tabbedDialog->hide();
    }
    else
    {
        tabHandler->disconnect(SIGNAL(currentChanged(QWidget*)));
        tabHandler->setCurrentPage(count-2);
        connect(tabHandler,SIGNAL(currentChanged(QWidget*)),this,SLOT(currentTabChanged(QWidget*)));
    }

    tabHandler->removePage(const_cast<ChatView*>(chat));
}


/*!
    \fn C6:: initTabStuff()
 */
void C6::initTabStuff()
{
    tabbedDialog = new C6TabQWidget();
    tabLayout = new QGridLayout(tabbedDialog, 0, 0, 0, 0, "tablayout");
    tabHandler = new C6TabWidget(tabbedDialog,"tabWidget");
    tabLayout->addWidget(tabHandler,0,0);

    connect(tabbedDialog,SIGNAL(closeTabWidget()),this,SLOT(hideTabWidget()));
    connect(tabHandler,SIGNAL(currentChanged(QWidget*)),this,SLOT(currentTabChanged(QWidget*)));
    connect(tabHandler,SIGNAL(signalCloseTab(int)),this,SLOT(closeTab(int)));
}

void C6::currentTabChanged(QWidget* tmp)
{
    if ((tmp != 0) && (tabbedDialog->isMinimized() == false ))
    {
        ChatView *pchat = static_cast<ChatView*>(tmp);

        markAsRead(pchat);
        emit chatHasFocus(pchat);
    }
}

/*!
    \fn C6::restoreWidget(QWidget &widget)
 */
void C6::restoreWidget(QWidget &widget)
{
    if (widget.hasFocus() == false)
    {
        widget.raise();             // raise if obscured
    }

    if (widget.isHidden())
    {
        widget.show();
    }

    if (widget.isMinimized())
    {
        widget.showNormal();
#if (QT_VERSION <= 0x030210)

        widget.setActiveWindow();
#else

        widget.setWindowState(widget.windowState() &
                              ~WindowMinimized | WindowActive);
#endif

        widget.raise();             // to be sure

        ChatView *chat=dynamic_cast<ChatView*>(&widget);
        if (chat !=0)
        {
            chat->takeFocus();
        }
    }
}


/*!
    \fn C6::setTabTo(QString const &nick)
 */
void C6::setTabTo(QString const &nick)
{
    int count =  tabHandler->count();
    ChatView *chat = 0;

    for(int i=0; i < count; i++)
    {
        chat = reinterpret_cast<ChatView*>(tabHandler->page(i));
        Q_CHECK_PTR(chat);

        if (chat->getOtherNick().compare(nick) == 0)
        {
            tabHandler->disconnect(SIGNAL(currentChanged(QWidget*)));
            tabHandler->setCurrentPage(i);
            tabHandler->showPage(chat);
            chat->takeFocus();
            connect(tabHandler,SIGNAL(currentChanged(QWidget*)),this,SLOT(currentTabChanged(QWidget*)));
            break;
        }
    }
}


/*!
    \fn C6::closeTab(int tabno)
 */
void C6::closeTab(int tabno)
{
    if (tabno != -1)
    {
        ChatView *chat = reinterpret_cast<ChatView*>(tabHandler->page(tabno));
        if (chat != 0)
        {
            chat->close();    
        }
    }
}


/*!
    \fn C6::extendedChangeStatus(const C6Users::C6Users &c6user)
 */
    void C6::extendedChangeStatus(const C6Users::C6Users &c6user)
{
    C6Settings &settings = C6Settings::getInstance();

    const QString nick = c6user.getNick();
        
    C6Users::C6USER_STATUS oldStatus = getNetfriendStatus(nick);
    C6Users::C6Users tmp = c6user;
    setNetfriendProperty(tmp);
    mainDialog->refreshList();

    QWidget *temp = const_cast<ChatView*>(getChatViewPtr(nick));

    if (_global->getTabActivated())
    {
        if(temp !=0)
        {
            tabHandler->updateTabIcon(*temp,c6user.getStatus());
        }
    }

    if (oldStatus == C6Users::U_OFFLINE)
    {
        if (_global->isInSpecialList(nick) == true)
        {
            if(settings.getSpecialFriendSwitch() == true)
            {
                playWav(settings.getSpecialFriendWav());
            }

            if (settings.getSpecialNotifySwitch() == true)
            {
                emit specialChatNotify(nick,c6user.getStatus());
            }
        }
        else
        {
            if (settings.getOnlineMessageSwitch() == true)
            {
                playWav(settings.getOnlineMessageWav());
            }
        }

        WriteOnSystemLog(nick+" now is ONLINE");
    }

    ChatView *chat = reinterpret_cast<ChatView*>(temp);

    if (chat != 0)                                                                                // if a chat is open
    {
        if (chat->isOnline() == false)                                                 // going from offline to online both for netfriend or not
        {
            notifyOnOfflineStatus(nick,c6user.getStatus(),true);
            chat->setOnlineStatus(true);
        }
    }
}


/*!
    \fn C6::hideTabWidget()
 */
void C6::hideTabWidget()
{
    disconnect(tabHandler,SIGNAL(currentChanged(QWidget*)),this,SLOT(currentTabChanged(QWidget*)));
    deleteReadChat();
    connect(tabHandler,SIGNAL(currentChanged(QWidget*)),this,SLOT(currentTabChanged(QWidget*)));
}

void C6::forceClientExit()
{
    disconnect(_c6socket,SIGNAL(SignalOffline(bool)),this,SLOT(closeConnection(bool)));
    clientExit();
    exitClicked();
}

void C6::checkIfIdle()
{
#if !defined(Q_OS_MACX) && !defined(Q_OS_DARWIN)
    static XScreenSaverInfo *mit_info = 0;
    QWidgetList *list = QApplication::topLevelWidgets();
    QWidgetListIt it(*list);
    QWidget *w = it.current();
    delete list;

    if (w != 0)
    {
        if (mit_info == 0)
        {
            int event_base=0;
            int error_base=0;

            if(XScreenSaverQueryExtension(w->x11Display(), &event_base, &error_base))
            {
                mit_info = XScreenSaverAllocInfo ();

                if (mit_info == 0)
                {
                    qWarning( "No XScreenSaver extension found on XServer, auto-away disabled.\n");
                    _idleTimer->stop();
                    return;
                }
            }
        }

        if (!XScreenSaverQueryInfo(w->x11Display(), qt_xrootwin(), mit_info))
        {
            qWarning("XScreenSaverQueryInfo failed,auto-away disabled.\n");
            _idleTimer->stop();
            return;
        }

        long  idleTime = mit_info->idle / 1000;
        tryAway(idleTime);
    }
#else
    tryAway(secondsIdle);
#endif
}

void C6::tryAway(long idleTime)
{
    C6Settings &settings = C6Settings::getInstance();

    if (idleTime > settings.getMinutesAway()*60)
    {
        if (awayState == false)
        {
            awayState = true;
            setAwayMode(true);
        }
    }

    if (idleTime == 0)
    {
        if (settings.getBackAutoAway() == true)
        {
            if (awayState == true)
            {
                setAwayMode(false);
            }
            awayState = false;
        }
    }
}

void C6::setAwayMode(bool state)
{
    if (_c6socket != 0)
    {
        if (state == true)
        {
            previousState = mainDialog->getOnlineStatus();
            if (previousState != C6Users::U_AWAY)
            {
                _c6socket->changeStatus(C6Users::U_AWAY);
                mainDialog->setOnlineStatus(C6Users::U_AWAY);
                emit statusChanged(C6Users::U_AWAY);
            }
        }
        else
        {
            if (previousState != C6Users::U_AWAY)
            {
                _c6socket->changeStatus(previousState);
                mainDialog->setOnlineStatus(previousState);
                emit statusChanged(previousState);
            }
        }
    }
}

void C6::changeMyStatus(C6Users::C6USER_STATUS status,const QString& message)
{
    if (_c6socket != 0)
    {
        _c6socket->changeStatus(status,message,true);
        awayState = false;
        
        if (message != QString::null)
        {
            const QString messageODD = mainDialog->getMessageODD();    
            _global->saveCurrentMessageODDay(loginDialog->getLogin(),messageODD);         
        }    
    }
              
    emit statusChanged(status);
}

void C6::playSoundOnReceivedMessage()
{
    C6Settings &settings = C6Settings::getInstance();

    if (settings.getSoundSwitch() == true)
    {
        if (settings.getInMessageSwitch() == true)
        {
            playWav(settings.getInMessageWav());
        }
    }
    else
    {
        if (settings.getBeepSwitch() == true)
        {
            qApp->beep();
        }
    }
}

/*!
    \fn C6::addGroup(const QString & group)
 */
void C6::addGroup(const QString & group)
{
    bool ok;
    QString text = QInputDialog::getText("Aggiungi un nuovo gruppo", "Inserisci il nome gruppo:",
                                         QLineEdit::Normal,QString::null, &ok);

    text = text.stripWhiteSpace();

    if (ok == true)
    {
        if (text.length() > 0)
        {
            if (_global->groupIsPresent(text) == true)
            {
                messageBox("Attenzione",QString::fromUtf8("Gruppo già presente !"));
            }
            else
            {
                _c6socket->addGroup(text);
                _global->addGroup(text);
                mainDialog->refreshList();
            }
        }
        else
        {
            messageBox("Attenzione",QString::fromUtf8("Nome di gruppo non corretto o vuoto !"));
        }
    }
}


/*!
    \fn C6::removeGroup(const QString & group)
 */
void C6::removeGroup(const QString & group)
{
    if (_global->removeGroup(group) == false)
    {
        messageBox("Attenzione",QString::fromUtf8("Non posso eliminare questo gruppo o ci sono utenti che è necessario rimuovere prima !"));
    }
    else
    {
        _c6socket->removeGroup(group);
        mainDialog->refreshList();
    }
}


/*!
    \fn C6::deleteAllChat()
 */
void C6::deleteAllChat()
{
    ChatView *tmp=0;

    for(tmp = ChatForm.first(); tmp; tmp = ChatForm.next())
    {
        tmp->deleteLater();    
    }

    ChatForm.clear();
    _portBindChatVector.clear();
}


/*!
    \fn C6::deleteAllRooms()
 */
void C6::deleteAllRooms()
{
    ChatRoom *tmp=0;

    for(tmp = chatRoomList.first(); tmp; tmp = chatRoomList.next())
    {
        tmp->deleteLater();
    }

    chatRoomList.clear();
}

/*!
    \fn C6::inviteNetfriend(QString &nick,QString &room,QString &message))
 */
void C6::inviteNetfriend(const QString &room,const QStringList &nick,const QString &message)
{
    C6Proto::C6MessageStyle style;
    style.setMessageType(C6Proto::INVITE);

    for (unsigned int i=0; i < nick.count(); i++)
    {
        _c6socket->sendMessage(nick[i],true,INVITEMESS(room,message),style);
    }
}


/*!
    \fn C6::renameGroup(QString const & group)
 */
void C6::renameGroup(QString const & group)
{
    bool ok;
    QString text = QInputDialog::getText("Rinomina gruppo", "Nuovo nome del gruppo:",
                                         QLineEdit::Normal,QString::null, &ok);

    text = text.stripWhiteSpace();

    if (ok && !text.isEmpty())
    {
        if (_global->renameGroup(group,text) == true)
        {
            _c6socket->renameGroup(group,text);
            mainDialog->refreshList();
        }
        else
        {
            messageBox("Attenzione",QString::fromUtf8("Non è possibile rinominare questo gruppo !"));
        }
    }
}


/*!
    \fn C6::deleteReadChat()
 */
void C6::deleteReadChat()
{
    ChatView* chat = ChatForm.first();
    
    while ((chat = ChatForm.current()))
    {
        if (chat->isMessaged() == false)
        {
            freeBindPort(chat->getServerPort());    

            disconnect(this,SIGNAL(specialChatNotify(QString,C6Users::C6USER_STATUS)),chat,
                       SLOT(specialChatNotify(QString,C6Users::C6USER_STATUS)));

            delete chat;

            ChatForm.remove(chat);
        }         
    }          
}


/*!
    \fn C6::changeTabName(ChatView *chat,QString const &caption)
 */
void C6::changeTabName(ChatView *chat,QString const &caption)
{
    tabHandler->disconnect(SIGNAL(currentChanged(QWidget*)));
    tabHandler->changeTabName(chat,caption);
    connect(tabHandler,SIGNAL(currentChanged(QWidget*)),this,SLOT(currentTabChanged(QWidget*)));
}

void C6::reloadInitialization()
{
    _c6socket->retrieveStuffFromServer();
}

void C6::parseBuddyList(QByteArray &data)
{
    QDomDocument doc("buddylist");
    doc.setContent(data);

    QDomElement docElem = doc.documentElement();
    QString groupName;
    QString user;
    QString displayName;

    QDomNodeList error = doc.elementsByTagName("xcap-error");

    if (error.count() > 0)                                  // old account or buddy list not present
    {
        _c6socket->initBuddyList();
    }
    else
    {
        QDomNodeList list = doc.elementsByTagName("list");
        for (unsigned int i=1; i < list.count(); i++)                 // skip the first item
        {
            QDomNode listnode = list.item(i);
            QDomElement group = listnode.toElement();
            if(!group.isNull())
            {
                groupName = group.attribute("name");

                if (groupName.length() > 0)
                {
                    _global->addGroup(groupName);
                }

                QDomNode entrylist = listnode.firstChild();

                while (!entrylist.isNull() )
                {
                    QDomElement entry = entrylist.toElement();

                    if (entry.tagName().compare("entry") == 0)
                    {
                        user = entry.attribute("uri").section(":",1,1);

                        QDomNode displayNameList = entry.firstChild();
                        while (!displayNameList.isNull())
                        {
                            if (displayNameList.nodeName().compare("display-name") == 0)
                            {
                                displayName = displayNameList.toElement().text();
                                break;
                            }
                            displayNameList = displayNameList.nextSibling();
                        }
                    }

                    addUser(groupName,user,displayName);
                    entrylist = entrylist.nextSibling();
                }
            }
        }
    }
}

void C6::parseBuddyAuth(QByteArray &data)
{
    QDomDocument doc("buddyauth");
    doc.setContent(data);

    QString groupName;
    QString user;
    QString displayName;

    QDomNodeList error = doc.elementsByTagName("xcap-error");

    if (error.count() > 0)
    {
        _c6socket->initAuthorization();
    }
    else
    {
        QDomNodeList list = doc.elementsByTagName("blacklist");

        for (unsigned int i=0; i < list.count(); i++)                 // should be one element
        {
            QDomNode listnode = list.item(i);
            QDomNode entry = listnode.firstChild();

            while (!entry.isNull())
            {
                if (entry.nodeName().compare("entry") == 0)
                {
                    user = entry.toElement().attribute("uri");

                    QDomNode displayNameList = entry.firstChild();
                    while (!displayNameList.isNull())
                    {
                        if (displayNameList.nodeName().compare("display-name") == 0)
                        {
                            displayName = displayNameList.toElement().text();
                            break;
                        }
                        displayNameList = displayNameList.nextSibling();
                    }
                }

                addUser(_global->getBlackListGroupName(),user,displayName);
                entry = entry.nextSibling();
            }
        }

        list = doc.elementsByTagName("whitelist");

        for (unsigned int i=0; i < list.count(); i++)
        {
            QDomNode listnode = list.item(i);
            QDomNode entry = listnode.firstChild();

            while (!entry.isNull())
            {
                if (entry.nodeName().compare("entry") == 0)
                {
                    user = entry.toElement().attribute("uri");

                    QDomNode displayNameList = entry.firstChild();
                    while (!displayNameList.isNull())
                    {
                        if (displayNameList.nodeName().compare("display-name") == 0)
                        {
                            displayName = displayNameList.toElement().text();
                            break;
                        }
                        displayNameList = displayNameList.nextSibling();
                    }
                }

                _global->addToWhiteList(user,displayName);
                entry = entry.nextSibling();
            }
        }

        sendUserList();
        _c6socket->getOfflineMessage();              
    }
}

void C6::parseBuddyConfig(QByteArray &data)
{
    QDomDocument doc("buddyconfig");
    doc.setContent(data);
    QDomNodeList error = doc.elementsByTagName("xcap-error");

    safeInitCounter++;

    if (error.count() > 0)
    {
        _c6socket->initConfiguration();
        if (safeInitCounter < 2)
        {
            QTimer::singleShot(200,this,SLOT(reloadInitialization()));
        }
    }
    else
    {
        QDomNodeList auth = doc.elementsByTagName("warnings");

        if (auth.count() > 0)
        {
            QDomNode entry = auth.item(0);
            QString authtext = entry.toElement().text();
            _c6socket->setAuthorizationMode(authtext);
        }

        QDomNodeList message = doc.elementsByTagName("reachability");

        if (message.count() > 0)
        {
            QDomNode entry = message.item(0);
            QString messagetext = entry.toElement().text();
            _c6socket->setOfflineMessageMode(messagetext);
        }
    }
}

void C6::saveNetfriendList()
{
    if (_c6socket->isOldAccount() == true)                 // load friendlist from file
    {
        _global->saveNetfriendList();
    }
}

void C6::infoLogin(bool oldAccount)
{
    if (oldAccount == true)
    {
        _global->loadNetfriendListFromFile();
        sendUserList();
        _c6socket->getOfflineMessage();             
    }
}

/*!
    \fn C6::acceptReception(bool accept)
 */
void C6::acceptReception(bool accept,const QString & from)
{
    ChatView *temp = const_cast<ChatView*>(getChatViewPtr(from));

    if (temp != 0)
    {
        if (accept == true)
        {
            int port = 0;
            QString ip;

            _c6socket->getGateway(ip,port);
            temp->activateFileServer(ip,port);
            temp->serviceMessage(ACCEPT_SERVICEMSG);
        }
        else
        {
            C6Proto::C6MessageStyle style;
            style.setMessageType(C6Proto::SELF);         
            style.setOperationType(C6Proto::REQUEST_FILE_DENY);

            QString mess = ACCEPT_DENYMSG;
            _c6socket->sendMessage(from,true,mess,style);
            temp->serviceMessage(ACCEPT_DENYSERVICEMSG);
        }
    }
}


/*!
    \fn C6::mergeLocalList()
 */
bool C6::mergeLocalList(bool firstAttempt)
{
    bool ret = false;    
    QString message = MERGE_MSG;    
    
    if (firstAttempt == true)
    {
        message = FIRST_ATTEMPT_STR_BEGIN + MERGE_MSG + FIRST_ATTEMPT_STR_END;     
    }          
    
    QMessageBox box("Attenzione",message,QMessageBox::Warning,
                    QMessageBox::Ok,QMessageBox::Cancel,
                    QMessageBox::NoButton,loginDialog);
    
    if (box.exec() == QMessageBox::Ok)
    {
        if (_global->mergeLocalListToServerSide() == true)
        {
            mainDialog->refreshList();
            QStringList tmp = getNickStringList();
            _c6socket->sendUserRequest(tmp);

            C6Proto::ListType list;
            QStringList groups = _global->getAllGroups();

            for(unsigned int i=0; i < groups.count(); i++)
            {
                if (groups[i].compare(_global->getBlackListGroupName()) != 0)
                {
                    QStringList nicks = _global->getGroupUsers(groups[i]);
                    list[groups[i]] = nicks;
                }
            }

            QStringList const& blacklist = _global->getBlackListUsers();
            QStringList const& whitelist = _global->getWhiteListUsers();

            _c6socket->setBuddyLists(list,blacklist,whitelist);
            ret = true;    
        }
        else
        {
            messageBox("Attenzione",NO_LISTMSG);
        }
    }
    return(ret);   
}


/*!
    \fn C6::addNickDialog()
 */
void C6::addNickDialog(QString const & group)
{
    bool ok = false;
    QString nick = QInputDialog::getText("Aggiungi un nuovo amico", "Inserisci il nick:",
                                         QLineEdit::Normal,QString::null, &ok);
    
    if (ok == true)
    {          
        nick = nick.simplifyWhiteSpace().lower();
        nick.replace(QChar(' '),QChar('_'));

        bool error = false;
              
        if (nick.isEmpty() == false && nick.length() > 1)
        {
            QRegExp checkEmailAddress("[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[_A-Za-z0-9-]+)");
                
            if (checkEmailAddress.search(nick) == -1)
            {
                QRegExp checkNickValidity("[^a-z0-9\\._-@]");
                    
                if (checkNickValidity.search(nick) >= 0)
                {
                    messageBox("Attenzione", WARN_NICK_FORMAT);
                    error = true;    
                }                   
            }                   
            
            if (error == false)
            {                   
                if (group.compare(_global->getWhiteListGroupName()) == 0)
                {
                    if (_global->isWhiteListed(nick))
                    {
                        messageBox("Attenzione","L'utente "+nick+" è già stato autorizzato");
                    }
                    else
                    {
                        _c6socket->addBuddyToWhiteList(nick);
                        _global->addToWhiteList(nick);
                        mainDialog->refreshList();
                    }
                }
                else
                {
                    if (getNetfriendStatus(nick) == C6Users::U_NOTPRESENT)
                    {
                        addUser(group,nick);
                        _c6socket->sendUserRequest(nick);
                        saveNetfriendList();
                        mainDialog->refreshList();
                    }
                    else
                    {
                        messageBox("Attenzione",QString::fromUtf8("Nick già presente in lista"));
                    }
                }
            }
        }
        else
        {
            messageBox("Attenzione",WARN_NICK_LENGTH);         
        }      
    }   
}


/*!
    \fn C6::acceptAuthorization(bool accept,const QString & from)
 */
void C6::acceptAuthorization(bool accept,const QString & from)
{
    if (accept == true)
    {
        if (_global->isWhiteListed(from) == false)
        {               
            _c6socket->addBuddyToWhiteList(from);
            _global->addToWhiteList(from);
            mainDialog->refreshList();
            ChatView *tmp = const_cast<ChatView*>(getChatViewPtr(from));         
            if (tmp !=0)
            {
                tmp->serviceMessage(ADD_TO_WHITELIST_MSG(from));
            }                
        }         
    }
}

void C6::sendChatMessage(QString& nick, bool isOnline, QString& message)
{
    C6Proto::C6MessageStyle style;
    ChatView *chat = const_cast<ChatView*>(getChatViewPtr(nick));
    if (chat != 0)
    {
        QColor &color = chat->getCurrentWritingColor();      
        style.setBold(chat->isBoldToggled());
        style.setItalics(chat->isItalicToggled());
        style.setUnderline(chat->isUnderlineToggled());
        style.setRGB(color.red(),color.green(),color.blue());                
        style.setFontTypeNo(chat->getCurrentFontNo());
        style.setFontSizePt(chat->getCurrentFontSizePt());   
        if (_c6socket->isConnected() == true)
        {         
            _c6socket->sendChatMessage(nick,isOnline,message,style);
        }         
    }          
}
      

/*!
    \fn C6::roomMenuUserAction(const QString& roomName,const QString& nick,USER_MENU_ACTIONS action)
 */
void C6::roomMenuUserAction(const QString& roomName,const QString& nick,USER_MENU_ACTIONS action)
{
    if (action >=MOVE)                 // handles this special case, ugly
    {
        QStringList groups = C6Global::getInstance().getAllGroups();
        doMenuAction(nick,ADDROOTNICK,groups[action-MOVE]);      
    }
    else
    {      
        doMenuAction(nick,action,roomName);
    }      
}


/*!
    \fn C6::askForPassword(const QString& roomName)
 */
void C6::askForPassword(const QString& roomName)
{
    bool ok;
    QString text = QInputDialog::getText("Richiesta password per la stanza <b>"+roomName, "Inserisci la password:",
                                         QLineEdit::Normal,QString::null, &ok);

    text = text.stripWhiteSpace();

    if (ok == true)
    {
        if (text.length() > 0)
        {
            enterRoom(roomName,const_cast<QString&>(text));         
        }
    }               
}


/*!
    \fn C6::void searchByNick(const QString& nick);   
 */
void C6::searchByNick(const QString& nick)
{
    _c6socket->searchByNick(nick);
}


/*!
    \fn C6::searchResultsFound(QStringList*,std::vector<C6Users::C6USER_STATUS>)
 */
void C6::userSearchResultsFound(QStringList* list,std::vector<C6Users::C6USER_STATUS> status)
{
    searchDialog->showResults(list,status);
}


/*!
    \fn C6::showFullUserProfile(QString const& nick)
 */
void C6::showFullUserProfile(QString const& nick)
{
    QString tmp = _c6socket->getProfileUrl();         
    if (tmp.length() > 0)
    {                
        tmp.replace("%onick",nick);
        execUrl(tmp);
    }           
}


/*!
    \fn C6::showUserProfile(const QString&,bool full)
 */
void C6::showUserProfile(const QString& nick,bool full)
{
    if (full == true)
    {
        showFullUserProfile(nick);      
    }      
    else
    {
        showShortProfile(nick);      
    }          
}


/*!
    \fn C6::openChat()
 */
void C6::openChat()
{
    bool ok = false;
    QString nick = QInputDialog::getText("Inizia una chat con un nuovo amico", "Inserisci il nick:",
                                         QLineEdit::Normal,QString::null, &ok);
    
    if (ok == true)
    {          
        nick = nick.simplifyWhiteSpace().lower();
        nick.replace(QChar(' '),QChar('_'));

        bool error = false;
              
        if (nick.isEmpty() == false && nick.length() > 1)
        {
            QRegExp checkEmailAddress("[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[_A-Za-z0-9-]+)");
                
            if (checkEmailAddress.search(nick) == -1)
            {
                QRegExp checkNickValidity("[^a-z0-9\\._-@]");
                    
                if (checkNickValidity.search(nick) >= 0)
                {
                    messageBox("Attenzione", WARN_NICK_FORMAT);
                    error = true;    
                }                   
            }                   
            
            if (error == false)
            {             
                buildChat(nick,false);         
            }
        }
        else
        {
            messageBox("Attenzione",WARN_NICK_LENGTH);         
        }      
    }   
}


/*!
    \fn C6::showMainDialog(int progress)
 */
void C6::showMainDialog(int progress)
{
    if (progress >= 100)
    {
        mainDialog->show();     
        C6Global &global = C6Global::getInstance();
            
        if (global.isFirstAccountLoginAttempt(loginDialog->getLogin()) == true)
        {
            if (global.localNetfriendListExists() == true)
            {            
                mergeLocalList(true);
            }            
            global.setFirstAccountLoginAttempt(loginDialog->getLogin()); 
        }             
    }      
}

/*!
    \fn C6::calibrateSystemFontSize()
 */
void C6::calibrateSystemFontSize()
{
    const int myConstWidth = 160;
    QFont sysFont = QApplication::font();
    unsigned int safeCounter = myConstWidth;
    bool nowIsOk = true;
    C6Settings &settings = C6Settings::getInstance();

    if (settings.getSelectGlobalFont() == false)
    {
        while (nowIsOk && safeCounter)
        {
            QFontMetrics fontMetrics(sysFont);
            int curWidth = fontMetrics.width("openc6 the c6 linux client");

            if (curWidth > myConstWidth)
            {
                int size = sysFont.pointSize()-1;

                if (size > 0)
                {
                    sysFont.setPointSize(size);
                }
            }
            else
            {
                nowIsOk = false;
            }
            safeCounter--;
        }
    }
    else
    {
        sysFont.setPointSize(settings.getGlobalFontSize());
        sysFont.setWeight(settings.getGlobalFontWeight());
        sysFont.setFamily(settings.getGlobalFontFamily());
    }
    
    _global->setBaseFont(sysFont);
}

/*!
    \fn C6::setFontOnWidget(QFont const& font)
 */
void C6::setFontOnWidgets()
{
    mainDialog->setCustomFont(); 
    loginDialog->setCustomFont();     
    searchDialog->setCustomFont();   
    reportDialog->setCustomFont();    
    aboutDialog->setCustomFont();      
    roomList->setCustomFont();     
}
