{
   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 Ufrmmain;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ComCtrls, ToolWin, GR32_Image, jpeg, gr32, StdCtrls, ExtCtrls,
  OleCtrls, GR32_Transforms, TB2Item, TB2Dock, TB2Toolbar, GR32_Layers,
  ImgList, ALHintBalloon, httpsend2, FreeBitmap, FreeImage, activex,
  comobj, comserv, shellapi, Menus, VistaAltFixUnit, im_Clipboard,
  ExtDlgs;

const
  thisregname = 'nSeries\nView\Mosaic';

type
  Tfrmmain = class(TForm)
    PageControl1: TPageControl;
    TabSheet1: TTabSheet;
    TabSheet2: TTabSheet;
    image1: TImgView32;
    image2: TImgView32;
    TBToolbar1: TTBToolbar;
    TBItem1: TTBItem;
    Panel1: TPanel;
    ProgressBar1: TProgressBar;
    Label1: TLabel;
    TBItem2: TTBItem;
    TBItem3: TTBItem;
    TBItem4: TTBItem;
    TBItem5: TTBItem;
    TBSeparatorItem1: TTBSeparatorItem;
    TBItem6: TTBItem;
    TBItem7: TTBItem;
    TBSeparatorItem2: TTBSeparatorItem;
    TBItem8: TTBItem;
    TBItem9: TTBItem;
    ImageList1: TImageList;
    Hint: TALHintBalloonControl;
    TBItem10: TTBItem;
    TabSheet3: TTabSheet;
    Memo1: TMemo;
    Button1: TButton;
    TabSheet4: TTabSheet;
    TBItem12: TTBItem;
    TBItem13: TTBItem;
    TBSeparatorItem3: TTBSeparatorItem;
    StatusBar1: TStatusBar;
    PopupMenu1: TPopupMenu;
    N1: TMenuItem;
    TBSeparatorItem4: TTBSeparatorItem;
    PopupMenu2: TPopupMenu;
    N2: TMenuItem;
    TabSheet5: TTabSheet;
    image3: TImgView32;
    N3: TMenuItem;
    Button2: TButton;
    PopupMenu3: TPopupMenu;
    N4: TMenuItem;
    N5: TMenuItem;
    N6: TMenuItem;
    N7: TMenuItem;
    ProgressBar2: TProgressBar;
    TBItem14: TTBItem;
    TBItem15: TTBItem;
    TBSubmenuItem7: TTBSubmenuItem;
    TBItem25: TTBItem;
    TBItem26: TTBItem;
    TBSeparatorItem5: TTBSeparatorItem;
    TBItem29: TTBItem;
    procedure FormCreate(Sender: TObject);
    procedure TBItem1Click(Sender: TObject);
    procedure TBItem2Click(Sender: TObject);
    procedure TBItem3Click(Sender: TObject);
    procedure TBItem4Click(Sender: TObject);
    procedure TBItem5Click(Sender: TObject);
    procedure TBItem6Click(Sender: TObject);
    procedure image1MouseWheelDown(Sender: TObject; Shift: TShiftState;
      MousePos: TPoint; var Handled: Boolean);
    procedure image1MouseWheelUp(Sender: TObject; Shift: TShiftState;
      MousePos: TPoint; var Handled: Boolean);
    procedure image1MouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
    procedure image1MouseLeave(Sender: TObject);
    procedure image1MouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer; Layer: TCustomLayer);
    procedure image1MouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
    procedure TBItem7Click(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure TBItem8Click(Sender: TObject);
    procedure TBItem9Click(Sender: TObject);
    procedure Panel1Resize(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure TBItem10Click(Sender: TObject);
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
    procedure wb1ProgressChange(Sender: TObject; Progress,
      ProgressMax: Integer);
    procedure wb1CommandStateChange(Sender: TObject; Command: Integer;
      Enable: WordBool);
    procedure TBItem13Click(Sender: TObject);
    procedure TBItem12Click(Sender: TObject);
    procedure PageControl1Change(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure N3Click(Sender: TObject);
    procedure PopupMenu1Popup(Sender: TObject);
    procedure PopupMenu3Popup(Sender: TObject);
    procedure N7Click(Sender: TObject);
    procedure PopupMenu2Popup(Sender: TObject);
    procedure wb1DocumentComplete(Sender: TObject; const pDisp: IDispatch;
      var URL: OleVariant);
    procedure TBItem14Click(Sender: TObject);
    procedure TBItem15Click(Sender: TObject);
    procedure TBItem25Click(Sender: TObject);
    procedure TBItem29Click(Sender: TObject);
  private
    { Private declarations }
    OldMousePos: TPoint;
    MouseDragging: Boolean;
    xorg,yorg,xmov,ymov:integer;
    SysImgList:TImageList;
    worktime:cardinal;

    procedure WndProc(var Message: TMessage); override;
    function get_activeimageview32:TImgView32;
    procedure mosaicworkOnTerminate(Sender: TObject);
    procedure start_loadimage(convertmosaic:boolean);
    procedure loadimageOnTerminate(Sender: TObject);
    procedure setwatermark(Bitmap:TBitmap32);
    procedure setconfig();
    procedure loadcacheimage(dir:string);
  public
    { Public declarations }
    procedure stop_loadimage;
  end;

var
  frmmain: Tfrmmain;

implementation
uses Umainhelper, Ufunction, Umain_hlp, Uconfig, Ufrmoption,
 Ufrmfolder, Ufrmwait, Uipicture, Ufrmresize, Ufrmfetch, Ufrmfragsize, Uupdate, Udialog, Ufrmwebviewer,
  Ufrmabout;

{$R *.dfm}

procedure Tfrmmain.WndProc(var Message: TMessage);
var
  pt:tpoint;
  bitmap:tbitmap32;
begin
  with Message do
    case Msg of
      wm_progress:begin
        ProgressBar1.Max:=wparam;
        ProgressBar1.Position:=lparam;
        label1.Caption:=format('%d/%d',[lparam,wparam]);
      end;
      wm_mosaic_proc1:begin
        PageControl1.ActivePageIndex:=0;
        PageControl1Change(nil);
        image2.Bitmap.Width:=wparam;
        image2.Bitmap.Height:=lparam;
        image2.Bitmap.Clear(clwhite32);
        Hint.ShowTextHintBalloon(bmtInfo, '알림', '현재 이미지 탭을 "원본이미지" 하면 속도가 더욱 빨라집니다. 화면을 그리는데 많은 시간이 소비됩니다.',
          400, 50, 50, ProgressBar1, bapbottomleft);
      end;
      wm_mosaic_proc2:begin
        pt:=ppoint(wparam)^;
        bitmap:=tbitmap32(lparam);
        image2.Bitmap.Draw(pt.X,pt.Y,bitmap);
      end;
      wm_mosaic_proc3:begin

      end;

    end;
  inherited;
end;

procedure Tfrmmain.FormCreate(Sender: TObject);
var
  i:integer;
  sfi:TSHFileInfo;
begin
  updatefilecheck();
  TVistaAltFix.Create(Self);

  ForceDirectories(GetAppDirectory);
  randomize;
  SysImgList:=TImageList.Create(self);
  SysImgList.ShareImages:=true;
  SysImgList.DrawingStyle:=dsTransparent;
  SysImgList.Handle:=ShGetFileInfo('', 0, sfi, sizeOf(sfi),
    SHGFI_SYSICONINDEX or SHGFI_SMALLICON);

  config.LoadFromFile(GetAppDirectory+'config.ini');
  self.Caption:=format('%s (%s)',[app_title,getversion(paramstr(0))]);

  self.PageControl1.Align:=alclient;
  PageControl1.ActivePageIndex:=0;
  PageControl1Change(nil);
  {$ifdef release}
  TabSheet3.TabVisible:=false;
  TabSheet4.TabVisible:=false;
  {$endif}

  setconfig();
end;
                
procedure Tfrmmain.FormDestroy(Sender: TObject);
begin
  config.SaveToFile(GetAppDirectory+'config.ini');
  SysImgList.Free;                                             

  checkupdate();
end;

procedure Tfrmmain.TBItem1Click(Sender: TObject);
var
  OpenPictureDialog1:TmyOpenPictureDialog;
begin
OpenPictureDialog1:=TmyOpenPictureDialog.Create(self);
try
  OpenPictureDialog1.Filter:='jpg 파일|*.jpg';
  OpenPictureDialog1.ExtraCheckbox.Checked:=config.c_dialog_preview;
  if config.c_lastdir='' then
    config.c_lastdir:=GetAppDirectory+'sample';
  OpenPictureDialog1.InitialDir:=config.c_lastdir;
  if OpenPictureDialog1.Execute=false then exit;
  config.c_lastdir:=sysutils.ExtractFilePath(OpenPictureDialog1.FileName);
  image1.Bitmap.LoadFromFile(OpenPictureDialog1.FileName);
  PageControl1.ActivePageIndex:=0;
  PageControl1Change(nil);
finally
  config.c_dialog_preview:=OpenPictureDialog1.ExtraCheckbox.Checked;
  OpenPictureDialog1.Free;
end;
end;

function Tfrmmain.get_activeimageview32:TImgView32;
var
  i:integer;
begin
  result:=nil;
  for i:=0 to PageControl1.ActivePage.ControlCount-1 do begin
    if PageControl1.ActivePage.Controls[i] is TImgView32 then begin
      result:=TImgView32(PageControl1.ActivePage.Controls[i]);
      break;
    end;
  end;
end;

procedure Tfrmmain.TBItem2Click(Sender: TObject);
var
  imgv:TImgView32;
begin
  imgv:=get_activeimageview32;
  if imgv.Bitmap.Empty then exit;
  imgv.Scale:=imgv.Scale*0.6;
  if imgv.Scale<0.1 then
    imgv.Scale:=0.1;
  PageControl1Change(nil);
end;

procedure Tfrmmain.TBItem3Click(Sender: TObject);
var
  imgv:TImgView32;
begin
  imgv:=get_activeimageview32;
  if imgv.Bitmap.Empty then exit;
  imgv.Scale:=imgv.Scale*1.2;
  if imgv.Scale>10 then
    imgv.Scale:=10;
  PageControl1Change(nil);
end;

procedure Tfrmmain.TBItem4Click(Sender: TObject);
begin
  get_activeimageview32.Scale:=1;
  PageControl1Change(nil);
end;

procedure Tfrmmain.TBItem5Click(Sender: TObject);
function RoundA(val:single) : Integer;
begin
   if val > 0 then result := Trunc(val + 0.5)
   else result := Trunc(val - 0.5)
end;
var
  fsize:integer;
begin
  if image1.Bitmap.Empty then begin
    MessageDlg('먼저 원하시는 이미지,사진을 열어 주세요...', mtInformation, [mbok], 0);
    exit;
  end;
  if (isloadimage=false) or (DirectoryExists(lastloadir)=false) then begin
    MessageDlg('로드한 조각이미지가 없습니다. 지금 선택하세요.', mtInformation, [mbok], 0);
    start_loadimage(true);
    exit;
  end;
  if lastloadir[length(lastloadir)]<>'\' then lastloadir:=lastloadir+'\';

  frmfragsize:=Tfrmfragsize.Create(self);
  try
    frmfragsize.c_mosaicsize.Value:=config.c_mosaicsize;
    fsize:=RoundA(image1.Bitmap.Width / 100);
    if fsize<1 then fsize:=1;
    frmfragsize.SpinEdit1.Value:=fsize;
    if frmfragsize.ShowModal<>mrok then exit;
  finally
    frmfragsize.Free;
  end;

  TBItem5.Enabled:=false;
  TBItem6.Enabled:=true;

  mosaicwork:=Tmosaic.CreateThread;
  mosaicwork.srcbmp.Width:=image1.Bitmap.Width;
  mosaicwork.srcbmp.Height:=image1.Bitmap.Height;
  mosaicwork.srcbmp.Draw(0,0,image1.Bitmap);
  mosaicwork.formhandle:=handle;
  mosaicwork.OnTerminate:=mosaicworkOnTerminate;
  mosaicwork.Resume;
end;

procedure Tfrmmain.mosaicworkOnTerminate(Sender: TObject);
begin
  TBItem5.Enabled:=true;
  TBItem6.Enabled:=false;
  if mosaicwork.errmsg='' then
//    MessageDlg('완료 되었습니다.', mtInformation, [mbok], 0)
  else begin
    if pos('Can''t allocate the DIB handle',mosaicwork.errmsg)>0 then
      MessageDlg(mosaicwork.errmsg+#13#10#13#10+
      '생성할 모자이크 이미지가 너무 큰것 같습니다.'+#13#10+
      '모자이크 분할사이즈를 높이거나 조각이미지 사이즈를 줄여 보시기 바랍니다.',
         mterror, [mbok], 0)
    else
      MessageDlg(mosaicwork.errmsg, mterror, [mbok], 0);
  end;

  self.PageControl1.ActivePageIndex:=1;
  PageControl1Change(nil);
end;

procedure Tfrmmain.TBItem6Click(Sender: TObject);
begin
  if assigned(mosaicwork) then begin
    mosaicwork.Terminate;
    mosaicwork.WaitFor;
    freeandnil(mosaicwork);
  end;
end;

procedure Tfrmmain.loadcacheimage(dir:string);
var
  i,k:integer;
  data:Pimagedata;
  strlist,strlist2:tstringlist;
  s,s1,s2:string;
begin
  clear_imagelist;
  strlist:=tstringlist.Create;
  strlist2:=tstringlist.Create;
  strlist.LoadFromFile(dir+'\color.ini');
  for i:=0 to strlist.Count-1 do begin
    s:=strlist.Strings[i];
    strlist2.Clear;
    SplitString(s,strlist2,#9);
    if strlist2.Count<>2 then continue;
    s1:=strlist2.Strings[0];
    s2:=strlist2.Strings[1];
    strlist2.Clear;
    SplitString(s2,strlist2,',');
    if strlist2.Count<>3 then continue;
    new(data);
    data.name:=s1;
    data.bitmap:=nil;
    data.usecount:=0;
    data.r:=strtointdef(strlist2.Strings[0],0);
    data.g:=strtointdef(strlist2.Strings[1],0);
    data.b:=strtointdef(strlist2.Strings[2],0);
    imagelist.Add(data);
  end;
  isloadimage:=true;
  strlist.Free;
  strlist2.Free;
end;

procedure Tfrmmain.start_loadimage(convertmosaic:boolean);
var
  s,s1:string;
  data:Pfolderrec;
begin
  frmfolder:=Tfrmfolder.Create(self);
  try
    s:=GetAppDirectory+'mosaic_images';
    sysutils.ForceDirectories(s);
    frmfolder.fragfolder:=s;
    frmfolder.Caption:='조각이미지 데이터를 선택하세요.';
    frmfolder.TreeView1.Images:=self.SysImgList;
    if frmfolder.ShowModal<>mrok then exit;
    lastloadir:='';
    if frmfolder.TreeView1.Selected=nil then begin
      MessageDlg('선택된 것이 없습니다.', mtError, [mbok], 0);
      exit;
    end;
    data:=Pfolderrec(frmfolder.TreeView1.Selected.Data);
    s1:=Pfolderrec(frmfolder.TreeView1.Selected.Data).path;
    if data.iscache then begin
      if MessageDlg('이전 캐쉬된 정보에서 읽으시겠습니까?'
        +#13#10#13#10+'(이전 캐쉬후 이미지가 변경되었다면 새롭게 읽어야합니다.)', mtConfirmation, [mbYes, mbNo], 0)=mryes then begin
        loadcacheimage(s1);
        ProgressBar1.Max:=imagelist.Count;
        ProgressBar1.Position:=imagelist.Count;
        lastloadir:=s1;
        MessageDlg('모두 읽었습니다.', mtinformation, [mbok], 0);
        if isloadimage and convertmosaic then
          TBItem5Click(nil);
        exit;
      end;
    end;
  finally
    frmfolder.Free;
  end;

  isloadimage:=false;

  clear_imagelist;
  loadimage:=Tloadimage.CreateThread;
  loadimage.formhandle:=handle;
  loadimage.thumbsize:=config.c_mosaicimgsize;
  loadimage.convertmosaic:=convertmosaic;
  loadimage.selectfolder:=s1;
  loadimage.OnTerminate:=loadimageOnTerminate;
  worktime:=gettickcount;
  loadimage.Resume;
  
  frmwait:=Tfrmwait.Create(self);
  frmwait.ShowModal;
  frmwait.Free;
end;

procedure Tfrmmain.stop_loadimage;
begin
  if assigned(loadimage) then begin
    loadimage.Terminate;
    loadimage.WaitFor;
    freeandnil(loadimage);
  end;
end;

procedure Tfrmmain.loadimageOnTerminate(Sender: TObject);
begin
//  showmessage(inttostr(gettickcount-worktime));
  if assigned(frmwait) then
    frmwait.Close;
  lastloadir:=Tloadimage(Sender).selectfolder;
  if isloadimage and Tloadimage(Sender).convertmosaic then
    TBItem5Click(nil);
end;

procedure Tfrmmain.image1MouseWheelDown(Sender: TObject;
  Shift: TShiftState; MousePos: TPoint; var Handled: Boolean);
var ImgView321:TImgView32;
begin
  ImgView321:=(Sender as TImgView32);
  if (ImgView321.Bitmap.Height*ImgView321.Scale) > ImgView321.ClientHeight then
    ImgView321.Scroll(0,50)
  else
    ImgView321.Scroll(50,0);
end;

procedure Tfrmmain.image1MouseWheelUp(Sender: TObject; Shift: TShiftState;
  MousePos: TPoint; var Handled: Boolean);
var ImgView321:TImgView32;
begin
  ImgView321:=(Sender as TImgView32);
  if (ImgView321.Bitmap.Height*ImgView321.Scale) > ImgView321.ClientHeight then
    ImgView321.Scroll(0,-50)
  else
    ImgView321.Scroll(-50,0);
end;

procedure Tfrmmain.image1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
var ImgView321:TImgView32;
begin
  ImgView321:=(Sender as TImgView32);
  imgview321.SetFocus;
  if Button=mbRight then begin
    exit;
  end;
  OldMousePos := Point(X, Y);
  MouseDragging := True;
  imgview321.Cursor := crSizeAll;
end;

procedure Tfrmmain.image1MouseLeave(Sender: TObject);
var ImgView321:TImgView32;
begin
  ImgView321:=(Sender as TImgView32);
  imgview321.Cursor:=crDefault;
end;

procedure Tfrmmain.image1MouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer; Layer: TCustomLayer);
var ImgView321:TImgView32;
begin
  if MouseDragging then begin
    ImgView321:=(Sender as TImgView32);
    imgview321.Scroll(OldMousePos.X - X, OldMousePos.Y - Y);
    OldMousePos := Point(X, Y);
  end;
end;

procedure Tfrmmain.image1MouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer);
var ImgView321:TImgView32;
begin
  if Button=mbRight then begin
    exit;
  end;
  ImgView321:=(Sender as TImgView32);
  MouseDragging := False;
  imgview321.Cursor := crDefault;
end;

procedure Tfrmmain.TBItem7Click(Sender: TObject);
var
  s:string;
  bmp:tbitmap;
  jpg:tjpegimage;
  image2: TImgView32;
  Bitmap:TBitmap32;
  SavePictureDialog1:TmySavePictureDialog;
begin
{  s:='홈페이지에서 저장할 수 있습니다. 로그인이 필요합니다.'+#13#10;
  s:=s+'지금 홈페이지로 이동합니다.';
  MessageDlg(s, mtInformation, [mbok], 0);
  self.PageControl1.ActivePageIndex:=2;
  wb1.Navigate(home_url);

}
  image2:=get_activeimageview32;
  if image2=nil then exit;

  if image2.Bitmap.Empty then begin
    MessageDlg('저장 할 이미지가 없습니다.', mtError, [mbok], 0);
    exit;
  end;

SavePictureDialog1:=TmySavePictureDialog.Create(self);
try
  SavePictureDialog1.Filter:='jpg 파일|*.jpg';
  SavePictureDialog1.ExtraCheckbox.Checked:=config.c_dialog_preview;
  if SavePictureDialog1.Execute=false then exit;
  bmp:=tbitmap.Create;
  jpg:=tjpegimage.Create;
  screen.Cursor:=crHourGlass;
  try
{    Bitmap:=TBitmap32.Create;
    try
      Bitmap.Assign(image2.Bitmap);
      setwatermark(Bitmap);
      Bitmap.AssignTo(bmp);
    finally
      Bitmap.Free;
    end;}
    image2.Bitmap.AssignTo(bmp);
    jpg.Assign(bmp);
    s:=SavePictureDialog1.FileName;
    s:=sysutils.ChangeFileExt(s,'.jpg');
    jpg.SaveToFile(s);
  finally
    screen.Cursor:=crdefault;
    jpg.Free;
    bmp.Free;
  end;
finally
  config.c_dialog_preview:=SavePictureDialog1.ExtraCheckbox.Checked;
  SavePictureDialog1.Free;
end;
  MessageDlg('저장 되었습니다.', mtInformation, [mbok], 0);
end;

procedure Tfrmmain.setconfig();
begin
  image1.Color:=config.c_backcolor;
  image2.Color:=config.c_backcolor;
  image3.Color:=config.c_backcolor;
end;

procedure Tfrmmain.TBItem8Click(Sender: TObject);
begin
  frmoption:=Tfrmoption.Create(self);
  if frmoption.ShowModal=mrok then
    setconfig();
  frmoption.Free;
end;

procedure Tfrmmain.TBItem9Click(Sender: TObject);
begin
  start_loadimage(false);
end;

procedure Tfrmmain.Panel1Resize(Sender: TObject);
begin
  ProgressBar1.Width:=panel1.Width-(label1.Width+35);
end;

procedure Tfrmmain.Button1Click(Sender: TObject);
var
  http:thttpsend2;
  strlist:tstringlist;
  s,s1,s2,s3:string;
  find:string;
  p1,p2:integer;
  picture:TIPicture;
  k:integer;
  bitmap:TFreeWinBitmap;
  FreeMemoryIO1:TFreeMemoryIO;
begin
  http:=thttpsend2.Create;
  strlist:=tstringlist.Create;
  picture:=TIPicture.Create;
  bitmap:=TFreeWinBitmap.Create();

  http.Clear;
  s:='http://search.empas.com/search/img.html?q=%s&wi=52&wm=44&cw=1824&s=&e=%d';
  s:=format(s,['김태희',1]);
  http.HTTPMethod('get',s);
  strlist.LoadFromStream(http.Document);

  k:=0;
  s1:=strlist.Text;
  find:='<img name="thumbimg_';
  p1:=pos(find,s1);
  while p1>0 do begin
    delete(s1,1,p1+5);
    p2:=pos('>',s1);
    if p2>0 then begin
      s2:=copy(s1,1,p2-1);
      s2:=getvalue(s2,'src="','"');
      if s2<>'' then begin
{        http.Clear;
        http.HTTPMethod('get',s2);
        FreeMemoryIO1:=TFreeMemoryIO.Create(http.Document.Memory,http.Document.Size);
        try
          bitmap.LoadFromMemory(FreeMemoryIO1);
          inc(k);
          s3:=GetAppDirectory+'temp\'+format('%s_%d.jpg',['김태희',k]);
          bitmap.Save(s3, FIF_JPEG);
        finally
          FreeMemoryIO1.Free;
        end;      }
        memo1.Lines.Add(s2);
      end;
    end;
    p1:=pos(find,s1);
  end;

//  memo1.Lines.Assign(strlist);

end;

procedure Tfrmmain.TBItem10Click(Sender: TObject);
begin
  frmfetch:=Tfrmfetch.Create(self);
  frmfetch.ShowModal;
  frmfetch.Free;
end;

procedure Tfrmmain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
  if config.c_closeprompt=false then exit;

  if MessageDlg('프로그램을 종료 하시겠습니까?',
    mtConfirmation, [mbYes, mbNo], 0) = mrno then
    canclose:=false
  else
    canclose:=true;
end;

procedure Tfrmmain.wb1ProgressChange(Sender: TObject; Progress,
  ProgressMax: Integer);
var
 dummy:integer;
begin
  if ProgressMax > 0 then begin
     dummy:=(Progress * 100 div ProgressMax);
     if dummy > 100 then dummy:=100;
     ProgressBar2.Max:=100;
     ProgressBar2.Position:=dummy;
  end;
end;

procedure Tfrmmain.wb1CommandStateChange(Sender: TObject; Command: Integer;
  Enable: WordBool);
begin
{  case Command of
    CSC_NAVIGATEBACK:begin
      TBItem13.Enabled:=enable;
    end;
    CSC_NAVIGATEFORWARD:begin
      TBItem12.Enabled:=enable;
    end;
  end;}
end;

procedure Tfrmmain.TBItem13Click(Sender: TObject);
begin
//  wb1.GoBack;
end;

procedure Tfrmmain.TBItem12Click(Sender: TObject);
begin
//  wb1.GoForward;
end;

procedure Tfrmmain.PageControl1Change(Sender: TObject);
var
  flag:boolean;
  imgv:TImgView32;
begin
  flag:=PageControl1.ActivePageIndex<=2;
  TBItem2.Enabled:=flag;
  TBItem3.Enabled:=flag;
  TBItem4.Enabled:=flag;
  TBItem7.Enabled:=(PageControl1.ActivePageIndex=1) or (PageControl1.ActivePageIndex=2);

  if flag then begin
    imgv:=get_activeimageview32;
    StatusBar1.Panels[0].Text:=format('%d X %d',[imgv.Bitmap.Width,imgv.Bitmap.Height]);
    StatusBar1.Panels[1].Text:=format('확대,축소: %d%%',[trunc(imgv.Scale*100)]);
  end else begin
    StatusBar1.Panels[0].Text:='';
    StatusBar1.Panels[1].Text:='';
  end;
end;

procedure Tfrmmain.FormShow(Sender: TObject);
begin
//  TBItem11Click(nil);
end;

procedure Tfrmmain.N3Click(Sender: TObject);
var
  bmp:tbitmap32;
begin
  if image2.Bitmap.Empty then exit;
  frmresize:=Tfrmresize.Create(self);
  try
    frmresize.src_w:=image2.Bitmap.Width;
    frmresize.src_h:=image2.Bitmap.Height;
    if frmresize.ShowModal<>mrok then exit;
    bmp:=tbitmap32.Create;
    screen.Cursor:=crHourGlass;
    try
      Resample(image2.Bitmap, bmp, frmresize.SpinEdit1.Value,
         frmresize.SpinEdit2.Value, TStretchFilter(frmresize.c_mosaicresize.ItemIndex));
      image3.Bitmap.Assign(bmp);
      image3.Scale:=1;
    finally
      bmp.Free;
      screen.Cursor:=crdefault;
    end;
    PageControl1.ActivePageIndex:=2;
    PageControl1Change(nil);
  finally
    frmresize.Free;
  end;
end;

procedure CromaKey(ABitmap: TBitmap32; TrColor: TColor32);
var
  P: PColor32;
  C: TColor32;
  I: Integer;
begin
  TrColor := TrColor and $00FFFFFF; // erase alpha, (just in case it has some)
  with ABitmap do
  begin
    P := PixelPtr[0, 0];
    for I := 0 to Width * Height - 1 do
    begin
      C := P^ and $00FFFFFF; // get RGB without alpha
      if C = TrColor then // is this pixel "transparent"?
        P^ := C; // write RGB with "transparent" alpha back into the SrcBitmap
      Inc(P); // proceed to the next pixel
    end;
  end;
end;


procedure Tfrmmain.setwatermark(Bitmap:TBitmap32);
var
  bmp,bmp2:tbitmap32;
  bmp3:tbitmap;
  x,y,w,h,diff,size:integer;
  s:string;
begin
  bmp:=tbitmap32.Create;
  bmp2:=tbitmap32.Create;
  bmp3:=tbitmap.Create;
  bmp.DrawMode:=dmBlend;
  bmp2.DrawMode:=dmBlend;
  try
    bmp3.Canvas.Font.Name:='Arial';
    if Bitmap.Width<Bitmap.Height then
      size:=Bitmap.Width
    else
      size:=Bitmap.Height;
    size:=size*40 div 1000;
    if size<8 then size:=8;
    bmp3.Canvas.Font.Size:=size;
    bmp3.Canvas.Font.Color:=clwhite;
    s:='iblogbox.com';
    w:=bmp3.Canvas.TextWidth(s);
    h:=bmp3.Canvas.TextHeight(s);
    diff:=h div 9;
    if diff<2 then diff:=2;
    w:=w+(diff*3);
    h:=h+diff;
    bmp3.Width:=w;
    bmp3.Height:=h;
    bmp3.Canvas.Brush.Color:=clblack;
    bmp3.Canvas.FillRect(rect(0,0,w,h));
    bmp3.Canvas.TextOut((diff*3) div 2,diff div 2,s);

    bmp.Assign(bmp3);
    bmp.MasterAlpha:=100;

    diff:=diff*2;
    if Bitmap.Width<bmp.Width+diff then begin
      w:=Bitmap.Width-diff;
      h:=round((bmp.Height*w)/bmp.Width);
      Resample(bmp, bmp2, w, h, sfLanczos);
      x:=Bitmap.Width-bmp2.Width-(diff div 2);
      y:=Bitmap.Height-bmp2.Height-(diff div 2);
    end else begin
      bmp2.Assign(bmp);
      x:=Bitmap.Width-bmp2.Width-diff;
      y:=Bitmap.Height-bmp2.Height-diff;
    end;
  
    Bitmap.Draw(x,y,bmp2);
  finally
    bmp.Free;
    bmp2.Free;
    bmp3.Free;
  end;
end;

procedure Tfrmmain.PopupMenu1Popup(Sender: TObject);
begin
  n1.Enabled:=not image2.Bitmap.Empty;
  n3.Enabled:=n1.Enabled;
  N6.Enabled:=n1.Enabled;
end;

procedure Tfrmmain.PopupMenu3Popup(Sender: TObject);
begin
  n4.Enabled:=not image3.Bitmap.Empty;
  N5.Enabled:=N4.Enabled;
end;

procedure Tfrmmain.N7Click(Sender: TObject);
var
  imgv:TImgView32;
begin
  imgv:=get_activeimageview32;
  if imgv=nil then exit;
  if imgv.Bitmap.Empty then exit;
  CopyBitmap32ToClipboard(imgv.Bitmap);
  MessageDlg('복사되었습니다.', mtInformation, [mbok], 0);
end;

procedure Tfrmmain.PopupMenu2Popup(Sender: TObject);
begin
  n7.Enabled:=not image1.Bitmap.Empty;
end;

procedure Tfrmmain.wb1DocumentComplete(Sender: TObject;
  const pDisp: IDispatch; var URL: OleVariant);
//var
//  curWebrowser: IWebBrowser;
//  topWebBrowser: IWebBrowser;
begin
{  curWebrowser:= pDisp as IWebBrowser;
  topWebBrowser:= wb1.DefaultInterface;
  if curWebrowser<>topWebBrowser then exit;
  ProgressBar2.Position:=0;}
end;

procedure Tfrmmain.TBItem14Click(Sender: TObject);
begin
  if sysutils.FileExists(GetAppDirectory+'template\webviewer.zip')=false then begin
    MessageDlg('템플릿파일이 존재하지 않습니다. 다시 설치를 해주세요.', mterror, [mbok], 0);
    exit;
  end;
{  if (image1.Bitmap.Width*image1.Bitmap.Height>1000000) or (image2.Bitmap.Width*image2.Bitmap.Height>1000000)
    or (image3.Bitmap.Width*image3.Bitmap.Height>1000000)  then begin
    if MessageDlg('메모리 문제로 현재 로드한 원본 또는 모자이크이미지를 제거 해야 합니다. 저장하지 않았다면 취소후 저장을 해주세요.'
      +#13#10+'지금 제거하고 계속 하시겠습니가?', mtConfirmation, [mbYes, mbNo], 0)<>mryes then
      exit;
    image1.Bitmap.SetSize(0,0);
    image2.Bitmap.SetSize(0,0);
    image3.Bitmap.SetSize(0,0);
  end;
}
  frmwebviewer:=Tfrmwebviewer.Create(self);
  frmwebviewer.ShowModal;
  frmwebviewer.Free;
end;

procedure Tfrmmain.TBItem15Click(Sender: TObject);
begin
  if MessageDlg('열려진 원본 또는 모자이크이미지를 모두 제거하시겠습니까?',
        mtConfirmation, [mbYes, mbNo], 0)<>mryes then
    exit;
  image1.Bitmap.SetSize(0,0);
  image2.Bitmap.SetSize(0,0);
  image3.Bitmap.SetSize(0,0);
end;

procedure Tfrmmain.TBItem25Click(Sender: TObject);
begin
  ShellExecute(Application.Handle, 'open', PChar(home_url), nil, nil, SW_NORMAL);
{  wb1.Navigate(home_url);
  PageControl1.ActivePageIndex:=3;
  PageControl1Change(nil);}
end;

procedure Tfrmmain.TBItem29Click(Sender: TObject);
begin
  frmabout:=Tfrmabout.Create(self);
  try
    frmabout.Caption:=self.Caption;
    frmabout.ShowModal;
  finally
    frmabout.Free;
  end;
end;

end.
