/***************************************************************************
 *   Copyright (C) 2004 by Sevin Roland                                    *
 *   upsis@club-internet.fr                                                *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/


#include "C_DlgMainDialog.h"

#include <qvariant.h>
#include <qmessagebox.h>
#include <qfiledialog.h>
#include <qeventloop.h>
#include <qlistbox.h>
#include <qpushbutton.h>
#include <qlabel.h>
#include <qprogressbar.h>
#include <qtabwidget.h>
#include <qwidget.h>
#include <qgroupbox.h>
#include <qcheckbox.h>
#include <qlineedit.h>
#include <qcombobox.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qstring.h>

#include "CApp.h"
#include "../../MedinTuxTools/CHtmlTools.h"
#include "../../MedinTuxTools/CW_EditText.h"
#include "../../MedinTuxTools/C_Huffman.h"
#include "../../MedinTuxTools/C_Zlib/C_Zlib.h"
#include <qdir.h>
#include <qfileinfo.h>
#include <qcolor.h>

#define INSTALL_BASE_GET               FALSE
#define INSTALL_BASE_DATASEMP          TRUE
#define INSTALL_VIDAL_RUN              TRUE
#define INSTALL_VIDAL_NOTRUN           FALSE
#define MAKE_EXE_RUN                   TRUE
#define MAKE_EXE_NOTRUN                FALSE

#ifdef Q_WS_X11
  #define F_EXE
#endif

#ifdef Q_WS_WIN
 #define F_EXE ".exe"
#endif

#ifdef  Q_WS_MAC
  #define F_EXE
#endif



C_DlgMainDialog::C_DlgMainDialog(QWidget* parent, const char* name, bool modal, WFlags fl)
    : Dlg_MainDialog(parent,name, modal,fl)
{
    connect( quitPushButton, SIGNAL( clicked() ), this, SLOT( close() ) );
    connect( pushButton_SetBases, SIGNAL( clicked() ), this, SLOT( pushButton_SetBases_clicked() ) );
    connect( pushButton_LancerDrTux, SIGNAL( clicked() ), this, SLOT( pushButton_LancerDrTux_clicked() ) );
    connect( pushButton_SetDatasemp, SIGNAL( clicked() ), this, SLOT( pushButton_SetDatasemp_clicked() ) );
    connect( pushButtonJustOneTable, SIGNAL( clicked() ), this, SLOT( pushButtonJustOneTable_clicked() ) );
    connect( checkBox_STD_MAJ, SIGNAL( stateChanged(int) ), this, SLOT( checkBox_STD_MAJ_stateChanged(int) ) );
    connect( checkBox_SQL_MAJ, SIGNAL( stateChanged(int) ), this, SLOT( checkBox_SQL_MAJ_stateChanged(int) ) );
    connect( pushButtonSwitchGetDatasemp, SIGNAL( clicked() ), this, SLOT( pushButtonSwitchGetDatasemp_clicked() ) );
    connect( pushButtonConnexionAppl, SIGNAL( clicked() ), this, SLOT( pushButtonConnexionAppl_clicked() ) );
    connect( pushButton_compilation, SIGNAL( clicked() ), this, SLOT( pushButton_compilation_clicked() ) );
    connect( pushButton_MajBases, SIGNAL( clicked() ), this, SLOT( pushButton_MajBases_clicked() ) );
    connect( comboBox_IP_Fav, SIGNAL( activated(const QString&) ), this, SLOT( comboBox_IP_Fav_activated(const QString&) ) );
    connect( comboBox_IP_Fav, SIGNAL( highlighted(const QString&) ), this, SLOT( comboBox_IP_Fav_highlighted(const QString&) ) );
    connect( pushButton12, SIGNAL( clicked() ), this, SLOT( pushButton12_clicked() ) );
    connect( pushButtonRemove, SIGNAL( clicked() ), this, SLOT( pushButtonRemove_clicked() ) );
    connect( pushButtonImagesCopy, SIGNAL( clicked() ), this, SLOT( pushButtonImagesCopy_clicked() ) );
    connect( pushButtonMakeSQL, SIGNAL( clicked() ), this, SLOT( pushButtonMakeSQL_clicked() ) );
    connect( pushButton_LireVitale, SIGNAL( clicked() ), this, SLOT( pushButton_LireVitale_clicked() ) );
    connect( pushButton_InstallSesam, SIGNAL( clicked() ), this, SLOT( pushButton_InstallSesam_clicked()) );
    connect( pushButton_IndexerDatasemp, SIGNAL( clicked() ), this, SLOT( pushButton_IndexerDatasemp_clicked()) );

    textLabel_AdminLinux->hide();
#ifdef  Q_OS_MACX
    textLabel_AdminLinux->setText("Sous Apple, se mettre EN MODE ADMINISTRATEUR");
    textLabel_AdminLinux->show();
#endif
#ifdef  Q_WS_X11
    textLabel_AdminLinux->show();
#endif
    QString path = G_pCApp->Construct_Name_File_Ini("set_bases",QFileInfo (qApp->argv()[0]).dirPath (true),"");
    G_pCApp->Param_Init(path);
    progressBar_Load->setIndicatorFollowsStyle(TRUE);
    textEdit_Message->setWordWrap ( QTextEdit::NoWrap );
    m_proc               = 0;
    m_pCUpdateThread     = 0;
    m_pCIndexMakeThread  = 0;
    m_pQTimer            = 0;
    m_pCindexQTimer      = 0;
    m_ProgressTotal      = 0;
    m_DatasempDir        = "";
    m_DatasempBase       = 0;
    m_pCMedicaBase       = 0;
    m_pCMoteurBase       = 0;
    m_TestBasesProc      = 0;
    m_PluginRun          = "";
    m_testBaseProcRun    = FALSE;
    m_BaseToInstallFlag  = INSTALL_BASE_GET;
    m_BaseVidalRun       = INSTALL_VIDAL_NOTRUN;
    m_MakeExeRun         = MAKE_EXE_NOTRUN;
    int mode             = GetDatasempMode();
    m_MessageNoConnect   = tr("\n================= CONNEXION INTERROMPUE==================\n"
                              "\n Veuillez choisir de nouveaux paramètres de connexion au serveur "
                              "\n de données MySQL soit : le nom de connexion, le mot de passe, "
                              "\n et l'adresse IP ou le nom de machine sur laquelle se trouve"
                              "\n le serveur MySQL  (localhost si c'est la machine sur laquelle"
                              "\n vous êtes actuellement)\n"
#ifdef  Q_WS_X11
                              "\n Vérifiez que le paquet : libqt3-mysql est bien installé sur votre système."
                              "\n Si il est installé le fichier suivant : /usr/lib/qt3/plugins/lib/sqldrivers/libqsqlmysql.so"
                              "\n devrait être présent\n"
#endif
                              "\n Puis appuyez sur le bouton 'Se connecter à la base de données''");


    textLabel_MedinTux->setPixmap ( Theme::getIcon( "medintux_logo.png") );


    if (mode&(CApp::Remove|CApp::Insert|CApp::Update))    checkBox_STD_MAJ->setChecked(TRUE);
    else                                                  checkBox_STD_MAJ->setChecked(FALSE);
    if (mode&CApp::SqlFiles)                              checkBox_SQL_MAJ->setChecked(TRUE);
    else                                                  checkBox_SQL_MAJ->setChecked(FALSE);
    G_pCApp->GotoDebug();
    //..................... recuperer les paramètres de connexion ....................................
    QString  driverName , baseName , userName , passWord, hostName;
    if (G_pCApp->Param_ReadParam( "DrTuxTest", "Connexion",
                                  &driverName, &baseName, &userName, &passWord, &hostName) !=0
        )  // zero = pas d'erreur
    {   driverName  = "QMYSQL3";
        baseName    = "DrTuxTest";
        userName    = "root";
        passWord    = "";
        hostName    = "localhost";
    }
    lineEdit_UserName->setText(userName);
    lineEdit_PassWord->setText(passWord);
    lineEdit_Hostname->setText(hostName);
    //...................... lire parametrage base Get ou Datasemp .................................
    path = G_pCApp->Construct_Name_File_Ini("drtux", QFileInfo (qApp->argv()[0]).dirPath (true),"MedicaBase.ini");
    // Affichage dans la Box
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n================= Lecture Base Get ou Datasemp ")
                                 + path + "=================");

    if (  ! QFile::exists (path) ) {
        G_pCApp->Datasemp_OutMessage(textEdit_Message, "\n Ce fichier n'existe pas");
        return ;
    }

    QString param, parametreBase;
    CGestIni::Param_UpdateFromDisk(path, param);
    CGestIni::Param_ReadParam(param, "Connexion" , "InUseBase" ,  &parametreBase);
    if ( parametreBase == "Parametres MedicaBase")
    {   pushButtonSwitchGetDatasemp->setText(tr("Activer la &base Get"));
        m_BaseToInstallFlag  = INSTALL_BASE_GET;
    }
    else
    {   pushButtonSwitchGetDatasemp->setText(tr("Activer la &base Datasemp"));
        m_BaseToInstallFlag  = INSTALL_BASE_DATASEMP;
    }
    textEdit_Message->setText("");
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n================= Bienvenue sur MedinTux =================="
                                                      "\n Veuillez choisir les paramètres de connexion au serveur de"
                                                      "\n données MySQL soit : le nom de connexion, le mot de passe, "
                                                      "\n et l'adresse IP ou le nom de machine sur laquelle se trouve"
                                                      "\n le serveur MySQL  (localhost si c'est la machine sur laquelle"
                                                      "\n vous êtes actuellement)\n"
                                                      "\n Puis appuyez sur le bouton 'Se connecter à la base de données'"));
    //..................... remplir combo des executables ...............................................
    comboBox_Executables->insertItem( tr("Tous les programmes"),0);
    //..................... remplir combo des bases .....................................................
    comboBox_Bases->insertItem( tr("Toutes les bases"));
    comboBox_Bases->insertStringList (G_pCApp->GetBaseList());

#ifdef Q_WS_WIN
    pushButton_compilation->hide();
    comboBox_Executables->hide();
    textLabel_RootField->hide();
    lineEdit_RootPass->hide();
    comboBox_PortLecteur->hide();
    lineEdit_SesamPath->setText("C:\\");
    lineEdit_BinaryPath->setText("C:\\WINDOWS");
    //comboBox_PortLecteurWin->setText();
#endif

#ifdef Q_WS_X11
    pushButtonMakeSQL->show();

    //textLabel_RootField->hide();
    //lineEdit_RootPass->hide();
    lineEdit_SesamPath->hide();
    textLabel_SesamPath->hide();
    //textLabel_WindPathField->hide();
    //lineEdit_BinaryPath->hide();
    comboBox_PortLecteurWin->hide();
    //lineEdit_SesamPath->setText("/usr/local");
    lineEdit_BinaryPath->setText("/usr/local");
#endif
#ifdef Q_OS_MACX
    pushButtonMakeSQL->show();

    //textLabel_RootField->hide();
    //lineEdit_RootPass->hide();
    lineEdit_SesamPath->hide();
    textLabel_SesamPath->hide();
    //textLabel_WindPathField->hide();
    //lineEdit_BinaryPath->hide();
    comboBox_PortLecteurWin->hide();
    //lineEdit_SesamPath->setText("/usr/local");
    lineEdit_BinaryPath->setText("/usr/local");
#else
    pushButtonMakeSQL->hide();
#endif
    //............................. titre du group box de compilation .....................................
    QString version;
    if (G_pCApp->Param_ReadParam( "CONFIG", "Version", &version) !=0 )  // zero = pas d'erreur
    {version = "0.09";
    }
    QString title = tr("Installation de la suite logicielle : MedinTux © 2005-2006 DATA MEDICAL DESIGN Version Libre");
    if ( IsCommercialVersionExist()  )
    {title = tr("Installation de la suite logicielle : MedinTux © 2005-2006 DATA MEDICAL DESIGN  Version Commerciale");
        comboBox_Executables->insertItem ( "QFseVitale" );
    }
    else
    {tabWidgetInstall->setTabEnabled ( tabWidgetInstall->page ( 1 ), FALSE );
    }
    groupBoxMedinTuxInstall->setTitle( title );
    SetTitle(GetMAJVersion());

    // Vérification existence du repertoir module tmp
    path = G_pCApp->Construct_PathBin_Module("set_bases", QFileInfo (qApp->argv()[0]).dirPath (true)) + "../../tmp";
    QDir dir(path);
    if (!dir.exists()) dir.mkdir (path);

    fillFavoris();
    comboBox_IP_Fav_insertItem("QMYSQL3,root,,localhost"); // faut s'assurer qu'il y est
    groupBoxMedinTuxInstall->hide();
    pushButton_SetBases->hide();
    pushButton_MajBases->hide();
    comboBox_Bases->hide();
    tabWidgetInstall->hide();
    //textEdit_Message->setTextFormat (Qt::AutoText );
}

C_DlgMainDialog::~C_DlgMainDialog()
{
}

/*$SPECIALIZATION$*/

//----------------------------------------- saveFavoris ---------------------------------------------
void C_DlgMainDialog::SetTitle(QString n_Version)
{setCaption( tr("DATA MEDICAL DESIGN   ( Installation et configuration de MedinTux )") + " V : " + n_Version);
}

//----------------------------------------- saveFavoris ---------------------------------------------
void C_DlgMainDialog::saveFavoris()
{ /*
  int nb =  comboBox_IP_Fav->count();
  for (int i=0; i<nb; ++i)
    { G_pCApp->Param_WriteParam( "Favoris", QString::number(i) , comboBox_IP_Fav->text(i));
    }
  G_pCApp->Param_UpdateToDisk();
  */

    //
    QString        val1;
    QString      section   = "";
    QString     var_name   = "";
    const char      *txt   = G_pCApp->m_ParamData;
    char             *pt   = (char*) txt;
    char     *prop_section = 0;       // permet de noter le pointeur sur la section propriete renouvelable/intercurent des produits

    //.................................. virer la section des variables ........................................................;
    while((pt=m_pCMoteurBase->Param_GotoNextSection(pt, 0, &section)) && *pt)
    {
        if (section=="Favoris")
        {char* pt_deb_var = pt;          //pointe à la ligne du mot '[Favoris]' donc au debut des variables
            while (*pt && *pt != '[')
            {pt = m_pCMoteurBase->Param_ExtraireNextValeurs(pt, var_name, &val1);
            }
            G_pCApp->m_ParamData.remove(pt_deb_var - txt, pt - pt_deb_var);
            break;
        }
    }
    //.................................. remplir la section des variables ........................................................;
    int nb =  comboBox_IP_Fav->count();
    for (int i=0; i<nb; ++i)
    {// pt = m_pCMoteurBase->Param_ExtraireNextValeurs(pt, var_name, &driver, &user, &pass, &hostname);
        G_pCApp->Param_WriteParam( "Favoris", QString::number(i) , comboBox_IP_Fav->text(i));
    }
    G_pCApp->Param_UpdateToDisk();   // ecrire et mettre à jour le fichier sur le disque
}

//----------------------------------------- fillFavoris ---------------------------------------------
void C_DlgMainDialog::fillFavoris()
{
    // 1 = QMYSQL3,hp_ro, ,192.168.2.10
    QString        driver, user, pass,hostname;
    QString      section   = "";
    QString     var_name   = "";
    const char      *txt   = G_pCApp->m_ParamData;
    char             *pt   = (char*) txt;
    char     *prop_section = 0;       // permet de noter le pointeur sur la section propriete renouvelable/intercurent des produits
    while((pt=m_pCMoteurBase->Param_GotoNextSection(pt, 0, &section)) && *pt)
    {//.................................. ATCD ........................................................;
        if (section=="Favoris")
        {comboBox_IP_Fav->clear();
            while (*pt && *pt != '[')
            {pt = m_pCMoteurBase->Param_ExtraireNextValeurs(pt, var_name, &driver, &user, &pass, &hostname);
                comboBox_IP_Fav_insertItem(driver.stripWhiteSpace() +","+      // 0
                                           user.stripWhiteSpace()   +","+      // 1
                                           pass.stripWhiteSpace()   +","+      // 2
                                           hostname.stripWhiteSpace());        // 3
            }
            break;
        }
    }
}

//----------------------------------------- comboBox_IP_Fav_activated ---------------------------------------------
void C_DlgMainDialog::comboBox_IP_Fav_activated( const QString &text )
{QStringList list = QStringList::split ( ",", text, TRUE);
    lineEdit_Hostname->setText(*(list.at(3)) );
    lineEdit_UserName->setText(*(list.at(1)) );
    lineEdit_PassWord->setText(*(list.at(2)) );
}

//----------------------------------------- comboBox_IP_Fav_highlighted ---------------------------------------------
void C_DlgMainDialog::comboBox_IP_Fav_highlighted( const QString &text )
{comboBox_IP_Fav_activated( text );
}

//----------------------------------------- pushButton12_clicked ---------------------------------------------
void C_DlgMainDialog::pushButton12_clicked()
{int i = comboBox_IP_Fav_insertItem(QString("QMYSQL3,")                          +
                                    lineEdit_UserName->text().stripWhiteSpace()  +","+
                                    lineEdit_PassWord->text().stripWhiteSpace()  +","+
                                    lineEdit_Hostname->text().stripWhiteSpace());
    if (i==-1) return;
    comboBox_IP_Fav->setCurrentItem ( i );
    saveFavoris();
}

//----------------------------------------- pushButtonRemove_clicked ---------------------------------------------
void C_DlgMainDialog::pushButtonRemove_clicked()
{if (comboBox_IP_Fav->text(comboBox_IP_Fav->currentItem())=="QMYSQL3,root,,localhost") return;
    comboBox_IP_Fav->removeItem ( comboBox_IP_Fav->currentItem() );
    if (comboBox_IP_Fav->count()<=0) comboBox_IP_Fav_insertItem("QMYSQL3,root,,localhost"); // si  il doit en rester un c'est lui
    comboBox_IP_Fav->setCurrentItem (0 );
    comboBox_IP_Fav_activated( comboBox_IP_Fav->text(0) );
    saveFavoris();
}

//----------------------------------------- comboBox_IP_Fav_insertItem ---------------------------------------------
int C_DlgMainDialog::comboBox_IP_Fav_insertItem(const QString &item_txt)
{QListBox *pQListBox = comboBox_IP_Fav->listBox ();
    if (pQListBox==0)  return -1;
    QListBoxItem *pQListBoxItem = pQListBox->findItem ( item_txt, Qt::ExactMatch );
    if (pQListBoxItem) return -1;                  // si il existe déjà cassos
    //int index = comboBox_IP_Fav->index (pQListBoxItem);
    //if (index ==0)     return;
    comboBox_IP_Fav->insertItem ( item_txt );
    return comboBox_IP_Fav->count()-1;
}
//----------------------------------------- destroy ---------------------------------------------
void C_DlgMainDialog::destroy()
{   StopCUpdateThread();
    StopCIndexMakeThread();
    if (m_proc)
    {if (m_proc->isRunning())
        {m_proc->tryTerminate();
            QTimer::singleShot( 5000, m_proc, SLOT( kill() ) );
        }
    }
    if (m_pCMoteurBase!=0) delete m_pCMoteurBase;
    if (m_pCMedicaBase!=0) delete m_pCMedicaBase;
    if (m_TestBasesProc)
    {m_TestBasesProc->tryTerminate();
        QTimer::singleShot( 4000, m_TestBasesProc, SLOT( Kill() ) );
    }
}

//----------------------------------------- pushButton_compilation_clicked ---------------------------------------------
void C_DlgMainDialog::pushButton_compilation_clicked()
{QString target(comboBox_Executables->currentText ());
    if (comboBox_Executables->currentItem ()==0)
        //if (target == tr("Tous les programmes"))
    {AllCompil();
    }
    else
    {OneCompil(target);
    }
}

//----------------------------------------- AllCompil ---------------------------------------------
void C_DlgMainDialog::AllCompil()
{   if (m_MakeExeRun == MAKE_EXE_RUN)
    //if (pushButton_compilation->text()=="Interrompre la compilation des exécutables en cours")
    {if (m_proc==0) return;
        if (m_proc->isRunning())
        {m_proc->tryTerminate();
            QTimer::singleShot( 5000, m_proc, SLOT( kill() ) );
        }
        pushButton_compilation->setText( tr("&Compilation des exécutables") );
        m_MakeExeRun = MAKE_EXE_NOTRUN;
        QApplication::restoreOverrideCursor();
        return;
    }
    int ret = 0;
    if (IsExecutablesExist())
    {ret =  QMessageBox::information( this, tr( "MedinTux demande votre attention" ),
                                      tr( "Les fichiers exécutables semblent déjà exister. \r\n"
                                          "La compilation de ceux-ci est une opération longue.\r\n"
                                          "Voulez-vous toujours la démarrer ?\r\n") ,
                                      tr("&Oui"), tr("&Non"), 0,
                                      1, 1 ) ;

    }
    if (ret != 0)                                     return;

    QString errorsmsg("OK");
    QString path  = CGestIni::Construct_Name_File_Ini("set_bases", QFileInfo (qApp->argv()[0]).dirPath (true), "/setup_part2.sh");
    QString qtdir = CGestIni::Construct_Name_File_Ini("set_bases", QFileInfo (qApp->argv()[0]).dirPath (true), "/../../QT");
    QString command; CGestIni::Param_UpdateFromDisk(path, command);
    int deb = command.find("#----- DEB FOR MAC --------");
    int end = command.find("#----- END FOR MAC --------");
    if ( deb != -1 && end != -1 )
       {command.remove(deb, end + 29 - deb);
       }
#ifdef  Q_WS_MAC
    QString toAdd =  "#! /bin/sh\r\n#----- DEB FOR MAC --------\r\n  QTDIR=\"";
    toAdd += qtdir + "\"\r\n export -n QTDIR\r\n";
    toAdd += "  PATH=$PATH\":" + qtdir +"/bin\"\r\n export -n PATH\r\n#----- END FOR MAC --------\r\n";
    qDebug(toAdd);
    command.replace("#! /bin/sh", toAdd);
#endif
    CGestIni::Param_UpdateToDisk(path, command);

    if ( !QFile::exists( path ) )     {qDebug(path); return;}
    QFile file( path );
    if ( !file.open( IO_ReadOnly ) )  {qDebug(path); return;}
    pushButton_SetBases->hide();
    pushButton_LancerDrTux->hide();
    comboBox_Bases->hide();
    comboBox_Executables->hide();

    //....................... corriger version des UI de MedinTuxTools...............................
    QString toolsPath(G_pCApp->m_PathAppli + "../..");
    QDir qDir(toolsPath);
    qDir.convertToAbs();
    toolsPath = qDir.path() + QDir::separator() + "MedinTuxTools";
    G_pCApp->RemoveAllDesignerVersion(toolsPath);
    //....................... corriger version des UI ...............................
    G_pCApp->RemoveAllDesignerVersion(getTargetSrcPath("QLightPad"));
    G_pCApp->RemoveAllDesignerVersion(getTargetSrcPath("gest_user"));
    G_pCApp->RemoveAllDesignerVersion(getTargetSrcPath("personnes"));
    G_pCApp->RemoveAllDesignerVersion(getTargetSrcPath("QLaboFTP"));
    G_pCApp->RemoveAllDesignerVersion(getTargetSrcPath("ccamview"));
    G_pCApp->RemoveAllDesignerVersion(getTargetSrcPath("Manager"));
    G_pCApp->RemoveAllDesignerVersion(getTargetSrcPath("med_stat"));
    G_pCApp->RemoveAllDesignerVersion(getTargetSrcPath("drtux"));
    G_pCApp->RemoveAllDesignerVersion(getTargetSrcPath("mise_a_jour"));
    G_pCApp->RemoveAllDesignerVersion(getTargetSrcPath("qgetdatasemp"));
    G_pCApp->RemoveAllDesignerVersion(getTargetSrcPath("manu"));
    //....................... versions commerciale .....................................
    if ( IsCommercialVersionExist() )
    {G_pCApp->RemoveAllDesignerVersion(getTargetSrcPath("QFseVitale"));
    }
    //................. relever date ..........................................
    QApplication::setOverrideCursor( QCursor( Qt::WaitCursor ) );
    m_dtDebComp = QDateTime::currentDateTime();
    textLabel_Progress->setText(tr("Compilation des exécutables en cours ...") );
    //................... lancer process ......................................
    QString main_path = G_pCApp->m_PathAppli; if (main_path.endsWith("/"))  { main_path = main_path.left(main_path.length()-1); }
    QDir::setCurrent ( main_path );
    execute(path);
    pushButton_compilation->setText(tr("I&nterrompre la compilation des exécutables en cours"));
    m_MakeExeRun = MAKE_EXE_RUN;
}

//----------------------------------------- IsCommercialVersionExist ---------------------------------------------
QString C_DlgMainDialog::IsCommercialVersionExist()
{QString path = G_pCApp->m_PathAppli + QDir::separator() + ".." + QDir::separator() + ".." + QDir::separator() +
                "Commercial" + QDir::separator() +"qtsingleapplication.pri";
    path   = QDir::cleanDirPath (path);
    if ( QFile::exists (path) ) return path;
    else                        return QString::null;
}

//----------------------------------------- OneCompil ---------------------------------------------
void C_DlgMainDialog::OneCompil( const QString &target )
{
    if (m_MakeExeRun == MAKE_EXE_RUN)
        //if (pushButton_compilation->text()==tr("Interrompre la compilation des exécutables en cours"))
    {if (m_proc==0) return;
        if (m_proc->isRunning())
        {m_proc->tryTerminate();
            QTimer::singleShot( 5000, m_proc, SLOT( kill() ) );
        }
        pushButton_compilation->setText(tr("&Compilation des exécutables"));
        m_MakeExeRun = MAKE_EXE_NOTRUN;
        QApplication::restoreOverrideCursor();
        return;
    }

    //........................... l'informaticienne compile le C (contrepeterie)...................................................
    Compilation(getTargetSrcPath(target));
}

//----------------------------------------- getTargetSrcPath -----------------------------------------------------------------
QString C_DlgMainDialog::getTargetSrcPath(const QString &target)
{   QString main_path(G_pCApp->m_PathAppli + "../..");
    QDir qDir(main_path);
    qDir.convertToAbs();
     if (target=="compta-plugins")
        {main_path = qDir.path() + "/comptabilite/compta-plugins";
        }
     else if ( target=="check_dus" )
        {main_path = qDir.path() + "/comptabilite/check_dus";
        }
     else if ( target=="comptabilite" )
        {main_path = qDir.path() + "/comptabilite/compta";
        }
     else
          {main_path = qDir.path() + QDir::separator() + target + QDir::separator() +"src";
          }
    return main_path;
}

//----------------------------------------- Compilation -----------------------------------------------------------------
void C_DlgMainDialog::Compilation(const QString &path)
{   pushButton_SetBases->hide();
    pushButton_LancerDrTux->hide();
    comboBox_Bases->hide();
    comboBox_Executables->hide();
    //....................... corriger version des UI de MedinTuxTools...............................
    QString toolsPath(G_pCApp->m_PathAppli + "../..");
    QDir qDir(toolsPath);
    qDir.convertToAbs();
    toolsPath = qDir.path() +  "/MedinTuxTools";
    G_pCApp->RemoveAllDesignerVersion(toolsPath);
    //.................... corriger les versions des UI .....................
    QDir::setCurrent ( path );
    G_pCApp->RemoveAllDesignerVersion(path);
    //................. relever date ..........................................
    QApplication::setOverrideCursor( QCursor( Qt::WaitCursor ) );
    m_dtDebComp = QDateTime::currentDateTime();
    textLabel_Progress->setText(tr("Compilation des exécutables en  cours ...") );
    //................... lancer process ......................................
    #ifdef Q_OS_MACX
    #else
    execute(path + QDir::separator() +"release.sh");
    #endif

    pushButton_compilation->setText(tr("&Interrompre la compilation des exécutables en cours"));
    m_MakeExeRun = MAKE_EXE_RUN;
}

//----------------------------------------- IsExecutablesExist --------------------------------------------------------------------
bool C_DlgMainDialog::IsExecutablesExist()
{   textEdit_Message->clear();

    if ( ! IsThisExecutableExist("drtux") )           return FALSE;
    if ( ! IsThisExecutableExist("ccamview") )        return FALSE;
    if ( ! IsThisExecutableExist("personnes") )       return FALSE;
    if ( ! IsThisExecutableExist("QLightPad") )       return FALSE;
    if ( ! IsThisExecutableExist("gest_user") )       return FALSE;
    if ( ! IsThisExecutableExist("Manager") )         return FALSE;
    if ( ! IsThisExecutableExist("med_stat") )        return FALSE;
    if ( ! IsThisExecutableExist("QLaboFTP") )        return FALSE;
    if ( ! IsThisExecutableExist("mise_a_jour") )     return FALSE;
    if ( ! IsThisExecutableExist("manu") )            return FALSE;
    if ( ! IsThisExecutableExist("comptabilite") )    return FALSE;
    if ( ! IsThisExecutableExist("compta-plugins") )  return FALSE;
    if ( ! IsThisExecutableExist("check_dus") )       return FALSE;
    if ( IsCommercialVersionExist() )
    {if ( ! IsThisExecutableExist("qgetdatasemp") )   return FALSE;
        if ( ! IsThisExecutableExist("QFseVitale") )  return FALSE;
    }
    return TRUE;
}

//----------------------------------------- IsThisExecutableExist --------------------------------------------------------------------
bool C_DlgMainDialog::IsThisExecutableExist(const QString &exe_name)
{   QString folder = G_pCApp->m_PathAppli; if (folder.endsWith("/")) {folder = folder.left(folder.length()-1);}
    QString path   =  G_pCApp->Construct_Name_Exe(exe_name, folder);

    textEdit_Message->append( tr("\n================= ") + path + " ================= " );
    if (  ! QFile::exists (path) ) return FALSE;
    textEdit_Message->append( tr("Cet exécutable existe déjà : ") + path + "\n");
    textEdit_Message->moveCursor(QTextEdit::MoveEnd);
    return TRUE;
}

/*
//--------------------------------------------------------- EndCompilation -----------------------------------------
void C_DlgMainDialog::EndCompilation()
{   QDateTime dtEnd= QDateTime::currentDateTime();
    long    s = m_dtDebComp.secsTo (dtEnd);
    long    h = s/3600; s -=  h*3600;
    long    m = s/60;   s -=  m*60;
    QApplication::restoreOverrideCursor();
    QString text   = textEdit_Message->text() + tr ("\r\n === Compilation des exécutables terminée en:  ")+
                     QString::number(h) + "h" + QString::number(m) + "mn" + QString::number(s) + "s ===";
    textEdit_Message->setText(text );
    textEdit_Message->moveCursor(QTextEdit::MoveEnd);
    textLabel_Progress->setText("" );
    progressBar_Load->setProgress(0);
}
*/

//----------------------------------------- execute ---------------------------------------------------------------------
void C_DlgMainDialog::execute(const QString &command)
{
    m_proc = new QProcess(this);  if (m_proc == 0 ) return;
    m_proc->addArgument("bash");
    m_proc->addArgument(command);
    //connect(m_proc, SIGNAL(processExited ()),  this, SLOT(EndCompilation()));
    connect(m_proc, SIGNAL(readyReadStderr()), this, SLOT(updateError()));
    connect(m_proc, SIGNAL(readyReadStdout()), this, SLOT(updateText()));
    connect(m_proc, SIGNAL(processExited()),   this, SLOT(updateExit()));
    m_proc->start();

}

//----------------------------------------- updateError -------------------------------------------------------------------
void C_DlgMainDialog::updateError()
{   //char *pt = 0;
    QByteArray data  = m_proc->readStderr();
    /*
    QString data_str = data;
    int pos = data_str.find(tr("error"));
    if (pos != -1)
       {QColor old_col = textEdit_Message->color();
        pt = (char*)(const char*) data_str;
        data_str = QString("<font color=#ffd200> === Erreur ===") + data_str + "</font><font color=" + old_col.name() + ">";
        qDebug(data_str);
       }
    //data_str.replace("\r\n","<br>");
    //data_str.replace("\n","<br>");
    //data_str.replace("\r","<br>");
    data_str.remove("\r");
    data_str.remove("\n");
    //data_str.replace("\n","<br>");
    //data_str.replace("\r","<br>");
    QString text = textEdit_Message->text() + data_str + "<br>";
    //QString text = textEdit_Message->text() + QString(data);
    */

    textEdit_Message->setText(textEdit_Message->text() + QString(data));
    textEdit_Message->moveCursor(QTextEdit::MoveEnd);
}

