Exemplo n.º 1
0
extern "C" void Sys_FPrintf_VA( int level, const char *text, va_list args ) {
	char buf[BUFFER_SIZE];

	buf[0] = 0;
	vsnprintf( buf, BUFFER_SIZE, text, args );
	buf[BUFFER_SIZE - 1] = 0;
	const unsigned int length = strlen( buf );

	if ( g_qeglobals.hLogFile ) {
#ifdef _WIN32
		_write( g_qeglobals.hLogFile, buf, length );
		_commit( g_qeglobals.hLogFile );
#endif
#if defined ( __linux__ ) || defined ( __APPLE__ )
		write( g_qeglobals.hLogFile, buf, length );
#endif
	}

	if ( level != SYS_NOCON ) {
		// TTimo: FIXME: killed the console to avoid GDI leak fuckup
		if ( g_qeglobals_gui.d_edit != NULL ) {
			GtkTextBuffer* buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW( g_qeglobals_gui.d_edit ) );

			GtkTextIter iter;
			gtk_text_buffer_get_end_iter( buffer, &iter );

			static GtkTextMark* end = gtk_text_buffer_create_mark( buffer, "end", &iter, FALSE );

			const GdkColor yellow = { 0, 0xb0ff, 0xb0ff, 0x0000 };
			const GdkColor red = { 0, 0xffff, 0x0000, 0x0000 };
			const GdkColor black = { 0, 0x0000, 0x0000, 0x0000 };

			static GtkTextTag* error_tag = gtk_text_buffer_create_tag( buffer, "red_foreground", "foreground-gdk", &red, NULL );
			static GtkTextTag* warning_tag = gtk_text_buffer_create_tag( buffer, "yellow_foreground", "foreground-gdk", &yellow, NULL );
			static GtkTextTag* standard_tag = gtk_text_buffer_create_tag( buffer, "black_foreground", "foreground-gdk", &black, NULL );
			GtkTextTag* tag;
			switch ( level )
			{
			case SYS_WRN:
				tag = warning_tag;
				break;
			case SYS_ERR:
				tag = error_tag;
				break;
			case SYS_STD:
			case SYS_VRB:
			default:
				tag = standard_tag;
				break;
			}
			gtk_text_buffer_insert_with_tags( buffer, &iter, buf, length, tag, NULL );

			gtk_text_view_scroll_mark_onscreen( GTK_TEXT_VIEW( g_qeglobals_gui.d_edit ), end );

			// update console widget immediatly if we're doing something time-consuming
			if ( !g_bScreenUpdates && GTK_WIDGET_REALIZED( g_qeglobals_gui.d_edit ) ) {
				gtk_grab_add( g_qeglobals_gui.d_edit );

				while ( gtk_events_pending() )
					gtk_main_iteration();

				gtk_grab_remove( g_qeglobals_gui.d_edit );
			}
		}
	}
}
Exemplo n.º 2
0
/**
 * Attempts to initialize the graphical video display.  Returns 0 on
 * success, -1 on failure.
 */
int
InitVideo(FCEUGI *gi)
{
    // XXX soules - const?  is this necessary?
    const SDL_VideoInfo *vinf;
    int error, flags = 0;
    int doublebuf, xstretch, ystretch, xres, yres, show_fps;

    FCEUI_printf("Initializing video...");

    // load the relevant configuration variables
    g_config->getOption("SDL.Fullscreen", &s_fullscreen);
    g_config->getOption("SDL.DoubleBuffering", &doublebuf);
#ifdef OPENGL
    g_config->getOption("SDL.OpenGL", &s_useOpenGL);
#endif
    g_config->getOption("SDL.SpecialFilter", &s_sponge);
    g_config->getOption("SDL.XStretch", &xstretch);
    g_config->getOption("SDL.YStretch", &ystretch);
    g_config->getOption("SDL.LastXRes", &xres);
    g_config->getOption("SDL.LastYRes", &yres);
    g_config->getOption("SDL.ClipSides", &s_clipSides);
    g_config->getOption("SDL.NoFrame", &noframe);
    g_config->getOption("SDL.ShowFPS", &show_fps);

    // check the starting, ending, and total scan lines
    FCEUI_GetCurrentVidSystem(&s_srendline, &s_erendline);
    s_tlines = s_erendline - s_srendline + 1;

    // check if we should auto-set x/y resolution

    // check for OpenGL and set the global flags
#if OPENGL
    if(s_useOpenGL && !s_sponge) {
        flags = SDL_OPENGL;
    }
#endif

    // initialize the SDL video subsystem if it is not already active
    if(!SDL_WasInit(SDL_INIT_VIDEO)) {
        error = SDL_InitSubSystem(SDL_INIT_VIDEO);
        if(error) {
            FCEUD_PrintError(SDL_GetError());
            return -1;
        }
    }
    s_inited = 1;

    // shows the cursor within the display window
    SDL_ShowCursor(1);

    // determine if we can allocate the display on the video card
    vinf = SDL_GetVideoInfo();
    if(vinf->hw_available) {
        flags |= SDL_HWSURFACE;
    }

    // get the monitor's current resolution if we do not already have it
    if(s_nativeWidth < 0) {
        s_nativeWidth = vinf->current_w;
    }
    if(s_nativeHeight < 0) {
        s_nativeHeight = vinf->current_h;
    }

    // check to see if we are showing FPS
    FCEUI_SetShowFPS(show_fps);

    // check if we are rendering fullscreen
    if(s_fullscreen) {
        int no_cursor;
        g_config->getOption("SDL.NoFullscreenCursor", &no_cursor);
        flags |= SDL_FULLSCREEN;
        SDL_ShowCursor(!no_cursor);
    }
    else {
        SDL_ShowCursor(1);
    }

    if(noframe) {
        flags |= SDL_NOFRAME;
    }

    // gives the SDL exclusive palette control... ensures the requested colors
    flags |= SDL_HWPALETTE;

    // enable double buffering if requested and we have hardware support
#ifdef OPENGL
    if(s_useOpenGL) {
        FCEU_printf("Initializing with OpenGL (Disable with '--opengl 0').\n");
        if(doublebuf) {
            SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
        }
    } else
#endif
        if(doublebuf && (flags & SDL_HWSURFACE)) {
            flags |= SDL_DOUBLEBUF;
        }

    if(s_fullscreen) {
        int desbpp, autoscale;
        g_config->getOption("SDL.BitsPerPixel", &desbpp);
        g_config->getOption("SDL.AutoScale", &autoscale);
        if (autoscale)
        {
            double auto_xscale = GetXScale(xres);
            double auto_yscale = GetYScale(yres);
            double native_ratio = ((double)NWIDTH) / s_tlines;
            double screen_ratio = ((double)xres) / yres;
            int keep_ratio;

            g_config->getOption("SDL.KeepRatio", &keep_ratio);

            // Try to choose resolution
            if (screen_ratio < native_ratio)
            {
                // The screen is narrower than the original. Maximizing width will not clip
                auto_xscale = auto_yscale = GetXScale(xres);
                if (keep_ratio)
                    auto_yscale = GetYScale(yres);
            }
            else
            {
                auto_yscale = auto_xscale = GetYScale(yres);
                if (keep_ratio)
                    auto_xscale = GetXScale(xres);
            }
            s_exs = auto_xscale;
            s_eys = auto_yscale;
        }
        else
        {
            g_config->getOption("SDL.XScale", &s_exs);
            g_config->getOption("SDL.YScale", &s_eys);
        }
        g_config->getOption("SDL.SpecialFX", &s_eefx);

#ifdef OPENGL
        if(!s_useOpenGL) {
            s_exs = (int)s_exs;
            s_eys = (int)s_eys;
        } else {
            desbpp = 0;
        }


        if((s_useOpenGL && !xstretch) || !s_useOpenGL)
#endif
            if(xres < (NWIDTH * s_exs) || s_exs <= 0.01) {
                FCEUD_PrintError("xscale out of bounds.");
                KillVideo();
                return -1;
            }

#ifdef OPENGL
        if((s_useOpenGL && !ystretch) || !s_useOpenGL)
#endif
            if(yres < s_tlines * s_eys || s_eys <= 0.01) {
                FCEUD_PrintError("yscale out of bounds.");
                KillVideo();
                return -1;
            }

#ifdef OPENGL
        s_screen = SDL_SetVideoMode(s_useOpenGL ? s_nativeWidth : xres,
                                    s_useOpenGL ? s_nativeHeight : yres,
                                    desbpp, flags);
#else
        s_screen = SDL_SetVideoMode(xres, yres, desbpp, flags);
#endif

        if(!s_screen) {
            FCEUD_PrintError(SDL_GetError());
            return -1;
        }
    } else {
        int desbpp;
        g_config->getOption("SDL.BitsPerPixel", &desbpp);

        g_config->getOption("SDL.XScale", &s_exs);
        g_config->getOption("SDL.YScale", &s_eys);
        g_config->getOption("SDL.SpecialFX", &s_eefx);

        // -Video Modes Tag-
        if(s_sponge) {
            if(s_sponge <= 3 && s_sponge >= 1)
            {
                s_exs = s_eys = 2;
            } else if (s_sponge >=4 && s_sponge <= 5)
            {
                s_exs = s_eys = 3;
            } else if (s_sponge >= 6 && s_sponge <= 8)
            {
                s_exs = s_eys = s_sponge - 4;
            }
            else if(s_sponge == 9)
            {
                s_exs = s_eys = 3;
            }
            else
            {
                s_exs = s_eys = 1;
            }
            if(s_sponge == 3) {
                xres = 301 * s_exs;
            }
            s_eefx = 0;
            if(s_sponge == 1 || s_sponge == 4) {
                desbpp = 32;
            }
        }

        int scrw = NWIDTH * s_exs;
        if(s_sponge == 3) {
            scrw = 301 * s_exs;
        }

#ifdef OPENGL
        if(!s_useOpenGL) {
            s_exs = (int)s_exs;
            s_eys = (int)s_eys;
        }
        if(s_exs <= 0.01) {
            FCEUD_PrintError("xscale out of bounds.");
            KillVideo();
            return -1;
        }
        if(s_eys <= 0.01) {
            FCEUD_PrintError("yscale out of bounds.");
            KillVideo();
            return -1;
        }
        if(s_sponge && s_useOpenGL) {
            FCEUD_PrintError("scalers not compatible with openGL mode.");
            KillVideo();
            return -1;
        }
#endif

#if defined(_GTK) && defined(SDL_VIDEO_DRIVER_X11) && defined(GDK_WINDOWING_X11)
        if(noGui == 0)
        {
            while (gtk_events_pending())
                gtk_main_iteration_do(FALSE);

            char SDL_windowhack[128];
            sprintf(SDL_windowhack, "SDL_WINDOWID=%u", (unsigned int)GDK_WINDOW_XID(gtk_widget_get_window(evbox)));
            SDL_putenv(SDL_windowhack);

            // init SDL video
            if (SDL_WasInit(SDL_INIT_VIDEO))
                SDL_QuitSubSystem(SDL_INIT_VIDEO);
            if ( SDL_InitSubSystem(SDL_INIT_VIDEO) < 0 )
            {
                fprintf(stderr, "Couldn't init SDL video: %s\n", SDL_GetError());
                gtk_main_quit();
            }
        }
#endif

        s_screen = SDL_SetVideoMode(scrw, (int)(s_tlines * s_eys),
                                    desbpp, flags);
        if(!s_screen) {
            FCEUD_PrintError(SDL_GetError());
            return -1;
        }

#ifdef _GTK
        if(noGui == 0)
        {
            GtkRequisition req;
            gtk_widget_size_request(GTK_WIDGET(MainWindow), &req);
            gtk_window_resize(GTK_WINDOW(MainWindow), req.width, req.height);
        }
#endif
    }
    s_curbpp = s_screen->format->BitsPerPixel;
    if(!s_screen) {
        FCEUD_PrintError(SDL_GetError());
        KillVideo();
        return -1;
    }

#if 0
    // XXX soules - this would be creating a surface on the video
    //              card, but was commented out for some reason...
    s_BlitBuf = SDL_CreateRGBSurface(SDL_HWSURFACE, 256, 240,
                                     s_screen->format->BitsPerPixel,
                                     s_screen->format->Rmask,
                                     s_screen->format->Gmask,
                                     s_screen->format->Bmask, 0);
#endif

    FCEU_printf(" Video Mode: %d x %d x %d bpp %s\n",
                s_screen->w, s_screen->h, s_screen->format->BitsPerPixel,
                s_fullscreen ? "full screen" : "");

    if(s_curbpp != 8 && s_curbpp != 16 && s_curbpp != 24 && s_curbpp != 32) {
        FCEU_printf("  Sorry, %dbpp modes are not supported by FCE Ultra.  Supported bit depths are 8bpp, 16bpp, and 32bpp.\n", s_curbpp);
        KillVideo();
        return -1;
    }

    // if the game being run has a name, set it as the window name
    if(gi)
    {
        if(gi->name) {
            SDL_WM_SetCaption((const char *)gi->name, (const char *)gi->name);
        } else {
            SDL_WM_SetCaption(FCEU_NAME_AND_VERSION,"FCE Ultra");
        }
    }

    // create the surface for displaying graphical messages
#ifdef LSB_FIRST
    s_IconSurface = SDL_CreateRGBSurfaceFrom((void *)fceu_playicon.pixel_data,
                    32, 32, 24, 32 * 3,
                    0xFF, 0xFF00, 0xFF0000, 0x00);
#else
    s_IconSurface = SDL_CreateRGBSurfaceFrom((void *)fceu_playicon.pixel_data,
                    32, 32, 24, 32 * 3,
                    0xFF0000, 0xFF00, 0xFF, 0x00);
#endif
    SDL_WM_SetIcon(s_IconSurface,0);
    s_paletterefresh = 1;

    // XXX soules - can't SDL do this for us?
    // if using more than 8bpp, initialize the conversion routines
    if(s_curbpp > 8) {
        InitBlitToHigh(s_curbpp >> 3,
                       s_screen->format->Rmask,
                       s_screen->format->Gmask,
                       s_screen->format->Bmask,
                       s_eefx, s_sponge, 0);
#ifdef OPENGL
        if(s_useOpenGL)
        {
            int openGLip;
            g_config->getOption("SDL.OpenGLip", &openGLip);

            if(!InitOpenGL(NOFFSET, 256 - (s_clipSides ? 8 : 0),
                           s_srendline, s_erendline + 1,
                           s_exs, s_eys, s_eefx,
                           openGLip, xstretch, ystretch, s_screen))
            {
                FCEUD_PrintError("Error initializing OpenGL.");
                KillVideo();
                return -1;
            }
        }
#endif
    }
Exemplo n.º 3
0
/* Updates mserv data (rating only) of @track using filename @name to
 look up mserv information.
 Return TRUE if successfully updated (or disabled), FALSE if not */
gboolean update_mserv_data_from_file(gchar *name, Track *track) {
    gboolean success = TRUE;

    if (!name || !track)
        return FALSE;

    if (g_file_test(name, G_FILE_TEST_IS_DIR))
        return FALSE;
    if (!g_file_test(name, G_FILE_TEST_EXISTS)) {
        gchar *buf = g_strdup_printf(_("Local filename not valid (%s)"), name);
        display_mserv_problems(track, buf);
        g_free(buf);
        return FALSE;
    }

    if (prefs_get_int("mserv_use")) {
        /* try getting the user's rating from the mserv db */
        gchar *music_root = prefs_get_string("path_mserv_music_root");
        gchar *trackinfo_root = prefs_get_string("path_mserv_trackinfo_root");

        /* we expect music_root and trackinfo_root to be initialized */
        if (!music_root)
            music_root = g_strdup("");
        if (!trackinfo_root)
            trackinfo_root = g_strdup("");

        success = FALSE;
        /* printf("mroot %s troot %s fname %s\n", music_root, trackinfo_root, name); */

        /* first, check if the file is in the mserv music directory */
        if (*music_root == 0 || strstr(name, music_root)) {
            gchar *infoname =
                    g_strdup_printf("%s%c%s.trk", trackinfo_root, G_DIR_SEPARATOR, &(name[strlen(music_root)]));
            /* printf("trying %s\n", infoname); */
            FILE *fp = fopen(infoname, "r");
            if (fp) {
                /* printf("opened\n");*/
                gchar buff[PATH_MAX];
                gchar *username = prefs_get_string("mserv_username");
                guint usernamelen;
                g_return_val_if_fail (username, (fclose (fp), FALSE));
                usernamelen = strlen(username);
                while (fgets(buff, PATH_MAX, fp)) {
                    /* printf("username %s (%d) read %s\n",
                     * prefs_get_string("mserv_username"), usernamelen,
                     * buff);*/
                    if (strncmp(buff, username, usernamelen) == 0 && buff[usernamelen] == (gchar) '=') {
                        /* found it */
                        track->rating = atoi(&buff[usernamelen + 1]) * ITDB_RATING_STEP;
                        /* printf("found it, = %d\n",
                         orig_track->rating/ITDB_RATING_STEP); */
                        success = TRUE;
                        break; /* while(fgets(... */
                    }
                }
                fclose(fp);
                g_free(username);
                if (!success) {
                    gchar *username = prefs_get_string("mserv_username");
                    gchar *buf = g_strdup_printf(_("No information found for user '%s' in '%s'"), username, infoname);
                    display_mserv_problems(track, buf);
                    g_free(buf);
                    g_free(username);
                }
            }
            else {
                gchar *buf = g_strdup_printf(_("mserv data file (%s) not available for track (%s)"), infoname, name);
                display_mserv_problems(track, buf);
                g_free(buf);
            }
            g_free(infoname);
        }
        else {
            gchar *buf = g_strdup_printf(_("Track (%s) not in mserv music root directory (%s)"), name, music_root);
            display_mserv_problems(track, buf);
            g_free(buf);
        }
        g_free(music_root);
        g_free(trackinfo_root);
    }

    while (widgets_blocked && gtk_events_pending())
        gtk_main_iteration();

    return success;
}
Exemplo n.º 4
0
void
open_grf_file (const char *fname)
{
	char *title, *tmp;
	GrfError err;
	Grf *newgrf;
	GList *list, *cols;

	if (!g_file_test (fname, G_FILE_TEST_EXISTS)) {
		show_error (_("File %s does not exist."), fname);
		return;
	}

	mainWin.busy (true);
	mainWin.status (_("Loading..."));
	while (gtk_events_pending ()) gtk_main_iteration ();
	newgrf = grf_open (fname, "r", &err);
	if (!newgrf) {
		char *base;

		base = g_path_get_basename (fname);
		mainWin.status ("");
		gdk_window_set_cursor (W(main)->window, NULL);
		show_error (_("Error while opening %s:\n%s"),
			base, grf_strerror (err));
		g_free (base);
		return;
	}
	if (document.grf)
		grf_free (document.grf);
	document.grf = newgrf;

	document.filename = fname;

	title = g_strdup_printf (_("%s - GRF Tool"), fname);
	gtk_window_set_title (GTK_WINDOW (W(main)), title);
	g_free (title);

	gtk_list_store_clear (GTK_LIST_STORE (filelist));

	cols = gtk_tree_view_get_columns (GTK_TREE_VIEW (W(filelist)));
	for (list = cols; list; list = list->next) {
		GtkTreeViewColumn *col = (GtkTreeViewColumn *) list->data;
		gtk_tree_view_column_set_sort_indicator (col, FALSE);
	}
	gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (filelist),
		GTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID, GTK_SORT_ASCENDING);
	g_list_free (cols);


	fill_filelist ();


	tmp = g_path_get_basename (fname);
	title = g_strdup_printf (_("%s: %ld files"), tmp, (long int)document.grf->nfiles);
	mainWin.status (title);
	g_free (tmp);
	g_free (title);
	gtk_widget_set_sensitive (W(extract), TRUE);
	mainWin.busy (false);
}
Exemplo n.º 5
0
void
main_loop ()
{
#if HAVE_SDL
  SDL_Event event[1];
#endif

#if HAVE_FREEGLUT

  // Passing the GTK+ signals to the FreeGLUT main loop
  glutIdleFunc ((void (*)) gtk_main_iteration);
  // Setting our draw resize function as the FreeGLUT reshape function
  glutReshapeFunc (draw_resize);
  // Setting our draw function as the FreeGLUT display function
  glutDisplayFunc (draw);
  // FreeGLUT main loop
  glutMainLoop ();

#else

#if HAVE_SDL
  while (1)
    {
      while (gtk_events_pending ())
        gtk_main_iteration ();
      while (SDL_PollEvent (event))
        {
          if (event->type == SDL_QUIT)
            return;
          if (event->type == SDL_WINDOWEVENT
              && event->window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
            draw_resize (event->window.data1, event->window.data2);
        }

#elif HAVE_GLFW

  while (!glfwWindowShouldClose (window))
    {
      while (gtk_events_pending ())
        gtk_main_iteration ();
      glfwPollEvents ();

#endif

      draw ();
    }

#endif
}

/**
 * \fn int main(int argn, char **argc)
 * \brief Main function
 * \param argn
 * \brief Arguments number.
 * \param argc
 * \brief Array of arguments.
 * \return 0 on success.
 */
int
main (int argn, char **argc)
{
  GLenum glew_status;

// PARALELLIZING INIT
#ifdef G_OS_WIN32
  SYSTEM_INFO sysinfo;
  GetSystemInfo (&sysinfo);
  nthreads = sysinfo.dwNumberOfProcessors;
#else
  nthreads = (int) sysconf (_SC_NPROCESSORS_CONF);
#endif
// END

  // Initing locales
#if DEBUG
  printf ("Initing locales\n");
  fflush (stdout);
#endif
  bindtextdomain ("fractal", "./po");
  bind_textdomain_codeset ("fractal", "UTF-8");
  textdomain ("fractal");

  // Initing graphic window
#if HAVE_FREEGLUT

#if DEBUG
  printf ("Initing FreeGLUT window\n");
  fflush (stdout);
#endif
  glutInit (&argn, argc);
  glutInitDisplayMode (GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
  glutInitWindowSize (window_width, window_height);
  glutCreateWindow ("fractal");

#elif HAVE_SDL

#if DEBUG
  printf ("Initing SDL window\n");
  fflush (stdout);
#endif
  SDL_Init (SDL_INIT_VIDEO);
  window = SDL_CreateWindow ("fractal",
                             SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                             window_width, window_height,
                             SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL);
  if (!window)
    {
      printf ("ERROR! unable to create the window: %s\n", SDL_GetError ());
      return 1;
    }
  SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 2);
  if (!SDL_GL_CreateContext (window))
    {
      printf ("ERROR! SDL_GL_CreateContext: %s\n", SDL_GetError ());
      return 1;
    }

#elif HAVE_GLFW

#if DEBUG
  printf ("Initing GLFW window\n");
  fflush (stdout);
#endif
  if (!glfwInit ())
    {
      printf ("ERROR! unable to init GLFW\n");
      return 1;
    }
  window
    = glfwCreateWindow (window_width, window_height, "fractal", NULL, NULL);
  if (!window)
    {
      printf ("ERROR! unable to open the window\n");
      glfwTerminate ();
      return 1;
    }
  glfwMakeContextCurrent (window);

#endif

  // Initing GLEW
#if DEBUG
  printf ("Initing GLEW\n");
  fflush (stdout);
#endif
  glew_status = glewInit ();
  if (glew_status != GLEW_OK)
    {
      printf ("ERROR! glewInit: %s\n", glewGetErrorString (glew_status));
      return 1;
    }

  // Initing FreeType
  if (FT_Init_FreeType (&ft))
  {
    printf("ERROR! could not init freetype library\n");
    return 1;
  }

  // Initing GTK+
#if DEBUG
  printf ("Initing GTK+\n");
  fflush (stdout);
#endif
  gtk_init (&argn, &argc);

  // Initing logo
#if DEBUG
  printf ("Initing logo\n");
  fflush (stdout);
#endif
  logo_new ("logo.png");

  // Initing drawing data
#if DEBUG
  printf ("Initing drawing data\n");
  fflush (stdout);
#endif
  if (!draw_init ())
    return 1;

  // Creating the main GTK+ window
#if DEBUG
  printf ("Creating simulator dialog\n");
  fflush (stdout);
#endif
  dialog_simulator_create (dialog_simulator);

#if DEBUG
  printf ("Main loop\n");
  fflush (stdout);
#endif
  main_loop ();

  // Freeing memory
#if HAVE_GLFW
  glfwDestroyWindow (window);
  glfwTerminate ();
#endif

  return 0;
}
Exemplo n.º 6
0
Arquivo: main.c Projeto: g0orx/pihpsdr
gint init(void* arg) {

  gint x;
  gint y;

  DISCOVERED* d;

  char *res;
  char wisdom_directory[1024];
  char wisdom_file[1024];

  fprintf(stderr,"init\n");

  audio_get_cards(0);
  audio_get_cards(1);

  cursor_arrow=gdk_cursor_new(GDK_ARROW);
  cursor_watch=gdk_cursor_new(GDK_WATCH);

  GdkWindow *gdk_splash_window = gtk_widget_get_window(splash_window);
  gdk_window_set_cursor(gdk_splash_window,cursor_watch);

  init_radio();

  // check if wisdom file exists
  res=getcwd(wisdom_directory, sizeof(wisdom_directory));
  strcpy(&wisdom_directory[strlen(wisdom_directory)],"/");
  strcpy(wisdom_file,wisdom_directory);
  strcpy(&wisdom_file[strlen(wisdom_file)],"wdspWisdom");
  splash_status("Checking FFTW Wisdom file ...");
  if(access(wisdom_file,F_OK)<0) {
      int rc=sem_init(&wisdom_sem, 0, 0);
      rc=pthread_create(&wisdom_thread_id, NULL, wisdom_thread, (void *)wisdom_directory);
      while(sem_trywait(&wisdom_sem)<0) {
        splash_status(wisdom_get_status());
        while (gtk_events_pending ())
          gtk_main_iteration ();
        usleep(100000); // 100ms
      }
  }

  while(!start) {
      gdk_window_set_cursor(gdk_splash_window,cursor_watch);
      selected_device=0;
      devices=0;
      splash_status("Old Protocol ... Discovering Devices");
      old_discovery();
      splash_status("New Protocol ... Discovering Devices");
      new_discovery();
#ifdef LIMESDR
      splash_status("LimeSDR ... Discovering Devices");
      lime_discovery();
#endif
      splash_status("Discovery");
      if(devices==0) {
          gdk_window_set_cursor(gdk_splash_window,cursor_arrow);
          fprintf(stderr,"No devices found!\n");
          GtkDialogFlags flags = GTK_DIALOG_DESTROY_WITH_PARENT;
          discovery_dialog = gtk_message_dialog_new (GTK_WINDOW(splash_window),
                                 flags,
                                 GTK_MESSAGE_ERROR,
                                 GTK_BUTTONS_OK_CANCEL,
                                 "No devices found! Retry Discovery?");
          gtk_widget_override_font(discovery_dialog, pango_font_description_from_string("FreeMono 18"));
          gint result=gtk_dialog_run (GTK_DIALOG (discovery_dialog));
          gtk_widget_destroy(discovery_dialog);
          if(result==GTK_RESPONSE_CANCEL) {
               _exit(0);
          }
      } else {
          fprintf(stderr,"%s: found %d devices.\n", (char *)arg, devices);
          gdk_window_set_cursor(gdk_splash_window,cursor_arrow);
          GtkDialogFlags flags=GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT;
          discovery_dialog = gtk_dialog_new_with_buttons ("Discovered",
                                      GTK_WINDOW(splash_window),
                                      flags,
#ifdef GPIO
                                      "Configure GPIO",
                                      GTK_RESPONSE_YES,
#endif
                                      "Discover",
                                      GTK_RESPONSE_REJECT,
                                      "Exit",
                                      GTK_RESPONSE_CLOSE,
                                      NULL);

          gtk_widget_override_font(discovery_dialog, pango_font_description_from_string("FreeMono 18"));
          GtkWidget *content;

          content=gtk_dialog_get_content_area(GTK_DIALOG(discovery_dialog));

          GtkWidget *grid=gtk_grid_new();
          gtk_grid_set_row_homogeneous(GTK_GRID(grid),TRUE);
          gtk_grid_set_column_homogeneous(GTK_GRID(grid),TRUE);
          gtk_grid_set_row_spacing (GTK_GRID(grid),10);

          int i;
          char version[16];
          char text[128];
          for(i=0;i<devices;i++) {
              d=&discovered[i];
fprintf(stderr,"%p protocol=%d name=%s\n",d,d->protocol,d->name);
              if(d->protocol==ORIGINAL_PROTOCOL) {
                  sprintf(version,"%d.%d",
                        d->software_version/10,
                        d->software_version%10);
              } else {
                  sprintf(version,"%d.%d.%d",
                        d->software_version/100,
                        (d->software_version%100)/10,
                        d->software_version%10);
              }
              switch(d->protocol) {
                case ORIGINAL_PROTOCOL:
                case NEW_PROTOCOL:
                  sprintf(text,"%s (%s %s) %s (%02X:%02X:%02X:%02X:%02X:%02X) on %s\n",
                        d->name,
                        d->protocol==ORIGINAL_PROTOCOL?"old":"new",
                        version,
                        inet_ntoa(d->info.network.address.sin_addr),
                        d->info.network.mac_address[0],
                        d->info.network.mac_address[1],
                        d->info.network.mac_address[2],
                        d->info.network.mac_address[3],
                        d->info.network.mac_address[4],
                        d->info.network.mac_address[5],
                        d->info.network.interface_name);
                  break;
#ifdef LIMESDR
                case LIMESDR_PROTOCOL:
/*
                  sprintf(text,"%s (%s %s)\n",
                        d->name,
                        "lime",
                        version);
*/
                  sprintf(text,"%s\n",
                        d->name);
                  break;
#endif
              }

              GtkWidget *label=gtk_label_new(text);
              gtk_widget_override_font(label, pango_font_description_from_string("FreeMono 12"));
              gtk_widget_show(label);
              gtk_grid_attach(GTK_GRID(grid),label,0,i,3,1);

              GtkWidget *start_button=gtk_button_new_with_label("Start");
              gtk_widget_override_font(start_button, pango_font_description_from_string("FreeMono 18"));
              gtk_widget_show(start_button);
              gtk_grid_attach(GTK_GRID(grid),start_button,3,i,1,1);
              g_signal_connect(start_button,"pressed",G_CALLBACK(start_cb),(gpointer)d);

              // if not available then cannot start it
              if(d->status!=STATE_AVAILABLE) {
                gtk_button_set_label(GTK_BUTTON(start_button),"In Use");
                gtk_widget_set_sensitive(start_button, FALSE);
              }

              // if not on the same subnet then cannot start it
              if((d->info.network.interface_address.sin_addr.s_addr&d->info.network.interface_netmask.sin_addr.s_addr) != (d->info.network.address.sin_addr.s_addr&d->info.network.interface_netmask.sin_addr.s_addr)) {
                gtk_button_set_label(GTK_BUTTON(start_button),"Subnet!");
                gtk_widget_set_sensitive(start_button, FALSE);
              }

          }

          gtk_container_add (GTK_CONTAINER (content), grid);
          gtk_widget_show_all(discovery_dialog);
          gint result=gtk_dialog_run(GTK_DIALOG(discovery_dialog));

          if(result==GTK_RESPONSE_CLOSE) {
              _exit(0);
          }
         
          if(!start) {
            gtk_widget_destroy(discovery_dialog);
          }
#ifdef GPIO
          if(result==GTK_RESPONSE_YES) {
              configure_gpio(splash_window);
          }
#endif
      }
  }

  gdk_window_set_cursor(gdk_splash_window,cursor_watch);

  splash_status("Initializing wdsp ...");

fprintf(stderr,"selected radio=%p device=%d\n",radio,radio->device);

  protocol=radio->protocol;
  device=radio->device;


  switch(radio->protocol) {
    case ORIGINAL_PROTOCOL:
    case NEW_PROTOCOL:
      sprintf(property_path,"%02X-%02X-%02X-%02X-%02X-%02X.props",
                        radio->info.network.mac_address[0],
                        radio->info.network.mac_address[1],
                        radio->info.network.mac_address[2],
                        radio->info.network.mac_address[3],
                        radio->info.network.mac_address[4],
                        radio->info.network.mac_address[5]);
      break;
#ifdef LIMESDR
    case LIMESDR_PROTOCOL:
      sprintf(property_path,"limesdr.props");
      break;
#endif
  }

  radioRestoreState();

  fprintf(stderr,"malloc samples\n");
  if(radio->protocol==NEW_PROTOCOL) {
    samples=malloc(display_width*sizeof(float)*2*4); // 192 -> 48
  } else {
    samples=malloc(display_width*sizeof(float)*2);
  }

  //splash_status("Initializing wdsp ...");
  fprintf(stderr,"wdsp_init\n");
  wdsp_init(0,display_width,radio->protocol);

  switch(radio->protocol) {
    case ORIGINAL_PROTOCOL:
      splash_status("Initializing old protocol ...");
  fprintf(stderr,"old_protocol_init\n");
      old_protocol_init(0,display_width);
      break;
    case NEW_PROTOCOL:
      splash_status("Initializing new protocol ...");
  fprintf(stderr,"new_protocol_init\n");
      new_protocol_init(0,display_width);
      break;
#ifdef LIMESDR
    case LIMESDR_PROTOCOL:
      splash_status("Initializing lime protocol ...");
      lime_protocol_init(0,display_width);
      break;
#endif
  }

  fprintf(stderr,"gpio_init\n");
  splash_status("Initializing GPIO ...");
#ifdef GPIO
  if(gpio_init()<0) {
  }
#endif

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title (GTK_WINDOW (window), "pihpsdr");
  gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER_ALWAYS);
  gtk_window_set_resizable(GTK_WINDOW(window), FALSE);
  g_signal_connect (window, "delete-event", G_CALLBACK (main_delete), NULL);

  fixed=gtk_fixed_new();
  gtk_container_add(GTK_CONTAINER(window), fixed);
  y=0;

fprintf(stderr,"vfo_height=%d\n",VFO_HEIGHT);
  vfo = vfo_init(VFO_WIDTH,VFO_HEIGHT,window);
  gtk_fixed_put(GTK_FIXED(fixed),vfo,0,0);



  rit_control = rit_init(RIT_WIDTH,MENU_HEIGHT,window);
  gtk_fixed_put(GTK_FIXED(fixed),rit_control,VFO_WIDTH,y);

fprintf(stderr,"menu_height=%d\n",MENU_HEIGHT);
  //menu = menu_init(MENU_WIDTH,MENU_HEIGHT,window);
  menu = new_menu_init(MENU_WIDTH-RIT_WIDTH,MENU_HEIGHT,window);
  gtk_fixed_put(GTK_FIXED(fixed),menu,VFO_WIDTH+((MENU_WIDTH/3)*2),y);

fprintf(stderr,"meter_height=%d\n",METER_HEIGHT);
  meter = meter_init(METER_WIDTH,METER_HEIGHT,window);
  gtk_fixed_put(GTK_FIXED(fixed),meter,VFO_WIDTH+MENU_WIDTH,y);
  y+=VFO_HEIGHT;

  if(display_panadapter) {
    int height=PANADAPTER_HEIGHT;
    if(!display_waterfall) {
      height+=WATERFALL_HEIGHT;
      if(!display_sliders) {
        height+=SLIDERS_HEIGHT;
      }
      if(!display_toolbar) {
        height+=TOOLBAR_HEIGHT;
      }
    } else {
      if(!display_sliders) {
        height+=SLIDERS_HEIGHT/2;
      }
    }
fprintf(stderr,"panadapter_height=%d\n",height);
    panadapter = panadapter_init(display_width,height);
    gtk_fixed_put(GTK_FIXED(fixed),panadapter,0,VFO_HEIGHT);
    y+=height;
  }

  if(display_waterfall) {
    int height=WATERFALL_HEIGHT;
    if(!display_panadapter) {
      height+=PANADAPTER_HEIGHT;
    }
    if(!display_sliders) {
      if(display_panadapter) {
        height+=SLIDERS_HEIGHT/2;
      } else {
        height+=SLIDERS_HEIGHT;
      }
    }
    if(!display_toolbar) {
      height+=TOOLBAR_HEIGHT;
    }
fprintf(stderr,"waterfall_height=%d\n",height);
    waterfall = waterfall_init(display_width,height);
    gtk_fixed_put(GTK_FIXED(fixed),waterfall,0,y);
    y+=height;

  }

#ifdef PSK
    int psk_height=PSK_WATERFALL_HEIGHT;
    if(!display_sliders) {
      psk_height+=SLIDERS_HEIGHT/2;
    }
    if(!display_toolbar) {
      psk_height+=TOOLBAR_HEIGHT/2;
    }
    psk_waterfall = psk_waterfall_init(display_width,psk_height);
    gtk_fixed_put(GTK_FIXED(fixed),psk_waterfall,0,VFO_HEIGHT);
    psk = init_psk();
    gtk_fixed_put(GTK_FIXED(fixed),psk,0,VFO_HEIGHT+psk_height);
#endif

  if(display_sliders) {
fprintf(stderr,"sliders_height=%d\n",SLIDERS_HEIGHT);
    sliders = sliders_init(display_width,SLIDERS_HEIGHT,window);
    gtk_fixed_put(GTK_FIXED(fixed),sliders,0,y);
    y+=SLIDERS_HEIGHT;
  }

  if(display_toolbar) {
fprintf(stderr,"toolbar_height=%d\n",TOOLBAR_HEIGHT);
    toolbar = toolbar_init(display_width,TOOLBAR_HEIGHT,window);
    gtk_fixed_put(GTK_FIXED(fixed),toolbar,0,y);
    y+=TOOLBAR_HEIGHT;
  }

  splash_close();

  gtk_widget_show_all (window);

  if(full_screen) {
    gtk_window_fullscreen(GTK_WINDOW(window));
  }

  GdkWindow *gdk_window = gtk_widget_get_window(window);
  gdk_window_set_cursor(gdk_window,cursor_arrow);

  // start the receiver
  SetChannelState(CHANNEL_RX0,1,1);

  //update_timer_id=gdk_threads_add_timeout(1000/updates_per_second, update, NULL);
  update_timer_id=gdk_threads_add_timeout_full(G_PRIORITY_HIGH_IDLE,1000/updates_per_second, update, NULL, NULL);

  // save every 30 seconds
  save_timer_id=gdk_threads_add_timeout(30000, save_cb, NULL);


  if(protocol!=NEW_PROTOCOL) {
    setFrequency(getFrequency());
  }

#ifdef PSK
  if(mode==modePSK) {
    show_psk();
  } else {
    show_waterfall();
  }
#endif

  g_idle_add(vfo_update,(gpointer)NULL);

  return 0;
}
Exemplo n.º 7
0
// wait_gtk_events: Waits for all pending gtk events
// to be handled before continuing execution
// ---------------------------------------------- >>
void wait_gtk_events()
{
	while(gtk_events_pending())
		gtk_main_iteration();
}
void WebViewTest::quitMainLoopAfterProcessingPendingEvents()
{
    while (gtk_events_pending())
        gtk_main_iteration();
    quitMainLoop();
}
Exemplo n.º 9
0
int
create_nasa_mapfile (double lat, double lon, int test, char *fn)
{
	/*     lat,lon= koordinates */
	/* test= test if maps are present */
	/* fn = filename of the generated file */
	int fdout, uc = 0;
	int scale, e, xsize_e, xsize_w;
	int xstart, ystart, y, x_w, x_e;
	double mylon;
	GtkWidget *myprogress, *text, *vbox;
	char textbuf[40];
	char *basename;

	if (!havenasamaps)
		return -1;

	scale = 2614061;
	mylon = lon;

	g_strlcpy (fn, "nofile.sorry", 255);

	/* return if no map found */
	if (lon > 0)
	{
		xstart = (int) (21600.0 * (lon / 180.0));
		if (((xstart < 1280) || (xstart > 20320)) && (fdin_w < 0))
			return -1;
		if (fdin_e < 0)
			return -1;
	}
	else
	{
		lon = 180.0 + lon;
		xstart = (int) (21600.0 * (lon / 180.0));
		if (((xstart < 1280) || (xstart > 20320)) && (fdin_e < 0))
			return -1;
		if (fdin_w < 0)
			return -1;
	}

	if (!test)
	{
		fdout = open (outfilename, O_RDWR | O_TRUNC | O_CREAT | O_BINARY, 0644);
		if (fdout < 0)
		{
			fprintf (stderr,
				 _("Could not create output map file \"%s\"!\n"),
				 outfilename);
			return -1;
		}

		nasawindow = gtk_window_new (GTK_WINDOW_POPUP);
		vbox = gtk_vbox_new (FALSE, 6);
		gtk_container_add (GTK_CONTAINER (nasawindow), vbox);

		gtk_window_set_position (GTK_WINDOW (nasawindow),
					 GTK_WIN_POS_CENTER);

		/*   g_signal_connect (window, "destroy", */
		/*              G_CALLBACK (gtk_widget_destroyed), &window); */

		gtk_window_set_title (GTK_WINDOW (nasawindow),
				      _("Creating map..."));
		gtk_container_set_border_width (GTK_CONTAINER (nasawindow), 20);

		myprogress = gtk_progress_bar_new ();

		gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (myprogress), 0.0);
		gtk_box_pack_start (GTK_BOX (vbox), myprogress, TRUE, TRUE, 2);

		text = gtk_label_new (
		    _("Creating a temporary map from NASA satellite images"));

		gtk_box_pack_start (GTK_BOX (vbox), text, TRUE, TRUE, 2);

		/*       gtk_widget_show_all (nasawindow); */
		gtk_widget_show_all (nasawindow);

		if (debug)
		    fprintf (stdout,
			_("Converting map for latitude: %f and longitude: %f ...\n"),
				 lat, lon);

		/*       if (lon < 0.0) */
		/*  lon = 180.0 + lon; */
		g_strlcpy (fn, "top_NASA_IMAGE.ppm", 255);


		g_snprintf (mybuffer, sizeof (mybuffer),
			    "P6\n# CREATOR: GpsDrive\n1280 1024\n255\n");

		e = write (fdout, mybuffer, strlen (mybuffer));
		uc = e;
		lon = mylon;
		xstart = (int) (21600.0 * (lon / 180.0));

		ystart = 3 * 21600 * (int) (10800 - 10800.0 * (lat / 90.0));

		/*    fprintf (stdout, "xstart: %d, ystart: %d\n", xstart, ystart);  */
		xstart -= 640;
		ystart = ystart - 512 * 21600 * 3;

		x_w = x_e = -1;
		xsize_w = xsize_e = 1280;

		if (xstart < 0)
		{
			x_w = 21600 + xstart;
			x_e = 1280 - x_w;

			if (x_e < -20320)
				x_e = -1;
			else if (x_e < 0)
				x_e = 0;

			if (x_w < -20320)
				x_w = -1;
			else if (x_w < 0)
				x_w = 0;
			xsize_w = 21600 - x_w;
			xsize_e = 1280 - xsize_w;
		}
		else if (xstart > 20320)
		{
			x_w = (xstart + 1280) - 21600;
			x_e = 1280 - x_w;
			if (x_e < 20320)
				x_e = -1;
			if (x_e < 0)
				x_e = 0;
			xsize_w = x_w;
			xsize_e = 1280 - xsize_w;
		}
		else
		{
			if (mylon >= 0.0)
				x_e = xstart;
			else
				x_w = xstart;
		}
		if (xsize_w > 1280)
			xsize_w = 1280;
		if (xsize_e > 1280)
			xsize_e = 1280;
		x_w *= 3;
		x_e *= 3;

		for (y = 0; y < 1024; y++)
		{
			if ((y % 32) == 0)
			{
				gtk_progress_bar_set_fraction
					(GTK_PROGRESS_BAR (myprogress),
					 y / 1024.0);
				g_snprintf (textbuf, sizeof (textbuf), "%d%%",
					    (int) (100.0 * y / 1024));
				gtk_progress_bar_set_text (GTK_PROGRESS_BAR
							   (myprogress),
							   textbuf);
				while (gtk_events_pending ())
					gtk_main_iteration ();

			}

			if (x_w != -3)
			{
				e = lseek (fdin_w,
					   x_w + ystart + y * 21600 * 3,
					   SEEK_SET);
				e = read (fdin_w, mybuffer, xsize_w * 3);
				e = write (fdout, mybuffer, xsize_w * 3);
				uc += e;
			}
			if (x_e != -3)
			{
				e = lseek (fdin_e,
					   x_e + ystart + y * 21600 * 3,
					   SEEK_SET);
				e = read (fdin_e, mybuffer, xsize_e * 3);
				e = write (fdout, mybuffer, xsize_e * 3);
				uc += e;
			}
		}
		/*       fprintf (stderr, "wrote %d bytes (%.1f MB) to mapfile\n", uc, */
		/*         uc / (1024.0 * 1024.0)); */

		gtk_widget_destroy (GTK_WIDGET (nasawindow));
		close (fdout);

		basename = g_path_get_basename(outfilename);
		g_strlcpy (mybuffer, basename, sizeof (mybuffer));
		g_free(basename);

		fprintf (stdout,
		    _("\nYou can permanently add this map file with following "
			"line in your\n"
			"map_koord.txt (rename the file!):\n"));
		fprintf (stdout, "\n%s %f %f %d\n", mybuffer, lat, lon, scale);

	}			/* End of if !test */

	return scale;
}
Exemplo n.º 10
0
/*!
 * main loop. Accept contribution from clients and dispatch digest of
 * the frame to all clients
 */
void
serve_dispatch (global_option_type * global_option)
{

  global_status_type global_status;
  int client_index;

  /*
   * Initialize global_status fields
   */
  global_status.frame_number = 1;
  global_status.number_identified_players = 0;
  global_status.number_allocation_request = 0;
#if defined(GTK)
	gtk_stop_asked = 0;
#endif

  for (client_index = 0; client_index < MAX_NUMBER_PLAYER; client_index++)
    {
      global_status.player_status[client_index] = UNIDENTIFIED;
    }

  global_status.server_socket = SDLNet_UDP_Open (global_option->server_port);
  if (global_status.server_socket == NULL)
    {
      printf_screen ("Couldn't open UDP socket on port %d.\nCheck privileges and availability.\n",
		     global_option->server_port);
      return;
    }

  /* global_status.server_socket is ready to serve our needs :) */

  global_status.current_packet = SDLNet_AllocPacket (CLIENT_PACKET_SIZE);

  if (global_status.current_packet == NULL)
    {
      SDLNet_UDP_Close (global_status.server_socket);
      printf_screen ("Failed to allocate a buffer for receiving client packets (size: %d bytes) (Not enough memory ?)",
		     CLIENT_PACKET_SIZE);
      return;
    }

  global_status.digest_packet = SDLNet_AllocPacket (SERVER_PACKET_SIZE);

  if (global_status.digest_packet == NULL)
    {
      SDLNet_UDP_Close (global_status.server_socket);
      SDLNet_FreePacket (global_status.digest_packet);
      printf_screen ("Failed to allocate a buffer for sending packets (size: %d bytes) (Not enough memory ?)",
		     SERVER_PACKET_SIZE);
      return;
    }

  /* Allocate enough space for a single socket */
  global_status.server_socket_set = SDLNet_AllocSocketSet (1);

  if (global_status.server_socket_set == NULL)
    {
      SDLNet_UDP_Close (global_status.server_socket);
      SDLNet_FreePacket (global_status.current_packet);
      SDLNet_FreePacket (global_status.digest_packet);
      printf_screen ("Couldn't allocate a socket set (not enough memory ?).\n");
      return;
    }

  if (SDLNet_UDP_AddSocket (global_status.server_socket_set, global_status.server_socket) !=
      1)
    {
      SDLNet_UDP_Close (global_status.server_socket);
      SDLNet_FreePacket (global_status.current_packet);
      SDLNet_FreePacket (global_status.digest_packet);
      SDLNet_FreeSocketSet (global_status.server_socket_set);
      printf_screen ("Error when adding socket to socket set.\n");
      return;
    }

  /* Identification loop */

  /*
   * We're expecting identification packets until we've filled all slots, then
   * we can proceed to the real meat
   */

  for (;;)
    {

      int number_ready_socket;

#if defined(DEBUG)
      printf_screen ("Waiting for identification\n");
#endif

      
      if (read_incoming_server_packet (&global_status))
	{
	  identify_client (&global_status, global_option);
	  
	  if (count_remaining_slot (&global_status, global_option) == 0)
	    {
	      /* Perfect, we've finished the identification of all slots */
	      break;
	    }
	  
	  printf_screen("%d slots open.\n", count_remaining_slot (&global_status, global_option));
	  
	  /* Going back to the identification loop */
	  continue;
	  
	}

#if defined(GTK)

      gtk_iteration = GTK_SERVER_SOCKET_RATIO;

      do {
	number_ready_socket =
	  SDLNet_CheckSockets (global_status.server_socket_set, SERVER_SOCKET_TIMEOUT / GTK_SERVER_SOCKET_RATIO);
	  
	while (gtk_events_pending())
	{
	  if (gtk_main_iteration())
	  {
	  	gtk_stop_asked = 1;
	  }
	}
      } while ( (number_ready_socket == 0) && (--gtk_iteration != 0) && !gtk_stop_asked);
#else

      number_ready_socket =
	SDLNet_CheckSockets (global_status.server_socket_set, SERVER_SOCKET_TIMEOUT);      

#endif

	if (gtk_stop_asked)
	{
		break;
	}

      if (number_ready_socket == -1)
	{
	  printf_screen ("Error in socket waiting (disconnection ?).\n");
	  break;
	}

      if (number_ready_socket == 1)
	{

#if defined(DEBUG)
	  printf_screen ("Got a packet\n");
#endif

	  /* We're awaiting a packet in the server socket */
	  if (read_incoming_server_packet (&global_status))
	    {

	      /*
	       * If we haven't identified all clients yet, we're trying to use the current packet
	       * to improve our knowledge of the typography
	       */
	      identify_client (&global_status, global_option);
	      
	      if (count_remaining_slot (&global_status, global_option) == 0)
		{
		  /* Perfect, we've finished the identification of all slots */
		  break;
		}

	      printf_screen("%d slots open.\n", count_remaining_slot (&global_status, global_option));

	    }
    }

	
	}

	if (!gtk_stop_asked)
	{

  printf_screen ("Identification finished\n");

#if defined(DEBUG)
  for (client_index = 0; client_index < MAX_NUMBER_PLAYER; client_index++)
    {
      printf_screen ("Mapping[%d] = { { 0x%08X, %d }, %d }\n", client_index,
		     global_status.input_mapping[client_index].address.host,
		     global_status.input_mapping[client_index].address.port,
		     global_status.input_mapping[client_index].remote_input_device);
    }
#endif

  switch (global_option->type_server)
    {
    case LAN_PROTOCOL_TYPE:
      serve_clients_lan_protocol(&global_status, global_option);
      break;
    case INTERNET_PROTOCOL_TYPE:
      serve_clients_internet_protocol(&global_status, global_option);
      break;
    default:
      printf_screen("Internal error, unknown internal server type : %d\n", global_option->type_server);
      break;
    }
  } // gtk_stop_asked
      
  /*
   * Free resources
   */
  SDLNet_FreePacket (global_status.current_packet);
  SDLNet_FreePacket (global_status.digest_packet);
  SDLNet_FreeSocketSet (global_status.server_socket_set);
  SDLNet_UDP_Close (global_status.server_socket);
  global_status.server_socket = NULL;

}
Exemplo n.º 11
0
void Pass (void)
{
  /* The next 4 lines must be there. */
  while (gtk_events_pending ())
  {
    gtk_main_iteration ();
  }
  if (ichangestuff == 0)
  {
    Play ("click.mp3", 0);
  }
  if ((((ifilestuff == 0) && ((biscomputer == 0) || (wiscomputer == 0))
    && (iyesno == 0)) && (((((Modulo (imoves, 2) == 0) && (iiamblack == 1)) ||
    ((Modulo (imoves, 2) != 0) && (iiamblack == 0))) && (inet == 1)) ||
    (inet == 0))) && (imoving == 0))
  {
    imoving = 1;
    if (inet == 1)
    {
      SendData (1, "pass");
    }
    if (Modulo (imoves, 2) == 0)
    {
      JudgeBoard ('w');
    }
    else
    {
      JudgeBoard ('b');
    }
    pass[ihistory] = 1;
    iscorewhite = ScoreWhite ();
    iscoreblack = ScoreBlack ();
    if (Modulo (imoves, 2) != 0)
    {
      if ((iscorewhite > iscoreblack) || (pass[ihistory - 1] == 1))
      {
        if (iscorewhite > iscoreblack)
        {
          iduh = 1;
        }
        EndGame ();
      }
      else
      {
        if (wiscomputer == 1)
        {
          Computer ('w');
          JudgeBoard ('b');
        }
      }
    }
    else
    {
      if ((iscoreblack > iscorewhite) || (pass[ihistory - 1] == 1))
      {
        if (iscoreblack > iscorewhite)
        {
          iduh = 1;
        }
        EndGame ();
      }
      else
      {
        if (biscomputer == 1)
        {
          Computer ('b');
          JudgeBoard ('w');
        }
      }
    }
    imoving = 0;
  }
  else
  {
    if (inet == 1)
    {
      Message ("It is not your move.", 3, 0);
    }
  }
}
Exemplo n.º 12
0
bool pApplication::pendingEvents() {
  return gtk_events_pending();
}
Exemplo n.º 13
0
Arquivo: main.c Projeto: ajmas/NewSRT
int main(int argc, char *argv[])
{
    GtkWidget *window;
    GtkWidget *button_clear, *button_azel, *button_freq, *button_offset;
    GtkWidget *button_help;
    GdkColor color;
    int i, ii;
    int yr, da, hr, mn, sc;
    double secstart;
    char buf[64];
    GdkGeometry geometry;
    GdkWindowHints geo_mask;
//    GdkRectangle update_rect;
    sprintf(d1.catnam, "srt.cat");
    sprintf(d1.hlpnam, "srt.hlp");
    for (i = 0; i < argc - 1; i++) {
        sscanf(argv[i], "%63s", buf);
        if (strstr(buf, "-c") && strlen(buf) == 2)
            sscanf(argv[i + 1], "%63s", d1.catnam);
        if (strstr(buf, "-h") && strlen(buf) == 2)
            sscanf(argv[i + 1], "%63s", d1.hlpnam);
    }
//    d1.azelport = 0x3f8;        // com1 default for old SRT 
    d1.ver = 4;  // SRT software version
    d1.secs = readclock();
    d1.run = 1;
    d1.record = 0;
    d1.entry1 = d1.entry2 = d1.entry3 = d1.entry5 = d1.entry6 = d1.entry8 = d1.helpwindow = d1.vwindow = 0;
    d1.plot = 0;
    d1.start_time = 0.0;
    d1.start_sec = 0.0;
    d1.speed_up = 0;
    d1.ppos = 0;
    d1.printout = 1;
    d1.debug = 0;
    d1.freq = 1420.4;           // default
    d1.bw = 0;                  // set to 2.4 for TV dongle 10 MHz for ADC card in init
    d1.fbw = 0;                 // set in init or srt.cat
    d1.nblk = 5;                // number of blocks in vspectra
    d1.record_int_sec = 0;
    d1.freqcorr = 0;            // frequency correction for L.O. may be needed for TV dongle
    d1.freqchng = 0;
    d1.clearint = 0;
    d1.record_clearint = 0;
    d1.noclearint = 0;
    d1.nfreq = NSPEC;
    d1.plotsec = 1;
    d1.displ = 1;
    d1.noisecal = 0;
//    used for old SRT mount and controller
//    d1.ptoler = 1;
//    d1.countperstep = 10000;    // default large number for no stepping 
//    d1.elcounts_per_deg = (52.0 * 27.0 / 120.0); // default for H-180
//    d1.azcounts_per_deg = 8.0 * 32.0 * 60.0 / (360.0 * 9.0); // default for CASSIMOUNT
//    d1.rod = 1;                 // default to rod as on CASSIMOUNT
//    d1.rod1 = 14.25;            // rigid arm length
//    d1.rod2 = 16.5;             // distance from pushrod upper joint to el axis
//    d1.rod3 = 2.0;              // pushrod collar offset
//    d1.rod4 = 110.0;            // angle at horizon
//    d1.rod5 = 30.0;             // pushrod counts per inch
    d1.azelsim = d1.radiosim = d1.fftsim = 0;
    d1.mainten = 0;
    d1.stowatlim = 1;
    d1.rms = -1;                // display max not rms 
    d1.calcons = 1.0;
    d1.caldone = 0;
    d1.nrfi = 0;
    d1.rfisigma = 6;            // level for RFI reporting to screen
    d1.tload = 300.0;
    d1.tspill = 20.0;
    d1.beamw = 5.0;
    d1.comerr = 0;
    d1.limiterr = 0;
    d1.restfreq = 1420.406;     /* H-line restfreq */
    d1.delay = 0;
    d1.azoff = 0.0;
    d1.eloff = 0.0;
    d1.drift = 0;
    d1.tstart = 0;
    d1.tsys = 100.0;            // expected on cold sky
    d1.pwroff = 0.0;
    d1.tant = 100.0;
    d1.calpwr = 0;
    d1.yfac = 0;
    d1.calon = 0;
    d1.calmode = 0;
    d1.docal = 0;
    d1.tcal = 290;              // absorber or bushes
    d1.sourn = 0;
    d1.track = 0;
    d1.scan = 0;
    d1.bsw = 0;
    d1.nbsw = 1;
    d1.obsn = 0;
    d1.stopproc = 0;
    d1.fstatus = 0;
    d1.cmdfl = 0;
    d1.south = 1;
    d1.hgt = 0;
    d1.dongle = 0;              // set to zero initially - set to 1 in Init_Device if dongle
    d1.npoly = 25;              // number of terms in polynomial fit of bandpass
    pwrst = pwrprev = 0.0;
    soutrack[0] = 0;
    sprintf(d1.cmdfnam, "cmd.txt");
    sprintf(d1.datadir, "./");  // default to local directory

    if (!catfile())
        return 0;
    d1.foutstatus = 0;
// to get permission su root chown root srtn then chmod u+s srtn then exit 
    if (!d1.azelsim) {
        if (d1.printout)
            printf("initializing antenna controller\n");
        i = rot2(&d1.aznow, &d1.elnow, -1, buf); // initialize
        i = rot2(&d1.aznow, &d1.elnow, 1, buf); // read
        if (i < 0) {
            printf("Couldn't talk to antenna controller\n");
            return 0;
        }
    } else {
        if (d1.stowatlim) {
            d1.azprev = d1.azlim1;
            d1.elprev = d1.ellim1;
        } else {
            d1.azprev = d1.stowaz;
            d1.elprev = d1.stowel;
        }
    }
    setgid(getgid());
    setuid(getuid());
    if (d1.mainten == 0) {
        if (d1.stowatlim) {
            d1.azcmd = d1.azlim1;
            d1.elcmd = d1.ellim1;
        } else {
            d1.azcmd = d1.stowaz;
            d1.elcmd = d1.stowel;
        }
        d1.azcount = 0;
        d1.elcount = 0;
        d1.stow = 1;
    }
    if (d1.azlim1 > d1.azlim2) {
        d1.south = 0;           // dish pointing North for southern hemisphere
        if (d1.azlim2 < 360.0)
            d1.azlim2 += 360.0;
    }

    if (!d1.radiosim)
        Init_Device(0);

    if (d1.displ) {
        gtk_init(&argc, &argv);
        window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
        geometry.min_width = 500;
        geometry.min_height = 300;
        geo_mask = GDK_HINT_MIN_SIZE;
        gtk_window_set_geometry_hints(GTK_WINDOW(window), window, &geometry, geo_mask);
        //Table size determines number of buttons across the top
        table = gtk_table_new(30, NUMBUTTONS, TRUE);

        drawing_area = gtk_drawing_area_new();
        gtk_window_set_default_size(GTK_WINDOW(window), 800, 600);
        color.red = 0xffff;
        color.blue = 0xffff;
        color.green = 0xffff;
        gtk_widget_show(drawing_area);
        gtk_table_attach_defaults(GTK_TABLE(table), drawing_area, 0, NUMBUTTONS, 3, 30);

        g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(quit), NULL);

        gtk_container_add(GTK_CONTAINER(window), table);

        g_signal_connect(G_OBJECT(drawing_area), "expose_event", (GtkSignalFunc) expose_event, NULL);
        g_signal_connect(G_OBJECT(drawing_area), "configure_event", (GtkSignalFunc) configure_event, NULL);

        g_signal_connect(G_OBJECT(drawing_area), "button_press_event",
                         (GtkSignalFunc) button_press_event, NULL);

        gtk_widget_set_events(drawing_area, GDK_EXPOSURE_MASK
                              | GDK_LEAVE_NOTIFY_MASK
                              | GDK_BUTTON_PRESS_MASK
                              | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK);


        button_clear = gtk_button_new_with_label("clear");
        button_stow = gtk_button_new_with_label("stow");
        button_azel = gtk_button_new_with_label("azel");
        button_npoint = gtk_button_new_with_label("npoint");
        button_bsw = gtk_button_new_with_label("beamsw");
        button_freq = gtk_button_new_with_label("freq");
        button_offset = gtk_button_new_with_label("offset");
        button_record = gtk_button_new_with_label("record");
        button_cmdfl = gtk_button_new_with_label("cmdfl");
        button_cal = gtk_button_new_with_label("cal");
        button_help = gtk_button_new_with_label("help");
        button_exit = gtk_button_new_with_label("exit");

        g_signal_connect(G_OBJECT(button_clear), "clicked", G_CALLBACK(button_clear_clicked), NULL);
        g_signal_connect(G_OBJECT(button_stow), "clicked", G_CALLBACK(button_stow_clicked), NULL);
        g_signal_connect(G_OBJECT(button_azel), "clicked", G_CALLBACK(button_azel_clicked), NULL);
        g_signal_connect(G_OBJECT(button_npoint), "clicked", G_CALLBACK(button_npoint_clicked), NULL);
        g_signal_connect(G_OBJECT(button_bsw), "clicked", G_CALLBACK(button_bsw_clicked), NULL);
        g_signal_connect(G_OBJECT(button_freq), "clicked", G_CALLBACK(button_freq_clicked), NULL);
        g_signal_connect(G_OBJECT(button_offset), "clicked", G_CALLBACK(button_offset_clicked), NULL);
        g_signal_connect(G_OBJECT(button_record), "clicked", G_CALLBACK(button_record_clicked), NULL);
        g_signal_connect(G_OBJECT(button_cmdfl), "clicked", G_CALLBACK(button_cmdfl_clicked), NULL);
        g_signal_connect(G_OBJECT(button_cal), "clicked", G_CALLBACK(button_cal_clicked), NULL);
        g_signal_connect(G_OBJECT(button_help), "clicked", G_CALLBACK(button_help_clicked), NULL);
        g_signal_connect(G_OBJECT(button_exit), "clicked", G_CALLBACK(button_exit_clicked), NULL);

        // test setting up tooltips instead of the "enter"/"leave" used below
        tooltips = gtk_tooltips_new();
        gtk_tooltips_set_tip(tooltips, button_clear,
                             "click to clear integration and reset time plot to 1/4-scale", NULL);
        gtk_tooltips_set_tip(tooltips, button_stow, "click to stow antenna", NULL);
        gtk_tooltips_set_tip(tooltips, button_azel, "click to enter az el coordinates", NULL);
        gtk_tooltips_set_tip(tooltips, button_npoint, "click to start npoint scan", NULL);
        gtk_tooltips_set_tip(tooltips, button_bsw, "click to start beam switch", NULL);
        gtk_tooltips_set_tip(tooltips, button_freq, "click to enter new frequency in MHz [bandwidth] [nfreq]",
                             NULL);
        gtk_tooltips_set_tip(tooltips, button_offset, "click to enter offsets", NULL);
        if (!d1.cmdfl)
            gtk_tooltips_set_tip(tooltips, button_cmdfl, "click to start cmd file", NULL);
        else
            gtk_tooltips_set_tip(tooltips, button_cmdfl, "click to stop cmd file", NULL);

        gtk_tooltips_set_tip(tooltips, button_cal, "click to start calibration", NULL);
        gtk_tooltips_set_tip(tooltips, button_help, "click to open help window", NULL);
        record_tooltip();


        gtk_table_attach(GTK_TABLE(table), button_clear, 0, 1, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_stow, 1, 2, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_azel, 2, 3, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_npoint, 3, 4, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_bsw, 4, 5, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_freq, 5, 6, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_offset, 6, 7, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_record, 7, 8, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_cmdfl, 8, 9, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_cal, 9, 10, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_help, 10, 11, 0, 2, GTK_FILL, GTK_FILL, 0, 0);
        gtk_table_attach(GTK_TABLE(table), button_exit, 11, 12, 0, 2, GTK_FILL, GTK_FILL, 0, 0);



        gtk_widget_show(button_clear);
        gtk_widget_show(button_stow);
        gtk_widget_show(button_azel);
        gtk_widget_show(button_npoint);
        gtk_widget_show(button_bsw);
        gtk_widget_show(button_freq);
        gtk_widget_show(button_offset);
        gtk_widget_show(button_record);
        gtk_widget_show(button_cmdfl);
        gtk_widget_show(button_cal);
        gtk_widget_show(button_help);
        gtk_widget_show(button_exit);


        gtk_widget_show(table);
        gtk_widget_show(window);
        clearpaint();
    }
    ii = 0;
    if (d1.printout) {
        toyrday(d1.secs, &yr, &da, &hr, &mn, &sc);
        printf("%4d:%03d:%02d:%02d:%02d %3s ", yr, da, hr, mn, sc, d1.timsource);
    }
    zerospectra(0);
    for (i = 0; i < d1.nfreq; i++)
        bspec[i] = 1;
    secstart = d1.nsecstart = -1;
    d1.secs = readclock();
    while (d1.run) {
        zerospectra(1);
        if (d1.clearint) {
            if (d1.displ)
                cleararea();
            zerospectra(0);
            d1.clearint = 0;
        }
        if (d1.freqchng) {
            if (d1.dongle)
                Init_Device(1);
            if (d1.printout) {
                toyrday(d1.secs, &yr, &da, &hr, &mn, &sc);
                printf("%4d:%03d:%02d:%02d:%02d %3s ", yr, da, hr, mn, sc, d1.timsource);
            }
            if (!d1.radiosim) {
                sleep(1);
            }
            zerospectra(0);
            d1.freqchng = 0;
        }
        if (d1.docal) {
            if (d1.docal == 1) {
                sprintf(d1.recnote, "* calibration started\n");
                outfile(d1.recnote);
            }
            if (d1.bsw) {
                d1.bsw = 0;
                d1.azoff = 0.0;
            }
            if (d1.scan) {
                d1.scan = 0;
                d1.eloff = d1.azoff = 0.0;
            }
            if (d1.slew)
                d1.slew = 0;
            if (d1.docal == 1)
                cal(0);
            d1.docal = 2;
            cal(1);
            if (d1.integ >= NCAL) {
                cal(2);
                d1.docal = 0;
            }
        }

        if (d1.displ)
            cleararea();
        azel(d1.azcmd, d1.elcmd); // allow time after cal 
        if (d1.comerr == -1)
            return 0;
        if (!d1.slew) {
            pwr = 0.0;
        }
        if (!d1.slew)
            vspectra();
        d1.secs = readclock();
        aver();
        d1.integ2++;
        if (d1.record_int_sec && d1.integ2 >= d1.record_int_sec) {
            outfile(" ");
            if (d1.record_clearint && d1.track && !d1.bsw && !d1.scan)
                d1.clearint = 1;
            d1.integ2 = 0;
        }
        if (d1.displ) {
            if (!d1.plot)
                Repaint();
            while (gtk_events_pending() || d1.stopproc == 1) {
                gtk_main_iteration();
                d1.plot = 0;
            }
        }
        if (!d1.displ && d1.domap)
            scanplot();
    }
    return 0;
}
Exemplo n.º 14
0
void DisplayChangesGui::display(const vector <ustring>& differences)
{
  // Store position of scrollled window.
  GtkAdjustment * adjustment = gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (scrolledwindow));
  int scrollbar_position = gtk_adjustment_get_value (adjustment);

  // Variable for holding the number of modifications.
  unsigned int modification_count = 0;

  // Temporally removing the view from the buffer speeds loading text up a huge lot.
  g_object_ref(textbuffer);
  gtk_text_view_set_buffer(GTK_TEXT_VIEW(textview), NULL);
  
  // Clear buffer.
  clear();

  // Load text.
  for (unsigned int i = 0; i < differences.size(); i++) {
    GtkTextIter iter;
    GtkTextTag *tag = NULL;
    ustring line = differences[i];
    while (!line.empty()) {
      // Handle insertion or deletion flag for the next character.
      tag = NULL;
      ustring character = line.substr (0, 1);
      if (!strcmp (character.c_str(), INSERTION_FLAG)) {
        tag = heavy_weight_tag;
      }
      if (!strcmp (character.c_str(), DELETION_FLAG)) {
        tag = strike_through_tag;
      }
      if (tag) {
        line.erase (0, 1);
        // Another modification.
        modification_count++;
      }
      // Print one character with optional markup.
      character = line.substr (0, 1);
      gtk_text_buffer_get_end_iter(textbuffer, &iter);
      gtk_text_buffer_insert_with_tags(textbuffer, &iter, character.c_str(), -1, tag, NULL);
      line.erase(0, 1);
    }
    // End of line.
    gtk_text_buffer_get_end_iter(textbuffer, &iter);
    gtk_text_buffer_insert(textbuffer, &iter, "\n", 1);
  }
  
  // Reconnect the view to the buffer.
  gtk_text_view_set_buffer(GTK_TEXT_VIEW(textview), textbuffer);
  g_object_unref(textbuffer);
  
  // Show modification count.
  ustring message = _("Number of modifications: ");
  message.append (convert_to_string (modification_count));
  gtk_label_set_text (GTK_LABEL (label), message.c_str());
  
  // Restore scrollled window's position.
  // The window will then show the same block of text as before loading. This makes editing the text easier.
  while (gtk_events_pending())
    gtk_main_iteration();
  gtk_scrolled_window_get_vadjustment (GTK_SCROLLED_WINDOW (scrolledwindow));
  gtk_adjustment_set_value (adjustment, scrollbar_position);
}
Exemplo n.º 15
0
/* - updates sizes, names, etc */
static gint
canvas_node_update(node_id_t * node_id, canvas_node_t * canvas_node,
		     GList **delete_list)
{
  node_t *node;
  gdouble node_size;
  static clock_t start = 0;
  clock_t end;
  gdouble cpu_time_used;
  char *nametmp = NULL;

  node = nodes_catalog_find(node_id);

  /* Remove node if node is too old or if capture is stopped */
  if (!node || !display_node (node))
    {
      /* adds current to list of canvas nodes to delete */
      *delete_list = g_list_prepend( *delete_list, node_id);
      g_my_debug ("Queing canvas node to remove.");
      need_reposition = TRUE;
      return FALSE;
    }

  switch (pref.node_size_variable)
    {
    case INST_TOTAL:
      node_size = get_node_size (node->node_stats.stats.average);
      break;
    case INST_INBOUND:
      node_size = get_node_size (node->node_stats.stats_in.average);
      break;
    case INST_OUTBOUND:
      node_size = get_node_size (node->node_stats.stats_out.average);
      break;
    case INST_PACKETS:
      node_size = get_node_size (node->node_stats.pkt_list.length);
      break;
    case ACCU_TOTAL:
      node_size = get_node_size (node->node_stats.stats.accumulated);
      break;
    case ACCU_INBOUND:
      node_size = get_node_size (node->node_stats.stats_in.accumulated);
      break;
    case ACCU_OUTBOUND:
      node_size = get_node_size (node->node_stats.stats_out.accumulated);
      break;
    case ACCU_PACKETS:
      node_size = get_node_size (node->node_stats.stats.accu_packets);
      break;
    case ACCU_AVG_SIZE:
      node_size = get_node_size (node->node_stats.stats.avg_size);
      break;
    default:
      node_size = get_node_size (node->node_stats.stats_out.average);
      g_warning (_("Unknown value or node_size_variable"));
    }

  /* limit the maximum size to avoid overload */
  if (node_size > MAX_NODE_SIZE)
    node_size = MAX_NODE_SIZE; 

  if (node->main_prot[pref.stack_level])
    {
      canvas_node->color = protohash_color(node->main_prot[pref.stack_level]);

      gnome_canvas_item_set (canvas_node->node_item,
			     "x1", -node_size / 2,
			     "x2", node_size / 2,
			     "y1", -node_size / 2,
			     "y2", node_size / 2,
			     "fill_color_gdk", &(canvas_node->color), NULL);
    }
  else
    {
      guint32 black = 0x000000ff;
      gnome_canvas_item_set (canvas_node->node_item,
			     "x1", -node_size / 2,
			     "x2", node_size / 2,
			     "y1", -node_size / 2,
			     "y2", node_size / 2,
			     "fill_color_rgba", black, NULL);
    }

  /* We check the name of the node, and update the canvas node name
   * if it has changed (useful for non blocking dns resolving) */
  /*TODO why is it exactly that sometimes it is NULL? */
  if (canvas_node->text_item)
    {
      g_object_get (G_OBJECT (canvas_node->text_item), 
                    "text", &nametmp,
		    NULL);
      if (strcmp (nametmp, node->name->str))
	{
	  gnome_canvas_item_set (canvas_node->text_item,
				 "text", node->name->str, 
                                 NULL);
	  gnome_canvas_item_request_update (canvas_node->text_item);
	}
      g_free (nametmp);
    }

  /* Processor time check. If too much time has passed, update the GUI */
  end = clock ();
  cpu_time_used = ((gdouble) (end - start)) / CLOCKS_PER_SEC;
  if (cpu_time_used > 0.05)
    {
      /* Force redraw */
      while (gtk_events_pending ())
	gtk_main_iteration ();
      start = end;
    }
  return FALSE;			/* False means keep on calling the function */

}				/* update_canvas_nodes */
Exemplo n.º 16
0
int hs20_web_browser(const char *url)
{
	GtkWidget *scroll;
	SoupSession *s;
	WebKitWebView *view;
	WebKitWebSettings *settings;
	struct browser_context ctx;

	memset(&ctx, 0, sizeof(ctx));
	if (!gtk_init_check(NULL, NULL))
		return -1;

	s = webkit_get_default_session();
	g_object_set(G_OBJECT(s), "ssl-ca-file",
		     "/etc/ssl/certs/ca-certificates.crt", NULL);
	g_object_set(G_OBJECT(s), "ssl-strict", FALSE, NULL);

	ctx.win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	gtk_window_set_role(GTK_WINDOW(ctx.win), "Hotspot 2.0 client");
	gtk_window_set_default_size(GTK_WINDOW(ctx.win), 800, 600);

	scroll = gtk_scrolled_window_new(NULL, NULL);
	gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
				       GTK_POLICY_NEVER, GTK_POLICY_NEVER);

	g_signal_connect(G_OBJECT(ctx.win), "destroy",
			 G_CALLBACK(win_cb_destroy), &ctx);

	view = WEBKIT_WEB_VIEW(webkit_web_view_new());
	g_signal_connect(G_OBJECT(view), "notify::progress",
			 G_CALLBACK(view_cb_notify_progress), &ctx);
	g_signal_connect(G_OBJECT(view), "notify::load-status",
			 G_CALLBACK(view_cb_notify_load_status), &ctx);
	g_signal_connect(G_OBJECT(view), "resource-request-starting",
			 G_CALLBACK(view_cb_resource_request_starting), &ctx);
	g_signal_connect(G_OBJECT(view), "mime-type-policy-decision-requested",
			 G_CALLBACK(view_cb_mime_type_policy_decision), &ctx);
	g_signal_connect(G_OBJECT(view), "download-requested",
			 G_CALLBACK(view_cb_download_requested), &ctx);
	g_signal_connect(G_OBJECT(view), "hovering-over-link",
			 G_CALLBACK(view_cb_hovering_over_link), &ctx);
	g_signal_connect(G_OBJECT(view), "title-changed",
			 G_CALLBACK(view_cb_title_changed), &ctx);

	gtk_container_add(GTK_CONTAINER(scroll), GTK_WIDGET(view));
	gtk_container_add(GTK_CONTAINER(ctx.win), GTK_WIDGET(scroll));

	gtk_widget_grab_focus(GTK_WIDGET(view));
	gtk_widget_show_all(ctx.win);

	settings = webkit_web_view_get_settings(view);
	g_object_set(G_OBJECT(settings), "user-agent",
		     "Mozilla/5.0 (X11; U; Unix; en-US) "
		     "AppleWebKit/537.15 (KHTML, like Gecko) "
		     "hs20-client/1.0", NULL);
	g_object_set(G_OBJECT(settings), "auto-load-images", TRUE, NULL);

	webkit_web_view_load_uri(view, url);

	gtk_main();
	gtk_widget_destroy(ctx.win);
	while (gtk_events_pending())
		gtk_main_iteration();

	free(ctx.hover_link);
	free(ctx.title);
	return ctx.success;
}
Exemplo n.º 17
0
int MsdDevice::Configure(int port, const std::string& api, void *data)
{
	GtkWidget *ro_frame, *ro_label, *rs_hbox, *rs_label, *rs_cb, *vbox;

	GtkWidget *dlg = gtk_dialog_new_with_buttons (
		"Mass Storage Settings", GTK_WINDOW (data), GTK_DIALOG_MODAL,
		GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
		GTK_STOCK_OK, GTK_RESPONSE_OK,
		NULL);
	gtk_window_set_position (GTK_WINDOW (dlg), GTK_WIN_POS_CENTER);
	gtk_window_set_resizable (GTK_WINDOW (dlg), TRUE);
	GtkWidget *dlg_area_box = gtk_dialog_get_content_area (GTK_DIALOG (dlg));

	ro_frame = gtk_frame_new (NULL);
	gtk_box_pack_start (GTK_BOX (dlg_area_box), ro_frame, TRUE, FALSE, 5);

	ro_label = gtk_label_new ("Select USB image:");
	gtk_frame_set_label_widget (GTK_FRAME (ro_frame), ro_label);
	gtk_label_set_use_markup (GTK_LABEL (ro_label), TRUE);

	vbox = gtk_vbox_new (FALSE, 5);
	gtk_container_add (GTK_CONTAINER (ro_frame), vbox);

	rs_hbox = gtk_hbox_new (FALSE, 0);
	gtk_box_pack_start (GTK_BOX (vbox), rs_hbox, FALSE, TRUE, 0);

	GtkWidget *entry = gtk_entry_new ();
	gtk_entry_set_max_length (GTK_ENTRY (entry), MAX_PATH); //TODO max length

	std::string var;
	if (LoadSetting(port, APINAME, N_CONFIG_PATH, var))
		gtk_entry_set_text(GTK_ENTRY(entry), var.c_str());

	g_signal_connect (entry, "changed", G_CALLBACK (entryChanged), NULL);

	GtkWidget *button = gtk_button_new_with_label ("Browse");
	gtk_button_set_image(GTK_BUTTON (button), gtk_image_new_from_icon_name ("gtk-open", GTK_ICON_SIZE_BUTTON));
	g_signal_connect (button, "clicked", G_CALLBACK (fileChooser), entry);

	gtk_box_pack_start (GTK_BOX (rs_hbox), entry, TRUE, TRUE, 5);
	gtk_box_pack_start (GTK_BOX (rs_hbox), button, FALSE, FALSE, 5);

	gtk_widget_show_all (dlg);
	gint result = gtk_dialog_run (GTK_DIALOG (dlg));
	std::string path = gtk_entry_get_text(GTK_ENTRY(entry));
	gtk_widget_destroy (dlg);

	// Wait for all gtk events to be consumed ...
	while (gtk_events_pending ())
		gtk_main_iteration_do (FALSE);

	if (result == GTK_RESPONSE_OK)
	{
		if(SaveSetting(port, APINAME, N_CONFIG_PATH, path))
			return RESULT_OK;
		else
			return RESULT_FAILED;
	}

	return RESULT_CANCELED;
}
Exemplo n.º 18
0
int main(int argc, char **argv)
{
struct gtkwave_dual_ipc_t *dual_ctx;
char buf[257], buf2[257];
int shmid;
GtkWidget *main_vbox, *mainwindow, *vpan;
int i;
int split_point = -1;
#ifdef __MINGW32__
char mapName[65];
HANDLE hMapFile;
#endif

GtkWidget *xsocket[2] = { NULL, NULL };

WAVE_LOCALE_FIX

if(!gtk_init_check(&argc, &argv))
        {
        printf("Could not initialize GTK!  Is DISPLAY env var/xhost set?\n\n");
	exit(255);
        }

#ifdef __CYGWIN__
fprintf(stderr, "TWINWAVE| If the viewer crashes with a Bad system call error,\n");
fprintf(stderr, "TWINWAVE| make sure that Cygserver is enabled.\n");
#endif

for(i=0;i<argc;i++)
	{
	if(!strcmp(argv[i], "+"))
		{
		split_point = i;
		break;
		}

	if(!strcmp(argv[i], "++"))
		{
		split_point = i;
		use_embedded = 0;
		break;
		}
	}

if(split_point < 0)
	{
	printf("Usage:\n------\n%s arglist1 separator arglist2\n\n"
		"The '+' between argument lists splits and creates one window.\n"
		"The '++' between argument lists splits and creates two windows.\n"
		"\n", argv[0]);
	exit(255);
	}

mainwindow = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(mainwindow), "TwinWave Initializing");
#ifndef MAC_INTEGRATION
gtk_widget_set_usize(GTK_WIDGET(mainwindow), 820, 800);
#else
gtk_widget_set_usize(GTK_WIDGET(mainwindow), 400,32); /* quartz doesn't retarget into mainwindow */
#endif
gtk_widget_show(mainwindow);

gtk_signal_connect(GTK_OBJECT(mainwindow), "destroy", GTK_SIGNAL_FUNC(quit_callback), "WM destroy");


xsocket[0] = gtk_socket_new ();
xsocket[1] = gtk_socket_new ();
gtk_widget_show (xsocket[0]);
gtk_widget_show (xsocket[1]);

gtk_signal_connect(GTK_OBJECT(xsocket[0]), "plug-removed", GTK_SIGNAL_FUNC(plug_removed), NULL);

main_vbox = gtk_vbox_new(FALSE, 5);
gtk_container_border_width(GTK_CONTAINER(main_vbox), 1);
gtk_container_add(GTK_CONTAINER(mainwindow), main_vbox);
gtk_widget_show(main_vbox);

vpan = gtk_vpaned_new ();
gtk_widget_show (vpan);
gtk_box_pack_start (GTK_BOX (main_vbox), vpan, TRUE, TRUE, 1);

gtk_paned_pack1 (GTK_PANED (vpan), xsocket[0], TRUE, FALSE);

gtk_signal_connect(GTK_OBJECT(xsocket[1]), "plug-removed", GTK_SIGNAL_FUNC(plug_removed), NULL);

gtk_paned_pack2 (GTK_PANED (vpan), xsocket[1], TRUE, FALSE);

