//  ======================================================================
//               THIS IMPLEMENTATION WRITTEN BY KK - SPRING 1998
//  ======================================================================

#include "winplus.h"
#pragma  hdrstop

CFileOpenDialog::CFileOpenDialog(HWND hwnd, char *title, char *filter,
  char *dirname, char *filename)
{
  if(filename) lstrcpy(File,filename); else File[0]=0;
  if(dirname) lstrcpy(DirName,dirname); else lstrcpy(DirName,".");
  memset(&ofn, 0, sizeof(OPENFILENAME));
  ofn.lStructSize = sizeof(OPENFILENAME);
  if(filter) ofn.lpstrFilter = filter;
    else ofn.lpstrFilter = "Все файлы (*.*)\0*.*\0\0";
  ofn.nFilterIndex = 1;
  ofn.lpstrFile= File;
  ofn.nMaxFile = sizeof(File);
  ofn.lpstrFileTitle = FileTitle;
  ofn.nMaxFileTitle = sizeof(FileTitle);
  ofn.lpstrInitialDir = DirName;
  if(title) ofn.lpstrTitle = title;
  else ofn.lpstrTitle = "Открытие файла:";
  ofn.hwndOwner = hwnd;
  ofn.Flags = OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST|OFN_HIDEREADONLY;
  bLastError = TRUE;
}

void CFileOpenDialog::DoModal()
{
  bLastError = !GetOpenFileName(&ofn);
}

CFileSaveDialog::CFileSaveDialog(HWND hwnd, char *title, char *filter,
  char *dirname, char *filename)
{
  if(filename) lstrcpy(File,filename); else File[0]=0;
  if(dirname) lstrcpy(DirName,dirname); else lstrcpy(DirName,".");
  memset(&ofn, 0, sizeof(OPENFILENAME));
  ofn.lStructSize = sizeof(OPENFILENAME);
  if(filter) ofn.lpstrFilter = filter;
    else ofn.lpstrFilter = "Все файлы (*.*)\0*.*\0\0";
  ofn.nFilterIndex = 1;
  ofn.lpstrFile= File;
  ofn.nMaxFile = sizeof(File);
  ofn.lpstrFileTitle = FileTitle;
  ofn.nMaxFileTitle = sizeof(FileTitle);
  ofn.lpstrInitialDir = DirName;
  if(title) ofn.lpstrTitle = title;
  else ofn.lpstrTitle = "Сохранить как:";
  ofn.hwndOwner = hwnd;
  ofn.Flags = OFN_PATHMUSTEXIST|OFN_HIDEREADONLY;
  bLastError = TRUE;
}

void CFileSaveDialog::DoModal()
{
  bLastError = !GetSaveFileName(&ofn);
  if(!bLastError)
  {
    char drv[16], dir[_MAX_DIR+16], nam[_MAX_FNAME+16], ext[_MAX_EXT+16];
    _splitpath(File,drv,dir,nam,ext);
    if(strlen(ext)) return;
    int i=1;
    int fi;
    char *ptr = (char *)ofn.lpstrFilter, str[_MAX_EXT+16];
    for(;;i++)
    {
      fi=0;
      if(!ptr[fi]) return;
      while(ptr[fi]) fi++;
      ptr+=fi+1;
      fi=0;
      if(!ptr[fi]) return;
      while(ptr[fi]) { str[fi]=ptr[fi]; fi++; }
      ptr+=fi+1;
      str[fi]=0;
      if(i==ofn.nFilterIndex)
      {
        _splitpath(str,NULL,NULL,NULL,ext);
        int validext=1;
        fi=0;
        while(ext[fi])
        {
          if(ext[fi]=='*'||ext[fi]=='!')
          {
            validext=0;
            break;
          }
          fi++;
        }
        if(validext) _makepath(File,drv,dir,nam,ext);
        return;
      }
    }
  }
}