//----------------------------------------- updateText --------------------------------------------------------------------
void C_DlgMainDialog::updateText()
{
    //char *pt = 0;
    QByteArray data  = m_proc->readStdout();
    /*
    QString data_str = data;
    int pos = data_str.find(tr("error"));

    if (pos != -1)
       {QColor old_col = textEdit_Message->color();
        pt = (char*)(const char*) data_str;
        data_str = QString("<font color=#ffd200> === Erreur ===") + data_str + "</font><font color=" + old_col.name() + ">";
        qDebug(data_str);
       }
    //data_str.replace("\r\n","<br>");
    //data_str.replace("\n","<br>");
    //data_str.replace("\r","<br>");
    data_str.remove("\r");
    data_str.remove("\n");

    QString text = textEdit_Message->text() + data_str + "<br>";
    */
    textEdit_Message->setText(textEdit_Message->text() + QString(data));
    textEdit_Message->moveCursor(QTextEdit::MoveEnd);
}

//----------------------------------------- updateExit --------------------------------------------------------------------
void C_DlgMainDialog::updateExit()
{
    if (m_proc->normalExit()) {

        QDateTime dtEnd= QDateTime::currentDateTime();
        long    s = m_dtDebComp.secsTo (dtEnd);
        long    h = s/3600; s -=  h*3600;
        long    m = s/60;   s -=  m*60;
        QApplication::restoreOverrideCursor();
        textEdit_Message->append( tr (" === Compilation des exécutables terminée en :  ")+
                                  QString::number(h) + "h" + QString::number(m) + "mn" + QString::number(s) + "s ===\n");
        textEdit_Message->moveCursor(QTextEdit::MoveEnd);
        textLabel_Progress->setText("" );

        pushButton_SetBases->show();
        comboBox_Bases->show();
        comboBox_Executables->show();
        pushButton_LancerDrTux->show();
        progressBar_Load->show();
        pushButton_compilation->setText(tr( "&Compilation des exécutables" ));
        m_MakeExeRun = MAKE_EXE_NOTRUN;
    }
    else {
        textEdit_Message->append("Error");
        textEdit_Message->moveCursor(QTextEdit::MoveEnd);
        pushButton_SetBases->show();
        comboBox_Executables->show();
        comboBox_Bases->show();
        pushButton_LancerDrTux->show();
        progressBar_Load->show();
    }
}


//----------------------------------------- pushButton_SetBases_clicked --------------------------------------------------------------------
void C_DlgMainDialog::pushButton_SetBases_clicked()
{
    QDateTime dtDeb = QDateTime::currentDateTime();
    //  [CONFIG]
    //      nb_progress = 340535
    long nb_pas;
    QString nb_progress;
    if (G_pCApp->Param_ReadParam( "CONFIG", "nb_progress",&nb_progress) !=0
        )  // zero = pas d'erreur
    {   nb_pas  = 340535;
    }
    else
    {   nb_pas  = nb_progress.toLong();
    }


    //.................. lire le fichier ini pour en retirer les paramêtres de connexion ...............
    QString  driverName , baseName , userName , passWord, hostName;
    if (G_pCApp->Param_ReadParam( "DrTuxTest", "Connexion",
                                  &driverName, &baseName, &userName, &passWord, &hostName) !=0
        )  // zero = pas d'erreur
    {   driverName  = "QMYSQL3";
        baseName    = "DrTuxTest";
        userName    = "root";
        passWord    = "";
        hostName    = "";
    }
    //.....................................  paramètres generaux ...........................................................


    textEdit_Message->clear();
    baseName = comboBox_Bases->currentText ();

    //if (baseName == tr("Toutes les bases"))
    if (comboBox_Bases->currentItem()==0)
    {   textLabel_Progress->setText( tr("Installation des bases de données : ") + QString::number(nb_pas) + tr(" lignes en  cours ..." ));
        G_pCApp->SetBase(driverName  ,        // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
                         baseName,            // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
                         userName,            // = "root"
                         passWord,            // = ""
                         hostName,            // = "localhost"
                         textEdit_Message,
                         progressBar_Load,
                         nb_pas
                         );
        SetButtonIndexVidal(0);
    }
    else
    {   QString qs_nb_pas;
        if (G_pCApp->Param_ReadParam( baseName, "nb_progress", &qs_nb_pas) ==0 ) nb_pas = qs_nb_pas.toLong();
        textLabel_Progress->setText( tr("Installation des bases de données : ") + QString::number(nb_pas) + tr(" lignes en  cours ..." ));
        QSqlDatabase* dataBase = G_pCApp->SetOneBase(driverName  ,        // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
                                                     baseName,            // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
                                                     userName,            // = "root"
                                                     passWord,            // = ""
                                                     hostName,            // = "localhost"
                                                     textEdit_Message,
                                                     progressBar_Load,
                                                     nb_pas
                                                     );
        if (baseName=="MedicaTuxTest"||baseName=="BaseGetTest")SetButtonIndexVidal(0);
        //QSqlDatabase::removeDatabase (dataBase);  // plante sous linux
    }
    QDateTime dtEnd = QDateTime::currentDateTime();
    long    s = dtDeb.secsTo (dtEnd);
    long    h = s/3600; s -=  h*3600;
    long    m = s/60;   s -=  m*60;

    QString text   = textEdit_Message->text() + tr (" === Installation des bases de données terminée en : ") +
                     QString::number(h) + "h" + QString::number(m) + "mn" + QString::number(s) + "s ===\n";
    textEdit_Message->setText(text );
    textEdit_Message->moveCursor(QTextEdit::MoveEnd);
    textLabel_Progress->setText("" );
    progressBar_Load->setProgress(0);
    if (setMajVersionButton()) pushButton_MajBases_clicked();

}

//----------------------------------------- pushButton_LancerDrTux_clicked --------------------------------------------------------------------
void C_DlgMainDialog::pushButton_LancerDrTux_clicked()
{
    QString path = G_pCApp->Construct_Name_Exe("Manager",QFileInfo (qApp->argv()[0]).dirPath (true));
    // Affichage dans la Box

    QProcess*  proc = new QProcess( this );
    if (proc==0) return;
    proc->addArgument( path );
    if ( !proc->start() )
    {//text_Label_Status->setText(qstr.sprintf("OnGlossaireFileToEdit(): Echec de l'ouverture du process: QLightPad"));
    }
    delete proc;

}

//----------------------------------------- DataSempBaseInit--------------------------------------------------------------------
QSqlDatabase* C_DlgMainDialog::DataSempBaseInit()
{   if (m_DatasempBase) return m_DatasempBase;

    QString  driverName , baseName , userName , passWord, hostName;
    if (G_pCApp->Param_ReadParam( "Datasemp", "Connexion",
                                  &driverName, &baseName, &userName, &passWord, &hostName) !=0
        )  // zero = pas d'erreur
    {   driverName  = "QMYSQL3";
        baseName    = "Datasemp";
        userName    = "root";
        passWord    = "";
        hostName    = "";
    }
    m_DatasempBase   = G_pCApp->BaseConnect(   driverName  ,        // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
                                               baseName    ,    // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
                                               userName,            // = "root"
                                               passWord,        // = ""
                                               hostName,        // = "localhost"
                                               "Datasemp");


    return m_DatasempBase;
}
//----------------------------------------- pushButtonJustOneTable_clicked--------------------------------------------------------------------
void C_DlgMainDialog::pushButtonJustOneTable_clicked()
{ //.................. lire le fichier ini pour en retirer les paramêtres de connexion ...............
    // if (pushButton_SetDatasemp->text()== tr("Interrompre l'installation de Datasemp en cours")) return;
    if (m_BaseVidalRun  == INSTALL_VIDAL_RUN) return;
    QString  driverName , baseName , userName , passWord, hostName;
    if (G_pCApp->Param_ReadParam( "Datasemp", "Connexion",
                                  &driverName, &baseName, &userName, &passWord, &hostName) !=0
        )  // zero = pas d'erreur
    {   driverName  = "QMYSQL3";
        baseName    = "Datasemp";
        userName    = "root";
        passWord    = "";
        hostName    = "";
    }
    if (m_DatasempBase)
    {   m_DatasempBase->close();
        QSqlDatabase::removeDatabase ("Datasemp");
        m_DatasempBase = 0;
    }
    int isThisBaseExist;
    if (m_DatasempBase==0)
        m_DatasempBase = G_pCApp->Datasemp_CreateBases( driverName  ,        // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
                                                        baseName,            // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
                                                        userName,            // = "root"
                                                        passWord,            // = ""
                                                        hostName,            // = "localhost"
                                                        textEdit_Message,
                                                        &isThisBaseExist
                                                        );
    if (m_DatasempBase == 0 ||  (m_DatasempBase->isOpen()==FALSE && m_DatasempBase->open()==FALSE) )
    {textEdit_Message->append( tr (" === La base Datasemp : ") + driverName + "." + baseName + tr(" n'existe pas ou n'a pu être créée ou ouverte ====\n") );
        textEdit_Message->moveCursor(QTextEdit::MoveEnd);
        return;
    }


    //m_DatasempDir      = QFileDialog::getExistingDirectory ( QString::null, this, "OuvrirDlg", tr(" Localisez les données Datasemp") );
    m_dtDeb            = QDateTime::currentDateTime();
    QString file_name  = QFileDialog::getOpenFileName(m_DatasempDir  + "tables" + QDir::separator() + "data" + QDir::separator(),
                                                      "Base SQL(*.sql *.SQL)", this, "open file dialog", tr( "Choix d'une table SQL à générer" ) );
    if (file_name.length()==0)                            return;

    QApplication::setOverrideCursor( QCursor( Qt::WaitCursor ) );
    QDateTime dtDeb = QDateTime::currentDateTime();
    QString toFind  = QString(" ") + QDir::separator() + "tables";
    toFind          = toFind.mid(1);
    int pos         = file_name.find(toFind);
    m_DatasempDir   = file_name.left(pos+1);
    if (m_DatasempDir.length()==0)                        return;
    //t5c_s.sql
    if ( !QFile::exists(file_name ) )                     return;
    QFile file(file_name );
    if ( !file.open( IO_ReadOnly ) )                      return;
    QFileInfo fileInfo(file_name);
    QString table = fileInfo.fileName().left(1) + fileInfo.fileName().mid(1,2).upper();
    if (G_pCApp->CreationTables(m_DatasempBase, m_DatasempDir + "tables" + QDir::separator() + "struct" + QDir::separator() + fileInfo.fileName().left(3) + "_s.sql")!=0)
    {textEdit_Message->append( tr ("  Création de la table ") + driverName + "." + baseName + "." + table ) ;
        textEdit_Message->moveCursor(QTextEdit::MoveEnd);
        int nb = G_pCApp->ExecSQL_File(m_DatasempBase, m_DatasempDir + "tables" + QDir::separator() + "data" + QDir::separator() + fileInfo.fileName().left(3) + "_d.sql");
        if (nb>0)
        {textEdit_Message->append( tr( " Insertion de " ) + QString::number(nb) + tr( " enregistrements." ));
            textEdit_Message->moveCursor(QTextEdit::MoveEnd);
        }
        else
        {textEdit_Message->append( tr( " échec de l'insertion des enregistrements de ") + m_DatasempDir + "tables" + QDir::separator() + "data" + QDir::separator() + fileInfo.fileName().left(3) + "_d.sql");
            textEdit_Message->moveCursor(QTextEdit::MoveEnd);
        }
    }
    else
    {textEdit_Message->append( tr( " échec de la création de la table ") + m_DatasempDir + "tables" + QDir::separator() + "struct" + QDir::separator() + fileInfo.fileName().left(3) + "_s.sql") ;
        textEdit_Message->moveCursor(QTextEdit::MoveEnd);
    }

    QDateTime dtEnd= QDateTime::currentDateTime();
    long    s = dtDeb.secsTo (dtEnd);
    long    h = s/3600; s -=  h*3600;
    long    m = s/60;   s -=  m*60;
    QApplication::restoreOverrideCursor();
    textEdit_Message->append( tr( " === Installation de la table " ) + table + tr( "   terminée en " ) +
                              QString::number(h) + "h" + QString::number(m) + "mn" + QString::number(s) + "s ===\n");
    textEdit_Message->moveCursor(QTextEdit::MoveEnd);

    textLabel_Progress->setText("" );
    progressBar_Load->setProgress(0);
}

//----------------------------------------- pushButton_SetDatasemp_clicked --------------------------------------------------------------------
void C_DlgMainDialog::pushButton_SetDatasemp_clicked()
{//[DatasempTest]
    // Connexion      = QMYSQL3 , DatasempTest , Medintux , ,localhost

    if (m_BaseVidalRun  == INSTALL_VIDAL_RUN)
        //if (pushButton_SetDatasemp->text()== tr("Interrompre l'installation de Datasemp en cours"))
    {StopCUpdateThread();
        pushButton_SetDatasemp->setText( tr( "&Installer les Bases Vidal Datasemp" ) );
        pushButton_IndexerDatasemp->show();
        m_BaseVidalRun  = INSTALL_VIDAL_NOTRUN;
        return;
    }


    if (m_DatasempBase)
    {m_DatasempBase->close();
        QSqlDatabase::removeDatabase ("Datasemp");
        m_DatasempBase = 0;
    }

    //.................. lire le fichier ini pour en retirer les paramêtres de connexion ...............
    QString  driverName , baseName , userName , passWord, hostName;
    if (G_pCApp->Param_ReadParam( "Datasemp", "Connexion",
                                  &driverName, &baseName, &userName, &passWord, &hostName) !=0
        )  // zero = pas d'erreur
    {   driverName  = "QMYSQL3";
        baseName    = "Datasemp2";
        userName    = "root";
        passWord    = "";
        hostName    = "";
    }
    int isThisBaseExist;
    m_DatasempBase = G_pCApp->Datasemp_CreateBases( driverName  ,        // nom du driver: "QODBC3" "QMYSQL3" "QPSQL7"
                                                    baseName,            // nom de la base: si QODBC3 -> nom de la source de données (userDSN)
                                                    userName,            // = "root"
                                                    passWord,            // = ""
                                                    hostName,            // = "localhost"
                                                    textEdit_Message,
                                                    &isThisBaseExist
                                                    );
    if (m_DatasempBase != 0 )
    {int ok = 1;
        if (isThisBaseExist)
        {
            QString numEdition, packBCArrete, packIRArrete;
            QString ods = G_pCApp->Datasemp_GetBaseVersion(m_DatasempBase , &numEdition, &packBCArrete, &packIRArrete);
            ok =  QMessageBox::warning( this,   tr( "Installation de Vidal Datasemp"),
                                        tr( "Il semble qu'une version de <b><u>Vidal Datasemp</b></u> :")+  //S041115
                                        tr("<br>    \r\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ° édition     N° : <b>")  + numEdition            +
                                        tr("</b><br>\r\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ° Arrêté Pack BC : <b>")  + packBCArrete /*.mid(4,2) + "-" + packBCArrete.mid(2,2) + "-20" + packBCArrete.mid(0,2) */ +
                                        tr("</b><br>\r\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ° Arrêté Pack IR : <b>")  + packIRArrete /*.mid(4,2) + "-" + packIRArrete.mid(2,2) + "-20" + packIRArrete.mid(0,2) */ +
                                        tr("</b><br>\r\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ° Version : <b>")         + ods.mid(6,2)          + "." + ods.mid(7,1)          +
                                        tr("</b><br>\r\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ° N° de Livraison : <b>") + ods.mid(9)            +
                                        tr("</b><br>\r\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ° Livraison ODS : <b>")   + ods                   +
                                        tr("</b><br>\r\n est déjà installée au niveau de la base <b>") + driverName  + "." + baseName +
                                        tr("</b><br>\r\nContinuer l'installation tout de même ?\n "
                                           "Ou installer juste les éventuelles mises à jour ?\n"),
                                        tr( "Tout annu&ler" ),
                                        tr( "Tout &Installer" ),
                                        tr( "Installer les &mises à jour" ),
                                        0 ) ;
        }
        if (ok !=0) m_DatasempDir = QFileDialog::getExistingDirectory ( m_DatasempDir  , this, "OuvrirDlg", tr( " Recherche des données Datasemp" ) );
        m_dtDeb                   = QDateTime::currentDateTime();
        //........................ relever noms des sous repertoires données SQL Vidal Datasemp .........................
        QString mainDir, dataDir, docsDir, structDir;
        if (G_pCApp->Param_ReadParam( "Datasemp", "CD_Dir", &mainDir, &dataDir, &docsDir, &structDir) !=0 )  // zero = pas d'erreur
        {   mainDir      = "plain";
            dataDir      = "data/std89";
            docsDir      = "data/docs";
            structDir    = "struct/mysql";
        }

        //........................ corriger si version MAJUSCULE (CD) ou Minuscules (FTP) .........................
        verifieDatasempDir(""     , mainDir);
        verifieDatasempDir(mainDir, dataDir);
        verifieDatasempDir(mainDir, docsDir);
        verifieDatasempDir(mainDir, structDir);

        if (ok==1) //......................................... installation de tout .....................................
        {   m_pCUpdateThread  = new CUpdateThread;
            qDebug(m_DatasempDir);
            if (m_pCUpdateThread==0)  return;
            long nb_pas = m_pCUpdateThread->Init(m_DatasempBase, m_DatasempDir ,mainDir, dataDir, docsDir, structDir, textEdit_Message);
            if (nb_pas!=0)
            {
                progressBar_Load->setTotalSteps(nb_pas);
                m_pCUpdateThread->start();
                pushButton_SetDatasemp->setText(tr("&Interrompre l'installation de Datasemp en cours"));
                pushButton_IndexerDatasemp->hide();
                m_BaseVidalRun  = INSTALL_VIDAL_RUN;
                m_pQTimer= new QTimer(this);
                if (m_pQTimer)
                {connect(m_pQTimer, SIGNAL(timeout()), this, SLOT(timerDisplayDone()) );
                    m_pQTimer->start(400, FALSE);
                }
            }
            //................. si echec initialisation thread ........................
            else
            {textEdit_Message->setText(m_pCUpdateThread->GetCurrentLog());
                textEdit_Message->moveCursor(QTextEdit::MoveEnd);
                m_pCUpdateThread->StopSetBases();
                m_pCUpdateThread->wait();
                delete m_pCUpdateThread;
                m_pCUpdateThread = 0;
            }
        }
        else if (ok==2) //......................................... installation que des mises à jour .....................................
        {QString baseODS = G_pCApp->Datasemp_GetBaseVersion( m_DatasempBase );
            QStringList list;
            int nb =  G_pCApp->Datasemp_Maj_GetMajList(m_DatasempDir , baseODS, list);    // extraire la liste des fichiers de mise à jour
            if (list.count()==0)
            {textEdit_Message->append(tr ("  Aucun fichier de mise à jour trouvé dans ce répertoire !!!!: "));
                textEdit_Message->moveCursor(QTextEdit::MoveEnd);
                return;
            }
            ok = 2;                 //
            if (nb != (int)list.count())
            {QString list_ok, list_no;
                for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it )
                {QString name = (*it);
                    if (name[0]=='+')  list_ok += QString("<br>    \r\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>") + name.mid(1) +"</b>";
                    else               list_no += QString("<br>    \r\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>") + name.mid(1) +"</b>";
                }
                ok =  QMessageBox::warning( this,  tr("Installation de Vidal Datasemp"),
                                            tr("Des fichiers de mise à jour ne correspondant pas")       +  //S041115
                                            tr("<br> à cette livraison de la base ont été trouvés : ")   + list_no +
                                            ((list_ok.length()) ? tr("<br> ceux valides étant :"):QString(""))     + list_ok +
                                            tr("</b><br>\r\n faut-il forcer l'installation des fichiers ne correspondant pas à cette livraison ?\n "
                                               "ou installer juste les éventuelles mises à jour valides ?\n"),
                                            tr("&Tout annuler"),
                                            tr("&Forcer la mise à jour"),
                                            tr("N'installer que les fichiers &valides"),
                                            0, 0 ) ;
                if (ok==0) return;
            }
            int mode = 0;
            if ( checkBox_STD_MAJ->isChecked()) mode |= CApp::MajFiles;
            if ( checkBox_SQL_MAJ->isChecked()) mode |= CApp::SqlFiles;

            // int mode = GetDatasempMode() &~ mode|CApp::Force; // recuperer mode de mise à jour (avec flag pour fichiers SQL)
            if      (ok==1)  G_pCApp->Datasemp_Maj_Update(m_DatasempBase , m_DatasempDir, baseODS , (CApp::UPDATE_MODE)(mode|CApp::Force),  textEdit_Message);
            else if (ok==2)  G_pCApp->Datasemp_Maj_Update(m_DatasempBase , m_DatasempDir, baseODS , (CApp::UPDATE_MODE) mode,               textEdit_Message);
        }
    }

}
//----------------------------------------- verifieDatasempDir--------------------------------------------------------------------
void C_DlgMainDialog::verifieDatasempDir(const QString &mainDir, QString &dir)
{      QString mainDirToInsert = mainDir; if (mainDirToInsert.length()) mainDirToInsert += "/";
    if      ( QFile::exists( m_DatasempDir + mainDirToInsert +  dir.lower() ) )      dir = dir.lower();
    else if ( QFile::exists( m_DatasempDir + mainDirToInsert +  dir.upper() ) )      dir = dir.upper();
    else  G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n ERREUR le répertoire : \n          \"")  + m_DatasempDir +  mainDirToInsert +  dir.upper() + tr("\" ou\n          \"")
                                       + m_DatasempDir +  mainDirToInsert +  dir.lower() + tr("\" n'a pas été trouvé.\n") );
}

//----------------------------------------- timerDisplayDone--------------------------------------------------------------------
void C_DlgMainDialog::timerDisplayDone()
{if (m_pCUpdateThread==0) return;
    if (m_pCUpdateThread->IsFini())
    {   QDateTime dtEnd= QDateTime::currentDateTime();
        long    s = m_dtDeb.secsTo (dtEnd);
        long    h = s/3600; s -=  h*3600;
        long    m = s/60;   s -=  m*60;
        StopCUpdateThread();
        //.......................... installation de l'update ..................................................................
        int mode = 0;
        if ( checkBox_STD_MAJ->isChecked()) mode |= CApp::MajFiles;
        if ( checkBox_SQL_MAJ->isChecked()) mode |= CApp::SqlFiles;
        QString baseODS = G_pCApp->Datasemp_GetBaseVersion( m_DatasempBase );
        G_pCApp->Datasemp_Maj_Update(m_DatasempBase , m_DatasempDir, baseODS  , (CApp::UPDATE_MODE) mode, textEdit_Message);
        textEdit_Message->append( tr (" === Installation de Datasemp terminée en : ") +
                                  QString::number(h) + "h" + QString::number(m) + "mn" + QString::number(s) + "s ===\n");
        textEdit_Message->moveCursor(QTextEdit::MoveEnd);
        pushButton_SetDatasemp->setText(tr("Installer le &Vidal Datasemp..."));
        m_BaseVidalRun  = INSTALL_VIDAL_NOTRUN;
        textLabel_Progress->setText("" );
        progressBar_Load->setProgress(0);
        copyDatasempImages();
        SetButtonIndexVidal(1);
        return;
    }


    progressBar_Load->setProgress( m_pCUpdateThread->GetCurrentProgress());
    textLabel_Progress->setText( m_pCUpdateThread->GetCurrentStatus() + QString::number( m_pCUpdateThread->GetCurrentLine()));
    textEdit_Message->setText(m_pCUpdateThread->GetCurrentLog());
    textEdit_Message->moveCursor(QTextEdit::MoveEnd);
}

//----------------------------------------- GetDatasempMode--------------------------------------------------------------------
int C_DlgMainDialog::GetDatasempMode()
{    // Mise a jour SQL     = non
    // Mise a jour STD     = Forcer
    QString isMajSQL(""), isMajSTD("");
    G_pCApp->Param_ReadParam( "Datasemp", "Mise a jour SQL", &isMajSQL);
    G_pCApp->Param_ReadParam( "Datasemp", "Mise a jour STD", &isMajSTD);
    isMajSQL = isMajSQL.lower();
    isMajSTD = isMajSTD.lower();
    int mode = 0;
    if (isMajSQL.find("oui") != -1) mode |= CApp::SqlFiles;
    if (isMajSTD.find("oui") != -1) mode |= (CApp::Remove|CApp::Insert|CApp::Update);
    return mode;
}

//----------------------------------------- checkBox_STD_MAJ_stateChanged--------------------------------------------------------------------
void C_DlgMainDialog::checkBox_STD_MAJ_stateChanged( int )
{if (checkBox_STD_MAJ->isChecked())
    {G_pCApp->Param_WriteParam( "Datasemp", "Mise a jour STD", "oui");
    }
    else
    {G_pCApp->Param_WriteParam( "Datasemp", "Mise a jour STD", "non");
    }
    G_pCApp->Param_UpdateToDisk();
}


//----------------------------------------- checkBox_SQL_MAJ_stateChanged--------------------------------------------------------------------
void C_DlgMainDialog::checkBox_SQL_MAJ_stateChanged( int )
{if (checkBox_SQL_MAJ->isChecked())
    {G_pCApp->Param_WriteParam( "Datasemp", "Mise a jour SQL", "oui");
    }
    else
    {G_pCApp->Param_WriteParam( "Datasemp", "Mise a jour SQL", "non");
    }
    G_pCApp->Param_UpdateToDisk();
}

//----------------------------------------- StopCUpdateThread--------------------------------------------------------------------
void C_DlgMainDialog::StopCUpdateThread()
{if (m_pCUpdateThread==0) return;
    if (m_pQTimer)
    { m_pQTimer->stop();
        delete m_pQTimer;
        m_pQTimer = 0;
    }
    m_pCUpdateThread->StopSetBases();
    m_pCUpdateThread->wait();
    delete m_pCUpdateThread;
    m_pCUpdateThread = 0;
}

//----------------------------------------- pushButtonSwitchGetDatasemp_clicked --------------------------------------------------------------------
void C_DlgMainDialog::pushButtonSwitchGetDatasemp_clicked()
{textEdit_Message->setText(tr("=========================================== Activation d'une base ===================================================="));
    QString path = G_pCApp->Construct_Name_File_Ini("drtux",QFileInfo (qApp->argv()[0]).dirPath (true),"MedicaBase.ini");
    // Affichage dans la Box
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n================= Lecture Base Get ou Datasemp \n ") +  path );

    if (  ! QFile::exists (path) ) {
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("Ce fichier n'existe pas"));
        return ;
    }
    QString param;
    CGestIni::Param_UpdateFromDisk(path, param);
    if (m_BaseToInstallFlag == INSTALL_BASE_GET)
    {CGestIni::Param_WriteParam(&param, "Connexion" , "InUseBase" ,  "Parametres Get_Base" ,  "MedicaBase");
        pushButtonSwitchGetDatasemp->setText(tr("Activer la &base Datasemp"));
        m_BaseToInstallFlag  = INSTALL_BASE_DATASEMP;
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n ====> Activation de la base Get"));
    }
    else
    {CGestIni::Param_WriteParam(&param, "Connexion" , "InUseBase" ,  "Parametres MedicaBase" ,  "noMedicaBase");
        pushButtonSwitchGetDatasemp->setText(tr("Activer la &base Get"));
        m_BaseToInstallFlag  = INSTALL_BASE_GET;
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n ====> Activation de la base Vidal Datasemp"));
    }
    CGestIni::Param_UpdateToDisk(path, param);
    G_pCApp->Datasemp_OutMessage(textEdit_Message, param);
}

//----------------------------------------- pushButtonConnexionAppl_clicked --------------------------------------------------------------------
void C_DlgMainDialog::pushButtonConnexionAppl_clicked()
{
    if (pushButtonConnexionAppl->text().left(11)==tr("Interrompre"))
    {//KillTestBasesProc();
        m_testBaseProcRun = FALSE;
        return;
    }
    QString userName = lineEdit_UserName->text();
    QString passWord = lineEdit_PassWord->text();
    QString hostName = lineEdit_Hostname->text();
    QString driverName, baseName;
    QString param;
    QString path;
    /*
    QString str =                   QString("QMYSQL3,")                          +
                                    lineEdit_UserName->text().stripWhiteSpace()  +","+
                                    lineEdit_PassWord->text().stripWhiteSpace()  +","+
                                    lineEdit_Hostname->text().stripWhiteSpace());
    comboBox_IP_Fav_activated( str ) ;
    */
    //.............................. DrTux.ini ..................................................................
    path = G_pCApp->Construct_Name_File_Ini("drtux",QFileInfo (qApp->argv()[0]).dirPath (true),"");
    // Affichage dans la Box
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n================================== Modification : ") + path + "==================================");
    if (  ! QFile::exists (path) ) {
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\nCe fichier n'existe pas"));
        return ;
    }
    CGestIni::Param_UpdateFromDisk(path, param);
    CGestIni::Param_ReadParam (param,  "Connexion" ,    "Parametres" , &driverName , &baseName);
    CGestIni::Param_WriteParam(&param, "Connexion" ,    "Parametres" ,  driverName ,  baseName, userName , passWord , hostName);
    CGestIni::Param_ReadParam (param,  "Codage CIM10" , "Connexion" , &driverName , &baseName);
    CGestIni::Param_WriteParam(&param, "Codage CIM10" , "Connexion" ,  driverName ,  baseName, userName , passWord , hostName);
    CGestIni::Param_UpdateToDisk(path, param);
    G_pCApp->Datasemp_OutMessage(textEdit_Message, param);

    //drtux-ccamview.ini
    path = G_pCApp->Construct_Name_File_Ini("drtux",QFileInfo (qApp->argv()[0]).dirPath (true),"Ressources/ccam/ccamview.ini");
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n================================== Modification : ") + path + "==================================");
    if (  ! QFile::exists (path) ) {
        G_pCApp->Datasemp_OutMessage(textEdit_Message, "\nCe fichier n'existe pas");
        return ;
    }
    CGestIni::Param_UpdateFromDisk(path, param);
    CGestIni::Param_ReadParam (param,  "Connexion"  , "Parametres" ,  &driverName   ,  &baseName);
    CGestIni::Param_WriteParam(&param, "Connexion"  , "Parametres" ,  driverName    ,  baseName, userName , passWord , hostName);
    CGestIni::Param_ReadParam (param,  "Praticiens" , "Connexion"  ,  &driverName   ,  &baseName);
    CGestIni::Param_WriteParam(&param, "Praticiens" , "Connexion"  ,  driverName    ,  baseName, userName , passWord , hostName);
    CGestIni::Param_UpdateToDisk(path, param);
    G_pCApp->Datasemp_OutMessage(textEdit_Message, param);
    //.............................. MedicaBase.ini ..................................................................
    // [Connexion]
    //     Parametres MedicaBase = QMYSQL3 , MedicaTuxTest , root,  , localhost
    //     Parametres SrceBase   = QMYSQL3 , DatasempTest , root,  , localhost
    //     Parametres Get_Base   = QMYSQL3 , BaseGetTest, root,  , localhost
    //     InUseBase             = Parametres Get_Base , MedicaBase
    path = G_pCApp->Construct_Name_File_Ini("drtux",QFileInfo (qApp->argv()[0]).dirPath (true),"MedicaBase.ini");
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n================================== Modification : ") + path + "==================================");
    if (  ! QFile::exists (path) ) {
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\nCe fichier n'existe pas"));
        return ;
    }
    CGestIni::Param_UpdateFromDisk(path, param);
    CGestIni::Param_ReadParam (param, "Connexion" , "Parametres MedicaBase" , &driverName , &baseName);
    CGestIni::Param_WriteParam(&param, "Connexion" , "Parametres MedicaBase" ,  driverName ,  baseName, userName , passWord , hostName);
    CGestIni::Param_ReadParam (param, "Connexion" , "Parametres SrceBase"   , &driverName , &baseName);
    CGestIni::Param_WriteParam(&param, "Connexion" , "Parametres SrceBase"   ,  driverName ,  baseName, userName , passWord , hostName);
    CGestIni::Param_ReadParam (param, "Connexion" , "Parametres Get_Base"   , &driverName , &baseName);
    CGestIni::Param_WriteParam(&param, "Connexion" , "Parametres Get_Base"   ,  driverName ,  baseName, userName , passWord , hostName);
    CGestIni::Param_UpdateToDisk(path, param);
    G_pCApp->Datasemp_OutMessage(textEdit_Message, param);

    //.............................. ccamview.ini ..................................................................
    path = G_pCApp->Construct_Name_File_Ini("ccamview",QFileInfo (qApp->argv()[0]).dirPath (true),"");
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n================================== Modification : ") + path + "==================================");
    if (  ! QFile::exists (path) ) {
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\nCe fichier n'existe pas"));
        return ;
    }
    CGestIni::Param_UpdateFromDisk(path, param);
    CGestIni::Param_ReadParam (param,  "Connexion"  , "Parametres" ,  &driverName  ,  &baseName);
    CGestIni::Param_WriteParam(&param, "Connexion"  , "Parametres" ,  driverName   ,  baseName, userName , passWord , hostName);
    CGestIni::Param_ReadParam (param,  "Praticiens" , "Connexion"  ,  &driverName  ,  &baseName);
    CGestIni::Param_WriteParam(&param, "Praticiens" , "Connexion"  ,  driverName   ,  baseName, userName , passWord , hostName);
    CGestIni::Param_UpdateToDisk(path, param);
    G_pCApp->Datasemp_OutMessage(textEdit_Message, param);

    //.............................. personnes.ini ..................................................................
    path = G_pCApp->Construct_Name_File_Ini("personnes",QFileInfo (qApp->argv()[0]).dirPath (true),"");
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n================================== Modification : ") + path + "==================================");
    if (  ! QFile::exists (path) ) {
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\nCe fichier n'existe pas"));
        return ;
    }
    CGestIni::Param_UpdateFromDisk(path, param);
    CGestIni::Param_ReadParam (param, "Connexion" , "Parametres" , &driverName , &baseName);
    CGestIni::Param_WriteParam(&param, "Connexion" , "Parametres" ,  driverName ,  baseName, userName , passWord , hostName);
    CGestIni::Param_UpdateToDisk(path, param);
    G_pCApp->Datasemp_OutMessage(textEdit_Message, param);

    //.............................. gest_user.ini ..................................................................
    path = G_pCApp->Construct_Name_File_Ini("gest_user",QFileInfo (qApp->argv()[0]).dirPath (true),"");
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n================================== Modification : ") +  path + "==================================");
    if (  ! QFile::exists (path) ) {
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\nCe fichier n'existe pas"));
        return ;
    }
    CGestIni::Param_UpdateFromDisk(path, param);
    CGestIni::Param_ReadParam (param, "Connexion" , "Parametres" , &driverName , &baseName);
    CGestIni::Param_WriteParam(&param, "Connexion" , "Parametres" ,  driverName ,  baseName, userName , passWord , hostName);
    CGestIni::Param_UpdateToDisk(path, param);
    G_pCApp->Datasemp_OutMessage(textEdit_Message,param);

    //.............................. Manager.ini ..................................................................
    path = G_pCApp->Construct_Name_File_Ini("Manager",QFileInfo (qApp->argv()[0]).dirPath (true),"");
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n================================== Modification : ") +  path + "==================================");
    if (  ! QFile::exists (path) ) {
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\nCe fichier n'existe pas"));
        return ;
    }
    CGestIni::Param_UpdateFromDisk(path, param);
    CGestIni::Param_ReadParam (param,  "Connexion" ,    "Parametres" , &driverName , &baseName);
    CGestIni::Param_WriteParam(&param, "Connexion" ,    "Parametres" ,  driverName ,  baseName, userName , passWord , hostName);
    CGestIni::Param_ReadParam (param,  "Codage CIM10" , "Connexion" , &driverName , &baseName);
    CGestIni::Param_WriteParam(&param, "Codage CIM10" , "Connexion" ,  driverName ,  baseName, userName , passWord , hostName);
    CGestIni::Param_UpdateToDisk(path, param);
    G_pCApp->Datasemp_OutMessage(textEdit_Message,param);

    //.............................. med_stat.ini ..................................................................
    path = G_pCApp->Construct_Name_File_Ini("med_stat",QFileInfo (qApp->argv()[0]).dirPath (true),"");
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n================================== Modification : ") +  path + "==================================");
    if (  ! QFile::exists (path) ) {
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\nCe fichier n'existe pas"));
        return ;
    }
    CGestIni::Param_UpdateFromDisk(path, param);
    CGestIni::Param_ReadParam (param,  "Connexion" ,    "Parametres" , &driverName , &baseName);
    CGestIni::Param_WriteParam(&param, "Connexion" ,    "Parametres" ,  driverName ,  baseName, userName , passWord , hostName);
    CGestIni::Param_UpdateToDisk(path, param);
    G_pCApp->Datasemp_OutMessage(textEdit_Message,param);

    //..............................QLaboFTP.ini ..................................................................
    path = G_pCApp->Construct_Name_File_Ini("QLaboFTP",QFileInfo (qApp->argv()[0]).dirPath (true),"");
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n================================== Modification : ") +   path + "==================================");
    if (  ! QFile::exists (path) ) {
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\nCe fichier n'existe pas"));
        return ;
    }
    CGestIni::Param_UpdateFromDisk(path, param);
    CGestIni::Param_ReadParam (param,  "ConnexionBase" ,    "Parametres" , &driverName , &baseName);
    CGestIni::Param_WriteParam(&param, "ConnexionBase" ,    "Parametres" ,  driverName ,  baseName, userName , passWord , hostName);
    CGestIni::Param_UpdateToDisk(path, param);
    G_pCApp->Datasemp_OutMessage(textEdit_Message,param);

    //..............................qgetdatasemp ..................................................................
    if ( IsCommercialVersionExist()  )
    {path = G_pCApp->Construct_Name_File_Ini("qgetdatasemp",QFileInfo (qApp->argv()[0]).dirPath (true),"");
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n================================== Modification : ") +  path + "==================================");
        if (  ! QFile::exists (path) ) {
            G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\nCe fichier n'existe pas"));
            return ;
        }
        CGestIni::Param_UpdateFromDisk(path, param);
        CGestIni::Param_ReadParam (  param,  "ConnexionBase" , "Parametres" , &driverName , &baseName);
        CGestIni::Param_WriteParam( &param,  "ConnexionBase" , "Parametres" ,  driverName ,  baseName, userName , passWord , hostName);
        CGestIni::Param_ReadParam(   param,  "DrTuxTest",      "Connexion",   &driverName, &baseName);
        CGestIni::Param_WriteParam( &param,  "DrTuxTest",      "Connexion",    driverName,  baseName,  userName,  passWord,  hostName);
        CGestIni::Param_ReadParam(   param,  "MedicaTuxTest",  "Connexion",   &driverName, &baseName);
        CGestIni::Param_WriteParam( &param,  "MedicaTuxTest",  "Connexion",    driverName,  baseName,  userName,  passWord,  hostName);
        CGestIni::Param_ReadParam(   param,  "BaseGetTest",    "Connexion",   &driverName, &baseName);
        CGestIni::Param_WriteParam( &param,  "BaseGetTest",    "Connexion",    driverName,  baseName,  userName,  passWord,  hostName);
        CGestIni::Param_ReadParam(   param,  "CIM10Test",      "Connexion",   &driverName, &baseName);
        CGestIni::Param_WriteParam( &param,  "CIM10Test",      "Connexion",    driverName,  baseName,  userName,  passWord,  hostName);
        CGestIni::Param_ReadParam(   param,  "CCAMTest",       "Connexion",   &driverName, &baseName);
        CGestIni::Param_WriteParam( &param,  "CCAMTest",       "Connexion",    driverName,  baseName,  userName,  passWord,  hostName);
        CGestIni::Param_ReadParam(   param,  "Datasemp",       "Connexion",   &driverName, &baseName);
        CGestIni::Param_WriteParam( &param,  "Datasemp",       "Connexion",    driverName,  baseName,  userName,  passWord,  hostName);
        CGestIni::Param_ReadParam(   param,  "QLaboFTPTest",   "Connexion",   &driverName, &baseName);
        CGestIni::Param_WriteParam( &param,  "QLaboFTPTest",   "Connexion",    driverName,  baseName,  userName,  passWord,  hostName);
        CGestIni::Param_UpdateToDisk(path, param);
        G_pCApp->Datasemp_OutMessage(textEdit_Message,param);

        path = G_pCApp->Construct_Name_File_Ini("qgetdatasemp",QFileInfo (qApp->argv()[0]).dirPath (true),"Ressources/MedicaBase.ini");
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n================================== Modification : ") +  path + "==================================");
        if (  ! QFile::exists (path) ) {
            G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\nCe fichier n'existe pas"));
            return ;
        }
        CGestIni::Param_UpdateFromDisk(path, param);
        CGestIni::Param_ReadParam (param, "Connexion" , "Parametres MedicaBase" , &driverName , &baseName);
        CGestIni::Param_WriteParam(&param, "Connexion" , "Parametres MedicaBase" ,  driverName ,  baseName, userName , passWord , hostName);
        CGestIni::Param_ReadParam (param, "Connexion" , "Parametres SrceBase"   , &driverName , &baseName);
        CGestIni::Param_WriteParam(&param, "Connexion" , "Parametres SrceBase"   ,  driverName ,  baseName, userName , passWord , hostName);
        CGestIni::Param_ReadParam (param, "Connexion" , "Parametres Get_Base"   , &driverName , &baseName);
        CGestIni::Param_WriteParam(&param, "Connexion" , "Parametres Get_Base"   ,  driverName ,  baseName, userName , passWord , hostName);
        CGestIni::Param_UpdateToDisk(path, param);
        G_pCApp->Datasemp_OutMessage(textEdit_Message, param);
    }
    //............................. setBases.ini .......................................................................
    //  [DrTuxTest]
    //     Connexion      = QMYSQL3 , DrTuxTest , root , ,localhost

    //     [MedicaTuxTest]
    //       Connexion      = QMYSQL3 , MedicaTuxTest , root , ,localhost

    //     [BaseGetTest]
    //       Connexion      = QMYSQL3 , BaseGetTest , root , ,localhost

    //     [CIM10Test]
    //       Connexion      = QMYSQL3 , CIM10Test , root , ,localhost

    //     [CCAMTest]
    //       Connexion      = QMYSQL3 , CCAMTest , root , ,localhost

    //     [Datasemp]
    //       Connexion            = QMYSQL3 , DatasempTest , root , ,localhost

    //     [QLaboFTPTest]
    //       Connexion = QMYSQL3 , QLaboFTPTest , root ,  , localhost

    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n================================== Modification : ") +  G_pCApp->m_ParamPath + "==================================");
    G_pCApp->Param_ReadParam(  "DrTuxTest",     "Connexion",  &driverName, &baseName);
    G_pCApp->Param_WriteParam( "DrTuxTest",     "Connexion",   driverName,  baseName,  userName,  passWord,  hostName);
    G_pCApp->Param_ReadParam(  "MedicaTuxTest", "Connexion",  &driverName, &baseName);
    G_pCApp->Param_WriteParam( "MedicaTuxTest", "Connexion",   driverName,  baseName,  userName,  passWord,  hostName);
    G_pCApp->Param_ReadParam(  "CIM10Test",     "Connexion",  &driverName, &baseName);
    G_pCApp->Param_WriteParam( "CIM10Test",     "Connexion",   driverName,  baseName,  userName,  passWord,  hostName);
    G_pCApp->Param_ReadParam(  "CCAMTest",      "Connexion",  &driverName, &baseName);
    G_pCApp->Param_WriteParam( "CCAMTest",      "Connexion",   driverName,  baseName,  userName,  passWord,  hostName);
    G_pCApp->Param_ReadParam(  "Datasemp",      "Connexion",  &driverName, &baseName);
    G_pCApp->Param_WriteParam( "Datasemp",      "Connexion",   driverName,  baseName,  userName,  passWord,  hostName);
    G_pCApp->Param_ReadParam(  "QLaboFTPTest",  "Connexion",  &driverName, &baseName);
    G_pCApp->Param_WriteParam( "QLaboFTPTest",  "Connexion",   driverName,  baseName,  userName,  passWord,  hostName);
    G_pCApp->Param_ReadParam(  "BaseGetTest",   "Connexion",  &driverName, &baseName);
    G_pCApp->Param_WriteParam( "BaseGetTest",   "Connexion",   driverName,  baseName,  userName,  passWord,  hostName);
    G_pCApp->Param_UpdateToDisk();
    G_pCApp->Datasemp_OutMessage(textEdit_Message, param);

    QString ret ="";
    groupBoxMedinTuxInstall->hide();
    pushButton_SetBases->hide();
    pushButton_MajBases->hide();
    comboBox_Bases->hide();

    tabWidgetInstall->hide();
    //.................................. tester mysql ................................................................
    pushButtonConnexionAppl->setText(tr("Interrompre le test de connexion à la base de données en cours ... "));
    ret = TestBases(driverName, "mysql", userName,  passWord,  hostName);
    if (ret == "ABORTED")
    {   textEdit_Message->setText("");
        G_pCApp->Datasemp_OutMessage(textEdit_Message, m_MessageNoConnect+ tr("\n\n (==> test de l'accès à la base mysql interrompu par l'utilisateur)\n"));
        pushButtonConnexionAppl->setText(tr("&Se connecter à la base de données"));
        return;
    }
    if (ret =="OK")
    {   groupBoxMedinTuxInstall->show();
        //groupBoxMedinTuxInstall->hide();
        pushButton_SetBases->show();
        //pushButton_MajBases->show();
        comboBox_Bases->show();
        pushButtonConnexionAppl->setText(tr("&Se connecter à la base de données"));
    }
    else
    {   textEdit_Message->setText("");
        G_pCApp->Datasemp_OutMessage(textEdit_Message, m_MessageNoConnect + tr("\n\n (==> erreur lors du test de l'accès à la base mysql)\n"));
        pushButtonConnexionAppl->setText(tr("&Se connecter à la base de données"));
        return;
    }

    //.................................. tester base_get ................................................................
    //                                   ce test sert a savoir si les bases ont ete installees car
    //                                   lors d'une installation elle est toujours installee
    // / *
    pushButtonConnexionAppl->setText(tr("Interrompre le test de connexion à la base de données en cours ... "));
    ret = TestBases(driverName, baseName, userName,  passWord,  hostName);
    if (ret == "ABORTED")
       {textEdit_Message->setText("");
        G_pCApp->Datasemp_OutMessage(textEdit_Message, m_MessageNoConnect+ tr("\n\n (==> test de vérification de l'installation des bases interrompu par l'utilisateur)\n"));
        pushButtonConnexionAppl->setText(tr("&Se connecter à la base de données"));
        return;
      }
      // * /
   if (ret=="OK")
    {   groupBoxMedinTuxInstall->show();
        pushButton_SetBases->show();
        pushButton_MajBases->show();
        comboBox_Bases->show();

        tabWidgetInstall->show();
        setMajVersionButton();
        SetButtonIndexVidal(0);
        pushButtonConnexionAppl->setText(tr("&Se connecter à la base de données"));
        if ( pushButton_MajBases->isVisible() )
        {pushButton_MajBases_clicked();
        }
    }
 // /*
    else
    {   textEdit_Message->setText("");
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n (====> les bases de données ne sont pas installées, ou incorrectement installées) <=====\n") + m_MessageNoConnect );
        pushButtonConnexionAppl->setText(tr("&Se connecter à la base de données"));
    }
// */
}

//----------------------------------------- TestBases ---------------------------------------------
QString C_DlgMainDialog::TestBases(  const QString &driver, const QString &base, const QString &userName,  const QString &passWord,  const QString &hostName)
{   QString path     = G_pCApp->Construct_Name_Exe("mise_a_jour", QFileInfo (qApp->argv()[0]).dirPath (true));
    QString exchFile = G_pCApp->Construct_Name_File_Ini("mise_a_jour", QFileInfo (qApp->argv()[0]).dirPath (true), "Ressources/Version.txt");
    CMoteurBase::Param_UpdateToDisk(exchFile , "début");

    QProcess*  m_TestBasesProc  = new QProcess( this );
    if (m_TestBasesProc==0) return "";
    m_TestBasesProc->addArgument( path );
    m_TestBasesProc->addArgument("Tester base");    // - 1 - Commande
    m_TestBasesProc->addArgument(driver);           // - 2 - Driver
    m_TestBasesProc->addArgument(base);             // - 3 - Base
    m_TestBasesProc->addArgument(userName);         // - 4 - userName
    if (passWord.length()<=0) m_TestBasesProc->addArgument("_=OO=_"); // - 5 - passWord
    else                      m_TestBasesProc->addArgument(passWord); // - 5 - passWord
    m_TestBasesProc->addArgument(hostName);         // - 6 - hostName
    m_testBaseProcRun = TRUE;
    if ( m_TestBasesProc->start())
    {qApp->processEvents ();
        QTimer timer;               // pour etre sur qu'un evenement se produise
        timer.start(400, FALSE);    // sinon boucle sans fin dans    processEvents ( QEventLoop::WaitForMore )
        while(m_TestBasesProc->isRunning () && m_testBaseProcRun==TRUE)
        {QApplication::eventLoop()->processEvents ( QEventLoop::WaitForMore );
        }
    }
    QString val;
    m_TestBasesProc->kill();
    delete m_TestBasesProc;
    m_TestBasesProc = 0;
    if (m_testBaseProcRun==FALSE)
    {val = "ABORTED";
    }
    else
    {CMoteurBase::Param_UpdateFromDisk(exchFile , val);
    }
    m_testBaseProcRun=FALSE;
    return val;
}

//------------------------------------------- pushButton_IndexerDatasemp_clicked -----------------------------------------
void C_DlgMainDialog::pushButton_IndexerDatasemp_clicked()
{

    QString path =  G_pCApp->m_PathAppli + "../../drtux/bin/";

    if (m_pCMedicaBase==0) m_pCMedicaBase = new CMedicaBase(path + "MedicaBase.ini", path +"MedicaBase.cfg");
    if (m_pCMedicaBase==0) return ;
    if (m_pCMedicaBase->m_DataBaseSrce->isOpen()==FALSE && m_pCMedicaBase->m_DataBaseSrce->open()==FALSE) return;

    m_IndexStatus = "";
    //................. si thread déjà lancé l'arreter et cassos .......................................
    if (m_pCIndexMakeThread)
    {StopCIndexMakeThread();
        QString str = "0.00";             // on met un numéro d'index bidon pour qu'il ne soit pas à jour
        SetDatasempIndexVersion(str);
        SetButtonIndexVidal(0);
        return;
    }
    //................. lancer le thread ...............................................................
    m_pCIndexMakeThread  = new CIndexMakeThread(m_pCMedicaBase);
    if (m_pCIndexMakeThread == 0) return;
    QApplication::setOverrideCursor( QCursor( Qt::WaitCursor ) );
    //..................positionner l'interface ..........................................
    pushButton_SetDatasemp->hide();
    pushButtonJustOneTable->hide();
    m_pCIndexMakeThread->start();
    pushButton_IndexerDatasemp->setText( tr("Arrêter la &Reindexation du VidalDatasemp ...") );
    //................. lancer le timer de lecture de l'état d'avancement ..............................
    m_pCindexQTimer = new QTimer(this);
    if (m_pCindexQTimer)
    {connect(m_pCindexQTimer, SIGNAL(timeout()), this, SLOT(IndexTimerDisplayDone()) );
        m_pCindexQTimer->start(400, FALSE);
    }
}

//----------------------------------------- IndexTimerDisplayDone --------------------------------------------------------------------
void C_DlgMainDialog::IndexTimerDisplayDone()
{    if (m_pCIndexMakeThread==0) return;
    if (m_IndexStatus.length() > 0 && !m_pCIndexMakeThread->IsRun())
    {StopCIndexMakeThread();
        return;
    }
    QString curStatus = m_pCIndexMakeThread->GetCurrentStatus();
    //................................ noter temps de départ ........................................;
    //  curStatus = ""                                                                   rien en cours
    //  curStatus = tr( "Index accélérateur en cours de création ... " )                 routine creation index
    //  curStatus = tr( "Table de spécifications produits en cours de création ... " )   routine creation specifications
    //  on reactualise la date de depart si status change car changement de routine et
    //  la durée et progress bar doit s'appliquer à la nouvelle routine
    if (m_IndexStatus != curStatus )
    {m_IndexStatus = curStatus;
        m_DateDeb     = QDateTime::currentDateTime();
        if (m_IndexStatus.left(3)  == "-1-")
        {m_ProgressTotal = m_pCIndexMakeThread->GetTotalProgress();
        }
        if (m_IndexStatus.left(3)  == "-2-")
        {m_ProgressTotal = m_pCIndexMakeThread->GetTotalProgress();
        }
        progressBar_Load->setTotalSteps(m_ProgressTotal); // 103237
    }
    //................................ calcul du temps restant ......................................;
    double currentProgress    = m_pCIndexMakeThread->GetCurrentProgress();
    QDateTime dtEnd           = QDateTime::currentDateTime();  // date actuelle
    long    s                 = m_DateDeb.secsTo (dtEnd);      // temps écoulé depuis le debut
    double  tpsPrevuPourTout  = ((double)s*(double)m_ProgressTotal)/currentProgress;
    long    sr                = (long)tpsPrevuPourTout - s;
    long    h  = s/3600;  s  -=  h*3600;
    long    m  = s/60;    s  -=  m*60;
    long    hr = sr/3600; sr -=  hr*3600;
    long    mr = sr/60;   sr -=  mr*60;
    textLabel_Progress->setText(m_IndexStatus +
                                QString::number(currentProgress)  + tr(" Produits traités sur ") + QString::number(m_ProgressTotal)    +
                                tr(" Temps écoulé ")  + QString::number(h)  + "h" + QString::number(m)  + "mn" + QString::number(s)    + "s"    +
                                tr(" Temps restant ") + QString::number(hr) + "h" + QString::number(mr) + "mn" + QString::number(sr)   + "s"
                                );
    progressBar_Load->setProgress((long)currentProgress);
}

//----------------------------------------- StopCIndexMakeThread --------------------------------------------------------------------
void C_DlgMainDialog::StopCIndexMakeThread()
{if (m_pCIndexMakeThread==0) return;
    if (m_pCindexQTimer)
    { m_pCindexQTimer->stop();
        delete m_pCindexQTimer;
        m_pCindexQTimer = 0;
    }
    m_pCIndexMakeThread->stop();
    m_pCIndexMakeThread->wait();
    delete m_pCIndexMakeThread;
    m_pCIndexMakeThread = 0;
    pushButton_IndexerDatasemp->setText( tr("&Reindexer le VidalDatasemp ...") );
    pushButton_SetDatasemp->show();
    pushButtonJustOneTable->show();
    QApplication::restoreOverrideCursor();
    progressBar_Load->setTotalSteps(0);
    textLabel_Progress->setText(tr("Reindexation du VidalDatasemp terminée"));
    QString str = "";             // numero vide ==> ce sera celui en cours de datasemp qui sera placé
    SetDatasempIndexVersion(str); // place dans l'index créé le N° de version afin de savoir si correspond avec Datasemp
    SetButtonIndexVidal(0);
}

//----------------------------------------- pushButton_MajBases_clicked --------------------------------------------------------------------
void C_DlgMainDialog::pushButton_MajBases_clicked()
{
    QString path     = G_pCApp->Construct_Name_Exe("mise_a_jour",QFileInfo (qApp->argv()[0]).dirPath (true));
    QString exchFile = G_pCApp->Construct_Name_File_Ini("mise_a_jour", QFileInfo (qApp->argv()[0]).dirPath (true), "Ressources/Version.txt");
    QProcess*  proc  = new QProcess( this );
    if (proc==0) return;
    proc->addArgument( path );
    proc->addArgument("Do Update");
    if ( proc->start() )
    {qApp->processEvents ();
        QTimer timer;               // pour etre sur qu'un evenement se produise
        timer.start(100, FALSE);    // sinon boucle sans fin dans    processEvents ( QEventLoop::WaitForMore )
        while(proc->isRunning () )
        {QApplication::eventLoop()->processEvents ( QEventLoop::WaitForMore );
        }
    }
    delete proc;
    QString val;
    CMoteurBase::Param_UpdateFromDisk(exchFile , val);
    if (val == tr("Erreur 00"))
       {
       }
    else if (setMajVersionButton()) SetButtonIndexVidal(0);
    SetTitle(GetMAJVersion());
}

//----------------------------------------- setMajVersionButton ---------------------------------------------
int C_DlgMainDialog::setMajVersionButton()
{
    pushButton_MajBases->hide();
    QString val = GetMAJVersion();
    QString version;
    if (G_pCApp->Param_ReadParam( "CONFIG", "VersBase", &version) !=0 )  // zero = pas d'erreur
    {version = "0.09";
    }
    pushButton_SetBases->setPaletteForegroundColor ( QColor("black") );


    //..................... Gros mystere  sous VC++ ...................................................
    //                      en mode compilàuniquement !!!
    //                      les deux textes : version et val contiennent la meme valeur àsavoir "1.20"
    //                      donc les conversions en flottant : fversion et fval devraient contenir
    //                      elles aussi 1.20   donc le test if (fversion > fval)  devrait etre FAUX.
    //                      et c'est bien ce qu'il se passe en mode DEBUG logique et rasurant.
    //                      mais pas en mode    RELEASE    !!! ou le test retourne VRAI !!! ben à alors.
    //
    //                      le plus fou est que si je rajoute les lignes d'affichage suivantes:
    //
    //                           qDebug(QString("\n version de 'mise_a_jour'   : ") + QString::number(fval));
    //                           qDebug(QString("\n version de 'set_bases.ini' : ") + QString::number(fversion));
    //
    //                      tout rentre dans l'ordre, du coup je les laisse (faut bien que à marche)!!!
    //                      cela sent l'option d'optimisation foireuse en mode RELEASE.
    //
    //float fversion =  version.toFloat();
    //float fval     =  val.toFloat() ;

    //qDebug(QString("\n version de 'mise_a_jour'   : ") + QString::number(fval));
    //qDebug(QString("\n version de 'set_bases.ini' : ") + QString::number(fversion));
    if ((version.toDouble()) > (val.toDouble()))
        //if (fversion > fval)
    {pushButton_MajBases->show();
        if (val=="0.00") pushButton_SetBases->setPaletteForegroundColor ( QColor("red") );
        return 1;
    }
    return 0;
}
//----------------------------------------- GetMAJVersion ------------------------------------------------
QString C_DlgMainDialog::GetMAJVersion()
{   QString path = G_pCApp->Construct_Name_Exe("mise_a_jour",QFileInfo (qApp->argv()[0]).dirPath (true));
    QProcess  proc( this );
    proc.addArgument( path );
    proc.addArgument("Get Version");
    if ( proc.start() )
    {qApp->processEvents ();
        QTimer timer;               // pour etre sur qu'un evenement se produise
        timer.start(100, FALSE);    // sinon boucle sans fin dans    processEvents ( QEventLoop::WaitForMore )
        while(proc.isRunning () )
        {QApplication::eventLoop()->processEvents ( QEventLoop::WaitForMore );
        }
    }
    //............ recuperer infos de 'mise_a_jour' ....................
    QString version,val;
    QString exchFile = G_pCApp->Construct_Name_File_Ini("mise_a_jour", QFileInfo (qApp->argv()[0]).dirPath (true), "Ressources/Version.txt");
    CMoteurBase::Param_UpdateFromDisk(exchFile , val);
    return val;
}

//----------------------------------------- SetButtonIndexVidal ------------------------------------------------
void C_DlgMainDialog::SetButtonIndexVidal(int mode)
{   if (DataSempBaseInit())
    {   pushButton_IndexerDatasemp->show();
        pushButton_SetDatasemp->setPaletteForegroundColor ( QColor("black") );
        QString indexVers     = GetDatasempIndexVersion();
        QString datasempVers  = GetDatasempBaseVersion();
        if (indexVers != datasempVers)
        {pushButton_IndexerDatasemp->setPaletteForegroundColor ( QColor("red") );
            pushButton_IndexerDatasemp->setText(tr("&Reindexer le VidalDatasemp ..."));
        }
        else
        {pushButton_IndexerDatasemp->setPaletteForegroundColor ( QColor("black") );
            pushButton_IndexerDatasemp->setText(tr("&Index à jour (cliquez pour forcer)"));
        }
        if (mode) textEdit_Message->append(tr ("Index Version : ") + indexVers + tr ("\r\nDatasemp Version : ")+datasempVers);
        else      textEdit_Message->setText(tr ("Index Version : ") + indexVers + tr ("\r\nDatasemp Version : ")+datasempVers);
    }
    else
    {   pushButton_SetDatasemp->setPaletteForegroundColor ( QColor("red") );
        pushButton_IndexerDatasemp->hide();
    }
}

//----------------------------------------- GetDatasempIndexVersion ---------------------------------------------
QString C_DlgMainDialog::GetDatasempIndexVersion()
{

    QString path     = G_pCApp->Construct_Name_Exe("mise_a_jour", QFileInfo (qApp->argv()[0]).dirPath (true) );
    QProcess*  proc  = new QProcess( this );
    if (proc==0) return 0;
    proc->addArgument( path );
    proc->addArgument("Get Datasemp Version");
    if ( proc->start() )
    {qApp->processEvents ();
        QTimer timer;               // pour etre sur qu'un evenement se produise
        timer.start(100, FALSE);    // sinon boucle sans fin dans    processEvents ( QEventLoop::WaitForMore )
        while(proc->isRunning () )
        {QApplication::eventLoop()->processEvents ( QEventLoop::WaitForMore );
        }
    }
    delete proc;

    QString version,val;
    QString exchFile = G_pCApp->Construct_Name_File_Ini("mise_a_jour", QFileInfo (qApp->argv()[0]).dirPath (true), "Ressources/Version.txt");
    CMoteurBase::Param_UpdateFromDisk(exchFile , val);
    return val;
}

//----------------------------------------- SetDatasempIndexVersion ---------------------------------------------
void C_DlgMainDialog::SetDatasempIndexVersion(QString &version)
{
    if (version.length()<=0)
    {version     =   GetDatasempBaseVersion();
    }
    QString path = G_pCApp->Construct_Name_Exe("mise_a_jour",QFileInfo (qApp->argv()[0]).dirPath (true));

    QProcess*  proc  = new QProcess( this );
    if (proc==0) return ;
    proc->addArgument( path );
    proc->addArgument("Set Datasemp Version");
    proc->addArgument(version);
    if ( proc->start() )
    {qApp->processEvents ();
        QTimer timer;               // pour etre sur qu'un evenement se produise
        timer.start(100, FALSE);    // sinon boucle sans fin dans    processEvents ( QEventLoop::WaitForMore )
        while(proc->isRunning () )
        {QApplication::eventLoop()->processEvents ( QEventLoop::WaitForMore );
        }
    }
    delete proc;
}

//----------------------------------------- GetDatasempBaseVersion ---------------------------------------------
QString C_DlgMainDialog::GetDatasempBaseVersion()
{if (m_DatasempBase==0) return QString("0.00");
    QString numEdition,packBCArrete,packIRArrete;
    QString ods         = G_pCApp->Datasemp_GetBaseVersion(m_DatasempBase , &numEdition, &packBCArrete, &packIRArrete);
    if (ods.length()==0)   return QString("0.00");
    QString version     =   numEdition + ods.mid(6,2)+ "." + ods.mid(7,1);
    return version;
}



//----------------------------------------- pushButtonImagesCopy_clicked ---------------------------------------------
void C_DlgMainDialog::pushButtonImagesCopy_clicked()
{       //................. copier dans la destination ...........................................
    m_DatasempDir = QFileDialog::getExistingDirectory ( m_DatasempDir  , this, "OuvrirDlg", tr( " Recherche des données Datasemp" ) );
    copyDatasempImages();
}
//----------------------------------------- copyDatasempImages ---------------------------------------------
void C_DlgMainDialog::copyDatasempImages()
{       //................. repérer directory source ...........................................
    if (!m_DatasempDir.endsWith("/") ) m_DatasempDir += "/";
    QString images_SrcDir = m_DatasempDir+"images";
    if ( !QFile::exists( images_SrcDir  ) )
    {images_SrcDir = m_DatasempDir+"IMAGES";
        if ( !QFile::exists( images_SrcDir  ) )
        {G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\nLe répertoire : ") + images_SrcDir + tr(" n'existe pas "));
            return;
        }
    }
    QString src_PrefixDir = images_SrcDir;

    //................. effacer la destination ................................................
    QString images_DstDir = G_pCApp->Construct_Name_File_Ini("drtux", QFileInfo (qApp->argv()[0]).dirPath (true),  "Ressources/ImgVidalDgl") + "/";
    if ( QFile::exists( images_DstDir + "images" ) )
        images_DstDir = images_DstDir + "images";
    else
        images_DstDir = images_DstDir + "IMAGES";
    if ( QFile::exists( images_DstDir  ) ) eraseDirectory(images_DstDir);

    //................. copier dans la destination ...........................................
    //                  la norme vidal est que les noms des images des mononographies sont en majuscules : src="IMAGES/B00/C01/D35.GIF"
    images_DstDir = G_pCApp->Construct_Name_File_Ini("drtux", QFileInfo (qApp->argv()[0]).dirPath (true),  "Ressources/ImgVidalDgl/IMAGES") ;
    copyDirectory(src_PrefixDir, images_SrcDir, images_DstDir);
}

//----------------------------------------- copyDirectory ---------------------------------------------
void C_DlgMainDialog::copyDirectory(QString &src_PrefixDir, QString dir_to_explore, QString images_DstDir)
{   int f = dir_to_explore.find(src_PrefixDir);
    QString dir_dest;
    if (f !=-1)
    {dir_dest = dir_to_explore.mid(f+src_PrefixDir.length()).upper();      // MAJUSCULER le répertoire
        dir_dest.prepend(images_DstDir);
    }
    //........................ explorer la source .......................................
    QDir cur_dir( dir_to_explore );
    cur_dir.setFilter( QDir::All | QDir::NoSymLinks );
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("----------- Création de ce répertoire en cours : ") + dir_dest + "-----------");
    cur_dir.mkdir(dir_dest);
    //............ exploration de la liste ......................
    const QFileInfoList * pQFileInfoList = cur_dir.entryInfoList();
    if (pQFileInfoList==0) return;
    QFileInfoListIterator it( *pQFileInfoList );
    QFileInfo            *fi;
    while ( (fi = it.current()) != 0 )
    {
        QString fname = fi->fileName().latin1();
        if      (fname == "..")
        {
        }
        else if (fi->isDir() && fname != "." )
        {copyDirectory(src_PrefixDir, dir_to_explore+"/" + fname, images_DstDir);
        }
        else if (fi->isFile())
        {QString dst_fname = fname.upper();                       // MAJUSCULER le fichier
            G_pCApp->Datasemp_OutMessage(textEdit_Message, QString (tr("Fichier en cours de copie : ")) + dir_dest + "/" + dst_fname);
            CHtmlTools::Copy_File(dir_to_explore+"/" + fname, dir_dest, &dst_fname);
        }
        ++it;
    }
}

//----------------------------------------- eraseDirectory ---------------------------------------------
void C_DlgMainDialog::eraseDirectory( QString dir_to_erase)
{   //........................ petit message .......................................
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("----------- Effacement de ce répertoire en cours : ") + dir_to_erase + "-----------");
    QDir cur_dir( dir_to_erase );
    cur_dir.setFilter( QDir::All | QDir::NoSymLinks );
    //............ exploration de la liste ......................
    const QFileInfoList * pQFileInfoList = cur_dir.entryInfoList();
    if (pQFileInfoList==0) return;
    QFileInfoListIterator it( *pQFileInfoList );
    QFileInfo            *fi;
    while ( (fi = it.current()) != 0 )
    {
        QString fname = fi->fileName().latin1();
        if      (fname == "..")
        {
        }
        else if (fi->isDir() && fname != "." )
        {eraseDirectory(dir_to_erase + "/" + fname);
        }
        else if (fi->isFile())
        {G_pCApp->Datasemp_OutMessage(textEdit_Message, QString (tr("Fichier en cours d'effacement : ")) + dir_to_erase + "/" + fname);
            cur_dir.remove(dir_to_erase + "/" + fname);
        }
        ++it;
    }
    cur_dir.rmdir(dir_to_erase );
}

//----------------------------------------- pushButtonMakeSQL_clicked ---------------------------------------------
// mysqldump --quote-name --compatible=mysql323 MedicaTuxTest IndexProd IndexDiet IndexVeterinaire IndexParapharmacie IndexAccessoire IndexDivers IndexHomeopathie > /home/ro/Dump_IndexMedica-0001-oo-0-oo-119A02.2.sql
// mysqldump --quote-name --compatible=mysql323 DatasempTest > /home/ro/Dump_Datasemp-0001-oo-0-oo-119A02.2.sql

//................................ r�gles de nommage des fichiers de mise à jour ................................
// Dl-1144774740-Dump_Datasemp-0001-oo-1234-oo-112B02.2.sql
// ^  ^          ^                     ^       ^_____________ Datasemp version
// |  |          |_____ Ident Patern   |___ nb progress
// |  |                 Le nom du fichier sur le FTP commence ici
// |  |________ DateTime from FTP upload
// |__________________ Le nom du fichier téléchargé commence ici (précédé de 'Dl-1144774740-')
//                                                                            ^
//                                                                            |________ DateTime from FTP upload
void C_DlgMainDialog::pushButtonMakeSQL_clicked()
{   //................... lancer process ......................................
    //    FILE *in  = stdin;
    //    FILE *out = stdout;
    QApplication::setOverrideCursor( QCursor( Qt::WaitCursor ) );
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("----------- Dump du Vidal Datasemp en cours : ") + "-----------");
    QString file_name  = QString("Dump_IndexMedica-0001-oo-0-oo-") + GetDatasempBaseVersion();
    QString main_path  = G_pCApp->m_PathAppli ;
    QDir::setCurrent ( main_path );
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("          Ecriture en cours : ") + file_name + ".sql");

    QString command    = "#!/bin/sh \nmysqldump --quote-name --compatible=mysql323 MedicaTuxTest IndexProd IndexDiet IndexVeterinaire IndexParapharmacie IndexAccessoire IndexDivers IndexHomeopathie SpecProd ClassesATC FormesAD FormesPA FormesST FormesUP > ";
    command           += file_name + ".sql";
    CGestIni::Param_UpdateToDisk(main_path + "/makeSqlIndex.sh", command);
    QProcess proc(this);
    proc.addArgument("chmod");
    proc.addArgument("777");
    proc.addArgument("makeSqlIndex.sh");
    proc.start();
    while(proc.isRunning());
    QProcess proc2(this);
    proc2.addArgument("bash");
    proc2.addArgument("makeSqlIndex.sh");
    proc2.start();
    while(proc2.isRunning());
    //............................... compresser le fichier ........................................
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("          Compression en cours : ") + file_name + ".zql");
    C_Zlib czlib;
    czlib.Compresse(file_name + ".sql", file_name, ".zql");   //   ".zip"   est ajouté
    QFile::remove(file_name + ".sql");


    file_name = QString("Dump_Datasemp-0001-oo-0-oo-")+ GetDatasempBaseVersion();
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("          Ecriture en cours : ") + file_name + ".sql");
    command   = "#!/bin/sh \nmysqldump --quote-name --compatible=mysql323 DatasempTest > ";
    command  += file_name + ".sql";
    CGestIni::Param_UpdateToDisk(main_path + "/makeSql.sh", command);
    QProcess proc3(this);
    proc3.addArgument("chmod");
    proc3.addArgument("777");
    proc3.addArgument("makeSql.sh");
    proc3.start();
    while(proc3.isRunning());
    QProcess proc4(this);
    proc4.addArgument("bash");
    proc4.addArgument("makeSql.sh");
    proc4.start();
    while(proc4.isRunning());
    //............................... compresser le fichier ........................................
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("          Compression en cours : ") + file_name + ".zql");
    czlib.Compresse(file_name + ".sql", file_name, ".zql");   //   ".zip"   est ajouté
    QFile::remove(file_name + ".sql");
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("----------- Dump du Vidal Datasemp terminée ") + "-----------");

    QFile::remove("makeSql.sh");
    QFile::remove("makeSqlIndex.sh");
    QApplication::restoreOverrideCursor();

}



//--------------------------------------- pushButton_LireVitale_clicked ----------------------------------
void C_DlgMainDialog::pushButton_LireVitale_clicked()
{    QString pluginScript  = "[Execute]\r\n";
             pluginScript += "pathPlugin="      + G_pCApp->Construct_Name_Exe("QFseVitale", QFileInfo (qApp->argv()[0]).dirPath (true))    + "\r\n" +
                             "pathIni=****\r\n" +                //**** car indique d'utiliser le pathIni du plugin
                             "maskExch=Bonjour tout le monde\r\n"
                             "[Parametres]\r\n"
                             "m_Command       = READ_CONFIG\r\n"
                             "m_PathLog       = " +  G_pCApp->m_PathAppli + "/ExchangeVitale.txt\r\n" +
                             "m_CodePorteur   = 1234 \r\n" +
                             "m_DateConsult   = " + QDate::currentDate().toString("yyyyMMdd");
      QString data = PluginExe(this, pluginScript, CMoteurBase::endWait);
      G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n================================== Resultat test Sesam-Vitale =================================="));
      G_pCApp->Datasemp_OutMessage(textEdit_Message, data) ;
}

//------------------------------------------------------- PluginExe --------------------------------------------------
QString C_DlgMainDialog::PluginExe(     QObject         * pQObject,
                                        const char      * pluginScript,
                                        int               waitFlag /* = CMoteurBase::endWait */)
{
      QString     pathPlugin;  // Chemin de l'executable plugin àactionner sans l'extension .exe
      QString     pathIni;     // Chemin de l'executable plugin àactionner sans l'extension .exe
      QString     maskExch;    // texte du fichier d'exchange
      QStringList param;
      char             *pt   = (char*)(const char*) pluginScript;
      CGestIni::Param_ReadParam(pt,"Execute","pathPlugin",&pathPlugin);
      CGestIni::Param_ReadParam(pt,"Execute","pathIni",   &pathIni);
      CGestIni::Param_ReadParam(pt,"Execute","maskExch",  &maskExch);
      //.................................. PARAMETRES ...........................................
      QString     val1;
      QString     var_name   = "";
      QString      section   = "";
      while((pt=CGestIni::Param_GotoNextSection(pt, 0, &section)) && *pt)
           {if (section=="Parametres")
               {while (*pt && *pt != '[')
                      {pt = CGestIni::Param_ExtraireNextValeurs(pt, var_name, &val1);
                       if (val1.length()) param.append(val1);
                      }
               }
            section="";
           }

      return                      PluginExe(  pQObject,
                                              pathPlugin,                       // Chemin de l'executable plugin àactionner sans l'extension .exe
                                              G_pCApp->m_PathAppli,             // Chemin de l'executable appelant (DrTux)
                                              pathIni,                          // Chemin d'un eventuel fichier de configuration pour XXXX.ini pour l'executable plugin ou %
                                              maskExch,                         // texte du fichier d'exchange
                                              CMoteurBase::GUID_Create()+"-New",
                                              " ",
                                              " ",
                                              " " ,
                                              param,
                                              CMoteurBase::endWait );
}

//------------------------------------------------------- PluginExe --------------------------------------------------
// un plungin est un executable communicant avec DrTux par l'intermediare du protocole suivant:
// DrTux appelle le plugin avec dans la ligne de commande:
// en :
//   0  Chemin de l'executable plugin àactionner
//   1  Chemin d'un eventuel fichier de configuration pour XXXX.ini l'executable ou %
//   2  Chemin de l'executable appelant
//   3  Chemin du fichier d'echange texte masque d'entrà dont l'executable devra modifier les valeurs de retour
//                        ce fichier est retournàmodifiàpar le plugin, ce fichier peut etre un masque html ou
//                        tout autre dàire en accord avec la syntaxe du plugin dà fois que ...
//                        si ce fichier est vide, o n'existe pas le plugin retournera son ràultat dans ce fichier
//                        d'àhange que l'appelant ràupera
//                        Le nom de ce fichier d'echange comporte : NomDuPlugin-GUID_Patient-
//   4  GUID du patient
//   5  PrimKey de l'observation en cours
//   6  PrimKey du terrain en cours
//   7  PrimKey de l'ordonnance en cours
//   8  Reservà
//   9  Reservà
//   10 Reservà
//   11 Reservà
//   12 Nb autres parametres d'appels specifiques au plugin
//   13 --> 13+Nb paramàres

QString C_DlgMainDialog::PluginExe(       QObject    *pQObject,
                                          const QString    &pathPlugin,  // Chemin de l'executable plugin àactionner sans l'extension .exe
                                          const QString    &pathAppli,   // Chemin de l'executable appelant (DrTux)
                                          const QString    &pathIni,     // Chemin d'un eventuel fichier de configuration pour XXXX.ini pour l'executable plugin ou %
                                          const QString    &maskExch,    // texte du fichier d'exchange
                                          const QString    &guid,
                                          const QString    &dosPk,
                                          const QString    &terPk,
                                          const QString    &ordPk ,
                                          QStringList      &param,
                                          int               waitFlag /* = CMoteurBase::endWait */)
{
 QString ret = "";
 //..................... creer le process ...........................................................
 QProcess*  proc =  new QProcess( pQObject );
 if (proc==0)       return QString(QObject::tr("Erreur:  PluginExe() the process can't be created"));

 //..................... copier le masque de retour dans le dossier temporaire ......................

 QString pathExe  = pathPlugin;
 if ( QDir::isRelativePath ( pathExe ) ) pathExe = QDir::cleanDirPath (pathExe.prepend(pathAppli) );
 QString nameExch = "VitaleSetBase-"+ guid +".exc";

 QString      dst = "";
 if ( QDir::isRelativePath ( dst ) )  dst = QDir::cleanDirPath (G_pCApp->m_PathAppli+"../../tmp") ;
 dst +=  QDir::separator() + nameExch;
 QFile::remove (dst);
 QFile qfdst(dst);
 if (qfdst.open(IO_ReadWrite)==FALSE)
    {QMessageBox::critical (0, QObject::tr("PluginExe(): write pathExch"),
                               QObject::tr("The file\r\n")+ dst + QObject::tr("\r\ncan't be opened"),
                               QMessageBox::Abort, QMessageBox::NoButton, QMessageBox::NoButton );
     delete proc;
     return QObject::tr("Error:  PluginExe() destination file can't be opened");
    }
 qfdst.writeBlock (maskExch, maskExch.length());
 qfdst.close();
 /*
 #define BUFF_LEN 2048
 char *buf = new char[BUFF_LEN];
 long len;
 if (buf==0)
    {delete proc;
     return QObject::tr("Error:  PluginExe() bufer can't be created");
    }
 do{len = qfsrc.readBlock (buf, BUFF_LEN);
          qfdst.writeBlock (buf, len);
   }while (len==BUFF_LEN);
 delete [] buf;
 */
 //......................... completer les autres arguments .........................................
 proc->addArgument( pathExe );                         // 0  Chemin de l'executable plugin àactionner
 proc->addArgument( pathIni );                         // 1  Chemin d'un eventuel fichier de configuration pour XXXX.ini l'executable ou %
 proc->addArgument( pathAppli + "set_bases"F_EXE ); // 2  Chemin de l'executable appelant
 proc->addArgument( dst );                             // 3  Chemin du fichier d'echange texte masque d'entrà dont l'executable devra modifier les valeurs de retour
 proc->addArgument(guid );                             // 4  GUID du patient
 proc->addArgument(dosPk);                             // 5  PrimKey de l'observation en cours
 proc->addArgument(terPk);                             // 6  PrimKey du terrain en cours
 proc->addArgument(ordPk);                             // 7  PrimKey de l'ordonnance en cours
 proc->addArgument(" ");                               // 8  reservà
 proc->addArgument(" ");                               // 9  reservà
 proc->addArgument(" ");                               // 10 reservà
 proc->addArgument(" ");                               // 11 reservà
 proc->addArgument(QString::number(param.count()));    // 12 Nb autres parametres d'appels specifiques au plugin
 for ( QStringList::Iterator it = param.begin(); it != param.end(); ++it )  // 13 --> 13+Nb paramàres
     {proc->addArgument(*it);
     }
 //................................. executer le process .............................................
 if ( m_PluginRun == "" && proc->start() )
    { m_PluginRun = pathExe;
     qApp->processEvents ();
     while (waitFlag==CMoteurBase::endWait && proc->isRunning () )
           { QApplication::eventLoop()->processEvents ( QEventLoop::WaitForMore );
           }
     m_PluginRun = "";
     //............lire le fichier d'echange ..........................
     if ( !QFile::exists( dst ) )     return  ret;
     QFile file( dst );
     if ( !file.open( IO_ReadOnly ) ) return  ret;
     QTextStream ts( &file );
     ret = ts.read();
    }
  delete proc;
  QFile::remove (dst);
  return ret;
}

//----------------------------------------- pushButton_InstallSesam_clicked --------------------------------------------------------------------
void C_DlgMainDialog::pushButton_InstallSesam_clicked()
{
#ifdef Q_WS_X11

    QString path        = G_pCApp->m_PathAppli; if (path.endsWith("/"))  { path = path.left(path.length()-1); }
    QString api_path    = path + "/../../Sesam-API-Local/ApiLinux";
    QString cpp_path    = path + "/../../qsfelib/src";
    QString system_path = lineEdit_BinaryPath->text();           // "/usr/local"
    QString sesamPath   = system_path + "/sesam";                // "/usr/local/sesam"

    textEdit_Message->setText("");
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("--------------- Journal d'installation du ") + QDate::currentDate().toString("dd-MM-yyyy") + tr(" de l'API Sesam-Vitale  sur plateforme LINUX ") );
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("      Path d'installation des composants binaires :  ") + lineEdit_BinaryPath->text());
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("      Path d'installation des tables :  ")              + sesamPath);


    //................. copier les tables sesam ................................................
    eraseDirectory(sesamPath);      //effacer la destination
    copyTables_Api( api_path, sesamPath);
    //................. creer le repertoire galss ................................................
    if ( ! QFile::exists( system_path+"/galss"  ) )
    {   QDir cur_dir( system_path + "/galss" );
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("----------- Création de ce répertoire en cours : ") + system_path + "/galss" + "-----------");
        cur_dir.mkdir(system_path + "/galss");
    }
    //................. creer le repertoire galsssrv ................................................
    if ( ! QFile::exists( system_path+"/galsssrv"  ) )
    {   QDir cur_dir( system_path + "/galsssrv" );
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("----------- Création de ce répertoire en cours : ") + system_path + "/galsssrv" + "-----------");
        cur_dir.mkdir(system_path + "/galsssrv");
    }
    //................. creer le repertoire adm ................................................
    if ( ! QFile::exists( sesamPath + "/adm"  ) )
    {   QDir cur_dir( sesamPath + "/adm" );
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("----------- Création de ce répertoire en cours : ") + sesamPath + "/adm" + "-----------");
        cur_dir.mkdir(sesamPath + "/adm");
    }
    //................. creer le repertoire etc ................................................
    if ( ! QFile::exists( sesamPath + "/etc"  ) )
    {   QDir cur_dir( sesamPath + "/etc" );
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("----------- Création de ce répertoire en cours : ") + sesamPath + "/etc" + "-----------");
        cur_dir.mkdir(sesamPath + "/etc");
    }
    copyTables_Api( path + "/../../Sesam-API-Local/adm", sesamPath + "/adm");
    copyLinux_Api(api_path,  system_path + "/galss",  cpp_path, sesamPath);

    //.................................. fichier io_comm.ini .........................................................
    QString io_comm =tr(";Fichier d'équivalence des ports séries sous Linux set by MedinTux\n"
                        "[MAP_DEVICE]\n")+ comboBox_PortLecteur->currentText ()+"\n";
    CMoteurBase::Param_UpdateToDisk(system_path + "/galss/io_comm.ini" , io_comm);
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("----------- Mise en place du fichier : ") + system_path + "/galss/io_comm.ini -----------");
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("\n") + io_comm);
    //................................ modifier le fichier de ld.so.conf ............................................
    QString etc;
    CMoteurBase::Param_UpdateFromDisk("/etc/ld.so.conf" , etc);
    if (etc.length()==0)
       {G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("\n    Erreur installation API Sesam :  /etc/ld.so.conf   non trouvé " ));
       }
    else
       {
        if (etc.find(system_path + "/galss")==-1)
           {   etc += "\n" + system_path + "/galss";
               G_pCApp->Datasemp_OutMessage(textEdit_Message, system_path + "/galss" +tr("   rajouté " ));
           }
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("----------- Mise en place du fichier : /etc/ld.so.conf  -----------"));
        G_pCApp->Datasemp_OutMessage(textEdit_Message, etc + "\r");
        CMoteurBase::Param_UpdateToDisk("/etc/ld.so.conf" , etc);
       }
    //................................ modifier les droits de l'API .................................................
    QString main_path = G_pCApp->m_PathAppli; if (main_path.endsWith("/"))  { main_path = main_path.left(main_path.length()-1); }
    QDir::setCurrent ( main_path );
    QString script   = "#! /bin/sh\n"
                       "echo \".\"\n"
                       "echo \" ... Modifier droits de l'API Sesam-Vitale .....\"\n";
            script  += "chmod -R 777 " + system_path + "/sesam\n";
            script  += "chmod -R 777 " + system_path + "/galss\n";
            script  += "chmod -R 777 " + system_path + "/galsssrv\n";
            script  += "ldconfig\n";
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("----------- Execution du script : ") + main_path + "/PostInstall-SesamAPI.sh  -----------");
    G_pCApp->Datasemp_OutMessage(textEdit_Message, "\n" + script);
    CMoteurBase::Param_UpdateToDisk(main_path + "/PostInstall-SesamAPI.sh" , script);
    //......................... changer les droits du script ........................................................
    QProcess proc(this);
    proc.addArgument("chmod");
    proc.addArgument("777");
    proc.addArgument("PostInstall-SesamAPI.sh");
    proc.start();
    while(proc.isRunning());
    //......................... execution du script lui meme........................................................
    QProcess proc2(this);
    proc2.addArgument("bash");
    proc2.addArgument("PostInstall-SesamAPI.sh");
    proc2.start();
    while(proc2.isRunning());
    CMoteurBase::Param_UpdateToDisk(path + "/Journal-Installation-SesamVitale.txt" , textEdit_Message->text());
#endif

#ifdef Q_OS_MACX
#endif

#ifdef Q_WS_WIN
    QString path        = G_pCApp->m_PathAppli; if (path.endsWith("/"))  { path = path.left(path.length()-1); }
    QString api_path    = path + "/../../Sesam-API-Local/ApiWin";
    QString cpp_path    = path + "/../../qsfelib/src";
    QString sesamPath   = lineEdit_SesamPath->text() + "\\sesam";         // "C:"
    QString system_path = lineEdit_BinaryPath->text();                    // "C:\\WINDOWS"

    sesamPath.replace("\\\\","\\");                                                                  // des fois que il soit plac�par l'utilisateur "C:\" et rajout� "\sesam"
    if (system_path.endsWith("\\")) system_path.truncate(system_path.length()-1);       // des fois que il soit plac�par l'utilisateur un \ en fin de chemin"
    textEdit_Message->setText("");
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("--------------- Journal d'installation de l'API Sesam-Vitale ---- en date du : ") + QDate::currentDate().toString("dd-MM-yyyy"));
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("      Path d'installation des composants binaires :  ") + system_path );
    G_pCApp->Datasemp_OutMessage(textEdit_Message, tr("      Path d'installation des tables :  ")              + sesamPath   );
    //................. copier les dll et .lib et .ini et .h et .exe ............................
    copyWindw_Api(api_path,  system_path, cpp_path, sesamPath);
    //................. copier les tables sesam ................................................
    eraseDirectory(sesamPath);      //effacer la destination
    copyTables_Api( path + "/../../Sesam-API-Local/ApiWin/", sesamPath);
    //................. creer le repertoire adm ................................................
    if ( ! QFile::exists( sesamPath + "/adm"  ) )
    {   QDir cur_dir( sesamPath + "/adm" );
        G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("----------- Création de ce répertoire en cours : ") + sesamPath + "/adm" + "-----------");
        cur_dir.mkdir(sesamPath + "/adm");
    }
    copyTables_Api( path + "/../../Sesam-API-Local/adm", sesamPath + "/adm");
    CMoteurBase::Param_UpdateToDisk(path +"/Journal-Installation-SesamVitale.txt" , textEdit_Message->text());      // enregistrer le ficher modifie dans la bonne destination
#endif

#ifdef  Q_WS_MAC

#endif

}

//----------------------------------------- copyLinux_Api -------------------------------------------------
void C_DlgMainDialog::copyLinux_Api(QString src_Dir,  QString bin_Dir,  QString cpp_Dir, QString sesam_Dir)
{
    //........................ explorer la source .......................................
    QDir cur_dir( src_Dir );
    cur_dir.setFilter( QDir::All | QDir::NoSymLinks );
    //............ exploration de la liste ......................
    const QFileInfoList * pQFileInfoList = cur_dir.entryInfoList();
    if (pQFileInfoList==0) return;
    QFileInfoListIterator it( *pQFileInfoList );
    QFileInfo            *fi;
    while ( (fi = it.current()) != 0 )
    {QString fname = fi->fileName().latin1();
        if      (fname == "..")
        {
        }
        else if (fi->isDir() && fname != "." )
        {if (fname.left(4).lower() != "sgal") copyLinux_Api(src_Dir + "/" + fname, bin_Dir, cpp_Dir, sesam_Dir);
        }
        else if (fi->isFile())
        {   QString ext = getExtension(fname).lower();
            if (ext==".gz")
            {
            }
            else if (fname =="libstslux.so" || fname =="libssvlux.so" || fname =="libsrtlux.so" || fname =="libsgdlux.so" )
            {   G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("     Copie de : ")  + src_Dir +"/" + fname + " vers : " + cpp_Dir + "/" + fname);
                CHtmlTools::Copy_File(src_Dir +"/" + fname, cpp_Dir);
                CHtmlTools::Copy_File(src_Dir +"/" + fname, bin_Dir);
            }
            //....................... fichiers a placer dans le repertoire binaire ....................................
            else if (ext ==".so" || fname =="galsvlux" || fname =="cpgeslux" || ext ==".gip"|| ext ==".ini")
            {   if (! TestAndSet_SesamVIniFiles(fname, sesam_Dir, src_Dir, sesam_Dir + "/etc" ))
                   {   G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("     Copie de : ") + src_Dir +"/" + fname + " vers : " + bin_Dir + "/" + fname);
                       CHtmlTools::Copy_File(src_Dir +"/" + fname, bin_Dir);
                   }
            }
            //....................... fichiers .h à modifier avant de recopier ....................................
            else if (TestAndSet_HeaderDevFiles(fname, src_Dir, cpp_Dir))
                    {
                    }

            //....................... repertoire de developpement ....................................
            else if (ext ==".h")
            {   G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("     Copie de : ")  + src_Dir +"/" + fname + " vers : " + cpp_Dir + "/" + fname);
                CHtmlTools::Copy_File(src_Dir +"/" + fname, cpp_Dir);
            }
        }
        ++it;
    } // endwhile ( (fi = it.current()) != 0 )
}


//----------------------------------------- copyWindw_Api -------------------------------------------------
void C_DlgMainDialog::copyWindw_Api(QString src_Dir,  QString bin_Dir,  QString cpp_Dir, QString sesam_Dir)
{ //........................ explorer la source .......................................
    QDir cur_dir( src_Dir );
    cur_dir.setFilter( QDir::All | QDir::NoSymLinks );
    //............ exploration de la liste ......................
    const QFileInfoList * pQFileInfoList = cur_dir.entryInfoList();
    if (pQFileInfoList==0) return;
    QFileInfoListIterator it( *pQFileInfoList );
    QFileInfo            *fi;
    while ( (fi = it.current()) != 0 )
    {QString fname = fi->fileName().latin1();
        if      (fname == "..")
        {
        }
        else if (fi->isDir() && fname != "." )
        {if (fname.left(4).lower() != "sgal") copyWindw_Api(src_Dir + "/" + fname, bin_Dir, cpp_Dir, sesam_Dir);
        }
        else if (fi->isFile())
        {   QString ext = getExtension(fname).lower();
            if (ext==".gz")
            {
            }
            else if (ext ==".dll" || ext ==".exe" || ext ==".ini" || ext ==".gip")
            {  if (! TestAndSet_SesamVIniFiles(fname, sesam_Dir, src_Dir, bin_Dir))
                  {  G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("     Copie de : ") + src_Dir +"/" + fname + " vers : " + bin_Dir + "/" + fname);
                     CHtmlTools::Copy_File(src_Dir +"/" + fname, bin_Dir);
                  }
            }
            else if (TestAndSet_HeaderDevFiles(fname, src_Dir, cpp_Dir))
                    {
                    }
            else if (ext ==".lib" || ext ==".h")
            {   G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("     Copie de : ")  + src_Dir +"/" + fname + " vers : " + cpp_Dir + "/" + fname);
                CHtmlTools::Copy_File(src_Dir +"/" + fname, cpp_Dir);
            }
        }
        ++it;
    } // endwhile ( (fi = it.current()) != 0 )
}

//----------------------------------------- TestAndSet_SesamVIniFiles  ---------------------------------------------
bool C_DlgMainDialog::TestAndSet_SesamVIniFiles(const QString &fname, const QString &sesam_Dir, const QString &src_Dir, const QString &dest_Dir)
{if (fname=="sesam.ini")
    {G_pCApp->Datasemp_OutMessage(textEdit_Message, tr (".......... Modification de : ")  +  fname + " ......................");
     QString str_ini;
     CMoteurBase::Param_UpdateFromDisk(src_Dir +"/" + fname , str_ini);    // charger le ficher et le modifier
     CMoteurBase::Param_WriteParam(&str_ini,"COMMUN", "RepertoireTravail", sesam_Dir + QDir::separator()+"adm");
     CMoteurBase::Param_WriteParam(&str_ini,"COMMUN", "RepertoireTable"  , sesam_Dir + QDir::separator()+"ssv");
     CMoteurBase::Param_WriteParam(&str_ini,"SSV",    "RepertoireTable"  , sesam_Dir + QDir::separator()+"ssv");
     CMoteurBase::Param_WriteParam(&str_ini,"SRT",    "RepertoireTable"  , sesam_Dir + QDir::separator()+"srt");
     CMoteurBase::Param_WriteParam(&str_ini,"STS",    "RepertoireTable"  , sesam_Dir + QDir::separator()+"sts");
     str_ini.prepend(tr ("; Installation de Sesam-Vitale le : ") + QDate::currentDate().toString("dd-MM-yyyy") + " par set_bases pour MedinTux\r\n");
     str_ini.replace(" = ","=");   // sinon le ini de Sesam Vitale ne fonctionne pas !!!
     G_pCApp->Datasemp_OutMessage(textEdit_Message, str_ini);
     G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("     Copie de : ") + src_Dir +"/" + fname + tr(" modifié vers : ") + dest_Dir + "/" + fname );
     CMoteurBase::Param_UpdateToDisk(dest_Dir +"/" + fname , str_ini);      // enregistrer le ficher modifie dans la bonne destination
     return TRUE;
    }
  return FALSE;
}

//----------------------------------------- TestAndSet_HeaderDevFiles  ---------------------------------------------
bool C_DlgMainDialog::TestAndSet_HeaderDevFiles(const QString &fname, const QString &src_Dir, const QString &cpp_Dir)
{ if (fname == "sgd.h" || fname == "srt.h" || fname == "ssv.h"|| fname == "sts.h")
     {
      G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("     Copie et modification de : ")  + src_Dir + "/" + fname + " vers : " + cpp_Dir + "/" + fname);
      QString cpp;
      CMoteurBase::Param_UpdateFromDisk(src_Dir +"/" + fname , cpp);    // charger le ficher et le modifier
      int pos = cpp.find(tr ("(## add by and for MedinTux)"));
      if (pos ==-1) cpp.replace("etc. */",
                             tr("etc. */\r\n//......... gérer les spécificités selon OS (## add by and for MedinTux) ...............\r\n"
                                " #if   defined(Q_WS_WIN)\r\n"
                                "   #include \"win32def.h\"\r\n"
                                "#elif defined(Q_WS_X11)\r\n"
                                "   #include \"unixdef.h\"\r\n"
                                "#elif defined(Q_WS_MAC)\r\n"
                                "   #include \"macosdef.h\"\r\n"
                                "#endif\r\n"));
       CMoteurBase::Param_UpdateToDisk(cpp_Dir +"/" + fname , cpp);      // enregistrer le ficher modifie dans la bonne destination
       return TRUE;
     }
  return FALSE;
}


//----------------------------------------- getExtension  ---------------------------------------------
QString C_DlgMainDialog::getExtension(const QString &file)
{   int pos = file.findRev('.');
    if (pos ==-1) return QString::null;
    return file.mid(pos);
}

//----------------------------------------- copyTables_Api ---------------------------------------------
void C_DlgMainDialog::copyTables_Api(QString src_Dir,  QString dest_Dir)
{
    //........................ explorer la source .......................................
    QDir cur_dir( src_Dir );
    cur_dir.setFilter( QDir::All | QDir::NoSymLinks );

    if ( ! QFile::exists( dest_Dir  ) )
    { G_pCApp->Datasemp_OutMessage(textEdit_Message, tr ("----------- Création de ce répertoire en cours : ") + dest_Dir + "-----------");
        cur_dir.mkdir(dest_Dir);
    }
    //............ exploration de la liste ......................
    const QFileInfoList * pQFileInfoList = cur_dir.entryInfoList();
    if (pQFileInfoList==0) return;
    QFileInfoListIterator it( *pQFileInfoList );
    QFileInfo            *fi;
    while ( (fi = it.current()) != 0 )
    {
        QString fname = fi->fileName().latin1();
        if      (fname == "..")
        {
        }
        else if (fi->isDir() && fname != "." )
        {   QString prefix = fname.left(3).lower();
            if (prefix == "srt" || prefix == "ssv" || prefix == "sts")
            {copyTables_Api( src_Dir + "/" + fname, dest_Dir + "/" + prefix);
            }
        }
        else if (fi->isFile())
        {   QString ext = getExtension(fname).lower();
            if (ext != ".h" && ext != ".dll" && ext != ".lib" && ext != ".exe" && ext != ".so" && ext != ".gz")
            {   G_pCApp->Datasemp_OutMessage(textEdit_Message, tr(" Table Sesam-Vitale en cours de copie : ") + src_Dir + "/" + fname + " vers : " + dest_Dir + "/" + fname);
                CHtmlTools::Copy_File(src_Dir + "/" + fname, dest_Dir);
            }
        }
        ++it;
    }
}


