Code

Merge from fe-moved
[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 = 1344; // 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;
194     Filter all_files, all_inkscape_files, all_image_files;
196     const gchar *all_files_filter_name = N_("All Files");
197     const gchar *all_inkscape_files_filter_name = N_("All Inkscape Files");
198     const gchar *all_image_files_filter_name = N_("All Image Files");
200     // Calculate the amount of memory required
201     int filter_count = 3;       // 3 - one for All Files, All Images and All Inkscape Files
202     int filter_length = 1;
204     for (Inkscape::Extension::DB::InputList::iterator current_item = extension_list.begin();
205          current_item != extension_list.end(); current_item++)
206     {
207         Filter filter;
209         Inkscape::Extension::Input *imod = *current_item;
210         if (imod->deactivated()) continue;
212         // Type
213         filter.name = g_utf8_to_utf16(_(imod->get_filetypename()),
214             -1, NULL, &filter.name_length, NULL);
216         // Extension
217         const gchar *file_extension_name = imod->get_extension();
218         filter.filter = g_utf8_to_utf16(file_extension_name,
219             -1, NULL, &filter.filter_length, NULL);
221         filter.mod = imod;
222         filter_list.push_back(filter);
224         filter_length += filter.name_length +
225             filter.filter_length + 3;   // Add 3 for two \0s and a *
227         // Add to the "All Inkscape Files" Entry
228         if(all_inkscape_files_filter.length() > 0)
229             all_inkscape_files_filter += ";*";
230         all_inkscape_files_filter += file_extension_name;
231         if( strncmp("image", imod->get_mimetype(), 5) == 0)
232         {
233             // Add to the "All Image Files" Entry
234             if(all_image_files_filter.length() > 0)
235                 all_image_files_filter += ";*";
236             all_image_files_filter += file_extension_name;
237         }
239         filter_count++;
240     }
242     int extension_index = 0;
243     _extension_map = new Inkscape::Extension::Extension*[filter_count];
245     // Filter Image Files
246     all_image_files.name = g_utf8_to_utf16(all_image_files_filter_name,
247         -1, NULL, &all_image_files.name_length, NULL);
248     all_image_files.filter = g_utf8_to_utf16(all_image_files_filter.data(),
249             -1, NULL, &all_image_files.filter_length, NULL);
250         all_image_files.mod = NULL;
251     filter_list.push_front(all_image_files);
253     // Filter Inkscape Files
254     all_inkscape_files.name = g_utf8_to_utf16(all_inkscape_files_filter_name,
255         -1, NULL, &all_inkscape_files.name_length, NULL);
256     all_inkscape_files.filter = g_utf8_to_utf16(all_inkscape_files_filter.data(),
257             -1, NULL, &all_inkscape_files.filter_length, NULL);
258         all_inkscape_files.mod = NULL;
259     filter_list.push_front(all_inkscape_files);
261     // Filter All Files
262     all_files.name = g_utf8_to_utf16(all_files_filter_name,
263         -1, NULL, &all_files.name_length, NULL);
264     all_files.filter = NULL;
265     all_files.filter_length = 0;
266         all_files.mod = NULL;
267     filter_list.push_front(all_files);
269     filter_length += all_files.name_length + 3 +
270                     all_inkscape_files.filter_length +
271                     all_inkscape_files.name_length + 3 +
272                     all_image_files.filter_length +
273                     all_image_files.name_length + 3 + 1;
274      // Add 3 for 2*2 \0s and a *, and 1 for a trailing \0
276         _filter = new wchar_t[filter_length];
277     wchar_t *filterptr = _filter;
279     for(list<Filter>::iterator filter_iterator = filter_list.begin();
280         filter_iterator != filter_list.end(); filter_iterator++)
281     {
282         const Filter &filter = *filter_iterator;
284         wcsncpy(filterptr, (wchar_t*)filter.name, filter.name_length);
285         filterptr += filter.name_length;
286         g_free(filter.name);
288         *(filterptr++) = L'\0';
289         *(filterptr++) = L'*';
291         if(filter.filter != NULL)
292         {
293             wcsncpy(filterptr, (wchar_t*)filter.filter, filter.filter_length);
294             filterptr += filter.filter_length;
295             g_free(filter.filter);
296         }
298         *(filterptr++) = L'\0';
300         // Associate this input extension with the file type name
301         _extension_map[extension_index++] = filter.mod;
302     }
303     *(filterptr++) = L'\0';
305         _filter_count = extension_index;
306     _filter_index = 2;  // Select the 2nd filter in the list - 2 is NOT the 3rd
309 void FileOpenDialogImplWin32::GetOpenFileName_thread()
311     OPENFILENAMEEXW ofn;
313     g_assert(this != NULL);
314         g_assert(_mutex != NULL);
316     WCHAR* current_directory_string = (WCHAR*)g_utf8_to_utf16(
317         _current_directory.data(), _current_directory.length(),
318                 NULL, NULL, NULL);
320     memset(&ofn, 0, sizeof(ofn));
322     // Copy the selected file name, converting from UTF-8 to UTF-16
323     memset(_path_string, 0, sizeof(_path_string));
324     gunichar2* utf16_path_string = g_utf8_to_utf16(
325         myFilename.data(), -1, NULL, NULL, NULL);
326     wcsncpy(_path_string, (wchar_t*)utf16_path_string, _MAX_PATH);
327     g_free(utf16_path_string);
329     ofn.lStructSize = sizeof(ofn);
330     ofn.hwndOwner = _ownerHwnd;
331     ofn.lpstrFile = _path_string;
332     ofn.nMaxFile = _MAX_PATH;
333     ofn.lpstrFileTitle = NULL;
334     ofn.nMaxFileTitle = 0;
335     ofn.lpstrInitialDir = current_directory_string;
336     ofn.lpstrTitle = _title;
337     ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ENABLEHOOK | OFN_HIDEREADONLY | OFN_ENABLESIZING;
338     ofn.lpstrFilter = _filter;
339     ofn.nFilterIndex = _filter_index;
340     ofn.lpfnHook = GetOpenFileName_hookproc;
341     ofn.lCustData = (LPARAM)this;
343     _result = GetOpenFileNameW(&ofn) != 0;
345         g_assert(ofn.nFilterIndex >= 1 && ofn.nFilterIndex <= _filter_count);
346     _filter_index = ofn.nFilterIndex;
347     _extension = _extension_map[ofn.nFilterIndex - 1];
349     // Copy the selected file name, converting from UTF-16 to UTF-8
350     myFilename = utf16_to_ustring(_path_string, _MAX_PATH);
352     // Tidy up
353     g_free(current_directory_string);
355     _mutex->lock();
356     _finished = true;
357     _mutex->unlock();
360 void FileOpenDialogImplWin32::register_preview_wnd_class()
362     HINSTANCE hInstance = GetModuleHandle(NULL);
363     const WNDCLASSA PreviewWndClass =
364     {
365         CS_HREDRAW | CS_VREDRAW,
366         preview_wnd_proc,
367         0,
368         0,
369         hInstance,
370         NULL,
371         LoadCursor(hInstance, IDC_ARROW),
372         (HBRUSH)(COLOR_BTNFACE + 1),
373         NULL,
374         PreviewWindowClassName
375     };
377     RegisterClassA(&PreviewWndClass);
380 UINT_PTR CALLBACK FileOpenDialogImplWin32::GetOpenFileName_hookproc(
381     HWND hdlg, UINT uiMsg, WPARAM, LPARAM lParam)
383     FileOpenDialogImplWin32 *pImpl = (FileOpenDialogImplWin32*)
384         GetWindowLongPtr(hdlg, GWLP_USERDATA);
386     switch(uiMsg)
387     {
388     case WM_INITDIALOG:
389         {
390             HWND hParentWnd = GetParent(hdlg);
391             HINSTANCE hInstance = GetModuleHandle(NULL);
393             // Make the window a bit wider
394             RECT rcRect;
395             GetWindowRect(hParentWnd, &rcRect);
396             MoveWindow(hParentWnd, rcRect.left, rcRect.top,
397                 rcRect.right - rcRect.left + PreviewWidening,
398                 rcRect.bottom - rcRect.top,
399                 FALSE);
401             // Set the pointer to the object
402             OPENFILENAMEW *ofn = (OPENFILENAMEW*)lParam;
403             SetWindowLongPtr(hdlg, GWLP_USERDATA, ofn->lCustData);
404             SetWindowLongPtr(hParentWnd, GWLP_USERDATA, ofn->lCustData);
405             pImpl = (FileOpenDialogImplWin32*)ofn->lCustData;
407             // Subclass the parent
408             pImpl->_base_window_proc = (WNDPROC)GetWindowLongPtr(hParentWnd, GWL_WNDPROC);
409             SetWindowLongPtr(hParentWnd, GWL_WNDPROC, (LONG_PTR)file_dialog_subclass_proc);
411             // Add a button to the toolbar
412             pImpl->_toolbar_wnd = FindWindowEx(hParentWnd, NULL, "ToolbarWindow32", NULL);
414             pImpl->_show_preview_button_bitmap = LoadBitmap(
415                 hInstance, MAKEINTRESOURCE(IDC_SHOW_PREVIEW));
416             TBADDBITMAP tbAddBitmap = {NULL, (UINT)pImpl->_show_preview_button_bitmap};
417             const int iBitmapIndex = SendMessage(pImpl->_toolbar_wnd,
418                 TB_ADDBITMAP, 1, (LPARAM)&tbAddBitmap);
420             TBBUTTON tbButton;
421             memset(&tbButton, 0, sizeof(TBBUTTON));
422             tbButton.iBitmap = iBitmapIndex;
423             tbButton.idCommand = IDC_SHOW_PREVIEW;
424             tbButton.fsState = (pImpl->_show_preview ? TBSTATE_CHECKED : 0)
425                 | TBSTATE_ENABLED;
426             tbButton.fsStyle = TBSTYLE_CHECK;
427             tbButton.iString = (INT_PTR)_("Show Preview");
428             SendMessage(pImpl->_toolbar_wnd, TB_ADDBUTTONS, 1, (LPARAM)&tbButton);
430             // Create preview pane
431             register_preview_wnd_class();
433             pImpl->_mutex->lock();
435                 pImpl->_file_dialog_wnd = hParentWnd;
437                 pImpl->_preview_wnd =
438                     CreateWindowA(PreviewWindowClassName, "",
439                         WS_CHILD | WS_VISIBLE,
440                         0, 0, 100, 100, hParentWnd, NULL, hInstance, NULL);
441                 SetWindowLongPtr(pImpl->_preview_wnd, GWLP_USERDATA, ofn->lCustData);
443             pImpl->_mutex->unlock();
445             pImpl->layout_dialog();
446         }
447         break;
449     case WM_NOTIFY:
450         {
452         OFNOTIFY *pOFNotify = reinterpret_cast<OFNOTIFY*>(lParam);
453         switch(pOFNotify->hdr.code)
454         {
455         case CDN_SELCHANGE:
456             {
457                 if(pImpl != NULL)
458                 {
459                     // Get the file name
460                     pImpl->_mutex->lock();
462                     SendMessage(pOFNotify->hdr.hwndFrom, CDM_GETFILEPATH,
463                         sizeof(pImpl->_path_string) / sizeof(wchar_t),
464                         (LPARAM)pImpl->_path_string);
466                     pImpl->_file_selected = true;
468                     pImpl->_mutex->unlock();
469                 }
470             }
471             break;
472         }
473         }
474         break;
476     case WM_CLOSE:
477         pImpl->_mutex->lock();
478         pImpl->_preview_file_size = 0;
480         pImpl->_file_dialog_wnd = NULL;
481         DestroyWindow(pImpl->_preview_wnd);
482         pImpl->_preview_wnd = NULL;
483         DeleteObject(pImpl->_show_preview_button_bitmap);
484         pImpl->_show_preview_button_bitmap = NULL;
485         pImpl->_mutex->unlock();
487         break;
488     }
490     // Use default dialog behaviour
491     return 0;
494 LRESULT CALLBACK FileOpenDialogImplWin32::file_dialog_subclass_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
496     FileOpenDialogImplWin32 *pImpl = (FileOpenDialogImplWin32*)
497         GetWindowLongPtr(hwnd, GWLP_USERDATA);
499     LRESULT lResult = CallWindowProc(pImpl->_base_window_proc, hwnd, uMsg, wParam, lParam);
501     switch(uMsg)
502     {
503     case WM_SHOWWINDOW:
504         if(wParam != 0)
505             pImpl->layout_dialog();
506         break;
508     case WM_SIZE:
509         pImpl->layout_dialog();
510         break;
512     case WM_COMMAND:
513         if(wParam == IDC_SHOW_PREVIEW)
514         {
515             const bool enable = SendMessage(pImpl->_toolbar_wnd,
516                 TB_ISBUTTONCHECKED, IDC_SHOW_PREVIEW, 0) != 0;
517             pImpl->enable_preview(enable);
518         }
519         break;
520     }
522     return lResult;
525 LRESULT CALLBACK FileOpenDialogImplWin32::preview_wnd_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
527     const int CaptionPadding = 4;
528     const int IconSize = 32;
530     FileOpenDialogImplWin32 *pImpl = (FileOpenDialogImplWin32*)
531         GetWindowLongPtr(hwnd, GWLP_USERDATA);
533     LRESULT lResult = 0;
535     switch(uMsg)
536     {
537     case WM_ERASEBKGND:
538         // Do nothing to erase the background
539         //  - otherwise there'll be flicker
540         lResult = 1;
541         break;
543     case WM_PAINT:
544         {
545             // Get the client rect
546             RECT rcClient;
547             GetClientRect(hwnd, &rcClient);
549             // Prepare to paint
550             PAINTSTRUCT paint_struct;
551             HDC dc = BeginPaint(hwnd, &paint_struct);
553             HFONT hCaptionFont = (HFONT)SendMessage(GetParent(hwnd),
554                     WM_GETFONT, 0, 0);
555             HFONT hOldFont = (HFONT)SelectObject(dc, hCaptionFont);
556             SetBkMode(dc, TRANSPARENT);
558             pImpl->_mutex->lock();
560             if(pImpl->_path_string[0] == 0)
561             {
562                 FillRect(dc, &rcClient, (HBRUSH)(COLOR_3DFACE + 1));
563                 DrawText(dc, _("No file selected"), -1, &rcClient,
564                     DT_CENTER | DT_VCENTER | DT_NOPREFIX);
565             }
566             else if(pImpl->_preview_bitmap != NULL)
567             {
568                 BITMAP bitmap;
569                 GetObject(pImpl->_preview_bitmap, sizeof(bitmap), &bitmap);
570                 const int destX = (rcClient.right - bitmap.bmWidth) / 2;
572                 // Render the image
573                 HDC hSrcDC = CreateCompatibleDC(dc);
574                 HBITMAP hOldBitmap = (HBITMAP)SelectObject(hSrcDC, pImpl->_preview_bitmap);
576                 BitBlt(dc, destX, 0, bitmap.bmWidth, bitmap.bmHeight,
577                     hSrcDC, 0, 0, SRCCOPY);
579                 SelectObject(hSrcDC, hOldBitmap);
580                 DeleteDC(hSrcDC);
582                 // Fill in the background area
583                 HRGN hEraseRgn = CreateRectRgn(rcClient.left, rcClient.top,
584                     rcClient.right, rcClient.bottom);
585                 HRGN hImageRgn = CreateRectRgn(destX, 0,
586                     destX + bitmap.bmWidth, bitmap.bmHeight);
587                 CombineRgn(hEraseRgn, hEraseRgn, hImageRgn, RGN_DIFF);
589                 FillRgn(dc, hEraseRgn, GetSysColorBrush(COLOR_3DFACE));
591                 DeleteObject(hImageRgn);
592                 DeleteObject(hEraseRgn);
594                 // Draw the caption on
595                 RECT rcCaptionRect = {rcClient.left,
596                     rcClient.top + bitmap.bmHeight + CaptionPadding,
597                     rcClient.right, rcClient.bottom};
599                 WCHAR szCaption[_MAX_FNAME + 32];
600                 const int iLength = pImpl->format_caption(
601                     szCaption, sizeof(szCaption) / sizeof(WCHAR));
603                 DrawTextW(dc, szCaption, iLength, &rcCaptionRect,
604                     DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS);
605             }
606             else if(pImpl->_preview_file_icon != NULL)
607             {
608                 FillRect(dc, &rcClient, (HBRUSH)(COLOR_3DFACE + 1));
610                 // Draw the files icon
611                 const int destX = (rcClient.right - IconSize) / 2;
612                 DrawIconEx(dc, destX, 0, pImpl->_preview_file_icon,
613                     IconSize, IconSize, 0, NULL,
614                     DI_NORMAL | DI_COMPAT);
616                 // Draw the caption on
617                 RECT rcCaptionRect = {rcClient.left,
618                     rcClient.top + IconSize + CaptionPadding,
619                     rcClient.right, rcClient.bottom};
621                 WCHAR szFileName[_MAX_FNAME], szCaption[_MAX_FNAME + 32];
622                 _wsplitpath(pImpl->_path_string, NULL, NULL, szFileName, NULL);
624                 const int iLength = snwprintf(szCaption,
625                     sizeof(szCaption), L"%s\n%d kB",
626                     szFileName, pImpl->_preview_file_size);
628                 DrawTextW(dc, szCaption, iLength, &rcCaptionRect,
629                     DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS);
630             }
631             else
632             {
633                 // Can't show anything!
634                 FillRect(dc, &rcClient, (HBRUSH)(COLOR_3DFACE + 1));
635             }
637             pImpl->_mutex->unlock();
639             // Finish painting
640             SelectObject(dc, hOldFont);
641             EndPaint(hwnd, &paint_struct);
642         }
644         break;
646     case WM_DESTROY:
647         pImpl->free_preview();
648         break;
650     default:
651         lResult = DefWindowProc(hwnd, uMsg, wParam, lParam);
652         break;
653     }
655     return lResult;
658 void FileOpenDialogImplWin32::enable_preview(bool enable)
660     _show_preview = enable;
662     // Relayout the dialog
663     ShowWindow(_preview_wnd, enable ? SW_SHOW : SW_HIDE);
664     layout_dialog();
666     // Load or unload the preview
667     if(enable)
668     {
669         _mutex->lock();
670         _file_selected = true;
671         _mutex->unlock();
672     }
673     else free_preview();
676 void FileOpenDialogImplWin32::layout_dialog()
678     union RECTPOINTS
679     {
680         RECT r;
681         POINT p[2];
682     };
684     const float MaxExtentScale = 2.0f / 3.0f;
686     RECT rcClient;
687     GetClientRect(_file_dialog_wnd, &rcClient);
689     // Re-layout the dialog
690     HWND hFileListWnd = GetDlgItem(_file_dialog_wnd, lst2);
691     HWND hFolderComboWnd = GetDlgItem(_file_dialog_wnd, cmb2);
694     RECT rcFolderComboRect;
695     RECTPOINTS rcFileList;
696     GetWindowRect(hFileListWnd, &rcFileList.r);
697     GetWindowRect(hFolderComboWnd, &rcFolderComboRect);
698     const int iPadding = rcFileList.r.top - rcFolderComboRect.bottom;
699     MapWindowPoints(NULL, _file_dialog_wnd, rcFileList.p, 2);
701     RECT rcPreview;
702     RECT rcBody = {rcFileList.r.left, rcFileList.r.top,
703         rcClient.right - iPadding, rcFileList.r.bottom};
704     rcFileList.r.right = rcBody.right;
706     if(_show_preview)
707     {
708         rcPreview.top = rcBody.top;
709         rcPreview.left = rcClient.right - (rcBody.bottom - rcBody.top);
710         const int iMaxExtent = (int)(MaxExtentScale * (float)(rcBody.left + rcBody.right)) + iPadding / 2;
711         if(rcPreview.left < iMaxExtent) rcPreview.left = iMaxExtent;
712         rcPreview.bottom = rcBody.bottom;
713         rcPreview.right = rcBody.right;
715         // Re-layout the preview box
716         _mutex->lock();
718             _preview_width = rcPreview.right - rcPreview.left;
719             _preview_height = rcPreview.bottom - rcPreview.top;
721         _mutex->unlock();
723         render_preview();
725         MoveWindow(_preview_wnd, rcPreview.left, rcPreview.top,
726             _preview_width, _preview_height, TRUE);
728         rcFileList.r.right = rcPreview.left - iPadding;
729     }
731     // Re-layout the file list box
732     MoveWindow(hFileListWnd, rcFileList.r.left, rcFileList.r.top,
733         rcFileList.r.right - rcFileList.r.left,
734         rcFileList.r.bottom - rcFileList.r.top, TRUE);
736     // Re-layout the toolbar
737     RECTPOINTS rcToolBar;
738     GetWindowRect(_toolbar_wnd, &rcToolBar.r);
739     MapWindowPoints(NULL, _file_dialog_wnd, rcToolBar.p, 2);
740     MoveWindow(_toolbar_wnd, rcToolBar.r.left, rcToolBar.r.top,
741         rcToolBar.r.right - rcToolBar.r.left, rcToolBar.r.bottom - rcToolBar.r.top, TRUE);
744 void FileOpenDialogImplWin32::file_selected()
746     // Destroy any previous previews
747     free_preview();
750     // Determine if the file exists
751     DWORD attributes = GetFileAttributesW(_path_string);
752     if(attributes == 0xFFFFFFFF ||
753         attributes == FILE_ATTRIBUTE_DIRECTORY)
754     {
755         InvalidateRect(_preview_wnd, NULL, FALSE);
756         return;
757     }
759     // Check the file exists and get the file size
760     HANDLE file_handle = CreateFileW(_path_string, GENERIC_READ,
761         FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
762     if(file_handle == INVALID_HANDLE_VALUE) return;
763     const DWORD file_size = GetFileSize(file_handle, NULL);
764     if (file_size == INVALID_FILE_SIZE) return;
765     _preview_file_size = file_size / 1024;
766     CloseHandle(file_handle);
768     if(_show_preview) load_preview();
771 void FileOpenDialogImplWin32::load_preview()
773     // Destroy any previous previews
774     free_preview();
776     // Try to get the file icon
777     SHFILEINFOW fileInfo;
778     if(SUCCEEDED(SHGetFileInfoW(_path_string, 0, &fileInfo,
779         sizeof(fileInfo), SHGFI_ICON | SHGFI_LARGEICON)))
780         _preview_file_icon = fileInfo.hIcon;
782     // Will this file be too big?
783     if(_preview_file_size > MaxPreviewFileSize)
784     {
785         InvalidateRect(_preview_wnd, NULL, FALSE);
786         return;
787     }
789     // Prepare to render a preview
790     const Glib::ustring svg = ".svg";
791     const Glib::ustring svgz = ".svgz";
792     const Glib::ustring emf = ".emf";
793     const Glib::ustring wmf = ".wmf";
794     const Glib::ustring path = utf16_to_ustring(_path_string);
796     bool success = false;
798     _preview_document_width = _preview_document_height = 0;
800     if ((dialogType == SVG_TYPES || dialogType == IMPORT_TYPES) &&
801             (hasSuffix(path, svg) || hasSuffix(path, svgz)))
802         success = set_svg_preview();
803     else if (hasSuffix(path, emf) || hasSuffix(path, wmf))
804         success = set_emf_preview();
805     else if (isValidImageFile(path))
806         success = set_image_preview();
807     else {
808         // Show no preview
809     }
811     if(success) render_preview();
813     InvalidateRect(_preview_wnd, NULL, FALSE);
816 void FileOpenDialogImplWin32::free_preview()
818     _mutex->lock();
819     if(_preview_bitmap != NULL)
820         DeleteObject(_preview_bitmap);
821     _preview_bitmap = NULL;
823     if(_preview_file_icon != NULL)
824         DestroyIcon(_preview_file_icon);
825     _preview_file_icon = NULL;
827     _preview_bitmap_image.clear();
828     _preview_emf_image = false;
829     _mutex->unlock();
832 bool FileOpenDialogImplWin32::set_svg_preview()
834     const int PreviewSize = 512;
836     gchar *utf8string = g_utf16_to_utf8((const gunichar2*)_path_string,
837         _MAX_PATH, NULL, NULL, NULL);
838     SPDocument *svgDoc = sp_document_new (utf8string, true);
839     g_free(utf8string);
841     // Check the document loaded properly
842     if(svgDoc == NULL) return false;
843     if(svgDoc->root == NULL)
844     {
845         sp_document_unref(svgDoc);
846         return false;
847     }
849     // Get the size of the document
850     const double svgWidth = sp_document_width(svgDoc);
851     const double svgHeight = sp_document_height(svgDoc);
853     // Find the minimum scale to fit the image inside the preview area
854     const double scaleFactorX =    PreviewSize / svgWidth;
855     const double scaleFactorY =    PreviewSize / svgHeight;
856     const double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX;
858     // Now get the resized values
859     const double scaledSvgWidth  = scaleFactor * svgWidth;
860     const double scaledSvgHeight = scaleFactor * svgHeight;
862     Geom::Rect area(Geom::Point(0, 0), Geom::Point(scaledSvgWidth, scaledSvgHeight));
863     NRRectL areaL = {0, 0, scaledSvgWidth, scaledSvgHeight};
864     NRRectL bbox = {0, 0, scaledSvgWidth, scaledSvgHeight};
866     // write object bbox to area
867     Geom::OptRect maybeArea(area);
868     sp_document_ensure_up_to_date (svgDoc);
869     sp_item_invoke_bbox((SPItem *) svgDoc->root, maybeArea,
870         sp_item_i2r_affine((SPItem *)(svgDoc->root)), TRUE);
872     NRArena *const arena = NRArena::create();
874     unsigned const key = sp_item_display_key_new(1);
876     NRArenaItem *root = sp_item_invoke_show((SPItem*)(svgDoc->root),
877         arena, key, SP_ITEM_SHOW_DISPLAY);
879     NRGC gc(NULL);
880     gc.transform = Geom::Matrix(Geom::Scale(scaleFactor, scaleFactor));
882     nr_arena_item_invoke_update (root, NULL, &gc,
883         NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
885     // Prepare a GDI compatible NRPixBlock
886     NRPixBlock pixBlock;
887     pixBlock.size = NR_PIXBLOCK_SIZE_BIG;
888     pixBlock.mode = NR_PIXBLOCK_MODE_R8G8B8;
889     pixBlock.empty = 1;
890     pixBlock.visible_area.x0 = pixBlock.area.x0 = 0;
891     pixBlock.visible_area.y0 = pixBlock.area.y0 = 0;
892     pixBlock.visible_area.x1 = pixBlock.area.x1 = scaledSvgWidth;
893     pixBlock.visible_area.y1 = pixBlock.area.y1 = scaledSvgHeight;
894     pixBlock.rs = 4 * ((3 * (int)scaledSvgWidth + 3) / 4);
895     pixBlock.data.px = g_try_new (unsigned char, pixBlock.rs * scaledSvgHeight);
897     // Fail if the pixblock failed to allocate
898     if(pixBlock.data.px == NULL)
899     {
900         sp_document_unref(svgDoc);
901         return false;
902     }
904     memset(pixBlock.data.px, 0xFF, pixBlock.rs * scaledSvgHeight);
906     memcpy(&root->bbox, &areaL, sizeof(areaL));
908     // Render the image
909     nr_arena_item_invoke_render(NULL, root, &bbox, &pixBlock, /*0*/NR_ARENA_ITEM_RENDER_NO_CACHE);
911     // Tidy up
912     sp_document_unref(svgDoc);
913     sp_item_invoke_hide((SPItem*)(svgDoc->root), key);
914     nr_object_unref((NRObject *) arena);
916     // Create the GDK pixbuf
917     _mutex->lock();
919     _preview_bitmap_image = Gdk::Pixbuf::create_from_data(
920         pixBlock.data.px, Gdk::COLORSPACE_RGB, false, 8,
921         (int)scaledSvgWidth, (int)scaledSvgHeight, pixBlock.rs,
922         sigc::ptr_fun(destroy_svg_rendering));
924     _preview_document_width = scaledSvgWidth;
925     _preview_document_height = scaledSvgHeight;
926     _preview_image_width = svgWidth;
927     _preview_image_height = svgHeight;
929     _mutex->unlock();
931     return true;
934 void FileOpenDialogImplWin32::destroy_svg_rendering(const guint8 *buffer)
936     g_assert(buffer != NULL);
937     g_free((void*)buffer);
940 bool FileOpenDialogImplWin32::set_image_preview()
942     const Glib::ustring path = utf16_to_ustring(_path_string, _MAX_PATH);
944     bool successful = false;
946     _mutex->lock();
948     try {
949         _preview_bitmap_image = Gdk::Pixbuf::create_from_file(path);
950         if (_preview_bitmap_image) {
951             _preview_image_width = _preview_bitmap_image->get_width();
952             _preview_document_width = _preview_image_width;
953             _preview_image_height = _preview_bitmap_image->get_height();
954             _preview_document_height = _preview_image_height;
955             successful = true;
956         }
957     }
958     catch (const Gdk::PixbufError&) {}
959     catch (const Glib::FileError&) {}
961     _mutex->unlock();
963     return successful;
966 // Aldus Placeable Header ===================================================
967 // Since we are a 32bit app, we have to be sure this structure compiles to
968 // be identical to a 16 bit app's version. To do this, we use the #pragma
969 // to adjust packing, we use a WORD for the hmf handle, and a SMALL_RECT
970 // for the bbox rectangle.
971 #pragma pack( push )
972 #pragma pack( 2 )
973 typedef struct
975     DWORD       dwKey;
976     WORD        hmf;
977     SMALL_RECT  bbox;
978     WORD        wInch;
979     DWORD       dwReserved;
980     WORD        wCheckSum;
981 } APMHEADER, *PAPMHEADER;
982 #pragma pack( pop )
985 static HENHMETAFILE
986 MyGetEnhMetaFileW( const WCHAR *filename )
988     // Try open as Enhanced Metafile
989     HENHMETAFILE hemf = GetEnhMetaFileW(filename);
991     if (!hemf) {
992         // Try open as Windows Metafile
993         HMETAFILE hmf = GetMetaFileW(filename);
995         METAFILEPICT mp;
996         HDC hDC;
998         if (!hmf) {
999             WCHAR szTemp[MAX_PATH];
1001             DWORD dw = GetShortPathNameW( filename, szTemp, MAX_PATH );
1002             if (dw) {
1003                 hmf = GetMetaFileW( szTemp );
1004             }
1005         }
1007         if (hmf) {
1008             // Convert Windows Metafile to Enhanced Metafile
1009             DWORD nSize = GetMetaFileBitsEx( hmf, 0, NULL );
1011             if (nSize) {
1012                 BYTE *lpvData = new BYTE[nSize];
1013                 if (lpvData) {
1014                     DWORD dw = GetMetaFileBitsEx( hmf, nSize, lpvData );
1015                     if (dw) {
1016                         // Fill out a METAFILEPICT structure
1017                         mp.mm = MM_ANISOTROPIC;
1018                         mp.xExt = 1000;
1019                         mp.yExt = 1000;
1020                         mp.hMF = NULL;
1021                         // Get a reference DC
1022                         hDC = GetDC( NULL );
1023                         // Make an enhanced metafile from the windows metafile
1024                         hemf = SetWinMetaFileBits( nSize, lpvData, hDC, &mp );
1025                         // Clean up
1026                         ReleaseDC( NULL, hDC );
1027                         DeleteMetaFile( hmf );
1028                     }
1029                     delete[] lpvData;
1030                 }
1031                 else {
1032                     DeleteMetaFile( hmf );
1033                 }
1034             }
1035             else {
1036                 DeleteMetaFile( hmf );
1037             }
1038         }
1039         else {
1040             // Try open as Aldus Placeable Metafile
1041             HANDLE hFile;
1042             hFile = CreateFileW( filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
1044             if (hFile != INVALID_HANDLE_VALUE) {
1045                 DWORD nSize = GetFileSize( hFile, NULL );
1046                 if (nSize) {
1047                     BYTE *lpvData = new BYTE[nSize];
1048                     if (lpvData) {
1049                         DWORD dw = ReadFile( hFile, lpvData, nSize, &nSize, NULL );
1050                         if (dw) {
1051                             if ( ((PAPMHEADER)lpvData)->dwKey == 0x9ac6cdd7l ) {
1052                                 // Fill out a METAFILEPICT structure
1053                                 mp.mm = MM_ANISOTROPIC;
1054                                 mp.xExt = ((PAPMHEADER)lpvData)->bbox.Right - ((PAPMHEADER)lpvData)->bbox.Left;
1055                                 mp.xExt = ( mp.xExt * 2540l ) / (DWORD)(((PAPMHEADER)lpvData)->wInch);
1056                                 mp.yExt = ((PAPMHEADER)lpvData)->bbox.Bottom - ((PAPMHEADER)lpvData)->bbox.Top;
1057                                 mp.yExt = ( mp.yExt * 2540l ) / (DWORD)(((PAPMHEADER)lpvData)->wInch);
1058                                 mp.hMF = NULL;
1059                                 // Get a reference DC
1060                                 hDC = GetDC( NULL );
1061                                 // Create an enhanced metafile from the bits
1062                                 hemf = SetWinMetaFileBits( nSize, lpvData+sizeof(APMHEADER), hDC, &mp );
1063                                 // Clean up
1064                                 ReleaseDC( NULL, hDC );
1065                             }
1066                         }
1067                         delete[] lpvData;
1068                     }
1069                 }
1070                 CloseHandle( hFile );
1071             }
1072         }
1073     }
1075     return hemf;
1079 bool FileOpenDialogImplWin32::set_emf_preview()
1081     _mutex->lock();
1083     BOOL ok = FALSE;
1085     DWORD w = 0;
1086     DWORD h = 0;
1088     HENHMETAFILE hemf = MyGetEnhMetaFileW( _path_string );
1090     if (hemf)
1091     {
1092         ENHMETAHEADER emh;
1093         ZeroMemory(&emh, sizeof(emh));
1094         ok = GetEnhMetaFileHeader(hemf, sizeof(emh), &emh) != 0;
1096         w = (emh.rclFrame.right - emh.rclFrame.left);
1097         h = (emh.rclFrame.bottom - emh.rclFrame.top);
1099         DeleteEnhMetaFile(hemf);
1100     }
1102     if (ok)
1103     {
1104         const int PreviewSize = 512;
1106         // Get the size of the document
1107         const double emfWidth = w;
1108         const double emfHeight = h;
1110         // Find the minimum scale to fit the image inside the preview area
1111         const double scaleFactorX =    PreviewSize / emfWidth;
1112         const double scaleFactorY =    PreviewSize / emfHeight;
1113         const double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX;
1115         // Now get the resized values
1116         const double scaledEmfWidth  = scaleFactor * emfWidth;
1117         const double scaledEmfHeight = scaleFactor * emfHeight;
1119         _preview_document_width = scaledEmfWidth;
1120         _preview_document_height = scaledEmfHeight;
1121         _preview_image_width = emfWidth;
1122         _preview_image_height = emfHeight;
1124         _preview_emf_image = true;
1125     }
1127     _mutex->unlock();
1129     return ok;
1132 void FileOpenDialogImplWin32::render_preview()
1134     double x, y;
1135     const double blurRadius = 8;
1136     const double halfBlurRadius = blurRadius / 2;
1137     const int shaddowOffsetX = 0;
1138     const int shaddowOffsetY = 2;
1139     const int pagePadding = 5;
1140     const double shaddowAlpha = 0.75;
1142     // Is the preview showing?
1143     if(!_show_preview)
1144         return;
1146     // Do we have anything to render?
1147     _mutex->lock();
1149     if(!_preview_bitmap_image && !_preview_emf_image)
1150     {
1151         _mutex->unlock();
1152         return;
1153     }
1155     // Tidy up any previous bitmap renderings
1156     if(_preview_bitmap != NULL)
1157         DeleteObject(_preview_bitmap);
1158     _preview_bitmap = NULL;
1160     // Calculate the size of the caption
1161     int captionHeight = 0;
1163     if(_preview_wnd != NULL)
1164     {
1165         RECT rcCaptionRect;
1166         WCHAR szCaption[_MAX_FNAME + 32];
1167         const int iLength = format_caption(szCaption,
1168             sizeof(szCaption) / sizeof(WCHAR));
1170         HDC dc = GetDC(_preview_wnd);
1171         DrawTextW(dc, szCaption, iLength, &rcCaptionRect,
1172             DT_CENTER | DT_TOP | DT_NOPREFIX | DT_PATH_ELLIPSIS | DT_CALCRECT);
1173         ReleaseDC(_preview_wnd, dc);
1175         captionHeight = rcCaptionRect.bottom - rcCaptionRect.top;
1176     }
1178     // Find the minimum scale to fit the image inside the preview area
1179     const double scaleFactorX =
1180         ((double)_preview_width - pagePadding * 2 - blurRadius)  / _preview_document_width;
1181     const double scaleFactorY =
1182         ((double)_preview_height - pagePadding * 2
1183         - shaddowOffsetY - halfBlurRadius - captionHeight) / _preview_document_height;
1184     double scaleFactor = (scaleFactorX > scaleFactorY) ? scaleFactorY : scaleFactorX;
1185     scaleFactor = (scaleFactor > 1.0) ? 1.0 : scaleFactor;
1187     // Now get the resized values
1188     const double scaledSvgWidth  = scaleFactor * _preview_document_width;
1189     const double scaledSvgHeight = scaleFactor * _preview_document_height;
1191     const int svgX = pagePadding + halfBlurRadius;
1192     const int svgY = pagePadding;
1194     const int frameX = svgX - pagePadding;
1195     const int frameY = svgY - pagePadding;
1196     const int frameWidth = scaledSvgWidth + pagePadding * 2;
1197     const int frameHeight = scaledSvgHeight + pagePadding * 2;
1199     const int totalWidth = (int)ceil(frameWidth + blurRadius);
1200     const int totalHeight = (int)ceil(frameHeight + blurRadius);
1202     // Prepare the drawing surface
1203     HDC hDC = GetDC(_preview_wnd);
1204     HDC hMemDC = CreateCompatibleDC(hDC);
1205     _preview_bitmap = CreateCompatibleBitmap(hDC, totalWidth, totalHeight);
1206     HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDC, _preview_bitmap);
1207     Cairo::RefPtr<Win32Surface> surface = Win32Surface::create(hMemDC);
1208     Cairo::RefPtr<Context> context = Context::create(surface);
1210     // Paint the background to match the dialog colour
1211     const COLORREF background = GetSysColor(COLOR_3DFACE);
1212     context->set_source_rgb(
1213         GetRValue(background) / 255.0,
1214         GetGValue(background) / 255.0,
1215         GetBValue(background) / 255.0);
1216     context->paint();
1218     //----- Draw the drop shaddow -----//
1220     // Left Edge
1221     x = frameX + shaddowOffsetX - halfBlurRadius;
1222     Cairo::RefPtr<LinearGradient> leftEdgeFade = LinearGradient::create(
1223         x, 0.0, x + blurRadius, 0.0);
1224     leftEdgeFade->add_color_stop_rgba (0, 0, 0, 0, 0);
1225     leftEdgeFade->add_color_stop_rgba (1, 0, 0, 0, shaddowAlpha);
1226     context->set_source(leftEdgeFade);
1227     context->rectangle (x, frameY + shaddowOffsetY + halfBlurRadius,
1228         blurRadius, frameHeight - blurRadius);
1229     context->fill();
1231     // Right Edge
1232     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1233     Cairo::RefPtr<LinearGradient> rightEdgeFade = LinearGradient::create(
1234         x, 0.0,    x + blurRadius, 0.0);
1235     rightEdgeFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1236     rightEdgeFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1237     context->set_source(rightEdgeFade);
1238     context->rectangle (frameX + frameWidth + shaddowOffsetX - halfBlurRadius,
1239         frameY + shaddowOffsetY + halfBlurRadius,
1240         blurRadius, frameHeight - blurRadius);
1241     context->fill();
1243     // Top Edge
1244     y = frameY + shaddowOffsetY - halfBlurRadius;
1245     Cairo::RefPtr<LinearGradient> topEdgeFade = LinearGradient::create(
1246         0.0, y, 0.0, y + blurRadius);
1247     topEdgeFade->add_color_stop_rgba (0, 0, 0, 0, 0);
1248     topEdgeFade->add_color_stop_rgba (1, 0, 0, 0, shaddowAlpha);
1249     context->set_source(topEdgeFade);
1250     context->rectangle (frameX + shaddowOffsetX + halfBlurRadius, y,
1251         frameWidth - blurRadius, blurRadius);
1252     context->fill();
1254     // Bottom Edge
1255     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1256     Cairo::RefPtr<LinearGradient> bottomEdgeFade = LinearGradient::create(
1257         0.0, y,    0.0, y + blurRadius);
1258     bottomEdgeFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1259     bottomEdgeFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1260     context->set_source(bottomEdgeFade);
1261     context->rectangle (frameX + shaddowOffsetX + halfBlurRadius, y,
1262         frameWidth - blurRadius, blurRadius);
1263     context->fill();
1265     // Top Left Corner
1266     x = frameX + shaddowOffsetX - halfBlurRadius;
1267     y = frameY + shaddowOffsetY - halfBlurRadius;
1268     Cairo::RefPtr<RadialGradient> topLeftCornerFade = RadialGradient::create(
1269         x + blurRadius, y + blurRadius, 0, x + blurRadius, y + blurRadius, blurRadius);
1270     topLeftCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1271     topLeftCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1272     context->set_source(topLeftCornerFade);
1273     context->rectangle (x, y, blurRadius, blurRadius);
1274     context->fill();
1276     // Top Right Corner
1277     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1278     y = frameY + shaddowOffsetY - halfBlurRadius;
1279     Cairo::RefPtr<RadialGradient> topRightCornerFade = RadialGradient::create(
1280         x, y + blurRadius, 0, x, y + blurRadius, blurRadius);
1281     topRightCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1282     topRightCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1283     context->set_source(topRightCornerFade);
1284     context->rectangle (x, y, blurRadius, blurRadius);
1285     context->fill();
1287     // Bottom Left Corner
1288     x = frameX + shaddowOffsetX - halfBlurRadius;
1289     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1290     Cairo::RefPtr<RadialGradient> bottomLeftCornerFade = RadialGradient::create(
1291         x + blurRadius, y, 0, x + blurRadius, y, blurRadius);
1292     bottomLeftCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1293     bottomLeftCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1294     context->set_source(bottomLeftCornerFade);
1295     context->rectangle (x, y, blurRadius, blurRadius);
1296     context->fill();
1298     // Bottom Right Corner
1299     x = frameX + frameWidth + shaddowOffsetX - halfBlurRadius;
1300     y = frameY + frameHeight + shaddowOffsetY - halfBlurRadius;
1301     Cairo::RefPtr<RadialGradient> bottomRightCornerFade = RadialGradient::create(
1302         x, y, 0, x, y, blurRadius);
1303     bottomRightCornerFade->add_color_stop_rgba (0, 0, 0, 0, shaddowAlpha);
1304     bottomRightCornerFade->add_color_stop_rgba (1, 0, 0, 0, 0);
1305     context->set_source(bottomRightCornerFade);
1306     context->rectangle (frameX + frameWidth + shaddowOffsetX - halfBlurRadius,
1307         frameY + frameHeight + shaddowOffsetY - halfBlurRadius,
1308         blurRadius, blurRadius);
1309     context->fill();
1311     // Draw the frame
1312     context->set_line_width(1);
1313     context->rectangle (frameX, frameY,    frameWidth, frameHeight);
1315     context->set_source_rgb(1.0, 1.0, 1.0);
1316     context->fill_preserve();
1317     context->set_source_rgb(0.25, 0.25, 0.25);
1318     context->stroke_preserve();
1320     // Draw the image
1321     if(_preview_bitmap_image)    // Is the image a pixbuf?
1322     {
1323         // Set the transformation
1324         const Matrix matrix = {
1325             scaleFactor, 0,
1326             0, scaleFactor,
1327             svgX, svgY };
1328         context->set_matrix (matrix);
1330         // Render the image
1331         set_source_pixbuf (context, _preview_bitmap_image, 0, 0);
1332         context->paint();
1334         // Reset the transformation
1335         context->set_identity_matrix();
1336     }
1338     // Draw the inner frame
1339     context->set_source_rgb(0.75, 0.75, 0.75);
1340     context->rectangle (svgX, svgY,    scaledSvgWidth, scaledSvgHeight);
1341     context->stroke();
1343     _mutex->unlock();
1345     // Finish drawing
1346     surface->finish();
1348     if (_preview_emf_image) {
1349         HENHMETAFILE hemf = MyGetEnhMetaFileW(_path_string);
1350         if (hemf) {
1351             RECT rc;
1352             rc.top = svgY+2;
1353             rc.left = svgX+2;
1354             rc.bottom = scaledSvgHeight-2;
1355             rc.right = scaledSvgWidth-2;
1356             PlayEnhMetaFile(hMemDC, hemf, &rc);
1357             DeleteEnhMetaFile(hemf);
1358         }
1359     }
1361     SelectObject(hMemDC, hOldBitmap) ;
1362     DeleteDC(hMemDC);
1364     // Refresh the preview pane
1365     InvalidateRect(_preview_wnd, NULL, FALSE);
1368 int FileOpenDialogImplWin32::format_caption(wchar_t *caption, int caption_size)
1370     wchar_t szFileName[_MAX_FNAME];
1371     _wsplitpath(_path_string, NULL, NULL, szFileName, NULL);
1373     return snwprintf(caption, caption_size,
1374         L"%s\n%d kB\n%d \xD7 %d", szFileName, _preview_file_size,
1375         (int)_preview_document_width, (int)_preview_document_height);
1378 /**
1379  * Show this dialog modally.  Return true if user hits [OK]
1380  */
1381 bool
1382 FileOpenDialogImplWin32::show()
1384     // We can only run one worker thread at a time
1385     if(_mutex != NULL) return false;
1387     if(!Glib::thread_supported())
1388         Glib::thread_init();
1390     _result = false;
1391     _finished = false;
1392     _file_selected = false;
1393     _mutex = new Glib::Mutex();
1394     _main_loop = g_main_loop_new(g_main_context_default(), FALSE);
1396     if(Glib::Thread::create(sigc::mem_fun(*this, &FileOpenDialogImplWin32::GetOpenFileName_thread), true))
1397     {
1398         while(1)
1399         {
1400             g_main_context_iteration(g_main_context_default(), FALSE);
1402             if(_mutex->trylock())
1403             {
1404                 // Read mutexed data
1405                 const bool finished = _finished;
1406                 const bool is_file_selected = _file_selected;
1407                 _file_selected = false;
1408                 _mutex->unlock();
1410                 if(finished) break;
1411                 if(is_file_selected) file_selected();
1412             }
1414             Sleep(10);
1415         }
1416     }
1418     // Tidy up
1419     delete _mutex;
1420     _mutex = NULL;
1422     return _result;
1425 /**
1426  * To Get Multiple filenames selected at-once.
1427  */
1428 std::vector<Glib::ustring>FileOpenDialogImplWin32::getFilenames()
1430     std::vector<Glib::ustring> result;
1431     result.push_back(getFilename());
1432     return result;
1436 /*#########################################################################
1437 ### F I L E    S A V E
1438 #########################################################################*/
1440 /**
1441  * Constructor
1442  */
1443 FileSaveDialogImplWin32::FileSaveDialogImplWin32(Gtk::Window &parent,
1444             const Glib::ustring &dir,
1445             FileDialogType fileTypes,
1446             const char *title,
1447             const Glib::ustring &/*default_key*/,
1448             const char *docTitle) :
1449     FileDialogBaseWin32(parent, dir, title, fileTypes, "dialogs.save_as"),
1450         _title_label(NULL),
1451         _title_edit(NULL)
1453     FileSaveDialog::myDocTitle = docTitle;
1454     createFilterMenu();
1457 FileSaveDialogImplWin32::~FileSaveDialogImplWin32()
1461 void FileSaveDialogImplWin32::createFilterMenu()
1463     list<Filter> filter_list;
1465     knownExtensions.clear();
1467     // Compose the filter string
1468     Glib::ustring all_inkscape_files_filter, all_image_files_filter;
1469     Inkscape::Extension::DB::OutputList extension_list;
1470     Inkscape::Extension::db.get_output_list(extension_list);
1472     int filter_count = 0;
1473     int filter_length = 1;
1475     for (Inkscape::Extension::DB::OutputList::iterator current_item = extension_list.begin();
1476          current_item != extension_list.end(); current_item++)
1477     {
1478         Inkscape::Extension::Output *omod = *current_item;
1479         if (omod->deactivated()) continue;
1481         filter_count++;
1483         Filter filter;
1485         // Extension
1486         const gchar *filter_extension = omod->get_extension();
1487         filter.filter = g_utf8_to_utf16(
1488             filter_extension, -1, NULL, &filter.filter_length, NULL);
1489         knownExtensions.insert( Glib::ustring(filter_extension).casefold() );
1491         // Type
1492         filter.name = g_utf8_to_utf16(
1493             _(omod->get_filetypename()), -1, NULL, &filter.name_length, NULL);
1495         filter.mod = omod;
1497         filter_length += filter.name_length +
1498             filter.filter_length + 3;   // Add 3 for two \0s and a *
1500         filter_list.push_back(filter);
1501     }
1503     int extension_index = 0;
1504     _extension_map = new Inkscape::Extension::Extension*[filter_count];
1506     _filter = new wchar_t[filter_length];
1507     wchar_t *filterptr = _filter;
1509     for(list<Filter>::iterator filter_iterator = filter_list.begin();
1510         filter_iterator != filter_list.end(); filter_iterator++)
1511     {
1512         const Filter &filter = *filter_iterator;
1514         wcsncpy(filterptr, (wchar_t*)filter.name, filter.name_length);
1515         filterptr += filter.name_length;
1516         g_free(filter.name);
1518         *(filterptr++) = L'\0';
1519         *(filterptr++) = L'*';
1521         wcsncpy(filterptr, (wchar_t*)filter.filter, filter.filter_length);
1522         filterptr += filter.filter_length;
1523         g_free(filter.filter);
1525         *(filterptr++) = L'\0';
1527         // Associate this input extension with the file type name
1528         _extension_map[extension_index++] = filter.mod;
1529     }
1530     *(filterptr++) = 0;
1532         _filter_count = extension_index;
1533     _filter_index = 1;  // A value of 1 selects the 1st filter - NOT the 2nd
1536 void FileSaveDialogImplWin32::GetSaveFileName_thread()
1538     OPENFILENAMEEXW ofn;
1540     g_assert(this != NULL);
1541     g_assert(_main_loop != NULL);
1543     WCHAR* current_directory_string = (WCHAR*)g_utf8_to_utf16(
1544         _current_directory.data(), _current_directory.length(),
1545                 NULL, NULL, NULL);
1547     // Copy the selected file name, converting from UTF-8 to UTF-16
1548     memset(_path_string, 0, sizeof(_path_string));
1549     gunichar2* utf16_path_string = g_utf8_to_utf16(
1550         myFilename.data(), -1, NULL, NULL, NULL);
1551     wcsncpy(_path_string, (wchar_t*)utf16_path_string, _MAX_PATH);
1552     g_free(utf16_path_string);
1554     ZeroMemory(&ofn, sizeof(ofn));
1555     ofn.lStructSize = sizeof(ofn);
1556     ofn.hwndOwner = _ownerHwnd;
1557     ofn.lpstrFile = _path_string;
1558     ofn.nMaxFile = _MAX_PATH;
1559     ofn.nFilterIndex = _filter_index;
1560     ofn.lpstrFileTitle = NULL;
1561     ofn.nMaxFileTitle = 0;
1562     ofn.lpstrInitialDir = current_directory_string;
1563     ofn.lpstrTitle = _title;
1564     ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ENABLEHOOK;
1565     ofn.lpstrFilter = _filter;
1566     ofn.nFilterIndex = _filter_index;
1567     ofn.lpfnHook = GetSaveFileName_hookproc;
1568     ofn.lCustData = (LPARAM)this;
1570     _result = GetSaveFileNameW(&ofn) != 0;
1572         g_assert(ofn.nFilterIndex >= 1 && ofn.nFilterIndex <= _filter_count);
1573     _filter_index = ofn.nFilterIndex;
1574     _extension = _extension_map[ofn.nFilterIndex - 1];
1576     // Copy the selected file name, converting from UTF-16 to UTF-8
1577     myFilename = utf16_to_ustring(_path_string, _MAX_PATH);
1579     // Tidy up
1580     g_free(current_directory_string);
1582     g_main_loop_quit(_main_loop);
1585 /**
1586  * Show this dialog modally.  Return true if user hits [OK]
1587  */
1588 bool
1589 FileSaveDialogImplWin32::show()
1591     if(!Glib::thread_supported())
1592         Glib::thread_init();
1594     _result = false;
1595     _main_loop = g_main_loop_new(g_main_context_default(), FALSE);
1597         if(_main_loop != NULL)
1598         {
1599             if(Glib::Thread::create(sigc::mem_fun(*this, &FileSaveDialogImplWin32::GetSaveFileName_thread), true))
1600                 g_main_loop_run(_main_loop);
1602             if(_result)
1603                 appendExtension(myFilename, (Inkscape::Extension::Output*)_extension);
1604         }
1606     return _result;
1609 void FileSaveDialogImplWin32::setSelectionType( Inkscape::Extension::Extension * /*key*/ )
1611     // If no pointer to extension is passed in, look up based on filename extension.
1615 UINT_PTR CALLBACK FileSaveDialogImplWin32::GetSaveFileName_hookproc(
1616     HWND hdlg, UINT uiMsg, WPARAM, LPARAM lParam)
1618     FileSaveDialogImplWin32 *pImpl = (FileSaveDialogImplWin32*)
1619         GetWindowLongPtr(hdlg, GWLP_USERDATA);
1621     switch(uiMsg)
1622     {
1623     case WM_INITDIALOG:
1624         {
1625             HWND hParentWnd = GetParent(hdlg);
1626             HINSTANCE hInstance = GetModuleHandle(NULL);
1628             // get size/pos of typical combo box
1629             RECT rEDT1, rCB1, rROOT, rST;
1630             GetWindowRect(GetDlgItem(hParentWnd, cmb1), &rCB1);
1631             GetWindowRect(GetDlgItem(hParentWnd, cmb13), &rEDT1);
1632             GetWindowRect(GetDlgItem(hParentWnd, stc2), &rST);
1633             GetWindowRect(hdlg, &rROOT);
1634             int ydelta = rCB1.top - rEDT1.top;
1636             // Make the window a bit longer
1637             RECT rcRect;
1638             GetWindowRect(hParentWnd, &rcRect);
1639             MoveWindow(hParentWnd, rcRect.left, rcRect.top, rcRect.right - rcRect.left,
1640                        rcRect.bottom - rcRect.top + ydelta, FALSE);
1642             // It is not necessary to delete stock objects by calling DeleteObject
1643             HGDIOBJ dlgFont = GetStockObject(DEFAULT_GUI_FONT);
1645             // Set the pointer to the object
1646             OPENFILENAMEW *ofn = (OPENFILENAMEW*)lParam;
1647             SetWindowLongPtr(hdlg, GWLP_USERDATA, ofn->lCustData);
1648             SetWindowLongPtr(hParentWnd, GWLP_USERDATA, ofn->lCustData);
1649             pImpl = (FileSaveDialogImplWin32*)ofn->lCustData;
1651             // Create the Title label and edit control
1652             pImpl->_title_label = CreateWindowEx(NULL, "STATIC", "Title:",
1653                                         WS_VISIBLE|WS_CHILD,
1654                                         CW_USEDEFAULT, CW_USEDEFAULT, rCB1.left-rST.left, rST.bottom-rST.top,
1655                                         hParentWnd, NULL, hInstance, NULL);
1656             if(pImpl->_title_label) {
1657               if(dlgFont) SendMessage(pImpl->_title_label, WM_SETFONT, (WPARAM)dlgFont, MAKELPARAM(FALSE, 0));
1658               SetWindowPos(pImpl->_title_label, NULL, rST.left-rROOT.left, rST.top+ydelta-rROOT.top,
1659                            rCB1.left-rST.left, rST.bottom-rST.top, SWP_SHOWWINDOW|SWP_NOZORDER);
1660             }
1662             pImpl->_title_edit = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "",
1663                                         WS_VISIBLE|WS_CHILD|WS_TABSTOP|ES_AUTOHSCROLL,
1664                                         CW_USEDEFAULT, CW_USEDEFAULT, rCB1.right-rCB1.left, rCB1.bottom-rCB1.top,
1665                                         hParentWnd, NULL, hInstance, NULL);
1666             if(pImpl->_title_edit) {
1667               if(dlgFont) SendMessage(pImpl->_title_edit, WM_SETFONT, (WPARAM)dlgFont, MAKELPARAM(FALSE, 0));
1668               SetWindowPos(pImpl->_title_edit, NULL, rCB1.left-rROOT.left, rCB1.top+ydelta-rROOT.top,
1669                            rCB1.right-rCB1.left, rCB1.bottom-rCB1.top, SWP_SHOWWINDOW|SWP_NOZORDER);
1670               // TODO: make sure this works for Unicode
1671               SetWindowText(pImpl->_title_edit, pImpl->myDocTitle.c_str());
1672             }
1673         }
1674         break;
1675     case WM_DESTROY:
1676       {
1677         if(pImpl->_title_edit) {
1678           int length = GetWindowTextLength(pImpl->_title_edit)+1;
1679           char* temp_title = new char[length];
1680           GetWindowText(pImpl->_title_edit, temp_title, length);
1681           pImpl->myDocTitle = temp_title;
1682           delete[] temp_title;
1683           DestroyWindow(pImpl->_title_label);
1684           pImpl->_title_label = NULL;
1685           DestroyWindow(pImpl->_title_edit);
1686           pImpl->_title_edit = NULL;
1687         }
1688       }
1689       break;
1690     }
1692     // Use default dialog behaviour
1693     return 0;
1696 } } } // namespace Dialog, UI, Inkscape
1698 #endif // ifdef WIN32
1700 /*
1701   Local Variables:
1702   mode:c++
1703   c-file-style:"stroustrup"
1704   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1705   indent-tabs-mode:nil
1706   fill-column:99
1707   End:
1708 */
1709 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :