Example #1
1
bool WDL_ChooseFileForSave(HWND parent, 
                                      const char *text, 
                                      const char *initialdir, 
                                      const char *initialfile, 
                                      const char *extlist,
                                      const char *defext,
                                      bool preservecwd,
                                      char *fn, 
                                      int fnsize,
                                      const char *dlgid,
                                      void *dlgProc,
#ifdef _WIN32
                                      HINSTANCE hInstance
#else
                                      struct SWELL_DialogResourceIndex *reshead
#endif
                                      )
{
  char cwd[2048];
  GetCurrentDirectory(sizeof(cwd),cwd);

#ifdef _WIN32
  char temp[4096];
  memset(temp,0,sizeof(temp));
  if (initialfile) lstrcpyn_safe(temp,initialfile,sizeof(temp));
  WDL_fixfnforopenfn(temp);

#ifdef WDL_FILEBROWSE_WIN7VISTAMODE
  {
    Win7FileDialog fd(text, 1);
    if(fd.inited())
    {
      fd.addOptions(FOS_DONTADDTORECENT);
      //vista+ file open dialog
      char olddir[2048];
      GetCurrentDirectory(sizeof(olddir),olddir);

      fd.setFilterList(extlist);
      if (defext) 
      {
        fd.setDefaultExtension(defext);

        int i = 0;
        const char *p = extlist;
        while(*p)
        {
          if(*p) p+=strlen(p)+1;
          if(!*p) break;
          if(stristr(p, defext)) 
          {
            fd.setFileTypeIndex(i+1);
            break;
          }
          i++;
          p+=strlen(p)+1;
        }
      }
      fd.setFolder(initialdir?initialdir:olddir, 0);
      if(initialfile) 
      {
        //check for folder name
        if (WDL_remove_filepart(temp))
        {
          //folder found
          fd.setFolder(temp, 0);
          fd.setFilename(temp + strlen(temp) + 1);
        }
        else
          fd.setFilename(*temp ? temp : initialfile);
      }
      fd.setTemplate(hInstance, dlgid, (LPOFNHOOKPROC)dlgProc);
      
      if(fd.show(parent))
      {
        //ifilesavedialog saves the last folder automatically
        fd.getResult(fn, fnsize);
        
        if (preservecwd) SetCurrentDirectory(olddir);
        return true;
      }
      
      if (preservecwd) SetCurrentDirectory(olddir);
      return NULL;
    }
  }
#endif


  OPENFILENAME l={sizeof(l),parent, hInstance, extlist, NULL,0, 0, temp, sizeof(temp)-1, NULL, 0, initialdir&&initialdir[0] ? initialdir : cwd, text, 
                  OFN_HIDEREADONLY|OFN_EXPLORER|OFN_OVERWRITEPROMPT,0,0,defext, 0, (LPOFNHOOKPROC)dlgProc, dlgid};

  if (hInstance&&dlgProc&&dlgid) l.Flags |= OFN_ENABLEHOOK|OFN_ENABLETEMPLATE|OFN_ENABLESIZING;
  if (preservecwd) l.Flags |= OFN_NOCHANGEDIR;

  if (!GetSaveFileName(&l)||!temp[0]) 
  {
    if (preservecwd) SetCurrentDirectory(cwd);
    return false;
  }
  if (preservecwd) SetCurrentDirectory(cwd);
  lstrcpyn_safe(fn,temp,fnsize);
  return true;

#else
  BrowseFile_SetTemplate(dlgid,(DLGPROC)dlgProc,reshead);
  char if_temp[4096];
  if (initialfile && *initialfile) 
  {
    lstrcpyn_safe(if_temp,initialfile,sizeof(if_temp));
    WDL_fixfnforopenfn(if_temp);
    initialfile = if_temp;
  }
  else
  {
    if (defext && *defext == '.') initialfile = defext; // SWELL supports default extension in filename field
  }

  bool r = BrowseForSaveFile(text,initialdir,initialfile,extlist,fn,fnsize);

  if (preservecwd) SetCurrentDirectory(cwd);

  return r;
#endif
}
Example #2
1
INT_PTR CALLBACK DlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  static int ids[]={IDC_INFO,IDC_NSISICON,IDC_SZIPFRAME,IDC_BROWSE,IDC_ZIPFILE,IDC_ZIPINFO_SUMMARY,IDC_ZIPINFO_FILES,IDC_OFRAME,IDC_INAMEST,
                        IDC_INSTNAME,IDC_INSTPATH,IDC_OEFST,IDC_OUTFILE,IDC_BROWSE2,IDC_COMPRESSOR,IDC_ZLIB,IDC_BZIP2,IDC_LZMA,IDC_SOLID,IDC_INTERFACE,IDC_MODERNUI,IDC_CLASSICUI,IDC_UNICODE};
  static HICON hIcon=0;
  static HFONT hFont=0;
  switch (uMsg)
  {
    case WM_INITDIALOG:
      g_hwnd=hwndDlg;
      CheckDlgButton(hwndDlg,IDC_LZMA,BST_CHECKED);
      CheckDlgButton(hwndDlg,IDC_MODERNUI,BST_CHECKED);
      CheckDlgButton(hwndDlg,IDC_UNICODE,BST_CHECKED);
      SendDlgItemMessage(hwndDlg,IDC_INSTPATH,CB_ADDSTRING,0,(LPARAM)gp_poi);
      SendDlgItemMessage(hwndDlg,IDC_INSTPATH,CB_ADDSTRING,0,(LPARAM)_T("$TEMP"));
      SendDlgItemMessage(hwndDlg,IDC_INSTPATH,CB_ADDSTRING,0,(LPARAM)_T("$SYSDIR"));
      SendDlgItemMessage(hwndDlg,IDC_INSTPATH,CB_ADDSTRING,0,(LPARAM)_T("$WINDIR"));
      SendDlgItemMessage(hwndDlg,IDC_INSTPATH,CB_ADDSTRING,0,(LPARAM)_T("$DESKTOP"));
      SendDlgItemMessage(hwndDlg,IDC_INSTPATH,CB_ADDSTRING,0,(LPARAM)_T("$DESKTOP\\YourNameHere"));
      SendDlgItemMessage(hwndDlg,IDC_INSTPATH,CB_ADDSTRING,0,(LPARAM)_T("$PROGRAMFILES\\YourNameHere"));
      SendDlgItemMessage(hwndDlg,IDC_INSTPATH,CB_ADDSTRING,0,(LPARAM)_T("$STARTMENU"));
      SendDlgItemMessage(hwndDlg,IDC_INSTPATH,CB_ADDSTRING,0,(LPARAM)_T("$SMPROGRAMS"));

      SendDlgItemMessage(hwndDlg,IDC_INSTPATH,CB_ADDSTRING,0,(LPARAM)gp_winamp);
      SendDlgItemMessage(hwndDlg,IDC_INSTPATH,CB_ADDSTRING,0,(LPARAM)gp_winamp_plugins);
      SendDlgItemMessage(hwndDlg,IDC_INSTPATH,CB_ADDSTRING,0,(LPARAM)gp_winamp_vis);
      SendDlgItemMessage(hwndDlg,IDC_INSTPATH,CB_ADDSTRING,0,(LPARAM)gp_winamp_dsp);
      SendDlgItemMessage(hwndDlg,IDC_INSTPATH,CB_ADDSTRING,0,(LPARAM)gp_winamp_skins);

      SetDlgItemText(hwndDlg,IDC_INSTPATH,gp_poi);

      hIcon=LoadIcon(g_hInstance,MAKEINTRESOURCE(IDI_ICON1));
      SetClassLongPtr(hwndDlg,GCLP_HICON,(LONG_PTR)hIcon);

      hFont=CreateFont(15,0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,
              OUT_CHARACTER_PRECIS,
              CLIP_DEFAULT_PRECIS,
              DEFAULT_QUALITY,FIXED_PITCH|FF_DONTCARE,_T("Courier New"));
      SendDlgItemMessage(hwndDlg,IDC_OUTPUTTEXT,WM_SETFONT,(WPARAM)hFont,0);

      DragAcceptFiles(hwndDlg,TRUE);
    return 1;
    case WM_NCDESTROY:
      DeleteObject(hIcon); hIcon=0;
      DeleteObject(hFont); hFont=0;
    break;
    case WM_CLOSE:
      if (!g_hThread)
      {
        tempzip_cleanup(hwndDlg,0);
        EndDialog(hwndDlg,1);
      }
    break;
    case WM_NOTIFYENDCOMPILE:

      if (g_hThread)
      {
        if (!lParam) ShowWindow(GetDlgItem(hwndDlg,IDC_TEST),SW_SHOWNA);
        CloseHandle(g_hThread);
        g_hThread=0;
      }
      g_made=true;
      ShowWindow(GetDlgItem(hwndDlg,IDC_BACK),SW_SHOWNA);
      EnableWindow(GetDlgItem(hwndDlg,IDOK),1);
      if (nsifilename[0]) DeleteFile(nsifilename);
      nsifilename[0]=0;
    break;
    case WM_DROPFILES:
    {
      TCHAR dropped_file[MAX_PATH]=_T("");
      if (DragQueryFile((HDROP)wParam,(UINT)-1,NULL,0)==1)
      {
        DragQueryFile((HDROP)wParam,0,dropped_file,MAX_PATH);
        if (lstrlen(dropped_file)>0)
        {
          SetZip(hwndDlg,dropped_file);
        }
      }
      else
      {
        MessageBox(hwndDlg,_T("Dropping more than one zip file at a time is not supported"),g_errcaption,MB_OK|MB_ICONSTOP);
      }
      DragFinish((HDROP)wParam);
      return TRUE;
    }
    case WM_COMMAND:
      switch (LOWORD(wParam))
      {
        case IDC_BROWSE:
          if (!g_extracting) {
            OPENFILENAME l={sizeof(l),};
            TCHAR buf[1024];
            l.hwndOwner = hwndDlg;
            l.lpstrFilter = _T("ZIP Files\0*.zip\0All Files\0*.*\0");
            l.lpstrFile = buf;
            l.nMaxFile = 1023;
            l.lpstrTitle = _T("Open ZIP File");
            l.lpstrDefExt = _T("zip");
            l.lpstrInitialDir = NULL;
            l.Flags = OFN_HIDEREADONLY|OFN_EXPLORER|OFN_PATHMUSTEXIST;
            buf[0]=0;
            if (GetOpenFileName(&l))
            {
              SetZip(hwndDlg,buf);
            }
          }
        break;
        case IDC_BROWSE2:
          {
            OPENFILENAME l={sizeof(l),};
            TCHAR buf[1024];
            l.hwndOwner = hwndDlg;
            l.lpstrFilter = _T("Executables\0*.exe\0All Files\0*.*\0");
            l.lpstrFile = buf;
            l.nMaxFile = 1023;
            l.lpstrTitle = _T("Select Output EXE File");
            l.lpstrDefExt = _T("exe");
            l.lpstrInitialDir = NULL;
            l.Flags = OFN_HIDEREADONLY|OFN_EXPLORER;
            GetDlgItemText(hwndDlg,IDC_OUTFILE,buf,sizeof(buf));
            if (GetSaveFileName(&l))
            {
              SetDlgItemText(hwndDlg,IDC_OUTFILE,buf);
            }
          }
        break;
        case IDC_BACK:
          if (!g_hThread)
          {
            g_made=false;
            ShowWindow(GetDlgItem(hwndDlg,IDC_BACK),SW_HIDE);
            ShowWindow(GetDlgItem(hwndDlg,IDC_TEST),SW_HIDE);
            ShowWindow(GetDlgItem(hwndDlg,IDC_OUTPUTTEXT),SW_HIDE);
            {
              for (size_t x = 0; x < COUNTOF(ids); x ++)
                ShowWindow(GetDlgItem(hwndDlg,ids[x]),SW_SHOWNA);
              SetDlgItemText(hwndDlg,IDOK,_T("&Generate"));
              EnableWindow(GetDlgItem(hwndDlg,IDOK),1);
            }
          }
        break;
        case IDC_TEST:
          if (!g_hThread) {
            TCHAR buf[1024];
            GetDlgItemText(hwndDlg,IDC_OUTFILE,buf,COUNTOF(buf));
            ShellExecute(hwndDlg,_T("open"),buf,_T(""),_T(""),SW_SHOW);
          }
        break;
        case IDOK:
          if (!g_hThread)
          {
            if (!g_made)
            {
              if (IsDlgButtonChecked(hwndDlg,IDC_ZLIB))
                g_compressor = 1;
              if (IsDlgButtonChecked(hwndDlg,IDC_BZIP2))
                g_compressor = 2;
              if (IsDlgButtonChecked(hwndDlg,IDC_LZMA))
                g_compressor = 3;
              if (IsDlgButtonChecked(hwndDlg,IDC_SOLID))
                g_compressor_solid = 1;
              else
                g_compressor_solid = 0;
              g_mui=!IsDlgButtonChecked(hwndDlg,IDC_CLASSICUI);
              SetDlgItemText(g_hwnd, IDC_OUTPUTTEXT, _T(""));
              for (size_t x = 0; x < COUNTOF(ids); x ++)
                ShowWindow(GetDlgItem(hwndDlg,ids[x]),SW_HIDE);
              ShowWindow(GetDlgItem(hwndDlg,IDC_OUTPUTTEXT),SW_SHOWNA);
              SetDlgItemText(hwndDlg,IDOK,_T("&Close"));
              EnableWindow(GetDlgItem(hwndDlg,IDOK),0);

              makeEXE(hwndDlg);
            }
            else
            {
              tempzip_cleanup(hwndDlg,0);
              EndDialog(hwndDlg,0);
            }
          }
        break;
      }
    break;
  }
  return FALSE;
}
Example #3
1
void Main_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
{

    switch(id)
    {
        case IDC_BUTTON2:
		{
			OPENFILENAME ofn;
			char szFile[MAX_PATH];
			ZeroMemory(&ofn,sizeof(ofn));
			ofn.lStructSize = sizeof(ofn);
			ofn.lpstrFile = szFile;
			ofn.lpstrFile[0] = TEXT('\0');
			ofn.nMaxFile = sizeof(szFile);
			ofn.lpstrFilter = TEXT("ALL\0*.*\0Text\0*.txt\0C++\0*.cpp\0mp3\0*.mp3\0");
			ofn.nFilterIndex = 1;
			ofn.lpstrFileTitle = NULL;
			ofn.nMaxFileTitle = 0;
			ofn.lpstrInitialDir = NULL;
			ofn.hwndOwner = hwnd;
			ofn.Flags = OFN_EXPLORER|OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST;
			if(GetOpenFileName(&ofn))
			{
				char songname[256];
				wsprintf(songname,"play %s repeat",szFile);
				mciSendString(songname,"",0,NULL);
				SetDlgItemText(hwnd,IDC_EDIT2,szFile);
			}
		}
        break;
		case IDC_BUTTON3:
		{
			OPENFILENAME ofn;
			char szFile[MAX_PATH];
			ZeroMemory(&ofn,sizeof(ofn));
			ofn.lStructSize = sizeof(ofn);
			ofn.lpstrFile = szFile;
			ofn.lpstrFile[0] = TEXT('\0');
			ofn.nMaxFile = sizeof(szFile);
			ofn.lpstrFilter = TEXT("mp3\0*.mp3\0AVI\0*.avi\0");
			ofn.nFilterIndex = 1;
			ofn.lpstrFileTitle = NULL;
			ofn.nMaxFileTitle = 0;
			ofn.lpstrInitialDir = NULL;
			ofn.hwndOwner = hwnd;
			ofn.Flags = OFN_EXPLORER|OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST|OFN_ALLOWMULTISELECT;
			if(GetOpenFileName(&ofn))
			{
				TCHAR songname[256];
				HWND Combo1 = GetDlgItem(hwnd,IDC_LIST1);
				int count = ListBox_GetCount(Combo1),loc,i=0;
				for(loc=0;loc<count;loc++)
				{
					ListBox_GetText(Combo1,loc,songname);
					if(strcmp(songname,szFile)==0){
						MessageBox(NULL,TEXT("此选项已经存在,请重新选择!"),TEXT("       重试"),MB_OK|MB_ICONEXCLAMATION);
						break;}
					i++;
				}
				if(i==count)
					ListBox_InsertString(Combo1,-1,szFile);
			}
		}
		break;
		case IDC_BUTTON4:
		{
			TCHAR EDIT[256],STOPSTR[256];
			GetDlgItemText(hwnd,IDC_EDIT2,EDIT,sizeof(EDIT));
			wsprintf(STOPSTR,"stop %s",EDIT);
			mciSendString(STOPSTR,"",0,NULL);
			TCHAR str1[256];
			HWND Combo1 = GetDlgItem(hwnd,IDC_LIST1);
			int cixu = ListBox_GetCurSel(Combo1);
			if(cixu==-1){
				MessageBox(NULL,TEXT("未选择播放歌曲"),TEXT("       重试"),MB_OK|MB_ICONEXCLAMATION);break;}
			ListBox_GetText(Combo1,cixu,str1);
			TCHAR songname[256];
			wsprintf(songname,"play %s repeat",str1);
			mciSendString(songname,"",0,NULL);
			SetDlgItemText(hwnd,IDC_EDIT2,str1);
			TCHAR leth[256],str2[256],str3[256];
			wsprintf(str2,"status %s length",str1);			
			mciSendString(str2,leth,sizeof(leth)/sizeof(char),NULL);
			int tminute,tsecond;
			int lll = atoi(leth);
			int totalsecond = atoi(leth)/1000;
			tminute = totalsecond/60;
			tsecond = totalsecond-tminute*60;
			wsprintf(str3,"%02d:%02d",tminute,tsecond);
			SetDlgItemText(hwnd,IDC_TIME,str3);
			SendDlgItemMessage(hwnd,IDC_SLIDER2,TBM_SETRANGEMAX,false,(LPARAM)(totalsecond-1));
			SendDlgItemMessage(hwnd,IDC_SLIDER2,TBM_SETRANGEMIN,false,(LPARAM)0);
			SetTimer(hwnd,1,1000,progressBar);			
		}
		break;
		case IDC_BUTTON1:
		{
			TCHAR str1[256];
			HWND Combo1 = GetDlgItem(hwnd,IDC_LIST1);
			int cixu = ListBox_GetCurSel(Combo1);
			if(cixu==-1){
				MessageBox(NULL,TEXT("未选择播放歌曲"),TEXT("       重试"),MB_OK|MB_ICONEXCLAMATION);break;}
			GetDlgItemText(hwnd,IDC_EDIT2,str1,sizeof(str1));
			TCHAR songname[256];
			wsprintf(songname,"pause %s",str1);
			mciSendString(songname,"",0,NULL);	
		}
		break;
		case IDC_BUTTON5:
		{
			
			HWND Combo1 = GetDlgItem(hwnd,IDC_LIST1);
			int cixu = ListBox_GetCurSel(Combo1);
			if(cixu==-1){
				MessageBox(NULL,TEXT("未选择歌曲"),TEXT("       重试"),MB_OK|MB_ICONEXCLAMATION);break;}			
			ListBox_DeleteString(Combo1,cixu);
		}
		break;
		case IDC_BUTTON6:
		{
			TCHAR str1[256];
			HWND Combo1 = GetDlgItem(hwnd,IDC_LIST1);
			int cixu = ListBox_GetCurSel(Combo1);
			if(cixu==-1){
				MessageBox(NULL,TEXT("未选择播放歌曲"),TEXT("       重试"),MB_OK|MB_ICONEXCLAMATION);break;}
			GetDlgItemText(hwnd,IDC_EDIT2,str1,sizeof(str1));
			TCHAR songname[256];
			wsprintf(songname,"play %s repeat",str1);
			mciSendString(songname,"",0,NULL);
			SetDlgItemText(hwnd,IDC_EDIT2,str1);
		}
		break;
		case IDC_BUTTON7:
		{
			TCHAR EDI[256],STOPS[256];
			HWND Combo1 = GetDlgItem(hwnd,IDC_LIST1);
			int cixu = ListBox_GetCurSel(Combo1);
			if(cixu==-1){
				MessageBox(NULL,TEXT("未选择歌曲"),TEXT("       重试"),MB_OK|MB_ICONEXCLAMATION);break;}
			GetDlgItemText(hwnd,IDC_EDIT2,EDI,sizeof(EDI));
			wsprintf(STOPS,"stop %s",EDI);
			mciSendString(STOPS,"",0,NULL);
			
			TCHAR str[256],str1[256],str2[256],str3[256];
			GetDlgItemText(hwnd,IDC_EDIT2,str,sizeof(str));
			int location;
			int count = ListBox_GetCount(Combo1);
			for(location=0;location<count;location++)
			{
				ListBox_GetText(Combo1,location,str2);
				if(strcmp(str,str2)==0)
				{
					if(location==0)
						location=count;
					location = location-1;
					ListBox_GetText(Combo1,location,str3);
					wsprintf(str1,"play %s repeat",str3);
					mciSendString(str1,"",0,NULL);
					SetDlgItemText(hwnd,IDC_EDIT2,str3);
					ListBox_SetCurSel(Combo1,location);
					break;
				}
			}
			TCHAR leth[256],str4[256],str5[256];
			wsprintf(str4,"status %s length",str3);			
			mciSendString(str4,leth,sizeof(leth)/sizeof(char),NULL);
			int tminute,tsecond;
			int lll = atoi(leth);
			int totalsecond = atoi(leth)/1000;
			tminute = totalsecond/60;
			tsecond = totalsecond-tminute*60;
			wsprintf(str5,"%02d:%02d",tminute,tsecond);
			SetDlgItemText(hwnd,IDC_TIME,str5);
			SendDlgItemMessage(hwnd,IDC_SLIDER2,TBM_SETRANGEMAX,false,(LPARAM)(totalsecond-1));
			SendDlgItemMessage(hwnd,IDC_SLIDER2,TBM_SETRANGEMIN,false,(LPARAM)0);
		}
		break;
		case IDC_BUTTON8:
		{	
			TCHAR EDIT[256],STOPSTR[256];
			HWND Combo1 = GetDlgItem(hwnd,IDC_LIST1);
			int cixu = ListBox_GetCurSel(Combo1);
			if(cixu==-1){
				MessageBox(NULL,TEXT("未选择播放歌曲"),TEXT("       重试"),MB_OK|MB_ICONEXCLAMATION);break;}
			GetDlgItemText(hwnd,IDC_EDIT2,EDIT,sizeof(EDIT));
			wsprintf(STOPSTR,"stop %s",EDIT);
			mciSendString(STOPSTR,"",0,NULL);
			
			TCHAR str[256],str1[256],str2[256],str3[256];
			GetDlgItemText(hwnd,IDC_EDIT2,str,sizeof(str));
			int location;
			int count = ListBox_GetCount(Combo1);
			for(location=0;location<count;location++)
			{
				ListBox_GetText(Combo1,location,str2);
				if(strcmp(str,str2)==0)
				{
					location++;
					if(location==count)
						location=0;
					ListBox_GetText(Combo1,location,str3);
					wsprintf(str1,"play %s repeat",str3);
					mciSendString(str1,"",0,NULL);
					SetDlgItemText(hwnd,IDC_EDIT2,str3);
					ListBox_SetCurSel(Combo1,location);
					break;
				}
			}
			TCHAR leth[256],str4[256],str5[256];
			wsprintf(str4,"status %s length",str3);			
			mciSendString(str4,leth,sizeof(leth)/sizeof(char),NULL);
			int tminute,tsecond;
			int totalsecond = atoi(leth)/1000;
			tminute = totalsecond/60;
			tsecond = totalsecond-tminute*60;
			wsprintf(str5,"%02d:%02d",tminute,tsecond);
			SetDlgItemText(hwnd,IDC_TIME,str5);
			SendDlgItemMessage(hwnd,IDC_SLIDER2,TBM_SETRANGEMAX,false,(LPARAM)(totalsecond-1));
			SendDlgItemMessage(hwnd,IDC_SLIDER2,TBM_SETRANGEMIN,false,(LPARAM)0);
		}
		case IDC_BUTTON9:
		{
			int loc;
			HWND Combo1 = GetDlgItem(hwnd,IDC_LIST1);
			int cixu = ListBox_GetCurSel(Combo1);
			if(cixu==-1){
				MessageBox(NULL,TEXT("无歌曲可保存"),TEXT("       重试"),MB_OK|MB_ICONEXCLAMATION);break;}
			OPENFILENAME ofn;
			char szFile[MAX_PATH];
			ZeroMemory(&ofn,sizeof(ofn));
			ofn.lStructSize = sizeof(ofn);
			ofn.lpstrFile = szFile;
			ofn.lpstrFile[0] = TEXT('\0');
			ofn.nMaxFile = sizeof(szFile);
			ofn.lpstrFilter = TEXT("mp3\0*.mp3\0AVI\0*.avi\0text\0*.txt\0");
			ofn.nFilterIndex = 3;
			ofn.lpstrFileTitle = NULL;
			ofn.nMaxFileTitle = 0;
			ofn.lpstrInitialDir = NULL;
			ofn.hwndOwner = hwnd;
			ofn.Flags = OFN_EXPLORER|OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST|OFN_ALLOWMULTISELECT;
			if(GetSaveFileName(&ofn))
			{
				
				
				FILE *fp;
				TCHAR EDI[256],str[256],str1[256];
				wsprintf(str1,"%s.txt",szFile);
				int count = ListBox_GetCount(Combo1);
				fp = fopen(str1,"w");
				for(loc=0;loc<count;loc++)
				{
					ListBox_GetText(Combo1,loc,EDI);
					wsprintf(str,"%s\n",EDI);								
					fputs(str,fp);				
				}
				fclose(fp);
			}
			
		}
		break;
		case IDC_GETLIST:
		{
			OPENFILENAME ofn;
			char szFile[MAX_PATH];
			ZeroMemory(&ofn,sizeof(ofn));
			ofn.lStructSize = sizeof(ofn);
			ofn.lpstrFile = szFile;
			ofn.lpstrFile[0] = TEXT('\0');
			ofn.nMaxFile = sizeof(szFile);
			ofn.lpstrFilter = TEXT("mp3\0*.mp3\0AVI\0*.avi\0text\0*.txt\0");
			ofn.nFilterIndex = 3;
			ofn.lpstrFileTitle = NULL;
			ofn.nMaxFileTitle = 0;
			ofn.lpstrInitialDir = NULL;
			ofn.hwndOwner = hwnd;
			ofn.Flags = OFN_EXPLORER|OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST|OFN_ALLOWMULTISELECT;
			if(GetOpenFileName(&ofn))
			{
				FILE *fp;
				HWND ListBox = GetDlgItem(hwnd,IDC_LIST1);
				TCHAR songname[256];
				fp = fopen(szFile,"a+");
				int size=100,loc;
				while(fgets(songname,sizeof(songname),fp)!=0)
				{
					for(loc = 0;loc<size;loc++)
					{
						if(songname[loc]=='\n')
							songname[loc]='\0';
					}
					ListBox_InsertString(ListBox,-1,songname);		
				}
				fclose(fp);
			}
			
		}
		break;
		case IDC_LIST1:
		{
			TCHAR buf[256];
			if(LBN_DBLCLK==codeNotify)
			{
				TCHAR EDIT[256],STOPSTR[256],PLAYSTR[256];
				HWND Combo1 = GetDlgItem(hwnd,IDC_LIST1);				
				GetDlgItemText(hwnd,IDC_EDIT2,EDIT,sizeof(EDIT));
				wsprintf(STOPSTR,"stop %s",EDIT);
				mciSendString(STOPSTR,"",0,NULL);
				int index = SendDlgItemMessage(hwnd,IDC_LIST1,LB_GETCURSEL,0,0);
				SetTimer(hwnd,2,1000,progressBar);
				SendDlgItemMessage(hwnd,IDC_LIST1,LB_GETTEXT,index,(LPARAM)buf);
				wsprintf(PLAYSTR,"play %s repeat",buf);
				mciSendString(PLAYSTR,"",0,NULL);
				SetDlgItemText(hwnd,IDC_EDIT2,buf);//				ListBox_SetCurSel(Combo1,index);
				TCHAR leth[256],str4[256],str5[256];
				wsprintf(str4,"status %s length",buf);			
				mciSendString(str4,leth,sizeof(leth)/sizeof(char),NULL);
				int tminute,tsecond;
				int totalsecond = atoi(leth)/1000;
				tminute = totalsecond/60;
				tsecond = totalsecond-tminute*60;
				wsprintf(str5,"%02d:%02d",tminute,tsecond);
				SetDlgItemText(hwnd,IDC_TIME,str5);
				SendDlgItemMessage(hwnd,IDC_SLIDER2,TBM_SETRANGEMAX,false,(LPARAM)(totalsecond-1));
				SendDlgItemMessage(hwnd,IDC_SLIDER2,TBM_SETRANGEMIN,false,(LPARAM)0);
								
			}						
		}
		break;
		case IDC_MOVIE:
		{
			TCHAR buf[256],buf1[256],buf2[256];
			TCHAR EDIT[256],STOPSTR[256],PLAYSTR[256];
			GetDlgItemText(hwnd,IDC_EDIT2,EDIT,sizeof(EDIT));
			wsprintf(STOPSTR,"stop %s",EDIT);
			mciSendString(STOPSTR,"",0,NULL);
			HWND movie = GetDlgItem(hwnd,IDC_LIST1);
			int cur = SendDlgItemMessage(hwnd,IDC_LIST1,LB_GETCURSEL,false,0);
			ListBox_GetText(movie,cur,buf);
			wsprintf(buf1,"open %s type MPEGVideo",buf);
			wsprintf(buf2,"play %s",buf);
			mciSendString(buf1,0,0,NULL);
			mciSendString(buf2,0,0,NULL);
			SetDlgItemText(hwnd,IDC_EDIT2,buf);								
		}
        default:
		break;
    }
}
Example #4
0
LRESULT CALLBACK WndProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
	PAINTSTRUCT ps;
	HDC hdc;
  HPEN hPen;
  HBRUSH hBrush;
	BOOL success;

  static BOOL enteringText = FALSE;
	static TCHAR text[256];
	static DWORD textLength = 0;

	static OPENFILENAME OpenFileName;
	static TCHAR FilePath[256];

  static PRINTDLG printDialog;
  ZeroMemory(&printDialog, sizeof(printDialog));
  printDialog.lStructSize = sizeof(printDialog);
  printDialog.hwndOwner = hWnd;
  printDialog.Flags = PD_RETURNDC;

  static CHOOSECOLOR chooseColorStructure;
  static COLORREF acrCustClr[16];
  ZeroMemory(&chooseColorStructure, sizeof(chooseColorStructure));
  chooseColorStructure.lStructSize = sizeof(chooseColorStructure);
  chooseColorStructure.hwndOwner = hWnd;
  chooseColorStructure.lpCustColors = (LPDWORD) acrCustClr;
  chooseColorStructure.rgbResult = 0;
  chooseColorStructure.Flags = CC_FULLOPEN | CC_RGBINIT;

  static DWORD lastX, lastY;

	switch (Message)
	{
	case WM_CREATE:
		viewController = new ViewController();
		viewController->SetScrollSettings(hWnd, CW_USEDEFAULT, CW_USEDEFAULT);
		mainCreator = new Creator();

		OpenFileName.lStructSize = sizeof(OPENFILENAME);
		OpenFileName.hwndOwner = hWnd;
		OpenFileName.lpstrFile = FilePath;
		OpenFileName.nMaxFile = sizeof(FilePath);

		break;
	case WM_COMMAND:
		switch (LOWORD(wParam))
		{
		case ID_OPEN:
			FilePath[0] = '\0';
			success = GetOpenFileName(&OpenFileName);
			if (success)
			{
				viewController->OpenMetaFile(OpenFileName.lpstrFile);
			}
			InvalidateRect(hWnd, NULL, TRUE);
			break;
		case ID_SAVEAS:
			FilePath[0] = '\0';
			success = GetSaveFileName(&OpenFileName);
			if (success)
			{
				viewController->SaveMetaFile(OpenFileName.lpstrFile);
			}
			break;
		case ID_NEW:
			delete viewController;
			viewController = new ViewController();
			InvalidateRect(hWnd, NULL, TRUE);
			break;
    case ID_FILE_EXIT:
      DestroyWindow(hWnd);
      break;
    case ID_PEN_COLOR:
      success = ChooseColor(&chooseColorStructure);
      if (success)
      {
        hPen = CreatePen(PS_SOLID, 1, chooseColorStructure.rgbResult);
        viewController->setPen(hPen);
      }
      break;
    case ID_BRUSH_COLOR:
      success = ChooseColor(&chooseColorStructure);
      if (success)
      {
        hBrush = CreateSolidBrush(chooseColorStructure.rgbResult);
        viewController->setBrush(hBrush);
      }
      break;
    case ID_PRINT:
      {
        PrintDlg(&printDialog);
        HDC printerhDC = printDialog.hDC;
        DOCINFO di = { sizeof (DOCINFO), _T("Printing...")};
        StartDoc(printerhDC, &di);
        StartPage(printerhDC);
        viewController->Print(printerhDC);
        EndPage(printerhDC);
        EndDoc(printerhDC);
        DeleteDC(printerhDC);
      }
      break;
    case ID_SET_CLIP:
      CreatingShapeType = -CLIP;
      break;
		}
		break;
	case WM_SIZE:
		viewController->SetScrollSettings(hWnd, HIWORD(lParam), LOWORD(lParam));
		break;
	case WM_VSCROLL:
	{
		int Move;
		bool AbsolutPosition = false;
		switch (LOWORD(wParam))
		{
		case SB_LINEUP:
			Move = -50;
			break;

		case SB_LINEDOWN:
			Move = 50;
			break;
			
		case SB_THUMBTRACK:
			Move = HIWORD(wParam);
			AbsolutPosition = true;
			break;

		default:
			Move = 0;
		}
		viewController->UpdateVerticalScroll(hWnd, Move, AbsolutPosition);
		break;
	}
	case WM_HSCROLL:
	{
		int Move;
		bool AbsolutPosition = false;
		switch (LOWORD(wParam))
		{
		case SB_LINELEFT:
			Move = -20;
			break;

		case SB_LINERIGHT:
			Move = 20;
			break;

		case SB_THUMBTRACK:
			Move = HIWORD(wParam);
			AbsolutPosition = true;
			break;

		default:
			Move = 0;
		}
		viewController->UpdateHorizontalScroll(hWnd, Move, AbsolutPosition);
		break;
	}
	case WM_LBUTTONDOWN:
    lastX = LOWORD(lParam);
    lastY = HIWORD(lParam);
    if (CreatingShapeType == -MTEXT)
    {
			CreatingShapeType = -CreatingShapeType;
      mainCreator->BeginCreatingShape(CreatingShapeType, lastX, lastY);
      textLength = 0;
      enteringText = TRUE;
    }
    else if (CreatingShapeType == MTEXT)
    {
      text[textLength++] = '\0';
      Figure tex = mainCreator->CreateShape(text);
			viewController->DrawToMetaFile(tex);
			CreatingShapeType = -CreatingShapeType;
      enteringText = FALSE;
    }
    else if (CreatingShapeType < 0)
		{
			CreatingShapeType = -CreatingShapeType;
      if (CreatingShapeType != MOVE)
        mainCreator->BeginCreatingShape(CreatingShapeType, lastX, lastY);
		}
    else if (CreatingShapeType > 0)
    {
      mainCreator->AddPoint(lastX, lastY);
			hdc = GetDC(hWnd);
			RECT r;
			GetClientRect(hWnd, &r);
			FillRect(hdc, &r, NULL);
			viewController->UpdateScreen(hdc);
      SelectObject(hdc, viewController->getPen());
      SelectObject(hdc, viewController->getBrush());
			mainCreator->DrawShape(hdc, 0, 0, NULL, 0);
			ReleaseDC(hWnd, hdc);
    }
		break;
	case WM_LBUTTONUP:
    if (CreatingShapeType > 0 && CreatingShapeType != MOVE && CreatingShapeType != MTEXT &&
        CreatingShapeType != POLYLINE && CreatingShapeType != POLYGON)
		{
      mainCreator->AddPoint(LOWORD(lParam), HIWORD(lParam));
      if (CreatingShapeType == CLIP)
        {
          viewController->SetPrintClip(mainCreator->points[0].x, mainCreator->points[0].y,
              mainCreator->points[1].x, mainCreator->points[1].y);
          hdc = GetDC(hWnd);
          RECT r;
          GetClientRect(hWnd, &r);
          FillRect(hdc, &r, NULL);
          viewController->UpdateScreen(hdc);
          ReleaseDC(hWnd, hdc);
        }
      else
        viewController->DrawToMetaFile(mainCreator->CreateShape());
		}
    if (CreatingShapeType != MTEXT && CreatingShapeType != POLYLINE && CreatingShapeType != POLYGON)
      CreatingShapeType = -CreatingShapeType;
    UpdateWindow(hWnd);
		break;
	case WM_RBUTTONDOWN:
    lastX = LOWORD(lParam);
    lastY = HIWORD(lParam);
    if (CreatingShapeType > 0)
    {
      viewController->DrawToMetaFile(mainCreator->CreateShape());
    }
	case WM_MOUSEMOVE:
    if (CreatingShapeType == MOVE)
    {
      DWORD dx = LOWORD(lParam) - lastX;
      DWORD dy = HIWORD(lParam) - lastY;
      lastX = LOWORD(lParam);
      lastY = HIWORD(lParam);
      viewController->UpdateVerticalScroll(hWnd, -dy, FALSE);
      viewController->UpdateHorizontalScroll(hWnd, -dx, FALSE);
    }
    else if (CreatingShapeType == PEN)
    {
      mainCreator->AddPoint(LOWORD(lParam), HIWORD(lParam));
			hdc = GetDC(hWnd);
			RECT r;
			GetClientRect(hWnd, &r);
			FillRect(hdc, &r, NULL);
			viewController->UpdateScreen(hdc);
      SelectObject(hdc, viewController->getPen());
      SelectObject(hdc, viewController->getBrush());
			mainCreator->DrawShape(hdc, 0, 0, NULL, 0);
			ReleaseDC(hWnd, hdc);
    }
    else if (CreatingShapeType > 0)
		{
			hdc = GetDC(hWnd);
			RECT r;
			GetClientRect(hWnd, &r);
			FillRect(hdc, &r, NULL);
			viewController->UpdateScreen(hdc);
      if (CreatingShapeType == CLIP)
      {
        SelectObject(hdc, GetStockObject(BLACK_PEN));
        SelectObject(hdc, GetStockObject(NULL_BRUSH));
      }
      else
      {
        SelectObject(hdc, viewController->getPen());
        SelectObject(hdc, viewController->getBrush());
      }
			mainCreator->DrawShape(hdc, LOWORD(lParam), HIWORD(lParam), text, textLength);
			ReleaseDC(hWnd, hdc);
		}
		break;
	case WM_MOUSEWHEEL:
		if (LOWORD(wParam) & MK_CONTROL)
		{
			viewController->ChangeScale(((short)HIWORD(wParam)) / ((float)(WHEEL_DELTA * 4)));
			RECT r;
			GetClientRect(hWnd, &r);
			viewController->SetScrollSettings(hWnd, r.bottom -  r.top, r.right - r.left);
		}
		else if (LOWORD(wParam) & MK_SHIFT)
		{
			int Move;
			Move = -((short)HIWORD(wParam));
			viewController->UpdateHorizontalScroll(hWnd, Move);
		}
		else
		{
			int Move;
			Move = -((short)HIWORD(wParam));
			viewController->UpdateVerticalScroll(hWnd, Move);
		}
		InvalidateRect(hWnd, NULL, TRUE);
		break;
  case WM_CHAR:
    if (enteringText)
    {
      text[textLength++] = wParam;
			hdc = GetDC(hWnd);
			RECT r;
			GetClientRect(hWnd, &r);
			FillRect(hdc, &r, NULL);
			viewController->UpdateScreen(hdc);
      SelectObject(hdc, viewController->getPen());
      SelectObject(hdc, viewController->getBrush());
			mainCreator->DrawShape(hdc, 0, 0, text, textLength);
			ReleaseDC(hWnd, hdc);
    }
    break;
	case WM_KEYDOWN:
    if (!enteringText)
      switch (wParam)
      {
        case 69: // E
          CreatingShapeType = -ELLIPSE;
          break;
        case 76: // L
          CreatingShapeType = -LINE;
          break;
        case 82: // R
          CreatingShapeType = -RECTANGLE;
          break;
        case 84: // T
          CreatingShapeType = -MTEXT;
          break;
        case 77: // M
          CreatingShapeType = -MOVE;
          break;
        case 73: // I
          CreatingShapeType = -POLYLINE;
          break;
        case 71: // G
          CreatingShapeType = -POLYGON;
          break;
        case 80: // P
          CreatingShapeType = -PEN;
          break;
      }
		break;
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		viewController->UpdateScreen(hdc);
		EndPaint(hWnd, &ps);
    break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;

	default:
		return DefWindowProc(hWnd, Message, wParam, lParam);
	}
	return 0;
}
Example #5
0
        virtual void run()
        {
            QString result;

            QString workDir;
            QString initSel;
            QFileInfo fi (mStartWith);

            if (fi.isDir())
                workDir = mStartWith;
            else
            {
                workDir = fi.absolutePath();
                initSel = fi.fileName();
            }

            workDir = QDir::toNativeSeparators (workDir);
            if (!workDir.endsWith ("\\"))
                workDir += "\\";

            QString title = mCaption.isNull() ? tr ("Select a file") : mCaption;

            QWidget *topParent = windowManager().realParentWindow(mParent ? mParent : windowManager().mainWindowShown());
            QString winFilters = winFilter (mFilters);
            AssertCompile (sizeof (TCHAR) == sizeof (QChar));
            TCHAR buf [1024];
            if (initSel.length() > 0 && initSel.length() < sizeof (buf))
                memcpy (buf, initSel.isNull() ? 0 : initSel.utf16(),
                        (initSel.length() + 1) * sizeof (TCHAR));
            else
                buf [0] = 0;

            OPENFILENAME ofn;
            memset (&ofn, 0, sizeof (OPENFILENAME));

            ofn.lStructSize = sizeof (OPENFILENAME);
            ofn.hwndOwner = topParent ? topParent->winId() : 0;
            ofn.lpstrFilter = (TCHAR *)(winFilters.isNull() ? 0 : winFilters.utf16());
            ofn.lpstrFile = buf;
            ofn.nMaxFile = sizeof (buf) - 1;
            ofn.lpstrInitialDir = (TCHAR *)(workDir.isNull() ? 0 : workDir.utf16());
            ofn.lpstrTitle = (TCHAR *)(title.isNull() ? 0 : title.utf16());
            ofn.Flags = (OFN_NOCHANGEDIR | OFN_HIDEREADONLY |
                         OFN_EXPLORER | OFN_ENABLEHOOK |
                         OFN_NOTESTFILECREATE | (m_fConfirmOverwrite ? OFN_OVERWRITEPROMPT : 0));
            ofn.lpfnHook = OFNHookProc;

            if (GetSaveFileName (&ofn))
            {
                result = QString::fromUtf16 ((ushort *) ofn.lpstrFile);
            }

            // qt_win_eatMouseMove();
            MSG msg = {0, 0, 0, 0, 0, 0, 0};
            while (PeekMessage (&msg, 0, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE));
            if (msg.message == WM_MOUSEMOVE)
                PostMessage (msg.hwnd, msg.message, 0, msg.lParam);

            result = result.isEmpty() ? result : QFileInfo (result).absoluteFilePath();

            QApplication::postEvent (mTarget, new GetOpenFileNameEvent (result));
        }
BOOL CTTSApp::CallSaveFileDialog( __in LPTSTR szFileName, LPCTSTR szFilter )  
/////////////////////////////////////////////////////////////////
//
// Display the save dialog box to save the wav file
{
    OPENFILENAME    ofn;
    BOOL            bRetVal     = TRUE;
    LONG            lRetVal;
    HKEY            hkResult;
    TCHAR           szPath[256]       = _T("");
    DWORD           size = 256;

    // Open the last directory used by this app (stored in registry)
    lRetVal = RegCreateKeyEx( HKEY_CLASSES_ROOT, _T("PathTTSDataFiles"), 0, NULL, 0,
                        KEY_ALL_ACCESS, NULL, &hkResult, NULL );

    if( lRetVal == ERROR_SUCCESS )
    {
        RegQueryValueEx( hkResult, _T("TTSFiles"), NULL, NULL, (PBYTE)szPath, &size );
    
        RegCloseKey( hkResult );
    }

    size_t ofnsize = (BYTE*)&ofn.lpTemplateName + sizeof(ofn.lpTemplateName) - (BYTE*)&ofn;
    ZeroMemory( &ofn, ofnsize);

    ofn.lStructSize       = (DWORD)ofnsize;
    ofn.hwndOwner         = m_hWnd;    
    ofn.lpstrFilter       = szFilter;
    ofn.lpstrCustomFilter = NULL;    
    ofn.nFilterIndex      = 1;    
    ofn.lpstrInitialDir   = szPath;
    ofn.lpstrFile         = szFileName;  
    ofn.nMaxFile          = 256;
    ofn.lpstrTitle        = NULL;
    ofn.lpstrFileTitle    = NULL;    
    ofn.lpstrDefExt       = _T("wav");
    ofn.Flags             = OFN_OVERWRITEPROMPT;

    // Pop the dialog
    bRetVal = GetSaveFileName( &ofn );

    // Write the directory path you're in to the registry
    TCHAR   pathstr[256] = _T("");
    _tcscpy_s( pathstr, _countof(pathstr), szFileName );

    if ( ofn.Flags & OFN_EXTENSIONDIFFERENT )
    {
        _tcscat_s( pathstr, _countof(pathstr), _T(".wav") );
    }

    int i=0; 
    while( pathstr[i] != NULL )
    {
        i++;
    }
    while( i > 0 && pathstr[i] != '\\' )
    {
        i--;
    }
    pathstr[i] = NULL;

    // Now write the string to the registry
    lRetVal = RegCreateKeyEx( HKEY_CLASSES_ROOT, _T("PathTTSDataFiles"), 0, NULL, 0,
                        KEY_ALL_ACCESS, NULL, &hkResult, NULL );

    if( lRetVal == ERROR_SUCCESS )
    {
        RegSetValueEx( hkResult, _T("TTSFiles"), NULL, REG_EXPAND_SZ, (PBYTE)pathstr, (DWORD)_tcslen(pathstr)+1 );
    
        RegCloseKey( hkResult );
    }

    return bRetVal;
}
Example #7
0
LRESULT CMainWindow::OnCommand(UINT nMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
    switch (LOWORD(wParam))
    {
        case IDM_HELPINFO:
        {
            HICON paintIcon = LoadIcon(hProgInstance, MAKEINTRESOURCE(IDI_APPICON));
            TCHAR infotitle[100];
            TCHAR infotext[200];
            LoadString(hProgInstance, IDS_INFOTITLE, infotitle, SIZEOF(infotitle));
            LoadString(hProgInstance, IDS_INFOTEXT, infotext, SIZEOF(infotext));
            ShellAbout(m_hWnd, infotitle, infotext, paintIcon);
            DeleteObject(paintIcon);
            break;
        }
        case IDM_HELPHELPTOPICS:
            HtmlHelp(m_hWnd, _T("help\\Paint.chm"), 0, 0);
            break;
        case IDM_FILEEXIT:
            SendMessage(WM_CLOSE, wParam, lParam);
            break;
        case IDM_FILENEW:
        {
            BOOL reset = TRUE;
            if (!imageModel.IsImageSaved())
            {
                TCHAR programname[20];
                TCHAR saveprompttext[100];
                TCHAR temptext[500];
                LoadString(hProgInstance, IDS_PROGRAMNAME, programname, SIZEOF(programname));
                LoadString(hProgInstance, IDS_SAVEPROMPTTEXT, saveprompttext, SIZEOF(saveprompttext));
                _stprintf(temptext, saveprompttext, filename);
                switch (MessageBox(temptext, programname, MB_YESNOCANCEL | MB_ICONQUESTION))
                {
                    case IDNO:
                        imageModel.imageSaved = TRUE; //TODO: move to ImageModel
                        break;
                    case IDYES:
                        saveImage(FALSE);
                        break;
                    case IDCANCEL:
                        reset = FALSE;
                        break;
                }
            }
            if (reset && imageModel.IsImageSaved()) //TODO: move to ImageModel
            {
                imageModel.Clear();
                imageModel.ClearHistory();
            }
            break;
        }
        case IDM_FILEOPEN:
            if (GetOpenFileName(&ofn) != 0)
            {
                HBITMAP bmNew = NULL;
                LoadDIBFromFile(&bmNew, ofn.lpstrFile, &fileTime, &fileSize, &fileHPPM, &fileVPPM);
                if (bmNew != NULL)
                {
                    UpdateApplicationProperties(bmNew, ofn.lpstrFileTitle, ofn.lpstrFileTitle);
                }
            }
            break;
        case IDM_FILESAVE:
            saveImage(TRUE);
            break;
        case IDM_FILESAVEAS:
            saveImage(FALSE);
            break;
        case IDM_FILEPAGESETUP:
            // DUMMY: Shows the dialog only, no functionality
            PAGESETUPDLG psd;
            ZeroMemory(&psd, sizeof(psd));
            psd.lStructSize = sizeof(psd);
            psd.hwndOwner = m_hWnd;
            PageSetupDlg(&psd);
            break;
        case IDM_FILEPRINT:
            // TODO: Test whether it actually works
            PRINTDLG pd;
            ZeroMemory(&pd, sizeof(pd));
            pd.lStructSize = sizeof(pd);
            pd.hwndOwner = m_hWnd;
            pd.hDevMode = NULL;  // freed by user
            pd.hDevNames = NULL;  // freed by user
            pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC;
            pd.nCopies = 1;
            pd.nFromPage = 0xffff;
            pd.nToPage = 0xffff;
            pd.nMinPage = 1;
            pd.nMaxPage = 0xffff;
            if (PrintDlg(&pd) == TRUE)
            {
                BitBlt(pd.hDC, 0, 0, imageModel.GetWidth(), imageModel.GetHeight(), imageModel.GetDC(), 0, 0, SRCCOPY);
                DeleteDC(pd.hDC);
            }
            if (pd.hDevMode)
                GlobalFree(pd.hDevMode);
            if (pd.hDevNames)
                GlobalFree(pd.hDevNames);
            break;
        case IDM_FILEASWALLPAPERPLANE:
            RegistrySettings::SetWallpaper(filepathname, 1, 1);
            break;
        case IDM_FILEASWALLPAPERCENTERED:
            RegistrySettings::SetWallpaper(filepathname, 1, 0);
            break;
        case IDM_FILEASWALLPAPERSTRETCHED:
            RegistrySettings::SetWallpaper(filepathname, 2, 0);
            break;
        case IDM_EDITUNDO:
            imageModel.Undo();
            imageArea.Invalidate(FALSE);
            break;
        case IDM_EDITREDO:
            imageModel.Redo();
            imageArea.Invalidate(FALSE);
            break;
        case IDM_EDITCOPY:
            OpenClipboard();
            EmptyClipboard();
            SetClipboardData(CF_BITMAP, CopyImage(selectionModel.GetBitmap(), IMAGE_BITMAP, 0, 0, LR_COPYRETURNORG));
            CloseClipboard();
            break;
        case IDM_EDITCUT:
            /* Copy */
            SendMessage(WM_COMMAND, IDM_EDITCOPY, 0);
            /* Delete selection */
            SendMessage(WM_COMMAND, IDM_EDITDELETESELECTION, 0);
            break;
        case IDM_EDITPASTE:
            OpenClipboard();
            if (GetClipboardData(CF_BITMAP) != NULL)
            {
                InsertSelectionFromHBITMAP((HBITMAP) GetClipboardData(CF_BITMAP), m_hWnd);
            }
            CloseClipboard();
            break;
        case IDM_EDITDELETESELECTION:
        {
            /* remove selection window and already painted content using undo */
            imageModel.Undo();
            break;
        }
        case IDM_EDITSELECTALL:
        {
            HWND hToolbar = FindWindowEx(toolBoxContainer.m_hWnd, NULL, TOOLBARCLASSNAME, NULL);
            SendMessage(hToolbar, TB_CHECKBUTTON, ID_RECTSEL, MAKELPARAM(TRUE, 0));
            toolBoxContainer.SendMessage(WM_COMMAND, ID_RECTSEL);
            //TODO: do this properly
            startPaintingL(imageModel.GetDC(), 0, 0, paletteModel.GetFgColor(), paletteModel.GetBgColor());
            whilePaintingL(imageModel.GetDC(), imageModel.GetWidth(), imageModel.GetHeight(), paletteModel.GetFgColor(), paletteModel.GetBgColor());
            endPaintingL(imageModel.GetDC(), imageModel.GetWidth(), imageModel.GetHeight(), paletteModel.GetFgColor(), paletteModel.GetBgColor());
            break;
        }
        case IDM_EDITCOPYTO:
            if (GetSaveFileName(&ofn) != 0)
                SaveDIBToFile(selectionModel.GetBitmap(), ofn.lpstrFile, imageModel.GetDC(), NULL, NULL, fileHPPM, fileVPPM);
            break;
        case IDM_EDITPASTEFROM:
            if (GetOpenFileName(&ofn) != 0)
            {
                HBITMAP bmNew = NULL;
                LoadDIBFromFile(&bmNew, ofn.lpstrFile, &fileTime, &fileSize, &fileHPPM, &fileVPPM);
                if (bmNew != NULL)
                {
                    InsertSelectionFromHBITMAP(bmNew, m_hWnd);
                    DeleteObject(bmNew);
                }
            }
            break;
        case IDM_COLORSEDITPALETTE:
            if (ChooseColor(&choosecolor))
                paletteModel.SetFgColor(choosecolor.rgbResult);
            break;
        case IDM_COLORSMODERNPALETTE:
            paletteModel.SelectPalette(1);
            break;
        case IDM_COLORSOLDPALETTE:
            paletteModel.SelectPalette(2);
            break;
        case IDM_IMAGEINVERTCOLORS:
        {
            imageModel.InvertColors();
            break;
        }
        case IDM_IMAGEDELETEIMAGE:
            imageModel.CopyPrevious();
            Rect(imageModel.GetDC(), 0, 0, imageModel.GetWidth(), imageModel.GetHeight(), paletteModel.GetBgColor(), paletteModel.GetBgColor(), 0, TRUE);
            imageArea.Invalidate(FALSE);
            break;
        case IDM_IMAGEROTATEMIRROR:
            switch (mirrorRotateDlg())
            {
                case 1: /* flip horizontally */
                    if (selectionWindow.IsWindowVisible())
                        selectionModel.FlipHorizontally();
                    else
                        imageModel.FlipHorizontally();
                    break;
                case 2: /* flip vertically */
                    if (selectionWindow.IsWindowVisible())
                        selectionModel.FlipVertically();
                    else
                        imageModel.FlipVertically();
                    break;
                case 3: /* rotate 90 degrees */
                    break;
                case 4: /* rotate 180 degrees */
                    if (selectionWindow.IsWindowVisible())
                        selectionModel.RotateNTimes90Degrees(2);
                    else
                        imageModel.RotateNTimes90Degrees(2);
                    break;
                case 5: /* rotate 270 degrees */
                    break;
            }
            break;
        case IDM_IMAGEATTRIBUTES:
        {
            if (attributesDlg())
            {
                imageModel.Crop(widthSetInDlg, heightSetInDlg, 0, 0);
            }
            break;
        }
        case IDM_IMAGESTRETCHSKEW:
        {
            if (changeSizeDlg())
            {
                imageModel.StretchSkew(stretchSkew.percentage.x, stretchSkew.percentage.y,
                                       stretchSkew.angle.x, stretchSkew.angle.y);
            }
            break;
        }
        case IDM_IMAGEDRAWOPAQUE:
            toolsModel.SetBackgroundTransparent(!toolsModel.IsBackgroundTransparent());
            break;
        case IDM_IMAGECROP:
            imageModel.Insert((HBITMAP) CopyImage(selectionModel.GetBitmap(), IMAGE_BITMAP, 0, 0, LR_COPYRETURNORG));
            break;

        case IDM_VIEWTOOLBOX:
            toolBoxContainer.ShowWindow(toolBoxContainer.IsWindowVisible() ? SW_HIDE : SW_SHOW);
            alignChildrenToMainWindow();
            break;
        case IDM_VIEWCOLORPALETTE:
            paletteWindow.ShowWindow(paletteWindow.IsWindowVisible() ? SW_HIDE : SW_SHOW);
            alignChildrenToMainWindow();
            break;
        case IDM_VIEWSTATUSBAR:
            ::ShowWindow(hStatusBar, ::IsWindowVisible(hStatusBar) ? SW_HIDE : SW_SHOW);
            alignChildrenToMainWindow();
            break;
        case IDM_FORMATICONBAR:
            textEditWindow.ShowWindow(textEditWindow.IsWindowVisible() ? SW_HIDE : SW_SHOW);

        case IDM_VIEWSHOWGRID:
            showGrid = !showGrid;
            imageArea.Invalidate(FALSE);
            break;
        case IDM_VIEWSHOWMINIATURE:
            showMiniature = !showMiniature;
            miniature.ShowWindow(showMiniature ? SW_SHOW : SW_HIDE);
            break;

        case IDM_VIEWZOOM125:
            zoomTo(125, 0, 0);
            break;
        case IDM_VIEWZOOM25:
            zoomTo(250, 0, 0);
            break;
        case IDM_VIEWZOOM50:
            zoomTo(500, 0, 0);
            break;
        case IDM_VIEWZOOM100:
            zoomTo(1000, 0, 0);
            break;
        case IDM_VIEWZOOM200:
            zoomTo(2000, 0, 0);
            break;
        case IDM_VIEWZOOM400:
            zoomTo(4000, 0, 0);
            break;
        case IDM_VIEWZOOM800:
            zoomTo(8000, 0, 0);
            break;

        case IDM_VIEWFULLSCREEN:
            fullscreenWindow.ShowWindow(SW_SHOW);
            ShowWindow(SW_HIDE);
            break;
    }
    return 0;
}
int FileDialog::ShowModal()
{
   HWND hWnd = 0;
   if (m_parent) hWnd = (HWND) m_parent->GetHWND();
   if (!hWnd && wxTheApp->GetTopWindow())
      hWnd = (HWND) wxTheApp->GetTopWindow()->GetHWND();
   
   static wxChar fileNameBuffer [ wxMAXPATH ];           // the file-name
   wxChar        titleBuffer    [ wxMAXFILE+1+wxMAXEXT ];  // the file-name, without path
   
   *fileNameBuffer = wxT('\0');
   *titleBuffer    = wxT('\0');
   
#if WXWIN_COMPATIBILITY_2_4
   long msw_flags = 0;
   if ( (m_dialogStyle & wxHIDE_READONLY) || (m_dialogStyle & wxSAVE) )
      msw_flags |= OFN_HIDEREADONLY;
#else
   long msw_flags = OFN_HIDEREADONLY;
#endif
   
   if ( m_dialogStyle & wxFILE_MUST_EXIST )
      msw_flags |= OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
   /*
    If the window has been moved the programmer is probably
    trying to center or position it.  Thus we set the callback
    or hook function so that we can actually adjust the position.
    Without moving or centering the dlg, it will just stay
    in the upper left of the frame, it does not center
    automatically..  One additional note, when the hook is
    enabled, the PLACES BAR in the dlg (shown on later versions
    of windows (2000 and XP) will automatically be turned off
    according to the MSDN docs.  This is normal.  If the
    programmer needs the PLACES BAR (left side of dlg) they
    just shouldn't move or center the dlg.
    */
   if (m_bMovedWindow) // we need these flags.
   {
      msw_flags |= OFN_EXPLORER|OFN_ENABLEHOOK;
#ifndef __WXWINCE__
      msw_flags |= OFN_ENABLESIZING;
#endif
   }
   
   if (m_dialogStyle & wxMULTIPLE )
   {
      // OFN_EXPLORER must always be specified with OFN_ALLOWMULTISELECT
      msw_flags |= OFN_EXPLORER | OFN_ALLOWMULTISELECT;
   }
   
   // if wxCHANGE_DIR flag is not given we shouldn't change the CWD which the
   // standard dialog does by default (notice that under NT it does it anyhow, 
   // OFN_NOCHANGEDIR or not, see below)
   if ( !(m_dialogStyle & wxCHANGE_DIR) )
   {
      msw_flags |= OFN_NOCHANGEDIR;
   }
   
   if ( m_dialogStyle & wxOVERWRITE_PROMPT )
   {
      msw_flags |= OFN_OVERWRITEPROMPT;
   }
   
   if ( m_dialogStyle & wxRESIZE_BORDER )
   {
      msw_flags |= OFN_ENABLESIZING;
   }
   
   if ( m_callback != NULL )
   {
      msw_flags |= OFN_SHOWHELP | OFN_EXPLORER | OFN_ENABLEHOOK;
   }
   
   // We always need EXPLORER and ENABLEHOOK to use our filtering code
   msw_flags |= OFN_EXPLORER | OFN_ENABLEHOOK;
   
   OPENFILENAME of;
   wxZeroMemory(of);
   
   // Allow Places bar to show on supported platforms
   if ( wxGetOsVersion() == wxWINDOWS_NT )
   {
      of.lStructSize       = sizeof(OPENFILENAME);
   }
   else
   {
      of.lStructSize       = OPENFILENAME_SIZE_VERSION_400;
   }
   
   of.hwndOwner         = hWnd;
   of.lpstrTitle        = WXSTRINGCAST m_message;
   of.lpstrFileTitle    = titleBuffer;
   of.nMaxFileTitle     = wxMAXFILE + 1 + wxMAXEXT;    // Windows 3.0 and 3.1
   of.lCustData         = (LPARAM) this;
   
   // Convert forward slashes to backslashes (file selector doesn't like
   // forward slashes) and also squeeze multiple consecutive slashes into one
   // as it doesn't like two backslashes in a row neither
   
   wxString  dir;
   size_t    i, len = m_dir.length();
   dir.reserve(len);
   for ( i = 0; i < len; i++ )
   {
      wxChar ch = m_dir[i];
      switch ( ch )
      {
         case _T('/'):
            // convert to backslash
            ch = _T('\\');
            
            // fall through
            
         case _T('\\'):
            while ( i < len - 1 )
            {
               wxChar chNext = m_dir[i + 1];
               if ( chNext != _T('\\') && chNext != _T('/') )
                  break;
               
               // ignore the next one, unless it is at the start of a UNC path
               if (i > 0)
                  i++;
               else
                  break;
            }
            // fall through
            
            default:
            // normal char
            dir += ch;
      }
   }
   
   of.lpstrInitialDir   = dir.c_str();
   
   of.Flags             = msw_flags;
   of.lpfnHook          = FileDialogHookFunction;
   
   wxArrayString wildDescriptions;
   
   size_t items = wxParseCommonDialogsFilter(m_wildCard, wildDescriptions, m_FilterGroups);
   
   wxASSERT_MSG( items > 0 , _T("empty wildcard list") );
   
   wxString filterBuffer;
   
   for (i = 0; i < items ; i++)
   {
      filterBuffer += wildDescriptions[i];
      filterBuffer += wxT("|");
      filterBuffer += wxT("*.*");
      filterBuffer += wxT("|");
   }
   
   // Replace | with \0
   for (i = 0; i < filterBuffer.Len(); i++ )
   {
      if ( filterBuffer.GetChar(i) == wxT('|') )
      {
         filterBuffer[i] = wxT('\0');
      }
   }
   
   of.lpstrFilter  = (LPTSTR)filterBuffer.c_str();
   of.nFilterIndex = m_filterIndex + 1;
   
   ParseFilter(of.nFilterIndex);
   
   //=== Setting defaultFileName >>=========================================
   
   wxStrncpy( fileNameBuffer, (const wxChar *)m_fileName, wxMAXPATH-1 );
   fileNameBuffer[ wxMAXPATH-1 ] = wxT('\0');
   
   of.lpstrFile = fileNameBuffer;  // holds returned filename
   of.nMaxFile  = wxMAXPATH;
   
   // we must set the default extension because otherwise Windows would check
   // for the existing of a wrong file with wxOVERWRITE_PROMPT (i.e. if the
   // user types "foo" and the default extension is ".bar" we should force it
   // to check for "foo.bar" existence and not "foo")
   wxString defextBuffer; // we need it to be alive until GetSaveFileName()!
   if (m_dialogStyle & wxSAVE && m_dialogStyle & wxOVERWRITE_PROMPT)
   {
      const wxChar* extension = filterBuffer;
      int maxFilter = (int)(of.nFilterIndex*2L) - 1;
      
      for( int i = 0; i < maxFilter; i++ )           // get extension
         extension = extension + wxStrlen( extension ) + 1;
      
      // use dummy name a to avoid assert in AppendExtension
      defextBuffer = AppendExtension(wxT("a"), extension);
      if (defextBuffer.StartsWith(wxT("a.")))
      {
         defextBuffer.Mid(2);
         of.lpstrDefExt = defextBuffer.c_str();
      }
   }
   
   // store off before the standard windows dialog can possibly change it 
   const wxString cwdOrig = wxGetCwd(); 
   
   //== Execute FileDialog >>=================================================
   
   bool success = (m_dialogStyle & wxSAVE ? GetSaveFileName(&of)
                   : GetOpenFileName(&of)) != 0;
   
#ifdef __WXWINCE__
   DWORD errCode = GetLastError();
#else
   DWORD errCode = CommDlgExtendedError();
   
   // GetOpenFileName will always change the current working directory on 
   // (according to MSDN) "Windows NT 4.0/2000/XP" because the flag 
   // OFN_NOCHANGEDIR has no effect.  If the user did not specify wxCHANGE_DIR 
   // let's restore the current working directory to what it was before the 
   // dialog was shown (assuming this behavior extends to Windows Server 2003 
   // seems safe). 
   if ( success && 
       (msw_flags & OFN_NOCHANGEDIR) && 
       wxGetOsVersion() == wxWINDOWS_NT ) 
   { 
      wxSetWorkingDirectory(cwdOrig); 
   } 
   
#ifdef __WIN32__
   if (!success && (errCode == CDERR_STRUCTSIZE))
   {
      // The struct size has changed so try a smaller or bigger size
      
      int oldStructSize = of.lStructSize;
      of.lStructSize       = oldStructSize - (sizeof(void *) + 2*sizeof(DWORD));
      success = (m_dialogStyle & wxSAVE) ? (GetSaveFileName(&of) != 0)
      : (GetOpenFileName(&of) != 0);
      errCode = CommDlgExtendedError();
      
      if (!success && (errCode == CDERR_STRUCTSIZE))
      {
         of.lStructSize       = oldStructSize + (sizeof(void *) + 2*sizeof(DWORD));
         success = (m_dialogStyle & wxSAVE) ? (GetSaveFileName(&of) != 0)
         : (GetOpenFileName(&of) != 0);
      }
   }
#endif // __WIN32__
#endif // __WXWINCE__
   
   if ( success )
   {
      m_fileNames.Empty();
      
      if ( ( m_dialogStyle & wxMULTIPLE ) &&
#if defined(OFN_EXPLORER)
          ( fileNameBuffer[of.nFileOffset-1] == wxT('\0') )
#else
          ( fileNameBuffer[of.nFileOffset-1] == wxT(' ') )
#endif // OFN_EXPLORER
          )
      {
#if defined(OFN_EXPLORER)
         m_dir = fileNameBuffer;
         i = of.nFileOffset;
         m_fileName = &fileNameBuffer[i];
         m_fileNames.Add(m_fileName);
         i += m_fileName.Len() + 1;
         
         while (fileNameBuffer[i] != wxT('\0'))
         {
            m_fileNames.Add(&fileNameBuffer[i]);
            i += wxStrlen(&fileNameBuffer[i]) + 1;
         }
#else
         wxStringTokenizer toke(fileNameBuffer, _T(" \t\r\n"));
         m_dir = toke.GetNextToken();
         m_fileName = toke.GetNextToken();
         m_fileNames.Add(m_fileName);
         
         while (toke.HasMoreTokens())
            m_fileNames.Add(toke.GetNextToken());
#endif // OFN_EXPLORER
         
         wxString dir(m_dir);
         if ( m_dir.Last() != _T('\\') )
            dir += _T('\\');
         
         m_path = dir + m_fileName;
         m_filterIndex = (int)of.nFilterIndex - 1;
      }
      else
      {
         //=== Adding the correct extension >>=================================
         m_filterIndex = (int)of.nFilterIndex - 1;
         
#if 0
         // LLL:  Removed to prevent adding extension during Export
         //       processing.
         
         if ( !of.nFileExtension ||
             (of.nFileExtension && fileNameBuffer[of.nFileExtension] == wxT('\0')) )
         {
            // User has typed a filename without an extension:
            const wxChar* extension = filterBuffer;
            int   maxFilter = (int)(of.nFilterIndex*2L) - 1;
            
            for( int i = 0; i < maxFilter; i++ )           // get extension
               extension = extension + wxStrlen( extension ) + 1;
            
            m_fileName = AppendExtension(fileNameBuffer, extension);
            wxStrncpy(fileNameBuffer, m_fileName.c_str(), wxMin(m_fileName.Len(), wxMAXPATH-1));
            fileNameBuffer[wxMin(m_fileName.Len(), wxMAXPATH-1)] = wxT('\0');
         }
#endif
         m_path = fileNameBuffer;
         m_fileName = wxFileNameFromPath(fileNameBuffer);
         m_fileNames.Add(m_fileName);
         m_dir = wxPathOnly(fileNameBuffer);
      }
   }
   else
   {
      // common dialog failed - why?
#ifdef __WXDEBUG__
#ifdef __WXWINCE__
      if (errCode == 0)
      {
         // OK, user cancelled the dialog
      }
      else if (errCode == ERROR_INVALID_PARAMETER)
      {
         wxLogError(wxT("Invalid parameter passed to file dialog function."));
      }
      else if (errCode == ERROR_OUTOFMEMORY)
      {
         wxLogError(wxT("Out of memory when calling file dialog function."));
      }
      else if (errCode == ERROR_CALL_NOT_IMPLEMENTED)
      {
         wxLogError(wxT("Call not implemented when calling file dialog function."));
      }
      else
      {
         wxLogError(wxT("Unknown error %d when calling file dialog function."), errCode);
      }
#else
      DWORD dwErr = CommDlgExtendedError();
      if ( dwErr != 0 )
      {
         // this msg is only for developers
         wxLogError(wxT("Common dialog failed with error code %0lx."),
                    dwErr);
      }
      //else: it was just cancelled
#endif
#endif
   }
   
   return success ? wxID_OK : wxID_CANCEL;
   
}
void menu(CBTYPE cbType, void* arg1)
{
    PLUG_CB_MENUENTRY* info = (PLUG_CB_MENUENTRY*)arg1;
    if(info->hEntry == 1)
    {
        // get patch information
        size_t buffersize;
        size_t numPatches;
        std::unique_ptr<DBGPATCHINFO> patchList(nullptr);
        if(!(patchList = EnumPatches(buffersize, numPatches)))
            return;
        // browse
        OPENFILENAME browse;
        memset(&browse, 0, sizeof(browse));
        browse.lStructSize = sizeof(browse);
        browse.hwndOwner = hwndDlg;
        browse.hInstance = hModule;
        wchar_t filter[512];
        memset(filter, 0, sizeof(filter));
        memset(templatename, 0, sizeof(templatename));
        memset(exportedname, 0, sizeof(exportedname));
        LoadString(hModule, IDS_FILTER, filter, 512);
        for(size_t i = 0; i < _countof(filter); i++)
        {
            if(filter[i] == '|')
                filter[i] = '\0';
        }
        browse.lpstrFilter = filter;
        browse.nFilterIndex = 1;
        browse.lpstrFile = templatename;
        browse.lpstrFileTitle = nullptr;
        browse.nMaxFile = 512;
        browse.Flags = OFN_FILEMUSTEXIST;
        if(GetOpenFileName(&browse) == 0)
            return;
        std::wstring templateContent = LoadFile(templatename);
        std::wstring filterString = getTemplateFilter(templateContent);
        browse.lpstrFile = exportedname;
        browse.lpstrFilter = filterString.c_str();
        browse.Flags = OFN_OVERWRITEPROMPT;
        if(GetSaveFileName(&browse) == 0)
            return;
        // export patches
        ExportPatch(templateContent, patchList.get(), numPatches);
    }
    else if(info->hEntry == 2)
    {
        // get patch information
        size_t buffersize;
        size_t numPatches;
        std::unique_ptr<DBGPATCHINFO> patchList(nullptr);
        if(!(patchList = EnumPatches(buffersize, numPatches)))
            return;
        // check last template
        if(wcslen(templatename) == 0)
        {
            MessageBox(hwndDlg, LoadWideString(IDS_NOLASTTEMPLATE).c_str(), LoadWideString(IDS_PLUGNAME).c_str(), MB_ICONERROR);
            return;
        }
        std::wstring templateContent = LoadFile(templatename);
        // browse
        OPENFILENAME browse;
        memset(&browse, 0, sizeof(browse));
        browse.lStructSize = sizeof(browse);
        browse.hwndOwner = hwndDlg;
        browse.hInstance = hModule;
        wchar_t filter[512];
        memset(filter, 0, sizeof(filter));
        memset(exportedname, 0, sizeof(exportedname));
        LoadString(hModule, IDS_FILTER, filter, 512);
        for(size_t i = 0; i < _countof(filter); i++)
        {
            if(filter[i] == '|')
                filter[i] = '\0';
        }
        std::wstring filterString = getTemplateFilter(templateContent);
        browse.lpstrFile = exportedname;
        browse.lpstrFilter = filterString.c_str();
        browse.nFilterIndex = 1;
        browse.lpstrFileTitle = nullptr;
        browse.nMaxFile = 512;
        browse.lpstrFile = exportedname;
        browse.Flags = OFN_OVERWRITEPROMPT;
        if(GetSaveFileName(&browse) == 0)
            return;
        // export patches
        ExportPatch(templateContent, patchList.get(), numPatches);
    }
    else if(info->hEntry == 3)
    {
        std::wstring text = LoadWideString(IDS_ABOUT);
        std::wstring compiledate;
        std::string compiledateASCII(__DATE__);
        utf8::utf8to16(compiledateASCII.begin(), compiledateASCII.end(), std::back_inserter(compiledate));
        ReplaceWString(text, L"$compiledate", compiledate);
        MessageBox(hwndDlg, text.c_str(), LoadWideString(IDS_PLUGNAME).c_str(), MB_OK);
    }
    else
    {
        __debugbreak();
    }
}
bool LLFilePickerBase::getSaveFile(ESaveFilter filter, std::string const& filename, std::string const& folder)
{
	if( mLocked )
	{
		return FALSE;
	}
	bool success = FALSE;

	llutf16string tstring = utf8str_to_utf16str(folder);
	mOFN.lpstrInitialDir = (LPCTSTR)tstring.data();
	mOFN.lpstrFile = mFilesW;
	if (!filename.empty())
	{
		llutf16string tstring = utf8str_to_utf16str(filename);
		wcsncpy(mFilesW, tstring.data(), FILENAME_BUFFER_SIZE);	}	/*Flawfinder: ignore*/
	else
	{
		mFilesW[0] = '\0';
	}

	switch( filter )
	{
	case FFSAVE_ALL:
		mOFN.lpstrDefExt = NULL;
		mOFN.lpstrFilter =
			L"All Files (*.*)\0*.*\0" \
			L"WAV Sounds (*.wav)\0*.wav\0" \
			L"Targa, Bitmap Images (*.tga; *.bmp)\0*.tga;*.bmp\0" \
			L"\0";
		break;
	case FFSAVE_WAV:
		if (filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.wav", FILENAME_BUFFER_SIZE);	/*Flawfinder: ignore*/
		}
		mOFN.lpstrDefExt = L"wav";
		mOFN.lpstrFilter =
			L"WAV Sounds (*.wav)\0*.wav\0" \
			L"\0";
		break;
	case FFSAVE_TGA:
		if (filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.tga", FILENAME_BUFFER_SIZE);	/*Flawfinder: ignore*/
		}
		mOFN.lpstrDefExt = L"tga";
		mOFN.lpstrFilter =
			L"Targa Images (*.tga)\0*.tga\0" \
			L"\0";
		break;
	case FFSAVE_BMP:
		if (filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.bmp", FILENAME_BUFFER_SIZE);	/*Flawfinder: ignore*/
		}
		mOFN.lpstrDefExt = L"bmp";
		mOFN.lpstrFilter =
			L"Bitmap Images (*.bmp)\0*.bmp\0" \
			L"\0";
		break;
	case FFSAVE_PNG:
		if (filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.png", FILENAME_BUFFER_SIZE);	/*Flawfinder: ignore*/
		}
		mOFN.lpstrDefExt = L"png";
		mOFN.lpstrFilter =
			L"PNG Images (*.png)\0*.png\0" \
			L"\0";
		break;
	case FFSAVE_JPEG:
		if (filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.jpg", FILENAME_BUFFER_SIZE);	/*Flawfinder: ignore*/
		}
		mOFN.lpstrDefExt = L"jpg";
		mOFN.lpstrFilter =
			L"JPEG Images (*.jpg *.jpeg)\0*.jpg;*.jpeg\0" \
			L"\0";
		break;
	case FFSAVE_AVI:
		if (filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.avi", FILENAME_BUFFER_SIZE);	/*Flawfinder: ignore*/
		}
		mOFN.lpstrDefExt = L"avi";
		mOFN.lpstrFilter =
			L"AVI Movie File (*.avi)\0*.avi\0" \
			L"\0";
		break;
	case FFSAVE_ANIM:
		if (filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.xaf", FILENAME_BUFFER_SIZE);	/*Flawfinder: ignore*/
		}
		mOFN.lpstrDefExt = L"xaf";
		mOFN.lpstrFilter =
			L"XAF Anim File (*.xaf)\0*.xaf\0" \
			L"\0";
		break;
#ifdef _CORY_TESTING
	case FFSAVE_GEOMETRY:
		if (filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.slg", FILENAME_BUFFER_SIZE);	/*Flawfinder: ignore*/
		}
		mOFN.lpstrDefExt = L"slg";
		mOFN.lpstrFilter =
			L"SLG SL Geometry File (*.slg)\0*.slg\0" \
			L"\0";
		break;
#endif
	case FFSAVE_XML:
		if (filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.xml", FILENAME_BUFFER_SIZE);	/*Flawfinder: ignore*/
		}

		mOFN.lpstrDefExt = L"xml";
		mOFN.lpstrFilter =
			L"XML File (*.xml)\0*.xml\0" \
			L"\0";
		break;
	case FFSAVE_COLLADA:
		if (filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.collada", FILENAME_BUFFER_SIZE);	/*Flawfinder: ignore*/
		}
		mOFN.lpstrDefExt = L"collada";
		mOFN.lpstrFilter =
			L"COLLADA File (*.collada)\0*.collada\0" \
			L"\0";
		break;
	case FFSAVE_RAW:
		if (filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.raw", FILENAME_BUFFER_SIZE);	/*Flawfinder: ignore*/
		}
		mOFN.lpstrDefExt = L"raw";
		mOFN.lpstrFilter =	RAW_FILTER \
							L"\0";
		break;
	case FFSAVE_J2C:
		if (filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.j2c", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"j2c";
		mOFN.lpstrFilter =
			L"Compressed Images (*.j2c)\0*.j2c\0" \
			L"\0";
		break;
	// <edit>
	case FFSAVE_ANIMATN:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.animatn", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"animatn";
		mOFN.lpstrFilter =
			L"SL Animations (*.animatn)\0*.animatn\0" \
			L"\0";
		break;
	case FFSAVE_OGG:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.ogg", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"ogg";
		mOFN.lpstrFilter =
			L"Ogg (*.ogg)\0*.ogg\0" \
			L"\0";
		break;
	case FFSAVE_NOTECARD:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.notecard", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"notecard";
		mOFN.lpstrFilter =
			L"Notecards (*.notecard)\0*.notecard\0" \
			L"\0";
		break;
	case FFSAVE_GESTURE:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.gesture", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"gesture";
		mOFN.lpstrFilter =
			L"Gestures (*.gesture)\0*.gesture\0" \
			L"\0";
		break;
	case FFSAVE_LSL:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.lsl", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"lsl";
		mOFN.lpstrFilter =
			L"LSL (*.lsl)\0*.lsl\0" \
			L"\0";
		break;
	case FFSAVE_SHAPE:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.shape", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"shape";
		mOFN.lpstrFilter =
			L"Shapes (*.shape)\0*.shape\0" \
			L"\0";
		break;
	case FFSAVE_SKIN:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.skin", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"skin";
		mOFN.lpstrFilter =
			L"Skins (*.skin)\0*.skin\0" \
			L"\0";
		break;
	case FFSAVE_HAIR:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.hair", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"hair";
		mOFN.lpstrFilter =
			L"Hair (*.hair)\0*.hair\0" \
			L"\0";
		break;
	case FFSAVE_EYES:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.eyes", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"eyes";
		mOFN.lpstrFilter =
			L"Eyes (*.eyes)\0*.eyes\0" \
			L"\0";
		break;
	case FFSAVE_SHIRT:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.shirt", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"shirt";
		mOFN.lpstrFilter =
			L"Shirts (*.shirt)\0*.shirt\0" \
			L"\0";
		break;
	case FFSAVE_PANTS:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.pants", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"pants";
		mOFN.lpstrFilter =
			L"Pants (*.pants)\0*.pants\0" \
			L"\0";
		break;
	case FFSAVE_SHOES:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.shoes", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"shoes";
		mOFN.lpstrFilter =
			L"Shoes (*.shoes)\0*.shoes\0" \
			L"\0";
		break;
	case FFSAVE_SOCKS:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.socks", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"socks";
		mOFN.lpstrFilter =
			L"Socks (*.socks)\0*.socks\0" \
			L"\0";
		break;
	case FFSAVE_JACKET:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.jacket", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"jacket";
		mOFN.lpstrFilter =
			L"Jackets (*.jacket)\0*.jacket\0" \
			L"\0";
		break;
	case FFSAVE_GLOVES:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.gloves", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"gloves";
		mOFN.lpstrFilter =
			L"Gloves (*.gloves)\0*.gloves\0" \
			L"\0";
		break;
	case FFSAVE_UNDERSHIRT:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.undershirt", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"undershirt";
		mOFN.lpstrFilter =
			L"Undershirts (*.undershirt)\0*.undershirt\0" \
			L"\0";
		break;
	case FFSAVE_UNDERPANTS:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.underpants", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"underpants";
		mOFN.lpstrFilter =
			L"Underpants (*.underpants)\0*.underpants\0" \
			L"\0";
		break;
	case FFSAVE_SKIRT:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.skirt", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"skirt";
		mOFN.lpstrFilter =
			L"Skirts (*.skirt)\0*.skirt\0" \
			L"\0";
		break;
	case FFSAVE_LANDMARK:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.landmark", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"landmark";
		mOFN.lpstrFilter =
			L"Landmarks (*.landmark)\0*.landmark\0" \
			L"\0";
		break;
	case FFSAVE_AO:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.ao", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"ao";
		mOFN.lpstrFilter =
			L"Animation overrides (*.ao)\0*.ao\0" \
			L"\0";
		break;
	case FFSAVE_INVGZ:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.inv", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L".inv";
		mOFN.lpstrFilter =
			L"InvCache (*.inv)\0*.inv\0" \
			L"\0";
		break;
	case FFSAVE_BLACKLIST:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.blacklist", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L".blacklist";
		mOFN.lpstrFilter =
			L"Asset Blacklists (*.blacklist)\0*.blacklist\0" \
			L"\0";
		break;
	case FFSAVE_PHYSICS:
		if(filename.empty())
		{
			wcsncpy( mFilesW,L"untitled.phy", FILENAME_BUFFER_SIZE);
		}
		mOFN.lpstrDefExt = L"phy";
		mOFN.lpstrFilter =
			L"Landmarks (*.phy)\0*.phy\0" \
			L"\0";
		break;
	// </edit>
	default:
		return FALSE;
	}
 
	mOFN.nMaxFile = SINGLE_FILENAME_BUFFER_SIZE;
	mOFN.Flags = OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR | OFN_PATHMUSTEXIST;

	reset();

	{
		// NOTA BENE: hitting the file dialog triggers a window focus event, destroying the selection manager!!
		success = GetSaveFileName(&mOFN);
		if (success)
		{
			std::string filename = utf16str_to_utf8str(llutf16string(mFilesW));
			mFiles.push_back(filename);
		}
	}

	return success;
}
Example #11
0
/*!
	ドラフトボードの内容をファイルに書き出す
	@param[in]	hWnd	ウインドウハンドル
	@param[in]	ptPath	未使用
*/
HRESULT DraughtItemExport( HWND hWnd, LPTSTR ptPath )
{
	CONST CHAR	cacSplit[] = ("[SPLIT]\r\n");	//	9BYTE

	UINT_PTR	dItems, cbSize;
	TCHAR		atPath[MAX_PATH], atName[MAX_PATH];
	BOOLEAN		bOpened;
	OPENFILENAME	stOpenFile;

	MAAM_ITR	itItem;

	HANDLE	hFile;
	DWORD	wrote;


	dItems = gvcDrtItems.size();
	if( 0 >= dItems )	return E_NOTIMPL;	//	空なら何もしない

	//ファイル名確定
	ZeroMemory( atPath, sizeof(atPath) );
	ZeroMemory( atName, sizeof(atName) );

	ZeroMemory( &stOpenFile, sizeof(OPENFILENAME) );
	stOpenFile.lStructSize     = sizeof(OPENFILENAME);
	stOpenFile.hwndOwner       = ghPtWnd;
	stOpenFile.lpstrFilter     = TEXT("複数行テンプレファイル(*.mlt)\0*.mlt\0全ての形式(*.*)\0*.*\0\0");
	stOpenFile.nFilterIndex    = 1;
	stOpenFile.lpstrFile       = atPath;
	stOpenFile.nMaxFile        = MAX_PATH;
	stOpenFile.lpstrFileTitle  = atName;
	stOpenFile.nMaxFileTitle   = MAX_PATH;
	stOpenFile.lpstrTitle      = TEXT("保存するファイル名を指定してね");
	stOpenFile.Flags           = OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY;
	stOpenFile.lpstrDefExt     = TEXT("mlt");

	//ここで FileOpenDialogue を出す
	bOpened = GetSaveFileName( &stOpenFile );
	wrote = CommDlgExtendedError();

	TRACE( TEXT("ファイル保存ダイヤログ通過[%X]"), wrote );

#ifndef _ORRVW
	ViewFocusSet(  );
#endif
	if( !(bOpened) ){	return  E_ABORT;	}	//	キャンセルしてたら何もしない

	hFile = CreateFile( atPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
	if( INVALID_HANDLE_VALUE == hFile ){	return E_HANDLE;	}

	SetFilePointer( hFile, 0, NULL, FILE_BEGIN );

	for( itItem = gvcDrtItems.begin(); gvcDrtItems.end() != itItem; itItem++ )
	{
		StringCchLengthA( itItem->pcItem, STRSAFE_MAX_LENGTH, &cbSize );
		
		WriteFile( hFile, itItem->pcItem, cbSize, &wrote, NULL );
		WriteFile( hFile, cacSplit, 9, &wrote, NULL );	//	固定値注意
	}

	CloseHandle( hFile );

	MessageBox( hWnd, TEXT("ファイルに保存したよ"), TEXT("お燐からのお知らせ"), MB_OK | MB_ICONINFORMATION );

	return S_OK;
}
Example #12
0
LRESULT WINAPI WMCommandProc(HWND hWnd, UINT id, HWND hwndCtl, UINT codeNotify) {
  switch (codeNotify) {
    case BN_CLICKED:    // The user pressed a button
    case LBN_SELCHANGE: // The user changed the selection in a ListBox control
//  case CBN_SELCHANGE: // The user changed the selection in a DropList control (same value as LBN_SELCHANGE)
    {
      char szBrowsePath[MAX_PATH];
      int nIdx = FindControlIdx(id);
      // Ignore if the dialog is in the process of being created
      if (g_done || nIdx < 0)
        break;
      if (pFields[nIdx].nType == FIELD_BROWSEBUTTON)
        --nIdx;
      FieldType *pField = pFields + nIdx;
      switch (pField->nType) {
        case FIELD_FILEREQUEST: {
          OPENFILENAME ofn={0,};

          ofn.lStructSize = sizeof(ofn);
          ofn.hwndOwner = hConfigWindow;
          ofn.lpstrFilter = pField->pszFilter;
          ofn.lpstrFile = szBrowsePath;
          ofn.nMaxFile  = sizeof(szBrowsePath);
          ofn.Flags = pField->nFlags & (OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_CREATEPROMPT | OFN_EXPLORER);

          GetWindowText(pField->hwnd, szBrowsePath, sizeof(szBrowsePath));

        tryagain:
          if ((pField->nFlags & FLAG_SAVEAS) ? GetSaveFileName(&ofn) : GetOpenFileName(&ofn)) {
            mySetWindowText(pField->hwnd, szBrowsePath);
            break;
          }
          else if (szBrowsePath[0] && CommDlgExtendedError() == FNERR_INVALIDFILENAME) {
            szBrowsePath[0] = '\0';
            goto tryagain;
          }

          break;
        }

        case FIELD_DIRREQUEST: {
          BROWSEINFO bi;

          bi.hwndOwner = hConfigWindow;
          bi.pidlRoot = NULL;
          bi.pszDisplayName = szBrowsePath;
          bi.lpszTitle = pField->pszText;
#ifndef BIF_NEWDIALOGSTYLE
#define BIF_NEWDIALOGSTYLE 0x0040
#endif
          bi.ulFlags = BIF_STATUSTEXT | BIF_RETURNONLYFSDIRS | BIF_NEWDIALOGSTYLE;
          bi.lpfn = BrowseCallbackProc;
          bi.lParam = nIdx;
          bi.iImage = 0;

          if (pField->pszRoot) {
            LPSHELLFOLDER sf;
            ULONG eaten;
            LPITEMIDLIST root;
            int ccRoot = (lstrlen(pField->pszRoot) * 2) + 2;
            LPWSTR pwszRoot = (LPWSTR) MALLOC(ccRoot);
            MultiByteToWideChar(CP_ACP, 0, pField->pszRoot, -1, pwszRoot, ccRoot);
            SHGetDesktopFolder(&sf);
            sf->ParseDisplayName(hConfigWindow, NULL, pwszRoot, &eaten, &root, NULL);
            bi.pidlRoot = root;
            sf->Release();
            FREE(pwszRoot);
          }
//          CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
          LPITEMIDLIST pResult = SHBrowseForFolder(&bi);
          if (!pResult)
            break;

          if (SHGetPathFromIDList(pResult, szBrowsePath)) {
            mySetWindowText(pField->hwnd, szBrowsePath);
          }

          LPMALLOC pMalloc;
          if (!SHGetMalloc(&pMalloc)) {
            pMalloc->Free(pResult);
          }

          break;
        }

        case FIELD_LINK:
        case FIELD_BUTTON:
          // Allow the state to be empty - this might be useful in conjunction
          // with the NOTIFY flag
          if (*pField->pszState)
            ShellExecute(hMainWindow, NULL, pField->pszState, NULL, NULL, SW_SHOWDEFAULT);
          break;
      }

      if (pField->nFlags & LBS_NOTIFY) {
        // Remember which control was activated then pretend the user clicked Next
        g_NotifyField = nIdx + 1;
        // the next button must be enabled or nsis will ignore WM_COMMAND
        BOOL bWasDisabled = EnableWindow(hNextButton, TRUE);
        FORWARD_WM_COMMAND(hMainWindow, IDOK, hNextButton, BN_CLICKED, mySendMessage);
        if (bWasDisabled)
          EnableWindow(hNextButton, FALSE);
      }
    }
    break;
  }
  return 0;
}
Example #13
0
/*
	FileSave: Handles a request to save the currently open file.

	Parameters:
	HWND sheet: Handle to the property sheet.
	bool as:		Save or Save As?
*/
void FileSave(HWND sheet, bool as, bool write)
{
	int error;			//error value from Scenario::save()
	HWND cpage;			//the current property page
	HCURSOR previous;	//the mouse cursor before/after save operation
	OPENFILENAME ofn;
	char titleBuffer[100];
	Game startver;
	Game conv = NOCONV;
    SaveFlags::Value flags = SaveFlags::NONE;

    char w1[] = {84, 104, 105, 115, 32, 115, 99, 101, 110, 97, 114, 105, 111, 32, 105, 115, 32, 112, 114, 111, 116, 101, 99, 116, 101, 100, 0};
    char w2[] = {83, 99, 101, 110, 97, 114, 105, 111, 32, 105, 115, 32, 112, 114, 111, 116, 101, 99, 116, 101, 100, 0};
    if (setts.disabletips) {
        MessageBox(sheet, w1, w2, MB_ICONWARNING);
        return;
    }

	//init
	cpage = PropSheet_GetCurrentPageHwnd(sheet);

	//Save As: Ask for filename.
	if (as || *setts.ScenPath == '\0')
	{
		char dir[_MAX_PATH];
		strcpy(dir, setts.BasePath);
		strcat(dir, "Scenario");

		ofn.lStructSize = sizeof(OPENFILENAME);
		ofn.hwndOwner = sheet;
		ofn.lpstrFilter = extSave;
		ofn.lpstrCustomFilter = NULL;
		ofn.lpstrFile = setts.ScenPath;
		ofn.nMaxFile = _MAX_PATH;
		ofn.lpstrFileTitle = NULL;
		ofn.lpstrInitialDir = dir;
		ofn.lpstrTitle = NULL;
		ofn.Flags = OFN_NOREADONLYRETURN | OFN_OVERWRITEPROMPT;

	    startver = scen.game;

		if (scen.header.header_type == HT_AOE2SCENARIO) {
		    ofn.nFilterIndex =	6;
		    ofn.lpstrDefExt =	"aoe2scenario";
		} else {
		    switch (scen.game) {
		    case AOK:
		        ofn.nFilterIndex =	1;
		        ofn.lpstrDefExt =	"scn";
		        break;
		    case AOC:
		        ofn.nFilterIndex =	2;
		        ofn.lpstrDefExt =	"scx";
		        break;
		    case UP:
		        ofn.nFilterIndex =	3;
		        ofn.lpstrDefExt =	"scx";
		        break;
		    case AOHD:
		    case AOHD4:
		        ofn.nFilterIndex =	4;
		        ofn.lpstrDefExt =	"scx";
		        break;
		    case AOF:
		    case AOF4:
		        ofn.nFilterIndex =	5;
		        ofn.lpstrDefExt =	"scx2";
		        break;
		    case SWGB:
		        ofn.nFilterIndex =	7;
		        ofn.lpstrDefExt =	"scx";
		        break;
		    case SWGBCC:
		        ofn.nFilterIndex =	8;
		        ofn.lpstrDefExt =	"sc1";
		        break;
		    case AOHD6:
		        ofn.nFilterIndex =	9;
		        ofn.lpstrDefExt =	"scx";
		        break;
		    case AOF6:
		        ofn.nFilterIndex =	10;
		        ofn.lpstrDefExt =	"scx2";
		        break;
		    }
		}

		if (!GetSaveFileName(&ofn))
			return;

		switch (ofn.nFilterIndex) {
		case 1:
		    conv = AOK;
		    break;
		case 2:
		    conv = AOC;
		    break;
		case 3:
		    conv = UP;
		    break;
		case 4:
		    conv = AOHD4;
		    break;
		case 5:
		    conv = AOF4;
		    break;
		case 6:
	        scen.header.header_type = HT_AOE2SCENARIO;
		    conv = startver;
		    break;
		case 7:
		    conv = SWGB;
		    break;
		case 8:
		    conv = SWGBCC;
		    break;
		case 9:
		    conv = AOHD6;
		    break;
		case 10:
		    conv = AOF6;
		    break;
		}

		if (!*scen.origname)
			strcpy(scen.origname, setts.ScenPath + ofn.nFileOffset);

		/* Update window title since filename has probably changed */
		_snprintf(titleBuffer, sizeof(titleBuffer),
			"%s - %s", szTitle, setts.ScenPath + ofn.nFileOffset);
		SetWindowText(sheet, titleBuffer);
	} else {
	    conv = scen.game;
	}

    if (isHD(startver) && conv == UP) {
        if (setts.asktoconverteffects &&
            MessageBox(sheet, "Also convert HD effects to UserPatch?", "Convert", MB_YESNOCANCEL) == IDYES) {
            flags = (SaveFlags::Value)(flags | SaveFlags::CONVERT_EFFECTS);
        }
    }

    if (startver == UP && isHD(conv)) {
        if (setts.asktoconverteffects &&
            MessageBox(sheet, "Also convert UserPatch effects to HD?", "Convert", MB_YESNOCANCEL) == IDYES) {
            flags = (SaveFlags::Value)(flags | SaveFlags::CONVERT_EFFECTS);
        }
    }

	//update scenario data
	SendMessage(cpage, AOKTS_Saving, 0, 0);

	//perform before-saving operations
	previous = SetCursor(LoadCursor(NULL, IDC_WAIT));
	// Pretend we're "closing" the scenario because it may change during the
	// save.
	SendMessage(cpage, AOKTS_Closing, 0, 0);
	scen.clean_triggers();

	//save the scenario
	try
	{
 		error = scen.save(setts.ScenPath, setts.TempPath, write, conv, flags);
		SetCursor(previous);

	    struct RecentFile *file = NULL;	//the file info will be stored here one way or another
		struct RecentFile *r_parse;

		/* Now check if file is already on recent list. */
		r_parse = setts.recent_first;
		while (r_parse)
		{
			if (!strcmp(r_parse->path, setts.ScenPath))
			{
				file = r_parse;
				break;
			}
			r_parse = r_parse->next;
		}

        if (file) {
            file->game = (int)conv;
        } else {
		    file = setts.recent_getnext();
		    strcpy(file->path, setts.ScenPath);
		    strcpy(file->display, PathFindFileName(setts.ScenPath));
		    file->game = (int)conv;
	        setts.recent_push(file);
	    }
	    UpdateRecentMenu(propdata.menu);
	}
	catch (std::exception &ex)
	{
		// TODO: better atomic cursor handling?
		SetCursor(previous);
		MessageBox(sheet, ex.what(), "Scenario Save Error", MB_ICONWARNING);
	}

	//perform after-saving operations
	SendMessage(cpage, AOKTS_Loading, 0, 0);

	//report any errors
	if (error)
	{
		SetWindowText(propdata.statusbar, scen.msg);
		//MessageBox(sheet, scen.msg, "Save Error", MB_OK);
	}
}
Example #14
0
	INT_PTR CALLBACK NewH86ProjectDlg::DlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam){
		switch(uMsg){
		case WM_CLOSE:
			EndDialog(hWnd, WM_QUIT);
			break;
		case WM_COMMAND:
			switch(LOWORD(wParam)){
			case IDC_BROWSE_PROJECT_PATH:
				{
					wchar_t path[MAX_PATH]={ 0 };

					OPENFILENAME ofn;
					ZeroMemory(&ofn, sizeof(ofn));
					ofn.lStructSize=sizeof(ofn);
					ofn.hwndOwner=m_hWnd;
					ofn.hInstance=Application::hInstance;
					ofn.lpstrFilter=L"Hard86 Project files\0*.h86\0\0All files\0*.*\0\0";
					ofn.nFilterIndex=1;
					ofn.lpstrFile=path;
					ofn.nMaxFile=MAX_PATH;

					if(!GetSaveFileName(&ofn)) break;	// if user pressed cancel, abort operation
					SetDlgItemText(hWnd, IDC_PROJECT_PATH, path);
				}
				break;
			case IDC_BROWSE_BINARY_PATH:
				{
					wchar_t path[MAX_PATH]={ 0 };

					OPENFILENAME ofn;
					ZeroMemory(&ofn, sizeof(ofn));
					ofn.lStructSize=sizeof(ofn);
					ofn.hwndOwner=m_hWnd;
					ofn.hInstance=Application::hInstance;
					ofn.lpstrFilter=L"Binary files\0*.com\0\0All files\0*.*\0\0";
					ofn.nFilterIndex=1;
					ofn.lpstrFile=path;
					ofn.nMaxFile=MAX_PATH;

					if(!GetSaveFileName(&ofn)) break;	// if user pressed cancel, abort operation
					SetDlgItemText(hWnd, IDC_BINARY_PATH, path);
				}
				break;

			case IDC_BROWSE_FAS_PATH:
				{
					wchar_t path[MAX_PATH]={ 0 };

					OPENFILENAME ofn;
					ZeroMemory(&ofn, sizeof(ofn));
					ofn.lStructSize=sizeof(ofn);
					ofn.hwndOwner=m_hWnd;
					ofn.hInstance=Application::hInstance;
					ofn.lpstrFilter=L"FASM symbol files\0*.fas\0\0All files\0*.*\0\0";
					ofn.nFilterIndex=1;
					ofn.lpstrFile=path;
					ofn.nMaxFile=MAX_PATH;

					if(!GetSaveFileName(&ofn)) break;	// if user pressed cancel, abort operation
					SetDlgItemText(hWnd, IDC_FAS_PATH, path);
				}
				break;
			case IDOK:
			{
					wchar_t tmp_path[MAX_PATH]={ 0 };
					GetDlgItemText(hWnd, IDC_PROJECT_PATH, tmp_path, MAX_PATH);
					m_projectPath=tmp_path;
					GetDlgItemText(hWnd, IDC_BINARY_PATH, tmp_path, MAX_PATH);
					m_binPath=File::GetRelativePath(tmp_path, m_projectPath);
					GetDlgItemText(hWnd, IDC_FAS_PATH, tmp_path, MAX_PATH);
					m_fasPath=File::GetRelativePath(tmp_path, m_projectPath);
					try{
						xml_document<>* doc=new xml_document<>();
						doc->append_node(doc->allocate_node(node_element, "Hard86Project"));
						xml_node<>* node=doc->first_node();
						node->append_node(doc->allocate_node(node_element, "Variables"));
						node=node->first_node();
						node->append_node(doc->allocate_node(node_element, "LoadSegAddr"));
						node=node->first_node();
						node->append_attribute(doc->allocate_attribute("seg", doc->allocate_string("0")));
						node->append_attribute(doc->allocate_attribute("addr", doc->allocate_string("0")));
						node=node->parent();	// Variables
						node=node->parent();	// Hard86Project
						node->append_node(doc->allocate_node(node_element, "Paths"));
						node=node->first_node("Paths");
						node->append_attribute(doc->allocate_attribute("binaryPath", doc->allocate_string(wstrtostr(m_binPath).c_str())));
						node->append_attribute(doc->allocate_attribute("FASPath", doc->allocate_string(wstrtostr(m_fasPath).c_str())));
						node->append_attribute(doc->allocate_attribute("userVDevPath", ""));
						node=node->parent();	// Hard86Project
						node->append_node(doc->allocate_node(node_element, "VDevs"));
						node->append_node(doc->allocate_node(node_element, "BPList"));

						File projectFile(m_projectPath);
						if(projectFile.Exists()){
							projectFile.Delete();
						}
						projectFile.Create();
						projectFile.Open();
						
						char* xmlBuffer=new char[1024*1024];

						*(print(xmlBuffer, *doc, 0))=NULL;
						projectFile.Write(xmlBuffer);
						projectFile.Close();

						delete[] xmlBuffer;
					}
					catch(rapidxml::parse_error e){
						OUT_DEBUG("RapidXML error encountered");
					}
					Application::GetInstance()->mainFrame->LoadProjectToFrontend(m_projectPath);
					EndDialog(hWnd, WM_QUIT);
				}
				break;
			}
		default:
			return 0;
		}
		return 0;
	}
Example #15
0
BOOL CALLBACK EV_DlgMain(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch(uMsg)
    {
    case WM_INITDIALOG:
    {
        EV_shared=hwndDlg;
        EV_list_hwnd=GetDlgItem(hwndDlg, IDC_LIST);
    }
    return TRUE;

    case WM_CLOSE:
    {
        EndDialog(hwndDlg, 0);
    }
    return TRUE;

    case WM_BROWSE:
    {
        SendMessageA(EV_list_hwnd, LB_RESETCONTENT, 0, 0);
        strcpy(EV_szFileName, (const char*)wParam);
        strcpy(EV_program_dir, EV_szFileName);
        int i=strlen(EV_program_dir);
        while(EV_program_dir[i]!='\\')
            i--;
        EV_program_dir[i]=0;
        CreateThread(0, 0, EV_DebugThread, 0, 0, 0);
    }
    return TRUE;

    case WM_DROPFILES:
    {
        SendMessageA(EV_list_hwnd, LB_RESETCONTENT, 0, 0);
        DragQueryFileA((HDROP)wParam, 0, EV_szFileName, MAX_PATH);
        strcpy(EV_program_dir, EV_szFileName);
        int i=strlen(EV_program_dir);
        while(EV_program_dir[i]!='\\')
            i--;
        EV_program_dir[i]=0;
        CreateThread(0, 0, EV_DebugThread, 0, 0, 0);
    }
    return TRUE;

    case WM_CONTEXTMENU:
    {
        if(GetDlgCtrlID((HWND)wParam)==IDC_LIST)
        {
            LeftClick();
            LeftClick();
        }
    }
    return TRUE;

    case WM_HELP:
    {
        char id[10]="";
        sprintf(id, "%d", IDS_HELPEVLOG);
        SetEnvironmentVariableA("HELPID", id);
        SetEnvironmentVariableA("HELPTITLE", "EVLog Help");
        DialogBox(hInst, MAKEINTRESOURCE(DLG_HELP), hwndDlg, DlgHelp);
    }
    return TRUE;

    case WM_COMMAND:
    {
        switch(LOWORD(wParam))
        {
        case IDC_LIST:
        {
            switch(HIWORD(wParam))
            {
            case LBN_DBLCLK:
            {
                int cursel=SendMessageA(EV_list_hwnd, LB_GETCURSEL, 0, 0);
                int count=SendMessageA(EV_list_hwnd, LB_GETCOUNT, 0, 0);
                if(!count)
                    return TRUE;
                char line_text[1024]="";
                char var_name[512]="";
                char var_value[512]="";
                SendMessageA(EV_list_hwnd, LB_GETTEXT, cursel, (LPARAM)line_text);
                int len=strlen(line_text);
                for(int i=0,j=0,k=0,l=0; i<len; i++)
                {
                    if(line_text[i]=='=')
                    {
                        i++;
                        j=1;
                    }
                    if(!j)
                        k+=sprintf(var_name+k, "%c", line_text[i]);
                    else
                        l+=sprintf(var_value+l, "%c", line_text[i]);
                }
                HMENU myMenu=0;
                myMenu=CreatePopupMenu();
                AppendMenu(myMenu, MF_STRING, 1, "Copy Variable &Name");
                if(strcmp(var_value, "(0)"))
                    AppendMenu(myMenu, MF_STRING, 2, "Copy Variable &Value");
                AppendMenu(myMenu, MF_STRING, 3, "Copy &Line");
                POINT cursorPos;
                GetCursorPos(&cursorPos);
                SetForegroundWindow(hwndDlg);
                UINT MenuItemClicked=TrackPopupMenu(myMenu, TPM_RETURNCMD|TPM_NONOTIFY, cursorPos.x, cursorPos.y, 0, hwndDlg, 0);
                SendMessage(hwndDlg, WM_NULL, 0, 0);
                switch(MenuItemClicked)
                {
                case 1:
                    CopyToClipboard(var_name);
                    break;
                case 2:
                    CopyToClipboard(var_value);
                    break;
                case 3:
                    CopyToClipboard(line_text);
                    break;
                }
            }
            return TRUE;
            }
        }
        return TRUE;

        case IDC_BTN_DUMP:
        {
            char massive_string[32768]="", single_string[255]="Coded by Mr. eXoDia // T.P.o.D.T 2012\r\n\r\n";
            int total=SendDlgItemMessage(hwndDlg, IDC_LIST, LB_GETCOUNT, 0, 0);
            for(int i=0; i!=total; i++)
            {
                SendDlgItemMessage(hwndDlg, IDC_LIST, LB_GETTEXT, (WPARAM)i, (LPARAM)single_string);
                sprintf(massive_string, "%s%s\r\n", massive_string, single_string);
            }
            char log_filename[MAX_PATH]="";
            log_filename[0]=0;
            OPENFILENAME ofstruct;
            memset(&ofstruct, 0, sizeof(ofstruct));
            ofstruct.lStructSize=sizeof(ofstruct);
            ofstruct.hwndOwner=hwndDlg;
            ofstruct.hInstance=hInst;
            ofstruct.lpstrFilter="Log files (*.log)\0*.log\0\0";
            ofstruct.lpstrFile=log_filename;
            ofstruct.nMaxFile=MAX_PATH;
            ofstruct.lpstrInitialDir=EV_program_dir;
            ofstruct.lpstrTitle="Save file";
            ofstruct.lpstrDefExt="log";
            ofstruct.Flags=OFN_EXTENSIONDIFFERENT|OFN_HIDEREADONLY|OFN_NONETWORKBUTTON|OFN_OVERWRITEPROMPT;
            GetSaveFileName(&ofstruct);
            if(!log_filename[0])
                return TRUE;
            HANDLE hFile=CreateFileA(log_filename, GENERIC_ALL, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
            if(hFile==INVALID_HANDLE_VALUE)
            {
                MessageBoxA(hwndDlg, "Could not create the file, maybe it's in use...", "Error!", MB_ICONERROR);
                return TRUE;
            }
            DWORD written=0;
            if(!WriteFile(hFile, massive_string, strlen(massive_string), &written, 0))
            {
                CloseHandle(hFile);
                MessageBoxA(hwndDlg, "Could not write to the file, maybe it's in use...", "Error!", MB_ICONERROR);
                return TRUE;
            }
            CloseHandle(hFile);
        }
        return TRUE;
        }
    }
    return TRUE;
    }
    return FALSE;
}
Example #16
0
BOOL DumpImage(HDC hScreen, HBITMAP hBitmap, int anX, int anY, int anWidth, int anHeight, LPCWSTR pszFile, bool PreserveTransparency/*=true*/)
{
	BOOL lbRc = FALSE;
	LPBYTE pScreen = NULL;
	DWORD cbOut = 0;

	wchar_t* pszDot = NULL;
	wchar_t szFile[MAX_PATH+1] = {};

	if (pszFile)
	{
		lstrcpynW(szFile, pszFile, MAX_PATH);
		pszDot = (wchar_t*)PointToExt(szFile);
	}


	#ifdef PNGDUMP
	// Если передали готовый hBitmap - сохранить сразу
	if (pszDot)
		lstrcpyW(pszDot, L".png");

	if (hBitmap && SaveImageEx(szFile, hBitmap))
	{
		return TRUE;
	}
	#endif


	// иначе - снять копию с hScreen
	if (!LoadScreen(hScreen, anX, anY, anWidth, anHeight, &pScreen, &cbOut, PreserveTransparency))
		return FALSE;

	if (!*szFile)
	{
		//static wchar_t szLastDumpFile[MAX_PATH];
        SYSTEMTIME st; GetLocalTime(&st);
        _wsprintf(szFile, SKIPLEN(countof(szFile)) L"%02u%02u%02u%02u%02u%02u",
        	st.wYear%100, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);

		OPENFILENAME ofn; memset(&ofn,0,sizeof(ofn));
		ofn.lStructSize=sizeof(ofn);
		HWND h = GetForegroundWindow();
		DWORD nPID = 0;
		if (h)
			GetWindowThreadProcessId(h, &nPID);
		ofn.hwndOwner = (nPID == GetCurrentProcessId()) ? h : ghWnd;
		#ifdef PNGDUMP
		ofn.lpstrFilter = L"PNG (*.png)\0*.png\0JPEG (*.jpg)\0*.jpg\0BMP (*.bmp)\0*.bmp\0\0";
		ofn.lpstrDefExt = L"png";
		#else
		ofn.lpstrFilter = L"BMP (*.bmp)\0*.bmp\0\0";
		ofn.lpstrDefExt = L"bmp";
		#endif
		ofn.nFilterIndex = 1;
		ofn.lpstrFile = szFile;
		ofn.nMaxFile = countof(szFile);
		ofn.lpstrTitle = L"Save screenshot";
		ofn.Flags = OFN_ENABLESIZING|OFN_NOCHANGEDIR
		        | OFN_PATHMUSTEXIST|OFN_EXPLORER|OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT;
		if (!GetSaveFileName(&ofn) || ((pszDot = (wchar_t*)PointToExt(szFile)) == NULL))
		{
			lbRc = TRUE; // чтобы не ругалось...
		    goto wrap;
	    }
		//wcscpy_c(szFile, szLastDumpFile);
	}

	#ifdef PNGDUMP
	if (SaveImageEx(szFile, pScreen, cbOut))
	{
		lbRc = TRUE;
        goto wrap;
	}
	#endif


	if (pScreen && cbOut)
	{
		if (pszDot)
		{
			#ifdef PNGDUMP
			lstrcpyW(pszDot, L".png");
			#else
			lstrcpyW(pszDot, L".bmp");
			#endif

			HANDLE hFile = CreateFile(szFile, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);

			if (hFile != INVALID_HANDLE_VALUE)
			{
				DWORD dwWritten = 0;
				lbRc = WriteFile(hFile, pScreen, cbOut, &dwWritten, 0);
				CloseHandle(hFile);
			}
		}
	}

wrap:
	SafeFree(pScreen);
	return lbRc;
}
Example #17
0
//---------------------------------------------------------------------------
bool TVPSelectFile(iTJSDispatch2 *params)
{
	// show open dialog box
	// NOTE: currently this only shows ANSI version of file open dialog.
	tTJSVariant val;
	char * filter = NULL;
	char * filename = NULL;
	AnsiString initialdir;
	AnsiString title;
	AnsiString defaultext;
	BOOL result;

	try
	{
		// prepare OPENFILENAME structure

		OPENFILENAME ofn;
		memset(&ofn, 0, sizeof(ofn));
		ofn.lStructSize = sizeof(ofn);
		ofn.hwndOwner = TVPGetModalWindowOwnerHandle();
		ofn.hInstance = NULL;

		// set application window position to current window position
		

		// get filter
		ofn.lpstrFilter = NULL;

		if(TJS_SUCCEEDED(params->PropGet(TJS_MEMBERMUSTEXIST, TJS_W("filter"), 0,
			&val, params)))
		{
			std::vector<AnsiString> filterlist;
			if(val.Type() != tvtObject)
			{
				TVPPushFilterPair(filterlist, ttstr(val).AsAnsiString());
			}
			else
			{
				iTJSDispatch2 * array = val.AsObjectNoAddRef();
				tjs_int count;
				tTJSVariant tmp;
				if(TJS_SUCCEEDED(array->PropGet(TJS_MEMBERMUSTEXIST,
					TJS_W("count"), 0, &tmp, array)))
					count = tmp;
				else
					count = 0;

				for(tjs_int i = 0; i < count; i++)
				{
					if(TJS_SUCCEEDED(array->PropGetByNum(TJS_MEMBERMUSTEXIST,
						i, &tmp, array)))
					{
						TVPPushFilterPair(filterlist, ttstr(tmp).AsAnsiString());
					}
				}
			}

			// create filter buffer
			tjs_int bufsize = 2;
			for(std::vector<AnsiString>::iterator i = filterlist.begin();
				i != filterlist.end(); i++)
			{
				bufsize += i->Length() + 1;
			}

			filter = new char[bufsize];

			char *p = filter;
			for(std::vector<AnsiString>::iterator i = filterlist.begin();
				i != filterlist.end(); i++)
			{
				strcpy(p, i->c_str());
				p += i->Length() + 1;
			}
			*(p++) = 0;
			*(p++) = 0;

			ofn.lpstrFilter = filter;
		}

		ofn.lpstrCustomFilter = NULL;
		ofn.nMaxCustFilter = 0;

		if(TJS_SUCCEEDED(params->PropGet(TJS_MEMBERMUSTEXIST, TJS_W("filterIndex"), 0,
			&val, params)))
			ofn.nFilterIndex = (tjs_int)val;
		else
			ofn.nFilterIndex = 0;

		// filenames
		filename = new char [MAX_PATH + 1];
 		filename[0] = 0;

		if(TJS_SUCCEEDED(params->PropGet(TJS_MEMBERMUSTEXIST, TJS_W("name"), 0,
			&val, params)))
		{
			ttstr lname(val);
			if(!lname.IsEmpty())
			{
				lname = TVPNormalizeStorageName(lname);
				TVPGetLocalName(lname);
				AnsiString name = lname.AsAnsiString();
				strncpy(filename, name.c_str(), MAX_PATH);
				filename[MAX_PATH] = 0;
			}
		}

		ofn.lpstrFile = filename;
		ofn.nMaxFile = MAX_PATH + 1;
		ofn.lpstrFileTitle = NULL;
		ofn.nMaxFileTitle = 0;

		// initial dir
		ofn.lpstrInitialDir = NULL;
		if(TJS_SUCCEEDED(params->PropGet(TJS_MEMBERMUSTEXIST, TJS_W("initialDir"), 0,
			&val, params)))
		{
			ttstr lname(val);
			if(!lname.IsEmpty())
			{
				lname = TVPNormalizeStorageName(lname);
				TVPGetLocalName(lname);
				initialdir = lname.AsAnsiString();
				ofn.lpstrInitialDir = initialdir.c_str();
			}
		}
	
		// title
		if(TJS_SUCCEEDED(params->PropGet(TJS_MEMBERMUSTEXIST, TJS_W("title"), 0,
			&val, params)))
		{
			title = ttstr(val).AsAnsiString();
			ofn.lpstrTitle = title.c_str();
		}
		else
		{
			ofn.lpstrTitle = NULL;
		}

		// flags
		bool issave = false;
		if(TJS_SUCCEEDED(params->PropGet(TJS_MEMBERMUSTEXIST, TJS_W("save"), 0,
			&val, params)))
			issave = val.operator bool();

		ofn.Flags = OFN_ENABLEHOOK|OFN_EXPLORER|OFN_NOCHANGEDIR|
			OFN_PATHMUSTEXIST|OFN_HIDEREADONLY|OFN_ENABLESIZING;


		if(!issave)
			ofn.Flags |= OFN_FILEMUSTEXIST;
		else
			ofn.Flags |= OFN_OVERWRITEPROMPT;

		// default extension
		if(TJS_SUCCEEDED(params->PropGet(TJS_MEMBERMUSTEXIST, TJS_W("defaultExt"), 0,
			&val, params)))
		{
			defaultext = ttstr(val).AsAnsiString();
			ofn.lpstrDefExt = defaultext.c_str();
		}
		else
		{
			ofn.lpstrDefExt = NULL;
		}

		// hook proc
		ofn.lpfnHook = TVPOFNHookProc;

		// show dialog box
		if(!issave)
			result = GetOpenFileName(&ofn);
		else
			result = GetSaveFileName(&ofn);


		if(!result && CommDlgExtendedError() == CDERR_STRUCTSIZE)
		{
			// for old windows
			// set lStructSize to old Windows' structure size
			ofn.lStructSize = TVP_OLD_OFN_STRUCT_SIZE;
			if(!issave)
				result = GetOpenFileName(&ofn);
			else
				result = GetSaveFileName(&ofn);
		}

		if(result)
		{
			// returns some informations

			// filter index
			val = (tjs_int)ofn.nFilterIndex;
			params->PropSet(TJS_MEMBERENSURE, TJS_W("filterIndex"), 0,
				&val, params);

			// file name
			val = TVPNormalizeStorageName(ttstr(filename));
			params->PropSet(TJS_MEMBERENSURE, TJS_W("name"), 0,
				&val, params);
		}

	}
	catch(...)
	{
		if(filter) delete [] filter;
		if(filename) delete [] filename;
		throw;
	}

	delete [] filter;
	delete [] filename;

	return (bool)result;
}
Example #18
0
static INT_PTR CALLBACK ElMaxPluginDlgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg)
	{
	case WM_INITDIALOG:
		{
			theElMaxPlugin.Init(hWnd);
			
			Interval animRange;
			ISpinnerControl* spin;
			int frameStart, frameEnd;

			// Setup the spinner control for the static frame#
			// We take the frame 0 as the default value
			animRange = theElMaxPlugin.GetInterface()->GetAnimRange();
			frameStart = animRange.Start() / GetTicksPerFrame();
			frameEnd = animRange.End() / GetTicksPerFrame();
			spin = GetISpinner(GetDlgItem(hWnd, IDC_STATIC_FRAME_SPIN)); 
			spin->LinkToEdit(GetDlgItem(hWnd,IDC_STATIC_FRAME), EDITTYPE_INT); 
			spin->SetLimits(frameStart, frameEnd, TRUE);
			spin->SetScale(1.0f);
			spin->SetValue(theElMaxPlugin.GetStaticFrame(), FALSE);
			ReleaseISpinner(spin);

			// Setup the spinner controls for the mesh animation start frame
			spin = GetISpinner(GetDlgItem(hWnd, IDC_MESHANIM_START_SPIN)); 
			spin->LinkToEdit(GetDlgItem(hWnd, IDC_MESHANIM_START), EDITTYPE_INT); 
			spin->SetLimits(frameStart, frameEnd, TRUE); 
			spin->SetScale(1.0f);
			spin->SetValue(frameStart, FALSE);
			ReleaseISpinner(spin);

			// Setup the spinner controls for the mesh animation end frame
			spin = GetISpinner(GetDlgItem(hWnd, IDC_MESHANIM_END_SPIN)); 
			spin->LinkToEdit(GetDlgItem(hWnd, IDC_MESHANIM_END), EDITTYPE_INT); 
			spin->SetLimits(frameStart, frameEnd, TRUE); 
			spin->SetScale(1.0f);
			spin->SetValue(frameEnd, FALSE);
			ReleaseISpinner(spin);

			// Setup the spinner controls for the mesh animation key sample rate 
			spin = GetISpinner(GetDlgItem(hWnd, IDC_MESHANIM_STEP_SPIN)); 
			spin->LinkToEdit(GetDlgItem(hWnd, IDC_MESHANIM_STEP), EDITTYPE_INT); 
			spin->SetLimits(1, 100, TRUE); 
			spin->SetScale(1.0f);
			spin->SetValue(theElMaxPlugin.GetMeshAnimFrameStep(), FALSE);
			ReleaseISpinner(spin);

			// Setup the spinner controls for the skeletal animation start frame
			spin = GetISpinner(GetDlgItem(hWnd, IDC_SKELETALANIM_START_SPIN)); 
			spin->LinkToEdit(GetDlgItem(hWnd, IDC_SKELETALANIM_START), EDITTYPE_INT); 
			spin->SetLimits(frameStart, frameEnd, TRUE); 
			spin->SetScale(1.0f);
			spin->SetValue(frameStart, FALSE);
			ReleaseISpinner(spin);

			// Setup the spinner controls for the skeletal animation end frame
			spin = GetISpinner(GetDlgItem(hWnd, IDC_SKELETALANIM_END_SPIN)); 
			spin->LinkToEdit(GetDlgItem(hWnd, IDC_SKELETALANIM_END), EDITTYPE_INT); 
			spin->SetLimits(frameStart, frameEnd, TRUE); 
			spin->SetScale(1.0f);
			spin->SetValue(frameEnd, FALSE);
			ReleaseISpinner(spin);

			// Setup the spinner controls for the skeletal animation key sample rate 
			spin = GetISpinner(GetDlgItem(hWnd, IDC_SKELETALANIM_STEP_SPIN)); 
			spin->LinkToEdit(GetDlgItem(hWnd, IDC_SKELETALANIM_STEP), EDITTYPE_INT); 
			spin->SetLimits(1, 100, TRUE); 
			spin->SetScale(1.0f);
			spin->SetValue(theElMaxPlugin.GetSkeletalAnimFrameStep(), FALSE);
			ReleaseISpinner(spin);
		}
		break;

	case WM_DESTROY:
		theElMaxPlugin.Destroy(hWnd);
		break;

	case WM_COMMAND:
		switch (LOWORD(wParam))
		{
		case IDC_EXPORT_MESH:
			if (HIWORD(wParam) == BN_CLICKED)
			{
				char filename[MAX_PATH] = {0};
				if (GetSaveFileName(hWnd, filename, sizeof(filename), _T("ElMesh(*.ELM)\0*.ELM\0All(*.*)\0*.*\0"), _T("ELM"), _T("Mesh file to save")))
				{
					ISpinnerControl* spin = GetISpinner(GetDlgItem(hWnd, IDC_STATIC_FRAME_SPIN));
					theElMaxPlugin.SetStaticFrame(spin->GetIVal());
					ReleaseISpinner(spin);

					theElMaxPlugin.ExportMesh(filename);
				}
			}
			break;
		case IDC_EXPORT_MESHANIM:
			if (HIWORD(wParam) == BN_CLICKED)
			{
				char filename[MAX_PATH] = {0};
				if (GetSaveFileName(hWnd, filename, sizeof(filename), _T("ElMeshAnimation(*.EMA)\0*.EMA\0All(*.*)\0*.*\0"), _T("EMA"), _T("MeshAnimation file to save")))
				{
					ISpinnerControl* spin = GetISpinner(GetDlgItem(hWnd, IDC_STATIC_FRAME_SPIN));
					theElMaxPlugin.SetStaticFrame(spin->GetIVal());
					ReleaseISpinner(spin);

					spin = GetISpinner(GetDlgItem(hWnd, IDC_MESHANIM_START_SPIN));
					theElMaxPlugin.SetMeshAnimFrameStart(spin->GetIVal());
					ReleaseISpinner(spin);

					spin = GetISpinner(GetDlgItem(hWnd, IDC_MESHANIM_END_SPIN));
					theElMaxPlugin.SetMeshAnimFrameEnd(spin->GetIVal());
					ReleaseISpinner(spin);

					spin = GetISpinner(GetDlgItem(hWnd, IDC_MESHANIM_STEP_SPIN));
					theElMaxPlugin.SetMeshAnimFrameStep(spin->GetIVal());
					ReleaseISpinner(spin);

					theElMaxPlugin.ExportMeshAnim(filename);
				}
			}
			break;
		case IDC_EXPORT_SKELETON:
			if (HIWORD(wParam) == BN_CLICKED)
			{
				char filename[MAX_PATH] = {0};
				if (GetSaveFileName(hWnd, filename, sizeof(filename), _T("ElSkeleton(*.ELS)\0*.ELS\0All(*.*)\0*.*\0"), _T("ELS"), _T("Skeleton file to save")))
				{
					ISpinnerControl* spin = GetISpinner(GetDlgItem(hWnd, IDC_STATIC_FRAME_SPIN));
					theElMaxPlugin.SetStaticFrame(spin->GetIVal());
					ReleaseISpinner(spin);

					theElMaxPlugin.ExportSkeleton(filename);
				}
			}
			break;
		case IDC_EXPORT_SKELETALANIM:
			if (HIWORD(wParam) == BN_CLICKED)
			{
				char filename[MAX_PATH] = {0};
				if (GetSaveFileName(hWnd, filename, sizeof(filename), _T("ElSkeletalAnimation(*.ESA)\0*.ESA\0All(*.*)\0*.*\0"), _T("ESA"), _T("SkeletalAnimation file to save")))
				{
					ISpinnerControl* spin = GetISpinner(GetDlgItem(hWnd, IDC_STATIC_FRAME_SPIN));
					theElMaxPlugin.SetStaticFrame(spin->GetIVal());
					ReleaseISpinner(spin);

					spin = GetISpinner(GetDlgItem(hWnd, IDC_SKELETALANIM_START_SPIN));
					theElMaxPlugin.SetSkeletalAnimFrameStart(spin->GetIVal());
					ReleaseISpinner(spin);

					spin = GetISpinner(GetDlgItem(hWnd, IDC_SKELETALANIM_END_SPIN));
					theElMaxPlugin.SetSkeletalAnimFrameEnd(spin->GetIVal());
					ReleaseISpinner(spin);

					spin = GetISpinner(GetDlgItem(hWnd, IDC_SKELETALANIM_STEP_SPIN));
					theElMaxPlugin.SetSkeletalAnimFrameStep(spin->GetIVal());
					ReleaseISpinner(spin);

					theElMaxPlugin.ExportSkeletalAnim(filename);
				}
			}
			break;
		}
		break;

	case WM_LBUTTONDOWN:
	case WM_LBUTTONUP:
	case WM_MOUSEMOVE:
		theElMaxPlugin.ip->RollupMouseMessage(hWnd,msg,wParam,lParam); 
		break;

	default:
		return 0;
	}
	return 1;
}
Example #19
0
void plSaveSelected()
{
    Interface *ip = GetCOREInterface();

    // Get the Max filename to save to
    char buf[256];
    memset(&buf, 0, sizeof(buf));
    OPENFILENAME ofn = {0};
    ofn.lStructSize = sizeof(OPENFILENAME);
    ofn.hwndOwner = ip->GetMAXHWnd();
    ofn.lpstrFilter = "3ds max (*.max)\0*.max\0\0";
    ofn.nFilterIndex = 1;
    ofn.lpstrFile = buf;
    ofn.nMaxFile = sizeof(buf);
//  ofn.lpstrInitialDir = ip->GetDir(APP_SCENE_DIR);
    ofn.Flags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;
    ofn.lpstrDefExt = "max";

    if (GetSaveFileName(&ofn))
    {
        int count = ip->GetSelNodeCount();
        int i;
        
        // Put all the selected nodes in a list
        INodeTab selected;
        for (i = 0; i < count; i++)
        {
            plMaxNode *node = (plMaxNode*)ip->GetSelNode(i);
            selected.Append(1, (INode**)&node);
        }

        // Put all the components attached to those nodes in a list
        INodeTab components;
        for (i = 0; i < count; i++)
        {
            plMaxNode *node = (plMaxNode*)ip->GetSelNode(i);

            uint32_t compCount = node->NumAttachedComponents();
            for (int j = 0; j < compCount; j++)
            {
                INode *compNode = node->GetAttachedComponent(j)->GetINode();//Node(j);

                if (!IIsNodeInTab(components, compNode))
                    components.Append(1, &compNode);
            }
        }

        // Find the objects that the components are reffing that are not part of the selection.
        // Back them up, and delete them out of the components ref list so they won't be saved too.
        std::vector<ComponentRefs> out;
        for (i = 0; i < components.Count(); i++)
        {
            plComponentBase *comp = ((plMaxNode*)components[i])->ConvertToComponent();

            for (int j = comp->NumTargets() - 1; j >= 0; --j)
            {
                plMaxNodeBase *node = comp->GetTarget(j);

                if (!node)
                    continue;
                
                const char *t1 = components[i]->GetName();
                const char *t2 = node->GetName();

                if (!IIsNodeInTab(selected, node))
                {
                    uint32_t idx = -1;
                    for (uint32_t k = 0; k < out.size(); k++)
                    {
                        if (out[k].comp == comp)
                            idx = k;
                    }

                    if (idx == -1)
                    {
                        idx = out.size();
                        out.resize(idx+1);
                        out[idx].comp = comp;
                    }

                    out[idx].refs.Append(1, (INode**)&node);

                    comp->DeleteTarget(node);
                }
            }
        }

        // Save the selected objects and their components
        INodeTab allNodes;
        allNodes.Append(selected.Count(), &selected[0]);
        allNodes.Append(components.Count(), &components[0]);

        ip->FileSaveNodes(&allNodes, buf);

        // Restore the component refs to objects that weren't selected
        for (i = 0; i < out.size(); i++)
        {
            for (int j = 0; j < out[i].refs.Count(); j++)
                out[i].comp->AddTarget((plMaxNode*)out[i].refs[j]);
        }
    }
}
Example #20
0
/*	XOPSaveFileDialog(prompt, fileFilterStr, fileIndexPtr, initialDir, defaultExtensionStr, filePath)

	Displays the save file dialog.
	
	Returns 0 if the user provides a file name or -1 if the user cancels or another
	non-zero number in the event of an error.
	
	Returns the full path to the file via filePath. filePath is both an input and an
	output as explained below. In the event of a cancel, filePath is unmodified.
	filePath is a Macintosh HFS path on Macintosh and a Windows path on Windows.
	
	On Windows, prompt sets the dialog caption. On Macintosh, it sets a prompt
	string in the dialog.
	
	fileFilterStr is now used to control the contents of the Format popup menu
	in the Save File dialog.
	
	On Macintosh, if there is only one format in which you can save the file,
	pass "" for fileFilterStr. This will cause the Format menu to be hidden.
	If you can save the file in more than one format, pass a string like this:
		"Plain Text:TEXT:.txt;Igor Text:IGTX:.itx;"
		
	This would give you a Format menu like this:
		Plain Text
		Igor Text
	
	fileFilterStr on Macintosh

		fileFilterStr consists of sections terminated by a semicolon. For example,
		here is one section:
			"Data Files:TEXT:.dat;"
			
		Each section consists of three components: a menu item string (e.g., Data Files)
		to be displayed in the Format popup menu, a Macintosh file type (e.g., TEXT),
		and an extension (e.g., .dat).

		At present, only the menu item string and extension are used.

		The Macintosh file type is currently not used. If there is no meaningful Macintosh
		file type, leave the file type component empty.

		If there is no meaningful extension, leave the extension component empty.

	fileFilterStr on Windows
	
		On Windows, fileFilterStr identifies the types of files to display and the types
		of files that can be created. It is constructed as for the lpstrFilter
		field of the OPENFILENAME structure for the Windows GetSaveFileName routine.
		For example, to allow the user to save as a text file or as an Igor Text file,
		use "Text Files (*.txt)\0*.txt\0Igor Text Files (*.itx)\0*.itx\0\0". Note that
		the string ends with two null characters (\0\0). If fileFilterStr is "", this
		behaves the same as "Text Files (*.txt)\0*.txt\0\0". 

	fileIndexPtr it is ignored if it is NULL. If it is not NULL, then *fileIndexPtr
	is the one-based index of the file type filter to be initially selected.
	In the example given above, setting *fileIndexPtr to 2 would select the Igor
	Text file type on entry to the dialog. On exit from the dialog, *fileIndexPtr
	is set to the index of the file type string that the user last selected.
	
	initialDir can be "" or it can point to a full path to a directory. It
	determines the directory that will be initially displayed in the save file
	dialog. If "", the directory will be the last directory that was seen in the
	open or save file dialogs. If initialDir points to a valid path to a directory,
	then this directory will be initially displayed in the dialog. On Macintosh,
	initialDir is a Macintosh HFS path. On Windows, it is a Windows path. 
	
	defaultExtensionStr points to the extension to be added to the
	file name if the user does not enter an extension. For example, pass "txt"
	to have ".txt" appended if the user does not enter an extension. If you don't
	want any extension to be added in this case, pass NULL.
	
	Prior to XOP Toolkit 6.00, defaultExtensionStr was ignored on Macintosh.
	
	Returns via filePath the full path to the file that the user chose
	or "" if the user cancelled. The path is a Macintosh HFS path on Macintosh
	and a Windows path on Windows. filePath must point to a buffer of
	at least MAX_PATH_LEN+1 bytes.
	
	On Windows and Macintosh, the initial value of filePath sets the initial contents of
	the File Name edit control in the save file dialog. The following values
	are valid:
		""									If there is no initial file name
		a file name
		a full Mac or Win path to a file
	
	In the event of an error other than a cancel, XOPSaveFileDialog displays
	an error dialog. This should never or rarely happen.
	
	WINDOWS NOTES
	
	The dialog will appear in the upper left corner of the screen. This is
	because Windows provides no straight-forward way to set the position of
	the dialog.
	
	Thread Safety: XOPSaveFileDialog is not thread-safe.
*/
int
XOPSaveFileDialog(
	const char* prompt,
	const char* fileFilterStr, int* fileIndexPtr,
	const char* initialDir,
	const char* defaultExtensionStr,
	char filePath[MAX_PATH_LEN+1])
{
	OPENFILENAME ofn;
	char filePath2[MAX_PATH_LEN+1];
	char initialDir2[MAX_PATH_LEN+1];
	
	if (!CheckRunningInMainThread("XOPSaveFileDialog"))
		return NOT_IN_THREADSAFE;
	
	if (*fileFilterStr == 0)
		fileFilterStr = "Text Files (*.txt)\0*.txt\0\0";
		
	if (*initialDir == 0) {
		GetStandardFileWinPath(initialDir2);	// Get Igor's save file dialog directory.
	}
	else {
		strcpy(initialDir2, initialDir);
		SetStandardFileWinPath(initialDir);		// Sets initial directory for next save file dialog. This will be overridden below, but not if the user cancels.
	}
		
	/*	HR, 040928, XOP Toolkit 5.04
		Previously this copied filePath to filePath2. This was correct because the filePath parameter
		was supposed to be either "" or just the proposed file name. However, I incorrectly passed
		a full path for the filePath parameter in all of the sample XOPs. This mistake undoubtedly
		leaked into users' XOPs. Therefore I now allow filePath to be either "", just a file name,
		or a full path.
	*/
	// strcpy(filePath2, filePath);				// HR, 010815: Previously filePath2 was set to "" which prevented the File Name item in the Windows Open File dialog from being preset as the comment above says it should be.
	GetLeafName(filePath, filePath2);

	MemClear(&ofn, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	ofn.hwndOwner = IgorClientHWND();
	ofn.lpstrFile = filePath2;
	ofn.nMaxFile = MAX_PATH_LEN+1;
	ofn.lpstrFilter = fileFilterStr;
	ofn.nFilterIndex = fileIndexPtr==NULL ? 1 : *fileIndexPtr;
	ofn.lpstrDefExt = defaultExtensionStr;
	ofn.lpstrTitle = prompt;
	ofn.lpstrFileTitle = NULL;
	ofn.lpstrInitialDir = initialDir2;
	ofn.lpfnHook = OpenOrSaveFileNameHook;		// Needed to set position of the dialog. Otherwise, it is in top/left corner of screen.
	ofn.Flags = OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT;
	ofn.Flags |= OFN_EXPLORER;
	ofn.Flags |= OFN_ENABLEHOOK;				// Needed so that hook will be called.
	ofn.Flags |= OFN_ENABLESIZING;				// HR, 090121: Added this to get resizeable dialog.
	ofn.Flags |= OFN_HIDEREADONLY;
	ofn.Flags |= OFN_NOCHANGEDIR;				// Changing the current directory causes problems. e.g., if set to floppy disk and the floppy is removed, the system slows down.

	if (GetSaveFileName(&ofn) == 0) {
		int err;
		err = CommDlgExtendedError();			// err will be zero if cancel.
		if (err == 0)
			return -1;

		// We got an error other than cancel.
		*filePath2 = 0;							// HR, 021114: Clear possible bad fields
		*initialDir2 = 0;						// and try again.
		if (GetSaveFileName(&ofn) != 0) {		// Succeeded this time?
			err = 0;
		}
		else {
			if (CommDlgExtendedError() == 0)
				return -1;						// User canceled.
			
			// Report the original error.
			err = WindowsErrorToIgorError(err);
			IgorError("XOPSaveFileDialog", err);
			return err;
		}
	}
	
	if (fileIndexPtr != NULL)
		*fileIndexPtr = ofn.nFilterIndex;
	
	strcpy(filePath, filePath2);
	SetStandardFileWinPath(filePath);			// Update Igor's open file dialog directory.

	return 0;
}
Example #21
0
BOOL FileGetName (HWND hWndParent, int nStringResourceID, LPTSTR lpFileName)
   {
   OPENFILENAME   ofn ;
   TCHAR          szFileSpec [256] ;
   TCHAR          szFileTitle [80] ;
   TCHAR          szDialogTitle [80] ;
   TCHAR          aszOpenFilter[LongTextLen] ;
   int            StringLength ;

   if (lpFileName)
      {

      if (nStringResourceID != IDS_EXPORTFILE)
         {
         // get the file extension strings
         LoadString (hInstance, nStringResourceID,
            aszOpenFilter,
            sizeof(aszOpenFilter) / sizeof(TCHAR) ) ;
         StringLength = lstrlen (aszOpenFilter) + 1 ;
         LoadString (hInstance, nStringResourceID+1,
            &aszOpenFilter[StringLength],
            sizeof(aszOpenFilter) / sizeof(TCHAR) - StringLength) ;

         StringLength += lstrlen (&aszOpenFilter[StringLength]) + 1 ;
         // get all file extension strings
         LoadString (hInstance, IDS_ALLFILES, 
            &aszOpenFilter[StringLength],
            sizeof(aszOpenFilter) / sizeof(TCHAR) - StringLength) ;
         StringLength += lstrlen (&aszOpenFilter[StringLength]) + 1 ;
         LoadString (hInstance, IDS_ALLFILESEXT,
            &aszOpenFilter[StringLength],
            sizeof(aszOpenFilter) / sizeof(TCHAR) - StringLength) ;
         }

      // setup the end strings
      StringLength += lstrlen (&aszOpenFilter[StringLength]) ;
      aszOpenFilter[StringLength+1] = aszOpenFilter[StringLength+2] = TEXT('\0') ;

      strclr (szFileSpec) ;
      strclr (szFileTitle) ;

      dwCurrentDlgID = HC_PM_idDlgFileSaveAs ;
      StringLoad (IDS_SAVEAS_TITLE, szDialogTitle) ;

      memset (&ofn, 0, sizeof(OPENFILENAME)) ;
      ofn.lStructSize = sizeof(OPENFILENAME) ;
      ofn.hwndOwner = hWndParent ;
      ofn.hInstance = hInstance;
      ofn.lpstrTitle = szDialogTitle ;
      ofn.lpstrFilter = aszOpenFilter ;
      ofn.nFilterIndex = 1L ;

      ofn.lpstrFile = szFileSpec;
      ofn.nMaxFile = sizeof(szFileSpec);
      ofn.lpstrFileTitle = szFileTitle;
      ofn.nMaxFileTitle = sizeof(szFileTitle);

      ofn.Flags = OptionsOFNStyle ;
      ofn.lpfnHook = (LPOFNHOOKPROC) FileOpenHookProc ;

      if (!GetSaveFileName(&ofn))
         {
         dwCurrentDlgID = 0 ;
         return (FALSE) ;
         }
      dwCurrentDlgID = 0 ;
      }
   else
      {
      return (FALSE) ;
      }

   lstrcpy (lpFileName, ofn.lpstrFile) ;

   return (TRUE) ;
   } // FileGetName
Example #22
0
int GUIGetFileName( gui_window *wnd, open_file_name *ofn )
{
    OPENFILENAME        wofn;
    bool                issave;
    int                 rc;
    unsigned            drive;
#if defined(HAVE_DRIVES)
    unsigned            old_drive;
    unsigned            drives;
#endif

    LastPath = NULL;
    if( ofn->initial_dir != NULL && ofn->initial_dir[0] != '\0' && ofn->initial_dir[1] == ':' ) {
        drive = ofn->initial_dir[0];
        memmove( ofn->initial_dir, ofn->initial_dir+2, strlen( ofn->initial_dir+2 ) + 1 );
    } else {
        drive = 0;
    }

    memset( &wofn, 0 , sizeof( wofn ) );

    if( ofn->flags & OFN_ISSAVE ) {
        issave = true;
    } else {
        issave = false;
    }

    wofn.Flags = 0;
    if( hookFileDlg ) {
        wofn.Flags |= OFN_ENABLEHOOK;
    }
    if( !(ofn->flags & OFN_CHANGEDIR) ) {
        wofn.Flags |= OFN_NOCHANGEDIR;
    }

    if( ofn->flags & OFN_OVERWRITEPROMPT ) {
        wofn.Flags |= OFN_OVERWRITEPROMPT;
    }
    if( ofn->flags & OFN_HIDEREADONLY ) {
        wofn.Flags |= OFN_HIDEREADONLY;
    }
    if( ofn->flags & OFN_FILEMUSTEXIST ) {
        wofn.Flags |= OFN_FILEMUSTEXIST;
    }
    if( ofn->flags & OFN_PATHMUSTEXIST ) {
        wofn.Flags |= OFN_PATHMUSTEXIST;
    }
    if( ofn->flags & OFN_ALLOWMULTISELECT ) {
        wofn.Flags |= OFN_ALLOWMULTISELECT;
    }
    wofn.hwndOwner = GUIGetParentFrameHWND( wnd );
    wofn.hInstance = GUIMainHInst;
    wofn.lStructSize = sizeof( wofn );
    wofn.lpstrFilter = ofn->filter_list;
    wofn.nFilterIndex = ofn->filter_index;
    wofn.lpstrFile = ofn->file_name;
    wofn.nMaxFile = ofn->max_file_name;
    wofn.lpstrFileTitle = ofn->base_file_name;
    wofn.nMaxFileTitle = ofn->max_base_file_name;
    wofn.lpstrTitle = ofn->title;
    wofn.lpstrInitialDir = ofn->initial_dir;
    wofn.lpfnHook = (LPOFNHOOKPROC)NULL;
    if( hookFileDlg ) {
        wofn.lpfnHook = (LPOFNHOOKPROC)MakeOpenFileHookProcInstance( OpenHook, GUIMainHInst );
    }

#if defined( HAVE_DRIVES )
    if( drive ) {
        _dos_getdrive( &old_drive );
        _dos_setdrive( tolower( drive ) - 'a' + 1, &drives );
    }
#endif
    if( issave ) {
        rc = GetSaveFileName( &wofn );
    } else {
        rc = GetOpenFileName( &wofn );
    }

    if( hookFileDlg ) {
        (void)FreeProcInstance( (FARPROC)wofn.lpfnHook );
    }

    if( LastPath && ( !rc || !( ofn->flags & OFN_WANT_LAST_PATH ) ) ) {
        GUIMemFree( LastPath );
        LastPath = NULL;
    }
    ofn->last_path = LastPath;
#if defined( HAVE_DRIVES )
    if( drive ) {
        _dos_setdrive( old_drive, &drives );
    }
#endif
    if( rc ) {
        return( OFN_RC_FILE_SELECTED );
    }
    if( !CommDlgExtendedError() ) {
        return( OFN_RC_NO_FILE_SELECTED );
    }
    return( OFN_RC_FAILED_TO_INITIALIZE );
} /* _GUIGetFileName */
Example #23
0
File: Text.c Project: atrniv/CLIPS
BOOL text_Save(
  HWND hwnd)
  {
   HWND hEditWnd;
   struct textWindowData *theData;
   HFILE hFile;
   OFSTRUCT OfStruct;
   char szTemp[398];
   int text_length; 
   char *pEditBuffer;
   HICON hSaveCursor;
   unsigned ioStatus;
   BOOL bSuccess;
   
   //hEditWnd = GetFirstChild(MDIClientWnd);
   hEditWnd = hwnd;
   
   /*======================*/
   /* Get the window data. */
   /*======================*/
   
   theData = (struct textWindowData *) GetWindowLong(hEditWnd,GWL_USERDATA);
   if (theData == NULL)
     {
	  if (! GetSaveFileName ((LPOPENFILENAME) &ofn))
        { return(FALSE); }
        
      theData = (struct textWindowData *) malloc(sizeof(struct textWindowData));
      if (theData == NULL) 
        { return(FALSE); }
        
      strcpy((char *) &theData->fileName,(char *) szFileName);
      SetWindowLong(hEditWnd,GWL_USERDATA,(long) theData);
      SetWindowText(hEditWnd,szFileName);
     }

   if ((hFile = OpenFile(theData->fileName, &OfStruct, OF_CANCEL | OF_CREATE)) < 0)
     {  
      sprintf(szTemp, "Cannot write to %s.",theData->fileName);
      MessageBox(hwnd,szTemp,NULL,MB_OK | MB_ICONHAND);
      return (FALSE);
     }
     
   hEditWnd = GetDlgItem(hEditWnd,ID_EDIT_CONTROL);
   text_length = SendMessage(hEditWnd,WM_GETTEXTLENGTH,0,0);
   pEditBuffer = (char *) malloc((size_t) text_length+1);

   if (pEditBuffer == NULL)
     {
      sprintf(szTemp, "Not enough memory to save %s.", theData->fileName);
      MessageBox(hwnd, szTemp, NULL, MB_OK | MB_ICONHAND);
      _lclose(hFile);
      return (FALSE);
	 }

   SendMessage(hEditWnd,WM_GETTEXT,(unsigned) text_length+1,(LPARAM) pEditBuffer);

   /*==========================================================*/
   /* Set the cursor to an hourglass during the file transfer. */
   /*==========================================================*/

   hSaveCursor = SetCursor(hHourGlass);
   
   ioStatus = _lwrite(hFile,pEditBuffer,strlen(pEditBuffer));

   _lclose(hFile);

   SetCursor(hSaveCursor);

   if (ioStatus != strlen(pEditBuffer))
     { 
      sprintf(szTemp, "Error writing to %s.", theData->fileName);
      MessageBox(hwnd, szTemp, NULL, MB_OK | MB_ICONHAND);
      bSuccess = FALSE;
     }
   else
     {  
      bSuccess = TRUE;     
      SendMessage(hEditWnd,EM_SETMODIFY,
                  (WPARAM) (UINT) FALSE, (LPARAM) 0);
     }
     
   free(pEditBuffer);
   return (bSuccess);
  }
Example #24
0
void IGraphicsWin::PromptForFile(WDL_String* pFilename, int action, char* dir, char* extensions)
{
  pFilename->Set("");
	if (!WindowIsOpen()) { 
		return;
	}

  WDL_String pathStr;
	char fnCStr[MAX_PATH_LEN], dirCStr[MAX_PATH_LEN];
	fnCStr[0] = '\0';
	dirCStr[0] = '\0';
	if (CSTR_NOT_EMPTY(dir)) {
  pathStr.Set(dir);
		strcpy(dirCStr, dir);
	}
  else {
    HostPath(&pathStr);
  }
	
	OPENFILENAME ofn;
	memset(&ofn, 0, sizeof(OPENFILENAME));

	ofn.lStructSize = sizeof(OPENFILENAME);
	ofn.hwndOwner = mPlugWnd;
	ofn.lpstrFile = fnCStr;
	ofn.nMaxFile = MAX_PATH_LEN - 1;
	ofn.lpstrInitialDir = dirCStr;
	ofn.Flags = OFN_PATHMUSTEXIST;

    //if (!extensions.empty()) {
        //static char extStr[256];
        //static char defExtStr[16];
        //int i, j, p;

        //for (j = 0, p = 0; j < extensions.size(); ++j) {
        //    extStr[p++] = extensions[j++];
        //}
        //extStr[p++] = '\0';

        //StrVector exts = SplitStr(extensions);
        //for (i = 0, p = 0; i < exts.size(); ++i) {
        //    const std::string& ext = exts[i];
        //    if (i) {
        //        extStr[p++] = ';';
        //    }
        //    extStr[p++] = '*';
        //    extStr[p++] = '.';
        //    for (j = 0; j < ext.size(); ++j) {
        //        extStr[p++] = ext[j];
        //    }
        //}
        //extStr[p++] = '\0';
        //extStr[p++] = '\0';
        //ofn.lpstrFilter = extStr;
        //
        //strcpy(defExtStr, exts.front().c_str());
        //ofn.lpstrDefExt = defExtStr;
    //}

    bool rc = false;
    switch (action) {
        case kFileSave:
            ofn.Flags |= OFN_OVERWRITEPROMPT;
            rc = GetSaveFileName(&ofn);
            break;

        case kFileOpen:     
        default:
            ofn.Flags |= OFN_FILEMUSTEXIST;
    	    rc = GetOpenFileName(&ofn);
            break;
    }

    if (rc) {
        pFilename->Set(ofn.lpstrFile);
    }
}
Example #25
0
// Handles the GUI events
void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext )
{
    switch( nControlID )
    {
        case IDC_TOGGLEFULLSCREEN:
		{
            DXUTToggleFullScreen();
			break;
		}
        case IDC_TOGGLEREF:
		{
            DXUTToggleREF();
			break;
		}
        case IDC_CHANGEDEVICE:
		{
            gD3DSettingsDlg.SetActive( !gD3DSettingsDlg.IsActive() );
			break;
		}
        case IDC_TEXT:
        case IDC_EXPOSURE:
        {
            gLog2Exposure = (gSampleUI.GetSlider(IDC_EXPOSURE)->GetValue() / 100.0f - 0.5f) * 33.33333;
			WCHAR wstr[MAX_PATH];
			swprintf_s(wstr, MAX_PATH, 
				L"Texture Size: %d x %d\n" 
                L"logRGB L1: %.2f%%\n"
                //L"logRGB RMSE: %.4f\n"
                //L"Relative error: %.2f%%\n"
                //L"mPSNR: %.2f%%\n"
                L"Exposure: %.2f\n"
				L"Compression Time: %0.2f ms\n"
				L"Compression Rate: %0.2f Mp/s\n", 
				gTexWidth, gTexHeight,
                gError, gLog2Exposure,
				gCompTime, gCompRate);
			gSampleUI.GetStatic(IDC_TEXT)->SetText(wstr);
			break;
		}
		case IDC_MT:
		{
			// Shut down all previous threading abilities.
			DestroyThreads();
			
			gMultithreaded = gSampleUI.GetCheckBox(IDC_MT)->GetChecked();
					
			if (gMultithreaded)
			{
				InitWin32Threads();
			}

			// Recompress the texture.
			RecompressTexture();
			gSampleUI.SendEvent(IDC_TEXT, true, gSampleUI.GetStatic(IDC_TEXT));

			break;
		}
		case IDC_PROFILE:
		{ 
			gCompressionFunc = (CompressionFunc*)gSampleUI.GetComboBox(IDC_PROFILE)->GetSelectedData();

			// Recompress the texture.
			RecompressTexture();
			gSampleUI.SendEvent(IDC_TEXT, true, gSampleUI.GetStatic(IDC_TEXT));

			break;
		}
		case IDC_LOAD_TEXTURE:
		{
			// Store the current working directory.
			TCHAR workingDirectory[MAX_PATH];
			GetCurrentDirectory(MAX_PATH, workingDirectory);

			// Open a file dialog.
			OPENFILENAME openFileName;
			WCHAR file[MAX_PATH];
			file[0] = 0;
			ZeroMemory(&openFileName, sizeof(OPENFILENAME));
			openFileName.lStructSize = sizeof(OPENFILENAME);
			openFileName.lpstrFile = file;
			openFileName.nMaxFile = MAX_PATH;
			openFileName.lpstrFilter = L"DDS\0*.dds\0\0";
			openFileName.nFilterIndex = 1;
			openFileName.lpstrInitialDir = NULL;
			openFileName.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
			if(GetOpenFileName(&openFileName))
			{
				//CreateTextures(openFileName.lpstrFile);
                SAFE_RELEASE(gUncompressedSRV);
                LoadTexture(openFileName.lpstrFile);
			}

			// Restore the working directory. GetOpenFileName changes the current working directory which causes problems with relative paths to assets.
			SetCurrentDirectory(workingDirectory);

            RecompressTexture();
			gSampleUI.SendEvent(IDC_TEXT, true, gSampleUI.GetStatic(IDC_TEXT));
			
			break;
		}
		case IDC_RECOMPRESS:
		{
			// Recompress the texture.
			RecompressTexture();
			gSampleUI.SendEvent(IDC_TEXT, true, gSampleUI.GetStatic(IDC_TEXT));

			break;
		}
		case IDC_SAVE_TEXTURE:
		{
			// Store the current working directory.
			TCHAR workingDirectory[MAX_PATH];
			GetCurrentDirectory(MAX_PATH, workingDirectory);

			// Open a file dialog.
			OPENFILENAME openFileName;
			WCHAR file[MAX_PATH];
			file[0] = 0;
			ZeroMemory(&openFileName, sizeof(OPENFILENAME));
			openFileName.lStructSize = sizeof(OPENFILENAME);
			openFileName.lpstrFile = file;
			openFileName.nMaxFile = MAX_PATH;
			openFileName.lpstrFilter = L"DDS\0*.dds\0\0";
			openFileName.lpstrDefExt = L"dds";
			openFileName.nFilterIndex = 1;
			openFileName.lpstrInitialDir = NULL;
			openFileName.Flags = OFN_PATHMUSTEXIST;
            
			if(GetSaveFileName(&openFileName))
			{
				SaveTexture(gCompressedSRV,openFileName.lpstrFile);
			}

			// Restore the working directory. GetOpenFileName changes the current working directory which causes problems with relative paths to assets.
			SetCurrentDirectory(workingDirectory);

			break;
		}
		case IDC_IMAGEVIEW:
		{
			gImageView = (EImageView)(INT_PTR)gSampleUI.GetComboBox(IDC_IMAGEVIEW)->GetSelectedData();

			break;
		}
	}
}
Example #26
0
QString qt_win_get_save_file_name(const QFileDialogArgs &args,
                                  QString *initialDirectory,
                                  QString *selectedFilter)
{
    QString result;

    QString isel = args.selection;
    if (initialDirectory && initialDirectory->left(5) == QLatin1String("file:"))
        initialDirectory->remove(0, 5);
    QFileInfo fi(*initialDirectory);

    if (initialDirectory && !fi.isDir()) {
        *initialDirectory = fi.absolutePath();
        if (isel.isEmpty())
            isel = fi.fileName();
    }

    if (!fi.exists())
        *initialDirectory = QDir::homePath();

    DWORD selFilIdx = 0;

    int idx = 0;
    if (selectedFilter) {
        QStringList filterLst = qt_win_make_filters_list(args.filter);
        idx = filterLst.indexOf(*selectedFilter);
    }

    QDialog modal_widget;
    modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
    modal_widget.setParent(args.parent, Qt::Window);
    QApplicationPrivate::enterModal(&modal_widget);
    bool hideFiltersDetails = args.options & QFileDialog::HideNameFilterDetails;
    // This block is used below for the lpstrDefExt member.
    // Note that the current MSDN docs document this member wrong.
    // It should rather be documented as "the default extension if no extension was given and if the
    // current filter does not have a extension (e.g (*)). If the current filter have an extension, use
    // the extension of the current filter"
    QString defaultSaveExt;
    if (selectedFilter && !selectedFilter->isEmpty()) {
        defaultSaveExt = qt_win_extract_filter(*selectedFilter);
        // make sure we only have the extension
        int firstDot = defaultSaveExt.indexOf(QLatin1Char('.'));
        if (firstDot != -1) {
            defaultSaveExt.remove(0, firstDot + 1);
        } else {
            defaultSaveExt.clear();
        }
    }

    OPENFILENAME *ofn = qt_win_make_OFN(args.parent, args.selection,
                                        args.directory, args.caption,
                                        qt_win_filter(args.filter, hideFiltersDetails),
                                        QFileDialog::AnyFile,
                                        args.options);

    ofn->lpstrDefExt = (wchar_t*)defaultSaveExt.utf16();

    if (idx)
        ofn->nFilterIndex = idx + 1;
    if (GetSaveFileName(ofn)) {
        result = QString::fromWCharArray(ofn->lpstrFile);
        selFilIdx = ofn->nFilterIndex;
    }
    qt_win_clean_up_OFN(&ofn);

#if defined(Q_WS_WINCE)
    int semIndex = result.indexOf(QLatin1Char(';'));
    if (semIndex >= 0)
        result = result.left(semIndex);
#endif

    QApplicationPrivate::leaveModal(&modal_widget);

    qt_win_eatMouseMove();

    if (result.isEmpty())
        return result;

    fi = result;
    *initialDirectory = fi.path();
    if (selectedFilter)
        *selectedFilter = qt_win_selected_filter(args.filter, selFilIdx);
    return fi.absoluteFilePath();
}
Example #27
0
BOOL CALLBACK PlayDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    OPENFILENAME sf;
    const LPTSTR pszSaveFilter = L"Waveforms (*.wav)\0*.wav\0\0";
    SHINITDLGINFO idi;
    TCHAR text[FL_MAX_TEXTLEN];
    TCHAR szFilePos[FL_MAX_TEXTLEN];
    TCHAR *x;
    int i, looptimes;
    SYSTEMTIME StartTime, EndTime;
    float elapsedtime;

    switch (msg)
    {
    case WM_INITDIALOG:
        idi.dwMask = SHIDIM_FLAGS;
        idi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIZEDLGFULLSCREEN;
        idi.hDlg = hwnd;
        SHInitDialog (&idi);

        for (i=0; flowm_voice_name(i); i++)
        {   /* Add regestered voices to the voice dropdown */
            SendDlgItemMessage(hwnd, FL_VOXLIST, CB_ADDSTRING, 
                               0, (LPARAM)flowm_voice_name(i));
        }
        /* Position cursor at start, selecting first voice */
        SendDlgItemMessage(hwnd, FL_VOXLIST, CB_SETCURSEL, 0, 0);

        /* Add Relation types to the selection box */
        SendDlgItemMessage(hwnd,FL_RELLIST,CB_ADDSTRING,0,(LPARAM)L"Token");
        SendDlgItemMessage(hwnd,FL_RELLIST,CB_ADDSTRING,0,(LPARAM)L"Word");
        SendDlgItemMessage(hwnd,FL_RELLIST,CB_ADDSTRING,0,(LPARAM)L"Segment");
        SendDlgItemMessage(hwnd,FL_RELLIST,CB_SETCURSEL,0,0);

        TTSWindow = 0;  /* just in case there is a race condition */

        return TRUE;
    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case FL_PUSHPLAY:
            /* Synthesis the text with selection voice */
            /* Output items in selected relation at end */
            GetDlgItemText(hwnd, FL_TEXT, text, FL_MAX_TEXTLEN);

            flowm_selected_voice = 
                ComboBox_GetCurSel(GetDlgItem(hwnd,FL_VOXLIST));
            flowm_selected_relation = 
                ComboBox_GetCurSel(GetDlgItem(hwnd,FL_RELLIST));
            flowm_play_status = FLOWM_PLAY;
            flowm_say_text(text);
            flowm_play_status = FLOWM_STOP;

            if (flowm_selected_relation > 0)
                SetDlgItemText(hwnd, FL_OUTPUT, fl_tts_msg);

            return TRUE;
        case FL_PUSHSAVE:
            /* Save the last synthesized waveform */
            ZeroMemory(&sf,sizeof(sf));
            sf.lStructSize = sizeof(sf);
            sf.lpstrFile = fl_filename;
            sf.nMaxFile = 256;
            sf.lpstrFilter = pszSaveFilter;
            sf.Flags = 0;
            sf.lpstrTitle = L"Flowm Save";

            if (GetSaveFileName(&sf) != 0)
            {
                if (flowm_save_wave(fl_filename) == -1)
                    wsprintf(fl_tts_msg,L"Wave NOT saved in %s",fl_filename);
                else
                    wsprintf(fl_tts_msg,L"Wave saved in %s",fl_filename);
                MessageBox(hwnd, fl_tts_msg, AppName, MB_OK);
            }
            fl_filename[0] = '\0';

            return TRUE;
        case FL_BENCH:
            /* Bench marking, find out the speed of synthesis on device */
            if (flowm_play_status == FLOWM_BENCH)
            {
                flowm_play_status = FLOWM_STOP;
                return TRUE;
            }
            flowm_play_status = FLOWM_BENCH;
            /* Find out what voice we want */
            flowm_selected_voice = 
                ComboBox_GetCurSel(GetDlgItem(hwnd,FL_VOXLIST));
            flowm_selected_relation = 0;

            flowm_duration = 0.0;
            GetSystemTime(&StartTime);
            GetDlgItemText(hwnd, FL_TEXT, szFilePos, FL_MAX_TEXTLEN);
            looptimes = wcstod(szFilePos,&x);
            if (looptimes < 5)
                looptimes = 5;
            wsprintf(fl_tts_msg,L"Bench marking: loop = %d ...",looptimes);
            SetDlgItemText(hwnd, FL_OUTPUT, fl_tts_msg);
            SetDlgItemText(hwnd, FL_TEXT,FL_BENCH_TEXT);
            for (i=0; i<looptimes; i++)
                flowm_say_text(FL_BENCH_TEXT);
            GetSystemTime(&EndTime);
            /* This will fail over noon (?) and midnight */
            elapsedtime = 
                (EndTime.wHour*60.0*60.0+EndTime.wMinute*60.0+
                 EndTime.wSecond+EndTime.wMilliseconds/1000.0) -
                (StartTime.wHour*60.0*60.0+StartTime.wMinute*60.0+
                 StartTime.wSecond+ StartTime.wMilliseconds/1000.0);
            wsprintf(fl_tts_msg,L"%2.1f speech; %2.1f seconds; %2.2f rate;",
                     flowm_duration,
                     elapsedtime,
                     flowm_duration/elapsedtime);
            SetDlgItemText(hwnd, FL_OUTPUT, fl_tts_msg);
            
            flowm_play_status = FLOWM_STOP;
            return TRUE;
        case IDOK:
        case IDCANCEL:
            flowm_play_status = FLOWM_STOP;
            EndDialog(hwnd,0);
            return TRUE;
        }
    break;
    }
    return FALSE;
}
Example #28
0
void __declspec(dllexport) SelectFileDialog(HWND hwndParent, int string_size, TCHAR *variables, stack_t **stacktop, extra_parameters *extra)
{
  OPENFILENAME ofn={0,}; // XXX WTF
  int save;
  TCHAR type[5];
  static TCHAR path[1024];
  static TCHAR filter[1024];
  static TCHAR currentDirectory[1024];
  static TCHAR initialDir[1024];
  DWORD gfa;

  EXDLL_INIT();

  ofn.lStructSize = sizeof(OPENFILENAME);
  ofn.hwndOwner = hwndParent;
  ofn.lpstrFilter = filter;
  ofn.lpstrFile = path;
  ofn.nMaxFile  = sizeof(path);
  //ofn.Flags = pField->nFlags & (OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_CREATEPROMPT | OFN_EXPLORER);
  ofn.Flags = OFN_CREATEPROMPT | OFN_EXPLORER;

  popstringn(type, sizeof(type));
  popstringn(path, sizeof(path));
  popstringn(filter, sizeof(filter));

  save = !lstrcmpi(type, _T("save"));

  // Check if the path given is a folder. If it is we initialize the 
  // ofn.lpstrInitialDir parameter
  gfa = GetFileAttributes(path);
  if ((gfa != INVALID_FILE_ATTRIBUTES) && (gfa & FILE_ATTRIBUTE_DIRECTORY))
  {
    lstrcpy(initialDir, path);
    ofn.lpstrInitialDir = initialDir;
    path[0] = _T('\0'); // disable initial file selection as path is actually a directory
  }

  if (!filter[0])
  {
    lstrcpy(filter, _T("All Files|*.*"));
  }

  {
    // Convert the filter to the format required by Windows: NULL after each
    // item followed by a terminating NULL
    TCHAR *p = filter;
    while (*p) // XXX take care for 1024
    {
      if (*p == _T('|'))
      {
        *p++ = 0;
      }
      else
      {
        p = CharNext(p);
      }
    }
    p++;
    *p = 0;
  }

  GetCurrentDirectory(sizeof(currentDirectory), currentDirectory); // save working dir

  if ((save ? GetSaveFileName(&ofn) : GetOpenFileName(&ofn)))
  {
    pushstring(path);
  }
  else if (CommDlgExtendedError() == FNERR_INVALIDFILENAME)
  {
    *path = _T('\0');
    if ((save ? GetSaveFileName(&ofn) : GetOpenFileName(&ofn)))
    {
      pushstring(path);
    }
    else
    {
      pushstring(_T(""));
    }
  }
  else
  {
    pushstring(_T(""));
  }

  // restore working dir
  // OFN_NOCHANGEDIR doesn't always work (see MSDN)
  SetCurrentDirectory(currentDirectory);
}
Example #29
0
bool GSCaptureDlg::OnCommand(HWND hWnd, UINT id, UINT code)
{
	if(id == IDC_BROWSE && code == BN_CLICKED)
	{
		char buff[MAX_PATH] = {0};

		OPENFILENAME ofn;

		memset(&ofn, 0, sizeof(ofn));

		ofn.lStructSize = sizeof(ofn);
		ofn.hwndOwner = m_hWnd;
		ofn.lpstrFile = buff;
		ofn.nMaxFile = countof(buff);
		ofn.lpstrFilter = "Avi files (*.avi)\0*.avi\0";
		ofn.Flags = OFN_EXPLORER | OFN_ENABLESIZING | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST;

		strcpy(ofn.lpstrFile, m_filename.c_str());

		if(GetSaveFileName(&ofn))
		{
			m_filename = ofn.lpstrFile;

			SetText(IDC_FILENAME, m_filename.c_str());
		}

		return true;
	}
	else if(id == IDC_CONFIGURE && code == BN_CLICKED)
	{
		Codec c;

		if(GetSelCodec(c) == 1)
		{
			if(CComQIPtr<ISpecifyPropertyPages> pSPP = c.filter)
			{
				CAUUID caGUID;

				memset(&caGUID, 0, sizeof(caGUID));

				if(SUCCEEDED(pSPP->GetPages(&caGUID)))
				{
					IUnknown* lpUnk = NULL;
					pSPP.QueryInterface(&lpUnk);
					OleCreatePropertyFrame(m_hWnd, 0, 0, c.FriendlyName.c_str(), 1, (IUnknown**)&lpUnk, caGUID.cElems, caGUID.pElems, 0, 0, NULL);
					lpUnk->Release();

					if(caGUID.pElems) CoTaskMemFree(caGUID.pElems);
				}
			}
			else if(CComQIPtr<IAMVfwCompressDialogs> pAMVfWCD = c.filter)
			{
				if(pAMVfWCD->ShowDialog(VfwCompressDialog_QueryConfig, NULL) == S_OK)
				{
					pAMVfWCD->ShowDialog(VfwCompressDialog_Config, m_hWnd);
				}
			}
		}

		return true;
	}
	else if(id == IDOK)
	{
		m_width = GetTextAsInt(IDC_WIDTH);
		m_height = GetTextAsInt(IDC_HEIGHT);
		m_filename = GetText(IDC_FILENAME);

		Codec c;

		int ris = GetSelCodec(c);
		if(ris == 0)
		{
			return false;
		}

		m_enc = c.filter;

		theApp.SetConfig("CaptureWidth", m_width);
		theApp.SetConfig("CaptureHeight", m_height);
		theApp.SetConfig("CaptureFileName", m_filename.c_str());

		if (ris != 2)
		{
			wstring s = wstring(c.DisplayName.m_str);
			theApp.SetConfig("CaptureVideoCodecDisplayName", string(s.begin(), s.end()).c_str());
		}
		else
		{
			theApp.SetConfig("CaptureVideoCodecDisplayName", "");
		}
	}

	return __super::OnCommand(hWnd, id, code);
}
void g2Dialog::Show()
{
    // Window implementation block
    #ifdef _WIN32
    
        if(Type == g2DialogType_Notification)
        {
            MessageBox(NULL, MessageBuffer, "GLUI2 - Message", MB_ICONINFORMATION);
        }
        else if(Type == g2DialogType_Open)
        {
            // Based on the MSDN article on open/saving dialogs
            // http://msdn.microsoft.com/en-us/library/windows/desktop/ms646829(v=vs.85).aspx
            
			// Allocate the args list for opening file
            OPENFILENAME ofn;
            ZeroMemory(&ofn, sizeof(ofn));
			char szFileName[MAX_PATH] = "";
            
			// Set default flags
            ofn.lStructSize = sizeof(ofn);
            ofn.hwndOwner = NULL;
            ofn.lpstrFile = szFileName;
            ofn.nMaxFile = MAX_PATH;
            ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
            
			// Set a file filter
            char szFileFilter[MAX_PATH];
			if(strlen(FileExtension) > 0)
				sprintf(szFileFilter, "(*.%s)\0*.%s\0", FileExtension, FileExtension);
			else
				strcpy(szFileFilter, "All Files (*.*)\0*.*\0");
            ofn.lpstrFilter = szFileFilter;
			ofn.lpstrDefExt = FileExtension;
			
            // Open file
            if(GetOpenFileName(&ofn))
            {
                strcpy(ResultBuffer, ofn.lpstrFile);
                Selection = g2DialogResult_OK;
            }
            else
            {
                strcpy(ResultBuffer, "");
                Selection = g2DialogResult_Cancel;
            }
        }
        else if(Type == g2DialogType_Save)
        {
            // Based on:
            // http://msdn.microsoft.com/en-us/library/windows/desktop/dd183519(v=VS.85).aspx
            
			// Allocate the args list for opening file
            OPENFILENAME ofn;
            ZeroMemory(&ofn, sizeof(ofn));
			char szFileName[MAX_PATH] = "";
            
			// Set default flags
            ofn.lStructSize = sizeof(ofn);
            ofn.hwndOwner = NULL;
            ofn.lpstrFile = szFileName;
            ofn.nMaxFile = MAX_PATH;
            ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
            
			// Set a file filter
            char szFileFilter[MAX_PATH];
			if(strlen(FileExtension) > 0)
				sprintf(szFileFilter, "(*.%s)\0*.%s\0", FileExtension, FileExtension);
			else
				strcpy(szFileFilter, "All Files (*.*)\0*.*\0");
            ofn.lpstrFilter = szFileFilter;
			ofn.lpstrDefExt = FileExtension;
			
            // Save file
            if(GetSaveFileName(&ofn))
            {
                strcpy(ResultBuffer, ofn.lpstrFile);
                Selection = g2DialogResult_OK;
            }
            else
            {
                strcpy(ResultBuffer, "");
                Selection = g2DialogResult_Cancel;
            }
        }
    
    
    // Linux implementation block
    #elif __linux__
    
        // Ask by the command line
        // Note that linux users shouldn't run the program
        // that instances this application in the background
        // as we need access to standard I/O
        strcpy(ResultBuffer, "");
        
        if(Type == g2DialogType_Notification)
        {
            printf("Message: \"%s\"\n", MessageBuffer);
            Selection = g2DialogResult_OK;
            strcpy(ResultBuffer, "");
            return;
        }
        else if(Type == g2DialogType_Open)
            printf("\"%s\"> ", MessageBuffer);
        else if(Type == g2DialogType_Save)
            printf("\"%s\"> ", MessageBuffer);
        
        char* TempBuffer = NULL;
        if(scanf("%s", TempBuffer) > 0)
        {
            Selection = g2DialogResult_OK;
            
            // Special rule: if we are saving, make sure to
            // add the extension if it exists
            if(Type == g2DialogType_Save && strlen(FileExtension) > 0)
            {
                // If this file does not end in the extension...
                char* ExtLocation = strrchr(TempBuffer, '.');
                if(strcmp(ExtLocation + 1, FileExtension) != 0)
                    sprintf(ResultBuffer, "%s.%s", TempBuffer, FileExtension);
                // Else, it does, just copy it over
                else
                    strcpy(ResultBuffer, TempBuffer);
            }
            // Else, just do a regular copy
            else
                strcpy(ResultBuffer, TempBuffer);
        }
        else
        {
            Selection = g2DialogResult_Cancel;
            strcpy(ResultBuffer, "");
        }
        
    // Apple/OSX includes
    #elif __APPLE__
        
        // Attempt to execute the appropriate notification
        bool result = false;
        if(Type == g2DialogType_Notification)
            result = __g2ShowDialog(MessageBuffer);
        else if(Type == g2DialogType_Open)
            result = __g2ShowOpenDialog(MessageBuffer, FileExtension, ResultBuffer, g2Dialog_MaxBufferLength);
        else if(Type == g2DialogType_Save)
            result = __g2ShowSaveDialog(MessageBuffer, FileExtension, ResultBuffer, g2Dialog_MaxBufferLength);
        
        // Based on the result (i.e. button index) save
        // the correct enumeration type
        if(result == true)
            Selection = g2DialogResult_OK;
        else
            Selection = g2DialogResult_Cancel;
        
    #endif
}