Code

Pot and Dutch translation update
[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  *
8  * Copyright (C) 2004-2008 The Inkscape Organization
9  *
10  * Released under GNU GPL, read the file 'COPYING' for more information
11  */
12 #ifdef WIN32
14 #ifdef HAVE_CONFIG_H
15 # include <config.h>
16 #endif
18 //General includes
19 #include <list>
20 #include <unistd.h>
21 #include <sys/stat.h>
22 #include <errno.h>
23 #include <set>
24 #include <gdk/gdkwin32.h>
25 #include <glib/gstdio.h>
26 #include <glibmm/i18n.h>
27 #include <gtkmm/window.h>
29 //Inkscape includes
30 #include "inkscape.h"
31 #include <dialogs/dialog-events.h>
32 #include <extension/input.h>
33 #include <extension/output.h>
34 #include <extension/db.h>
36 #include <libnr/nr-pixops.h>
37 #include <libnr/nr-translate-scale-ops.h>
38 #include <display/nr-arena-item.h>
39 #include <display/nr-arena.h>
40 #include "sp-item.h"
41 #include "display/canvas-arena.h"
43 #include "filedialog.h"
44 #include "filedialogimpl-win32.h"
46 #include <zlib.h>
47 #include <cairomm/win32_surface.h>
48 #include <cairomm/context.h>
50 using namespace std;
51 using namespace Glib;
52 using namespace Cairo;
53 using namespace Gdk::Cairo;
55 namespace Inkscape
56 {
57 namespace UI
58 {
59 namespace Dialog
60 {
62 const int PREVIEW_WIDENING = 150;
63 const int WINDOW_WIDTH_MINIMUM = 32;
64 const int WINDOW_WIDTH_FALLBACK = 450;
65 const int WINDOW_HEIGHT_MINIMUM = 32;
66 const int WINDOW_HEIGHT_FALLBACK = 360;
67 const char PreviewWindowClassName[] = "PreviewWnd";
68 const unsigned long MaxPreviewFileSize = 10240; // kB
70 #define IDC_SHOW_PREVIEW    1000
72 // Windows 2000 version of OPENFILENAMEW
73 struct OPENFILENAMEEXW : public OPENFILENAMEW {
74   void *        pvReserved;
75   DWORD         dwReserved;
76   DWORD         FlagsEx;
77 };
79 struct Filter
80 {
81     gunichar2* name;
82     glong name_length;
83     gunichar2* filter;
84     glong filter_length;
85     Inkscape::Extension::Extension* mod;
86 };
88 ustring utf16_to_ustring(const wchar_t *utf16string, int utf16length = -1)
89 {
90     gchar *utf8string = g_utf16_to_utf8((const gunichar2*)utf16string,
91         utf16length, NULL, NULL, NULL);
92     ustring result(utf8string);
93     g_free(utf8string);
95     return result;
96 }
98 namespace {
100 int sanitizeWindowSizeParam( int size, int delta, int minimum, int fallback )
102     int result = size;
103     if ( size < minimum ) {
104         g_warning( "Window size %d is less than cutoff.", size );
105         result = fallback - delta;
106     }
107     result += delta;
108     return result;
111 } // namespace
113 /*#########################################################################
114 ### F I L E     D I A L O G    B A S E    C L A S S
115 #########################################################################*/
117 FileDialogBaseWin32::FileDialogBaseWin32(Gtk::Window &parent,
118         const Glib::ustring &dir, const gchar *title,
119         FileDialogType type, gchar const* /*preferenceBase*/) :
120         dialogType(type),
121         parent(parent),
122         _current_directory(dir)
124     _main_loop = NULL;
126         _filter_index = 1;
127         _filter_count = 0;
129     _title = (wchar_t*)g_utf8_to_utf16(title, -1, NULL, NULL, NULL);
130         g_assert(_title != NULL);
132     Glib::RefPtr<const Gdk::Window> parentWindow = parent.get_window();
133     g_assert(parentWindow->gobj() != NULL);
134     _ownerHwnd = (HWND)gdk_win32_drawable_get_handle((GdkDrawable*)parentWindow->gobj());
137 FileDialogBaseWin32::~FileDialogBaseWin32()
139     g_free(_title);
142 Inkscape::Extension::Extension *FileDialogBaseWin32::getSelectionType()
144     return _extension;
147 Glib::ustring FileDialogBaseWin32::getCurrentDirectory()
149     return _current_directory;
152 /*#########################################################################
153 ### F I L E    O P E N
154 #########################################################################*/
156 bool FileOpenDialogImplWin32::_show_preview = true;
158 /**
159  * Constructor.  Not called directly.  Use the factory.
160  */
161 FileOpenDialogImplWin32::FileOpenDialogImplWin32(Gtk::Window &parent,
162                                        const Glib::ustring &dir,
163                                        FileDialogType fileTypes,
164                                        const gchar *title) :
165     FileDialogBaseWin32(parent, dir, title, fileTypes, "dialogs.open")
167     // Initalize to Autodetect
168     _extension = NULL;
170     // Set our dialog type (open, import, etc...)
171     dialogType = fileTypes;
173     _show_preview_button_bitmap = NULL;
174     _preview_wnd = NULL;
175     _file_dialog_wnd = NULL;
176     _base_window_proc = NULL;
178     _preview_file_size = 0;
179     _preview_bitmap = NULL;
180     _preview_file_icon = NULL;
181     _preview_document_width = 0;
182     _preview_document_height = 0;
183     _preview_image_width = 0;
184     _preview_image_height = 0;
185     _preview_emf_image = false;
187         _mutex = NULL;
189     createFilterMenu();
193 /**
194  * Destructor
195  */
196 FileOpenDialogImplWin32::~FileOpenDialogImplWin32()
198     if(_filter != NULL)
199         delete[] _filter;
200     if(_extension_map != NULL)
201         delete[] _extension_map;
204 void FileOpenDialogImplWin32::createFilterMenu()
206     list<Filter> filter_list;
208     // Compose the filter string
209     Inkscape::Extension::DB::InputList extension_list;
210     Inkscape::Extension::db.get_input_list(extension_list);
212     ustring all_inkscape_files_filter, all_image_files_filter, all_vectors_filter, all_bitmaps_filter;
213     Filter all_files, all_inkscape_files, all_image_files, all_vectors, all_bitmaps;
215     const gchar *all_files_filter_name = _("All Files");
216     const gchar *all_inkscape_files_filter_name = _("All Inkscape Files");
217     const gchar *all_image_files_filter_name = _("All Images");
218     const gchar *all_vectors_filter_name = _("All Vectors");
219     const gchar *all_bitmaps_filter_name = _("All Bitmaps");
221     // Calculate the amount of memory required
222     int filter_count = 5;       // 5 - one for each filter type
223     int filter_length = 1;
225     for (Inkscape::Extension::DB::InputList::iterator current_item = extension_list.begin();
226          current_item != extension_list.end(); current_item++)
227     {
228         Filter filter;
230         Inkscape::Extension::Input *imod = *current_item;
231         if (imod->deactivated()) continue;
233         // Type
234         filter.name = g_utf8_to_utf16(_(imod->get_filetypename()),
235             -1, NULL, &filter.name_length, NULL);
237         // Extension
238         const gchar *file_extension_name = imod->get_extension();
239         filter.filter = g_utf8_to_utf16(file_extension_name,
240             -1, NULL, &filter.filter_length, NULL);
242         filter.mod = imod;
243         filter_list.push_back(filter);
245         filter_length += filter.name_length +
246             filter.filter_length + 3;   // Add 3 for two \0s and a *
248         // Add to the "All Inkscape Files" Entry
249         if(all_inkscape_files_filter.length() > 0)
250             all_inkscape_files_filter += ";*";
251         all_inkscape_files_filter += file_extension_name;
252         if( strncmp("image", imod->get_mimetype(), 5) == 0)
253         {
254             // Add to the "All Image Files" Entry
255             if(all_image_files_filter.length() > 0)
256                 all_image_files_filter += ";*";
257             all_image_files_filter += file_extension_name;
258         }
260         // I don't know of any other way to define "bitmap" formats other than by listing them
261         // if you change it here, do the same change in filedialogimpl-gtkmm
262         if ( 
263             strncmp("image/png", imod->get_mimetype(), 9)==0 ||
264             strncmp("image/jpeg", imod->get_mimetype(), 10)==0 ||
265             strncmp("image/gif", imod->get_mimetype(), 9)==0 ||
266             strncmp("image/x-icon", imod->get_mimetype(), 12)==0 ||
267             strncmp("image/x-navi-animation", imod->get_mimetype(), 22)==0 ||
268             strncmp("image/x-cmu-raster", imod->get_mimetype(), 18)==0 ||
269             strncmp("image/x-xpixmap", imod->get_mimetype(), 15)==0 ||
270             strncmp("image/bmp", imod->get_mimetype(), 9)==0 ||
271             strncmp("image/vnd.wap.wbmp", imod->get_mimetype(), 18)==0 ||
272             strncmp("image/tiff", imod->get_mimetype(), 10)==0 ||
273             strncmp("image/x-xbitmap", imod->get_mimetype(), 15)==0 ||
274             strncmp("image/x-tga", imod->get_mimetype(), 11)==0 ||
275             strncmp("image/x-pcx", imod->get_mimetype(), 11)==0 
276             ) {
277             if(all_bitmaps_filter.length() > 0)
278                 all_bitmaps_filter += ";*";
279             all_bitmaps_filter += file_extension_name;
280         } else {
281             if(all_vectors_filter.length() > 0)
282                 all_vectors_filter += ";*";
283             all_vectors_filter += file_extension_name;
284         }
286         filter_count++;
287     }
289     int extension_index = 0;
290     _extension_map = new Inkscape::Extension::Extension*[filter_count];
292     // Filter bitmap files
293     all_bitmaps.name = g_utf8_to_utf16(all_bitmaps_filter_name,
294         -1, NULL, &all_bitmaps.name_length, NULL);
295     all_bitmaps.filter = g_utf8_to_utf16(all_bitmaps_filter.data(),
296             -1, NULL, &all_bitmaps.filter_length, NULL);
297         all_bitmaps.mod = NULL;
298     filter_list.push_front(all_bitmaps);
300     // Filter vector files
301     all_vectors.name = g_utf8_to_utf16(all_vectors_filter_name,
302         -1, NULL, &all_vectors.name_length, NULL);
303     all_vectors.filter = g_utf8_to_utf16(all_vectors_filter.data(),
304             -1, NULL, &all_vectors.filter_length, NULL);
305         all_vectors.mod = NULL;
306     filter_list.push_front(all_vectors);
308     // Filter Image Files
309     all_image_files.name = g_utf8_to_utf16(all_image_files_filter_name,
310         -1, NULL, &all_image_files.name_length, NULL);
311     all_image_files.filter = g_utf8_to_utf16(all_image_files_filter.data(),
312             -1, NULL, &all_image_files.filter_length, NULL);
313         all_image_files.mod = NULL;
314     filter_list.push_front(all_image_files);
316     // Filter Inkscape Files
317     all_inkscape_files.name = g_utf8_to_utf16(all_inkscape_files_filter_name,
318         -1, NULL, &all_inkscape_files.name_length, NULL);
319     all_inkscape_files.filter = g_utf8_to_utf16(all_inkscape_files_filter.data(),
320             -1, NULL, &all_inkscape_files.filter_length, NULL);
321         all_inkscape_files.mod = NULL;
322     filter_list.push_front(all_inkscape_files);
324     // Filter All Files
325     all_files.name = g_utf8_to_utf16(all_files_filter_name,
326         -1, NULL, &all_files.name_length, NULL);
327     all_files.filter = NULL;
328     all_files.filter_length = 0;
329         all_files.mod = NULL;
330     filter_list.push_front(all_files);
332     filter_length += all_files.name_length + 3 +
333                     all_inkscape_files.filter_length +
334                     all_inkscape_files.name_length + 3 +
335                     all_image_files.filter_length +
336                     all_image_files.name_length + 3 +
337                     all_vectors.filter_length +
338                     all_vectors.name_length + 3 +
339                     all_bitmaps.filter_length +
340                     all_bitmaps.name_length + 3 +
341                                                   1;
342      // Add 3 for 2*2 \0s and a *, and 1 for a trailing \0
344         _filter = new wchar_t[filter_length];
345     wchar_t *filterptr = _filter;
347     for(list<Filter>::iterator filter_iterator = filter_list.begin();
348         filter_iterator != filter_list.end(); filter_iterator++)
349     {
350         const Filter &filter = *filter_iterator;
352         wcsncpy(filterptr, (wchar_t*)filter.name, filter.name_length);
353         filterptr += filter.name_length;
354         g_free(filter.name);
356         *(filterptr++) = L'\0';
357         *(filterptr++) = L'*';
359         if(filter.filter != NULL)
360         {
361             wcsncpy(filterptr, (wchar_t*)filter.filter, filter.filter_length);
362             filterptr += filter.filter_length;
363             g_free(filter.filter);
364         }
366         *(filterptr++) = L'\0';
368         // Associate this input extension with the file type name
369         _extension_map[extension_index++] = filter.mod;
370     }
371     *(filterptr++) = L'\0';
373         _filter_count = extension_index;
374     _filter_index = 2;  // Select the 2nd filter in the list - 2 is NOT the 3rd
377 void FileOpenDialogImplWin32::GetOpenFileName_thread()
379     OPENFILENAMEEXW ofn;
381     g_assert(this != NULL);
382         g_assert(_mutex != NULL);
384     WCHAR* current_directory_string = (WCHAR*)g_utf8_to_utf16(
385         _current_directory.data(), _current_directory.length(),
386                 NULL, NULL, NULL);
388     memset(&ofn, 0, sizeof(ofn));
390     // Copy the selected file name, converting from UTF-8 to UTF-16
391     memset(_path_string, 0, sizeof(_path_string));
392     gunichar2* utf16_path_string = g_utf8_to_utf16(
393         myFilename.data(), -1, NULL, NULL, NULL);
394     wcsncpy(_path_string, (wchar_t*)utf16_path_string, _MAX_PATH);
395     g_free(utf16_path_string);
397     ofn.lStructSize = sizeof(ofn);
398     ofn.hwndOwner = _ownerHwnd;
399     ofn.lpstrFile = _path_string;
400     ofn.nMaxFile = _MAX_PATH;
401     ofn.lpstrFileTitle = NULL;
402     ofn.nMaxFileTitle = 0;
403     ofn.lpstrInitialDir = current_directory_string;
404     ofn.lpstrTitle = _title;
405     ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ENABLEHOOK | OFN_HIDEREADONLY | OFN_ENABLESIZING;
406     ofn.lpstrFilter = _filter;
407     ofn.nFilterIndex = _filter_index;
408     ofn.lpfnHook = GetOpenFileName_hookproc;
409     ofn.lCustData = (LPARAM)this;
411     _result = GetOpenFileNameW(&ofn) != 0;
413         g_assert(ofn.nFilterIndex >= 1 && ofn.nFilterIndex <= _filter_count);
414     _filter_index = ofn.nFilterIndex;
415     _extension = _extension_map[ofn.nFilterIndex - 1];
417     // Copy the selected file name, converting from UTF-16 to UTF-8
418     myFilename = utf16_to_ustring(_path_string, _MAX_PATH);
420     // Tidy up
421     g_free(current_directory_string);
423     _mutex->lock();
424     _finished = true;
425     _mutex->unlock();
428 void FileOpenDialogImplWin32::register_preview_wnd_class()
430     HINSTANCE hInstance = GetModuleHandle(NULL);
431     const WNDCLASSA PreviewWndClass =
432     {
433         CS_HREDRAW | CS_VREDRAW,
434         preview_wnd_proc,
435         0,
436         0,
437         hInstance,
438         NULL,
439         LoadCursor(hInstance, IDC_ARROW),
440         (HBRUSH)(COLOR_BTNFACE + 1),
441         NULL,
442         PreviewWindowClassName
443     };
445     RegisterClassA(&PreviewWndClass);
448 UINT_PTR CALLBACK FileOpenDialogImplWin32::GetOpenFileName_hookproc(
449     HWND hdlg, UINT uiMsg, WPARAM, LPARAM lParam)
451     FileOpenDialogImplWin32 *pImpl = (FileOpenDialogImplWin32*)
452         GetWindowLongPtr(hdlg, GWLP_USERDATA);
454     switch(uiMsg)
455     {
456     case WM_INITDIALOG:
457         {
458             HWND hParentWnd = GetParent(hdlg);
459             HINSTANCE hInstance = GetModuleHandle(NULL);
461             // Make the window a bit wider
462             RECT rcRect;
463             GetWindowRect(hParentWnd, &rcRect);
464             MoveWindow(hParentWnd, rcRect.left, rcRect.top,
465                        rcRect.right - rcRect.left + PREVIEW_WIDENING,
466                        rcRect.bottom - rcRect.top,
467                        FALSE);
469             // Set the pointer to the object
470             OPENFILENAMEW *ofn = (OPENFILENAMEW*)lParam;
471             SetWindowLongPtr(hdlg, GWLP_USERDATA, ofn->lCustData);
472             SetWindowLongPtr(hParentWnd, GWLP_USERDATA, ofn->lCustData);
473             pImpl = (FileOpenDialogImplWin32*)ofn->lCustData;
475             // Subclass the parent
476             pImpl->_base_window_proc = (WNDPROC)GetWindowLongPtr(hParentWnd, GWLP_WNDPROC);
477             SetWindowLongPtr(hParentWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(file_dialog_subclass_proc));
479             // Add a button to the toolbar
480             pImpl->_toolbar_wnd = FindWindowEx(hParentWnd, NULL, "ToolbarWindow32", NULL);
482             pImpl->_show_preview_button_bitmap = LoadBitmap(
483                 hInstance, MAKEINTRESOURCE(IDC_SHOW_PREVIEW));
484             TBADDBITMAP tbAddBitmap = {NULL, reinterpret_cast<UINT_PTR>(pImpl->_show_preview_button_bitmap)};
485             const int iBitmapIndex = SendMessage(pImpl->_toolbar_wnd,
486                 TB_ADDBITMAP, 1, (LPARAM)&tbAddBitmap);
488             TBBUTTON tbButton;
489             memset(&tbButton, 0, sizeof(TBBUTTON));
490             tbButton.iBitmap = iBitmapIndex;
491             tbButton.idCommand = IDC_SHOW_PREVIEW;
492             tbButton.fsState = (pImpl->_show_preview ? TBSTATE_CHECKED : 0)
493                 | TBSTATE_ENABLED;
494             tbButton.fsStyle = TBSTYLE_CHECK;
495             tbButton.iString = (INT_PTR)_("Show Preview");
496             SendMessage(pImpl->_toolbar_wnd, TB_ADDBUTTONS, 1, (LPARAM)&tbButton);
498             // Create preview pane
499             register_preview_wnd_class();
501             pImpl->_mutex->lock();
503                 pImpl->_file_dialog_wnd = hParentWnd;
505                 pImpl->_preview_wnd =
506                     CreateWindowA(PreviewWindowClassName, "",
507                         WS_CHILD | WS_VISIBLE,
508                         0, 0, 100, 100, hParentWnd, NULL, hInstance, NULL);
509                 SetWindowLongPtr(pImpl->_preview_wnd, GWLP_USERDATA, ofn->lCustData);
511             pImpl->_mutex->unlock();
513             pImpl->layout_dialog();
514         }
515         break;
517     case WM_NOTIFY:
518         {
520         OFNOTIFY *pOFNotify = reinterpret_cast<OFNOTIFY*>(lParam);
521         switch(pOFNotify->hdr.code)
522         {
523         case CDN_SELCHANGE:
524             {
525                 if(pImpl != NULL)
526                 {
527                     // Get the file name
528                     pImpl->_mutex->lock();
530                     SendMessage(pOFNotify->hdr.hwndFrom, CDM_GETFILEPATH,
531                         sizeof(pImpl->_path_string) / sizeof(wchar_t),
532                         (LPARAM)pImpl->_path_string);
534                     pImpl->_file_selected = true;
536                     pImpl->_mutex->unlock();
537                 }
538             }
539             break;
540         }
541         }
542         break;
544     case WM_CLOSE:
545         pImpl->_mutex->lock();
546         pImpl->_preview_file_size = 0;
548         pImpl->_file_dialog_wnd = NULL;
549         DestroyWindow(pImpl->_preview_wnd);
550         pImpl->_preview_wnd = NULL;
551         DeleteObject(pImpl->_show_preview_button_bitmap);
552         pImpl->_show_preview_button_bitmap = NULL;
553         pImpl->_mutex->unlock();
555         break;
556     }
558     // Use default dialog behaviour
559     return 0;
562 LRESULT CALLBACK FileOpenDialogImplWin32::file_dialog_subclass_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
564     FileOpenDialogImplWin32 *pImpl = (FileOpenDialogImplWin32*)
565         GetWindowLongPtr(hwnd, GWLP_USERDATA);
567     LRESULT lResult = CallWindowProc(pImpl->_base_window_proc, hwnd, uMsg, wParam, lParam);
569     switch(uMsg)
570     {
571     case WM_SHOWWINDOW:
572         if(wParam != 0)
573             pImpl->layout_dialog();
574         break;
576     case WM_SIZE:
577         pImpl->layout_dialog();
578         break;
580     case WM_COMMAND:
581         if(wParam == IDC_SHOW_PREVIEW)
582         {
583             const bool enable = SendMessage(pImpl->_toolbar_wnd,
584                 TB_ISBUTTONCHECKED, IDC_SHOW_PREVIEW, 0) != 0;
585             pImpl->enable_preview(enable);
586         }
587         break;
588     }
590     return lResult;
593 LRESULT CALLBACK FileOpenDialogImplWin32::preview_wnd_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
595     const int CaptionPadding = 4;
596     const int IconSize = 32;
598     FileOpenDialogImplWin32 *pImpl = (FileOpenDialogImplWin32*)
599         GetWindowLongPtr(hwnd, GWLP_USERDATA);
601     LRESULT lResult = 0;
603     switch(uMsg)
604     {
605     case WM_ERASEBKGND:
606         // Do nothing to erase the background
607         //  - otherwise there'll be flicker
608         lResult = 1;
609         break;
611     case WM_PAINT:
612         {
613             // Get the client rect
614             RECT rcClient;
615             GetClientRect(hwnd, &rcClient);
617             // Prepare to paint
618             PAINTSTRUCT paint_struct;
619             HDC dc = BeginPaint(hwnd, &paint_struct);
621             HFONT hCaptionFont = (HFONT)SendMessage(GetParent(hwnd),
622                     WM_GETFONT, 0, 0);
623             HFONT hOldFont = (HFONT)SelectObject(dc, hCaptionFont);
624             SetBkMode(dc, TRANSPARENT);
626             pImpl->_mutex->lock();
628             if(pImpl->_path_string[0] == 0)
629             {
630                 WCHAR* noFileText=(WCHAR*)g_utf8_to_utf16(_("No file selected"),
631                     -1, NULL, NULL, NULL);
632                 FillRect(dc, &rcClient, (HBRUSH)(COLOR_3DFACE + 1));
633                 DrawTextW(dc,  noFileText, -1, &rcClient, 
634                     DT_CENTER | DT_VCENTER | DT_NOPREFIX);
635                 g_free(noFileText);
636             }
637             else if(pImpl->_preview_bitmap != NULL)
638             {
639                 BITMAP bitmap;
640                 GetObject(pImpl->_preview_bitmap, sizeof(bitmap), &bitmap);
641                 const int destX = (rcClient.right - bitmap.bmWidth) / 2;
643                 // Render the image
644                 HDC hSrcDC = CreateCompatibleDC(dc);
645                 HBITMAP hOldBitmap = (HBITMAP)SelectObject(hSrcDC, pImpl->_preview_bitmap);
647                 BitBlt(dc, destX, 0, bitmap.bmWidth, bitmap.bmHeight,
648                     hSrcDC, 0, 0, SRCCOPY);
650                 SelectObject(hSrcDC, hOldBitmap);
651                 DeleteDC(hSrcDC);
653                 // Fill in the background area
654                 HRGN hEraseRgn = CreateRectRgn(rcClient.left, rcClient.top,
655                     rcClient.right, rcClient.bottom);
656                 HRGN hImageRgn = CreateRectRgn(destX, 0,
657                     destX + bitmap.bmWidth, bitmap.bmHeight);
658                 CombineRgn(hEraseRgn, hEraseRgn, hImageRgn, RGN_DIFF);
660                 FillRgn(dc, hEraseRgn, GetSysColorBrush(COLOR_3DFACE));
662                 DeleteObject(hImageRgn);
663                 DeleteObject(hEraseRgn);
665                 // Draw the caption on
666                 RECT rcCaptionRect = {rcClient.left,
667                     rcClient.top + bitmap.bmHeight + CaptionPadding,
668                     rcClient.right, rcClient.bottom};
670                 WCHAR szCaption[_MAX_FNAME + 32];
671                 const int iLength = pImpl->format_caption(
672                     szCaption, sizeof(szCaption) / sizeof(WCHAR));
674                 DrawTextW(dc, szCaption, iLength, &rcCaptionRect,
675                     DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS);
676             }
677             else if(pImpl->_preview_file_icon != NULL)
678             {
679                 FillRect(dc, &rcClient, (HBRUSH)(COLOR_3DFACE + 1));
681                 // Draw the files icon
682                 const int destX = (rcClient.right - IconSize) / 2;
683                 DrawIconEx(dc, destX, 0, pImpl->_preview_file_icon,
684                     IconSize, IconSize, 0, NULL,
685                     DI_NORMAL | DI_COMPAT);
687                 // Draw the caption on
688                 RECT rcCaptionRect = {rcClient.left,
689                     rcClient.top + IconSize + CaptionPadding,
690                     rcClient.right, rcClient.bottom};
692                 WCHAR szFileName[_MAX_FNAME], szCaption[_MAX_FNAME + 32];
693                 _wsplitpath(pImpl->_path_string, NULL, NULL, szFileName, NULL);
695                 const int iLength = snwprintf(szCaption,
696                     sizeof(szCaption), L"%s\n%d kB",
697                     szFileName, pImpl->_preview_file_size);
699                 DrawTextW(dc, szCaption, iLength, &rcCaptionRect,
700                     DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS);
701             }
702             else
703             {
704                 // Can't show anything!
705                 FillRect(dc, &rcClient, (HBRUSH)(COLOR_3DFACE + 1));
706             }
708             pImpl->_mutex->unlock();
710             // Finish painting
711             SelectObject(dc, hOldFont);
712             EndPaint(hwnd, &paint_struct);
713         }
715         break;
717     case WM_DESTROY:
718         pImpl->free_preview();
719         break;
721     default:
722         lResult = DefWindowProc(hwnd, uMsg, wParam, lParam);
723         break;
724     }
726     return lResult;
729 void FileOpenDialogImplWin32::enable_preview(bool enable)
731     _show_preview = enable;
733     // Relayout the dialog
734     ShowWindow(_preview_wnd, enable ? SW_SHOW : SW_HIDE);
735     layout_dialog();
737     // Load or unload the preview
738     if(enable)
739     {
740         _mutex->lock();
741         _file_selected = true;
742         _mutex->unlock();
743     }
744     else free_preview();
747 void FileOpenDialogImplWin32::layout_dialog()
749     union RECTPOINTS
750     {
751         RECT r;
752         POINT p[2];
753     };
755     const float MaxExtentScale = 2.0f / 3.0f;
757     RECT rcClient;
758     GetClientRect(_file_dialog_wnd, &rcClient);
760     // Re-layout the dialog
761     HWND hFileListWnd = GetDlgItem(_file_dialog_wnd, lst2);
762     HWND hFolderComboWnd = GetDlgItem(_file_dialog_wnd, cmb2);
765     RECT rcFolderComboRect;
766     RECTPOINTS rcFileList;
767     GetWindowRect(hFileListWnd, &rcFileList.r);
768     GetWindowRect(hFolderComboWnd, &rcFolderComboRect);
769     const int iPadding = rcFileList.r.top - rcFolderComboRect.bottom;
770     MapWindowPoints(NULL, _file_dialog_wnd, rcFileList.p, 2);
772     RECT rcPreview;
773     RECT rcBody = {rcFileList.r.left, rcFileList.r.top,
774         rcClient.right - iPadding, rcFileList.r.bottom};
775     rcFileList.r.right = rcBody.right;
777     if(_show_preview)
778     {
779         rcPreview.top = rcBody.top;
780         rcPreview.left = rcClient.right - (rcBody.bottom - rcBody.top);
781         const int iMaxExtent = (int)(MaxExtentScale * (float)(rcBody.left + rcBody.right)) + iPadding / 2;
782         if(rcPreview.left < iMaxExtent) rcPreview.left = iMaxExtent;
783         rcPreview.bottom = rcBody.bottom;
784         rcPreview.right = rcBody.right;
786         // Re-layout the preview box
787         _mutex->lock();
789             _preview_width = rcPreview.right - rcPreview.left;
790             _preview_height = rcPreview.bottom - rcPreview.top;
792         _mutex->unlock();
794         render_preview();
796         MoveWindow(_preview_wnd, rcPreview.left, rcPreview.top,
797             _preview_width, _preview_height, TRUE);
799         rcFileList.r.right = rcPreview.left - iPadding;
800     }
802     // Re-layout the file list box
803     MoveWindow(hFileListWnd, rcFileList.r.left, rcFileList.r.top,
804         rcFileList.r.right - rcFileList.r.left,
805         rcFileList.r.bottom - rcFileList.r.top, TRUE);
807     // Re-layout the toolbar
808     RECTPOINTS rcToolBar;
809     GetWindowRect(_toolbar_wnd, &rcToolBar.r);
810     MapWindowPoints(NULL, _file_dialog_wnd, rcToolBar.p, 2);
811     MoveWindow(_toolbar_wnd, rcToolBar.r.left, rcToolBar.r.top,
812         rcToolBar.r.right - rcToolBar.r.left, rcToolBar.r.bottom - rcToolBar.r.top, TRUE);
815 void FileOpenDialogImplWin32::file_selected()
817     // Destroy any previous previews
818     free_preview();
821     // Determine if the file exists
822     DWORD attributes = GetFileAttributesW(_path_string);
823     if(attributes == 0xFFFFFFFF ||
824         attributes == FILE_ATTRIBUTE_DIRECTORY)
825     {
826         InvalidateRect(_preview_wnd, NULL, FALSE);
827         return;
828     }
830     // Check the file exists and get the file size
831     HANDLE file_handle = CreateFileW(_path_string, GENERIC_READ,
832         FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
833     if(file_handle == INVALID_HANDLE_VALUE) return;
834     const DWORD file_size = GetFileSize(file_handle, NULL);
835     if (file_size == INVALID_FILE_SIZE) return;
836     _preview_file_size = file_size / 1024;
837     CloseHandle(file_handle);
839     if(_show_preview) load_preview();
842 void FileOpenDialogImplWin32::load_preview()
844     // Destroy any previous previews
845     free_preview();
847     // Try to get the file icon
848     SHFILEINFOW fileInfo;
849     if(SUCCEEDED(SHGetFileInfoW(_path_string, 0, &fileInfo,
850         sizeof(fileInfo), SHGFI_ICON | SHGFI_LARGEICON)))
851         _preview_file_icon = fileInfo.hIcon;
853     // Will this file be too big?
854     if(_preview_file_size > MaxPreviewFileSize)
855     {
856         InvalidateRect(_preview_wnd, NULL, FALSE);
857         return;
858     }
860     // Prepare to render a preview
861     const Glib::ustring svg = ".svg";
862     const Glib::ustring svgz = ".svgz";
863     const Glib::ustring emf = ".emf";
864     const Glib::ustring wmf = ".wmf";
865     const Glib::ustring path = utf16_to_ustring(_path_string);
867     bool success = false;
869     _preview_document_width = _preview_document_height = 0;
871     if ((dialogType == SVG_TYPES || dialogType == IMPORT_TYPES) &&
872             (hasSuffix(path, svg) || hasSuffix(path, svgz)))
873         success = set_svg_preview();
874     else if (hasSuffix(path, emf) || hasSuffix(path, wmf))
875         success = set_emf_preview();
876     else if (isValidImageFile(path))
877         success = set_image_preview();
878     else {
879         // Show no preview
880     }
882     if(success) render_preview();
884     InvalidateRect(_preview_wnd, NULL, FALSE);
887 void FileOpenDialogImplWin32::free_preview()
889     _mutex->lock();
890     if(_preview_bitmap != NULL)
891         DeleteObject(_preview_bitmap);
892     _preview_bitmap = NULL;
894     if(_preview_file_icon != NULL)
895         DestroyIcon(_preview_file_icon);
896     _preview_file_icon = NULL;
898     _preview_bitmap_image.clear();
899     _preview_emf_image = false;
900     _mutex->unlock();
903 bool FileOpenDialogImplWin32::set_svg_preview()
905     const int PreviewSize = 512;
907     gchar *utf8string = g_utf16_to_utf8((const gunichar2*)_path_string,
908         _MAX_PATH, NULL, NULL, NULL);
909     SPDocument *svgDoc = sp_document_new (utf8string, true);
910     g_free(utf8string);
912     // Check the document loaded properly
913     if(svgDoc == NULL) return false;
914     if(svgDoc->root == NULL)
915     {
916         sp_document_unref(svgDoc);
917         return false;
918     }
920     // Get the size of the document
921     const double svgWidth = sp_document_width(svgDoc);
922     const double svgHeight = sp_document_height(svgDoc);
924     // Find the minimum scale to fit the image inside the preview area
925     const double scaleFactorX =    PreviewSize / svgWidth;
926     const double scaleFactorY =    PreviewSize / svgHeight;
927     const double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX;
929     // Now get the resized values
930     const double scaledSvgWidth  = scaleFactor * svgWidth;
931     const double scaledSvgHeight = scaleFactor * svgHeight;
933     Geom::Rect area(Geom::Point(0, 0), Geom::Point(scaledSvgWidth, scaledSvgHeight));
934     NRRectL areaL = {0, 0, scaledSvgWidth, scaledSvgHeight};
935     NRRectL bbox = {0, 0, scaledSvgWidth, scaledSvgHeight};
937     // write object bbox to area
938     Geom::OptRect maybeArea(area);
939     sp_document_ensure_up_to_date (svgDoc);
940     sp_item_invoke_bbox((SPItem *) svgDoc->root, maybeArea,
941         sp_item_i2d_affine((SPItem *)(svgDoc->root)), TRUE);
943     NRArena *const arena = NRArena::create();
945     unsigned const key = sp_item_display_key_new(1);
947     NRArenaItem *root = sp_item_invoke_show((SPItem*)(svgDoc->root),
948         arena, key, SP_ITEM_SHOW_DISPLAY);
950     NRGC gc(NULL);
951     gc.transform = Geom::Matrix(Geom::Scale(scaleFactor, scaleFactor));
953     nr_arena_item_invoke_update (root, NULL, &gc,
954         NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
956     // Prepare a GDI compatible NRPixBlock
957     NRPixBlock pixBlock;
958     pixBlock.size = NR_PIXBLOCK_SIZE_BIG;
959     pixBlock.mode = NR_PIXBLOCK_MODE_R8G8B8;
960     pixBlock.empty = 1;
961     pixBlock.visible_area.x0 = pixBlock.area.x0 = 0;
962     pixBlock.visible_area.y0 = pixBlock.area.y0 = 0;
963     pixBlock.visible_area.x1 = pixBlock.area.x1 = scaledSvgWidth;
964     pixBlock.visible_area.y1 = pixBlock.area.y1 = scaledSvgHeight;
965     pixBlock.rs = 4 * ((3 * (int)scaledSvgWidth + 3) / 4);
966     pixBlock.data.px = g_try_new (unsigned char, pixBlock.rs * scaledSvgHeight);
968     // Fail if the pixblock failed to allocate
969     if(pixBlock.data.px == NULL)
970     {
971         sp_document_unref(svgDoc);
972         return false;
973     }
975     memset(pixBlock.data.px, 0xFF, pixBlock.rs * scaledSvgHeight);
977     memcpy(&root->bbox, &areaL, sizeof(areaL));
979     // Render the image
980     nr_arena_item_invoke_render(NULL, root, &bbox, &pixBlock, /*0*/NR_ARENA_ITEM_RENDER_NO_CACHE);
982     // Tidy up
983     sp_document_unref(svgDoc);
984     sp_item_invoke_hide((SPItem*)(svgDoc->root), key);
985     nr_object_unref((NRObject *) arena);
987     // Create the GDK pixbuf
988     _mutex->lock();
990     _preview_bitmap_image = Gdk::Pixbuf::create_from_data(
991         pixBlock.data.px, Gdk::COLORSPACE_RGB, false, 8,
992         (int)scaledSvgWidth, (int)scaledSvgHeight, pixBlock.rs,
993         sigc::ptr_fun(destroy_svg_rendering));
995     _preview_document_width = scaledSvgWidth;
996     _preview_document_height = scaledSvgHeight;
997     _preview_image_width = svgWidth;
998     _preview_image_height = svgHeight;
1000     _mutex->unlock();
1002     return true;
1005 void FileOpenDialogImplWin32::destroy_svg_rendering(const guint8 *buffer)
1007     g_assert(buffer != NULL);
1008     g_free((void*)buffer);
1011 bool FileOpenDialogImplWin32::set_image_preview()
1013     const Glib::ustring path = utf16_to_ustring(_path_string, _MAX_PATH);
1015     bool successful = false;
1017     _mutex->lock();
1019     try {
1020         _preview_bitmap_image = Gdk::Pixbuf::create_from_file(path);
1021         if (_preview_bitmap_image) {
1022             _preview_image_width = _preview_bitmap_image->get_width();
1023             _preview_document_width = _preview_image_width;
1024             _preview_image_height = _preview_bitmap_image->get_height();
1025             _preview_document_height = _preview_image_height;
1026             successful = true;
1027         }
1028     }
1029     catch (const Gdk::PixbufError&) {}
1030     catch (const Glib::FileError&) {}
1032     _mutex->unlock();
1034     return successful;
1037 // Aldus Placeable Header ===================================================
1038 // Since we are a 32bit app, we have to be sure this structure compiles to
1039 // be identical to a 16 bit app's version. To do this, we use the #pragma
1040 // to adjust packing, we use a WORD for the hmf handle, and a SMALL_RECT
1041 // for the bbox rectangle.
1042 #pragma pack( push )
1043 #pragma pack( 2 )
1044 typedef struct
1046     DWORD       dwKey;
1047     WORD        hmf;
1048     SMALL_RECT  bbox;
1049     WORD        wInch;
1050     DWORD       dwReserved;
1051     WORD        wCheckSum;
1052 } APMHEADER, *PAPMHEADER;
1053 #pragma pack( pop )
1056 static HENHMETAFILE
1057 MyGetEnhMetaFileW( const WCHAR *filename )
1059     // Try open as Enhanced Metafile
1060     HENHMETAFILE hemf = GetEnhMetaFileW(filename);
1062     if (!hemf) {
1063         // Try open as Windows Metafile
1064         HMETAFILE hmf = GetMetaFileW(filename);
1066         METAFILEPICT mp;
1067         HDC hDC;
1069         if (!hmf) {
1070             WCHAR szTemp[MAX_PATH];
1072             DWORD dw = GetShortPathNameW( filename, szTemp, MAX_PATH );
1073             if (dw) {
1074                 hmf = GetMetaFileW( szTemp );
1075             }
1076         }
1078         if (hmf) {
1079             // Convert Windows Metafile to Enhanced Metafile
1080             DWORD nSize = GetMetaFileBitsEx( hmf, 0, NULL );
1082             if (nSize) {
1083                 BYTE *lpvData = new BYTE[nSize];
1084                 if (lpvData) {
1085                     DWORD dw = GetMetaFileBitsEx( hmf, nSize, lpvData );
1086                     if (dw) {
1087                         // Fill out a METAFILEPICT structure
1088                         mp.mm = MM_ANISOTROPIC;
1089                         mp.xExt = 1000;
1090                         mp.yExt = 1000;
1091                         mp.hMF = NULL;
1092                         // Get a reference DC
1093                         hDC = GetDC( NULL );
1094                         // Make an enhanced metafile from the windows metafile
1095                         hemf = SetWinMetaFileBits( nSize, lpvData, hDC, &mp );
1096                         // Clean up
1097                         ReleaseDC( NULL, hDC );
1098                         DeleteMetaFile( hmf );
1099                     }
1100                     delete[] lpvData;
1101                 }
1102                 else {
1103                     DeleteMetaFile( hmf );
1104                 }
1105             }
1106             else {
1107                 DeleteMetaFile( hmf );
1108             }
1109         }
1110         else {
1111             // Try open as Aldus Placeable Metafile
1112             HANDLE hFile;
1113             hFile = CreateFileW( filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
1115             if (hFile != INVALID_HANDLE_VALUE) {
1116                 DWORD nSize = GetFileSize( hFile, NULL );
1117                 if (nSize) {
1118                     BYTE *lpvData = new BYTE[nSize];
1119                     if (lpvData) {
1120                         DWORD dw = ReadFile( hFile, lpvData, nSize, &nSize, NULL );
1121                         if (dw) {
1122                             if ( ((PAPMHEADER)lpvData)->dwKey == 0x9ac6cdd7l ) {
1123                                 // Fill out a METAFILEPICT structure
1124                                 mp.mm = MM_ANISOTROPIC;
1125                                 mp.xExt = ((PAPMHEADER)lpvData)->bbox.Right - ((PAPMHEADER)lpvData)->bbox.Left;
1126                                 mp.xExt = ( mp.xExt * 2540l ) / (DWORD)(((PAPMHEADER)lpvData)->wInch);
1127                                 mp.yExt = ((PAPMHEADER)lpvData)->bbox.Bottom - ((PAPMHEADER)lpvData)->bbox.Top;
1128                                 mp.yExt = ( mp.yExt * 2540l ) / (DWORD)(((PAPMHEADER)lpvData)->wInch);
1129                                 mp.hMF = NULL;
1130                                 // Get a reference DC
1131                                 hDC = GetDC( NULL );
1132                                 // Create an enhanced metafile from the bits
1133                                 hemf = SetWinMetaFileBits( nSize, lpvData+sizeof(APMHEADER), hDC, &mp );
1134                                 // Clean up
1135                                 ReleaseDC( NULL, hDC );
1136                             }
1137                         }
1138                         delete[] lpvData;
1139                     }
1140                 }
1141                 CloseHandle( hFile );
1142             }
1143         }
1144     }
1146     return hemf;
1150 bool FileOpenDialogImplWin32::set_emf_preview()
1152     _mutex->lock();
1154     BOOL ok = FALSE;
1156     DWORD w = 0;
1157     DWORD h = 0;
1159     HENHMETAFILE hemf = MyGetEnhMetaFileW( _path_string );
1161     if (hemf)
1162     {
1163         ENHMETAHEADER emh;
1164         ZeroMemory(&emh, sizeof(emh));
1165         ok = GetEnhMetaFileHeader(hemf, sizeof(emh), &emh) != 0;
1167         w = (emh.rclFrame.right - emh.rclFrame.left);
1168         h = (emh.rclFrame.bottom - emh.rclFrame.top);
1170         DeleteEnhMetaFile(hemf);
1171     }
1173     if (ok)
1174     {
1175         const int PreviewSize = 512;
1177         // Get the size of the document
1178         const double emfWidth = w;
1179         const double emfHeight = h;
1181         // Find the minimum scale to fit the image inside the preview area
1182         const double scaleFactorX =    PreviewSize / emfWidth;
1183         const double scaleFactorY =    PreviewSize / emfHeight;
1184         const double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX;
1186         // Now get the resized values
1187         const double scaledEmfWidth  = scaleFactor * emfWidth;
1188         const double scaledEmfHeight = scaleFactor * emfHeight;
1190         _preview_document_width = scaledEmfWidth;
1191         _preview_document_height = scaledEmfHeight;
1192         _preview_image_width = emfWidth;
1193         _preview_image_height = emfHeight;
1195         _preview_emf_image = true;
1196     }
1198     _mutex->unlock();
1200     return ok;
1203 void FileOpenDialogImplWin32::render_preview()
1205     double x, y;
1206     const double blurRadius = 8;
1207     const double halfBlurRadius = blurRadius / 2;
1208     const int shaddowOffsetX = 0;
1209     const int shaddowOffsetY = 2;
1210     const int pagePadding = 5;
1211     const double shaddowAlpha = 0.75;
1213     // Is the preview showing?
1214     if(!_show_preview)
1215         return;
1217     // Do we have anything to render?
1218     _mutex->lock();
1220     if(!_preview_bitmap_image && !_preview_emf_image)
1221     {
1222         _mutex->unlock();
1223         return;
1224     }
1226     // Tidy up any previous bitmap renderings
1227     if(_preview_bitmap != NULL)
1228         DeleteObject(_preview_bitmap);
1229     _preview_bitmap = NULL;
1231     // Calculate the size of the caption
1232     int captionHeight = 0;
1234     if(_preview_wnd != NULL)
1235     {
1236         RECT rcCaptionRect;
1237         WCHAR szCaption[_MAX_FNAME + 32];
1238         const int iLength = format_caption(szCaption,
1239             sizeof(szCaption) / sizeof(WCHAR));
1241         HDC dc = GetDC(_preview_wnd);
1242         DrawTextW(dc, szCaption, iLength, &rcCaptionRect,
1243             DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_CALCRECT);
1244         ReleaseDC(_preview_wnd, dc);
1246         captionHeight = rcCaptionRect.bottom - rcCaptionRect.top;
1247     }
1249     // Find the minimum scale to fit the image inside the preview area
1250     const double scaleFactorX =
1251         ((double)_preview_width - pagePadding * 2 - blurRadius)  / _preview_document_width;
1252     const double scaleFactorY =
1253         ((double)_preview_height - pagePadding * 2
1254         - shaddowOffsetY - halfBlurRadius - captionHeight) / _preview_document_height;
1255     double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX;
1256     scaleFactor = (scaleFactor > 1.0) ? 1.0 : scaleFactor;
1258     // Now get the resized values
1259     const double scaledSvgWidth  = scaleFactor * _preview_document_width;
1260     const double scaledSvgHeight = scaleFactor * _preview_document_height;
1262     const int svgX = pagePadding + halfBlurRadius;
1263     const int svgY = pagePadding;
1265     const int frameX = svgX - pagePadding;
1266     const int frameY = svgY - pagePadding;
1267     const int frameWidth = scaledSvgWidth + pagePadding * 2;
1268     const int frameHeight = scaledSvgHeight + pagePadding * 2;
1270     const int totalWidth = (int)ceil(frameWidth + blurRadius);
1271     const int totalHeight = (int)ceil(frameHeight + blurRadius);
1273     // Prepare the drawing surface
1274     HDC hDC = GetDC(_preview_wnd);
1275     HDC hMemDC = CreateCompatibleDC(hDC);
1276     _preview_bitmap = CreateCompatibleBitmap(hDC, totalWidth, totalHeight);
1277     HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDC, _preview_bitmap);
1278     Cairo::RefPtr<Win32Surface> surface = Win32Surface::create(hMemDC);
1279     Cairo::RefPtr<Context> context = Context::create(surface);
1281     // Paint the background to match the dialog colour
1282     const COLORREF background = GetSysColor(COLOR_3DFACE);
1283     context->set_source_rgb(
1284         GetRValue(background) / 255.0,
1285         GetGValue(background) / 255.0,
1286         GetBValue(background) / 255.0);
1287     context->paint();
1289     //----- Draw the drop shaddow -----//
1291     // Left Edge
1292     x = frameX + shaddowOffsetX - halfBlurRadius;
1293     Cairo::RefPtr<LinearGradient> leftEdgeFade = LinearGradient::create(
1294         x, 0.0, x + blurRadius, 0.0);
1295     leftEdgeFade->add_color_stop_rgba (0, 0, 0, 0, 0);
1296     leftEdgeFade->add_color_stop_rgba (1, 0, 0, 0, shaddowAlpha);
1297     context->set_source(leftEdgeFade);
1298     context->rectangle (x, frameY + shaddowOffsetY + halfBlurRadius,
1299         blurRadius, frameHeight - blurRadius);
1300     context->fill();
1302     // Right Edge
1303     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1304     Cairo::RefPtr<LinearGradient> rightEdgeFade = LinearGradient::create(
1305         x, 0.0,    x + blurRadius, 0.0);
1306     rightEdgeFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1307     rightEdgeFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1308     context->set_source(rightEdgeFade);
1309     context->rectangle (frameX + frameWidth + shaddowOffsetX - halfBlurRadius,
1310         frameY + shaddowOffsetY + halfBlurRadius,
1311         blurRadius, frameHeight - blurRadius);
1312     context->fill();
1314     // Top Edge
1315     y = frameY + shaddowOffsetY - halfBlurRadius;
1316     Cairo::RefPtr<LinearGradient> topEdgeFade = LinearGradient::create(
1317         0.0, y, 0.0, y + blurRadius);
1318     topEdgeFade->add_color_stop_rgba (0, 0, 0, 0, 0);
1319     topEdgeFade->add_color_stop_rgba (1, 0, 0, 0, shaddowAlpha);
1320     context->set_source(topEdgeFade);
1321     context->rectangle (frameX + shaddowOffsetX + halfBlurRadius, y,
1322         frameWidth - blurRadius, blurRadius);
1323     context->fill();
1325     // Bottom Edge
1326     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1327     Cairo::RefPtr<LinearGradient> bottomEdgeFade = LinearGradient::create(
1328         0.0, y,    0.0, y + blurRadius);
1329     bottomEdgeFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1330     bottomEdgeFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1331     context->set_source(bottomEdgeFade);
1332     context->rectangle (frameX + shaddowOffsetX + halfBlurRadius, y,
1333         frameWidth - blurRadius, blurRadius);
1334     context->fill();
1336     // Top Left Corner
1337     x = frameX + shaddowOffsetX - halfBlurRadius;
1338     y = frameY + shaddowOffsetY - halfBlurRadius;
1339     Cairo::RefPtr<RadialGradient> topLeftCornerFade = RadialGradient::create(
1340         x + blurRadius, y + blurRadius, 0, x + blurRadius, y + blurRadius, blurRadius);
1341     topLeftCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1342     topLeftCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1343     context->set_source(topLeftCornerFade);
1344     context->rectangle (x, y, blurRadius, blurRadius);
1345     context->fill();
1347     // Top Right Corner
1348     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1349     y = frameY + shaddowOffsetY - halfBlurRadius;
1350     Cairo::RefPtr<RadialGradient> topRightCornerFade = RadialGradient::create(
1351         x, y + blurRadius, 0, x, y + blurRadius, blurRadius);
1352     topRightCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1353     topRightCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1354     context->set_source(topRightCornerFade);
1355     context->rectangle (x, y, blurRadius, blurRadius);
1356     context->fill();
1358     // Bottom Left Corner
1359     x = frameX + shaddowOffsetX - halfBlurRadius;
1360     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1361     Cairo::RefPtr<RadialGradient> bottomLeftCornerFade = RadialGradient::create(
1362         x + blurRadius, y, 0, x + blurRadius, y, blurRadius);
1363     bottomLeftCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1364     bottomLeftCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1365     context->set_source(bottomLeftCornerFade);
1366     context->rectangle (x, y, blurRadius, blurRadius);
1367     context->fill();
1369     // Bottom Right Corner
1370     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1371     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1372     Cairo::RefPtr<RadialGradient> bottomRightCornerFade = RadialGradient::create(
1373         x, y, 0, x, y, blurRadius);
1374     bottomRightCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1375     bottomRightCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1376     context->set_source(bottomRightCornerFade);
1377     context->rectangle (frameX + frameWidth + shaddowOffsetX - halfBlurRadius,
1378         frameY + frameHeight + shaddowOffsetY - halfBlurRadius,
1379         blurRadius, blurRadius);
1380     context->fill();
1382     // Draw the frame
1383     context->set_line_width(1);
1384     context->rectangle (frameX, frameY,    frameWidth, frameHeight);
1386     context->set_source_rgb(1.0, 1.0, 1.0);
1387     context->fill_preserve();
1388     context->set_source_rgb(0.25, 0.25, 0.25);
1389     context->stroke_preserve();
1391     // Draw the image
1392     if(_preview_bitmap_image)    // Is the image a pixbuf?
1393     {
1394         // Set the transformation
1395         const Cairo::Matrix matrix(
1396             scaleFactor, 0,
1397             0, scaleFactor,
1398             svgX, svgY);
1399         context->set_matrix (matrix);
1401         // Render the image
1402         set_source_pixbuf (context, _preview_bitmap_image, 0, 0);
1403         context->paint();
1405         // Reset the transformation
1406         context->set_identity_matrix();
1407     }
1409     // Draw the inner frame
1410     context->set_source_rgb(0.75, 0.75, 0.75);
1411     context->rectangle (svgX, svgY,    scaledSvgWidth, scaledSvgHeight);
1412     context->stroke();
1414     _mutex->unlock();
1416     // Finish drawing
1417     surface->finish();
1419     if (_preview_emf_image) {
1420         HENHMETAFILE hemf = MyGetEnhMetaFileW(_path_string);
1421         if (hemf) {
1422             RECT rc;
1423             rc.top = svgY+2;
1424             rc.left = svgX+2;
1425             rc.bottom = scaledSvgHeight-2;
1426             rc.right = scaledSvgWidth-2;
1427             PlayEnhMetaFile(hMemDC, hemf, &rc);
1428             DeleteEnhMetaFile(hemf);
1429         }
1430     }
1432     SelectObject(hMemDC, hOldBitmap) ;
1433     DeleteDC(hMemDC);
1435     // Refresh the preview pane
1436     InvalidateRect(_preview_wnd, NULL, FALSE);
1439 int FileOpenDialogImplWin32::format_caption(wchar_t *caption, int caption_size)
1441     wchar_t szFileName[_MAX_FNAME];
1442     _wsplitpath(_path_string, NULL, NULL, szFileName, NULL);
1444     return snwprintf(caption, caption_size,
1445         L"%s\n%d kB\n%d \xD7 %d", szFileName, _preview_file_size,
1446         (int)_preview_document_width, (int)_preview_document_height);
1449 /**
1450  * Show this dialog modally.  Return true if user hits [OK]
1451  */
1452 bool
1453 FileOpenDialogImplWin32::show()
1455     // We can only run one worker thread at a time
1456     if(_mutex != NULL) return false;
1458     if(!Glib::thread_supported())
1459         Glib::thread_init();
1461     _result = false;
1462     _finished = false;
1463     _file_selected = false;
1464     _mutex = new Glib::Mutex();
1465     _main_loop = g_main_loop_new(g_main_context_default(), FALSE);
1467     if(Glib::Thread::create(sigc::mem_fun(*this, &FileOpenDialogImplWin32::GetOpenFileName_thread), true))
1468     {
1469         while(1)
1470         {
1471             g_main_context_iteration(g_main_context_default(), FALSE);
1473             if(_mutex->trylock())
1474             {
1475                 // Read mutexed data
1476                 const bool finished = _finished;
1477                 const bool is_file_selected = _file_selected;
1478                 _file_selected = false;
1479                 _mutex->unlock();
1481                 if(finished) break;
1482                 if(is_file_selected) file_selected();
1483             }
1485             Sleep(10);
1486         }
1487     }
1489     // Tidy up
1490     delete _mutex;
1491     _mutex = NULL;
1493     return _result;
1496 /**
1497  * To Get Multiple filenames selected at-once.
1498  */
1499 std::vector<Glib::ustring>FileOpenDialogImplWin32::getFilenames()
1501     std::vector<Glib::ustring> result;
1502     result.push_back(getFilename());
1503     return result;
1507 /*#########################################################################
1508 ### F I L E    S A V E
1509 #########################################################################*/
1511 /**
1512  * Constructor
1513  */
1514 FileSaveDialogImplWin32::FileSaveDialogImplWin32(Gtk::Window &parent,
1515             const Glib::ustring &dir,
1516             FileDialogType fileTypes,
1517             const char *title,
1518             const Glib::ustring &/*default_key*/,
1519             const char *docTitle,
1520             const Inkscape::Extension::FileSaveMethod save_method) :
1521     FileDialogBaseWin32(parent, dir, title, fileTypes,
1522                         (save_method == Inkscape::Extension::FILE_SAVE_METHOD_SAVE_COPY) ? "dialogs.save_copy" :  "dialogs.save_as"),
1523         _title_label(NULL),
1524         _title_edit(NULL)
1526     FileSaveDialog::myDocTitle = docTitle;
1527     createFilterMenu();
1530 FileSaveDialogImplWin32::~FileSaveDialogImplWin32()
1534 void FileSaveDialogImplWin32::createFilterMenu()
1536     list<Filter> filter_list;
1538     knownExtensions.clear();
1540     // Compose the filter string
1541     Glib::ustring all_inkscape_files_filter, all_image_files_filter;
1542     Inkscape::Extension::DB::OutputList extension_list;
1543     Inkscape::Extension::db.get_output_list(extension_list);
1545     int filter_count = 0;
1546     int filter_length = 1;
1548     for (Inkscape::Extension::DB::OutputList::iterator current_item = extension_list.begin();
1549          current_item != extension_list.end(); current_item++)
1550     {
1551         Inkscape::Extension::Output *omod = *current_item;
1552         if (omod->deactivated()) continue;
1554         filter_count++;
1556         Filter filter;
1558         // Extension
1559         const gchar *filter_extension = omod->get_extension();
1560         filter.filter = g_utf8_to_utf16(
1561             filter_extension, -1, NULL, &filter.filter_length, NULL);
1562         knownExtensions.insert( Glib::ustring(filter_extension).casefold() );
1564         // Type
1565         filter.name = g_utf8_to_utf16(
1566             _(omod->get_filetypename()), -1, NULL, &filter.name_length, NULL);
1568         filter.mod = omod;
1570         filter_length += filter.name_length +
1571             filter.filter_length + 3;   // Add 3 for two \0s and a *
1573         filter_list.push_back(filter);
1574     }
1576     int extension_index = 0;
1577     _extension_map = new Inkscape::Extension::Extension*[filter_count];
1579     _filter = new wchar_t[filter_length];
1580     wchar_t *filterptr = _filter;
1582     for(list<Filter>::iterator filter_iterator = filter_list.begin();
1583         filter_iterator != filter_list.end(); filter_iterator++)
1584     {
1585         const Filter &filter = *filter_iterator;
1587         wcsncpy(filterptr, (wchar_t*)filter.name, filter.name_length);
1588         filterptr += filter.name_length;
1589         g_free(filter.name);
1591         *(filterptr++) = L'\0';
1592         *(filterptr++) = L'*';
1594         wcsncpy(filterptr, (wchar_t*)filter.filter, filter.filter_length);
1595         filterptr += filter.filter_length;
1596         g_free(filter.filter);
1598         *(filterptr++) = L'\0';
1600         // Associate this input extension with the file type name
1601         _extension_map[extension_index++] = filter.mod;
1602     }
1603     *(filterptr++) = 0;
1605         _filter_count = extension_index;
1606     _filter_index = 1;  // A value of 1 selects the 1st filter - NOT the 2nd
1609 void FileSaveDialogImplWin32::GetSaveFileName_thread()
1611     OPENFILENAMEEXW ofn;
1613     g_assert(this != NULL);
1614     g_assert(_main_loop != NULL);
1616     WCHAR* current_directory_string = (WCHAR*)g_utf8_to_utf16(
1617         _current_directory.data(), _current_directory.length(),
1618                 NULL, NULL, NULL);
1620     // Copy the selected file name, converting from UTF-8 to UTF-16
1621     memset(_path_string, 0, sizeof(_path_string));
1622     gunichar2* utf16_path_string = g_utf8_to_utf16(
1623         myFilename.data(), -1, NULL, NULL, NULL);
1624     wcsncpy(_path_string, (wchar_t*)utf16_path_string, _MAX_PATH);
1625     g_free(utf16_path_string);
1627     ZeroMemory(&ofn, sizeof(ofn));
1628     ofn.lStructSize = sizeof(ofn);
1629     ofn.hwndOwner = _ownerHwnd;
1630     ofn.lpstrFile = _path_string;
1631     ofn.nMaxFile = _MAX_PATH;
1632     ofn.nFilterIndex = _filter_index;
1633     ofn.lpstrFileTitle = NULL;
1634     ofn.nMaxFileTitle = 0;
1635     ofn.lpstrInitialDir = current_directory_string;
1636     ofn.lpstrTitle = _title;
1637     ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ENABLEHOOK;
1638     ofn.lpstrFilter = _filter;
1639     ofn.nFilterIndex = _filter_index;
1640     ofn.lpfnHook = GetSaveFileName_hookproc;
1641     ofn.lCustData = (LPARAM)this;
1643     _result = GetSaveFileNameW(&ofn) != 0;
1645         g_assert(ofn.nFilterIndex >= 1 && ofn.nFilterIndex <= _filter_count);
1646     _filter_index = ofn.nFilterIndex;
1647     _extension = _extension_map[ofn.nFilterIndex - 1];
1649     // Copy the selected file name, converting from UTF-16 to UTF-8
1650     myFilename = utf16_to_ustring(_path_string, _MAX_PATH);
1652     // Tidy up
1653     g_free(current_directory_string);
1655     g_main_loop_quit(_main_loop);
1658 /**
1659  * Show this dialog modally.  Return true if user hits [OK]
1660  */
1661 bool
1662 FileSaveDialogImplWin32::show()
1664     if(!Glib::thread_supported())
1665         Glib::thread_init();
1667     _result = false;
1668     _main_loop = g_main_loop_new(g_main_context_default(), FALSE);
1670         if(_main_loop != NULL)
1671         {
1672             if(Glib::Thread::create(sigc::mem_fun(*this, &FileSaveDialogImplWin32::GetSaveFileName_thread), true))
1673                 g_main_loop_run(_main_loop);
1675             if(_result)
1676                 appendExtension(myFilename, (Inkscape::Extension::Output*)_extension);
1677         }
1679     return _result;
1682 void FileSaveDialogImplWin32::setSelectionType( Inkscape::Extension::Extension * /*key*/ )
1684     // If no pointer to extension is passed in, look up based on filename extension.
1688 UINT_PTR CALLBACK FileSaveDialogImplWin32::GetSaveFileName_hookproc(
1689     HWND hdlg, UINT uiMsg, WPARAM, LPARAM lParam)
1691     FileSaveDialogImplWin32 *pImpl = (FileSaveDialogImplWin32*)
1692         GetWindowLongPtr(hdlg, GWLP_USERDATA);
1694     switch(uiMsg)
1695     {
1696     case WM_INITDIALOG:
1697         {
1698             HWND hParentWnd = GetParent(hdlg);
1699             HINSTANCE hInstance = GetModuleHandle(NULL);
1701             // get size/pos of typical combo box
1702             RECT rEDT1, rCB1, rROOT, rST;
1703             GetWindowRect(GetDlgItem(hParentWnd, cmb1), &rCB1);
1704             GetWindowRect(GetDlgItem(hParentWnd, cmb13), &rEDT1);
1705             GetWindowRect(GetDlgItem(hParentWnd, stc2), &rST);
1706             GetWindowRect(hdlg, &rROOT);
1707             int ydelta = rCB1.top - rEDT1.top;
1708             if ( ydelta < 0 ) {
1709                 g_warning("Negative dialog ydelta");
1710                 ydelta = 0;
1711             }
1713             // Make the window a bit longer
1714             // Note: we have a width delta of 1 because there is a suspicion that MoveWindow() to the same size causes zero-width results.
1715             RECT rcRect;
1716             GetWindowRect(hParentWnd, &rcRect);
1717             MoveWindow(hParentWnd, rcRect.left, rcRect.top,
1718                        sanitizeWindowSizeParam( rcRect.right - rcRect.left, 1, WINDOW_WIDTH_MINIMUM, WINDOW_WIDTH_FALLBACK ),
1719                        sanitizeWindowSizeParam( rcRect.bottom - rcRect.top, ydelta, WINDOW_HEIGHT_MINIMUM, WINDOW_HEIGHT_FALLBACK ),
1720                        FALSE);
1722             // It is not necessary to delete stock objects by calling DeleteObject
1723             HGDIOBJ dlgFont = GetStockObject(DEFAULT_GUI_FONT);
1725             // Set the pointer to the object
1726             OPENFILENAMEW *ofn = (OPENFILENAMEW*)lParam;
1727             SetWindowLongPtr(hdlg, GWLP_USERDATA, ofn->lCustData);
1728             SetWindowLongPtr(hParentWnd, GWLP_USERDATA, ofn->lCustData);
1729             pImpl = (FileSaveDialogImplWin32*)ofn->lCustData;
1731             // Create the Title label and edit control
1732             pImpl->_title_label = CreateWindowEx(NULL, "STATIC", "Title:",
1733                                         WS_VISIBLE|WS_CHILD,
1734                                         CW_USEDEFAULT, CW_USEDEFAULT, rCB1.left-rST.left, rST.bottom-rST.top,
1735                                         hParentWnd, NULL, hInstance, NULL);
1736             if(pImpl->_title_label) {
1737               if(dlgFont) SendMessage(pImpl->_title_label, WM_SETFONT, (WPARAM)dlgFont, MAKELPARAM(FALSE, 0));
1738               SetWindowPos(pImpl->_title_label, NULL, rST.left-rROOT.left, rST.top+ydelta-rROOT.top,
1739                            rCB1.left-rST.left, rST.bottom-rST.top, SWP_SHOWWINDOW|SWP_NOZORDER);
1740             }
1742             pImpl->_title_edit = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "",
1743                                         WS_VISIBLE|WS_CHILD|WS_TABSTOP|ES_AUTOHSCROLL,
1744                                         CW_USEDEFAULT, CW_USEDEFAULT, rCB1.right-rCB1.left, rCB1.bottom-rCB1.top,
1745                                         hParentWnd, NULL, hInstance, NULL);
1746             if(pImpl->_title_edit) {
1747               if(dlgFont) SendMessage(pImpl->_title_edit, WM_SETFONT, (WPARAM)dlgFont, MAKELPARAM(FALSE, 0));
1748               SetWindowPos(pImpl->_title_edit, NULL, rCB1.left-rROOT.left, rCB1.top+ydelta-rROOT.top,
1749                            rCB1.right-rCB1.left, rCB1.bottom-rCB1.top, SWP_SHOWWINDOW|SWP_NOZORDER);
1750               // TODO: make sure this works for Unicode
1751               SetWindowText(pImpl->_title_edit, pImpl->myDocTitle.c_str());
1752             }
1753         }
1754         break;
1755     case WM_DESTROY:
1756       {
1757         if(pImpl->_title_edit) {
1758           int length = GetWindowTextLength(pImpl->_title_edit)+1;
1759           char* temp_title = new char[length];
1760           GetWindowText(pImpl->_title_edit, temp_title, length);
1761           pImpl->myDocTitle = temp_title;
1762           delete[] temp_title;
1763           DestroyWindow(pImpl->_title_label);
1764           pImpl->_title_label = NULL;
1765           DestroyWindow(pImpl->_title_edit);
1766           pImpl->_title_edit = NULL;
1767         }
1768       }
1769       break;
1770     }
1772     // Use default dialog behaviour
1773     return 0;
1776 } } } // namespace Dialog, UI, Inkscape
1778 #endif // ifdef WIN32
1780 /*
1781   Local Variables:
1782   mode:c++
1783   c-file-style:"stroustrup"
1784   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1785   indent-tabs-mode:nil
1786   fill-column:99
1787   End:
1788 */
1789 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :