]> de.git.xonotic.org Git - xonotic/netradiant.git/blobdiff - radiant/main.cpp
radiant: ask user to restart the editor when map load switches the brush format
[xonotic/netradiant.git] / radiant / main.cpp
index a2e0e793141cb52d3f2adc8bee63441c7cc21954..6c8ffd037992e5173a564986264232adbd9f2562 100644 (file)
-/*\r
-Copyright (C) 1999-2007 id Software, Inc. and contributors.\r
-For a list of contributors, see the accompanying CONTRIBUTORS file.\r
-\r
-This file is part of GtkRadiant.\r
-\r
-GtkRadiant is free software; you can redistribute it and/or modify\r
-it under the terms of the GNU General Public License as published by\r
-the Free Software Foundation; either version 2 of the License, or\r
-(at your option) any later version.\r
-\r
-GtkRadiant is distributed in the hope that it will be useful,\r
-but WITHOUT ANY WARRANTY; without even the implied warranty of\r
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
-GNU General Public License for more details.\r
-\r
-You should have received a copy of the GNU General Public License\r
-along with GtkRadiant; if not, write to the Free Software\r
-Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\r
-*/\r
-\r
-#if defined (__linux__) || defined (__APPLE__)\r
-  #include <gdk/gdkx.h>\r
-  #include <pwd.h>\r
-  #include <unistd.h> \r
-  #ifdef __linux__\r
-    #include <mntent.h>\r
-  #endif\r
-  #include <dirent.h>\r
-  #include <pthread.h>\r
-  #include <sys/wait.h>\r
-  #include <signal.h>\r
-  #include <sys/stat.h>\r
-#endif\r
-\r
-#include <gtk/gtk.h>\r
-#include "stdafx.h"\r
-#include <assert.h>\r
-#include <sys/types.h>\r
-#include <sys/stat.h>\r
-\r
-#include <stdlib.h>\r
-\r
-#include "watchbsp.h"\r
-#include "filters.h"\r
-\r
-bool g_bBuildList = false;\r
-int g_argc;\r
-char** g_argv;\r
-\r
-// =============================================================================\r
-// Splash screen\r
-\r
-// get rid of it when debugging\r
-#if defined (_DEBUG)\r
-  #define SKIP_SPLASH\r
-#endif\r
-\r
-static GtkWidget *splash_screen;\r
-\r
-// called based on a timer, or in particular cases when we don't want to keep it around\r
-gint try_destroy_splash (gpointer data)\r
-{\r
-  if (splash_screen)\r
-  {\r
-    gtk_widget_destroy (splash_screen);\r
-    splash_screen = NULL;\r
-  }\r
-  return FALSE;\r
-}\r
-\r
-static void create_splash ()\r
-{\r
-  GtkWidget *alert_frame, *alert_frame1, *pixmap;\r
-\r
-  splash_screen = gtk_window_new (GTK_WINDOW_POPUP);\r
-  gtk_window_position (GTK_WINDOW (splash_screen), GTK_WIN_POS_CENTER);\r
-  gtk_widget_realize (splash_screen);\r
-\r
-  alert_frame1 = gtk_frame_new (NULL);\r
-  gtk_widget_show (alert_frame1);\r
-  gtk_container_add (GTK_CONTAINER (splash_screen), alert_frame1);\r
-  gtk_frame_set_shadow_type (GTK_FRAME (alert_frame1), GTK_SHADOW_OUT);\r
-\r
-  alert_frame = gtk_frame_new (NULL);\r
-  gtk_widget_show (alert_frame);\r
-\r
-  gtk_container_add (GTK_CONTAINER (alert_frame1), alert_frame);\r
-  gtk_frame_set_shadow_type (GTK_FRAME (alert_frame), GTK_SHADOW_IN);\r
-  gtk_container_border_width (GTK_CONTAINER (alert_frame), 3);\r
-\r
-  pixmap = gtk_preview_new (GTK_PREVIEW_COLOR);\r
-  gtk_widget_show (pixmap);\r
-  gtk_container_add (GTK_CONTAINER (alert_frame), pixmap);\r
-\r
-  CString str;\r
-  guint16 width, height;\r
-  unsigned char *buf;\r
-\r
-  str = g_strGameToolsPath;\r
-  str += "bitmaps/splash.bmp";\r
-\r
-  unsigned char* load_bitmap_file (const char* filename, guint16* width, guint16* height);\r
-  buf = load_bitmap_file (str.GetBuffer (), &width, &height);\r
-\r
-  if (!buf)\r
-  {\r
-    str = g_strBitmapsPath;\r
-    str += "splash.bmp";\r
-\r
-    buf = load_bitmap_file (str.GetBuffer (), &width, &height);\r
-  }\r
-\r
-  if (buf)\r
-  {\r
-    GtkPreview *preview = GTK_PREVIEW (pixmap);\r
-    gtk_preview_size (preview, width, height);\r
-    for (int y = 0; y < height; y++)\r
-      gtk_preview_draw_row (preview, buf+y*width*3, 0, y, width);\r
-  }\r
-\r
-  gtk_widget_show_all (splash_screen);\r
-\r
-  while (gtk_events_pending ())\r
-    gtk_main_iteration ();\r
-}\r
-\r
-// =============================================================================\r
-// Loki stuff\r
-\r
-#if defined (__linux__) || defined (__APPLE__)\r
-\r
-/* A short game name, could be used as argv[0] */\r
-static char game_name[100] = "";\r
-\r
-/* The directory where the data files can be found (run directory) */\r
-static char datapath[PATH_MAX];\r
-\r
-char *loki_gethomedir(void)\r
-{\r
-  char *home = NULL;\r
-\r
-  home = getenv("HOME");\r
-  if ( home == NULL )\r
-  {\r
-    uid_t id = getuid();\r
-    struct passwd *pwd;\r
-\r
-    setpwent();\r
-    while ( (pwd = getpwent()) != NULL )\r
-    {\r
-      if ( pwd->pw_uid == id )\r
-      {\r
-        home = pwd->pw_dir;\r
-        break;\r
-      }\r
-    }\r
-    endpwent();\r
-  }\r
-  return home;\r
-}\r
-\r
-/* Must be called BEFORE loki_initialize */\r
-void loki_setgamename(const char *n)\r
-{\r
-  strncpy(game_name, n, sizeof(game_name));\r
-}\r
-\r
-  #ifdef __linux__\r
-/* Code to determine the mount point of a CD-ROM */\r
-int loki_getmountpoint(const char *device, char *mntpt, int max_size)\r
-{\r
-  char devpath[PATH_MAX], mntdevpath[PATH_MAX];\r
-  FILE * mountfp;\r
-  struct mntent *mntent;\r
-  int mounted;\r
-\r
-  /* Nothing to do with no device file */\r
-  if ( device == NULL )\r
-  {\r
-    *mntpt = '\0';\r
-    return -1;\r
-  }\r
-\r
-  /* Get the fully qualified path of the CD-ROM device */\r
-  if ( realpath(device, devpath) == NULL )\r
-  {\r
-    perror("realpath() on your CD-ROM failed");\r
-    return(-1);\r
-  }\r
-\r
-  /* Get the mount point */\r
-  mounted = -1;\r
-  memset(mntpt, 0, max_size);\r
-  mountfp = setmntent( _PATH_MNTTAB, "r" );\r
-  if ( mountfp != NULL )\r
-  {\r
-    mounted = 0;\r
-    while ( (mntent = getmntent( mountfp )) != NULL )\r
-    {\r
-      char *tmp, mntdev[1024];\r
-\r
-      strcpy(mntdev, mntent->mnt_fsname);\r
-      if ( strcmp(mntent->mnt_type, "supermount") == 0 )\r
-      {\r
-        tmp = strstr(mntent->mnt_opts, "dev=");\r
-        if ( tmp )\r
-        {\r
-          strcpy(mntdev, tmp+strlen("dev="));\r
-          tmp = strchr(mntdev, ',');\r
-          if ( tmp )\r
-          {\r
-            *tmp = '\0';\r
-          }\r
-        }\r
-      }\r
-      if ( strncmp(mntdev, "/dev", 4) ||\r
-           realpath(mntdev, mntdevpath) == NULL )\r
-      {\r
-        continue;\r
-      }\r
-      if ( strcmp( mntdevpath, devpath ) == 0 )\r
-      {\r
-        mounted = 1;\r
-        assert((int)strlen( mntent->mnt_dir ) < max_size);\r
-        strncpy( mntpt, mntent->mnt_dir, max_size-1);\r
-        mntpt[max_size-1] = '\0';\r
-        break;\r
-      }\r
-    }\r
-    endmntent( mountfp );\r
-  }\r
-  return(mounted);\r
-} \r
-  #endif\r
-\r
-/* \r
-    This function gets the directory containing the running program.\r
-    argv0 - the 0'th argument to the program\r
-*/\r
-// FIXME TTimo\r
-// I don't understand this function. It looks like something cut from another piece of software\r
-// we somehow get the g_strAppPath from it, but it's done through a weird scan across $PATH env. var.\r
-// even worse, it doesn't behave the same in all cases .. works well when ran through gdb and borks when ran from a shell\r
-void loki_initpaths(char *argv0)\r
-{\r
-  char temppath[PATH_MAX]; //, env[100];\r
-  char *home; //, *ptr, *data_env;\r
-\r
-  home = loki_gethomedir();\r
-  if ( home == NULL )\r
-  {\r
-    home = ".";\r
-  }\r
-\r
-  if (*game_name == 0) /* Game name defaults to argv[0] */\r
-    loki_setgamename(argv0);\r
-\r
-  strcpy(temppath, argv0);  /* If this overflows, it's your own fault :) */\r
-  if ( ! strrchr(temppath, '/') )\r
-  {\r
-    char *path;\r
-    char *last;\r
-    int found;\r
-\r
-    found = 0;\r
-    path = getenv("PATH");\r
-    do\r
-    {\r
-      /* Initialize our filename variable */\r
-      temppath[0] = '\0';\r
-\r
-      /* Get next entry from path variable */\r
-      last = strchr(path, ':');\r
-      if ( ! last )\r
-        last = path+strlen(path);\r
-\r
-      /* Perform tilde expansion */\r
-      if ( *path == '~' )\r
-      {\r
-        strcpy(temppath, home);\r
-        ++path;\r
-      }\r
-\r
-      /* Fill in the rest of the filename */\r
-      if ( last > (path+1) )\r
-      {\r
-        strncat(temppath, path, (last-path));\r
-        strcat(temppath, "/");\r
-      }\r
-      strcat(temppath, "./");\r
-      strcat(temppath, argv0);\r
-\r
-      /* See if it exists, and update path */\r
-      if ( access(temppath, X_OK) == 0 )\r
-      {\r
-        ++found;\r
-      }\r
-      path = last+1;\r
-\r
-    } while ( *last && !found );\r
-\r
-  } else\r
-  {\r
-    /* Increment argv0 to the basename */\r
-    argv0 = strrchr(argv0, '/')+1;\r
-  }\r
-\r
-  /* Now canonicalize it to a full pathname for the data path */\r
-  if ( realpath(temppath, datapath) )\r
-  {\r
-    /* There should always be '/' in the path */\r
-    *(strrchr(datapath, '/')) = '\0';\r
-  }\r
-}\r
-\r
-char *loki_getdatapath(void)\r
-{\r
-  return(datapath);\r
-}\r
-\r
-#endif\r
-\r
-// end of Loki stuff\r
-// =============================================================================\r
-\r
-void error_redirect (const gchar *domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data)\r
-{\r
-  gboolean in_recursion;\r
-  gboolean is_fatal;\r
-  char buf[256];\r
-\r
-  in_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;\r
-  is_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;\r
-  log_level = (GLogLevelFlags) (log_level & G_LOG_LEVEL_MASK);\r
-\r
-  if (!message)\r
-    message = "(NULL) message";\r
-\r
-  if (domain)\r
-    strcpy (buf, domain);\r
-  else\r
-    strcpy (buf, "**");\r
-  strcat (buf, "-");\r
-\r
-  switch (log_level)\r
-  {\r
-  case G_LOG_LEVEL_ERROR:\r
-    if (in_recursion)\r
-      strcat (buf, "ERROR (recursed) **: ");\r
-    else\r
-      strcat (buf, "ERROR **: ");\r
-    break;\r
-  case G_LOG_LEVEL_CRITICAL:\r
-    if (in_recursion)\r
-      strcat (buf, "CRITICAL (recursed) **: ");\r
-    else\r
-      strcat (buf, "CRITICAL **: ");\r
-    break;\r
-  case G_LOG_LEVEL_WARNING:\r
-    if (in_recursion)\r
-      strcat (buf, "WARNING (recursed) **: ");\r
-    else\r
-      strcat (buf, "WARNING **: ");\r
-    break;\r
-  case G_LOG_LEVEL_MESSAGE:\r
-    if (in_recursion)\r
-      strcat (buf, "Message (recursed): ");\r
-    else\r
-      strcat (buf, "Message: ");\r
-    break;\r
-  case G_LOG_LEVEL_INFO:\r
-    if (in_recursion)\r
-      strcat (buf, "INFO (recursed): ");\r
-    else\r
-      strcat (buf, "INFO: ");\r
-    break;\r
-  case G_LOG_LEVEL_DEBUG:\r
-    if (in_recursion)\r
-      strcat (buf, "DEBUG (recursed): ");\r
-    else\r
-      strcat (buf, "DEBUG: ");\r
-    break;\r
-  default:\r
-    /* we are used for a log level that is not defined by GLib itself,\r
-     * try to make the best out of it.\r
-     */\r
-    if (in_recursion)\r
-      strcat (buf, "LOG (recursed:");\r
-    else\r
-      strcat (buf, "LOG (");\r
-    if (log_level)\r
-    {\r
-      gchar string[] = "0x00): ";\r
-      gchar *p = string + 2;\r
-      guint i;\r
-\r
-      i = g_bit_nth_msf (log_level, -1);\r
-      *p = i >> 4;\r
-      p++;\r
-      *p = '0' + (i & 0xf);\r
-      if (*p > '9')\r
-        *p += 'A' - '9' - 1;\r
-\r
-      strcat (buf, string);\r
-    } else\r
-      strcat (buf, "): ");\r
-  }\r
-\r
-  strcat (buf, message);\r
-  if (is_fatal)\r
-    strcat (buf, "\naborting...\n");\r
-  else\r
-    strcat (buf, "\n");\r
-\r
-  printf ("%s\n", buf);\r
-  Sys_FPrintf (SYS_WRN, buf);\r
-  // TTimo NOTE: in some cases it may be handy to log only to the file\r
-//  Sys_FPrintf (SYS_NOCON, buf);\r
-}\r
-\r
-int main (int argc, char* argv[])\r
-{\r
-  char *libgl, *ptr;\r
-  int i, j, k;\r
-\r
-#ifdef _WIN32\r
-  libgl = "opengl32.dll";\r
-#endif\r
-\r
-#if defined (__linux__)\r
-  libgl = "libGL.so.1";\r
-#endif\r
-\r
-#ifdef __APPLE__\r
-  libgl = "/usr/X11R6/lib/libGL.1.dylib";\r
-#endif\r
-\r
-#if defined (__linux__) || defined (__APPLE__)\r
-  // Give away unnecessary root privileges.\r
-  // Important: must be done before calling gtk_init().\r
-  char *loginname;\r
-  struct passwd *pw;\r
-  seteuid(getuid());\r
-  if (geteuid() == 0 && (loginname = getlogin()) != NULL &&\r
-      (pw = getpwnam(loginname)) != NULL)\r
-    setuid(pw->pw_uid);\r
-#endif\r
-\r
-  gtk_disable_setlocale();\r
-\r
-  gtk_init(&argc, &argv);\r
-\r
-  if ((ptr = getenv ("Q3R_LIBGL")) != NULL)\r
-    libgl = ptr;\r
-\r
-  for (i = 1; i < argc; i++)\r
-  {\r
-    char* param = argv[i];\r
-\r
-    if (param[0] == '-' && param[1] == '-')\r
-    {\r
-      param += 2;\r
-\r
-      if ((strcmp (param, "libgl") == 0) && (i != argc))\r
-      {\r
-        libgl = argv[i+1];\r
-        argv[i] = argv[i+1] = NULL;\r
-        i++;\r
-      } else if (strcmp (param, "builddefs") == 0)\r
-      {\r
-        g_bBuildList = true;\r
-        argv[i] = NULL;\r
-      }\r
-    }\r
-  }\r
-\r
-  for (i = 1; i < argc; i++)\r
-  {\r
-    for (k = i; k < argc; k++)\r
-      if (argv[k] != NULL)\r
-        break;\r
-\r
-    if (k > i)\r
-    {\r
-      k -= i;\r
-      for (j = i + k; j < argc; j++)\r
-        argv[j-k] = argv[j];\r
-      argc -= k;\r
-    }\r
-  }\r
-\r
-  g_argc = argc;\r
-  g_argv = argv;\r
-\r
-  g_strPluginsDir = "plugins/";\r
-  g_strModulesDir = "modules/";\r
-\r
-#ifdef _WIN32\r
-  // get path to the editor\r
-  char* pBuffer = g_strAppPath.GetBufferSetLength(_MAX_PATH + 1);\r
-  GetModuleFileName(NULL, pBuffer, _MAX_PATH);\r
-  pBuffer[g_strAppPath.ReverseFind('\\') + 1] = '\0';\r
-  QE_ConvertDOSToUnixName(pBuffer, pBuffer);\r
-  g_strAppPath.ReleaseBuffer();\r
-\r
-  g_strBitmapsPath = g_strAppPath;\r
-  g_strBitmapsPath += "bitmaps/";\r
-\r
-#if 0\r
-  // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=639\r
-  // now check if we are running from a network installation\r
-  // use a dummy file as the flag\r
-  FILE *f_netrun;\r
-  CString strNetrun;\r
-  strNetrun = g_strAppPath; strNetrun += NETRUN_FILENAME;\r
-  f_netrun = fopen(strNetrun.GetBuffer(), "r");\r
-  if (f_netrun)\r
-  {\r
-    fclose(f_netrun);\r
-    g_PrefsDlg.m_bUseHomePath = true;\r
-  }\r
-#endif\r
-  CGameDialog::UpdateNetrun(false); // read the netrun configuration\r
-\r
-  if (CGameDialog::GetNetrun())\r
-  {\r
-    // we have to find a per-user g_strTempPath\r
-    // this behaves the same as on Linux\r
-    g_strTempPath = getenv("USERPROFILE");\r
-    if (!g_strTempPath.GetLength())\r
-    {\r
-      CString msg;\r
-      msg = "Radiant is configured to run from a network installation.\n";\r
-      msg += "I couldn't find the environement variable USERPROFILE\n";\r
-      msg += "I'm going to use C:\\RadiantSettings. Please set USERPROFILE\n";\r
-      gtk_MessageBox (NULL, msg, "Radiant - Network mode", MB_OK);\r
-      g_strTempPath = "C:\\";\r
-    }\r
-    g_strTempPath += "\\RadiantSettings\\";\r
-    Q_mkdir(g_strTempPath.GetBuffer(), 0755);\r
-    g_strTempPath += RADIANT_VERSION;\r
-    g_strTempPath += "\\";\r
-    Q_mkdir(g_strTempPath.GetBuffer(), 0755);\r
-  }\r
-  else\r
-  {\r
-    // use the core path as temp (to save commandlist.txt, and do the .pid files)\r
-    g_strTempPath = g_strAppPath;\r
-  }\r
-\r
-#endif\r
-\r
-#if defined (__linux__) || defined (__APPLE__)\r
-  Str home;\r
-  home = g_get_home_dir ();\r
-  AddSlash (home);\r
-  home += ".radiant/";\r
-  Q_mkdir (home.GetBuffer (), 0775);\r
-  home += RADIANT_VERSION;\r
-  Q_mkdir (home.GetBuffer (), 0775);\r
-  g_strTempPath = home.GetBuffer ();\r
-  AddSlash (g_strTempPath);\r
-\r
-  loki_initpaths(argv[0]);\r
-\r
-  // NOTE: we build g_strAppPath with a '/' (or '\' on WIN32)\r
-  // it's a general convention in Radiant to have the slash at the end of directories\r
-  char real[PATH_MAX];\r
-  realpath (loki_getdatapath(), real);\r
-  if (real[strlen(real)-1] != '/')\r
-    strcat(real, "/");\r
-\r
-  g_strAppPath = real;\r
-\r
-#if 0\r
-  printf("g_strAppPath: %s\n", g_strAppPath.GetBuffer());\r
-#endif\r
-\r
-  // radiant is installed in the parent dir of "tools/"\r
-  // NOTE: this is not very easy for debugging\r
-  // maybe add options to lookup in several places?\r
-  // (for now I had to create symlinks)\r
-  g_strBitmapsPath = g_strAppPath;\r
-  g_strBitmapsPath += "bitmaps/";\r
-#if 0\r
-  printf("g_strBitmapsPath: %s\n", g_strBitmapsPath.GetBuffer());\r
-#endif\r
-  \r
-  // we will set this right after the game selection is done\r
-  g_strGameToolsPath = g_strAppPath;\r
-\r
-#endif\r
-\r
-  // init the DTD path\r
-  g_strDTDPath = g_strAppPath;\r
-  g_strDTDPath += "dtds/";\r
-\r
-  /*!\r
-  the global prefs loading / game selection dialog might fail for any reason we don't know about\r
-  we need to catch when it happens, to cleanup the stateful prefs which might be killing it\r
-  and to turn on console logging for lookup of the problem\r
-  this is the first part of the two step .pid system\r
-  http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=297\r
-  */\r
-  g_pidFile = g_strTempPath.GetBuffer ();\r
-  g_pidFile += "radiant.pid";\r
-\r
-  FILE *pid;\r
-  pid = fopen (g_pidFile.GetBuffer(), "r");\r
-  if (pid != NULL)\r
-  {\r
-    fclose (pid);\r
-    CString msg;\r
-\r
-    if (remove (g_pidFile.GetBuffer ()) == -1)\r
-    {\r
-      msg = "WARNING: Could not delete "; msg += g_pidFile;\r
-      gtk_MessageBox (NULL, msg, "Radiant", MB_OK | MB_ICONERROR );\r
-    }\r
-\r
-    // in debug, never prompt to clean registry, turn console logging auto after a failed start\r
-#if !defined(_DEBUG)\r
-    msg = "Found the file ";\r
-    msg += g_pidFile;\r
-    msg += ".\nThis indicates that Radiant failed during the game selection startup last time it was run.\n"\r
-           "Choose YES to clean Radiant's registry settings and shut down Radiant.\n"\r
-           "WARNING: the global prefs will be lost if you choose YES.";\r
-\r
-    if (gtk_MessageBox (NULL, msg, "Radiant - Reset global startup?", MB_YESNO | MB_ICONQUESTION) == IDYES)\r
-    {\r
-      // remove global prefs and shutdown\r
-      g_PrefsDlg.mGamesDialog.Reset();\r
-      // remove the prefs file (like a full reset of the registry)\r
-      //remove (g_PrefsDlg.m_inipath->str);\r
-      gtk_MessageBox(NULL, "Removed global settings, choose OK to close Radiant.", "Radiant", MB_OK );\r
-      _exit(-1);\r
-    }\r
-    msg = "Logging console output to ";\r
-    msg += g_strTempPath;\r
-    msg += "radiant.log\nRefer to the log if Radiant fails to start again.";\r
-\r
-    gtk_MessageBox (NULL, msg, "Radiant - Console Log", MB_OK);\r
-#endif\r
-\r
-    // set without saving, the class is not in a coherent state yet\r
-    // just do the value change and call to start logging, CGamesDialog will pickup when relevant\r
-    g_PrefsDlg.mGamesDialog.m_bLogConsole = true;\r
-    g_PrefsDlg.mGamesDialog.m_bForceLogConsole = true;\r
-    Sys_LogFile();\r
-  }\r
-\r
-  // create a primary .pid for global init run\r
-  pid = fopen (g_pidFile.GetBuffer(), "w");\r
-  if (pid)\r
-    fclose (pid);\r
-  \r
-  // a safe check to avoid people running broken installations\r
-  // (otherwise, they run it, crash it, and blame us for not forcing them hard enough to pay attention while installing)\r
-  // make something idiot proof and someone will make better idiots, this may be overkill\r
-  // let's leave it disabled in debug mode in any case\r
-  // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=431\r
-#ifndef _DEBUG\r
-#define CHECK_VERSION\r
-#endif\r
-#ifdef CHECK_VERSION  \r
-  // locate and open RADIANT_MAJOR and RADIANT_MINOR\r
-  qboolean bVerIsGood = true;\r
-  Str ver_file_name;\r
-  ver_file_name = g_strAppPath;\r
-  ver_file_name += "RADIANT_MAJOR";\r
-  FILE *ver_file = fopen (ver_file_name.GetBuffer(), "r");\r
-  if (ver_file)\r
-  {\r
-    char buf[10];\r
-    int chomp;\r
-    fread(buf, 1, 10, ver_file);\r
-    // chomp it (the hard way)\r
-    chomp = 0;\r
-    while(buf[chomp] >= '0' && buf[chomp] <= '9')\r
-      chomp++;\r
-    buf[chomp] = '\0';\r
-    if (strcmp(buf, RADIANT_MAJOR_VERSION))\r
-    {\r
-      Sys_Printf("ERROR: file RADIANT_MAJOR doesn't match ('%s')\n", buf);\r
-      bVerIsGood = false;\r
-    }\r
-  }\r
-  else\r
-  {\r
-    Sys_Printf("ERROR: can't find RADIANT_MAJOR in '%s'\n", ver_file_name.GetBuffer());\r
-    bVerIsGood = false;\r
-  }\r
-  ver_file_name = g_strAppPath;\r
-  ver_file_name += "RADIANT_MINOR";\r
-  ver_file = fopen (ver_file_name.GetBuffer(), "r");\r
-  if (ver_file)\r
-  {\r
-    char buf[10];\r
-    int chomp;\r
-    fread(buf, 1, 10, ver_file);\r
-    // chomp it (the hard way)\r
-    chomp = 0;\r
-    while(buf[chomp] >= '0' && buf[chomp] <= '9')\r
-      chomp++;\r
-    buf[chomp] = '\0';\r
-    if (strcmp(buf, RADIANT_MINOR_VERSION))\r
-    {\r
-      Sys_Printf("ERROR: file RADIANT_MINOR doesn't match ('%s')\n", buf);\r
-      bVerIsGood = false;\r
-    }\r
-  }\r
-  else\r
-  {\r
-    Sys_Printf("ERROR: can't find RADIANT_MINOR in '%s'\n", ver_file_name.GetBuffer());\r
-    bVerIsGood = false;\r
-  }\r
-  if (!bVerIsGood)\r
-  {\r
-    CString msg;\r
-    msg = "This editor binary (" RADIANT_VERSION ") doesn't match what the latest setup has configured in this directory\n";\r
-    msg += "Make sure you run the right/latest editor binary you installed\n";\r
-    msg += g_strAppPath; msg += "\n";\r
-    msg += "Check http://www.qeradiant.com/faq/index.cgi?file=219 for more information";\r
-    gtk_MessageBox(NULL, msg.GetBuffer(), "Radiant", MB_OK, "http://www.qeradiant.com/faq/index.cgi?file=219");\r
-    _exit(-1);\r
-  }\r
-#endif\r
-  \r
-  g_qeglobals.disable_ini = false;\r
-  g_PrefsDlg.Init ();\r
-\r
-  // close the primary\r
-  if (remove (g_pidFile.GetBuffer ()) == -1)\r
-  {\r
-    CString msg;\r
-    msg = "WARNING: Could not delete "; msg += g_pidGameFile;\r
-    gtk_MessageBox (NULL, msg, "Radiant", MB_OK | MB_ICONERROR );\r
-  }\r
-  \r
-  /*!\r
-  now the secondary game dependant .pid file\r
-  http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=297\r
-  */\r
-  g_pidGameFile = g_PrefsDlg.m_rc_path->str;\r
-  g_pidGameFile += "radiant-game.pid";\r
-\r
-  pid = fopen (g_pidGameFile.GetBuffer(), "r");\r
-  if (pid != NULL)\r
-  {\r
-    fclose (pid);\r
-    CString msg;\r
-    if (remove (g_pidGameFile.GetBuffer ()) == -1)\r
-    {\r
-      msg = "WARNING: Could not delete "; msg += g_pidGameFile;\r
-      gtk_MessageBox (NULL, msg, "Radiant", MB_OK | MB_ICONERROR );\r
-    }\r
-\r
-    msg = "Found the file ";\r
-    msg += g_pidGameFile;\r
-    msg += ".\nThis indicates that Radiant failed to load the last time it was run.\n"\r
-           "Choose YES to clean Radiant's registry settings and shut down Radiant.\n"\r
-           "WARNING: preferences will be lost if you choose YES.";\r
-\r
-    // in debug, never prompt to clean registry, turn console logging auto after a failed start\r
-#if !defined(_DEBUG)\r
-    //bleh\r
-    if (gtk_MessageBox (NULL, msg, "Radiant - Clean Registry?", MB_YESNO | MB_ICONQUESTION) == IDYES)\r
-    {\r
-      // remove the game prefs files\r
-      remove (g_PrefsDlg.m_inipath->str);\r
-      char buf[PATH_MAX];\r
-      sprintf(buf, "%sSavedInfo.bin", g_PrefsDlg.m_rc_path->str);\r
-      remove(buf);\r
-      // remove the global pref too\r
-      g_PrefsDlg.mGamesDialog.Reset();\r
-      gtk_MessageBox(NULL, "Cleaned registry settings, choose OK to close Radiant.\nThe next time Radiant runs it will use default settings.", "Radiant", MB_OK );\r
-      _exit(-1);\r
-    }\r
-    msg = "Logging console output to ";\r
-    msg += g_strTempPath;\r
-    msg += "radiant.log\nRefer to the log if Radiant fails to start again.";\r
-\r
-    gtk_MessageBox (NULL, msg, "Radiant - Console Log", MB_OK);\r
-#endif\r
-\r
-    // force console logging on! (will go in prefs too)\r
-    g_PrefsDlg.mGamesDialog.m_bLogConsole = true;\r
-    g_PrefsDlg.mGamesDialog.SavePrefs();\r
-    Sys_LogFile();\r
-\r
-    g_PrefsDlg.LoadPrefs();\r
-\r
-  } else\r
-  {\r
-    // create one, will remove right after entering message loop\r
-    pid = fopen (g_pidGameFile.GetBuffer(), "w");\r
-    if (pid)\r
-      fclose (pid);\r
-\r
-    g_PrefsDlg.LoadPrefs();\r
-\r
-#ifndef _DEBUG // I can't be arsed about that prompt in debug mode\r
-    // if console logging is on in the prefs, warn about performance hit\r
-    if (g_PrefsDlg.mGamesDialog.m_bLogConsole)\r
-    {\r
-      if (gtk_MessageBox (NULL, "Preferences indicate that console logging is on. This affects performance.\n"\r
-                          "Turn it off?", "Radiant", MB_YESNO | MB_ICONQUESTION) == IDYES)\r
-      {\r
-        g_PrefsDlg.mGamesDialog.m_bLogConsole = false;\r
-        g_PrefsDlg.mGamesDialog.SavePrefs();\r
-      }\r
-    }\r
-#endif\r
-    // toggle console logging if necessary\r
-    Sys_LogFile();\r
-  }\r
-\r
-  // FIXME http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=639\r
-  // we should search in g_strTempPath, then move over to look at g_strAppPath?\r
-#ifdef _WIN32\r
-  // fine tune the look of the app using a gtk rc file\r
-  // we try to load an RC file placed in the application directory\r
-  // build the full path\r
-  Str sRCFile;\r
-  sRCFile = g_strAppPath;\r
-  sRCFile += "radiantgtkrc";\r
-  // we load that file with g_new in gtk_rc_parse_file (gtkrc.c), change the '/' into '\\'\r
-  pBuffer = (char *)sRCFile.GetBuffer();\r
-  for (i=0; i<sRCFile.GetLength(); i++)\r
-  {\r
-    if (pBuffer[i]=='/')\r
-    {\r
-      pBuffer[i] = '\\';\r
-    }\r
-  }\r
-  // check the file exists\r
-  if (access(sRCFile.GetBuffer(), R_OK) != 0)\r
-    Sys_Printf("RC file %s not found\n", sRCFile.GetBuffer());\r
-  else\r
-  {\r
-    Sys_Printf ("Attemping to load RC file %s\n", sRCFile.GetBuffer());\r
-    gtk_rc_parse (sRCFile.GetBuffer());\r
-  }\r
-#endif\r
-\r
-#ifndef SKIP_SPLASH\r
-  create_splash ();\r
-#endif\r
-\r
-  if (!QGL_Init(libgl, ""))\r
-  {\r
-    Sys_FPrintf (SYS_ERR, "Failed to load OpenGL libraries\n");\r
-    _exit (1);\r
-    return 1;\r
-  }\r
-\r
-#if defined (__linux__) || defined (__APPLE__)\r
-  if ((qglXQueryExtension == NULL) || (qglXQueryExtension(GDK_DISPLAY(),NULL,NULL) != True))\r
-  {\r
-    Sys_FPrintf (SYS_ERR, "glXQueryExtension failed\n");\r
-    _exit (1);\r
-    return 1;\r
-  }\r
-#endif\r
-\r
-  // redirect Gtk warnings to the console\r
-  g_log_set_handler ("Gdk", (GLogLevelFlags)(G_LOG_LEVEL_ERROR|G_LOG_LEVEL_CRITICAL|G_LOG_LEVEL_WARNING|\r
-                                             G_LOG_LEVEL_MESSAGE|G_LOG_LEVEL_INFO|G_LOG_LEVEL_DEBUG), error_redirect, NULL);\r
-  g_log_set_handler ("Gtk", (GLogLevelFlags)(G_LOG_LEVEL_ERROR|G_LOG_LEVEL_CRITICAL|G_LOG_LEVEL_WARNING|\r
-                                             G_LOG_LEVEL_MESSAGE|G_LOG_LEVEL_INFO|G_LOG_LEVEL_DEBUG), error_redirect, NULL);\r
-\r
-  // spog - creates new filters list for the first time\r
-  g_qeglobals.d_savedinfo.filters = NULL; //initialise to NULL\r
-  g_qeglobals.d_savedinfo.filters = FilterUpdate(g_qeglobals.d_savedinfo.filters);\r
-\r
-  g_pParentWnd = new MainFrame ();\r
-\r
-  if (g_PrefsDlg.m_bLoadLastMap && g_PrefsDlg.m_strLastMap.GetLength() > 0)\r
-    Map_LoadFile(g_PrefsDlg.m_strLastMap.GetBuffer());\r
-  else\r
-    Map_New();\r
-\r
-  // load up shaders now that we have the map loaded\r
-  // eviltypeguy\r
-  Texture_ShowStartupShaders ();\r
-\r
-#ifndef SKIP_SPLASH\r
-  gdk_window_raise (splash_screen->window);\r
-  gtk_window_set_transient_for (GTK_WINDOW (splash_screen), GTK_WINDOW (g_pParentWnd->m_pWidget));\r
-  gtk_timeout_add (1000, try_destroy_splash, NULL);\r
-#endif\r
-  \r
-  g_pParentWnd->GetSynapseServer().DumpActiveClients();\r
-\r
-  //++timo: temporary debug\r
-  g_pParentWnd->DoWatchBSP();\r
-\r
-  gtk_main ();\r
-\r
-  // close the log file if any\r
-  // NOTE: don't save prefs past this point!\r
-  g_PrefsDlg.mGamesDialog.m_bLogConsole = false;\r
-  // set the console window to NULL to avoid Sys_Printf crashing\r
-  g_qeglobals_gui.d_edit = NULL;\r
-  Sys_LogFile();\r
-\r
-  // NOTE TTimo not sure what this _exit(0) call is worth\r
-  //   restricting it to linux build\r
-#ifdef __linux__\r
-  _exit (0);\r
-#endif\r
-  return 0;\r
-}\r
-\r
-// ydnar: quick and dirty fix, just make the buffer bigger\r
-#define BIG_PATH_MAX   4096\r
-\r
-// TTimo: decompose the BSP command into several steps so we can monitor them eventually\r
-void QE_ExpandBspString (char *bspaction, GPtrArray *out_array, char *mapname)\r
-{\r
-  const char  *in;\r
-  char  *out;\r
-  char  src[BIG_PATH_MAX];\r
-  char  rsh[BIG_PATH_MAX];\r
-  char  base[BIG_PATH_MAX];\r
-\r
-  strcpy(src, mapname);\r
-  strlwr(src);\r
-  in = strstr(src, "maps/");\r
-  if (!in)\r
-  {\r
-    in = strstr(src, "maps/");\r
-  }\r
-  if (in)\r
-  {\r
-    in += 5;\r
-    strcpy(base, in);\r
-    out = base;\r
-    while (*out)\r
-    {\r
-      if (*out == '\\')\r
-      {\r
-        *out = '/';\r
-      }\r
-      out++;\r
-    }\r
-  } else\r
-  {\r
-    ExtractFileName (mapname, base);\r
-  }\r
-\r
-  // this important step alters the map name to add fs_game\r
-  // NOTE: it used to add fs_basepath too\r
-  // the fs_basepath addition moved to being in the project file during the bug fixing rush\r
-  // but it may not have been the right thing to do\r
-\r
-  // HACK: halflife compiler tools don't support -fs_game\r
-  // HACK: neither does JKII/SoF2/ etc..\r
-  // do we use & have fs_game?\r
-  \r
-  if (g_pGameDescription->mGameFile != "hl.game" &&\r
-      *ValueForKey(g_qeglobals.d_project_entity,"gamename") != '\0')\r
-    {\r
-      // set with fs_game\r
-      sprintf(src, "-fs_game %s \"%s\"", ValueForKey(g_qeglobals.d_project_entity,"gamename"), mapname);\r
-    }\r
-    else\r
-    {\r
-      sprintf(src, "\"%s\"", mapname);\r
-  }\r
-\r
-  rsh[0] = 0;\r
-\r
-  QE_ConvertDOSToUnixName(src, src);\r
-\r
-  // initialise the first step\r
-  out = new char[BIG_PATH_MAX];        //% PATH_MAX\r
-  g_ptr_array_add( out_array, out );\r
-\r
-  in = ValueForKey( g_qeglobals.d_project_entity, bspaction );\r
-  while (*in)\r
-  {\r
-    if (in[0] == '!')\r
-    {\r
-      strcpy (out, rsh);\r
-      out += strlen(rsh);\r
-      in++;\r
-      continue;\r
-    }\r
-    if (in[0] == '#')\r
-    {\r
-      char tmp[2048];\r
-      // we process these only if monitoring\r
-      if (g_PrefsDlg.m_bWatchBSP)\r
-      {\r
-        // -connect global option (the only global option so far anyway)\r
-        strcpy (tmp, " -connect 127.0.0.1:39000 ");\r
-        strcpy (out, tmp);\r
-        out += strlen(tmp);\r
-      }\r
-      in++;\r
-      continue;\r
-    }\r
-    if (in[0] == '$')\r
-    {\r
-      // $ expansion\r
-      strcpy (out, src);\r
-      out += strlen(src);\r
-      in++;\r
-      continue;\r
-    }\r
-    if (in[0] == '@')\r
-    {\r
-      *out++ = '"';\r
-      in++;\r
-      continue;\r
-    }\r
-    if (in[0] == '&')\r
-      if (in[1] == '&')\r
-      {\r
-        // start a new step\r
-        *out = 0;\r
-        in = in + 2;\r
-        out = new char[BIG_PATH_MAX];  //% PATH_MAX\r
-        g_ptr_array_add( out_array, out );\r
-      }\r
-    *out++ = *in++;\r
-  }\r
-  *out = 0;\r
-}\r
-\r
-void FindReplace(CString& strContents, const char* pTag, const char* pValue)\r
-{\r
-  if (strcmp(pTag, pValue) == 0)\r
-    return;\r
-  for (int nPos = strContents.Find(pTag); nPos >= 0; nPos = strContents.Find(pTag))\r
-  {\r
-    int nRightLen = strContents.GetLength() - strlen(pTag) - nPos;\r
-    CString strLeft = strContents.Left(nPos);\r
-    CString strRight = strContents.Right(nRightLen);\r
-    strLeft += pValue;\r
-    strLeft += strRight;\r
-    strContents = strLeft;\r
-  }\r
-}\r
-\r
-// save the map, deals with regioning\r
-void SaveWithRegion(char *name)\r
-{\r
-  strcpy (name, currentmap);\r
-  if (region_active)\r
-  {\r
-    // temporary cut the region to save regular map\r
-    region_active = false;\r
-    Map_SaveFile (name, false);\r
-    region_active = true;\r
-    StripExtension (name);\r
-    strcat (name, ".reg");\r
-  }\r
-\r
-  Map_SaveFile (name, region_active);\r
-}\r
-\r
-void RunBsp (char *command)\r
-{\r
-  GPtrArray *sys;\r
-  char  batpath[BIG_PATH_MAX]; //% PATH_MAX\r
-  char  temppath[BIG_PATH_MAX];        //% PATH_MAX\r
-  char  name[BIG_PATH_MAX];            //% PATH_MAX\r
-  char  cWork[BIG_PATH_MAX];   //% PATH_MAX\r
-  FILE  *hFile;\r
-  unsigned int   i;\r
-\r
-  SetInspectorMode(W_CONSOLE);\r
-\r
-  strcpy (temppath, g_strTempPath.GetBuffer ());\r
-\r
-  SaveWithRegion(name);\r
-\r
-  const char *rsh = ValueForKey(g_qeglobals.d_project_entity, "rshcmd");\r
-  if (rsh == NULL)\r
-  {\r
-    CString strPath, strFile;\r
-\r
-    ExtractPath_and_Filename(name, strPath, strFile);\r
-    AddSlash(strPath);\r
-    strncpy(cWork, strPath, 1024);\r
-    strcat(cWork, strFile);\r
-  } else\r
-  {\r
-    strcpy(cWork, name);\r
-  }\r
-\r
-  // get the array ready\r
-  //++timo TODO: free the array, free the strings ourselves with delete[]\r
-  sys = g_ptr_array_new();\r
-\r
-  QE_ExpandBspString (command, sys, cWork);\r
-\r
-  if (g_PrefsDlg.m_bWatchBSP)\r
-  {\r
-    // grab the file name for engine running\r
-    char *bspname = new char[1024];\r
-    ExtractFileName( currentmap, bspname );\r
-    StripExtension( bspname );\r
-    g_pParentWnd->GetWatchBSP()->DoMonitoringLoop( sys, bspname );\r
-  } else\r
-  {\r
-    // write all the steps in a single BAT / .sh file and run it, don't bother monitoring it\r
-    CString strSys;\r
-    for (i=0; i < sys->len; i++ )\r
-    {\r
-      strSys += (char *)g_ptr_array_index( sys, i);\r
-#ifdef _WIN32  // write temp\junk.txt in win32... NOTE: stops output to shell prompt window\r
-      if (i==0) \r
-        strSys += " >";\r
-      else \r
-        strSys += " >>";\r
-      strSys += "\"";\r
-      strSys += temppath;\r
-      strSys += "junk.txt\"";\r
-#endif\r
-      strSys += "\n";\r
-    };\r
-\r
-#if defined (__linux__) || defined (__APPLE__)\r
-\r
-    // write qe3bsp.sh\r
-    sprintf (batpath, "%sqe3bsp.sh", temppath);\r
-    Sys_Printf("Writing the compile script to '%s'\n", batpath);\r
-    Sys_Printf("The build output will be saved in '%sjunk.txt'\n", temppath);\r
-    hFile = fopen(batpath, "w");\r
-    if (!hFile)\r
-      Error ("Can't write to %s", batpath);\r
-    fprintf (hFile, "#!/bin/sh \n\n");\r
-    fprintf (hFile, strSys.GetBuffer());\r
-    fclose (hFile);\r
-    chmod (batpath, 0744);\r
-#endif\r
-\r
-#ifdef _WIN32\r
-    sprintf (batpath, "%sqe3bsp.bat", temppath);\r
-    Sys_Printf("Writing the compile script to '%s'\n", batpath);\r
-    Sys_Printf("The build output will be saved in '%sjunk.txt'\n", temppath);\r
-    hFile = fopen(batpath, "w");\r
-    if (!hFile)\r
-      Error ("Can't write to %s", batpath);\r
-    fprintf (hFile, strSys.GetBuffer());\r
-    fclose (hFile); \r
-#endif\r
-\r
-    Pointfile_Delete ();\r
-\r
-#if defined (__linux__) || defined (__APPLE__)\r
-\r
-    pid_t pid;\r
-\r
-    pid = fork ();\r
-    switch (pid)\r
-    {\r
-    case -1:\r
-      Error ("CreateProcess failed");\r
-      break;\r
-    case 0:\r
-      execlp (batpath, batpath, NULL);\r
-      printf ("execlp error !");\r
-      _exit (0);\r
-      break;\r
-    default:\r
-      break;\r
-    }\r
-#endif\r
-\r
-#ifdef _WIN32\r
-    Sys_Printf ("Running bsp command...\n");\r
-    Sys_Printf ("\n%s\n", strSys.GetBuffer());\r
-\r
-    WinExec( batpath, SW_SHOWNORMAL );\r
-#endif\r
-  }\r
-#ifdef _DEBUG\r
-  // yeah, do it .. but not now right before 1.1-TA-beta release\r
-  Sys_Printf("TODO: erase GPtrArray\n");\r
-#endif\r
-}\r
-\r
-#if 0\r
-\r
-#ifdef _WIN32\r
-\r
-int WINAPI QEW_SetupPixelFormat(HDC hDC, qboolean zbuffer )\r
-{\r
-  static PIXELFORMATDESCRIPTOR pfd = {\r
-    sizeof(PIXELFORMATDESCRIPTOR),  // size of this pfd\r
-    1,                              // version number\r
-    PFD_DRAW_TO_WINDOW |            // support window\r
-    PFD_SUPPORT_OPENGL |            // support OpenGL\r
-    PFD_DOUBLEBUFFER,               // double buffered\r
-    PFD_TYPE_RGBA,                  // RGBA type\r
-    24,                             // 24-bit color depth\r
-    0, 0, 0, 0, 0, 0,               // color bits ignored\r
-    0,                              // no alpha buffer\r
-    0,                              // shift bit ignored\r
-    0,                              // no accumulation buffer\r
-    0, 0, 0, 0,                     // accum bits ignored\r
-    32,                             // depth bits\r
-    0,                              // no stencil buffer\r
-    0,                              // no auxiliary buffer\r
-    PFD_MAIN_PLANE,                 // main layer\r
-    0,                              // reserved\r
-    0, 0, 0                         // layer masks ignored\r
-  };                              //\r
-  int pixelformat = 0;            \r
-\r
-  zbuffer = true;\r
-  if ( !zbuffer )\r
-    pfd.cDepthBits = 0;\r
-\r
-  if ( (pixelformat = ChoosePixelFormat(hDC, &pfd)) == 0 )\r
-  {\r
-    LPVOID lpMsgBuf;\r
-    FormatMessage(\r
-                 FORMAT_MESSAGE_ALLOCATE_BUFFER | \r
-                 FORMAT_MESSAGE_FROM_SYSTEM | \r
-                 FORMAT_MESSAGE_IGNORE_INSERTS,\r
-                 NULL,\r
-                 GetLastError(),\r
-                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language\r
-                 (LPTSTR) &lpMsgBuf,\r
-                 0,\r
-                 NULL \r
-                 );\r
-    Sys_FPrintf (SYS_WRN, "GetLastError: %s", lpMsgBuf);\r
-    Error ("ChoosePixelFormat failed");\r
-  }\r
-\r
-  if (!SetPixelFormat(hDC, pixelformat, &pfd))\r
-    Error ("SetPixelFormat failed");\r
-\r
-  return pixelformat;\r
-}\r
-\r
-#endif\r
-\r
-#endif\r
+/*
+   Copyright (C) 1999-2006 Id Software, Inc. and contributors.
+   For a list of contributors, see the accompanying CONTRIBUTORS file.
+
+   This file is part of GtkRadiant.
+
+   GtkRadiant is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2 of the License, or
+   (at your option) any later version.
+
+   GtkRadiant is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with GtkRadiant; if not, write to the Free Software
+   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ */
+
+/*! \mainpage GtkRadiant Documentation Index
+
+   \section intro_sec Introduction
+
+   This documentation is generated from comments in the source code.
+
+   \section links_sec Useful Links
+
+   \link include/itextstream.h include/itextstream.h \endlink - Global output and error message streams, similar to std::cout and std::cerr. \n
+
+   FileInputStream - similar to std::ifstream (binary mode) \n
+   FileOutputStream - similar to std::ofstream (binary mode) \n
+   TextFileInputStream - similar to std::ifstream (text mode) \n
+   TextFileOutputStream - similar to std::ofstream (text mode) \n
+   StringOutputStream - similar to std::stringstream \n
+
+   \link string/string.h string/string.h \endlink - C-style string comparison and memory management. \n
+   \link os/path.h os/path.h \endlink - Path manipulation for radiant's standard path format \n
+   \link os/file.h os/file.h \endlink - OS file-system access. \n
+
+   ::CopiedString - automatic string memory management \n
+   Array - automatic array memory management \n
+   HashTable - generic hashtable, similar to std::hash_map \n
+
+   \link math/vector.h math/vector.h \endlink - Vectors \n
+   \link math/matrix.h math/matrix.h \endlink - Matrices \n
+   \link math/quaternion.h math/quaternion.h \endlink - Quaternions \n
+   \link math/plane.h math/plane.h \endlink - Planes \n
+   \link math/aabb.h math/aabb.h \endlink - AABBs \n
+
+   Callback MemberCaller0 FunctionCaller - callbacks similar to using boost::function with boost::bind \n
+   SmartPointer SmartReference - smart-pointer and smart-reference similar to Loki's SmartPtr \n
+
+   \link generic/bitfield.h generic/bitfield.h \endlink - Type-safe bitfield \n
+   \link generic/enumeration.h generic/enumeration.h \endlink - Type-safe enumeration \n
+
+   DefaultAllocator - Memory allocation using new/delete, compliant with std::allocator interface \n
+
+   \link debugging/debugging.h debugging/debugging.h \endlink - Debugging macros \n
+
+ */
+
+#include "main.h"
+#include "globaldefs.h"
+
+#include "debugging/debugging.h"
+
+#include "iundo.h"
+
+#include "uilib/uilib.h"
+
+#include "cmdlib.h"
+#include "os/file.h"
+#include "os/path.h"
+#include "stream/stringstream.h"
+#include "stream/textfilestream.h"
+
+#include "gtkutil/messagebox.h"
+#include "gtkutil/image.h"
+#include "console.h"
+#include "texwindow.h"
+#include "map.h"
+#include "mainframe.h"
+#include "commands.h"
+#include "preferences.h"
+#include "environment.h"
+#include "referencecache.h"
+#include "stacktrace.h"
+
+#if GDEF_OS_WINDOWS
+#include <windows.h>
+#endif
+
+void show_splash();
+void hide_splash();
+
+void error_redirect( const gchar *domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data ){
+       gboolean in_recursion;
+       gboolean is_fatal;
+       char buf[256];
+
+       in_recursion = ( log_level & G_LOG_FLAG_RECURSION ) != 0;
+       is_fatal = ( log_level & G_LOG_FLAG_FATAL ) != 0;
+       log_level = (GLogLevelFlags) ( log_level & G_LOG_LEVEL_MASK );
+
+       if ( !message ) {
+               message = "(0) message";
+       }
+
+       if ( domain ) {
+               strcpy( buf, domain );
+       }
+       else{
+               strcpy( buf, "**" );
+       }
+       strcat( buf, "-" );
+
+       switch ( log_level )
+       {
+       case G_LOG_LEVEL_ERROR:
+               if ( in_recursion ) {
+                       strcat( buf, "ERROR (recursed) **: " );
+               }
+               else{
+                       strcat( buf, "ERROR **: " );
+               }
+               break;
+       case G_LOG_LEVEL_CRITICAL:
+               if ( in_recursion ) {
+                       strcat( buf, "CRITICAL (recursed) **: " );
+               }
+               else{
+                       strcat( buf, "CRITICAL **: " );
+               }
+               break;
+       case G_LOG_LEVEL_WARNING:
+               if ( in_recursion ) {
+                       strcat( buf, "WARNING (recursed) **: " );
+               }
+               else{
+                       strcat( buf, "WARNING **: " );
+               }
+               break;
+       case G_LOG_LEVEL_MESSAGE:
+               if ( in_recursion ) {
+                       strcat( buf, "Message (recursed): " );
+               }
+               else{
+                       strcat( buf, "Message: " );
+               }
+               break;
+       case G_LOG_LEVEL_INFO:
+               if ( in_recursion ) {
+                       strcat( buf, "INFO (recursed): " );
+               }
+               else{
+                       strcat( buf, "INFO: " );
+               }
+               break;
+       case G_LOG_LEVEL_DEBUG:
+               if ( in_recursion ) {
+                       strcat( buf, "DEBUG (recursed): " );
+               }
+               else{
+                       strcat( buf, "DEBUG: " );
+               }
+               break;
+       default:
+               /* we are used for a log level that is not defined by GLib itself,
+                * try to make the best out of it.
+                */
+               if ( in_recursion ) {
+                       strcat( buf, "LOG (recursed:" );
+               }
+               else{
+                       strcat( buf, "LOG (" );
+               }
+               if ( log_level ) {
+                       gchar string[] = "0x00): ";
+                       gchar *p = string + 2;
+                       guint i;
+
+                       i = g_bit_nth_msf( log_level, -1 );
+                       *p = i >> 4;
+                       p++;
+                       *p = '0' + ( i & 0xf );
+                       if ( *p > '9' ) {
+                               *p += 'A' - '9' - 1;
+                       }
+
+                       strcat( buf, string );
+               }
+               else{
+                       strcat( buf, "): " );
+               }
+       }
+
+       strcat( buf, message );
+       if ( is_fatal ) {
+               strcat( buf, "\naborting...\n" );
+       }
+       else{
+               strcat( buf, "\n" );
+       }
+
+       // spam it...
+       globalErrorStream() << buf << "\n";
+
+       if (is_fatal) {
+           ERROR_MESSAGE( "GTK+ error: " << buf );
+    }
+}
+
+#if GDEF_COMPILER_MSVC && GDEF_DEBUG
+#include "crtdbg.h"
+#endif
+
+void crt_init(){
+#if GDEF_COMPILER_MSVC && GDEF_DEBUG
+       _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
+#endif
+}
+
+class Lock
+{
+bool m_locked;
+public:
+Lock() : m_locked( false ){
+}
+void lock(){
+       m_locked = true;
+}
+void unlock(){
+       m_locked = false;
+}
+bool locked() const {
+       return m_locked;
+}
+};
+
+class ScopedLock
+{
+Lock& m_lock;
+public:
+ScopedLock( Lock& lock ) : m_lock( lock ){
+       m_lock.lock();
+}
+~ScopedLock(){
+       m_lock.unlock();
+}
+};
+
+class LineLimitedTextOutputStream : public TextOutputStream
+{
+TextOutputStream& outputStream;
+std::size_t count;
+public:
+LineLimitedTextOutputStream( TextOutputStream& outputStream, std::size_t count )
+       : outputStream( outputStream ), count( count ){
+}
+std::size_t write( const char* buffer, std::size_t length ){
+       if ( count != 0 ) {
+               const char* p = buffer;
+               const char* end = buffer + length;
+               for (;; )
+               {
+                       p = std::find( p, end, '\n' );
+                       if ( p == end ) {
+                               break;
+                       }
+                       ++p;
+                       if ( --count == 0 ) {
+                               length = p - buffer;
+                               break;
+                       }
+               }
+               outputStream.write( buffer, length );
+       }
+       return length;
+}
+};
+
+class PopupDebugMessageHandler : public DebugMessageHandler
+{
+StringOutputStream m_buffer;
+Lock m_lock;
+public:
+TextOutputStream& getOutputStream(){
+       if ( !m_lock.locked() ) {
+               return m_buffer;
+       }
+       return globalErrorStream();
+}
+bool handleMessage(){
+       getOutputStream() << "----------------\n";
+       LineLimitedTextOutputStream outputStream( getOutputStream(), 24 );
+       write_stack_trace( outputStream );
+       getOutputStream() << "----------------\n";
+       globalErrorStream() << m_buffer.c_str();
+       if ( !m_lock.locked() ) {
+               ScopedLock lock( m_lock );
+        if (GDEF_DEBUG) {
+            m_buffer << "Break into the debugger?\n";
+            bool handled = ui::alert(ui::root, m_buffer.c_str(), RADIANT_NAME " - Runtime Error", ui::alert_type::YESNO, ui::alert_icon::Error) == ui::alert_response::NO;
+            m_buffer.clear();
+            return handled;
+        } else {
+            m_buffer << "Please report this error to the developers\n";
+            ui::alert(ui::root, m_buffer.c_str(), RADIANT_NAME " - Runtime Error", ui::alert_type::OK, ui::alert_icon::Error);
+            m_buffer.clear();
+        }
+       }
+       return true;
+}
+};
+
+typedef Static<PopupDebugMessageHandler> GlobalPopupDebugMessageHandler;
+
+void streams_init(){
+       GlobalErrorStream::instance().setOutputStream( getSysPrintErrorStream() );
+       GlobalOutputStream::instance().setOutputStream( getSysPrintOutputStream() );
+}
+
+void paths_init(){
+       g_strSettingsPath = environment_get_home_path();
+
+       Q_mkdir( g_strSettingsPath.c_str() );
+
+       g_strAppFilePath = environment_get_app_filepath();
+       g_strAppPath = environment_get_app_path();
+       g_strLibPath = environment_get_lib_path();
+       g_strDataPath = environment_get_data_path();
+
+       // radiant is installed in the parent dir of "tools/"
+       // NOTE: this is not very easy for debugging
+       // maybe add options to lookup in several places?
+       // (for now I had to create symlinks)
+       {
+               StringOutputStream path( 256 );
+               path << g_strDataPath.c_str() << "bitmaps/";
+               BitmapsPath_set( path.c_str() );
+       }
+
+       // we will set this right after the game selection is done
+       g_strGameToolsPath = g_strDataPath;
+}
+
+bool check_version_file( const char* filename, const char* version ){
+       TextFileInputStream file( filename );
+       if ( !file.failed() ) {
+               char buf[10];
+               buf[file.read( buf, 9 )] = '\0';
+
+               // chomp it (the hard way)
+               int chomp = 0;
+               while ( buf[chomp] >= '0' && buf[chomp] <= '9' )
+                       chomp++;
+               buf[chomp] = '\0';
+
+               return string_equal( buf, version );
+       }
+       return false;
+}
+
+void create_global_pid(){
+       /*!
+          the global prefs loading / game selection dialog might fail for any reason we don't know about
+          we need to catch when it happens, to cleanup the stateful prefs which might be killing it
+          and to turn on console logging for lookup of the problem
+          this is the first part of the two step .pid system
+          http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=297
+        */
+       StringOutputStream g_pidFile( 256 ); ///< the global .pid file (only for global part of the startup)
+
+       g_pidFile << SettingsPath_get() << "radiant.pid";
+
+       FILE *pid;
+       pid = fopen( g_pidFile.c_str(), "r" );
+       if ( pid != 0 ) {
+               fclose( pid );
+
+               if ( remove( g_pidFile.c_str() ) == -1 ) {
+                       StringOutputStream msg( 256 );
+                       msg << "WARNING: Could not delete " << g_pidFile.c_str();
+                       ui::alert( ui::root, msg.c_str(), RADIANT_NAME, ui::alert_type::OK, ui::alert_icon::Error );
+               }
+
+               // in debug, never prompt to clean registry, turn console logging auto after a failed start
+               if (!GDEF_DEBUG) {
+                       StringOutputStream msg(256);
+                       msg << RADIANT_NAME " failed to start properly the last time it was run.\n"
+                                       "The failure may be related to current global preferences.\n"
+                                       "Do you want to reset global preferences to defaults?";
+
+                       if (ui::alert(ui::root, msg.c_str(), RADIANT_NAME " - Startup Failure", ui::alert_type::YESNO, ui::alert_icon::Question) == ui::alert_response::YES) {
+                               g_GamesDialog.Reset();
+                       }
+
+                       msg.clear();
+                       msg << "Logging console output to " << SettingsPath_get()
+                               << "radiant.log\nRefer to the log if " RADIANT_NAME " fails to start again.";
+
+                       ui::alert(ui::root, msg.c_str(), RADIANT_NAME " - Console Log", ui::alert_type::OK);
+               }
+
+               // set without saving, the class is not in a coherent state yet
+               // just do the value change and call to start logging, CGamesDialog will pickup when relevant
+               g_GamesDialog.m_bForceLogConsole = true;
+               Sys_EnableLogFile( true );
+       }
+
+       // create a primary .pid for global init run
+       pid = fopen( g_pidFile.c_str(), "w" );
+       if ( pid ) {
+               fclose( pid );
+       }
+}
+
+void remove_global_pid(){
+       StringOutputStream g_pidFile( 256 );
+       g_pidFile << SettingsPath_get() << "radiant.pid";
+
+       // close the primary
+       if ( remove( g_pidFile.c_str() ) == -1 ) {
+               StringOutputStream msg( 256 );
+               msg << "WARNING: Could not delete " << g_pidFile.c_str();
+               ui::alert( ui::root, msg.c_str(), RADIANT_NAME, ui::alert_type::OK, ui::alert_icon::Error );
+       }
+}
+
+/*!
+   now the secondary game dependant .pid file
+   http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=297
+ */
+void create_local_pid(){
+       StringOutputStream g_pidGameFile( 256 ); ///< the game-specific .pid file
+       g_pidGameFile << SettingsPath_get() << g_pGameDescription->mGameFile.c_str() << "/radiant-game.pid";
+
+       FILE *pid = fopen( g_pidGameFile.c_str(), "r" );
+       if ( pid != 0 ) {
+               fclose( pid );
+               if ( remove( g_pidGameFile.c_str() ) == -1 ) {
+                       StringOutputStream msg;
+                       msg << "WARNING: Could not delete " << g_pidGameFile.c_str();
+                       ui::alert( ui::root, msg.c_str(), RADIANT_NAME, ui::alert_type::OK, ui::alert_icon::Error );
+               }
+
+               // in debug, never prompt to clean registry, turn console logging auto after a failed start
+               if (!GDEF_DEBUG) {
+                       StringOutputStream msg;
+                       msg << RADIANT_NAME " failed to start properly the last time it was run.\n"
+                                       "The failure may be caused by current preferences.\n"
+                                       "Do you want to reset all preferences to defaults?";
+
+                       if (ui::alert(ui::root, msg.c_str(), RADIANT_NAME " - Startup Failure", ui::alert_type::YESNO, ui::alert_icon::Question) == ui::alert_response::YES) {
+                               Preferences_Reset();
+                       }
+
+                       msg.clear();
+                       msg << "Logging console output to " << SettingsPath_get()
+                               << "radiant.log\nRefer to the log if " RADIANT_NAME " fails to start again.";
+
+                       ui::alert(ui::root, msg.c_str(), RADIANT_NAME " - Console Log", ui::alert_type::OK);
+               }
+
+               // force console logging on! (will go in prefs too)
+               g_GamesDialog.m_bForceLogConsole = true;
+               Sys_EnableLogFile( true );
+       }
+       else
+       {
+               // create one, will remove right after entering message loop
+               pid = fopen( g_pidGameFile.c_str(), "w" );
+               if ( pid ) {
+                       fclose( pid );
+               }
+       }
+}
+
+
+/*!
+   now the secondary game dependant .pid file
+   http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=297
+ */
+void remove_local_pid(){
+       StringOutputStream g_pidGameFile( 256 );
+       g_pidGameFile << SettingsPath_get() << g_pGameDescription->mGameFile.c_str() << "/radiant-game.pid";
+       remove( g_pidGameFile.c_str() );
+}
+
+void user_shortcuts_init(){
+       StringOutputStream path( 256 );
+       path << SettingsPath_get() << g_pGameDescription->mGameFile.c_str() << '/';
+       LoadCommandMap( path.c_str() );
+       SaveCommandMap( path.c_str() );
+}
+
+void user_shortcuts_save(){
+       StringOutputStream path( 256 );
+       path << SettingsPath_get() << g_pGameDescription->mGameFile.c_str() << '/';
+       SaveCommandMap( path.c_str() );
+}
+
+/* HACK: If ui::main is not called yet,
+gtk_main_quit will not quit, so tell main
+to not call ui::main. This happens when a
+map is loaded from command line and require
+a restart because of wrong format.
+Delete this when the code to not have to
+restart to load another format is merged. */
+bool g_dontStart = false;
+
+int main( int argc, char* argv[] ){
+#if GTK_TARGET == 3
+       // HACK: force legacy GL backend as we don't support GL3 yet
+       setenv("GDK_GL", "LEGACY", 0);
+#if GDEF_OS_LINUX || GDEF_OS_BSD
+       setenv("GDK_BACKEND", "x11", 0);
+#endif
+#endif // GTK_TARGET == 3
+       crt_init();
+
+       streams_init();
+
+#if GDEF_OS_WINDOWS
+       HMODULE lib;
+       lib = LoadLibrary( "dwmapi.dll" );
+       if ( lib != 0 ) {
+               void ( WINAPI *qDwmEnableComposition )( bool bEnable ) = ( void (WINAPI *) ( bool bEnable ) )GetProcAddress( lib, "DwmEnableComposition" );
+               if ( qDwmEnableComposition ) {
+                       qDwmEnableComposition( FALSE );
+               }
+               FreeLibrary( lib );
+       }
+#endif
+
+       const char* mapname = NULL;
+
+#if GDEF_OS_WINDOWS
+       StringOutputStream mapname_buffer( 256 );
+#endif
+
+    char const *error = NULL;
+
+       if ( !ui::init( &argc, &argv, "<filename.map>", &error) ) {
+               g_print( "%s\n", error );
+               return -1;
+       }
+
+       // Gtk already removed parsed `--options`
+       if ( argc == 2 ) {
+               if ( strlen( argv[ 1 ] ) > 1 ) {
+                       mapname = argv[ 1 ];
+
+                       if ( g_str_has_suffix( mapname, ".map" ) ) {
+                               if ( !g_path_is_absolute( mapname ) ) {
+                                       mapname = g_build_filename( g_get_current_dir(), mapname, NULL );
+                               }
+
+#if GDEF_OS_WINDOWS
+                               mapname_buffer << PathCleaned( mapname );
+                               mapname = mapname_buffer.c_str();
+#endif
+                       }
+                       else {
+                               g_print( "bad file name, will not load: %s\n", mapname );
+                               mapname = NULL;
+                       }
+               }
+       }
+       else if ( argc > 2 ) {
+               g_print ( "%s\n", "too many arguments" );
+               return -1;
+       }
+
+       // redirect Gtk warnings to the console
+       g_log_set_handler( "Gdk", (GLogLevelFlags)( G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING |
+                                                                                               G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION ), error_redirect, 0 );
+       g_log_set_handler( "Gtk", (GLogLevelFlags)( G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING |
+                                                                                               G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION ), error_redirect, 0 );
+       g_log_set_handler( "GtkGLExt", (GLogLevelFlags)( G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING |
+                                                                                                        G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION ), error_redirect, 0 );
+       g_log_set_handler( "GLib", (GLogLevelFlags)( G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING |
+                                                                                                G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION ), error_redirect, 0 );
+       g_log_set_handler( 0, (GLogLevelFlags)( G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING |
+                                                                                       G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG | G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION ), error_redirect, 0 );
+
+       GlobalDebugMessageHandler::instance().setHandler( GlobalPopupDebugMessageHandler::instance() );
+
+       environment_init(argc, (char const **) argv);
+
+       paths_init();
+
+       show_splash();
+
+       create_global_pid();
+
+       GlobalPreferences_Init();
+
+       g_GamesDialog.Init();
+
+       g_strGameToolsPath = g_pGameDescription->mGameToolsPath;
+
+       remove_global_pid();
+
+       g_Preferences.Init(); // must occur before create_local_pid() to allow preferences to be reset
+
+       create_local_pid();
+
+       // in a very particular post-.pid startup
+       // we may have the console turned on and want to keep it that way
+       // so we use a latching system
+       if ( g_GamesDialog.m_bForceLogConsole ) {
+               Sys_EnableLogFile( true );
+               g_Console_enableLogging = true;
+               g_GamesDialog.m_bForceLogConsole = false;
+       }
+
+
+       Radiant_Initialise();
+
+       user_shortcuts_init();
+
+       g_pParentWnd = 0;
+       g_pParentWnd = new MainFrame();
+
+       hide_splash();
+
+       if ( mapname != NULL ) {
+               Map_LoadFile( mapname );
+       }
+       else if ( g_bLoadLastMap && !g_strLastMap.empty() ) {
+               Map_LoadFile( g_strLastMap.c_str() );
+       }
+       else
+       {
+               Map_New();
+       }
+
+       // load up shaders now that we have the map loaded
+       // eviltypeguy
+       TextureBrowser_ShowStartupShaders( GlobalTextureBrowser() );
+
+
+       remove_local_pid();
+
+       /* HACK: If ui::main is not called yet,
+       gtk_main_quit will not quit, so tell main
+       to not call ui::main. This happens when a
+       map is loaded from command line and require
+       a restart because of wrong format.
+       Delete this when the code to not have to
+       restart to load another format is merged. */
+       if ( !g_dontStart )
+       {
+               ui::main();
+       }
+
+       // avoid saving prefs when the app is minimized
+       if ( g_pParentWnd->IsSleeping() ) {
+               globalOutputStream() << "Shutdown while sleeping, not saving prefs\n";
+               g_preferences_globals.disable_ini = true;
+       }
+
+       Map_Free();
+
+       if ( !Map_Unnamed( g_map ) ) {
+               g_strLastMap = Map_Name( g_map );
+       }
+
+       delete g_pParentWnd;
+
+       user_shortcuts_save();
+
+       Radiant_Shutdown();
+
+       // close the log file if any
+       Sys_EnableLogFile( false );
+
+       return EXIT_SUCCESS;
+}