Connect CommentClick handler
[xboard.git] / xboard.c
index 69079be..4a4cdad 100644 (file)
--- a/xboard.c
+++ b/xboard.c
@@ -63,6 +63,7 @@
 #include <math.h>
 #include <cairo/cairo.h>
 #include <cairo/cairo-xlib.h>
+#include <gtk/gtk.h>
 
 #if !OMIT_SOCKETS
 # if HAVE_SYS_SOCKET_H
@@ -148,62 +149,18 @@ extern char *getenv();
 #include <locale.h>
 #endif
 
-#include <X11/Intrinsic.h>
-#include <X11/StringDefs.h>
-#include <X11/Shell.h>
-#include <X11/cursorfont.h>
-#include <X11/Xatom.h>
-#include <X11/Xmu/Atoms.h>
-#if USE_XAW3D
-#include <X11/Xaw3d/Dialog.h>
-#include <X11/Xaw3d/Form.h>
-#include <X11/Xaw3d/List.h>
-#include <X11/Xaw3d/Label.h>
-#include <X11/Xaw3d/SimpleMenu.h>
-#include <X11/Xaw3d/SmeBSB.h>
-#include <X11/Xaw3d/SmeLine.h>
-#include <X11/Xaw3d/Box.h>
-#include <X11/Xaw3d/MenuButton.h>
-#include <X11/Xaw3d/Text.h>
-#include <X11/Xaw3d/AsciiText.h>
-#else
-#include <X11/Xaw/Dialog.h>
-#include <X11/Xaw/Form.h>
-#include <X11/Xaw/List.h>
-#include <X11/Xaw/Label.h>
-#include <X11/Xaw/SimpleMenu.h>
-#include <X11/Xaw/SmeBSB.h>
-#include <X11/Xaw/SmeLine.h>
-#include <X11/Xaw/Box.h>
-#include <X11/Xaw/MenuButton.h>
-#include <X11/Xaw/Text.h>
-#include <X11/Xaw/AsciiText.h>
-#endif
-
 // [HGM] bitmaps: put before incuding the bitmaps / pixmaps, to know how many piece types there are.
 #include "common.h"
 
-#if HAVE_LIBXPM
-#include <X11/xpm.h>
-#define IMAGE_EXT "xpm"
-#else
-#define IMAGE_EXT "xim"
-#endif
-
-#include "bitmaps/icon_white.bm"
-#include "bitmaps/icon_black.bm"
-#include "bitmaps/checkmark.bm"
-
 #include "frontend.h"
 #include "backend.h"
 #include "backendz.h"
 #include "moves.h"
 #include "xboard.h"
+#include "xboard2.h"
 #include "childio.h"
 #include "xgamelist.h"
 #include "xhistory.h"
-#include "xevalgraph.h"
-#include "xedittags.h"
 #include "menus.h"
 #include "board.h"
 #include "dialogs.h"
@@ -232,17 +189,15 @@ int main P((int argc, char **argv));
 RETSIGTYPE CmailSigHandler P((int sig));
 RETSIGTYPE IntSigHandler P((int sig));
 RETSIGTYPE TermSizeSigHandler P((int sig));
-Widget CreateMenuBar P((Menu *mb, int boardWidth));
 #if ENABLE_NLS
 char *InsertPxlSize P((char *pattern, int targetPxlSize));
 XFontSet CreateFontSet P((char *base_fnt_lst));
 #else
 char *FindFont P((char *pattern, int targetPxlSize));
 #endif
-void ReadBitmap P((Pixmap *pm, String name, unsigned char bits[],
-                  u_int wreq, u_int hreq));
-void EventProc P((Widget widget, caddr_t unused, XEvent *event));
 void DelayedDrag P((void));
+void ICSInputBoxPopUp P((void));
+#ifdef TODO_GTK
 static void MoveTypeInProc P((Widget widget, caddr_t unused, XEvent *event));
 void HandlePV P((Widget w, XEvent * event,
                     String * params, Cardinal * nParams));
@@ -250,7 +205,6 @@ void DrawPositionProc P((Widget w, XEvent *event,
                     String *prms, Cardinal *nprms));
 void CommentClick P((Widget w, XEvent * event,
                   String * params, Cardinal * nParams));
-void ICSInputBoxPopUp P((void));
 void SelectCommand P((Widget w, XtPointer client_data, XtPointer call_data));
 void KeyBindingProc P((Widget w, XEvent *event, String *prms, Cardinal *nprms));
 void QuitWrapper P((Widget w, XEvent *event, String *prms, Cardinal *nprms));
@@ -259,14 +213,16 @@ static void UpKeyProc P((Widget w, XEvent *event, String *prms, Cardinal *nprms)
 static void DownKeyProc P((Widget w, XEvent *event, String *prms, Cardinal *nprms));
 void TempBackwardProc P((Widget w, XEvent *event, String *prms, Cardinal *nprms));
 void TempForwardProc P((Widget w, XEvent *event, String *prms, Cardinal *nprms));
-Boolean TempBackwardActive = False;
 void ManInner P((Widget w, XEvent *event, String *prms, Cardinal *nprms));
+void SelectMove P((Widget w, XEvent * event, String * params, Cardinal * nParams));
+#endif
+Boolean TempBackwardActive = False;
 void DisplayMove P((int moveNumber));
 void ICSInitScript P((void));
-void SelectMove P((Widget w, XEvent * event, String * params, Cardinal * nParams));
 void update_ics_width P(());
 int CopyMemoProc P(());
 
+#ifdef TODO_GTK
 /*
 * XBoard depends on Xt R4 or higher
 */
@@ -278,7 +234,6 @@ Window xBoardWindow;
 Pixel lowTimeWarningColor, dialogColor, buttonColor; // used in widgets
 Pixmap iconPixmap, wIconPixmap, bIconPixmap, xMarkPixmap;
 Widget shellWidget, formWidget, boardWidget, titleWidget, dropMenu, menuBarWidget;
-Option *optList; // contains all widgets of main window
 #if ENABLE_NLS
 XFontSet fontSet, clockFontSet;
 #else
@@ -288,12 +243,16 @@ XFontStruct *clockFontStruct;
 Font coordFontID, countFontID;
 XFontStruct *coordFontStruct, *countFontStruct;
 XtAppContext appContext;
+#else
+void *shellWidget, *formWidget, *boardWidget, *titleWidget, *dropMenu, *menuBarWidget;
+void *appContext;
+GtkWidget       *mainwindow;
+#endif
+Option *optList; // contains all widgets of main window
 char *layoutName;
 
 char installDir[] = "."; // [HGM] UCI: needed for UCI; probably needs run-time initializtion
 
-Position commentX = -1, commentY = -1;
-Dimension commentW, commentH;
 typedef unsigned int BoardSize;
 BoardSize boardSize;
 Boolean chessProgram;
@@ -303,9 +262,11 @@ int smallLayout = 0, tinyLayout = 0,
   marginW, marginH, // [HGM] for run-time resizing
   fromX = -1, fromY = -1, toX, toY, commentUp = False,
   errorExitStatus = -1, defaultLineGap;
+#ifdef TODO_GTK
 Dimension textHeight;
 Pixel timerForegroundPixel, timerBackgroundPixel;
 Pixel buttonForegroundPixel, buttonBackgroundPixel;
+#endif
 char *chessDir, *programName, *programVersion;
 Boolean alwaysOnTop = False;
 char *icsTextMenuString;
@@ -322,7 +283,6 @@ WindowPlacement wpEngineOutput;
 WindowPlacement wpGameList;
 WindowPlacement wpTags;
 
-
 /* This magic number is the number of intermediate frames used
    in each half of the animation. For short moves it's reduced
    by 1. The total number of frames will be factor * 2 + 1.  */
@@ -343,6 +303,7 @@ DropMenuEnables dmEnables[] = {
     { 'Q', "Queen" }
 };
 
+#ifdef TODO_GTK
 Arg shellArgs[] = {
     { XtNwidth, 0 },
     { XtNheight, 0 },
@@ -388,6 +349,7 @@ XtActionsRec boardActions[] = {
     { "WheelProc", WheelProc },
     { "TabProc", TabProc },
 };
+#endif
 
 char globalTranslations[] =
   ":<Key>F9: MenuItem(Actions.Resign) \n \
@@ -468,11 +430,12 @@ char ICSInputTranslations[] =
 //             as the widget is destroyed before the up-click can call extend-end
 char commentTranslations[] = "<Btn3Down>: extend-end() select-start() CommentClick() \n";
 
+#ifdef TODO_GTK
 String xboardResources[] = {
     "*Error*translations: #override\\n <Key>Return: ErrorPopDown()",
     NULL
   };
-
+#endif
 
 /* Max possible square size */
 #define MAXSQSIZE 256
@@ -599,6 +562,7 @@ Warning: No DIR structure found on this system --\n\
 #endif /* HAVE_DIR_STRUCT */
 
 
+#ifdef TODO_GTK
 /* Arrange to catch delete-window events */
 Atom wm_delete_window;
 void
@@ -609,15 +573,12 @@ CatchDeleteWindow (Widget w, String procname)
   snprintf(buf, sizeof(buf), "<Message>WM_PROTOCOLS: %s() \n", procname);
   XtAugmentTranslations(w, XtParseTranslationTable(buf));
 }
+#endif
 
 void
 BoardToTop ()
 {
-  Arg args[16];
-  XtSetArg(args[0], XtNiconic, False);
-  XtSetValues(shellWidget, args, 1);
-
-  XtPopup(shellWidget, XtGrabNone); /* Raise if lowered  */
+  gtk_window_present(GTK_WINDOW(mainwindow));
 }
 
 //---------------------------------------------------------------------------------------------------------
@@ -795,6 +756,7 @@ ParseCommPortSettings (char *s)
 
 int frameX, frameY;
 
+#ifdef TODO_GTK
 void
 GetActualPlacement (Widget wg, WindowPlacement *wp)
 {
@@ -813,11 +775,13 @@ GetActualPlacement (Widget wg, WindowPlacement *wp)
   wp->width = winAt.width;
   frameX = winAt.x; frameY = winAt.y; // remember to decide if windows touch
 }
+#endif
 
 void
 GetWindowCoords ()
 { // wrapper to shield use of window handles from back-end (make addressible by number?)
   // In XBoard this will have to wait until awareness of window parameters is implemented
+#ifdef TODO_GTK
   GetActualPlacement(shellWidget, &wpMain);
   if(shellUp[EngOutDlg]) GetActualPlacement(shells[EngOutDlg], &wpEngineOutput);
   if(shellUp[HistoryDlg]) GetActualPlacement(shells[HistoryDlg], &wpMoveHistory);
@@ -825,6 +789,7 @@ GetWindowCoords ()
   if(shellUp[GameListDlg]) GetActualPlacement(shells[GameListDlg], &wpGameList);
   if(shellUp[CommentDlg]) GetActualPlacement(shells[CommentDlg], &wpComment);
   if(shellUp[TagsDlg]) GetActualPlacement(shells[TagsDlg], &wpTags);
+#endif
 }
 
 void
@@ -841,7 +806,11 @@ EnsureOnScreen (int *x, int *y, int minX, int minY)
 int
 MainWindowUp ()
 { // [HGM] args: allows testing if main window is realized from back-end
+#ifdef TODO_GTK
   return xBoardWindow != 0;
+#else
+  return 0;
+#endif
 }
 
 void
@@ -875,6 +844,7 @@ ConvertToLine (int argc, char **argv)
 void
 ResizeBoardWindow (int w, int h, int inhibit)
 {
+#ifdef TODO_GTK
     w += marginW + 1; // [HGM] not sure why the +1 is (sometimes) needed...
     h += marginH;
     shellArgs[0].value = w;
@@ -884,8 +854,10 @@ ResizeBoardWindow (int w, int h, int inhibit)
     XtSetValues(shellWidget, &shellArgs[0], inhibit ? 6 : 2);
 
     XSync(xDisplay, False);
+#endif
 }
 
+#ifdef TODO_GTK
 static int
 MakeOneColor (char *name, Pixel *color)
 {
@@ -903,16 +875,19 @@ MakeOneColor (char *name, Pixel *color)
     }
     return False;
 }
+#endif
 
 int
 MakeColors ()
 {   // [HGM] taken out of main(), so it can be called from BoardOptions dialog
     int forceMono = False;
 
+#ifdef TODO_GTK
     if (appData.lowTimeWarning)
        forceMono |= MakeOneColor(appData.lowTimeWarningColor, &lowTimeWarningColor);
     if(appData.dialogColor[0]) MakeOneColor(appData.dialogColor, &dialogColor);
     if(appData.buttonColor[0]) MakeOneColor(appData.buttonColor, &buttonColor);
+#endif
 
     return forceMono;
 }
