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.
31 #define WIN32_LEAN_AND_MEAN
43 #include <gdk/gdkwin32.h>
51 #include "sciwrappers.h"
53 #include "filetypes.h"
60 struct _geany_win32_spawn
64 HANDLE hChildStdoutRd
;
65 HANDLE hChildStdoutWr
;
66 HANDLE hChildStderrRd
;
67 HANDLE hChildStderrWr
;
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)
87 static wchar_t title
[4096];
88 GString
*str
= g_string_sized_new(100);
89 GString
*all_patterns
= g_string_sized_new(100);
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
))
113 tmp
= g_strjoinv(";", ft
->pattern
);
114 g_string_append_printf(str
, "%s\t%s\t", ft
->title
, tmp
);
117 g_string_append_c(str
, '\t'); /* the final \0 byte to mark the end of the string */
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
));
132 static wchar_t *get_file_filter_all_files(void)
135 static wchar_t title
[4096];
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
));
151 static wchar_t *get_filters(gboolean project_files
)
155 static wchar_t title
[1024];
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
);
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
));
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
];
188 if (g_file_test(utf8_filename
, G_FILE_TEST_IS_DIR
))
189 result
= (gchar
*) utf8_filename
;
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
)
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
)
210 case BFFM_INITIALIZED
:
212 SendMessageW(hwnd
, BFFM_SETSELECTIONW
, TRUE
, pData
);
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
);
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
)
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
));
244 parent
= main_widgets
.window
;
246 memset(&bi
, 0, sizeof bi
);
247 bi
.hwndOwner
= GDK_WINDOW_HWND(gtk_widget_get_window(parent
));
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 ;-) */
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? */
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
)
282 wchar_t fname
[MAX_PATH
];
283 wchar_t w_title
[512];
288 MultiByteToWideChar(CP_UTF8
, 0, title
, -1, w_title
, sizeof(w_title
));
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
;
298 of
.lStructSize
= sizeof of
;
300 of
.hwndOwner
= GDK_WINDOW_HWND(gtk_widget_get_window(parent
));
301 of
.lpstrFilter
= get_filters(project_file_filter
);
303 of
.lpstrCustomFilter
= NULL
;
305 of
.lpstrFile
= fname
;
306 of
.lpstrInitialDir
= get_dir_for_path(initial_dir
);
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
);
319 if (CommDlgExtendedError())
322 error
= g_strdup_printf("File dialog box error (%x)", (int)CommDlgExtendedError());
323 win32_message_dialog(NULL
, GTK_MESSAGE_ERROR
, error
);
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
);
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
)
344 wchar_t fname
[MAX_PATH
];
345 wchar_t w_dir
[MAX_PATH
];
346 wchar_t w_title
[512];
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
;
360 of
.lStructSize
= sizeof of
;
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
;
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
);
379 if (CommDlgExtendedError())
382 g_snprintf(error
, sizeof error
, "File dialog box error (%x)", (int)CommDlgExtendedError());
383 win32_message_dialog(NULL
, GTK_MESSAGE_ERROR
, error
);
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
);
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
);
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
);
418 return (retval
!= 0);
422 gchar
*win32_show_document_save_as_dialog(GtkWindow
*parent
, const gchar
*title
,
423 const gchar
*initial_file
)
428 wchar_t w_file
[MAX_PATH
];
429 wchar_t w_title
[512];
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
;
443 of
.lStructSize
= sizeof of
;
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
;
451 of
.lpstrFile
= w_file
;
453 of
.lpstrFileTitle
= NULL
;
454 of
.lpstrTitle
= w_title
;
455 of
.lpstrDefExt
= L
"";
456 of
.Flags
= OFN_FILEMUSTEXIST
| OFN_EXPLORER
;
457 retval
= GetSaveFileNameW(&of
);
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
);
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
)
484 wchar_t w_file
[MAX_PATH
];
485 wchar_t w_title
[512];
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
;
499 of
.lStructSize
= sizeof of
;
501 of
.hwndOwner
= GDK_WINDOW_HWND(gtk_widget_get_window(GTK_WIDGET(parent
)));
503 of
.lpstrFile
= w_file
;
505 of
.lpstrFileTitle
= NULL
;
506 of
.lpstrTitle
= w_title
;
507 of
.lpstrDefExt
= L
"";
508 of
.Flags
= OFN_FILEMUSTEXIST
| OFN_EXPLORER
;
509 retval
= GetOpenFileNameW(&of
);
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
);
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)
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
));
542 /* support CF_APPLY? */
543 cf
.Flags
= CF_NOSCRIPTSEL
| CF_FORCEFONTEXIST
| CF_INITTOLOGFONTSTRUCT
| CF_SCREENFONTS
;
545 retval
= ChooseFont(&cf
);
549 gchar
*editorfont
= g_strdup_printf("%s %d", lf
.lfFaceName
, (cf
.iPointSize
/ 10));
550 ui_set_editor_font(editorfont
);
556 void win32_show_color_dialog(const gchar
*colour
)
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
);
586 void win32_show_pref_file_dialog(GtkEntry
*item
)
590 wchar_t fname
[MAX_PATH
];
592 gchar
**field
, *filename
;
596 /* cut the options from the command line */
597 field
= g_strsplit(gtk_entry_get_text(GTK_ENTRY(item
)), " ", 2);
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
));
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
;
613 of
.lStructSize
= sizeof of
;
615 of
.hwndOwner
= GDK_WINDOW_HWND(gtk_widget_get_window(ui_widgets
.prefs_dialog
));
617 of
.lpstrFilter
= get_filters(FALSE
);
618 of
.lpstrCustomFilter
= NULL
;
621 of
.lpstrFile
= fname
;
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
);
633 if (CommDlgExtendedError())
636 g_snprintf(error
, sizeof error
, "File dialog box error (%x)", (int)CommDlgExtendedError());
637 win32_message_dialog(NULL
, GTK_MESSAGE_ERROR
, error
);
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
);
652 filename
= g_strdup(tmp
);
654 gtk_entry_set_text(GTK_ENTRY(item
), filename
);
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
)
670 HWND parent_hwnd
= NULL
;
671 static wchar_t w_msg
[512];
672 static wchar_t w_title
[512];
676 case GTK_MESSAGE_ERROR
:
678 t
= MB_OK
| MB_ICONERROR
;
682 case GTK_MESSAGE_QUESTION
:
684 t
= MB_YESNO
| MB_ICONQUESTION
;
685 title
= _("Question");
688 case GTK_MESSAGE_WARNING
:
690 t
= MB_OK
| MB_ICONWARNING
;
691 title
= _("Warning");
696 t
= MB_OK
| MB_ICONINFORMATION
;
697 title
= _("Information");
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
));
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
)
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)
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)
740 if (strchr(uri
, ':') != NULL
)
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
)
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;
766 CONSOLE_SCREEN_BUFFER_INFO coninfo
;
769 /* allocate a console for this app */
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");
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");
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" );
796 setvbuf(stdin
, NULL
, _IONBF
, 0);
800 void win32_init_debug_code(void)
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)
816 DWORD size
= sizeof(hostname
);
818 if (GetComputerName(hostname
, &size
))
819 return g_strdup(hostname
);
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
};
837 SECURITY_ATTRIBUTES saAttr
;
839 geany_win32_spawn gw_spawn
;
842 HANDLE hStdoutTempFile
= NULL
;
843 HANDLE hStderrTempFile
= NULL
;
845 gchar
*stdout_content
= NULL
;
846 gchar
*stderr_content
= NULL
;
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
);
861 g_snprintf(cmdline
, sizeof(cmdline
), "\"%s\"", buffer
);
863 g_strlcpy(cmdline
, argv
[0], sizeof(cmdline
));
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);*/
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());
881 *error
= g_error_new(G_SPAWN_ERROR
, G_FILE_ERROR
, "%s", msg
);
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());
895 *error
= g_error_new(G_SPAWN_ERROR
, G_FILE_ERROR
, "%s", msg
);
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());
917 *error
= g_error_new(G_SPAWN_ERROR
, G_FILE_ERROR_PIPE
, "%s", msg
);
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");
931 *error
= g_error_new(G_SPAWN_ERROR
, G_FILE_ERROR_PIPE
, "%s", msg
);
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");
945 *error
= g_error_new(G_SPAWN_ERROR
, G_FILE_ERROR_PIPE
, "%s", msg
);
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
);
957 *exit_status
= gw_spawn
.dwExitCode
;
962 geany_debug("win32_spawn: Create process failed");
966 /* Read from pipe that is the standard output for child process. */
969 ReadFromPipe(gw_spawn
.hChildStdoutRd
, gw_spawn
.hChildStdoutWr
, hStdoutTempFile
, error
);
970 if (! GetContentFromHandle(hStdoutTempFile
, &stdout_content
, error
))
974 *std_out
= stdout_content
;
979 ReadFromPipe(gw_spawn
.hChildStderrRd
, gw_spawn
.hChildStderrWr
, hStderrTempFile
, error
);
980 if (! GetContentFromHandle(hStderrTempFile
, &stderr_content
, error
))
984 *std_err
= stderr_content
;
990 static gboolean
GetContentFromHandle(HANDLE hFile
, gchar
**content
, GError
**error
)
996 filesize
= GetFileSize(hFile
, NULL
);
1003 buffer
= g_malloc(filesize
+ 1);
1006 gchar
*msg
= g_win32_error_message(GetLastError());
1007 geany_debug("GetContentFromHandle: Alloc failed");
1009 *error
= g_error_new(G_SPAWN_ERROR
, G_SPAWN_ERROR
, "%s", msg
);
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");
1020 *error
= g_error_new(G_SPAWN_ERROR
, G_FILE_ERROR_FAILED
, "%s", msg
);
1025 if (! CloseHandle(hFile
))
1027 gchar
*msg
= g_win32_error_message(GetLastError());
1028 geany_debug("GetContentFromHandle: CloseHandle failed (%d)", (gint
) GetLastError());
1030 *error
= g_error_new(G_SPAWN_ERROR
, G_FILE_ERROR_FAILED
, "%s", msg
);
1036 buffer
[filesize
] = '\0';
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
);
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
);
1097 gchar
*msg
= g_win32_error_message(GetLastError());
1098 geany_debug("CreateChildProcess: CreateProcess failed (%s)", msg
);
1100 *error
= g_error_new(G_SPAWN_ERROR
, G_SPAWN_ERROR_FAILED
, "%s", msg
);
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
);
1119 *error
= g_error_new(G_SPAWN_ERROR
, G_FILE_ERROR_FAILED
, "%s", msg
);
1122 CloseHandle(piProcInfo
.hProcess
);
1123 CloseHandle(piProcInfo
.hThread
);
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");
1142 *error
= g_error_new(G_SPAWN_ERROR
, G_FILE_ERROR_PIPE
, "%s", msg
);
1147 /* Read output from the child process, and write to parent's STDOUT. */
1150 if (! ReadFile(hRead
, chBuf
, BUFSIZE
, &dwRead
, NULL
) || dwRead
== 0)
1153 if (! WriteFile(hFile
, chBuf
, dwRead
, &dwWritten
, NULL
))
1159 static HANDLE
GetTempFileHandle(GError
**error
)
1162 DWORD dwBufSize
= BUFSIZE
;
1164 TCHAR szTempName
[BUFSIZE
];
1165 TCHAR lpPathBuffer
[BUFSIZE
];
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());
1178 *error
= g_error_new(G_SPAWN_ERROR
, G_FILE_ERROR
, "%s", msg
);
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 */
1190 gchar
*msg
= g_win32_error_message(GetLastError());
1191 geany_debug("GetTempFileName failed (%d)", (gint
) GetLastError());
1193 *error
= g_error_new(G_SPAWN_ERROR
, G_FILE_ERROR
, "%s", msg
);
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());
1211 *error
= g_error_new(G_SPAWN_ERROR
, G_FILE_ERROR
, "%s", msg
);
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
;
1224 IShellLinkW
*pslW
= NULL
;
1225 IPersistFile
*ppf
= NULL
;
1226 LPVOID pslWV
= 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))
1237 /* Assume failure to start with: */
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
);
1276 ppf
->lpVtbl
->Release(ppf
);
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
)
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
);
1297 return g_strdup(file_name
);
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
);