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.
31 #define WIN32_LEAN_AND_MEAN
43 #include <glib/gstdio.h>
44 #include <gdk/gdkwin32.h>
52 #include "sciwrappers.h"
54 #include "filetypes.h"
61 struct _geany_win32_spawn
65 HANDLE hChildStdoutRd
;
66 HANDLE hChildStdoutWr
;
67 HANDLE hChildStderrRd
;
68 HANDLE hChildStderrWr
;
75 typedef struct _geany_win32_spawn geany_win32_spawn
;
77 static gboolean
GetContentFromHandle(HANDLE hFile
, gchar
**content
, GError
**error
);
78 static HANDLE
GetTempFileHandle(GError
**error
);
79 static gboolean
CreateChildProcess(geany_win32_spawn
*gw_spawn
, TCHAR
*szCmdline
,
80 const TCHAR
*dir
, GError
**error
);
81 static VOID
ReadFromPipe(HANDLE hRead
, HANDLE hWrite
, HANDLE hFile
, GError
**error
);
84 static wchar_t *get_file_filters(void)
88 static wchar_t title
[4096];
89 GString
*str
= g_string_sized_new(100);
90 GString
*all_patterns
= g_string_sized_new(100);
94 /* create meta file filter "All files" */
95 g_string_append_printf(str
, "%s\t*\t", _("All files"));
96 /* create meta file filter "All Source" (skip GEANY_FILETYPES_NONE) */
97 for (i
= GEANY_FILETYPES_NONE
+ 1; i
< filetypes_array
->len
; i
++)
99 for (j
= 0; filetypes
[i
]->pattern
[j
] != NULL
; j
++)
101 g_string_append(all_patterns
, filetypes
[i
]->pattern
[j
]);
102 g_string_append_c(all_patterns
, ';');
105 g_string_append_printf(str
, "%s\t%s\t", _("All Source"), all_patterns
->str
);
106 g_string_free(all_patterns
, TRUE
);
107 /* add 'usual' filetypes */
108 foreach_slist(node
, filetypes_by_title
)
110 GeanyFiletype
*ft
= node
->data
;
112 if (G_UNLIKELY(ft
->id
== GEANY_FILETYPES_NONE
))
114 tmp
= g_strjoinv(";", ft
->pattern
);
115 g_string_append_printf(str
, "%s\t%s\t", ft
->title
, tmp
);
118 g_string_append_c(str
, '\t'); /* the final \0 byte to mark the end of the string */
120 g_string_free(str
, FALSE
);
122 /* replace all "\t"s by \0 */
123 len
= strlen(string
);
124 g_strdelimit(string
, "\t", '\0');
125 g_assert(string
[len
- 1] == 0x0);
126 MultiByteToWideChar(CP_UTF8
, 0, string
, len
, title
, sizeof(title
));
133 static wchar_t *get_file_filter_all_files(void)
136 static wchar_t title
[4096];
139 /* create meta file filter "All files" */
140 filter
= g_strdup_printf("%s\t*\t", _("All files"));
142 len
= strlen(filter
);
143 g_strdelimit(filter
, "\t", '\0');
144 g_assert(filter
[len
- 1] == 0x0);
145 MultiByteToWideChar(CP_UTF8
, 0, filter
, len
, title
, sizeof(title
));
152 static wchar_t *get_filters(gboolean project_files
)
156 static wchar_t title
[1024];
160 string
= g_strconcat(_("Geany project files"), "\t", "*." GEANY_PROJECT_EXT
, "\t",
161 _("All files"), "\t", "*", "\t", NULL
);
165 string
= g_strconcat(_("Executables"), "\t", "*.exe;*.bat;*.cmd", "\t",
166 _("All files"), "\t", "*", "\t", NULL
);
169 /* replace all "\t"s by \0 */
170 len
= strlen(string
);
171 g_strdelimit(string
, "\t", '\0');
172 g_assert(string
[len
- 1] == 0x0);
173 MultiByteToWideChar(CP_UTF8
, 0, string
, len
, title
, sizeof(title
));
180 /* Converts the given UTF-8 filename or directory name into something usable for Windows and
181 * returns the directory part of the given filename. */
182 static wchar_t *get_dir_for_path(const gchar
*utf8_filename
)
184 static wchar_t w_dir
[MAX_PATH
];
187 if (g_file_test(utf8_filename
, G_FILE_TEST_IS_DIR
))
188 result
= (gchar
*) utf8_filename
;
190 result
= g_path_get_dirname(utf8_filename
);
192 MultiByteToWideChar(CP_UTF8
, 0, result
, -1, w_dir
, sizeof(w_dir
));
194 if (result
!= utf8_filename
)
201 /* Callback function for setting the initial directory of the folder open dialog. This could also
202 * be done with BROWSEINFO.pidlRoot and SHParseDisplayName but SHParseDisplayName is not available
203 * on systems below Windows XP. So, we go the hard way by creating a callback which will set up the
204 * folder when the dialog is initialised. Yeah, I like Windows. */
205 INT CALLBACK
BrowseCallbackProc(HWND hwnd
, UINT uMsg
, LPARAM lp
, LPARAM pData
)
209 case BFFM_INITIALIZED
:
211 SendMessageW(hwnd
, BFFM_SETSELECTIONW
, TRUE
, pData
);
214 case BFFM_SELCHANGED
:
216 /* set the status window to the currently selected path. */
217 static wchar_t szDir
[MAX_PATH
];
218 if (SHGetPathFromIDListW((LPITEMIDLIST
) lp
, szDir
))
220 SendMessageW(hwnd
, BFFM_SETSTATUSTEXTW
, 0, (LPARAM
) szDir
);
229 /* Shows a folder selection dialog.
230 * initial_dir is expected in UTF-8
231 * The selected folder name is returned. */
232 gchar
*win32_show_folder_dialog(GtkWidget
*parent
, const gchar
*title
, const gchar
*initial_dir
)
236 gchar
*result
= NULL
;
237 wchar_t fname
[MAX_PATH
];
238 wchar_t w_title
[512];
240 MultiByteToWideChar(CP_UTF8
, 0, title
, -1, w_title
, sizeof(w_title
));
243 parent
= main_widgets
.window
;
245 memset(&bi
, 0, sizeof bi
);
246 bi
.hwndOwner
= GDK_WINDOW_HWND(gtk_widget_get_window(parent
));
248 bi
.lpszTitle
= w_title
;
249 bi
.lpfn
= BrowseCallbackProc
;
250 bi
.lParam
= (LPARAM
) get_dir_for_path(initial_dir
);
251 bi
.ulFlags
= BIF_DONTGOBELOWDOMAIN
| BIF_RETURNONLYFSDIRS
| BIF_STATUSTEXT
;
253 pidl
= SHBrowseForFolderW(&bi
);
255 /* convert the strange Windows folder list item something into an usual path string ;-) */
258 if (SHGetPathFromIDListW(pidl
, fname
))
260 result
= g_malloc0(MAX_PATH
* 2);
261 WideCharToMultiByte(CP_UTF8
, 0, fname
, -1, result
, MAX_PATH
* 2, NULL
, NULL
);
263 /* SHBrowseForFolder() probably leaks memory here, but how to free the allocated memory? */
269 /* Shows a file open dialog.
270 * If allow_new_file is set, the file to be opened doesn't have to exist.
271 * initial_dir is expected in UTF-8
272 * The selected file name is returned.
273 * If project_file_filter is set, the file open dialog will have a file filter for Geany project
274 * files, a filter for executables otherwise. */
275 gchar
*win32_show_project_open_dialog(GtkWidget
*parent
, const gchar
*title
,
276 const gchar
*initial_dir
, gboolean allow_new_file
,
277 gboolean project_file_filter
)
281 wchar_t fname
[MAX_PATH
];
282 wchar_t w_title
[512];
287 MultiByteToWideChar(CP_UTF8
, 0, title
, -1, w_title
, sizeof(w_title
));
290 parent
= main_widgets
.window
;
292 /* initialise file dialog info struct */
293 memset(&of
, 0, sizeof of
);
294 #ifdef OPENFILENAME_SIZE_VERSION_400
295 of
.lStructSize
= OPENFILENAME_SIZE_VERSION_400
;
297 of
.lStructSize
= sizeof of
;
299 of
.hwndOwner
= GDK_WINDOW_HWND(gtk_widget_get_window(parent
));
300 of
.lpstrFilter
= get_filters(project_file_filter
);
302 of
.lpstrCustomFilter
= NULL
;
304 of
.lpstrFile
= fname
;
305 of
.lpstrInitialDir
= get_dir_for_path(initial_dir
);
307 of
.lpstrFileTitle
= NULL
;
308 of
.lpstrTitle
= w_title
;
309 of
.lpstrDefExt
= L
"";
310 of
.Flags
= OFN_PATHMUSTEXIST
| OFN_EXPLORER
| OFN_HIDEREADONLY
;
311 if (! allow_new_file
)
312 of
.Flags
|= OFN_FILEMUSTEXIST
;
314 retval
= GetOpenFileNameW(&of
);
318 if (CommDlgExtendedError())
321 error
= g_strdup_printf("File dialog box error (%x)", (int)CommDlgExtendedError());
322 win32_message_dialog(NULL
, GTK_MESSAGE_ERROR
, error
);
327 /* convert the resulting filename into UTF-8 (from whatever encoding it has at this moment) */
328 filename
= g_malloc0(MAX_PATH
* 2);
329 WideCharToMultiByte(CP_UTF8
, 0, fname
, -1, filename
, MAX_PATH
* 2, NULL
, NULL
);
335 /* initial_dir can be NULL to use the current working directory.
336 * Returns: TRUE if the dialog was not cancelled. */
337 gboolean
win32_show_document_open_dialog(GtkWindow
*parent
, const gchar
*title
, const gchar
*initial_dir
)
343 wchar_t fname
[MAX_PATH
];
344 wchar_t w_dir
[MAX_PATH
];
345 wchar_t w_title
[512];
349 if (initial_dir
!= NULL
)
350 MultiByteToWideChar(CP_UTF8
, 0, initial_dir
, -1, w_dir
, sizeof(w_dir
));
352 MultiByteToWideChar(CP_UTF8
, 0, title
, -1, w_title
, sizeof(w_title
));
354 /* initialise file dialog info struct */
355 memset(&of
, 0, sizeof of
);
356 #ifdef OPENFILENAME_SIZE_VERSION_400
357 of
.lStructSize
= OPENFILENAME_SIZE_VERSION_400
;
359 of
.lStructSize
= sizeof of
;
361 of
.hwndOwner
= GDK_WINDOW_HWND(gtk_widget_get_window(GTK_WIDGET(parent
)));
362 of
.lpstrFilter
= get_file_filters();
364 of
.lpstrCustomFilter
= NULL
;
365 of
.nFilterIndex
= GEANY_FILETYPES_NONE
+ 1;
366 of
.lpstrFile
= fname
;
367 of
.lpstrInitialDir
= (initial_dir
!= NULL
) ? w_dir
: NULL
;
369 of
.lpstrFileTitle
= NULL
;
370 of
.lpstrTitle
= w_title
;
371 of
.lpstrDefExt
= L
"";
372 of
.Flags
= OFN_ALLOWMULTISELECT
| OFN_FILEMUSTEXIST
| OFN_EXPLORER
;
374 retval
= GetOpenFileNameW(&of
);
378 if (CommDlgExtendedError())
381 g_snprintf(error
, sizeof error
, "File dialog box error (%x)", (int)CommDlgExtendedError());
382 win32_message_dialog(NULL
, GTK_MESSAGE_ERROR
, error
);
387 x
= of
.nFileOffset
- 1;
388 if (x
!= wcslen(fname
))
389 { /* open a single file */
390 WideCharToMultiByte(CP_UTF8
, 0, fname
, -1, tmp
, sizeof(tmp
), NULL
, NULL
);
391 document_open_file(tmp
, of
.Flags
& OFN_READONLY
, NULL
, NULL
);
394 { /* open multiple files */
395 gchar file_name
[MAX_PATH
];
396 gchar dir_name
[MAX_PATH
];
398 WideCharToMultiByte(CP_UTF8
, 0, fname
, of
.nFileOffset
,
399 dir_name
, sizeof(dir_name
), NULL
, NULL
);
407 WideCharToMultiByte(CP_UTF8
, 0, fname
+ x
+ 1, -1,
408 tmp
, sizeof(tmp
), NULL
, NULL
);
409 g_snprintf(file_name
, 511, "%s\\%s", dir_name
, tmp
);
411 /* convert the resulting filename into UTF-8 */
412 document_open_file(file_name
, of
.Flags
& OFN_READONLY
, NULL
, NULL
);
417 return (retval
!= 0);
421 gchar
*win32_show_document_save_as_dialog(GtkWindow
*parent
, const gchar
*title
,
422 const gchar
*initial_file
)
427 wchar_t w_file
[MAX_PATH
];
428 wchar_t w_title
[512];
432 if (initial_file
!= NULL
)
433 MultiByteToWideChar(CP_UTF8
, 0, initial_file
, -1, w_file
, sizeof(w_file
));
435 MultiByteToWideChar(CP_UTF8
, 0, title
, -1, w_title
, sizeof(w_title
));
437 /* initialise file dialog info struct */
438 memset(&of
, 0, sizeof of
);
439 #ifdef OPENFILENAME_SIZE_VERSION_400
440 of
.lStructSize
= OPENFILENAME_SIZE_VERSION_400
;
442 of
.lStructSize
= sizeof of
;
444 of
.hwndOwner
= GDK_WINDOW_HWND(gtk_widget_get_window(GTK_WIDGET(parent
)));
446 of
.lpstrFilter
= get_file_filter_all_files();
447 of
.lpstrCustomFilter
= NULL
;
450 of
.lpstrFile
= w_file
;
452 of
.lpstrFileTitle
= NULL
;
453 of
.lpstrTitle
= w_title
;
454 of
.lpstrDefExt
= L
"";
455 of
.Flags
= OFN_FILEMUSTEXIST
| OFN_EXPLORER
;
456 retval
= GetSaveFileNameW(&of
);
460 if (CommDlgExtendedError())
462 gchar
*error
= g_strdup_printf(
463 "File dialog box error (%x)", (gint
) CommDlgExtendedError());
464 win32_message_dialog(NULL
, GTK_MESSAGE_ERROR
, error
);
470 WideCharToMultiByte(CP_UTF8
, 0, w_file
, -1, tmp
, sizeof(tmp
), NULL
, NULL
);
472 return g_strdup(tmp
);
476 /* initial_dir can be NULL to use the current working directory.
477 * Returns: the selected filename */
478 gchar
*win32_show_file_dialog(GtkWindow
*parent
, const gchar
*title
, const gchar
*initial_file
)
483 wchar_t w_file
[MAX_PATH
];
484 wchar_t w_title
[512];
488 if (initial_file
!= NULL
)
489 MultiByteToWideChar(CP_UTF8
, 0, initial_file
, -1, w_file
, sizeof(w_file
));
491 MultiByteToWideChar(CP_UTF8
, 0, title
, -1, w_title
, sizeof(w_title
));
493 /* initialise file dialog info struct */
494 memset(&of
, 0, sizeof of
);
495 #ifdef OPENFILENAME_SIZE_VERSION_400
496 of
.lStructSize
= OPENFILENAME_SIZE_VERSION_400
;
498 of
.lStructSize
= sizeof of
;
500 of
.hwndOwner
= GDK_WINDOW_HWND(gtk_widget_get_window(GTK_WIDGET(parent
)));
502 of
.lpstrFile
= w_file
;
504 of
.lpstrFileTitle
= NULL
;
505 of
.lpstrTitle
= w_title
;
506 of
.lpstrDefExt
= L
"";
507 of
.Flags
= OFN_FILEMUSTEXIST
| OFN_EXPLORER
;
508 retval
= GetOpenFileNameW(&of
);
512 if (CommDlgExtendedError())
514 gchar
*error
= g_strdup_printf(
515 "File dialog box error (%x)", (gint
) CommDlgExtendedError());
516 win32_message_dialog(NULL
, GTK_MESSAGE_ERROR
, error
);
522 WideCharToMultiByte(CP_UTF8
, 0, w_file
, -1, tmp
, sizeof(tmp
), NULL
, NULL
);
524 return g_strdup(tmp
);
528 void win32_show_font_dialog(void)
532 LOGFONT lf
; /* logical font structure */
534 memset(&lf
, 0, sizeof lf
);
535 /* TODO: init lf members */
537 memset(&cf
, 0, sizeof cf
);
538 cf
.lStructSize
= sizeof cf
;
539 cf
.hwndOwner
= GDK_WINDOW_HWND(gtk_widget_get_window(main_widgets
.window
));
541 /* support CF_APPLY? */
542 cf
.Flags
= CF_NOSCRIPTSEL
| CF_FORCEFONTEXIST
| CF_INITTOLOGFONTSTRUCT
| CF_SCREENFONTS
;
544 retval
= ChooseFont(&cf
);
548 gchar
*editorfont
= g_strdup_printf("%s %d", lf
.lfFaceName
, (cf
.iPointSize
/ 10));
549 ui_set_editor_font(editorfont
);
555 void win32_show_color_dialog(const gchar
*colour
)
558 static COLORREF acr_cust_clr
[16];
559 static DWORD rgb_current
;
560 gchar
*hex
= g_malloc0(12);
561 GeanyDocument
*doc
= document_get_current();
563 /* Initialize CHOOSECOLOR */
564 memset(&cc
, 0, sizeof cc
);
565 cc
.lStructSize
= sizeof(cc
);
566 cc
.hwndOwner
= GDK_WINDOW_HWND(gtk_widget_get_window(main_widgets
.window
));
567 cc
.lpCustColors
= (LPDWORD
) acr_cust_clr
;
568 cc
.rgbResult
= (colour
!= NULL
) ? utils_strtod(colour
, NULL
, colour
[0] == '#') : 0;
569 cc
.Flags
= CC_FULLOPEN
| CC_RGBINIT
;
571 if (ChooseColor(&cc
))
573 rgb_current
= cc
.rgbResult
;
574 g_snprintf(hex
, 11, "#%02X%02X%02X",
575 (guint
) (utils_scale_round(GetRValue(rgb_current
), 255)),
576 (guint
) (utils_scale_round(GetGValue(rgb_current
), 255)),
577 (guint
) (utils_scale_round(GetBValue(rgb_current
), 255)));
579 editor_insert_color(doc
->editor
, hex
);
585 void win32_show_pref_file_dialog(GtkEntry
*item
)
589 wchar_t fname
[MAX_PATH
];
591 gchar
**field
, *filename
;
595 /* cut the options from the command line */
596 field
= g_strsplit(gtk_entry_get_text(GTK_ENTRY(item
)), " ", 2);
599 filename
= g_find_program_in_path(field
[0]);
600 if (filename
!= NULL
&& g_file_test(filename
, G_FILE_TEST_EXISTS
))
602 MultiByteToWideChar(CP_UTF8
, 0, filename
, -1, fname
, sizeof(fname
));
607 /* initialize file dialog info struct */
608 memset(&of
, 0, sizeof of
);
609 #ifdef OPENFILENAME_SIZE_VERSION_400
610 of
.lStructSize
= OPENFILENAME_SIZE_VERSION_400
;
612 of
.lStructSize
= sizeof of
;
614 of
.hwndOwner
= GDK_WINDOW_HWND(gtk_widget_get_window(ui_widgets
.prefs_dialog
));
616 of
.lpstrFilter
= get_filters(FALSE
);
617 of
.lpstrCustomFilter
= NULL
;
620 of
.lpstrFile
= fname
;
622 of
.lpstrFileTitle
= NULL
;
623 /*of.lpstrInitialDir = g_get_home_dir();*/
624 of
.lpstrInitialDir
= NULL
;
625 of
.lpstrTitle
= NULL
;
626 of
.lpstrDefExt
= L
"exe";
627 of
.Flags
= OFN_HIDEREADONLY
| OFN_FILEMUSTEXIST
| OFN_EXPLORER
;
628 retval
= GetOpenFileNameW(&of
);
632 if (CommDlgExtendedError())
635 g_snprintf(error
, sizeof error
, "File dialog box error (%x)", (int)CommDlgExtendedError());
636 win32_message_dialog(NULL
, GTK_MESSAGE_ERROR
, error
);
642 len
= WideCharToMultiByte(CP_UTF8
, 0, fname
, -1, tmp
, sizeof(tmp
), NULL
, NULL
);
643 if ((of
.nFileOffset
- 1) != len
)
645 if (g_strv_length(field
) > 1)
646 /* add the command line args of the old command */
647 /** TODO this fails badly when the old command contained spaces, we need quoting here */
648 filename
= g_strconcat(tmp
, " ", field
[1], NULL
);
651 filename
= g_strdup(tmp
);
653 gtk_entry_set_text(GTK_ENTRY(item
), filename
);
660 /* Creates a native Windows message box of the given type and returns always TRUE
661 * or FALSE representing th pressed Yes or No button.
662 * If type is not GTK_MESSAGE_QUESTION, it returns always TRUE. */
663 gboolean
win32_message_dialog(GtkWidget
*parent
, GtkMessageType type
, const gchar
*msg
)
669 HWND parent_hwnd
= NULL
;
670 static wchar_t w_msg
[512];
671 static wchar_t w_title
[512];
675 case GTK_MESSAGE_ERROR
:
677 t
= MB_OK
| MB_ICONERROR
;
681 case GTK_MESSAGE_QUESTION
:
683 t
= MB_YESNO
| MB_ICONQUESTION
;
684 title
= _("Question");
687 case GTK_MESSAGE_WARNING
:
689 t
= MB_OK
| MB_ICONWARNING
;
690 title
= _("Warning");
695 t
= MB_OK
| MB_ICONINFORMATION
;
696 title
= _("Information");
701 /* convert the Unicode chars to wide chars */
702 /** TODO test if LANG == C then possibly skip conversion => g_win32_getlocale() */
703 MultiByteToWideChar(CP_UTF8
, 0, msg
, -1, w_msg
, G_N_ELEMENTS(w_msg
));
704 MultiByteToWideChar(CP_UTF8
, 0, title
, -1, w_title
, G_N_ELEMENTS(w_title
));
707 parent_hwnd
= GDK_WINDOW_HWND(gtk_widget_get_window(parent
));
708 else if (main_widgets
.window
!= NULL
)
709 parent_hwnd
= GDK_WINDOW_HWND(gtk_widget_get_window(main_widgets
.window
));
711 /* display the message box */
712 rc
= MessageBoxW(parent_hwnd
, w_msg
, w_title
, t
);
714 if (type
== GTK_MESSAGE_QUESTION
&& rc
!= IDYES
)
721 /* Little wrapper for _waccess(), returns errno or 0 if there was no error */
722 gint
win32_check_write_permission(const gchar
*dir
)
724 static wchar_t w_dir
[MAX_PATH
];
725 MultiByteToWideChar(CP_UTF8
, 0, dir
, -1, w_dir
, sizeof w_dir
);
726 if (_waccess(w_dir
, R_OK
| W_OK
) != 0)
733 /* Just a simple wrapper function to open a browser window */
734 void win32_open_browser(const gchar
*uri
)
736 if (strncmp(uri
, "file://", 7) == 0)
739 if (strchr(uri
, ':') != NULL
)
745 ShellExecute(NULL
, "open", uri
, NULL
, NULL
, SW_SHOWNORMAL
);
749 /* Returns TRUE if the command, which child_pid refers to, returned with a successful exit code,
750 * otherwise FALSE. */
751 gboolean
win32_get_exit_status(GPid child_pid
)
754 GetExitCodeProcess(child_pid
, &exit_code
);
756 return (exit_code
== 0);
760 static FILE *open_std_handle(DWORD handle
, const char *mode
)
766 lStdHandle
= GetStdHandle(handle
);
767 if (lStdHandle
== INVALID_HANDLE_VALUE
)
769 gchar
*err
= g_win32_error_message(GetLastError());
770 g_warning("GetStdHandle(%ld) failed: %s", (long)handle
, err
);
774 hConHandle
= _open_osfhandle((long)lStdHandle
, _O_TEXT
);
775 if (hConHandle
== -1)
777 gchar
*err
= g_win32_error_message(GetLastError());
778 g_warning("_open_osfhandle(%ld, _O_TEXT) failed: %s", (long)lStdHandle
, err
);
782 fp
= _fdopen(hConHandle
, mode
);
785 gchar
*err
= g_win32_error_message(GetLastError());
786 g_warning("_fdopen(%d, \"%s\") failed: %s", hConHandle
, mode
, err
);
790 if (setvbuf(fp
, NULL
, _IONBF
, 0) != 0)
792 gchar
*err
= g_win32_error_message(GetLastError());
793 g_warning("setvbuf(%p, NULL, _IONBF, 0) failed: %s", fp
, err
);
803 static void debug_setup_console()
805 static const WORD MAX_CONSOLE_LINES
= 500;
806 CONSOLE_SCREEN_BUFFER_INFO coninfo
;
809 /* allocate a console for this app */
812 /* set the screen buffer to be big enough to let us scroll text */
813 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE
), &coninfo
);
814 coninfo
.dwSize
.Y
= MAX_CONSOLE_LINES
;
815 SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE
), coninfo
.dwSize
);
817 /* redirect unbuffered STDOUT to the console */
818 fp
= open_std_handle(STD_OUTPUT_HANDLE
, "w");
822 /* redirect unbuffered STDERR to the console */
823 fp
= open_std_handle(STD_ERROR_HANDLE
, "w");
827 /* redirect unbuffered STDIN to the console */
828 fp
= open_std_handle(STD_INPUT_HANDLE
, "r");
834 void win32_init_debug_code(void)
838 /* create a console window to get log messages on Windows,
839 * especially useful when generating tags files */
840 debug_setup_console();
841 /* Enable GLib process spawn debug mode when Geany was started with the debug flag */
842 g_setenv("G_SPAWN_WIN32_DEBUG", "1", FALSE
);
847 gchar
*win32_get_hostname(void)
850 DWORD size
= sizeof(hostname
);
852 if (GetComputerName(hostname
, &size
))
853 return g_strdup(hostname
);
855 return g_strdup("localhost");
859 static gchar
*create_temp_file(void)
864 fd
= g_file_open_tmp("tmp_XXXXXX", &name
, NULL
);
874 /* Sometimes this blocks for 30s before aborting when there are several
875 * pages of (error) output and sometimes hangs - see the FIXME.
876 * Also gw_spawn.dwExitCode seems to be not set properly. */
877 /* Process spawning implementation for Windows, by Pierre Joye.
878 * Don't call this function directly, use utils_spawn_[a]sync() instead. */
880 gboolean
_broken_win32_spawn(const gchar
*dir
, gchar
**argv
, gchar
**env
, GSpawnFlags flags
,
881 gchar
**std_out
, gchar
**std_err
, gint
*exit_status
, GError
**error
)
883 TCHAR buffer
[CMDSIZE
]=TEXT("");
884 TCHAR cmdline
[CMDSIZE
] = TEXT("");
885 TCHAR
* lpPart
[CMDSIZE
]={NULL
};
890 SECURITY_ATTRIBUTES saAttr
;
892 geany_win32_spawn gw_spawn
;
895 HANDLE hStdoutTempFile
= NULL
;
896 HANDLE hStderrTempFile
= NULL
;
898 gchar
*stdout_content
= NULL
;
899 gchar
*stderr_content
= NULL
;
905 g_return_val_if_fail (std_out
== NULL
||
906 !(flags
& G_SPAWN_STDOUT_TO_DEV_NULL
), FALSE
);
907 g_return_val_if_fail (std_err
== NULL
||
908 !(flags
& G_SPAWN_STDERR_TO_DEV_NULL
), FALSE
);
910 if (flags
& G_SPAWN_SEARCH_PATH
)
912 retval
= SearchPath(NULL
, argv
[0], ".exe", sizeof(buffer
), buffer
, lpPart
);
914 g_snprintf(cmdline
, sizeof(cmdline
), "\"%s\"", buffer
);
916 g_strlcpy(cmdline
, argv
[0], sizeof(cmdline
));
920 for (i
= cmdpos
; i
< argc
; i
++)
922 g_snprintf(cmdline
, sizeof(cmdline
), "%s %s", cmdline
, argv
[i
]);
923 /*MessageBox(NULL, cmdline, cmdline, MB_OK);*/
928 hStderrTempFile
= GetTempFileHandle(error
);
929 if (hStderrTempFile
== INVALID_HANDLE_VALUE
)
931 gchar
*msg
= g_win32_error_message(GetLastError());
932 geany_debug("win32_spawn: Second CreateFile failed (%d)", (gint
) GetLastError());
933 g_set_error(error
, G_SPAWN_ERROR
, G_FILE_ERROR
, "%s", msg
);
941 hStdoutTempFile
= GetTempFileHandle(error
);
942 if (hStdoutTempFile
== INVALID_HANDLE_VALUE
)
944 gchar
*msg
= g_win32_error_message(GetLastError());
945 geany_debug("win32_spawn: Second CreateFile failed (%d)", (gint
) GetLastError());
946 g_set_error(error
, G_SPAWN_ERROR
, G_FILE_ERROR
, "%s", msg
);
952 /* Set the bInheritHandle flag so pipe handles are inherited. */
953 saAttr
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
954 saAttr
.bInheritHandle
= TRUE
;
955 saAttr
.lpSecurityDescriptor
= NULL
;
957 /* Get the handle to the current STDOUT and STDERR. */
958 gw_spawn
.hStdout
= GetStdHandle(STD_OUTPUT_HANDLE
);
959 gw_spawn
.hStderr
= GetStdHandle(STD_ERROR_HANDLE
);
960 gw_spawn
.dwExitCode
= 0;
962 /* Create a pipe for the child process's STDOUT. */
963 if (! CreatePipe(&(gw_spawn
.hChildStdoutRd
), &(gw_spawn
.hChildStdoutWr
), &saAttr
, 0))
965 gchar
*msg
= g_win32_error_message(GetLastError());
966 geany_debug("win32_spawn: Stdout pipe creation failed (%d)", (gint
) GetLastError());
967 g_set_error(error
, G_SPAWN_ERROR
, G_FILE_ERROR_PIPE
, "%s", msg
);
972 /* Ensure that the read handle to the child process's pipe for STDOUT is not inherited.*/
973 SetHandleInformation(gw_spawn
.hChildStdoutRd
, HANDLE_FLAG_INHERIT
, 0);
975 /* Create a pipe for the child process's STDERR. */
976 if (! CreatePipe(&(gw_spawn
.hChildStderrRd
), &(gw_spawn
.hChildStderrWr
), &saAttr
, 0))
978 gchar
*msg
= g_win32_error_message(GetLastError());
979 geany_debug("win32_spawn: Stderr pipe creation failed");
980 g_set_error(error
, G_SPAWN_ERROR
, G_FILE_ERROR_PIPE
, "%s", msg
);
985 /* Ensure that the read handle to the child process's pipe for STDOUT is not inherited.*/
986 SetHandleInformation(gw_spawn
.hChildStderrRd
, HANDLE_FLAG_INHERIT
, 0);
988 /* Create a pipe for the child process's STDIN. */
989 if (! CreatePipe(&(gw_spawn
.hChildStdinRd
), &(gw_spawn
.hChildStdinWr
), &saAttr
, 0))
991 gchar
*msg
= g_win32_error_message(GetLastError());
992 geany_debug("win32_spawn: Stdin pipe creation failed");
993 g_set_error(error
, G_SPAWN_ERROR
, G_FILE_ERROR_PIPE
, "%s", msg
);
998 /* Ensure that the write handle to the child process's pipe for STDIN is not inherited. */
999 SetHandleInformation(gw_spawn
.hChildStdinWr
, HANDLE_FLAG_INHERIT
, 0);
1001 /* Now create the child process. */
1002 fSuccess
= CreateChildProcess(&gw_spawn
, cmdline
, dir
, error
);
1005 *exit_status
= gw_spawn
.dwExitCode
;
1010 geany_debug("win32_spawn: Create process failed");
1014 /* Read from pipe that is the standard output for child process. */
1015 if (std_out
!= NULL
)
1017 ReadFromPipe(gw_spawn
.hChildStdoutRd
, gw_spawn
.hChildStdoutWr
, hStdoutTempFile
, error
);
1018 if (! GetContentFromHandle(hStdoutTempFile
, &stdout_content
, error
))
1022 *std_out
= stdout_content
;
1025 if (std_err
!= NULL
)
1027 ReadFromPipe(gw_spawn
.hChildStderrRd
, gw_spawn
.hChildStderrWr
, hStderrTempFile
, error
);
1028 if (! GetContentFromHandle(hStderrTempFile
, &stderr_content
, error
))
1032 *std_err
= stderr_content
;
1038 /* Simple replacement for _broken_win32_spawn().
1039 * flags is ignored, G_SPAWN_SEARCH_PATH is implied.
1040 * Don't call this function directly, use utils_spawn_[a]sync() instead.
1041 * Adapted from tm_workspace_create_global_tags(). */
1042 gboolean
win32_spawn(const gchar
*dir
, gchar
**argv
, gchar
**env
, GSpawnFlags flags
,
1043 gchar
**std_out
, gchar
**std_err
, gint
*exit_status
, GError
**error
)
1047 gchar
*tmp_file
= create_temp_file();
1048 gchar
*tmp_errfile
= create_temp_file();
1053 return _broken_win32_spawn(dir
, argv
, env
, flags
, std_out
, std_err
,
1054 exit_status
, error
);
1056 if (!tmp_file
|| !tmp_errfile
)
1058 g_warning("%s: Could not create temporary files!", G_STRFUNC
);
1061 command
= g_strjoinv(" ", argv
);
1062 SETPTR(command
, g_strdup_printf("%s >%s 2>%s",
1063 command
, tmp_file
, tmp_errfile
));
1065 ret
= system(command
);
1066 /* the command can return -1 as an exit code, so check errno also */
1067 fail
= ret
== -1 && errno
;
1070 if (std_out
!= NULL
)
1071 g_file_get_contents(tmp_file
, std_out
, NULL
, NULL
);
1072 if (std_err
!= NULL
)
1073 g_file_get_contents(tmp_errfile
, std_err
, NULL
, NULL
);
1076 g_set_error_literal(error
, G_SPAWN_ERROR
, errno
, g_strerror(errno
));
1081 g_unlink(tmp_errfile
);
1082 g_free(tmp_errfile
);
1090 static gboolean
GetContentFromHandle(HANDLE hFile
, gchar
**content
, GError
**error
)
1096 filesize
= GetFileSize(hFile
, NULL
);
1103 buffer
= g_malloc(filesize
+ 1);
1106 gchar
*msg
= g_win32_error_message(GetLastError());
1107 geany_debug("GetContentFromHandle: Alloc failed");
1108 g_set_error(error
, G_SPAWN_ERROR
, G_SPAWN_ERROR
, "%s", msg
);
1113 SetFilePointer(hFile
, 0, NULL
, FILE_BEGIN
);
1114 if (! ReadFile(hFile
, buffer
, filesize
, &dwRead
, NULL
) || dwRead
== 0)
1116 gchar
*msg
= g_win32_error_message(GetLastError());
1117 geany_debug("GetContentFromHandle: Cannot read tempfile");
1118 g_set_error(error
, G_SPAWN_ERROR
, G_FILE_ERROR_FAILED
, "%s", msg
);
1123 if (! CloseHandle(hFile
))
1125 gchar
*msg
= g_win32_error_message(GetLastError());
1126 geany_debug("GetContentFromHandle: CloseHandle failed (%d)", (gint
) GetLastError());
1127 g_set_error(error
, G_SPAWN_ERROR
, G_FILE_ERROR_FAILED
, "%s", msg
);
1133 buffer
[filesize
] = '\0';
1139 gchar
*win32_expand_environment_variables(const gchar
*str
)
1141 gchar expCmdline
[32768]; /* 32768 is the limit for ExpandEnvironmentStrings() */
1143 if (ExpandEnvironmentStrings((LPCTSTR
) str
, (LPTSTR
) expCmdline
, sizeof(expCmdline
)) != 0)
1144 return g_strdup(expCmdline
);
1146 return g_strdup(str
);
1150 static gboolean
CreateChildProcess(geany_win32_spawn
*gw_spawn
, TCHAR
*szCmdline
,
1151 const TCHAR
*dir
, GError
**error
)
1153 PROCESS_INFORMATION piProcInfo
;
1154 STARTUPINFOW siStartInfo
;
1155 BOOL bFuncRetn
= FALSE
;
1156 gchar
*expandedCmdline
;
1157 wchar_t w_commandline
[CMDSIZE
];
1158 wchar_t w_dir
[MAX_PATH
];
1160 /* Set up members of the PROCESS_INFORMATION structure. */
1161 ZeroMemory(&piProcInfo
, sizeof(PROCESS_INFORMATION
));
1163 /* Set up members of the STARTUPINFO structure.*/
1164 ZeroMemory(&siStartInfo
, sizeof(STARTUPINFO
));
1166 siStartInfo
.cb
= sizeof(STARTUPINFO
);
1167 siStartInfo
.hStdError
= gw_spawn
->hChildStderrWr
;
1168 siStartInfo
.hStdOutput
= gw_spawn
->hChildStdoutWr
;
1169 siStartInfo
.hStdInput
= gw_spawn
->hChildStdinRd
;
1170 siStartInfo
.dwFlags
|= STARTF_USESTDHANDLES
;
1172 /* Expand environment variables like %blah%. */
1173 expandedCmdline
= win32_expand_environment_variables(szCmdline
);
1175 MultiByteToWideChar(CP_UTF8
, 0, expandedCmdline
, -1, w_commandline
, sizeof(w_commandline
));
1176 MultiByteToWideChar(CP_UTF8
, 0, dir
, -1, w_dir
, sizeof(w_dir
));
1178 /* Create the child process. */
1179 bFuncRetn
= CreateProcessW(NULL
,
1180 w_commandline
, /* command line */
1181 NULL
, /* process security attributes */
1182 NULL
, /* primary thread security attributes */
1183 TRUE
, /* handles are inherited */
1184 CREATE_NO_WINDOW
, /* creation flags */
1185 NULL
, /* use parent's environment */
1186 w_dir
, /* use parent's current directory */
1187 &siStartInfo
, /* STARTUPINFO pointer */
1188 &piProcInfo
); /* receives PROCESS_INFORMATION */
1190 g_free(expandedCmdline
);
1194 gchar
*msg
= g_win32_error_message(GetLastError());
1195 geany_debug("CreateChildProcess: CreateProcess failed (%s)", msg
);
1196 g_set_error(error
, G_SPAWN_ERROR
, G_SPAWN_ERROR_FAILED
, "%s", msg
);
1205 /* FIXME: this seems to timeout when there are many lines
1206 * to read - maybe because the child's pipe is full */
1207 for (i
= 0; i
< 2 &&
1208 WaitForSingleObject(piProcInfo
.hProcess
, ms
) == WAIT_TIMEOUT
; i
++)
1210 ui_set_statusbar(FALSE
, _("Process timed out after %.02f s!"), ms
/ 1000.0F
);
1211 geany_debug("CreateChildProcess: timed out");
1212 TerminateProcess(piProcInfo
.hProcess
, WAIT_TIMEOUT
); /* NOTE: This will not kill grandkids. */
1215 if (!GetExitCodeProcess(piProcInfo
.hProcess
, &gw_spawn
->dwExitCode
))
1217 gchar
*msg
= g_win32_error_message(GetLastError());
1218 geany_debug("GetExitCodeProcess failed: %s", msg
);
1219 g_set_error(error
, G_SPAWN_ERROR
, G_FILE_ERROR_FAILED
, "%s", msg
);
1222 CloseHandle(piProcInfo
.hProcess
);
1223 CloseHandle(piProcInfo
.hThread
);
1230 static VOID
ReadFromPipe(HANDLE hRead
, HANDLE hWrite
, HANDLE hFile
, GError
**error
)
1232 DWORD dwRead
, dwWritten
;
1233 CHAR chBuf
[BUFSIZE
];
1235 /* Close the write end of the pipe before reading from the
1236 read end of the pipe. */
1237 if (! CloseHandle(hWrite
))
1239 gchar
*msg
= g_win32_error_message(GetLastError());
1240 geany_debug("ReadFromPipe: Closing handle failed");
1241 g_set_error(error
, G_SPAWN_ERROR
, G_FILE_ERROR_PIPE
, "%s", msg
);
1246 /* Read output from the child process, and write to parent's STDOUT. */
1249 if (! ReadFile(hRead
, chBuf
, BUFSIZE
, &dwRead
, NULL
) || dwRead
== 0)
1252 if (! WriteFile(hFile
, chBuf
, dwRead
, &dwWritten
, NULL
))
1258 static HANDLE
GetTempFileHandle(GError
**error
)
1261 DWORD dwBufSize
= BUFSIZE
;
1263 TCHAR szTempName
[BUFSIZE
];
1264 TCHAR lpPathBuffer
[BUFSIZE
];
1268 /* Get the temp path. */
1269 dwRetVal
= GetTempPath(dwBufSize
, /* length of the buffer*/
1270 lpPathBuffer
); /* buffer for path */
1272 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1274 gchar
*msg
= g_win32_error_message(GetLastError());
1275 geany_debug("GetTempFileHandle: GetTempPath failed (%d)", (gint
) GetLastError());
1276 g_set_error(error
, G_SPAWN_ERROR
, G_FILE_ERROR
, "%s", msg
);
1281 /* Create a temporary file for STDOUT. */
1282 uRetVal
= GetTempFileName(lpPathBuffer
, /* directory for tmp files */
1283 TEXT("GEANY_VCDIFF_"), /* temp file name prefix */
1284 0, /* create unique name */
1285 szTempName
); /* buffer for name */
1288 gchar
*msg
= g_win32_error_message(GetLastError());
1289 geany_debug("GetTempFileName failed (%d)", (gint
) GetLastError());
1290 g_set_error(error
, G_SPAWN_ERROR
, G_FILE_ERROR
, "%s", msg
);
1295 hTempFile
= CreateFile((LPTSTR
) szTempName
, /* file name */
1296 GENERIC_READ
| GENERIC_WRITE
, /* open r-w */
1297 0, /* do not share */
1298 NULL
, /* default security */
1299 CREATE_ALWAYS
, /* overwrite existing */
1300 FILE_ATTRIBUTE_NORMAL
,/* normal file */
1301 NULL
); /* no template */
1303 if (hTempFile
== INVALID_HANDLE_VALUE
)
1305 gchar
*msg
= g_win32_error_message(GetLastError());
1306 geany_debug("GetTempFileHandle: Second CreateFile failed (%d)", (gint
) GetLastError());
1307 g_set_error(error
, G_SPAWN_ERROR
, G_FILE_ERROR
, "%s", msg
);
1315 /* From GDK (they got it from MS Knowledge Base article Q130698) */
1316 static gboolean
resolve_link(HWND hWnd
, wchar_t *link
, gchar
**lpszPath
)
1318 WIN32_FILE_ATTRIBUTE_DATA wfad
;
1320 IShellLinkW
*pslW
= NULL
;
1321 IPersistFile
*ppf
= NULL
;
1322 LPVOID pslWV
= NULL
;
1325 /* Check if the file is empty first because IShellLink::Resolve for some reason succeeds
1326 * with an empty file and returns an empty "link target". (#524151) */
1327 if (!GetFileAttributesExW(link
, GetFileExInfoStandard
, &wfad
) ||
1328 (wfad
.nFileSizeHigh
== 0 && wfad
.nFileSizeLow
== 0))
1333 /* Assume failure to start with: */
1338 hres
= CoCreateInstance(
1339 &CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
, &IID_IShellLinkW
, &pslWV
);
1341 if (SUCCEEDED(hres
))
1343 /* The IShellLink interface supports the IPersistFile interface.
1344 * Get an interface pointer to it. */
1345 pslW
= (IShellLinkW
*) pslWV
;
1346 hres
= pslW
->lpVtbl
->QueryInterface(pslW
, &IID_IPersistFile
, &ppfV
);
1349 if (SUCCEEDED(hres
))
1351 /* Load the file. */
1352 ppf
= (IPersistFile
*) ppfV
;
1353 hres
= ppf
->lpVtbl
->Load(ppf
, link
, STGM_READ
);
1356 if (SUCCEEDED(hres
))
1358 /* Resolve the link by calling the Resolve() interface function. */
1359 hres
= pslW
->lpVtbl
->Resolve(pslW
, hWnd
, SLR_ANY_MATCH
| SLR_NO_UI
);
1362 if (SUCCEEDED(hres
))
1364 wchar_t wtarget
[MAX_PATH
];
1366 hres
= pslW
->lpVtbl
->GetPath(pslW
, wtarget
, MAX_PATH
, NULL
, 0);
1367 if (SUCCEEDED(hres
))
1368 *lpszPath
= g_utf16_to_utf8(wtarget
, -1, NULL
, NULL
, NULL
);
1372 ppf
->lpVtbl
->Release(ppf
);
1375 pslW
->lpVtbl
->Release(pslW
);
1377 return SUCCEEDED(hres
);
1381 /* Checks whether file_name is a Windows shortcut. file_name is expected in UTF-8 encoding.
1382 * If file_name is a Windows shortcut, it returns the target in UTF-8 encoding.
1383 * If it is not a shortcut, it returns a newly allocated copy of file_name. */
1384 gchar
*win32_get_shortcut_target(const gchar
*file_name
)
1387 wchar_t *wfilename
= g_utf8_to_utf16(file_name
, -1, NULL
, NULL
, NULL
);
1389 resolve_link(GDK_WINDOW_HWND(gtk_widget_get_window(main_widgets
.window
)), wfilename
, &path
);
1393 return g_strdup(file_name
);
1399 void win32_set_working_directory(const gchar
*dir
)
1401 SetCurrentDirectory(dir
);
1405 gchar
*win32_get_installation_dir(void)
1407 return g_win32_get_package_installation_directory_of_module(NULL
);