Recognize #!/bin/dash as shebang for Shell files (closes #3470986)
[geany-mirror.git] / src / win32.c
blob3412f67afeeaf681d2f9e9ea6a5236e0a5b9bce3
1 /*
2 * win32.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2011 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2011 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
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 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 <shlobj.h>
35 #include <io.h>
36 #include <fcntl.h>
38 #include <string.h>
39 #include <ctype.h>
40 #include <math.h>
41 #include <stdlib.h>
43 #include <gdk/gdkwin32.h>
45 #include "win32.h"
47 #include "document.h"
48 #include "support.h"
49 #include "utils.h"
50 #include "ui_utils.h"
51 #include "sciwrappers.h"
52 #include "dialogs.h"
53 #include "filetypes.h"
54 #include "project.h"
55 #include "editor.h"
57 #define BUFSIZE 4096
58 #define CMDSIZE 32768
60 struct _geany_win32_spawn
62 HANDLE hChildStdinRd;
63 HANDLE hChildStdinWr;
64 HANDLE hChildStdoutRd;
65 HANDLE hChildStdoutWr;
66 HANDLE hChildStderrRd;
67 HANDLE hChildStderrWr;
68 HANDLE hInputFile;
69 HANDLE hStdout;
70 HANDLE hStderr;
71 HANDLE processId;
72 DWORD dwExitCode;
74 typedef struct _geany_win32_spawn geany_win32_spawn;
76 static gboolean GetContentFromHandle(HANDLE hFile, gchar **content, GError **error);
77 static HANDLE GetTempFileHandle(GError **error);
78 static gboolean CreateChildProcess(geany_win32_spawn *gw_spawn, TCHAR *szCmdline,
79 const TCHAR *dir, GError **error);
80 static VOID ReadFromPipe(HANDLE hRead, HANDLE hWrite, HANDLE hFile, GError **error);
83 static wchar_t *get_file_filters(void)
85 gchar *string;
86 guint i, j, len;
87 static wchar_t title[4096];
88 GString *str = g_string_sized_new(100);
89 GString *all_patterns = g_string_sized_new(100);
90 GSList *node;
91 gchar *tmp;
93 /* create meta file filter "All files" */
94 g_string_append_printf(str, "%s\t*\t", _("All files"));
95 /* create meta file filter "All Source" (skip GEANY_FILETYPES_NONE) */
96 for (i = GEANY_FILETYPES_NONE + 1; i < filetypes_array->len; i++)
98 for (j = 0; filetypes[i]->pattern[j] != NULL; j++)
100 g_string_append(all_patterns, filetypes[i]->pattern[j]);
101 g_string_append_c(all_patterns, ';');
104 g_string_append_printf(str, "%s\t%s\t", _("All Source"), all_patterns->str);
105 g_string_free(all_patterns, TRUE);
106 /* add 'usual' filetypes */
107 foreach_slist(node, filetypes_by_title)
109 GeanyFiletype *ft = node->data;
111 if (G_UNLIKELY(ft->id == GEANY_FILETYPES_NONE))
112 continue;
113 tmp = g_strjoinv(";", ft->pattern);
114 g_string_append_printf(str, "%s\t%s\t", ft->title, tmp);
115 g_free(tmp);
117 g_string_append_c(str, '\t'); /* the final \0 byte to mark the end of the string */
118 string = str->str;
119 g_string_free(str, FALSE);
121 /* replace all "\t"s by \0 */
122 len = strlen(string);
123 g_strdelimit(string, "\t", '\0');
124 g_assert(string[len - 1] == 0x0);
125 MultiByteToWideChar(CP_UTF8, 0, string, len, title, sizeof(title));
126 g_free(string);
128 return title;
132 static wchar_t *get_file_filter_all_files(void)
134 guint len;
135 static wchar_t title[4096];
136 gchar *filter;
138 /* create meta file filter "All files" */
139 filter = g_strdup_printf("%s\t*\t", _("All files"));
141 len = strlen(filter);
142 g_strdelimit(filter, "\t", '\0');
143 g_assert(filter[len - 1] == 0x0);
144 MultiByteToWideChar(CP_UTF8, 0, filter, len, title, sizeof(title));
145 g_free(filter);
147 return title;
151 static wchar_t *get_filters(gboolean project_files)
153 gchar *string;
154 gint len;
155 static wchar_t title[1024];
157 if (project_files)
159 string = g_strconcat(_("Geany project files"), "\t", "*." GEANY_PROJECT_EXT, "\t",
160 filetypes[GEANY_FILETYPES_NONE]->title, "\t",
161 filetypes[GEANY_FILETYPES_NONE]->pattern[0], "\t", NULL);
163 else
165 string = g_strconcat(_("Executables"), "\t", "*.exe;*.bat;*.cmd", "\t",
166 filetypes[GEANY_FILETYPES_NONE]->title, "\t",
167 filetypes[GEANY_FILETYPES_NONE]->pattern[0], "\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, sizeof(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, sizeof(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, sizeof(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, sizeof(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, sizeof(w_dir));
353 MultiByteToWideChar(CP_UTF8, 0, title, -1, w_title, sizeof(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 const gchar *initial_file)
425 OPENFILENAMEW of;
426 gint retval;
427 gchar tmp[MAX_PATH];
428 wchar_t w_file[MAX_PATH];
429 wchar_t w_title[512];
431 w_file[0] = '\0';
433 if (initial_file != NULL)
434 MultiByteToWideChar(CP_UTF8, 0, initial_file, -1, w_file, sizeof(w_file));
436 MultiByteToWideChar(CP_UTF8, 0, title, -1, w_title, sizeof(w_title));
438 /* initialise file dialog info struct */
439 memset(&of, 0, sizeof of);
440 #ifdef OPENFILENAME_SIZE_VERSION_400
441 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
442 #else
443 of.lStructSize = sizeof of;
444 #endif
445 of.hwndOwner = GDK_WINDOW_HWND(gtk_widget_get_window(GTK_WIDGET(parent)));
447 of.lpstrFilter = get_file_filter_all_files();
448 of.lpstrCustomFilter = NULL;
449 of.nFilterIndex = 0;
451 of.lpstrFile = w_file;
452 of.nMaxFile = 2048;
453 of.lpstrFileTitle = NULL;
454 of.lpstrTitle = w_title;
455 of.lpstrDefExt = L"";
456 of.Flags = OFN_FILEMUSTEXIST | OFN_EXPLORER;
457 retval = GetSaveFileNameW(&of);
459 if (! retval)
461 if (CommDlgExtendedError())
463 gchar *error = g_strdup_printf(
464 "File dialog box error (%x)", (gint) CommDlgExtendedError());
465 win32_message_dialog(NULL, GTK_MESSAGE_ERROR, error);
466 g_free(error);
468 return NULL;
471 WideCharToMultiByte(CP_UTF8, 0, w_file, -1, tmp, sizeof(tmp), NULL, NULL);
473 return g_strdup(tmp);
477 /* initial_dir can be NULL to use the current working directory.
478 * Returns: the selected filename */
479 gchar *win32_show_file_dialog(GtkWindow *parent, const gchar *title, const gchar *initial_file)
481 OPENFILENAMEW of;
482 gint retval;
483 gchar tmp[MAX_PATH];
484 wchar_t w_file[MAX_PATH];
485 wchar_t w_title[512];
487 w_file[0] = '\0';
489 if (initial_file != NULL)
490 MultiByteToWideChar(CP_UTF8, 0, initial_file, -1, w_file, sizeof(w_file));
492 MultiByteToWideChar(CP_UTF8, 0, title, -1, w_title, sizeof(w_title));
494 /* initialise file dialog info struct */
495 memset(&of, 0, sizeof of);
496 #ifdef OPENFILENAME_SIZE_VERSION_400
497 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
498 #else
499 of.lStructSize = sizeof of;
500 #endif
501 of.hwndOwner = GDK_WINDOW_HWND(gtk_widget_get_window(GTK_WIDGET(parent)));
503 of.lpstrFile = w_file;
504 of.nMaxFile = 2048;
505 of.lpstrFileTitle = NULL;
506 of.lpstrTitle = w_title;
507 of.lpstrDefExt = L"";
508 of.Flags = OFN_FILEMUSTEXIST | OFN_EXPLORER;
509 retval = GetOpenFileNameW(&of);
511 if (! retval)
513 if (CommDlgExtendedError())
515 gchar *error = g_strdup_printf(
516 "File dialog box error (%x)", (gint) CommDlgExtendedError());
517 win32_message_dialog(NULL, GTK_MESSAGE_ERROR, error);
518 g_free(error);
520 return NULL;
523 WideCharToMultiByte(CP_UTF8, 0, w_file, -1, tmp, sizeof(tmp), NULL, NULL);
525 return g_strdup(tmp);
529 void win32_show_font_dialog(void)
531 gint retval;
532 CHOOSEFONT cf;
533 LOGFONT lf; /* logical font structure */
535 memset(&lf, 0, sizeof lf);
536 /* TODO: init lf members */
538 memset(&cf, 0, sizeof cf);
539 cf.lStructSize = sizeof cf;
540 cf.hwndOwner = GDK_WINDOW_HWND(gtk_widget_get_window(main_widgets.window));
541 cf.lpLogFont = &lf;
542 /* support CF_APPLY? */
543 cf.Flags = CF_NOSCRIPTSEL | CF_FORCEFONTEXIST | CF_INITTOLOGFONTSTRUCT | CF_SCREENFONTS;
545 retval = ChooseFont(&cf);
547 if (retval)
549 gchar *editorfont = g_strdup_printf("%s %d", lf.lfFaceName, (cf.iPointSize / 10));
550 ui_set_editor_font(editorfont);
551 g_free(editorfont);
556 void win32_show_color_dialog(const gchar *colour)
558 CHOOSECOLOR cc;
559 static COLORREF acr_cust_clr[16];
560 static DWORD rgb_current;
561 gchar *hex = g_malloc0(12);
562 GeanyDocument *doc = document_get_current();
564 /* Initialize CHOOSECOLOR */
565 memset(&cc, 0, sizeof cc);
566 cc.lStructSize = sizeof(cc);
567 cc.hwndOwner = GDK_WINDOW_HWND(gtk_widget_get_window(main_widgets.window));
568 cc.lpCustColors = (LPDWORD) acr_cust_clr;
569 cc.rgbResult = (colour != NULL) ? utils_strtod(colour, NULL, colour[0] == '#') : 0;
570 cc.Flags = CC_FULLOPEN | CC_RGBINIT;
572 if (ChooseColor(&cc))
574 rgb_current = cc.rgbResult;
575 g_snprintf(hex, 11, "#%02X%02X%02X",
576 (guint) (utils_scale_round(GetRValue(rgb_current), 255)),
577 (guint) (utils_scale_round(GetGValue(rgb_current), 255)),
578 (guint) (utils_scale_round(GetBValue(rgb_current), 255)));
580 editor_insert_color(doc->editor, hex);
582 g_free(hex);
586 void win32_show_pref_file_dialog(GtkEntry *item)
588 OPENFILENAMEW of;
589 gint retval, len;
590 wchar_t fname[MAX_PATH];
591 gchar tmp[MAX_PATH];
592 gchar **field, *filename;
594 fname[0] = '\0';
596 /* cut the options from the command line */
597 field = g_strsplit(gtk_entry_get_text(GTK_ENTRY(item)), " ", 2);
598 if (field[0])
600 filename = g_find_program_in_path(field[0]);
601 if (filename != NULL && g_file_test(filename, G_FILE_TEST_EXISTS))
603 MultiByteToWideChar(CP_UTF8, 0, filename, -1, fname, sizeof(fname));
604 g_free(filename);
608 /* initialize file dialog info struct */
609 memset(&of, 0, sizeof of);
610 #ifdef OPENFILENAME_SIZE_VERSION_400
611 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
612 #else
613 of.lStructSize = sizeof of;
614 #endif
615 of.hwndOwner = GDK_WINDOW_HWND(gtk_widget_get_window(ui_widgets.prefs_dialog));
617 of.lpstrFilter = get_filters(FALSE);
618 of.lpstrCustomFilter = NULL;
619 of.nFilterIndex = 1;
621 of.lpstrFile = fname;
622 of.nMaxFile = 2048;
623 of.lpstrFileTitle = NULL;
624 /*of.lpstrInitialDir = g_get_home_dir();*/
625 of.lpstrInitialDir = NULL;
626 of.lpstrTitle = NULL;
627 of.lpstrDefExt = L"exe";
628 of.Flags = OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_EXPLORER;
629 retval = GetOpenFileNameW(&of);
631 if (!retval)
633 if (CommDlgExtendedError())
635 gchar error[100];
636 g_snprintf(error, sizeof error, "File dialog box error (%x)", (int)CommDlgExtendedError());
637 win32_message_dialog(NULL, GTK_MESSAGE_ERROR, error);
639 g_strfreev(field);
640 return;
643 len = WideCharToMultiByte(CP_UTF8, 0, fname, -1, tmp, sizeof(tmp), NULL, NULL);
644 if ((of.nFileOffset - 1) != len)
646 if (g_strv_length(field) > 1)
647 /* add the command line args of the old command */
648 /** TODO this fails badly when the old command contained spaces, we need quoting here */
649 filename = g_strconcat(tmp, " ", field[1], NULL);
650 else
652 filename = g_strdup(tmp);
654 gtk_entry_set_text(GTK_ENTRY(item), filename);
655 g_free(filename);
657 g_strfreev(field);
661 /* Creates a native Windows message box of the given type and returns always TRUE
662 * or FALSE representing th pressed Yes or No button.
663 * If type is not GTK_MESSAGE_QUESTION, it returns always TRUE. */
664 gboolean win32_message_dialog(GtkWidget *parent, GtkMessageType type, const gchar *msg)
666 gboolean ret = TRUE;
667 gint rc;
668 guint t;
669 const gchar *title;
670 HWND parent_hwnd = NULL;
671 static wchar_t w_msg[512];
672 static wchar_t w_title[512];
674 switch (type)
676 case GTK_MESSAGE_ERROR:
678 t = MB_OK | MB_ICONERROR;
679 title = _("Error");
680 break;
682 case GTK_MESSAGE_QUESTION:
684 t = MB_YESNO | MB_ICONQUESTION;
685 title = _("Question");
686 break;
688 case GTK_MESSAGE_WARNING:
690 t = MB_OK | MB_ICONWARNING;
691 title = _("Warning");
692 break;
694 default:
696 t = MB_OK | MB_ICONINFORMATION;
697 title = _("Information");
698 break;
702 /* convert the Unicode chars to wide chars */
703 /** TODO test if LANG == C then possibly skip conversion => g_win32_getlocale() */
704 MultiByteToWideChar(CP_UTF8, 0, msg, -1, w_msg, G_N_ELEMENTS(w_msg));
705 MultiByteToWideChar(CP_UTF8, 0, title, -1, w_title, G_N_ELEMENTS(w_title));
707 if (parent != NULL)
708 parent_hwnd = GDK_WINDOW_HWND(gtk_widget_get_window(parent));
709 else if (main_widgets.window != NULL)
710 parent_hwnd = GDK_WINDOW_HWND(gtk_widget_get_window(main_widgets.window));
712 /* display the message box */
713 rc = MessageBoxW(parent_hwnd, w_msg, w_title, t);
715 if (type == GTK_MESSAGE_QUESTION && rc != IDYES)
716 ret = FALSE;
718 return ret;
722 /* Little wrapper for _waccess(), returns errno or 0 if there was no error */
723 gint win32_check_write_permission(const gchar *dir)
725 static wchar_t w_dir[MAX_PATH];
726 MultiByteToWideChar(CP_UTF8, 0, dir, -1, w_dir, sizeof w_dir);
727 if (_waccess(w_dir, R_OK | W_OK) != 0)
728 return errno;
729 else
730 return 0;
734 /* Just a simple wrapper function to open a browser window */
735 void win32_open_browser(const gchar *uri)
737 if (strncmp(uri, "file://", 7) == 0)
739 uri += 7;
740 if (strchr(uri, ':') != NULL)
742 while (*uri == '/')
743 uri++;
746 ShellExecute(NULL, "open", uri, NULL, NULL, SW_SHOWNORMAL);
750 /* Returns TRUE if the command, which child_pid refers to, returned with a successful exit code,
751 * otherwise FALSE. */
752 gboolean win32_get_exit_status(GPid child_pid)
754 DWORD exit_code;
755 GetExitCodeProcess(child_pid, &exit_code);
757 return (exit_code == 0);
761 static void debug_setup_console()
763 static const WORD MAX_CONSOLE_LINES = 500;
764 gint hConHandle;
765 glong lStdHandle;
766 CONSOLE_SCREEN_BUFFER_INFO coninfo;
767 FILE *fp;
769 /* allocate a console for this app */
770 AllocConsole();
772 /* set the screen buffer to be big enough to let us scroll text */
773 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
774 coninfo.dwSize.Y = MAX_CONSOLE_LINES;
775 SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);
777 /* redirect unbuffered STDOUT to the console */
778 lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
779 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
780 fp = _fdopen(hConHandle, "w");
781 *stdout = *fp;
782 setvbuf(stdout, NULL, _IONBF, 0);
784 /* redirect unbuffered STDERR to the console */
785 lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
786 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
787 fp = _fdopen(hConHandle, "w");
788 *stderr = *fp;
789 setvbuf(stderr, NULL, _IONBF, 0);
791 /* redirect unbuffered STDIN to the console */
792 lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
793 hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
794 fp = _fdopen( hConHandle, "r" );
795 *stdin = *fp;
796 setvbuf(stdin, NULL, _IONBF, 0);
800 void win32_init_debug_code(void)
802 if (app->debug_mode)
804 /* create a console window to get log messages on Windows,
805 * especially useful when generating tags files */
806 debug_setup_console();
807 /* Enable GLib process spawn debug mode when Geany was started with the debug flag */
808 g_setenv("G_SPAWN_WIN32_DEBUG", "1", FALSE);
813 gchar *win32_get_hostname(void)
815 gchar hostname[100];
816 DWORD size = sizeof(hostname);
818 if (GetComputerName(hostname, &size))
819 return g_strdup(hostname);
820 else
821 return g_strdup("localhost");
825 /* Process spawning implementation for Windows, by Pierre Joye.
826 * Don't call this function directly, use utils_spawn_[a]sync() instead. */
827 gboolean win32_spawn(const gchar *dir, gchar **argv, gchar **env, GSpawnFlags flags,
828 gchar **std_out, gchar **std_err, gint *exit_status, GError **error)
830 TCHAR buffer[CMDSIZE]=TEXT("");
831 TCHAR cmdline[CMDSIZE] = TEXT("");
832 TCHAR* lpPart[CMDSIZE]={NULL};
833 DWORD retval = 0;
834 gint argc = 0, i;
835 gint cmdpos = 0;
837 SECURITY_ATTRIBUTES saAttr;
838 BOOL fSuccess;
839 geany_win32_spawn gw_spawn;
841 /* Temp file */
842 HANDLE hStdoutTempFile = NULL;
843 HANDLE hStderrTempFile = NULL;
845 gchar *stdout_content = NULL;
846 gchar *stderr_content = NULL;
848 while (argv[argc])
850 ++argc;
852 g_return_val_if_fail (std_out == NULL ||
853 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
854 g_return_val_if_fail (std_err == NULL ||
855 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
857 if (flags & G_SPAWN_SEARCH_PATH)
859 retval = SearchPath(NULL, argv[0], ".exe", sizeof(buffer), buffer, lpPart);
860 if (retval > 0)
861 g_snprintf(cmdline, sizeof(cmdline), "\"%s\"", buffer);
862 else
863 g_strlcpy(cmdline, argv[0], sizeof(cmdline));
864 cmdpos = 1;
867 for (i = cmdpos; i < argc; i++)
869 g_snprintf(cmdline, sizeof(cmdline), "%s %s", cmdline, argv[i]);
870 /*MessageBox(NULL, cmdline, cmdline, MB_OK);*/
873 if (std_err != NULL)
875 hStderrTempFile = GetTempFileHandle(error);
876 if (hStderrTempFile == INVALID_HANDLE_VALUE)
878 gchar *msg = g_win32_error_message(GetLastError());
879 geany_debug("win32_spawn: Second CreateFile failed (%d)", (gint) GetLastError());
880 if (error != NULL)
881 *error = g_error_new(G_SPAWN_ERROR, G_FILE_ERROR, "%s", msg);
882 g_free(msg);
883 return FALSE;
887 if (std_out != NULL)
889 hStdoutTempFile = GetTempFileHandle(error);
890 if (hStdoutTempFile == INVALID_HANDLE_VALUE)
892 gchar *msg = g_win32_error_message(GetLastError());
893 geany_debug("win32_spawn: Second CreateFile failed (%d)", (gint) GetLastError());
894 if (error != NULL)
895 *error = g_error_new(G_SPAWN_ERROR, G_FILE_ERROR, "%s", msg);
896 g_free(msg);
897 return FALSE;
901 /* Set the bInheritHandle flag so pipe handles are inherited. */
902 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
903 saAttr.bInheritHandle = TRUE;
904 saAttr.lpSecurityDescriptor = NULL;
906 /* Get the handle to the current STDOUT and STDERR. */
907 gw_spawn.hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
908 gw_spawn.hStderr = GetStdHandle(STD_ERROR_HANDLE);
909 gw_spawn.dwExitCode = 0;
911 /* Create a pipe for the child process's STDOUT. */
912 if (! CreatePipe(&(gw_spawn.hChildStdoutRd), &(gw_spawn.hChildStdoutWr), &saAttr, 0))
914 gchar *msg = g_win32_error_message(GetLastError());
915 geany_debug("win32_spawn: Stdout pipe creation failed (%d)", (gint) GetLastError());
916 if (error != NULL)
917 *error = g_error_new(G_SPAWN_ERROR, G_FILE_ERROR_PIPE, "%s", msg);
918 g_free(msg);
919 return FALSE;
922 /* Ensure that the read handle to the child process's pipe for STDOUT is not inherited.*/
923 SetHandleInformation(gw_spawn.hChildStdoutRd, HANDLE_FLAG_INHERIT, 0);
925 /* Create a pipe for the child process's STDERR. */
926 if (! CreatePipe(&(gw_spawn.hChildStderrRd), &(gw_spawn.hChildStderrWr), &saAttr, 0))
928 gchar *msg = g_win32_error_message(GetLastError());
929 geany_debug("win32_spawn: Stderr pipe creation failed");
930 if (error != NULL)
931 *error = g_error_new(G_SPAWN_ERROR, G_FILE_ERROR_PIPE, "%s", msg);
932 g_free(msg);
933 return FALSE;
936 /* Ensure that the read handle to the child process's pipe for STDOUT is not inherited.*/
937 SetHandleInformation(gw_spawn.hChildStderrRd, HANDLE_FLAG_INHERIT, 0);
939 /* Create a pipe for the child process's STDIN. */
940 if (! CreatePipe(&(gw_spawn.hChildStdinRd), &(gw_spawn.hChildStdinWr), &saAttr, 0))
942 gchar *msg = g_win32_error_message(GetLastError());
943 geany_debug("win32_spawn: Stdin pipe creation failed");
944 if (error != NULL)
945 *error = g_error_new(G_SPAWN_ERROR, G_FILE_ERROR_PIPE, "%s", msg);
946 g_free(msg);
947 return FALSE;
950 /* Ensure that the write handle to the child process's pipe for STDIN is not inherited. */
951 SetHandleInformation(gw_spawn.hChildStdinWr, HANDLE_FLAG_INHERIT, 0);
953 /* Now create the child process. */
954 fSuccess = CreateChildProcess(&gw_spawn, cmdline, dir, error);
955 if (exit_status)
957 *exit_status = gw_spawn.dwExitCode;
960 if (! fSuccess)
962 geany_debug("win32_spawn: Create process failed");
963 return FALSE;
966 /* Read from pipe that is the standard output for child process. */
967 if (std_out != NULL)
969 ReadFromPipe(gw_spawn.hChildStdoutRd, gw_spawn.hChildStdoutWr, hStdoutTempFile, error);
970 if (! GetContentFromHandle(hStdoutTempFile, &stdout_content, error))
972 return FALSE;
974 *std_out = stdout_content;
977 if (std_err != NULL)
979 ReadFromPipe(gw_spawn.hChildStderrRd, gw_spawn.hChildStderrWr, hStderrTempFile, error);
980 if (! GetContentFromHandle(hStderrTempFile, &stderr_content, error))
982 return FALSE;
984 *std_err = stderr_content;
986 return TRUE;
990 static gboolean GetContentFromHandle(HANDLE hFile, gchar **content, GError **error)
992 DWORD filesize;
993 gchar * buffer;
994 DWORD dwRead;
996 filesize = GetFileSize(hFile, NULL);
997 if (filesize < 1)
999 *content = NULL;
1000 return TRUE;
1003 buffer = g_malloc(filesize + 1);
1004 if (! buffer)
1006 gchar *msg = g_win32_error_message(GetLastError());
1007 geany_debug("GetContentFromHandle: Alloc failed");
1008 if (error != NULL)
1009 *error = g_error_new(G_SPAWN_ERROR, G_SPAWN_ERROR, "%s", msg);
1010 g_free(msg);
1011 return FALSE;
1014 SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
1015 if (! ReadFile(hFile, buffer, filesize, &dwRead, NULL) || dwRead == 0)
1017 gchar *msg = g_win32_error_message(GetLastError());
1018 geany_debug("GetContentFromHandle: Cannot read tempfile");
1019 if (error != NULL)
1020 *error = g_error_new(G_SPAWN_ERROR, G_FILE_ERROR_FAILED, "%s", msg);
1021 g_free(msg);
1022 return FALSE;
1025 if (! CloseHandle(hFile))
1027 gchar *msg = g_win32_error_message(GetLastError());
1028 geany_debug("GetContentFromHandle: CloseHandle failed (%d)", (gint) GetLastError());
1029 if (error != NULL)
1030 *error = g_error_new(G_SPAWN_ERROR, G_FILE_ERROR_FAILED, "%s", msg);
1031 g_free(msg);
1032 g_free(buffer);
1033 *content = NULL;
1034 return FALSE;
1036 buffer[filesize] = '\0';
1037 *content = buffer;
1038 return TRUE;
1042 gchar *win32_expand_environment_variables(const gchar *str)
1044 gchar expCmdline[32768]; /* 32768 is the limit for ExpandEnvironmentStrings() */
1046 if (ExpandEnvironmentStrings((LPCTSTR) str, (LPTSTR) expCmdline, sizeof(expCmdline)) != 0)
1047 return g_strdup(expCmdline);
1048 else
1049 return g_strdup(str);
1053 static gboolean CreateChildProcess(geany_win32_spawn *gw_spawn, TCHAR *szCmdline,
1054 const TCHAR *dir, GError **error)
1056 PROCESS_INFORMATION piProcInfo;
1057 STARTUPINFOW siStartInfo;
1058 BOOL bFuncRetn = FALSE;
1059 gchar *expandedCmdline;
1060 wchar_t w_commandline[CMDSIZE];
1061 wchar_t w_dir[MAX_PATH];
1063 /* Set up members of the PROCESS_INFORMATION structure. */
1064 ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
1066 /* Set up members of the STARTUPINFO structure.*/
1067 ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
1069 siStartInfo.cb = sizeof(STARTUPINFO);
1070 siStartInfo.hStdError = gw_spawn->hChildStderrWr;
1071 siStartInfo.hStdOutput = gw_spawn->hChildStdoutWr;
1072 siStartInfo.hStdInput = gw_spawn->hChildStdinRd;
1073 siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
1075 /* Expand environment variables like %blah%. */
1076 expandedCmdline = win32_expand_environment_variables(szCmdline);
1078 MultiByteToWideChar(CP_UTF8, 0, expandedCmdline, -1, w_commandline, sizeof(w_commandline));
1079 MultiByteToWideChar(CP_UTF8, 0, dir, -1, w_dir, sizeof(w_dir));
1081 /* Create the child process. */
1082 bFuncRetn = CreateProcessW(NULL,
1083 w_commandline, /* command line */
1084 NULL, /* process security attributes */
1085 NULL, /* primary thread security attributes */
1086 TRUE, /* handles are inherited */
1087 CREATE_NO_WINDOW, /* creation flags */
1088 NULL, /* use parent's environment */
1089 w_dir, /* use parent's current directory */
1090 &siStartInfo, /* STARTUPINFO pointer */
1091 &piProcInfo); /* receives PROCESS_INFORMATION */
1093 g_free(expandedCmdline);
1095 if (bFuncRetn == 0)
1097 gchar *msg = g_win32_error_message(GetLastError());
1098 geany_debug("CreateChildProcess: CreateProcess failed (%s)", msg);
1099 if (error != NULL)
1100 *error = g_error_new(G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED, "%s", msg);
1101 g_free(msg);
1102 return FALSE;
1104 else
1106 gint i;
1108 for (i = 0; i < 2 && WaitForSingleObject(piProcInfo.hProcess, 30*1000) == WAIT_TIMEOUT; i++)
1110 geany_debug("CreateChildProcess: CreateProcess failed");
1111 TerminateProcess(piProcInfo.hProcess, WAIT_TIMEOUT); /* NOTE: This will not kill grandkids. */
1114 if (!GetExitCodeProcess(piProcInfo.hProcess, &gw_spawn->dwExitCode))
1116 gchar *msg = g_win32_error_message(GetLastError());
1117 geany_debug("GetExitCodeProcess failed: %s", msg);
1118 if (error != NULL)
1119 *error = g_error_new(G_SPAWN_ERROR, G_FILE_ERROR_FAILED, "%s", msg);
1120 g_free(msg);
1122 CloseHandle(piProcInfo.hProcess);
1123 CloseHandle(piProcInfo.hThread);
1124 return bFuncRetn;
1126 return FALSE;
1130 static VOID ReadFromPipe(HANDLE hRead, HANDLE hWrite, HANDLE hFile, GError **error)
1132 DWORD dwRead, dwWritten;
1133 CHAR chBuf[BUFSIZE];
1135 /* Close the write end of the pipe before reading from the
1136 read end of the pipe. */
1137 if (! CloseHandle(hWrite))
1139 gchar *msg = g_win32_error_message(GetLastError());
1140 geany_debug("ReadFromPipe: Closing handle failed");
1141 if (error != NULL)
1142 *error = g_error_new(G_SPAWN_ERROR, G_FILE_ERROR_PIPE, "%s", msg);
1143 g_free(msg);
1144 return;
1147 /* Read output from the child process, and write to parent's STDOUT. */
1148 for (;;)
1150 if (! ReadFile(hRead, chBuf, BUFSIZE, &dwRead, NULL) || dwRead == 0)
1151 break;
1153 if (! WriteFile(hFile, chBuf, dwRead, &dwWritten, NULL))
1154 break;
1159 static HANDLE GetTempFileHandle(GError **error)
1161 /* Temp file */
1162 DWORD dwBufSize = BUFSIZE;
1163 UINT uRetVal;
1164 TCHAR szTempName[BUFSIZE];
1165 TCHAR lpPathBuffer[BUFSIZE];
1166 DWORD dwRetVal;
1167 HANDLE hTempFile;
1169 /* Get the temp path. */
1170 dwRetVal = GetTempPath(dwBufSize, /* length of the buffer*/
1171 lpPathBuffer); /* buffer for path */
1173 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1175 gchar *msg = g_win32_error_message(GetLastError());
1176 geany_debug("GetTempFileHandle: GetTempPath failed (%d)", (gint) GetLastError());
1177 if (error != NULL)
1178 *error = g_error_new(G_SPAWN_ERROR, G_FILE_ERROR, "%s", msg);
1179 g_free(msg);
1180 return NULL;
1183 /* Create a temporary file for STDOUT. */
1184 uRetVal = GetTempFileName(lpPathBuffer, /* directory for tmp files */
1185 TEXT("GEANY_VCDIFF_"), /* temp file name prefix */
1186 0, /* create unique name */
1187 szTempName); /* buffer for name */
1188 if (uRetVal == 0)
1190 gchar *msg = g_win32_error_message(GetLastError());
1191 geany_debug("GetTempFileName failed (%d)", (gint) GetLastError());
1192 if (error != NULL)
1193 *error = g_error_new(G_SPAWN_ERROR, G_FILE_ERROR, "%s", msg);
1194 g_free(msg);
1195 return NULL;
1198 hTempFile = CreateFile((LPTSTR) szTempName, /* file name */
1199 GENERIC_READ | GENERIC_WRITE, /* open r-w */
1200 0, /* do not share */
1201 NULL, /* default security */
1202 CREATE_ALWAYS, /* overwrite existing */
1203 FILE_ATTRIBUTE_NORMAL,/* normal file */
1204 NULL); /* no template */
1206 if (hTempFile == INVALID_HANDLE_VALUE)
1208 gchar *msg = g_win32_error_message(GetLastError());
1209 geany_debug("GetTempFileHandle: Second CreateFile failed (%d)", (gint) GetLastError());
1210 if (error != NULL)
1211 *error = g_error_new(G_SPAWN_ERROR, G_FILE_ERROR, "%s", msg);
1212 g_free(msg);
1213 return NULL;
1215 return hTempFile;
1219 /* From GDK (they got it from MS Knowledge Base article Q130698) */
1220 static gboolean resolve_link(HWND hWnd, wchar_t *link, gchar **lpszPath)
1222 WIN32_FILE_ATTRIBUTE_DATA wfad;
1223 HRESULT hres;
1224 IShellLinkW *pslW = NULL;
1225 IPersistFile *ppf = NULL;
1226 LPVOID pslWV = NULL;
1227 LPVOID ppfV = NULL;
1229 /* Check if the file is empty first because IShellLink::Resolve for some reason succeeds
1230 * with an empty file and returns an empty "link target". (#524151) */
1231 if (!GetFileAttributesExW(link, GetFileExInfoStandard, &wfad) ||
1232 (wfad.nFileSizeHigh == 0 && wfad.nFileSizeLow == 0))
1234 return FALSE;
1237 /* Assume failure to start with: */
1238 *lpszPath = 0;
1240 CoInitialize(NULL);
1242 hres = CoCreateInstance(
1243 &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, &IID_IShellLinkW, &pslWV);
1245 if (SUCCEEDED(hres))
1247 /* The IShellLink interface supports the IPersistFile interface.
1248 * Get an interface pointer to it. */
1249 pslW = (IShellLinkW*) pslWV;
1250 hres = pslW->lpVtbl->QueryInterface(pslW, &IID_IPersistFile, &ppfV);
1253 if (SUCCEEDED(hres))
1255 /* Load the file. */
1256 ppf = (IPersistFile*) ppfV;
1257 hres = ppf->lpVtbl->Load(ppf, link, STGM_READ);
1260 if (SUCCEEDED(hres))
1262 /* Resolve the link by calling the Resolve() interface function. */
1263 hres = pslW->lpVtbl->Resolve(pslW, hWnd, SLR_ANY_MATCH | SLR_NO_UI);
1266 if (SUCCEEDED(hres))
1268 wchar_t wtarget[MAX_PATH];
1270 hres = pslW->lpVtbl->GetPath(pslW, wtarget, MAX_PATH, NULL, 0);
1271 if (SUCCEEDED(hres))
1272 *lpszPath = g_utf16_to_utf8(wtarget, -1, NULL, NULL, NULL);
1275 if (ppf)
1276 ppf->lpVtbl->Release(ppf);
1278 if (pslW)
1279 pslW->lpVtbl->Release(pslW);
1281 return SUCCEEDED(hres);
1285 /* Checks whether file_name is a Windows shortcut. file_name is expected in UTF-8 encoding.
1286 * If file_name is a Windows shortcut, it returns the target in UTF-8 encoding.
1287 * If it is not a shortcut, it returns a newly allocated copy of file_name. */
1288 gchar *win32_get_shortcut_target(const gchar *file_name)
1290 gchar *path = NULL;
1291 wchar_t *wfilename = g_utf8_to_utf16(file_name, -1, NULL, NULL, NULL);
1293 resolve_link(GDK_WINDOW_HWND(gtk_widget_get_window(main_widgets.window)), wfilename, &path);
1294 g_free(wfilename);
1296 if (path == NULL)
1297 return g_strdup(file_name);
1298 else
1299 return path;
1303 void win32_set_working_directory(const gchar *dir)
1305 SetCurrentDirectory(dir);
1309 gchar *win32_get_installation_dir(void)
1311 return g_win32_get_package_installation_directory_of_module(NULL);
1315 #endif