{
   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., 675 Mass Ave, Cambridge, MA 02139, USA.
}
unit Ufrmwork_tif;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Ufrmworkbase, StdCtrls, Spin, FreeBitmap, FreeImage, FreeUtils,
  UBrowserListView;

type
  TWorkThread = class;

  Tfrmwork_tif = class(Tfrmworkbase)
    GroupBox1: TGroupBox;
    Label11: TLabel;
    Label12: TLabel;
    Label14: TLabel;
    Label13: TLabel;
    CheckBox1: TCheckBox;
    SpinEdit1: TSpinEdit;
    SpinEdit2: TSpinEdit;
    TypeCombo: TComboBox;
    Button1: TButton;
    CheckBox2: TCheckBox;
    CheckBox3: TCheckBox;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
    WorkThread:TWorkThread;

    procedure OkSeleted; override;
    function CancelSeleted:boolean; override;
    procedure WorkThreadOnTerminate(sender:tobject);
  public
    { Public declarations }
  end;

  TWorkThread = class(TThread)
  private
    mbitmap:TFreeMultiBitmap;
    currentcount:integer;

    procedure savefile(data:PThumbImage);
  protected
    procedure Execute; override;
  public
    formhandle:thandle;
    list:tlist;
    destfilename:string;
    resize:boolean;
    resize_width,resize_height:integer;
    resize_method:integer;
    convert24bit,removetrans:boolean;

    constructor CreateThread;
    destructor Destroy; override;
  end;

var
  frmwork_tif: Tfrmwork_tif;

implementation
uses Uconfig, Ufrmmain, Udialog, Ufrmsaveopt;
{$R *.dfm}

{TWorkThread}
constructor TWorkThread.CreateThread;
begin
  FreeOnTerminate:=false;
  currentcount:=0;
  inherited Create(true);
end;

destructor TWorkThread.Destroy;
begin
  inherited Destroy;
end;

procedure TWorkThread.Execute;
var
  i:integer;
  PThumbImage1:PThumbImage;
  s:string;
begin
mbitmap:=TFreeMultiBitmap.Create();
try
 try
    s:='파일들을 합치고 있습니다...';
    sendmessage(formhandle, wm_user+1003, integer(pchar(s)), 0);

    mbitmap.Open(destfilename,true,false);
     for i:=0 to list.Count-1 do begin
       if self.Terminated then break;
       PThumbImage1:=PThumbImage(list.Items[i]);
       inc(currentcount);
       savefile(PThumbImage1);
     end;

    s:='저장하고 있습니다...';
    sendmessage(formhandle, wm_user+1003, integer(pchar(s)), 0);
    if mbitmap.Close(selectsaveflag) then
      s:=format('%s 저장했습니다.',[ExtractFileName(destfilename)])
    else
      s:=format('%s 저장에 실패했습니다.',[ExtractFileName(destfilename)]);
    sendmessage(formhandle, wm_user+1003, integer(pchar(s)), 0);
  except
    on E: Exception do
      sendmessage(formhandle, wm_user+1003, integer(pchar(E.Message)), 0);
  end;

  s:='완료되었습니다.';
  sendmessage(formhandle, wm_user+1003, integer(pchar(s)), 0);
finally
  mbitmap.Free;
end;
end;

procedure TWorkThread.savefile(data:PThumbImage);
var
  FBitmap:TFreeWinBitmap;
  w,h,NewWidth,NewHeight:integer;
  s:string;
begin
  sendmessage(formhandle, wm_user+1001, list.Count, currentcount);
  s:=format('%d/%d (%s)',[currentcount,list.Count,ExtractFileName(data.name)]);
  sendmessage(formhandle, wm_user+1002, integer(pchar(s)), 0);

  FBitmap:=TFreeWinBitmap.Create;
  try
    if FBitmap.Load(data.name)=false then begin
      s:=format('%s 파일을 읽을수 없습니다.',[ExtractFileName(data.name)]);
      sendmessage(formhandle, wm_user+1003, integer(pchar(s)), 0);
      exit;
    end;

    if resize then begin
      w:=FBitmap.GetWidth;
      h:=FBitmap.GetHeight;
      if (resize_width>0) and (resize_height=0) then begin
        NewWidth:=resize_width;
        NewHeight:=Round(NewWidth * h / w);
      end else if (resize_width=0) and (resize_height>0) then begin
        NewHeight:=resize_height;
        NewWidth:=Round(NewHeight * w / h);
      end else if (resize_width>0) and (resize_height>0) then begin
        NewHeight:=resize_height;
        NewWidth:=resize_width;
      end else begin
        NewHeight:=h;
        NewWidth:=w;
      end;
      FBitmap.Rescale(NewWidth,NewHeight,TFreeStretchFilter(self.resize_method));
    end;

    if comparetext(ExtractFileExt(data.name),'.gif')=0 then begin
      if FBitmap.IsTransparent then
        FBitmap.SetTransparentBg(nil);
      FBitmap.ConvertTo24Bits;
      FBitmap.ColorQuantize(FIQ_WUQUANT);
    end else begin
      if removetrans and FBitmap.IsTransparent then
        FBitmap.SetTransparentBg(nil);
      if convert24bit and (FBitmap.GetBitsPerPixel>24) then
        FBitmap.ConvertTo24Bits;
    end;

    mbitmap.AppendPage(FBitmap);
  finally
    FBitmap.Free;
  end;
end;

{Tfrmwork_tif}
procedure Tfrmwork_tif.FormCreate(Sender: TObject);
begin
  inherited;
  self.TypeCombo.ItemIndex:=config.c_resize_method;
  CheckBox2.Checked:=boolean(config.getvaluebyinteger('config_saveas_convert24bit',0));
  CheckBox3.Checked:=boolean(config.getvaluebyinteger('config_saveas_removetrans',0));
  btnok.Caption:='저장';
end;

procedure Tfrmwork_tif.OkSeleted;
var
  s,path:string;
  i,count:integer;
  PThumbImage1:PThumbImage;
label reopendialog;
begin
  if lastfilename<>'' then
    s:=lastfilename
  else
    s:=PThumbImage(list.items[0]).name;
  SaveDialog1.Filter:='tif 파일(*.tif;*.tiff)|*.tif;*.tiff|모든파일|*.*';
  SaveDialog1.FilterIndex:=1;
  if config.c_uselastdir then
    SaveDialog1.InitialDir:=config.lastdir
  else
    SaveDialog1.InitialDir:=ExtractFilePath(s);
  SaveDialog1.FileName:=ChangeFileExt(ExtractFileName(s),'');
  SaveDialog1.enablesaveopt:=true;

reopendialog:
  if SaveDialog1.Execute=false then exit;

  if pos(lowercase('*'+ExtractFileExt(SaveDialog1.FileName)+';'),
       '*.tif;*.tiff;')=0 then
    s:=sysutils.ChangeFileExt(SaveDialog1.FileName,'.tif')
  else
    s:=SaveDialog1.FileName;
  config.lastdir:=sysutils.ExtractFilePath(s);

    if sysutils.FileExists(s) then begin
      if MessageDlg(format('"%s" 파일이 이미 존재합니다.',[ExtractFileName(s)])+#13#10+'덮어 씌우시겠습니까?',
           mtConfirmation, [mbYes, mbNo], 0)<>mrYes then
       goto reopendialog;
    end;

  lastfilename:=s;

  existnoanswer:=false;
  btnok.Enabled:=false;
  self.btncancel.Caption:='취소';

  selectsaveflag:=get_reg_saveopt_flag(FIU_GetFIFType2('.tif'),false);

  WorkThread:=TWorkThread.CreateThread;
  WorkThread.formhandle:=handle;
  WorkThread.list:=list;
  WorkThread.destfilename:=s;

  WorkThread.resize:=self.CheckBox1.Checked;
  WorkThread.resize_width:=self.SpinEdit1.Value;
  WorkThread.resize_height:=self.SpinEdit2.Value;
  WorkThread.resize_method:=self.TypeCombo.ItemIndex;
  WorkThread.convert24bit:=CheckBox2.Checked;
  WorkThread.removetrans:=CheckBox3.Checked;

  WorkThread.OnTerminate:=WorkThreadOnTerminate;
  WorkThread.Resume;
end;

procedure Tfrmwork_tif.WorkThreadOnTerminate(sender:tobject);
begin
  WorkThread:=nil;
  self.btncancel.Caption:='닫기';
  btnok.Enabled:=true;
  btncancel.SetFocus;
end;

function Tfrmwork_tif.CancelSeleted:boolean;
begin
  result:=true;
  if WorkThread=nil then exit;
  result:=false;
  WorkThread.Terminate;
  WorkThread.WaitFor;
  WorkThread.Free;
end;

procedure Tfrmwork_tif.FormDestroy(Sender: TObject);
begin
  config.c_resize_method:=self.TypeCombo.ItemIndex;
  config.setvaluebyinteger('config_saveas_convert24bit',integer(CheckBox2.Checked));
  config.setvaluebyinteger('config_saveas_removetrans',integer(CheckBox3.Checked));
  inherited;
end;

procedure Tfrmwork_tif.Button1Click(Sender: TObject);
begin
  frmsaveopt:=Tfrmsaveopt.Create(self);
  try
    frmsaveopt.selectformat:=FIU_GetFIFType2('.tif');
    if frmsaveopt.ShowModal=mrok then ;
  finally
    frmsaveopt.Free;
  end;
end;

end.
