Пример #1
0
// Select a file
static void select_file(const string& /* question */, string& reply)
{
    gdbOpenFileCB(find_shell(), 0, 0);

    open_file_reply = "";
    while (open_file_reply.empty() 
	   && gdb->running() && !gdb->isReadyWithPrompt())
	XtAppProcessEvent(XtWidgetToApplicationContext(gdb_w), XtIMAll);

    // Found a reply - return
    reply = open_file_reply + "\n";
}
Пример #2
0
void XtEvents::idleProcess()
    {
    for( int i = 0;
         i < 1000; // only up to 1000 iterations, in order to avoid starving
         ++i )
        {
        XtInputMask mask = XtAppPending( context );
        mask &= ~XtIMXEvent; // these are processed in x11Event()
        if( mask == 0 )
            break;
        XtAppProcessEvent( context, mask );
        }
    }
Пример #3
0
/* ************************************************************* */
static void animate(XtPointer closure, XtIntervalId *id )
{
  XtInputMask maske;
  if ((maske = XtAppPending(kontext)))
    {
      XtAppProcessEvent(kontext, maske);
    } 
  else
    {
      C3D_postredisplay();
      animateID = XtAppAddTimeOut(kontext, 1, animate, 0);
    }
}
Пример #4
0
/*
** PopDownBugPatch
**
** Under some circumstances, popping down a dialog and its parent in
** rapid succession causes a crash.  This routine delays and
** processs events until receiving a ReparentNotify event.
** (I have no idea why a ReparentNotify event occurs at all, but it does
** mark the point where it is safe to destroy or pop down the parent, and
** it might have something to do with the bug.)  There is a failsafe in
** the form of a ~1.5 second timeout in case no ReparentNotify arrives.
** Use this sparingly, only when real crashes are observed, and periodically
** check to make sure that it is still necessary.
*/
void PopDownBugPatch(Widget w)
{
    time_t stopTime;

    stopTime = time(NULL) + 1;
    while (time(NULL) <= stopTime) {
    	XEvent event;
    	XtAppContext context = XtWidgetToApplicationContext(w);
    	XtAppPeekEvent(context, &event);
    	if (event.xany.type == ReparentNotify)
    	    return;
    	XtAppProcessEvent(context, XtIMAll);
    }
}
Пример #5
0
Файл: xsm.c Проект: aosm/X11
static void
NewConnectionXtProc(XtPointer client_data, int *source, XtInputId *id)
{
    IceConn 	ice_conn;
    char	*connstr;
    IceAcceptStatus status;

    if (shutdownInProgress)
    {
	/*
	 * Don't accept new connections if we are in the middle
	 * of a shutdown.
	 */

	return;
    }

    ice_conn = IceAcceptConnection((IceListenObj) client_data, &status);
    if (! ice_conn) {
	if (verbose)
	    printf ("IceAcceptConnection failed\n");
    } else {
	IceConnectStatus cstatus;

	while ((cstatus = IceConnectionStatus (ice_conn))==IceConnectPending) {
	    XtAppProcessEvent (appContext, XtIMAll);
	}

	if (cstatus == IceConnectAccepted) {
	    if (verbose) {
		printf ("ICE Connection opened by client, IceConn fd = %d, ",
			IceConnectionNumber (ice_conn));
		connstr = IceConnectionString (ice_conn);
		printf ("Accept at networkId %s\n", connstr);
		free (connstr);
		printf ("\n");
	    }
	} else {
	    if (verbose)
	    {
		if (cstatus == IceConnectIOError)
		    printf ("IO error opening ICE Connection!\n");
		else
		    printf ("ICE Connection rejected!\n");
	    }

	    IceCloseConnection (ice_conn);
	}
    }
}
Пример #6
0
    void
workshop_init(void)
{
    char_u	 buf[64];
    int		 is_dirty = FALSE;
    int		 width, height;
    XtInputMask	 mask;

    /*
     * Turn on MenuBar, ToolBar, and Footer.
     */
    STRCPY(buf, p_go);
    if (vim_strchr(p_go, GO_MENUS) == NULL)
    {
	STRCAT(buf, "m");
	is_dirty = TRUE;
    }
    if (vim_strchr(p_go, GO_TOOLBAR) == NULL)
    {
	STRCAT(buf, "T");
	is_dirty = TRUE;
    }
    if (vim_strchr(p_go, GO_FOOTER) == NULL)
    {
	STRCAT(buf, "F");
	is_dirty = TRUE;
    }
    if (is_dirty)
	set_option_value((char_u *)"go", 0L, buf, 0);

    /*
     * Set size from workshop_get_width_height().
     */
    width = height = 0;
    if (workshop_get_width_height(&width, &height))
    {
	XtVaSetValues(vimShell,
		XmNwidth, width,
		XmNheight, height,
		NULL);
    }

    /*
     * Now read in the initial messages from eserve.
     */
    while ((mask = XtAppPending(app_context))
	    && (mask & XtIMAlternateInput) && !workshopInitDone)
	XtAppProcessEvent(app_context, (XtInputMask)XtIMAlternateInput);
}
Пример #7
0
void Message(char *s) {
    XmString msgString, okString;
    char buf[512];

    answer = UNANSWERED;
    sprintf (buf, "%s", s);
    msgString = XmStringCreateLtoR (buf, XmSTRING_DEFAULT_CHARSET);
    XtVaSetValues (dialog, XmNmessageString, msgString, NULL);

    XtManageChild (dialog);
    XtPopup (XtParent(dialog), XtGrabNone);

    while (answer==UNANSWERED)
      XtAppProcessEvent(theAppContext, XtIMAll);
}
Пример #8
0
int Gprocessevents (int waitflag, int mode) {
    int rtn;

    if (Glazyq.flag)
        Gflushlazyq ();
    rtn = 0;
    switch (waitflag) {
    case TRUE:
        XtAppProcessEvent (appcontext, XtIMAll);
        if (mode == G_ONEEVENT)
            return 1;
        rtn = 1;
        /* FALL THROUGH */
    case FALSE:
        while (XtAppPending (appcontext)) {
            XtAppProcessEvent (appcontext, XtIMAll);
            if (mode == G_ONEEVENT)
                return 1;
            rtn = 1;
        }
        break;
    }
    return rtn;
}
Пример #9
0
void GUI_GeneralPreview(Widget w,XtPointer client, XtPointer call)
{
  struct CTransform *ctransform=(struct CTransform *)client;
  struct FFTSound *copy;
  int length;

  PlayStopHard();

  if( ! DA_initialized(ctransform->fftsound)){
    fprintf(stderr,"No Sound loaded\n");
    return;
  }


  XmUpdateDisplay(w);
  SetWatchCursor(topLevel);

  if(ctransform->doprogress==true){
    XtVaSetValues(progressScale, XmNvalue, 0, NULL);
    XtManageChild(progressDialog);
  }

  while (XtAppPending(app_context)) {
     XtAppProcessEvent(app_context,XtIMXEvent|XtIMTimer|XtIMAlternateInput);
  }


  length=min(areat2-areat1,CONFIG_getMaxPreviewLength(ctransform->fftsound));

  copy=makeFFTSoundCopy(ctransform->fftsound,areat1,areat1+length);
  copyFFTSound(ctransform->fftsound,copy,areat1);
  //  copy=ctransform->fftsound;
  (*ctransform->Transform)(ctransform,ctransform->pointer,copy,0,length,areat1);

  Play(copy,0,length);


  /*
  if(pthread_create(&pthread,NULL,DoPlay,copy)!=0){
    fprintf(stderr,"Could not make pthread\n");
  }
  */

  //   RedrawWin(ctransform->fftsound);
  if(ctransform->doprogress==true) XtUnmanageChild(progressDialog);
  ResetCursor(topLevel);

}
Пример #10
0
static int
TesteventloopCmd(
    ClientData clientData,	/* Not used. */
    Tcl_Interp *interp,		/* Current interpreter. */
    int argc,			/* Number of arguments. */
    const char **argv)		/* Argument strings. */
{
    static int *framePtr = NULL;/* Pointer to integer on stack frame of
				 * innermost invocation of the "wait"
				 * subcommand. */

    if (argc < 2) {
	Tcl_AppendResult(interp, "wrong # arguments: should be \"", argv[0],
		" option ... \"", NULL);
	return TCL_ERROR;
    }
    if (strcmp(argv[1], "done") == 0) {
	*framePtr = 1;
    } else if (strcmp(argv[1], "wait") == 0) {
	int *oldFramePtr;
	int done;
	int oldMode = Tcl_SetServiceMode(TCL_SERVICE_ALL);

	/*
	 * Save the old stack frame pointer and set up the current frame.
	 */

	oldFramePtr = framePtr;
	framePtr = &done;

	/*
	 * Enter an Xt event loop until the flag changes. Note that we do not
	 * explicitly call Tcl_ServiceEvent().
	 */

	done = 0;
	while (!done) {
	    XtAppProcessEvent(TclSetAppContext(NULL), XtIMAll);
	}
	(void) Tcl_SetServiceMode(oldMode);
	framePtr = oldFramePtr;
    } else {
	Tcl_AppendResult(interp, "bad option \"", argv[1],
		"\": must be done or wait", NULL);
	return TCL_ERROR;
    }
    return TCL_OK;
}
Пример #11
0
/*ARGSUSED*/
Bool
ConfigLoop(ConfigCheckFunction config_fn)
{
    Arg args[1];
    config_popped = True;
    XtPopup(shell, XtGrabExclusive);

    config_function = config_fn;
    while (config_popped)
	XtAppProcessEvent(XtWidgetToApplicationContext(shell), XtIMAll);

    XtSetArg(args[0], XtNstring, &ident_string);
    XtGetValues(ident_widget, args, 1);

    return (config_status);
}
Пример #12
0
Boolean XltYesNo(Widget w, String Question)
{
static Widget Dialog = NULL;
static int Result;
Boolean Return;
XmString string;

	if (Dialog == NULL)
	{
	Widget shell = w;

		while (XtParent(shell) && !XtIsTopLevelShell(shell)) shell = XtParent(shell);
		Dialog = XmCreateQuestionDialog(shell, "YesNo", NULL, 0);
		XtUnmanageChild(XmMessageBoxGetChild(Dialog, XmDIALOG_HELP_BUTTON));
		XtAddCallback(Dialog, XmNokCallback, (XtCallbackProc)callback, &Result);
		XtAddCallback(Dialog, XmNcancelCallback, (XtCallbackProc)callback, &Result);
		XtAddCallback(Dialog, XmNunmapCallback, (XtCallbackProc)callback, &Result);
	}
	string = XmStringCreateSimple(Question);
	XtVaSetValues(Dialog,
		XmNmessageString, string,
		NULL);
	XmStringFree(string);
	XtManageChild(Dialog);
	Result = XmCR_NONE;
	while (Result == XmCR_NONE)
	{
		XtAppProcessEvent(XtWidgetToApplicationContext(w), XtIMAll);
	}
	switch (Result)
	{
	case XmCR_OK:
		Return = True;
		break;
	case XmCR_CANCEL:
	case XmCR_UNMAP:
		Return = False;
		break;
	default:
		fprintf(stderr, "%s(%d):XltYesNo() - Unknown result code >%i<\n",
			__FILE__, __LINE__, Result);
		Return = False;
		break;
	}
	return(Return);
}
Пример #13
0
static void
SendByte(Widget w)
{
int i;

    while ((XtAppPending(XtWidgetToApplicationContext(w)) & XtIMAlternateInput) == XtIMAlternateInput)
    {
	XtAppProcessEvent(XtWidgetToApplicationContext(w), XtIMAlternateInput);
    }
    Host_OutputId(w) = (XtIntervalId)NULL;
    if (!Host_Throttle(w))
    {
	if (Host_OutputSize(w) > 0)
	{
	    switch (Host_Type(w))
	    {
	    case XltHOST_CLIENT:
		write(Host_Fd(w), &(Host_OutputData(w)[0]), 1);
		break;
	    case XltHOST_SERVER:
		for (i = 0; i < Host_NumClients(w); i++)
		{
		    write(Host_ClientList(w)[i].fd, &(Host_OutputData(w)[0]), 1);
		}
		break;
	    default:
		break;
	    }
	    memmove(&(Host_OutputData(w)[0]), &(Host_OutputData(w)[1]), Host_OutputSize(w));
	    Host_OutputSize(w)--;
	    if (Host_OutputCallback(w))
	    {
		_XltHostCallbackStruct tmp;

		tmp.reason = XltCR_OUTPUT;
		tmp.data = NULL;
		tmp.len = Host_OutputSize(w);
		tmp.input_size = 0;
		tmp.input_need = 0;
		XtCallCallbackList(w, Host_OutputCallback(w), &tmp);
	    }
	}
    }
    Throttle(w, Host_Throttle(w));
}
Пример #14
0
static void doErrorDialog(const char *errorString, const char *filename)
{
    char string[255];
    XmString mString;

    ErrorDone = False;

    sprintf(string, errorString, filename);
    mString = XmStringCreateLtoR(string, XmSTRING_DEFAULT_CHARSET);
    
    SET_ONE_RSRC(ErrorDialog, XmNmessageString, mString);
    XmStringFree(mString);
    ManageDialogCenteredOnPointer(ErrorDialog);

    while (!ErrorDone)
	XtAppProcessEvent (XtWidgetToApplicationContext(ErrorDialog), XtIMAll);
    
    XtUnmanageChild(ErrorDialog);
}
Пример #15
0
static gboolean
xt_event_polling_timer_callback(gpointer user_data)
{
  Display * display;
  XtAppContext ac;
  int eventsToProcess = 20;

  display = (Display *)user_data;
  ac = XtDisplayToApplicationContext(display);

  /* We need to process many Xt events here. If we just process
     one event we might starve one or more Xt consumers. On the other hand
     this could hang the whole app if Xt events come pouring in. So process
     up to 20 Xt events right now and save the rest for later. This is a hack,
     but it oughta work. We *really* should have out of process plugins.
  */
  while (eventsToProcess-- && XtAppPending(ac))
    XtAppProcessEvent(ac, XtIMAll);
  return TRUE;
}
Пример #16
0
static gboolean
xt_event_dispatch (GSource*  source_data,
                    GSourceFunc call_back,
                    gpointer  user_data)
{
  XEvent event;
  XtAppContext ac;
  int i = 0;

  ac = XtDisplayToApplicationContext(xtdisplay);

  /* Process only real X traffic here.  We only look for data on the
   * pipe, limit it to XTBIN_MAX_EVENTS and only call
   * XtAppProcessEvent so that it will look for X events.  There's no
   * timer processing here since we already have a timer callback that
   * does it.  */
  for (i=0; i < XTBIN_MAX_EVENTS && XPending(xtdisplay); i++) {
    XtAppProcessEvent(ac, XtIMXEvent);
  }

  return TRUE;  
}
Пример #17
0
Файл: vidmode.c Проект: aosm/X11
static int
AddMode(void)
{
    if (addshell == NULL) {
	Widget dialog;

	addshell = XtCreatePopupShell("addMode", transientShellWidgetClass,
				      toplevel, NULL, 0);
	dialog = XtVaCreateManagedWidget("dialog", dialogWidgetClass,
					 addshell, XtNvalue, NULL, NULL, 0);
	XawDialogAddButton(dialog, "yes", PopdownAdd, (XtPointer)True);
	XawDialogAddButton(dialog, "no", PopdownAdd, (XtPointer)False);
	XtRealizeWidget(addshell);
	XSetWMProtocols(DPY, XtWindow(addshell), &wm_delete_window, 1);
    }

    asking_add = 1;

    XtPopup(addshell, XtGrabExclusive);
    while (asking_add)
	XtAppProcessEvent(XtWidgetToApplicationContext(addshell), XtIMAll);

    return (do_add);
}
Пример #18
0
void GUI_GeneralOk(Widget w,XtPointer client, XtPointer call)
{
  struct CTransform *ctransform=(struct CTransform *)client;

  if( ! DA_initialized(ctransform->fftsound)){
    fprintf(stderr,"No Sound loaded\n");
    return;
  }

  XmUpdateDisplay(w);
  SetWatchCursor(topLevel);

  if(ctransform->doprogress==true){
    XtVaSetValues(progressScale, XmNvalue, 0, NULL);
    XtManageChild(progressDialog);
  }

  while (XtAppPending(app_context)) {
     XtAppProcessEvent(app_context,XtIMXEvent|XtIMTimer|XtIMAlternateInput);
  }

  UNDO_addTransform(ctransform->fftsound);

  (*ctransform->Transform)(ctransform,ctransform->pointer,ctransform->fftsound,areat1,areat2,0);

  SetVisibleFunc(1,2);
  SetVisibleFunc(2,2);
  SetVisibleFunc(3,2);

  RedrawWin(ctransform->fftsound);
  if(ctransform->doprogress==true) XtUnmanageChild(progressDialog);
  ResetCursor(topLevel);

  XtUnmanageChild(ctransform->parentwidget);

}
Пример #19
0
int XETrapAppWhileLoop(XtAppContext app, XETC *tc, Bool *done)
{
    XEvent event;
    XtInputMask imask;
    int status = True;

    if(done)
    {
        while (!(*done))
        {
            imask = XETrapAppPending(app);
            /* Check to see what's going on so that we don't block
             * in either NextEvent or ProcessEvent since neither
             * of these routines can correctly deal with XTrap Events
             */
            if (imask & XtIMXEvent)
            {
                (void)XtAppNextEvent(app, &event);
                (void)XETrapDispatchEvent(&event,tc);
            }
            else if (imask & (XtIMTimer | XtIMAlternateInput))
            {
                XtAppProcessEvent(app, (XtIMTimer | XtIMAlternateInput));
            }
            else
            {   /* Nothing going on, so we need to block */
                (void)XETrapWaitForSomething(app);
            }
        }
    }
    else
    {
        status = False;
    }
    return(status);
}
Пример #20
0
// Answer GDB question
static void select_from_gdb(const string& question, string& reply)
{
    int count       = question.freq('\n') + 1;
    string *choices = new string[count];
    bool *selected  = new bool[count];

    split(question, choices, count, '\n');

    // Highlight choice #1 by default
    for (int i = 0; i < count; i++)
    {
	if (!has_nr(choices[i]))
	{
	    // Choice has no number (prompt) - remove it
	    for (int j = i; j < count - 1; j++)
		choices[j] = choices[j + 1];
	    count--;
	    i--;
	}
	else
	{
	    selected[i] = (get_positive_nr(choices[i]) == 1);
	}
    }

    if (count < 2)
    {
	// Nothing to choose from
	if (count == 1)
	{
	    // Take the first choice.
	    reply = itostring(atoi(choices[0].chars())) + "\n";
	}
	
	delete[] choices;
	delete[] selected;
	return;
    }

    // Popup selection dialog
    static string selection_reply;

    if (gdb_selection_dialog == 0)
    {
	Arg args[10];
	Cardinal arg = 0;
	XtSetArg(args[arg], XmNautoUnmanage, False); arg++;

	gdb_selection_dialog = 
	    verify(XmCreateSelectionDialog(find_shell(gdb_w),
					   XMST("gdb_selection_dialog"),
					   args, arg));
	Delay::register_shell(gdb_selection_dialog);

	XtUnmanageChild(XmSelectionBoxGetChild(gdb_selection_dialog,
					       XmDIALOG_TEXT));
	XtUnmanageChild(XmSelectionBoxGetChild(gdb_selection_dialog, 
					       XmDIALOG_SELECTION_LABEL));
	XtUnmanageChild(XmSelectionBoxGetChild(gdb_selection_dialog, 
					       XmDIALOG_APPLY_BUTTON));

	gdb_selection_list_w = XmSelectionBoxGetChild(gdb_selection_dialog, 
						      XmDIALOG_LIST);
	XtVaSetValues(gdb_selection_list_w,
		      XmNselectionPolicy, XmSINGLE_SELECT,
		      XtPointer(0));
	XtAddCallback(gdb_selection_dialog,
		      XmNokCallback, SelectCB, &selection_reply);
	XtAddCallback(gdb_selection_dialog,
		      XmNcancelCallback, CancelCB, &selection_reply);
	XtAddCallback(gdb_selection_dialog,
		      XmNhelpCallback, ImmediateHelpCB, 0);
    }

    setLabelList(gdb_selection_list_w, choices, selected, count, false, false);

    delete[] choices;
    delete[] selected;

    manage_and_raise(gdb_selection_dialog);

    selection_reply = "";
    while (selection_reply.empty() 
	   && gdb->running() && !gdb->isReadyWithPrompt())
	XtAppProcessEvent(XtWidgetToApplicationContext(gdb_w), XtIMAll);

    // Found a reply - return
    reply = selection_reply;
}
Пример #21
0
int main(int argc, char **argv)
{
    // nspluginviewer is a helper app, it shouldn't do session management at all
    setenv("SESSION_MANAGER", "", 1);

    // trap X errors
    kdDebug(1430) << "1 - XSetErrorHandler" << endl;
    XSetErrorHandler(x_errhandler);
    setvbuf(stderr, NULL, _IONBF, 0);

    kdDebug(1430) << "2 - parseCommandLine" << endl;
    parseCommandLine(argc, argv);

#if QT_VERSION < 0x030100
    // Create application
    kdDebug(1430) << "3 - XtToolkitInitialize" << endl;
    XtToolkitInitialize();
    g_appcon = XtCreateApplicationContext();
    Display *dpy = XtOpenDisplay(g_appcon, NULL, "nspluginviewer", "nspluginviewer", 0, 0, &argc, argv);

    _notifiers[0].setAutoDelete(TRUE);
    _notifiers[1].setAutoDelete(TRUE);
    _notifiers[2].setAutoDelete(TRUE);

    kdDebug(1430) << "4 - KXtApplication app" << endl;
    KLocale::setMainCatalogue("nsplugin");
    KXtApplication app(dpy, argc, argv, "nspluginviewer");
#else
    kdDebug(1430) << "3 - create QXtEventLoop" << endl;
    QXtEventLoop integrator("nspluginviewer");
    parseCommandLine(argc, argv);
    KLocale::setMainCatalogue("nsplugin");

    kdDebug(1430) << "4 - create KApplication" << endl;
    KApplication app(argc, argv, "nspluginviewer");
    GlibEvents glibevents;
#endif

    {
        KConfig cfg("kcmnspluginrc", true);
        cfg.setGroup("Misc");
        int v = KCLAMP(cfg.readNumEntry("Nice Level", 0), 0, 19);
        if(v > 0)
        {
            nice(v);
        }
        v = cfg.readNumEntry("Max Memory", 0);
        if(v > 0)
        {
            rlimit rl;
            memset(&rl, 0, sizeof(rl));
            if(0 == getrlimit(RLIMIT_AS, &rl))
            {
                rl.rlim_cur = kMin(v, int(rl.rlim_max));
                setrlimit(RLIMIT_AS, &rl);
            }
        }
    }

    // initialize the dcop client
    kdDebug(1430) << "5 - app.dcopClient" << endl;
    DCOPClient *dcop = app.dcopClient();
    if(!dcop->attach())
    {
        KMessageBox::error(NULL, i18n("There was an error connecting to the Desktop "
                                      "communications server. Please make sure that "
                                      "the 'dcopserver' process has been started, and "
                                      "then try again."),
                           i18n("Error Connecting to DCOP Server"));
        exit(1);
    }

    kdDebug(1430) << "6 - dcop->registerAs" << endl;
    if(g_dcopId)
        g_dcopId = dcop->registerAs(g_dcopId, false);
    else
        g_dcopId = dcop->registerAs("nspluginviewer");

    dcop->setNotifications(true);

    // create dcop interface
    kdDebug(1430) << "7 - new NSPluginViewer" << endl;
    NSPluginViewer *viewer = new NSPluginViewer("viewer", 0);

// start main loop
#if QT_VERSION < 0x030100
    kdDebug(1430) << "8 - XtAppProcessEvent" << endl;
    while(!g_quit)
        XtAppProcessEvent(g_appcon, XtIMAll);
#else
    kdDebug(1430) << "8 - app.exec()" << endl;
    app.exec();
#endif

    // delete viewer
    delete viewer;
}
Пример #22
0
status
ws_dispatch(Int FD, Any timeout)
{ XtIntervalId tid = 0;
  XtInputId iid = 0;
  status rval = SUCCEED;
  int ofd = dispatch_fd;
  int fd = (isDefault(FD) ? dispatch_fd :
	    isNil(FD)	  ? -1
			  : valInt(FD));

					/* No context: wait for input */
					/* timeout */
  if ( ThePceXtAppContext == NULL )
  { int ready;
#ifdef HAVE_POLL
    int to;
    struct pollfd fds[1];

    if ( isNil(timeout) )
    { to = -1;
    } else if ( isDefault(timeout) )
    { to = 250;
    } else if ( isInteger(timeout) )
    { to = valInt(timeout);
    } else if ( instanceOfObject(timeout, ClassReal) )
    { to = (int)(valReal(timeout)*1000.0);
    } else
      to = 256;

    fds[0].fd = fd;
    fds[0].events = POLLIN;

    ready = poll(fds, 1, to);
#else
    struct timeval to;
    struct timeval *tp = &to;
    fd_set readfds;
    int setmax = 0;

    if ( isNil(timeout) )
    { tp = NULL;
    } else if ( isDefault(timeout) )
    { to.tv_sec = 0;
      to.tv_usec = 250000;
    } else
    { double v;

      if ( isInteger(timeout) )
	v = (double)valInt(timeout)/1000.0;
      else if ( instanceOfObject(timeout, ClassReal) )
	v = valReal(timeout);
      else
	v = 0.25;

      to.tv_sec  = (long)v;
      to.tv_usec = (long)(v * 1000000.0) % 1000000;
    }

    FD_ZERO(&readfds);
    if ( fd >= 0 )
    { FD_SET(fd, &readfds);
      setmax = max(setmax, fd);
      dispatch_fd = fd;
    }

    ready = select(setmax+1, &readfds, NULL, NULL, tp);
#endif
    dispatch_fd = ofd;

    return (ready > 0 ? SUCCEED : FAIL);
  }					/* A display: dispatch until there */
					/* is input or a timeout */

  if ( fd >= 0 )
  { iid = XtAppAddInput(ThePceXtAppContext, fd,
			(XtPointer) XtInputReadMask, is_pending, NULL);
    dispatch_fd = fd;
  }

  if ( notNil(timeout) )
  { long to = -1;

    if ( isInteger(timeout) )
      to = valInt(timeout);
    else if ( instanceOfObject(timeout, ClassReal) )
      to = (long)(valReal(timeout)*1000.0);

    if ( to > 0 )
      tid = XtAppAddTimeOut(ThePceXtAppContext, to, is_timeout,
			    (XtPointer) &rval);
  }

  DEBUG(NAME_dispatch, Cprintf("Dispatch: timeout = %s, tid = %p\n",
			       pp(timeout), (void*)tid));

  if ( pceMTTryLock(LOCK_PCE) )
  { RedrawDisplayManager(TheDisplayManager());
    pceMTUnlock(LOCK_PCE);
  }
					/* All callbacks must be locked! */
  XtAppProcessEvent(ThePceXtAppContext,
		    XtIMXEvent|XtIMTimer|XtIMAlternateInput);

  if ( tid && rval )			/* if rval = FAIL, we had a timeout */
    XtRemoveTimeOut(tid);
  if ( iid )
    XtRemoveInput(iid);
  dispatch_fd = ofd;

  considerLocStillEvent();

  return rval;
}
Пример #23
0
// Create a separate tty window; return its name in TTYNAME, its
// process id in PID, its terminal type in TERM, and its window id in
// WINDOWID.
static void launch_separate_tty(string& ttyname, pid_t& pid, string& term,
				Window& windowid, Widget origin)
{
    // If we're already running, all is done.
    if (pid > 0 && (remote_gdb() || kill(pid, 0) == 0))
	return;

    string term_command = app_data.term_command;
    term_command.gsub("@FONT@", make_font(app_data, FixedWidthDDDFont));

    static bool canceled;
    canceled = false;

    static Widget dialog = 0;
    if (dialog == 0)
    {
	Arg args[10];
	Cardinal arg = 0;
	XtSetArg(args[arg], XmNdialogStyle, 
		 XmDIALOG_FULL_APPLICATION_MODAL); arg++;
	dialog = verify(XmCreateWorkingDialog(find_shell(origin), 
					      XMST("launch_tty_dialog"), 
					      args, arg));
	XtUnmanageChild(XmMessageBoxGetChild(dialog, 
					     XmDIALOG_OK_BUTTON));
	XtUnmanageChild(XmMessageBoxGetChild(dialog, 
					     XmDIALOG_HELP_BUTTON));
	XtAddCallback(dialog, XmNcancelCallback, CancelTTYCB,
		      XtPointer(&canceled));
    }

    string base = term_command;
    if (base.contains(' '))
	base = base.before(' ');
    MString msg = rm("Starting ") + tt(base) + rm("...");
    XtVaSetValues(dialog, XmNmessageString, msg.xmstring(), XtPointer(0));
    manage_and_raise(dialog);
    wait_until_mapped(dialog);

    StatusDelay delay("Starting execution window");

    // Fill in defaults
    ttyname = "";
    pid     = -1;

    string command = 
	
	// Set up a temporary file in TMP.
	"tmp=${TMPDIR-/tmp}/ddd$$; export tmp; "

	// Be sure to remove it when exiting...
	"trap \"rm -f $tmp\" 0; "

	// ... or being interrupted.
	"trap 'exit 1' 1 2 15; "

	// Now execute the xterm command
	+ term_command +

	// which saves TTY, PID, TERM, and WINDOWID in TMP and goes to
	// sleep forever.  Signal 2 (SIGINT) is blocked for two
	// reasons: first, we don't want ^C to kill the tty window;
	// second, later invocations will send us SIGINT to find out
	// whether we're still alive.
	" '"
	"echo `tty` $$ $TERM $WINDOWID >$tmp; "
	"trap \"\" 2; "
	"while true; do sleep 3600; done"
	"' "

	// The whole thing is redirected and in the background such
	// that rsh won't wait for us.
	">/dev/null </dev/null 2>&1 & "

	// The main file waits for TMP to be created...
	"while test ! -s $tmp; do sleep 1; done; "

	// ...and sends TMP's contents to stdout, where DDD is waiting.
	"cat $tmp";

    if (pid > 0 && remote_gdb())
    {
	// We're already running.  Don't start a new tty
	// if the old one is still running.
	std::ostringstream os;
	os << "kill -2 " << pid << " 2>/dev/null"
	   << " || ( " << command << " )";
	command = string(os);
    }

    command = sh_command(command);

    {
	XtAppContext app_context = XtWidgetToApplicationContext(dialog);
	LiterateAgent tty(app_context, command);

	string reply = "";
	tty.addHandler(Input, GotReplyHP, (void *)&reply);
	tty.start();

	while (!reply.contains('\n') && !canceled && tty.running())
	    XtAppProcessEvent(app_context, XtIMAll);

	if (reply.length() > 2)
	{
	    std::istringstream is(reply.chars());
	    is >> ttyname >> pid >> term >> windowid;
	}

	tty.terminate();
    }
Пример #24
0
static void process_events(int queuefd)
{
  struct timeval await;
#define	BRIEF	0.1
  static struct timeval brief = { 0, 100000 };
  float timelimit;
  fd_set thesefds;
  XtInputMask xim;

  if (queuefd < 0) {
    queuefd = ConnectionNumber(dpy);
  }

  if(drawerstate.pause) {
    if(!dragging && !drawer_moving())
      select(0, NULL, NULL, NULL, &brief);
    nseen = 0;
  } else {
    int nwatch = 0;

    timelimit = PoolInputFDs( &thesefds, &nwatch );

    if(timelimit > 0 && drawer_moving())
      timelimit = 0;	/* "Is anything moving?" */

    if (queuefd >= 0 )
      FD_SET(queuefd, &thesefds);

    if(queuefd >= nwatch)
      nwatch = queuefd+1;

    if(timelimit > BRIEF) timelimit = BRIEF;

    await.tv_sec = floor(timelimit);
    await.tv_usec = 1000000*(timelimit - await.tv_sec);

    nseen = select(nwatch, &thesefds, NULL, NULL, &await);
  }

  gettimeofday(&perf.then, NULL);

  if(!drawerstate.pause)
    PoolInAll( &thesefds, &nseen );

  ui_update();

  justdragged = 0;
  deldrag = gev.t;


  while ((xim = XtAppPending(App)) != 0) {
    XtAppProcessEvent(App, xim);
  }

  if (dragging && !justdragged && !dragstop) {
    D1PRINT(("gvevent at 1\n"));
    GV_RAWEVENT( gev.dev, -1, gev.x, gev.y, gev.t);
    dragstop = 1;
  }

  if (dragging) {
    deldrag = gev.t - deldrag;
  } else {
    deldrag = 0;
  }

  XSync(dpy, False);

  gv_update_draw( ALLCAMS, 0.001 * (float)deldrag );
  mg_textureclock();

  if(perf.interval > 0)
    perftick();

  numdrags = 0;
}
Пример #25
0
int main (int argc,char *argv[])
{/* Main */    
   static char FuncName[]={"prompt_user"}; 
   SUMA_GENERIC_PROG_OPTIONS_STRUCT *Opt;  
   SUMA_GENERIC_ARGV_PARSE *ps=NULL;
   char * esc_str = NULL;
   int ii;
   Widget w=NULL;
   XtAppContext    app;
   XEvent ev;
   XtInputMask pp;
   SUMA_Boolean LocalHead = NOPE;
   
   SUMA_STANDALONE_INIT;
	SUMA_mainENTRY;

   /* Allocate space for DO structure */
	SUMAg_DOv = SUMA_Alloc_DisplayObject_Struct (SUMA_MAX_DISPLAYABLE_OBJECTS);
   ps = SUMA_Parse_IO_Args(argc, argv, "");
   
   if (argc < 2) {
      usage_prompt_user(ps);
      exit (1);
   }
   
   Opt = SUMA_prompt_user_ParseInput (argv, argc, ps);

   w = XtOpenApplication(&app, "prompt_user", 
                           NULL, 0, &argc, argv,
                           SUMA_get_fallbackResources(), 
                           topLevelShellWidgetClass, NULL, 0); 
   
   switch (Opt->b1) {
      case 1:
         /* apply some escape characters     31 Jul 2009 [rickr] */
         esc_str = unescape_unix_str(Opt->in_name);
         ii = SUMA_PauseForUser(w, esc_str, SWP_POINTER_LEFT_BOTTOM, &app, 1);
         fprintf(SUMA_STDOUT,"%d\n", ii);
         break;
      default:
         SUMA_S_Err("Bad opt");
         exit(1);
         
   }
   
   /* because you have no XtAppMainLoop, you'll need to process the next 
   event for the XtDestroy command on w's child takes effect. So you'll
   just have this zombie widget that stares at you.
   In this simple command line program, the widget dies anyway when you
   exit the program, so the call below is a teaching moment for when
   functions like SUMA_PauseForUser are called from programs without an
   XtAppMainLoop. 
   See also SUMA_PAUSE_PROMPT macro */
   
   while ((pp = XtAppPending(app))) {  \
      XtAppProcessEvent(app, pp); \
   } 
   
   if (Opt->debug > 2) LocalHead = YUP;
   if (ps) SUMA_FreeGenericArgParse(ps); ps = NULL;
   if (Opt) Opt = SUMA_Free_Generic_Prog_Options_Struct(Opt);
   if (!SUMA_Free_CommonFields(SUMAg_CF)) 
      SUMA_error_message(FuncName,"SUMAg_CF Cleanup Failed!",1);

   if( esc_str ) free(esc_str);
   
   exit(0);
   
} 
Пример #26
0
ENTRYPOINT void
draw_fliptext (ModeInfo *mi)
{
  fliptext_configuration *sc = &scs[MI_SCREEN(mi)];
/*  XtAppContext app = XtDisplayToApplicationContext (sc->dpy);*/
  Display *dpy = MI_DISPLAY(mi);
  Window window = MI_WINDOW(mi);
  int i;

  if (!sc->glx_context)
    return;

  glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(sc->glx_context));

#if 0
  if (XtAppPending (app) & (XtIMTimer|XtIMAlternateInput))
    XtAppProcessEvent (app, XtIMTimer|XtIMAlternateInput);
#endif

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  mi->polygon_count = 0;

  glPushMatrix();
  glRotatef(current_device_rotation(), 0, 0, 1);
  {
    GLfloat s = 3.0 / (sc->top_margin - sc->bottom_margin);
    glScalef(s, s, s);
  }

  glRotatef (sc->rotation.x, 1, 0, 0);
  glRotatef (sc->rotation.y, 0, 1, 0);
  glRotatef (sc->rotation.z, 0, 0, 1);

#if 0
  glDisable (GL_TEXTURE_2D);
  glColor3f (1,1,1);
  glBegin (GL_LINE_LOOP);
  glVertex3f (sc->left_margin,  sc->top_margin, 0);
  glVertex3f (sc->right_margin, sc->top_margin, 0);
  glVertex3f (sc->right_margin, sc->bottom_margin, 0);
  glVertex3f (sc->left_margin,  sc->bottom_margin, 0);
  glEnd();
  glBegin (GL_LINES);
  glVertex3f (sc->in.x,  sc->top_margin,    sc->in.z);
  glVertex3f (sc->in.x,  sc->bottom_margin, sc->in.z);
  glVertex3f (sc->mid.x, sc->top_margin,    sc->mid.z);
  glVertex3f (sc->mid.x, sc->bottom_margin, sc->mid.z);
  glVertex3f (sc->out.x, sc->top_margin,    sc->out.z);
  glVertex3f (sc->out.x, sc->bottom_margin, sc->out.z);
  glEnd();
  glEnable (GL_TEXTURE_2D);
#endif

  for (i = 0; i < sc->nlines; i++)
    {
      line *line = sc->lines[i];
      draw_line (mi, line);
      tick_line (sc, line);
    }

  for (i = sc->nlines-1; i >= 0; i--)
    {
      line *line = sc->lines[i];
      if (line->state == DEAD)
        free_line (sc, line);
    }

  if (sc->nlines == 0)
    reset_lines (mi);

  glPopMatrix();

  if (mi->fps_p) do_fps (mi);
  glFinish();
  glXSwapBuffers(dpy, window);
}
Пример #27
0
char *GetResponse (char *message) {
  char buf[512];
  Widget w, aLabel, rowcol;
  Arg args[16];
  int n;

  if (!responseShell) {
      responseShell = 
	  XtVaCreatePopupShell( "responseShell", xmDialogShellWidgetClass, 
                             theToplevelShell, 
/* width and/or height necessary to force the realizeWidget?? */
XmNwidth, 100, XmNheight, 100,
				XmNdialogType, XmDIALOG_SYSTEM_MODAL, 
				XmNtitle, "Add comment:", NULL);
      /* the XtRealizeWidget is not necessary if we set a width and height? */
      /*XtRealizeWidget (responseShell); */

      XtVaSetValues (responseShell, XmNtitle, "Add comment:", NULL);
      XtAddCallback 
        (responseShell, XmNpopupCallback, (XtCallbackProc) centerMe, NULL);
      XtAddEventHandler (responseShell, VisibilityChangeMask, False, 
						  (XtEventHandler) keepOnTop, NULL);

      responseForm = XtVaCreateWidget
                       ("responseForm",xmFormWidgetClass,responseShell,args,n);

      n = 0;
      XtSetArg (args[n], XmNtopAttachment, XmATTACH_FORM);                n++;
      XtSetArg (args[n], XmNleftAttachment, XmATTACH_FORM);               n++;
      XtSetArg (args[n], XmNrightAttachment, XmATTACH_FORM);              n++;
      XtSetArg (args[n], XmNorientation, XmHORIZONTAL);                   n++;
      aLabel = 
	  XtCreateManagedWidget(message, xmLabelWidgetClass, responseForm,args,n);

      n = 0;
      XtSetArg (args[n], XmNleftAttachment, XmATTACH_FORM);               n++;
      XtSetArg (args[n], XmNrightAttachment, XmATTACH_FORM);              n++;
      XtSetArg (args[n], XmNbottomAttachment, XmATTACH_FORM);             n++;
      XtSetArg (args[n], XmNorientation, XmHORIZONTAL);                   n++;
      rowcol = XtCreateManagedWidget
			  ("rowcol",xmRowColumnWidgetClass,responseForm,args,n);
  
      w = XtCreateManagedWidget("Ok", xmPushButtonWidgetClass, rowcol, NULL, 0);
      XtAddCallback
          (w, XmNactivateCallback, (XtCallbackProc)responseCB, (XtPointer)TRUE);
      w = XtCreateManagedWidget("Cancel",xmPushButtonWidgetClass,rowcol,NULL,0);
      XtAddCallback (w, XmNactivateCallback, (XtCallbackProc)responseCB, FALSE);

      n = 0;
      XtSetArg (args[n], XmNtopAttachment, XmATTACH_WIDGET);              n++;
      XtSetArg (args[n], XmNtopWidget, aLabel);                           n++;
      XtSetArg (args[n], XmNleftAttachment, XmATTACH_FORM);               n++;
      XtSetArg (args[n], XmNrightAttachment, XmATTACH_FORM);              n++;
      XtSetArg (args[n], XmNeditMode,  XmMULTI_LINE_EDIT);                n++;
      XtSetArg (args[n], XmNbottomAttachment, XmATTACH_WIDGET);           n++;
      XtSetArg (args[n], XmNbottomWidget, rowcol);                        n++;
      responseText = XtCreateManagedWidget 
	    ("responseText", xmTextWidgetClass, responseForm, args, n);

      w = XtCreateManagedWidget 
	    ("Add Timestamp", xmPushButtonWidgetClass, rowcol, NULL,0);    
	  XtAddCallback 
		(w, XmNactivateCallback, (XtCallbackProc) timestampCB, responseText);

  }
  XtManageChild (responseForm);
  XtPopup (XtParent(responseShell), XtGrabNone);

  answer = UNANSWERED;
  while (answer==UNANSWERED)
    XtAppProcessEvent(theAppContext, XtIMAll);

  return theResponse;
}
Пример #28
0
void
OptionsPopup(XF86OptionPtr *opts)
#endif
{
    static int first = 1;
#ifdef USE_MODULES
    static Widget button, menu;
    static char label[256], menuName[16];
    Widget sme;
    char buf[256];
    int i = 0;
    Arg args[1];
    static int menuN;
#endif

    option_str = NULL;
    options = opts;
    if (first) {
	Widget pane, form, viewport, bottom, popdown;

	first = 0;

	if (optionsShell == NULL)
	    CreateOptionsShell();
	pane = XtCreateManagedWidget("pane", panedWidgetClass,
				     optionsShell, NULL, 0);

	form = XtCreateManagedWidget("commands", formWidgetClass,
				     pane, NULL, 0);
	add = XtCreateManagedWidget("add", commandWidgetClass,
				    form, NULL, 0);
	XtAddCallback(add, XtNcallback, AddOption, NULL);
	remov = XtCreateManagedWidget("remove", commandWidgetClass,
				      form, NULL, 0);
	XtAddCallback(remov, XtNcallback, RemoveOption, NULL);
	update = XtCreateManagedWidget("update", commandWidgetClass,
				       form, NULL, 0);
	XtAddCallback(update, XtNcallback, UpdateOption, NULL);
#ifdef USE_MODULES
	if (!nomodules) {
	    Widget command;

	    command = XtCreateManagedWidget("help", commandWidgetClass,
					    form, NULL, 0);
	    XtAddCallback(command, XtNcallback, ModuleOptionsPopup, NULL);
	}
#endif
	form = XtCreateManagedWidget("form", formWidgetClass,
				     pane, NULL, 0);
	XtVaCreateManagedWidget("label1", labelWidgetClass, form,
				XtNlabel, " Option \"",
				NULL);
	name = XtVaCreateManagedWidget("name", asciiTextWidgetClass, form,
				       XtNeditType, XawtextEdit,
				       NULL);
	XtVaCreateManagedWidget("label2", labelWidgetClass,
				form,
				XtNlabel, "\" \"",
				NULL);
	value = XtVaCreateManagedWidget("value", asciiTextWidgetClass, form,
					XtNeditType, XawtextEdit,
					NULL);
	XtVaCreateManagedWidget("label3", labelWidgetClass, form,
				XtNlabel, "\" ",
				NULL);
	viewport = XtCreateManagedWidget("viewport", viewportWidgetClass,
					 form, NULL, 0);
	list = XtCreateManagedWidget("list", listWidgetClass,
				     viewport, NULL, 0);
	XtAddCallback(list, XtNcallback, SelectOptionCallback, NULL);
	bottom = XtCreateManagedWidget("bottom", formWidgetClass,
				       pane, NULL, 0);
#ifdef USE_MODULES
	if (!nomodules)
	    button = XtCreateManagedWidget("driverOpts", menuButtonWidgetClass,
					    bottom, NULL, 0);
#endif
	popdown = XtVaCreateManagedWidget("popdown", commandWidgetClass,
					bottom, NULL);
#ifdef USE_MODULES
	if (!nomodules)
	    XtVaSetValues(popdown, XtNfromHoriz, button, NULL);
#endif

	XtAddCallback(popdown, XtNcallback, PopdownCallback, NULL);
	XtRealizeWidget(optionsShell);
	XSetWMProtocols(DPY, XtWindow(optionsShell), &wm_delete_window, 1);

#ifdef USE_MODULES
	if (!nomodules) {
	    char *str;

	    XtSetArg(args[0], XtNlabel, &str);
	    XtGetValues(button, args, 1);
	    XmuSnprintf(label, sizeof(label), "%s", str);
	}
#endif
    }

#ifdef USE_MODULES
    if (!nomodules) {
	if (menu)
	    XtDestroyWidget(menu);
	XmuSnprintf(menuName, sizeof(menuName), "optionM%d", menuN);
	menuN = !menuN;
	menu = XtCreatePopupShell(menuName, simpleMenuWidgetClass, button,
				  NULL, 0);
	XtVaSetValues(button, XtNmenuName, menuName, NULL);
	if (drv_opts) {
	    int len, longest = 0;
	    char fmt[32];

	    for (i = 0; drv_opts[i].name != NULL; i++) {
		len = strlen(drv_opts[i].name);
		if (len > longest)
		    longest = len;
	    }
	    XmuSnprintf(fmt, sizeof(fmt), "%c-%ds  %%s", '%', longest);
	    for (; drv_opts->name != NULL; drv_opts++) {
		char *type;

		if (drv_opts->type >= OPTV_NONE && drv_opts->type <= OPTV_FREQ)
		    type = types[drv_opts->type];
		else
		    type = "UNKNOWN";

		XmuSnprintf(buf, sizeof(buf), fmt, drv_opts->name, type);
		sme = XtVaCreateManagedWidget(drv_opts->name, smeBSBObjectClass,
					      menu, XtNlabel, buf, NULL);
		XtAddCallback(sme, XtNcallback, AddDriverOption, (XtPointer)drv_opts);
	    }
	}
	if (i) {
	    xf86cfgModuleOptions *mod = module_options;

	    while (mod) {
		if (strcmp(mod->name, driver) == 0) {
		    /* don't assign to driver, as it may be a temp string */
		    module_sel = mod->name;
		    break;
		}
		mod = mod->next;
	    }
	    XmuSnprintf(buf, sizeof(buf), "%s%s", label, driver);
	    XtSetArg(args[0], XtNlabel, buf);
	    XtSetValues(button, args, 1);
	    XtMapWidget(button);
	}
	else
	    XtUnmapWidget(button);
    }
#endif

    UpdateOptionList();
    popped = True;
    XtPopup(optionsShell, XtGrabExclusive);

    while (popped)
	XtAppProcessEvent(XtWidgetToApplicationContext(optionsShell), XtIMAll);
}
Пример #29
0
static int motFileDlgPopup(Ihandle* ih, int x, int y)
{
  InativeHandle* parent = iupDialogGetNativeParent(ih);
  Widget filebox, dialog;
  int dialogtype, style = XmDIALOG_FULL_APPLICATION_MODAL;
  IFnss file_cb = NULL;
  Widget preview_canvas = NULL;
  char* value;

  iupAttribSetInt(ih, "_IUPDLG_X", x);   /* used in iupDialogUpdatePosition */
  iupAttribSetInt(ih, "_IUPDLG_Y", y);

  value = iupAttribGetStr(ih, "DIALOGTYPE");
  if (iupStrEqualNoCase(value, "SAVE"))
    dialogtype = IUP_DIALOGSAVE;
  else if (iupStrEqualNoCase(value, "DIR"))
    dialogtype = IUP_DIALOGDIR;
  else
    dialogtype = IUP_DIALOGOPEN;
  iupAttribSetInt(ih, "_IUPDLG_DIALOGTYPE", dialogtype);

  if (parent)
  {
    filebox = XmCreateFileSelectionDialog(parent, "filedialog", NULL, 0);
    dialog = XtParent(filebox);
  }
  else
  {
    dialog = XtAppCreateShell(NULL, "filedialog", topLevelShellWidgetClass, iupmot_display, NULL, 0);
    filebox = XmCreateFileSelectionBox(dialog, "filebox", NULL, 0);
    style = XmDIALOG_MODELESS;
    XtVaSetValues(dialog,
      XmNmwmInputMode, MWM_INPUT_FULL_APPLICATION_MODAL,
      XmNmappedWhenManaged, False,
      XmNsaveUnder, True,
      NULL);
  }
  if (!filebox)
    return IUP_NOERROR;

  if (!iupAttribGetBoolean(ih, "SHOWHIDDEN"))
    XtVaSetValues(filebox, XmNfileFilterStyle, XmFILTER_HIDDEN_FILES, NULL);

  value = iupAttribGet(ih, "TITLE");
  if (!value)
  {
    if (dialogtype == IUP_DIALOGSAVE)
      value = "IUP_SAVEAS";
    else if (dialogtype == IUP_DIALOGOPEN)
      value = "IUP_OPEN";
    else
      value = "IUP_SELECTDIR";
    iupAttribSetStr(ih, "TITLE", iupStrMessageGet(value));
  }
  iupmotSetString(filebox, XmNdialogTitle, value);

  XtVaSetValues(filebox,
                XmNdialogStyle, style,
                XmNautoUnmanage, False,
                XmNresizePolicy, XmRESIZE_GROW,
                NULL);

  if (dialogtype == IUP_DIALOGDIR)
    XtVaSetValues(filebox, XmNfileTypeMask, XmFILE_DIRECTORY, NULL);

  /* just check for the path inside FILE */
  value = iupAttribGet(ih, "FILE");
  if (value && value[0] == '/')
  {
    char* dir = iupStrFileGetPath(value);
    iupAttribStoreStr(ih, "DIRECTORY", dir);
    free(dir);
  }

  /* set XmNdirectory before XmNpattern and before XmNdirSpec */

  value = iupAttribGet(ih, "DIRECTORY");
  if (value)
    iupmotSetString(filebox, XmNdirectory, value);

  value = iupAttribGet(ih, "FILTER");
  if (value)
  {
    char *filter = value;
    char *p = strchr(value, ';');
    if (p) 
    {
      /* Use only the first filter */
      int size = p-value;
      filter = (char*)malloc(size+1);
      memcpy(filter, value, size);
      filter[size] = 0;
    }

    iupmotSetString(filebox, XmNpattern, filter);

    if (filter != value) 
      free(filter);
  }

  value = iupAttribGet(ih, "FILE");
  if (value)
  {
    char* file = value;

    if (value[0] != '/')  /* if does not contains a full path, then add the directory */
    {
      char* cur_dir = NULL;
      char* dir = iupAttribGet(ih, "DIRECTORY");
      if (!dir)
      {
        cur_dir = iupdrvGetCurrentDirectory();
        dir = cur_dir;
      }

      file = iupStrFileMakeFileName(dir, value);

      if (cur_dir)
        free(cur_dir);
    }

  /* clear value before setting. Do not know why we have to do this, 
     but if not cleared it will fail to set the XmNdirSpec value. */
    iupmotSetString(filebox, XmNdirSpec, "");
    iupmotSetString(filebox, XmNdirSpec, file);

    if (file != value)
      free(file);
  }

  if (!IupGetCallback(ih, "HELP_CB"))
    XtUnmanageChild(XmFileSelectionBoxGetChild(filebox, XmDIALOG_HELP_BUTTON));

  XtAddCallback(filebox, XmNokCallback, (XtCallbackProc)motFileDlgCallback, (XtPointer)ih);
  XtAddCallback(filebox, XmNcancelCallback, (XtCallbackProc)motFileDlgCallback, (XtPointer)ih);
  XtAddCallback(filebox, XmNhelpCallback, (XtCallbackProc)motFileDlgHelpCallback, (XtPointer)ih);

  if (dialogtype == IUP_DIALOGDIR)
  {
    Widget new_folder = XtVaCreateManagedWidget("new_folder", xmPushButtonWidgetClass, filebox, 
                                                XmNlabelType, XmSTRING, 
                                                NULL);
    iupmotSetString(new_folder, XmNlabelString, iupStrMessageGet("IUP_CREATEFOLDER"));
    XtAddCallback(new_folder, XmNactivateCallback, (XtCallbackProc)motFileDlgNewFolderCallback, (XtPointer)filebox);
  }
  else
  {
    file_cb = (IFnss)IupGetCallback(ih, "FILE_CB");
    if (file_cb)
    {
      Widget list = XmFileSelectionBoxGetChild(filebox, XmDIALOG_LIST);
      XtAddCallback(list, XmNbrowseSelectionCallback, (XtCallbackProc)motFileDlgBrowseSelectionCallback, (XtPointer)ih);
      list = XmFileSelectionBoxGetChild(filebox, XmDIALOG_DIR_LIST);
      XtAddCallback(list, XmNbrowseSelectionCallback, (XtCallbackProc)motFileDlgBrowseSelectionCallback, (XtPointer)ih);

      if (iupAttribGetBoolean(ih, "SHOWPREVIEW"))
      {
        Widget frame = XtVaCreateManagedWidget("preview_canvas", xmFrameWidgetClass, filebox, 
                                                        XmNshadowType, XmSHADOW_ETCHED_IN,
                                                        NULL);

        preview_canvas = XtVaCreateManagedWidget("preview_canvas", xmDrawingAreaWidgetClass, frame, 
                                                        XmNwidth, 180, 
                                                        XmNheight, 150,
                                                        XmNresizePolicy, XmRESIZE_GROW,
                                                        NULL);

        XtAddCallback(preview_canvas, XmNexposeCallback, (XtCallbackProc)motFileDlgPreviewCanvasExposeCallback, (XtPointer)ih);
        XtAddCallback(preview_canvas, XmNresizeCallback, (XtCallbackProc)motFileDlgPreviewCanvasResizeCallback,  (XtPointer)ih);

        iupAttribSetStr(ih, "_IUPDLG_FILEBOX", (char*)filebox);
      }
    }

    if (iupAttribGetBoolean(ih, "MULTIPLEFILES"))
    {
      Widget wList = XmFileSelectionBoxGetChild(filebox, XmDIALOG_LIST);
      XtVaSetValues(wList, XmNselectionPolicy, XmEXTENDED_SELECT, NULL);

      if (file_cb)
        XtAddCallback(wList, XmNextendedSelectionCallback, (XtCallbackProc)motFileDlgBrowseSelectionCallback, (XtPointer)ih);
    }
  }

  XmAddWMProtocolCallback(dialog, iupmot_wm_deletewindow, motFileDlgCBclose, (XtPointer)ih);
  XtManageChild(filebox);

  XtRealizeWidget(dialog);
  ih->handle = dialog;
  iupDialogUpdatePosition(ih);
  ih->handle = NULL;  /* reset handle */

  if (file_cb)
  {
    if (preview_canvas)
      motFileDlgPreviewCanvasInit(ih, preview_canvas);

    file_cb(ih, NULL, "INIT");
  }

  if (ih->userwidth && ih->userheight)
  {
    XtVaSetValues(dialog,
      XmNwidth, (XtArgVal)(ih->userwidth),
      XmNheight, (XtArgVal)(ih->userheight),
      NULL);
  }

  if (style == XmDIALOG_MODELESS)
    XtPopup(dialog, XtGrabExclusive);

  /* while the user hasn't provided an answer, simulate main loop.
  ** The answer changes as soon as the user selects one of the
  ** buttons and the callback routine changes its value. */
  iupAttribSetStr(ih, "STATUS", NULL);
  while (iupAttribGet(ih, "STATUS") == NULL)
    XtAppProcessEvent(iupmot_appcontext, XtIMAll);

  if (file_cb)
  {
    if (preview_canvas)
      XFreeGC(iupmot_display, (GC)iupAttribGet(ih, "PREVIEWDC"));

    file_cb(ih, NULL, "FINISH");
  }

  if (!iupAttribGet(ih, "_IUP_WM_DELETE"))
  {
    XtUnmanageChild(filebox);

    if (style == XmDIALOG_MODELESS)
    {
      XtPopdown(dialog);
      XtDestroyWidget(dialog);
    }
  }

  return IUP_NOERROR;
}
Пример #30
0
static void DoExportCB(Widget w, XtPointer client_data, XtPointer call_data)
{
    SelectPlotCB(w, client_data, call_data);

    PlotWindowInfo *plot = (PlotWindowInfo *)client_data;
    string target = get_file(w, client_data, call_data);
    if (target.empty())
	return;

    const StringArray& titles  = plot->plotter->data_titles();
    const StringArray& sources = plot->plotter->data_files();

    string source = "";
    string title  = "";
    for (int i = 0; source.empty() && i < sources.size(); i++)
    {
	if (!sources[i].empty())
	{
	    source = sources[i];
	    title  = titles[i];
	}
    }
    
    if (source.empty())
	return;			// This should not happen

    if (access(target.chars(), W_OK) == 0 && is_regular_file(target))
    {
	// File exists - request confirmation
	static Widget confirm_overwrite_dialog = 0;
	if (confirm_overwrite_dialog != 0)
	    DestroyWhenIdle(confirm_overwrite_dialog);

	Arg args[10];
	Cardinal arg = 0;
	XtSetArg(args[arg], XmNdialogStyle, 
		 XmDIALOG_FULL_APPLICATION_MODAL); arg++;
	confirm_overwrite_dialog = 
	    verify(XmCreateQuestionDialog(plot->shell,
					  XMST("confirm_overwrite_dialog"), 
					  args, arg));
	Delay::register_shell(confirm_overwrite_dialog);

	bool yes = false;
	bool no  = false;
	   
	XtAddCallback(confirm_overwrite_dialog,
		      XmNokCallback, SetCB, XtPointer(&yes));
	XtAddCallback(confirm_overwrite_dialog,
		      XmNcancelCallback, SetCB, XtPointer(&no));
	XtAddCallback(confirm_overwrite_dialog, 
		      XmNhelpCallback, ImmediateHelpCB, 0);

	MString question = rm("Overwrite existing file " 
			      + quote(target) + "?");
	XtVaSetValues (confirm_overwrite_dialog, XmNmessageString, 
		       question.xmstring(), XtPointer(0));
	manage_and_raise(confirm_overwrite_dialog);

	XtAppContext app_context = XtWidgetToApplicationContext(plot->shell);
	while (!yes && !no)
	    XtAppProcessEvent(app_context, XtIMAll);

	if (no)
	    return;
    }

    StatusDelay delay("Saving " + title + " data to " + quote(target));

    // Copy SOURCE to TARGET
    std::ifstream is(source.chars());
    std::ofstream os(target.chars());

    if (os.bad())
    {
	FILE *fp = fopen(target.chars(), "w");
	post_error(string("Cannot open ") 
		   + quote(target) + ": " + strerror(errno), 
		   "export_failed_error", plot->shell);
	if (fp)
	    fclose(fp);
	delay.outcome = strerror(errno);
	return;
    }

    int c;
    while ((c = is.get()) != EOF)
	os.put((unsigned char) c);

    XtUnmanageChild(plot->export_dialog);
}