@@ -920,6 +895,7 @@ MakeColors ()
 void
 InitializeFonts (int clockFontPxlSize, int coordFontPxlSize, int fontPxlSize)
 {   // detervtomine what fonts to use, and create them
+#ifdef TODO_GTK
     XrmValue vTo;
     XrmDatabase xdb;
 
@@ -970,6 +946,7 @@ InitializeFonts (int clockFontPxlSize, int coordFontPxlSize, int fontPxlSize)
 #else
     XrmPutStringResource(&xdb, "*font", appData.font);
 #endif
+#endif
 }
 
 char *
@@ -1033,11 +1010,16 @@ int
 main (int argc, char **argv)
 {
     int i, clockFontPxlSize, coordFontPxlSize, fontPxlSize;
+#ifdef TODO_GTK
     XSetWindowAttributes window_attributes;
     Arg args[16];
     Dimension boardWidth, boardHeight, w, h;
+#else
+#endif
+    int boardWidth, boardHeight, w, h;
     char *p;
     int forceMono = False;
+    GError *gtkerror=NULL;
 
     srandom(time(0)); // [HGM] book: make random truly random
 
@@ -1055,6 +1037,9 @@ main (int argc, char **argv)
        exit(0);
     }
 
+    /* set up GTK */
+    gtk_init (&argc, &argv);
+
     programName = strrchr(argv[0], '/');
     if (programName == NULL)
       programName = argv[0];
@@ -1062,10 +1047,9 @@ main (int argc, char **argv)
       programName++;
 
 #ifdef ENABLE_NLS
-    XtSetLanguageProc(NULL, NULL, NULL);
-    if (appData.debugMode) {
-      fprintf(debugFP, "locale = %s\n", setlocale(LC_ALL, NULL));
-    }
+//    if (appData.debugMode) {
+//      fprintf(debugFP, "locale = %s\n", setlocale(LC_ALL, NULL));
+//    }
 
     bindtextdomain(PACKAGE, LOCALEDIR);
     textdomain(PACKAGE);
@@ -1112,6 +1096,12 @@ main (int argc, char **argv)
         setbuf(debugFP, NULL);
     }
 
+#if ENABLE_NLS
+    if (appData.debugMode) {
+      fprintf(debugFP, "locale = %s\n", setlocale(LC_ALL, NULL));
+    }
+#endif
+
     /* [HGM,HR] make sure board size is acceptable */
     if(appData.NrFiles > BOARD_FILES ||
        appData.NrRanks > BOARD_RANKS   )
@@ -1126,6 +1116,17 @@ main (int argc, char **argv)
        gameInfo.variant = StringToVariant(appData.variant);
        InitPosition(FALSE);
 
+#ifdef TODO_GTK
+    /* GTK */
+    builder = gtk_builder_new();
+    filename = get_glade_filename ("mainboard.glade");
+    if(! gtk_builder_add_from_file (builder, filename, &gtkerror) )
+      {
+      if(gtkerror)
+        printf ("Error: %d %s\n",gtkerror->code,gtkerror->message);
+      }
+    mainwindow = GTK_WIDGET(gtk_builder_get_object (builder, "mainwindow"));
+
     shellWidget =
       XtAppInitialize(&appContext, "XBoard", shellOptions,
                      XtNumber(shellOptions),
@@ -1138,6 +1139,7 @@ main (int argc, char **argv)
     xDisplay = XtDisplay(shellWidget);
     xScreen = DefaultScreen(xDisplay);
     wm_delete_window = XInternAtom(xDisplay, "WM_DELETE_WINDOW", True);
+#endif
 
     /*
      * determine size, based on supplied or remembered -size, or screen size
@@ -1174,10 +1176,20 @@ main (int argc, char **argv)
     } else {
         SizeDefaults *szd = sizeDefaults;
         if (*appData.boardSize == NULLCHAR) {
+#ifdef TODO_GTK
            while (DisplayWidth(xDisplay, xScreen) < szd->minScreenSize ||
                   DisplayHeight(xDisplay, xScreen) < szd->minScreenSize) {
              szd++;
            }
+#else
+            GdkScreen *screen = gtk_window_get_screen(GTK_WINDOW(mainwindow));
+            guint screenwidth = gdk_screen_get_width(screen);
+            guint screenheight = gdk_screen_get_height(screen);
+           while (screenwidth < szd->minScreenSize ||
+                  screenheight < szd->minScreenSize) {
+             szd++;
+           }
+#endif
            if (szd->name == NULL) szd--;
            appData.boardSize = strdup(szd->name); // [HGM] settings: remember name for saving settings
        } else {
@@ -1209,14 +1221,18 @@ main (int argc, char **argv)
     /*
      * Determine what fonts to use.
      */
+#ifdef TODO_GTK
     InitializeFonts(clockFontPxlSize, coordFontPxlSize, fontPxlSize);
+#endif
 
     /*
      * Detect if there are not enough colors available and adapt.
      */
+#ifdef TODO_GTK
     if (DefaultDepth(xDisplay, xScreen) <= 2) {
       appData.monoMode = True;
     }
+#endif
 
     forceMono = MakeColors();
 
@@ -1226,15 +1242,11 @@ main (int argc, char **argv)
        appData.monoMode = True;
     }
 
-    if (appData.monoMode && appData.debugMode) {
-       fprintf(stderr, _("white pixel = 0x%lx, black pixel = 0x%lx\n"),
-               (unsigned long) XWhitePixel(xDisplay, xScreen),
-               (unsigned long) XBlackPixel(xDisplay, xScreen));
-    }
-
     ParseIcsTextColors();
 
+#ifdef TODO_GTK
     XtAppAddActions(appContext, boardActions, XtNumber(boardActions));
+#endif
 
     /*
      * widget hierarchy
@@ -1248,17 +1260,22 @@ main (int argc, char **argv)
     }
 
     optList = BoardPopUp(squareSize, lineGap, (void*)
+#ifdef TODO_GTK
 #if ENABLE_NLS
                                                &clockFontSet);
 #else
                                                clockFontStruct);
 #endif
+#else
+0);
+#endif
     InitDrawingHandle(optList + W_BOARD);
     currBoard        = &optList[W_BOARD];
     boardWidget      = optList[W_BOARD].handle;
     menuBarWidget    = optList[W_MENU].handle;
     dropMenu         = optList[W_DROP].handle;
     titleWidget = optList[optList[W_TITLE].type != -1 ? W_TITLE : W_SMALL].handle;
+#ifdef TODO_GTK
     formWidget  = XtParent(boardWidget);
     XtSetArg(args[0], XtNbackground, &timerBackgroundPixel);
     XtSetArg(args[1], XtNforeground, &timerForegroundPixel);
@@ -1268,23 +1285,21 @@ main (int argc, char **argv)
       XtSetArg(args[1], XtNforeground, &buttonForegroundPixel);
       XtGetValues(optList[W_PAUSE].handle, args, 2);
     }
-    AppendEnginesToMenu(appData.recentEngineList);
+#endif
 
+#ifdef TODO_GTK
     xBoardWindow = XtWindow(boardWidget);
+#endif
 
     // [HGM] it seems the layout code ends here, but perhaps the color stuff is size independent and would
     //       not need to go into InitDrawingSizes().
 
-    /*
-     * Create X checkmark bitmap and initialize option menu checks.
-     */
-    ReadBitmap(&xMarkPixmap, "checkmark.bm",
-              checkmark_bits, checkmark_width, checkmark_height);
     InitMenuMarkers();
 
     /*
      * Create an icon.
      */
+#ifdef TODO_GTK
     ReadBitmap(&wIconPixmap, "icon_white.bm",
               icon_white_bits, icon_white_width, icon_white_height);
     ReadBitmap(&bIconPixmap, "icon_black.bm",
@@ -1293,27 +1308,34 @@ main (int argc, char **argv)
     i = 0;
     XtSetArg(args[i], XtNiconPixmap, iconPixmap);  i++;
     XtSetValues(shellWidget, args, i);
+#endif
 
     /*
      * Create a cursor for the board widget.
      */
+#ifdef TODO_GTK
     window_attributes.cursor = XCreateFontCursor(xDisplay, XC_hand2);
     XChangeWindowAttributes(xDisplay, xBoardWindow,
                            CWCursor, &window_attributes);
+#endif
 
     /*
      * Inhibit shell resizing.
      */
+#ifdef TODO_GTK
     shellArgs[0].value = (XtArgVal) &w;
     shellArgs[1].value = (XtArgVal) &h;
     XtGetValues(shellWidget, shellArgs, 2);
     shellArgs[4].value = shellArgs[2].value = w;
     shellArgs[5].value = shellArgs[3].value = h;
 //    XtSetValues(shellWidget, &shellArgs[2], 4);
+#endif
     marginW =  w - boardWidth; // [HGM] needed to set new shellWidget size when we resize board
     marginH =  h - boardHeight;
 
+#ifdef TODO_GTK
     CatchDeleteWindow(shellWidget, "QuitProc");
+#endif
 
     CreateAnyPieces();
     CreateGrid();
@@ -1328,6 +1350,7 @@ main (int argc, char **argv)
     if (appData.animate || appData.animateDragging)
       CreateAnimVars();
 
+#ifdef TODO_GTK
     XtAugmentTranslations(formWidget,
                          XtParseTranslationTable(globalTranslations));
 
@@ -1335,6 +1358,7 @@ main (int argc, char **argv)
                      (XtEventHandler) MoveTypeInProc, NULL);
     XtAddEventHandler(shellWidget, StructureNotifyMask, False,
                      (XtEventHandler) EventProc, NULL);
+#endif
 
     /* [AS] Restore layout */
     if( wpMoveHistory.visible ) {
@@ -1374,9 +1398,16 @@ main (int argc, char **argv)
     InitPosition(TRUE);
     UpdateLogos(TRUE);
 //    XtSetKeyboardFocus(shellWidget, formWidget);
+#ifdef TODO_GTK
     XSetInputFocus(xDisplay, XtWindow(formWidget), RevertToPointerRoot, CurrentTime);
+#endif
+
+    /* check for GTK events and process them */
+//    gtk_main();
+while(1) {
+gtk_main_iteration();
+}
 
-    XtAppMainLoop(appContext);
     if (appData.debugMode) fclose(debugFP); // [DM] debug
     return 0;
 }
@@ -1470,6 +1501,7 @@ InsertPxlSize (char *pattern, int targetPxlSize)
     return base_fnt_lst;
 }
 
+#ifdef TODO_GTK
 XFontSet
 CreateFontSet (char *base_fnt_lst)
 {
@@ -1504,6 +1536,7 @@ CreateFontSet (char *base_fnt_lst)
     }
     return fntSet;
 }
+#endif
 #else // not ENABLE_NLS
 /*
  * Find a font that matches "pattern" that is as close as
@@ -1520,6 +1553,7 @@ FindFont (char *pattern, int targetPxlSize)
     char **fonts, *p, *best, *scalable, *scalableTail;
     int i, j, nfonts, minerr, err, pxlSize;
 
+#ifdef TODO_GTK
     fonts = XListFonts(xDisplay, pattern, 999999, &nfonts);
     if (nfonts < 1) {
        fprintf(stderr, _("%s: no fonts match pattern %s\n"),
@@ -1568,43 +1602,25 @@ FindFont (char *pattern, int targetPxlSize)
                pattern, targetPxlSize, p);
     }
     XFreeFontNames(fonts);
+#endif
     return p;
 }
 #endif
 
 void
-ReadBitmap (Pixmap *pm, String name, unsigned char bits[], u_int wreq, u_int hreq)
-{
-    if (bits != NULL) {
-       *pm = XCreateBitmapFromData(xDisplay, xBoardWindow, (char *) bits,
-                                   wreq, hreq);
-    }
-}
-
-void
-MarkMenuItem (char *menuRef, int state)
-{
-    MenuItem *item = MenuNameToItem(menuRef);
-
-    if(item) {
-       Arg args[2];
-       XtSetArg(args[0], XtNleftBitmap, state ? xMarkPixmap : None);
-       XtSetValues(item->handle, args, 1);
-    }
-}
-
-void
 EnableNamedMenuItem (char *menuRef, int state)
 {
     MenuItem *item = MenuNameToItem(menuRef);
 
-    if(item) XtSetSensitive(item->handle, state);
+    if(item) gtk_widget_set_sensitive(item->handle, state);
 }
 
 void
 EnableButtonBar (int state)
 {
+#ifdef TODO_GTK
     XtSetSensitive(optList[W_BUTTON].handle, state);
+#endif
 }
 
 
@@ -1617,6 +1633,44 @@ SetMenuEnables (Enables *enab)
   }
 }
 
+#ifdef TODO_GTK
+gboolean KeyPressProc(window, eventkey, data)
+     GtkWindow *window;
+     GdkEventKey  *eventkey;
+     gpointer data;
+{
+
+    MoveTypeInProc(eventkey); // pop up for typed in moves
+
+    // handle shift+<number> cases
+    if (eventkey->state & GDK_SHIFT_MASK) {
+        guint keyval;
+
+        gdk_keymap_translate_keyboard_state(NULL, eventkey->hardware_keycode,
+                                           0, eventkey->group,
+                                           &keyval, NULL, NULL, NULL);
+        switch(keyval) {
+            case GDK_1:
+                AskQuestionEvent("Direct command", "Send to chess program:", "", "1");
+                break;
+            case GDK_2:
+                AskQuestionEvent("Direct command", "Send to second chess program:", "", "2");
+                break;
+            default:
+                break;
+        }
+    }
+
+    /* check for other key values */
+    switch(eventkey->keyval) {
+        case GDK_question:
+         AboutGameEvent();
+         break;
+        default:
+         break;
+    }
+    return False;
+}
 void
 KeyBindingProc (Widget w, XEvent *event, String *prms, Cardinal *nprms)
 {   // [HGM] new method of key binding: specify MenuItem(FlipView) in stead of FlipViewProc in translation string
@@ -1625,22 +1679,12 @@ KeyBindingProc (Widget w, XEvent *event, String *prms, Cardinal *nprms)
     item = MenuNameToItem(prms[0]);
     if(item) ((MenuProc *) item->proc) ();
 }
-
-static void
-MenuEngineSelect (Widget w, caddr_t addr, caddr_t index)
-{
-    RecentEngineEvent((int) (intptr_t) addr);
-}
-
-void
-AppendMenuItem (char *msg, int n)
-{
-    CreateMenuItem((Widget) optList[W_ENGIN].textValue, msg, (XtCallbackProc) MenuEngineSelect, n);
-}
+#endif
 
 void
 SetupDropMenu ()
 {
+#ifdef TODO_GTK
     int i, j, count;
     char label[32];
     Arg args[16];
@@ -1661,6 +1705,7 @@ SetupDropMenu ()
        XtSetArg(args[j], XtNlabel, label); j++;
        XtSetValues(entry, args, j);
     }
+#endif
 }
 
 static void
@@ -1672,7 +1717,6 @@ do_flash_delay (unsigned long msec)
 void
 FlashDelay (int flash_delay)
 {
-       XSync(xDisplay, False);
        if(flash_delay) do_flash_delay(flash_delay);
 }
 
@@ -1686,6 +1730,7 @@ Fraction (int x, int start, int stop)
 
 static WindowPlacement wpNew;
 
+#ifdef TODO_GTK
 void
 CoDrag (Widget sh, WindowPlacement *wp)
 {
@@ -1716,9 +1761,11 @@ CoDrag (Widget sh, WindowPlacement *wp)
     wp->y += wpNew.y - wpMain.y;
     if(touch == 1) wp->x += wpNew.width - wpMain.width; else
     if(touch == 3) wp->y += wpNew.height - wpMain.height;
+#ifdef TODO_GTK
     XtSetArg(args[j], XtNx, wp->x); j++;
     XtSetArg(args[j], XtNy, wp->y); j++;
     XtSetValues(sh, args, j);
+#endif
 }
 
 void
@@ -1740,7 +1787,11 @@ ReSize (WindowPlacement *wp)
        if(optList[W_BOARD].value > h) optList[W_BOARD].value = h;
 }
 
+#ifdef TODO_GTK
 static XtIntervalId delayedDragID = 0;
+#else
+static int delayedDragID = 0;
+#endif
 
 void
 DragProc ()
@@ -1764,77 +1815,39 @@ DragProc ()
        delayedDragID = 0; // now drag executed, make sure next DelayedDrag will not cancel timer event (which could now be used by other)
        busy = 0;
 }
-
+#endif
 
 void
 DelayedDrag ()
 {
+#ifdef TODO_GTK
     if(delayedDragID) XtRemoveTimeOut(delayedDragID); // cancel pending
     delayedDragID =
       XtAppAddTimeOut(appContext, 200, (XtTimerCallbackProc) DragProc, (XtPointer) 0); // and schedule new one 50 msec later
+#endif
 }
 
+#ifdef TODO_GTK
 void
 EventProc (Widget widget, caddr_t unused, XEvent *event)
 {
     if(XtIsRealized(widget) && event->type == ConfigureNotify || appData.useStickyWindows)
        DelayedDrag(); // as long as events keep coming in faster than 50 msec, they destroy each other
 }
+#endif
 
 /*
  * event handler for redrawing the board
  */
+#ifdef TODO_GTK
 void
 DrawPositionProc (Widget w, XEvent *event, String *prms, Cardinal *nprms)
 {
     DrawPosition(True, NULL);
 }
+#endif
 
 
-void
-HandlePV (Widget w, XEvent * event, String * params, Cardinal * nParams)
-{   // [HGM] pv: walk PV
-    MovePV(event->xmotion.x, event->xmotion.y, lineGap + BOARD_HEIGHT * (squareSize + lineGap));
-}
-
-static int savedIndex;  /* gross that this is global */
-
-void
-CommentClick (Widget w, XEvent * event, String * params, Cardinal * nParams)
-{
-       String val;
-       XawTextPosition index, dummy;
-       Arg arg;
-
-       XawTextGetSelectionPos(w, &index, &dummy);
-       XtSetArg(arg, XtNstring, &val);
-       XtGetValues(w, &arg, 1);
-       ReplaceComment(savedIndex, val);
-       if(savedIndex != currentMove) ToNrEvent(savedIndex);
-       LoadVariation( index, val ); // [HGM] also does the actual moving to it, now
-}
-
-void
-EditCommentPopUp (int index, char *title, char *text)
-{
-    savedIndex = index;
-    if (text == NULL) text = "";
-    NewCommentPopup(title, text, index);
-}
-
-void
-CommentPopUp (char *title, char *text)
-{
-    savedIndex = currentMove; // [HGM] vari
-    NewCommentPopup(title, text, currentMove);
-}
-
-void
-CommentPopDown ()
-{
-    PopDown(CommentDlg);
-}
-
 
 /* Disable all user input other than deleting the window */
 static int frozen = 0;
@@ -1844,7 +1857,7 @@ FreezeUI ()
 {
   if (frozen) return;
   /* Grab by a widget that doesn't accept input */
-  XtAddGrab(optList[W_MESSG].handle, TRUE, FALSE);
+  gtk_grab_add(optList[W_MESSG].handle);
   frozen = 1;
 }
 
@@ -1853,19 +1866,17 @@ void
 ThawUI ()
 {
   if (!frozen) return;
-  XtRemoveGrab(optList[W_MESSG].handle);
+  gtk_grab_remove(optList[W_MESSG].handle);
   frozen = 0;
 }
 
 void
 ModeHighlight ()
 {
-    Arg args[16];
     static int oldPausing = FALSE;
     static GameMode oldmode = (GameMode) -1;
     char *wname;
-
-    if (!boardWidget || !XtIsRealized(boardWidget)) return;
+    if (!boardWidget) return;
 
     if (pausing != oldPausing) {
        oldPausing = pausing;
@@ -1875,16 +1886,9 @@ ModeHighlight ()
          /* Always toggle, don't set.  Previous code messes up when
             invoked while the button is pressed, as releasing it
             toggles the state again. */
-         {
-           Pixel oldbg, oldfg;
-           XtSetArg(args[0], XtNbackground, &oldbg);
-           XtSetArg(args[1], XtNforeground, &oldfg);
-           XtGetValues(optList[W_PAUSE].handle,
-                       args, 2);
-           XtSetArg(args[0], XtNbackground, oldfg);
-           XtSetArg(args[1], XtNforeground, oldbg);
-         }
-         XtSetValues(optList[W_PAUSE].handle, args, 2);
+           GdkColor color;     
+            gdk_color_parse( pausing ? "#808080" : "#F0F0F0", &color );
+            gtk_widget_modify_bg ( GTK_WIDGET(optList[W_PAUSE].handle), GTK_STATE_NORMAL, &color );
        }
     }
 
@@ -1910,6 +1914,7 @@ ModeHighlight ()
  * Button/menu procedures
  */
 
+#ifdef TODO_GTK
 /* this variable is shared between CopyPositionProc and SendPositionSelection */
 char *selected_fen_position=NULL;
 
@@ -1976,6 +1981,7 @@ SendPositionSelection (Widget w, Atom *selection, Atom *target,
     return False;
   }
 }
+#endif
 
 /* note: when called from menu all parameters are NULL, so no clue what the
  * Widget which was clicked on was, or what the click event was
@@ -1983,6 +1989,7 @@ SendPositionSelection (Widget w, Atom *selection, Atom *target,
 void
 CopySomething (char *src)
 {
+#ifdef TODO_GTK
     selected_fen_position = src;
     /*
      * Set both PRIMARY (the selection) and CLIPBOARD, since we don't
@@ -1999,8 +2006,10 @@ CopySomething (char *src)
                   SendPositionSelection,
                   NULL/* lose_ownership_proc */ ,
                   NULL/* transfer_done_proc */);
+#endif
 }
 
+#ifdef TODO_GTK
 /* function called when the data to Paste is ready */
 static void
 PastePositionCB (Widget w, XtPointer client_data, Atom *selection,
@@ -2012,12 +2021,14 @@ PastePositionCB (Widget w, XtPointer client_data, Atom *selection,
   EditPositionPasteFEN(fenstr);
   XtFree(value);
 }
+#endif
 
 /* called when Paste Position button is pressed,
  * all parameters will be NULL */
 void
 PastePositionProc ()
 {
+#ifdef TODO_GTK
     XtGetSelectionValue(menuBarWidget,
       appData.pasteSelection ? XA_PRIMARY: XA_CLIPBOARD(xDisplay), XA_STRING,
       /* (XtSelectionCallbackProc) */ PastePositionCB,
@@ -2029,8 +2040,10 @@ PastePositionProc ()
       CurrentTime
     );
     return;
+#endif
 }
 
+#ifdef TODO_GTK
 /* note: when called from menu all parameters are NULL, so no clue what the
  * Widget which was clicked on was, or what the click event was
  */
@@ -2053,12 +2066,14 @@ PasteGameCB (Widget w, XtPointer client_data, Atom *selection,
   XtFree(value);
   LoadGameFromFile(gamePasteFilename, 0, gamePasteFilename, TRUE);
 }
+#endif
 
 /* called when Paste Game button is pressed,
  * all parameters will be NULL */
 void
 PasteGameProc ()
 {
+#ifdef TODO_GTK
     XtGetSelectionValue(menuBarWidget,
       appData.pasteSelection ? XA_PRIMARY: XA_CLIPBOARD(xDisplay), XA_STRING,
       /* (XtSelectionCallbackProc) */ PasteGameCB,
@@ -2070,59 +2085,52 @@ PasteGameProc ()
       CurrentTime
     );
     return;
+#endif
 }
 
 
+#ifdef TODO_GTK
 void
 QuitWrapper (Widget w, XEvent *event, String *prms, Cardinal *nprms)
 {
     QuitProc();
 }
+#endif
 
 int
 ShiftKeys ()
 {   // bassic primitive for determining if modifier keys are pressed
+    int i,j,  k=0;
+#ifdef TODO_GTK
     long int codes[] = { XK_Meta_L, XK_Meta_R, XK_Control_L, XK_Control_R, XK_Shift_L, XK_Shift_R };
     char keys[32];
-    int i,j,  k=0;
     XQueryKeymap(xDisplay,keys);
     for(i=0; i<6; i++) {
        k <<= 1;
        j = XKeysymToKeycode(xDisplay, codes[i]);
        k += ( (keys[j>>3]&1<<(j&7)) != 0 );
     }
+#endif
     return k;
 }
 
-static void
-MoveTypeInProc (Widget widget, caddr_t unused, XEvent *event)
+void MoveTypeInProc(eventkey)
+    GdkEventKey  *eventkey;
 {
     char buf[10];
-    KeySym sym;
-    int n = XLookupString(&(event->xkey), buf, 10, &sym, NULL);
-    if ( n == 1 && *buf >= 32 // printable
-        && !(ShiftKeys() & 0x3C) // no Alt, Ctrl
-       ) BoxAutoPopUp (buf);
-}
-
-static void
-UpKeyProc (Widget w, XEvent *event, String *prms, Cardinal *nprms)
-{   // [HGM] input: let up-arrow recall previous line from history
-    IcsKey(1);
-}
 
-static void
-DownKeyProc (Widget w, XEvent *event, String *prms, Cardinal *nprms)
-{   // [HGM] input: let down-arrow recall next line from history
-    IcsKey(-1);
-}
+    // ingnore if ctrl or alt is pressed
+    if (eventkey->state & (GDK_CONTROL_MASK | GDK_MOD1_MASK)) {
+        return;
+    }
 
-static void
-EnterKeyProc (Widget w, XEvent *event, String *prms, Cardinal *nprms)
-{
-    IcsKey(0);
+    buf[0]=eventkey->keyval;
+    buf[1]='\0';
+    if (*buf >= 32)        
+       BoxAutoPopUp (buf);
 }
 
+#ifdef TODO_GTK
 void
 TempBackwardProc (Widget w, XEvent *event, String *prms, Cardinal *nprms)
 {
@@ -2160,16 +2168,20 @@ ManInner (Widget w, XEvent *event, String *prms, Cardinal *nprms)
     snprintf(buf, sizeof(buf), "xterm -e man %s &", name);
     system(buf);
 }
+#endif
 
 void
 ManProc ()
 {   // called from menu
+#ifdef TODO_GTK
     ManInner(NULL, NULL, NULL, NULL);
+#endif
 }
 
 void
 SetWindowTitle (char *text, char *title, char *icon)
 {
+#ifdef TODO_GTK
     Arg args[16];
     int i;
     if (appData.titleInWindow) {
@@ -2182,6 +2194,11 @@ SetWindowTitle (char *text, char *title, char *icon)
     XtSetArg(args[i], XtNtitle, (XtArgVal) title);      i++;
     XtSetValues(shellWidget, args, i);
     XSync(xDisplay, False);
+#endif
+    if (appData.titleInWindow) {
+       SetWidgetLabel(titleWidget, text);
+    }
+    gtk_window_set_title (GTK_WINDOW(shells[BoardWindow]), title);
 }
 
 
@@ -2194,6 +2211,7 @@ NullXErrorCheck (Display *dpy, XErrorEvent *error_event)
 void
 DisplayIcsInteractionTitle (String message)
 {
+#ifdef TODO_GTK
   if (oldICSInteractionTitle == NULL) {
     /* Magic to find the old window title, adapted from vim */
     char *wina = getenv("WINDOWID");
@@ -2218,183 +2236,50 @@ DisplayIcsInteractionTitle (String message)
   }
   printf("\033]0;%s\007", message);
   fflush(stdout);
+#endif
 }
 
 
-XtIntervalId delayedEventTimerXID = 0;
-DelayedEventCallback delayedEventCallback = 0;
-
-void
-FireDelayedEvent ()
-{
-    delayedEventTimerXID = 0;
-    delayedEventCallback();
-}
-
-void
-ScheduleDelayedEvent (DelayedEventCallback cb, long millisec)
-{
-    if(delayedEventTimerXID && delayedEventCallback == cb)
-       // [HGM] alive: replace, rather than add or flush identical event
-       XtRemoveTimeOut(delayedEventTimerXID);
-    delayedEventCallback = cb;
-    delayedEventTimerXID =
-      XtAppAddTimeOut(appContext, millisec,
-                     (XtTimerCallbackProc) FireDelayedEvent, (XtPointer) 0);
-}
-
-DelayedEventCallback
-GetDelayedEvent ()
-{
-  if (delayedEventTimerXID) {
-    return delayedEventCallback;
-  } else {
-    return NULL;
-  }
-}
-
-void
-CancelDelayedEvent ()
-{
-  if (delayedEventTimerXID) {
-    XtRemoveTimeOut(delayedEventTimerXID);
-    delayedEventTimerXID = 0;
-  }
-}
-
-XtIntervalId loadGameTimerXID = 0;
-
-int
-LoadGameTimerRunning ()
-{
-    return loadGameTimerXID != 0;
-}
-
-int
-StopLoadGameTimer ()
-{
-    if (loadGameTimerXID != 0) {
-       XtRemoveTimeOut(loadGameTimerXID);
-       loadGameTimerXID = 0;
-       return TRUE;
-    } else {
-       return FALSE;
-    }
-}
-
-void
-LoadGameTimerCallback (XtPointer arg, XtIntervalId *id)
-{
-    loadGameTimerXID = 0;
-    AutoPlayGameLoop();
-}
-
-void
-StartLoadGameTimer (long millisec)
-{
-    loadGameTimerXID =
-      XtAppAddTimeOut(appContext, millisec,
-                     (XtTimerCallbackProc) LoadGameTimerCallback,
-                     (XtPointer) 0);
-}
-
-XtIntervalId analysisClockXID = 0;
-
 void
-AnalysisClockCallback (XtPointer arg, XtIntervalId *id)
-{
-    if (gameMode == AnalyzeMode || gameMode == AnalyzeFile
-         || appData.icsEngineAnalyze) { // [DM]
-       AnalysisPeriodicEvent(0);
-       StartAnalysisClock();
-    }
-}
-
-void
-StartAnalysisClock ()
+DisplayTimerLabel (Option *opt, char *color, long timer, int highlight)
 {
-    analysisClockXID =
-      XtAppAddTimeOut(appContext, 2000,
-                     (XtTimerCallbackProc) AnalysisClockCallback,
-                     (XtPointer) 0);
-}
+    GtkWidget *w = (GtkWidget *) opt->handle;
+    char *markup;
+    char bgcolor[10];
+    char fgcolor[10];
 
-XtIntervalId clockTimerXID = 0;
-
-int
-ClockTimerRunning ()
-{
-    return clockTimerXID != 0;
-}
-
-int
-StopClockTimer ()
-{
-    if (clockTimerXID != 0) {
-       XtRemoveTimeOut(clockTimerXID);
-       clockTimerXID = 0;
-       return TRUE;
+    if (highlight) {
+       strcpy(bgcolor, "black");
+        strcpy(fgcolor, "white");
     } else {
-       return FALSE;
+        strcpy(bgcolor, "white");
+        strcpy(fgcolor, "black");
     }
-}
-
-void
-ClockTimerCallback (XtPointer arg, XtIntervalId *id)
-{
-    clockTimerXID = 0;
-    DecrementClocks();
-}
-
-void
-StartClockTimer (long millisec)
-{
-    clockTimerXID =
-      XtAppAddTimeOut(appContext, millisec,
-                     (XtTimerCallbackProc) ClockTimerCallback,
-                     (XtPointer) 0);
-}
-
-void
-DisplayTimerLabel (Option *opt, char *color, long timer, int highlight)
-{
-    char buf[MSG_SIZ];
-    Arg args[16];
-    Widget w = (Widget) opt->handle;
-
-    /* check for low time warning */
-    Pixel foregroundOrWarningColor = timerForegroundPixel;
-
     if (timer > 0 &&
         appData.lowTimeWarning &&
-        (timer / 1000) < appData.icsAlarmTime)
-      foregroundOrWarningColor = lowTimeWarningColor;
-
-    if (appData.clockMode) {
-      snprintf(buf, MSG_SIZ, "%s:%s%s", color, appData.logoSize && !partnerUp ? "\n" : " ", TimeString(timer));
-      XtSetArg(args[0], XtNlabel, buf);
-    } else {
-      snprintf(buf, MSG_SIZ, "%s  ", color);
-      XtSetArg(args[0], XtNlabel, buf);
+        (timer / 1000) < appData.icsAlarmTime) {
+        strcpy(fgcolor, appData.lowTimeWarningColor);
     }
 
-    if (highlight) {
-
-       XtSetArg(args[1], XtNbackground, foregroundOrWarningColor);
-       XtSetArg(args[2], XtNforeground, timerBackgroundPixel);
+    if (appData.clockMode) {
+        markup = g_markup_printf_escaped("<span size=\"xx-large\" weight=\"heavy\" background=\"%s\" foreground=\"%s\">%s:%s%s</span>",
+                                        bgcolor, fgcolor, color, appData.logoSize && !partnerUp ? "\n" : " ", TimeString(timer));
     } else {
-       XtSetArg(args[1], XtNbackground, timerBackgroundPixel);
-       XtSetArg(args[2], XtNforeground, foregroundOrWarningColor);
+        markup = g_markup_printf_escaped("<span size=\"xx-large\" weight=\"heavy\" background=\"%s\" foreground=\"%s\">%s  </span>",
+                                        bgcolor, fgcolor, color);
     }
-
-    XtSetValues(w, args, 3);
+    gtk_label_set_markup(GTK_LABEL(w), markup);
+    g_free(markup);
 }
 
+#ifdef TODO_GTK
 static Pixmap *clockIcons[] = { &wIconPixmap, &bIconPixmap };
+#endif
 
 void
 SetClockIcon (int color)
 {
+#ifdef TODO_GTK
     Arg args[16];
     Pixmap pm = *clockIcons[color];
     if (iconPixmap != pm) {
@@ -2402,25 +2287,53 @@ SetClockIcon (int color)
        XtSetArg(args[0], XtNiconPixmap, iconPixmap);
        XtSetValues(shellWidget, args, 1);
     }
+#endif
 }
 
-void
-DoInputCallback (caddr_t closure, int *source, XtInputId *xid)
-{
-    InputSource *is = (InputSource *) closure;
+#define INPUT_SOURCE_BUF_SIZE 8192
+
+typedef struct {
+    CPKind kind;
+    int fd;
+    int lineByLine;
+    char *unused;
+    InputCallback func;
+    guint sid;
+    char buf[INPUT_SOURCE_BUF_SIZE];
+    VOIDSTAR closure;
+} InputSource;
+
+gboolean
+DoInputCallback(io, cond, data)
+     GIOChannel  *io;
+     GIOCondition cond;
+     gpointer    *data;
+{
+  /* read input from one of the input source (for example a chess program, ICS, etc).
+   * and call a function that will handle the input
+   */
+
     int count;
     int error;
     char *p, *q;
 
+    /* All information (callback function, file descriptor, etc) is
+     * saved in an InputSource structure
+     */
+    InputSource *is = (InputSource *) data;
+
     if (is->lineByLine) {
        count = read(is->fd, is->unused,
                     INPUT_SOURCE_BUF_SIZE - (is->unused - is->buf));
        if (count <= 0) {
            (is->func)(is, is->closure, is->buf, count, count ? errno : 0);
-           return;
+           return True;
        }
        is->unused += count;
        p = is->buf;
+       /* break input into lines and call the callback function on each
+        * line
+        */
        while (p < is->unused) {
            q = memchr(p, '\n', is->unused - p);
            if (q == NULL) break;
@@ -2428,12 +2341,16 @@ DoInputCallback (caddr_t closure, int *source, XtInputId *xid)
            (is->func)(is, is->closure, p, q - p, 0);
            p = q;
        }
+       /* remember not yet used part of the buffer */
        q = is->buf;
        while (p < is->unused) {
            *q++ = *p++;
        }
        is->unused = q;
     } else {
+      /* read maximum length of input buffer and send the whole buffer
+       * to the callback function
+       */
        count = read(is->fd, is->buf, INPUT_SOURCE_BUF_SIZE);
        if (count == -1)
          error = errno;
@@ -2441,12 +2358,17 @@ DoInputCallback (caddr_t closure, int *source, XtInputId *xid)
          error = 0;
        (is->func)(is, is->closure, is->buf, count, error);
     }
+    return True; // Must return true or the watch will be removed
 }
 
-InputSourceRef
-AddInputSource (ProcRef pr, int lineByLine, InputCallback func, VOIDSTAR closure)
+InputSourceRef AddInputSource(pr, lineByLine, func, closure)
+     ProcRef pr;
+     int lineByLine;
+     InputCallback func;
+     VOIDSTAR closure;
 {
     InputSource *is;
+    GIOChannel *channel;
     ChildProc *cp = (ChildProc *) pr;
 
     is = (InputSource *) calloc(1, sizeof(InputSource));
@@ -2459,26 +2381,32 @@ AddInputSource (ProcRef pr, int lineByLine, InputCallback func, VOIDSTAR closure
        is->kind = cp->kind;
        is->fd = cp->fdFrom;
     }
-    if (lineByLine) {
-       is->unused = is->buf;
-    }
+    if (lineByLine)
+      is->unused = is->buf;
+    else
+      is->unused = NULL;
+
+   /* GTK-TODO: will this work on windows?*/
+
+    channel = g_io_channel_unix_new(is->fd);
+    g_io_channel_set_close_on_unref (channel, TRUE);
+    is->sid = g_io_add_watch(channel, G_IO_IN,(GIOFunc) DoInputCallback, is);
 
-    is->xid = XtAppAddInput(appContext, is->fd,
-                           (XtPointer) (XtInputReadMask),
-                           (XtInputCallbackProc) DoInputCallback,
-                           (XtPointer) is);
     is->closure = closure;
     return (InputSourceRef) is;
 }
 
+
 void
-RemoveInputSource (InputSourceRef isr)
+RemoveInputSource(isr)
+     InputSourceRef isr;
 {
     InputSource *is = (InputSource *) isr;
 
-    if (is->xid == 0) return;
-    XtRemoveInput(is->xid);
-    is->xid = 0;
+    if (is->sid == 0) return;
+    g_source_remove(is->sid);
+    is->sid = 0;
+    return;
 }
 
 #ifndef HAVE_USLEEP
@@ -2498,8 +2426,6 @@ FrameDelay (int time)
 {
   struct itimerval delay;
 
-  XSync(xDisplay, False);
-
   if (time > 0) {
     frameWaiting = True;
     signal(SIGALRM, FrameAlarm);
@@ -2520,7 +2446,11 @@ FrameDelay (int time)
 void
 FrameDelay (int time)
 {
+#ifdef TODO_GTK
   XSync(xDisplay, False);
+#endif
+//  gtk_main_iteration_do(False);
+
   if (time > 0)
     usleep(time * 1000);
 }