Code

A simple layout document as to what, why and how is cppification.
[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 PreviewWidening = 150;
63 const char PreviewWindowClassName[] = "PreviewWnd";
64 const unsigned long MaxPreviewFileSize = 10240; // kB
66 #define IDC_SHOW_PREVIEW    1000
68 // Windows 2000 version of OPENFILENAMEW
69 struct OPENFILENAMEEXW : public OPENFILENAMEW {
70   void *        pvReserved;
71   DWORD         dwReserved;
72   DWORD         FlagsEx;
73 };
75 struct Filter
76 {
77     gunichar2* name;
78     glong name_length;
79     gunichar2* filter;
80     glong filter_length;
81     Inkscape::Extension::Extension* mod;
82 };
84 ustring utf16_to_ustring(const wchar_t *utf16string, int utf16length = -1)
85 {
86     gchar *utf8string = g_utf16_to_utf8((const gunichar2*)utf16string,
87         utf16length, NULL, NULL, NULL);
88     ustring result(utf8string);
89     g_free(utf8string);
91     return result;
92 }
94 /*#########################################################################
95 ### F I L E     D I A L O G    B A S E    C L A S S
96 #########################################################################*/
98 FileDialogBaseWin32::FileDialogBaseWin32(Gtk::Window &parent,
99         const Glib::ustring &dir, const gchar *title,
100         FileDialogType type, gchar const* /*preferenceBase*/) :
101         dialogType(type),
102         parent(parent),
103         _current_directory(dir)
105     _main_loop = NULL;
107         _filter_index = 1;
108         _filter_count = 0;
110     _title = (wchar_t*)g_utf8_to_utf16(title, -1, NULL, NULL, NULL);
111         g_assert(_title != NULL);
113     Glib::RefPtr<const Gdk::Window> parentWindow = parent.get_window();
114     g_assert(parentWindow->gobj() != NULL);
115     _ownerHwnd = (HWND)gdk_win32_drawable_get_handle((GdkDrawable*)parentWindow->gobj());
118 FileDialogBaseWin32::~FileDialogBaseWin32()
120     g_free(_title);
123 Inkscape::Extension::Extension *FileDialogBaseWin32::getSelectionType()
125     return _extension;
128 Glib::ustring FileDialogBaseWin32::getCurrentDirectory()
130     return _current_directory;
133 /*#########################################################################
134 ### F I L E    O P E N
135 #########################################################################*/
137 bool FileOpenDialogImplWin32::_show_preview = true;
139 /**
140  * Constructor.  Not called directly.  Use the factory.
141  */
142 FileOpenDialogImplWin32::FileOpenDialogImplWin32(Gtk::Window &parent,
143                                        const Glib::ustring &dir,
144                                        FileDialogType fileTypes,
145                                        const gchar *title) :
146     FileDialogBaseWin32(parent, dir, title, fileTypes, "dialogs.open")
148     // Initalize to Autodetect
149     _extension = NULL;
151     // Set our dialog type (open, import, etc...)
152     dialogType = fileTypes;
154     _show_preview_button_bitmap = NULL;
155     _preview_wnd = NULL;
156     _file_dialog_wnd = NULL;
157     _base_window_proc = NULL;
159     _preview_file_size = 0;
160     _preview_bitmap = NULL;
161     _preview_file_icon = NULL;
162     _preview_document_width = 0;
163     _preview_document_height = 0;
164     _preview_image_width = 0;
165     _preview_image_height = 0;
166     _preview_emf_image = false;
168         _mutex = NULL;
170     createFilterMenu();
174 /**
175  * Destructor
176  */
177 FileOpenDialogImplWin32::~FileOpenDialogImplWin32()
179     if(_filter != NULL)
180         delete[] _filter;
181     if(_extension_map != NULL)
182         delete[] _extension_map;
185 void FileOpenDialogImplWin32::createFilterMenu()
187     list<Filter> filter_list;
189     // Compose the filter string
190     Inkscape::Extension::DB::InputList extension_list;
191     Inkscape::Extension::db.get_input_list(extension_list);
193     ustring all_inkscape_files_filter, all_image_files_filter, all_vectors_filter, all_bitmaps_filter;
194     Filter all_files, all_inkscape_files, all_image_files, all_vectors, all_bitmaps;
196     const gchar *all_files_filter_name = _("All Files");
197     const gchar *all_inkscape_files_filter_name = _("All Inkscape Files");
198     const gchar *all_image_files_filter_name = _("All Images");
199     const gchar *all_vectors_filter_name = _("All Vectors");
200     const gchar *all_bitmaps_filter_name = _("All Bitmaps");
202     // Calculate the amount of memory required
203     int filter_count = 5;       // 5 - one for each filter type
204     int filter_length = 1;
206     for (Inkscape::Extension::DB::InputList::iterator current_item = extension_list.begin();
207          current_item != extension_list.end(); current_item++)
208     {
209         Filter filter;
211         Inkscape::Extension::Input *imod = *current_item;
212         if (imod->deactivated()) continue;
214         // Type
215         filter.name = g_utf8_to_utf16(_(imod->get_filetypename()),
216             -1, NULL, &filter.name_length, NULL);
218         // Extension
219         const gchar *file_extension_name = imod->get_extension();
220         filter.filter = g_utf8_to_utf16(file_extension_name,
221             -1, NULL, &filter.filter_length, NULL);
223         filter.mod = imod;
224         filter_list.push_back(filter);
226         filter_length += filter.name_length +
227             filter.filter_length + 3;   // Add 3 for two \0s and a *
229         // Add to the "All Inkscape Files" Entry
230         if(all_inkscape_files_filter.length() > 0)
231             all_inkscape_files_filter += ";*";
232         all_inkscape_files_filter += file_extension_name;
233         if( strncmp("image", imod->get_mimetype(), 5) == 0)
234         {
235             // Add to the "All Image Files" Entry
236             if(all_image_files_filter.length() > 0)
237                 all_image_files_filter += ";*";
238             all_image_files_filter += file_extension_name;
239         }
241         // I don't know of any other way to define "bitmap" formats other than by listing them
242         // if you change it here, do the same change in filedialogimpl-gtkmm
243         if ( 
244             strncmp("image/png", imod->get_mimetype(), 9)==0 ||
245             strncmp("image/jpeg", imod->get_mimetype(), 10)==0 ||
246             strncmp("image/gif", imod->get_mimetype(), 9)==0 ||
247             strncmp("image/x-icon", imod->get_mimetype(), 12)==0 ||
248             strncmp("image/x-navi-animation", imod->get_mimetype(), 22)==0 ||
249             strncmp("image/x-cmu-raster", imod->get_mimetype(), 18)==0 ||
250             strncmp("image/x-xpixmap", imod->get_mimetype(), 15)==0 ||
251             strncmp("image/bmp", imod->get_mimetype(), 9)==0 ||
252             strncmp("image/vnd.wap.wbmp", imod->get_mimetype(), 18)==0 ||
253             strncmp("image/tiff", imod->get_mimetype(), 10)==0 ||
254             strncmp("image/x-xbitmap", imod->get_mimetype(), 15)==0 ||
255             strncmp("image/x-tga", imod->get_mimetype(), 11)==0 ||
256             strncmp("image/x-pcx", imod->get_mimetype(), 11)==0 
257             ) {
258             if(all_bitmaps_filter.length() > 0)
259                 all_bitmaps_filter += ";*";
260             all_bitmaps_filter += file_extension_name;
261         } else {
262             if(all_vectors_filter.length() > 0)
263                 all_vectors_filter += ";*";
264             all_vectors_filter += file_extension_name;
265         }
267         filter_count++;
268     }
270     int extension_index = 0;
271     _extension_map = new Inkscape::Extension::Extension*[filter_count];
273     // Filter bitmap files
274     all_bitmaps.name = g_utf8_to_utf16(all_bitmaps_filter_name,
275         -1, NULL, &all_bitmaps.name_length, NULL);
276     all_bitmaps.filter = g_utf8_to_utf16(all_bitmaps_filter.data(),
277             -1, NULL, &all_bitmaps.filter_length, NULL);
278         all_bitmaps.mod = NULL;
279     filter_list.push_front(all_bitmaps);
281     // Filter vector files
282     all_vectors.name = g_utf8_to_utf16(all_vectors_filter_name,
283         -1, NULL, &all_vectors.name_length, NULL);
284     all_vectors.filter = g_utf8_to_utf16(all_vectors_filter.data(),
285             -1, NULL, &all_vectors.filter_length, NULL);
286         all_vectors.mod = NULL;
287     filter_list.push_front(all_vectors);
289     // Filter Image Files
290     all_image_files.name = g_utf8_to_utf16(all_image_files_filter_name,
291         -1, NULL, &all_image_files.name_length, NULL);
292     all_image_files.filter = g_utf8_to_utf16(all_image_files_filter.data(),
293             -1, NULL, &all_image_files.filter_length, NULL);
294         all_image_files.mod = NULL;
295     filter_list.push_front(all_image_files);
297     // Filter Inkscape Files
298     all_inkscape_files.name = g_utf8_to_utf16(all_inkscape_files_filter_name,
299         -1, NULL, &all_inkscape_files.name_length, NULL);
300     all_inkscape_files.filter = g_utf8_to_utf16(all_inkscape_files_filter.data(),
301             -1, NULL, &all_inkscape_files.filter_length, NULL);
302         all_inkscape_files.mod = NULL;
303     filter_list.push_front(all_inkscape_files);
305     // Filter All Files
306     all_files.name = g_utf8_to_utf16(all_files_filter_name,
307         -1, NULL, &all_files.name_length, NULL);
308     all_files.filter = NULL;
309     all_files.filter_length = 0;
310         all_files.mod = NULL;
311     filter_list.push_front(all_files);
313     filter_length += all_files.name_length + 3 +
314                     all_inkscape_files.filter_length +
315                     all_inkscape_files.name_length + 3 +
316                     all_image_files.filter_length +
317                     all_image_files.name_length + 3 +
318                     all_vectors.filter_length +
319                     all_vectors.name_length + 3 +
320                     all_bitmaps.filter_length +
321                     all_bitmaps.name_length + 3 +
322                                                   1;
323      // Add 3 for 2*2 \0s and a *, and 1 for a trailing \0
325         _filter = new wchar_t[filter_length];
326     wchar_t *filterptr = _filter;
328     for(list<Filter>::iterator filter_iterator = filter_list.begin();
329         filter_iterator != filter_list.end(); filter_iterator++)
330     {
331         const Filter &filter = *filter_iterator;
333         wcsncpy(filterptr, (wchar_t*)filter.name, filter.name_length);
334         filterptr += filter.name_length;
335         g_free(filter.name);
337         *(filterptr++) = L'\0';
338         *(filterptr++) = L'*';
340         if(filter.filter != NULL)
341         {
342             wcsncpy(filterptr, (wchar_t*)filter.filter, filter.filter_length);
343             filterptr += filter.filter_length;
344             g_free(filter.filter);
345         }
347         *(filterptr++) = L'\0';
349         // Associate this input extension with the file type name
350         _extension_map[extension_index++] = filter.mod;
351     }
352     *(filterptr++) = L'\0';
354         _filter_count = extension_index;
355     _filter_index = 2;  // Select the 2nd filter in the list - 2 is NOT the 3rd
358 void FileOpenDialogImplWin32::GetOpenFileName_thread()
360     OPENFILENAMEEXW ofn;
362     g_assert(this != NULL);
363         g_assert(_mutex != NULL);
365     WCHAR* current_directory_string = (WCHAR*)g_utf8_to_utf16(
366         _current_directory.data(), _current_directory.length(),
367                 NULL, NULL, NULL);
369     memset(&ofn, 0, sizeof(ofn));
371     // Copy the selected file name, converting from UTF-8 to UTF-16
372     memset(_path_string, 0, sizeof(_path_string));
373     gunichar2* utf16_path_string = g_utf8_to_utf16(
374         myFilename.data(), -1, NULL, NULL, NULL);
375     wcsncpy(_path_string, (wchar_t*)utf16_path_string, _MAX_PATH);
376     g_free(utf16_path_string);
378     ofn.lStructSize = sizeof(ofn);
379     ofn.hwndOwner = _ownerHwnd;
380     ofn.lpstrFile = _path_string;
381     ofn.nMaxFile = _MAX_PATH;
382     ofn.lpstrFileTitle = NULL;
383     ofn.nMaxFileTitle = 0;
384     ofn.lpstrInitialDir = current_directory_string;
385     ofn.lpstrTitle = _title;
386     ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ENABLEHOOK | OFN_HIDEREADONLY | OFN_ENABLESIZING;
387     ofn.lpstrFilter = _filter;
388     ofn.nFilterIndex = _filter_index;
389     ofn.lpfnHook = GetOpenFileName_hookproc;
390     ofn.lCustData = (LPARAM)this;
392     _result = GetOpenFileNameW(&ofn) != 0;
394         g_assert(ofn.nFilterIndex >= 1 && ofn.nFilterIndex <= _filter_count);
395     _filter_index = ofn.nFilterIndex;
396     _extension = _extension_map[ofn.nFilterIndex - 1];
398     // Copy the selected file name, converting from UTF-16 to UTF-8
399     myFilename = utf16_to_ustring(_path_string, _MAX_PATH);
401     // Tidy up
402     g_free(current_directory_string);
404     _mutex->lock();
405     _finished = true;
406     _mutex->unlock();
409 void FileOpenDialogImplWin32::register_preview_wnd_class()
411     HINSTANCE hInstance = GetModuleHandle(NULL);
412     const WNDCLASSA PreviewWndClass =
413     {
414         CS_HREDRAW | CS_VREDRAW,
415         preview_wnd_proc,
416         0,
417         0,
418         hInstance,
419         NULL,
420         LoadCursor(hInstance, IDC_ARROW),
421         (HBRUSH)(COLOR_BTNFACE + 1),
422         NULL,
423         PreviewWindowClassName
424     };
426     RegisterClassA(&PreviewWndClass);
429 UINT_PTR CALLBACK FileOpenDialogImplWin32::GetOpenFileName_hookproc(
430     HWND hdlg, UINT uiMsg, WPARAM, LPARAM lParam)
432     FileOpenDialogImplWin32 *pImpl = (FileOpenDialogImplWin32*)
433         GetWindowLongPtr(hdlg, GWLP_USERDATA);
435     switch(uiMsg)
436     {
437     case WM_INITDIALOG:
438         {
439             HWND hParentWnd = GetParent(hdlg);
440             HINSTANCE hInstance = GetModuleHandle(NULL);
442             // Make the window a bit wider
443             RECT rcRect;
444             GetWindowRect(hParentWnd, &rcRect);
445             MoveWindow(hParentWnd, rcRect.left, rcRect.top,
446                 rcRect.right - rcRect.left + PreviewWidening,
447                 rcRect.bottom - rcRect.top,
448                 FALSE);
450             // Set the pointer to the object
451             OPENFILENAMEW *ofn = (OPENFILENAMEW*)lParam;
452             SetWindowLongPtr(hdlg, GWLP_USERDATA, ofn->lCustData);
453             SetWindowLongPtr(hParentWnd, GWLP_USERDATA, ofn->lCustData);
454             pImpl = (FileOpenDialogImplWin32*)ofn->lCustData;
456             // Subclass the parent
457             pImpl->_base_window_proc = (WNDPROC)GetWindowLongPtr(hParentWnd, GWLP_WNDPROC);
458             SetWindowLongPtr(hParentWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(file_dialog_subclass_proc));
460             // Add a button to the toolbar
461             pImpl->_toolbar_wnd = FindWindowEx(hParentWnd, NULL, "ToolbarWindow32", NULL);
463             pImpl->_show_preview_button_bitmap = LoadBitmap(
464                 hInstance, MAKEINTRESOURCE(IDC_SHOW_PREVIEW));
465             TBADDBITMAP tbAddBitmap = {NULL, reinterpret_cast<UINT_PTR>(pImpl->_show_preview_button_bitmap)};
466             const int iBitmapIndex = SendMessage(pImpl->_toolbar_wnd,
467                 TB_ADDBITMAP, 1, (LPARAM)&tbAddBitmap);
469             TBBUTTON tbButton;
470             memset(&tbButton, 0, sizeof(TBBUTTON));
471             tbButton.iBitmap = iBitmapIndex;
472             tbButton.idCommand = IDC_SHOW_PREVIEW;
473             tbButton.fsState = (pImpl->_show_preview ? TBSTATE_CHECKED : 0)
474                 | TBSTATE_ENABLED;
475             tbButton.fsStyle = TBSTYLE_CHECK;
476             tbButton.iString = (INT_PTR)_("Show Preview");
477             SendMessage(pImpl->_toolbar_wnd, TB_ADDBUTTONS, 1, (LPARAM)&tbButton);
479             // Create preview pane
480             register_preview_wnd_class();
482             pImpl->_mutex->lock();
484                 pImpl->_file_dialog_wnd = hParentWnd;
486                 pImpl->_preview_wnd =
487                     CreateWindowA(PreviewWindowClassName, "",
488                         WS_CHILD | WS_VISIBLE,
489                         0, 0, 100, 100, hParentWnd, NULL, hInstance, NULL);
490                 SetWindowLongPtr(pImpl->_preview_wnd, GWLP_USERDATA, ofn->lCustData);
492             pImpl->_mutex->unlock();
494             pImpl->layout_dialog();
495         }
496         break;
498     case WM_NOTIFY:
499         {
501         OFNOTIFY *pOFNotify = reinterpret_cast<OFNOTIFY*>(lParam);
502         switch(pOFNotify->hdr.code)
503         {
504         case CDN_SELCHANGE:
505             {
506                 if(pImpl != NULL)
507                 {
508                     // Get the file name
509                     pImpl->_mutex->lock();
511                     SendMessage(pOFNotify->hdr.hwndFrom, CDM_GETFILEPATH,
512                         sizeof(pImpl->_path_string) / sizeof(wchar_t),
513                         (LPARAM)pImpl->_path_string);
515                     pImpl->_file_selected = true;
517                     pImpl->_mutex->unlock();
518                 }
519             }
520             break;
521         }
522         }
523         break;
525     case WM_CLOSE:
526         pImpl->_mutex->lock();
527         pImpl->_preview_file_size = 0;
529         pImpl->_file_dialog_wnd = NULL;
530         DestroyWindow(pImpl->_preview_wnd);
531         pImpl->_preview_wnd = NULL;
532         DeleteObject(pImpl->_show_preview_button_bitmap);
533         pImpl->_show_preview_button_bitmap = NULL;
534         pImpl->_mutex->unlock();
536         break;
537     }
539     // Use default dialog behaviour
540     return 0;
543 LRESULT CALLBACK FileOpenDialogImplWin32::file_dialog_subclass_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
545     FileOpenDialogImplWin32 *pImpl = (FileOpenDialogImplWin32*)
546         GetWindowLongPtr(hwnd, GWLP_USERDATA);
548     LRESULT lResult = CallWindowProc(pImpl->_base_window_proc, hwnd, uMsg, wParam, lParam);
550     switch(uMsg)
551     {
552     case WM_SHOWWINDOW:
553         if(wParam != 0)
554             pImpl->layout_dialog();
555         break;
557     case WM_SIZE:
558         pImpl->layout_dialog();
559         break;
561     case WM_COMMAND:
562         if(wParam == IDC_SHOW_PREVIEW)
563         {
564             const bool enable = SendMessage(pImpl->_toolbar_wnd,
565                 TB_ISBUTTONCHECKED, IDC_SHOW_PREVIEW, 0) != 0;
566             pImpl->enable_preview(enable);
567         }
568         break;
569     }
571     return lResult;
574 LRESULT CALLBACK FileOpenDialogImplWin32::preview_wnd_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
576     const int CaptionPadding = 4;
577     const int IconSize = 32;
579     FileOpenDialogImplWin32 *pImpl = (FileOpenDialogImplWin32*)
580         GetWindowLongPtr(hwnd, GWLP_USERDATA);
582     LRESULT lResult = 0;
584     switch(uMsg)
585     {
586     case WM_ERASEBKGND:
587         // Do nothing to erase the background
588         //  - otherwise there'll be flicker
589         lResult = 1;
590         break;
592     case WM_PAINT:
593         {
594             // Get the client rect
595             RECT rcClient;
596             GetClientRect(hwnd, &rcClient);
598             // Prepare to paint
599             PAINTSTRUCT paint_struct;
600             HDC dc = BeginPaint(hwnd, &paint_struct);
602             HFONT hCaptionFont = (HFONT)SendMessage(GetParent(hwnd),
603                     WM_GETFONT, 0, 0);
604             HFONT hOldFont = (HFONT)SelectObject(dc, hCaptionFont);
605             SetBkMode(dc, TRANSPARENT);
607             pImpl->_mutex->lock();
609             if(pImpl->_path_string[0] == 0)
610             {
611                 WCHAR* noFileText=(WCHAR*)g_utf8_to_utf16(_("No file selected"),
612                     -1, NULL, NULL, NULL);
613                 FillRect(dc, &rcClient, (HBRUSH)(COLOR_3DFACE + 1));
614                 DrawTextW(dc,  noFileText, -1, &rcClient, 
615                     DT_CENTER | DT_VCENTER | DT_NOPREFIX);
616                 g_free(noFileText);
617             }
618             else if(pImpl->_preview_bitmap != NULL)
619             {
620                 BITMAP bitmap;
621                 GetObject(pImpl->_preview_bitmap, sizeof(bitmap), &bitmap);
622                 const int destX = (rcClient.right - bitmap.bmWidth) / 2;
624                 // Render the image
625                 HDC hSrcDC = CreateCompatibleDC(dc);
626                 HBITMAP hOldBitmap = (HBITMAP)SelectObject(hSrcDC, pImpl->_preview_bitmap);
628                 BitBlt(dc, destX, 0, bitmap.bmWidth, bitmap.bmHeight,
629                     hSrcDC, 0, 0, SRCCOPY);
631                 SelectObject(hSrcDC, hOldBitmap);
632                 DeleteDC(hSrcDC);
634                 // Fill in the background area
635                 HRGN hEraseRgn = CreateRectRgn(rcClient.left, rcClient.top,
636                     rcClient.right, rcClient.bottom);
637                 HRGN hImageRgn = CreateRectRgn(destX, 0,
638                     destX + bitmap.bmWidth, bitmap.bmHeight);
639                 CombineRgn(hEraseRgn, hEraseRgn, hImageRgn, RGN_DIFF);
641                 FillRgn(dc, hEraseRgn, GetSysColorBrush(COLOR_3DFACE));
643                 DeleteObject(hImageRgn);
644                 DeleteObject(hEraseRgn);
646                 // Draw the caption on
647                 RECT rcCaptionRect = {rcClient.left,
648                     rcClient.top + bitmap.bmHeight + CaptionPadding,
649                     rcClient.right, rcClient.bottom};
651                 WCHAR szCaption[_MAX_FNAME + 32];
652                 const int iLength = pImpl->format_caption(
653                     szCaption, sizeof(szCaption) / sizeof(WCHAR));
655                 DrawTextW(dc, szCaption, iLength, &rcCaptionRect,
656                     DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS);
657             }
658             else if(pImpl->_preview_file_icon != NULL)
659             {
660                 FillRect(dc, &rcClient, (HBRUSH)(COLOR_3DFACE + 1));
662                 // Draw the files icon
663                 const int destX = (rcClient.right - IconSize) / 2;
664                 DrawIconEx(dc, destX, 0, pImpl->_preview_file_icon,
665                     IconSize, IconSize, 0, NULL,
666                     DI_NORMAL | DI_COMPAT);
668                 // Draw the caption on
669                 RECT rcCaptionRect = {rcClient.left,
670                     rcClient.top + IconSize + CaptionPadding,
671                     rcClient.right, rcClient.bottom};
673                 WCHAR szFileName[_MAX_FNAME], szCaption[_MAX_FNAME + 32];
674                 _wsplitpath(pImpl->_path_string, NULL, NULL, szFileName, NULL);
676                 const int iLength = snwprintf(szCaption,
677                     sizeof(szCaption), L"%s\n%d kB",
678                     szFileName, pImpl->_preview_file_size);
680                 DrawTextW(dc, szCaption, iLength, &rcCaptionRect,
681                     DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS);
682             }
683             else
684             {
685                 // Can't show anything!
686                 FillRect(dc, &rcClient, (HBRUSH)(COLOR_3DFACE + 1));
687             }
689             pImpl->_mutex->unlock();
691             // Finish painting
692             SelectObject(dc, hOldFont);
693             EndPaint(hwnd, &paint_struct);
694         }
696         break;
698     case WM_DESTROY:
699         pImpl->free_preview();
700         break;
702     default:
703         lResult = DefWindowProc(hwnd, uMsg, wParam, lParam);
704         break;
705     }
707     return lResult;
710 void FileOpenDialogImplWin32::enable_preview(bool enable)
712     _show_preview = enable;
714     // Relayout the dialog
715     ShowWindow(_preview_wnd, enable ? SW_SHOW : SW_HIDE);
716     layout_dialog();
718     // Load or unload the preview
719     if(enable)
720     {
721         _mutex->lock();
722         _file_selected = true;
723         _mutex->unlock();
724     }
725     else free_preview();
728 void FileOpenDialogImplWin32::layout_dialog()
730     union RECTPOINTS
731     {
732         RECT r;
733         POINT p[2];
734     };
736     const float MaxExtentScale = 2.0f / 3.0f;
738     RECT rcClient;
739     GetClientRect(_file_dialog_wnd, &rcClient);
741     // Re-layout the dialog
742     HWND hFileListWnd = GetDlgItem(_file_dialog_wnd, lst2);
743     HWND hFolderComboWnd = GetDlgItem(_file_dialog_wnd, cmb2);
746     RECT rcFolderComboRect;
747     RECTPOINTS rcFileList;
748     GetWindowRect(hFileListWnd, &rcFileList.r);
749     GetWindowRect(hFolderComboWnd, &rcFolderComboRect);
750     const int iPadding = rcFileList.r.top - rcFolderComboRect.bottom;
751     MapWindowPoints(NULL, _file_dialog_wnd, rcFileList.p, 2);
753     RECT rcPreview;
754     RECT rcBody = {rcFileList.r.left, rcFileList.r.top,
755         rcClient.right - iPadding, rcFileList.r.bottom};
756     rcFileList.r.right = rcBody.right;
758     if(_show_preview)
759     {
760         rcPreview.top = rcBody.top;
761         rcPreview.left = rcClient.right - (rcBody.bottom - rcBody.top);
762         const int iMaxExtent = (int)(MaxExtentScale * (float)(rcBody.left + rcBody.right)) + iPadding / 2;
763         if(rcPreview.left < iMaxExtent) rcPreview.left = iMaxExtent;
764         rcPreview.bottom = rcBody.bottom;
765         rcPreview.right = rcBody.right;
767         // Re-layout the preview box
768         _mutex->lock();
770             _preview_width = rcPreview.right - rcPreview.left;
771             _preview_height = rcPreview.bottom - rcPreview.top;
773         _mutex->unlock();
775         render_preview();
777         MoveWindow(_preview_wnd, rcPreview.left, rcPreview.top,
778             _preview_width, _preview_height, TRUE);
780         rcFileList.r.right = rcPreview.left - iPadding;
781     }
783     // Re-layout the file list box
784     MoveWindow(hFileListWnd, rcFileList.r.left, rcFileList.r.top,
785         rcFileList.r.right - rcFileList.r.left,
786         rcFileList.r.bottom - rcFileList.r.top, TRUE);
788     // Re-layout the toolbar
789     RECTPOINTS rcToolBar;
790     GetWindowRect(_toolbar_wnd, &rcToolBar.r);
791     MapWindowPoints(NULL, _file_dialog_wnd, rcToolBar.p, 2);
792     MoveWindow(_toolbar_wnd, rcToolBar.r.left, rcToolBar.r.top,
793         rcToolBar.r.right - rcToolBar.r.left, rcToolBar.r.bottom - rcToolBar.r.top, TRUE);
796 void FileOpenDialogImplWin32::file_selected()
798     // Destroy any previous previews
799     free_preview();
802     // Determine if the file exists
803     DWORD attributes = GetFileAttributesW(_path_string);
804     if(attributes == 0xFFFFFFFF ||
805         attributes == FILE_ATTRIBUTE_DIRECTORY)
806     {
807         InvalidateRect(_preview_wnd, NULL, FALSE);
808         return;
809     }
811     // Check the file exists and get the file size
812     HANDLE file_handle = CreateFileW(_path_string, GENERIC_READ,
813         FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
814     if(file_handle == INVALID_HANDLE_VALUE) return;
815     const DWORD file_size = GetFileSize(file_handle, NULL);
816     if (file_size == INVALID_FILE_SIZE) return;
817     _preview_file_size = file_size / 1024;
818     CloseHandle(file_handle);
820     if(_show_preview) load_preview();
823 void FileOpenDialogImplWin32::load_preview()
825     // Destroy any previous previews
826     free_preview();
828     // Try to get the file icon
829     SHFILEINFOW fileInfo;
830     if(SUCCEEDED(SHGetFileInfoW(_path_string, 0, &fileInfo,
831         sizeof(fileInfo), SHGFI_ICON | SHGFI_LARGEICON)))
832         _preview_file_icon = fileInfo.hIcon;
834     // Will this file be too big?
835     if(_preview_file_size > MaxPreviewFileSize)
836     {
837         InvalidateRect(_preview_wnd, NULL, FALSE);
838         return;
839     }
841     // Prepare to render a preview
842     const Glib::ustring svg = ".svg";
843     const Glib::ustring svgz = ".svgz";
844     const Glib::ustring emf = ".emf";
845     const Glib::ustring wmf = ".wmf";
846     const Glib::ustring path = utf16_to_ustring(_path_string);
848     bool success = false;
850     _preview_document_width = _preview_document_height = 0;
852     if ((dialogType == SVG_TYPES || dialogType == IMPORT_TYPES) &&
853             (hasSuffix(path, svg) || hasSuffix(path, svgz)))
854         success = set_svg_preview();
855     else if (hasSuffix(path, emf) || hasSuffix(path, wmf))
856         success = set_emf_preview();
857     else if (isValidImageFile(path))
858         success = set_image_preview();
859     else {
860         // Show no preview
861     }
863     if(success) render_preview();
865     InvalidateRect(_preview_wnd, NULL, FALSE);
868 void FileOpenDialogImplWin32::free_preview()
870     _mutex->lock();
871     if(_preview_bitmap != NULL)
872         DeleteObject(_preview_bitmap);
873     _preview_bitmap = NULL;
875     if(_preview_file_icon != NULL)
876         DestroyIcon(_preview_file_icon);
877     _preview_file_icon = NULL;
879     _preview_bitmap_image.clear();
880     _preview_emf_image = false;
881     _mutex->unlock();
884 bool FileOpenDialogImplWin32::set_svg_preview()
886     const int PreviewSize = 512;
888     gchar *utf8string = g_utf16_to_utf8((const gunichar2*)_path_string,
889         _MAX_PATH, NULL, NULL, NULL);
890     SPDocument *svgDoc = SPDocument::createNewDoc (utf8string, true);
891     g_free(utf8string);
893     // Check the document loaded properly
894     if(svgDoc == NULL) return false;
895     if(svgDoc->root == NULL)
896     {
897         svgDoc->doUnref();
898         return false;
899     }
901     // Get the size of the document
902     const double svgWidth = svgDoc->getWidth();
903     const double svgHeight = svgDoc->getHeight();
905     // Find the minimum scale to fit the image inside the preview area
906     const double scaleFactorX =    PreviewSize / svgWidth;
907     const double scaleFactorY =    PreviewSize / svgHeight;
908     const double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX;
910     // Now get the resized values
911     const double scaledSvgWidth  = scaleFactor * svgWidth;
912     const double scaledSvgHeight = scaleFactor * svgHeight;
914     Geom::Rect area(Geom::Point(0, 0), Geom::Point(scaledSvgWidth, scaledSvgHeight));
915     NRRectL areaL = {0, 0, scaledSvgWidth, scaledSvgHeight};
916     NRRectL bbox = {0, 0, scaledSvgWidth, scaledSvgHeight};
918     // write object bbox to area
919     Geom::OptRect maybeArea(area);
920     svgDoc->ensure_up_to_date ();
921     static_cast<(SPItem *)>(svgDoc->root)->invoke_bbox( maybeArea,
922         static_cast<(SPItem *)>(svgDoc->root)->i2d_affine(), TRUE);
924     NRArena *const arena = NRArena::create();
926     unsigned const key = sp_item_display_key_new(1);
928     NRArenaItem *root = sp_item_invoke_show((SPItem*)(svgDoc->root),
929         arena, key, SP_ITEM_SHOW_DISPLAY);
931     NRGC gc(NULL);
932     gc.transform = Geom::Matrix(Geom::Scale(scaleFactor, scaleFactor));
934     nr_arena_item_invoke_update (root, NULL, &gc,
935         NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
937     // Prepare a GDI compatible NRPixBlock
938     NRPixBlock pixBlock;
939     pixBlock.size = NR_PIXBLOCK_SIZE_BIG;
940     pixBlock.mode = NR_PIXBLOCK_MODE_R8G8B8;
941     pixBlock.empty = 1;
942     pixBlock.visible_area.x0 = pixBlock.area.x0 = 0;
943     pixBlock.visible_area.y0 = pixBlock.area.y0 = 0;
944     pixBlock.visible_area.x1 = pixBlock.area.x1 = scaledSvgWidth;
945     pixBlock.visible_area.y1 = pixBlock.area.y1 = scaledSvgHeight;
946     pixBlock.rs = 4 * ((3 * (int)scaledSvgWidth + 3) / 4);
947     pixBlock.data.px = g_try_new (unsigned char, pixBlock.rs * scaledSvgHeight);
949     // Fail if the pixblock failed to allocate
950     if(pixBlock.data.px == NULL)
951     {
952         svgDoc->doUnref();
953         return false;
954     }
956     memset(pixBlock.data.px, 0xFF, pixBlock.rs * scaledSvgHeight);
958     memcpy(&root->bbox, &areaL, sizeof(areaL));
960     // Render the image
961     nr_arena_item_invoke_render(NULL, root, &bbox, &pixBlock, /*0*/NR_ARENA_ITEM_RENDER_NO_CACHE);
963     // Tidy up
964     svgDoc->doUnref();
965     sp_item_invoke_hide((SPItem*)(svgDoc->root), key);
966     nr_object_unref((NRObject *) arena);
968     // Create the GDK pixbuf
969     _mutex->lock();
971     _preview_bitmap_image = Gdk::Pixbuf::create_from_data(
972         pixBlock.data.px, Gdk::COLORSPACE_RGB, false, 8,
973         (int)scaledSvgWidth, (int)scaledSvgHeight, pixBlock.rs,
974         sigc::ptr_fun(destroy_svg_rendering));
976     _preview_document_width = scaledSvgWidth;
977     _preview_document_height = scaledSvgHeight;
978     _preview_image_width = svgWidth;
979     _preview_image_height = svgHeight;
981     _mutex->unlock();
983     return true;
986 void FileOpenDialogImplWin32::destroy_svg_rendering(const guint8 *buffer)
988     g_assert(buffer != NULL);
989     g_free((void*)buffer);
992 bool FileOpenDialogImplWin32::set_image_preview()
994     const Glib::ustring path = utf16_to_ustring(_path_string, _MAX_PATH);
996     bool successful = false;
998     _mutex->lock();
1000     try {
1001         _preview_bitmap_image = Gdk::Pixbuf::create_from_file(path);
1002         if (_preview_bitmap_image) {
1003             _preview_image_width = _preview_bitmap_image->get_width();
1004             _preview_document_width = _preview_image_width;
1005             _preview_image_height = _preview_bitmap_image->get_height();
1006             _preview_document_height = _preview_image_height;
1007             successful = true;
1008         }
1009     }
1010     catch (const Gdk::PixbufError&) {}
1011     catch (const Glib::FileError&) {}
1013     _mutex->unlock();
1015     return successful;
1018 // Aldus Placeable Header ===================================================
1019 // Since we are a 32bit app, we have to be sure this structure compiles to
1020 // be identical to a 16 bit app's version. To do this, we use the #pragma
1021 // to adjust packing, we use a WORD for the hmf handle, and a SMALL_RECT
1022 // for the bbox rectangle.
1023 #pragma pack( push )
1024 #pragma pack( 2 )
1025 typedef struct
1027     DWORD       dwKey;
1028     WORD        hmf;
1029     SMALL_RECT  bbox;
1030     WORD        wInch;
1031     DWORD       dwReserved;
1032     WORD        wCheckSum;
1033 } APMHEADER, *PAPMHEADER;
1034 #pragma pack( pop )
1037 static HENHMETAFILE
1038 MyGetEnhMetaFileW( const WCHAR *filename )
1040     // Try open as Enhanced Metafile
1041     HENHMETAFILE hemf = GetEnhMetaFileW(filename);
1043     if (!hemf) {
1044         // Try open as Windows Metafile
1045         HMETAFILE hmf = GetMetaFileW(filename);
1047         METAFILEPICT mp;
1048         HDC hDC;
1050         if (!hmf) {
1051             WCHAR szTemp[MAX_PATH];
1053             DWORD dw = GetShortPathNameW( filename, szTemp, MAX_PATH );
1054             if (dw) {
1055                 hmf = GetMetaFileW( szTemp );
1056             }
1057         }
1059         if (hmf) {
1060             // Convert Windows Metafile to Enhanced Metafile
1061             DWORD nSize = GetMetaFileBitsEx( hmf, 0, NULL );
1063             if (nSize) {
1064                 BYTE *lpvData = new BYTE[nSize];
1065                 if (lpvData) {
1066                     DWORD dw = GetMetaFileBitsEx( hmf, nSize, lpvData );
1067                     if (dw) {
1068                         // Fill out a METAFILEPICT structure
1069                         mp.mm = MM_ANISOTROPIC;
1070                         mp.xExt = 1000;
1071                         mp.yExt = 1000;
1072                         mp.hMF = NULL;
1073                         // Get a reference DC
1074                         hDC = GetDC( NULL );
1075                         // Make an enhanced metafile from the windows metafile
1076                         hemf = SetWinMetaFileBits( nSize, lpvData, hDC, &mp );
1077                         // Clean up
1078                         ReleaseDC( NULL, hDC );
1079                         DeleteMetaFile( hmf );
1080                     }
1081                     delete[] lpvData;
1082                 }
1083                 else {
1084                     DeleteMetaFile( hmf );
1085                 }
1086             }
1087             else {
1088                 DeleteMetaFile( hmf );
1089             }
1090         }
1091         else {
1092             // Try open as Aldus Placeable Metafile
1093             HANDLE hFile;
1094             hFile = CreateFileW( filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
1096             if (hFile != INVALID_HANDLE_VALUE) {
1097                 DWORD nSize = GetFileSize( hFile, NULL );
1098                 if (nSize) {
1099                     BYTE *lpvData = new BYTE[nSize];
1100                     if (lpvData) {
1101                         DWORD dw = ReadFile( hFile, lpvData, nSize, &nSize, NULL );
1102                         if (dw) {
1103                             if ( ((PAPMHEADER)lpvData)->dwKey == 0x9ac6cdd7l ) {
1104                                 // Fill out a METAFILEPICT structure
1105                                 mp.mm = MM_ANISOTROPIC;
1106                                 mp.xExt = ((PAPMHEADER)lpvData)->bbox.Right - ((PAPMHEADER)lpvData)->bbox.Left;
1107                                 mp.xExt = ( mp.xExt * 2540l ) / (DWORD)(((PAPMHEADER)lpvData)->wInch);
1108                                 mp.yExt = ((PAPMHEADER)lpvData)->bbox.Bottom - ((PAPMHEADER)lpvData)->bbox.Top;
1109                                 mp.yExt = ( mp.yExt * 2540l ) / (DWORD)(((PAPMHEADER)lpvData)->wInch);
1110                                 mp.hMF = NULL;
1111                                 // Get a reference DC
1112                                 hDC = GetDC( NULL );
1113                                 // Create an enhanced metafile from the bits
1114                                 hemf = SetWinMetaFileBits( nSize, lpvData+sizeof(APMHEADER), hDC, &mp );
1115                                 // Clean up
1116                                 ReleaseDC( NULL, hDC );
1117                             }
1118                         }
1119                         delete[] lpvData;
1120                     }
1121                 }
1122                 CloseHandle( hFile );
1123             }
1124         }
1125     }
1127     return hemf;
1131 bool FileOpenDialogImplWin32::set_emf_preview()
1133     _mutex->lock();
1135     BOOL ok = FALSE;
1137     DWORD w = 0;
1138     DWORD h = 0;
1140     HENHMETAFILE hemf = MyGetEnhMetaFileW( _path_string );
1142     if (hemf)
1143     {
1144         ENHMETAHEADER emh;
1145         ZeroMemory(&emh, sizeof(emh));
1146         ok = GetEnhMetaFileHeader(hemf, sizeof(emh), &emh) != 0;
1148         w = (emh.rclFrame.right - emh.rclFrame.left);
1149         h = (emh.rclFrame.bottom - emh.rclFrame.top);
1151         DeleteEnhMetaFile(hemf);
1152     }
1154     if (ok)
1155     {
1156         const int PreviewSize = 512;
1158         // Get the size of the document
1159         const double emfWidth = w;
1160         const double emfHeight = h;
1162         // Find the minimum scale to fit the image inside the preview area
1163         const double scaleFactorX =    PreviewSize / emfWidth;
1164         const double scaleFactorY =    PreviewSize / emfHeight;
1165         const double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX;
1167         // Now get the resized values
1168         const double scaledEmfWidth  = scaleFactor * emfWidth;
1169         const double scaledEmfHeight = scaleFactor * emfHeight;
1171         _preview_document_width = scaledEmfWidth;
1172         _preview_document_height = scaledEmfHeight;
1173         _preview_image_width = emfWidth;
1174         _preview_image_height = emfHeight;
1176         _preview_emf_image = true;
1177     }
1179     _mutex->unlock();
1181     return ok;
1184 void FileOpenDialogImplWin32::render_preview()
1186     double x, y;
1187     const double blurRadius = 8;
1188     const double halfBlurRadius = blurRadius / 2;
1189     const int shaddowOffsetX = 0;
1190     const int shaddowOffsetY = 2;
1191     const int pagePadding = 5;
1192     const double shaddowAlpha = 0.75;
1194     // Is the preview showing?
1195     if(!_show_preview)
1196         return;
1198     // Do we have anything to render?
1199     _mutex->lock();
1201     if(!_preview_bitmap_image && !_preview_emf_image)
1202     {
1203         _mutex->unlock();
1204         return;
1205     }
1207     // Tidy up any previous bitmap renderings
1208     if(_preview_bitmap != NULL)
1209         DeleteObject(_preview_bitmap);
1210     _preview_bitmap = NULL;
1212     // Calculate the size of the caption
1213     int captionHeight = 0;
1215     if(_preview_wnd != NULL)
1216     {
1217         RECT rcCaptionRect;
1218         WCHAR szCaption[_MAX_FNAME + 32];
1219         const int iLength = format_caption(szCaption,
1220             sizeof(szCaption) / sizeof(WCHAR));
1222         HDC dc = GetDC(_preview_wnd);
1223         DrawTextW(dc, szCaption, iLength, &rcCaptionRect,
1224             DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_CALCRECT);
1225         ReleaseDC(_preview_wnd, dc);
1227         captionHeight = rcCaptionRect.bottom - rcCaptionRect.top;
1228     }
1230     // Find the minimum scale to fit the image inside the preview area
1231     const double scaleFactorX =
1232         ((double)_preview_width - pagePadding * 2 - blurRadius)  / _preview_document_width;
1233     const double scaleFactorY =
1234         ((double)_preview_height - pagePadding * 2
1235         - shaddowOffsetY - halfBlurRadius - captionHeight) / _preview_document_height;
1236     double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX;
1237     scaleFactor = (scaleFactor > 1.0) ? 1.0 : scaleFactor;
1239     // Now get the resized values
1240     const double scaledSvgWidth  = scaleFactor * _preview_document_width;
1241     const double scaledSvgHeight = scaleFactor * _preview_document_height;
1243     const int svgX = pagePadding + halfBlurRadius;
1244     const int svgY = pagePadding;
1246     const int frameX = svgX - pagePadding;
1247     const int frameY = svgY - pagePadding;
1248     const int frameWidth = scaledSvgWidth + pagePadding * 2;
1249     const int frameHeight = scaledSvgHeight + pagePadding * 2;
1251     const int totalWidth = (int)ceil(frameWidth + blurRadius);
1252     const int totalHeight = (int)ceil(frameHeight + blurRadius);
1254     // Prepare the drawing surface
1255     HDC hDC = GetDC(_preview_wnd);
1256     HDC hMemDC = CreateCompatibleDC(hDC);
1257     _preview_bitmap = CreateCompatibleBitmap(hDC, totalWidth, totalHeight);
1258     HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDC, _preview_bitmap);
1259     Cairo::RefPtr<Win32Surface> surface = Win32Surface::create(hMemDC);
1260     Cairo::RefPtr<Context> context = Context::create(surface);
1262     // Paint the background to match the dialog colour
1263     const COLORREF background = GetSysColor(COLOR_3DFACE);
1264     context->set_source_rgb(
1265         GetRValue(background) / 255.0,
1266         GetGValue(background) / 255.0,
1267         GetBValue(background) / 255.0);
1268     context->paint();
1270     //----- Draw the drop shaddow -----//
1272     // Left Edge
1273     x = frameX + shaddowOffsetX - halfBlurRadius;
1274     Cairo::RefPtr<LinearGradient> leftEdgeFade = LinearGradient::create(
1275         x, 0.0, x + blurRadius, 0.0);
1276     leftEdgeFade->add_color_stop_rgba (0, 0, 0, 0, 0);
1277     leftEdgeFade->add_color_stop_rgba (1, 0, 0, 0, shaddowAlpha);
1278     context->set_source(leftEdgeFade);
1279     context->rectangle (x, frameY + shaddowOffsetY + halfBlurRadius,
1280         blurRadius, frameHeight - blurRadius);
1281     context->fill();
1283     // Right Edge
1284     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1285     Cairo::RefPtr<LinearGradient> rightEdgeFade = LinearGradient::create(
1286         x, 0.0,    x + blurRadius, 0.0);
1287     rightEdgeFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1288     rightEdgeFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1289     context->set_source(rightEdgeFade);
1290     context->rectangle (frameX + frameWidth + shaddowOffsetX - halfBlurRadius,
1291         frameY + shaddowOffsetY + halfBlurRadius,
1292         blurRadius, frameHeight - blurRadius);
1293     context->fill();
1295     // Top Edge
1296     y = frameY + shaddowOffsetY - halfBlurRadius;
1297     Cairo::RefPtr<LinearGradient> topEdgeFade = LinearGradient::create(
1298         0.0, y, 0.0, y + blurRadius);
1299     topEdgeFade->add_color_stop_rgba (0, 0, 0, 0, 0);
1300     topEdgeFade->add_color_stop_rgba (1, 0, 0, 0, shaddowAlpha);
1301     context->set_source(topEdgeFade);
1302     context->rectangle (frameX + shaddowOffsetX + halfBlurRadius, y,
1303         frameWidth - blurRadius, blurRadius);
1304     context->fill();
1306     // Bottom Edge
1307     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1308     Cairo::RefPtr<LinearGradient> bottomEdgeFade = LinearGradient::create(
1309         0.0, y,    0.0, y + blurRadius);
1310     bottomEdgeFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1311     bottomEdgeFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1312     context->set_source(bottomEdgeFade);
1313     context->rectangle (frameX + shaddowOffsetX + halfBlurRadius, y,
1314         frameWidth - blurRadius, blurRadius);
1315     context->fill();
1317     // Top Left Corner
1318     x = frameX + shaddowOffsetX - halfBlurRadius;
1319     y = frameY + shaddowOffsetY - halfBlurRadius;
1320     Cairo::RefPtr<RadialGradient> topLeftCornerFade = RadialGradient::create(
1321         x + blurRadius, y + blurRadius, 0, x + blurRadius, y + blurRadius, blurRadius);
1322     topLeftCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1323     topLeftCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1324     context->set_source(topLeftCornerFade);
1325     context->rectangle (x, y, blurRadius, blurRadius);
1326     context->fill();
1328     // Top Right Corner
1329     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1330     y = frameY + shaddowOffsetY - halfBlurRadius;
1331     Cairo::RefPtr<RadialGradient> topRightCornerFade = RadialGradient::create(
1332         x, y + blurRadius, 0, x, y + blurRadius, blurRadius);
1333     topRightCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1334     topRightCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1335     context->set_source(topRightCornerFade);
1336     context->rectangle (x, y, blurRadius, blurRadius);
1337     context->fill();
1339     // Bottom Left Corner
1340     x = frameX + shaddowOffsetX - halfBlurRadius;
1341     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1342     Cairo::RefPtr<RadialGradient> bottomLeftCornerFade = RadialGradient::create(
1343         x + blurRadius, y, 0, x + blurRadius, y, blurRadius);
1344     bottomLeftCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1345     bottomLeftCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1346     context->set_source(bottomLeftCornerFade);
1347     context->rectangle (x, y, blurRadius, blurRadius);
1348     context->fill();
1350     // Bottom Right Corner
1351     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1352     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1353     Cairo::RefPtr<RadialGradient> bottomRightCornerFade = RadialGradient::create(
1354         x, y, 0, x, y, blurRadius);
1355     bottomRightCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1356     bottomRightCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1357     context->set_source(bottomRightCornerFade);
1358     context->rectangle (frameX + frameWidth + shaddowOffsetX - halfBlurRadius,
1359         frameY + frameHeight + shaddowOffsetY - halfBlurRadius,
1360         blurRadius, blurRadius);
1361     context->fill();
1363     // Draw the frame
1364     context->set_line_width(1);
1365     context->rectangle (frameX, frameY,    frameWidth, frameHeight);
1367     context->set_source_rgb(1.0, 1.0, 1.0);
1368     context->fill_preserve();
1369     context->set_source_rgb(0.25, 0.25, 0.25);
1370     context->stroke_preserve();
1372     // Draw the image
1373     if(_preview_bitmap_image)    // Is the image a pixbuf?
1374     {
1375         // Set the transformation
1376         const Cairo::Matrix matrix(
1377             scaleFactor, 0,
1378             0, scaleFactor,
1379             svgX, svgY);
1380         context->set_matrix (matrix);
1382         // Render the image
1383         set_source_pixbuf (context, _preview_bitmap_image, 0, 0);
1384         context->paint();
1386         // Reset the transformation
1387         context->set_identity_matrix();
1388     }
1390     // Draw the inner frame
1391     context->set_source_rgb(0.75, 0.75, 0.75);
1392     context->rectangle (svgX, svgY,    scaledSvgWidth, scaledSvgHeight);
1393     context->stroke();
1395     _mutex->unlock();
1397     // Finish drawing
1398     surface->finish();
1400     if (_preview_emf_image) {
1401         HENHMETAFILE hemf = MyGetEnhMetaFileW(_path_string);
1402         if (hemf) {
1403             RECT rc;
1404             rc.top = svgY+2;
1405             rc.left = svgX+2;
1406             rc.bottom = scaledSvgHeight-2;
1407             rc.right = scaledSvgWidth-2;
1408             PlayEnhMetaFile(hMemDC, hemf, &rc);
1409             DeleteEnhMetaFile(hemf);
1410         }
1411     }
1413     SelectObject(hMemDC, hOldBitmap) ;
1414     DeleteDC(hMemDC);
1416     // Refresh the preview pane
1417     InvalidateRect(_preview_wnd, NULL, FALSE);
1420 int FileOpenDialogImplWin32::format_caption(wchar_t *caption, int caption_size)
1422     wchar_t szFileName[_MAX_FNAME];
1423     _wsplitpath(_path_string, NULL, NULL, szFileName, NULL);
1425     return snwprintf(caption, caption_size,
1426         L"%s\n%d kB\n%d \xD7 %d", szFileName, _preview_file_size,
1427         (int)_preview_document_width, (int)_preview_document_height);
1430 /**
1431  * Show this dialog modally.  Return true if user hits [OK]
1432  */
1433 bool
1434 FileOpenDialogImplWin32::show()
1436     // We can only run one worker thread at a time
1437     if(_mutex != NULL) return false;
1439     if(!Glib::thread_supported())
1440         Glib::thread_init();
1442     _result = false;
1443     _finished = false;
1444     _file_selected = false;
1445     _mutex = new Glib::Mutex();
1446     _main_loop = g_main_loop_new(g_main_context_default(), FALSE);
1448     if(Glib::Thread::create(sigc::mem_fun(*this, &FileOpenDialogImplWin32::GetOpenFileName_thread), true))
1449     {
1450         while(1)
1451         {
1452             g_main_context_iteration(g_main_context_default(), FALSE);
1454             if(_mutex->trylock())
1455             {
1456                 // Read mutexed data
1457                 const bool finished = _finished;
1458                 const bool is_file_selected = _file_selected;
1459                 _file_selected = false;
1460                 _mutex->unlock();
1462                 if(finished) break;
1463                 if(is_file_selected) file_selected();
1464             }
1466             Sleep(10);
1467         }
1468     }
1470     // Tidy up
1471     delete _mutex;
1472     _mutex = NULL;
1474     return _result;
1477 /**
1478  * To Get Multiple filenames selected at-once.
1479  */
1480 std::vector<Glib::ustring>FileOpenDialogImplWin32::getFilenames()
1482     std::vector<Glib::ustring> result;
1483     result.push_back(getFilename());
1484     return result;
1488 /*#########################################################################
1489 ### F I L E    S A V E
1490 #########################################################################*/
1492 /**
1493  * Constructor
1494  */
1495 FileSaveDialogImplWin32::FileSaveDialogImplWin32(Gtk::Window &parent,
1496             const Glib::ustring &dir,
1497             FileDialogType fileTypes,
1498             const char *title,
1499             const Glib::ustring &/*default_key*/,
1500             const char *docTitle,
1501             const Inkscape::Extension::FileSaveMethod save_method) :
1502     FileDialogBaseWin32(parent, dir, title, fileTypes,
1503                         (save_method == Inkscape::Extension::FILE_SAVE_METHOD_SAVE_COPY) ? "dialogs.save_copy" :  "dialogs.save_as"),
1504         _title_label(NULL),
1505         _title_edit(NULL)
1507     FileSaveDialog::myDocTitle = docTitle;
1508     createFilterMenu();
1511 FileSaveDialogImplWin32::~FileSaveDialogImplWin32()
1515 void FileSaveDialogImplWin32::createFilterMenu()
1517     list<Filter> filter_list;
1519     knownExtensions.clear();
1521     // Compose the filter string
1522     Glib::ustring all_inkscape_files_filter, all_image_files_filter;
1523     Inkscape::Extension::DB::OutputList extension_list;
1524     Inkscape::Extension::db.get_output_list(extension_list);
1526     int filter_count = 0;
1527     int filter_length = 1;
1529     for (Inkscape::Extension::DB::OutputList::iterator current_item = extension_list.begin();
1530          current_item != extension_list.end(); current_item++)
1531     {
1532         Inkscape::Extension::Output *omod = *current_item;
1533         if (omod->deactivated()) continue;
1535         filter_count++;
1537         Filter filter;
1539         // Extension
1540         const gchar *filter_extension = omod->get_extension();
1541         filter.filter = g_utf8_to_utf16(
1542             filter_extension, -1, NULL, &filter.filter_length, NULL);
1543         knownExtensions.insert( Glib::ustring(filter_extension).casefold() );
1545         // Type
1546         filter.name = g_utf8_to_utf16(
1547             _(omod->get_filetypename()), -1, NULL, &filter.name_length, NULL);
1549         filter.mod = omod;
1551         filter_length += filter.name_length +
1552             filter.filter_length + 3;   // Add 3 for two \0s and a *
1554         filter_list.push_back(filter);
1555     }
1557     int extension_index = 0;
1558     _extension_map = new Inkscape::Extension::Extension*[filter_count];
1560     _filter = new wchar_t[filter_length];
1561     wchar_t *filterptr = _filter;
1563     for(list<Filter>::iterator filter_iterator = filter_list.begin();
1564         filter_iterator != filter_list.end(); filter_iterator++)
1565     {
1566         const Filter &filter = *filter_iterator;
1568         wcsncpy(filterptr, (wchar_t*)filter.name, filter.name_length);
1569         filterptr += filter.name_length;
1570         g_free(filter.name);
1572         *(filterptr++) = L'\0';
1573         *(filterptr++) = L'*';
1575         wcsncpy(filterptr, (wchar_t*)filter.filter, filter.filter_length);
1576         filterptr += filter.filter_length;
1577         g_free(filter.filter);
1579         *(filterptr++) = L'\0';
1581         // Associate this input extension with the file type name
1582         _extension_map[extension_index++] = filter.mod;
1583     }
1584     *(filterptr++) = 0;
1586         _filter_count = extension_index;
1587     _filter_index = 1;  // A value of 1 selects the 1st filter - NOT the 2nd
1590 void FileSaveDialogImplWin32::GetSaveFileName_thread()
1592     OPENFILENAMEEXW ofn;
1594     g_assert(this != NULL);
1595     g_assert(_main_loop != NULL);
1597     WCHAR* current_directory_string = (WCHAR*)g_utf8_to_utf16(
1598         _current_directory.data(), _current_directory.length(),
1599                 NULL, NULL, NULL);
1601     // Copy the selected file name, converting from UTF-8 to UTF-16
1602     memset(_path_string, 0, sizeof(_path_string));
1603     gunichar2* utf16_path_string = g_utf8_to_utf16(
1604         myFilename.data(), -1, NULL, NULL, NULL);
1605     wcsncpy(_path_string, (wchar_t*)utf16_path_string, _MAX_PATH);
1606     g_free(utf16_path_string);
1608     ZeroMemory(&ofn, sizeof(ofn));
1609     ofn.lStructSize = sizeof(ofn);
1610     ofn.hwndOwner = _ownerHwnd;
1611     ofn.lpstrFile = _path_string;
1612     ofn.nMaxFile = _MAX_PATH;
1613     ofn.nFilterIndex = _filter_index;
1614     ofn.lpstrFileTitle = NULL;
1615     ofn.nMaxFileTitle = 0;
1616     ofn.lpstrInitialDir = current_directory_string;
1617     ofn.lpstrTitle = _title;
1618     ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ENABLEHOOK;
1619     ofn.lpstrFilter = _filter;
1620     ofn.nFilterIndex = _filter_index;
1621     ofn.lpfnHook = GetSaveFileName_hookproc;
1622     ofn.lCustData = (LPARAM)this;
1624     _result = GetSaveFileNameW(&ofn) != 0;
1626         g_assert(ofn.nFilterIndex >= 1 && ofn.nFilterIndex <= _filter_count);
1627     _filter_index = ofn.nFilterIndex;
1628     _extension = _extension_map[ofn.nFilterIndex - 1];
1630     // Copy the selected file name, converting from UTF-16 to UTF-8
1631     myFilename = utf16_to_ustring(_path_string, _MAX_PATH);
1633     // Tidy up
1634     g_free(current_directory_string);
1636     g_main_loop_quit(_main_loop);
1639 /**
1640  * Show this dialog modally.  Return true if user hits [OK]
1641  */
1642 bool
1643 FileSaveDialogImplWin32::show()
1645     if(!Glib::thread_supported())
1646         Glib::thread_init();
1648     _result = false;
1649     _main_loop = g_main_loop_new(g_main_context_default(), FALSE);
1651         if(_main_loop != NULL)
1652         {
1653             if(Glib::Thread::create(sigc::mem_fun(*this, &FileSaveDialogImplWin32::GetSaveFileName_thread), true))
1654                 g_main_loop_run(_main_loop);
1656             if(_result)
1657                 appendExtension(myFilename, (Inkscape::Extension::Output*)_extension);
1658         }
1660     return _result;
1663 void FileSaveDialogImplWin32::setSelectionType( Inkscape::Extension::Extension * /*key*/ )
1665     // If no pointer to extension is passed in, look up based on filename extension.
1669 UINT_PTR CALLBACK FileSaveDialogImplWin32::GetSaveFileName_hookproc(
1670     HWND hdlg, UINT uiMsg, WPARAM, LPARAM lParam)
1672     FileSaveDialogImplWin32 *pImpl = (FileSaveDialogImplWin32*)
1673         GetWindowLongPtr(hdlg, GWLP_USERDATA);
1675     switch(uiMsg)
1676     {
1677     case WM_INITDIALOG:
1678         {
1679             HWND hParentWnd = GetParent(hdlg);
1680             HINSTANCE hInstance = GetModuleHandle(NULL);
1682             // get size/pos of typical combo box
1683             RECT rEDT1, rCB1, rROOT, rST;
1684             GetWindowRect(GetDlgItem(hParentWnd, cmb1), &rCB1);
1685             GetWindowRect(GetDlgItem(hParentWnd, cmb13), &rEDT1);
1686             GetWindowRect(GetDlgItem(hParentWnd, stc2), &rST);
1687             GetWindowRect(hdlg, &rROOT);
1688             int ydelta = rCB1.top - rEDT1.top;
1690             // Make the window a bit longer
1691             RECT rcRect;
1692             GetWindowRect(hParentWnd, &rcRect);
1693             MoveWindow(hParentWnd, rcRect.left, rcRect.top, rcRect.right - rcRect.left,
1694                        rcRect.bottom - rcRect.top + ydelta, FALSE);
1696             // It is not necessary to delete stock objects by calling DeleteObject
1697             HGDIOBJ dlgFont = GetStockObject(DEFAULT_GUI_FONT);
1699             // Set the pointer to the object
1700             OPENFILENAMEW *ofn = (OPENFILENAMEW*)lParam;
1701             SetWindowLongPtr(hdlg, GWLP_USERDATA, ofn->lCustData);
1702             SetWindowLongPtr(hParentWnd, GWLP_USERDATA, ofn->lCustData);
1703             pImpl = (FileSaveDialogImplWin32*)ofn->lCustData;
1705             // Create the Title label and edit control
1706             pImpl->_title_label = CreateWindowEx(NULL, "STATIC", "Title:",
1707                                         WS_VISIBLE|WS_CHILD,
1708                                         CW_USEDEFAULT, CW_USEDEFAULT, rCB1.left-rST.left, rST.bottom-rST.top,
1709                                         hParentWnd, NULL, hInstance, NULL);
1710             if(pImpl->_title_label) {
1711               if(dlgFont) SendMessage(pImpl->_title_label, WM_SETFONT, (WPARAM)dlgFont, MAKELPARAM(FALSE, 0));
1712               SetWindowPos(pImpl->_title_label, NULL, rST.left-rROOT.left, rST.top+ydelta-rROOT.top,
1713                            rCB1.left-rST.left, rST.bottom-rST.top, SWP_SHOWWINDOW|SWP_NOZORDER);
1714             }
1716             pImpl->_title_edit = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "",
1717                                         WS_VISIBLE|WS_CHILD|WS_TABSTOP|ES_AUTOHSCROLL,
1718                                         CW_USEDEFAULT, CW_USEDEFAULT, rCB1.right-rCB1.left, rCB1.bottom-rCB1.top,
1719                                         hParentWnd, NULL, hInstance, NULL);
1720             if(pImpl->_title_edit) {
1721               if(dlgFont) SendMessage(pImpl->_title_edit, WM_SETFONT, (WPARAM)dlgFont, MAKELPARAM(FALSE, 0));
1722               SetWindowPos(pImpl->_title_edit, NULL, rCB1.left-rROOT.left, rCB1.top+ydelta-rROOT.top,
1723                            rCB1.right-rCB1.left, rCB1.bottom-rCB1.top, SWP_SHOWWINDOW|SWP_NOZORDER);
1724               // TODO: make sure this works for Unicode
1725               SetWindowText(pImpl->_title_edit, pImpl->myDocTitle.c_str());
1726             }
1727         }
1728         break;
1729     case WM_DESTROY:
1730       {
1731         if(pImpl->_title_edit) {
1732           int length = GetWindowTextLength(pImpl->_title_edit)+1;
1733           char* temp_title = new char[length];
1734           GetWindowText(pImpl->_title_edit, temp_title, length);
1735           pImpl->myDocTitle = temp_title;
1736           delete[] temp_title;
1737           DestroyWindow(pImpl->_title_label);
1738           pImpl->_title_label = NULL;
1739           DestroyWindow(pImpl->_title_edit);
1740           pImpl->_title_edit = NULL;
1741         }
1742       }
1743       break;
1744     }
1746     // Use default dialog behaviour
1747     return 0;
1750 } } } // namespace Dialog, UI, Inkscape
1752 #endif // ifdef WIN32
1754 /*
1755   Local Variables:
1756   mode:c++
1757   c-file-style:"stroustrup"
1758   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1759   indent-tabs-mode:nil
1760   fill-column:99
1761   End:
1762 */
1763 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :