Code

Win32 post-GSoC fixups.
[inkscape.git] / src / ui / dialog / filedialogimpl-win32.cpp
1 /** @file
2  * @brief Implementation of native file dialogs for Win32
3  */
4 /* Authors:
5  *   Joel Holdsworth
6  *   The Inkscape Organization
7  *   Abhishek Sharma
8  *
9  * Copyright (C) 2004-2008 The Inkscape Organization
10  *
11  * Released under GNU GPL, read the file 'COPYING' for more information
12  */
13 #ifdef WIN32
15 #ifdef HAVE_CONFIG_H
16 # include <config.h>
17 #endif
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 <dialogs/dialog-events.h>
33 #include <extension/input.h>
34 #include <extension/output.h>
35 #include <extension/db.h>
37 #include <libnr/nr-pixops.h>
38 #include <libnr/nr-translate-scale-ops.h>
39 #include <display/nr-arena-item.h>
40 #include <display/nr-arena.h>
41 #include "sp-item.h"
42 #include "display/canvas-arena.h"
44 #include "filedialog.h"
45 #include "filedialogimpl-win32.h"
47 #include <zlib.h>
48 #include <cairomm/win32_surface.h>
49 #include <cairomm/context.h>
51 using namespace std;
52 using namespace Glib;
53 using namespace Cairo;
54 using namespace Gdk::Cairo;
56 namespace Inkscape
57 {
58 namespace UI
59 {
60 namespace Dialog
61 {
63 const int PREVIEW_WIDENING = 150;
64 const int WINDOW_WIDTH_MINIMUM = 32;
65 const int WINDOW_WIDTH_FALLBACK = 450;
66 const int WINDOW_HEIGHT_MINIMUM = 32;
67 const int WINDOW_HEIGHT_FALLBACK = 360;
68 const char PreviewWindowClassName[] = "PreviewWnd";
69 const unsigned long MaxPreviewFileSize = 10240; // kB
71 #define IDC_SHOW_PREVIEW    1000
73 // Windows 2000 version of OPENFILENAMEW
74 struct OPENFILENAMEEXW : public OPENFILENAMEW {
75   void *        pvReserved;
76   DWORD         dwReserved;
77   DWORD         FlagsEx;
78 };
80 struct Filter
81 {
82     gunichar2* name;
83     glong name_length;
84     gunichar2* filter;
85     glong filter_length;
86     Inkscape::Extension::Extension* mod;
87 };
89 ustring utf16_to_ustring(const wchar_t *utf16string, int utf16length = -1)
90 {
91     gchar *utf8string = g_utf16_to_utf8((const gunichar2*)utf16string,
92         utf16length, NULL, NULL, NULL);
93     ustring result(utf8string);
94     g_free(utf8string);
96     return result;
97 }
99 namespace {
101 int sanitizeWindowSizeParam( int size, int delta, int minimum, int fallback )
103     int result = size;
104     if ( size < minimum ) {
105         g_warning( "Window size %d is less than cutoff.", size );
106         result = fallback - delta;
107     }
108     result += delta;
109     return result;
112 } // namespace
114 /*#########################################################################
115 ### F I L E     D I A L O G    B A S E    C L A S S
116 #########################################################################*/
118 FileDialogBaseWin32::FileDialogBaseWin32(Gtk::Window &parent,
119         const Glib::ustring &dir, const gchar *title,
120         FileDialogType type, gchar const* /*preferenceBase*/) :
121         dialogType(type),
122         parent(parent),
123         _current_directory(dir)
125     _main_loop = NULL;
127         _filter_index = 1;
128         _filter_count = 0;
130     _title = (wchar_t*)g_utf8_to_utf16(title, -1, NULL, NULL, NULL);
131         g_assert(_title != NULL);
133     Glib::RefPtr<const Gdk::Window> parentWindow = parent.get_window();
134     g_assert(parentWindow->gobj() != NULL);
135     _ownerHwnd = (HWND)gdk_win32_drawable_get_handle((GdkDrawable*)parentWindow->gobj());
138 FileDialogBaseWin32::~FileDialogBaseWin32()
140     g_free(_title);
143 Inkscape::Extension::Extension *FileDialogBaseWin32::getSelectionType()
145     return _extension;
148 Glib::ustring FileDialogBaseWin32::getCurrentDirectory()
150     return _current_directory;
153 /*#########################################################################
154 ### F I L E    O P E N
155 #########################################################################*/
157 bool FileOpenDialogImplWin32::_show_preview = true;
159 /**
160  * Constructor.  Not called directly.  Use the factory.
161  */
162 FileOpenDialogImplWin32::FileOpenDialogImplWin32(Gtk::Window &parent,
163                                        const Glib::ustring &dir,
164                                        FileDialogType fileTypes,
165                                        const gchar *title) :
166     FileDialogBaseWin32(parent, dir, title, fileTypes, "dialogs.open")
168     // Initalize to Autodetect
169     _extension = NULL;
171     // Set our dialog type (open, import, etc...)
172     dialogType = fileTypes;
174     _show_preview_button_bitmap = NULL;
175     _preview_wnd = NULL;
176     _file_dialog_wnd = NULL;
177     _base_window_proc = NULL;
179     _preview_file_size = 0;
180     _preview_bitmap = NULL;
181     _preview_file_icon = NULL;
182     _preview_document_width = 0;
183     _preview_document_height = 0;
184     _preview_image_width = 0;
185     _preview_image_height = 0;
186     _preview_emf_image = false;
188         _mutex = NULL;
190     createFilterMenu();
194 /**
195  * Destructor
196  */
197 FileOpenDialogImplWin32::~FileOpenDialogImplWin32()
199     if(_filter != NULL)
200         delete[] _filter;
201     if(_extension_map != NULL)
202         delete[] _extension_map;
205 void FileOpenDialogImplWin32::createFilterMenu()
207     list<Filter> filter_list;
209     // Compose the filter string
210     Inkscape::Extension::DB::InputList extension_list;
211     Inkscape::Extension::db.get_input_list(extension_list);
213     ustring all_inkscape_files_filter, all_image_files_filter, all_vectors_filter, all_bitmaps_filter;
214     Filter all_files, all_inkscape_files, all_image_files, all_vectors, all_bitmaps;
216     const gchar *all_files_filter_name = _("All Files");
217     const gchar *all_inkscape_files_filter_name = _("All Inkscape Files");
218     const gchar *all_image_files_filter_name = _("All Images");
219     const gchar *all_vectors_filter_name = _("All Vectors");
220     const gchar *all_bitmaps_filter_name = _("All Bitmaps");
222     // Calculate the amount of memory required
223     int filter_count = 5;       // 5 - one for each filter type
224     int filter_length = 1;
226     for (Inkscape::Extension::DB::InputList::iterator current_item = extension_list.begin();
227          current_item != extension_list.end(); current_item++)
228     {
229         Filter filter;
231         Inkscape::Extension::Input *imod = *current_item;
232         if (imod->deactivated()) continue;
234         // Type
235         filter.name = g_utf8_to_utf16(_(imod->get_filetypename()),
236             -1, NULL, &filter.name_length, NULL);
238         // Extension
239         const gchar *file_extension_name = imod->get_extension();
240         filter.filter = g_utf8_to_utf16(file_extension_name,
241             -1, NULL, &filter.filter_length, NULL);
243         filter.mod = imod;
244         filter_list.push_back(filter);
246         filter_length += filter.name_length +
247             filter.filter_length + 3;   // Add 3 for two \0s and a *
249         // Add to the "All Inkscape Files" Entry
250         if(all_inkscape_files_filter.length() > 0)
251             all_inkscape_files_filter += ";*";
252         all_inkscape_files_filter += file_extension_name;
253         if( strncmp("image", imod->get_mimetype(), 5) == 0)
254         {
255             // Add to the "All Image Files" Entry
256             if(all_image_files_filter.length() > 0)
257                 all_image_files_filter += ";*";
258             all_image_files_filter += file_extension_name;
259         }
261         // I don't know of any other way to define "bitmap" formats other than by listing them
262         // if you change it here, do the same change in filedialogimpl-gtkmm
263         if ( 
264             strncmp("image/png", imod->get_mimetype(), 9)==0 ||
265             strncmp("image/jpeg", imod->get_mimetype(), 10)==0 ||
266             strncmp("image/gif", imod->get_mimetype(), 9)==0 ||
267             strncmp("image/x-icon", imod->get_mimetype(), 12)==0 ||
268             strncmp("image/x-navi-animation", imod->get_mimetype(), 22)==0 ||
269             strncmp("image/x-cmu-raster", imod->get_mimetype(), 18)==0 ||
270             strncmp("image/x-xpixmap", imod->get_mimetype(), 15)==0 ||
271             strncmp("image/bmp", imod->get_mimetype(), 9)==0 ||
272             strncmp("image/vnd.wap.wbmp", imod->get_mimetype(), 18)==0 ||
273             strncmp("image/tiff", imod->get_mimetype(), 10)==0 ||
274             strncmp("image/x-xbitmap", imod->get_mimetype(), 15)==0 ||
275             strncmp("image/x-tga", imod->get_mimetype(), 11)==0 ||
276             strncmp("image/x-pcx", imod->get_mimetype(), 11)==0 
277             ) {
278             if(all_bitmaps_filter.length() > 0)
279                 all_bitmaps_filter += ";*";
280             all_bitmaps_filter += file_extension_name;
281         } else {
282             if(all_vectors_filter.length() > 0)
283                 all_vectors_filter += ";*";
284             all_vectors_filter += file_extension_name;
285         }
287         filter_count++;
288     }
290     int extension_index = 0;
291     _extension_map = new Inkscape::Extension::Extension*[filter_count];
293     // Filter bitmap files
294     all_bitmaps.name = g_utf8_to_utf16(all_bitmaps_filter_name,
295         -1, NULL, &all_bitmaps.name_length, NULL);
296     all_bitmaps.filter = g_utf8_to_utf16(all_bitmaps_filter.data(),
297             -1, NULL, &all_bitmaps.filter_length, NULL);
298         all_bitmaps.mod = NULL;
299     filter_list.push_front(all_bitmaps);
301     // Filter vector files
302     all_vectors.name = g_utf8_to_utf16(all_vectors_filter_name,
303         -1, NULL, &all_vectors.name_length, NULL);
304     all_vectors.filter = g_utf8_to_utf16(all_vectors_filter.data(),
305             -1, NULL, &all_vectors.filter_length, NULL);
306         all_vectors.mod = NULL;
307     filter_list.push_front(all_vectors);
309     // Filter Image Files
310     all_image_files.name = g_utf8_to_utf16(all_image_files_filter_name,
311         -1, NULL, &all_image_files.name_length, NULL);
312     all_image_files.filter = g_utf8_to_utf16(all_image_files_filter.data(),
313             -1, NULL, &all_image_files.filter_length, NULL);
314         all_image_files.mod = NULL;
315     filter_list.push_front(all_image_files);
317     // Filter Inkscape Files
318     all_inkscape_files.name = g_utf8_to_utf16(all_inkscape_files_filter_name,
319         -1, NULL, &all_inkscape_files.name_length, NULL);
320     all_inkscape_files.filter = g_utf8_to_utf16(all_inkscape_files_filter.data(),
321             -1, NULL, &all_inkscape_files.filter_length, NULL);
322         all_inkscape_files.mod = NULL;
323     filter_list.push_front(all_inkscape_files);
325     // Filter All Files
326     all_files.name = g_utf8_to_utf16(all_files_filter_name,
327         -1, NULL, &all_files.name_length, NULL);
328     all_files.filter = NULL;
329     all_files.filter_length = 0;
330         all_files.mod = NULL;
331     filter_list.push_front(all_files);
333     filter_length += all_files.name_length + 3 +
334                     all_inkscape_files.filter_length +
335                     all_inkscape_files.name_length + 3 +
336                     all_image_files.filter_length +
337                     all_image_files.name_length + 3 +
338                     all_vectors.filter_length +
339                     all_vectors.name_length + 3 +
340                     all_bitmaps.filter_length +
341                     all_bitmaps.name_length + 3 +
342                                                   1;
343      // Add 3 for 2*2 \0s and a *, and 1 for a trailing \0
345         _filter = new wchar_t[filter_length];
346     wchar_t *filterptr = _filter;
348     for(list<Filter>::iterator filter_iterator = filter_list.begin();
349         filter_iterator != filter_list.end(); filter_iterator++)
350     {
351         const Filter &filter = *filter_iterator;
353         wcsncpy(filterptr, (wchar_t*)filter.name, filter.name_length);
354         filterptr += filter.name_length;
355         g_free(filter.name);
357         *(filterptr++) = L'\0';
358         *(filterptr++) = L'*';
360         if(filter.filter != NULL)
361         {
362             wcsncpy(filterptr, (wchar_t*)filter.filter, filter.filter_length);
363             filterptr += filter.filter_length;
364             g_free(filter.filter);
365         }
367         *(filterptr++) = L'\0';
369         // Associate this input extension with the file type name
370         _extension_map[extension_index++] = filter.mod;
371     }
372     *(filterptr++) = L'\0';
374         _filter_count = extension_index;
375     _filter_index = 2;  // Select the 2nd filter in the list - 2 is NOT the 3rd
378 void FileOpenDialogImplWin32::GetOpenFileName_thread()
380     OPENFILENAMEEXW ofn;
382     g_assert(this != NULL);
383         g_assert(_mutex != NULL);
385     WCHAR* current_directory_string = (WCHAR*)g_utf8_to_utf16(
386         _current_directory.data(), _current_directory.length(),
387                 NULL, NULL, NULL);
389     memset(&ofn, 0, sizeof(ofn));
391     // Copy the selected file name, converting from UTF-8 to UTF-16
392     memset(_path_string, 0, sizeof(_path_string));
393     gunichar2* utf16_path_string = g_utf8_to_utf16(
394         myFilename.data(), -1, NULL, NULL, NULL);
395     wcsncpy(_path_string, (wchar_t*)utf16_path_string, _MAX_PATH);
396     g_free(utf16_path_string);
398     ofn.lStructSize = sizeof(ofn);
399     ofn.hwndOwner = _ownerHwnd;
400     ofn.lpstrFile = _path_string;
401     ofn.nMaxFile = _MAX_PATH;
402     ofn.lpstrFileTitle = NULL;
403     ofn.nMaxFileTitle = 0;
404     ofn.lpstrInitialDir = current_directory_string;
405     ofn.lpstrTitle = _title;
406     ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ENABLEHOOK | OFN_HIDEREADONLY | OFN_ENABLESIZING;
407     ofn.lpstrFilter = _filter;
408     ofn.nFilterIndex = _filter_index;
409     ofn.lpfnHook = GetOpenFileName_hookproc;
410     ofn.lCustData = (LPARAM)this;
412     _result = GetOpenFileNameW(&ofn) != 0;
414         g_assert(ofn.nFilterIndex >= 1 && ofn.nFilterIndex <= _filter_count);
415     _filter_index = ofn.nFilterIndex;
416     _extension = _extension_map[ofn.nFilterIndex - 1];
418     // Copy the selected file name, converting from UTF-16 to UTF-8
419     myFilename = utf16_to_ustring(_path_string, _MAX_PATH);
421     // Tidy up
422     g_free(current_directory_string);
424     _mutex->lock();
425     _finished = true;
426     _mutex->unlock();
429 void FileOpenDialogImplWin32::register_preview_wnd_class()
431     HINSTANCE hInstance = GetModuleHandle(NULL);
432     const WNDCLASSA PreviewWndClass =
433     {
434         CS_HREDRAW | CS_VREDRAW,
435         preview_wnd_proc,
436         0,
437         0,
438         hInstance,
439         NULL,
440         LoadCursor(hInstance, IDC_ARROW),
441         (HBRUSH)(COLOR_BTNFACE + 1),
442         NULL,
443         PreviewWindowClassName
444     };
446     RegisterClassA(&PreviewWndClass);
449 UINT_PTR CALLBACK FileOpenDialogImplWin32::GetOpenFileName_hookproc(
450     HWND hdlg, UINT uiMsg, WPARAM, LPARAM lParam)
452     FileOpenDialogImplWin32 *pImpl = (FileOpenDialogImplWin32*)
453         GetWindowLongPtr(hdlg, GWLP_USERDATA);
455     switch(uiMsg)
456     {
457     case WM_INITDIALOG:
458         {
459             HWND hParentWnd = GetParent(hdlg);
460             HINSTANCE hInstance = GetModuleHandle(NULL);
462             // Make the window a bit wider
463             RECT rcRect;
464             GetWindowRect(hParentWnd, &rcRect);
465             MoveWindow(hParentWnd, rcRect.left, rcRect.top,
466                        rcRect.right - rcRect.left + PREVIEW_WIDENING,
467                        rcRect.bottom - rcRect.top,
468                        FALSE);
470             // Set the pointer to the object
471             OPENFILENAMEW *ofn = (OPENFILENAMEW*)lParam;
472             SetWindowLongPtr(hdlg, GWLP_USERDATA, ofn->lCustData);
473             SetWindowLongPtr(hParentWnd, GWLP_USERDATA, ofn->lCustData);
474             pImpl = (FileOpenDialogImplWin32*)ofn->lCustData;
476             // Subclass the parent
477             pImpl->_base_window_proc = (WNDPROC)GetWindowLongPtr(hParentWnd, GWLP_WNDPROC);
478             SetWindowLongPtr(hParentWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(file_dialog_subclass_proc));
480             // Add a button to the toolbar
481             pImpl->_toolbar_wnd = FindWindowEx(hParentWnd, NULL, "ToolbarWindow32", NULL);
483             pImpl->_show_preview_button_bitmap = LoadBitmap(
484                 hInstance, MAKEINTRESOURCE(IDC_SHOW_PREVIEW));
485             TBADDBITMAP tbAddBitmap = {NULL, reinterpret_cast<UINT_PTR>(pImpl->_show_preview_button_bitmap)};
486             const int iBitmapIndex = SendMessage(pImpl->_toolbar_wnd,
487                 TB_ADDBITMAP, 1, (LPARAM)&tbAddBitmap);
489             TBBUTTON tbButton;
490             memset(&tbButton, 0, sizeof(TBBUTTON));
491             tbButton.iBitmap = iBitmapIndex;
492             tbButton.idCommand = IDC_SHOW_PREVIEW;
493             tbButton.fsState = (pImpl->_show_preview ? TBSTATE_CHECKED : 0)
494                 | TBSTATE_ENABLED;
495             tbButton.fsStyle = TBSTYLE_CHECK;
496             tbButton.iString = (INT_PTR)_("Show Preview");
497             SendMessage(pImpl->_toolbar_wnd, TB_ADDBUTTONS, 1, (LPARAM)&tbButton);
499             // Create preview pane
500             register_preview_wnd_class();
502             pImpl->_mutex->lock();
504                 pImpl->_file_dialog_wnd = hParentWnd;
506                 pImpl->_preview_wnd =
507                     CreateWindowA(PreviewWindowClassName, "",
508                         WS_CHILD | WS_VISIBLE,
509                         0, 0, 100, 100, hParentWnd, NULL, hInstance, NULL);
510                 SetWindowLongPtr(pImpl->_preview_wnd, GWLP_USERDATA, ofn->lCustData);
512             pImpl->_mutex->unlock();
514             pImpl->layout_dialog();
515         }
516         break;
518     case WM_NOTIFY:
519         {
521         OFNOTIFY *pOFNotify = reinterpret_cast<OFNOTIFY*>(lParam);
522         switch(pOFNotify->hdr.code)
523         {
524         case CDN_SELCHANGE:
525             {
526                 if(pImpl != NULL)
527                 {
528                     // Get the file name
529                     pImpl->_mutex->lock();
531                     SendMessage(pOFNotify->hdr.hwndFrom, CDM_GETFILEPATH,
532                         sizeof(pImpl->_path_string) / sizeof(wchar_t),
533                         (LPARAM)pImpl->_path_string);
535                     pImpl->_file_selected = true;
537                     pImpl->_mutex->unlock();
538                 }
539             }
540             break;
541         }
542         }
543         break;
545     case WM_CLOSE:
546         pImpl->_mutex->lock();
547         pImpl->_preview_file_size = 0;
549         pImpl->_file_dialog_wnd = NULL;
550         DestroyWindow(pImpl->_preview_wnd);
551         pImpl->_preview_wnd = NULL;
552         DeleteObject(pImpl->_show_preview_button_bitmap);
553         pImpl->_show_preview_button_bitmap = NULL;
554         pImpl->_mutex->unlock();
556         break;
557     }
559     // Use default dialog behaviour
560     return 0;
563 LRESULT CALLBACK FileOpenDialogImplWin32::file_dialog_subclass_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
565     FileOpenDialogImplWin32 *pImpl = (FileOpenDialogImplWin32*)
566         GetWindowLongPtr(hwnd, GWLP_USERDATA);
568     LRESULT lResult = CallWindowProc(pImpl->_base_window_proc, hwnd, uMsg, wParam, lParam);
570     switch(uMsg)
571     {
572     case WM_SHOWWINDOW:
573         if(wParam != 0)
574             pImpl->layout_dialog();
575         break;
577     case WM_SIZE:
578         pImpl->layout_dialog();
579         break;
581     case WM_COMMAND:
582         if(wParam == IDC_SHOW_PREVIEW)
583         {
584             const bool enable = SendMessage(pImpl->_toolbar_wnd,
585                 TB_ISBUTTONCHECKED, IDC_SHOW_PREVIEW, 0) != 0;
586             pImpl->enable_preview(enable);
587         }
588         break;
589     }
591     return lResult;
594 LRESULT CALLBACK FileOpenDialogImplWin32::preview_wnd_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
596     const int CaptionPadding = 4;
597     const int IconSize = 32;
599     FileOpenDialogImplWin32 *pImpl = (FileOpenDialogImplWin32*)
600         GetWindowLongPtr(hwnd, GWLP_USERDATA);
602     LRESULT lResult = 0;
604     switch(uMsg)
605     {
606     case WM_ERASEBKGND:
607         // Do nothing to erase the background
608         //  - otherwise there'll be flicker
609         lResult = 1;
610         break;
612     case WM_PAINT:
613         {
614             // Get the client rect
615             RECT rcClient;
616             GetClientRect(hwnd, &rcClient);
618             // Prepare to paint
619             PAINTSTRUCT paint_struct;
620             HDC dc = BeginPaint(hwnd, &paint_struct);
622             HFONT hCaptionFont = (HFONT)SendMessage(GetParent(hwnd),
623                     WM_GETFONT, 0, 0);
624             HFONT hOldFont = (HFONT)SelectObject(dc, hCaptionFont);
625             SetBkMode(dc, TRANSPARENT);
627             pImpl->_mutex->lock();
629             if(pImpl->_path_string[0] == 0)
630             {
631                 WCHAR* noFileText=(WCHAR*)g_utf8_to_utf16(_("No file selected"),
632                     -1, NULL, NULL, NULL);
633                 FillRect(dc, &rcClient, (HBRUSH)(COLOR_3DFACE + 1));
634                 DrawTextW(dc,  noFileText, -1, &rcClient, 
635                     DT_CENTER | DT_VCENTER | DT_NOPREFIX);
636                 g_free(noFileText);
637             }
638             else if(pImpl->_preview_bitmap != NULL)
639             {
640                 BITMAP bitmap;
641                 GetObject(pImpl->_preview_bitmap, sizeof(bitmap), &bitmap);
642                 const int destX = (rcClient.right - bitmap.bmWidth) / 2;
644                 // Render the image
645                 HDC hSrcDC = CreateCompatibleDC(dc);
646                 HBITMAP hOldBitmap = (HBITMAP)SelectObject(hSrcDC, pImpl->_preview_bitmap);
648                 BitBlt(dc, destX, 0, bitmap.bmWidth, bitmap.bmHeight,
649                     hSrcDC, 0, 0, SRCCOPY);
651                 SelectObject(hSrcDC, hOldBitmap);
652                 DeleteDC(hSrcDC);
654                 // Fill in the background area
655                 HRGN hEraseRgn = CreateRectRgn(rcClient.left, rcClient.top,
656                     rcClient.right, rcClient.bottom);
657                 HRGN hImageRgn = CreateRectRgn(destX, 0,
658                     destX + bitmap.bmWidth, bitmap.bmHeight);
659                 CombineRgn(hEraseRgn, hEraseRgn, hImageRgn, RGN_DIFF);
661                 FillRgn(dc, hEraseRgn, GetSysColorBrush(COLOR_3DFACE));
663                 DeleteObject(hImageRgn);
664                 DeleteObject(hEraseRgn);
666                 // Draw the caption on
667                 RECT rcCaptionRect = {rcClient.left,
668                     rcClient.top + bitmap.bmHeight + CaptionPadding,
669                     rcClient.right, rcClient.bottom};
671                 WCHAR szCaption[_MAX_FNAME + 32];
672                 const int iLength = pImpl->format_caption(
673                     szCaption, sizeof(szCaption) / sizeof(WCHAR));
675                 DrawTextW(dc, szCaption, iLength, &rcCaptionRect,
676                     DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS);
677             }
678             else if(pImpl->_preview_file_icon != NULL)
679             {
680                 FillRect(dc, &rcClient, (HBRUSH)(COLOR_3DFACE + 1));
682                 // Draw the files icon
683                 const int destX = (rcClient.right - IconSize) / 2;
684                 DrawIconEx(dc, destX, 0, pImpl->_preview_file_icon,
685                     IconSize, IconSize, 0, NULL,
686                     DI_NORMAL | DI_COMPAT);
688                 // Draw the caption on
689                 RECT rcCaptionRect = {rcClient.left,
690                     rcClient.top + IconSize + CaptionPadding,
691                     rcClient.right, rcClient.bottom};
693                 WCHAR szFileName[_MAX_FNAME], szCaption[_MAX_FNAME + 32];
694                 _wsplitpath(pImpl->_path_string, NULL, NULL, szFileName, NULL);
696                 const int iLength = snwprintf(szCaption,
697                     sizeof(szCaption), L"%s\n%d kB",
698                     szFileName, pImpl->_preview_file_size);
700                 DrawTextW(dc, szCaption, iLength, &rcCaptionRect,
701                     DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS);
702             }
703             else
704             {
705                 // Can't show anything!
706                 FillRect(dc, &rcClient, (HBRUSH)(COLOR_3DFACE + 1));
707             }
709             pImpl->_mutex->unlock();
711             // Finish painting
712             SelectObject(dc, hOldFont);
713             EndPaint(hwnd, &paint_struct);
714         }
716         break;
718     case WM_DESTROY:
719         pImpl->free_preview();
720         break;
722     default:
723         lResult = DefWindowProc(hwnd, uMsg, wParam, lParam);
724         break;
725     }
727     return lResult;
730 void FileOpenDialogImplWin32::enable_preview(bool enable)
732     _show_preview = enable;
734     // Relayout the dialog
735     ShowWindow(_preview_wnd, enable ? SW_SHOW : SW_HIDE);
736     layout_dialog();
738     // Load or unload the preview
739     if(enable)
740     {
741         _mutex->lock();
742         _file_selected = true;
743         _mutex->unlock();
744     }
745     else free_preview();
748 void FileOpenDialogImplWin32::layout_dialog()
750     union RECTPOINTS
751     {
752         RECT r;
753         POINT p[2];
754     };
756     const float MaxExtentScale = 2.0f / 3.0f;
758     RECT rcClient;
759     GetClientRect(_file_dialog_wnd, &rcClient);
761     // Re-layout the dialog
762     HWND hFileListWnd = GetDlgItem(_file_dialog_wnd, lst2);
763     HWND hFolderComboWnd = GetDlgItem(_file_dialog_wnd, cmb2);
766     RECT rcFolderComboRect;
767     RECTPOINTS rcFileList;
768     GetWindowRect(hFileListWnd, &rcFileList.r);
769     GetWindowRect(hFolderComboWnd, &rcFolderComboRect);
770     const int iPadding = rcFileList.r.top - rcFolderComboRect.bottom;
771     MapWindowPoints(NULL, _file_dialog_wnd, rcFileList.p, 2);
773     RECT rcPreview;
774     RECT rcBody = {rcFileList.r.left, rcFileList.r.top,
775         rcClient.right - iPadding, rcFileList.r.bottom};
776     rcFileList.r.right = rcBody.right;
778     if(_show_preview)
779     {
780         rcPreview.top = rcBody.top;
781         rcPreview.left = rcClient.right - (rcBody.bottom - rcBody.top);
782         const int iMaxExtent = (int)(MaxExtentScale * (float)(rcBody.left + rcBody.right)) + iPadding / 2;
783         if(rcPreview.left < iMaxExtent) rcPreview.left = iMaxExtent;
784         rcPreview.bottom = rcBody.bottom;
785         rcPreview.right = rcBody.right;
787         // Re-layout the preview box
788         _mutex->lock();
790             _preview_width = rcPreview.right - rcPreview.left;
791             _preview_height = rcPreview.bottom - rcPreview.top;
793         _mutex->unlock();
795         render_preview();
797         MoveWindow(_preview_wnd, rcPreview.left, rcPreview.top,
798             _preview_width, _preview_height, TRUE);
800         rcFileList.r.right = rcPreview.left - iPadding;
801     }
803     // Re-layout the file list box
804     MoveWindow(hFileListWnd, rcFileList.r.left, rcFileList.r.top,
805         rcFileList.r.right - rcFileList.r.left,
806         rcFileList.r.bottom - rcFileList.r.top, TRUE);
808     // Re-layout the toolbar
809     RECTPOINTS rcToolBar;
810     GetWindowRect(_toolbar_wnd, &rcToolBar.r);
811     MapWindowPoints(NULL, _file_dialog_wnd, rcToolBar.p, 2);
812     MoveWindow(_toolbar_wnd, rcToolBar.r.left, rcToolBar.r.top,
813         rcToolBar.r.right - rcToolBar.r.left, rcToolBar.r.bottom - rcToolBar.r.top, TRUE);
816 void FileOpenDialogImplWin32::file_selected()
818     // Destroy any previous previews
819     free_preview();
822     // Determine if the file exists
823     DWORD attributes = GetFileAttributesW(_path_string);
824     if(attributes == 0xFFFFFFFF ||
825         attributes == FILE_ATTRIBUTE_DIRECTORY)
826     {
827         InvalidateRect(_preview_wnd, NULL, FALSE);
828         return;
829     }
831     // Check the file exists and get the file size
832     HANDLE file_handle = CreateFileW(_path_string, GENERIC_READ,
833         FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
834     if(file_handle == INVALID_HANDLE_VALUE) return;
835     const DWORD file_size = GetFileSize(file_handle, NULL);
836     if (file_size == INVALID_FILE_SIZE) return;
837     _preview_file_size = file_size / 1024;
838     CloseHandle(file_handle);
840     if(_show_preview) load_preview();
843 void FileOpenDialogImplWin32::load_preview()
845     // Destroy any previous previews
846     free_preview();
848     // Try to get the file icon
849     SHFILEINFOW fileInfo;
850     if(SUCCEEDED(SHGetFileInfoW(_path_string, 0, &fileInfo,
851         sizeof(fileInfo), SHGFI_ICON | SHGFI_LARGEICON)))
852         _preview_file_icon = fileInfo.hIcon;
854     // Will this file be too big?
855     if(_preview_file_size > MaxPreviewFileSize)
856     {
857         InvalidateRect(_preview_wnd, NULL, FALSE);
858         return;
859     }
861     // Prepare to render a preview
862     const Glib::ustring svg = ".svg";
863     const Glib::ustring svgz = ".svgz";
864     const Glib::ustring emf = ".emf";
865     const Glib::ustring wmf = ".wmf";
866     const Glib::ustring path = utf16_to_ustring(_path_string);
868     bool success = false;
870     _preview_document_width = _preview_document_height = 0;
872     if ((dialogType == SVG_TYPES || dialogType == IMPORT_TYPES) &&
873             (hasSuffix(path, svg) || hasSuffix(path, svgz)))
874         success = set_svg_preview();
875     else if (hasSuffix(path, emf) || hasSuffix(path, wmf))
876         success = set_emf_preview();
877     else if (isValidImageFile(path))
878         success = set_image_preview();
879     else {
880         // Show no preview
881     }
883     if(success) render_preview();
885     InvalidateRect(_preview_wnd, NULL, FALSE);
888 void FileOpenDialogImplWin32::free_preview()
890     _mutex->lock();
891     if(_preview_bitmap != NULL)
892         DeleteObject(_preview_bitmap);
893     _preview_bitmap = NULL;
895     if(_preview_file_icon != NULL)
896         DestroyIcon(_preview_file_icon);
897     _preview_file_icon = NULL;
899     _preview_bitmap_image.clear();
900     _preview_emf_image = false;
901     _mutex->unlock();
904 bool FileOpenDialogImplWin32::set_svg_preview()
906     const int PreviewSize = 512;
908     gchar *utf8string = g_utf16_to_utf8((const gunichar2*)_path_string,
909         _MAX_PATH, NULL, NULL, NULL);
910     SPDocument *svgDoc = SPDocument::createNewDoc (utf8string, true);
911     g_free(utf8string);
913     // Check the document loaded properly
914     if(svgDoc == NULL) return false;
915     if(svgDoc->root == NULL)
916     {
917         svgDoc->doUnref();
918         return false;
919     }
921     // Get the size of the document
922     const double svgWidth = svgDoc->getWidth();
923     const double svgHeight = svgDoc->getHeight();
925     // Find the minimum scale to fit the image inside the preview area
926     const double scaleFactorX =    PreviewSize / svgWidth;
927     const double scaleFactorY =    PreviewSize / svgHeight;
928     const double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX;
930     // Now get the resized values
931     const double scaledSvgWidth  = scaleFactor * svgWidth;
932     const double scaledSvgHeight = scaleFactor * svgHeight;
934     Geom::Rect area(Geom::Point(0, 0), Geom::Point(scaledSvgWidth, scaledSvgHeight));
935     NRRectL areaL = {0, 0, scaledSvgWidth, scaledSvgHeight};
936     NRRectL bbox = {0, 0, scaledSvgWidth, scaledSvgHeight};
938     // write object bbox to area
939     Geom::OptRect maybeArea(area);
940     svgDoc->ensureUpToDate();
941     static_cast<SPItem *>(svgDoc->root)->invoke_bbox( maybeArea,
942         static_cast<SPItem *>(svgDoc->root)->i2d_affine(), TRUE);
944     NRArena *const arena = NRArena::create();
946     unsigned const key = SPItem::display_key_new(1);
948     NRArenaItem *root = static_cast<SPItem*>(svgDoc->root)->invoke_show(
949         arena, key, SP_ITEM_SHOW_DISPLAY);
951     NRGC gc(NULL);
952     gc.transform = Geom::Matrix(Geom::Scale(scaleFactor, scaleFactor));
954     nr_arena_item_invoke_update (root, NULL, &gc,
955         NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
957     // Prepare a GDI compatible NRPixBlock
958     NRPixBlock pixBlock;
959     pixBlock.size = NR_PIXBLOCK_SIZE_BIG;
960     pixBlock.mode = NR_PIXBLOCK_MODE_R8G8B8;
961     pixBlock.empty = 1;
962     pixBlock.visible_area.x0 = pixBlock.area.x0 = 0;
963     pixBlock.visible_area.y0 = pixBlock.area.y0 = 0;
964     pixBlock.visible_area.x1 = pixBlock.area.x1 = scaledSvgWidth;
965     pixBlock.visible_area.y1 = pixBlock.area.y1 = scaledSvgHeight;
966     pixBlock.rs = 4 * ((3 * (int)scaledSvgWidth + 3) / 4);
967     pixBlock.data.px = g_try_new (unsigned char, pixBlock.rs * scaledSvgHeight);
969     // Fail if the pixblock failed to allocate
970     if(pixBlock.data.px == NULL)
971     {
972         svgDoc->doUnref();
973         return false;
974     }
976     memset(pixBlock.data.px, 0xFF, pixBlock.rs * scaledSvgHeight);
978     memcpy(&root->bbox, &areaL, sizeof(areaL));
980     // Render the image
981     nr_arena_item_invoke_render(NULL, root, &bbox, &pixBlock, /*0*/NR_ARENA_ITEM_RENDER_NO_CACHE);
983     // Tidy up
984     svgDoc->doUnref();
985     static_cast<SPItem*>(svgDoc->root)->invoke_hide(key);
986     nr_object_unref((NRObject *) arena);
988     // Create the GDK pixbuf
989     _mutex->lock();
991     _preview_bitmap_image = Gdk::Pixbuf::create_from_data(
992         pixBlock.data.px, Gdk::COLORSPACE_RGB, false, 8,
993         (int)scaledSvgWidth, (int)scaledSvgHeight, pixBlock.rs,
994         sigc::ptr_fun(destroy_svg_rendering));
996     _preview_document_width = scaledSvgWidth;
997     _preview_document_height = scaledSvgHeight;
998     _preview_image_width = svgWidth;
999     _preview_image_height = svgHeight;
1001     _mutex->unlock();
1003     return true;
1006 void FileOpenDialogImplWin32::destroy_svg_rendering(const guint8 *buffer)
1008     g_assert(buffer != NULL);
1009     g_free((void*)buffer);
1012 bool FileOpenDialogImplWin32::set_image_preview()
1014     const Glib::ustring path = utf16_to_ustring(_path_string, _MAX_PATH);
1016     bool successful = false;
1018     _mutex->lock();
1020     try {
1021         _preview_bitmap_image = Gdk::Pixbuf::create_from_file(path);
1022         if (_preview_bitmap_image) {
1023             _preview_image_width = _preview_bitmap_image->get_width();
1024             _preview_document_width = _preview_image_width;
1025             _preview_image_height = _preview_bitmap_image->get_height();
1026             _preview_document_height = _preview_image_height;
1027             successful = true;
1028         }
1029     }
1030     catch (const Gdk::PixbufError&) {}
1031     catch (const Glib::FileError&) {}
1033     _mutex->unlock();
1035     return successful;
1038 // Aldus Placeable Header ===================================================
1039 // Since we are a 32bit app, we have to be sure this structure compiles to
1040 // be identical to a 16 bit app's version. To do this, we use the #pragma
1041 // to adjust packing, we use a WORD for the hmf handle, and a SMALL_RECT
1042 // for the bbox rectangle.
1043 #pragma pack( push )
1044 #pragma pack( 2 )
1045 typedef struct
1047     DWORD       dwKey;
1048     WORD        hmf;
1049     SMALL_RECT  bbox;
1050     WORD        wInch;
1051     DWORD       dwReserved;
1052     WORD        wCheckSum;
1053 } APMHEADER, *PAPMHEADER;
1054 #pragma pack( pop )
1057 static HENHMETAFILE
1058 MyGetEnhMetaFileW( const WCHAR *filename )
1060     // Try open as Enhanced Metafile
1061     HENHMETAFILE hemf = GetEnhMetaFileW(filename);
1063     if (!hemf) {
1064         // Try open as Windows Metafile
1065         HMETAFILE hmf = GetMetaFileW(filename);
1067         METAFILEPICT mp;
1068         HDC hDC;
1070         if (!hmf) {
1071             WCHAR szTemp[MAX_PATH];
1073             DWORD dw = GetShortPathNameW( filename, szTemp, MAX_PATH );
1074             if (dw) {
1075                 hmf = GetMetaFileW( szTemp );
1076             }
1077         }
1079         if (hmf) {
1080             // Convert Windows Metafile to Enhanced Metafile
1081             DWORD nSize = GetMetaFileBitsEx( hmf, 0, NULL );
1083             if (nSize) {
1084                 BYTE *lpvData = new BYTE[nSize];
1085                 if (lpvData) {
1086                     DWORD dw = GetMetaFileBitsEx( hmf, nSize, lpvData );
1087                     if (dw) {
1088                         // Fill out a METAFILEPICT structure
1089                         mp.mm = MM_ANISOTROPIC;
1090                         mp.xExt = 1000;
1091                         mp.yExt = 1000;
1092                         mp.hMF = NULL;
1093                         // Get a reference DC
1094                         hDC = GetDC( NULL );
1095                         // Make an enhanced metafile from the windows metafile
1096                         hemf = SetWinMetaFileBits( nSize, lpvData, hDC, &mp );
1097                         // Clean up
1098                         ReleaseDC( NULL, hDC );
1099                         DeleteMetaFile( hmf );
1100                     }
1101                     delete[] lpvData;
1102                 }
1103                 else {
1104                     DeleteMetaFile( hmf );
1105                 }
1106             }
1107             else {
1108                 DeleteMetaFile( hmf );
1109             }
1110         }
1111         else {
1112             // Try open as Aldus Placeable Metafile
1113             HANDLE hFile;
1114             hFile = CreateFileW( filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
1116             if (hFile != INVALID_HANDLE_VALUE) {
1117                 DWORD nSize = GetFileSize( hFile, NULL );
1118                 if (nSize) {
1119                     BYTE *lpvData = new BYTE[nSize];
1120                     if (lpvData) {
1121                         DWORD dw = ReadFile( hFile, lpvData, nSize, &nSize, NULL );
1122                         if (dw) {
1123                             if ( ((PAPMHEADER)lpvData)->dwKey == 0x9ac6cdd7l ) {
1124                                 // Fill out a METAFILEPICT structure
1125                                 mp.mm = MM_ANISOTROPIC;
1126                                 mp.xExt = ((PAPMHEADER)lpvData)->bbox.Right - ((PAPMHEADER)lpvData)->bbox.Left;
1127                                 mp.xExt = ( mp.xExt * 2540l ) / (DWORD)(((PAPMHEADER)lpvData)->wInch);
1128                                 mp.yExt = ((PAPMHEADER)lpvData)->bbox.Bottom - ((PAPMHEADER)lpvData)->bbox.Top;
1129                                 mp.yExt = ( mp.yExt * 2540l ) / (DWORD)(((PAPMHEADER)lpvData)->wInch);
1130                                 mp.hMF = NULL;
1131                                 // Get a reference DC
1132                                 hDC = GetDC( NULL );
1133                                 // Create an enhanced metafile from the bits
1134                                 hemf = SetWinMetaFileBits( nSize, lpvData+sizeof(APMHEADER), hDC, &mp );
1135                                 // Clean up
1136                                 ReleaseDC( NULL, hDC );
1137                             }
1138                         }
1139                         delete[] lpvData;
1140                     }
1141                 }
1142                 CloseHandle( hFile );
1143             }
1144         }
1145     }
1147     return hemf;
1151 bool FileOpenDialogImplWin32::set_emf_preview()
1153     _mutex->lock();
1155     BOOL ok = FALSE;
1157     DWORD w = 0;
1158     DWORD h = 0;
1160     HENHMETAFILE hemf = MyGetEnhMetaFileW( _path_string );
1162     if (hemf)
1163     {
1164         ENHMETAHEADER emh;
1165         ZeroMemory(&emh, sizeof(emh));
1166         ok = GetEnhMetaFileHeader(hemf, sizeof(emh), &emh) != 0;
1168         w = (emh.rclFrame.right - emh.rclFrame.left);
1169         h = (emh.rclFrame.bottom - emh.rclFrame.top);
1171         DeleteEnhMetaFile(hemf);
1172     }
1174     if (ok)
1175     {
1176         const int PreviewSize = 512;
1178         // Get the size of the document
1179         const double emfWidth = w;
1180         const double emfHeight = h;
1182         // Find the minimum scale to fit the image inside the preview area
1183         const double scaleFactorX =    PreviewSize / emfWidth;
1184         const double scaleFactorY =    PreviewSize / emfHeight;
1185         const double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX;
1187         // Now get the resized values
1188         const double scaledEmfWidth  = scaleFactor * emfWidth;
1189         const double scaledEmfHeight = scaleFactor * emfHeight;
1191         _preview_document_width = scaledEmfWidth;
1192         _preview_document_height = scaledEmfHeight;
1193         _preview_image_width = emfWidth;
1194         _preview_image_height = emfHeight;
1196         _preview_emf_image = true;
1197     }
1199     _mutex->unlock();
1201     return ok;
1204 void FileOpenDialogImplWin32::render_preview()
1206     double x, y;
1207     const double blurRadius = 8;
1208     const double halfBlurRadius = blurRadius / 2;
1209     const int shaddowOffsetX = 0;
1210     const int shaddowOffsetY = 2;
1211     const int pagePadding = 5;
1212     const double shaddowAlpha = 0.75;
1214     // Is the preview showing?
1215     if(!_show_preview)
1216         return;
1218     // Do we have anything to render?
1219     _mutex->lock();
1221     if(!_preview_bitmap_image && !_preview_emf_image)
1222     {
1223         _mutex->unlock();
1224         return;
1225     }
1227     // Tidy up any previous bitmap renderings
1228     if(_preview_bitmap != NULL)
1229         DeleteObject(_preview_bitmap);
1230     _preview_bitmap = NULL;
1232     // Calculate the size of the caption
1233     int captionHeight = 0;
1235     if(_preview_wnd != NULL)
1236     {
1237         RECT rcCaptionRect;
1238         WCHAR szCaption[_MAX_FNAME + 32];
1239         const int iLength = format_caption(szCaption,
1240             sizeof(szCaption) / sizeof(WCHAR));
1242         HDC dc = GetDC(_preview_wnd);
1243         DrawTextW(dc, szCaption, iLength, &rcCaptionRect,
1244             DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_CALCRECT);
1245         ReleaseDC(_preview_wnd, dc);
1247         captionHeight = rcCaptionRect.bottom - rcCaptionRect.top;
1248     }
1250     // Find the minimum scale to fit the image inside the preview area
1251     const double scaleFactorX =
1252         ((double)_preview_width - pagePadding * 2 - blurRadius)  / _preview_document_width;
1253     const double scaleFactorY =
1254         ((double)_preview_height - pagePadding * 2
1255         - shaddowOffsetY - halfBlurRadius - captionHeight) / _preview_document_height;
1256     double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX;
1257     scaleFactor = (scaleFactor > 1.0) ? 1.0 : scaleFactor;
1259     // Now get the resized values
1260     const double scaledSvgWidth  = scaleFactor * _preview_document_width;
1261     const double scaledSvgHeight = scaleFactor * _preview_document_height;
1263     const int svgX = pagePadding + halfBlurRadius;
1264     const int svgY = pagePadding;
1266     const int frameX = svgX - pagePadding;
1267     const int frameY = svgY - pagePadding;
1268     const int frameWidth = scaledSvgWidth + pagePadding * 2;
1269     const int frameHeight = scaledSvgHeight + pagePadding * 2;
1271     const int totalWidth = (int)ceil(frameWidth + blurRadius);
1272     const int totalHeight = (int)ceil(frameHeight + blurRadius);
1274     // Prepare the drawing surface
1275     HDC hDC = GetDC(_preview_wnd);
1276     HDC hMemDC = CreateCompatibleDC(hDC);
1277     _preview_bitmap = CreateCompatibleBitmap(hDC, totalWidth, totalHeight);
1278     HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDC, _preview_bitmap);
1279     Cairo::RefPtr<Win32Surface> surface = Win32Surface::create(hMemDC);
1280     Cairo::RefPtr<Context> context = Context::create(surface);
1282     // Paint the background to match the dialog colour
1283     const COLORREF background = GetSysColor(COLOR_3DFACE);
1284     context->set_source_rgb(
1285         GetRValue(background) / 255.0,
1286         GetGValue(background) / 255.0,
1287         GetBValue(background) / 255.0);
1288     context->paint();
1290     //----- Draw the drop shaddow -----//
1292     // Left Edge
1293     x = frameX + shaddowOffsetX - halfBlurRadius;
1294     Cairo::RefPtr<LinearGradient> leftEdgeFade = LinearGradient::create(
1295         x, 0.0, x + blurRadius, 0.0);
1296     leftEdgeFade->add_color_stop_rgba (0, 0, 0, 0, 0);
1297     leftEdgeFade->add_color_stop_rgba (1, 0, 0, 0, shaddowAlpha);
1298     context->set_source(leftEdgeFade);
1299     context->rectangle (x, frameY + shaddowOffsetY + halfBlurRadius,
1300         blurRadius, frameHeight - blurRadius);
1301     context->fill();
1303     // Right Edge
1304     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1305     Cairo::RefPtr<LinearGradient> rightEdgeFade = LinearGradient::create(
1306         x, 0.0,    x + blurRadius, 0.0);
1307     rightEdgeFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1308     rightEdgeFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1309     context->set_source(rightEdgeFade);
1310     context->rectangle (frameX + frameWidth + shaddowOffsetX - halfBlurRadius,
1311         frameY + shaddowOffsetY + halfBlurRadius,
1312         blurRadius, frameHeight - blurRadius);
1313     context->fill();
1315     // Top Edge
1316     y = frameY + shaddowOffsetY - halfBlurRadius;
1317     Cairo::RefPtr<LinearGradient> topEdgeFade = LinearGradient::create(
1318         0.0, y, 0.0, y + blurRadius);
1319     topEdgeFade->add_color_stop_rgba (0, 0, 0, 0, 0);
1320     topEdgeFade->add_color_stop_rgba (1, 0, 0, 0, shaddowAlpha);
1321     context->set_source(topEdgeFade);
1322     context->rectangle (frameX + shaddowOffsetX + halfBlurRadius, y,
1323         frameWidth - blurRadius, blurRadius);
1324     context->fill();
1326     // Bottom Edge
1327     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1328     Cairo::RefPtr<LinearGradient> bottomEdgeFade = LinearGradient::create(
1329         0.0, y,    0.0, y + blurRadius);
1330     bottomEdgeFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1331     bottomEdgeFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1332     context->set_source(bottomEdgeFade);
1333     context->rectangle (frameX + shaddowOffsetX + halfBlurRadius, y,
1334         frameWidth - blurRadius, blurRadius);
1335     context->fill();
1337     // Top Left Corner
1338     x = frameX + shaddowOffsetX - halfBlurRadius;
1339     y = frameY + shaddowOffsetY - halfBlurRadius;
1340     Cairo::RefPtr<RadialGradient> topLeftCornerFade = RadialGradient::create(
1341         x + blurRadius, y + blurRadius, 0, x + blurRadius, y + blurRadius, blurRadius);
1342     topLeftCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1343     topLeftCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1344     context->set_source(topLeftCornerFade);
1345     context->rectangle (x, y, blurRadius, blurRadius);
1346     context->fill();
1348     // Top Right Corner
1349     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1350     y = frameY + shaddowOffsetY - halfBlurRadius;
1351     Cairo::RefPtr<RadialGradient> topRightCornerFade = RadialGradient::create(
1352         x, y + blurRadius, 0, x, y + blurRadius, blurRadius);
1353     topRightCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1354     topRightCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1355     context->set_source(topRightCornerFade);
1356     context->rectangle (x, y, blurRadius, blurRadius);
1357     context->fill();
1359     // Bottom Left Corner
1360     x = frameX + shaddowOffsetX - halfBlurRadius;
1361     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1362     Cairo::RefPtr<RadialGradient> bottomLeftCornerFade = RadialGradient::create(
1363         x + blurRadius, y, 0, x + blurRadius, y, blurRadius);
1364     bottomLeftCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1365     bottomLeftCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1366     context->set_source(bottomLeftCornerFade);
1367     context->rectangle (x, y, blurRadius, blurRadius);
1368     context->fill();
1370     // Bottom Right Corner
1371     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1372     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1373     Cairo::RefPtr<RadialGradient> bottomRightCornerFade = RadialGradient::create(
1374         x, y, 0, x, y, blurRadius);
1375     bottomRightCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1376     bottomRightCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1377     context->set_source(bottomRightCornerFade);
1378     context->rectangle (frameX + frameWidth + shaddowOffsetX - halfBlurRadius,
1379         frameY + frameHeight + shaddowOffsetY - halfBlurRadius,
1380         blurRadius, blurRadius);
1381     context->fill();
1383     // Draw the frame
1384     context->set_line_width(1);
1385     context->rectangle (frameX, frameY,    frameWidth, frameHeight);
1387     context->set_source_rgb(1.0, 1.0, 1.0);
1388     context->fill_preserve();
1389     context->set_source_rgb(0.25, 0.25, 0.25);
1390     context->stroke_preserve();
1392     // Draw the image
1393     if(_preview_bitmap_image)    // Is the image a pixbuf?
1394     {
1395         // Set the transformation
1396         const Cairo::Matrix matrix(
1397             scaleFactor, 0,
1398             0, scaleFactor,
1399             svgX, svgY);
1400         context->set_matrix (matrix);
1402         // Render the image
1403         set_source_pixbuf (context, _preview_bitmap_image, 0, 0);
1404         context->paint();
1406         // Reset the transformation
1407         context->set_identity_matrix();
1408     }
1410     // Draw the inner frame
1411     context->set_source_rgb(0.75, 0.75, 0.75);
1412     context->rectangle (svgX, svgY,    scaledSvgWidth, scaledSvgHeight);
1413     context->stroke();
1415     _mutex->unlock();
1417     // Finish drawing
1418     surface->finish();
1420     if (_preview_emf_image) {
1421         HENHMETAFILE hemf = MyGetEnhMetaFileW(_path_string);
1422         if (hemf) {
1423             RECT rc;
1424             rc.top = svgY+2;
1425             rc.left = svgX+2;
1426             rc.bottom = scaledSvgHeight-2;
1427             rc.right = scaledSvgWidth-2;
1428             PlayEnhMetaFile(hMemDC, hemf, &rc);
1429             DeleteEnhMetaFile(hemf);
1430         }
1431     }
1433     SelectObject(hMemDC, hOldBitmap) ;
1434     DeleteDC(hMemDC);
1436     // Refresh the preview pane
1437     InvalidateRect(_preview_wnd, NULL, FALSE);
1440 int FileOpenDialogImplWin32::format_caption(wchar_t *caption, int caption_size)
1442     wchar_t szFileName[_MAX_FNAME];
1443     _wsplitpath(_path_string, NULL, NULL, szFileName, NULL);
1445     return snwprintf(caption, caption_size,
1446         L"%s\n%d kB\n%d \xD7 %d", szFileName, _preview_file_size,
1447         (int)_preview_document_width, (int)_preview_document_height);
1450 /**
1451  * Show this dialog modally.  Return true if user hits [OK]
1452  */
1453 bool
1454 FileOpenDialogImplWin32::show()
1456     // We can only run one worker thread at a time
1457     if(_mutex != NULL) return false;
1459     if(!Glib::thread_supported())
1460         Glib::thread_init();
1462     _result = false;
1463     _finished = false;
1464     _file_selected = false;
1465     _mutex = new Glib::Mutex();
1466     _main_loop = g_main_loop_new(g_main_context_default(), FALSE);
1468     if(Glib::Thread::create(sigc::mem_fun(*this, &FileOpenDialogImplWin32::GetOpenFileName_thread), true))
1469     {
1470         while(1)
1471         {
1472             g_main_context_iteration(g_main_context_default(), FALSE);
1474             if(_mutex->trylock())
1475             {
1476                 // Read mutexed data
1477                 const bool finished = _finished;
1478                 const bool is_file_selected = _file_selected;
1479                 _file_selected = false;
1480                 _mutex->unlock();
1482                 if(finished) break;
1483                 if(is_file_selected) file_selected();
1484             }
1486             Sleep(10);
1487         }
1488     }
1490     // Tidy up
1491     delete _mutex;
1492     _mutex = NULL;
1494     return _result;
1497 /**
1498  * To Get Multiple filenames selected at-once.
1499  */
1500 std::vector<Glib::ustring>FileOpenDialogImplWin32::getFilenames()
1502     std::vector<Glib::ustring> result;
1503     result.push_back(getFilename());
1504     return result;
1508 /*#########################################################################
1509 ### F I L E    S A V E
1510 #########################################################################*/
1512 /**
1513  * Constructor
1514  */
1515 FileSaveDialogImplWin32::FileSaveDialogImplWin32(Gtk::Window &parent,
1516             const Glib::ustring &dir,
1517             FileDialogType fileTypes,
1518             const char *title,
1519             const Glib::ustring &/*default_key*/,
1520             const char *docTitle,
1521             const Inkscape::Extension::FileSaveMethod save_method) :
1522     FileDialogBaseWin32(parent, dir, title, fileTypes,
1523                         (save_method == Inkscape::Extension::FILE_SAVE_METHOD_SAVE_COPY) ? "dialogs.save_copy" :  "dialogs.save_as"),
1524         _title_label(NULL),
1525         _title_edit(NULL)
1527     FileSaveDialog::myDocTitle = docTitle;
1528     createFilterMenu();
1531 FileSaveDialogImplWin32::~FileSaveDialogImplWin32()
1535 void FileSaveDialogImplWin32::createFilterMenu()
1537     list<Filter> filter_list;
1539     knownExtensions.clear();
1541     // Compose the filter string
1542     Glib::ustring all_inkscape_files_filter, all_image_files_filter;
1543     Inkscape::Extension::DB::OutputList extension_list;
1544     Inkscape::Extension::db.get_output_list(extension_list);
1546     int filter_count = 0;
1547     int filter_length = 1;
1549     for (Inkscape::Extension::DB::OutputList::iterator current_item = extension_list.begin();
1550          current_item != extension_list.end(); current_item++)
1551     {
1552         Inkscape::Extension::Output *omod = *current_item;
1553         if (omod->deactivated()) continue;
1555         filter_count++;
1557         Filter filter;
1559         // Extension
1560         const gchar *filter_extension = omod->get_extension();
1561         filter.filter = g_utf8_to_utf16(
1562             filter_extension, -1, NULL, &filter.filter_length, NULL);
1563         knownExtensions.insert( Glib::ustring(filter_extension).casefold() );
1565         // Type
1566         filter.name = g_utf8_to_utf16(
1567             _(omod->get_filetypename()), -1, NULL, &filter.name_length, NULL);
1569         filter.mod = omod;
1571         filter_length += filter.name_length +
1572             filter.filter_length + 3;   // Add 3 for two \0s and a *
1574         filter_list.push_back(filter);
1575     }
1577     int extension_index = 0;
1578     _extension_map = new Inkscape::Extension::Extension*[filter_count];
1580     _filter = new wchar_t[filter_length];
1581     wchar_t *filterptr = _filter;
1583     for(list<Filter>::iterator filter_iterator = filter_list.begin();
1584         filter_iterator != filter_list.end(); filter_iterator++)
1585     {
1586         const Filter &filter = *filter_iterator;
1588         wcsncpy(filterptr, (wchar_t*)filter.name, filter.name_length);
1589         filterptr += filter.name_length;
1590         g_free(filter.name);
1592         *(filterptr++) = L'\0';
1593         *(filterptr++) = L'*';
1595         wcsncpy(filterptr, (wchar_t*)filter.filter, filter.filter_length);
1596         filterptr += filter.filter_length;
1597         g_free(filter.filter);
1599         *(filterptr++) = L'\0';
1601         // Associate this input extension with the file type name
1602         _extension_map[extension_index++] = filter.mod;
1603     }
1604     *(filterptr++) = 0;
1606         _filter_count = extension_index;
1607     _filter_index = 1;  // A value of 1 selects the 1st filter - NOT the 2nd
1610 void FileSaveDialogImplWin32::GetSaveFileName_thread()
1612     OPENFILENAMEEXW ofn;
1614     g_assert(this != NULL);
1615     g_assert(_main_loop != NULL);
1617     WCHAR* current_directory_string = (WCHAR*)g_utf8_to_utf16(
1618         _current_directory.data(), _current_directory.length(),
1619                 NULL, NULL, NULL);
1621     // Copy the selected file name, converting from UTF-8 to UTF-16
1622     memset(_path_string, 0, sizeof(_path_string));
1623     gunichar2* utf16_path_string = g_utf8_to_utf16(
1624         myFilename.data(), -1, NULL, NULL, NULL);
1625     wcsncpy(_path_string, (wchar_t*)utf16_path_string, _MAX_PATH);
1626     g_free(utf16_path_string);
1628     ZeroMemory(&ofn, sizeof(ofn));
1629     ofn.lStructSize = sizeof(ofn);
1630     ofn.hwndOwner = _ownerHwnd;
1631     ofn.lpstrFile = _path_string;
1632     ofn.nMaxFile = _MAX_PATH;
1633     ofn.nFilterIndex = _filter_index;
1634     ofn.lpstrFileTitle = NULL;
1635     ofn.nMaxFileTitle = 0;
1636     ofn.lpstrInitialDir = current_directory_string;
1637     ofn.lpstrTitle = _title;
1638     ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ENABLEHOOK;
1639     ofn.lpstrFilter = _filter;
1640     ofn.nFilterIndex = _filter_index;
1641     ofn.lpfnHook = GetSaveFileName_hookproc;
1642     ofn.lCustData = (LPARAM)this;
1644     _result = GetSaveFileNameW(&ofn) != 0;
1646         g_assert(ofn.nFilterIndex >= 1 && ofn.nFilterIndex <= _filter_count);
1647     _filter_index = ofn.nFilterIndex;
1648     _extension = _extension_map[ofn.nFilterIndex - 1];
1650     // Copy the selected file name, converting from UTF-16 to UTF-8
1651     myFilename = utf16_to_ustring(_path_string, _MAX_PATH);
1653     // Tidy up
1654     g_free(current_directory_string);
1656     g_main_loop_quit(_main_loop);
1659 /**
1660  * Show this dialog modally.  Return true if user hits [OK]
1661  */
1662 bool
1663 FileSaveDialogImplWin32::show()
1665     if(!Glib::thread_supported())
1666         Glib::thread_init();
1668     _result = false;
1669     _main_loop = g_main_loop_new(g_main_context_default(), FALSE);
1671         if(_main_loop != NULL)
1672         {
1673             if(Glib::Thread::create(sigc::mem_fun(*this, &FileSaveDialogImplWin32::GetSaveFileName_thread), true))
1674                 g_main_loop_run(_main_loop);
1676             if(_result)
1677                 appendExtension(myFilename, (Inkscape::Extension::Output*)_extension);
1678         }
1680     return _result;
1683 void FileSaveDialogImplWin32::setSelectionType( Inkscape::Extension::Extension * /*key*/ )
1685     // If no pointer to extension is passed in, look up based on filename extension.
1689 UINT_PTR CALLBACK FileSaveDialogImplWin32::GetSaveFileName_hookproc(
1690     HWND hdlg, UINT uiMsg, WPARAM, LPARAM lParam)
1692     FileSaveDialogImplWin32 *pImpl = (FileSaveDialogImplWin32*)
1693         GetWindowLongPtr(hdlg, GWLP_USERDATA);
1695     switch(uiMsg)
1696     {
1697     case WM_INITDIALOG:
1698         {
1699             HWND hParentWnd = GetParent(hdlg);
1700             HINSTANCE hInstance = GetModuleHandle(NULL);
1702             // get size/pos of typical combo box
1703             RECT rEDT1, rCB1, rROOT, rST;
1704             GetWindowRect(GetDlgItem(hParentWnd, cmb1), &rCB1);
1705             GetWindowRect(GetDlgItem(hParentWnd, cmb13), &rEDT1);
1706             GetWindowRect(GetDlgItem(hParentWnd, stc2), &rST);
1707             GetWindowRect(hdlg, &rROOT);
1708             int ydelta = rCB1.top - rEDT1.top;
1709             if ( ydelta < 0 ) {
1710                 g_warning("Negative dialog ydelta");
1711                 ydelta = 0;
1712             }
1714             // Make the window a bit longer
1715             // Note: we have a width delta of 1 because there is a suspicion that MoveWindow() to the same size causes zero-width results.
1716             RECT rcRect;
1717             GetWindowRect(hParentWnd, &rcRect);
1718             MoveWindow(hParentWnd, rcRect.left, rcRect.top,
1719                        sanitizeWindowSizeParam( rcRect.right - rcRect.left, 1, WINDOW_WIDTH_MINIMUM, WINDOW_WIDTH_FALLBACK ),
1720                        sanitizeWindowSizeParam( rcRect.bottom - rcRect.top, ydelta, WINDOW_HEIGHT_MINIMUM, WINDOW_HEIGHT_FALLBACK ),
1721                        FALSE);
1723             // It is not necessary to delete stock objects by calling DeleteObject
1724             HGDIOBJ dlgFont = GetStockObject(DEFAULT_GUI_FONT);
1726             // Set the pointer to the object
1727             OPENFILENAMEW *ofn = (OPENFILENAMEW*)lParam;
1728             SetWindowLongPtr(hdlg, GWLP_USERDATA, ofn->lCustData);
1729             SetWindowLongPtr(hParentWnd, GWLP_USERDATA, ofn->lCustData);
1730             pImpl = (FileSaveDialogImplWin32*)ofn->lCustData;
1732             // Create the Title label and edit control
1733             pImpl->_title_label = CreateWindowEx(NULL, "STATIC", "Title:",
1734                                         WS_VISIBLE|WS_CHILD,
1735                                         CW_USEDEFAULT, CW_USEDEFAULT, rCB1.left-rST.left, rST.bottom-rST.top,
1736                                         hParentWnd, NULL, hInstance, NULL);
1737             if(pImpl->_title_label) {
1738               if(dlgFont) SendMessage(pImpl->_title_label, WM_SETFONT, (WPARAM)dlgFont, MAKELPARAM(FALSE, 0));
1739               SetWindowPos(pImpl->_title_label, NULL, rST.left-rROOT.left, rST.top+ydelta-rROOT.top,
1740                            rCB1.left-rST.left, rST.bottom-rST.top, SWP_SHOWWINDOW|SWP_NOZORDER);
1741             }
1743             pImpl->_title_edit = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "",
1744                                         WS_VISIBLE|WS_CHILD|WS_TABSTOP|ES_AUTOHSCROLL,
1745                                         CW_USEDEFAULT, CW_USEDEFAULT, rCB1.right-rCB1.left, rCB1.bottom-rCB1.top,
1746                                         hParentWnd, NULL, hInstance, NULL);
1747             if(pImpl->_title_edit) {
1748               if(dlgFont) SendMessage(pImpl->_title_edit, WM_SETFONT, (WPARAM)dlgFont, MAKELPARAM(FALSE, 0));
1749               SetWindowPos(pImpl->_title_edit, NULL, rCB1.left-rROOT.left, rCB1.top+ydelta-rROOT.top,
1750                            rCB1.right-rCB1.left, rCB1.bottom-rCB1.top, SWP_SHOWWINDOW|SWP_NOZORDER);
1751               // TODO: make sure this works for Unicode
1752               SetWindowText(pImpl->_title_edit, pImpl->myDocTitle.c_str());
1753             }
1754         }
1755         break;
1756     case WM_DESTROY:
1757       {
1758         if(pImpl->_title_edit) {
1759           int length = GetWindowTextLength(pImpl->_title_edit)+1;
1760           char* temp_title = new char[length];
1761           GetWindowText(pImpl->_title_edit, temp_title, length);
1762           pImpl->myDocTitle = temp_title;
1763           delete[] temp_title;
1764           DestroyWindow(pImpl->_title_label);
1765           pImpl->_title_label = NULL;
1766           DestroyWindow(pImpl->_title_edit);
1767           pImpl->_title_edit = NULL;
1768         }
1769       }
1770       break;
1771     }
1773     // Use default dialog behaviour
1774     return 0;
1777 } } } // namespace Dialog, UI, Inkscape
1779 #endif // ifdef WIN32
1781 /*
1782   Local Variables:
1783   mode:c++
1784   c-file-style:"stroustrup"
1785   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1786   indent-tabs-mode:nil
1787   fill-column:99
1788   End:
1789 */
1790 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :