{******************************************************

       MXDRV Emulator For Windows2000

       with X68Sound.DLL or Full Compatibile DLL
            TGogoTea and Quadruple-D Component
            WinFMP.DLL and PMDWin.DLL and fft_c60.pas

       Copyright (c) 1998-2003 Moonlight Presents.

*******************************************************}

// Indy Modified BSD License
// The Indy Modified BSD license is a very no nonsense license that allows you to do almost anything you want with Indy, provided you provide proper attribution.
// Copyright
// Portions of this software are Copyright (c) 1993 - 2002, Chad Z. Hower (Kudzu) and the Indy Pit Crew - http://www.nevrona.com/Indy/
// This compile provides some notes concerning Indy 9.0.4 beta.

unit MainWin;

{$WARN UNIT_PLATFORM OFF}
{$WARN SYMBOL_PLATFORM OFF}

// Enable_EDisk1を定義し、EDisk1.rcとEDisk1Win.pasをプロジェクトに加えるとEventDiskVol.1仕様になります。
{$DEFINE Disable_EDisk1}

// ライブラリパスに、_PasLibと_PasFormsを追加すること。
// もしくは、_PasLibと_PasFormsの全てのファイルをプロジェクトフォルダにコピーしてもコンパイルできます。

interface

uses
  Windows, Messages, SysUtils, Forms, ShellAPI, ExtCtrls,_SimpleDialog,
  StdCtrls, Controls, Classes, Graphics, Menus, MMSystem, Grids,ComCtrls,
  QDArc, TrayIcon,Dialogs,IdBaseComponent, IdComponent, IdTCPServer,
  _MDXWin_const,_NetRemote,_gFileInfo,_Images,_Catalog,_Network,_HTTPSocket;

type
  TX68proc=procedure cdecl export;

  TSysMat=record
    YCap:LongInt;
    XBorder:LongInt;
    YBorder:LongInt;
  end;

  TMusicTitle=record
    Text:string;
    ESCMode:integer;
  end;

type
  TMain = class(TForm)
    MuteCheckImage: TImage;
    VolumeBarImg: TImage;
    TempoBarImg: TImage;
    TitleBarImg: TImage;
    SeekBarImg: TImage;
    _SpeFlame: TShape;
    SpeBarLbl: TLabel;
    SpeScrLbl: TLabel;
    SpeLineLbl: TLabel;
    SpeWaveLbl: TLabel;
    MusicTitleImg: TImage;
    SpeVisSetLbl: TLabel;
    FileGrid: TStringGrid;
    InfomationTimer: TTimer;
    FileGridTimer: TTimer;
    RewriteTimer: TTimer;
    DragTimer: TTimer;
    IdTCPServer: TIdTCPServer;
    NetStatusTimer: TTimer;
    NextTimerFromPCMOut: TTimer;
    DriveMenu: TPopupMenu;
    DriveMenu_Set: TMenuItem;
    DriveMenu_All: TMenuItem;
    DriveMenu_RegUser: TMenuItem;
    DriveMenu_UnregUser: TMenuItem;
    DriveMenu_EditUser: TMenuItem;
    BootED1Timer: TTimer;
    FileGridImg: TImage;
    SKIOpenDlg: TOpenDialog;
    FuncImg: TImage;
    NetPrgImg: TImage;
    CompactImg: TImage;

    procedure CMShowingChanged(var Msg:TMessage);message CM_SHOWINGCHANGED;
    procedure WMDROPFILES(var msg:TWMDROPFILES);message WM_DROPFILES;
    procedure WMCopyData(var Msg:TWMCopyData); message WM_COPYDATA;
    procedure FormCreate(Sender: TObject);
    procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure ApplicationActive(Sender: TObject);
    procedure ApplicationDeactive(Sender: TObject);
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
    procedure InfomationTimerTimer(Sender: TObject);
    procedure FileGridTimerTimer(Sender: TObject);
    procedure FormResize(Sender: TObject);

    procedure MuteCheckImageMouseDown(Sender: TObject;
      Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
    procedure VolumeBarImgMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure VolumeBarImgMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure TempoBarImgMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure TempoBarImgMouseMove(Sender: TObject; Shift: TShiftState;
      X, Y: Integer);
    procedure TitleBarImgMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure TitleBarImgMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure TitleBarImgMouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure TitleBarImgDblClick(Sender: TObject);
    procedure SpeBarLblClick(Sender: TObject);
    procedure SpeScrLblClick(Sender: TObject);
    procedure SeekBarImgMouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure SpeWaveLblClick(Sender: TObject);
    procedure SpeLineLblClick(Sender: TObject);
    procedure RewriteTimerTimer(Sender: TObject);
    procedure FileGridDrawCell(Sender: TObject; ACol, ARow: Integer;
      Rect: TRect; State: TGridDrawState);
    procedure FileGridMouseWheelDown(Sender: TObject; Shift: TShiftState;
      MousePos: TPoint; var Handled: Boolean);
    procedure FileGridMouseWheelUp(Sender: TObject; Shift: TShiftState;
      MousePos: TPoint; var Handled: Boolean);
    procedure FileGridStartDrag(Sender: TObject;
      var DragObject: TDragObject);
    procedure FileGridMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure FileGridDragOver(Sender, Source: TObject; X, Y: Integer;
      State: TDragState; var Accept: Boolean);
    procedure FileGridEndDrag(Sender, Target: TObject; X, Y: Integer);
    procedure DragTimerTimer(Sender: TObject);
    procedure FileGridMouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure FormPaint(Sender: TObject);
    procedure TempoBarImgMouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure IdTCPServerConnect(AThread: TIdPeerThread);
    procedure IdTCPServerDisconnect(AThread: TIdPeerThread);
    procedure IdTCPServerCmdHnd_LOGINCommand(ASender: TIdCommand);
    procedure IdTCPServerCmdHnd_LOGOUTCommand(ASender: TIdCommand);
    procedure IdTCPServerCmdHnd_GETSTATUSCommand(ASender: TIdCommand);
    procedure IdTCPServerCmdHnd_CHDIRCommand(ASender: TIdCommand);
    procedure IdTCPServerCmdHnd_GETVERSIONCommand(ASender: TIdCommand);
    procedure IdTCPServerCmdHnd_EXECUTECommand(ASender: TIdCommand);
    procedure IdTCPServerCmdHnd_GETDIRCommand(ASender: TIdCommand);
    procedure IdTCPServerCmdHnd_SETSEEKCommand(ASender: TIdCommand);
    procedure IdTCPServerCmdHnd_PLAYCommand(ASender: TIdCommand);
    procedure IdTCPServerCmdHnd_CHDRVCommand(ASender: TIdCommand);
    procedure IdTCPServerCmdHnd_SETTOTALVOLUMECommand(ASender: TIdCommand);
    procedure IdTCPServerCmdHnd_SETTRANSTEMPOCommand(ASender: TIdCommand);
    procedure NetStatusTimerTimer(Sender: TObject);
    procedure NextTimerFromPCMOutTimer(Sender: TObject);
    procedure IdTCPServerCmdHnd_SETPLAYMODECommand(ASender: TIdCommand);
    procedure SpeVisSetLblClick(Sender: TObject);
    procedure BootED1TimerTimer(Sender: TObject);
    procedure FormKeyUp(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure MusicTitleImgClick(Sender: TObject);
    procedure FileGridDblClick(Sender: TObject);
    procedure SKIOpenDlgShow(Sender: TObject);
    procedure SKIOpenDlgClose(Sender: TObject);
    procedure SKIOpenDlgSelectionChange(Sender: TObject);
  private
    ParamFilename:string; // 起動パラメータのファイル名が入っていてCMShowingChangedで処理される。
    MMoveFlag:boolean;
    MMoveX,MMoveY:integer;
    BootShowing:boolean;
    DragX,DragY:integer;
    procedure onNetworkProgressStart(msg:string);
    procedure onNetworkProgressRefresh(RefStatus,RefProgress:boolean;Status:string;Size,Pos:integer);
    procedure onNetworkProgressEnd;
    procedure RewriteImage;
    procedure DrawSeekBar(x1,x2:integer;Enabled:boolean);
    procedure RedrawSeekBar;
    procedure SpeanaModeRefresh;
    procedure FormPaintDriverMode;
    procedure IdTCPServerCmdHnd(var ASender:TIdCommand;resstr:string);
    procedure RefreshScreenComponents;
  public
    DragFiles:TDragFiles;
    MusicTitle:TMusicTitle;

    NetRemote:TNetRemote;
    gFileInfo:TgFileInfo;
    Catalog:TCatalog;
    Network:TNetwork;
    HTTPSocket:THTTPSocket;
    TrayIcon:TTrayIcon;

    WavesFormLoaded:boolean;
    NetFindLoaded:boolean;
    NetRankLoaded:boolean;
    NetVoteLoaded:boolean;
    KDDLoaded:boolean;

    goEtcWindowFlag:boolean;
    DesktopDir,DesktopPath:string;
    SysMat:TSysMat;
    FilereadBusyFlag:boolean;
    PrevSeekX:integer;

    DDBlurMode:integer;

    NowAnalyzeFrame:LongInt;
    NowAnalyzeFFT:LongInt;
    NowUseDSound:integer;
    NowDSoundSafeTime:LongInt;
    NowDSoundRate:dword;
    NowUseKDD:boolean;
    NowWAO_DLLName:string;

    function  isCanDrag:boolean;
    procedure DebugInt(x:LongInt);
    procedure DebugStr(x:string);
    procedure SaveDebugOut(x:string);
    function  isCompactWindow:boolean;
    procedure ReflectionINILocate;
    procedure InfomationVisible(MesStr:string);
    procedure SetMusicTitle(_Text:string;_ESCMode:integer);
    procedure ChangeLoopMax(vector:integer);
    procedure ReflectionMainSetting;
    procedure ChangeDriverMode;
    procedure CreateDragFilesOne(idx:integer);
    procedure PlayButtonsCallback;
    procedure TempoBarImgRefresh(Tempo:integer);
    procedure VolumeBarImgRefresh;
    procedure FormPaintVolumeTempo;
    procedure PCMOutMenuCallback;
    procedure TitleBarScroll;
    procedure TrayIconMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
    procedure TrayIconDblClick(Sender: TObject);
    procedure SetVisMode(_VisualMode:integer);
    procedure SetCompactWindow;
    procedure DriveMenu_Popup;
    procedure ReloadSkin(SKIFilename:string);
  end;

var
  Main: TMain;

implementation

uses
{$IFDEF Enable_EDisk1}
    EDisk1Win,
{$ENDIF}
    KDDWin, WavesOutWin, SplashWin, PeekWin, FlortFileWin, NetFindWin,
    NetRankWin, NetVoteWin, PathHistWin,
    _MDXWinINI,_const,_SndDrv_const,_SndDrv,_Vis_const,_Vis,
    _m_Tools,_PicTools,_PCMOut,_CSkin,_netconst,_ID3_const,DX3DRap,
    _MainFileCtl, _Compact,_CurrentFiles,_KeyDef,_KeyDef_const,_TermLog,
    _GridScroll,_GridScroll_Rap,_WinPosConst,_Func,_PopupMenus,
    VisSetupWin, KeySetupWin, SKIDlgWin;

{$R *.DFM}

procedure TMain.DebugInt(x:LongInt);
begin
  SaveDebugOut('Int:'+IntToStr(x));
end;

procedure TMain.DebugStr(x:string);
begin
  SaveDebugOut(x);
end;

procedure TMain.SaveDebugOut(x:string);
var
  Filename:string;
  T:TextFile;
  TargetFilename:string;
begin
  TargetFilename:=ExtractFilename(Main.gFileInfo.GetFullPath);

  Filename:=ExtractFileDir(Application.ExeName)+'\MDXError.log';
  AssignFile(T,Filename);
  if FileExists(Filename)=False then
    Rewrite(T)
    else
    Append(T);
  Writeln(T,'['+TargetFilename+'] '+x);
  Flush(T);
  CloseFile(T);
end;

function TMain.isCanDrag:boolean;
begin
  Result:=False;
  if DragFiles.Enabled=True then exit;

  if WavesFormLoaded=True then begin
    if WavesOut.Visible=True then Result:=True;
  end;
end;

procedure TMain.FileGridMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  if Application.Title='MDXClose' then exit;

  DragTimer.Enabled:=False;

  if Button=mbLeft then begin
    Dragx:=x;
    Dragy:=y;
    DragTimer.Enabled:=True;
  end;

  if Button=mbRight then PopupMenus.FileMenu_Popup;
end;

procedure TMain.FileGridDragOver(Sender, Source: TObject; X, Y: Integer;
  State: TDragState; var Accept: Boolean);
begin
  if Application.Title='MDXClose' then exit;
  Accept:=DragFiles.Enabled;
end;

procedure TMain.FileGridEndDrag(Sender, Target: TObject; X, Y: Integer);
begin
  if Application.Title='MDXClose' then exit;
  DragTimer.Enabled:=False;
  DragFiles.Enabled:=False;
end;

procedure TMain.DragTimerTimer(Sender: TObject);
begin
  DragTimer.Enabled:=False;
  FileGrid.BeginDrag(False);
end;

procedure TMain.FileGridMouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  DragTimer.Enabled:=False;
end;

procedure TMain.FileGridStartDrag(Sender: TObject;
  var DragObject: TDragObject);
var
  idx:integer;
begin
  if Application.Title='MDXClose' then exit;

  DragTimer.Enabled:=False;

  idx:=CurrentFiles.MouseToCell(Dragx,Dragy);
  CurrentFiles.SetCursorIndex(idx);
  if (0<=idx) and (idx<CurrentFiles.GetItemsCount) then begin
    end else begin
    CancelDrag;
    exit;
  end;

  if isCanDrag=False then begin
    CancelDrag;
    exit;
  end;

  CreateDragFilesOne(idx);
end;

procedure TMain.CreateDragFilesOne(idx:integer);
var
  SelectItem:TFilesItem;
begin
  with DragFiles do begin
    Enabled:=False;
    Count:=0;
    SetLength(DragFile,Count+1);
  end;

  if isCanDrag=False then exit;

  if (idx<0) or (CurrentFiles.GetItemsCount<=idx) then begin
    CancelDrag;
    exit;
  end;
  CurrentFiles.GetItem(idx,SelectItem);

  case SelectItem.Attr of
    ir_None: CancelDrag;
    ir_Drive: CancelDrag;
    ir_Dir: CancelDrag;
    ir_File: begin
      with DragFiles do begin
        Enabled:=True;
        Count:=0;
        SetLength(DragFile,Count+1);
        with DragFile[Count] do begin
          FullPath:=MainFileCtl.GetFullFilename(SelectItem.Name);
          if SelectItem.Value='' then begin
            Title:='['+SelectItem.Name+']';
            end else begin
            Title:=strCnvAnk2to1byte(strGetCompact(strCnvX68kPlusSJIS(strClearESC(SelectItem.Value))));
          end;
          ClearID3(ID3);
        end;
        inc(Count);
      end;
    end;
  end;
end;

procedure TMain.WMCopyData(var Msg:TWMCopyData);
var
  Filename:string;
begin
  if FilereadBusyFlag=True then exit;
  if goEtcWindowFlag=True then exit;

  Filename:=PChar(Msg.CopyDataStruct^.lpData);
  if copy(Filename,1,1)='"' then Filename:=copy(Filename,2,Length(Filename)-2);
  if length(Filename)>255 then exit;

  if (Filename<>'') and (copy(Filename,1,3)<>'#:\') then begin
    while Filename[Length(Filename)]='\' do begin
      Filename:=copy(Filename,1,Length(Filename)-1);
    end;
    if FileExists(Filename)=False then begin
      Filename:=Filename+'\';
      if DirectoryExists(Filename)=False then begin
        Filename:='';
      end;
    end;
  end;

  if Filename<>'' then begin
    MainFileCtl.ExecutePlayFile(Filename,True);
  end;

  if MainINI.DropActiveWindow=True then begin
    Application.ProcessMessages;
    SetForegroundWindow(Main.Handle);
    SetActiveWindow(Main.Handle);
  end;
end;

procedure TMain.WMDROPFILES(var msg:TWMDROPFILES);
var
  Drop:hdrop;
  index:longint;
  Filename:string;
  filebuf:array[0..1024] of char;
  cnt:integer;
begin
  if FilereadBusyFlag=True then exit;
  if goEtcWindowFlag=True then exit;

  Filename:=StringOfChar(' ',1024);
  Drop:=msg.Drop;
  index:=DragQueryFile(Drop,$FFFFFFFF,nil,0);
  if index=0 then begin
    DragFinish(Drop);
    exit;
  end;

  if index>=2 then begin
    ShowMessage('複数ファイルのドラッグアンドドロップは'+CRLF+'Wave/MP3/Ogg作成ウィンドウ以外では許可されていません。');
    end else begin
    DragQueryFile(Drop,0,filebuf,1024);
    Filename:='';
    cnt:=0;
    while ((filebuf[cnt]<>char($00)) and (cnt<1024)) do begin
      Filename:=Filename+filebuf[cnt];
      inc(cnt);
    end;
    if Filename[Length(Filename)]<>'\' then begin
      if FileExists(Filename)=False then Filename:=Filename+'\';
    end;
    if Filename[Length(Filename)]='\' then begin
      if DirectoryExists(Filename)=False then Filename:='';
    end;
    if Filename<>'' then begin
      if copy(Filename,1,2)='\\' then begin
        ShowMessage('ネットワーク経由でのドラッグアンドドロップはサポートされていません。'+chr(13)+chr(10)+'ネットワークドライブを割り当て場合は使用可能です。'+CRLF+'または、ユーザー定義パスを割り当てて下さい。');
        end else begin
        MainFileCtl.ExecutePlayFile(Filename,True);
      end;
    end;
  end;
  DragFinish(Drop);

  if MainINI.DropActiveWindow=True then begin
    Application.ProcessMessages;
    SetForegroundWindow(Main.Handle);
    SetActiveWindow(Main.Handle);
  end;
end;

procedure TMain.ReflectionINILocate;
var
  pos:TWindowPos;
begin
  pos:=MainINI.MainPos;
  if MainINI.CompactWindowEnabled=True then pos.Height:=TitleBarImg.Top+TitleBarImg.Height+CompactImg.Height;
  AdjustWindowSize(Screen.Width,Screen.Height,pos);
  if MainINI.CompactWindowEnabled=True then pos.Height:=MainINI.MainPos.Height;
  MainINI.MainPos:=pos;

  with MainINI.MainPos do begin
    MoveWindow(Main.Handle,Left,Top,Width,Height,True);
  end;
end;

procedure TMain.FormCreate(Sender: TObject);
var
  Title:string;
  Wnd:hwnd;
  tc:TTIMECAPS;
  procedure SendCopyData(wnd:hwnd;Mes:string);
  var
    CDS:TCopyDataStruct;
  begin
    CDS.cbData:=Length(Mes)+1;
    CDS.lpData:=pchar(Mes);
    SendMessage(Wnd,WM_COPYDATA,0,LongInt(@CDS));
  end;
  procedure SetMouseCursor;
  var
    WF:TMemoryStream;
  begin
    WF:=ExtractFromQDAFile(StartPath+'MDXWin.qda','MDXWin.cur');
    WF.SaveToFile(StartPath+'MDXWin.cur');
    WF.Free;
    Screen.Cursors[crXWindowCursor]:=LoadCursorFromFile(PChar(StartPath+'MDXWin.cur'));
    DeleteFile(StartPath+'MDXWin.cur');
    Main.Cursor:=crXWindowCursor;
    FileGrid.Cursor:=crXWindowCursor;
  end;
  procedure SplashInit;
  begin
    if MainINI.SplashScreen=False then exit;
    Splash:=TSplash.Create(nil);
    Splash.Init(MainINI.MainPos.Left,MainINI.MainPos.Top);
  end;
  procedure SplashTextOut(txt:string);
  begin
    if MainINI.SplashScreen=False then exit;
    Splash.TextOut(txt);
  end;
  procedure SplashFree;
  begin
    if MainINI.SplashScreen=False then exit;
    Splash.FreeMemory;
  end;
procedure p0;
begin
  TermLog('MMTimer','');
  timeGetDevCaps(@tc,sizeof(TTIMECAPS));
  timeBeginPeriod(tc.wPeriodMin);
{$IFDEF DebugDriver}
  DebugStr('Debug.マルチメディアタイマーの分解能 '+IntToStr(tc.wPeriodMin)+'~'+IntToStr(tc.wPeriodMax)+'/1000ms');
{$ENDIF}
end;
procedure p1;
begin
  TermLog('SimpleDialog','SetShowMessageHandle');
  SetShowMessageHandle(Application.Handle);
end;
procedure p2;
begin
  TermLog('GetDesktopPath','');
  DesktopDir:=GetDesktopPath;
  DesktopPath:=DesktopDir+'\';
  TermLog('GetDesktopPath',DesktopPath);

end;
procedure p3;
begin
  TermLog('GetDefaultPosition','');
  Main.Left:=Screen.Width;
  Main.Top:=Screen.Height;

end;
procedure p4;
var
  Param:integer;
begin
  TermLog('SetApplicationTitle','MDXWin '+MDXWinVersion+'-'+MDXWinDate);
  Application.Title:='MDXWin '+MDXWinVersion+'-'+MDXWinDate;

  TermLog('ProcessParametors','Start');
  ParamFilename:='';
  for Param:=1 to ParamCount do begin
    TermLog('ProcessParametors',ParamStr(Param));
    if copy(ParamStr(Param),1,1)<>'/' then begin
      if FileExists(ParamStr(Param))=True then ParamFilename:=ParamStr(Param);
      if copy(ParamStr(Param),1,8)='mdxo:///' then begin
        ParamFilename:='#:\'+ConvURL2Filename(copy(ParamStr(Param),9,255));
      end;
    end;
  end;

end;
procedure p5;
begin
  TermLog('CurrentFiles','Create');
  CurrentFiles:=TCurrentFiles.Create;
  TermLog('CurrentFiles','MemInit');
  CurrentFiles.MemInit(FileGrid);

end;
procedure p6;
begin
  TermLog('SetDefaultPosition','MDXWin 2.xx');
  with MainINI.MainPos do begin
    Left:=(Screen.Width-Main.Width) div 2;
    Top:=(Screen.Height-Main.Height) div 2;
    Width:=Main.Width;
    Height:=Main.Height;
  end;

end;
procedure p7;
begin
  TermLog('MDXWinINIFileload',ExtractFileDir(Application.ExeName)+'\MDXWin.ini');
  MDXWinINIFileload(ExtractFileDir(Application.ExeName)+'\MDXWin.ini');
  TermLog('ReflectionINILocate','');
  ReflectionINILocate;
  TermLog('ReflectionMainSetting','');
  ReflectionMainSetting;

end;
procedure p8;
begin
  TermLog('MainFileCtl','Create');
  MainFileCtl:=TMainFileCtl.Create;
  TermLog('MainFileCtl','Init');
  MainFileCtl.Init;
  TermLog('Compact','Create');
  Compact:=TCompact.Create;
  TermLog('Compact','Init');
  Compact.Init(CompactImg);

end;
procedure p9;
begin
  TermLog('Images','Create');
  Images:=TImages.Create;
  TermLog('SplashInit','');
  SplashInit;

  TermLog('SplashTextOut','');
  SplashTextOut('MDXWin for X680x0 version '+MDXWinVersion);
  SplashTextOut('-'+MDXWinDate+'- Copyright Moonlight.');
  SplashTextOut('MDXRender version 2.11');
  SplashTextOut('');
  SplashTextOut('C>bootseq.x');

end;
procedure p10;
begin
  TermLog('Images','Init');
  Images.Init;
  SplashTextOut('LoadDefaultSkin.');
  TermLog('CSkin','LoadSkin');
  CSkin.LoadSkin(MainINI.SKIFilename);
  TermLog('Images','LoadSkin');
  Images.LoadSkin(CSkin);
  TermLog('GridScroll','LoadSkin');
  GridScroll_LoadSkin(CSkin);
  GridScrollAll_RedrawAll;

  Main.Color:=CSkin.dwBG;

end;
procedure p11;
begin
  TermLog('Func','Create');
  Func:=TFunc.Create;
  TermLog('FuncImg','SetMaterial');
  with FuncImg do begin
    Left:=2;
    Top:=0;
    Width:=Main.Width-FuncImg.Left-2;
    Height:=Func.Height+1;
  end;
  TermLog('Func','Regist');
  FuncImg.Left:=2;
  Func.Regist(FuncImg);

end;
procedure p12;
begin
  TermLog('RefreshScreenComponents','');
  RefreshScreenComponents;

end;
procedure p13;
begin
  TermLog('PopupMenus','Create');
  PopupMenus:=TPopupMenus.Create(Main);

  TermLog('KeyDef','Create');
  KeyDef:=TKeyDef.Create;

end;
procedure p14;
begin
  TermLog('SetNowParams','');
  NowAnalyzeFrame:=VisINI.AnalyzeFrame;
  NowAnalyzeFFT:=VisINI.AnalyzeFFT;
  NowUseDSound:=MainINI.UseDSound;
  NowDSoundSafeTime:=MainINI.DSoundSafeTime;
  NowDSoundRate:=MainINI.DSoundRate;
  NowUseKDD:=MainINI.UseKDD;
  NowWAO_DLLName:=MainINI.WAO_DLLName;

end;
procedure p15;
begin
  TermLog('SetMouseCursor','');
  SetMouseCursor;

end;
procedure p16;
begin
  TermLog('SetWindowOr','');
  goEtcWindowFlag:=False;
  FilereadBusyFlag:=False;
  Main.Font.Height:=-11; // 大きいフォント対策
  MakeBlankImg(TitleBarImg,pf24bit);

end;
procedure p17;
begin
  TermLog('BootNetRemoteServer','');
  if (MainINI.NetRemoteEnabled=False) and (MainINI.NetRemotePort>=1) then begin
    SplashTextOut('NetRemoteServerSkip.');
    NetRemote:=nil;
    end else begin
    SplashTextOut('NetRemoteServerInitialize.');
    NetRemote:=TNetRemote.Create;
    NetRemote.MemInit(MainINI.NetRemotePort,MainINI.NetRemoteLoginPassword,MainINI.NetRemoteLocalOnly);
    try
      IdTCPServer.DefaultPort:=MainINI.NetRemotePort;
      IdTCPServer.Active:=True;
      NetStatusTimer.Enabled:=True;
      except else begin
        ShowMessage('NetRemoteサーバ起動に失敗しました。一時的に停止して起動を続行します。');
        IdTCPServer:=nil;
      end;
    end;
  end;

end;
procedure p18;
begin
  TermLog('PeekLevel','Create');
  PeekLevel:=TPeekLevel.Create;
  TermLog('PeekLevel','Init');
  PeekLevel.ResetAll;

end;
procedure p19;
begin

end;
procedure p20;
begin
  SplashTextOut('SoundDeviceCreated.');

  TermLog('gFileInfo','Create');
  gFileInfo:=TgFileInfo.Create;
  TermLog('gFileInfo','Init');
  gFileInfo.Init;

end;
procedure p21;
begin
  TermLog('sdSndEff','Create');
  sdSndEffCreate;
  TermLog('sdSetTotalVolume',inttostr(MainINI.TotalVolume));
  sdSetTotalVolume(MainINI.TotalVolume);

end;
procedure p220;
begin
  TermLog('Vis','Create');
  Vis:=TVis.Create;
end;
procedure p221;
begin
  TermLog('Vis','Init');
  Vis.Init(VisINI.AnalyzeFrame);
end;
procedure p222;
begin
  TermLog('Catalog','Create');
  Catalog:=TCatalog.Create;
end;
procedure p223;
begin
  TermLog('Catalog','Init');
  Catalog.Init(MainINI.CatalogFilePath);
end;
procedure p224;
begin
  TermLog('Catalog','LoadIndex');
  Catalog.LoadIndex;
end;
procedure p225;
begin
  TermLog('Network','Create');
  Network:=TNetwork.Create;
end;
procedure p226;
begin
  TermLog('Network','Startup:'+StartPath);
  Network.Startup(StartPath);
end;
procedure p227;
begin
  TermLog('HTTPSocket','Create');
  HTTPSocket:=THTTPSocket.Create;
end;
procedure p228;
begin
  TermLog('HTTPSocket','Startup');
  HTTPSocket.Startup(True,MainINI.MDXOnlineTimeoutSec,onNetworkProgressStart,onNetworkProgressRefresh,onNetworkProgressEnd);

end;
procedure p23;
begin
  SplashTextOut('ToolClassCreated.');

  TermLog('GetSystemMetrics','');
  SysMat.YCap:=GetSystemMetrics(SM_CYCAPTION)-1;
  SysMat.XBorder:=GetSystemMetrics(SM_CXBORDER)+3;
  SysMat.YBorder:=GetSystemMetrics(SM_CYBORDER)+3;

  TermLog('SetLoadedFlag','False');
  WavesFormLoaded:=False;
  NetFindLoaded:=False;
  NetRankLoaded:=False;
  NetVoteLoaded:=False;

end;
procedure p24;
begin
  TermLog('SetWindowMaterial','VolumeImage');
  MakeBlankImg(VolumeBarImg,pf24bit);
  VolumeBarImgRefresh;

end;
procedure p25;
begin
  TermLog('SetWindowMaterial','TransTempoImg');
  MakeBlankImg(TempoBarImg,pf24bit);
  TempoBarImgRefresh(0);

end;
procedure p26;
begin
  // Any Font Colors
  TermLog('Any Font Colors','');

  Func.SetItem(FuncNo_F1 ,DCT_PressF1 ,False,'Drive', 1,5);
  Func.SetItem(FuncNo_F2 ,DCT_PressF2 ,False,'PLAY' , 8,5);
  Func.SetItem(FuncNo_F3 ,DCT_PressF3 ,False,'STOP' ,15,5);
  Func.SetItem(FuncNo_F4 ,DCT_PressF4 ,False,'MODE' ,22,6);
  Func.SetItem(FuncNo_F5 ,DCT_PressF5 ,False,inttostr(NowDSoundRate),30,5);
  Func.SetItem(FuncNo_F6 ,DCT_PressF6 ,False,'D_OFF',37,5);
  Func.SetItem(FuncNo_F7 ,DCT_PressF7 ,False,'3D'   ,44,5);
  Func.SetItem(FuncNo_F8 ,DCT_PressF8 ,False,'WAVE' ,51,5);
  Func.SetItem(FuncNo_F9 ,DCT_PressF9 ,False,'SETUP',58,5);
  Func.SetItem(FuncNo_F10,DCT_PressF10,False,'MENU' ,65,5);
  Func.SetItem(FuncNo_F11,DCT_PressF11,False,'Network',72,6);

end;
procedure p27;
begin
  SplashTextOut('WindowColorSetting.');

  TermLog('SpeanaModeRefresh','');
  SpeanaModeRefresh;

end;
procedure p28;
begin
  TermLog('SeekBarImg','Init');
  MakeBlankImg(SeekBarImg,pf24bit);
  RedrawSeekBar;

end;
procedure p29;
begin
  // NoteAnalyzer From BackScreen
  TermLog('Vis','ResetImages');
  Vis.ClearImage;

end;
procedure p30;
begin
  TermLog('ChangeLoopMax','0');
  ChangeLoopMax(0);

end;
procedure p31;
begin
  // Screen Init.
  TermLog('Screen Init','');
  Compact.SetTime(0);
  Images.WritePlayTime(0);
  Images.WriteTimerBClock(0);
  Images.WriteTimerBCycle(0);
  Images.WriteLoopCount(0);

end;
procedure p32;
begin
  // Title Init.
  TermLog('MusicTitle','Init');
  with MusicTitle do begin
    Text:='';
    ESCMode:=ESCModeNone;
  end;

  TermLog('MusicTitle','SetString');
  SetMusicTitle(MDXWinCurrent,ESCModeNone);
  TermLog('MusicTitle','SetString');
{$IFDEF DebugDriver}
  SetMusicTitle('MDXWin Ver'+MDXWinVersion+'-'+MDXWinDate+' DebugDriverVersion',ESCModeNone);
{$ENDIF}

end;
procedure p33;
begin
  if dx3dEnabled=True then begin
    Func.SetItemText(FuncNo_F7,'3D');
    end else begin
    Func.SetItemText(FuncNo_F7,'3D');
  end;

end;
procedure p34;
begin
end;
procedure p35;
begin
end;
procedure p36;
begin
  TermLog('FileGrid','SetColor');
  FileGrid.Color:=CSkin.dwGridBG;
  TermLog('GridScroll','Create');
  GS_Main:=TGridScroll.Create;
  GS_Main.LinkComponent(FileGrid,FileGridImg);

  SplashTextOut('EtcProcInitialized.');

end;
procedure p37;
begin

end;
procedure p38;
begin
  TermLog('sdSetDriverMode','DriverModeUnknown');
  sdSetDriverMode(DriverModeUnknown);
  TermLog('ChangeDriverMode','');
  ChangeDriverMode;

end;
procedure p39;
begin

end;
procedure p40;
begin
  SplashTextOut('SoundDLLInitialized.');

  TermLog('sdCreateWADSPPlugin','');
  if MainINI.WADSPEnabled=True then begin
    sdCreateWADSPPlugin(Main.Handle);
  end;

end;
procedure p41;
begin
  TermLog('PCMOut','StartDSound');
  PCMOut.StartDSound;

  SplashTextOut('SoundDeviceInitialized.');

end;
procedure p42;
begin
  TermLog('TrayIcon','Create');
  TrayIcon:=nil;
  try
    TrayIcon:=TTrayIcon.Create(Main);
    TrayIcon.TipHelp:='MDXWin Ver'+MDXWinVersion+'-'+MDXWinDate;
    TrayIcon.OnDblClick:=TrayIconDblClick;
    TrayIcon.OnMouseUp:=TrayIconMouseUp;
    TrayIcon.Visible:=MainINI.VisibleTrayIcon;
    except else begin
      TermLog('TrayIcon','except error setnil');
      TrayIcon:=nil;
    end;
  end;
  if TrayIcon<>nil then ShowWindow(Application.Handle, SW_HIDE);

end;
procedure p43;
begin
  // WindowsMessages
  TermLog('WindowsMessages','D&D Start');
  DragAcceptFiles(Main.handle,True); // D&D Start
  TermLog('WindowsMessages','SetApplicationIvent');
  Application.OnActivate:=ApplicationActive;
  Application.OnDeactivate:=ApplicationDeactive;

end;
procedure p44;
begin

end;
procedure p45;
begin
  TermLog('PCMOutMenuCallback','');
  PCMOutMenuCallback;
  TermLog('PlayButtonsCallback','');
  PlayButtonsCallback;

end;
procedure p46;
begin
  TermLog('Func','AllRedraw');
  Func.AllRedraw(MainINI.LoopMax);

  TermLog('SplashFree','');
  if MainINI.SplashScreen=True then Splash.Visible:=False;
  SplashFree;

  BootShowing:=True;
end;
begin
  p0; p1; p2;

  TermLog('CheckNetworkBoot','');
  if copy(StartPath,1,2)='\\' then begin
    ShowMessage('ネットワーク経由での起動はサポートされていません。'+chr(13)+chr(10)+'ネットワークドライブを割り当て場合は使用可能です。');
    Application.Terminate;
    exit;
  end;

  p3; p4;

  TermLog('CheckAlreadyExecute','MDXWin 2.xx');
  Title:='MDXWin 2.xx';
  Main.Caption:='dummy';
  Wnd:=FindWindow('TMain',pchar(Title));
  Main.Caption:=Title;
  if Wnd<>0 then begin
    if ParamFilename<>'' then SendCopyData(wnd,'"'+ParamFilename+'"');
    ParamFilename:='';
    TermLog('Application','Terminate');
    Application.Terminate;
    exit;
  end;

  p5; p6; p7; p8; p9;
  p10; p11; p12; p13; p14; p15; p16; p17; p18;

  SplashTextOut('SoundDeviceInitialize.');

  TermLog('SoundDevice','NullStart');
  PCMOut:=TPCMOut.Create;
  if PCMOut.Init(PCMOut_Null,NowAnalyzeFrame,NowAnalyzeFFT,NowDSoundSafeTime,NowDSoundRate,MainINI.WAO_DLLName)=False then begin
    ShowMessage('無音ドライバの仮起動に失敗しました。'+CRLF+'DirectX7以上がインストールされているかどうか確認して下さい。');
    Application.Terminate;
    exit;
  end;

  p20; p21;
  p220;
  p221;
  p222;
  p223;
  p224;
  p225;
  p226;
  p227;
  p228;
  p23; p24; p25; p26; p27; p28; p29;
  p30; p31; p32; p33; p34; p35; p36; p37; p38;

  TermLog('sdLoadDLL_MXDRV','');
{
  if sdLoadDLL_MXDRV(MXDRVgINI.Enabled,MainINI.UseRomeo,NowDSoundSafeTime)=False then begin
    Application.Terminate;
    exit;
  end;
}

  p40; p41; p42; p43; p44; p45; p46;
end;


procedure TMain.CMShowingChanged(var Msg:TMessage);
begin
  inherited;

  if Main.Visible=False then exit;

  if BootShowing=True then begin
    TermLog('SetCompactWindow','');
    SetCompactWindow;

    TermLog('Application','ProcessMessages');
    Application.ProcessMessages;
    TermLog('BootShowing:=False;','');
    BootShowing:=False;
    TermLog('ApplicationActive','');
    ApplicationActive(nil);

    TermLog('SetForegroundWindow','');
    SetForegroundWindow(Main.Handle);
    TermLog('SetActiveWindow','');
    SetActiveWindow(Main.Handle);

    TermLog('MainFileCtl','FileGridRefresh');
    MainFileCtl.FileGridRefresh;

    TermLog('BootED1','');
    if copy(MainINI.CurrentFilePath,1,1)='#' then begin
      Main.BootED1Timer.Enabled:=True;
    end;

    TermLog('Process','ParamFilename');
    if ParamFilename<>'' then begin
      MainFileCtl.ExecutePlayFile(ParamFilename,True);
      ParamFilename:='';
    end;

//    Peek.Init;
  end;
end;

procedure TMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
//  SetPriorityClass(GetCurrentProcess,IDLE_PRIORITY_CLASS);

  TermLog('StartCloseProcess','');

{$IFDEF Enable_EDisk1}
  if ED1<>nil then begin
    ED1.Close;
    ED1.Release;
  end;
{$ENDIF}

  TermLog('WADSPPlugin','Free');
  sdFreeWADSPPlugin;

  TermLog('ApplicationMinimized','');

  Application.Minimize;
  Application.ProcessMessages;

  TermLog('OnIdleEvent','SetNil');
  Application.OnIdle:=nil;

  TermLog('DragAcceptFiles','False');
  DragAcceptFiles(Main.handle,False); // D&D End

  TermLog('Main','SetWindowStyle');
  Application.Title:='MDXClose';
  Main.Caption:='MDXClose';
  if FlortFile<>nil then FlortFile.Visible:=False;
  NetStatusTimer.Enabled:=False;

  TermLog('GridScroll','Free');
  GS_Main.Free;
  GS_Main:=nil;

  TermLog('KeyDef','Free');
  KeyDef.Free;
  KeyDef:=nil;

  TermLog('PopupMenus','Free');
  PopupMenus.Free;
  PopupMenus:=nil;

  TermLog('SndDrv','StopDriver');
  sdStop;
  TermLog('PCMOut','StopDriver');
  PCMOut.StopDriver;

  if NetRemote<>nil then begin
    try
      TermLog('NetRemote','IdTCPServerDisactivate.');
      IdTCPServer.Active:=False;
      except begin
        TermLog('NetRemote','IdTCPServerDisactive ExceptionError.');
      end;
    end;
    TermLog('NetRemote','Free.');
    NetRemote.MemFree;
    NetRemote.Free;
    NetRemote:=nil;
  end;

  if TrayIcon<>nil then begin
    TermLog('TrayIcon','Hidden');
    TrayIcon.Visible:=False;
    TermLog('TrayIcon','Diabled');
    TrayIcon.Enabled:=False;
    TermLog('TrayIcon','Free');
    TrayIcon.Free;
    TermLog('TrayIcon','SetNil');
    TrayIcon:=nil;
  end;

  if NetFindLoaded=True then begin
    TermLog('NetFind','SavePosition');
    with MainINI.NetFindPos do begin
      Left:=NetFind.Left;
      Width:=NetFind.Width;
      Top:=NetFind.Top;
      Height:=NetFind.Height;
    end;
    TermLog('NetFind','Hidden');
    NetFindLoaded:=False;
    TermLog('NetFind','Close');
    NetFind.Close;
    TermLog('NetFind','Messages');
    Application.ProcessMessages;
    TermLog('NetFind','Free');
    NetFind.Free;
    NetFind:=nil;
  end;

  if NetRankLoaded=True then begin
    TermLog('NetRank','SavePosition');
    with MainINI.NetRankPos do begin
      Left:=NetRank.Left;
      Width:=NetRank.Width;
      Top:=NetRank.Top;
      Height:=NetRank.Height;
    end;
    TermLog('NetRank','Hidden');
    NetRankLoaded:=False;
    TermLog('NetRank','Close');
    NetRank.Close;
    TermLog('NetRank','Messages');
    Application.ProcessMessages;
    TermLog('NetRank','Free');
    NetRank.Free;
    NetRank:=nil;
  end;

  if NetVoteLoaded=True then begin
    TermLog('NetVote','SavePosition');
    with MainINI.NetVotePos do begin
      Left:=NetVote.Left;
      Width:=NetVote.Width;
      Top:=NetVote.Top;
      Height:=NetVote.Height;
    end;
    TermLog('NetVote','Hidden');
    NetVoteLoaded:=False;
    TermLog('NetVote','Close');
    NetVote.Close;
    TermLog('NetVote','Messages');
    Application.ProcessMessages;
    TermLog('NetVote','Free');
    NetVote.Free;
    NetVote:=nil;
  end;

  if FlortFile<>nil then begin
    TermLog('FlortFile','Close');
    FlortFile.Close;
    TermLog('FlortFile','Free');
    FlortFile.Free;
    FlortFile:=nil;
  end;

  if KeySetup<>nil then begin
    TermLog('KeySetup','Close');
    KeySetup.Close;
    TermLog('KeySetup','Free');
    KeySetup.Free;
    KeySetup:=nil;
  end;

  TermLog('Timers','Disabled');
  InfomationTimer.Enabled:=False;
  FileGridTimer.Enabled:=False;
  RewriteTimer.Enabled:=False;

  if WavesFormLoaded=True then begin
    TermLog('WavesOut','SavePosition');
    with MainINI.WavesPos do begin
      Left:=WavesOut.Left;
      Width:=WavesOut.Width;
      Top:=WavesOut.Top;
      Height:=WavesOut.Height;
    end;
    TermLog('WavesOut','Hidden');
    WavesOut.Visible:=False;
    TermLog('WavesOut','Close');
    WavesOut.Close;
    TermLog('WavesOut','Messages');
    Application.ProcessMessages;
    TermLog('WavesOut','Free');
    WavesOut.Free;
    WavesOut:=nil;
  end;

  if FMPLoadFlag=True then begin
    TermLog('FMP','FreeDLL');
    FMP.FreeDLL;
    TermLog('FMP','Free');
    FMP.Free;
    FMP:=nil;
    FMPLoadFlag:=False;
  end;
  
  if PMDLoadFlag=True then begin
    TermLog('PMD','FreeDLL');
    PMD.FreeDLL;
    TermLog('PMD','Free');
    PMD.Free;
    PMD:=nil;
    PMDLoadFlag:=False;
  end;

  if SPCLoadFlag=True then begin
    TermLog('SPC','FreeDLL');
    SPC.FreeDLL;
    TermLog('SPC','Free');
    SPC.Free;
    SPC:=nil;
    SPCLoadFlag:=False;
  end;

  if KDDLoaded=True then begin
    TermLog('KDD','SavePosition');
    with MainINI.KDDPos do begin
      Left:=KDD.Left;
      Width:=KDD.Width;
      Top:=KDD.Top;
      Height:=KDD.Height;
    end;
    TermLog('KDD','Hidden');
    KDD.Visible:=False;
    TermLog('KDD','Close');
    KDD.Close;
    TermLog('KDD','Messages');
    Application.ProcessMessages;
    TermLog('KDD','Free');
    KDD.Free;
    KDD:=nil;
  end;

  TermLog('DX3D','FreeMemory');
  dx3dFreeMemory;

  TermLog('Main','SavePosition');
  with MainINI.MainPos do begin
    Left:=Main.Left;
    Top:=Main.Top;
    if isCompactWindow=False then begin
      Width:=Main.Width;
      Height:=Main.Height;
    end;
  end;

  TermLog('Main','SaveINIFile');
  MDXWinINIFilesave(ExtractFileDir(Application.ExeName)+'\MDXWin.ini');

  TermLog('Network','FreeMemory');
  Network.FreeMemory;
  TermLog('Network','Free');
  Network.Free;
  Network:=nil;

  TermLog('HTTPSocket','FreeMemory');
  HTTPSocket.FreeMemory;
  TermLog('HTTPSocket','Free');
  HTTPSocket.Free;
  HTTPSocket:=nil;

  TermLog('MainFileCtl','FreeMemory');
  MainFileCtl.FreeMemory;
  TermLog('MainFileCtl','Free');
  MainFileCtl.Free;
  MainFileCtl:=nil;

  TermLog('Compact','FreeMemory');
  Compact.FreeMemory;
  TermLog('Compact','Free');
  Compact.Free;
  Compact:=nil;

  TermLog('gFileInfo','Free');
  gFileInfo.Free;
  gFileInfo:=nil;

  TermLog('sdSndEff','Free');
  sdSndEffFree;

  TermLog('Vis','FreeMemory');
  Vis.FreeMemory;
  TermLog('Vis','Free');
  Vis.Free;
  Vis:=nil;

  TermLog('Catalog','Free');
  Catalog.Free;
  Catalog:=nil;

  TermLog('PCMOut','FreeMemory');
  PCMOut.FreeMemory;
  TermLog('PCMOut','Free');
  PCMOut.Free;
  PCMOut:=nil;

  if MXDRVLoadFlag=True then begin
    if MXDRVm<>nil then begin
      TermLog('MXDRVm','FreeMemory');
      MXDRVm.FreeMemory;
      TermLog('MXDRVm','Free');
      MXDRVm.Free;
      MXDRVm:=nil;
    end;
    if MXDRVg<>nil then begin
      TermLog('MXDRVg','FreeMemory');
      MXDRVg.FreeMemory;
      TermLog('MXDRVg','Free');
      MXDRVg.Free;
      MXDRVg:=nil;
    end;
    MXDRVLoadFlag:=False;
  end;

  TermLog('Func','FreeMemory');
  Func.FreeMemory;
  TermLog('Func','Free');
  Func.Free;
  Func:=nil;

  TermLog('Images','FreeMemory');
  Images.FreeMemory;
  TermLog('Images','Free');
  Images.Free;
  Images:=nil;

  TermLog('TimeEndPeriod','Set 1');
  timeEndPeriod(1);

  TermLog('CurrentFiles','MemFree');
  CurrentFiles.MemFree;
  TermLog('CurrentFiles','Free');
  CurrentFiles.Free;
  CurrentFiles:=nil;

  TermLog('CanClose','True');
  CanClose:=True;
end;

procedure TMain.ReflectionMainSetting;
begin
  SetPriorityLevel(MainINI.MainPriorityLevel);

  with FileGrid do begin
    Font.Name:=ListFontINI.Name;
    Font.Size:=ListFontINI.Size;
    DefaultRowHeight:=-Font.Height+2;
    Canvas.Font:=Font;
  end;
  GS_Main.ResetPosition;

  Main.FormResize(nil);
end;

procedure TMain.ChangeDriverMode;
var
  Channel:integer;
  ChMode:string;
  ChTrack:integer;
begin
  FormPaintDriverMode;

  // NoteAnalyzer Init.
  for Channel:=0 to 7 do begin
    ChMode:='';
    ChTrack:=0;
    sdGetChMode(Channel,ChMode,ChTrack);

    Images.WriteNoteSmallString(1*6,Channel*34+1,ChMode,CSkin.ColVisKeyTrackText);
    Images.WriteNoteSmallString(0*6,Channel*34+10,'Track.',CSkin.ColVisKeyTrackText);
    Images.WriteNoteMath(5*6,Channel*34,CSkin.ColVisKeyTrackText,ChTrack,2);
  end;
end;

procedure TMain.FormResize(Sender: TObject);
begin
  if Application.Title='MDXClose' then exit;
  if isCompactWindow then exit;
  if Func=nil then exit;

  with FileGrid do begin
    Left:=SeekBarImg.Left;
    Top:=SeekBarImg.Top+SeekBarImg.Height;
    Width:=SeekBarImg.Width-GS_PartsSize;
    Height:=Main.Height-Top-Func.Height-2;
    DefaultColWidth:=Width;
    Update;
  end;
  GS_Main.ResetPosition;

  MainINI.MainPos.Width:=Main.Width;
  MainINI.MainPos.Height:=Main.Height;

  FuncImg.Top:=Main.Height-Func.Height-2;
  FuncImg.Update;
end;

procedure TMain.InfomationVisible(MesStr:string);
begin
  InfomationTimer.Enabled:=False;
  Func.SetInfo(MesStr,MainINI.LoopMax);
  Func.Draw;
  FuncImg.Update;
  InfomationTimer.Enabled:=True;
end;

procedure TMain.InfomationTimerTimer(Sender: TObject);
begin
  if Application.Title='MDXClose' then exit;
  Func.SetInfo('',MainINI.LoopMax);
  Func.Draw;
  InfomationTimer.Enabled:=False;
end;

procedure TMain.SetMusicTitle(_Text:string;_ESCMode:integer);
begin
  if _Text<>'' then begin
    MusicTitle.Text:=_Text;
    MusicTitle.ESCMode:=_ESCMode;
  end;

  MakeBlankImg(MusicTitleImg,pf24bit);
  with MusicTitleImg.Canvas do begin
    Brush.Color:=CSkin.dwTitleBG;
    FillRect(Rect(0,0,Width,Height));
    Font.Color:=CSkin.dwTitleText;
    Font.Height:=-16;
    Font.Name:='ＭＳ ゴシック';
  end;

  with MusicTitleImg do begin
    BitBlt(Canvas.Handle,0,0,Width,Height,Images.BGBM.Canvas.Handle,Left,Top,SRCCOPY);
    FillAlphaBM(Picture.Bitmap,CSkin.ColTitleBG,CSkin.TitleBGAlpha);
  end;
  Images.WriteMoeString(MusicTitleImg.Picture.Bitmap,0,0,-1,MusicTitle.Text,CSkin.dwTitleText,False,MusicTitle.ESCMode,MainINI.TitleFontName);
  MusicTitleImg.Refresh;

  Compact.DrawTitle;
end;

procedure TMain.FileGridDblClick(Sender: TObject);
var
  SelectItem:TFilesItem;
begin
  if Application.Title='MDXClose' then exit;

  if CurrentFiles.GetCursorIndex<0 then exit;

  CurrentFiles.GetItem(CurrentFiles.GetCursorIndex,SelectItem);

  case SelectItem.Attr of
    ir_None:  begin end;
    ir_Drive: MainFileCtl.ChangeDrive(SelectItem.Name);
    ir_Dir:   MainFileCtl.ChangeDir(SelectItem.Name);
    ir_File:  MainFileCtl.ExecutePlayFile(SelectItem.Name,False);
    else      begin end;
  end;
end;

procedure TMain.FileGridTimerTimer(Sender: TObject);
begin
  if Application.Title='MDXClose' then exit;
  MainFileCtl.FileGridTimerProcess;
end;

procedure TMain.ChangeLoopMax(vector:integer);
begin
  with MainINI do begin
    LoopMax:=LoopMax+vector;
    if LoopMax<=1 then LoopMax:=1;
    if LoopMax>=99 then LoopMax:=99;
    Func.SetInfo('',LoopMax);
    Func.Draw;
  end;
end;

procedure TMain.VolumeBarImgRefresh;
var
  Width,Height:integer;
  Vol:LongInt;
  x,y:integer;
  pBM,pNegaBar,pPosiBar:PRGB;
  PosiAlpha,NegaAlpha:integer;
begin
  Width:=64;
  Height:=VolumeBarImg.Height;

  Vol:=sdGetTotalVolume;
  Vol:=Vol div 32; // Max.2048 -> Max.64
  if Vol<0 then Vol:=0;
  if Vol>Width then Vol:=Width;

  NegaAlpha:=CSkin.PlayCntVolumeBarNegaAlpha;
  PosiAlpha:=CSkin.PlayCntVolumeBarPosiAlpha;

  BitBlt(VolumeBarImg.Canvas.Handle,0,0,Width,Height,Images.BGBM.Canvas.Handle,VolumeBarImg.Left,VolumeBarImg.Top,SRCCOPY);

  for y:=0 to Height-1 do begin
    pBM:=VolumeBarImg.Picture.Bitmap.ScanLine[y];
    pNegaBar:=@Images.VolumeBarBMEx.NegaPtr[y][0];
    pPosiBar:=@Images.VolumeBarBMEx.PosiPtr[y][0];
    for x:=0 to Width-1 do begin
      if x<=vol then begin
        RGBModulateVar(pBM^,pPosiBar^,PosiAlpha);
        end else begin
        RGBModulateVar(pBM^,pNegaBar^,NegaAlpha);
      end;
      inc(pBM);
      inc(pNegaBar);
      inc(pPosiBar);
    end;
  end;

  VolumeBarImg.Refresh;
end;

procedure TMain.VolumeBarImgMouseMove(Sender: TObject; Shift: TShiftState;
  X, Y: Integer);
begin
  if Application.Title='MDXClose' then exit;
  if Shift=[ssLeft] then begin
    if x<0 then x:=0;
    if 256<x then x:=256;
    MainINI.TotalVolume:=x*32; // max.8192
    sdSetTotalVolume(MainINI.TotalVolume);
    VolumeBarImgRefresh;
    FormPaintVolumeTempo;
  end;
end;

procedure TMain.VolumeBarImgMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  if Application.Title='MDXClose' then exit;
  case Button of
    mbRight: MainINI.TotalVolume:=1024;
    mbLeft: begin
      if x<0 then x:=0;
      if 256<x then x:=256;
      MainINI.TotalVolume:=x*32;
    end;
  end;

  sdSetTotalVolume(MainINI.TotalVolume);
  VolumeBarImgRefresh;
  FormPaintVolumeTempo;
end;

procedure TMain.ApplicationActive(Sender: TObject);
begin
  if Main.Visible=False then exit;
  if BootShowing=True then exit;

  if isCompactWindow=False then Vis.ClearImage;
  with TitleBarImg do begin
    BitBlt(Canvas.Handle,0,0,Width,Height,Images.TitleBarBMEx.PosiBM.Canvas.Handle,0,0,SRCCOPY);
    Refresh;
  end;
end;

procedure TMain.ApplicationDeactive(Sender: TObject);
begin
  if Main.Visible=False then exit;
  if BootShowing=True then exit;

  if isCompactWindow=False then Vis.ClearImage;
  with TitleBarImg do begin
    BitBlt(Canvas.Handle,0,0,Width,Height,Images.TitleBarBMEx.NegaBM.Canvas.Handle,0,0,SRCCOPY);
    Refresh;
  end;
end;

procedure TMain.RewriteTimerTimer(Sender: TObject);
begin
  if Application.Title='MDXClose' then exit;
  // メッセージ強制送受信用タイマー
  RewriteImage;
end;

var
  LastTickCount:dword;

procedure TMain.RewriteImage;
var
  tick:dword;
  RewriteSystemOnly:boolean;
  procedure ProcessKDD;
  var
    DispClock:dword;
  begin
    if KDDLoaded=True then begin
      if (sdGetDriverMode=DriverModeMXDRVm) or (sdGetDriverMode=DriverModeMXDRVg) then begin
        if MainINI.UseKDD=True then begin
          DispClock:=Vis.GetDispClock;
          if ((DispClock<>0) and (DispClock<$ffff)) then begin
            KDD.Interrupt(Vis.GetKDDID,DispClock,True);
          end;
        end;
      end;
    end;
  end;
  procedure SeekBarRefresh;
  var
    x1,x2,DrawX:integer;
    MesureClock:integer;
    procedure DrawImage(var mstimg:TImage);
    begin
      with mstimg do begin
        BitBlt(Main.Canvas.Handle,Left,Top,Width,Height,Canvas.Handle,0,0,SRCCOPY);
      end;
    end;
  begin
    MesureClock:=integer(Vis.GetMesureClock);
    if MesureClock<=0 then begin
      DrawX:=PrevSeekX;
      end else begin
      DrawX:=integer(Vis.GetTotalClock)*SeekBarImg.Width div MesureClock;
    end;

    if DrawX<>PrevSeekX then begin
      if DrawX<PrevSeekX then begin
        x1:=DrawX;
        x2:=PrevSeekX;
        end else begin
        x1:=PrevSeekX;
        x2:=DrawX;
      end;
      if x1<DrawX then begin
        DrawSeekBar(x1,x2,True);
        end else begin
        DrawSeekBar(x1,x2,False);
      end;
      DrawImage(SeekBarImg);
      PrevSeekX:=DrawX;
    end;
  end;
begin
  if (timeGetTime-LastTickCount)<16 then exit;
  LastTickCount:=timeGetTime;

  if Main.Visible=False then exit;
  if MMoveFlag=True then exit;
  if FilereadBusyFlag=True then exit;

  tick:=timeGetTime-dword(NowDSoundSafeTime);
  if Vis.GetVisualPointer(tick)=False then begin
    exit;
  end;

  ProcessKDD;

  if NetRemote<>nil then begin
    if NetRemote.Connected=True then begin
      with NetRemote.StatusInfo do begin
        MemSync.BeginWrite;
        PlayTime:=Vis.GetPlayTime;
        DispClock:=Vis.GetDispClock;
        TotalClock:=Vis.GetTotalClock;
        MesureClock:=Vis.GetMesureClock;
        LoopCount:=Vis.GetLoopCount;
        TimerBCount:=Vis.GetTimerBCount;
        MemSync.EndWrite;
      end;
    end;
  end;

  if isCompactWindow then begin
    Compact.SetTime(Vis.GetPlayTime);
    Compact.DrawTime;
    exit;
  end;

  SeekBarRefresh;

  RewriteSystemOnly:=False;
  if (Application.Active=False) and (VisINI.AlreadyRefresh=False) then RewriteSystemOnly:=True;
  if sdGetQuietMode=True then RewriteSystemOnly:=True;

  Vis.RewriteImage(RewriteSystemOnly);
end;

procedure TMain.DrawSeekBar(x1,x2:integer;Enabled:boolean);
var
  Width:integer;
  x,y:integer;
  pBG,pBM,pBar:PRGB;
  Alpha:integer;
  xoff:integer;
begin
  if x2<=x1 then exit;

  Width:=SeekBarImg.Picture.Bitmap.Width;
  if x1<0 then x1:=0;
  if x2<0 then x2:=0;
  if Width<=x1 then x1:=Width-1;
  if Width<=x2 then x2:=Width-1;

  if Enabled=True then begin
    Alpha:=CSkin.PlayCntSeekBarPosiAlpha;
    end else begin
    Alpha:=CSkin.PlayCntSeekBarNegaAlpha;
  end;

  xoff:=SeekBarImg.Left+x1;

  for y:=0 to SeekBarImg.Height-1 do begin
    pBG:=@Images.BGPtr[SeekBarImg.Top+y][xoff];
    pBM:=SeekBarImg.Picture.Bitmap.ScanLine[y];
    inc(pBM,x1);
    if Enabled=True then begin
      pBar:=@Images.SeekBarBMEx.PosiPtr[y][0];
      end else begin
      pBar:=@Images.SeekBarBMEx.NegaPtr[y][0];
    end;
    for x:=x1 to x2-1 do begin
      pBM^:=RGBModulate(pBG^,pBar^,Alpha);
      inc(pBG);
      inc(pBM);
      inc(pBar);
    end;
  end;
end;

procedure TMain.RedrawSeekBar;
var
  DrawX:integer;
  MesureClock:integer;
begin
  MesureClock:=integer(Vis.GetMesureClock);
  if MesureClock<=0 then begin
    DrawX:=PrevSeekX;
    end else begin
    DrawX:=integer(Vis.GetTotalClock)*SeekBarImg.Width div MesureClock;
  end;

  DrawSeekBar(0,DrawX,True);
  DrawSeekBar(DrawX,SeekBarImg.Width,False);
  with SeekBarImg do begin
    BitBlt(Main.Canvas.Handle,Left,Top,Width,Height,Canvas.Handle,0,0,SRCCOPY);
  end;
  PrevSeekX:=DrawX;
end;

procedure TMain.NetStatusTimerTimer(Sender: TObject);
begin
  if (NetRemote<>nil) and (0=0) then begin
    if NetRemote.Connected=True then begin
      with NetRemote.StatusInfo do begin
        MemSync.BeginWrite;
        PlayFilename:=Main.gFileInfo.GetFullPath;
        PlayTitle:=Main.gFileInfo.GetCompactTitle;
        CurrentPath:=MainINI.CurrentFilePath;
        TotalVolume:=sdGetTotalVolume;
        TransTempo:=sdGetTransTempo;
        fPlay:=sdGetPlay;
        fPause:=sdGetPause;
        fStop:=sdGetStop;
        PlayMode:=MainINI.PlayMode;
        PlayIndex:=CurrentFiles.GetPlayIndex;
        MemSync.EndWrite;
      end;
    end;
  end;
end;

procedure TMain.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
var
  Find:char;
  NowIdx,Idx:LongInt;
  CommandIndex:integer;
  function SeekFind(idx:integer;FindChar:char):boolean;
  var
    TargetItem:TFilesItem;
    Target:char;
  begin
    Result:=False;
    CurrentFiles.GetItem(idx,TargetItem);
    if TargetItem.Attr=ir_File then begin
      Target:=TargetItem.Name[1];
      if ('A'<=Target) and (Target<='Z') then Target:=char(LongInt(Target)+(LongInt('a')-LongInt('A')));
      if Target=FindChar then begin
        CurrentFiles.SetCursorIndex(Idx);
        Result:=True;
      end;
    end;
  end;
begin
  if (Key=VK_F4) and (Shift=[ssAlt]) then begin
    Key:=0;
    Main.Close;
    exit;
  end;

  CommandIndex:=KeyDef.FindCommandIndexFromKey(Key,Shift);
  if CommandIndex<>-1 then begin
    KeyDef.ExecuteCommandIndex(CommandIndex);
    Key:=0;
    exit;
  end;

  Find:=Char(Key);
  if ('A'<=Find) and (Find<='Z') then
    Find:=char(LongInt(Find)+(LongInt('a')-LongInt('A')));

  if (('a'<=Find) and (Find<='z')) or (('0'<=Find) and (Find<='9')) then begin
    NowIdx:=CurrentFiles.GetCursorIndex+1;
    if NowIdx>=CurrentFiles.GetItemsCount then NowIdx:=0;

    for Idx:=NowIdx to CurrentFiles.GetItemsCount-1 do begin
      if SeekFind(idx,Find)=True then exit;
    end;

    for Idx:=0 to NowIdx do begin
      if SeekFind(idx,Find)=True then exit;
    end;
  end;
end;

procedure TMain.FormKeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if Key=VK_LEFT then begin
    TempoBarImgRefresh(0);
    Key:=0;
    exit;
  end;
  if Key=VK_RIGHT then begin
    TempoBarImgRefresh(0);
    Key:=0;
    exit;
  end;
end;

procedure TMain.MuteCheckImageMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  Ch:LongInt;
begin
  if Application.Title='MDXClose' then exit;

  Ch:=X div 18;
  if Ch>=16 then exit;

  if Button=mbLeft then sdToggleMute(Ch);

  if Button=mbRight then KeyDef.ExecuteCommand(DCT_MuteShowMenu);

  if Button=mbMiddle then begin
    if sdGetMute(Ch)=True then begin
      sdSetAllMute(True);
      sdSetMute(Ch,False);
      end else begin
      sdSetAllMute(False);
      sdSetMute(Ch,True);
    end;
    exit;
  end;
end;

procedure TMain.FileGridDrawCell(Sender: TObject; ACol, ARow: Integer;
  Rect: TRect; State: TGridDrawState);
var
  col:dword;
begin
  if Application.Title='MDXClose' then exit;
  if (gdFixed in State) then exit;

  with FileGrid.Canvas do begin
    Brush.Style:=bsSolid;
    if (gdSelected in State) then begin
      col:=CSkin.dwGridSelectBG;
      end else begin
      if ARow=CurrentFiles.GetPlayIndex then begin
        col:=CSkin.dwGridPlayBG;
        end else begin
        col:=CSkin.dwGridBG;
      end;
    end;
    Brush.Color:=col;
    FillRect(Rect);

    Brush.Color:=CSkin.dwGridBG;
    Pen.Color:=CSkin.dwGridLine;
    if (ARow mod 2)=0 then
      Pen.Style:=psDot
      else
      Pen.Style:=psSolid;
    MoveTo(Rect.Left,Rect.Bottom-1);
    LineTo(Rect.Right,Rect.Bottom-1);

    case CurrentFiles.GetItemAttr(ARow) of
      ir_None:  Font.Color:=CSkin.dwGridBG; // error
      ir_Drive: Font.Color:=CSkin.dwGridDrive;
      ir_Dir:   Font.Color:=CSkin.dwGridDir;
      ir_File:  Font.Color:=CSkin.dwGridFile;
      else      Font.Color:=CSkin.dwGridBG; // error
    end;

    Brush.Style:=bsClear;
    TextRect(Rect,Rect.Left+2,Rect.Top+1,CurrentFiles.GetItemViewStr(ARow,MainINI.CurrentFilePath));
  end;
end;

procedure TMain.TempoBarImgMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  if Application.Title='MDXClose' then exit;

  if (Button=mbLeft) or (Button=mbRight) then begin
    TempoBarImgRefresh(x-(TempoBarImg.Width div 2));
  end;
end;

procedure TMain.TempoBarImgMouseMove(Sender: TObject; Shift: TShiftState;
  X, Y: Integer);
begin
  if Application.Title='MDXClose' then exit;

  if (Shift=[ssLeft]) or (Shift=[ssRight]) then begin
    TempoBarImgRefresh(x-(TempoBarImg.Width div 2));
  end;
end;

procedure TMain.TempoBarImgMouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  if Application.Title='MDXClose' then exit;

  if Button=mbLeft then begin
    TempoBarImgRefresh(0);
  end;
end;

procedure TMain.TempoBarImgRefresh(Tempo:integer);
var
  Width,Height:integer;
  TempTempo:integer;
  x,y:integer;
  pBM,pNegaBar,pPosiBar:PRGB;
  PosiAlpha,NegaAlpha:integer;
begin
  Width:=64;
  Height:=TempoBarImg.Height;

  if Tempo<=-128 then Tempo:=-128;
  if 128<=Tempo then Tempo:=128;

  sdSetTransTempo(Tempo);
  FormPaintVolumeTempo;

  TempTempo:=Tempo+32;
  if TempTempo<0 then TempTempo:=0;
  if TempTempo>Width then TempTempo:=TempTempo;

  NegaAlpha:=CSkin.PlayCntTempoBarNegaAlpha;
  PosiAlpha:=CSkin.PlayCntTempoBarPosiAlpha;

  BitBlt(TempoBarImg.Canvas.Handle,0,0,Width,Height,Images.BGBM.Canvas.Handle,TempoBarImg.Left,TempoBarImg.Top,SRCCOPY);

  for y:=0 to Height-1 do begin
    pBM:=TempoBarImg.Picture.Bitmap.ScanLine[y];
    pNegaBar:=@Images.TempoBarBMEx.NegaPtr[y][0];
    pPosiBar:=@Images.TempoBarBMEx.PosiPtr[y][0];
    for x:=0 to Width-1 do begin
      if ((x<32) and (TempTempo<=x)) or ((x>=32) and (TempTempo>=x)) then begin
        RGBModulateVar(pBM^,pPosiBar^,PosiAlpha);
        end else begin
        RGBModulateVar(pBM^,pNegaBar^,NegaAlpha);
      end;
      inc(pBM);
      inc(pNegaBar);
      inc(pPosiBar);
    end;
  end;

  TempoBarImg.Refresh;
end;

procedure TMain.SpeanaModeRefresh;
begin
  SpeWaveLbl.Font.Color:=CSkin.dwMask;
  SpeBarLbl.Font.Color:=CSkin.dwMask;
  SpeScrLbl.Font.Color:=CSkin.dwMask;
  SpeLineLbl.Font.Color:=CSkin.dwMask;
  SpeVisSetLbl.Font.Color:=CSkin.dwBright;

  case VisINI.SpeanaMode of
    SpeanaModeWave: SpeWaveLbl.Font.Color:=CSkin.dwBright;
    SpeanaModeBar: SpeBarLbl.Font.Color:=CSkin.dwBright;
    SpeanaModeScr: SpeScrLbl.Font.Color:=CSkin.dwBright;
    SpeanaModeLine: SpeLineLbl.Font.Color:=CSkin.dwBright;
  end;
end;

procedure TMain.TitleBarImgMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  MMoveFlag:=False;

  if Button=mbRight then begin
    KeyDef.ExecuteCommand(DCT_ShowMainMenu);
    exit;
  end;

  if (TitleBarImg.Width-56)<=x then exit;

  if x<=17 then begin
    KeyDef.ExecuteCommand(DCT_ShowMainMenu);
    exit;
  end;

  MMoveFlag:=True;
  MMoveX:=X;
  MMoveY:=Y;
end;

procedure TMain.TitleBarImgMouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer);
var
  isDocking:boolean;
  wx,wy:integer;
  tagpos:TWindowPos;
begin
  if MMoveFlag=True then begin
    wx:=Main.Left+(X-MMoveX);
    wy:=Main.Top+(Y-MMoveY);
    MoveWindow(Main.Handle,wx,wy,Main.Width,Main.Height,True);
    dx3dChangePosition;
    if (isCompactWindow=True) and (FlortFile<>nil) then begin
      isDocking:=FlortFile.isDocking(FlortFile.Left,FlortFile.Top);
      if isDocking then begin
        tagpos.Left:=Main.Left;
        tagpos.Top:=Main.Top+Main.Height;
        tagpos.Width:=FlortFile.Width;
        tagpos.Height:=FlortFile.Height;
        with tagpos do begin
          MoveWindow(FlortFile.Handle,Left,Top,Width,Height,True);
        end;
        with MainINI.CompactWindowFlortPos do begin
          Left:=FlortFile.Left;
          Top:=FlortFile.Top;
        end;
      end;
    end;
    end else begin
    MMoveX:=X;
    MMoveY:=Y;
  end;
end;

procedure TMain.TitleBarImgMouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var
  tbiWidth:integer;
begin
  if MMoveFlag=True then begin
    MMoveFlag:=False;
    exit;
  end;

  tbiWidth:=TitleBarImg.Width;

  if ((tbiWidth-56)<=x) and (x<=(tbiWidth-38)) then begin
    TrayIconDblClick(Sender);
    exit;
  end;
  if ((tbiWidth-38)<=x) and (x<=(tbiWidth-20)) then begin
    TitleBarScroll;
    exit;
  end;
  if (tbiWidth-20)<=x then begin
    Main.Close;
    exit;
  end;
end;

procedure TMain.TitleBarImgDblClick(Sender: TObject);
begin
  if (17<MMoveX) and (MMoveX<=(TitleBarImg.Width-35)) then TitleBarScroll;
end;

procedure TMain.TitleBarScroll;
begin
  MainINI.CompactWindowEnabled:=not MainINI.CompactWindowEnabled;
  SetCompactWindow;
end;

procedure TMain.SetCompactWindow;
var
  tagpos:TWindowPos;
begin
  if MainINI.CompactWindowEnabled=False then begin
    Main.Height:=MainINI.MainPos.Height;
    Main.Constraints.MinHeight:=400;
    CompactImg.Visible:=False;
    SetVisMode(VisINI.VisualMode);

    FileGrid.Parent:=Main;
    FileGridImg.Parent:=Main;
    if FlortFile<>nil then FlortFile.Visible:=False;
    Main.FormResize(nil);
    SetForegroundWindow(Main.Handle);
    SetActiveWindow(Main.Handle);
    Main.ActiveControl:=FileGrid;
    FuncImg.Visible:=True;
    end else begin
    Main.Constraints.MinHeight:=0;
    Main.Height:=TitleBarImg.Top+TitleBarImg.Height+CompactImg.Height;
    CompactImg.Top:=TitleBarImg.Top+TitleBarImg.Height;
    Compact.DrawAll;
    CompactImg.Visible:=True;
    dx3dSetVisible(False);

    if FlortFile=nil then begin
      Application.CreateForm(TFlortFile,FlortFile);
      FlortFile.LoadSkin;
    end;
    tagpos:=MainINI.CompactWindowFlortPos;
    AdjustWindowSize(Screen.Width,Screen.Height,tagpos);
    with tagpos do begin
      MoveWindow(FlortFile.Handle,Left,Top,Width,Height,True);
    end;
    FlortFile.Color:=CSkin.dwEtcBG;
    FileGrid.Parent:=FlortFile;
    FileGridImg.Parent:=FlortFile;
    FlortFile.FormResize(nil);
    FlortFile.Visible:=MainINI.CompactWindowFlortEnabled;
    FuncImg.Visible:=False;
  end;

end;

function TMain.isCompactWindow:boolean;
begin
  Result:=MainINI.CompactWindowEnabled;
end;

procedure TMain.SpeWaveLblClick(Sender: TObject);
begin
  VisINI.SpeanaMode:=SpeanaModeWave;
  Vis.ClearImage;
  SpeanaModeRefresh;
end;

procedure TMain.SpeBarLblClick(Sender: TObject);
begin
  VisINI.SpeanaMode:=SpeanaModeBar;
  Vis.ClearImage;
  SpeanaModeRefresh;
end;

procedure TMain.SpeScrLblClick(Sender: TObject);
begin
  VisINI.SpeanaMode:=SpeanaModeScr;
  Vis.ClearImage;
  SpeanaModeRefresh;
end;

procedure TMain.SpeLineLblClick(Sender: TObject);
begin
  VisINI.SpeanaMode:=SpeanaModeLine;
  Vis.ClearImage;
  SpeanaModeRefresh;
end;

procedure TMain.SpeVisSetLblClick(Sender: TObject);
begin
  KeyDef.ExecuteCommand(DCT_ShowVisualMenu);
end;

procedure TMain.SeekBarImgMouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  if Application.Title='MDXClose' then exit;
  if sdEnd=True then exit;
  if (x<0) or (SeekBarImg.Width<x) then exit;

  if Main.KDDLoaded=True then begin
    if (sdGetDriverMode=DriverModeMXDRVm) or (sdGetDriverMode=DriverModeMXDRVg) then begin
      if MainINI.UseKDD=True then begin
        exit;
      end;
    end;
  end;

  RewriteTimer.Enabled:=False;
  sdSeek(x*integer(Vis.GetMesureClock) div SeekBarImg.Width);
  RewriteTimer.Enabled:=True;
end;

procedure TMain.SetVisMode(_VisualMode:integer);
begin
  VisINI.VisualMode:=_VisualMode;

  if (VisINI.VisualMode<>VisualModeKeyboard) and (VisINI.VisualMode<>VisualModeSonar) and (VisINI.VisualMode<>VisualModeMDXDis) then begin
    dx3dLoadWindow;
    dx3dDDVisParamInit;
    dx3dSetVisible(True);
    end else begin
    dx3dSetVisible(False);
    Vis.ClearImage;
  end;

end;

type
  TNetPrg=record
    Title,Status:string;
    Position,Max:integer;
  end;

var
  NetPrg:TNetPrg;

procedure NetPrg_Draw(Img:TImage);
var
  Width,Height:integer;
  TempX:integer;
  x,y:integer;
  pBM,pNegaBar,pPosiBar:PRGB;
  PosiAlpha,NegaAlpha:integer;
begin
  MakeBlankImg(Img,pf24bit);
  with Img do begin
    BitBlt(Canvas.Handle,0,0,Width,Height,Images.BGBM.Canvas.Handle,Left,Top,SRCCOPY);
  end;
  FillAlphaBM(Img.Picture.Bitmap,CSkin.ColNetPrgBG,CSkin.NetPrgBGAlpha);

  DrawFlameBitmap(Img.Picture.Bitmap,CSkin.ColNetPrgFrameBright,CSkin.ColNetPrgFrameMask);

  Img.Canvas.Font.Name:='Terminal';
  Img.Canvas.Font.Height:=-13;
  Img.Canvas.Font.Color:=rgb2dword(CSkin.ColNetPrgText);
  Img.Canvas.Brush.Style:=bsClear;

  Img.Canvas.TextOut(8,6,NetPrg.Title);
  Img.Canvas.TextOut(8,44,NetPrg.Status);

  Width:=Images.NetPrgBarBMEx.Width;
  Height:=Images.NetPrgBarBMEx.Height;

  TempX:=(Width*NetPrg.Position) div NetPrg.Max;

  NegaAlpha:=CSkin.NetPrgBarNegaAlpha;
  PosiAlpha:=CSkin.NetPrgBarPosiAlpha;

  for y:=0 to Height-1 do begin
    pBM:=Img.Picture.Bitmap.ScanLine[24+y];
    inc(pBM,8);
    pNegaBar:=@Images.NetPrgBarBMEx.NegaPtr[y][0];
    pPosiBar:=@Images.NetPrgBarBMEx.PosiPtr[y][0];
    for x:=0 to Width-1 do begin
      if x<=TempX then begin
        RGBModulateVar(pBM^,pPosiBar^,PosiAlpha);
        end else begin
        RGBModulateVar(pBM^,pNegaBar^,NegaAlpha);
      end;
      inc(pBM);
      inc(pNegaBar);
      inc(pPosiBar);
    end;
  end;
end;

procedure TMain.onNetworkProgressStart(msg:string);
begin
  NetPrg.Title:=msg;
  NetPrg.Status:='Standby...';
  NetPrg.Position:=0;
  NetPrg.Max:=1;

  NetPrgImg.Left:=NetPrgPos.Left;
  NetPrgImg.Top:=NetPrgPos.Top;
  NetPrgImg.Width:=NetPrgPos.Width;
  NetPrgImg.Height:=NetPrgPos.Height;

  NetPrg_Draw(NetPrgImg);
  NetPrgImg.Visible:=True;
  NetPrgImg.Refresh;
  Main.Update;
end;

procedure TMain.onNetworkProgressRefresh(RefStatus,RefProgress:boolean;Status:string;Size,Pos:integer);
begin
  if RefStatus=True then begin
    NetPrg.Status:=Status;
  end;

  if RefProgress=True then begin
    if Size=0 then begin
      NetPrg.Position:=0;
      NetPrg.Max:=1;
      end else begin
      NetPrg.Position:=Pos;
      NetPrg.Max:=Size;
    end;
  end;

  NetPrg_Draw(NetPrgImg);
  NetPrgImg.Refresh;
  Main.Update;
end;

procedure TMain.onNetworkProgressEnd;
begin
  NetPrgImg.Visible:=False;
  Main.Update;
end;

procedure TMain.FileGridMouseWheelDown(Sender: TObject; Shift: TShiftState;
  MousePos: TPoint; var Handled: Boolean);
begin
  if Application.Title='MDXClose' then exit;
  Handled:=True;
  CurrentFiles.MouseWheel(1,Shift);
end;

procedure TMain.FileGridMouseWheelUp(Sender: TObject; Shift: TShiftState;
  MousePos: TPoint; var Handled: Boolean);
begin
  if Application.Title='MDXClose' then exit;
  Handled:=True;
  CurrentFiles.MouseWheel(-1,Shift);
end;

procedure TMain.TrayIconDblClick(Sender: TObject);
begin
  KeyDef.ExecuteCommand(DCT_EmulateTrayIcon_DoubleClick);
end;

procedure TMain.TrayIconMouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  if Button=mbLeft then begin
    KeyDef.ExecuteCommand(DCT_EmulateTrayIcon_LeftButtonClick);
  end;

  if Button=mbRight then begin
    KeyDef.ExecuteCommand(DCT_EmulateTrayIcon_RightButtonClick);
  end;
end;

procedure TMain.PlayButtonsCallback;
begin
  if sdGetStop=True then begin
    Func.SetItemEnabled(FuncNo_F3,True);
    Func.SetItemEnabled(FuncNo_F2,False);
    Func.SetItemText(FuncNo_F2,'PLAY');
    end else begin
    Func.SetItemEnabled(FuncNo_F3,False);
    Func.SetItemEnabled(FuncNo_F2,True);
    if sdGetPause=False then begin
      Func.SetItemText(FuncNo_F2,'PLAY');
      end else begin
      Func.SetItemText(FuncNo_F2,'PAUSE');
    end;
  end;
  Func.Draw;

  case MainINI.PlayMode of
    PlayMode_Single:    Func.SetItemText(FuncNo_F4,'Single');
    PlayMode_ALL:       Func.SetItemText(FuncNo_F4,'ALL');
    PlayMode_ALLRepeat: Func.SetItemText(FuncNo_F4,'ALLRep');
    PlayMode_Random:    Func.SetItemText(FuncNo_F4,'Random');
    PlayMode_None:      Func.SetItemText(FuncNo_F4,'None');
    else                Func.SetItemText(FuncNo_F4,'Error');
  end;
  Func.Draw;
end;

procedure TMain.FormPaint(Sender: TObject);
var
  pos:TWindowPos;
begin
  if Application.Title='MDXClose' then exit;

  with Main do begin
    DrawFlameCanvas(Canvas,ClientWidth,ClientHeight,CSkin.ColFrameBright,CSkin.ColFrameMask);
  end;

  if isCompactWindow=True then exit;

  with Main.Canvas do begin
    pos.Left:=2;
    pos.Top:=2;
    pos.Width:=Main.ClientWidth-pos.Left-2;
//    pos.Height:=Main.ClientHeight-pos.Top-2;
    pos.Height:=FileGrid.Top;
    Images.ScreenRefresh(pos);
  end;
end;

procedure TMain.RefreshScreenComponents;
var
  x1,y1,x2,y2:integer;
begin
  Images.WriteSmallStringToScreen(371, 30,CSkin.ColBright,'X68Sound by Puusan. WinFMP&PMDWin by C60. SNESAPU');

  Images.WriteSmallStringToScreen(299, 30,CSkin.ColPlayCntVolumeText,'Total Volume');
  Images.WriteSmallStringToScreen(299, 64,CSkin.ColPlayCntTempoText,'Trans TEMPO');

  Images.WriteSmallStringToScreen(371, 46,CSkin.ColBright,'| Play Time');
  Images.WriteSmallStringToScreen(371, 54,CSkin.ColBright,'| (MIN:SEC)');
  Images.WriteSmallStringToScreen(567, 46,CSkin.ColBright,'| LOOP');
  Images.WriteSmallStringToScreen(567, 54,CSkin.ColBright,'| COUNT');
  Images.WriteSmallStringToScreen(371, 70,CSkin.ColBright,'| TimerB');
  Images.WriteSmallStringToScreen(371, 78,CSkin.ColBright,'| TotalClock');
  Images.WriteSmallStringToScreen(534, 70,CSkin.ColBright,'| TimerB');
  Images.WriteSmallStringToScreen(534, 78,CSkin.ColBright,'|  CYCLE');

  Images.WriteSmallStringToScreen(347,186,CSkin.ColMask,'Tr01');
  Images.WriteSmallStringToScreen(491,186,CSkin.ColMask,'Tr09');
  Images.WriteSmallStringToScreen(547,186,CSkin.ColBright,'VELOCITY GRAPHICS');

  Images.WriteSmallStringToScreen(547,106,CSkin.ColBright,'SPECTRUM ANALYZER');

  Images.WriteSmallStringToScreen(307,261,CSkin.ColWhite,' PANPOT');
  Images.WriteSmallStringToScreen(307,269,CSkin.ColWhite,' ON/OFF');
  Images.WriteSmallStringToScreen(307,277,CSkin.ColWhite,'PROGRAM');
  Images.WriteSmallStringToScreen(307,285,CSkin.ColWhite,'KEYCODE');

  Images.WriteSmallStringToScreen( 11,300,CSkin.ColWhite,'NOW PLAYING');
  Images.WriteSmallStringToScreen( 11,308,CSkin.ColWhite,' MUSIC DATA>');

  Images.WriteSmallStringToScreen(478,106,CSkin.ColBright,inttostr(NowDSoundRate)+'Hz');

  with Images.ScreenBM.Canvas do begin
    Pen.Color:=CSkin.dwMask;
    x1:=SpeFlamePos.Left;
    y1:=SpeFlamePos.Top;
    x2:=x1+SpeFlamePos.Width;
    y2:=y1+SpeFlamePos.Height;
    MoveTo(x1,y1);
    LineTo(x2,y1);
    LineTo(x2,y2);
    LineTo(x1,y2);
    LineTo(x1,y1);
  end;

  FormPaintDriverMode;
  FormPaintVolumeTempo;
end;

procedure TMain.FormPaintDriverMode;
var
  MXDRVCaption:string;
begin
  Images.WriteSmallStringToScreen(348,106,CSkin.ColBright,'Driver');

  if MXDRVgINI.Enabled=False then begin
    if MainINI.UseRomeo=False then begin
      MXDRVCaption:='MXDRVm';
      end else begin
      MXDRVCaption:='MXDRVr';
    end;
    end else begin
    MXDRVCaption:='MXDRVg';
  end;

  Images.WriteSmallStringToScreen(383,106,CSkin.ColMask,MXDRVCaption);
  Images.WriteSmallStringToScreen(418,106,CSkin.ColMask,'FMP');
  Images.WriteSmallStringToScreen(438,106,CSkin.ColMask,'PMD');
  Images.WriteSmallStringToScreen(458,106,CSkin.ColMask,'SPC');

  case sdGetDriverMode of
    DriverModeUnknown: begin end;
    DriverModeMXDRVm: Images.WriteSmallStringToScreen(383,106,CSkin.ColBright,MXDRVCaption);
    DriverModeMXDRVg: Images.WriteSmallStringToScreen(383,106,CSkin.ColBright,MXDRVCaption);
    DriverModeFMP:    Images.WriteSmallStringToScreen(418,106,CSkin.ColBright,'FMP');
    DriverModePMD:    Images.WriteSmallStringToScreen(438,106,CSkin.ColBright,'PMD');
    DriverModeSPC:    Images.WriteSmallStringToScreen(458,106,CSkin.ColBright,'SPC');
    else begin end;
  end;
end;

procedure TMain.FormPaintVolumeTempo;
var
  Tempo:integer;
  msg:string;
begin
  Images.WriteSmallStringToScreen(299, 38,CSkin.ColPlayCntVolumeText,Format('%5d /%5d',[sdGetTotalVolume,1024]));

  Tempo:=sdGetTransTempo;
  msg:='';
  if Tempo<0 then msg:=' -';
  if Tempo=0 then msg:='  ';
  if Tempo>0 then msg:=' +';
  msg:=msg+Format('%3d /  %3d',[abs(Tempo),128]);

  Images.WriteSmallStringToScreen(299, 72,CSkin.ColPlayCntTempoText,msg);
end;

procedure TMain.IdTCPServerConnect(AThread: TIdPeerThread);
begin
  NetRemote.onConnect(AThread);
end;

procedure TMain.IdTCPServerDisconnect(AThread: TIdPeerThread);
begin
  NetRemote.onDisconnect;
end;

procedure TMain.IdTCPServerCmdHnd(var ASender:TIdCommand;resstr:string);
var
  ss:TStrings;
begin
  ss:=TStringList.Create;
  ss.Add(resstr);
  ASender.SetResponse(ss);
  ss.Free;
  ASender.Reply.SetReply(NetRemote.resCode,NetRemote.resText);
end;

procedure TMain.IdTCPServerCmdHnd_GETVERSIONCommand(ASender: TIdCommand);
begin
  IdTCPServerCmdHnd(ASender,NetRemote.CmdHnd_GETVERSION(ASender.UnparsedParams));
end;

procedure TMain.IdTCPServerCmdHnd_LOGINCommand(ASender: TIdCommand);
begin
  IdTCPServerCmdHnd(ASender,NetRemote.CmdHnd_LOGIN(ASender.UnparsedParams));
end;

procedure TMain.IdTCPServerCmdHnd_LOGOUTCommand(ASender: TIdCommand);
begin
  IdTCPServerCmdHnd(ASender,NetRemote.CmdHnd_LOGOUT);
end;

procedure TMain.IdTCPServerCmdHnd_GETSTATUSCommand(ASender: TIdCommand);
begin
  IdTCPServerCmdHnd(ASender,NetRemote.CmdHnd_GETSTATUS(ASender.UnparsedParams));
end;

procedure TMain.IdTCPServerCmdHnd_CHDRVCommand(ASender: TIdCommand);
begin
  IdTCPServerCmdHnd(ASender,NetRemote.CmdHnd_CHDRV(ASender.UnparsedParams));
end;

procedure TMain.IdTCPServerCmdHnd_CHDIRCommand(ASender: TIdCommand);
begin
  IdTCPServerCmdHnd(ASender,NetRemote.CmdHnd_CHDIR(ASender.UnparsedParams));
end;

procedure TMain.IdTCPServerCmdHnd_EXECUTECommand(ASender: TIdCommand);
begin
  IdTCPServerCmdHnd(ASender,NetRemote.CmdHnd_EXECUTE(ASender.UnparsedParams));
end;

procedure TMain.IdTCPServerCmdHnd_GETDIRCommand(ASender: TIdCommand);
begin
  IdTCPServerCmdHnd(ASender,NetRemote.CmdHnd_GETDIR);
end;

procedure TMain.IdTCPServerCmdHnd_SETSEEKCommand(ASender: TIdCommand);
begin
  IdTCPServerCmdHnd(ASender,NetRemote.CmdHnd_SETSEEK(ASender.UnparsedParams));
end;

procedure TMain.IdTCPServerCmdHnd_PLAYCommand(ASender: TIdCommand);
begin
  IdTCPServerCmdHnd(ASender,NetRemote.CmdHnd_PLAY(ASender.UnparsedParams));
end;

procedure TMain.IdTCPServerCmdHnd_SETTOTALVOLUMECommand(
  ASender: TIdCommand);
begin
  IdTCPServerCmdHnd(ASender,NetRemote.CmdHnd_SETTOTALVOLUME(ASender.UnparsedParams));
end;

procedure TMain.IdTCPServerCmdHnd_SETTRANSTEMPOCommand(
  ASender: TIdCommand);
begin
  IdTCPServerCmdHnd(ASender,NetRemote.CmdHnd_SETTRANSTEMPO(ASender.UnparsedParams));
end;

procedure TMain.IdTCPServerCmdHnd_SETPLAYMODECommand(ASender: TIdCommand);
begin
  IdTCPServerCmdHnd(ASender,NetRemote.CmdHnd_SETPLAYMODE(ASender.UnparsedParams));
end;

procedure TMain.NextTimerFromPCMOutTimer(Sender: TObject);
begin
  NextTimerFromPCMOut.Enabled:=False;
  MainFileCtl.NextPlay(0);
end;

procedure TMain.PCMOutMenuCallback;
begin
  Images.WriteSmallStringToScreen(478,106,CSkin.ColBright,inttostr(NowDSoundRate)+'Hz');
  Func.SetItemText(FuncNo_F5,inttostr(NowDSoundRate));
  Func.Draw;
  Vis.ClearImage;
end;

{$IFNDEF Enable_EDisk1}
procedure TMain.BootED1TimerTimer(Sender: TObject);
begin
  BootED1Timer.Enabled:=False;
end;
{$ENDIF}

{$IFDEF Enable_EDisk1}
procedure TMain.BootED1TimerTimer(Sender: TObject);
var
  date:string;
  msg:string;
begin
  BootED1Timer.Enabled:=False;
  date:=formatdatetime('yyyymmdd',now);
  if (date<>'20040213') and (date<>'20040214') then exit;

  if (random(100)<=2) or (ParamStr(1)='boot_edisk1') then begin
    msg:='唐突ですが、イベントディスクを起動してもよろしいですか？'+CRLF;
    msg:=msg+'注：すっごく重いです。Celeron-750MHz以上くらいないとキツいです…。';
    if MessageDlg(msg,mtConfirmation,[mbYes,mbNo],0)=mrNo then exit;
    sdSetQuietMode(True);
    ShowMessage('MDXWin側のビジュアルエフェクトを一時OFFにしました。'+CRLF+'[D_OFF]ボタンを押すと解除できますが、ウィンドウを閉じると自動的にONに戻ります。');
    Application.CreateForm(TED1, ED1);
    ED1.Visible:=True;
  end;
end;
{$ENDIF}

procedure TMain.MusicTitleImgClick(Sender: TObject);
begin
  KeyDef.ExecuteCommand(DCT_ShowTitle);
end;

procedure TMain.DriveMenu_Popup;
var
  pos:TPoint;
begin
  GetCursorPos(pos);
  DriveMenu.Popup(pos.X,pos.Y);
end;

procedure TMain.ReloadSkin(SKIFilename:string);
begin
  if SKIFilename<>'' then MainINI.SKIFilename:=SKIFilename;

  CSkin.LoadSkin(MainINI.SKIFilename);
  Main.Color:=CSkin.dwBG;

  Images.LoadSkin(CSkin);

  if Main.WavesFormLoaded=True then WavesOut.LoadSkin;
  if Main.NetFindLoaded=True then NetFind.LoadSkin;
  if Main.NetRankLoaded=True then NetRank.LoadSkin;
  if Main.NetVoteLoaded=True then NetVote.LoadSkin;

  GridScroll_LoadSkin(CSkin);
  GridScrollAll_RedrawAll;

  Func.AllRedraw(MainINI.LoopMax);
  FileGrid.Color:=CSkin.dwGridBG;
  FileGrid.Refresh;
  TempoBarImgRefresh(sdGetTransTempo);
  VolumeBarImgRefresh;
  FormPaintVolumeTempo;
  RedrawSeekBar;
  SpeanaModeRefresh;
  RefreshScreenComponents;
  Compact.DrawAll;
  SetMusicTitle('',ESCModeNone);
  if FlortFile<>nil then FlortFile.LoadSkin;
  Vis.ClearImage;
  ApplicationActive(nil);
  Main.Refresh;
end;

procedure TMain.SKIOpenDlgShow(Sender: TObject);
begin
  SKIDlg.Show;
end;

procedure TMain.SKIOpenDlgClose(Sender: TObject);
begin
  SKIDlg.Close;
end;

procedure TMain.SKIOpenDlgSelectionChange(Sender: TObject);
begin
  SKIDlg.LoadID(SKIOpenDlg.FileName);
end;

end.
