Add detection of PKGBUILD files as Shell scripts
[geany-mirror.git] / src / main.c
blobf95860738587ccb804784750811d842d9b93dc93
1 /*
2 * main.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.
22 /**
23 * @file: main.h
24 * Main program-related commands.
25 * Handles program initialization and cleanup.
28 #include <signal.h>
29 #include <time.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <errno.h>
33 #include <string.h>
34 #include <stdlib.h>
36 #include "geany.h"
37 #include <glib/gstdio.h>
39 #ifdef HAVE_LOCALE_H
40 # include <locale.h>
41 #endif
43 #include "main.h"
44 #include "prefix.h"
45 #include "prefs.h"
46 #include "support.h"
47 #include "callbacks.h"
48 #include "log.h"
49 #include "ui_utils.h"
50 #include "utils.h"
51 #include "document.h"
52 #include "filetypes.h"
53 #include "keyfile.h"
54 #include "win32.h"
55 #include "msgwindow.h"
56 #include "dialogs.h"
57 #include "templates.h"
58 #include "encodings.h"
59 #include "sidebar.h"
60 #include "notebook.h"
61 #include "keybindings.h"
62 #include "editor.h"
63 #include "search.h"
64 #include "build.h"
65 #include "highlighting.h"
66 #include "symbols.h"
67 #include "project.h"
68 #include "tools.h"
69 #include "navqueue.h"
70 #include "plugins.h"
71 #include "printing.h"
72 #include "toolbar.h"
73 #include "geanyobject.h"
75 #ifdef HAVE_SOCKET
76 # include "socket.h"
77 #endif
79 #ifdef HAVE_VTE
80 # include "vte.h"
81 #endif
83 #ifndef N_
84 # define N_(String) (String)
85 #endif
88 GeanyApp *app;
89 gboolean ignore_callback; /* hack workaround for GTK+ toggle button callback problem */
91 GeanyStatus main_status;
92 CommandLineOptions cl_options; /* fields initialised in parse_command_line_options */
95 static const gchar geany_lib_versions[] = "GTK %u.%u.%u, GLib %u.%u.%u";
97 static gboolean want_plugins;
99 /* command-line options */
100 static gboolean verbose_mode = FALSE;
101 static gboolean ignore_global_tags = FALSE;
102 static gboolean no_msgwin = FALSE;
103 static gboolean show_version = FALSE;
104 static gchar *alternate_config = NULL;
105 #ifdef HAVE_VTE
106 static gboolean no_vte = FALSE;
107 static gchar *lib_vte = NULL;
108 #endif
109 static gboolean generate_tags = FALSE;
110 static gboolean no_preprocessing = FALSE;
111 static gboolean ft_names = FALSE;
112 static gboolean print_prefix = FALSE;
113 #ifdef HAVE_PLUGINS
114 static gboolean no_plugins = FALSE;
115 #endif
116 static gboolean dummy = FALSE;
118 /* in alphabetical order of short options */
119 static GOptionEntry entries[] =
121 { "column", 0, 0, G_OPTION_ARG_INT, &cl_options.goto_column, N_("Set initial column number for the first opened file (useful in conjunction with --line)"), NULL },
122 { "config", 'c', 0, G_OPTION_ARG_FILENAME, &alternate_config, N_("Use an alternate configuration directory"), NULL },
123 { "ft-names", 0, 0, G_OPTION_ARG_NONE, &ft_names, N_("Print internal filetype names"), NULL },
124 { "generate-tags", 'g', 0, G_OPTION_ARG_NONE, &generate_tags, N_("Generate global tags file (see documentation)"), NULL },
125 { "no-preprocessing", 'P', 0, G_OPTION_ARG_NONE, &no_preprocessing, N_("Don't preprocess C/C++ files when generating tags"), NULL },
126 #ifdef HAVE_SOCKET
127 { "new-instance", 'i', 0, G_OPTION_ARG_NONE, &cl_options.new_instance, N_("Don't open files in a running instance, force opening a new instance"), NULL },
128 { "socket-file", 0, 0, G_OPTION_ARG_FILENAME, &cl_options.socket_filename, N_("Use this socket filename for communication with a running Geany instance"), NULL },
129 { "list-documents", 0, 0, G_OPTION_ARG_NONE, &cl_options.list_documents, N_("Return a list of open documents in a running Geany instance"), NULL },
130 #endif
131 { "line", 'l', 0, G_OPTION_ARG_INT, &cl_options.goto_line, N_("Set initial line number for the first opened file"), NULL },
132 { "no-msgwin", 'm', 0, G_OPTION_ARG_NONE, &no_msgwin, N_("Don't show message window at startup"), NULL },
133 { "no-ctags", 'n', 0, G_OPTION_ARG_NONE, &ignore_global_tags, N_("Don't load auto completion data (see documentation)"), NULL },
134 #ifdef HAVE_PLUGINS
135 { "no-plugins", 'p', 0, G_OPTION_ARG_NONE, &no_plugins, N_("Don't load plugins"), NULL },
136 #endif
137 { "print-prefix", 0, 0, G_OPTION_ARG_NONE, &print_prefix, N_("Print Geany's installation prefix"), NULL },
138 { "read-only", 'r', 0, G_OPTION_ARG_NONE, &cl_options.readonly, N_("Open all FILES in read-only mode (see documention)"), NULL },
139 { "no-session", 's', G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &cl_options.load_session, N_("Don't load the previous session's files"), NULL },
140 #ifdef HAVE_VTE
141 { "no-terminal", 't', 0, G_OPTION_ARG_NONE, &no_vte, N_("Don't load terminal support"), NULL },
142 { "vte-lib", 0, 0, G_OPTION_ARG_FILENAME, &lib_vte, N_("Filename of libvte.so"), NULL },
143 #endif
144 { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose_mode, N_("Be verbose"), NULL },
145 { "version", 'V', 0, G_OPTION_ARG_NONE, &show_version, N_("Show version and exit"), NULL },
146 { "dummy", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_NONE, &dummy, NULL, NULL }, /* for +NNN line number arguments */
147 { NULL, 0, 0, 0, NULL, NULL, NULL }
151 static void setup_window_position(void)
153 /* interprets the saved window geometry */
154 if (!prefs.save_winpos)
155 return;
157 if (ui_prefs.geometry[0] != -1 && ui_prefs.geometry[1] != -1)
158 gtk_window_move(GTK_WINDOW(main_widgets.window),
159 ui_prefs.geometry[0], ui_prefs.geometry[1]);
161 if (ui_prefs.geometry[2] != -1 && ui_prefs.geometry[3] != -1)
162 gtk_window_set_default_size(GTK_WINDOW(main_widgets.window),
163 ui_prefs.geometry[2], ui_prefs.geometry[3]);
165 if (ui_prefs.geometry[4] == 1)
166 gtk_window_maximize(GTK_WINDOW(main_widgets.window));
170 /* special things for the initial setup of the checkboxes and related stuff
171 * an action on a setting is only performed if the setting is not equal to the program default
172 * (all the following code is not perfect but it works for the moment) */
173 static void apply_settings(void)
175 ui_update_fold_items();
177 /* toolbar, message window and sidebar are by default visible, so don't change it if it is true */
178 toolbar_show_hide();
179 if (! ui_prefs.msgwindow_visible)
181 ignore_callback = TRUE;
182 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(ui_lookup_widget(main_widgets.window, "menu_show_messages_window1")), FALSE);
183 gtk_widget_hide(ui_lookup_widget(main_widgets.window, "scrolledwindow1"));
184 ignore_callback = FALSE;
186 if (! ui_prefs.sidebar_visible)
188 ignore_callback = TRUE;
189 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(ui_lookup_widget(main_widgets.window, "menu_show_sidebar1")), FALSE);
190 ignore_callback = FALSE;
193 toolbar_apply_settings();
194 toolbar_update_ui();
196 ui_update_view_editor_menu_items();
198 /* hide statusbar if desired */
199 if (! interface_prefs.statusbar_visible)
201 gtk_widget_hide(ui_widgets.statusbar);
204 /* set the tab placements of the notebooks */
205 gtk_notebook_set_tab_pos(GTK_NOTEBOOK(main_widgets.notebook), interface_prefs.tab_pos_editor);
206 gtk_notebook_set_tab_pos(GTK_NOTEBOOK(msgwindow.notebook), interface_prefs.tab_pos_msgwin);
207 gtk_notebook_set_tab_pos(GTK_NOTEBOOK(main_widgets.sidebar_notebook), interface_prefs.tab_pos_sidebar);
209 /* whether to show notebook tabs or not */
210 gtk_notebook_set_show_tabs(GTK_NOTEBOOK(main_widgets.notebook), interface_prefs.show_notebook_tabs);
212 #ifdef HAVE_VTE
213 if (! vte_info.have_vte)
214 #endif
216 gtk_widget_set_sensitive(
217 ui_lookup_widget(main_widgets.window, "send_selection_to_vte1"), FALSE);
220 if (interface_prefs.sidebar_pos != GTK_POS_LEFT)
221 ui_swap_sidebar_pos();
223 gtk_orientable_set_orientation(GTK_ORIENTABLE(ui_lookup_widget(main_widgets.window, "vpaned1")),
224 interface_prefs.msgwin_orientation);
228 static void main_init(void)
230 /* add our icon path in case we aren't installed in the system prefix */
231 gchar *path;
232 #ifdef G_OS_WIN32
233 gchar *install_dir = win32_get_installation_dir();
234 path = g_build_filename(install_dir, "share", "icons", NULL);
235 g_free(install_dir);
236 #else
237 path = g_build_filename(GEANY_DATADIR, "icons", NULL);
238 #endif
239 gtk_icon_theme_append_search_path(gtk_icon_theme_get_default(), path);
240 g_free(path);
242 /* inits */
243 ui_init_stock_items();
245 ui_init_builder();
247 main_widgets.window = NULL;
248 app->project = NULL;
249 ui_widgets.open_fontsel = NULL;
250 ui_widgets.open_colorsel = NULL;
251 ui_widgets.prefs_dialog = NULL;
252 main_status.main_window_realized = FALSE;
253 file_prefs.tab_order_ltr = FALSE;
254 file_prefs.tab_order_beside = FALSE;
255 main_status.quitting = FALSE;
256 ignore_callback = FALSE;
257 app->tm_workspace = tm_get_workspace();
258 ui_prefs.recent_queue = g_queue_new();
259 ui_prefs.recent_projects_queue = g_queue_new();
260 main_status.opening_session_files = FALSE;
262 main_widgets.window = create_window1();
264 /* add recent projects to the Project menu */
265 ui_widgets.recent_projects_menuitem = ui_lookup_widget(main_widgets.window, "recent_projects1");
266 ui_widgets.recent_projects_menu_menubar = gtk_menu_new();
267 gtk_menu_item_set_submenu(GTK_MENU_ITEM(ui_widgets.recent_projects_menuitem),
268 ui_widgets.recent_projects_menu_menubar);
270 /* store important pointers for later reference */
271 main_widgets.toolbar = toolbar_init();
272 main_widgets.sidebar_notebook = ui_lookup_widget(main_widgets.window, "notebook3");
273 main_widgets.notebook = ui_lookup_widget(main_widgets.window, "notebook1");
274 main_widgets.editor_menu = create_edit_menu1();
275 main_widgets.tools_menu = ui_lookup_widget(main_widgets.window, "tools1_menu");
276 main_widgets.message_window_notebook = ui_lookup_widget(main_widgets.window, "notebook_info");
277 main_widgets.project_menu = ui_lookup_widget(main_widgets.window, "menu_project1_menu");
279 ui_widgets.toolbar_menu = create_toolbar_popup_menu1();
280 ui_init();
282 /* set widget names for matching with .gtkrc-2.0 */
283 gtk_widget_set_name(main_widgets.window, "GeanyMainWindow");
284 gtk_widget_set_name(ui_widgets.toolbar_menu, "GeanyToolbarMenu");
285 gtk_widget_set_name(main_widgets.editor_menu, "GeanyEditMenu");
286 gtk_widget_set_name(ui_lookup_widget(main_widgets.window, "menubar1"), "GeanyMenubar");
287 gtk_widget_set_name(main_widgets.toolbar, "GeanyToolbar");
289 gtk_window_set_default_size(GTK_WINDOW(main_widgets.window),
290 GEANY_WINDOW_DEFAULT_WIDTH, GEANY_WINDOW_DEFAULT_HEIGHT);
294 const gchar *main_get_version_string(void)
296 static gchar full[] = VERSION " (git >= " REVISION ")";
298 if (utils_str_equal(REVISION, "-1"))
299 return VERSION;
300 else
301 return full;
305 /* get the full file path of a command-line argument
306 * N.B. the result should be freed and may contain '/../' or '/./ ' */
307 gchar *main_get_argv_filename(const gchar *filename)
309 gchar *result;
311 if (g_path_is_absolute(filename) || utils_is_uri(filename))
312 result = g_strdup(filename);
313 else
315 /* use current dir */
316 gchar *cur_dir = g_get_current_dir();
318 result = g_strjoin(
319 G_DIR_SEPARATOR_S, cur_dir, filename, NULL);
320 g_free(cur_dir);
322 return result;
326 /* get a :line:column specifier from the end of a filename (if present),
327 * return the line/column values, and remove the specifier from the string
328 * (Note that *line and *column must both be set to -1 initially) */
329 static void get_line_and_column_from_filename(gchar *filename, gint *line, gint *column)
331 gsize i;
332 gint colon_count = 0;
333 gboolean have_number = FALSE;
334 gsize len;
336 g_assert(*line == -1 && *column == -1);
338 if (G_UNLIKELY(EMPTY(filename)))
339 return;
341 /* allow to open files like "test:0" */
342 if (g_file_test(filename, G_FILE_TEST_EXISTS))
343 return;
345 len = strlen(filename);
346 for (i = len - 1; i >= 1; i--)
348 gboolean is_colon = filename[i] == ':';
349 gboolean is_digit = g_ascii_isdigit(filename[i]);
351 if (! is_colon && ! is_digit)
352 break;
354 if (is_colon)
356 if (++colon_count > 1)
357 break; /* bail on 2+ colons in a row */
359 else
360 colon_count = 0;
362 if (is_digit)
363 have_number = TRUE;
365 if (is_colon && have_number)
367 gint number = atoi(&filename[i + 1]);
369 filename[i] = '\0';
370 have_number = FALSE;
372 *column = *line;
373 *line = number;
376 if (*column >= 0)
377 break; /* line and column are set, so we're done */
382 #ifdef G_OS_WIN32
383 static void change_working_directory_on_windows(const gchar *install_dir)
385 /* On Windows, change the working directory to the Geany installation path to not lock
386 * the directory of a file passed as command line argument (see bug #2626124).
387 * This also helps if plugins or other code uses relative paths to load
388 * any additional resources (e.g. share/geany-plugins/...). */
389 win32_set_working_directory(install_dir);
391 #endif
394 static void setup_paths(void)
396 gchar *data_dir;
397 gchar *doc_dir;
399 /* set paths */
400 #ifdef G_OS_WIN32
401 /* use the installation directory(the one where geany.exe is located) as the base for the
402 * documentation and data files */
403 gchar *install_dir = win32_get_installation_dir();
405 data_dir = g_build_filename(install_dir, "data", NULL); /* e.g. C:\Program Files\geany\data */
406 doc_dir = g_build_filename(install_dir, "doc", NULL);
408 change_working_directory_on_windows(install_dir);
410 g_free(install_dir);
411 #else
412 data_dir = g_build_filename(GEANY_DATADIR, "geany", NULL); /* e.g. /usr/share/geany */
413 doc_dir = g_build_filename(GEANY_DOCDIR, "html", NULL);
414 #endif
416 /* convert path names to locale encoding */
417 app->datadir = utils_get_locale_from_utf8(data_dir);
418 app->docdir = utils_get_locale_from_utf8(doc_dir);
420 g_free(data_dir);
421 g_free(doc_dir);
426 * Checks whether the main window has been realized.
427 * This is an easy indicator whether Geany is right now starting up (main window is not
428 * yet realized) or whether it has finished the startup process (main window is realized).
429 * This is because the main window is realized (i.e. actually drawn on the screen) at the
430 * end of the startup process.
432 * @note Maybe you want to use the @link pluginsignals.c @c "geany-startup-complete" signal @endlink
433 * to get notified about the completed startup process.
435 * @return @c TRUE if the Geany main window has been realized or @c FALSE otherwise.
437 * @since 0.19
439 gboolean main_is_realized(void)
441 return main_status.main_window_realized;
446 * Initialises the gettext translation system.
447 * This is a convenience function to set up gettext for internationalisation support
448 * in external plugins. You should call this function early in @ref plugin_init().
449 * If the macro HAVE_LOCALE_H is defined, @c setlocale(LC_ALL, "") is called.
450 * The codeset for the message translations is set to UTF-8.
452 * Note that this function only setups the gettext textdomain for you. You still have
453 * to adjust the build system of your plugin to get internationalisation support
454 * working properly.
456 * If you have already used @ref PLUGIN_SET_TRANSLATABLE_INFO() you
457 * don't need to call main_locale_init() again as it has already been done.
459 * @param locale_dir The location where the translation files should be searched. This is
460 * usually the @c LOCALEDIR macro, defined by the build system.
461 * E.g. @c $prefix/share/locale.
462 * Only used on non-Windows systems. On Windows, the directory is determined
463 * by @c g_win32_get_package_installation_directory().
464 * @param package The package name, usually this is the @c GETTEXT_PACKAGE macro,
465 * defined by the build system.
467 * @since 0.16
469 void main_locale_init(const gchar *locale_dir, const gchar *package)
471 gchar *l_locale_dir = NULL;
473 #ifdef HAVE_LOCALE_H
474 setlocale(LC_ALL, "");
475 #endif
477 #ifdef G_OS_WIN32
479 gchar *install_dir = win32_get_installation_dir();
480 /* e.g. C:\Program Files\geany\lib\locale */
481 l_locale_dir = g_build_filename(install_dir, "share", "locale", NULL);
482 g_free(install_dir);
484 #else
485 l_locale_dir = g_strdup(locale_dir);
486 #endif
488 bindtextdomain(package, l_locale_dir);
489 bind_textdomain_codeset(package, "UTF-8");
490 g_free(l_locale_dir);
494 static void print_filetypes(void)
496 const GSList *list, *node;
498 filetypes_init_types();
499 printf("Geany's filetype names:\n");
501 list = filetypes_get_sorted_by_name();
502 foreach_slist(node, list)
504 GeanyFiletype *ft = node->data;
506 printf("%s\n", ft->name);
508 filetypes_free_types();
512 static void wait_for_input_on_windows(void)
514 #ifdef G_OS_WIN32
515 if (verbose_mode)
517 geany_debug("Press any key to continue");
518 getchar();
520 #endif
524 static void parse_command_line_options(gint *argc, gchar ***argv)
526 GError *error = NULL;
527 GOptionContext *context;
528 gint i;
529 CommandLineOptions def_clo = {FALSE, NULL, TRUE, -1, -1, FALSE, FALSE, FALSE};
531 /* first initialise cl_options fields with default values */
532 cl_options = def_clo;
534 /* the GLib option parser can't handle the +NNN (line number) option,
535 * so we grab that here and replace it with a no-op */
536 for (i = 1; i < (*argc); i++)
538 if ((*argv)[i][0] != '+')
539 continue;
541 cl_options.goto_line = atoi((*argv)[i] + 1);
542 (*argv)[i] = "--dummy";
545 context = g_option_context_new(_("[FILES...]"));
546 g_option_context_add_main_entries(context, entries, GETTEXT_PACKAGE);
547 g_option_group_set_translation_domain(g_option_context_get_main_group(context), GETTEXT_PACKAGE);
548 g_option_context_add_group(context, gtk_get_option_group(FALSE));
549 g_option_context_parse(context, argc, argv, &error);
550 g_option_context_free(context);
552 if (error != NULL)
554 g_printerr("Geany: %s\n", error->message);
555 g_error_free(error);
556 exit(1);
559 app->debug_mode = verbose_mode;
560 if (app->debug_mode)
562 /* Since GLib 2.32 messages logged with levels INFO and DEBUG aren't output by the
563 * default log handler unless the G_MESSAGES_DEBUG environment variable contains the
564 * domain of the message or is set to the special value "all" */
565 g_setenv("G_MESSAGES_DEBUG", "all", FALSE);
568 #ifdef G_OS_WIN32
569 win32_init_debug_code();
570 #endif
572 if (show_version)
574 gchar *build_date = utils_parse_and_format_build_date(__DATE__);
576 printf(PACKAGE " %s (", main_get_version_string());
577 /* note for translators: library versions are printed after this */
578 printf(_("built on %s with "), build_date);
579 printf(geany_lib_versions,
580 GTK_MAJOR_VERSION, GTK_MINOR_VERSION, GTK_MICRO_VERSION,
581 GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
582 printf(")\n");
583 g_free(build_date);
584 wait_for_input_on_windows();
585 exit(0);
588 if (print_prefix)
590 printf("%s\n", GEANY_PREFIX);
591 printf("%s\n", GEANY_DATADIR);
592 printf("%s\n", GEANY_LIBDIR);
593 printf("%s\n", GEANY_LOCALEDIR);
594 wait_for_input_on_windows();
595 exit(0);
598 if (alternate_config)
600 geany_debug("alternate config: %s", alternate_config);
601 app->configdir = alternate_config;
603 else
605 app->configdir = g_build_filename(g_get_user_config_dir(), "geany", NULL);
608 if (generate_tags)
610 gboolean ret;
612 filetypes_init_types();
613 ret = symbols_generate_global_tags(*argc, *argv, ! no_preprocessing);
614 filetypes_free_types();
615 wait_for_input_on_windows();
616 exit(ret);
619 if (ft_names)
621 print_filetypes();
622 wait_for_input_on_windows();
623 exit(0);
626 #ifdef HAVE_SOCKET
627 socket_info.ignore_socket = cl_options.new_instance;
628 if (cl_options.socket_filename)
630 socket_info.file_name = cl_options.socket_filename;
632 #endif
634 #ifdef HAVE_VTE
635 vte_info.lib_vte = lib_vte;
636 #endif
637 cl_options.ignore_global_tags = ignore_global_tags;
639 if (! gtk_init_check(NULL, NULL))
640 { /* check whether we have a valid X display and exit if not */
641 g_printerr("Geany: cannot open display\n");
642 exit(1);
647 static gint create_config_dir(void)
649 gint saved_errno = 0;
650 gchar *conf_file = g_build_filename(app->configdir, "geany.conf", NULL);
651 gchar *filedefs_dir = g_build_filename(app->configdir, GEANY_FILEDEFS_SUBDIR, NULL);
653 gchar *templates_dir = g_build_filename(app->configdir, GEANY_TEMPLATES_SUBDIR, NULL);
655 if (! g_file_test(app->configdir, G_FILE_TEST_EXISTS))
657 #ifndef G_OS_WIN32
658 /* if we are *not* using an alternate config directory, we check whether the old one
659 * in ~/.geany still exists and try to move it */
660 if (alternate_config == NULL)
662 gchar *old_dir = g_build_filename(g_get_home_dir(), ".geany", NULL);
663 /* move the old config dir if it exists */
664 if (g_file_test(old_dir, G_FILE_TEST_EXISTS))
666 if (! dialogs_show_question_full(main_widgets.window,
667 GTK_STOCK_YES, GTK_STOCK_QUIT, _("Move it now?"),
668 "%s",
669 _("Geany needs to move your old configuration directory before starting.")))
670 exit(0);
672 if (! g_file_test(app->configdir, G_FILE_TEST_IS_DIR))
673 utils_mkdir(app->configdir, TRUE);
675 if (g_rename(old_dir, app->configdir) == 0)
677 dialogs_show_msgbox(GTK_MESSAGE_INFO,
678 _("Your configuration directory has been successfully moved from \"%s\" to \"%s\"."),
679 old_dir, app->configdir);
680 g_free(old_dir);
681 return 0;
683 else
685 dialogs_show_msgbox(GTK_MESSAGE_WARNING,
686 /* for translators: the third %s in brackets is the error message which
687 * describes why moving the dir didn't work */
688 _("Your old configuration directory \"%s\" could not be moved to \"%s\" (%s). "
689 "Please move manually the directory to the new location."),
690 old_dir, app->configdir, g_strerror(errno));
693 g_free(old_dir);
695 #endif
696 geany_debug("creating config directory %s", app->configdir);
697 saved_errno = utils_mkdir(app->configdir, TRUE);
700 if (saved_errno == 0 && ! g_file_test(conf_file, G_FILE_TEST_EXISTS))
701 { /* check whether geany.conf can be written */
702 saved_errno = utils_is_file_writable(app->configdir);
705 /* make subdir for filetype definitions */
706 if (saved_errno == 0)
708 gchar *filedefs_readme = g_build_filename(app->configdir,
709 GEANY_FILEDEFS_SUBDIR, "filetypes.README", NULL);
711 if (! g_file_test(filedefs_dir, G_FILE_TEST_EXISTS))
713 saved_errno = utils_mkdir(filedefs_dir, FALSE);
715 if (saved_errno == 0 && ! g_file_test(filedefs_readme, G_FILE_TEST_EXISTS))
717 gchar *text = g_strconcat(
718 "Copy files from ", app->datadir, " to this directory to overwrite "
719 "them. To use the defaults, just delete the file in this directory.\nFor more information read "
720 "the documentation (in ", app->docdir, G_DIR_SEPARATOR_S "index.html or visit " GEANY_HOMEPAGE ").", NULL);
721 utils_write_file(filedefs_readme, text);
722 g_free(text);
724 g_free(filedefs_readme);
727 /* make subdir for template files */
728 if (saved_errno == 0)
730 gchar *templates_readme = g_build_filename(app->configdir, GEANY_TEMPLATES_SUBDIR,
731 "templates.README", NULL);
733 if (! g_file_test(templates_dir, G_FILE_TEST_EXISTS))
735 saved_errno = utils_mkdir(templates_dir, FALSE);
737 if (saved_errno == 0 && ! g_file_test(templates_readme, G_FILE_TEST_EXISTS))
739 gchar *text = g_strconcat(
740 "There are several template files in this directory. For these templates you can use wildcards.\n\
741 For more information read the documentation (in ", app->docdir, G_DIR_SEPARATOR_S "index.html or visit " GEANY_HOMEPAGE ").",
742 NULL);
743 utils_write_file(templates_readme, text);
744 g_free(text);
746 g_free(templates_readme);
749 g_free(filedefs_dir);
750 g_free(templates_dir);
751 g_free(conf_file);
753 return saved_errno;
757 /* Returns 0 if config dir is OK. */
758 static gint setup_config_dir(void)
760 gint mkdir_result = 0;
762 /* convert configdir to locale encoding to avoid troubles */
763 SETPTR(app->configdir, utils_get_locale_from_utf8(app->configdir));
765 mkdir_result = create_config_dir();
766 if (mkdir_result != 0)
768 if (! dialogs_show_question(
769 _("Configuration directory could not be created (%s).\nThere could be some problems "
770 "using Geany without a configuration directory.\nStart Geany anyway?"),
771 g_strerror(mkdir_result)))
773 exit(0);
776 /* make configdir a real path */
777 if (g_file_test(app->configdir, G_FILE_TEST_EXISTS))
778 SETPTR(app->configdir, tm_get_real_path(app->configdir));
780 return mkdir_result;
783 /* Signal handling removed since on_exit_clicked() uses functions that are
784 * illegal in signal handlers
785 static void signal_cb(gint sig)
787 if (sig == SIGTERM)
789 on_exit_clicked(NULL, NULL);
794 /* Used for command-line arguments at startup or from socket.
795 * this will strip any :line:col filename suffix from locale_filename */
796 gboolean main_handle_filename(const gchar *locale_filename)
798 GeanyDocument *doc;
799 gint line = -1, column = -1;
800 gchar *filename;
802 g_return_val_if_fail(locale_filename, FALSE);
804 /* check whether the passed filename is an URI */
805 filename = utils_get_path_from_uri(locale_filename);
806 if (filename == NULL)
807 return FALSE;
809 get_line_and_column_from_filename(filename, &line, &column);
810 if (line >= 0)
811 cl_options.goto_line = line;
812 if (column >= 0)
813 cl_options.goto_column = column;
815 if (g_file_test(filename, G_FILE_TEST_IS_REGULAR))
817 doc = document_open_file(filename, cl_options.readonly, NULL, NULL);
818 /* add recent file manually if opening_session_files is set */
819 if (doc != NULL && main_status.opening_session_files)
820 ui_add_recent_document(doc);
821 g_free(filename);
822 return TRUE;
824 else if (file_prefs.cmdline_new_files)
825 { /* create new file with the given filename */
826 gchar *utf8_filename = utils_get_utf8_from_locale(filename);
828 doc = document_new_file(utf8_filename, NULL, NULL);
829 if (doc != NULL)
830 ui_add_recent_document(doc);
831 g_free(utf8_filename);
832 g_free(filename);
833 return TRUE;
835 g_free(filename);
836 return FALSE;
840 /* open files from command line */
841 static void open_cl_files(gint argc, gchar **argv)
843 gint i;
845 for (i = 1; i < argc; i++)
847 gchar *filename = main_get_argv_filename(argv[i]);
849 if (g_file_test(filename, G_FILE_TEST_IS_DIR))
851 g_free(filename);
852 continue;
855 #ifdef G_OS_WIN32
856 /* It seems argv elements are encoded in CP1252 on a German Windows */
857 SETPTR(filename, g_locale_to_utf8(filename, -1, NULL, NULL, NULL));
858 #endif
859 if (filename && ! main_handle_filename(filename))
861 const gchar *msg = _("Could not find file '%s'.");
863 g_printerr(msg, filename); /* also print to the terminal */
864 g_printerr("\n");
865 ui_set_statusbar(TRUE, msg, filename);
867 g_free(filename);
872 static void load_session_project_file(void)
874 gchar *locale_filename;
876 g_return_if_fail(project_prefs.session_file != NULL);
878 locale_filename = utils_get_locale_from_utf8(project_prefs.session_file);
880 if (G_LIKELY(!EMPTY(locale_filename)))
881 project_load_file(locale_filename);
883 g_free(locale_filename);
884 g_free(project_prefs.session_file); /* no longer needed */
888 static void load_settings(void)
890 configuration_load();
891 /* let cmdline options overwrite configuration settings */
892 #ifdef HAVE_VTE
893 vte_info.have_vte = (no_vte) ? FALSE : vte_info.load_vte;
894 #endif
895 if (no_msgwin)
896 ui_prefs.msgwindow_visible = FALSE;
898 #ifdef HAVE_PLUGINS
899 want_plugins = prefs.load_plugins && !no_plugins;
900 #endif
904 void main_load_project_from_command_line(const gchar *locale_filename, gboolean use_session)
906 gchar *pfile;
908 pfile = utils_get_path_from_uri(locale_filename);
909 if (pfile != NULL)
911 if (use_session)
912 project_load_file_with_session(pfile);
913 else
914 project_load_file(pfile);
916 g_free(pfile);
920 static void load_startup_files(gint argc, gchar **argv)
922 gboolean load_session = FALSE;
924 if (argc > 1 && g_str_has_suffix(argv[1], ".geany"))
926 /* project file specified: load it, but decide the session later */
927 main_load_project_from_command_line(argv[1], FALSE);
928 argc--, argv++;
929 /* force session load if using project-based session files */
930 load_session = project_prefs.project_session;
933 /* Load the default session if:
934 * 1. "Load files from the last session" is active.
935 * 2. --no-session is not specified.
936 * 3. We are a primary instance.
937 * Has no effect if a CL project is loaded and using project-based session files. */
938 if (prefs.load_session && cl_options.load_session && !cl_options.new_instance)
940 if (app->project == NULL)
941 load_session_project_file();
942 load_session = TRUE;
945 if (load_session)
947 /* load session files into tabs, as they are found in the session_files variable */
948 configuration_open_files();
950 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
952 ui_update_popup_copy_items(NULL);
953 ui_update_popup_reundo_items(NULL);
957 open_cl_files(argc, argv);
961 static gboolean send_startup_complete(gpointer data)
963 g_signal_emit_by_name(geany_object, "geany-startup-complete");
964 return FALSE;
968 static const gchar *get_locale(void)
970 const gchar *locale = "unknown";
971 #ifdef HAVE_LOCALE_H
972 locale = setlocale(LC_CTYPE, NULL);
973 #endif
974 return locale;
978 #if ! GTK_CHECK_VERSION(3, 0, 0)
979 /* This prepends our own gtkrc file to the list of RC files to be loaded by GTK at startup.
980 * This function *has* to be called before gtk_init().
982 * We have a custom RC file defining various styles we need, and we want the user to be
983 * able to override them (e.g. if they want -- or need -- other colors). Fair enough, one
984 * would simply call gtk_rc_parse() with the appropriate filename. However, the styling
985 * rules applies in the order they are loaded, then if we load our styles after GTK has
986 * loaded the user's ones we'd override them.
988 * There are 2 solutions to fix this:
989 * 1) set our styles' priority to something with lower than "user" (actually "theme"
990 * priority because rules precedence are first calculated depending on the priority
991 * no matter of how precise the rules is, so we need to override the theme).
992 * 2) prepend our custom style to GTK's list while keeping priority to user (which is the
993 * default), so it gets loaded before real user's ones and so gets overridden by them.
995 * One would normally go for 1 because it's ways simpler and requires less code: you just
996 * have to add the priorities to your styles, which is a matter of adding a few ":theme" in
997 * the RC file. However, KDE being a bitch it doesn't set the gtk-theme-name but rather
998 * directly includes the style to use in a user gtkrc file, which makes the theme have
999 * "user" priority, hence overriding our styles. So, we cannot set priorities in the RC
1000 * file if we want to support running under KDE, which pretty much leave us with no choice
1001 * but to go with solution 2, which unfortunately requires writing ugly code since GTK
1002 * don't have a gtk_rc_prepend_default_file() function. Thank you very much KDE.
1004 * Though, as a side benefit it also makes the code work with people using gtk-chtheme,
1005 * which also found it funny to include the theme in the user RC file. */
1006 static void setup_gtk2_styles(void)
1008 gchar **gtk_files = gtk_rc_get_default_files();
1009 gchar **new_files = g_malloc(sizeof *new_files * (g_strv_length(gtk_files) + 2));
1010 guint i = 0;
1012 new_files[i++] = g_build_filename(app->datadir, "geany.gtkrc", NULL);
1013 for (; *gtk_files; gtk_files++)
1014 new_files[i++] = g_strdup(*gtk_files);
1015 new_files[i] = NULL;
1017 gtk_rc_set_default_files(new_files);
1019 g_strfreev(new_files);
1021 #endif
1024 gint main(gint argc, gchar **argv)
1026 GeanyDocument *doc;
1027 gint config_dir_result;
1028 const gchar *locale;
1030 log_handlers_init();
1032 app = g_new0(GeanyApp, 1);
1033 memset(&main_status, 0, sizeof(GeanyStatus));
1034 memset(&prefs, 0, sizeof(GeanyPrefs));
1035 memset(&interface_prefs, 0, sizeof(GeanyInterfacePrefs));
1036 memset(&toolbar_prefs, 0, sizeof(GeanyToolbarPrefs));
1037 memset(&file_prefs, 0, sizeof(GeanyFilePrefs));
1038 memset(&search_prefs, 0, sizeof(GeanySearchPrefs));
1039 memset(&tool_prefs, 0, sizeof(GeanyToolPrefs));
1040 memset(&template_prefs, 0, sizeof(GeanyTemplatePrefs));
1041 memset(&ui_prefs, 0, sizeof(UIPrefs));
1042 memset(&ui_widgets, 0, sizeof(UIWidgets));
1044 setup_paths();
1045 #if ! GTK_CHECK_VERSION(3, 0, 0)
1046 setup_gtk2_styles();
1047 #endif
1048 #ifdef ENABLE_NLS
1049 main_locale_init(GEANY_LOCALEDIR, GETTEXT_PACKAGE);
1050 #endif
1051 parse_command_line_options(&argc, &argv);
1053 #if ! GLIB_CHECK_VERSION(2, 32, 0)
1054 /* Initialize GLib's thread system in case any plugins want to use it or their
1055 * dependencies (e.g. WebKit, Soup, ...). Deprecated since GLIB 2.32. */
1056 if (!g_thread_supported())
1057 g_thread_init(NULL);
1058 #endif
1060 /* removed as signal handling was wrong, see signal_cb()
1061 signal(SIGTERM, signal_cb); */
1063 #ifdef G_OS_UNIX
1064 /* ignore SIGPIPE signal for preventing sudden death of program */
1065 signal(SIGPIPE, SIG_IGN);
1066 #endif
1068 config_dir_result = setup_config_dir();
1069 #ifdef HAVE_SOCKET
1070 /* check and create (unix domain) socket for remote operation */
1071 if (! socket_info.ignore_socket)
1073 socket_info.lock_socket = -1;
1074 socket_info.lock_socket_tag = 0;
1075 socket_info.lock_socket = socket_init(argc, argv);
1076 /* Socket exists */
1077 if (socket_info.lock_socket == -2)
1079 /* Quit if filenames were sent to first instance or the list of open
1080 * documents has been sent */
1081 if (argc > 1 || cl_options.list_documents)
1083 gdk_notify_startup_complete();
1084 g_free(app->configdir);
1085 g_free(app->datadir);
1086 g_free(app->docdir);
1087 g_free(app);
1088 return 0;
1090 /* Start a new instance if no command line strings were passed */
1091 socket_info.ignore_socket = TRUE;
1092 cl_options.new_instance = TRUE;
1095 #endif
1097 locale = get_locale();
1098 geany_debug("Geany %s, %s",
1099 main_get_version_string(),
1100 locale);
1101 geany_debug(geany_lib_versions,
1102 gtk_major_version, gtk_minor_version, gtk_micro_version,
1103 glib_major_version, glib_minor_version, glib_micro_version);
1104 geany_debug("System data dir: %s", app->datadir);
1105 geany_debug("User config dir: %s", app->configdir);
1107 /* create the object so Geany signals can be connected in init() functions */
1108 geany_object = geany_object_new();
1110 /* inits */
1111 main_init();
1113 encodings_init();
1114 editor_init();
1116 /* init stash groups before loading keyfile */
1117 configuration_init();
1118 ui_init_prefs();
1119 search_init();
1120 project_init();
1121 #ifdef HAVE_PLUGINS
1122 plugins_init();
1123 #endif
1124 sidebar_init();
1125 load_settings(); /* load keyfile */
1127 msgwin_init();
1128 build_init();
1129 ui_create_insert_menu_items();
1130 ui_create_insert_date_menu_items();
1131 keybindings_init();
1132 notebook_init();
1133 filetypes_init();
1134 templates_init();
1135 navqueue_init();
1136 document_init_doclist();
1137 symbols_init();
1138 editor_snippets_init();
1140 /* registering some basic events */
1141 g_signal_connect(main_widgets.window, "delete-event", G_CALLBACK(on_exit_clicked), NULL);
1142 g_signal_connect(main_widgets.window, "window-state-event", G_CALLBACK(on_window_state_event), NULL);
1144 g_signal_connect(msgwindow.scribble, "motion-notify-event", G_CALLBACK(on_motion_event), NULL);
1146 #ifdef HAVE_VTE
1147 vte_init();
1148 #endif
1149 ui_create_recent_menus();
1151 ui_set_statusbar(TRUE, _("This is Geany %s."), main_get_version_string());
1152 if (config_dir_result != 0)
1153 ui_set_statusbar(TRUE, _("Configuration directory could not be created (%s)."),
1154 g_strerror(config_dir_result));
1156 /* apply all configuration options */
1157 apply_settings();
1159 #ifdef HAVE_PLUGINS
1160 /* load any enabled plugins before we open any documents */
1161 if (want_plugins)
1162 plugins_load_active();
1163 #endif
1165 ui_sidebar_show_hide();
1167 /* set the active sidebar page after plugins have been loaded */
1168 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.sidebar_notebook), ui_prefs.sidebar_page);
1170 /* load keybinding settings after plugins have added their groups */
1171 keybindings_load_keyfile();
1173 /* create the custom command menu after the keybindings have been loaded to have the proper
1174 * accelerator shown for the menu items */
1175 tools_create_insert_custom_command_menu_items();
1177 /* load any command line files or session files */
1178 main_status.opening_session_files = TRUE;
1179 load_startup_files(argc, argv);
1180 main_status.opening_session_files = FALSE;
1182 /* open a new file if no other file was opened */
1183 document_new_file_if_non_open();
1185 ui_document_buttons_update();
1186 ui_save_buttons_toggle(FALSE);
1188 doc = document_get_current();
1189 sidebar_select_openfiles_item(doc);
1190 build_menu_update(doc);
1191 sidebar_update_tag_list(doc, FALSE);
1193 #ifdef G_OS_WIN32
1194 /* Manually realise the main window to be able to set the position but don't show it.
1195 * We don't set the position after showing the window to avoid flickering. */
1196 gtk_widget_realize(main_widgets.window);
1197 #endif
1198 setup_window_position();
1200 /* finally show the window */
1201 document_grab_focus(doc);
1202 gtk_widget_show(main_widgets.window);
1203 main_status.main_window_realized = TRUE;
1205 configuration_apply_settings();
1207 #ifdef HAVE_SOCKET
1208 /* register the callback of socket input */
1209 if (! socket_info.ignore_socket && socket_info.lock_socket > 0)
1211 socket_info.read_ioc = g_io_channel_unix_new(socket_info.lock_socket);
1212 socket_info.lock_socket_tag = g_io_add_watch(socket_info.read_ioc,
1213 G_IO_IN | G_IO_PRI | G_IO_ERR, socket_lock_input_cb, main_widgets.window);
1215 #endif
1217 /* when we are really done with setting everything up and the main event loop is running,
1218 * tell other components, mainly plugins, that startup is complete */
1219 g_idle_add_full(G_PRIORITY_LOW, send_startup_complete, NULL, NULL);
1221 gtk_main();
1222 return 0;
1226 static void queue_free(GQueue *queue)
1228 while (! g_queue_is_empty(queue))
1230 g_free(g_queue_pop_tail(queue));
1232 g_queue_free(queue);
1236 void main_quit()
1238 geany_debug("Quitting...");
1240 #ifdef HAVE_SOCKET
1241 socket_finalize();
1242 #endif
1244 #ifdef HAVE_PLUGINS
1245 plugins_finalize();
1246 #endif
1248 navqueue_free();
1249 keybindings_free();
1250 notebook_free();
1251 highlighting_free_styles();
1252 templates_free_templates();
1253 msgwin_finalize();
1254 search_finalize();
1255 build_finalize();
1256 document_finalize();
1257 symbols_finalize();
1258 project_finalize();
1259 editor_finalize();
1260 editor_snippets_free();
1261 encodings_finalize();
1262 toolbar_finalize();
1263 sidebar_finalize();
1264 configuration_finalize();
1265 filetypes_free_types();
1266 log_finalize();
1268 tm_workspace_free(TM_WORK_OBJECT(app->tm_workspace));
1269 g_free(app->configdir);
1270 g_free(app->datadir);
1271 g_free(app->docdir);
1272 g_free(prefs.default_open_path);
1273 g_free(prefs.custom_plugin_path);
1274 g_free(ui_prefs.custom_date_format);
1275 g_free(interface_prefs.editor_font);
1276 g_free(interface_prefs.tagbar_font);
1277 g_free(interface_prefs.msgwin_font);
1278 g_free(editor_prefs.long_line_color);
1279 g_free(editor_prefs.comment_toggle_mark);
1280 g_free(editor_prefs.color_scheme);
1281 g_free(tool_prefs.context_action_cmd);
1282 g_free(template_prefs.developer);
1283 g_free(template_prefs.company);
1284 g_free(template_prefs.mail);
1285 g_free(template_prefs.initials);
1286 g_free(template_prefs.version);
1287 g_free(tool_prefs.term_cmd);
1288 g_free(tool_prefs.browser_cmd);
1289 g_free(tool_prefs.grep_cmd);
1290 g_free(printing_prefs.external_print_cmd);
1291 g_free(printing_prefs.page_header_datefmt);
1292 g_strfreev(ui_prefs.custom_commands);
1293 g_strfreev(ui_prefs.custom_commands_labels);
1295 queue_free(ui_prefs.recent_queue);
1296 queue_free(ui_prefs.recent_projects_queue);
1298 if (ui_widgets.prefs_dialog && GTK_IS_WIDGET(ui_widgets.prefs_dialog)) gtk_widget_destroy(ui_widgets.prefs_dialog);
1299 if (ui_widgets.open_fontsel && GTK_IS_WIDGET(ui_widgets.open_fontsel)) gtk_widget_destroy(ui_widgets.open_fontsel);
1300 if (ui_widgets.open_colorsel && GTK_IS_WIDGET(ui_widgets.open_colorsel)) gtk_widget_destroy(ui_widgets.open_colorsel);
1301 #ifdef HAVE_VTE
1302 if (vte_info.have_vte) vte_close();
1303 g_free(vte_info.lib_vte);
1304 g_free(vte_info.dir);
1305 #endif
1306 gtk_widget_destroy(main_widgets.window);
1308 /* destroy popup menus */
1309 if (main_widgets.editor_menu && GTK_IS_WIDGET(main_widgets.editor_menu))
1310 gtk_widget_destroy(main_widgets.editor_menu);
1311 if (ui_widgets.toolbar_menu && GTK_IS_WIDGET(ui_widgets.toolbar_menu))
1312 gtk_widget_destroy(ui_widgets.toolbar_menu);
1313 if (msgwindow.popup_status_menu && GTK_IS_WIDGET(msgwindow.popup_status_menu))
1314 gtk_widget_destroy(msgwindow.popup_status_menu);
1315 if (msgwindow.popup_msg_menu && GTK_IS_WIDGET(msgwindow.popup_msg_menu))
1316 gtk_widget_destroy(msgwindow.popup_msg_menu);
1317 if (msgwindow.popup_compiler_menu && GTK_IS_WIDGET(msgwindow.popup_compiler_menu))
1318 gtk_widget_destroy(msgwindow.popup_compiler_menu);
1320 g_object_unref(geany_object);
1321 geany_object = NULL;
1323 g_free(app);
1325 ui_finalize_builder();
1327 gtk_main_quit();
1332 * Reloads most of Geany's configuration files without restarting. Currently the following
1333 * files are reloaded: all template files, also new file templates and the 'New (with template)'
1334 * menus will be updated, Snippets (snippets.conf), filetype extensions (filetype_extensions.conf),
1335 * and 'settings' and 'build_settings' sections of the filetype definition files.
1337 * Plugins may call this function if they changed any of these files (e.g. a configuration file
1338 * editor plugin).
1340 * @since 0.15
1342 void main_reload_configuration(void)
1344 /* reload templates */
1345 templates_free_templates();
1346 templates_init();
1348 /* reload snippets */
1349 editor_snippets_free();
1350 editor_snippets_init();
1352 filetypes_reload_extensions();
1353 filetypes_reload();
1355 /* C tag names to ignore */
1356 symbols_reload_config_files();
1358 ui_set_statusbar(TRUE, _("Configuration files reloaded."));