Debian Codegraph @

android/app/jni/extern/nfd-modified/src/nfd_win.cpp

raw
1 /*
2 Native File Dialog
3
4 http://www.frogtoss.com/labs
5 */
6
7
8 #ifdef __MINGW32__
9 // Explicitly setting NTDDI version, this is necessary for the MinGW compiler
10 #ifdef NTDDI_VERSION
11 #undef NTDDI_VERSION
12 #endif
13 #ifdef _WIN32_WINNT
14 #undef _WIN32_WINNT
15 #endif
16 #define NTDDI_VERSION NTDDI_VISTA
17 #define _WIN32_WINNT _WIN32_WINNT_VISTA
18 #endif
19
20 #define _CRTDBG_MAP_ALLOC
21 #include <stdlib.h>
22 #include <crtdbg.h>
23
24 /* only locally define UNICODE in this compilation unit */
25 #ifndef UNICODE
26 #define UNICODE
27 #endif
28
29 #include <wchar.h>
30 #include <stdio.h>
31 #include <assert.h>
32 #include <windows.h>
33 #include <shobjidl.h>
34 #include "nfd_common.h"
35
36 // hack I know
37 #include "../../../src/utfutils.h"
38
39 // hack 2...
40 #include "../../../src/ta-log.h"
41
42 class NFDWinEvents: public IFileDialogEvents {
43 nfdselcallback_t selCallback;
44 size_t refCount;
45
46 virtual ~NFDWinEvents() {
47 }
48 public:
49 IFACEMETHODIMP QueryInterface(REFIID riid, void** ppv) {
50 logV("%p: QueryInterface called DAMN IT",(const void*)this);
51 *ppv=NULL;
52 return E_NOTIMPL;
53 }
54
55 IFACEMETHODIMP_(ULONG) AddRef() {
56 logV("%p: AddRef() called",(const void*)this);
57 return InterlockedIncrement(&refCount);
58 }
59
60 IFACEMETHODIMP_(ULONG) Release() {
61 logV("%p: Release() called",(const void*)this);
62 LONG ret=InterlockedDecrement(&refCount);
63 if (ret==0) {
64 logV("%p: Destroying the final object.",(const void*)this);
65 delete this;
66 }
67 return ret;
68 }
69
70 IFACEMETHODIMP OnFileOk(IFileDialog*) { return S_OK; }
71 IFACEMETHODIMP OnFolderChange(IFileDialog*) { return E_NOTIMPL; }
72 IFACEMETHODIMP OnFolderChanging(IFileDialog*, IShellItem*) { return E_NOTIMPL; }
73 IFACEMETHODIMP OnOverwrite(IFileDialog*, IShellItem*, FDE_OVERWRITE_RESPONSE*) { return E_NOTIMPL; }
74 IFACEMETHODIMP OnShareViolation(IFileDialog*, IShellItem*, FDE_SHAREVIOLATION_RESPONSE*) { return E_NOTIMPL; }
75 IFACEMETHODIMP OnTypeChange(IFileDialog*) { return E_NOTIMPL; }
76
77 IFACEMETHODIMP OnSelectionChange(IFileDialog* dialog) {
78 // Get the file name
79 logV("%p: OnSelectionChange() called",(const void*)this);
80 ::IShellItem *shellItem(NULL);
81 logV("%p: GetCurrentSelection",(const void*)this);
82 HRESULT result = dialog->GetCurrentSelection(&shellItem);
83 if ( !SUCCEEDED(result) )
84 {
85 logV("%p: failure!",(const void*)this);
86 return S_OK;
87 }
88 wchar_t *filePath(NULL);
89 result = shellItem->GetDisplayName(::SIGDN_FILESYSPATH, &filePath);
90 if ( !SUCCEEDED(result) )
91 {
92 logV("%p: GDN failure!",(const void*)this);
93 shellItem->Release();
94 return S_OK;
95 }
96 std::string utf8FilePath=utf16To8(filePath);
97 if (selCallback!=NULL) {
98 logV("%p: calling back.",(const void*)this);
99 selCallback(utf8FilePath.c_str());
100 logV("%p: end of callback",(const void*)this);
101 } else {
102 logV("%p: no callback.",(const void*)this);
103 }
104 logV("%p: I got you for a value of %s",(const void*)this,utf8FilePath.c_str());
105 shellItem->Release();
106 logV("%p: shellItem->Release()",(const void*)this);
107 return S_OK;
108 }
109 NFDWinEvents(nfdselcallback_t callback):
110 selCallback(callback),
111 refCount(1) {
112 logV("%p: CONSTRUCT!",(const void*)this);
113 }
114 };
115
116 #define COM_INITFLAGS ::COINIT_APARTMENTTHREADED | ::COINIT_DISABLE_OLE1DDE
117
118 static BOOL COMIsInitialized(HRESULT coResult)
119 {
120 if (coResult == RPC_E_CHANGED_MODE)
121 {
122 // If COM was previously initialized with different init flags,
123 // NFD still needs to operate. Eat this warning.
124 return TRUE;
125 }
126
127 return SUCCEEDED(coResult);
128 }
129
130 static HRESULT COMInit(void)
131 {
132 return ::CoInitializeEx(NULL, COM_INITFLAGS);
133 }
134
135 static void COMUninit(HRESULT coResult)
136 {
137 // do not uninitialize if RPC_E_CHANGED_MODE occurred -- this
138 // case does not refcount COM.
139 if (SUCCEEDED(coResult))
140 ::CoUninitialize();
141 }
142
143 // allocs the space in outPath -- call free()
144 static void CopyWCharToNFDChar( const wchar_t *inStr, nfdchar_t **outStr )
145 {
146 int inStrCharacterCount = static_cast<int>(wcslen(inStr));
147 int bytesNeeded = WideCharToMultiByte( CP_UTF8, 0,
148 inStr, inStrCharacterCount,
149 NULL, 0, NULL, NULL );
150 assert( bytesNeeded );
151 bytesNeeded += 1;
152
153 *outStr = (nfdchar_t*)NFDi_Malloc( bytesNeeded );
154 if ( !*outStr )
155 return;
156
157 int bytesWritten = WideCharToMultiByte( CP_UTF8, 0,
158 inStr, -1,
159 *outStr, bytesNeeded,
160 NULL, NULL );
161 assert( bytesWritten ); _NFD_UNUSED( bytesWritten );
162 }
163
164 /* includes NULL terminator byte in return */
165 static size_t GetUTF8ByteCountForWChar( const wchar_t *str )
166 {
167 size_t bytesNeeded = WideCharToMultiByte( CP_UTF8, 0,
168 str, -1,
169 NULL, 0, NULL, NULL );
170 assert( bytesNeeded );
171 return bytesNeeded+1;
172 }
173
174 // write to outPtr -- no free() necessary.
175 static int CopyWCharToExistingNFDCharBuffer( const wchar_t *inStr, nfdchar_t *outPtr )
176 {
177 int bytesNeeded = static_cast<int>(GetUTF8ByteCountForWChar( inStr ));
178
179 /* invocation copies null term */
180 int bytesWritten = WideCharToMultiByte( CP_UTF8, 0,
181 inStr, -1,
182 outPtr, bytesNeeded,
183 NULL, 0 );
184 assert( bytesWritten );
185
186 return bytesWritten;
187
188 }
189
190
191 // allocs the space in outStr -- call free()
192 static void CopyNFDCharToWChar( const nfdchar_t *inStr, wchar_t **outStr )
193 {
194 int inStrByteCount = static_cast<int>(strlen(inStr));
195 int charsNeeded = MultiByteToWideChar(CP_UTF8, 0,
196 inStr, inStrByteCount,
197 NULL, 0 );
198 assert( charsNeeded );
199 assert( !*outStr );
200 charsNeeded += 1; // terminator
201
202 *outStr = (wchar_t*)NFDi_Malloc( charsNeeded * sizeof(wchar_t) );
203 if ( !*outStr )
204 return;
205
206 int ret = MultiByteToWideChar(CP_UTF8, 0,
207 inStr, inStrByteCount,
208 *outStr, charsNeeded);
209 (*outStr)[charsNeeded-1] = '\0';
210
211 #ifdef _DEBUG
212 int inStrCharacterCount = static_cast<int>(NFDi_UTF8_Strlen(inStr));
213 if (ret!=inStrCharacterCount) {
214 logW("length does not match! %d != %d",ret,inStrCharacterCount);
215 }
216 #else
217 _NFD_UNUSED(ret);
218 #endif
219 }
220
221 static nfdresult_t AddFiltersToDialog( ::IFileDialog *fileOpenDialog, const std::vector<std::string>& filterList )
222 {
223 const wchar_t WILDCARD[] = L"*.*";
224
225 if (filterList.empty())
226 return NFD_OKAY;
227
228 // list size has to be an even number (name/filter)
229 if (filterList.size()&1)
230 return NFD_ERROR;
231
232 // Count rows to alloc
233 UINT filterCount = filterList.size()>>1; /* guaranteed to have one filter on a correct, non-empty parse */
234
235 if (filterCount==0) filterCount=1;
236
237 if ( !filterCount )
238 {
239 NFDi_SetError("Error parsing filters.");
240 return NFD_ERROR;
241 }
242
243 /* filterCount plus 1 because we hardcode the *.* wildcard after the while loop */
244 COMDLG_FILTERSPEC *specList = (COMDLG_FILTERSPEC*)NFDi_Malloc( sizeof(COMDLG_FILTERSPEC) * ((size_t)filterCount) );
245 if ( !specList )
246 {
247 return NFD_ERROR;
248 }
249 for (UINT i = 0; i < filterCount; ++i )
250 {
251 specList[i].pszName = NULL;
252 specList[i].pszSpec = NULL;
253 }
254
255 size_t specIdx = 0;
256
257 for (size_t i=0; i<filterList.size(); i+=2) {
258 String name=filterList[i];
259 String spec=filterList[i+1];
260 for (char& i: spec) {
261 if (i==' ') i=';';
262 }
263 if (spec==".*") spec="*.*";
264
265 CopyNFDCharToWChar( name.c_str(), (wchar_t**)&specList[specIdx].pszName );
266 CopyNFDCharToWChar( spec.c_str(), (wchar_t**)&specList[specIdx].pszSpec );
267 ++specIdx;
268 }
269
270 /* Add wildcard if specIdx is 0 */
271 if (specIdx==0) {
272 specList[specIdx].pszSpec = WILDCARD;
273 specList[specIdx].pszName = WILDCARD;
274 }
275
276 fileOpenDialog->SetFileTypes( filterCount, specList );
277
278 /* free speclist */
279 for ( size_t i = 0; i < filterCount; ++i )
280 {
281 NFDi_Free( (void*)specList[i].pszSpec );
282 }
283 NFDi_Free( specList );
284
285 return NFD_OKAY;
286 }
287
288 static nfdresult_t AllocPathSet( IShellItemArray *shellItems, nfdpathset_t *pathSet )
289 {
290 const char ERRORMSG[] = "Error allocating pathset.";
291
292 assert(shellItems);
293 assert(pathSet);
294
295 // How many items in shellItems?
296 DWORD numShellItems;
297 HRESULT result = shellItems->GetCount(&numShellItems);
298 if ( !SUCCEEDED(result) )
299 {
300 NFDi_SetError(ERRORMSG);
301 return NFD_ERROR;
302 }
303
304 pathSet->count = static_cast<size_t>(numShellItems);
305 assert( pathSet->count > 0 );
306
307 pathSet->indices = (size_t*)NFDi_Malloc( sizeof(size_t)*pathSet->count );
308 if ( !pathSet->indices )
309 {
310 return NFD_ERROR;
311 }
312
313 /* count the total bytes needed for buf */
314 size_t bufSize = 0;
315 for ( DWORD i = 0; i < numShellItems; ++i )
316 {
317 ::IShellItem *shellItem;
318 result = shellItems->GetItemAt(i, &shellItem);
319 if ( !SUCCEEDED(result) )
320 {
321 NFDi_SetError(ERRORMSG);
322 return NFD_ERROR;
323 }
324
325 // Confirm SFGAO_FILESYSTEM is true for this shellitem, or ignore it.
326 SFGAOF attribs;
327 result = shellItem->GetAttributes( SFGAO_FILESYSTEM, &attribs );
328 if ( !SUCCEEDED(result) )
329 {
330 NFDi_SetError(ERRORMSG);
331 return NFD_ERROR;
332 }
333 if ( !(attribs & SFGAO_FILESYSTEM) )
334 continue;
335
336 LPWSTR name;
337 shellItem->GetDisplayName(SIGDN_FILESYSPATH, &name);
338
339 // Calculate length of name with UTF-8 encoding
340 bufSize += GetUTF8ByteCountForWChar( name );
341
342 CoTaskMemFree(name);
343 }
344
345 assert(bufSize);
346
347 pathSet->buf = (nfdchar_t*)NFDi_Malloc( sizeof(nfdchar_t) * bufSize );
348 memset( pathSet->buf, 0, sizeof(nfdchar_t) * bufSize );
349
350 /* fill buf */
351 nfdchar_t *p_buf = pathSet->buf;
352 for (DWORD i = 0; i < numShellItems; ++i )
353 {
354 ::IShellItem *shellItem;
355 result = shellItems->GetItemAt(i, &shellItem);
356 if ( !SUCCEEDED(result) )
357 {
358 NFDi_SetError(ERRORMSG);
359 return NFD_ERROR;
360 }
361
362 // Confirm SFGAO_FILESYSTEM is true for this shellitem, or ignore it.
363 SFGAOF attribs;
364 result = shellItem->GetAttributes( SFGAO_FILESYSTEM, &attribs );
365 if ( !SUCCEEDED(result) )
366 {
367 NFDi_SetError(ERRORMSG);
368 return NFD_ERROR;
369 }
370 if ( !(attribs & SFGAO_FILESYSTEM) )
371 continue;
372
373 LPWSTR name;
374 shellItem->GetDisplayName(SIGDN_FILESYSPATH, &name);
375
376 int bytesWritten = CopyWCharToExistingNFDCharBuffer(name, p_buf);
377 CoTaskMemFree(name);
378
379 ptrdiff_t index = p_buf - pathSet->buf;
380 assert( index >= 0 );
381 pathSet->indices[i] = static_cast<size_t>(index);
382
383 p_buf += bytesWritten;
384 }
385
386 return NFD_OKAY;
387 }
388
389
390 static nfdresult_t SetDefaultPath( IFileDialog *dialog, const char *defaultPath )
391 {
392 if ( !defaultPath || strlen(defaultPath) == 0 || strcmp(defaultPath,"\\")==0 )
393 return NFD_OKAY;
394
395 wchar_t *defaultPathW = {0};
396 CopyNFDCharToWChar( defaultPath, &defaultPathW );
397
398 IShellItem *folder;
399 HRESULT result = SHCreateItemFromParsingName( defaultPathW, NULL, IID_PPV_ARGS(&folder) );
400
401 // Valid non results.
402 if ( result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) || result == HRESULT_FROM_WIN32(ERROR_INVALID_DRIVE) )
403 {
404 NFDi_Free( defaultPathW );
405 return NFD_OKAY;
406 }
407
408 if ( !SUCCEEDED(result) )
409 {
410 NFDi_SetError("Error creating ShellItem");
411 NFDi_Free( defaultPathW );
412 return NFD_ERROR;
413 }
414
415 // Could also call SetDefaultFolder(), but this guarantees defaultPath -- more consistency across API.
416 dialog->SetFolder( folder );
417
418 NFDi_Free( defaultPathW );
419 folder->Release();
420
421 return NFD_OKAY;
422 }
423
424 /* public */
425
426
427 nfdresult_t NFD_OpenDialog( const std::vector<std::string>& filterList,
428 const nfdchar_t *defaultPath,
429 nfdchar_t **outPath,
430 nfdselcallback_t selCallback,
431 const nfdchar_t *defaultFileName )
432 {
433 nfdresult_t nfdResult = NFD_ERROR;
434 NFDWinEvents* winEvents;
435 bool hasEvents=true;
436 DWORD eventID=0;
437
438 HRESULT coResult = COMInit();
439 if (!COMIsInitialized(coResult))
440 {
441 NFDi_SetError("Could not initialize COM.");
442 return nfdResult;
443 }
444
445 // Create dialog
446 ::IFileOpenDialog *fileOpenDialog(NULL);
447 HRESULT result = ::CoCreateInstance(::CLSID_FileOpenDialog, NULL,
448 CLSCTX_ALL, ::IID_IFileOpenDialog,
449 reinterpret_cast<void**>(&fileOpenDialog) );
450
451 if ( !SUCCEEDED(result) )
452 {
453 NFDi_SetError("Could not create dialog.");
454 goto end;
455 }
456
457 // Build the filter list
458 if ( !AddFiltersToDialog( fileOpenDialog, filterList ) )
459 {
460 goto end;
461 }
462
463 // Set the default path
464 if ( !SetDefaultPath( fileOpenDialog, defaultPath ) )
465 {
466 goto end;
467 }
468
469 // Set the file name
470 if (defaultFileName!=NULL) {
471 std::wstring defFileName=utf8To16(defaultFileName);
472 result = fileOpenDialog->SetFileName(defFileName.c_str());
473 if ( !SUCCEEDED(result) ) {
474 // ignore
475 }
476 }
477
478 // Pass the callback
479 winEvents=new NFDWinEvents(selCallback);
480 if ( !SUCCEEDED(fileOpenDialog->Advise(winEvents,&eventID)) ) {
481 // error... ignore
482 hasEvents=false;
483 winEvents->Release();
484 } else {
485 winEvents->Release();
486 }
487
488 // Show the dialog.
489 // TODO: pass the Furnace window here
490 result = fileOpenDialog->Show(NULL);
491 if ( SUCCEEDED(result) )
492 {
493 // Get the file name
494 ::IShellItem *shellItem(NULL);
495 result = fileOpenDialog->GetResult(&shellItem);
496 if ( !SUCCEEDED(result) )
497 {
498 NFDi_SetError("Could not get shell item from dialog.");
499 goto end;
500 }
501 wchar_t *filePath(NULL);
502 result = shellItem->GetDisplayName(::SIGDN_FILESYSPATH, &filePath);
503 if ( !SUCCEEDED(result) )
504 {
505 NFDi_SetError("Could not get file path for selected.");
506 shellItem->Release();
507 goto end;
508 }
509
510 CopyWCharToNFDChar( filePath, outPath );
511 CoTaskMemFree(filePath);
512 if ( !*outPath )
513 {
514 /* error is malloc-based, error message would be redundant */
515 shellItem->Release();
516 goto end;
517 }
518
519 nfdResult = NFD_OKAY;
520 shellItem->Release();
521 }
522 else if (result == HRESULT_FROM_WIN32(ERROR_CANCELLED) )
523 {
524 nfdResult = NFD_CANCEL;
525 }
526 else
527 {
528 NFDi_SetError("File dialog box show failed.");
529 nfdResult = NFD_ERROR;
530 }
531
532 end:
533 if (fileOpenDialog) {
534 if (hasEvents) {
535 fileOpenDialog->Unadvise(eventID);
536 }
537 fileOpenDialog->Release();
538 }
539
540 COMUninit(coResult);
541
542 return nfdResult;
543 }
544
545 nfdresult_t NFD_OpenDialogMultiple( const std::vector<std::string>& filterList,
546 const nfdchar_t *defaultPath,
547 nfdpathset_t *outPaths,
548 nfdselcallback_t selCallback,
549 const nfdchar_t *defaultFileName )
550 {
551 nfdresult_t nfdResult = NFD_ERROR;
552 NFDWinEvents* winEvents;
553 bool hasEvents=true;
554 DWORD eventID=0;
555
556
557 HRESULT coResult = COMInit();
558 if (!COMIsInitialized(coResult))
559 {
560 NFDi_SetError("Could not initialize COM.");
561 return nfdResult;
562 }
563
564 // Create dialog
565 ::IFileOpenDialog *fileOpenDialog(NULL);
566 HRESULT result = ::CoCreateInstance(::CLSID_FileOpenDialog, NULL,
567 CLSCTX_ALL, ::IID_IFileOpenDialog,
568 reinterpret_cast<void**>(&fileOpenDialog) );
569
570 if ( !SUCCEEDED(result) )
571 {
572 fileOpenDialog = NULL;
573 NFDi_SetError("Could not create dialog.");
574 goto end;
575 }
576
577 // Build the filter list
578 if ( !AddFiltersToDialog( fileOpenDialog, filterList ) )
579 {
580 goto end;
581 }
582
583 // Set the default path
584 if ( !SetDefaultPath( fileOpenDialog, defaultPath ) )
585 {
586 goto end;
587 }
588
589 // Set the file name
590 if (defaultFileName!=NULL) {
591 std::wstring defFileName=utf8To16(defaultFileName);
592 result = fileOpenDialog->SetFileName(defFileName.c_str());
593 if ( !SUCCEEDED(result) ) {
594 // ignore
595 }
596 }
597
598 // Pass the callback
599 winEvents=new NFDWinEvents(selCallback);
600 if ( !SUCCEEDED(fileOpenDialog->Advise(winEvents,&eventID)) ) {
601 // error... ignore
602 hasEvents=false;
603 winEvents->Release();
604 } else {
605 winEvents->Release();
606 }
607
608 // Set a flag for multiple options
609 DWORD dwFlags;
610 result = fileOpenDialog->GetOptions(&dwFlags);
611 if ( !SUCCEEDED(result) )
612 {
613 NFDi_SetError("Could not get options.");
614 goto end;
615 }
616 result = fileOpenDialog->SetOptions(dwFlags | FOS_ALLOWMULTISELECT);
617 if ( !SUCCEEDED(result) )
618 {
619 NFDi_SetError("Could not set options.");
620 goto end;
621 }
622
623 // Show the dialog.
624 result = fileOpenDialog->Show(NULL);
625 if ( SUCCEEDED(result) )
626 {
627 IShellItemArray *shellItems;
628 result = fileOpenDialog->GetResults( &shellItems );
629 if ( !SUCCEEDED(result) )
630 {
631 NFDi_SetError("Could not get shell items.");
632 goto end;
633 }
634
635 if ( AllocPathSet( shellItems, outPaths ) == NFD_ERROR )
636 {
637 shellItems->Release();
638 goto end;
639 }
640
641 shellItems->Release();
642 nfdResult = NFD_OKAY;
643 }
644 else if (result == HRESULT_FROM_WIN32(ERROR_CANCELLED) )
645 {
646 nfdResult = NFD_CANCEL;
647 }
648 else
649 {
650 NFDi_SetError("File dialog box show failed.");
651 nfdResult = NFD_ERROR;
652 }
653
654 end:
655 if (fileOpenDialog) {
656 if (hasEvents) {
657 fileOpenDialog->Unadvise(eventID);
658 }
659 fileOpenDialog->Release();
660 }
661
662 COMUninit(coResult);
663
664 return nfdResult;
665 }
666
667 nfdresult_t NFD_SaveDialog( const std::vector<std::string>& filterList,
668 const nfdchar_t *defaultPath,
669 nfdchar_t **outPath,
670 nfdselcallback_t selCallback,
671 const nfdchar_t *defaultFileName )
672 {
673 nfdresult_t nfdResult = NFD_ERROR;
674
675 HRESULT coResult = COMInit();
676 if (!COMIsInitialized(coResult))
677 {
678 NFDi_SetError("Could not initialize COM.");
679 return nfdResult;
680 }
681
682 // Create dialog
683 ::IFileSaveDialog *fileSaveDialog(NULL);
684 HRESULT result = ::CoCreateInstance(::CLSID_FileSaveDialog, NULL,
685 CLSCTX_ALL, ::IID_IFileSaveDialog,
686 reinterpret_cast<void**>(&fileSaveDialog) );
687
688 if ( !SUCCEEDED(result) )
689 {
690 fileSaveDialog = NULL;
691 NFDi_SetError("Could not create dialog.");
692 goto end;
693 }
694
695 // Build the filter list
696 if ( !AddFiltersToDialog( fileSaveDialog, filterList ) )
697 {
698 goto end;
699 }
700
701 // Set the default path
702 if ( !SetDefaultPath( fileSaveDialog, defaultPath ) )
703 {
704 goto end;
705 }
706
707 // Set the file name
708 if (defaultFileName!=NULL) {
709 std::wstring defFileName=utf8To16(defaultFileName);
710 result = fileSaveDialog->SetFileName(defFileName.c_str());
711 if ( !SUCCEEDED(result) ) {
712 // ignore
713 }
714 }
715
716 // Set a flag for no history
717 DWORD dwFlags;
718 result = fileSaveDialog->GetOptions(&dwFlags);
719 if ( !SUCCEEDED(result) )
720 {
721 NFDi_SetError("Could not get options.");
722 goto end;
723 }
724 result = fileSaveDialog->SetOptions(dwFlags | FOS_DONTADDTORECENT);
725 if ( !SUCCEEDED(result) )
726 {
727 NFDi_SetError("Could not set options.");
728 goto end;
729 }
730
731 // Show the dialog.
732 result = fileSaveDialog->Show(NULL);
733 if ( SUCCEEDED(result) )
734 {
735 // Get the file name
736 ::IShellItem *shellItem;
737 result = fileSaveDialog->GetResult(&shellItem);
738 if ( !SUCCEEDED(result) )
739 {
740 NFDi_SetError("Could not get shell item from dialog.");
741 goto end;
742 }
743 wchar_t *filePath(NULL);
744 result = shellItem->GetDisplayName(::SIGDN_FILESYSPATH, &filePath);
745 if ( !SUCCEEDED(result) )
746 {
747 shellItem->Release();
748 NFDi_SetError("Could not get file path for selected.");
749 goto end;
750 }
751
752 CopyWCharToNFDChar( filePath, outPath );
753 CoTaskMemFree(filePath);
754 if ( !*outPath )
755 {
756 /* error is malloc-based, error message would be redundant */
757 shellItem->Release();
758 goto end;
759 }
760
761 nfdResult = NFD_OKAY;
762 shellItem->Release();
763 }
764 else if (result == HRESULT_FROM_WIN32(ERROR_CANCELLED) )
765 {
766 nfdResult = NFD_CANCEL;
767 }
768 else
769 {
770 NFDi_SetError("File dialog box show failed.");
771 nfdResult = NFD_ERROR;
772 }
773
774 end:
775 if ( fileSaveDialog )
776 fileSaveDialog->Release();
777
778 COMUninit(coResult);
779
780 return nfdResult;
781 }
782
783
784
785 nfdresult_t NFD_PickFolder(const nfdchar_t *defaultPath,
786 nfdchar_t **outPath)
787 {
788 nfdresult_t nfdResult = NFD_ERROR;
789 DWORD dwOptions = 0;
790
791 HRESULT coResult = COMInit();
792 if (!COMIsInitialized(coResult))
793 {
794 NFDi_SetError("CoInitializeEx failed.");
795 return nfdResult;
796 }
797
798 // Create dialog
799 ::IFileOpenDialog *fileDialog(NULL);
800 HRESULT result = CoCreateInstance(CLSID_FileOpenDialog,
801 NULL,
802 CLSCTX_ALL,
803 IID_PPV_ARGS(&fileDialog));
804 if ( !SUCCEEDED(result) )
805 {
806 NFDi_SetError("CoCreateInstance for CLSID_FileOpenDialog failed.");
807 goto end;
808 }
809
810 // Set the default path
811 if (SetDefaultPath(fileDialog, defaultPath) != NFD_OKAY)
812 {
813 NFDi_SetError("SetDefaultPath failed.");
814 goto end;
815 }
816
817 // Get the dialogs options
818 if (!SUCCEEDED(fileDialog->GetOptions(&dwOptions)))
819 {
820 NFDi_SetError("GetOptions for IFileDialog failed.");
821 goto end;
822 }
823
824 // Add in FOS_PICKFOLDERS which hides files and only allows selection of folders
825 if (!SUCCEEDED(fileDialog->SetOptions(dwOptions | FOS_PICKFOLDERS)))
826 {
827 NFDi_SetError("SetOptions for IFileDialog failed.");
828 goto end;
829 }
830
831 // Show the dialog to the user
832 result = fileDialog->Show(NULL);
833 if ( SUCCEEDED(result) )
834 {
835 // Get the folder name
836 ::IShellItem *shellItem(NULL);
837
838 result = fileDialog->GetResult(&shellItem);
839 if ( !SUCCEEDED(result) )
840 {
841 NFDi_SetError("Could not get file path for selected.");
842 shellItem->Release();
843 goto end;
844 }
845
846 wchar_t *path = NULL;
847 result = shellItem->GetDisplayName(SIGDN_DESKTOPABSOLUTEPARSING, &path);
848 if ( !SUCCEEDED(result) )
849 {
850 NFDi_SetError("GetDisplayName for IShellItem failed.");
851 shellItem->Release();
852 goto end;
853 }
854
855 CopyWCharToNFDChar(path, outPath);
856 CoTaskMemFree(path);
857 if ( !*outPath )
858 {
859 shellItem->Release();
860 goto end;
861 }
862
863 nfdResult = NFD_OKAY;
864 shellItem->Release();
865 }
866 else if (result == HRESULT_FROM_WIN32(ERROR_CANCELLED) )
867 {
868 nfdResult = NFD_CANCEL;
869 }
870 else
871 {
872 NFDi_SetError("Show for IFileDialog failed.");
873 nfdResult = NFD_ERROR;
874 }
875
876 end:
877
878 if (fileDialog)
879 fileDialog->Release();
880
881 COMUninit(coResult);
882
883 return nfdResult;
884 }