static void SaveClipboardToFile(void) { OPENFILENAMEW sfn; LPWSTR c; WCHAR szFileName[MAX_PATH]; WCHAR szFilterMask[MAX_STRING_LEN + 10]; ZeroMemory(&szFilterMask, sizeof(szFilterMask)); c = szFilterMask + LoadStringW(Globals.hInstance, STRING_FORMAT_NT, szFilterMask, MAX_STRING_LEN) + 1; wcscpy(c, L"*.clp"); ZeroMemory(&szFileName, sizeof(szFileName)); ZeroMemory(&sfn, sizeof(sfn)); sfn.lStructSize = sizeof(sfn); sfn.hwndOwner = Globals.hMainWnd; sfn.hInstance = Globals.hInstance; sfn.lpstrFilter = szFilterMask; sfn.lpstrFile = szFileName; sfn.nMaxFile = ARRAYSIZE(szFileName); sfn.Flags = OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT; sfn.lpstrDefExt = L"clp"; if (!GetSaveFileNameW(&sfn)) return; if (!OpenClipboard(Globals.hMainWnd)) { ShowLastWin32Error(Globals.hMainWnd); return; } WriteClipboardFile(szFileName, CLIP_FMT_NT /* CLIP_FMT_31 */); CloseClipboard(); }
static int ShowSaveDialog(wchar_t* name, size_t nameLength) { wchar_t* defaultPath = xmalloc(MAX_PATH * sizeof(wchar_t)); OPENFILENAMEW ofn = { .lStructSize = sizeof(OPENFILENAMEW), .lpstrFilter = L"PNG image\0*.png\0", .nFilterIndex = 1, .lpstrFile = name, .nMaxFile = nameLength, .Flags = OFN_EXPLORER | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST, }; /* This may seem like an archaic way of getting the default pictures directory since it doesn't understand Windows 7 libraries, however GetSaveFileName will open the library anyway if given CSIDL_MYPICTURES and doing it this way is backwards compatible with Windows Vista */ if (SHGetFolderPathW(NULL, CSIDL_MYPICTURES, NULL, SHGFP_TYPE_CURRENT, defaultPath) == S_OK) ofn.lpstrInitialDir = defaultPath; if (!GetSaveFileNameW(&ofn)) { free(defaultPath); return 0; } free(defaultPath); return 1; } static FILE* OpenFileWrite(wchar_t* name) { /* Every Windows program should have a variant of this function to replace fopen. That is, one that supports Unicode and FILE_SHARE_DELETE. */ HANDLE winHandle = CreateFileW( name, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, CREATE_ALWAYS, 0, NULL); if (!winHandle) return NULL; int crtHandle = _open_osfhandle((intptr_t)winHandle, 0); if (crtHandle == -1) { CloseHandle(winHandle); return NULL; } FILE* result = _fdopen(crtHandle, "wb"); if (!result) { _close(crtHandle); return NULL; } return result; }
VOID SaveProtocol(VOID) { HANDLE hEventLog; WCHAR szFileName[MAX_PATH]; ZeroMemory(szFileName, sizeof(szFileName)); sfn.lpstrFile = szFileName; sfn.nMaxFile = MAX_PATH; if (!GetSaveFileNameW(&sfn)) { return; } hEventLog = OpenEventLogW(lpComputerName, lpSourceLogName); if (!hEventLog) { ShowLastWin32Error(); return; } if (!BackupEventLogW(hEventLog, szFileName)) { ShowLastWin32Error(); } CloseEventLog(hEventLog); }
void MainWnd_OnExport(HWND hwnd) { OPENFILENAMEW ofn = {0}; WCHAR szFile[MAX_PATH] = L""; WCHAR szExportTitle[MAX_STRING]; WCHAR szCannotExport[MAX_STRING]; WCHAR szExportFilter[MAX_STRING]; LoadStringW(g_hInstance, IDS_EXPORT, szExportTitle, _countof(szExportTitle)); LoadStringW(g_hInstance, IDS_CANTEXPORT, szCannotExport, _countof(szCannotExport)); LoadStringW(g_hInstance, IDS_OUTFILTER, szExportFilter, _countof(szExportFilter)); MakeFilter(szExportFilter); ofn.lStructSize = OPENFILENAME_SIZE_VERSION_400; ofn.hwndOwner = hwnd; ofn.lpstrFilter = szExportFilter; ofn.lpstrFile = szFile; ofn.nMaxFile = _countof(szFile); ofn.lpstrTitle = szExportTitle; ofn.Flags = OFN_DONTADDTORECENT | OFN_ENABLESIZING | OFN_EXPLORER | OFN_HIDEREADONLY | OFN_LONGNAMES | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT; ofn.lpstrDefExt = L"reg"; if (GetSaveFileNameW(&ofn)) { if (!DoExport(hwnd, szFile)) { MessageBoxW(hwnd, szCannotExport, g_szTitle, MB_ICONERROR); } } }
bool fileSaveAs() { wchar_t temp[_MAX_FNAME + 1]; temp[0] = '\0'; OPENFILENAMEW ofn; ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.lpstrFile = temp; ofn.nMaxFile = _MAX_FNAME; ofn.lpstrDefExt = L"rocket"; ofn.lpstrFilter = L"ROCKET File (*.rocket)\0*.rocket\0All Files (*.*)\0*.*\0\0"; ofn.Flags = OFN_SHOWHELP | OFN_OVERWRITEPROMPT; if (GetSaveFileNameW(&ofn)) { if (document.save(temp)) { document.sendSaveCommand(); setWindowFileName(temp); fileName = temp; mruFileList.insert(temp); mruFileList.update(); DrawMenuBar(hwnd); return true; } else error("Failed to save file"); } return false; }
static LPWSTR dialog_print_to_file(HWND hMainWnd) { OPENFILENAMEW ofn; static WCHAR file[MAX_PATH] = {'O','U','T','P','U','T','.','P','R','N',0}; static const WCHAR defExt[] = {'P','R','N',0}; static LPWSTR file_filter; if(!file_filter) file_filter = get_print_file_filter(hMainWnd); ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.Flags = OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT; ofn.hwndOwner = hMainWnd; ofn.lpstrFilter = file_filter; ofn.lpstrFile = file; ofn.nMaxFile = MAX_PATH; ofn.lpstrDefExt = defExt; if(GetSaveFileNameW(&ofn)) return file; else return FALSE; }
BOOL ClearEvents(VOID) { HANDLE hEventLog; WCHAR szFileName[MAX_PATH]; WCHAR szMessage[MAX_LOADSTRING]; ZeroMemory(szFileName, sizeof(szFileName)); ZeroMemory(szMessage, sizeof(szMessage)); LoadStringW(hInst, IDS_CLEAREVENTS_MSG, szMessage, MAX_LOADSTRING); sfn.lpstrFile = szFileName; sfn.nMaxFile = MAX_PATH; switch (MessageBoxW(hwndMainWindow, szMessage, szTitle, MB_YESNOCANCEL | MB_ICONINFORMATION)) { case IDCANCEL: { return FALSE; } case IDNO: { sfn.lpstrFile = NULL; break; } case IDYES: { if (!GetSaveFileNameW(&sfn)) { return FALSE; } break; } } hEventLog = OpenEventLogW(lpComputerName, lpSourceLogName); if (!hEventLog) { ShowLastWin32Error(); return FALSE; } if (!ClearEventLogW(hEventLog, sfn.lpstrFile)) { ShowLastWin32Error(); CloseEventLog(hEventLog); return FALSE; } CloseEventLog(hEventLog); return TRUE; }
BOOL DIALOG_FileSaveAs(VOID) { OPENFILENAMEW saveas; WCHAR szPath[MAX_PATH]; WCHAR szDir[MAX_PATH]; static const WCHAR szDefaultExt[] = { 't','x','t',0 }; static const WCHAR txt_files[] = { '*','.','t','x','t',0 }; ZeroMemory(&saveas, sizeof(saveas)); GetCurrentDirectoryW(ARRAY_SIZE(szDir), szDir); lstrcpyW(szPath, txt_files); saveas.lStructSize = sizeof(OPENFILENAMEW); saveas.hwndOwner = Globals.hMainWnd; saveas.hInstance = Globals.hInstance; saveas.lpstrFilter = Globals.szFilter; saveas.lpstrFile = szPath; saveas.nMaxFile = ARRAY_SIZE(szPath); saveas.lpstrInitialDir = szDir; saveas.Flags = OFN_ENABLETEMPLATE | OFN_ENABLEHOOK | OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY | OFN_ENABLESIZING; saveas.lpfnHook = OfnHookProc; saveas.lpTemplateName = MAKEINTRESOURCEW(IDD_OFN_TEMPLATE); saveas.lpstrDefExt = szDefaultExt; /* Preset encoding to what file was opened/saved last with. */ Globals.encOfnCombo = Globals.encFile; Globals.bOfnIsOpenDialog = FALSE; retry: if (!GetSaveFileNameW(&saveas)) return FALSE; switch (DoSaveFile(szPath, Globals.encOfnCombo)) { case SAVED_OK: SetFileNameAndEncoding(szPath, Globals.encOfnCombo); UpdateWindowCaption(); return TRUE; case SHOW_SAVEAS_DIALOG: goto retry; default: return FALSE; } }
wchar_t *askfilesaveW(const char *title, const char *default_name) { int i; OPENFILENAMEW ofn; wchar_t cwd[MAX_PATH], wdef_name[MAX_PATH], wtitle[1000]; if (!default_name) wcscpy(wdef_name, L""); else mbstowcs(wdef_name, default_name, MAX_PATH); wcscpy(wcsbuf, wdef_name); mbstowcs(wtitle, title, 1000); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = current_window ? current_window->handle : 0; ofn.hInstance = 0; ofn.lpstrFilter = userfilterW ? userfilterW : wfilter[0]; ofn.lpstrCustomFilter = NULL; ofn.nMaxCustFilter = 0; ofn.nFilterIndex = 0; ofn.lpstrFile = wcsbuf; ofn.nMaxFile = BUFSIZE; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = _MAX_FNAME + _MAX_EXT; if (GetCurrentDirectoryW(MAX_PATH, cwd)) ofn.lpstrInitialDir = cwd; else ofn.lpstrInitialDir = NULL; ofn.lpstrTitle = wtitle; ofn.Flags = OFN_OVERWRITEPROMPT | OFN_NOCHANGEDIR | OFN_HIDEREADONLY; ofn.nFileOffset = 0; ofn.nFileExtension = 0; ofn.lpstrDefExt = NULL; ofn.lCustData = 0L; ofn.lpfnHook = NULL; ofn.lpTemplateName = NULL; if (GetSaveFileNameW(&ofn) == 0) return NULL; else { for (i = 0; i < 10; i++) if (peekevent()) doevent(); return wcsbuf; } }
// CMeshExporterDlg message handlers bool CMeshExporterDlg::get_saved_filename(wchar_t* file_name) { OPENFILENAMEW ofn; ZeroMemory(&ofn, sizeof(OPENFILENAMEW)); ofn.lStructSize = sizeof(OPENFILENAMEW); ofn.hwndOwner = ::GetActiveWindow(); ofn.lpstrFile = file_name; ofn.nMaxFile = MAX_PATH; ofn.lpstrFilter = L"XEvol模型文件(*.xrm)\0*.xrm\0XEvol网格文件(*.mesh)\0*.mesh\0所有文件(*.*)\0*.*\0"; ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.lpstrDefExt = L"mesh"; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; if(GetSaveFileNameW(&ofn) == FALSE) { return false; } return true; }
static VOID DoSaveAs(PINFO pInfo) { OPENFILENAMEW ofn; WCHAR szFileName[MAX_PATH] = L"Default.rdp"; static WCHAR szFilter[] = L"Remote Desktop Files (*.RDP)\0*.rdp\0"; ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(OPENFILENAMEW); ofn.hwndOwner = pInfo->hGeneralPage; ofn.nMaxFile = MAX_PATH; ofn.nMaxFileTitle = MAX_PATH; ofn.lpstrDefExt = L"RDP"; ofn.lpstrFilter = szFilter; ofn.lpstrFile = szFileName; ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT; if (GetSaveFileNameW(&ofn)) { SaveAllSettings(pInfo); SaveRdpSettingsToFile(szFileName, pInfo->pRdpSettings); } }
/// <summary> /// Invoke Open/Save file dialog /// </summary> /// <param name="filter">File filter</param> /// <param name="defIndex">Default filter index</param> /// <param name="selectedPath">Target file path</param> /// <param name="bSave">true to Save file, false to open</param> /// <param name="defExt">Default file extension for file save</param> /// <returns>true on success, false if operation was canceled by user</returns> bool MainDlg::OpenSaveDialog( const wchar_t* filter, int defIndex, std::wstring& selectedPath, bool bSave /*= false*/, const std::wstring& defExt /*= L""*/ ) { OPENFILENAMEW ofn = { 0 }; wchar_t path[MAX_PATH] = { 0 }; ofn.lStructSize = sizeof( ofn ); ofn.hwndOwner = NULL; ofn.lpstrFile = path; ofn.lpstrFile[0] = '\0'; ofn.nMaxFile = MAX_PATH; ofn.lpstrFilter = filter; ofn.nFilterIndex = defIndex; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; if (!bSave) { ofn.Flags = OFN_PATHMUSTEXIST; } else { ofn.Flags = OFN_OVERWRITEPROMPT; ofn.lpstrDefExt = defExt.c_str(); } auto res = bSave ? GetSaveFileNameW( &ofn ) : GetOpenFileNameW( &ofn ); if (res) selectedPath = path; return res != FALSE; }
int file_open_dialog(Value *vret, const char *title, RefArray *filter, WndHandle parent, int type) { enum { RETBUF_MAX = 32 * 1024, }; int ret = FALSE; wchar_t *title_p = cstr_to_utf16(title, -1); wchar_t *filter_p = NULL; wchar_t *wbuf = malloc(RETBUF_MAX); int offset = 0; memset(wbuf, 0, RETBUF_MAX); if (type == FILEOPEN_DIR) { BROWSEINFOW bi; LPMALLOC pm = NULL; if (SHGetMalloc(&pm) != E_FAIL) { ITEMIDLIST *id; memset(&bi, 0, sizeof(bi)); bi.hwndOwner = parent; bi.ulFlags = BIF_RETURNONLYFSDIRS; bi.lpszTitle = title_p; id = SHBrowseForFolderW(&bi); if (id != NULL){ SHGetPathFromIDListW(id, wbuf); pm->lpVtbl->Free(pm, id); pm->lpVtbl->Release(pm); ret = TRUE; } } } else { OPENFILENAMEW of; memset(&of, 0, sizeof(of)); of.hwndOwner = parent; of.lpstrFile = wbuf; of.nMaxFile = RETBUF_MAX - 16; of.hInstance = GetModuleHandle(NULL); of.lStructSize = sizeof(of); of.Flags = OFN_NOCHANGEDIR | OFN_CREATEPROMPT; of.lpstrTitle = title_p; if (filter != NULL) { filter_p = make_filter_string(filter); of.lpstrFilter = filter_p; } switch (type) { case FILEOPEN_OPEN: of.Flags |= OFN_HIDEREADONLY; ret = (GetOpenFileNameW(&of) != 0); break; case FILEOPEN_OPEN_MULTI: of.Flags |= OFN_HIDEREADONLY | OFN_ALLOWMULTISELECT | OFN_EXPLORER; ret = (GetOpenFileNameW(&of) != 0); offset = of.nFileOffset; break; case FILEOPEN_SAVE: of.Flags |= OFN_OVERWRITEPROMPT | OFN_EXTENSIONDIFFERENT | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST; ret = (GetSaveFileNameW(&of) != 0); break; } } if (ret) { if (type == FILEOPEN_OPEN_MULTI) { RefArray *aret = fs->refarray_new(0); wchar_t *p = wbuf; int dlen = wcslen(p); *vret = vp_Value(aret); if (offset <= dlen) { array_add_file(aret, p); } else { wchar_t *dir_part = p; p = &p[offset]; while (*p != L'\0'){ wchar_t *filename = concat_filename(dir_part, p); array_add_file(aret, filename); free(filename); p += wcslen(p) + 1; } } } else { *vret = utf16_file_Value(wbuf); } } free(title_p); free(wbuf); free(filter_p); return ret; }
BOOL WINAPI __GetSaveFileNameW(LPOPENFILENAMEW lpofn) { if (g_bOutput) if (!wcscmp(lpofn->lpstrTitle, L"Save .VDR signpost for AVIFile handler")) return FALSE; return GetSaveFileNameW(lpofn); }
/* bug 6829 */ static void test_DialogCancel(void) { OPENFILENAMEA ofn; BOOL result; char szFileName[MAX_PATH] = ""; char szInitialDir[MAX_PATH]; GetWindowsDirectory(szInitialDir, MAX_PATH); ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = NULL; ofn.lpstrFilter = "Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0"; ofn.lpstrFile = szFileName; ofn.nMaxFile = MAX_PATH; ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_ENABLEHOOK; ofn.lpstrDefExt = "txt"; ofn.lpfnHook = OFNHookProc; ofn.lpstrInitialDir = szInitialDir; PrintDlgA(NULL); ok(CDERR_INITIALIZATION == CommDlgExtendedError(), "expected CDERR_INITIALIZATION, got %d\n", CommDlgExtendedError()); result = GetOpenFileNameA(&ofn); ok(0 == result, "expected 0, got %d\n", result); ok(0 == CommDlgExtendedError(), "expected 0, got %d\n", CommDlgExtendedError()); PrintDlgA(NULL); ok(CDERR_INITIALIZATION == CommDlgExtendedError(), "expected CDERR_INITIALIZATION, got %d\n", CommDlgExtendedError()); result = GetSaveFileNameA(&ofn); ok(0 == result, "expected 0, got %d\n", result); ok(0 == CommDlgExtendedError(), "expected 0, got %d\n", CommDlgExtendedError()); PrintDlgA(NULL); ok(CDERR_INITIALIZATION == CommDlgExtendedError(), "expected CDERR_INITIALIZATION, got %d\n", CommDlgExtendedError()); /* Before passing the ofn to Unicode functions, remove the ANSI strings */ ofn.lpstrFilter = NULL; ofn.lpstrInitialDir = NULL; ofn.lpstrDefExt = NULL; PrintDlgA(NULL); ok(CDERR_INITIALIZATION == CommDlgExtendedError(), "expected CDERR_INITIALIZATION, got %d\n", CommDlgExtendedError()); SetLastError(0xdeadbeef); result = GetOpenFileNameW((LPOPENFILENAMEW) &ofn); if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) win_skip("GetOpenFileNameW is not implemented\n"); else { ok(0 == result, "expected 0, got %d\n", result); ok(0 == CommDlgExtendedError() || broken(CDERR_INITIALIZATION == CommDlgExtendedError()), /* win9x */ "expected 0, got %d\n", CommDlgExtendedError()); } SetLastError(0xdeadbeef); result = GetSaveFileNameW((LPOPENFILENAMEW) &ofn); if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED) win_skip("GetSaveFileNameW is not implemented\n"); else { ok(0 == result, "expected 0, got %d\n", result); ok(0 == CommDlgExtendedError() || broken(CDERR_INITIALIZATION == CommDlgExtendedError()), /* win9x */ "expected 0, got %d\n", CommDlgExtendedError()); } }
bbString bbRequesters::RequestFile( bbString title,bbString exts,bbBool save,bbString path ){ bbString file,dir; path=path.replace( "/","\\" ); int i=path.findLast( "\\" ); if( i!=-1 ){ dir=path.slice( 0,i ); file=path.slice( 1+1 ); }else{ file=path; } if( file.length()>MAX_PATH ) return ""; if( exts.length() ){ if( exts.find( ":" )==-1 ){ exts=bbString( "Files\0*.",8 )+exts; }else{ exts=exts.replace( ":",bbString( "\0*.",3 ) ); } exts=exts.replace( ";",bbString( "\0",1 ) ); exts=exts.replace( ",",";*." )+bbString( "\0",1 ); } WCHAR buf[MAX_PATH+1]; memcpy( buf,file.data(),file.length()*2 ); buf[file.length()]=0; OPENFILENAMEW of={sizeof(of)}; of.hwndOwner=GetActiveWindow(); of.lpstrTitle=tmpWString( title ); of.lpstrFilter=tmpWString( exts ); of.lpstrFile=buf; of.lpstrInitialDir=dir.length() ? tmpWString( dir ) : 0; of.nMaxFile=MAX_PATH; of.Flags=OFN_HIDEREADONLY|OFN_NOCHANGEDIR; bbString str; beginPanel(); if( save ){ of.lpstrDefExt=L""; of.Flags|=OFN_OVERWRITEPROMPT; if( GetSaveFileNameW( &of ) ){ str=bbString( buf ); } }else{ of.Flags|=OFN_FILEMUSTEXIST; if( GetOpenFileNameW( &of ) ){ str=bbString( buf ); } } endPanel(); free( (void*)of.lpstrTitle ); free( (void*)of.lpstrFilter ); free( (void*)of.lpstrInitialDir ); str=str.replace( "\\","/" ); return str; }
sBool sSystemOpenFileDialog(const sChar *label,const sChar *extensions,sInt flags,const sStringDesc &buffer) { sChar oldpath[2048]; OPENFILENAMEW ofn; sInt result=0; // determine default extension (=first in list) sString<256> defaultExt; defaultExt = extensions; sInt pipePos; if((pipePos = sFindFirstChar(defaultExt,'|')) != -1) defaultExt[pipePos] = 0; sChar ext[2048]; sClear(ext); sChar *extp = ext; sInt filterindex = 0; if((flags & 3) == sSOF_LOAD && sFindChar(extensions,'|')>=0) // opening, more than one extension specified? { filterindex = 1; static const sChar allSupported[] = L"All supported extensions"; sCopyMem(extp,allSupported,sizeof(allSupported)); extp += sCOUNTOF(allSupported); // add all supported extensions const sChar *curExt = extensions; sBool first = sTRUE; for(;;) { while(*curExt=='|') curExt++; if(!*curExt) break; if(!first) *extp++ = ';'; *extp++ = '*'; *extp++ = '.'; while(*curExt!='|' && *curExt) *extp++ = *curExt++; first = sFALSE; } *extp++ = 0; } for(;;) { while(*extensions=='|') extensions++; if(!*extensions) break; const sChar *ext1 = extensions; while(*ext1!='|' && *ext1) *extp++ = *ext1++; *extp++ = 0; *extp++ = '*'; *extp++ = '.'; while(*extensions!='|' && *extensions) *extp++ = *extensions++; *extp++ = 0; } static const sChar allFiles[] = L"All files (*.*)\0*.*\0"; sCopyMem(extp,allFiles,sizeof(allFiles)); extp += sCOUNTOF(allFiles); sSetMem(&ofn,0,sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = sHWND; ofn.lpstrFile = buffer.Buffer; ofn.nMaxFile = buffer.Size; ofn.lpstrFilter = ext; ofn.nFilterIndex = filterindex; ofn.lpstrTitle = label; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; if(0) // this stuff does not work in windows any more. thanks to microsoft being so very intuitive { sString<sMAXPATH> initialdir; sGetCurrentDir(initialdir); initialdir.AddPath(buffer.Buffer); sChar *lastslash = 0; for(sInt i=0;initialdir[i];i++) if(initialdir[i]=='/' || initialdir[i]=='\\') lastslash = &initialdir[i]; if(lastslash) *lastslash = 0; if(buffer.Buffer[0]!=0) ofn.lpstrInitialDir = initialdir; } if(!defaultExt.IsEmpty()) ofn.lpstrDefExt = defaultExt; for(sInt i=0;buffer.Buffer[i];i++) if(buffer.Buffer[i]=='/') buffer.Buffer[i]='\\'; sInt len = sGetStringLen(buffer.Buffer); if(len>0 && buffer.Buffer[len-1]=='\\') buffer.Buffer[len-1]=0; GetCurrentDirectoryW(sCOUNTOF(oldpath),oldpath); sWin32::ModalDialogActive = sTRUE; switch(flags & 3) { case sSOF_LOAD: ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER; if (flags&sSOF_MULTISELECT) ofn.Flags|=OFN_ALLOWMULTISELECT; result = GetOpenFileNameW(&ofn); break; case sSOF_SAVE: ofn.Flags = OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT | OFN_EXPLORER; result = GetSaveFileNameW(&ofn); break; case sSOF_DIR: { CoInitializeEx(0L,COINIT_APARTMENTTHREADED); BROWSEINFO bi; memset(&bi, 0, sizeof(bi)); bi.ulFlags = BIF_USENEWUI; bi.hwndOwner = GetDesktopWindow(); bi.lpszTitle = label; SetActiveWindow(GetDesktopWindow()); UpdateWindow(GetDesktopWindow()); LPITEMIDLIST pIDL; pIDL = SHBrowseForFolderW(&bi); if(pIDL!=0L) { // Create a buffer to store the path, then // get the path. sChar buffer2[_MAX_PATH] = L"\0"; if(SHGetPathFromIDList(pIDL, buffer2) != 0) { // Set the string value. sCopyString(buffer,buffer2); result = true; } // free the item id list CoTaskMemFree(pIDL); } } break; default: result = 0; break; } sWin32::ModalDialogActive = sFALSE; SetCurrentDirectoryW(oldpath); for(sInt i=0;buffer.Buffer[i];i++) if(buffer.Buffer[i]=='\\') buffer.Buffer[i]='/'; return result; }
BBString *bbSystemRequestFile( BBString *text,BBString *exts,int defext,int save,BBString *file,BBString *dir ){ BBString *str=&bbEmptyString; if( _usew ){ wchar_t buf[MAX_PATH]; OPENFILENAMEW of={sizeof(of)}; wcscpy( buf,bbTmpWString( file ) ); of.hwndOwner=GetActiveWindow(); of.lpstrTitle=bbTmpWString( text ); of.lpstrFilter=bbTmpWString( exts ); of.nFilterIndex=defext; of.lpstrFile=buf; of.lpstrInitialDir=dir->length ? bbTmpWString( dir ) : 0; of.nMaxFile=MAX_PATH; of.Flags=OFN_HIDEREADONLY|OFN_NOCHANGEDIR; beginPanel(); if( save ){ of.lpstrDefExt=L""; of.Flags|=OFN_OVERWRITEPROMPT; if( GetSaveFileNameW( &of ) ){ str=bbStringFromWString( buf ); } }else{ of.Flags|=OFN_FILEMUSTEXIST; if( GetOpenFileNameW( &of ) ){ str=bbStringFromWString( buf ); } } endPanel(); }else{ char buf[MAX_PATH]; OPENFILENAMEA of={sizeof(of)}; strcpy( buf,bbTmpCString( file ) ); of.hwndOwner=GetActiveWindow(); of.lpstrTitle=bbTmpCString( text ); of.lpstrFilter=bbTmpCString( exts ); of.nFilterIndex=defext; of.lpstrFile=buf; of.lpstrInitialDir=dir->length ? bbTmpCString( dir ) : 0; of.nMaxFile=MAX_PATH; of.Flags=OFN_HIDEREADONLY|OFN_NOCHANGEDIR; beginPanel(); if( save ){ of.lpstrDefExt=""; of.Flags|=OFN_OVERWRITEPROMPT; if( GetSaveFileNameA( &of ) ){ str=bbStringFromCString( buf ); } }else{ of.Flags|=OFN_FILEMUSTEXIST; if( GetOpenFileNameA( &of ) ){ str=bbStringFromCString( buf ); } } endPanel(); } return str; }
void native_export_chatlog_init(uint32_t friend_number) { FRIEND *f = get_friend(friend_number); if (!f) { LOG_ERR("Windows7", "Could not get friend with number: %u", friend_number); return; } char *path = calloc(1, UTOX_FILE_NAME_LENGTH); if (!path){ LOG_ERR("Windows7", " Could not allocate memory." ); return; } snprintf(path, UTOX_FILE_NAME_LENGTH, "%.*s.txt", (int)f->name_length, f->name); wchar_t filepath[UTOX_FILE_NAME_LENGTH] = { 0 }; utf8_to_nativestr(path, filepath, UTOX_FILE_NAME_LENGTH * 2); OPENFILENAMEW ofn = { .lStructSize = sizeof(OPENFILENAMEW), .lpstrFilter = L".txt", .lpstrFile = filepath, .nMaxFile = UTOX_FILE_NAME_LENGTH, .Flags = OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_NOREADONLYRETURN | OFN_OVERWRITEPROMPT, .lpstrDefExt = L"txt", }; if (GetSaveFileNameW(&ofn)) { path = calloc(1, UTOX_FILE_NAME_LENGTH); if (!path){ LOG_ERR("Windows7", " Could not allocate memory." ); return; } native_to_utf8str(filepath, path, UTOX_FILE_NAME_LENGTH); FILE *file = utox_get_file_simple(path, UTOX_FILE_OPTS_WRITE); if (file) { utox_export_chatlog(f->id_str, file); } else { LOG_ERR("Windows7", "Opening file %s failed", path); } } else { LOG_ERR("Windows7", "Unable to open file and export chatlog."); } free(path); } void native_select_dir_ft(uint32_t fid, uint32_t num, FILE_TRANSFER *file) { if (!sanitize_filename(file->name)) { LOG_ERR("Windows7", "Filename is invalid and could not be sanitized"); return; } wchar_t filepath[UTOX_FILE_NAME_LENGTH] = { 0 }; utf8_to_nativestr((char *)file->name, filepath, file->name_length * 2); OPENFILENAMEW ofn = { .lStructSize = sizeof(OPENFILENAMEW), .lpstrFile = filepath, .nMaxFile = UTOX_FILE_NAME_LENGTH, .Flags = OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_NOREADONLYRETURN | OFN_OVERWRITEPROMPT, }; if (GetSaveFileNameW(&ofn)) { char *path = calloc(1, UTOX_FILE_NAME_LENGTH); if (!path) { LOG_ERR("Windows7", "Could not allocate memory for path."); return; } native_to_utf8str(filepath, path, UTOX_FILE_NAME_LENGTH * 2); postmessage_toxcore(TOX_FILE_ACCEPT, fid, num, path); } else { LOG_ERR("Windows7", "Unable to Get save file for incoming FT."); } } void native_autoselect_dir_ft(uint32_t fid, FILE_TRANSFER *file) { wchar_t *autoaccept_folder = NULL; if (settings.portable_mode) { autoaccept_folder = calloc(1, UTOX_FILE_NAME_LENGTH * sizeof(wchar_t)); utf8_to_nativestr(portable_mode_save_path, autoaccept_folder, strlen(portable_mode_save_path) * 2); } else if (SHGetKnownFolderPath((REFKNOWNFOLDERID)&FOLDERID_Downloads, KF_FLAG_CREATE, NULL, &autoaccept_folder) != S_OK) { LOG_ERR("Windows7", "Unable to get auto accept file folder!"); return; } wchar_t subpath[UTOX_FILE_NAME_LENGTH] = { 0 }; swprintf(subpath, UTOX_FILE_NAME_LENGTH, L"%ls%ls", autoaccept_folder, L"\\Tox_Auto_Accept"); if (settings.portable_mode) { free(autoaccept_folder); } else { CoTaskMemFree(autoaccept_folder); } CreateDirectoryW(subpath, NULL); if (!sanitize_filename(file->name)) { LOG_ERR("Windows7", "Filename is invalid and could not be sanitized"); return; } wchar_t filename[UTOX_FILE_NAME_LENGTH] = { 0 }; utf8_to_nativestr((char *)file->name, filename, file->name_length * 2); wchar_t fullpath[UTOX_FILE_NAME_LENGTH] = { 0 }; swprintf(fullpath, UTOX_FILE_NAME_LENGTH, L"%ls\\%ls", subpath, filename); char *path = calloc(1, UTOX_FILE_NAME_LENGTH); if (!path) { LOG_ERR("Windows7", "Could not allocate memory for path."); return; } native_to_utf8str(fullpath, path, UTOX_FILE_NAME_LENGTH); postmessage_toxcore(TOX_FILE_ACCEPT_AUTO, fid, file->file_number, path); } void launch_at_startup(bool should) { const wchar_t *run_key_path = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"; if (should) { HKEY hKey; if (RegOpenKeyW(HKEY_CURRENT_USER, run_key_path, &hKey) == ERROR_SUCCESS) { wchar_t path[UTOX_FILE_NAME_LENGTH * 2]; uint16_t path_length = GetModuleFileNameW(NULL, path + 1, UTOX_FILE_NAME_LENGTH * 2); path[0] = '\"'; path[path_length + 1] = '\"'; path[path_length + 2] = '\0'; path_length += 2; // 2 bytes per wchar_t uint16_t ret = RegSetKeyValueW(hKey, NULL, L"uTox", REG_SZ, path, path_length * 2); if (ret == ERROR_SUCCESS) { LOG_INFO("Windows7", "Set uTox to run at startup."); } else { LOG_ERR("Windows7", "Unable to set Registry key for startup."); } RegCloseKey(hKey); } } else { HKEY hKey; if (ERROR_SUCCESS == RegOpenKeyW(HKEY_CURRENT_USER, run_key_path, &hKey)) { uint16_t ret = RegDeleteKeyValueW(hKey, NULL, L"uTox"); if (ret == ERROR_SUCCESS) { LOG_INFO("Windows7", "Set uTox to not run at startup."); } else { LOG_ERR("Windows7", "Unable to delete Registry key for startup."); } RegCloseKey(hKey); } } }
static void pSaveImageAs(HWND hwnd) { OPENFILENAMEW sfn; ImageCodecInfo *codecInfo; WCHAR szSaveFileName[MAX_PATH]; WCHAR *szFilterMask; GUID rawFormat; UINT num; UINT size; UINT sizeRemain; UINT j; WCHAR *c; GdipGetImageEncodersSize(&num, &size); codecInfo = malloc(size); if (!codecInfo) { DPRINT1("malloc() failed in pSaveImageAs()\n"); return; } GdipGetImageEncoders(num, size, codecInfo); GdipGetImageRawFormat(image, &rawFormat); sizeRemain = 0; for (j = 0; j < num; ++j) { // Every pair needs space for the Description, twice the Extensions, 1 char for the space, 2 for the braces and 2 for the NULL terminators. sizeRemain = sizeRemain + (((wcslen(codecInfo[j].FormatDescription) + (wcslen(codecInfo[j].FilenameExtension) * 2) + 5) * sizeof(WCHAR))); } /* Add two more chars for the last terminator */ sizeRemain = sizeRemain + (sizeof(WCHAR) * 2); szFilterMask = malloc(sizeRemain); if (!szFilterMask) { DPRINT1("cannot allocate memory for filter mask in pSaveImageAs()"); free(codecInfo); return; } ZeroMemory(szSaveFileName, sizeof(szSaveFileName)); ZeroMemory(szFilterMask, sizeRemain); ZeroMemory(&sfn, sizeof(sfn)); sfn.lStructSize = sizeof(sfn); sfn.hwndOwner = hwnd; sfn.hInstance = hInstance; sfn.lpstrFile = szSaveFileName; sfn.lpstrFilter = szFilterMask; sfn.nMaxFile = MAX_PATH; sfn.Flags = OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY; c = szFilterMask; for (j = 0; j < num; ++j) { StringCbPrintfExW(c, sizeRemain, &c, &sizeRemain, 0, L"%ls (%ls)", codecInfo[j].FormatDescription, codecInfo[j].FilenameExtension); /* Skip the NULL character */ c++; sizeRemain -= sizeof(*c); StringCbPrintfExW(c, sizeRemain, &c, &sizeRemain, 0, L"%ls", codecInfo[j].FilenameExtension); /* Skip the NULL character */ c++; sizeRemain -= sizeof(*c); if (IsEqualGUID(&rawFormat, &codecInfo[j].FormatID) == TRUE) { sfn.nFilterIndex = j + 1; } } if (GetSaveFileNameW(&sfn)) { if (GdipSaveImageToFile(image, szSaveFileName, &codecInfo[sfn.nFilterIndex - 1].Clsid, NULL) != Ok) { DPRINT1("GdipSaveImageToFile() failed\n"); } } free(szFilterMask); free(codecInfo); }
static int MCA_do_file_dialog(MCStringRef p_title, MCStringRef p_prompt, MCStringRef p_filter, MCStringRef p_initial, unsigned int p_options, MCStringRef &r_value, MCStringRef &r_result) { int t_result = 0; MCAutoStringRef t_initial_file; MCAutoStringRef t_initial_folder; MCAutoStringRef t_initial_native_folder; if (p_initial != nil && !MCStringIsEmpty(p_initial)) { MCAutoStringRef t_fixed_path; /* UNCHECKED */ MCU_fix_path(p_initial, &t_fixed_path); if (MCS_exists(*t_fixed_path, False)) t_initial_folder = *t_fixed_path; else if ((p_options & MCA_OPTION_SAVE_DIALOG) != 0) { uindex_t t_last_slash; if (!MCStringLastIndexOfChar(*t_fixed_path, '/', UINDEX_MAX, kMCStringOptionCompareExact, t_last_slash)) { if (MCStringGetLength(*t_fixed_path) != 0) t_initial_file = *t_fixed_path; } else { if (t_last_slash < MCStringGetLength(*t_fixed_path) - 1) /* UNCHECKED */ MCStringCopySubstring(*t_fixed_path, MCRangeMake(t_last_slash + 1, MCStringGetLength(*t_fixed_path) - (t_last_slash + 1)), &t_initial_file); MCAutoStringRef t_folder_split; /* UNCHECKED */ MCStringCopySubstring(*t_fixed_path, MCRangeMake(0, t_last_slash - 1), &t_folder_split); if (MCS_exists(*t_folder_split, False)) t_initial_folder = *t_folder_split; } } else { uindex_t t_last_slash; if (MCStringLastIndexOfChar(*t_fixed_path, '/', UINDEX_MAX, kMCStringOptionCompareExact, t_last_slash)) { MCAutoStringRef t_folder_split; /* UNCHECKED */ MCStringCopySubstring(*t_fixed_path, MCRangeMake(0, t_last_slash - 1), &t_folder_split); if (MCS_exists(*t_folder_split, False)) t_initial_folder = *t_folder_split; } } MCAutoStringRef t_resolved_folder; /* UNCHECKED */ MCS_resolvepath(*t_initial_folder != nil ? *t_initial_folder : kMCEmptyString, &t_resolved_folder); /* UNCHECKED */ MCS_pathtonative(*t_resolved_folder, &t_initial_native_folder); } if (!MCModeMakeLocalWindows()) { MCAutoStringRefArray t_filters; if (p_filter != NULL) { /* UNCHECKED */ MCStringsSplit(p_filter, '\0', t_filters.PtrRef(), t_filters.CountRef()); } MCRemoteFileDialog(p_title, p_prompt, *t_filters, t_filters.Count(), *t_initial_native_folder, *t_initial_file, (p_options & MCA_OPTION_SAVE_DIALOG) != 0, (p_options & MCA_OPTION_PLURAL) != 0, r_value); return 0; } Window t_window; t_window = MCModeGetParentWindow(); MCAutoStringRef t_value; bool t_succeeded; int t_filter_index; if (MCmajorosversion >= 0x0600) { static SHCreateItemFromParsingNamePtr s_shcreateitemfromparsingname = NULL; if (s_shcreateitemfromparsingname == NULL) { static HMODULE s_shell32_module = NULL; s_shell32_module = LoadLibraryW(L"shell32.dll"); s_shcreateitemfromparsingname = (SHCreateItemFromParsingNamePtr)GetProcAddress(s_shell32_module, "SHCreateItemFromParsingName"); } IFileSaveDialog *t_file_save_dialog; IFileOpenDialog *t_file_open_dialog; IFileDialog *t_file_dialog; t_file_dialog = NULL; HRESULT t_hresult; if ((p_options & MCA_OPTION_SAVE_DIALOG) == 0) { t_hresult = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, __uuidof(IFileOpenDialog), (LPVOID *)&t_file_open_dialog); t_succeeded = SUCCEEDED(t_hresult); t_file_dialog = t_file_open_dialog; } else { t_hresult = CoCreateInstance(CLSID_FileSaveDialog, NULL, CLSCTX_INPROC_SERVER, __uuidof(IFileSaveDialog), (LPVOID *)&t_file_save_dialog); t_succeeded = SUCCEEDED(t_hresult); t_file_dialog = t_file_save_dialog; } if (t_succeeded) { DWORD t_options; t_options = FOS_FORCEFILESYSTEM | FOS_NOCHANGEDIR | FOS_PATHMUSTEXIST; if (p_options & MCA_OPTION_PLURAL) t_options |= FOS_ALLOWMULTISELECT; if (p_options & MCA_OPTION_SAVE_DIALOG) t_options |= FOS_OVERWRITEPROMPT; if (p_options & MCA_OPTION_FOLDER_DIALOG) t_options |= FOS_PICKFOLDERS; else t_options |= FOS_FILEMUSTEXIST; t_hresult = t_file_dialog -> SetOptions(t_options); t_succeeded = SUCCEEDED(t_hresult); } if (t_succeeded && *t_initial_native_folder != NULL) { IShellItem *t_initial_folder_shellitem; t_initial_folder_shellitem = NULL; MCAutoStringRefAsWString t_initial_folder_wstr; /* UNCHECKED */ t_initial_folder_wstr.Lock(*t_initial_native_folder); t_hresult = s_shcreateitemfromparsingname(*t_initial_folder_wstr, NULL, __uuidof(IShellItem), (LPVOID *)&t_initial_folder_shellitem); if (SUCCEEDED(t_hresult)) t_file_dialog -> SetFolder(t_initial_folder_shellitem); if (t_initial_folder_shellitem != NULL) t_initial_folder_shellitem -> Release(); t_succeeded = SUCCEEDED(t_hresult); } if (t_succeeded && *t_initial_file != NULL) { MCAutoStringRefAsWString t_initial_file_wstr; /* UNCHECKED */ t_initial_file_wstr.Lock(*t_initial_file); t_hresult = t_file_dialog -> SetFileName(*t_initial_file_wstr); t_succeeded = SUCCEEDED(t_hresult); } if (t_succeeded && p_filter != NULL && (p_options & MCA_OPTION_FOLDER_DIALOG) == 0) { uint4 t_filter_length, t_filter_count; measure_filter(p_filter, t_filter_length, t_filter_count); MCAutoStringRefAsWString t_filter_wstr; /* UNCHECKED */ t_filter_wstr.Lock(p_filter); COMDLG_FILTERSPEC *t_filter_spec; filter_to_spec(*t_filter_wstr, t_filter_count, t_filter_spec); t_hresult = t_file_dialog -> SetFileTypes(t_filter_count, t_filter_spec); t_succeeded = SUCCEEDED(t_hresult); delete t_filter_spec; } if (t_succeeded && p_filter != NULL && (p_options & MCA_OPTION_FOLDER_DIALOG) == 0) { t_hresult = t_file_dialog -> SetFileTypeIndex(1); t_succeeded = SUCCEEDED(t_hresult); } if (t_succeeded) { MCAutoStringRefAsWString t_prompt_wstr; /* UNCHECKED */ t_prompt_wstr.Lock(p_prompt); t_hresult = t_file_dialog -> SetTitle(*t_prompt_wstr); } if (t_succeeded) { t_hresult = t_file_dialog -> Show(t_window != NULL ? (HWND)t_window -> handle . window : NULL); t_succeeded = SUCCEEDED(t_hresult); } if ((p_options & MCA_OPTION_SAVE_DIALOG) == 0) { IShellItemArray *t_file_items; t_file_items = NULL; if (t_succeeded) { t_hresult = t_file_open_dialog -> GetResults(&t_file_items); t_succeeded = SUCCEEDED(t_hresult); } DWORD t_file_item_count; if (t_succeeded) { t_hresult = t_file_items -> GetCount(&t_file_item_count); t_succeeded = SUCCEEDED(t_hresult); } if (t_succeeded) { for(uint4 t_index = 0; t_index < t_file_item_count && t_succeeded; ++t_index) { IShellItem *t_file_item; t_file_item = NULL; if (t_succeeded) { t_hresult = t_file_items -> GetItemAt(t_index, &t_file_item); t_succeeded = SUCCEEDED(t_hresult); } if (t_succeeded) { t_hresult = append_shellitem_path_and_release(t_file_item, t_index == 0, &t_value); t_succeeded = SUCCEEDED(t_hresult); } } } if (t_file_items != NULL) t_file_items -> Release(); } else { IShellItem *t_file_item; t_file_item = NULL; if (t_succeeded) { t_hresult = t_file_dialog -> GetResult(&t_file_item); t_succeeded = SUCCEEDED(t_hresult); } if (t_succeeded) { t_hresult = append_shellitem_path_and_release(t_file_item, true, &t_value); t_succeeded = SUCCEEDED(t_hresult); } } t_filter_index = 0; if (t_succeeded && (p_options & MCA_OPTION_FOLDER_DIALOG) == 0) { UINT t_index; t_hresult = t_file_dialog -> GetFileTypeIndex(&t_index); t_succeeded = SUCCEEDED(t_hresult); if (t_succeeded) t_filter_index = (int)t_index; } if (t_file_dialog != NULL) t_file_dialog -> Release(); if (!t_succeeded) t_result = t_hresult; else t_result = 0; } else { OPENFILENAMEW t_open_dialog; memset(&t_open_dialog, 0, sizeof(OPENFILENAMEW)); t_open_dialog . lStructSize = sizeof(OPENFILENAMEW); MCAutoStringRefAsWString t_initial_folder_wstr; MCAutoStringRefAsWString t_prompt_wstr; MCAutoStringRefAsWString t_filter_wstr; /* UNCHECKED */ t_filter_wstr.Lock(p_filter); /* UNCHECKED */ t_initial_folder_wstr.Lock(*t_initial_native_folder); /* UNCHECKED */ t_prompt_wstr.Lock(p_prompt); MCAutoArray<unichar_t> t_buffer; /* UNCHECKED */ t_buffer.New(MAX_PATH); if (!MCStringIsEmpty(*t_initial_file)) /* UNCHECKED */ MCStringGetChars(*t_initial_file, MCRangeMake(0, t_buffer.Size()), t_buffer.Ptr()); else t_buffer[0] = '\0'; t_open_dialog . lpstrFilter = *t_filter_wstr; t_open_dialog . nFilterIndex = 1; t_open_dialog . lpstrFile = t_buffer.Ptr(); t_open_dialog . nMaxFile = t_buffer.Size(); t_open_dialog . lpstrInitialDir = *t_initial_folder_wstr; t_open_dialog . lpstrTitle = *t_prompt_wstr; t_open_dialog . Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_NOCHANGEDIR | OFN_LONGNAMES | OFN_PATHMUSTEXIST | OFN_EXPLORER | OFN_ENABLEHOOK | OFN_ENABLESIZING; if (p_options & MCA_OPTION_PLURAL) t_open_dialog . Flags |= OFN_ALLOWMULTISELECT; if (p_options & MCA_OPTION_SAVE_DIALOG) t_open_dialog . Flags |= OFN_OVERWRITEPROMPT; t_open_dialog . lpstrFilter = *t_filter_wstr; t_open_dialog . lpfnHook = open_dialog_hook; t_open_dialog . hwndOwner = t_window != NULL ? (HWND)t_window -> handle . window : NULL; if (p_options & MCA_OPTION_SAVE_DIALOG) t_succeeded = GetSaveFileNameW(&t_open_dialog) == TRUE; else { *t_open_dialog . lpstrFile = '\0'; t_succeeded = GetOpenFileNameW(&t_open_dialog) == TRUE; } if (!t_succeeded) t_result = CommDlgExtendedError(); // MW-2005-07-26: Try again without the specified filename if it was invalid if (t_result == FNERR_INVALIDFILENAME) { *t_open_dialog . lpstrFile = '\0'; if (p_options & MCA_OPTION_SAVE_DIALOG) t_succeeded = GetSaveFileNameW(&t_open_dialog) == TRUE; else t_succeeded = GetOpenFileNameW(&t_open_dialog) == TRUE; if (!t_succeeded) t_result = CommDlgExtendedError(); } if (t_result == FNERR_BUFFERTOOSMALL) t_succeeded = true; if (t_succeeded) { build_paths(&t_value); t_filter_index = t_open_dialog . nFilterIndex; } } if (t_succeeded) { if (p_options & MCA_OPTION_RETURN_FILTER) { // The filter string has the following format: // "<description0>\0<extensions0>\0<description1>\0...\0<extensionsN>\0" // so the n'th filter comes after the 2(n - 1)'th null character uindex_t t_index = 2 * (t_filter_index - 1); uindex_t t_offset = 0; while (t_index--) { /* UNCHECKED */ MCStringFirstIndexOfChar(p_filter, '\0', t_offset, kMCStringOptionCompareExact, t_offset); t_offset++; } uindex_t t_end; t_end = UINDEX_MAX; /* UNCHECKED */ MCStringFirstIndexOfChar(p_filter, '\0', t_offset, kMCStringOptionCompareExact, t_end); /* UNCHECKED */ MCStringCopySubstring(p_filter, MCRangeMake(t_offset, t_end-t_offset), r_result); } t_result = 0; r_value = MCValueRetain(*t_value); } else r_result = MCValueRetain(MCNameGetString(MCN_cancel)); waitonbutton(); return t_result; }
static BOOL GetOpenSaveFileNameUTF8(LPOPENFILENAME lpofn, BOOL save) { OPENFILENAMEW tmp={sizeof(tmp),lpofn->hwndOwner,lpofn->hInstance,}; BOOL ret; // allocate, convert input if (lpofn->lpstrFilter) tmp.lpstrFilter = WDL_UTF8ToWC(lpofn->lpstrFilter,TRUE,0,0); tmp.nFilterIndex = lpofn->nFilterIndex ; if (lpofn->lpstrFile) tmp.lpstrFile = WDL_UTF8ToWC(lpofn->lpstrFile,FALSE,lpofn->nMaxFile,&tmp.nMaxFile); if (lpofn->lpstrFileTitle) tmp.lpstrFileTitle = WDL_UTF8ToWC(lpofn->lpstrFileTitle,FALSE,lpofn->nMaxFileTitle,&tmp.nMaxFileTitle); if (lpofn->lpstrInitialDir) tmp.lpstrInitialDir = WDL_UTF8ToWC(lpofn->lpstrInitialDir,0,0,0); if (lpofn->lpstrTitle) tmp.lpstrTitle = WDL_UTF8ToWC(lpofn->lpstrTitle,0,0,0); if (lpofn->lpstrDefExt) tmp.lpstrDefExt = WDL_UTF8ToWC(lpofn->lpstrDefExt,0,0,0); tmp.Flags = lpofn->Flags; tmp.lCustData = lpofn->lCustData; tmp.lpfnHook = lpofn->lpfnHook; tmp.lpTemplateName = (const WCHAR *)lpofn->lpTemplateName ; ret=save ? GetSaveFileNameW(&tmp) : GetOpenFileNameW(&tmp); // free, convert output if (ret && lpofn->lpstrFile && tmp.lpstrFile) { if ((tmp.Flags & OFN_ALLOWMULTISELECT) && tmp.lpstrFile[wcslen(tmp.lpstrFile)+1]) { char *op = lpofn->lpstrFile; WCHAR *ip = tmp.lpstrFile; while (*ip) { const int bcount = WideCharToMultiByte(CP_UTF8,0,ip,-1,NULL,0,NULL,NULL); const int maxout=lpofn->nMaxFile - 2 - (int)(op - lpofn->lpstrFile); if (maxout < 2+bcount) break; op += WideCharToMultiByte(CP_UTF8,0,ip,-1,op,maxout,NULL,NULL); ip += wcslen(ip)+1; } *op=0; } else { int len = WideCharToMultiByte(CP_UTF8,0,tmp.lpstrFile,-1,lpofn->lpstrFile,lpofn->nMaxFile-1,NULL,NULL); if (len == 0 && GetLastError()==ERROR_INSUFFICIENT_BUFFER) len = lpofn->nMaxFile-2; lpofn->lpstrFile[len]=0; if (!len) { lpofn->lpstrFile[len+1]=0; ret=0; } } // convert } lpofn->nFileOffset = tmp.nFileOffset ; lpofn->nFileExtension = tmp.nFileExtension; lpofn->lCustData = tmp.lCustData; free((WCHAR *)tmp.lpstrFilter); free((WCHAR *)tmp.lpstrFile); free((WCHAR *)tmp.lpstrFileTitle); free((WCHAR *)tmp.lpstrInitialDir); free((WCHAR *)tmp.lpstrTitle); free((WCHAR *)tmp.lpstrDefExt ); lpofn->nFilterIndex = tmp.nFilterIndex ; return ret; }
void keyPressed(int vk){ switch (vk){ case VK_ESCAPE: if (hbitmap != NULL){ if (selectRect.valid){ selectRect.valid = false; } else{ DeleteObject(hbitmap); hbitmap = NULL; selectRect.valid = false; delete[] capturePixels; DeleteObject(buffer); ShowWindow(hwnd, SW_HIDE); } } break; case VK_RETURN: sendToClipboard(); disposeWindow(); break; case 'C': if (ctrlPressed) sendToClipboard(); break; case 'X': if (ctrlPressed){ sendToClipboard(); disposeWindow(); } break; case 'S': if (ctrlPressed){ OPENFILENAMEW openFile = { 0 }; wchar_t filePath[261]; memset(&filePath, 0, 261); openFile.lStructSize = sizeof(OPENFILENAMEA); openFile.hwndOwner = hwnd; openFile.lpstrFile = filePath; openFile.nMaxFile = 261; openFile.Flags = OFN_EXPLORER; unsigned int num = 0, size = 0; GetImageEncodersSize(&num, &size); ImageCodecInfo *pImageCodecInfo = (ImageCodecInfo *)(malloc(size)); GetImageEncoders(num, size, pImageCodecInfo); wstring s; DWORD index = 0; for (unsigned int i = 0; i < num; ++i){ const wchar_t *format = pImageCodecInfo[i].FormatDescription; const wchar_t *filename = pImageCodecInfo[i].FilenameExtension; wstring fileLower(filename); transform(fileLower.begin(), fileLower.end(), fileLower.begin(), tolower); s = s + wstring(format, wcslen(format)) + wstring(L" (") + fileLower + wstring(L")", 2) + wstring(filename, wcslen(filename) + 1); if (wcscmp(format, L"PNG") == 0) { index = i + 1; } } s = s + wstring(L"\0", 1); openFile.lpstrFilter = s.c_str(); openFile.lpstrCustomFilter = NULL; openFile.lpstrFileTitle = NULL; openFile.lpstrInitialDir = NULL; openFile.lpstrTitle = L"Save Capture As"; openFile.nFilterIndex = index; if (!GetSaveFileNameW(&openFile)){ return; } BITMAPINFOHEADER bmih; bmih.biSize = sizeof(BITMAPINFOHEADER); bmih.biWidth = selectRect.width; bmih.biHeight = -selectRect.height; bmih.biPlanes = 1; bmih.biBitCount = 32; bmih.biCompression = BI_RGB; BITMAPINFO dbmi; dbmi.bmiHeader = bmih; HDC hdc = GetDC(NULL); HDC hdcMem = CreateCompatibleDC(hdc); HBITMAP capture = CreateCompatibleBitmap(hdc, selectRect.width, selectRect.height); bufferWidth = rect.right - rect.left; bufferHeight = rect.bottom - rect.top; pixel *ps = new pixel[selectRect.width * selectRect.height]; HGDIOBJ old = SelectObject(hdcMem, hbitmap); for (int i = 0; i < selectRect.height; i++){ memcpy(&ps[i * selectRect.width], &capturePixels[(i + selectRect.y) * bufferWidth + selectRect.x], selectRect.width * 4); } SetDIBits(hdc, capture, 0, selectRect.height, ps, &dbmi, 0); ImageCodecInfo info = pImageCodecInfo[openFile.nFilterIndex - 1]; wchar_t *fne = new wchar_t[wcslen(info.FilenameExtension) + 1]; wcscpy_s(fne, wcslen(info.FilenameExtension) + 1, info.FilenameExtension); wchar_t *context = NULL; wchar_t *c = wcstok_s(fne, L";", &context); wchar_t *first = c; bool found = false; while (c != NULL){ wstring str(filePath); transform(str.begin(), str.end(), str.begin(), toupper); wstring suffix(c); suffix = suffix.substr(1); if (str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0){ found = true; } c = wcstok_s(NULL, L";", &context); } wstring path(filePath); if (!found){ wstring extension = wstring(first).substr(1); transform(extension.begin(), extension.end(), extension.begin(), tolower); path = path + extension; } Bitmap bitmap(capture, NULL); bitmap.Save(path.c_str(), &(info.Clsid)); delete[] fne; SelectObject(hdc, old); ReleaseDC(NULL, hdc); DeleteDC(hdcMem); DeleteObject(capture); delete[] ps; delete[] pImageCodecInfo; } break; } }