#ifdef __MINGW32__
shmid = getpid();
sprintf(mapName, "twinwave%d", shmid);
hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 2 * sizeof(struct gtkwave_dual_ipc_t), mapName);
if(hMapFile != NULL)
        {
        dual_ctx = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 2 * sizeof(struct gtkwave_dual_ipc_t));

        if(dual_ctx)
               	{
               	memset(dual_ctx, 0, 2 * sizeof(struct gtkwave_dual_ipc_t));
               	memcpy(&dual_ctx[0].matchword, DUAL_MATCHWORD, 4);
               	memcpy(&dual_ctx[1].matchword, DUAL_MATCHWORD, 4);

		/* child 0 */
				{
				int idx;
				int n_items = split_point + 5;
				int slen;
				char **arglist = calloc(n_items, sizeof(char *));
				char *mylist;
				STARTUPINFO si;
				PROCESS_INFORMATION pi;
				BOOL rc;

				memset(&si, 0, sizeof(STARTUPINFO));
				memset(&pi, 0, sizeof(PROCESS_INFORMATION));

				sprintf(buf, "0+%08X", shmid);
#ifdef MINGW_USE_XID
				sprintf(buf2, "%x", gtk_socket_get_id (GTK_SOCKET(xsocket[0])));
#else
				sprintf(buf2, "%x", 0);
#endif

				arglist[0] = "gtkwave.exe";
				arglist[1] = "-D";
				arglist[2] = buf;
				arglist[3] = "-X";
				arglist[4] = buf2;

				for(i=1;i<split_point;i++)
					{
					arglist[i+4] = argv[i];
					}

				arglist[i+4] = NULL;

				slen = 1;
				for(idx=0;idx<i+4;idx++)
					{
					slen += strlen(arglist[idx]);
					slen++;
					}
				mylist = calloc(1, slen);
				for(idx=0;idx<i+4;idx++)
					{
					strcat(mylist, arglist[idx]);
					strcat(mylist, " ");
					}

				si.cb = sizeof(si);

				rc = CreateProcess(
					arglist[0],
					mylist,
					NULL,
					NULL,
					FALSE,
					0,
					NULL,
					NULL,
					&si,
					&pi);
			
				if(!rc) 
					{
					fprintf(stderr, "Child 0 failed '%s' '%s'\n", arglist[0], mylist);
					exit(255);
					}

				free(mylist);
				free(arglist);
				}

		/* child 1 */
				{
				int idx;
				int n_items = argc - split_point + 5;
				int slen;
				char **arglist = calloc(n_items, sizeof(char *));
				char *mylist;
				STARTUPINFO si;
				PROCESS_INFORMATION pi;
				BOOL rc;

				memset(&si, 0, sizeof(STARTUPINFO));
				memset(&pi, 0, sizeof(PROCESS_INFORMATION));

				sprintf(buf, "1+%08X", shmid);
#ifdef MINGW_USE_XID
				sprintf(buf2, "%x", gtk_socket_get_id (GTK_SOCKET(xsocket[1])));
#else
				sprintf(buf2, "%x", 0);
#endif

				arglist[0] = "gtkwave.exe";
				arglist[1] = "-D";
				arglist[2] = buf;
				arglist[3] = "-X";
				arglist[4] = buf2;

				for(i=split_point+1;i<argc;i++)
					{
					arglist[i-split_point+4] = argv[i];
					}

				i-=split_point;
				arglist[i+4] = NULL;

				slen = 1;
				for(idx=0;idx<i+4;idx++)
					{
					slen += strlen(arglist[idx]);
					slen++;
					}
				mylist = calloc(1, slen);
				for(idx=0;idx<i+4;idx++)
					{
					strcat(mylist, arglist[idx]);
					strcat(mylist, " ");
					}

				si.cb = sizeof(si);

				rc = CreateProcess(
					arglist[0],
					mylist,
					NULL,
					NULL,
					FALSE,
					0,
					NULL,
					NULL,
					&si,
					&pi);
			
				if(!rc) 
					{
					fprintf(stderr, "Child 1 failed '%s' '%s'\n", arglist[0], mylist);
					exit(255);
					}

				free(mylist);
				free(arglist);
				}


		for(;;)
			{
			Sleep(1000 / 5);
			while (gtk_events_pending()) gtk_main_iteration();

			if((!dual_ctx[0].viewer_is_initialized)&&(dual_ctx[1].viewer_is_initialized))
				{
				gtk_window_set_title(GTK_WINDOW(mainwindow), "TwinWave Waiting on Viewer #1");
				}
			else
			if((dual_ctx[0].viewer_is_initialized)&&(!dual_ctx[1].viewer_is_initialized))
				{
				gtk_window_set_title(GTK_WINDOW(mainwindow), "TwinWave Waiting on Viewer #2");
				}
			else
			if((dual_ctx[0].viewer_is_initialized)&&(dual_ctx[1].viewer_is_initialized))
				{
				gtk_window_set_title(GTK_WINDOW(mainwindow), "TwinWave");
				break;
				}
			}
#ifdef MINGW_USE_XID
		gtk_main();
#endif
		}
	}
#else
shmid = shmget(0, 2 * sizeof(struct gtkwave_dual_ipc_t), IPC_CREAT | 0600 );
if(shmid >=0)
	{
        struct shmid_ds ds;
                                 
        dual_ctx = shmat(shmid, NULL, 0);
        if(dual_ctx)
               	{
               	memset(dual_ctx, 0, 2 * sizeof(struct gtkwave_dual_ipc_t));
               	memcpy(&dual_ctx[0].matchword, DUAL_MATCHWORD, 4);
               	memcpy(&dual_ctx[1].matchword, DUAL_MATCHWORD, 4);
	         
#ifdef __linux__
              	shmctl(shmid, IPC_RMID, &ds); /* mark for destroy */
#endif

		if(fork())
			{
			if(fork())
				{
				struct timeval tv;
			
				for(;;)
					{
			                tv.tv_sec = 0;
		                        tv.tv_usec = 1000000 / 5;
	        	                select(0, NULL, NULL, NULL, &tv);

					while (gtk_events_pending()) gtk_main_iteration();

					if((!dual_ctx[0].viewer_is_initialized)&&(dual_ctx[1].viewer_is_initialized))
						{
						gtk_window_set_title(GTK_WINDOW(mainwindow), "TwinWave Waiting on Viewer #1");
						}
					else
					if((dual_ctx[0].viewer_is_initialized)&&(!dual_ctx[1].viewer_is_initialized))
						{
						gtk_window_set_title(GTK_WINDOW(mainwindow), "TwinWave Waiting on Viewer #2");
						}
					else
					if((dual_ctx[0].viewer_is_initialized)&&(dual_ctx[1].viewer_is_initialized))
						{
						gtk_window_set_title(GTK_WINDOW(mainwindow), "TwinWave");
						break;
						}
					}

#ifndef __linux__
				while (gtk_events_pending()) gtk_main_iteration();
				sleep(2);
		               	shmctl(shmid, IPC_RMID, &ds); /* mark for destroy */
#endif
				if(use_embedded)
					{
					gtk_main();
					}
				}
				else
				{
				int n_items = split_point + 5;
				char **arglist = calloc(n_items, sizeof(char *));

				sprintf(buf, "0+%08X", shmid);
				if(use_embedded)
					{
					sprintf(buf2, "%x", gtk_socket_get_id (GTK_SOCKET(xsocket[0])));
					}
					else
					{
					sprintf(buf2, "%x", 0);
					}

				arglist[0] = "gtkwave";
				arglist[1] = "-D";
				arglist[2] = buf;
				arglist[3] = "-X";
				arglist[4] = buf2;

				for(i=1;i<split_point;i++)
					{
					arglist[i+4] = argv[i];
					}

				arglist[i+4] = NULL;

				execvp(arglist[0], arglist);

				fprintf(stderr, "Child failed\n");
				exit(255);
				}
			}
			else			
			{
			int n_items = argc - split_point + 5;
			char **arglist = calloc(n_items, sizeof(char *));

			sprintf(buf, "1+%08X", shmid);
			if(use_embedded)
				{
				sprintf(buf2, "%x", gtk_socket_get_id (GTK_SOCKET(xsocket[1])));
				}
				else
				{
				sprintf(buf2, "%x", 0);
				}

			arglist[0] = "gtkwave";
			arglist[1] = "-D";
			arglist[2] = buf;
			arglist[3] = "-X";
			arglist[4] = buf2;

			for(i=split_point+1;i<argc;i++)
				{
				arglist[i-split_point+4] = argv[i];
				}
			i-=split_point;
			arglist[i+4] = NULL;

			execvp(arglist[0], arglist);

			fprintf(stderr, "Child failed\n");
			exit(255);
			}
		}
	}
#endif

return(0);
}
Exemplo n.º 19
0
static void
gimp_thumb_box_create_thumbnails (GimpThumbBox *box,
                                  gboolean      force)
{
  Gimp           *gimp     = box->imagefile->gimp;
  GimpProgress   *progress = GIMP_PROGRESS (box);
  GimpFileDialog *dialog   = NULL;
  GtkWidget      *toplevel;
  GSList         *list;
  gint            n_uris;
  gint            i;

  if (gimp->config->thumbnail_size == GIMP_THUMBNAIL_SIZE_NONE)
    return;

  toplevel = gtk_widget_get_toplevel (GTK_WIDGET (box));

  if (GIMP_IS_FILE_DIALOG (toplevel))
    dialog = GIMP_FILE_DIALOG (toplevel);

  gimp_set_busy (gimp);

  if (dialog)
    gimp_file_dialog_set_sensitive (dialog, FALSE);
  else
    gtk_widget_set_sensitive (toplevel, FALSE);

  if (box->uris)
    {
      gtk_widget_hide (box->info);
      gtk_widget_show (box->progress);
    }

  n_uris = g_slist_length (box->uris);

  if (n_uris > 1)
    {
      gchar *str;

      gimp_progress_start (GIMP_PROGRESS (box), "", TRUE);

      progress = gimp_sub_progress_new (GIMP_PROGRESS (box));

      gimp_sub_progress_set_step (GIMP_SUB_PROGRESS (progress), 0, n_uris);

      for (list = box->uris->next, i = 1;
           list;
           list = g_slist_next (list), i++)
        {
          str = g_strdup_printf (_("Thumbnail %d of %d"), i, n_uris);
          gtk_progress_bar_set_text (GTK_PROGRESS_BAR (box->progress), str);
          g_free (str);

          gimp_progress_set_value (progress, 0.0);

          while (gtk_events_pending ())
            gtk_main_iteration ();

          gimp_thumb_box_create_thumbnail (box,
                                           list->data,
                                           gimp->config->thumbnail_size,
                                           force,
                                           progress);

          if (dialog && dialog->canceled)
            goto canceled;

          gimp_sub_progress_set_step (GIMP_SUB_PROGRESS (progress), i, n_uris);
        }

      str = g_strdup_printf (_("Thumbnail %d of %d"), n_uris, n_uris);
      gtk_progress_bar_set_text (GTK_PROGRESS_BAR (box->progress), str);
      g_free (str);

      gimp_progress_set_value (progress, 0.0);

      while (gtk_events_pending ())
        gtk_main_iteration ();
    }

  if (box->uris)
    {
      gimp_thumb_box_create_thumbnail (box,
                                       box->uris->data,
                                       gimp->config->thumbnail_size,
                                       force,
                                       progress);

      gimp_progress_set_value (progress, 1.0);
    }

 canceled:

  if (n_uris > 1)
    {
      g_object_unref (progress);

      gimp_progress_end (GIMP_PROGRESS (box));
      gtk_progress_bar_set_text (GTK_PROGRESS_BAR (box->progress), "");
    }

  if (box->uris)
    {
      gtk_widget_hide (box->progress);
      gtk_widget_show (box->info);
    }

  if (dialog)
    gimp_file_dialog_set_sensitive (dialog, TRUE);
  else
    gtk_widget_set_sensitive (toplevel, TRUE);

  gimp_unset_busy (gimp);
}
Exemplo n.º 20
0
void
splash_update(register_action_e action, const char *message, gpointer client_data)
{
    GtkWidget  *win;
    GtkWidget  *main_lb;
    GtkWidget  *prog_bar;
    GtkWidget  *percentage_lb;
    gfloat     percentage;
    gulong     ul_percentage;
    gchar      tmp[100];
    const char *action_msg;

    static gulong ul_sofar = 0;
    static gulong ul_count = 0;

    static register_action_e last_action = RA_NONE;

    static GTimeVal cur_tv;
    static GTimeVal next_tv = {0, 0};

    win = (GtkWidget *)client_data;

    if (win == NULL) return;

    g_get_current_time(&cur_tv);
    if (last_action == action && cur_tv.tv_sec <= next_tv.tv_sec && cur_tv.tv_usec <= next_tv.tv_usec && ul_sofar < ul_count - 1) {
      /* Only update every splash_register_freq milliseconds */
      ul_sofar++;
      return;
    }
    memcpy(&next_tv, &cur_tv, sizeof(next_tv));
    next_tv.tv_usec += info_update_freq * 1000;
    if (next_tv.tv_usec >= 1000000) {
        next_tv.tv_sec++;
        next_tv.tv_usec -= 1000000;
    }

    if(last_action != action) {
      /* the action has changed */
      switch(action) {
      case RA_DISSECTORS:
	action_msg = "Initializing dissectors ...";
	break;
      case RA_LISTENERS:
	action_msg = "Initializing tap listeners ...";
	break;
      case RA_REGISTER:
	action_msg = "Registering dissector ...";
	break;
      case RA_PLUGIN_REGISTER:
	action_msg = "Registering plugins ...";
	break;
      case RA_PYTHON_REGISTER:
	action_msg = "Registering Python dissectors ...";
	break;
      case RA_HANDOFF:
	action_msg = "Handing off dissector ...";
	break;
      case RA_PLUGIN_HANDOFF:
	action_msg = "Handing off plugins ...";
	break;
      case RA_PYTHON_HANDOFF:
	action_msg = "Handing off Python dissectors ...";
	break;
      case RA_LUA_PLUGINS:
	action_msg = "Loading Lua plugins ...";
	break;
      case RA_PREFERENCES:
	action_msg = "Loading module preferences ...";
	break;
      case RA_CONFIGURATION:
	action_msg = "Loading configuration files ...";
	break;
      default:
	action_msg = "(Unknown action)";;
	break;
      }
      splash_update_label(win, action_msg);
      last_action = action;
    }

    if(ul_count == 0) { /* get the count of dissectors */
      ul_count = register_count() + 6; /* additional 6 for:
					  dissectors, listeners,
					  registering plugins, handingoff plugins,
					  preferences and configuration */
#ifdef HAVE_LUA_5_1
      ul_count++;   /* additional one for lua plugins */
#endif
#ifdef HAVE_PYTHON
      ul_count += 2;   /* additional 2 for python register and handoff */
#endif
    }

    main_lb = g_object_get_data(G_OBJECT(win), "protocol_label");
    /* make_dissector_reg.py changed -
       so we need to strip off the leading elements to get back to the protocol */
    if(message) {
      if(!strncmp(message, "proto_register_", 15))
	message += 15;
      else if(!strncmp(message, "proto_reg_handoff_", 18))
	message += 18;
    }
    gtk_label_set_text(GTK_LABEL(main_lb), message ? message : "");

    ul_sofar++;

    g_assert (ul_sofar <= ul_count);

    percentage = (gfloat)ul_sofar/(gfloat)ul_count;
    ul_percentage = (gulong)(percentage * 100);

    /* update progress bar */
    prog_bar = g_object_get_data(G_OBJECT(win), "progress_bar");
    gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(prog_bar), percentage);

    percentage_lb = g_object_get_data(G_OBJECT(win), "percentage_label");
    g_snprintf(tmp, sizeof(tmp), "%lu%%", ul_percentage);
    gtk_label_set_text((GtkLabel*)percentage_lb, tmp);

    /* Process all pending GUI events before continuing, so that
       the splash screen window gets updated. */
    while (gtk_events_pending()) gtk_main_iteration();

}
Exemplo n.º 21
0
void _gtk_loop()
{
	while (gtk_events_pending()) {
		gtk_main_iteration();
	}
}
Exemplo n.º 22
0
/**
 * @brief Process all pending events.
 */
void gtkEvents(void)
{
    while (gtk_events_pending())
        gtk_main_iteration();
}
Exemplo n.º 23
0
int main(int argc, char *argv[])
{
	GtkWidget *window, *ok_but, *fix_but, *diag, *list, *scroll;
	GtkAdjustment *adj;
    product_component_t *component;
	product_option_t *option;
	product_file_t *file;
	int removed = 0, modified = 0;
	
    goto_installpath(argv[0]);

	/* Set the locale */
    init_locale();

	if ( argc < 2 ) {
		fprintf(stderr, _("Usage: %s product\n"), argv[0]);
		return 1;
	}

    gtk_init(&argc,&argv);

	argv0 = argv[0];

    /* Initialize Glade */
    glade_init();
    check_glade = glade_xml_new("check.glade", "check_dialog"); 

    /* Add all signal handlers defined in glade file */
    glade_xml_signal_autoconnect(check_glade);

    window = glade_xml_get_widget(check_glade, "check_dialog");
    gtk_widget_realize(window);
    while( gtk_events_pending() ) {
        gtk_main_iteration();
    }

	diag = glade_xml_get_widget(check_glade, "diagnostic_label");
	ok_but = glade_xml_get_widget(check_glade, "dismiss_button");
	fix_but = glade_xml_get_widget(check_glade, "rescue_button");
	list = glade_xml_get_widget(check_glade, "main_list");
	scroll = glade_xml_get_widget(check_glade, "scrolledwindow");

	product = loki_openproduct(argv[1]);
	if ( ! product ) {
	  message_dialog(_("Impossible to locate the product information.\nMaybe another user installed it?"),
					 _("Error"));
		return 1;
	}

	info = loki_getinfo_product(product);

	gtk_label_set_text(GTK_LABEL(diag), "");
	gtk_widget_set_sensitive(fix_but, FALSE);

	adj = GTK_ADJUSTMENT(gtk_adjustment_new(100.0, 1.0, 100.0, 1.0, 10.0, 10.0));
	gtk_scrolled_window_set_vadjustment(GTK_SCROLLED_WINDOW(scroll), adj);

	/* Iterate through the components */
	for ( component = loki_getfirst_component(product);
		  component;
		  component = loki_getnext_component(component) ) {

		add_message(list, _("---> Checking component '%s'..."), loki_getname_component(component));

		for ( option = loki_getfirst_option(component);
			  option;
			  option = loki_getnext_option(option) ) {
			
			add_message(list, _("-> Checking option '%s'..."), loki_getname_option(option));

			for ( file = loki_getfirst_file(option);
				  file;
				  file = loki_getnext_file(file) ) {

				gtk_main_iteration();
				switch ( loki_check_file(file) ) {
				case LOKI_REMOVED:
					add_message(list, _("%s was REMOVED"), loki_getpath_file(file));
					removed ++;
					add_corrupt_file(product, loki_getpath_file(file), loki_getname_option(option));
					break;
				case LOKI_CHANGED:
					add_message(list, _("%s was MODIFIED"), loki_getpath_file(file));
					modified ++;
					add_corrupt_file(product, loki_getpath_file(file), loki_getname_option(option));
					break;
				case LOKI_OK:
					add_message(list, _("%s is OK"), loki_getpath_file(file));
					break;
				}
			}
		}
	}

	if ( removed || modified ) {
		char status[200];

		snprintf(status, sizeof(status), _("Changes detected: %d files removed, %d files modified."), 
				 removed, modified);
		gtk_label_set_text(GTK_LABEL(diag), status);
		gtk_widget_set_sensitive(fix_but, TRUE);
	} else {
		gtk_label_set_text(GTK_LABEL(diag), _("No problems were found."));
	}

    /* Run the UI.. */
    gtk_main();

	return 0;
}
static const gchar*
tny_gnome_keyring_password_getter_get_password (TnyPasswordGetter *self, const gchar *aid, const gchar *prompt, gboolean *cancel)
{
	gchar *retval = NULL;
	GList *list;
	GnomeKeyringResult keyringret;
	gchar *keyring;

	gnome_keyring_get_default_keyring_sync (&keyring);

	keyringret = gnome_keyring_find_network_password_sync (aid, "Mail", 
		aid /* hostname */,
		"password", aid /* proto */, 
		"PLAIN", 0, &list);

	if ((keyringret != GNOME_KEYRING_RESULT_OK) || (list == NULL))
	{
		gboolean canc = FALSE;

		GnomePasswordDialog *dialog = GNOME_PASSWORD_DIALOG 
				(gnome_password_dialog_new
					(_("Enter password"), prompt,
					NULL, 
					NULL, TRUE));

		gnome_password_dialog_set_domain (dialog, "Mail");
		gnome_password_dialog_set_remember (dialog, 
			GNOME_PASSWORD_DIALOG_REMEMBER_FOREVER);

		gnome_password_dialog_set_readonly_username (dialog, TRUE);
		/* gnome_password_dialog_set_username (dialog, 
			tny_account_get_user (account)); */

		gnome_password_dialog_set_show_username (dialog, FALSE);
		gnome_password_dialog_set_show_remember (dialog, 
			gnome_keyring_is_available ());
		gnome_password_dialog_set_show_domain (dialog, FALSE);
		gnome_password_dialog_set_show_userpass_buttons (dialog, FALSE);

		canc = gnome_password_dialog_run_and_block (dialog);

		if (canc)
		{
			guint32 item_id;
			GnomePasswordDialogRemember r;

			retval = gnome_password_dialog_get_password (dialog);

			mlock (retval, strlen (retval));

			r = gnome_password_dialog_get_remember (dialog);

			if (r == GNOME_PASSWORD_DIALOG_REMEMBER_FOREVER)
			{
				gnome_keyring_set_network_password_sync (keyring,
					aid /* user */,
					"Mail", aid /* hostname */,
					"password", aid /* proto */, 
					"PLAIN", 0, retval, &item_id);
			}
		} else retval = NULL;

		*cancel = (!canc);

		/* this causes warnings, but should be done afaik */
		gtk_object_destroy (GTK_OBJECT (dialog));

		while (gtk_events_pending ())
			gtk_main_iteration ();

	} else {

		GnomeKeyringNetworkPasswordData *pwd_data;
		pwd_data = list->data;
		retval = g_strdup (pwd_data->password);

		*cancel = FALSE;

		gnome_keyring_network_password_list_free (list);
	}

	return retval;
}
Exemplo n.º 25
0
gint DeviceBoxOKEvent(GtkWidget *widget, GdkEvent event, gpointer data)
{
	char templine[256];
	u8 tempbuffer[2352];
	struct IsoFile *tofile;
	const char *tempdevice;
	s32 retval;
	cdvdTD cdvdtd;
	int stop;
	int compressmethod;
	int multi;
	int imagetype;
	int i;

	DeviceBoxUnfocus();

	tempdevice = gtk_entry_get_text(GTK_ENTRY(devicebox.device));
	strcpy(conf.devicename, tempdevice); // Temporarily put in new device name
	tempdevice = NULL;
	retval = DeviceOpen();
	if (retval != 0)
	{
		DeviceClose();
		MessageBoxShow("Could not open the device", 2);
		return(TRUE);
	} // ENDIF- Trouble opening device? Abort here.

	DeviceTrayStatus();
	retval = DiscInserted();
	if (retval != 0)
	{
		DeviceClose();
		MessageBoxShow("No disc in the device\r\nPlease put a disc in and try again.", 2);
		return(TRUE);
	} // ENDIF- Trouble opening device? Abort here.

	retval = DeviceGetTD(0, &cdvdtd); // Fish for Ending Sector
	if (retval < 0)
	{
		DeviceClose();
		MessageBoxShow("Could not retrieve disc sector size", 2);
		return(TRUE);
	} // ENDIF- Trouble getting disc sector count?

	compressmethod = gtk_combo_box_get_active(GTK_COMBO_BOX(devicebox.compress));
	if (compressmethod > 0)  compressmethod += 2;
	multi = 0;
	if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(devicebox.multi)) == TRUE)
		multi = 1;

	imagetype = 0;
	if ((disctype != CDVD_TYPE_PS2DVD) &&
	        (disctype != CDVD_TYPE_DVDV))  imagetype = 8;

	tofile = IsoFileOpenForWrite(gtk_entry_get_text(GTK_ENTRY(devicebox.file)),
	                             imagetype,
	                             multi,
	                             compressmethod);
	if (tofile == NULL)
	{
		DeviceClose();
		MessageBoxShow("Could not create the new ISO file", 2);
		return(TRUE);
	} // ENDIF- Trouble opening the ISO file?

	// Open Progress Bar
	sprintf(templine, "%s -> %s",
	        gtk_entry_get_text(GTK_ENTRY(devicebox.device)), tofile->name);
	ProgressBoxStart(templine, (off64_t) cdvdtd.lsn);

	tofile->cdvdtype = disctype;
	for (i = 0; i < 2048; i++)  tofile->toc[i] = tocbuffer[i];

	stop = 0;
	mainbox.stop = 0;
	progressbox.stop = 0;
	while ((stop == 0) && (tofile->sectorpos < cdvdtd.lsn))
	{
		if (imagetype == 0)
		{
			retval = DeviceReadTrack((u32) tofile->sectorpos,
			                         CDVD_MODE_2048,
			                         tempbuffer);
		}
		else
		{
			retval = DeviceReadTrack((u32) tofile->sectorpos,
			                         CDVD_MODE_2352,
			                         tempbuffer);
		} // ENDIF- Are we reading a DVD sector? (Or a CD sector?)
		if (retval < 0)
		{
			for (i = 0; i < 2352; i++)
			{
				tempbuffer[i] = 0;
			} // NEXT i- Zeroing the buffer
		} // ENDIF- Trouble reading next block?
		retval = IsoFileWrite(tofile, tempbuffer);
		if (retval < 0)
		{
			MessageBoxShow("Trouble writing new file", 3);
			stop = 1;
		} // ENDIF- Trouble writing out the next block?

		ProgressBoxTick(tofile->sectorpos);
		while (gtk_events_pending())  gtk_main_iteration();

		if (mainbox.stop != 0)  stop = 2;
		if (progressbox.stop != 0)  stop = 2;
	} // ENDWHILE- No reason found to stop...

	ProgressBoxStop();

	if (stop == 0)
	{
		if (tofile->multi == 1)  tofile->name[tofile->multipos] = '0'; // First file
		strcpy(templine, tofile->name);
	} // ENDIF- Did we succeed with the transfer?

	DeviceClose();
	if (stop == 0)
	{
		IsoSaveTOC(tofile);
		tofile = IsoFileClose(tofile);
		gtk_entry_set_text(GTK_ENTRY(mainbox.file), templine);
	}
	else
	{
		tofile = IsoFileCloseAndDelete(tofile);
	} // ENDIF- (Failed to complete writing file? Get rid of the garbage files.)

	if (stop != 1)  DeviceBoxRefocus();
	if (stop == 0)  DeviceBoxCancelEvent(widget, event, data);
	return(TRUE);
} // END DeviceBoxOKEvent()
void VectorTableToDialog (vector_table_options_D *dialog, BUS_LAYOUT *bus_layout, int *sim_type, VectorTable *pvt)
  {
  GList *llCols = NULL, *llItr = NULL ;
  int Nix ;
  GtkTreeModel *model = NULL ;
  GtkWidget *tbtn = NULL ;
  GtkTreeViewColumn *col = NULL ;

  if (NULL == dialog || NULL == sim_type || NULL == pvt) return ;

  g_object_set_data (G_OBJECT (dialog->dialog), "user_sim_type", sim_type) ;
  g_object_set_data (G_OBJECT (dialog->dialog), "user_pvt", pvt) ;
  g_object_set_data (G_OBJECT (dialog->dialog), "user_bus_layout", bus_layout) ;
  g_object_set_data (G_OBJECT (dialog->dialog), "idxVector", (gpointer)-1) ;

  if (0 == bus_layout->inputs->icUsed)
    (*sim_type) = EXHAUSTIVE_VERIFICATION ;

  gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (tbtn = (VECTOR_TABLE == (*sim_type) ? dialog->tbtnVT : dialog->tbtnExhaustive)), TRUE) ;

  g_object_set_data (G_OBJECT (dialog->crActive), "pvt", pvt) ;

  if (NULL != (model = GTK_TREE_MODEL (design_bus_layout_tree_store_new (bus_layout, ROW_TYPE_INPUT, 1, G_TYPE_BOOLEAN))))
    {
    gboolean bActive = FALSE ;
    GtkTreeIter itr, itrChild ;
    int row_type = -1, idx = -1 ;
    QCADCell *cell = NULL ;
    gboolean bBusActive = FALSE ;

    // First reflect the active_flag of current cell inputs
    if (gtk_tree_model_get_iter_first (model, &itr))
      while (TRUE)
        {
        gtk_tree_model_get (model, &itr, 
          BUS_LAYOUT_MODEL_COLUMN_TYPE, &row_type,
          BUS_LAYOUT_MODEL_COLUMN_CELL, &cell, -1) ;
        if (ROW_TYPE_CELL_INPUT == row_type && NULL != cell)
          if (-1 != (idx = VectorTable_find_input_idx (pvt, cell)))
            gtk_tree_store_set (GTK_TREE_STORE (model), &itr, 
              VECTOR_TABLE_MODEL_COLUMN_ACTIVE, exp_array_index_1d (pvt->inputs, VT_INPUT, idx).active_flag, -1) ;
        if (!gtk_tree_model_iter_next_dfs (model, &itr)) break ;
        }

    // For any given bus, if any of its cells are active, then the bus is active. Reflect this.
    if (gtk_tree_model_get_iter_first (model, &itr))
      while (TRUE)
        {
        bBusActive = FALSE ;
        if (gtk_tree_model_iter_children (model, &itrChild, &itr))
          {
          while (TRUE)
            {
            gtk_tree_model_get (model, &itrChild, VECTOR_TABLE_MODEL_COLUMN_ACTIVE, &bActive, -1) ;
            if ((bBusActive = bActive)) break ;
            if (!gtk_tree_model_iter_next (model, &itrChild)) break ;
            }
          gtk_tree_store_set (GTK_TREE_STORE (model), &itr, VECTOR_TABLE_MODEL_COLUMN_ACTIVE, bBusActive, -1) ;
          }
        if (!gtk_tree_model_iter_next (model, &itr)) break ;
        }

    llCols = gtk_tree_view_get_columns (GTK_TREE_VIEW (dialog->tv)) ;
    for (Nix = 0, llItr = llCols ; Nix < 2 && NULL != llItr ; Nix++, llItr = llItr->next) ;
    for (; llItr != NULL ; llItr = llItr->next)
      gtk_tree_view_remove_column (GTK_TREE_VIEW (dialog->tv), GTK_TREE_VIEW_COLUMN (llItr->data)) ;
    g_list_free (llCols) ;

    gtk_tree_view_set_model (GTK_TREE_VIEW (dialog->tv), model) ;
    }

  gtk_tree_view_expand_all (GTK_TREE_VIEW (dialog->tv)) ;

  for (Nix = 0 ; Nix < pvt->vectors->icUsed ; Nix++)
    {
    if (NULL == col)
      col = add_vector_to_dialog (dialog, pvt, Nix) ;
    else
      add_vector_to_dialog (dialog, pvt, Nix) ;
    // Give the dialog a chance to update itself
    if (0 == Nix % 10)
      while (gtk_events_pending ())
        gtk_main_iteration () ;
    }

  if (NULL != col)
    gtk_tree_view_column_clicked (col) ;

  if (!gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (tbtn)))
    vector_table_options_dialog_btnSimType_clicked (tbtn, dialog) ;

  vector_table_options_dialog_reflect_state (dialog) ;
  }
Exemplo n.º 27
0
static void do_test_webkit_web_view_adjustments(gboolean with_page_cache)
{
    char* effective_uri = g_strconcat(base_uri, "bigdiv.html", NULL);
    char* second_uri = g_strconcat(base_uri, "iframe.html", NULL);
    GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    GtkWidget* scrolled_window = gtk_scrolled_window_new(NULL, NULL);
    WebKitWebView* view = WEBKIT_WEB_VIEW(webkit_web_view_new());
    GtkAdjustment* adjustment;
    double lower;
    double upper;

    if (with_page_cache) {
        WebKitWebSettings* settings = webkit_web_view_get_settings(view);
        g_object_set(settings, "enable-page-cache", TRUE, NULL);
    }

    gtk_window_set_default_size(GTK_WINDOW(window), 400, 200);

    gtk_container_add(GTK_CONTAINER(window), scrolled_window);
    gtk_container_add(GTK_CONTAINER(scrolled_window), GTK_WIDGET(view));

    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled_window),
                                   GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);

    loop = g_main_loop_new(NULL, TRUE);

    g_object_connect(G_OBJECT(view),
                     "signal::notify::load-status", idle_quit_loop_cb, NULL,
                     NULL);

    /* Wait for window to show up */
    gtk_widget_show_all(window);
    g_signal_connect(window, "map-event",
                     G_CALLBACK(map_event_cb), loop);
    g_main_loop_run(loop);

    /* Load a page with a big div that will cause scrollbars to appear */
    webkit_web_view_load_uri(view, effective_uri);
    g_main_loop_run(loop);

    /* Adjustments update asynchronously, so we must wait a bit. */
    g_timeout_add(100, quit_after_short_delay_cb, loop);
    g_main_loop_run(loop);

    adjustment = gtk_scrolled_window_get_vadjustment(GTK_SCROLLED_WINDOW(scrolled_window));
    g_assert_cmpfloat(gtk_adjustment_get_value(adjustment), ==, 0.0);

    lower = gtk_adjustment_get_lower(adjustment);
    upper = gtk_adjustment_get_upper(adjustment);

    /* Scroll the view using JavaScript */
    webkit_web_view_execute_script(view, "window.scrollBy(0, 100)");

    /* Adjustments update asynchronously, so we must wait a bit. */
    g_timeout_add(100, quit_after_short_delay_cb, loop);
    g_main_loop_run(loop);

    /* Make sure the ScrolledWindow noticed the scroll */
    g_assert_cmpfloat(gtk_adjustment_get_value(adjustment), ==, 100.0);

    /* Load a second URI */
    webkit_web_view_load_uri(view, second_uri);
    g_main_loop_run(loop);

    /* The page loaded but the adjustments may not be updated yet. Wait a bit. */
    g_timeout_add(100, quit_after_short_delay_cb, loop);
    g_main_loop_run(loop);

    /* Make sure the scrollbar has been reset */
    g_assert_cmpfloat(gtk_adjustment_get_value(adjustment), ==, 0.0);

    /* Go back */
    webkit_web_view_go_back(view);

    /* When using page cache, go_back will return syncronously */
    if (!with_page_cache)
        g_main_loop_run(loop);

    /* Make sure GTK+ has time to process the changes in size, for the adjusments */
    while (gtk_events_pending())
        gtk_main_iteration();

    /* Make sure upper and lower bounds have been restored correctly */
    g_assert_cmpfloat(lower, ==, gtk_adjustment_get_lower(adjustment));
    g_assert_cmpfloat(upper, ==, gtk_adjustment_get_upper(adjustment));
    g_assert_cmpfloat(gtk_adjustment_get_value(adjustment), ==, 100.0);

    g_free(effective_uri);
    g_free(second_uri);

    gtk_widget_destroy(window);
}
Exemplo n.º 28
0
/* Refreshes the diagram. Called each refresh_period ms
 * 1. Checks for new protocols and displays them
 * 2. Updates nodes looks
 * 3. Updates links looks
 */
guint update_diagram(GtkWidget * canvas)
{
  static struct timeval last_refresh_time = { 0, 0 };
  double diffms;
  enum status_t status;

  /* if requested and enabled, dump to xml */
  if (appdata.request_dump && appdata.export_file_signal)
    {
      g_warning (_("SIGUSR1 received: exporting to %s"), appdata.export_file_signal);
      dump_xml(appdata.export_file_signal);
      appdata.request_dump = FALSE; 
    }
  
  status = get_capture_status();
  if (status == PAUSE)
    return FALSE;

  if (status == CAP_EOF)
    {
      gui_eof_capture ();
      return FALSE;
    }
  
  /* 
   * It could happen that during an intensive calculation, in order
   * to update the GUI and make the application responsive gtk_main_iteration
   * is called. But that could also trigger this very function's timeout.
   * If we let it run twice many problems could come up. Thus,
   * we are preventing it with the already_updating variable
   */

  if (already_updating)
    {
      g_my_debug ("update_diagram called while already updating");
      return FALSE;
    }

  already_updating = TRUE;
  gettimeofday (&appdata.now, NULL);

  /* update nodes */
  diagram_update_nodes(canvas);

  /* update links */
  diagram_update_links(canvas);

  /* Update protocol information */
  protocol_summary_update_all();

  /* update proto legend */
  update_legend();

  /* Now update info windows */
  update_info_windows ();

  /* With this we make sure that we don't overload the
   * CPU with redraws */

  if ((last_refresh_time.tv_sec == 0) && (last_refresh_time.tv_usec == 0))
    last_refresh_time = appdata.now;

  /* Force redraw */
  while (gtk_events_pending ())
    gtk_main_iteration ();

  gettimeofday (&appdata.now, NULL);
  diffms = substract_times_ms(&appdata.now, &last_refresh_time);
  last_refresh_time = appdata.now;

  already_updating = FALSE;

  if (!is_idle)
    {
      if (diffms > pref.refresh_period * 1.2)
        return FALSE;		/* Removes the timeout */
    }
  else
    {
      if (diffms < pref.refresh_period)
        return FALSE;		/* removes the idle */
    }

  if (stop_requested)
    gui_stop_capture();
  
  return TRUE;			/* Keep on calling this function */
}				/* update_diagram */
Exemplo n.º 29
0
void ZLGtkApplicationWindow::processAllEvents() {
	while (gtk_events_pending()) {
		gtk_main_iteration();
	}
}
Exemplo n.º 30
0
int main(int argc, char *argv[])
{
	setlocale (LC_ALL, "");
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
	textdomain (GETTEXT_PACKAGE);

	gboolean explicit_username = FALSE;
	gboolean explicit_message = FALSE;
	int error = 0;
	int m = 0, i = 1;
	guint counter = 0;
	gchar *command = NULL;
	gchar *command_run = NULL;
	gchar *username = NULL;
	gchar *password = NULL;

	uid_t whoami;
	struct passwd *pw;

	char err_msg[256];

	gchar *message = NULL;

	char **cmd_argv = NULL;
	GError *cmd_error = NULL;

	GtkWidget *dialog;
	GtkSizeGroup *sizegroup;
	GtkWidget *hbox;
	GtkWidget *image;
	GtkWidget *align;
	GtkWidget *label;
	GtkWidget *user;
	GtkWidget *pass;

	gtk_init(&argc, &argv);

	/* Parse arguments */
	while (i < argc) {
		if (argv[i][0] != '-')
			break;
		if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h"))
			say_help(argv[0]);
		if (!strcmp(argv[i], "--version") || !strcmp(argv[i], "-v"))
			say_about();
		if (!strcmp(argv[i], "--user") || !strcmp(argv[i], "-u")) {
			if ((username = argv[i + 1]) == NULL)
				Werror(ERR_MISSING_USER_AND_COMMAND, NULL, 1, 1);
			explicit_username = TRUE;
			i += 1;
		}
		if (!strcmp(argv[i], "--message") || !strcmp(argv[i], "-m")) {
			if ((message = argv[i + 1]) == NULL)
				Werror(ERR_MISSING_MESSAGE_AND_COMMAND, NULL, 1, 1);
			explicit_message = TRUE;
			i += 1;
		}
		i += 1;
	}

	if (argv[i] == NULL)
		Werror(ERR_MISSING_COMMAND, NULL, 1, 1);

	/* handle arguments and spaces in the subcommand correctly */
	if (! g_shell_parse_argv(argv[i], NULL, &cmd_argv, &cmd_error))
		/* Something bad has happened */
		Werror(ERR_INVALID_COMMAND, cmd_error->message, 1, 1);

	/* Get the full path command */
	command = get_real_name(cmd_argv[0]);
	if (command == NULL)
		Werror(ERR_INVALID_COMMAND, cmd_argv[0], 1, 1);

	/* Sanity check */
	whoami = getuid();
	if ((pw = getpwuid(whoami)) == NULL)
		exit(2 + 0 * fprintf(stderr, "Who you think you are? Houdini?\n"));

	if (!explicit_username)
		username = g_strdup("root");

	if (username && !strcmp(pw->pw_name, username)) {
		/* username was me so let's just run it and get the hell out */
		if (execvp(command, &(cmd_argv[0])) == -1) {
			Werror(ERR_PERMISSION_DENIED, NULL, 1, 1);
			exit(1);
		}
		/* We should never get here, but just in case */
		exit(0);
	}

	if (explicit_username && !explicit_message)
		message = g_strdup_printf(gettext("Please enter the\npassword for %s:"), username);
	else if (!explicit_message)
		message = g_strdup(gettext("Please enter the desired\nusername and password:"******"ktsuss");
	gtk_container_set_border_width(GTK_CONTAINER(dialog), 5);
	gtk_container_set_border_width(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), 5);
	gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog)->vbox), 5);
	hbox = gtk_hbox_new(FALSE, 6);
#if GTK_CHECK_VERSION(2, 10, 0)
	image = gtk_image_new_from_stock(GTK_STOCK_DIALOG_AUTHENTICATION, GTK_ICON_SIZE_DIALOG);
#else
	image = gtk_image_new_from_icon_name("ktsuss", GTK_ICON_SIZE_DIALOG);
#endif
	gtk_box_pack_start(GTK_BOX(hbox), image, FALSE, FALSE, 0);
	label = gtk_label_new(message);
	gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0);
	gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), hbox);
	sizegroup = gtk_size_group_new(GTK_SIZE_GROUP_HORIZONTAL);
	if (!explicit_username) {
		hbox = gtk_hbox_new(FALSE, 6);
		label = gtk_label_new(gettext("Username"));
		align = gtk_alignment_new(0, 0.5, 0, 0);
		gtk_container_add(GTK_CONTAINER(align), label);
		gtk_size_group_add_widget(sizegroup, align);
		gtk_box_pack_start(GTK_BOX(hbox), align, FALSE, FALSE, 0);
		user = gtk_entry_new();
		gtk_entry_set_text(GTK_ENTRY(user), username ? username : "******");
		gtk_box_pack_start(GTK_BOX(hbox), user, FALSE, FALSE, 0);
		gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), hbox);
	}
	hbox = gtk_hbox_new(FALSE, 6);
	label = gtk_label_new(gettext("Password"));
	align = gtk_alignment_new(0, 0.5, 0, 0);
	gtk_container_add(GTK_CONTAINER(align), label);
	gtk_size_group_add_widget(sizegroup, align);
	gtk_box_pack_start(GTK_BOX(hbox), align, FALSE, FALSE, 0);
	pass = gtk_entry_new_with_max_length(32);
	gtk_entry_set_visibility(GTK_ENTRY(pass), FALSE);
	gtk_box_pack_start(GTK_BOX(hbox), pass, FALSE, FALSE, 0);
	gtk_entry_set_activates_default(GTK_ENTRY(pass), TRUE);
	gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), hbox);
	gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_OK);
	gtk_widget_grab_focus(pass);
	gtk_widget_show_all(GTK_DIALOG(dialog)->vbox);

	/* Show the dialog up to 3 times */
	while (counter < 3) {
		if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) {
			if (!explicit_username)
				username = strdup(gtk_entry_get_text(GTK_ENTRY(user)));
			password = strdup(gtk_entry_get_text(GTK_ENTRY(pass)));

#ifdef SUDOPATH
			if ((error = check_password_sudo(username, password)) == ERR_SUCCESS) {
#else
			if ((error = check_password_su(username, password)) == ERR_SUCCESS) {
#endif
				gtk_widget_destroy(dialog);
				while (gtk_events_pending())
					gtk_main_iteration();
				dialog = NULL;
				/* using argv instead of cmd_argv is fine, because 'su' is going
				 * to implement its only parsing nevertheless */
				command_run = g_strjoinv(" ", &argv[i]);
#ifdef SUDOPATH
				run_sudo(username, password, command_run);
#else
				run_su(username, password, command_run);
#endif
				g_free(command_run);

				counter = 3;
			}
			if (!explicit_username) {
				free(username);
				username = NULL;
			}
			memset(password, '\0', strlen(password));
			free(password);
			if (error != ERR_SUCCESS) {
				snprintf(err_msg, sizeof(err_msg), gettext("Could not run '%s'"), command);
				Werror(error, err_msg, 0, 0);
				counter++;
			}
		}
		else
			break;
		if (counter < 3)
			gtk_widget_grab_focus(pass);
	}

	/* Clean up process */
	if (dialog)
		gtk_widget_destroy(dialog);
	if ((explicit_username && !explicit_message) || !explicit_message)
        free(message);
	if (!explicit_username && username)
		g_free(username);
	
	g_strfreev(cmd_argv);
	if (cmd_error)
		g_error_free(cmd_error);

	return 0;
}