Code

remove many unnecessary to_2geom and from_2geom calls
[inkscape.git] / src / ui / dialog / filedialogimpl-win32.cpp
1 /**
2  * Implementation of the file dialog interfaces defined in filedialog.h for Win32
3  *
4  * Authors:
5  *   Joel Holdsworth
6  *   The Inkscape Organization
7  *
8  * Copyright (C) 2004-2008 The Inkscape Organization
9  *
10  * Released under GNU GPL, read the file 'COPYING' for more information
11  */
13 #ifdef HAVE_CONFIG_H
14 # include <config.h>
15 #endif
17 #ifdef WIN32
19 //General includes
20 #include <list>
21 #include <unistd.h>
22 #include <sys/stat.h>
23 #include <errno.h>
24 #include <set>
25 #include <gdk/gdkwin32.h>
26 #include <glib/gstdio.h>
27 #include <glibmm/i18n.h>
28 #include <gtkmm/window.h>
30 //Inkscape includes
31 #include "inkscape.h"
32 #include "prefs-utils.h"
33 #include <dialogs/dialog-events.h>
34 #include <extension/input.h>
35 #include <extension/output.h>
36 #include <extension/db.h>
38 #include <libnr/nr-pixops.h>
39 #include <libnr/nr-translate-scale-ops.h>
40 #include <display/nr-arena-item.h>
41 #include <display/nr-arena.h>
42 #include "sp-item.h"
43 #include "display/canvas-arena.h"
45 #include "filedialog.h"
46 #include "filedialogimpl-win32.h"
48 #include <zlib.h>
49 #include <cairomm/win32_surface.h>
50 #include <cairomm/context.h>
52 using namespace std;
53 using namespace Glib;
54 using namespace Cairo;
55 using namespace Gdk::Cairo;
57 namespace Inkscape
58 {
59 namespace UI
60 {
61 namespace Dialog
62 {
64 const int PreviewWidening = 150;
65 const char PreviewWindowClassName[] = "PreviewWnd";
66 const unsigned long MaxPreviewFileSize = 1344; // kB
68 #define IDC_SHOW_PREVIEW    1000
70 // Windows 2000 version of OPENFILENAMEW
71 struct OPENFILENAMEEXW : public OPENFILENAMEW {
72   void *        pvReserved;
73   DWORD         dwReserved;
74   DWORD         FlagsEx;
75 };
77 struct Filter
78 {
79     gunichar2* name;
80     glong name_length;
81     gunichar2* filter;
82     glong filter_length;
83     Inkscape::Extension::Extension* mod;
84 };
86 ustring utf16_to_ustring(const wchar_t *utf16string, int utf16length = -1)
87 {
88     gchar *utf8string = g_utf16_to_utf8((const gunichar2*)utf16string,
89         utf16length, NULL, NULL, NULL);
90     ustring result(utf8string);
91     g_free(utf8string);
93     return result;
94 }
96 /*#########################################################################
97 ### F I L E     D I A L O G    B A S E    C L A S S
98 #########################################################################*/
100 FileDialogBaseWin32::FileDialogBaseWin32(Gtk::Window &parent,
101         const Glib::ustring &dir, const gchar *title,
102         FileDialogType type, gchar const* /*preferenceBase*/) :
103         dialogType(type),
104         parent(parent),
105         _current_directory(dir)
107     _main_loop = NULL;
109         _filter_index = 1;
110         _filter_count = 0;
111         
112     _title = (wchar_t*)g_utf8_to_utf16(title, -1, NULL, NULL, NULL);
113         g_assert(_title != NULL);
115     Glib::RefPtr<const Gdk::Window> parentWindow = parent.get_window();
116     g_assert(parentWindow->gobj() != NULL);
117     _ownerHwnd = (HWND)gdk_win32_drawable_get_handle((GdkDrawable*)parentWindow->gobj());
120 FileDialogBaseWin32::~FileDialogBaseWin32()
122     g_free(_title);
125 Inkscape::Extension::Extension *FileDialogBaseWin32::getSelectionType()
127     return _extension;
130 Glib::ustring FileDialogBaseWin32::getCurrentDirectory()
132     return _current_directory;
135 /*#########################################################################
136 ### F I L E    O P E N
137 #########################################################################*/
139 bool FileOpenDialogImplWin32::_show_preview = true;
141 /**
142  * Constructor.  Not called directly.  Use the factory.
143  */
144 FileOpenDialogImplWin32::FileOpenDialogImplWin32(Gtk::Window &parent,
145                                        const Glib::ustring &dir,
146                                        FileDialogType fileTypes,
147                                        const gchar *title) :
148     FileDialogBaseWin32(parent, dir, title, fileTypes, "dialogs.open")
150     // Initalize to Autodetect
151     _extension = NULL;
153     // Set our dialog type (open, import, etc...)
154     dialogType = fileTypes;
156     _show_preview_button_bitmap = NULL;
157     _preview_wnd = NULL;
158     _file_dialog_wnd = NULL;
159     _base_window_proc = NULL;
161     _preview_file_size = 0;
162     _preview_bitmap = NULL;
163     _preview_file_icon = NULL;
164     _preview_document_width = 0;
165     _preview_document_height = 0;
166     _preview_image_width = 0;
167     _preview_image_height = 0;
168     _preview_emf_image = false;
169         
170         _mutex = NULL;
172     createFilterMenu();
176 /**
177  * Destructor
178  */
179 FileOpenDialogImplWin32::~FileOpenDialogImplWin32()
181     if(_filter != NULL)
182         delete[] _filter;
183     if(_extension_map != NULL)
184         delete[] _extension_map;
187 void FileOpenDialogImplWin32::createFilterMenu()
189     list<Filter> filter_list;
191     // Compose the filter string
192     Inkscape::Extension::DB::InputList extension_list;
193     Inkscape::Extension::db.get_input_list(extension_list);
195     ustring all_inkscape_files_filter, all_image_files_filter;
196     Filter all_files, all_inkscape_files, all_image_files;
198     const gchar *all_files_filter_name = N_("All Files");
199     const gchar *all_inkscape_files_filter_name = N_("All Inkscape Files");
200     const gchar *all_image_files_filter_name = N_("All Image Files");
202     // Calculate the amount of memory required
203     int filter_count = 3;       // 3 - one for All Files, All Images and All Inkscape Files
204     int filter_length = 1;
206     for (Inkscape::Extension::DB::InputList::iterator current_item = extension_list.begin();
207          current_item != extension_list.end(); current_item++)
208     {
209         Filter filter;
211         Inkscape::Extension::Input *imod = *current_item;
212         if (imod->deactivated()) continue;
214         // Type
215         filter.name = g_utf8_to_utf16(_(imod->get_filetypename()),
216             -1, NULL, &filter.name_length, NULL);
218         // Extension
219         const gchar *file_extension_name = imod->get_extension();
220         filter.filter = g_utf8_to_utf16(file_extension_name,
221             -1, NULL, &filter.filter_length, NULL);
223         filter.mod = imod;
224         filter_list.push_back(filter);
226         filter_length += filter.name_length +
227             filter.filter_length + 3;   // Add 3 for two \0s and a *
229         // Add to the "All Inkscape Files" Entry
230         if(all_inkscape_files_filter.length() > 0)
231             all_inkscape_files_filter += ";*";
232         all_inkscape_files_filter += file_extension_name;
233         if( strncmp("image", imod->get_mimetype(), 5) == 0)
234         {
235             // Add to the "All Image Files" Entry
236             if(all_image_files_filter.length() > 0)
237                 all_image_files_filter += ";*";
238             all_image_files_filter += file_extension_name;
239         }
241         filter_count++;
242     }
244     int extension_index = 0;
245     _extension_map = new Inkscape::Extension::Extension*[filter_count];
247     // Filter Image Files
248     all_image_files.name = g_utf8_to_utf16(all_image_files_filter_name,
249         -1, NULL, &all_image_files.name_length, NULL);
250     all_image_files.filter = g_utf8_to_utf16(all_image_files_filter.data(),
251             -1, NULL, &all_image_files.filter_length, NULL);
252         all_image_files.mod = NULL;
253     filter_list.push_front(all_image_files);
255     // Filter Inkscape Files
256     all_inkscape_files.name = g_utf8_to_utf16(all_inkscape_files_filter_name,
257         -1, NULL, &all_inkscape_files.name_length, NULL);
258     all_inkscape_files.filter = g_utf8_to_utf16(all_inkscape_files_filter.data(),
259             -1, NULL, &all_inkscape_files.filter_length, NULL);
260         all_inkscape_files.mod = NULL;
261     filter_list.push_front(all_inkscape_files);
263     // Filter All Files
264     all_files.name = g_utf8_to_utf16(all_files_filter_name,
265         -1, NULL, &all_files.name_length, NULL);
266     all_files.filter = NULL;
267     all_files.filter_length = 0;
268         all_files.mod = NULL;
269     filter_list.push_front(all_files);
271     filter_length += all_files.name_length + 3 +
272                     all_inkscape_files.filter_length +
273                     all_inkscape_files.name_length + 3 +
274                     all_image_files.filter_length +
275                     all_image_files.name_length + 3 + 1;
276      // Add 3 for 2*2 \0s and a *, and 1 for a trailing \0
277          
278         _filter = new wchar_t[filter_length];
279     wchar_t *filterptr = _filter;
280         
281     for(list<Filter>::iterator filter_iterator = filter_list.begin();
282         filter_iterator != filter_list.end(); filter_iterator++)
283     {
284         const Filter &filter = *filter_iterator;
286         wcsncpy(filterptr, (wchar_t*)filter.name, filter.name_length);
287         filterptr += filter.name_length;
288         g_free(filter.name);
290         *(filterptr++) = L'\0';
291         *(filterptr++) = L'*';
293         if(filter.filter != NULL)
294         {
295             wcsncpy(filterptr, (wchar_t*)filter.filter, filter.filter_length);
296             filterptr += filter.filter_length;
297             g_free(filter.filter);
298         }
300         *(filterptr++) = L'\0';
302         // Associate this input extension with the file type name
303         _extension_map[extension_index++] = filter.mod;
304     }
305     *(filterptr++) = L'\0';
306         
307         _filter_count = extension_index;
308     _filter_index = 2;  // Select the 2nd filter in the list - 2 is NOT the 3rd
311 void FileOpenDialogImplWin32::GetOpenFileName_thread()
313     OPENFILENAMEEXW ofn;
315     g_assert(this != NULL);
316         g_assert(_mutex != NULL);
317     
318     WCHAR* current_directory_string = (WCHAR*)g_utf8_to_utf16(
319         _current_directory.data(), _current_directory.length(),
320                 NULL, NULL, NULL);
322     memset(&ofn, 0, sizeof(ofn));
324     // Copy the selected file name, converting from UTF-8 to UTF-16
325     memset(_path_string, 0, sizeof(_path_string));
326     gunichar2* utf16_path_string = g_utf8_to_utf16(
327         myFilename.data(), -1, NULL, NULL, NULL);
328     wcsncpy(_path_string, (wchar_t*)utf16_path_string, _MAX_PATH);
329     g_free(utf16_path_string);
331     ofn.lStructSize = sizeof(ofn);
332     ofn.hwndOwner = _ownerHwnd;
333     ofn.lpstrFile = _path_string;
334     ofn.nMaxFile = _MAX_PATH;
335     ofn.lpstrFileTitle = NULL;
336     ofn.nMaxFileTitle = 0;
337     ofn.lpstrInitialDir = current_directory_string;
338     ofn.lpstrTitle = _title;
339     ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ENABLEHOOK | OFN_HIDEREADONLY | OFN_ENABLESIZING;
340     ofn.lpstrFilter = _filter;
341     ofn.nFilterIndex = _filter_index;
342     ofn.lpfnHook = GetOpenFileName_hookproc;
343     ofn.lCustData = (LPARAM)this;
345     _result = GetOpenFileNameW(&ofn) != 0;
347         g_assert(ofn.nFilterIndex >= 1 && ofn.nFilterIndex <= _filter_count);
348     _filter_index = ofn.nFilterIndex;
349     _extension = _extension_map[ofn.nFilterIndex - 1];
351     // Copy the selected file name, converting from UTF-16 to UTF-8
352     myFilename = utf16_to_ustring(_path_string, _MAX_PATH);
354     // Tidy up
355     g_free(current_directory_string);
357     _mutex->lock();
358     _finished = true;
359     _mutex->unlock();
362 void FileOpenDialogImplWin32::register_preview_wnd_class()
364     HINSTANCE hInstance = GetModuleHandle(NULL);
365     const WNDCLASSA PreviewWndClass =
366     {
367         CS_HREDRAW | CS_VREDRAW,
368         preview_wnd_proc,
369         0,
370         0,
371         hInstance,
372         NULL,
373         LoadCursor(hInstance, IDC_ARROW),
374         (HBRUSH)(COLOR_BTNFACE + 1),
375         NULL,
376         PreviewWindowClassName
377     };
379     RegisterClassA(&PreviewWndClass);
382 UINT_PTR CALLBACK FileOpenDialogImplWin32::GetOpenFileName_hookproc(
383     HWND hdlg, UINT uiMsg, WPARAM, LPARAM lParam)
385     FileOpenDialogImplWin32 *pImpl = (FileOpenDialogImplWin32*)
386         GetWindowLongPtr(hdlg, GWLP_USERDATA);
388     switch(uiMsg)
389     {
390     case WM_INITDIALOG:
391         {
392             HWND hParentWnd = GetParent(hdlg);
393             HINSTANCE hInstance = GetModuleHandle(NULL);
395             // Make the window a bit wider
396             RECT rcRect;
397             GetWindowRect(hParentWnd, &rcRect);
398             MoveWindow(hParentWnd, rcRect.left, rcRect.top,
399                 rcRect.right - rcRect.left + PreviewWidening,
400                 rcRect.bottom - rcRect.top,
401                 FALSE);
403             // Set the pointer to the object
404             OPENFILENAMEW *ofn = (OPENFILENAMEW*)lParam;
405             SetWindowLongPtr(hdlg, GWLP_USERDATA, ofn->lCustData);
406             SetWindowLongPtr(hParentWnd, GWLP_USERDATA, ofn->lCustData);
407             pImpl = (FileOpenDialogImplWin32*)ofn->lCustData;
409             // Subclass the parent
410             pImpl->_base_window_proc = (WNDPROC)GetWindowLongPtr(hParentWnd, GWL_WNDPROC);
411             SetWindowLongPtr(hParentWnd, GWL_WNDPROC, (LONG_PTR)file_dialog_subclass_proc);
413             // Add a button to the toolbar
414             pImpl->_toolbar_wnd = FindWindowEx(hParentWnd, NULL, "ToolbarWindow32", NULL);
416             pImpl->_show_preview_button_bitmap = LoadBitmap(
417                 hInstance, MAKEINTRESOURCE(IDC_SHOW_PREVIEW));
418             TBADDBITMAP tbAddBitmap = {NULL, (UINT)pImpl->_show_preview_button_bitmap};
419             const int iBitmapIndex = SendMessage(pImpl->_toolbar_wnd,
420                 TB_ADDBITMAP, 1, (LPARAM)&tbAddBitmap);
422             TBBUTTON tbButton;
423             memset(&tbButton, 0, sizeof(TBBUTTON));
424             tbButton.iBitmap = iBitmapIndex;
425             tbButton.idCommand = IDC_SHOW_PREVIEW;
426             tbButton.fsState = (pImpl->_show_preview ? TBSTATE_CHECKED : 0)
427                 | TBSTATE_ENABLED;
428             tbButton.fsStyle = TBSTYLE_CHECK;
429             tbButton.iString = (INT_PTR)_("Show Preview");
430             SendMessage(pImpl->_toolbar_wnd, TB_ADDBUTTONS, 1, (LPARAM)&tbButton);
432             // Create preview pane
433             register_preview_wnd_class();
435             pImpl->_mutex->lock();
437                 pImpl->_file_dialog_wnd = hParentWnd;
439                 pImpl->_preview_wnd =
440                     CreateWindowA(PreviewWindowClassName, "",
441                         WS_CHILD | WS_VISIBLE,
442                         0, 0, 100, 100, hParentWnd, NULL, hInstance, NULL);
443                 SetWindowLongPtr(pImpl->_preview_wnd, GWLP_USERDATA, ofn->lCustData);
445             pImpl->_mutex->unlock();
447             pImpl->layout_dialog();
448         }
449         break;
451     case WM_NOTIFY:
452         {
454         OFNOTIFY *pOFNotify = reinterpret_cast<OFNOTIFY*>(lParam);
455         switch(pOFNotify->hdr.code)
456         {
457         case CDN_SELCHANGE:
458             {
459                 if(pImpl != NULL)
460                 {
461                     // Get the file name
462                     pImpl->_mutex->lock();
464                     SendMessage(pOFNotify->hdr.hwndFrom, CDM_GETFILEPATH,
465                         sizeof(pImpl->_path_string) / sizeof(wchar_t),
466                         (LPARAM)pImpl->_path_string);
468                     pImpl->_file_selected = true;
470                     pImpl->_mutex->unlock();
471                 }
472             }
473             break;
474         }
475         }
476         break;
478     case WM_CLOSE:
479         pImpl->_mutex->lock();
480         pImpl->_preview_file_size = 0;
482         pImpl->_file_dialog_wnd = NULL;
483         DestroyWindow(pImpl->_preview_wnd);
484         pImpl->_preview_wnd = NULL;
485         DeleteObject(pImpl->_show_preview_button_bitmap);
486         pImpl->_show_preview_button_bitmap = NULL;
487         pImpl->_mutex->unlock();
489         break;
490     }
492     // Use default dialog behaviour
493     return 0;
496 LRESULT CALLBACK FileOpenDialogImplWin32::file_dialog_subclass_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
498     FileOpenDialogImplWin32 *pImpl = (FileOpenDialogImplWin32*)
499         GetWindowLongPtr(hwnd, GWLP_USERDATA);
501     LRESULT lResult = CallWindowProc(pImpl->_base_window_proc, hwnd, uMsg, wParam, lParam);
503     switch(uMsg)
504     {
505     case WM_SHOWWINDOW:
506         if(wParam != 0)
507             pImpl->layout_dialog();
508         break;
510     case WM_SIZE:
511         pImpl->layout_dialog();
512         break;
514     case WM_COMMAND:
515         if(wParam == IDC_SHOW_PREVIEW)
516         {
517             const bool enable = SendMessage(pImpl->_toolbar_wnd,
518                 TB_ISBUTTONCHECKED, IDC_SHOW_PREVIEW, 0) != 0;
519             pImpl->enable_preview(enable);
520         }
521         break;
522     }
524     return lResult;
527 LRESULT CALLBACK FileOpenDialogImplWin32::preview_wnd_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
529     const int CaptionPadding = 4;
530     const int IconSize = 32;
532     FileOpenDialogImplWin32 *pImpl = (FileOpenDialogImplWin32*)
533         GetWindowLongPtr(hwnd, GWLP_USERDATA);
535     LRESULT lResult = 0;
537     switch(uMsg)
538     {
539     case WM_ERASEBKGND:
540         // Do nothing to erase the background
541         //  - otherwise there'll be flicker
542         lResult = 1;
543         break;
545     case WM_PAINT:
546         {
547             // Get the client rect
548             RECT rcClient;
549             GetClientRect(hwnd, &rcClient);
551             // Prepare to paint
552             PAINTSTRUCT paint_struct;
553             HDC dc = BeginPaint(hwnd, &paint_struct);
555             HFONT hCaptionFont = (HFONT)SendMessage(GetParent(hwnd),
556                     WM_GETFONT, 0, 0);
557             HFONT hOldFont = (HFONT)SelectObject(dc, hCaptionFont);
558             SetBkMode(dc, TRANSPARENT);
560             pImpl->_mutex->lock();
562             if(pImpl->_path_string[0] == 0)
563             {
564                 FillRect(dc, &rcClient, (HBRUSH)(COLOR_3DFACE + 1));
565                 DrawText(dc, _("No file selected"), -1, &rcClient,
566                     DT_CENTER | DT_VCENTER | DT_NOPREFIX);
567             }
568             else if(pImpl->_preview_bitmap != NULL)
569             {
570                 BITMAP bitmap;
571                 GetObject(pImpl->_preview_bitmap, sizeof(bitmap), &bitmap);
572                 const int destX = (rcClient.right - bitmap.bmWidth) / 2;
574                 // Render the image
575                 HDC hSrcDC = CreateCompatibleDC(dc);
576                 HBITMAP hOldBitmap = (HBITMAP)SelectObject(hSrcDC, pImpl->_preview_bitmap);
578                 BitBlt(dc, destX, 0, bitmap.bmWidth, bitmap.bmHeight,
579                     hSrcDC, 0, 0, SRCCOPY);
581                 SelectObject(hSrcDC, hOldBitmap);
582                 DeleteDC(hSrcDC);
584                 // Fill in the background area
585                 HRGN hEraseRgn = CreateRectRgn(rcClient.left, rcClient.top,
586                     rcClient.right, rcClient.bottom);
587                 HRGN hImageRgn = CreateRectRgn(destX, 0,
588                     destX + bitmap.bmWidth, bitmap.bmHeight);
589                 CombineRgn(hEraseRgn, hEraseRgn, hImageRgn, RGN_DIFF);
591                 FillRgn(dc, hEraseRgn, GetSysColorBrush(COLOR_3DFACE));
593                 DeleteObject(hImageRgn);
594                 DeleteObject(hEraseRgn);
596                 // Draw the caption on
597                 RECT rcCaptionRect = {rcClient.left,
598                     rcClient.top + bitmap.bmHeight + CaptionPadding,
599                     rcClient.right, rcClient.bottom};
601                 WCHAR szCaption[_MAX_FNAME + 32];
602                 const int iLength = pImpl->format_caption(
603                     szCaption, sizeof(szCaption) / sizeof(WCHAR));
605                 DrawTextW(dc, szCaption, iLength, &rcCaptionRect,
606                     DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS);
607             }
608             else if(pImpl->_preview_file_icon != NULL)
609             {
610                 FillRect(dc, &rcClient, (HBRUSH)(COLOR_3DFACE + 1));
612                 // Draw the files icon
613                 const int destX = (rcClient.right - IconSize) / 2;
614                 DrawIconEx(dc, destX, 0, pImpl->_preview_file_icon,
615                     IconSize, IconSize, 0, NULL,
616                     DI_NORMAL | DI_COMPAT);
618                 // Draw the caption on
619                 RECT rcCaptionRect = {rcClient.left,
620                     rcClient.top + IconSize + CaptionPadding,
621                     rcClient.right, rcClient.bottom};
623                 WCHAR szFileName[_MAX_FNAME], szCaption[_MAX_FNAME + 32];
624                 _wsplitpath(pImpl->_path_string, NULL, NULL, szFileName, NULL);
626                 const int iLength = snwprintf(szCaption,
627                     sizeof(szCaption), L"%s\n%d kB",
628                     szFileName, pImpl->_preview_file_size);
630                 DrawTextW(dc, szCaption, iLength, &rcCaptionRect,
631                     DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS);
632             }
633             else
634             {
635                 // Can't show anything!
636                 FillRect(dc, &rcClient, (HBRUSH)(COLOR_3DFACE + 1));
637             }
639             pImpl->_mutex->unlock();
641             // Finish painting
642             SelectObject(dc, hOldFont);
643             EndPaint(hwnd, &paint_struct);
644         }
646         break;
648     case WM_DESTROY:
649         pImpl->free_preview();
650         break;
652     default:
653         lResult = DefWindowProc(hwnd, uMsg, wParam, lParam);
654         break;
655     }
657     return lResult;
660 void FileOpenDialogImplWin32::enable_preview(bool enable)
662     _show_preview = enable;
664     // Relayout the dialog
665     ShowWindow(_preview_wnd, enable ? SW_SHOW : SW_HIDE);
666     layout_dialog();
668     // Load or unload the preview
669     if(enable)
670     {
671         _mutex->lock();
672         _file_selected = true;
673         _mutex->unlock();
674     }
675     else free_preview();
678 void FileOpenDialogImplWin32::layout_dialog()
680     union RECTPOINTS
681     {
682         RECT r;
683         POINT p[2];
684     };
686     const float MaxExtentScale = 2.0f / 3.0f;
688     RECT rcClient;
689     GetClientRect(_file_dialog_wnd, &rcClient);
691     // Re-layout the dialog
692     HWND hFileListWnd = GetDlgItem(_file_dialog_wnd, lst2);
693     HWND hFolderComboWnd = GetDlgItem(_file_dialog_wnd, cmb2);
696     RECT rcFolderComboRect;
697     RECTPOINTS rcFileList;
698     GetWindowRect(hFileListWnd, &rcFileList.r);
699     GetWindowRect(hFolderComboWnd, &rcFolderComboRect);
700     const int iPadding = rcFileList.r.top - rcFolderComboRect.bottom;
701     MapWindowPoints(NULL, _file_dialog_wnd, rcFileList.p, 2);
703     RECT rcPreview;
704     RECT rcBody = {rcFileList.r.left, rcFileList.r.top,
705         rcClient.right - iPadding, rcFileList.r.bottom};
706     rcFileList.r.right = rcBody.right;
708     if(_show_preview)
709     {
710         rcPreview.top = rcBody.top;
711         rcPreview.left = rcClient.right - (rcBody.bottom - rcBody.top);
712         const int iMaxExtent = (int)(MaxExtentScale * (float)(rcBody.left + rcBody.right)) + iPadding / 2;
713         if(rcPreview.left < iMaxExtent) rcPreview.left = iMaxExtent;
714         rcPreview.bottom = rcBody.bottom;
715         rcPreview.right = rcBody.right;
717         // Re-layout the preview box
718         _mutex->lock();
720             _preview_width = rcPreview.right - rcPreview.left;
721             _preview_height = rcPreview.bottom - rcPreview.top;
723         _mutex->unlock();
725         render_preview();
727         MoveWindow(_preview_wnd, rcPreview.left, rcPreview.top,
728             _preview_width, _preview_height, TRUE);
730         rcFileList.r.right = rcPreview.left - iPadding;
731     }
733     // Re-layout the file list box
734     MoveWindow(hFileListWnd, rcFileList.r.left, rcFileList.r.top,
735         rcFileList.r.right - rcFileList.r.left,
736         rcFileList.r.bottom - rcFileList.r.top, TRUE);
738     // Re-layout the toolbar
739     RECTPOINTS rcToolBar;
740     GetWindowRect(_toolbar_wnd, &rcToolBar.r);
741     MapWindowPoints(NULL, _file_dialog_wnd, rcToolBar.p, 2);
742     MoveWindow(_toolbar_wnd, rcToolBar.r.left, rcToolBar.r.top,
743         rcToolBar.r.right - rcToolBar.r.left, rcToolBar.r.bottom - rcToolBar.r.top, TRUE);
746 void FileOpenDialogImplWin32::file_selected()
748     // Destroy any previous previews
749     free_preview();
752     // Determine if the file exists
753     DWORD attributes = GetFileAttributesW(_path_string);
754     if(attributes == 0xFFFFFFFF ||
755         attributes == FILE_ATTRIBUTE_DIRECTORY)
756     {
757         InvalidateRect(_preview_wnd, NULL, FALSE);
758         return;
759     }
761     // Check the file exists and get the file size
762     HANDLE file_handle = CreateFileW(_path_string, GENERIC_READ,
763         FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
764     if(file_handle == INVALID_HANDLE_VALUE) return;
765     const DWORD file_size = GetFileSize(file_handle, NULL);
766     if (file_size == INVALID_FILE_SIZE) return;
767     _preview_file_size = file_size / 1024;
768     CloseHandle(file_handle);
770     if(_show_preview) load_preview();
773 void FileOpenDialogImplWin32::load_preview()
775     // Destroy any previous previews
776     free_preview();
778     // Try to get the file icon
779     SHFILEINFOW fileInfo;
780     if(SUCCEEDED(SHGetFileInfoW(_path_string, 0, &fileInfo,
781         sizeof(fileInfo), SHGFI_ICON | SHGFI_LARGEICON)))
782         _preview_file_icon = fileInfo.hIcon;
784     // Will this file be too big?
785     if(_preview_file_size > MaxPreviewFileSize)
786     {
787         InvalidateRect(_preview_wnd, NULL, FALSE);
788         return;
789     }
791     // Prepare to render a preview
792     const Glib::ustring svg = ".svg";
793     const Glib::ustring svgz = ".svgz";
794     const Glib::ustring emf = ".emf";
795     const Glib::ustring wmf = ".wmf";
796     const Glib::ustring path = utf16_to_ustring(_path_string);
798     bool success = false;
800     _preview_document_width = _preview_document_height = 0;
802     if ((dialogType == SVG_TYPES || dialogType == IMPORT_TYPES) &&
803             (hasSuffix(path, svg) || hasSuffix(path, svgz)))
804         success = set_svg_preview();
805     else if (hasSuffix(path, emf) || hasSuffix(path, wmf))
806         success = set_emf_preview();
807     else if (isValidImageFile(path))
808         success = set_image_preview();
809     else {
810         // Show no preview
811     }
813     if(success) render_preview();
815     InvalidateRect(_preview_wnd, NULL, FALSE);
818 void FileOpenDialogImplWin32::free_preview()
820     _mutex->lock();
821     if(_preview_bitmap != NULL)
822         DeleteObject(_preview_bitmap);
823     _preview_bitmap = NULL;
825     if(_preview_file_icon != NULL)
826         DestroyIcon(_preview_file_icon);
827     _preview_file_icon = NULL;
829     _preview_bitmap_image.clear();
830     _preview_emf_image = false;
831     _mutex->unlock();
834 bool FileOpenDialogImplWin32::set_svg_preview()
836     const int PreviewSize = 512;
838     gchar *utf8string = g_utf16_to_utf8((const gunichar2*)_path_string,
839         _MAX_PATH, NULL, NULL, NULL);
840     SPDocument *svgDoc = sp_document_new (utf8string, true);
841     g_free(utf8string);
843     // Check the document loaded properly
844     if(svgDoc == NULL) return false;
845     if(svgDoc->root == NULL)
846     {
847         sp_document_unref(svgDoc);
848         return false;
849     }
851     // Get the size of the document
852     const double svgWidth = sp_document_width(svgDoc);
853     const double svgHeight = sp_document_height(svgDoc);
855     // Find the minimum scale to fit the image inside the preview area
856     const double scaleFactorX =    PreviewSize / svgWidth;
857     const double scaleFactorY =    PreviewSize / svgHeight;
858     const double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX;
860     // Now get the resized values
861     const double scaledSvgWidth  = scaleFactor * svgWidth;
862     const double scaledSvgHeight = scaleFactor * svgHeight;
864     Geom::Rect area(Geom::Point(0, 0), Geom::Point(scaledSvgWidth, scaledSvgHeight));
865     NRRectL areaL = {0, 0, scaledSvgWidth, scaledSvgHeight};
866     NRRectL bbox = {0, 0, scaledSvgWidth, scaledSvgHeight};
868     // write object bbox to area
869     boost::optional<NR::Rect> maybeArea(from_2geom(area));
870     sp_document_ensure_up_to_date (svgDoc);
871     sp_item_invoke_bbox((SPItem *) svgDoc->root, &maybeArea,
872         sp_item_i2r_affine((SPItem *)(svgDoc->root)), TRUE);
874     NRArena *const arena = NRArena::create();
876     unsigned const key = sp_item_display_key_new(1);
878     NRArenaItem *root = sp_item_invoke_show((SPItem*)(svgDoc->root),
879         arena, key, SP_ITEM_SHOW_DISPLAY);
881     NRGC gc(NULL);
882     gc.transform = Geom::Matrix(Geom::Scale(scaleFactor, scaleFactor));
884     nr_arena_item_invoke_update (root, NULL, &gc,
885         NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
887     // Prepare a GDI compatible NRPixBlock
888     NRPixBlock pixBlock;
889     pixBlock.size = NR_PIXBLOCK_SIZE_BIG;
890     pixBlock.mode = NR_PIXBLOCK_MODE_R8G8B8;
891     pixBlock.empty = 1;
892     pixBlock.visible_area.x0 = pixBlock.area.x0 = 0;
893     pixBlock.visible_area.y0 = pixBlock.area.y0 = 0;
894     pixBlock.visible_area.x1 = pixBlock.area.x1 = scaledSvgWidth;
895     pixBlock.visible_area.y1 = pixBlock.area.y1 = scaledSvgHeight;
896     pixBlock.rs = 4 * ((3 * (int)scaledSvgWidth + 3) / 4);
897     pixBlock.data.px = g_try_new (unsigned char, pixBlock.rs * scaledSvgHeight);
899     // Fail if the pixblock failed to allocate
900     if(pixBlock.data.px == NULL)
901     {
902         sp_document_unref(svgDoc);
903         return false;
904     }
906     memset(pixBlock.data.px, 0xFF, pixBlock.rs * scaledSvgHeight);
908     memcpy(&root->bbox, &areaL, sizeof(areaL));
910     // Render the image
911     nr_arena_item_invoke_render(NULL, root, &bbox, &pixBlock, /*0*/NR_ARENA_ITEM_RENDER_NO_CACHE);
913     // Tidy up
914     sp_document_unref(svgDoc);
915     sp_item_invoke_hide((SPItem*)(svgDoc->root), key);
916     nr_arena_item_unref(root);
917     nr_object_unref((NRObject *) arena);
919     // Create the GDK pixbuf
920     _mutex->lock();
922     _preview_bitmap_image = Gdk::Pixbuf::create_from_data(
923         pixBlock.data.px, Gdk::COLORSPACE_RGB, false, 8,
924         (int)scaledSvgWidth, (int)scaledSvgHeight, pixBlock.rs,
925         sigc::ptr_fun(destroy_svg_rendering));
927     _preview_document_width = scaledSvgWidth;
928     _preview_document_height = scaledSvgHeight;
929     _preview_image_width = svgWidth;
930     _preview_image_height = svgHeight;
932     _mutex->unlock();
934     return true;
937 void FileOpenDialogImplWin32::destroy_svg_rendering(const guint8 *buffer)
939     g_assert(buffer != NULL);
940     g_free((void*)buffer);
943 bool FileOpenDialogImplWin32::set_image_preview()
945     const Glib::ustring path = utf16_to_ustring(_path_string, _MAX_PATH);
947     bool successful = false;
949     _mutex->lock();
951     try {
952         _preview_bitmap_image = Gdk::Pixbuf::create_from_file(path);
953         if (_preview_bitmap_image) {
954             _preview_image_width = _preview_bitmap_image->get_width();
955             _preview_document_width = _preview_image_width;
956             _preview_image_height = _preview_bitmap_image->get_height();
957             _preview_document_height = _preview_image_height;
958             successful = true;
959         }
960     }
961     catch (const Gdk::PixbufError&) {}
962     catch (const Glib::FileError&) {}
964     _mutex->unlock();
966     return successful;
969 // Aldus Placeable Header ===================================================
970 // Since we are a 32bit app, we have to be sure this structure compiles to
971 // be identical to a 16 bit app's version. To do this, we use the #pragma
972 // to adjust packing, we use a WORD for the hmf handle, and a SMALL_RECT
973 // for the bbox rectangle.
974 #pragma pack( push )
975 #pragma pack( 2 )
976 typedef struct
978     DWORD       dwKey;
979     WORD        hmf;
980     SMALL_RECT  bbox;
981     WORD        wInch;
982     DWORD       dwReserved;
983     WORD        wCheckSum;
984 } APMHEADER, *PAPMHEADER;
985 #pragma pack( pop )
988 static HENHMETAFILE
989 MyGetEnhMetaFileW( const WCHAR *filename )
991     // Try open as Enhanced Metafile
992     HENHMETAFILE hemf = GetEnhMetaFileW(filename);
994     if (!hemf) {
995         // Try open as Windows Metafile
996         HMETAFILE hmf = GetMetaFileW(filename);
998         METAFILEPICT mp;
999         HDC hDC;
1001         if (!hmf) {
1002             WCHAR szTemp[MAX_PATH];
1004             DWORD dw = GetShortPathNameW( filename, szTemp, MAX_PATH );
1005             if (dw) {
1006                 hmf = GetMetaFileW( szTemp );
1007             }
1008         }
1010         if (hmf) {
1011             // Convert Windows Metafile to Enhanced Metafile
1012             DWORD nSize = GetMetaFileBitsEx( hmf, 0, NULL );
1013             
1014             if (nSize) {
1015                 BYTE *lpvData = new BYTE[nSize];
1016                 if (lpvData) {
1017                     DWORD dw = GetMetaFileBitsEx( hmf, nSize, lpvData );
1018                     if (dw) {
1019                         // Fill out a METAFILEPICT structure
1020                         mp.mm = MM_ANISOTROPIC;
1021                         mp.xExt = 1000;
1022                         mp.yExt = 1000;
1023                         mp.hMF = NULL;
1024                         // Get a reference DC
1025                         hDC = GetDC( NULL );
1026                         // Make an enhanced metafile from the windows metafile
1027                         hemf = SetWinMetaFileBits( nSize, lpvData, hDC, &mp );
1028                         // Clean up
1029                         ReleaseDC( NULL, hDC );
1030                         DeleteMetaFile( hmf );
1031                     }
1032                     delete[] lpvData;
1033                 }
1034                 else {
1035                     DeleteMetaFile( hmf );
1036                 }
1037             }
1038             else {
1039                 DeleteMetaFile( hmf );
1040             }
1041         }
1042         else {
1043             // Try open as Aldus Placeable Metafile
1044             HANDLE hFile;
1045             hFile = CreateFileW( filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
1047             if (hFile != INVALID_HANDLE_VALUE) {
1048                 DWORD nSize = GetFileSize( hFile, NULL );
1049                 if (nSize) {
1050                     BYTE *lpvData = new BYTE[nSize];
1051                     if (lpvData) {
1052                         DWORD dw = ReadFile( hFile, lpvData, nSize, &nSize, NULL );
1053                         if (dw) {
1054                             if ( ((PAPMHEADER)lpvData)->dwKey == 0x9ac6cdd7l ) {
1055                                 // Fill out a METAFILEPICT structure
1056                                 mp.mm = MM_ANISOTROPIC;
1057                                 mp.xExt = ((PAPMHEADER)lpvData)->bbox.Right - ((PAPMHEADER)lpvData)->bbox.Left;
1058                                 mp.xExt = ( mp.xExt * 2540l ) / (DWORD)(((PAPMHEADER)lpvData)->wInch);
1059                                 mp.yExt = ((PAPMHEADER)lpvData)->bbox.Bottom - ((PAPMHEADER)lpvData)->bbox.Top;
1060                                 mp.yExt = ( mp.yExt * 2540l ) / (DWORD)(((PAPMHEADER)lpvData)->wInch);
1061                                 mp.hMF = NULL;
1062                                 // Get a reference DC
1063                                 hDC = GetDC( NULL );
1064                                 // Create an enhanced metafile from the bits
1065                                 hemf = SetWinMetaFileBits( nSize, lpvData+sizeof(APMHEADER), hDC, &mp );
1066                                 // Clean up
1067                                 ReleaseDC( NULL, hDC );
1068                             }
1069                         }
1070                         delete[] lpvData;
1071                     }
1072                 }
1073                 CloseHandle( hFile );
1074             }
1075         }
1076     }
1078     return hemf;
1082 bool FileOpenDialogImplWin32::set_emf_preview()
1084     _mutex->lock();
1086     BOOL ok = FALSE;
1088     DWORD w = 0;
1089     DWORD h = 0;
1091     HENHMETAFILE hemf = MyGetEnhMetaFileW( _path_string );
1093     if (hemf)
1094     {
1095         ENHMETAHEADER emh;
1096         ZeroMemory(&emh, sizeof(emh));
1097         ok = GetEnhMetaFileHeader(hemf, sizeof(emh), &emh) != 0;
1099         w = (emh.rclFrame.right - emh.rclFrame.left);
1100         h = (emh.rclFrame.bottom - emh.rclFrame.top);
1102         DeleteEnhMetaFile(hemf);
1103     }
1105     if (ok)
1106     {
1107         const int PreviewSize = 512;
1109         // Get the size of the document
1110         const double emfWidth = w;
1111         const double emfHeight = h;
1113         // Find the minimum scale to fit the image inside the preview area
1114         const double scaleFactorX =    PreviewSize / emfWidth;
1115         const double scaleFactorY =    PreviewSize / emfHeight;
1116         const double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX;
1118         // Now get the resized values
1119         const double scaledEmfWidth  = scaleFactor * emfWidth;
1120         const double scaledEmfHeight = scaleFactor * emfHeight;
1122         _preview_document_width = scaledEmfWidth;
1123         _preview_document_height = scaledEmfHeight;
1124         _preview_image_width = emfWidth;
1125         _preview_image_height = emfHeight;
1127         _preview_emf_image = true;
1128     }
1130     _mutex->unlock();
1132     return ok;
1135 void FileOpenDialogImplWin32::render_preview()
1137     double x, y;
1138     const double blurRadius = 8;
1139     const double halfBlurRadius = blurRadius / 2;
1140     const int shaddowOffsetX = 0;
1141     const int shaddowOffsetY = 2;
1142     const int pagePadding = 5;
1143     const double shaddowAlpha = 0.75;
1145     // Is the preview showing?
1146     if(!_show_preview)
1147         return;
1149     // Do we have anything to render?
1150     _mutex->lock();
1152     if(!_preview_bitmap_image && !_preview_emf_image)
1153     {
1154         _mutex->unlock();
1155         return;
1156     }
1158     // Tidy up any previous bitmap renderings
1159     if(_preview_bitmap != NULL)
1160         DeleteObject(_preview_bitmap);
1161     _preview_bitmap = NULL;
1163     // Calculate the size of the caption
1164     int captionHeight = 0;
1166     if(_preview_wnd != NULL)
1167     {
1168         RECT rcCaptionRect;
1169         WCHAR szCaption[_MAX_FNAME + 32];
1170         const int iLength = format_caption(szCaption,
1171             sizeof(szCaption) / sizeof(WCHAR));
1173         HDC dc = GetDC(_preview_wnd);
1174         DrawTextW(dc, szCaption, iLength, &rcCaptionRect,
1175             DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_CALCRECT);
1176         ReleaseDC(_preview_wnd, dc);
1178         captionHeight = rcCaptionRect.bottom - rcCaptionRect.top;
1179     }
1181     // Find the minimum scale to fit the image inside the preview area
1182     const double scaleFactorX =
1183         ((double)_preview_width - pagePadding * 2 - blurRadius)  / _preview_document_width;
1184     const double scaleFactorY =
1185         ((double)_preview_height - pagePadding * 2
1186         - shaddowOffsetY - halfBlurRadius - captionHeight) / _preview_document_height;
1187     double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX;
1188     scaleFactor = (scaleFactor > 1.0) ? 1.0 : scaleFactor;
1190     // Now get the resized values
1191     const double scaledSvgWidth  = scaleFactor * _preview_document_width;
1192     const double scaledSvgHeight = scaleFactor * _preview_document_height;
1194     const int svgX = pagePadding + halfBlurRadius;
1195     const int svgY = pagePadding;
1197     const int frameX = svgX - pagePadding;
1198     const int frameY = svgY - pagePadding;
1199     const int frameWidth = scaledSvgWidth + pagePadding * 2;
1200     const int frameHeight = scaledSvgHeight + pagePadding * 2;
1202     const int totalWidth = (int)ceil(frameWidth + blurRadius);
1203     const int totalHeight = (int)ceil(frameHeight + blurRadius);
1205     // Prepare the drawing surface
1206     HDC hDC = GetDC(_preview_wnd);
1207     HDC hMemDC = CreateCompatibleDC(hDC);
1208     _preview_bitmap = CreateCompatibleBitmap(hDC, totalWidth, totalHeight);
1209     HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDC, _preview_bitmap);
1210     Cairo::RefPtr<Win32Surface> surface = Win32Surface::create(hMemDC);
1211     Cairo::RefPtr<Context> context = Context::create(surface);
1213     // Paint the background to match the dialog colour
1214     const COLORREF background = GetSysColor(COLOR_3DFACE);
1215     context->set_source_rgb(
1216         GetRValue(background) / 255.0,
1217         GetGValue(background) / 255.0,
1218         GetBValue(background) / 255.0);
1219     context->paint();
1221     //----- Draw the drop shaddow -----//
1223     // Left Edge
1224     x = frameX + shaddowOffsetX - halfBlurRadius;
1225     Cairo::RefPtr<LinearGradient> leftEdgeFade = LinearGradient::create(
1226         x, 0.0, x + blurRadius, 0.0);
1227     leftEdgeFade->add_color_stop_rgba (0, 0, 0, 0, 0);
1228     leftEdgeFade->add_color_stop_rgba (1, 0, 0, 0, shaddowAlpha);
1229     context->set_source(leftEdgeFade);
1230     context->rectangle (x, frameY + shaddowOffsetY + halfBlurRadius,
1231         blurRadius, frameHeight - blurRadius);
1232     context->fill();
1234     // Right Edge
1235     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1236     Cairo::RefPtr<LinearGradient> rightEdgeFade = LinearGradient::create(
1237         x, 0.0,    x + blurRadius, 0.0);
1238     rightEdgeFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1239     rightEdgeFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1240     context->set_source(rightEdgeFade);
1241     context->rectangle (frameX + frameWidth + shaddowOffsetX - halfBlurRadius,
1242         frameY + shaddowOffsetY + halfBlurRadius,
1243         blurRadius, frameHeight - blurRadius);
1244     context->fill();
1246     // Top Edge
1247     y = frameY + shaddowOffsetY - halfBlurRadius;
1248     Cairo::RefPtr<LinearGradient> topEdgeFade = LinearGradient::create(
1249         0.0, y, 0.0, y + blurRadius);
1250     topEdgeFade->add_color_stop_rgba (0, 0, 0, 0, 0);
1251     topEdgeFade->add_color_stop_rgba (1, 0, 0, 0, shaddowAlpha);
1252     context->set_source(topEdgeFade);
1253     context->rectangle (frameX + shaddowOffsetX + halfBlurRadius, y,
1254         frameWidth - blurRadius, blurRadius);
1255     context->fill();
1257     // Bottom Edge
1258     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1259     Cairo::RefPtr<LinearGradient> bottomEdgeFade = LinearGradient::create(
1260         0.0, y,    0.0, y + blurRadius);
1261     bottomEdgeFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1262     bottomEdgeFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1263     context->set_source(bottomEdgeFade);
1264     context->rectangle (frameX + shaddowOffsetX + halfBlurRadius, y,
1265         frameWidth - blurRadius, blurRadius);
1266     context->fill();
1268     // Top Left Corner
1269     x = frameX + shaddowOffsetX - halfBlurRadius;
1270     y = frameY + shaddowOffsetY - halfBlurRadius;
1271     Cairo::RefPtr<RadialGradient> topLeftCornerFade = RadialGradient::create(
1272         x + blurRadius, y + blurRadius, 0, x + blurRadius, y + blurRadius, blurRadius);
1273     topLeftCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1274     topLeftCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1275     context->set_source(topLeftCornerFade);
1276     context->rectangle (x, y, blurRadius, blurRadius);
1277     context->fill();
1279     // Top Right Corner
1280     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1281     y = frameY + shaddowOffsetY - halfBlurRadius;
1282     Cairo::RefPtr<RadialGradient> topRightCornerFade = RadialGradient::create(
1283         x, y + blurRadius, 0, x, y + blurRadius, blurRadius);
1284     topRightCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1285     topRightCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1286     context->set_source(topRightCornerFade);
1287     context->rectangle (x, y, blurRadius, blurRadius);
1288     context->fill();
1290     // Bottom Left Corner
1291     x = frameX + shaddowOffsetX - halfBlurRadius;
1292     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1293     Cairo::RefPtr<RadialGradient> bottomLeftCornerFade = RadialGradient::create(
1294         x + blurRadius, y, 0, x + blurRadius, y, blurRadius);
1295     bottomLeftCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1296     bottomLeftCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1297     context->set_source(bottomLeftCornerFade);
1298     context->rectangle (x, y, blurRadius, blurRadius);
1299     context->fill();
1301     // Bottom Right Corner
1302     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1303     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1304     Cairo::RefPtr<RadialGradient> bottomRightCornerFade = RadialGradient::create(
1305         x, y, 0, x, y, blurRadius);
1306     bottomRightCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1307     bottomRightCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1308     context->set_source(bottomRightCornerFade);
1309     context->rectangle (frameX + frameWidth + shaddowOffsetX - halfBlurRadius,
1310         frameY + frameHeight + shaddowOffsetY - halfBlurRadius,
1311         blurRadius, blurRadius);
1312     context->fill();
1314     // Draw the frame
1315     context->set_line_width(1);
1316     context->rectangle (frameX, frameY,    frameWidth, frameHeight);
1318     context->set_source_rgb(1.0, 1.0, 1.0);
1319     context->fill_preserve();
1320     context->set_source_rgb(0.25, 0.25, 0.25);
1321     context->stroke_preserve();
1323     // Draw the image
1324     if(_preview_bitmap_image)    // Is the image a pixbuf?
1325     {
1326         // Set the transformation
1327         const Matrix matrix = {
1328             scaleFactor, 0,
1329             0, scaleFactor,
1330             svgX, svgY };
1331         context->set_matrix (matrix);
1333         // Render the image
1334         set_source_pixbuf (context, _preview_bitmap_image, 0, 0);
1335         context->paint();
1337         // Reset the transformation
1338         context->set_identity_matrix();
1339     }
1341     // Draw the inner frame
1342     context->set_source_rgb(0.75, 0.75, 0.75);
1343     context->rectangle (svgX, svgY,    scaledSvgWidth, scaledSvgHeight);
1344     context->stroke();
1346     _mutex->unlock();
1348     // Finish drawing
1349     surface->finish();
1351     if (_preview_emf_image) {
1352         HENHMETAFILE hemf = MyGetEnhMetaFileW(_path_string);
1353         if (hemf) {
1354             RECT rc;
1355             rc.top = svgY+2;
1356             rc.left = svgX+2;
1357             rc.bottom = scaledSvgHeight-2;
1358             rc.right = scaledSvgWidth-2;
1359             PlayEnhMetaFile(hMemDC, hemf, &rc);
1360             DeleteEnhMetaFile(hemf);
1361         }
1362     }
1364     SelectObject(hMemDC, hOldBitmap) ;
1365     DeleteDC(hMemDC);
1367     // Refresh the preview pane
1368     InvalidateRect(_preview_wnd, NULL, FALSE);
1371 int FileOpenDialogImplWin32::format_caption(wchar_t *caption, int caption_size)
1373     wchar_t szFileName[_MAX_FNAME];
1374     _wsplitpath(_path_string, NULL, NULL, szFileName, NULL);
1376     return snwprintf(caption, caption_size,
1377         L"%s\n%d kB\n%d \xD7 %d", szFileName, _preview_file_size,
1378         (int)_preview_document_width, (int)_preview_document_height);
1381 /**
1382  * Show this dialog modally.  Return true if user hits [OK]
1383  */
1384 bool
1385 FileOpenDialogImplWin32::show()
1387     // We can only run one worker thread at a time
1388     if(_mutex != NULL) return false;
1390     if(!Glib::thread_supported())
1391         Glib::thread_init();
1393     _result = false;
1394     _finished = false;
1395     _file_selected = false;
1396     _mutex = new Glib::Mutex();
1397     _main_loop = g_main_loop_new(g_main_context_default(), FALSE);
1399     if(Glib::Thread::create(sigc::mem_fun(*this, &FileOpenDialogImplWin32::GetOpenFileName_thread), true))
1400     {
1401         while(1)
1402         {
1403             g_main_context_iteration(g_main_context_default(), FALSE);
1405             if(_mutex->trylock())
1406             {
1407                 // Read mutexed data
1408                 const bool finished = _finished;
1409                 const bool is_file_selected = _file_selected;
1410                 _file_selected = false;
1411                 _mutex->unlock();
1413                 if(finished) break;
1414                 if(is_file_selected) file_selected();
1415             }
1417             Sleep(10);
1418         }
1419     }
1421     // Tidy up
1422     delete _mutex;
1423     _mutex = NULL;
1425     return _result;
1428 /**
1429  * To Get Multiple filenames selected at-once.
1430  */
1431 std::vector<Glib::ustring>FileOpenDialogImplWin32::getFilenames()
1433     std::vector<Glib::ustring> result;
1434     result.push_back(getFilename());
1435     return result;
1439 /*#########################################################################
1440 ### F I L E    S A V E
1441 #########################################################################*/
1443 /**
1444  * Constructor
1445  */
1446 FileSaveDialogImplWin32::FileSaveDialogImplWin32(Gtk::Window &parent,
1447             const Glib::ustring &dir,
1448             FileDialogType fileTypes,
1449             const char *title,
1450             const Glib::ustring &/*default_key*/) :
1451     FileDialogBaseWin32(parent, dir, title, fileTypes, "dialogs.save_as")
1453     createFilterMenu();
1456 FileSaveDialogImplWin32::~FileSaveDialogImplWin32()
1460 void FileSaveDialogImplWin32::createFilterMenu()
1462     list<Filter> filter_list;
1464     knownExtensions.clear();
1466     // Compose the filter string
1467     Glib::ustring all_inkscape_files_filter, all_image_files_filter;
1468     Inkscape::Extension::DB::OutputList extension_list;
1469     Inkscape::Extension::db.get_output_list(extension_list);
1471     int filter_count = 0;
1472     int filter_length = 1;
1474     for (Inkscape::Extension::DB::OutputList::iterator current_item = extension_list.begin();
1475          current_item != extension_list.end(); current_item++)
1476     {
1477         Inkscape::Extension::Output *omod = *current_item;
1478         if (omod->deactivated()) continue;
1480         filter_count++;
1482         Filter filter;
1484         // Extension
1485         const gchar *filter_extension = omod->get_extension();
1486         filter.filter = g_utf8_to_utf16(
1487             filter_extension, -1, NULL, &filter.filter_length, NULL);
1488         knownExtensions.insert( Glib::ustring(filter_extension).casefold() );
1490         // Type
1491         filter.name = g_utf8_to_utf16(
1492             _(omod->get_filetypename()), -1, NULL, &filter.name_length, NULL);
1494         filter.mod = omod;
1496         filter_length += filter.name_length +
1497             filter.filter_length + 3;   // Add 3 for two \0s and a *
1499         filter_list.push_back(filter);
1500     }
1502     int extension_index = 0;
1503     _extension_map = new Inkscape::Extension::Extension*[filter_count];
1505     _filter = new wchar_t[filter_length];
1506     wchar_t *filterptr = _filter;
1508     for(list<Filter>::iterator filter_iterator = filter_list.begin();
1509         filter_iterator != filter_list.end(); filter_iterator++)
1510     {
1511         const Filter &filter = *filter_iterator;
1513         wcsncpy(filterptr, (wchar_t*)filter.name, filter.name_length);
1514         filterptr += filter.name_length;
1515         g_free(filter.name);
1517         *(filterptr++) = L'\0';
1518         *(filterptr++) = L'*';
1520         wcsncpy(filterptr, (wchar_t*)filter.filter, filter.filter_length);
1521         filterptr += filter.filter_length;
1522         g_free(filter.filter);
1524         *(filterptr++) = L'\0';
1526         // Associate this input extension with the file type name
1527         _extension_map[extension_index++] = filter.mod;
1528     }
1529     *(filterptr++) = 0;
1531         _filter_count = extension_index;
1532     _filter_index = 1;  // A value of 1 selects the 1st filter - NOT the 2nd
1535 void FileSaveDialogImplWin32::GetSaveFileName_thread()
1537     OPENFILENAMEEXW ofn;
1539     g_assert(this != NULL);
1540     g_assert(_main_loop != NULL);
1542     WCHAR* current_directory_string = (WCHAR*)g_utf8_to_utf16(
1543         _current_directory.data(), _current_directory.length(),
1544                 NULL, NULL, NULL);
1546     // Copy the selected file name, converting from UTF-8 to UTF-16
1547     memset(_path_string, 0, sizeof(_path_string));
1548     gunichar2* utf16_path_string = g_utf8_to_utf16(
1549         myFilename.data(), -1, NULL, NULL, NULL);
1550     wcsncpy(_path_string, (wchar_t*)utf16_path_string, _MAX_PATH);
1551     g_free(utf16_path_string);
1553     ZeroMemory(&ofn, sizeof(ofn));
1554     ofn.lStructSize = sizeof(ofn);
1555     ofn.hwndOwner = _ownerHwnd;
1556     ofn.lpstrFile = _path_string;
1557     ofn.nMaxFile = _MAX_PATH;
1558     ofn.nFilterIndex = _filter_index;
1559     ofn.lpstrFileTitle = NULL;
1560     ofn.nMaxFileTitle = 0;
1561     ofn.lpstrInitialDir = current_directory_string;
1562     ofn.lpstrTitle = _title;
1563     ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
1564     ofn.lpstrFilter = _filter;
1565     ofn.nFilterIndex = _filter_index;
1567     _result = GetSaveFileNameW(&ofn) != 0;
1569         g_assert(ofn.nFilterIndex >= 1 && ofn.nFilterIndex <= _filter_count);
1570     _filter_index = ofn.nFilterIndex;
1571     _extension = _extension_map[ofn.nFilterIndex - 1];
1573     // Copy the selected file name, converting from UTF-16 to UTF-8
1574     myFilename = utf16_to_ustring(_path_string, _MAX_PATH);
1576     // Tidy up
1577     g_free(current_directory_string);
1579     g_main_loop_quit(_main_loop);
1582 /**
1583  * Show this dialog modally.  Return true if user hits [OK]
1584  */
1585 bool
1586 FileSaveDialogImplWin32::show()
1588     if(!Glib::thread_supported())
1589         Glib::thread_init();
1591     _result = false;
1592     _main_loop = g_main_loop_new(g_main_context_default(), FALSE);
1593         
1594         if(_main_loop != NULL)
1595         {
1596             if(Glib::Thread::create(sigc::mem_fun(*this, &FileSaveDialogImplWin32::GetSaveFileName_thread), true))
1597                 g_main_loop_run(_main_loop);
1599             if(_result)
1600                 appendExtension(myFilename, (Inkscape::Extension::Output*)_extension);
1601         }
1602         
1603     return _result;
1606 void FileSaveDialogImplWin32::setSelectionType( Inkscape::Extension::Extension * /*key*/ )
1608     // If no pointer to extension is passed in, look up based on filename extension.
1616 #endif
1618 /*
1619   Local Variables:
1620   mode:c++
1621   c-file-style:"stroustrup"
1622   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1623   indent-tabs-mode:nil
1624   fill-column:99
1625   End:
1626 */
1627 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :