Start to make it easier to compile the core in isolation
[geany-mirror.git] / src / win32.c
blob961d53c8610a393bd2747f0655c83cc7b8ee5fdc
1 /*
2 * win32.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2012 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2012 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 * Special functions for the win32 platform, to provide native dialogs.
26 #include "geany.h"
28 #ifdef G_OS_WIN32
30 #define VC_EXTRALEAN
31 #define WIN32_LEAN_AND_MEAN
32 #include <windows.h>
33 #include <commdlg.h>
34 #include <shellapi.h>
35 #include <shlobj.h>
36 #include <io.h>
37 #include <fcntl.h>
39 #include <string.h>
40 #include <ctype.h>
41 #include <math.h>
42 #include <stdlib.h>
44 #include <glib/gstdio.h>
45 #include <gdk/gdkwin32.h>
47 #include "win32.h"
49 #include "document.h"
50 #include "support.h"
51 #include "utils.h"
52 #include "ui_utils.h"
53 #include "sciwrappers.h"
54 #include "dialogs.h"
55 #include "filetypes.h"
56 #include "project.h"
57 #include "editor.h"
59 #define BUFSIZE 4096
60 #define CMDSIZE 32768
62 struct _geany_win32_spawn
64 HANDLE hChildStdinRd;
65 HANDLE hChildStdinWr;
66 HANDLE hChildStdoutRd;
67 HANDLE hChildStdoutWr;
68 HANDLE hChildStderrRd;
69 HANDLE hChildStderrWr;
70 HANDLE hInputFile;
71 HANDLE hStdout;
72 HANDLE hStderr;
73 HANDLE processId;
74 DWORD dwExitCode;
76 typedef struct _geany_win32_spawn geany_win32_spawn;
78 static gboolean GetContentFromHandle(HANDLE hFile, gchar **content, GError **error);
79 static HANDLE GetTempFileHandle(GError **error);
80 static gboolean CreateChildProcess(geany_win32_spawn *gw_spawn, TCHAR *szCmdline,
81 const TCHAR *dir, GError **error);
82 static VOID ReadFromPipe(HANDLE hRead, HANDLE hWrite, HANDLE hFile, GError **error);
85 static wchar_t *get_file_filters(void)
87 gchar *string;
88 guint i, j, len;
89 static wchar_t title[4096];
90 GString *str = g_string_sized_new(100);
91 GString *all_patterns = g_string_sized_new(100);
92 GSList *node;
93 gchar *tmp;
95 /* create meta file filter "All files" */
96 g_string_append_printf(str, "%s\t*\t", _("All files"));
97 /* create meta file filter "All Source" (skip GEANY_FILETYPES_NONE) */
98 for (i = GEANY_FILETYPES_NONE + 1; i < filetypes_array->len; i++)
100 for (j = 0; filetypes[i]->pattern[j] != NULL; j++)
102 g_string_append(all_patterns, filetypes[i]->pattern[j]);
103 g_string_append_c(all_patterns, ';');
106 g_string_append_printf(str, "%s\t%s\t", _("All Source"), all_patterns->str);
107 g_string_free(all_patterns, TRUE);
108 /* add 'usual' filetypes */
109 foreach_slist(node, filetypes_by_title)
111 GeanyFiletype *ft = node->data;
113 if (G_UNLIKELY(ft->id == GEANY_FILETYPES_NONE))
114 continue;
115 tmp = g_strjoinv(";", ft->pattern);
116 g_string_append_printf(str, "%s\t%s\t", ft->title, tmp);
117 g_free(tmp);
119 g_string_append_c(str, '\t'); /* the final \0 byte to mark the end of the string */
120 string = str->str;
121 g_string_free(str, FALSE);
123 /* replace all "\t"s by \0 */
124 len = strlen(string);
125 g_strdelimit(string, "\t", '\0');
126 g_assert(string[len - 1] == 0x0);
127 MultiByteToWideChar(CP_UTF8, 0, string, len, title, G_N_ELEMENTS(title));
128 g_free(string);
130 return title;
134 static wchar_t *get_file_filter_all_files(void)
136 guint len;
137 static wchar_t title[4096];
138 gchar *filter;
140 /* create meta file filter "All files" */
141 filter = g_strdup_printf("%s\t*\t", _("All files"));
143 len = strlen(filter);
144 g_strdelimit(filter, "\t", '\0');
145 g_assert(filter[len - 1] == 0x0);
146 MultiByteToWideChar(CP_UTF8, 0, filter, len, title, G_N_ELEMENTS(title));
147 g_free(filter);
149 return title;
153 static wchar_t *get_filters(gboolean project_files)
155 gchar *string;
156 gint len;
157 static wchar_t title[1024];
159 if (project_files)
161 string = g_strconcat(_("Geany project files"), "\t", "*." GEANY_PROJECT_EXT, "\t",
162 _("All files"), "\t", "*", "\t", NULL);
164 else
166 string = g_strconcat(_("Executables"), "\t", "*.exe;*.bat;*.cmd", "\t",
167 _("All files"), "\t", "*", "\t", NULL);
170 /* replace all "\t"s by \0 */
171 len = strlen(string);
172 g_strdelimit(string, "\t", '\0');
173 g_assert(string[len - 1] == 0x0);
174 MultiByteToWideChar(CP_UTF8, 0, string, len, title, G_N_ELEMENTS(title));
175 g_free(string);
177 return title;
181 /* Converts the given UTF-8 filename or directory name into something usable for Windows and
182 * returns the directory part of the given filename. */
183 static wchar_t *get_dir_for_path(const gchar *utf8_filename)
185 static wchar_t w_dir[MAX_PATH];
186 gchar *result;
188 if (g_file_test(utf8_filename, G_FILE_TEST_IS_DIR))
189 result = (gchar*) utf8_filename;
190 else
191 result = g_path_get_dirname(utf8_filename);
193 MultiByteToWideChar(CP_UTF8, 0, result, -1, w_dir, G_N_ELEMENTS(w_dir));
195 if (result != utf8_filename)
196 g_free(result);
198 return w_dir;
202 /* Callback function for setting the initial directory of the folder open dialog. This could also
203 * be done with BROWSEINFO.pidlRoot and SHParseDisplayName but SHParseDisplayName is not available
204 * on systems below Windows XP. So, we go the hard way by creating a callback which will set up the
205 * folder when the dialog is initialised. Yeah, I like Windows. */
206 INT CALLBACK BrowseCallbackProc(HWND hwnd, UINT uMsg, LPARAM lp, LPARAM pData)
208 switch (uMsg)
210 case BFFM_INITIALIZED:
212 SendMessageW(hwnd, BFFM_SETSELECTIONW, TRUE, pData);
213 break;
215 case BFFM_SELCHANGED:
217 /* set the status window to the currently selected path. */
218 static wchar_t szDir[MAX_PATH];
219 if (SHGetPathFromIDListW((LPITEMIDLIST) lp, szDir))
221 SendMessageW(hwnd, BFFM_SETSTATUSTEXTW, 0, (LPARAM) szDir);
223 break;
226 return 0;
230 /* Shows a folder selection dialog.
231 * initial_dir is expected in UTF-8
232 * The selected folder name is returned. */
233 gchar *win32_show_folder_dialog(GtkWidget *parent, const gchar *title, const gchar *initial_dir)
235 BROWSEINFOW bi;
236 LPCITEMIDLIST pidl;
237 gchar *result = NULL;
238 wchar_t fname[MAX_PATH];
239 wchar_t w_title[512];
241 MultiByteToWideChar(CP_UTF8, 0, title, -1, w_title, G_N_ELEMENTS(w_title));
243 if (parent == NULL)
244 parent = main_widgets.window;
246 memset(&bi, 0, sizeof bi);
247 bi.hwndOwner = GDK_WINDOW_HWND(gtk_widget_get_window(parent));
248 bi.pidlRoot = NULL;
249 bi.lpszTitle = w_title;
250 bi.lpfn = BrowseCallbackProc;
251 bi.lParam = (LPARAM) get_dir_for_path(initial_dir);
252 bi.ulFlags = BIF_DONTGOBELOWDOMAIN | BIF_RETURNONLYFSDIRS | BIF_STATUSTEXT;
254 pidl = SHBrowseForFolderW(&bi);
256 /* convert the strange Windows folder list item something into an usual path string ;-) */
257 if (pidl != 0)
259 if (SHGetPathFromIDListW(pidl, fname))
261 result = g_malloc0(MAX_PATH * 2);
262 WideCharToMultiByte(CP_UTF8, 0, fname, -1, result, MAX_PATH * 2, NULL, NULL);
264 /* SHBrowseForFolder() probably leaks memory here, but how to free the allocated memory? */
266 return result;
270 /* Shows a file open dialog.
271 * If allow_new_file is set, the file to be opened doesn't have to exist.
272 * initial_dir is expected in UTF-8
273 * The selected file name is returned.
274 * If project_file_filter is set, the file open dialog will have a file filter for Geany project
275 * files, a filter for executables otherwise. */
276 gchar *win32_show_project_open_dialog(GtkWidget *parent, const gchar *title,
277 const gchar *initial_dir, gboolean allow_new_file,
278 gboolean project_file_filter)
280 OPENFILENAMEW of;
281 gint retval;
282 wchar_t fname[MAX_PATH];
283 wchar_t w_title[512];
284 gchar *filename;
286 fname[0] = '\0';
288 MultiByteToWideChar(CP_UTF8, 0, title, -1, w_title, G_N_ELEMENTS(w_title));
290 if (parent == NULL)
291 parent = main_widgets.window;
293 /* initialise file dialog info struct */
294 memset(&of, 0, sizeof of);
295 #ifdef OPENFILENAME_SIZE_VERSION_400
296 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
297 #else
298 of.lStructSize = sizeof of;
299 #endif
300 of.hwndOwner = GDK_WINDOW_HWND(gtk_widget_get_window(parent));
301 of.lpstrFilter = get_filters(project_file_filter);
303 of.lpstrCustomFilter = NULL;
304 of.nFilterIndex = 0;
305 of.lpstrFile = fname;
306 of.lpstrInitialDir = get_dir_for_path(initial_dir);
307 of.nMaxFile = 2048;
308 of.lpstrFileTitle = NULL;
309 of.lpstrTitle = w_title;
310 of.lpstrDefExt = L"";
311 of.Flags = OFN_PATHMUSTEXIST | OFN_EXPLORER | OFN_HIDEREADONLY;
312 if (! allow_new_file)
313 of.Flags |= OFN_FILEMUSTEXIST;
315 retval = GetOpenFileNameW(&of);
317 if (! retval)
319 if (CommDlgExtendedError())
321 gchar *error;
322 error = g_strdup_printf("File dialog box error (%x)", (int)CommDlgExtendedError());
323 win32_message_dialog(NULL, GTK_MESSAGE_ERROR, error);
324 g_free(error);
326 return NULL;
328 /* convert the resulting filename into UTF-8 (from whatever encoding it has at this moment) */
329 filename = g_malloc0(MAX_PATH * 2);
330 WideCharToMultiByte(CP_UTF8, 0, fname, -1, filename, MAX_PATH * 2, NULL, NULL);
332 return filename;
336 /* initial_dir can be NULL to use the current working directory.
337 * Returns: TRUE if the dialog was not cancelled. */
338 gboolean win32_show_document_open_dialog(GtkWindow *parent, const gchar *title, const gchar *initial_dir)
340 OPENFILENAMEW of;
341 gint retval;
342 guint x;
343 gchar tmp[MAX_PATH];
344 wchar_t fname[MAX_PATH];
345 wchar_t w_dir[MAX_PATH];
346 wchar_t w_title[512];
348 fname[0] = '\0';
350 if (initial_dir != NULL)
351 MultiByteToWideChar(CP_UTF8, 0, initial_dir, -1, w_dir, G_N_ELEMENTS(w_dir));
353 MultiByteToWideChar(CP_UTF8, 0, title, -1, w_title, G_N_ELEMENTS(w_title));
355 /* initialise file dialog info struct */
356 memset(&of, 0, sizeof of);
357 #ifdef OPENFILENAME_SIZE_VERSION_400
358 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
359 #else
360 of.lStructSize = sizeof of;
361 #endif
362 of.hwndOwner = GDK_WINDOW_HWND(gtk_widget_get_window(GTK_WIDGET(parent)));
363 of.lpstrFilter = get_file_filters();
365 of.lpstrCustomFilter = NULL;
366 of.nFilterIndex = GEANY_FILETYPES_NONE + 1;
367 of.lpstrFile = fname;
368 of.lpstrInitialDir = (initial_dir != NULL) ? w_dir : NULL;
369 of.nMaxFile = 2048;
370 of.lpstrFileTitle = NULL;
371 of.lpstrTitle = w_title;
372 of.lpstrDefExt = L"";
373 of.Flags = OFN_ALLOWMULTISELECT | OFN_FILEMUSTEXIST | OFN_EXPLORER;
375 retval = GetOpenFileNameW(&of);
377 if (!retval)
379 if (CommDlgExtendedError())
381 gchar error[100];
382 g_snprintf(error, sizeof error, "File dialog box error (%x)", (int)CommDlgExtendedError());
383 win32_message_dialog(NULL, GTK_MESSAGE_ERROR, error);
385 return FALSE;
388 x = of.nFileOffset - 1;
389 if (x != wcslen(fname))
390 { /* open a single file */
391 WideCharToMultiByte(CP_UTF8, 0, fname, -1, tmp, sizeof(tmp), NULL, NULL);
392 document_open_file(tmp, of.Flags & OFN_READONLY, NULL, NULL);
394 else
395 { /* open multiple files */
396 gchar file_name[MAX_PATH];
397 gchar dir_name[MAX_PATH];
399 WideCharToMultiByte(CP_UTF8, 0, fname, of.nFileOffset,
400 dir_name, sizeof(dir_name), NULL, NULL);
401 for (; ;)
403 if (! fname[x])
405 if (! fname[x + 1])
406 break;
408 WideCharToMultiByte(CP_UTF8, 0, fname + x + 1, -1,
409 tmp, sizeof(tmp), NULL, NULL);
410 g_snprintf(file_name, 511, "%s\\%s", dir_name, tmp);
412 /* convert the resulting filename into UTF-8 */
413 document_open_file(file_name, of.Flags & OFN_READONLY, NULL, NULL);
415 x++;
418 return (retval != 0);
422 gchar *win32_show_document_save_as_dialog(GtkWindow *parent, const gchar *title,
423 GeanyDocument *doc)
425 OPENFILENAMEW of;
426 gint retval;
427 gchar tmp[MAX_PATH];
428 wchar_t w_file[MAX_PATH];
429 wchar_t w_title[512];
430 int n;
432 w_file[0] = '\0';
434 /* Convert the name of the file for of.lpstrFile */
435 n = MultiByteToWideChar(CP_UTF8, 0, DOC_FILENAME(doc), -1, w_file, G_N_ELEMENTS(w_file));
437 /* If creating a new file name, convert and append the extension if any */
438 if (! doc->file_name && doc->file_type && doc->file_type->extension &&
439 n + 1 < (int)G_N_ELEMENTS(w_file))
441 w_file[n - 1] = L'.';
442 MultiByteToWideChar(CP_UTF8, 0, doc->file_type->extension, -1, &w_file[n],
443 G_N_ELEMENTS(w_file) - n - 1);
446 MultiByteToWideChar(CP_UTF8, 0, title, -1, w_title, G_N_ELEMENTS(w_title));
448 /* initialise file dialog info struct */
449 memset(&of, 0, sizeof of);
450 #ifdef OPENFILENAME_SIZE_VERSION_400
451 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
452 #else
453 of.lStructSize = sizeof of;
454 #endif
455 of.hwndOwner = GDK_WINDOW_HWND(gtk_widget_get_window(GTK_WIDGET(parent)));
457 of.lpstrFilter = get_file_filter_all_files();
458 of.lpstrCustomFilter = NULL;
459 of.nFilterIndex = 0;
461 of.lpstrFile = w_file;
462 of.nMaxFile = 2048;
463 of.lpstrFileTitle = NULL;
464 of.lpstrTitle = w_title;
465 of.lpstrDefExt = L"";
466 of.Flags = OFN_FILEMUSTEXIST | OFN_EXPLORER;
467 retval = GetSaveFileNameW(&of);
469 if (! retval)
471 if (CommDlgExtendedError())
473 gchar *error = g_strdup_printf(
474 "File dialog box error (%x)", (gint) CommDlgExtendedError());
475 win32_message_dialog(NULL, GTK_MESSAGE_ERROR, error);
476 g_free(error);
478 return NULL;
481 WideCharToMultiByte(CP_UTF8, 0, w_file, -1, tmp, sizeof(tmp), NULL, NULL);
483 return g_strdup(tmp);
487 /* initial_dir can be NULL to use the current working directory.
488 * Returns: the selected filename */
489 gchar *win32_show_file_dialog(GtkWindow *parent, const gchar *title, const gchar *initial_file)
491 OPENFILENAMEW of;
492 gint retval;
493 gchar tmp[MAX_PATH];
494 wchar_t w_file[MAX_PATH];
495 wchar_t w_title[512];
497 w_file[0] = '\0';
499 if (initial_file != NULL)
500 MultiByteToWideChar(CP_UTF8, 0, initial_file, -1, w_file, G_N_ELEMENTS(w_file));
502 MultiByteToWideChar(CP_UTF8, 0, title, -1, w_title, G_N_ELEMENTS(w_title));
504 /* initialise file dialog info struct */
505 memset(&of, 0, sizeof of);
506 #ifdef OPENFILENAME_SIZE_VERSION_400
507 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
508 #else
509 of.lStructSize = sizeof of;
510 #endif
511 of.hwndOwner = GDK_WINDOW_HWND(gtk_widget_get_window(GTK_WIDGET(parent)));
513 of.lpstrFile = w_file;
514 of.nMaxFile = 2048;
515 of.lpstrFileTitle = NULL;
516 of.lpstrTitle = w_title;
517 of.lpstrDefExt = L"";
518 of.Flags = OFN_FILEMUSTEXIST | OFN_EXPLORER;
519 retval = GetOpenFileNameW(&of);
521 if (! retval)
523 if (CommDlgExtendedError())
525 gchar *error = g_strdup_printf(
526 "File dialog box error (%x)", (gint) CommDlgExtendedError());
527 win32_message_dialog(NULL, GTK_MESSAGE_ERROR, error);
528 g_free(error);
530 return NULL;
533 WideCharToMultiByte(CP_UTF8, 0, w_file, -1, tmp, sizeof(tmp), NULL, NULL);
535 return g_strdup(tmp);
539 void win32_show_font_dialog(void)
541 gint retval;
542 CHOOSEFONT cf;
543 LOGFONT lf; /* logical font structure */
545 memset(&lf, 0, sizeof lf);
546 /* TODO: init lf members */
548 memset(&cf, 0, sizeof cf);
549 cf.lStructSize = sizeof cf;
550 cf.hwndOwner = GDK_WINDOW_HWND(gtk_widget_get_window(main_widgets.window));
551 cf.lpLogFont = &lf;
552 /* support CF_APPLY? */
553 cf.Flags = CF_NOSCRIPTSEL | CF_FORCEFONTEXIST | CF_INITTOLOGFONTSTRUCT | CF_SCREENFONTS;
555 retval = ChooseFont(&cf);
557 if (retval)
559 gchar *editorfont = g_strdup_printf("%s %d", lf.lfFaceName, (cf.iPointSize / 10));
560 ui_set_editor_font(editorfont);
561 g_free(editorfont);
566 void win32_show_color_dialog(const gchar *colour)
568 CHOOSECOLOR cc;
569 static COLORREF acr_cust_clr[16];
570 static DWORD rgb_current;
571 gchar *hex = g_malloc0(12);
572 GeanyDocument *doc = document_get_current();
574 /* Initialize CHOOSECOLOR */
575 memset(&cc, 0, sizeof cc);
576 cc.lStructSize = sizeof(cc);
577 cc.hwndOwner = GDK_WINDOW_HWND(gtk_widget_get_window(main_widgets.window));
578 cc.lpCustColors = (LPDWORD) acr_cust_clr;
579 cc.rgbResult = (colour != NULL) ? utils_parse_color_to_bgr(colour) : 0;
580 cc.Flags = CC_FULLOPEN | CC_RGBINIT;
582 if (ChooseColor(&cc))
584 rgb_current = cc.rgbResult;
585 g_snprintf(hex, 11, "#%02X%02X%02X",
586 (guint) (utils_scale_round(GetRValue(rgb_current), 255)),
587 (guint) (utils_scale_round(GetGValue(rgb_current), 255)),
588 (guint) (utils_scale_round(GetBValue(rgb_current), 255)));
590 editor_insert_color(doc->editor, hex);
592 g_free(hex);
596 void win32_show_pref_file_dialog(GtkEntry *item)
598 OPENFILENAMEW of;
599 gint retval, len;
600 wchar_t fname[MAX_PATH];
601 gchar tmp[MAX_PATH];
602 gchar **field, *filename;
604 fname[0] = '\0';
606 /* cut the options from the command line */
607 field = g_strsplit(gtk_entry_get_text(GTK_ENTRY(item)), " ", 2);
608 if (field[0])
610 filename = g_find_program_in_path(field[0]);
611 if (filename != NULL && g_file_test(filename, G_FILE_TEST_EXISTS))
613 MultiByteToWideChar(CP_UTF8, 0, filename, -1, fname, G_N_ELEMENTS(fname));
614 g_free(filename);
618 /* initialize file dialog info struct */
619 memset(&of, 0, sizeof of);
620 #ifdef OPENFILENAME_SIZE_VERSION_400
621 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
622 #else
623 of.lStructSize = sizeof of;
624 #endif
625 of.hwndOwner = GDK_WINDOW_HWND(gtk_widget_get_window(ui_widgets.prefs_dialog));
627 of.lpstrFilter = get_filters(FALSE);
628 of.lpstrCustomFilter = NULL;
629 of.nFilterIndex = 1;
631 of.lpstrFile = fname;
632 of.nMaxFile = 2048;
633 of.lpstrFileTitle = NULL;
634 /*of.lpstrInitialDir = g_get_home_dir();*/
635 of.lpstrInitialDir = NULL;
636 of.lpstrTitle = NULL;
637 of.lpstrDefExt = L"exe";
638 of.Flags = OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_EXPLORER;
639 retval = GetOpenFileNameW(&of);
641 if (!retval)
643 if (CommDlgExtendedError())
645 gchar error[100];
646 g_snprintf(error, sizeof error, "File dialog box error (%x)", (int)CommDlgExtendedError());
647 win32_message_dialog(NULL, GTK_MESSAGE_ERROR, error);
649 g_strfreev(field);
650 return;
653 len = WideCharToMultiByte(CP_UTF8, 0, fname, -1, tmp, sizeof(tmp), NULL, NULL);
654 if ((of.nFileOffset - 1) != len)
656 if (g_strv_length(field) > 1)
657 /* add the command line args of the old command */
658 /** TODO this fails badly when the old command contained spaces, we need quoting here */
659 filename = g_strconcat(tmp, " ", field[1], NULL);
660 else
662 filename = g_strdup(tmp);
664 gtk_entry_set_text(GTK_ENTRY(item), filename);
665 g_free(filename);
667 g_strfreev(field);
671 /* Creates a native Windows message box of the given type and returns always TRUE
672 * or FALSE representing th pressed Yes or No button.
673 * If type is not GTK_MESSAGE_QUESTION, it returns always TRUE. */
674 gboolean win32_message_dialog(GtkWidget *parent, GtkMessageType type, const gchar *msg)
676 gboolean ret = TRUE;
677 gint rc;
678 guint t;
679 const gchar *title;
680 HWND parent_hwnd = NULL;
681 static wchar_t w_msg[512];
682 static wchar_t w_title[512];
684 switch (type)
686 case GTK_MESSAGE_ERROR:
688 t = MB_OK | MB_ICONERROR;
689 title = _("Error");
690 break;
692 case GTK_MESSAGE_QUESTION:
694 t = MB_YESNO | MB_ICONQUESTION;
695 title = _("Question");
696 break;
698 case GTK_MESSAGE_WARNING:
700 t = MB_OK | MB_ICONWARNING;
701 title = _("Warning");
702 break;
704 default:
706 t = MB_OK | MB_ICONINFORMATION;
707 title = _("Information");
708 break;
712 /* convert the Unicode chars to wide chars */
713 /** TODO test if LANG == C then possibly skip conversion => g_win32_getlocale() */
714 MultiByteToWideChar(CP_UTF8, 0, msg, -1, w_msg, G_N_ELEMENTS(w_msg));
715 MultiByteToWideChar(CP_UTF8, 0, title, -1, w_title, G_N_ELEMENTS(w_title));
717 if (parent != NULL)
718 parent_hwnd = GDK_WINDOW_HWND(gtk_widget_get_window(parent));
719 else if (main_widgets.window != NULL)
720 parent_hwnd = GDK_WINDOW_HWND(gtk_widget_get_window(main_widgets.window));
722 /* display the message box */
723 rc = MessageBoxW(parent_hwnd, w_msg, w_title, t);
725 if (type == GTK_MESSAGE_QUESTION && rc != IDYES)
726 ret = FALSE;
728 return ret;
732 /* Little wrapper for _waccess(), returns errno or 0 if there was no error */
733 gint win32_check_write_permission(const gchar *dir)
735 static wchar_t w_dir[MAX_PATH];
736 MultiByteToWideChar(CP_UTF8, 0, dir, -1, w_dir, G_N_ELEMENTS(w_dir));
737 if (_waccess(w_dir, R_OK | W_OK) != 0)
738 return errno;
739 else
740 return 0;
744 /* Just a simple wrapper function to open a browser window */
745 void win32_open_browser(const gchar *uri)
747 if (strncmp(uri, "file://", 7) == 0)
749 uri += 7;
750 if (strchr(uri, ':') != NULL)
752 while (*uri == '/')
753 uri++;
756 ShellExecute(NULL, "open", uri, NULL, NULL, SW_SHOWNORMAL);
760 /* Returns TRUE if the command, which child_pid refers to, returned with a successful exit code,
761 * otherwise FALSE. */
762 gboolean win32_get_exit_status(GPid child_pid)
764 DWORD exit_code;
765 GetExitCodeProcess(child_pid, &exit_code);
767 return (exit_code == 0);
771 static FILE *open_std_handle(DWORD handle, const char *mode)
773 HANDLE lStdHandle;
774 int hConHandle;
775 FILE *fp;
777 lStdHandle = GetStdHandle(handle);
778 if (lStdHandle == INVALID_HANDLE_VALUE)
780 gchar *err = g_win32_error_message(GetLastError());
781 g_warning("GetStdHandle(%ld) failed: %s", (long)handle, err);
782 g_free(err);
783 return NULL;
785 hConHandle = _open_osfhandle((long)lStdHandle, _O_TEXT);
786 if (hConHandle == -1)
788 gchar *err = g_win32_error_message(GetLastError());
789 g_warning("_open_osfhandle(%ld, _O_TEXT) failed: %s", (long)lStdHandle, err);
790 g_free(err);
791 return NULL;
793 fp = _fdopen(hConHandle, mode);
794 if (! fp)
796 gchar *err = g_win32_error_message(GetLastError());
797 g_warning("_fdopen(%d, \"%s\") failed: %s", hConHandle, mode, err);
798 g_free(err);
799 return NULL;
801 if (setvbuf(fp, NULL, _IONBF, 0) != 0)
803 gchar *err = g_win32_error_message(GetLastError());
804 g_warning("setvbuf(%p, NULL, _IONBF, 0) failed: %s", fp, err);
805 g_free(err);
806 fclose(fp);
807 return NULL;
810 return fp;
814 static void debug_setup_console(void)
816 static const WORD MAX_CONSOLE_LINES = 500;
817 CONSOLE_SCREEN_BUFFER_INFO coninfo;
818 FILE *fp;
820 /* allocate a console for this app */
821 AllocConsole();
823 /* set the screen buffer to be big enough to let us scroll text */
824 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
825 coninfo.dwSize.Y = MAX_CONSOLE_LINES;
826 SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);
828 /* redirect unbuffered STDOUT to the console */
829 fp = open_std_handle(STD_OUTPUT_HANDLE, "w");
830 if (fp)
831 *stdout = *fp;
833 /* redirect unbuffered STDERR to the console */
834 fp = open_std_handle(STD_ERROR_HANDLE, "w");
835 if (fp)
836 *stderr = *fp;
838 /* redirect unbuffered STDIN to the console */
839 fp = open_std_handle(STD_INPUT_HANDLE, "r");
840 if (fp)
841 *stdin = *fp;
845 void win32_init_debug_code(void)
847 if (app->debug_mode)
849 /* create a console window to get log messages on Windows,
850 * especially useful when generating tags files */
851 debug_setup_console();
852 /* Enable GLib process spawn debug mode when Geany was started with the debug flag */
853 g_setenv("G_SPAWN_WIN32_DEBUG", "1", FALSE);
858 static gchar *create_temp_file(void)
860 gchar *name;
861 gint fd;
863 fd = g_file_open_tmp("tmp_XXXXXX", &name, NULL);
864 if (fd == -1)
865 name = NULL;
866 else
867 close(fd);
869 return name;
873 /* Sometimes this blocks for 30s before aborting when there are several
874 * pages of (error) output and sometimes hangs - see the FIXME.
875 * Also gw_spawn.dwExitCode seems to be not set properly. */
876 /* Process spawning implementation for Windows, by Pierre Joye.
877 * Don't call this function directly, use utils_spawn_[a]sync() instead. */
878 static
879 gboolean _broken_win32_spawn(const gchar *dir, gchar **argv, gchar **env, GSpawnFlags flags,
880 gchar **std_out, gchar **std_err, gint *exit_status, GError **error)
882 TCHAR buffer[CMDSIZE]=TEXT("");
883 TCHAR cmdline[CMDSIZE] = TEXT("");
884 TCHAR* lpPart[CMDSIZE]={NULL};
885 DWORD retval = 0;
886 gint argc = 0, i;
887 gint cmdpos = 0;
889 SECURITY_ATTRIBUTES saAttr;
890 BOOL fSuccess;
891 geany_win32_spawn gw_spawn;
893 /* Temp file */
894 HANDLE hStdoutTempFile = NULL;
895 HANDLE hStderrTempFile = NULL;
897 gchar *stdout_content = NULL;
898 gchar *stderr_content = NULL;
900 while (argv[argc])
902 ++argc;
904 g_return_val_if_fail (std_out == NULL ||
905 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
906 g_return_val_if_fail (std_err == NULL ||
907 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
909 if (flags & G_SPAWN_SEARCH_PATH)
911 retval = SearchPath(NULL, argv[0], ".exe", sizeof(buffer), buffer, lpPart);
912 if (retval > 0)
913 g_snprintf(cmdline, sizeof(cmdline), "\"%s\"", buffer);
914 else
915 g_strlcpy(cmdline, argv[0], sizeof(cmdline));
916 cmdpos = 1;
919 for (i = cmdpos; i < argc; i++)
921 g_snprintf(cmdline, sizeof(cmdline), "%s %s", cmdline, argv[i]);
922 /*MessageBox(NULL, cmdline, cmdline, MB_OK);*/
925 if (std_err != NULL)
927 hStderrTempFile = GetTempFileHandle(error);
928 if (hStderrTempFile == INVALID_HANDLE_VALUE)
930 gchar *msg = g_win32_error_message(GetLastError());
931 geany_debug("win32_spawn: Second CreateFile failed (%d)", (gint) GetLastError());
932 g_set_error(error, G_SPAWN_ERROR, G_FILE_ERROR, "%s", msg);
933 g_free(msg);
934 return FALSE;
938 if (std_out != NULL)
940 hStdoutTempFile = GetTempFileHandle(error);
941 if (hStdoutTempFile == INVALID_HANDLE_VALUE)
943 gchar *msg = g_win32_error_message(GetLastError());
944 geany_debug("win32_spawn: Second CreateFile failed (%d)", (gint) GetLastError());
945 g_set_error(error, G_SPAWN_ERROR, G_FILE_ERROR, "%s", msg);
946 g_free(msg);
947 return FALSE;
951 /* Set the bInheritHandle flag so pipe handles are inherited. */
952 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
953 saAttr.bInheritHandle = TRUE;
954 saAttr.lpSecurityDescriptor = NULL;
956 /* Get the handle to the current STDOUT and STDERR. */
957 gw_spawn.hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
958 gw_spawn.hStderr = GetStdHandle(STD_ERROR_HANDLE);
959 gw_spawn.dwExitCode = 0;
961 /* Create a pipe for the child process's STDOUT. */
962 if (! CreatePipe(&(gw_spawn.hChildStdoutRd), &(gw_spawn.hChildStdoutWr), &saAttr, 0))
964 gchar *msg = g_win32_error_message(GetLastError());
965 geany_debug("win32_spawn: Stdout pipe creation failed (%d)", (gint) GetLastError());
966 g_set_error(error, G_SPAWN_ERROR, G_FILE_ERROR_PIPE, "%s", msg);
967 g_free(msg);
968 return FALSE;
971 /* Ensure that the read handle to the child process's pipe for STDOUT is not inherited.*/
972 SetHandleInformation(gw_spawn.hChildStdoutRd, HANDLE_FLAG_INHERIT, 0);
974 /* Create a pipe for the child process's STDERR. */
975 if (! CreatePipe(&(gw_spawn.hChildStderrRd), &(gw_spawn.hChildStderrWr), &saAttr, 0))
977 gchar *msg = g_win32_error_message(GetLastError());
978 geany_debug("win32_spawn: Stderr pipe creation failed");
979 g_set_error(error, G_SPAWN_ERROR, G_FILE_ERROR_PIPE, "%s", msg);
980 g_free(msg);
981 return FALSE;
984 /* Ensure that the read handle to the child process's pipe for STDOUT is not inherited.*/
985 SetHandleInformation(gw_spawn.hChildStderrRd, HANDLE_FLAG_INHERIT, 0);
987 /* Create a pipe for the child process's STDIN. */
988 if (! CreatePipe(&(gw_spawn.hChildStdinRd), &(gw_spawn.hChildStdinWr), &saAttr, 0))
990 gchar *msg = g_win32_error_message(GetLastError());
991 geany_debug("win32_spawn: Stdin pipe creation failed");
992 g_set_error(error, G_SPAWN_ERROR, G_FILE_ERROR_PIPE, "%s", msg);
993 g_free(msg);
994 return FALSE;
997 /* Ensure that the write handle to the child process's pipe for STDIN is not inherited. */
998 SetHandleInformation(gw_spawn.hChildStdinWr, HANDLE_FLAG_INHERIT, 0);
1000 /* Now create the child process. */
1001 fSuccess = CreateChildProcess(&gw_spawn, cmdline, dir, error);
1002 if (exit_status)
1004 *exit_status = gw_spawn.dwExitCode;
1007 if (! fSuccess)
1009 geany_debug("win32_spawn: Create process failed");
1010 return FALSE;
1013 /* Read from pipe that is the standard output for child process. */
1014 if (std_out != NULL)
1016 ReadFromPipe(gw_spawn.hChildStdoutRd, gw_spawn.hChildStdoutWr, hStdoutTempFile, error);
1017 if (! GetContentFromHandle(hStdoutTempFile, &stdout_content, error))
1019 return FALSE;
1021 *std_out = stdout_content;
1024 if (std_err != NULL)
1026 ReadFromPipe(gw_spawn.hChildStderrRd, gw_spawn.hChildStderrWr, hStderrTempFile, error);
1027 if (! GetContentFromHandle(hStderrTempFile, &stderr_content, error))
1029 return FALSE;
1031 *std_err = stderr_content;
1033 return TRUE;
1037 /* Note: g_spawn is broken for receiving both stdio and stderr e.g. when
1038 * running make and there are compile errors. See glib/giowin32.c header
1039 * comment about Windows bugs, e.g. #338943 */
1040 /* Simple replacement for _broken_win32_spawn().
1041 * flags is ignored, G_SPAWN_SEARCH_PATH is implied.
1042 * Don't call this function directly, use utils_spawn_[a]sync() instead.
1043 * Adapted from tm_workspace_create_global_tags(). */
1044 gboolean win32_spawn(const gchar *dir, gchar **argv, gchar **env, GSpawnFlags flags,
1045 gchar **std_out, gchar **std_err, gint *exit_status, GError **error)
1047 gint ret;
1048 gboolean fail;
1049 gchar *tmp_file = create_temp_file();
1050 gchar *tmp_errfile = create_temp_file();
1051 gchar *command;
1052 gchar *locale_command;
1054 if (env != NULL)
1056 return _broken_win32_spawn(dir, argv, env, flags, std_out, std_err,
1057 exit_status, error);
1059 if (!tmp_file || !tmp_errfile)
1061 g_warning("%s: Could not create temporary files!", G_STRFUNC);
1062 return FALSE;
1064 command = g_strjoinv(" ", argv);
1065 SETPTR(command, g_strdup_printf("cmd.exe /S /C \"%s >%s 2>%s\"",
1066 command, tmp_file, tmp_errfile));
1067 locale_command = g_locale_from_utf8(command, -1, NULL, NULL, NULL);
1068 if (! locale_command)
1069 locale_command = g_strdup(command);
1070 geany_debug("WIN32: actually running command:\n%s", command);
1071 g_chdir(dir);
1072 errno = 0;
1073 ret = system(locale_command);
1074 /* the command can return -1 as an exit code, so check errno also */
1075 fail = ret == -1 && errno;
1076 if (!fail)
1078 if (std_out != NULL)
1079 g_file_get_contents(tmp_file, std_out, NULL, NULL);
1080 if (std_err != NULL)
1081 g_file_get_contents(tmp_errfile, std_err, NULL, NULL);
1083 else if (error)
1084 g_set_error_literal(error, G_SPAWN_ERROR, errno, g_strerror(errno));
1086 g_free(command);
1087 g_free(locale_command);
1088 g_unlink(tmp_file);
1089 g_free(tmp_file);
1090 g_unlink(tmp_errfile);
1091 g_free(tmp_errfile);
1092 if (exit_status)
1093 *exit_status = ret;
1095 return !fail;
1099 static gboolean GetContentFromHandle(HANDLE hFile, gchar **content, GError **error)
1101 DWORD filesize;
1102 gchar * buffer;
1103 DWORD dwRead;
1105 filesize = GetFileSize(hFile, NULL);
1106 if (filesize < 1)
1108 *content = NULL;
1109 return TRUE;
1112 buffer = g_malloc(filesize + 1);
1113 if (! buffer)
1115 gchar *msg = g_win32_error_message(GetLastError());
1116 geany_debug("GetContentFromHandle: Alloc failed");
1117 g_set_error(error, G_SPAWN_ERROR, G_SPAWN_ERROR, "%s", msg);
1118 g_free(msg);
1119 return FALSE;
1122 SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
1123 if (! ReadFile(hFile, buffer, filesize, &dwRead, NULL) || dwRead == 0)
1125 gchar *msg = g_win32_error_message(GetLastError());
1126 geany_debug("GetContentFromHandle: Cannot read tempfile");
1127 g_set_error(error, G_SPAWN_ERROR, G_FILE_ERROR_FAILED, "%s", msg);
1128 g_free(msg);
1129 return FALSE;
1132 if (! CloseHandle(hFile))
1134 gchar *msg = g_win32_error_message(GetLastError());
1135 geany_debug("GetContentFromHandle: CloseHandle failed (%d)", (gint) GetLastError());
1136 g_set_error(error, G_SPAWN_ERROR, G_FILE_ERROR_FAILED, "%s", msg);
1137 g_free(msg);
1138 g_free(buffer);
1139 *content = NULL;
1140 return FALSE;
1142 buffer[filesize] = '\0';
1143 *content = buffer;
1144 return TRUE;
1148 gchar *win32_expand_environment_variables(const gchar *str)
1150 gchar expCmdline[32768]; /* 32768 is the limit for ExpandEnvironmentStrings() */
1152 if (ExpandEnvironmentStrings((LPCTSTR) str, (LPTSTR) expCmdline, sizeof(expCmdline)) != 0)
1153 return g_strdup(expCmdline);
1154 else
1155 return g_strdup(str);
1159 static gboolean CreateChildProcess(geany_win32_spawn *gw_spawn, TCHAR *szCmdline,
1160 const TCHAR *dir, GError **error)
1162 PROCESS_INFORMATION piProcInfo;
1163 STARTUPINFOW siStartInfo;
1164 BOOL bFuncRetn = FALSE;
1165 gchar *expandedCmdline;
1166 wchar_t w_commandline[CMDSIZE];
1167 wchar_t w_dir[MAX_PATH];
1169 /* Set up members of the PROCESS_INFORMATION structure. */
1170 ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
1172 /* Set up members of the STARTUPINFO structure.*/
1173 ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
1175 siStartInfo.cb = sizeof(STARTUPINFO);
1176 siStartInfo.hStdError = gw_spawn->hChildStderrWr;
1177 siStartInfo.hStdOutput = gw_spawn->hChildStdoutWr;
1178 siStartInfo.hStdInput = gw_spawn->hChildStdinRd;
1179 siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
1181 /* Expand environment variables like %blah%. */
1182 expandedCmdline = win32_expand_environment_variables(szCmdline);
1184 MultiByteToWideChar(CP_UTF8, 0, expandedCmdline, -1, w_commandline, G_N_ELEMENTS(w_commandline));
1185 MultiByteToWideChar(CP_UTF8, 0, dir, -1, w_dir, G_N_ELEMENTS(w_dir));
1187 /* Create the child process. */
1188 bFuncRetn = CreateProcessW(NULL,
1189 w_commandline, /* command line */
1190 NULL, /* process security attributes */
1191 NULL, /* primary thread security attributes */
1192 TRUE, /* handles are inherited */
1193 CREATE_NO_WINDOW, /* creation flags */
1194 NULL, /* use parent's environment */
1195 w_dir, /* use parent's current directory */
1196 &siStartInfo, /* STARTUPINFO pointer */
1197 &piProcInfo); /* receives PROCESS_INFORMATION */
1199 g_free(expandedCmdline);
1201 if (bFuncRetn == 0)
1203 gchar *msg = g_win32_error_message(GetLastError());
1204 geany_debug("CreateChildProcess: CreateProcess failed (%s)", msg);
1205 g_set_error(error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED, "%s", msg);
1206 g_free(msg);
1207 return FALSE;
1209 else
1211 gint i;
1212 gsize ms = 30*1000;
1214 /* FIXME: this seems to timeout when there are many lines
1215 * to read - maybe because the child's pipe is full */
1216 for (i = 0; i < 2 &&
1217 WaitForSingleObject(piProcInfo.hProcess, ms) == WAIT_TIMEOUT; i++)
1219 ui_set_statusbar(FALSE, _("Process timed out after %.02f s!"), ms / 1000.0F);
1220 geany_debug("CreateChildProcess: timed out");
1221 TerminateProcess(piProcInfo.hProcess, WAIT_TIMEOUT); /* NOTE: This will not kill grandkids. */
1224 if (!GetExitCodeProcess(piProcInfo.hProcess, &gw_spawn->dwExitCode))
1226 gchar *msg = g_win32_error_message(GetLastError());
1227 geany_debug("GetExitCodeProcess failed: %s", msg);
1228 g_set_error(error, G_SPAWN_ERROR, G_FILE_ERROR_FAILED, "%s", msg);
1229 g_free(msg);
1231 CloseHandle(piProcInfo.hProcess);
1232 CloseHandle(piProcInfo.hThread);
1233 return bFuncRetn;
1235 return FALSE;
1239 static VOID ReadFromPipe(HANDLE hRead, HANDLE hWrite, HANDLE hFile, GError **error)
1241 DWORD dwRead, dwWritten;
1242 CHAR chBuf[BUFSIZE];
1244 /* Close the write end of the pipe before reading from the
1245 read end of the pipe. */
1246 if (! CloseHandle(hWrite))
1248 gchar *msg = g_win32_error_message(GetLastError());
1249 geany_debug("ReadFromPipe: Closing handle failed");
1250 g_set_error(error, G_SPAWN_ERROR, G_FILE_ERROR_PIPE, "%s", msg);
1251 g_free(msg);
1252 return;
1255 /* Read output from the child process, and write to parent's STDOUT. */
1256 for (;;)
1258 if (! ReadFile(hRead, chBuf, BUFSIZE, &dwRead, NULL) || dwRead == 0)
1259 break;
1261 if (! WriteFile(hFile, chBuf, dwRead, &dwWritten, NULL))
1262 break;
1267 static HANDLE GetTempFileHandle(GError **error)
1269 /* Temp file */
1270 DWORD dwBufSize = BUFSIZE;
1271 UINT uRetVal;
1272 TCHAR szTempName[BUFSIZE];
1273 TCHAR lpPathBuffer[BUFSIZE];
1274 DWORD dwRetVal;
1275 HANDLE hTempFile;
1277 /* Get the temp path. */
1278 dwRetVal = GetTempPath(dwBufSize, /* length of the buffer*/
1279 lpPathBuffer); /* buffer for path */
1281 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1283 gchar *msg = g_win32_error_message(GetLastError());
1284 geany_debug("GetTempFileHandle: GetTempPath failed (%d)", (gint) GetLastError());
1285 g_set_error(error, G_SPAWN_ERROR, G_FILE_ERROR, "%s", msg);
1286 g_free(msg);
1287 return NULL;
1290 /* Create a temporary file for STDOUT. */
1291 uRetVal = GetTempFileName(lpPathBuffer, /* directory for tmp files */
1292 TEXT("GEANY_VCDIFF_"), /* temp file name prefix */
1293 0, /* create unique name */
1294 szTempName); /* buffer for name */
1295 if (uRetVal == 0)
1297 gchar *msg = g_win32_error_message(GetLastError());
1298 geany_debug("GetTempFileName failed (%d)", (gint) GetLastError());
1299 g_set_error(error, G_SPAWN_ERROR, G_FILE_ERROR, "%s", msg);
1300 g_free(msg);
1301 return NULL;
1304 hTempFile = CreateFile((LPTSTR) szTempName, /* file name */
1305 GENERIC_READ | GENERIC_WRITE, /* open r-w */
1306 0, /* do not share */
1307 NULL, /* default security */
1308 CREATE_ALWAYS, /* overwrite existing */
1309 FILE_ATTRIBUTE_NORMAL,/* normal file */
1310 NULL); /* no template */
1312 if (hTempFile == INVALID_HANDLE_VALUE)
1314 gchar *msg = g_win32_error_message(GetLastError());
1315 geany_debug("GetTempFileHandle: Second CreateFile failed (%d)", (gint) GetLastError());
1316 g_set_error(error, G_SPAWN_ERROR, G_FILE_ERROR, "%s", msg);
1317 g_free(msg);
1318 return NULL;
1320 return hTempFile;
1324 /* From GDK (they got it from MS Knowledge Base article Q130698) */
1325 static gboolean resolve_link(HWND hWnd, wchar_t *link, gchar **lpszPath)
1327 WIN32_FILE_ATTRIBUTE_DATA wfad;
1328 HRESULT hres;
1329 IShellLinkW *pslW = NULL;
1330 IPersistFile *ppf = NULL;
1331 LPVOID pslWV = NULL;
1332 LPVOID ppfV = NULL;
1334 /* Check if the file is empty first because IShellLink::Resolve for some reason succeeds
1335 * with an empty file and returns an empty "link target". (#524151) */
1336 if (!GetFileAttributesExW(link, GetFileExInfoStandard, &wfad) ||
1337 (wfad.nFileSizeHigh == 0 && wfad.nFileSizeLow == 0))
1339 return FALSE;
1342 /* Assume failure to start with: */
1343 *lpszPath = 0;
1345 CoInitialize(NULL);
1347 hres = CoCreateInstance(
1348 &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, &IID_IShellLinkW, &pslWV);
1350 if (SUCCEEDED(hres))
1352 /* The IShellLink interface supports the IPersistFile interface.
1353 * Get an interface pointer to it. */
1354 pslW = (IShellLinkW*) pslWV;
1355 hres = pslW->lpVtbl->QueryInterface(pslW, &IID_IPersistFile, &ppfV);
1358 if (SUCCEEDED(hres))
1360 /* Load the file. */
1361 ppf = (IPersistFile*) ppfV;
1362 hres = ppf->lpVtbl->Load(ppf, link, STGM_READ);
1365 if (SUCCEEDED(hres))
1367 /* Resolve the link by calling the Resolve() interface function. */
1368 hres = pslW->lpVtbl->Resolve(pslW, hWnd, SLR_ANY_MATCH | SLR_NO_UI);
1371 if (SUCCEEDED(hres))
1373 wchar_t wtarget[MAX_PATH];
1375 hres = pslW->lpVtbl->GetPath(pslW, wtarget, MAX_PATH, NULL, 0);
1376 if (SUCCEEDED(hres))
1377 *lpszPath = g_utf16_to_utf8(wtarget, -1, NULL, NULL, NULL);
1380 if (ppf)
1381 ppf->lpVtbl->Release(ppf);
1383 if (pslW)
1384 pslW->lpVtbl->Release(pslW);
1386 return SUCCEEDED(hres);
1390 /* Checks whether file_name is a Windows shortcut. file_name is expected in UTF-8 encoding.
1391 * If file_name is a Windows shortcut, it returns the target in UTF-8 encoding.
1392 * If it is not a shortcut, it returns a newly allocated copy of file_name. */
1393 gchar *win32_get_shortcut_target(const gchar *file_name)
1395 gchar *path = NULL;
1396 wchar_t *wfilename = g_utf8_to_utf16(file_name, -1, NULL, NULL, NULL);
1398 resolve_link(GDK_WINDOW_HWND(gtk_widget_get_window(main_widgets.window)), wfilename, &path);
1399 g_free(wfilename);
1401 if (path == NULL)
1402 return g_strdup(file_name);
1403 else
1404 return path;
1408 void win32_set_working_directory(const gchar *dir)
1410 SetCurrentDirectory(dir);
1414 gchar *win32_get_installation_dir(void)
1416 return g_win32_get_package_installation_directory_of_module(NULL);
1420 #endif