unit u_webbookscreate;

{$IFDEF FPC}
{$R *.lfm}
{$mode objfpc}{$H+}
{$ELSE}
{$DEFINE WINDOWS}
{$R *.lfm}
{$ENDIF}

////////////////////////////////////////////////////////////////////////////////
// Satic Web Books Create
// Création de sites web statiques de livrels libres et gratuits.
// Licence : GPL
// LIBERLOG 2019
// Auteur : Matthieu GIROUX
// Descriptions
// Création d'un arbre complet, d'une page de contact en PHP, de fiches, etc.
// Historique
// 0.9.9.0 : première version publiée
////////////////////////////////////////////////////////////////////////////////

interface

uses
{$ifdef unix}
  BaseUnix,
{$endif}

{$IFNDEF FPC}
  Mask,  rxToolEdit, JvExControls,
{$ELSE}
  LCLIntf, LCLType, EditBtn,FileUtil,
{$ENDIF}
  fonctions_string,
{$ifdef windows}
  Windows,
{$endif}
{$IFDEF WIN32}
  Registry,
{$ENDIF}
{$IFNDEF FPC}
  fonctions_version,
{$ENDIF}
  SysUtils, Classes, Graphics, Controls,
  Forms, Dialogs, StdCtrls, DB,
  DBCtrls, ExtCtrls, Buttons,
  ComCtrls, DBGrids, Grids,
  functions_html, ExtJvXPCheckCtrls,
  U_OnFormInfoIni, fonctions_system,
  u_buttons_appli, U_ExtFileCopy,
  fonctions_web,
  u_extabscopy,
  BGRABitmap,
  u_buttons_defs, u_extgrid;

{$IFNDEF FPC}
const
  gVer_WebBooks : T_Version = ( Component : 'Application WebBooksCreator' ;
                                             FileUnit : 'U_WebBooksCreate' ;
                                             Owner : 'Matthieu Giroux' ;
                                             Comment : 'Créateur de sites web HTML de livrels.' ;
                                             BugsStory :  '1.0.0.0 : More compliance and back picture.' +#13#10  +
                                                          '0.9.9.9 : Mobile.' +#13#10  +
                                                          '0.9.9.1 : Testing not fully ok.' +#13#10  +
                                                          '0.9.9.0 : First published version';
                                             UnitType : CST_TYPE_UNITE_APPLI ;
                                             Major : 1 ; Minor : 0 ; Release : 0 ; Build : 0 );
{$ENDIF}

const
  {$IFDEF LINUX}
      CST_GETPDFMETADATA = 'pdfinfo' ;
      CST_GETPDFIMAGE = 'pdftocairo' ;
      CST_GETPDFIMAGE_OPTION1 = '-jpeg' ;
      CST_GETPDFIMAGE_OPTION2 = '-singlefile' ;

      CST_GET_EPUB_INFOS = 'einfo';
      CST_GET_EPUB_FILES = 'unzip';
      CST_GET_SOZI_IMG   = 'inkscape' ;
      CST_GET_SOZI_IMG_OPTIONS_1   = '-z' ;
      CST_GET_SOZI_IMG_OPTIONS_2   = '-h' ;
      CST_GET_SOZI_IMG_OPTIONS_3   = '1000' ;
  {$ENDIF}
      CST_IMG_DIRECTORY  = 'IMG' ;
      CST_IMG_BACK       = 'back.png' ;
      CST_TILDE = '''';
      CST_REPLACE_TILDE = '''\''''';
      CST_WebBooks = 'WebBooks' ;
      CST_WebBooks_WithLicense = CST_WebBooks + ' Creator  GNU GPL ';
      CST_HTML_CLASS_TEXT = ' class="Text">';
      CST_HTML_CLASS_DOWNLOADS = ' class="downloads">';
      CST_HTML_TARGET_SEE     = 'voir';
      CST_EXTENSION_PDF_MINI  = 'pdf';
      CST_EXTENSION_EPUB_MINI = 'epub';
      CST_EXTENSION_ODT_MINI  = 'odt';
      CST_EXTENSION_ODP_MINI  = 'odp';
      CST_EXTENSION_PPT_MINI  = 'ppt';
      CST_EXTENSION_PPS_MINI  = 'pps';
      CST_EXTENSION_CSV_MINI  = 'csv';
      CST_EXTENSION_TXT_MINI  =  'txt';
      CST_EXTENSION_SLA_MINI  =  'sla';
      CST_EXTENSION_RTF_MINI  =  'rtf';
      CST_EXTENSION_DOC_MINI  =  'doc';
      CST_EXTENSION_DOCX_MINI =  'docx';
      CST_EXTENSION_SVG_MINI  =  'svg';
      CST_EXTENSION_SOZI_ONLY =  'sozi';
      CST_EXTENSION_SOZI_MINI =  'sozi.html';
      CST_EXTENSION_JSON_MINI =  'sozi.json';
      CST_EXTENSION_PDF  = CST_DOT+CST_EXTENSION_PDF_MINI;
      CST_EXTENSION_EPUB = CST_DOT+CST_EXTENSION_EPUB_MINI;
      CST_EXTENSION_ODT  = CST_DOT+CST_EXTENSION_ODT_MINI;
      CST_EXTENSION_ODP  = CST_DOT+CST_EXTENSION_ODP_MINI;
      CST_EXTENSION_PPT  = CST_DOT+CST_EXTENSION_PPT_MINI;
      CST_EXTENSION_PPS  = CST_DOT+CST_EXTENSION_PPS_MINI;
      CST_EXTENSION_CSV  = CST_DOT+CST_EXTENSION_CSV_MINI;
      CST_EXTENSION_TXT  = CST_DOT+CST_EXTENSION_TXT_MINI;
      CST_EXTENSION_SLA  = CST_DOT+CST_EXTENSION_SLA_MINI;
      CST_EXTENSION_RTF  = CST_DOT+CST_EXTENSION_RTF_MINI;
      CST_EXTENSION_DOC  = CST_DOT+CST_EXTENSION_DOC_MINI;
      CST_EXTENSION_DOCX = CST_DOT+CST_EXTENSION_DOCX_MINI;
      CST_EXTENSION_SVG  = CST_DOT+CST_EXTENSION_SVG_MINI;
      CST_EXTENSION_SOZI = CST_DOT+CST_EXTENSION_SOZI_MINI;
      CST_EXTENSION_JSON = CST_DOT+CST_EXTENSION_JSON_MINI;
      CST_EXTENSION_SOZI_ONLY_DOT = CST_DOT+CST_EXTENSION_SOZI_ONLY;
      CST_SCRIPT_FILE   = 'conversion';
      CST_CONVERTED     = '-Converted';
      CST_INDEX_MOBILE  = CST_INDEX+'mobile';
      CST_INDEX_SOURCE  = CST_INDEX+'source';
      CST_INDEX_BODY    = CST_INDEX+'body';
      CST_INDEX_PDF     = CST_INDEX+'pdf';
      CST_INDEX_DOWNLOADS = CST_INDEX+'downloads';

type

  { TF_WebBooks }

  TF_WebBooks = class(TForm)
    bt_export: TFWExport;
    bt_gen: TFWExport;
    bt_LookAt: TFWSearch;
    bt_see: TFWSearch;
    cb_Files: TComboBox;
    cb_Themes: TComboBox;
    ch_7ZIPLiv: TCheckBox;
    ch_7ZIPScr: TCheckBox;
    ch_7ZIPSo1: TCheckBox;
    ch_convert: TCheckBox;
    ch_DOC: TCheckBox;
    ch_DOCX: TCheckBox;
    ch_downloads: TCheckBox;
    ch_EPUB: TCheckBox;
    ch_EraseOrigin: TFWTrash;
    ch_EraseOrigin1: TFWTrash;
    ch_GZLiv: TCheckBox;
    ch_GZScr: TCheckBox;
    ch_GZSo1: TCheckBox;
    ch_HTM: TCheckBox;
    ch_Impress: TCheckBox;
    ch_Names64: TCheckBox;
    ch_OD: TCheckBox;
    ch_PDF: TCheckBox;
    ch_Pictures: TCheckBox;
    ch_PPS: TCheckBox;
    ch_PS: TCheckBox;
    ch_PS1: TCheckBox;
    ch_RecurseMemo: TCheckBox;
    ch_RecurseSubDirs: TCheckBox;
    ch_RTF: TCheckBox;
    ch_SLA: TCheckBox;
    ch_Slides: TCheckBox;
    ch_Sounds: TCheckBox;
    ch_Sozi: TCheckBox;
    ch_SVG: TCheckBox;
    ch_TorrentLiv: TCheckBox;
    ch_TorrentScr: TCheckBox;
    ch_TorrentSo1: TCheckBox;
    ch_TXT: TCheckBox;
    ch_Videos: TCheckBox;
    ch_ZIPLiv: TCheckBox;
    ch_ZIPScr: TCheckBox;
    ch_ZIPSo: TCheckBox;
    ch_ZIPSo1: TCheckBox;
    ch_ZIPSo2: TCheckBox;
    ch_ZIPSo4: TCheckBox;
    de_indexdir: TDirectoryEdit;
    de_websitedir: TDirectoryEdit;
    ed_Author: TEdit;
    ed_Author1: TEdit;
    ed_ExtMobile: TEdit;
    ed_Language: TEdit;
    ed_IndexName: TEdit;
    ed_TXTResume: TEdit;
    GridFlags: TExtGrid;
    FileCopy: TExtFileCopy;
    ds_Individu: TDatasource;
    fne_export: TFileNameEdit;
    fne_import: TFileNameEdit;
    FWClose1: TFWClose;
    GroupBox1: TGroupBox;
    GroupBox2: TGroupBox;
    GroupBox3: TGroupBox;
    GroupBox4: TGroupBox;
    GroupBox5: TGroupBox;
    Label10: TLabel;
    Label11: TLabel;
    Label13: TLabel;
    Label14: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    Label44: TLabel;
    Label5: TLabel;
    Label6: TLabel;
    Label7: TLabel;
    lb_Comments: TLabel;
    lb_Images: TLabel;
    lb_Images1: TLabel;
    L_thema: TLabel;
    me_BottomMemo: TMemo;
    me_Description: TMemo;
    OnFormInfoIni: TOnFormInfoIni;
    OpenDialog: TOpenDialog;
    Panel1: TPanel;
    Panel10: TPanel;
    Panel2: TPanel;
    Panel3: TPanel;
    Panel4: TPanel;
    Panel5: TPanel;
    Panel6: TPanel;
    Panel7: TPanel;
    Panel8: TPanel;
    Panel9: TPanel;
    pArchives: TPanel;
    pArchiveScrib: TPanel;
    pArchiveScrib1: TPanel;
    pArchiveScrib2: TPanel;
    pArchiveScrib3: TPanel;
    pAuthor: TPanel;
    pAuthor1: TPanel;
    pAuthor2: TPanel;
    pa_options: TPanel;
    pb_Progress: TProgressBar;
    pdowloadConvert: TPanel;
    pexport: TPanel;
    pFiles: TPanel;
    pFolders: TPanel;
    pimport: TPanel;
    pLivrels: TPanel;
    pMedias: TPanel;
    pOptionsScLiv: TPanel;
    pScribels: TPanel;
    pScribels1: TPanel;
    pScribLivr: TPanel;
    pthema: TPanel;
    Splitter1: TSplitter;
    Splitter2: TSplitter;
    Splitter3: TSplitter;
    Splitter4: TSplitter;
    Splitter5: TSplitter;
    Splitter6: TSplitter;
    spSkinPanel1: TPanel;
    procedure bt_exportClick(Sender: TObject);
    procedure bt_genClick(Sender: TObject);
    procedure bt_seeClick(Sender: TObject);
    procedure ch_EraseOrigin1Click(Sender: TObject);
    procedure de_websitedirChange(Sender: TObject);
    procedure ed_LanguageChange(Sender: TObject);
    procedure fne_ExportAcceptFileName(Sender: TObject; var Value: String);
    procedure fne_importAcceptFileName(Sender: TObject; var Value: String);
    procedure fne_importChange(Sender: TObject);
    procedure FormShow(Sender: TObject);
  private
    { Déclarations privées }
    procedure DoAfterInit(const ab_Ini: Boolean=True);
    procedure p_AddFiles ( const as_Source, as_dest, as_subdirForward, as_ExtMobile : String ;
                           const astl_files : TStringList;
                           const ai_eraseBegin, ai_Level : Integer;
                           const ab_Root : Boolean ;
                           var   as_BackDirText : String ;
                           var  at_SheetsLinks : TAHTMLULTabSheet);
    procedure p_CreateAHtmlFile(const astl_Destination: TStrings;
      const as_BeginingFile, as_Describe, as_file, as_Title, as_LittleTitle, as_LongTitle: string;
      const as_Subdir: string = '';
      const as_ExtFile: string = CST_EXTENSION_HTML;
      const as_BeforeHTML: string = ''; const astl_Body : TStrings = nil );
    procedure p_genHtmlHome ( const as_directory, as_dirDest,
                                    as_subdirForward, as_TitleDir, as_backDirText, as_ExtMobile : String;
                              const astl_Files : TStringList;
                              const ab_Root : Boolean  ;
                              const at_SheetsLinks : TAHTMLULTabSheet);
    procedure p_comment(const as_Comment: String);
    procedure p_Unfat(const as_directory: String);
  public
    { Déclarations publiques }
    constructor Create(aowner:TComponent); override;
  end;

var
  F_WebBooks: TF_WebBooks;
  gs_sourcedir : String;
  gb_Generate : boolean = False;


implementation

uses  fonctions_ini,
  functions_html_tree,
{$IFDEF FPC}
  unite_messages,
  web_strings,
  webbooks_strings, strutils,
{$ELSE}
  unite_messages_delphi,
  web_strings_delphi,
  webbooks_strings_delphi,
{$ENDIF}
{$IFDEF WIN32}
//  windirs,
{$ENDIF}
  fonctions_dialogs,
  fonctions_webfiles,
  LazFileUtils,
  fonctions_languages,
  U_HTMTri,
  fonctions_file;

procedure TF_WebBooks.bt_genClick(Sender: TObject);
var lb_gen : Boolean;
    ls_question : String;
    lstl_Files :  TStringList;
    lt_Sheets : TAHTMLULTabSheet;
var ls_Source, ls_SourceText : String;
Begin
  if not fb_genUnGenPrepare(de_indexdir,cb_Files,cb_Themes,ls_Source)
   Then
    Exit;

  gs_RootPathForExport := IncludeTrailingPathDelimiter ( de_websitedir.Directory );
  gs_html_source_file := CST_SUBDIR_FILES + cb_files.Items[cb_files.ItemIndex]+DirectorySeparator;
  gs_sourcedir         := IncludeTrailingPathDelimiter ( de_indexdir  .Directory );

  lb_gen := False;
  if not DirectoryExistsUTF8(gs_sourcedir) Then
   Begin
    MessageDlg(gs_Error_only,gs_error_WebSite_Sources_do_not_exists,mtError,[mbOK],0,mbOK);
    Exit;
   end;
  if not DirectoryExistsUTF8(gs_RootPathForExport) Then
   Begin
    if MessageDlg(gs_Warning,fs_RemplaceMsg(gs_confirm_WebSite_directory_do_not_exists_create_it,[gs_RootPathForExport]),mtConfirmation,mbYesNo,0,mbYes)=mrYes Then
     try
      fb_CreateDirectoryStructure(gs_RootPathForExport);
     finally
     end;
    if not DirectoryExistsUTF8(gs_RootPathForExport) Then
     Begin
       MessageDlg(gs_Error_only,gs_error_cannot_create_WebSite_directory,mtError,[mbOK],0,mbOK);
       Exit;
     end;
   end;
  if pos(de_websitedir.Directory,de_indexdir.Directory)>0 Then
   Begin
    MessageDlg(gs_Error_only,gs_cannot_create_website_including_sources,mtError,[mbOK],0,mbOK);
    Exit;
   end;
  ls_question := fs_RemplaceMsg ( gs_warning_WebSite_Create,[gs_RootPathForExport]);
  if FileExistsUTF8(gs_RootPathForExport+ed_IndexName.Text+CST_EXTENSION_HTML_PLAIN) Then
   Begin
    if ch_convert.Checked Then
     AppendStr(ls_question,gs_warning_Converting_can_be_long+gs_warning_Every_Converted_Files_Rewritten);
    AppendStr(ls_question,gs_warning_Every_WebSite_Files_Rewritten+gs_ready);
    lb_gen:=MessageDlg(gs_Warning,ls_question,mtConfirmation,mbOKCancel,0)=mrOK;
   end
  Else
   if DirectoryIsEmpty(gs_RootPathForExport) Then
     Begin
       if ch_convert.Checked Then
         AppendStr(ls_question,gs_warning_Converting_can_be_long);
       AppendStr(ls_question,gs_ready);
       lb_gen:=MessageDlg(gs_Warning,ls_question,mtConfirmation,mbYesNo,0,mbYes)=mrYes;
     end;


    with FileCopy do
     try
      FileOptions:=FileOptions-[cpDestinationIsFile];
      Source := ls_Source;
      Destination := gs_RootPathForExport;
      CopySourceToDestination;
      Source := gs_Root + CST_SUBDIR_CLASSES;
      CopySourceToDestination;
    finally
      FileOptions:=FileOptions+[cpDestinationIsFile];
      FilesOptions:=FilesOptions+[cpCopyAll];
     end;

  lstl_Files := TStringList.Create;
  if lb_gen Then
    try // starting work
      gb_Generate := True;
      ls_SourceText := '';
      Finalize(lt_Sheets);
      p_AddFiles(gs_sourcedir, gs_RootPathForExport, '', '', lstl_Files, 0, 1, True, ls_SourceText, lt_Sheets );
      p_genHtmlHome ( gs_sourcedir, gs_RootPathForExport, '', fs_ReplaceChar(ExtractDirName(gs_sourcedir),'_',' '), '', '',  lstl_Files, True, lt_Sheets );
      lstl_Files.Clear;
      Finalize(lt_Sheets);
      p_AddFiles(gs_sourcedir, gs_RootPathForExport, '', ed_ExtMobile.Text, lstl_Files, 0, 1, True, ls_SourceText, lt_Sheets );
      p_genHtmlHome ( gs_sourcedir, gs_RootPathForExport, '', fs_ReplaceChar(ExtractDirName(gs_sourcedir),'_',' '), '', ed_ExtMobile.Text,  lstl_Files, True, lt_Sheets );
    finally
      lstl_Files.Destroy;
      pa_options.Enabled:=True;
      gb_Generate := False;
      p_comment ( gs_Web_Finished ); // advert for user
    end;
end;

function fs_CreateIMG_HTML ( const as_subdirforward, as_ImageName : string; const ab_PC : Boolean):String;
Begin
  Result := CST_HTML_IMAGE_SRC+as_subdirForward+CST_IMG_DIRECTORY+CST_HTML_DIR_SEPARATOR+as_ImageName+'"';
  if ab_PC Then
    AppendStr(Result,' HEIGHT="28"');
  AppendStr(Result,' />');
end;

// procedure TF_WebBooks.p_genHtmlHome
// Default HTML page
procedure TF_WebBooks.p_genHtmlHome ( const as_directory, as_dirDest,
                                            as_subdirForward, as_TitleDir, as_backDirText, as_ExtMobile : String;
                                      const astl_Files : TStringList;
                                      const ab_Root : Boolean ;
                                      const at_SheetsLinks : TAHTMLULTabSheet);
var
  lstl_HTMLHome,lstl_HTMLMetas,lstl_HTMLMeta,
  lstl_HTMLaDownload,lstl_HTMLDownloads, lstl_processes   : TStringList;
  li_PosFiles,i: integer;
  lb_slides, lb_covered : boolean;

  ls_afile, ls_afileWithoutExt  : String;

  //  transcode en html les métadonnées PDF ou EPUB de GNU Linux
  function fs_HtmlTranscode ( const as_meta : String ; const ab_epub : Boolean) : String;
  const CST_FORGET_IT_COUNT =  6;
        CST_FORGET_IT :  Array [1..CST_FORGET_IT_COUNT] of String = ('Filename:','Root(s):','parser error','(UUID:','(uuid:','(calibre:');
  var li_i,li_j : Integer;
      ls_meta,ls_metaold : String;
      lb_found  : Boolean;
  begin
    Result     :='';
    ls_metaold :='';
    write ( as_meta );
    lstl_HTMLMeta.Text:=as_meta;
    for li_i:=0  to lstl_HTMLMeta.Count-1 do
      Begin
        lb_found := False;
        ls_meta  := trim  ( lstl_HTMLMeta [li_i] );
        for li_j:=1  to CST_FORGET_IT_COUNT do
          if pos ( CST_FORGET_IT[li_j], ls_meta ) > 0 Then
            Begin
             lb_found := True;
             Break;
            end;
        if lb_found
        or ( ls_meta =  '' )
          Then
            Continue;
        if ( pos(':',ls_meta) > 0 ) Then
           Begin
            if ab_epub  Then
               Begin
                if ( pos('(ISBN',ls_meta) > 0 )
                  Then AppendStr(Result,CST_HTML_BEGIN+CST_HTML_LI+' class="ISBN">'+trim(copy(ls_meta,1,pos('(ISBN',ls_meta)-1))+CST_HTML_LI_END+#10)
                  Else if  pos ( '(s):', ls_meta ) = 0
                    Then
                      Begin
                       if pos('(',ls_meta) > 0
                       Then AppendStr(Result,CST_HTML_BEGIN+CST_HTML_LI+' class="'+trim(copy(ls_meta, 1, pos(':',ls_meta)-1))+'">'+trim(copy(ls_meta, pos(':',ls_meta)+1,pos('(',ls_meta)-1-pos(':',ls_meta)))+CST_HTML_LI_END+#10)
                       Else AppendStr(Result,CST_HTML_BEGIN+CST_HTML_LI+' class="'+trim(copy(ls_meta, 1, pos(':',ls_meta)-1))+'">'+trim(copy(ls_meta, pos(':',ls_meta)+1,Length(ls_meta)))+CST_HTML_LI_END+#10)
                      End
                    Else
                     Begin
                      ls_metaold := copy(ls_meta,1,pos ('(s):', ls_meta )-1)+':';
                      Continue;
                     end;
               end
              else
                Begin
                 if pos ( 'eywords:', ls_meta ) > 0 then
                   Begin
                    p_addKeyWord(copy(ls_meta,  pos(':',ls_meta)+1,Length(ls_meta)),',');
                    Continue;
                   end;
                 AppendStr(Result,CST_HTML_BEGIN+CST_HTML_LI+' class="'+trim(copy(ls_meta, 1, pos(':',ls_meta)-1))+'">'+trim(copy(ls_meta,  pos(':',ls_meta)+1,Length(ls_meta)))+CST_HTML_LI_END+#10);
                end;
           End
         Else
           if ab_epub  Then
             Begin
              if pos ( 'eyword(s):', ls_metaold ) > 0 then
                Begin
                 p_addKeyWord(ls_meta,',');
                 Continue;
                end;
              if ( pos(':',ls_metaold) = 0 ) Then
               Begin
                AppendStr(ls_metaold,ls_meta);
                Continue;
               end;
              if ( pos('(',ls_meta) > 0 )
                Then AppendStr(Result,CST_HTML_BEGIN+CST_HTML_LI+' class="'+trim(copy(ls_metaold, 1, pos(':',ls_metaold)-1))+'">'+trim(copy(ls_meta,1,pos('(',ls_meta)-1))+CST_HTML_LI_END+#10)
                else AppendStr(Result,CST_HTML_BEGIN+CST_HTML_LI+' class="'+trim(copy(ls_metaold, 1, pos(':',ls_metaold)-1))+'">'+trim(ls_meta)+CST_HTML_LI_END+#10);
             end;
        ls_metaold := ls_meta;
      end;
  end;

  //  Enlève la fin PDF des métadonnées GNU Linux
  function fs_HtmlTranscodePDF ( const as_meta : String ) : String;
  begin
    if as_meta > ''
      Then Result:=copy(as_meta, 1,pos('Creator:',as_meta)-2)
      Else Result:='';
  end;

  //  Enlève la fin EPUB des métadonnées GNU Linux
  function fs_HtmlTranscodeEPUB ( const as_meta : String ) : String;
  begin
    if as_meta > ''
      Then Result:=copy(as_meta, 1,pos('Reading order:',as_meta)-2)
      Else Result:='';
  end;


  // Crée la présentation des livrels en HTML
  function fb_FillandAddFile (  const as_BookFile, as_BookFileWithoutExt, as_PathDest, as_Ext : String;var ab_covered : Boolean):Boolean;
  var ls_extAFile, ls_metas, ls_FileDest, ls_PathSource : String;
      lts_Strings : TStrings;

      procedure p_AddDownload (const as_aBookFilePath, as_ExtDownload : String);
      var ls_dest  : String;
        begin
          lstl_HTMLaDownload.Clear;
          if (as_ExtDownload = CST_EXTENSION_PDF)
          or (as_ExtDownload = CST_EXTENSION_SVG)
          or (as_ExtDownload = CST_EXTENSION_SOZI)
          or (as_ExtDownload = CST_EXTENSION_JSON)
            Then p_LoadStringList (lstl_HTMLaDownload, CST_INDEX_PDF   +CST_EXTENSION_HTML )
            Else p_LoadStringList (lstl_HTMLaDownload, CST_INDEX_SOURCE+CST_EXTENSION_HTML );

          ls_dest := as_PathDest+as_BookFileWithoutExt+as_ExtDownload;
          p_ReplaceLanguageString(lstl_HTMLaDownload,'Link', as_BookFileWithoutExt+as_ExtDownload,[rfReplaceAll]);
          if Pos(CST_EXTENSION_JSON,as_ExtDownload) > 0
           Then p_ReplaceLanguageString(lstl_HTMLaDownload,'Caption',CST_EXTENSION_JSON_MINI,[rfReplaceAll])
           else if PosEx('.',as_ExtDownload,2) > 0
            Then p_ReplaceLanguageString(lstl_HTMLaDownload,'Caption',copy(as_ExtDownload,2,PosEx('.',as_ExtDownload,2)-2),[rfReplaceAll])
            Else p_ReplaceLanguageString(lstl_HTMLaDownload,'Caption',copy(as_ExtDownload,2,Length(as_ExtDownload)-1),[rfReplaceAll]);
          lstl_HTMLDownloads.AddStrings(lstl_HTMLaDownload);
          if not FileExistsUTF8(ls_dest) Then
            CopyFileUTF8 ( ExtractFilePath(as_aBookFilePath)+as_BookFileWithoutExt+as_ExtDownload,ls_dest );
        end;

      begin
          Result :=False;
          ls_PathSource:=IncludeTrailingPathDelimiter(ExtractFileDir(as_BookFile));
          if  as_Ext=CST_EXTENSION_EPUB  Then
            Begin
              p_AddDownload (as_BookFile,as_Ext);
              Result :=True;
              ls_FileDest := as_PathDest+as_BookFileWithoutExt;
              //RenameFileUTF8(as_PathDest+as_BookFileWithoutExt+as_Ext,as_PathDest+'coverring.zip');
              ls_extAFile := CST_EXTENSION_JPG;
              if ( FileExistsUTF8(ls_PathSource+as_BookFileWithoutExt+CST_EXTENSION_EPUB)) Then
                Begin
                  lts_Strings := TStringList.Create;
                  try
                   lts_Strings.Add(ls_PathSource+as_BookFileWithoutExt+CST_EXTENSION_EPUB);
                   lts_Strings.Add('cover.jpeg');
                   lts_Strings.Add('-d');
                   lts_Strings.Add(as_PathDest);
                   fs_ExecuteProcess (  CST_GET_EPUB_FILES, '', lts_Strings,False);

                  finally
                    lts_Strings.Destroy;
                  end;

                end;
              Application.ProcessMessages;
              if ( FileExistsUTF8(as_PathDest+'cover.jpeg')) Then
                Begin
                  ab_covered := True;
                  if FileExistsUTF8(ls_FileDest+CST_EXTENSION_JPG)  then
                    DeleteFileUTF8(ls_FileDest+CST_EXTENSION_JPG);
                  RenameFileUTF8(as_PathDest+'cover.jpeg',ls_FileDest+CST_EXTENSION_JPG);
                End;
             if ( FileExistsUTF8(ls_FileDest+CST_EXTENSION_JPG)) Then
              Begin

{                  if  ( ls_extAFile <> CST_EXTENSION_JPG )
                and ( ls_extAFile <> CST_EXTENSION_JPEG ) Then
                  Begin
                    RenameFileUTF8(ls_FileDest+CST_EXTENSION_JPG,ls_FileDest+ls_extAFile);
                  End
                 Else ls_extAFile := CST_EXTENSION_JPG;  }
                lstl_HTMLMetas.Text:= fs_Create_Link(as_BookFileWithoutExt+ls_extAFile,
                                      fs_Create_Image(as_BookFileWithoutExt+ls_extAFile,gs_WebBooks_Cover+'" class="img_response'),CST_HTML_TARGET_SEE);
                lstl_HTMLMetas.Add(CST_HTML_TD_END+CST_HTML_BEGIN+CST_HTML_TD+CST_HTML_CLASS_TEXT);
              end;
            ls_metas := fs_ExecuteProcess (  CST_GET_EPUB_INFOS, ls_FileDest+CST_EXTENSION_EPUB);
           // RenameFileUTF8(as_PathDest+'coverring.zip',as_PathDest+as_BookFileWithoutExt+as_Ext);
//                  ls_metas:=getEpubMetadata(astl_Files [ li_PosFiles ], EPUB_TYPE);
                //for li_posMetas := 0 to High(las_metas) do
            lstl_HTMLMetas.Add(CST_HTML_BEGIN+CST_HTML_UL+' class="desc">');
            lstl_HTMLMetas.Add(fs_HtmlTranscode(fs_HtmlTranscodeEPUB(ls_metas),True));
            lstl_HTMLMetas.Add(CST_HTML_UL_END);
            lstl_HTMLMetas.Add(CST_HTML_BEGIN+CST_HTML_UL+CST_HTML_CLASS_DOWNLOADS);
            Exit;
          end
        else if  (LowerCase(as_Ext)=CST_EXTENSION_PDF) Then
          Begin
            p_AddDownload (as_BookFile,as_Ext);
             if FileExistsUTF8(as_PathDest+as_BookFileWithoutExt+CST_EXTENSION_EPUB) then
               Exit;
             if FileExistsUTF8(ls_PathSource+as_BookFileWithoutExt+CST_EXTENSION_PDF)
             or FileExistsUTF8(ls_PathSource+as_BookFileWithoutExt+UpperCase(CST_EXTENSION_PDF))
              Then
                Begin
                 lts_Strings := TStringList.Create;
                 try
                  lts_Strings.Add(CST_GETPDFIMAGE_OPTION1);
                  lts_Strings.Add(CST_GETPDFIMAGE_OPTION2);
                   if FileExistsUTF8(ls_PathSource+as_BookFileWithoutExt+CST_EXTENSION_PDF)
                    Then lts_Strings.Add(ls_PathSource+as_BookFileWithoutExt+CST_EXTENSION_PDF)
                    else if FileExistsUTF8(ls_PathSource+as_BookFileWithoutExt+UpperCase(CST_EXTENSION_PDF))
                      Then lts_Strings.Add(ls_PathSource+as_BookFileWithoutExt+UpperCase(CST_EXTENSION_PDF));
                  lts_Strings.Add(as_PathDest+as_BookFileWithoutExt);

                   fs_ExecuteProcess ( CST_GETPDFIMAGE,'', lts_Strings );
                 finally
                   lts_Strings.Destroy;
                 end;
                end;
            Application.ProcessMessages;
            ls_FileDest := as_PathDest+as_BookFileWithoutExt+CST_EXTENSION_JPG;
             if lb_slides
               Then lstl_HTMLMetas.Text:= fs_Create_Link(as_BookFileWithoutExt+CST_EXTENSION_JPG,
                                          fs_Create_Image(as_BookFileWithoutExt+CST_EXTENSION_JPG,gs_WebBooks_FirstPage+'" class="img_response_v'),CST_HTML_TARGET_SEE)
               Else lstl_HTMLMetas.Text:= fs_Create_Link(as_BookFileWithoutExt+CST_EXTENSION_JPG,
                                          fs_Create_Image(as_BookFileWithoutExt+CST_EXTENSION_JPG,gs_WebBooks_FirstPage+'" class="img_response'),CST_HTML_TARGET_SEE);
            lstl_HTMLMetas.Add(CST_HTML_TD_END+CST_HTML_TD_BEGIN);
             if FileExistsUTF8(ls_PathSource+as_BookFileWithoutExt+		CST_EXTENSION_PDF)
              Then ls_metas := fs_ExecuteProcess (  CST_GETPDFMETADATA, as_PathDest+as_BookFileWithoutExt+          CST_EXTENSION_PDF )
              Else ls_metas := fs_ExecuteProcess (  CST_GETPDFMETADATA, as_PathDest+as_BookFileWithoutExt+UpperCase(CST_EXTENSION_PDF));
            lstl_HTMLMetas.Add(CST_HTML_BEGIN+CST_HTML_UL+' class="desc">');
            lstl_HTMLMetas.Add(fs_HtmlTranscode(fs_HtmlTranscodePDF(ls_metas),False));
            lstl_HTMLMetas.Add(CST_HTML_UL_END);
            lstl_HTMLMetas.Add(CST_HTML_BEGIN+CST_HTML_UL+CST_HTML_CLASS_DOWNLOADS);
          end
          else if (as_Ext = CST_EXTENSION_SOZI) Then
            Begin
             lstl_HTMLDownloads.Add(CST_HTML_BEGIN+CST_HTML_UL+CST_HTML_CLASS_DOWNLOADS);
             p_AddDownload (as_BookFile,as_Ext);
             ls_extAFile := copy(as_BookFile,1,Length(as_BookFile)-Length(as_Ext));
              if FileExistsUTF8(ls_extAFile+CST_EXTENSION_JSON) Then
                p_AddDownload (ls_extAFile,CST_EXTENSION_JSON);
             if FileExistsUTF8(ls_extAFile+CST_EXTENSION_SVG)
             and not ab_covered then
               Begin
                 p_AddDownload (ls_extAFile,CST_EXTENSION_SVG);
                 p_AddDownload (ls_extAFile,CST_EXTENSION_PNG);
                 ab_covered := True;
                 lts_Strings := TStringList.Create;
                    try
                     lts_Strings.Add(CST_GET_SOZI_IMG_OPTIONS_2);
                     lts_Strings.Add(CST_GET_SOZI_IMG_OPTIONS_3);
                     lts_Strings.Add(ls_extAFile+CST_EXTENSION_SVG);
                     lts_Strings.Add('-e');
                     lts_Strings.Add(as_PathDest+as_BookFileWithoutExt+CST_EXTENSION_PNG);
                     fs_ExecuteProcess ( CST_GET_SOZI_IMG, CST_GET_SOZI_IMG_OPTIONS_1, lts_Strings);
                    finally
                      lts_Strings.Destroy;
                    end;
                 lstl_HTMLMetas.Text:= fs_Create_Link(as_BookFileWithoutExt+CST_EXTENSION_PNG,
                                       fs_Create_Image(as_BookFileWithoutExt+CST_EXTENSION_PNG,gs_WebBooks_FirstPage+'" class="img_response_v'),CST_HTML_TARGET_SEE);
                 lstl_HTMLMetas.Add(CST_HTML_TD_END+CST_HTML_BEGIN+CST_HTML_TD+ CST_HTML_CLASS_TEXT);
               end;
            end
          else
            p_AddDownload (as_BookFile,as_Ext);
      end;

  //  Création de l'index en HTML
begin
  if not assigned ( astl_Files )
    Then Exit;
  if (High(at_SheetsLinks)<0)
  and ( astl_Files.Count = 0 )
    Then Exit;
  if not DirectoryExistsUTF8(as_dirDest)
    Then CreateDirUTF8(as_dirDest);
  p_comment (( gs_Web_Home )); // advert for user
  lstl_HTMLHome       := TStringList.Create;
  lstl_HTMLDownloads  := TStringList.Create;
  lstl_HTMLaDownload  := TStringList.Create;
  lstl_HTMLMetas      := TStringList.Create;
  lstl_HTMLMeta       := TStringList.Create;
  if ab_Root
  and ch_convert.Checked Then
    lstl_processes := TStringList.Create;

  li_PosFiles        := 0;

  try
   p_ClearKeyWords;

   p_LoadStringList ( lstl_HTMLHome, CST_INDEX_BODY+CST_EXTENSION_HTML );

   lstl_HTMLHome.add(CST_HTML_BEGIN+CST_HTML_TABLE+' class="header">' );
   lstl_HTMLHome.add(CST_HTML_TR_BEGIN+CST_HTML_TD_BEGIN+CST_HTML_H1_BEGIN);
    if not ab_Root then
      lstl_HTMLHome.add(fs_Create_Link(CST_HTML_PARENT_DIRECTORY+as_ExtMobile+ed_IndexName.Text+CST_EXTENSION_HTML,fs_CreateIMG_HTML(as_subdirForward,CST_IMG_BACK,as_ExtMobile=''),CST_HTML_TARGET_SEE));
   lstl_HTMLHome.add(fs_FormatText ( as_TitleDir, mftFirstCharOfWordsIsMaj ));
   lstl_HTMLHome.add(CST_HTML_H1_END );
   lstl_HTMLHome.add(CST_HTML_TD_END+CST_HTML_BEGIN+CST_HTML_TD+' class="flags">' );
   with GridFlags do
    if RowCount> FixedRows Then
      Begin
       if not DirectoryExistsUTF8(IncludeTrailingPathDelimiter(de_websitedir.Directory)+CST_SUBDIR_IMAGES_SOFT) Then
         CreateDirUTF8(IncludeTrailingPathDelimiter(de_websitedir.Directory)+CST_SUBDIR_IMAGES_SOFT);
         for i:=FixedRows to RowCount - 1 do
           Begin
             CopyFileUTF8(fs_GetGridImagesDir+Cells[0,i],IncludeTrailingPathDelimiter(de_websitedir.Directory)+CST_SUBDIR_IMAGES_SOFT+Cells[0,i]);
             if Cells [3,i]>''
               Then lstl_HTMLHome.add(fs_Create_Link('#" onclick="'+StringReplace(Cells[3,i],'"','\"',[rfReplaceAll]),fs_Create_Image(as_subdirForward+CST_SUBDIR_IMAGES+CST_HTML_DIR_SEPARATOR+Cells[0,i],Cells[1,i],'flags')))
               Else lstl_HTMLHome.add(fs_Create_Link(               StringReplace(Cells[2,i],'"','\"',[rfReplaceAll]),fs_Create_Image(as_subdirForward+CST_SUBDIR_IMAGES+CST_HTML_DIR_SEPARATOR+Cells[0,i],Cells[1,i],'flags')));
           end;
      end;
   lstl_HTMLHome.add(CST_HTML_TD_END+CST_HTML_TR_END);
   lstl_HTMLHome.add(CST_HTML_TR_BEGIN+CST_HTML_BEGIN+CST_HTML_TD+' colspan="2">' );
   lstl_HTMLHome.add(fs_CreateULTabsheets(at_SheetsLinks, ''));
   lstl_HTMLHome.add(CST_HTML_TD_END+CST_HTML_TR_END);
   lstl_HTMLHome.add(CST_HTML_TABLE_END );
   if  (trim(me_Description.Text)>'')
   and ( ab_Root or ch_RecurseMemo.Checked )
     Then
       Begin
         lstl_HTMLHome.add(CST_HTML_Paragraph_BEGIN );
         lstl_HTMLHome.Add(fs_html_Lines(me_Description.Text));
         lstl_HTMLHome.add(CST_HTML_Paragraph_END );
       end;
   lstl_HTMLHome.add(CST_HTML_DIV_END+CST_HTML_BR+CST_HTML_BR);
   lb_covered         := False;
   p_LoadStringList ( lstl_HTMLDownloads, CST_INDEX_DOWNLOADS+CST_EXTENSION_HTML );

   while li_PosFiles < astl_Files.Count do
     Begin  // download and back link
      ls_afile:=astl_Files [ li_PosFiles ];
      if pos  ('.html',ls_afile  ) > 0 then
        ls_afileWithoutExt    :=  ExtractFileNameWithoutExt ( ls_aFile );
      if pos  ('.epub',ls_afile  ) > 0 then
        ls_afileWithoutExt    :=  ExtractFileNameWithoutExt ( ls_aFile );
      ls_afileWithoutExt    :=  ExtractFileNameWithoutExt ( ls_aFile );
      if (pos ( CST_EXTENSION_SOZI_ONLY_DOT, ls_afileWithoutExt ) > Length(ls_afileWithoutExt)-6)
      or (pos ( CST_EXTENSION_TAR, ls_afileWithoutExt ) > Length(ls_afileWithoutExt)-6)
        then  ls_afileWithoutExt:=ExtractFileNameWithoutExt(ls_afileWithoutExt);

      if pos ( CST_EXTENSION_SOZI_ONLY_DOT, ls_afileWithoutExt ) > 0
       then  ls_afileWithoutExt:=ExtractFileNameWithoutExt(ls_afileWithoutExt);
      lb_slides :=    FileExistsUTF8 ( ls_afileWithoutExt + CST_EXTENSION_PPS  )
                   or FileExistsUTF8 ( ls_afileWithoutExt + CST_EXTENSION_PPT  )
                   or FileExistsUTF8 ( ls_afileWithoutExt + CST_EXTENSION_SOZI )
                   or FileExistsUTF8 ( ls_afileWithoutExt + CST_EXTENSION_HTML_PLAIN )
                   or FileExistsUTF8 ( ls_afileWithoutExt + CST_EXTENSION_HTML )
                   or FileExistsUTF8 ( ls_afileWithoutExt + CST_EXTENSION_ODP  );
      fb_FillandAddFile ( ls_afile, ExtractFileNameOnly(ls_afileWithoutExt), as_dirDest, copy(ls_aFile,Length(ls_afileWithoutExt)+1,Length(ls_afile)), lb_covered );
      inc  ( li_PosFiles );
      if (li_PosFiles = astl_Files.Count)
      or (pos (ls_afileWithoutExt, astl_Files[li_PosFiles])=0) Then
        Begin
         if lb_slides
           Then lstl_HTMLHome.Add(CST_HTML_BEGIN+CST_HTML_DIV+' class="aslide">'+ CST_HTML_TABLE_BEGIN)
           Else lstl_HTMLHome.Add(CST_HTML_BEGIN+CST_HTML_DIV+' class="aside">' + CST_HTML_TABLE_BEGIN);
         lstl_HTMLHome.Add(CST_HTML_TR_BEGIN+CST_HTML_TD_BEGIN);
          if lstl_HTMLMetas.Count=0
            Then lstl_HTMLMetas.add(CST_HTML_BEGIN+CST_HTML_LI+' class="Title">'+fs_ReplaceChar(ExtractFileName (ls_afileWithoutExt),'_',' ')+CST_HTML_LI_END);
          lb_covered         := False;
          lstl_HTMLHome.AddStrings(lstl_HTMLMetas);
          lstl_HTMLMetas.Clear;
          lstl_HTMLHome.AddStrings(lstl_HTMLDownloads);
          p_LoadStringList ( lstl_HTMLDownloads, CST_INDEX_DOWNLOADS+CST_EXTENSION_HTML );
          lstl_HTMLHome.Add(CST_HTML_UL_END);
          lstl_HTMLHome.Add(CST_HTML_TD_END+CST_HTML_TR_END);
          lstl_HTMLHome.Add(CST_HTML_TABLE_END+CST_HTML_DIV_END);    //adding
        end;
   End;

   lstl_HTMLHome.add(CST_HTML_BEGIN+CST_HTML_DIV+' class="footer">' );
   if  (trim(me_BottomMemo.Text)>'')
     Then
       Begin
         lstl_HTMLHome.add(CST_HTML_Paragraph_BEGIN );
         lstl_HTMLHome.Add(fs_html_Lines(me_BottomMemo.Text));
         lstl_HTMLHome.add(CST_HTML_Paragraph_END );
       end;
    p_LoadStringList ( lstl_HTMLDownloads, CST_INDEX_FOOTER+CST_EXTENSION_HTML );
    lstl_HTMLHome.AddStrings( lstl_HTMLDownloads );
    lstl_HTMLHome.add(CST_HTML_DIV_END );
    if as_ExtMobile=''
      Then p_CreateAHtmlFile(lstl_HTMLHome, CST_INDEX, me_Description.Text,
             ExtractDirName(as_dirDest),
             as_TitleDir , gs_Web_Home, '', '')
      Else p_CreateAHtmlFile(lstl_HTMLHome, CST_INDEX_MOBILE, me_Description.Text,
             ExtractDirName(as_dirDest),
             as_TitleDir , gs_Web_Home, '', '');
    p_ReplaceLanguageString(lstl_HTMLHome,'SubDir',as_subdirForward,[rfReplaceAll]);
    p_ReplaceLanguageString(lstl_HTMLHome,'IndexMobile',ed_ExtMobile.Text+ed_IndexName.Text,[rfReplaceAll]);
    // saving the page
    p_saveFile(lstl_HTMLHome,gs_Web_Phase + ' - ' + gs_Web_Home,as_dirDest + as_ExtMobile + ed_IndexName.Text + CST_EXTENSION_HTML );
    if ab_Root
    and ch_convert.Checked Then
      if (lstl_processes.Count > 0) Then
       Begin
        p_saveFile(lstl_processes,gs_Web_Phase + ' - ' + gs_Web_Convert,as_dirDest + CST_SCRIPT_FILE + CST_EXTENSION_SCRIPT);
        if MessageDlg(gs_Web_Convert,fs_RemplaceMsg(gs_Web_Script_will_be_executed,[as_dirDest + CST_SCRIPT_FILE + CST_EXTENSION_SCRIPT]),
                      mtConfirmation,mbYesNo,0) = mrYes Then
         Begin
          p_comment(fs_RemplaceMsg(gs_Web_Convert,[CST_EXTENSION_ODT]));
          {$IFDEF WINDOWS}
          fs_ExecuteProcess(as_dirDest + CST_SCRIPT_FILE + CST_EXTENSION_SCRIPT,nil,'',False)
          {$ELSE}
          fs_ExecuteProcess('sh',as_dirDest,nil,False)
          {$ENDIF}
         End;
       end
       else if FileExistsUTF8(as_dirDest + CST_SCRIPT_FILE + CST_EXTENSION_SCRIPT) then
       if MessageDlg(gs_Web_Delete_File,fs_RemplaceMsg(gs_Web_Delete_File_confirm,[as_dirDest + CST_SCRIPT_FILE + CST_EXTENSION_SCRIPT]),mtConfirmation,mbYesNo,0) = mrYes
        Then
         DeleteFileUTF8(as_dirDest + CST_SCRIPT_FILE + CST_EXTENSION_SCRIPT);
  finally
    lstl_HTMLHome    .Destroy;
    lstl_HTMLMetas   .Destroy;
    lstl_HTMLMeta    .Destroy;

    lstl_HTMLDownloads.Destroy;
    lstl_HTMLaDownload.Destroy;
    if ab_Root
    and ch_convert.Checked Then
     lstl_processes.Destroy;
  end;
end;


// procedure TF_WebBooks.p_CreateAHtmlFile
// Creating a HTML page from parameters
procedure TF_WebBooks.p_CreateAHtmlFile(const astl_Destination: TStrings;
  const as_BeginingFile,
  as_Describe, as_file, as_Title, as_LittleTitle, as_LongTitle: string;
  const as_Subdir: string = '';
  const as_ExtFile: string =
  CST_EXTENSION_HTML;
  const as_BeforeHTML: string = ''; const astl_Body : TStrings = nil );
var ls_title : String;
begin
  if not assigned ( gstl_HeadKeyWords ) Then
    Abort;       // can quit while creating
  if as_LittleTitle = ''
   Then ls_title := as_Title
   else ls_title := as_Title+' - ' +as_LittleTitle;
  p_CreateHTMLFile(nil, astl_Destination, nil, '',
     as_Describe,
     gstl_HeadKeyWords.Text, ls_Title,
    as_LongTitle, as_BeginingFile + '1' + as_ExtFile, as_BeginingFile + '2' +
    as_ExtFile, as_BeginingFile + '3' + as_ExtFile, as_BeginingFile +
    '4' + as_ExtFile, as_Subdir, as_BeforeHTML, gs_Web_Language, astl_Body, False );
end;

// procedure TF_WebBooks.DoAfterInit
// initing components and ini
procedure TF_WebBooks.DoAfterInit( const ab_Ini : Boolean = True );
begin
  {$IFNDEF FPC}
  de_indexdir.InitialDir:=GetWindir(CSIDL_DESKTOPDIRECTORY);
  {$ENDIF}

  // Reading ini
  if not ab_Ini Then
    Exit;
  f_GetMainMemIniFile(nil,nil,nil,False,CST_WebBooks);
  OnFormInfoIni.p_ExecuteLecture(Self);
end;

// procedure TF_WebBooks.FormCreate
// initializing software and form
constructor TF_WebBooks.Create(aowner:TComponent);
var ls_Path : String ;
Begin
  inherited;
  gs_Root:=ExtractFileDir(Application.ExeName)+DirectorySeparator;
  AppendStr(gs_Root,CST_WebBooks+DirectorySeparator);//pas dans plugins pour l'exe

  ls_Path:=GetAppConfigDir(False) + DirectorySeparator + CST_SUBDIR_THEMES;
  try
    cb_Themes.Items.Clear;
    fb_FindFiles(cb_Themes.Items, gs_Root + CST_SUBDIR_THEMES, False);
    if not DirectoryExistsUTF8(ls_Path)
     Then
      fb_CreateDirectoryStructure(ls_Path);
    fb_FindFiles(cb_Themes.Items, ls_Path, False);

  except

  end;

  try
    cb_Files.Items.Clear;
    fb_FindFiles(cb_Files.Items, gs_Root + CST_SUBDIR_FILES, False);
  except

  end;

  // ici mettre la taille initiale car avec les skins, les fenetres se resize
  Width := 640;
  Height := 400;
  Caption := fs_getCorrectString(CST_WebBooks_WithLicense+' : '+gs_Web_FORM_CAPTION);
  OnFormInfoIni.p_ExecuteLecture(Self);
end;

procedure TF_WebBooks.bt_seeClick(Sender: TObject);
begin
  p_OpenFileOrDirectory(de_websitedir.Directory);
end;

procedure TF_WebBooks.ch_EraseOrigin1Click(Sender: TObject);
begin
  if MyMessageDlg(gs_DeleteIndexOnly+de_websitedir.Directory,mmtConfirmation,mmbYesNo,Self)=ID_YES Then
   Begin
    p_Unindex(de_websitedir.Directory,nil,True,ed_IndexName.Text,CST_EXTENSION_HTML);
    p_Unindex(de_websitedir.Directory,nil,True,ed_ExtMobile.Text+ed_IndexName.Text,CST_EXTENSION_HTML);
    p_UnindexPictures (de_websitedir.Directory,[CST_EXTENSION_PDF,CST_EXTENSION_EPUB],CST_EXTENSION_JPG);
    p_UnindexPictures (de_websitedir.Directory,[CST_EXTENSION_SVG],CST_EXTENSION_PNG);
   end;
end;

procedure TF_WebBooks.de_websitedirChange(Sender: TObject);
begin
  (TExtColumn(GridFlags.Columns[2])).BaseLinks:=de_websitedir.Directory;
end;

procedure TF_WebBooks.ed_LanguageChange(Sender: TObject);
begin
  gs_Lang:=ed_Language.Text;
end;


// procedure TF_WebBooks.fne_ExportAcceptFileName
// Exporting ini on filename's accept
procedure TF_WebBooks.fne_ExportAcceptFileName(Sender: TObject;
  var Value: String);
begin
  bt_exportClick(bt_export);
end;


procedure TF_WebBooks.p_AddFiles ( const as_Source, as_dest, as_subdirForward, as_ExtMobile : String ;
                                    const astl_files : TStringList;
                                    const ai_eraseBegin, ai_Level : Integer;
                                    const ab_Root : Boolean ;
                                    var  as_BackDirText : String ;
                                    var  at_SheetsLinks : TAHTMLULTabSheet);
var li_EndExt : Integer ;
    ls_FileSource ,
    ls_FileDest ,
    ls_FileName ,
    ls_FileNameLower   : String;
    lsr_AttrSource     : Tsearchrec;
    ls_BackDirText:String;
    lstl_temp2, lstl_Files2 : TStringList ;

    procedure p_addDownload ( const as_BookFile, as_ext : String );
    var ls_FileName : String;
    Begin
      if not FileExistsUTF8(as_dest+as_BookFile) Then
        CopyFileUTF8(as_Source+as_BookFile,as_dest+as_BookFile);
      p_AddTabSheet(at_SheetsLinks,fs_ReplaceChar( fs_FormatText(copy(as_BookFile,1,Length(as_BookFile)-Length(as_ext)),mftFirstCharOfWordsIsMaj),
                                                    '_',' '),as_BookFile,gs_WebBooks_Sources);
    end;


    procedure p_AddFile ( const ab_add : Boolean; const as_Ext : String );
    var ls_FileWithoutExt      ,
        ls_FileNameWithoutExt  : String;
        li_pos : Integer;


    procedure p_AddExt ( as_ext : String; const as_BookFile : String );
    var ls_Dest64:String;
    Begin

      if ch_Names64.Checked
        Then ls_Dest64 := copy ( ls_FileNameWithoutExt, 1, 60 )
        Else ls_Dest64 := ls_FileNameWithoutExt;
    {  if fb_FileExistsExtVar(ls_FileWithoutExt,as_ext)
       Then p_ReplaceLanguageString(astl_temp1,as_BookFile,StringReplace(ls_DirHtml+ls_Dest64 +as_ext,'"','\"',[rfReplaceAll]),[rfReplaceAll])
       Else p_ReplaceLanguageString(astl_temp1,as_BookFile,'',[rfReplaceAll]);   }
    end;

    function fs_MiniPath ( const as_path : String ) : String;
    Begin
      if ai_eraseBegin>length ( as_path )-5
       Then Result:=CST_HTML_PARENT_DIRECTORY+ExtractFileName(as_path)
       Else Result := copy ( as_path, ai_eraseBegin, length ( as_path ) - ai_eraseBegin + 1 );
    end;

    begin
      if not ab_add
       Then
         Exit;
      p_addKeyWord(StringReplace(fs_ReplaceChar(fs_ReplaceChar(fs_ReplaceChar(fs_ReplaceChar(ls_FileNameWithoutExt,',',' '),':',' '),'_',' '),'-',' '),'   ',' ',[rfReplaceAll]));
      li_pos := PosEx ( as_Ext, ls_FileNameLower, Length(ls_FileName)-Length(as_ext)-1 );
      if  ( li_pos > 0 )
      and ( PosEx ( CST_CONVERTED, ls_FileNameWithoutExt,  Length(ls_FileNameWithoutExt) -11) = 0 )
      and (( pos ( as_Source+ls_FileName, astl_files.Text ) = 0 ) or (FileAgeUTF8(ls_FileName)<>FileAgeUTF8(ls_FileDest)))
       then
         Begin
           //get the file without extension to filter with extension
           ls_FileWithoutExt := copy ( ls_FileDest, 1, PosEx ( '.', ls_FileDest, length ( ls_FileDest ) - 5 ) - 1 );
           ls_FileNameWithoutExt:=ExtractFileName(ls_FileWithoutExt);
           astl_files.Add(as_Source+ls_FileName);
         end;

    end;

   var lstl_DownloadInTextFile : TStringList;
       lt_SheetsLinks : TAHTMLULTabSheet;
begin
  p_CreateKeyWords;
  lstl_temp2 := TStringList.Create;
  if ch_Slides.Checked Then
   lstl_DownloadInTextFile := TStringList.Create;
  try
   if fb_FindFiles ( lstl_temp2, as_Source, True, True, True, '*' ) Then
    Begin
     lstl_temp2.Sort;
     while lstl_temp2.count > 0 do
      Begin
        ls_FileSource := lstl_temp2.Strings [ 0 ];
        FindFirstUTF8( ls_FileSource,faanyfile,lsr_AttrSource);
        ls_FileName := lsr_AttrSource.Name ;
        ls_FileDest := as_dest+ls_FileName;
        FindCloseUTF8(lsr_AttrSource);
        if DirectoryExistsUTF8 ( ls_FileSource ) Then
          Begin
            if not DirectoryExistsUTF8 ( ls_FileDest ) Then
              CreateDirUTF8(ls_FileDest);
            p_addKeyWord(ls_FileName);
            p_AddTabSheet(at_SheetsLinks, fs_FormatText(fs_ReplaceChar(ls_FileName,'_',' '),mftFirstCharOfWordsIsMaj),
                                          ls_FileName+CST_HTML_DIR_SEPARATOR+as_ExtMobile+ed_IndexName.Text+CST_EXTENSION_HTML,gs_WebBooks_More);
            ls_BackDirText:=as_BackDirText+CST_HTML_PARENT_DIRECTORY;
        //    if ls_FileName='Bach'
           //  then ShowMessage(ls_BackDirText+' '+as_BackDirText);

            lstl_Files2 := TStringList.Create;
            try
              if  ch_RecurseSubDirs.Checked Then
               Begin
                Finalize(lt_SheetsLinks);
                p_AddFiles ( ls_FileSource+DirectorySeparator, ls_FileDest +  DirectorySeparator, as_subdirForward+CST_HTML_PARENT_DIRECTORY, as_ExtMobile, lstl_Files2, ai_eraseBegin, ai_Level + 1, False, ls_BackDirText, lt_SheetsLinks );
                p_genHtmlHome ( ls_FileSource+DirectorySeparator, ls_FileDest +  DirectorySeparator, as_subdirForward+CST_HTML_PARENT_DIRECTORY, ls_FileName, ls_BackDirText, as_ExtMobile, lstl_Files2, False, lt_SheetsLinks );
               end;

            finally
              lstl_Files2.Destroy;
            end;
            if  ab_Root
            and ( ai_Level = 1 )
             Then
              p_IncProgress (pb_Progress);
          End
        Else
          if FileExistsUTF8 ( ls_FileSource ) Then
            Begin
               ls_FileNameLower := LowerCase(ls_FileName);
               p_addFile( ch_EPUB .Checked, CST_EXTENSION_EPUB );
               p_addFile( ch_TXT  .Checked, CST_EXTENSION_TXT );
               p_addFile( ch_SLA  .Checked, CST_EXTENSION_SLA );
               p_addFile( ch_OD   .Checked, CST_EXTENSION_ODT );
               p_addFile( ch_RTF  .Checked, CST_EXTENSION_RTF );
               p_addFile( ch_DOC  .Checked, CST_EXTENSION_DOC );
               p_addFile( ch_DOCX .Checked, CST_EXTENSION_DOCX );
               p_addFile( ch_PDF  .Checked, CST_EXTENSION_PDF );
              if  ( ls_FileName  <> ed_IndexName.Text+CST_EXTENSION_HTML)
              and ( ls_FileName  <> ed_ExtMobile.Text+ed_IndexName.Text+CST_EXTENSION_HTML)
              and ( pos ( CST_EXTENSION_SOZI, ls_FileNameLower ) < Length(ls_FileName)-10)  Then
                p_addFile( ch_HTM  .Checked, CST_EXTENSION_HTML );

               if ch_Slides.Checked  Then
                Begin
                 p_addFile( ch_Sozi .Checked, CST_EXTENSION_SOZI );
                 p_addFile( ch_PPS  .Checked, CST_EXTENSION_PPS  );
                 p_addFile( ch_PPS  .Checked, CST_EXTENSION_PPT  );
                 p_addFile( ch_OD   .Checked, CST_EXTENSION_ODP  ) ;
                end;

               li_EndExt := Length(ls_FileName)-5;

{              if (pos ( CST_EXTENSION_TXT+CST_EXTENSION_JS  , ls_FileNameLower ) >= li_EndExt-3)
              and (pos ( ed_TXTResume.Text+'.', ls_FileNameLower ) = 1 ) Then
                p_addOldText ( ls_FileSource );}
             if ch_ZIPLiv.Checked
             and (pos ( CST_EXTENSION_ZIP, ls_FileNameLower ) >= li_EndExt) Then
               p_addDownload ( ls_FileName, CST_EXTENSION_ZIP);
             if ch_TorrentLiv.Checked
             and (pos ( CST_EXTENSION_TORRENT, ls_FileNameLower ) > 1) Then
               p_addDownload ( ls_FileName, CST_EXTENSION_TORRENT);
             if ch_7ZIPLiv.Checked Then
               Begin
                if (PosEx ( CST_EXTENSION_TAR7Z, ls_FileNameLower, li_EndExt-4) > 0 ) Then
                  p_addDownload ( ls_FileName, CST_EXTENSION_TAR7Z)
                else if (pos ( CST_EXTENSION_7Z, ls_FileNameLower ) > li_EndExt) Then
                 p_addDownload ( ls_FileName, CST_EXTENSION_7Z);
               end;
             if ch_GZLiv.Checked Then
             Begin
              if (PosEx ( CST_EXTENSION_TARGZ, ls_FileNameLower, li_EndExt-4 ) > 0) Then
                p_addDownload ( ls_FileName, CST_EXTENSION_TARGZ)
              else if (pos ( CST_EXTENSION_GZ, ls_FileNameLower ) > li_EndExt) Then
               p_addDownload ( ls_FileName, CST_EXTENSION_GZ);
             end;
            End;
        lstl_temp2.Delete(0);
      End ;
    end;
  finally
    if ch_Slides.Checked Then
      lstl_DownloadInTextFile.Destroy;
    lstl_temp2.Destroy;
  end;
End ;


procedure TF_WebBooks.fne_importChange(Sender: TObject);
var as_text : String;
Begin
  as_text := fne_import.{$IFDEF FPC}Filename{$ELSE}Text{$ENDIF};
  p_importAcceptFileName ( Self, CST_WebBooks, as_text, OnFormInfoIni);
End;

procedure TF_WebBooks.FormShow(Sender: TObject);
begin
  ed_LanguageChange(self);
end;

// procedure TF_WebBooks.fne_importAcceptFileName
// Importing ini on filename's accept
procedure TF_WebBooks.fne_importAcceptFileName(Sender: TObject;
  var Value: String);
var ls_FileImport : String;
begin
  ls_FileImport := {$IFDEF FPC}Value{$ELSE}fne_import.Text{$ENDIF};
  p_importAcceptFileName(Self,CST_WebBooks, ls_FileImport, OnFormInfoIni);
end;

procedure TF_WebBooks.p_Unfat(const as_directory : String);
var lstl_FilesToVerify : TStringList;
  ls_source64,ls_ext:String;
begin
  lstl_FilesToVerify := TStringList.Create;
  try
  finally
    lstl_FilesToVerify.Destroy;
  end;
end;

// procedure TF_WebBooks.bt_exportClick
// Export ini click event
procedure TF_WebBooks.bt_exportClick(Sender: TObject);
begin
  f_GetMainMemIniFile(nil,nil,nil,False,CST_WebBooks);
  p_exportClick(Self,fne_export.FileName,OnFormInfoIni);
end;


procedure TF_WebBooks.p_comment(const as_Comment: String);
begin
  p_Setcomments(lb_Comments,as_Comment,gs_Web_Generating );
end;



{$IFNDEF FPC}
initialization
  p_ConcatVersion ( gVer_WebBooks );
{$ENDIF}


end.

