Code

Merging from trunk
[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;
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;
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
278         _filter = new wchar_t[filter_length];
279     wchar_t *filterptr = _filter;
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';
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);
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<Geom::Rect> maybeArea(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_object_unref((NRObject *) arena);
918     // Create the GDK pixbuf
919     _mutex->lock();
921     _preview_bitmap_image = Gdk::Pixbuf::create_from_data(
922         pixBlock.data.px, Gdk::COLORSPACE_RGB, false, 8,
923         (int)scaledSvgWidth, (int)scaledSvgHeight, pixBlock.rs,
924         sigc::ptr_fun(destroy_svg_rendering));
926     _preview_document_width = scaledSvgWidth;
927     _preview_document_height = scaledSvgHeight;
928     _preview_image_width = svgWidth;
929     _preview_image_height = svgHeight;
931     _mutex->unlock();
933     return true;
936 void FileOpenDialogImplWin32::destroy_svg_rendering(const guint8 *buffer)
938     g_assert(buffer != NULL);
939     g_free((void*)buffer);
942 bool FileOpenDialogImplWin32::set_image_preview()
944     const Glib::ustring path = utf16_to_ustring(_path_string, _MAX_PATH);
946     bool successful = false;
948     _mutex->lock();
950     try {
951         _preview_bitmap_image = Gdk::Pixbuf::create_from_file(path);
952         if (_preview_bitmap_image) {
953             _preview_image_width = _preview_bitmap_image->get_width();
954             _preview_document_width = _preview_image_width;
955             _preview_image_height = _preview_bitmap_image->get_height();
956             _preview_document_height = _preview_image_height;
957             successful = true;
958         }
959     }
960     catch (const Gdk::PixbufError&) {}
961     catch (const Glib::FileError&) {}
963     _mutex->unlock();
965     return successful;
968 // Aldus Placeable Header ===================================================
969 // Since we are a 32bit app, we have to be sure this structure compiles to
970 // be identical to a 16 bit app's version. To do this, we use the #pragma
971 // to adjust packing, we use a WORD for the hmf handle, and a SMALL_RECT
972 // for the bbox rectangle.
973 #pragma pack( push )
974 #pragma pack( 2 )
975 typedef struct
977     DWORD       dwKey;
978     WORD        hmf;
979     SMALL_RECT  bbox;
980     WORD        wInch;
981     DWORD       dwReserved;
982     WORD        wCheckSum;
983 } APMHEADER, *PAPMHEADER;
984 #pragma pack( pop )
987 static HENHMETAFILE
988 MyGetEnhMetaFileW( const WCHAR *filename )
990     // Try open as Enhanced Metafile
991     HENHMETAFILE hemf = GetEnhMetaFileW(filename);
993     if (!hemf) {
994         // Try open as Windows Metafile
995         HMETAFILE hmf = GetMetaFileW(filename);
997         METAFILEPICT mp;
998         HDC hDC;
1000         if (!hmf) {
1001             WCHAR szTemp[MAX_PATH];
1003             DWORD dw = GetShortPathNameW( filename, szTemp, MAX_PATH );
1004             if (dw) {
1005                 hmf = GetMetaFileW( szTemp );
1006             }
1007         }
1009         if (hmf) {
1010             // Convert Windows Metafile to Enhanced Metafile
1011             DWORD nSize = GetMetaFileBitsEx( hmf, 0, NULL );
1013             if (nSize) {
1014                 BYTE *lpvData = new BYTE[nSize];
1015                 if (lpvData) {
1016                     DWORD dw = GetMetaFileBitsEx( hmf, nSize, lpvData );
1017                     if (dw) {
1018                         // Fill out a METAFILEPICT structure
1019                         mp.mm = MM_ANISOTROPIC;
1020                         mp.xExt = 1000;
1021                         mp.yExt = 1000;
1022                         mp.hMF = NULL;
1023                         // Get a reference DC
1024                         hDC = GetDC( NULL );
1025                         // Make an enhanced metafile from the windows metafile
1026                         hemf = SetWinMetaFileBits( nSize, lpvData, hDC, &mp );
1027                         // Clean up
1028                         ReleaseDC( NULL, hDC );
1029                         DeleteMetaFile( hmf );
1030                     }
1031                     delete[] lpvData;
1032                 }
1033                 else {
1034                     DeleteMetaFile( hmf );
1035                 }
1036             }
1037             else {
1038                 DeleteMetaFile( hmf );
1039             }
1040         }
1041         else {
1042             // Try open as Aldus Placeable Metafile
1043             HANDLE hFile;
1044             hFile = CreateFileW( filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
1046             if (hFile != INVALID_HANDLE_VALUE) {
1047                 DWORD nSize = GetFileSize( hFile, NULL );
1048                 if (nSize) {
1049                     BYTE *lpvData = new BYTE[nSize];
1050                     if (lpvData) {
1051                         DWORD dw = ReadFile( hFile, lpvData, nSize, &nSize, NULL );
1052                         if (dw) {
1053                             if ( ((PAPMHEADER)lpvData)->dwKey == 0x9ac6cdd7l ) {
1054                                 // Fill out a METAFILEPICT structure
1055                                 mp.mm = MM_ANISOTROPIC;
1056                                 mp.xExt = ((PAPMHEADER)lpvData)->bbox.Right - ((PAPMHEADER)lpvData)->bbox.Left;
1057                                 mp.xExt = ( mp.xExt * 2540l ) / (DWORD)(((PAPMHEADER)lpvData)->wInch);
1058                                 mp.yExt = ((PAPMHEADER)lpvData)->bbox.Bottom - ((PAPMHEADER)lpvData)->bbox.Top;
1059                                 mp.yExt = ( mp.yExt * 2540l ) / (DWORD)(((PAPMHEADER)lpvData)->wInch);
1060                                 mp.hMF = NULL;
1061                                 // Get a reference DC
1062                                 hDC = GetDC( NULL );
1063                                 // Create an enhanced metafile from the bits
1064                                 hemf = SetWinMetaFileBits( nSize, lpvData+sizeof(APMHEADER), hDC, &mp );
1065                                 // Clean up
1066                                 ReleaseDC( NULL, hDC );
1067                             }
1068                         }
1069                         delete[] lpvData;
1070                     }
1071                 }
1072                 CloseHandle( hFile );
1073             }
1074         }
1075     }
1077     return hemf;
1081 bool FileOpenDialogImplWin32::set_emf_preview()
1083     _mutex->lock();
1085     BOOL ok = FALSE;
1087     DWORD w = 0;
1088     DWORD h = 0;
1090     HENHMETAFILE hemf = MyGetEnhMetaFileW( _path_string );
1092     if (hemf)
1093     {
1094         ENHMETAHEADER emh;
1095         ZeroMemory(&emh, sizeof(emh));
1096         ok = GetEnhMetaFileHeader(hemf, sizeof(emh), &emh) != 0;
1098         w = (emh.rclFrame.right - emh.rclFrame.left);
1099         h = (emh.rclFrame.bottom - emh.rclFrame.top);
1101         DeleteEnhMetaFile(hemf);
1102     }
1104     if (ok)
1105     {
1106         const int PreviewSize = 512;
1108         // Get the size of the document
1109         const double emfWidth = w;
1110         const double emfHeight = h;
1112         // Find the minimum scale to fit the image inside the preview area
1113         const double scaleFactorX =    PreviewSize / emfWidth;
1114         const double scaleFactorY =    PreviewSize / emfHeight;
1115         const double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX;
1117         // Now get the resized values
1118         const double scaledEmfWidth  = scaleFactor * emfWidth;
1119         const double scaledEmfHeight = scaleFactor * emfHeight;
1121         _preview_document_width = scaledEmfWidth;
1122         _preview_document_height = scaledEmfHeight;
1123         _preview_image_width = emfWidth;
1124         _preview_image_height = emfHeight;
1126         _preview_emf_image = true;
1127     }
1129     _mutex->unlock();
1131     return ok;
1134 void FileOpenDialogImplWin32::render_preview()
1136     double x, y;
1137     const double blurRadius = 8;
1138     const double halfBlurRadius = blurRadius / 2;
1139     const int shaddowOffsetX = 0;
1140     const int shaddowOffsetY = 2;
1141     const int pagePadding = 5;
1142     const double shaddowAlpha = 0.75;
1144     // Is the preview showing?
1145     if(!_show_preview)
1146         return;
1148     // Do we have anything to render?
1149     _mutex->lock();
1151     if(!_preview_bitmap_image && !_preview_emf_image)
1152     {
1153         _mutex->unlock();
1154         return;
1155     }
1157     // Tidy up any previous bitmap renderings
1158     if(_preview_bitmap != NULL)
1159         DeleteObject(_preview_bitmap);
1160     _preview_bitmap = NULL;
1162     // Calculate the size of the caption
1163     int captionHeight = 0;
1165     if(_preview_wnd != NULL)
1166     {
1167         RECT rcCaptionRect;
1168         WCHAR szCaption[_MAX_FNAME + 32];
1169         const int iLength = format_caption(szCaption,
1170             sizeof(szCaption) / sizeof(WCHAR));
1172         HDC dc = GetDC(_preview_wnd);
1173         DrawTextW(dc, szCaption, iLength, &rcCaptionRect,
1174             DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_CALCRECT);
1175         ReleaseDC(_preview_wnd, dc);
1177         captionHeight = rcCaptionRect.bottom - rcCaptionRect.top;
1178     }
1180     // Find the minimum scale to fit the image inside the preview area
1181     const double scaleFactorX =
1182         ((double)_preview_width - pagePadding * 2 - blurRadius)  / _preview_document_width;
1183     const double scaleFactorY =
1184         ((double)_preview_height - pagePadding * 2
1185         - shaddowOffsetY - halfBlurRadius - captionHeight) / _preview_document_height;
1186     double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX;
1187     scaleFactor = (scaleFactor > 1.0) ? 1.0 : scaleFactor;
1189     // Now get the resized values
1190     const double scaledSvgWidth  = scaleFactor * _preview_document_width;
1191     const double scaledSvgHeight = scaleFactor * _preview_document_height;
1193     const int svgX = pagePadding + halfBlurRadius;
1194     const int svgY = pagePadding;
1196     const int frameX = svgX - pagePadding;
1197     const int frameY = svgY - pagePadding;
1198     const int frameWidth = scaledSvgWidth + pagePadding * 2;
1199     const int frameHeight = scaledSvgHeight + pagePadding * 2;
1201     const int totalWidth = (int)ceil(frameWidth + blurRadius);
1202     const int totalHeight = (int)ceil(frameHeight + blurRadius);
1204     // Prepare the drawing surface
1205     HDC hDC = GetDC(_preview_wnd);
1206     HDC hMemDC = CreateCompatibleDC(hDC);
1207     _preview_bitmap = CreateCompatibleBitmap(hDC, totalWidth, totalHeight);
1208     HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDC, _preview_bitmap);
1209     Cairo::RefPtr<Win32Surface> surface = Win32Surface::create(hMemDC);
1210     Cairo::RefPtr<Context> context = Context::create(surface);
1212     // Paint the background to match the dialog colour
1213     const COLORREF background = GetSysColor(COLOR_3DFACE);
1214     context->set_source_rgb(
1215         GetRValue(background) / 255.0,
1216         GetGValue(background) / 255.0,
1217         GetBValue(background) / 255.0);
1218     context->paint();
1220     //----- Draw the drop shaddow -----//
1222     // Left Edge
1223     x = frameX + shaddowOffsetX - halfBlurRadius;
1224     Cairo::RefPtr<LinearGradient> leftEdgeFade = LinearGradient::create(
1225         x, 0.0, x + blurRadius, 0.0);
1226     leftEdgeFade->add_color_stop_rgba (0, 0, 0, 0, 0);
1227     leftEdgeFade->add_color_stop_rgba (1, 0, 0, 0, shaddowAlpha);
1228     context->set_source(leftEdgeFade);
1229     context->rectangle (x, frameY + shaddowOffsetY + halfBlurRadius,
1230         blurRadius, frameHeight - blurRadius);
1231     context->fill();
1233     // Right Edge
1234     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1235     Cairo::RefPtr<LinearGradient> rightEdgeFade = LinearGradient::create(
1236         x, 0.0,    x + blurRadius, 0.0);
1237     rightEdgeFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1238     rightEdgeFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1239     context->set_source(rightEdgeFade);
1240     context->rectangle (frameX + frameWidth + shaddowOffsetX - halfBlurRadius,
1241         frameY + shaddowOffsetY + halfBlurRadius,
1242         blurRadius, frameHeight - blurRadius);
1243     context->fill();
1245     // Top Edge
1246     y = frameY + shaddowOffsetY - halfBlurRadius;
1247     Cairo::RefPtr<LinearGradient> topEdgeFade = LinearGradient::create(
1248         0.0, y, 0.0, y + blurRadius);
1249     topEdgeFade->add_color_stop_rgba (0, 0, 0, 0, 0);
1250     topEdgeFade->add_color_stop_rgba (1, 0, 0, 0, shaddowAlpha);
1251     context->set_source(topEdgeFade);
1252     context->rectangle (frameX + shaddowOffsetX + halfBlurRadius, y,
1253         frameWidth - blurRadius, blurRadius);
1254     context->fill();
1256     // Bottom Edge
1257     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1258     Cairo::RefPtr<LinearGradient> bottomEdgeFade = LinearGradient::create(
1259         0.0, y,    0.0, y + blurRadius);
1260     bottomEdgeFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1261     bottomEdgeFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1262     context->set_source(bottomEdgeFade);
1263     context->rectangle (frameX + shaddowOffsetX + halfBlurRadius, y,
1264         frameWidth - blurRadius, blurRadius);
1265     context->fill();
1267     // Top Left Corner
1268     x = frameX + shaddowOffsetX - halfBlurRadius;
1269     y = frameY + shaddowOffsetY - halfBlurRadius;
1270     Cairo::RefPtr<RadialGradient> topLeftCornerFade = RadialGradient::create(
1271         x + blurRadius, y + blurRadius, 0, x + blurRadius, y + blurRadius, blurRadius);
1272     topLeftCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1273     topLeftCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1274     context->set_source(topLeftCornerFade);
1275     context->rectangle (x, y, blurRadius, blurRadius);
1276     context->fill();
1278     // Top Right Corner
1279     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1280     y = frameY + shaddowOffsetY - halfBlurRadius;
1281     Cairo::RefPtr<RadialGradient> topRightCornerFade = RadialGradient::create(
1282         x, y + blurRadius, 0, x, y + blurRadius, blurRadius);
1283     topRightCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1284     topRightCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1285     context->set_source(topRightCornerFade);
1286     context->rectangle (x, y, blurRadius, blurRadius);
1287     context->fill();
1289     // Bottom Left Corner
1290     x = frameX + shaddowOffsetX - halfBlurRadius;
1291     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1292     Cairo::RefPtr<RadialGradient> bottomLeftCornerFade = RadialGradient::create(
1293         x + blurRadius, y, 0, x + blurRadius, y, blurRadius);
1294     bottomLeftCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1295     bottomLeftCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1296     context->set_source(bottomLeftCornerFade);
1297     context->rectangle (x, y, blurRadius, blurRadius);
1298     context->fill();
1300     // Bottom Right Corner
1301     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1302     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1303     Cairo::RefPtr<RadialGradient> bottomRightCornerFade = RadialGradient::create(
1304         x, y, 0, x, y, blurRadius);
1305     bottomRightCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1306     bottomRightCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1307     context->set_source(bottomRightCornerFade);
1308     context->rectangle (frameX + frameWidth + shaddowOffsetX - halfBlurRadius,
1309         frameY + frameHeight + shaddowOffsetY - halfBlurRadius,
1310         blurRadius, blurRadius);
1311     context->fill();
1313     // Draw the frame
1314     context->set_line_width(1);
1315     context->rectangle (frameX, frameY,    frameWidth, frameHeight);
1317     context->set_source_rgb(1.0, 1.0, 1.0);
1318     context->fill_preserve();
1319     context->set_source_rgb(0.25, 0.25, 0.25);
1320     context->stroke_preserve();
1322     // Draw the image
1323     if(_preview_bitmap_image)    // Is the image a pixbuf?
1324     {
1325         // Set the transformation
1326         const Matrix matrix = {
1327             scaleFactor, 0,
1328             0, scaleFactor,
1329             svgX, svgY };
1330         context->set_matrix (matrix);
1332         // Render the image
1333         set_source_pixbuf (context, _preview_bitmap_image, 0, 0);
1334         context->paint();
1336         // Reset the transformation
1337         context->set_identity_matrix();
1338     }
1340     // Draw the inner frame
1341     context->set_source_rgb(0.75, 0.75, 0.75);
1342     context->rectangle (svgX, svgY,    scaledSvgWidth, scaledSvgHeight);
1343     context->stroke();
1345     _mutex->unlock();
1347     // Finish drawing
1348     surface->finish();
1350     if (_preview_emf_image) {
1351         HENHMETAFILE hemf = MyGetEnhMetaFileW(_path_string);
1352         if (hemf) {
1353             RECT rc;
1354             rc.top = svgY+2;
1355             rc.left = svgX+2;
1356             rc.bottom = scaledSvgHeight-2;
1357             rc.right = scaledSvgWidth-2;
1358             PlayEnhMetaFile(hMemDC, hemf, &rc);
1359             DeleteEnhMetaFile(hemf);
1360         }
1361     }
1363     SelectObject(hMemDC, hOldBitmap) ;
1364     DeleteDC(hMemDC);
1366     // Refresh the preview pane
1367     InvalidateRect(_preview_wnd, NULL, FALSE);
1370 int FileOpenDialogImplWin32::format_caption(wchar_t *caption, int caption_size)
1372     wchar_t szFileName[_MAX_FNAME];
1373     _wsplitpath(_path_string, NULL, NULL, szFileName, NULL);
1375     return snwprintf(caption, caption_size,
1376         L"%s\n%d kB\n%d \xD7 %d", szFileName, _preview_file_size,
1377         (int)_preview_document_width, (int)_preview_document_height);
1380 /**
1381  * Show this dialog modally.  Return true if user hits [OK]
1382  */
1383 bool
1384 FileOpenDialogImplWin32::show()
1386     // We can only run one worker thread at a time
1387     if(_mutex != NULL) return false;
1389     if(!Glib::thread_supported())
1390         Glib::thread_init();
1392     _result = false;
1393     _finished = false;
1394     _file_selected = false;
1395     _mutex = new Glib::Mutex();
1396     _main_loop = g_main_loop_new(g_main_context_default(), FALSE);
1398     if(Glib::Thread::create(sigc::mem_fun(*this, &FileOpenDialogImplWin32::GetOpenFileName_thread), true))
1399     {
1400         while(1)
1401         {
1402             g_main_context_iteration(g_main_context_default(), FALSE);
1404             if(_mutex->trylock())
1405             {
1406                 // Read mutexed data
1407                 const bool finished = _finished;
1408                 const bool is_file_selected = _file_selected;
1409                 _file_selected = false;
1410                 _mutex->unlock();
1412                 if(finished) break;
1413                 if(is_file_selected) file_selected();
1414             }
1416             Sleep(10);
1417         }
1418     }
1420     // Tidy up
1421     delete _mutex;
1422     _mutex = NULL;
1424     return _result;
1427 /**
1428  * To Get Multiple filenames selected at-once.
1429  */
1430 std::vector<Glib::ustring>FileOpenDialogImplWin32::getFilenames()
1432     std::vector<Glib::ustring> result;
1433     result.push_back(getFilename());
1434     return result;
1438 /*#########################################################################
1439 ### F I L E    S A V E
1440 #########################################################################*/
1442 /**
1443  * Constructor
1444  */
1445 FileSaveDialogImplWin32::FileSaveDialogImplWin32(Gtk::Window &parent,
1446             const Glib::ustring &dir,
1447             FileDialogType fileTypes,
1448             const char *title,
1449             const Glib::ustring &/*default_key*/,
1450             const char *docTitle) :
1451     FileDialogBaseWin32(parent, dir, title, fileTypes, "dialogs.save_as"),
1452         _title_label(NULL),
1453         _title_edit(NULL)
1455     FileSaveDialog::myDocTitle = docTitle;
1456     createFilterMenu();
1459 FileSaveDialogImplWin32::~FileSaveDialogImplWin32()
1463 void FileSaveDialogImplWin32::createFilterMenu()
1465     list<Filter> filter_list;
1467     knownExtensions.clear();
1469     // Compose the filter string
1470     Glib::ustring all_inkscape_files_filter, all_image_files_filter;
1471     Inkscape::Extension::DB::OutputList extension_list;
1472     Inkscape::Extension::db.get_output_list(extension_list);
1474     int filter_count = 0;
1475     int filter_length = 1;
1477     for (Inkscape::Extension::DB::OutputList::iterator current_item = extension_list.begin();
1478          current_item != extension_list.end(); current_item++)
1479     {
1480         Inkscape::Extension::Output *omod = *current_item;
1481         if (omod->deactivated()) continue;
1483         filter_count++;
1485         Filter filter;
1487         // Extension
1488         const gchar *filter_extension = omod->get_extension();
1489         filter.filter = g_utf8_to_utf16(
1490             filter_extension, -1, NULL, &filter.filter_length, NULL);
1491         knownExtensions.insert( Glib::ustring(filter_extension).casefold() );
1493         // Type
1494         filter.name = g_utf8_to_utf16(
1495             _(omod->get_filetypename()), -1, NULL, &filter.name_length, NULL);
1497         filter.mod = omod;
1499         filter_length += filter.name_length +
1500             filter.filter_length + 3;   // Add 3 for two \0s and a *
1502         filter_list.push_back(filter);
1503     }
1505     int extension_index = 0;
1506     _extension_map = new Inkscape::Extension::Extension*[filter_count];
1508     _filter = new wchar_t[filter_length];
1509     wchar_t *filterptr = _filter;
1511     for(list<Filter>::iterator filter_iterator = filter_list.begin();
1512         filter_iterator != filter_list.end(); filter_iterator++)
1513     {
1514         const Filter &filter = *filter_iterator;
1516         wcsncpy(filterptr, (wchar_t*)filter.name, filter.name_length);
1517         filterptr += filter.name_length;
1518         g_free(filter.name);
1520         *(filterptr++) = L'\0';
1521         *(filterptr++) = L'*';
1523         wcsncpy(filterptr, (wchar_t*)filter.filter, filter.filter_length);
1524         filterptr += filter.filter_length;
1525         g_free(filter.filter);
1527         *(filterptr++) = L'\0';
1529         // Associate this input extension with the file type name
1530         _extension_map[extension_index++] = filter.mod;
1531     }
1532     *(filterptr++) = 0;
1534         _filter_count = extension_index;
1535     _filter_index = 1;  // A value of 1 selects the 1st filter - NOT the 2nd
1538 void FileSaveDialogImplWin32::GetSaveFileName_thread()
1540     OPENFILENAMEEXW ofn;
1542     g_assert(this != NULL);
1543     g_assert(_main_loop != NULL);
1545     WCHAR* current_directory_string = (WCHAR*)g_utf8_to_utf16(
1546         _current_directory.data(), _current_directory.length(),
1547                 NULL, NULL, NULL);
1549     // Copy the selected file name, converting from UTF-8 to UTF-16
1550     memset(_path_string, 0, sizeof(_path_string));
1551     gunichar2* utf16_path_string = g_utf8_to_utf16(
1552         myFilename.data(), -1, NULL, NULL, NULL);
1553     wcsncpy(_path_string, (wchar_t*)utf16_path_string, _MAX_PATH);
1554     g_free(utf16_path_string);
1556     ZeroMemory(&ofn, sizeof(ofn));
1557     ofn.lStructSize = sizeof(ofn);
1558     ofn.hwndOwner = _ownerHwnd;
1559     ofn.lpstrFile = _path_string;
1560     ofn.nMaxFile = _MAX_PATH;
1561     ofn.nFilterIndex = _filter_index;
1562     ofn.lpstrFileTitle = NULL;
1563     ofn.nMaxFileTitle = 0;
1564     ofn.lpstrInitialDir = current_directory_string;
1565     ofn.lpstrTitle = _title;
1566     ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ENABLEHOOK;
1567     ofn.lpstrFilter = _filter;
1568     ofn.nFilterIndex = _filter_index;
1569     ofn.lpfnHook = GetSaveFileName_hookproc;
1570     ofn.lCustData = (LPARAM)this;
1572     _result = GetSaveFileNameW(&ofn) != 0;
1574         g_assert(ofn.nFilterIndex >= 1 && ofn.nFilterIndex <= _filter_count);
1575     _filter_index = ofn.nFilterIndex;
1576     _extension = _extension_map[ofn.nFilterIndex - 1];
1578     // Copy the selected file name, converting from UTF-16 to UTF-8
1579     myFilename = utf16_to_ustring(_path_string, _MAX_PATH);
1581     // Tidy up
1582     g_free(current_directory_string);
1584     g_main_loop_quit(_main_loop);
1587 /**
1588  * Show this dialog modally.  Return true if user hits [OK]
1589  */
1590 bool
1591 FileSaveDialogImplWin32::show()
1593     if(!Glib::thread_supported())
1594         Glib::thread_init();
1596     _result = false;
1597     _main_loop = g_main_loop_new(g_main_context_default(), FALSE);
1599         if(_main_loop != NULL)
1600         {
1601             if(Glib::Thread::create(sigc::mem_fun(*this, &FileSaveDialogImplWin32::GetSaveFileName_thread), true))
1602                 g_main_loop_run(_main_loop);
1604             if(_result)
1605                 appendExtension(myFilename, (Inkscape::Extension::Output*)_extension);
1606         }
1608     return _result;
1611 void FileSaveDialogImplWin32::setSelectionType( Inkscape::Extension::Extension * /*key*/ )
1613     // If no pointer to extension is passed in, look up based on filename extension.
1617 UINT_PTR CALLBACK FileSaveDialogImplWin32::GetSaveFileName_hookproc(
1618     HWND hdlg, UINT uiMsg, WPARAM, LPARAM lParam)
1620     FileSaveDialogImplWin32 *pImpl = (FileSaveDialogImplWin32*)
1621         GetWindowLongPtr(hdlg, GWLP_USERDATA);
1623     switch(uiMsg)
1624     {
1625     case WM_INITDIALOG:
1626         {
1627             HWND hParentWnd = GetParent(hdlg);
1628             HINSTANCE hInstance = GetModuleHandle(NULL);
1630             // get size/pos of typical combo box
1631             RECT rEDT1, rCB1, rROOT, rST;
1632             GetWindowRect(GetDlgItem(hParentWnd, cmb1), &rCB1);
1633             GetWindowRect(GetDlgItem(hParentWnd, cmb13), &rEDT1);
1634             GetWindowRect(GetDlgItem(hParentWnd, stc2), &rST);
1635             GetWindowRect(hdlg, &rROOT);
1636             int ydelta = rCB1.top - rEDT1.top;
1638             // Make the window a bit longer
1639             RECT rcRect;
1640             GetWindowRect(hParentWnd, &rcRect);
1641             MoveWindow(hParentWnd, rcRect.left, rcRect.top, rcRect.right - rcRect.left,
1642                        rcRect.bottom - rcRect.top + ydelta, FALSE);
1644             // It is not necessary to delete stock objects by calling DeleteObject
1645             HGDIOBJ dlgFont = GetStockObject(DEFAULT_GUI_FONT);
1647             // Set the pointer to the object
1648             OPENFILENAMEW *ofn = (OPENFILENAMEW*)lParam;
1649             SetWindowLongPtr(hdlg, GWLP_USERDATA, ofn->lCustData);
1650             SetWindowLongPtr(hParentWnd, GWLP_USERDATA, ofn->lCustData);
1651             pImpl = (FileSaveDialogImplWin32*)ofn->lCustData;
1653             // Create the Title label and edit control
1654             pImpl->_title_label = CreateWindowEx(NULL, "STATIC", "Title:",
1655                                         WS_VISIBLE|WS_CHILD,
1656                                         CW_USEDEFAULT, CW_USEDEFAULT, rCB1.left-rST.left, rST.bottom-rST.top,
1657                                         hParentWnd, NULL, hInstance, NULL);
1658             if(pImpl->_title_label) {
1659               if(dlgFont) SendMessage(pImpl->_title_label, WM_SETFONT, (WPARAM)dlgFont, MAKELPARAM(FALSE, 0));
1660               SetWindowPos(pImpl->_title_label, NULL, rST.left-rROOT.left, rST.top+ydelta-rROOT.top,
1661                            rCB1.left-rST.left, rST.bottom-rST.top, SWP_SHOWWINDOW|SWP_NOZORDER);
1662             }
1664             pImpl->_title_edit = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "",
1665                                         WS_VISIBLE|WS_CHILD|WS_TABSTOP|ES_AUTOHSCROLL,
1666                                         CW_USEDEFAULT, CW_USEDEFAULT, rCB1.right-rCB1.left, rCB1.bottom-rCB1.top,
1667                                         hParentWnd, NULL, hInstance, NULL);
1668             if(pImpl->_title_edit) {
1669               if(dlgFont) SendMessage(pImpl->_title_edit, WM_SETFONT, (WPARAM)dlgFont, MAKELPARAM(FALSE, 0));
1670               SetWindowPos(pImpl->_title_edit, NULL, rCB1.left-rROOT.left, rCB1.top+ydelta-rROOT.top,
1671                            rCB1.right-rCB1.left, rCB1.bottom-rCB1.top, SWP_SHOWWINDOW|SWP_NOZORDER);
1672               // TODO: make sure this works for Unicode
1673               SetWindowText(pImpl->_title_edit, pImpl->myDocTitle.c_str());
1674             }
1675         }
1676         break;
1677     case WM_DESTROY:
1678       {
1679         if(pImpl->_title_edit) {
1680           int length = GetWindowTextLength(pImpl->_title_edit)+1;
1681           char* temp_title = new char[length];
1682           GetWindowText(pImpl->_title_edit, temp_title, length);
1683           pImpl->myDocTitle = temp_title;
1684           delete[] temp_title;
1685           DestroyWindow(pImpl->_title_label);
1686           pImpl->_title_label = NULL;
1687           DestroyWindow(pImpl->_title_edit);
1688           pImpl->_title_edit = NULL;
1689         }
1690       }
1691       break;
1692     }
1694     // Use default dialog behaviour
1695     return 0;
1702 #endif
1704 /*
1705   Local Variables:
1706   mode:c++
1707   c-file-style:"stroustrup"
1708   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1709   indent-tabs-mode:nil
1710   fill-column:99
1711   End:
1712 */
1713 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :