Beispiel #1
0
/*
 * filter associated with fileType
 */
static void
af_fs_filter_change(GtkFileChooser *chooser,  FsDialogData *fsdata )
{
   GtkFileFilter *filter;
   char *name;

   /* file filter for active file type (*.ihx) */
   if ( fsdata->filter){
       gtk_file_chooser_remove_filter(chooser, fsdata->filter);
   }

   filter = gtk_file_filter_new ();
   fsdata->filter = filter;
   name = app_strdup_printf(_("%s formats"), fsdata->format );
   gtk_file_filter_set_name (filter, name);
   app_free(name);
   char **listpat = fileformat_get_patterns(fileformat_get_index(fsdata->format));
   while(*listpat){
      name = app_strdup_printf("*.%s", *listpat );
      gtk_file_filter_add_pattern (filter, name);
      app_free(name);
      listpat++;
   }
   gtk_file_chooser_add_filter (chooser, filter);
}
Beispiel #2
0
static void
as_card_changed_cb (GtkWidget *widget, gpointer pdata)
{
   GawSndData *snd = (GawSndData *) pdata; 
   UserPrefs *up = snd->ud->up;
   SoundParams *sparams = snd->sparams;
   char name[32] ;
   char *p;
   char *text;

   text = gtk_combo_box_text_get_active_text (GTK_COMBO_BOX_TEXT (widget));
   app_free(sparams->indexstr);
   app_free(sparams->device_name);
   if ( ( p = strchr( text, ' ' )) ){
      *p = 0;
   }
   sparams->indexstr = app_strdup(text);
   if ( *text == '-' ){
      sparams->device_name = app_strdup("default");
   } else {
      sprintf(name, "hw:%s", text );
      sparams->device_name = app_strdup(name);
   }
   msg_dbg(_("card changed: idex = %s device = %s"),  sparams->indexstr, sparams->device_name );
   
   app_free(up->cardidstr);
   up->cardidstr = app_strdup(sparams->indexstr);
   as_setup_rate_combo( snd );
   as_setup_format_combo(snd);
}
static App *
app_new (void)
{
  App *app;

  app = g_slice_new0 (App);
  if (!app)
    return NULL;

  g_mutex_init (&app->mutex);
  g_cond_init (&app->event_cond);
  g_cond_init (&app->decoder_ready);
  g_cond_init (&app->render_ready);

  app_set_framerate (app, 60, 1);
  app->window_width = 640;
  app->window_height = 480;

  app->decoder_queue = g_async_queue_new_full (
      (GDestroyNotify) render_frame_free);
  if (!app->decoder_queue)
    goto error;

  app->timer = g_timer_new ();
  if (!app->timer)
    goto error;
  return app;

error:
  app_free (app);
  return NULL;
}
Beispiel #4
0
static void
af_fs_filter_add (GtkFileChooser *chooser, FsDialogData *fsdata )
{
   GtkFileFilter *filter;
   char *name;
   int i;

   /* file filter for all data type files (*.dat ...) */
   filter = gtk_file_filter_new ();
   gtk_file_filter_set_name (filter, _("All Data formats"));
   i = -1 ; 
   do {
      name = fileformat_get_next_name( &i, fsdata->option);
      if ( ! name ){
         continue;
      }
      char **listpat = fileformat_get_patterns(i);
      while(listpat && *listpat){
         name = app_strdup_printf("*.%s", *listpat );
         gtk_file_filter_add_pattern (filter, name);
         app_free(name);
         listpat++;
      }
   } while ( i != -1 );
   gtk_file_chooser_add_filter (chooser, filter);
   fsdata->alldatafilter = filter;
   
   /* file filter that match any file */
   filter = gtk_file_filter_new ();
   gtk_file_filter_set_name (filter, _("All files"));
   gtk_file_filter_add_pattern (filter, "*");
   gtk_file_chooser_add_filter (chooser, filter);
}
Beispiel #5
0
Datei: main.c Projekt: ceyusa/ytv
gint
main (gint argc, gchar** argv)
{
        App* app;
        
        g_thread_init (NULL);
        gtk_init (&argc, &argv);

        app = app_new ();

        if (!parse_options (app, &argc, &argv))
        {
                goto beach;
        }
        
        app_create_ui (app);
        /* g_timeout_add_seconds (5, (GSourceFunc) app_fetch_feed, app); */
        g_idle_add ((GSourceFunc) app_fetch_feed, (gpointer) app);
        
        gtk_main ();

beach:
        app_free (app);
        
        return 0;
}
Beispiel #6
0
void as_sound_destroy(void *snd)
{

   if (snd == NULL) {
      return;
   }
#ifdef HAVE_LIBASOUND
   GawSndData *this = (GawSndData *) snd;
   
   app_free(this->sparams->indexstr);
   app_free(this->sparams->device_name);
   app_free(this->sparams);

   app_class_destroy( snd );
#endif /* HAVE_LIBASOUND */
}
Beispiel #7
0
void
af_export_displayed_gaction (GSimpleAction *action, GVariant *param, gpointer user_data )
{
   UserData *ud = (UserData *) user_data;
   WaveTable *wt = ap_wavetable_new_from_displayed( ud );
   
//   msg_dbg("called");
   if ( ! wt ) {
      msg_info(_("\n\nNo waves displayed"));
      return;
   }
   FsDialogData *fsdata = g_new0 (FsDialogData, 1);

   fsdata->option = FILE_WRITE_OP;
   fsdata->ud = ud;
   if ( ud->listFiles ){
      fsdata->filename = (char *) g_slist_nth_data ( ud->listFiles, 0 )  ;
   }
   
   if (af_create_open_file_selection(fsdata) == GTK_RESPONSE_ACCEPT) {
      wt->bits = ud->bits;
      wt->rate = ud->rate;

      fileformat_file_write( wt, (char *) fsdata->files->data, fsdata->format, ud->printFmt );
   }
   wavetable_destroy(wt);
   app_free(fsdata->format);
   g_free(fsdata);
}
Beispiel #8
0
int main() {
	int ret = 0;

	picframe_init();


	arrow_setup();
//	clock_setup();

	weather_today_setup();
	weather_tomorrow_setup();
	weather_dayAfterTomorrow_setup();
	weather_dayAfterTomorrowPlus1_setup();

	curr_window = picframe_get_window(START_WINDOW);

	picframe_set_backlight(500);

	while (1) {

		picframe_clear_screen();

		switch (curr_window_idx) {
		/*
		case 1:
			ret = clock_loop();
			break;
		*/
		case 1:
			ret = weather_today_loop();
			break;
		case 2:
			ret = weather_tomorrow_loop();
			break;
		case 3:
			ret = weather_dayAfterTomorrow_loop();
			break;
		case 4:
			ret = weather_dayAfterTomorrowPlus1_loop();
			break;
		default:
			break;
		}
		if (ret == 1)
			goto cleanup;

	}

	// Try a friendly shotdown to prevent memory leaks...
	cleanup: picframe_cleanup();

	app_free();

	return 0;
}
Beispiel #9
0
void wcs_free(wcs_t wcs)
{
    struct wcamsrv *ws = wcs;
    wcs_srv_free(ws);
#if defined(VID_FUNC)
    vid_free(ws->vid);
#endif
    pool_free(ws->pool);
    app_free(ws->app);
    cfg_free(ws->cfg);
    free(ws);
}
Beispiel #10
0
static void
run_tui(void)
{
    struct app *app = app_alloc();
    
    struct result result = app_run(app);
    if (!result_is_success(result)) {
        result_print_error(result);
    }
    
    app_free(app);
}
Beispiel #11
0
/********************************************************************
* @作者 :周炳权
* @功能 :数据上传任务
* @输入 :NONE
* @输出 :NONE
********************************************************************/
static void _upload_task(void*arg)
{
	uint8_t m_flag = 0;
	Esum_save_arg_t *m_pdata 
		= app_malloc(sizeof(Esum_save_arg_t));
	while(1)
	{
		msleep( TYPE_DELAY );
		if ( os_task_delete_req( SELF_PRO ) == OS_TASK_DEL_REQ )/*判断是否有删除请求*/
		{
			app_free(m_pdata);
			os_task_delete( SELF_PRO );   			
		}
		if ( g_upload_start == 1 )
		{
			if ( (g_upload_cur_num == g_upload_all_size) && (g_upload_all_size != 0))
			{
				app_upload_tips("全部数据已上传完成...");
				m_flag = 0;
				g_upload_start = 0;
				continue;
			}
			if ( m_flag == 0 )
			{
				m_flag = 1;
				g_upload_all_size = data_allsize_obtain();
				if ( g_upload_all_size == 0 )
				{
					app_upload_tips("无数据可以上传...");
					m_flag = 0;
					continue;
				}
				app_upload_allsize(g_upload_all_size);
				app_upload_cursize(g_upload_cur_num);
				app_upload_tips("正在上传数据...");
			}
			cur_one_record_obtain(m_pdata,g_upload_cur_num);
			app_upload_send(m_pdata,sizeof(Esum_save_arg_t));
			g_upload_cur_num++;
			app_upload_cursize(g_upload_cur_num);
			msleep(10);
			if ( g_upload_cur_num == g_upload_all_size )
			{
				app_upload_tips("全部数据已上传完成...");
				m_flag = 0;
				g_upload_start = 0;
			}
		}
	}
}
Beispiel #12
0
/*
 * The purpose of this function is to let the user to select 
 *   the input where he plugged his signals.
 * Now if user select "default", as device, we have to select the input
 *   on the mixer of the card used by  "default".
 * What is the card used by device  "default" ?
 */ 
static void
as_setup_input_combo (GtkWidget *combo, SoundParams *sparams)
{
   snd_mixer_t *handle;
   int i ;
   snd_mixer_selem_id_t *sid;
   snd_mixer_elem_t *elem;
   snd_mixer_selem_id_alloca(&sid);
   char *devname;
   char name[32];

   devname = sparams->device_name;
   if ( *sparams->indexstr == '-' ) {
      sprintf(name, "hw:%d", sparams->firstcard);
      devname = name;
   }
   handle = sound_open_mixer(devname);
   if ( handle == NULL ){
      return ;
   }   

   for (elem = snd_mixer_first_elem(handle); elem; elem = snd_mixer_elem_next(elem)) {
      snd_mixer_selem_get_id(elem, sid);
      if (! snd_mixer_selem_is_active(elem)) {
	 continue;
      }
      const char *control_name = snd_mixer_selem_id_get_name(sid);
//      printf("Simple mixer control '%s',%i\n", control_name,  snd_mixer_selem_id_get_index(sid));
      if (snd_mixer_selem_is_enum_capture(elem)) {
	 int items;
	 char itemname[40];
	 app_free(sparams->control_name);
	 sparams->control_name = app_strdup(control_name);
	 items = snd_mixer_selem_get_enum_items(elem);
//	 printf("  Items:");
	 for (i = 0; i < items; i++) {
	    snd_mixer_selem_get_enum_item_name(elem, i, sizeof(itemname) - 1, itemname);
//	    printf(" '%s'", itemname);
            gtk_combo_box_text_append_text (GTK_COMBO_BOX_TEXT (combo), itemname );
	    if ( i == sparams->input ) {
	       gtk_combo_box_set_active (GTK_COMBO_BOX (combo), i);
	    }
	 }
//	 printf("\n");
      }
   }
   snd_mixer_close(handle);
   return ;
}
Beispiel #13
0
int main(int argc, char *argv[])
{
    app_t a = app_create(0);
    
    v4l2_dev_t v = v4l2_create(a, "/dev/video2", 0, 0);
    v4l2_set_img_proc(v, img_proc, v);
    v4l2_start_capture(v);

    app_exec(a);

    v4l2_stop_capture(v);
    v4l2_free(v);

    app_free(a);

    return 0;
}
static App *
app_new (const gchar * input_fn, const gchar * output_fn)
{
  App *app = g_slice_new0 (App);
  if (!app)
    return NULL;

  app->parser = y4m_reader_open (input_fn);
  if (!app->parser) {
    g_warning ("Could not parse input stream.");
    goto error;
  }

  app->output_file = fopen (output_fn, "w");
  if (app->output_file == NULL) {
    g_warning ("Could not open file \"%s\" for writing: %s.", output_fn,
        g_strerror (errno));
    goto error;
  }

  app->display = video_output_create_display (NULL);
  if (!app->display) {
    g_warning ("Could not create VA display.");
    goto error;
  }

  app->encoder = encoder_new (app->display);
  if (!app->encoder) {
    g_warning ("Could not create encoder.");
    goto error;
  }

  if (!set_format (app->encoder, app->parser->width, app->parser->height,
          app->parser->fps_n, app->parser->fps_d)) {
    g_warning ("Could not set format.");
    goto error;
  }

  return app;

error:
  app_free (app);
  return NULL;
}
Beispiel #15
0
wcs_t wcs_create(char *cfg_path) 
{
    struct wcamsrv *ws = calloc(1, sizeof(struct wcamsrv));
    if (!ws) {
		perror("wcs_create");
		return NULL;
	}

    ws->cfg = cfg_create(cfg_path);
    if (ws->cfg == NULL)
        goto err_mem;

    ws->app = app_create(cfg_get_max_app_event(ws->cfg));
    if (ws->app == NULL)
        goto err_cfg;

    ws->pool = pool_create(cfg_get_thread_in_pool(ws->cfg));
    if (ws->pool == NULL)
        goto err_app;

#if defined(VID_FUNC)
    ws->vid = vid_create(ws);
    if (ws->vid == NULL)
        goto err_pool;
#endif

    if (wcs_srv_init(ws) == -1)
        goto err_cam;

	return ws;
err_cam:
#if defined(VID_FUNC)
    vid_free(ws->vid);
#endif
err_pool:
    pool_free(ws->pool);
err_app:
    app_free(ws->app);
err_cfg:
    cfg_free(ws->cfg);
err_mem:
    free(ws);
    return NULL;
}
Beispiel #16
0
int main(int argc, char *argv[])
{
    app_t a = app_create(0);
    jpg_dec_t d = jpg_dec_create();

    v4l2_dev_t v = v4l2_create(a, NULL, 0, 0);
    v4l2_set_img_proc(v, img_proc, d);
    v4l2_start_capture(v);

    app_exec(a);

    v4l2_stop_capture(v);
    v4l2_free(v);
    jpg_dec_free(d);

    app_free(a);

    return 0;
}
Beispiel #17
0
int
main(int argc, char *argv[])
{
    App *app;
    int ret = EXIT_FAILURE;

    if (argc == 1) {
        print_help(argv[0]);
        return EXIT_SUCCESS;
    }

    app = app_new();
    if (!app || !app_parse_options(app, argc, argv) || !app_run(app))
        goto cleanup;
    ret = EXIT_SUCCESS;

cleanup:
    app_free(app);
    return ret;
}
int
main (int argc, char *argv[])
{
  App *app;
  gint ret;

  if (!video_output_init (&argc, argv, g_options))
    g_error ("failed to initialize video output subsystem");

  app = app_new ();
  if (!app)
    g_error ("failed to create application context");

  ret = !app_run (app, argc, argv);

  app_free (app);
  g_free (g_codec_str);
  video_output_exit ();
  return ret;
}
Beispiel #19
0
int main() {

	int ret = 0;

	app_create();

	picframe_set_backlight(500);

	while (1) {

		picframe_clear_screen();

		if ((ret = window[curr_window_idx]->wndProc()) == 1)
			break;

	}

	app_free();

	return 0;
}
Beispiel #20
0
void
af_open_file_gaction (GSimpleAction *action, GVariant *param,  gpointer user_data)
{
   UserData *ud = (UserData *) user_data;
   FsDialogData *fsdata = g_new0 (FsDialogData, 1);

   fsdata->option = FILE_READ_OP;
   fsdata->ud = ud;
   if ( ud->listFiles ){
      fsdata->filename = (char *) g_slist_nth_data ( ud->listFiles, 0 ) ;
   }

   if (af_create_open_file_selection(fsdata) == GTK_RESPONSE_ACCEPT) {
      af_list_files_free( &ud->listFiles);
      ud->listFiles = fsdata->files;
      app_dup_str(&ud->format, fsdata->format);
      af_load_wave_file (ud);

   }
   app_free(fsdata->format);
   g_free(fsdata);
}
int
main (int argc, char *argv[])
{
  App *app;
  int ret = EXIT_FAILURE;
  gchar *input_fn;

  if (!parse_options (&argc, argv))
    return EXIT_FAILURE;

  /* @TODO: iterate all the input files */
  input_fn = g_input_files ? g_input_files[0] : NULL;
  if (input_fn && !g_file_test (input_fn,
          G_FILE_TEST_EXISTS | G_FILE_TEST_IS_REGULAR)) {
    g_warning ("input file \"%s\" doesn't exist", input_fn);
    goto bail;
  }

  app = app_new (input_fn, g_output_file_name);
  if (!app)
    goto bail;

  print_yuv_info (app);
  ret = app_run (app);
  print_num_frame (app);

  app_free (app);

bail:
  g_free (g_codec_str);
  g_free (g_output_file_name);
  g_strfreev (g_input_files);

  gst_deinit ();

  return ret;
}
Beispiel #22
0
void
af_vl_export_data_gaction (GSimpleAction *action, GVariant *param, gpointer user_data )
{
   DataFile *wdata = (DataFile *) user_data;
   UserData  *ud = wdata->ud;
   
//   msg_dbg("called");

   FsDialogData *fsdata = g_new0 (FsDialogData, 1);

   fsdata->option = FILE_WRITE_OP;
   fsdata->ud = ud;
   if ( ud->listFiles ){
      fsdata->filename = (char *) g_slist_nth_data ( ud->listFiles, 0 )  ;
   }
   if (af_create_open_file_selection(fsdata) == GTK_RESPONSE_ACCEPT) {
      wdata->wt->bits = ud->bits;
      wdata->wt->rate = ud->rate;

      fileformat_file_write( wdata->wt, (char *) fsdata->files->data, fsdata->format, ud->printFmt );
   }
   app_free(fsdata->format);
   g_free(fsdata);
}
Beispiel #23
0
static void XCERR_record_detail(Slist_t*plist)
{
    uint8_t key;
	Errsave_t*pD = app_malloc(sizeof(Errsave_t));
	XCERR_obtain(plist,pD);
    _DLstr_to_DLf(&pD->DLarg,&g_DL_param);
	global_memcpy(&g_user_arg.DL_app_user_set,&pD->DL_app_user_set, sizeof(DL_app_user_set_t));
	global_memcpy(&g_user_arg.DL_app_user_info,&pD->DL_app_user_info,sizeof(DL_app_user_info_t));
	app_module_color_select(2);
	app_XCerrmod_record_detail_win_creat();
	GUI_3D_window_title_mod(m_XCERR_3DWIN,"信息详情");
    app_XCERR_errPAINT();
	app_XCERR_DLpaint();
	app_global_key_control_power_req();
    while(1)
    {
        msleep(1);
		if ( app_global_key_force_obtain( &key, 1 )== 1 )
		{
			if(key==KEY_EXIT)break;
			else if(key==KEY_F5)
			{
				app_global_key_control_power_release();
				if ( MsgBox(100,100,350,150,(char*)m_XCERRmod_MSG_48[g_language],(char*)m_XCERRmod_MSG_49[g_language],APP_HALF_SEC*100) == GUIE_KEY_ENTER )
				{
					app_XCERRmod_record_print(pD);
				}
				app_global_key_control_power_req();
			}
		}
	}
	app_free(pD);
	app_XCerrmod_window_destory();
	app_global_key_control_power_release();
    return;
}
Beispiel #24
0
int main(int argc,char *argv[])
{
   	//Inicia MPI
   	inicializa_mpi(argc,argv);
   	
  	// Obtiene rutas de trabajo y crea archivos generales
  	if(inicializa_archivos(argc, argv, rank) == -1) exit(-1); 
  	   
   	#ifdef _PRINT_MIGRACION_
   		printf("#Bienvenido a MAPAPOC (MÁquina PAralela para Problemas de Optimización Combinatoria) en Rank %d... [OK]\n", rank);
    #endif
      
   	if(rank != 0) {
            //Inicializa semilla aleatoria
            inicializa_semilla();

            //Espera que nodo0 entregue dato runmax (cantidad de archivos a procesar)
            for(;;){
                MPI_Iprobe(nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &flag1, &status);
                if(flag1 == true){
                    if (status.MPI_TAG == MSJ_RUNMAX){
                        MPI_Recv(&runmax, 1, MPI_INT, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                        flag1 = 0;
                        #ifdef _PRINT_MIGRACION_
                            printf("Rank = %d Recibió desde Rank = 0 Mensaje RUNMAX = %d (cantidad máxima de instancias a resolver)...\n", rank, runmax);
                        #endif
                        break;
                    }//End else if
                }//End if
            }//End for

            for(run=1; run<=runmax; run++) {
                #ifdef _PRINT_MIGRACION_
                        printf("Rank = %d Antes de generar semilla aleatoria...\n", rank);
                #endif
                //Nueva semilla aleatoria
                for(rank_seed = 1; rank_seed <= rank; rank_seed++) {
                    int s = 0;
/*
                    s = atoi(argv[7]);
*/
                    if(s==0) {
                        do {
                            randomseed = nueva_semilla();
                        } while (randomseed == 0);
                    } else {
                        randomseed = (float)((s%10000)/10000.0);
                    }
                }//End for
                #ifdef _PRINT_MIGRACION_
                    printf("Rank = %d Después de generar semilla aleatoria...\n", rank);
                #endif

                //Espera que nodo0 entregue información relevante para nodox
                for(;;) {
                    MPI_Iprobe(nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &flag1, &status);
                    if(flag1 == true){
                        if (status.MPI_TAG == MSJ_LINEA_IN){
                            MPI_Recv(linea_in, 100, MPI_CHAR, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                            flag1 = 0;
                            //Asigna variables globales desde linea_in recibida desde Rank 0
                            //sscanf(linea_in,"%d %s %d %s %d %f %f %f %d %s %f", &tipo_problema, nomarch, &popsize, answer, &maxgen, &pcross, &pmutation, &pind_env_rec, &tasa_migracion, answer_mod_mig, &randomseed);
                            sscanf(linea_in,"%d %s %d %s %d %f %f %f %f %d %s %f", &tipo_problema, nomarch, &popsize, answer, &maxgen, &pcross, &pmutation, &pind_env, &pind_rec, &tasa_migracion, answer_mod_mig, &randomseed);                 		
                            randomseed = randomseed + (rank * 0.001);
                            //printf("#Rank = %d estableción semilla : %f\n", rank, randomseed);
                            #ifdef _PRINT_MIGRACION_
                                printf("Rank = %d Recibió desde Rank = 0 Mensaje LINEA_IN (PARAMETROS GLOBALES)...\n", rank);
                            #endif
                        } else if (status.MPI_TAG == MSJ_CANT_CHAR_A_REC) {
                            //cantidad_char_a_recibir es la variable que indica cuantos enteros recibirá nodox desde Rank 0
                            MPI_Recv(&cantidad_char_a_recibir, 1, MPI_INT, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                            flag1 = 0;
                            #ifdef _PRINT_MIGRACION_
                            printf("Rank = %d Recibió desde Rank = 0 Mensaje MSJ_CANT_CHAR_A_REC...\n", rank);
                            #endif
                            break;
                        } else if (status.MPI_TAG == MSJ_ERROR_ARCHIVO_INSTANCIA) {
                            MPI_Recv(0, 0, MPI_INT, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                            flag1 = 0;
                            cantidad_char_a_recibir = -1; //setea a -1 para indicar que hubo error al leer archivo instancia
                            #ifdef _PRINT_MIGRACION_
                            printf("Rank = %d Recibió desde Rank = 0 Mensaje MSJ_ERROR_ARCHIVO_INSTANCIA...\n", rank);
                            #endif
                            break;
                        }//End else if
                    }//End if
                }//End for

                //Setea variable printstrings
                if(strncmp(answer,"n",1) == 0) printstrings = 0;
                else printstrings = 1;

                //Setea variables dependiendo de la cantidad de workers 
                popsize = popsize / workers;
                if(popsize%2) popsize++;
                //n_ind_a_enviar = (int) popsize * pind_env_rec;  //% de la subpoblación se envía
                //n_ind_a_recibir = (int) popsize * pind_env_rec; //% de la subpoblación se recibe
                n_ind_a_enviar = (int) popsize * pind_env;  //% de la subpoblación se envía
                n_ind_a_recibir = (int) popsize * pind_rec; //% de la subpoblación se recibe
                //tasa_migracion = maxgen / workers; //tasa de migración depende de la cantidad de generaciones
                #ifdef _PRINT_MIGRACION_
                    printf("Rank = %d tiene popsize %d, n_ind_a_enviar %d, n_ind_a_recibir %d, tasa_migracion %d...\n", rank, popsize, n_ind_a_enviar, n_ind_a_recibir, tasa_migracion);
                #endif

                // nro. que identifica que migración está ocurriendo
                n_migracion = 0;

                //Inicializa contador de segundos de comunicación 
                time_comm = 0.0;

                //Setea variable modelo_migracion
                if(strncmp(answer_mod_mig,"A",1) == 0) modelo_migracion = 0; // Migración Asíncrona
                else modelo_migracion = 1; //Migración Síncrona

                #ifdef _PRINT_MIGRACION_
                    printf("Rank %d debería recibir %d caracteres representando la instancia a resolver...\n", rank, cantidad_char_a_recibir);
                #endif

                if(cantidad_char_a_recibir > 0) {
                    //Lee enteros con información del archivo instancia  
                    if(lee_char_y_genera_achivo_instancia_tmp(tipo_problema, cantidad_char_a_recibir)) {
                        #ifdef _PRINT_MIGRACION_
                                printf("Espere, MAPAPOC en Rank %d está procesando archivo %s...\n", rank, nomarch);
                        #endif

                        //Actualiza Resultados Estadísticos Evolutivos para cada problema particular
                        fprintf(evofp, "\n\nCorrida : %d, PROBLEMA : %s\n", run, nomarch);
                        fprintf(evofp, "Migracion Generacion Minimo Maximo Media DesvEstandar TiempoTranscurrido GenMejor\n");
                        // Inicia la cuenta de Segundos
                        time_start = MPI_Wtime();

                        // Rutina de inicialización de variables globales
                        initialize();

                        // Ubica espacio malloc para las estructuras de datos globales
                        initmalloc();

                        // Define tipos de Individuos a Enviar y Recibir
                        Build_type_pop(envpop, &message_type_send, n_ind_a_enviar);
                        Build_type_pop(recpop, &message_type_receive, n_ind_a_recibir);

                        // Initializa la población de individuos y determina datos estadísticos
                        // y mejor individuo de la población
                        initpop(tipo_problema);
                        statistics(oldpop);

                        //Avisa a nodo0 que esté listo para comenzar evolución...
                        time_send = MPI_Wtime();
                        MPI_Isend(0, 0, MPI_INT, nodo0, MSJ_LISTO_PARA_COMENZAR, MPI_COMM_WORLD, &request);
                        for(;;){
                            MPI_Test(&request, &flag2, &status);
                            if(flag2 == true){
                            time_send = MPI_Wtime() - time_send;
                            time_comm += time_send;
                            #ifdef _PRINT_MIGRACION_
                                    printf("Envió desde Rank = %d a Rank = 0 Mensaje Listo para comenzar...\n", rank);
                            #endif
                            break;
                            }//End If
                        }//End for

                            //Espera que nodo0 dé la partida para comenzar evolución...
                        for(;;){
                            MPI_Iprobe(nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &flag1, &status);
                            if(flag1 == true) {
                                if (status.MPI_TAG == MSJ_COMIENCE){
                                    MPI_Recv(0, 0, MPI_INT, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                                    flag1 = 0;
                                    #ifdef _PRINT_MIGRACION_
                                            printf("Rank = %d Recibió desde Rank = 0 Mensaje de COMINECE, comienza evolución...\n", rank);
                                    #endif
                                    break;
                                }//End if
                            }//End if
                        }//End for

                        //Setea contador de generaciones para Migrar en Modelo de Migración Asíncrona
                        if (modelo_migracion == 0) cuenta_gen_para_migracion=1;

                        for(gen=0; gen<maxgen; gen++) {
                            if(printstrings == 1) fprintf(outfp,"\nGENERATION %d->%d\n",gen,maxgen);
                            // Crea una nueva generación
                            generation(tipo_problema);
/*
                            printf("generacion: %d de %d => %f\n",gen, maxgen, bestfit.fitness);
*/

                            // Efectúa estadísticas sobre nueva población y obtiene mejor individuo
                            statistics(newpop);

                            if (modelo_migracion == 0) 
                            //Establece comunicación Asincrona con Coordinador
                            comunicacion_asincrona_con_coordinador();         
                            else
                            //Establece comunicación sincrona con Coordinador
                            comunicacion_sincrona_con_coordinador();    
/*
                            printf("rank %i gen %i best fitness: %f\n", rank, gen, bestfit.fitness);
*/
/*
                            if(bestfit.fitness < 107.0) {
                                printf("rank %i gen %i best fitness: %f done!\n", rank, gen, bestfit.fitness);
                                gen = maxgen;
                            }
*/
/*
                            printf("%i.%i=>%f\n", rank, gen, bestfit.fitness);
*/
                            // Avanza de Generación
                            temppop = oldpop;
                            oldpop = newpop;
                            newpop = temppop;
                        }//End for

                            // Libera memoria temporal
                        freeall();

                            //Libera memoria tipos creados por MPI
                        MPI_Type_free(&message_type_send);
                        MPI_Type_free(&message_type_receive);

                    } else
                        printf("!!! ADVERTENCIA ¡¡¡ Rank %d no procesó archivo de instancia ya que hubo problemas al leer enteros, generar o leer tmp...\n", rank);
                } else 
                    printf("!!! ADVERTENCIA ¡¡¡ Rank %d no procesó archivo de instancia ya que Rank 0 tuvo problemas al leerlo...\n", rank);

                // Libera variables del problema  
                app_free(tipo_problema);

                //Mensaje de término de procesamiento de archivo actual se envía a Rank = 0
                MPI_Isend(&time_comm, 1, MPI_DOUBLE, nodo0, MSJ_TERMINO, MPI_COMM_WORLD, &request);
                for(;;){
                    MPI_Test(&request, &flag2, &status);
                    if(flag2 == true){
                        #ifdef _PRINT_MIGRACION_
                            printf("Envió desde Rank = %d a Rank = 0 Mensaje de Término, archivo %s...\n", rank, nomarch);
                        #endif
                        break;
                    }//End If
                }//End for

                    //Espera que nodo0 dé el OK para poder finalizar el procesamiento del archivo actual
                for(;;){
                    MPI_Iprobe(nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &flag1, &status);
                    if(flag1 == true){
                        if(status.MPI_TAG == MSJ_TERMINO_CONFIRMADO){
                            MPI_Recv(0, 0, MPI_INT, nodo0, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
                            flag1 = 0;
                            #ifdef _PRINT_MIGRACION_
                                printf("Rank = %d Recibió desde Rank = 0 Mensaje de TERMINO_CONFIRMADO, pasa siguiente archivo o termina...\n", rank);
                            #endif
                            break;
                        }//End if
                    }//End if
                }//End for
                #ifdef _PRINT_MIGRACION_
                        printf("#Corrida %d, Archivo %s procesado por Rank %d...   [OK]\n", run, nomarch, rank);
                #endif
            }//End for

            if(runmax == 0){
                //Que runmax = 0 significa que la consistencia del archivo arrojó un error 
                //=> rank debe mandar mensaje al Coordinador que va ha terminar el proceso...
                //Mensaje de término de procesamiento de archivo actual se envía a Rank = 0
                MPI_Isend(&time_comm, 1, MPI_DOUBLE, nodo0, MSJ_TERMINO, MPI_COMM_WORLD, &request);
                for(;;){
                    MPI_Test(&request, &flag2, &status);
                    if(flag2 == true){
                        #ifdef _PRINT_MIGRACION_
                                printf("Envió desde Rank = %d a Rank = 0 Mensaje de Término, archivo %s...\n", rank, nomarch);
                        #endif
                        break;
                    }//End If
                }//End for
                printf("Proceso en Rank %d detenido ya que Rank 0 informa error en archivo de entrada...   [OK]\n", rank);
            }//End if
        } else {
      	//Rank = 0 => Coordinador
/*
   		printf("#Bienvenido a Máquina Paralela para Problemas de Optimización Combinatoria, espere por favor...\n");
*/
      	
      	// Revisa consistencia del archivo de entrada in.txt
      	runmax = consistenciaarchivo(workers);
      	
      	//Envía runmax a cada Rank
      	envia_a_cada_rank(MSJ_RUNMAX);
   
      	for(run=1;run<=runmax;run++) {
         	//Lee archivo en infp con parametros (todos ya chequeados)
         	//OJO => Cada AG tendrá popsize/workers individuos => Población Total = popsize          	
			//fscanf(infp,"%d %s %d %s %d %f %f %f %d %s %f", &tipo_problema, nomarch, &popsize, answer, &maxgen, &pcross, &pmutation, &pind_env_rec, &tasa_migracion, answer_mod_mig, &randomseed);
            fscanf(infp,"%d %s %d %s %d %f %f %f %f %d %s %f", &tipo_problema, nomarch, &popsize, answer, &maxgen, &pcross, &pmutation, &pind_env, &pind_rec, &tasa_migracion, answer_mod_mig, &randomseed);
            int i=0;
            randomseed = (float)((atoi(argv[7])%100)/100.0);
            
/*
            printf("argv[7]: %i\n", atoi(argv[7]));
            printf("randomseed: %f\n", randomseed);
*/
            for(i=0; i<argc; i++) {
//                printf("argv[%i]: %s\n", i, argv[i]);
                if(strcmp(argv[i], "-pr")==0) tipo_problema = atoi(argv[++i]);
                if(strcmp(argv[i], "-po")==0) popsize = atoi(argv[++i]);
                if(strcmp(argv[i], "-g")==0) maxgen = atoi(argv[++i]);
                if(strcmp(argv[i], "-m")==0) pmutation = atof(argv[++i]);
                if(strcmp(argv[i], "-c")==0) pcross = atof(argv[++i]);
                if(strcmp(argv[i], "-pe")==0) pind_env = atof(argv[++i]);
                if(strcmp(argv[i], "-pa")==0) pind_rec = atof(argv[++i]);
                if(strcmp(argv[i], "-tm")==0) tasa_migracion = atoi(argv[++i]);
                if(strcmp(argv[i], "-am")==0) sprintf(answer_mod_mig, "%s", argv[++i]);
                if(strcmp(argv[i], "-f")==0) sprintf(nomarch, "%s", argv[++i]);
                if(strcmp(argv[i], "-a")==0) sprintf(answer, "%s", argv[++i]);
            }
//            exit(0);
         	
			//Inicializa contador de segundos de comunicación 
         	time_comm = 0.0;
         
         	//Llena con información linea_in para ser enviada a cada Rank
         	//sprintf(linea_in,"%d %s %d %s %d %f %f %f %d %s %f\n", tipo_problema, nomarch, popsize, answer, maxgen, pcross, pmutation, pind_env_rec, tasa_migracion, answer_mod_mig, randomseed);
			sprintf(linea_in,"%d %s %d %s %d %f %f %f %f %d %s %f", tipo_problema, nomarch, popsize, answer, maxgen, pcross, pmutation, pind_env, pind_rec, tasa_migracion, answer_mod_mig, randomseed);
/*
                        printf("%d %s %d %s %d %f %f %f %f %d %s %f\n", tipo_problema, nomarch, popsize, answer, maxgen, pcross, pmutation, pind_env, pind_rec, tasa_migracion, answer_mod_mig, randomseed);
*/

       		#ifdef _PRINT_MIGRACION_
       			printf("Espere, MAPAPOC en Rank %d está enviando archivo %s a todos los rank...\n", rank, nomarch);
       		#endif

        	//Envía linea_in a cada Rank
      		envia_a_cada_rank(MSJ_LINEA_IN);
      	
         	//Setea variable printstrings
         	if(strncmp(answer,"n",1) == 0) printstrings = 0;
         	else printstrings = 1;
      
         	//Setea variables dependiendo de la cantidad de workers 
         	popsize = popsize / workers;
/*
                printf("popsize: %i\n", popsize);
*/
         	if(popsize%2) popsize++;
         	//n_ind_a_enviar = (int) popsize * pind_env_rec;  //% de la subpoblación se envía
         	//n_ind_a_recibir = (int) popsize * pind_env_rec; //% de la subpoblación se recibe
                n_ind_a_enviar = (int) popsize * pind_env;  //% de la subpoblación se envía
         	n_ind_a_recibir = (int) popsize * pind_rec; //% de la subpoblación se recibe
         	//tasa_migracion = maxgen / workers; //tasa de migración debende de la cantidad de generaciones
               
         	//Setea variable modelo_migracion
         	if(strncmp(answer_mod_mig,"A",1) == 0) modelo_migracion = 0; //Migración Asíncrona
         	else modelo_migracion = 1; //Migración Síncrona
         
         	if(app_leearchivo(tipo_problema, nomarch, rank)) {     
            	if(almacena_archivo_instancia(nomarch)) {
	            	//Determina cantidad_char_a_recibir por cada rank que coordinador enviará. Todos estos char determinan los datos del problema a resolver
	            	cantidad_char_a_recibir = cantidad_char_que_determinan_instancia_del_problema;
	            	
	            	//Envía a cada Rank cantidad de char a recibir del problema
	            	envia_a_cada_rank(MSJ_CANT_CHAR_A_REC); 
	            
	            	//Envía a cada Rank un grupo de char que determinan la estructura de una instancia del problema
	            	envia_a_cada_rank(MSJ_CHAR_ARCHIVO_INSTANCIA);
	            	
	        		// Rutina de inicialización de variables globales
	           		// nro. individuos a enviar desde coord. a nodo AG
	           		coord_ind_a_env  = n_ind_a_recibir;  
	           		// nro. individuos a recibir desde cada nodo AG a coord
	           		coord_ind_a_rec = n_ind_a_enviar; 
	           		// nro. individuos total recibidos => Población Global del Coordinador
	           		coord_ind_global = workers * n_ind_a_enviar; 
	           		// nro. que identifica qué migración está ocurriendo
	           		n_migracion = 1;  
	           		#ifdef _PRINT_MIGRACION_
	           			printf("Espere, MAPAPOC en Rank %d está procesando archivo %s...\n", rank, nomarch);
	              		printf("Rank = %d tiene popsize %d, coord_ind_a_env %d, coord_ind_a_rec %d, coord_ind_global % d, tasa_migracion %d...\n", rank, popsize, coord_ind_a_env, coord_ind_a_rec, coord_ind_global, tasa_migracion);
	           		#endif
	     
				   	//Actualiza Resultados Estadísticos Evolutivos para cada problema particular
				   	fprintf(evofp, "\n\nCorrida : %d, PROBLEMA : %s\n", run, nomarch);
				   	fprintf(evofp, "Migracion Generacion Minimo Maximo Media DesvEstandar TiempoTranscurrido\n");
				   	// Inicia la cuenta de Segundos
				   	time_start = MPI_Wtime();
	           
	           		//Rutina de inicialización de variables globales
	           		initialize();
	           
	           		//Dimensiona poblaciones de individuos que recibe y envía...
	           		initmallocMaster(coord_ind_a_rec, coord_ind_a_env, coord_ind_global);
	     
	           		//Define tipos de Individuos a Enviar y Recibir
	           		Build_type_pop(envpop, &message_type_send, coord_ind_a_env);
	           		Build_type_pop(recpop, &message_type_receive, coord_ind_a_rec);
	  
	           		if (modelo_migracion == 0) 
	              		//Establece comunicación Asincrona con cada rank (AG)
		              		comunicacion_asincrona_con_cada_rank();         
	           		else
	              		//Establece comunicación sincrona con cada rank (AG)
	              		comunicacion_sincrona_con_cada_rank();         
	              
                                // Calcula cantidad de segundos que demoró en cada Algoritmo Genético
                                time_end = MPI_Wtime() - time_start;
                                time_consumation.elapsed_time = time_end;
                                time_consumation.comm_time = time_comm;
                                time_consumation.cpu_time = time_end - time_comm;

                                //Graba datos en archivo de resultados del algoritmo
                                genera_resultados_algoritmo(run, tipo_problema, nomarch, &time_consumation);

                                //Graba datos en archivo de resultados del problema
                                app_genera_resultados_problema(run, tipo_problema, nomarch);

                                //IMPRIME SALIDA PARA PROGRAMA PARAMILS
/*
                                printf("RunsExecuted = 1\n");
                                printf("CPUTime_Mean = %f\n", time_consumation.elapsed_time);
                                printf("BestSolution_Mean = %f\n", bestfit.fitness);
*/
/*
                                printf("Result for ParamILS: SAT, %f, %i, %f, %s\n", -1.0, -1, bestfit.fitness, argv[7]);
*/
                                printf("Resultado: SAT, %s, %f, %f, %f, %f\n", nomarch, time_consumation.elapsed_time, time_consumation.cpu_time, bestfit.fitness, randomseed);

                                //Genera la Salida hacia archivo de Resultados LAYOUT
                                app_objfuncfinal(tipo_problema, &(bestfit));
				  	
	           		//Libera memoria del Coordinador
	           		freeallMaster(coord_ind_a_rec, coord_ind_a_env, coord_ind_global);
	           
	           		//Libera memoria tipos creados por MPI
	           		MPI_Type_free(&message_type_send);
	           		MPI_Type_free(&message_type_receive);
	         	}//End if
	         	else {
	            	printf("!!! ERROR ¡¡¡ Rank 0, en datos del archivo de piezas <%s> => Archivo no procesado...\n", nomarch);
	            	//Envía a cada Rank que ARCHIVO_INSTANCIA está con algún error
	            	envia_a_cada_rank(MSJ_ERROR_ARCHIVO_INSTANCIA); 
	         	}//End else
         	}//End if
         	else {
            	printf("!!! ERROR ¡¡¡ Rank 0, en datos del archivo de piezas <%s> => Archivo no procesado...\n", nomarch);
            	//Envía a cada Rank que ARCHIVO_INSTANCIA está con algún error
            	envia_a_cada_rank(MSJ_ERROR_ARCHIVO_INSTANCIA); 
         	}//End else
	      	// Libera variables del problema  
	      	app_free(tipo_problema);

                #ifdef _PRINT_MIGRACION_
         		printf("#Corrida %d, Archivo %s procesado por Coordinador...   [OK]\n", run, nomarch);
         	#else
//         		printf("#Corrida %d, Archivo %s procesado...   [OK]\n", run, nomarch);
         	#endif
      	}//End for
      	if(runmax == 0){
         	//Que runmax = 0 significa que la consistencia del archivo arrojó un error 
         	printf("Archivo %s NO procesado por Rank %d debido a error...   [OK]\n", nomarch, rank);
      	}//End if
   	}//End else    

	//Cierra archivos
	cierra_archivos();
	
   	//Rutina para MPI
   	MPI_Finalize();
 
   	#ifdef _PRINT_MIGRACION_
   		printf("Terminó rank = %d...\n", rank);
    #endif
   
	exit(0);
}//End main
Beispiel #25
0
static void _txtView(char*path)
{
    hwin_t* pwin;
	char  * pbuf ;
	FIL   * fil;
	char  *p;
	uint8_t key_buf;
	int   y = 5;
	pbuf = app_malloc(1000);
	GUI_window_hwin_req( GET_GUIWIN );
	GUI_set_Bgcolor( 0 );
	GUI_clean_screen();
	GUI_set_Bgcolor( 0 );
	GUI_set_Fgcolor( C_GUI_WHITE);
	pwin = Gui_3D_window_creat( 0, 0, LCD_WIDE - 2, LCD_HIGH, "文本浏览器", WIN_3D | WIN_FILL, 0 );
	GUI_window_hwin_release( GET_GUIWIN ); 
	fil=fatfs_open(path,FA_OPEN_EXISTING|FA_READ|FA_WRITE);
	while(1)
	{
	    p = f_gets(pbuf,500,fil);
		if(!p)
		{
		    while(1)
			{
			    msleep(1);
				if ( app_global_key_obtain( &key_buf, 1 ) == 1 ) 
				{
					 if(key_buf==KEY_EXIT)
					 {
					    fatfs_close(fil);
						app_free(pbuf);
						GUI_window_destory(pwin);
						return;
					 }
				}
		    }
		}
		GUI_window_hwin_req( pwin );
		GUI_set_Bgcolor( 0 );
		GUI_set_Fgcolor( C_GUI_WHITE);
		GUI_SetFront(&GUI_HZK16_EXTASCII);
		GUI_string_display_At(2,y,pbuf);
		GUI_window_hwin_release( pwin );
		y+=GUI_conText.CUR_Front->high;
		if((y+GUI_conText.CUR_Front->high)>pwin->win_high)
		{
		    while(1)
		    {
		        msleep(1);
				if ( app_global_key_obtain( &key_buf, 1 ) == 1 ) 
				{
				     if(key_buf==KEY_DOWN)
				     {
				     	 GUI_window_hwin_req( pwin );
						 GUI_set_Bgcolor( 0 );
						 GUI_set_Fgcolor( C_GUI_WHITE);
					     GUI_clean_window();
			             y = 5;
						 GUI_window_hwin_release( pwin );
						 break;
				     }
					 else if(key_buf==KEY_EXIT)
					 {
						app_free(pbuf);
						GUI_window_destory(pwin);
						return;
					 }
				}
		    }
		}
	}
}
Beispiel #26
0
/*
*func:计算给定字符串text 在给定宽度内以自动断行的方式
*       能输出多少行,并返回每一行的指针
*gc[IN]:字符输出的系统环境
*width[IN]:给定宽度
*lang[IN]:文本本地化代码标志
*text[IN]:给定字符串
*len[IN]:给定字符串的字节长
*max_line[IN]:给定的最大可输出行数,即line_len的数组大小,防止越界,请注意不能小于2
*line_from[IN,OUT]:需要外部分配内存后传入,用于返回各行的字符串在  给定字符串text
				:中的索引,若为NULL,表示 不需要返回字节长度
*line_len[IN,OUT]:需要外部分配内存后传入,用于返回各行的字符串字节长度
                         :若为NULL,表示 不需要返回字节长度
*line_width[IN,OUT]:用于返回各行的字符串输出的实际宽度,
  需要外部分配提供,大小同line_len,如果为NULL,表示不需要返回宽度
*返回:能输出的行数,-1为出错

*常用用法:1 . 获取字符串能输出的行数
                             lines = utf32GetTextExWordBreakLines(gc,screenwidth,lang,pStr,strlen(pStr),100,NULL,NULL,NULL);
                       2 . 获取字符串能输出的行数及各行的信息(长度、位置)
                             int *line_from = malloc(100);
                             int *line_len = malloc(100);
                             lines = utf32GetTextExWordBreakLines(gc,screenwidth,lang,pStr,strlen(pStr),100,line_from,line_len,NULL);   
                             for(i=0;i<lines;i++)
                             	drawText(gc,pStr+line_from[i],line_len[i]); 
                             
*/
int
utf32GetTextExWordBreakLines(GR_GC_ID gc, GR_SIZE width,const char* lang,
		const char *text, size_t len, int max_line,int line_from[],int line_len[],int line_width[])
{
	GR_SIZE w, h, b;
	GR_SIZE last_w;//当前字符宽度超过给定宽度时,用于回退到上一次小于给定宽度时的宽度
	char *brks;//保存各字节能否break的信息
	int i;
	int line_start;//每行行首所在(相对于整个字符串)
	int last_word;//上一次字符串宽度小于给定宽度时的那个字符所在
	int line_count = 0;//可输出行数
	int word_locate;
	int wordcount = len/4;//字符个数
	const char *text_lang;
	
	NxGetGCTextSize(gc, text, len, MWTF_UC32, &w, &h, &b);
	if (w <= width) {//不够输出一行
		if(line_len){
			line_len[line_count] = len;
		}
		if(line_from){
			line_from[line_count] = 0;
		}
		
		if(line_width){
			line_width[line_count] = w;
		}
		line_count = 1;
		
		return line_count;
	}

	brks = app_malloc(wordcount);
	if (brks == NULL)
		return -1;

	text_lang = get_text_lang(UTF32LE, text, len);
	/* Show the breaking points */
    set_linebreaks_utf32(text, wordcount, text_lang, brks);

	line_start = 0;
	last_word = 0;
	for (i = 1; i <= wordcount; i++) {
		switch (brks[i-1]) {
		case LINEBREAK_MUSTBREAK:
		case LINEBREAK_ALLOWBREAK:
			NxGetGCTextSize(gc, text + 4*line_start, 4*(i - line_start), MWTF_UC32, &w, &h, &b);
			if (w > width) {
				if (last_word > line_start) {
					if (w - last_w > width) {
						int partial_len;
						GR_SIZE partial_w;
						partial_len = locate_word_to_fit(gc, width - last_w,
									text + 4*last_word, 4*(i - last_word), &partial_w);
						partial_len /= 4;
						last_word += partial_len;
						last_w += partial_w;
					}
					if(line_len){
						line_len[line_count] = 4*(last_word - line_start);
					}
					if(line_from){
						line_from[line_count] = 4*(line_start);
					}
					if(line_width){
						line_width[line_count] = last_w;
					}
					line_count++;
					line_start = last_word;
					w = w - last_w;
					if(line_count>=max_line){
						app_free(brks);
						return line_count;
					}
				}

				/* too long word */
				while (w > width) {
					word_locate = locate_word_to_fit(gc, width, text + 4*line_start, 4*(i - line_start), &last_w);
					word_locate /= 4;
					if(line_len){
						line_len[line_count] = 4*word_locate;//locate_word_to_fit(gc, width, text + line_start, i - line_start, &last_w);
					}
					if(line_from){
						line_from[line_count] = 4*line_start;
					}
					if(line_width){
						line_width[line_count] = last_w;
					}

					line_start += word_locate;

					line_count++;
					w = w - last_w;
					if(line_count>=max_line){
						app_free(brks);
						return line_count;
					}
				}
			}
			if (brks[i-1] == LINEBREAK_MUSTBREAK || w == width) {
				if(line_len){
					line_len[line_count] = 4*(i - line_start);
				}
				if(line_from){
					line_from[line_count] = 4*(line_start);
				}
				if(line_width){
					line_width[line_count] = w;
				}
				
				line_count++;

				line_start = i;
				last_word = line_start;
				last_w = 0;
				if(line_count>=max_line){
					app_free(brks);
					return line_count;
				}
			} else {
				last_word = i;
				last_w = w;
			}
			break;
		}
	}

	if (line_start < wordcount) {

		if(line_count>=max_line){
			app_free(brks);
			return line_count;
		}
		if(line_len){
			line_len[line_count] = 4*(wordcount - line_start);
		}
		if(line_from){
			line_from[line_count] = 4*line_start;
		}
		if(line_width){
			line_width[line_count] = w;
		}
		
		line_count++;
	}

	app_free(brks);
	return line_count;
}
int
main (int    argc,
      char **argv)
{
  GError *error;
  GOptionContext *opt_context;
  GMainLoop *main_loop;
  gint ret;
  guint name_owner_id;
  GIOChannel *stdin_channel;

  ret = 1;
  opt_context = NULL;
  name_owner_id = 0;
  stdin_channel = NULL;

  introspection_data = g_dbus_node_info_new_for_xml (introspection_xml, NULL);
  g_assert (introspection_data != NULL);

  opt_context = g_option_context_new ("gnome-shell calendar server");
  g_option_context_add_main_entries (opt_context, opt_entries, NULL);
  error = NULL;
  if (!g_option_context_parse (opt_context, &argc, &argv, &error))
    {
      g_printerr ("Error parsing options: %s", error->message);
      g_error_free (error);
      goto out;
    }

  main_loop = g_main_loop_new (NULL, FALSE);

  stdin_channel = g_io_channel_unix_new (STDIN_FILENO);
  g_io_add_watch_full (stdin_channel,
                       G_PRIORITY_DEFAULT,
                       G_IO_HUP,
                       stdin_channel_io_func,
                       g_main_loop_ref (main_loop),
                       (GDestroyNotify) g_main_loop_unref);

  name_owner_id = g_bus_own_name (G_BUS_TYPE_SESSION,
                                  BUS_NAME,
                                  G_BUS_NAME_OWNER_FLAGS_ALLOW_REPLACEMENT |
                                   (opt_replace ? G_BUS_NAME_OWNER_FLAGS_REPLACE : 0),
                                  on_bus_acquired,
                                  on_name_acquired,
                                  on_name_lost,
                                  g_main_loop_ref (main_loop),
                                  (GDestroyNotify) g_main_loop_unref);

  g_main_loop_run (main_loop);

  g_main_loop_unref (main_loop);

  ret = 0;

 out:
  if (stdin_channel != NULL)
    g_io_channel_unref (stdin_channel);
  if (_global_app != NULL)
    app_free (_global_app);
  if (name_owner_id != 0)
    g_bus_unown_name (name_owner_id);
  if (opt_context != NULL)
    g_option_context_free (opt_context);
  return ret;
}
Beispiel #28
0
/* ins_app */
WORD ins_app(BYTE *pfname, ANODE *pa)
{			       
	LONG	tree;
	ANODE	*newpa;
	BYTE	pname[12];
	BYTE	ntypes[6*8];
	WORD	oicon, nicon;
	WORD	oflag, nflag;
	WORD	change, field;
	WORD	uninstalled, h;
#if MULTIAPP
	BYTE	memszstr[4];
	WORD	omemsz, nmemsz;
#endif

	tree = G.a_trees[ADINSAPP];
#if MULTIAPP
	LWSET(OB_NEXT(APMEMBOX),APMEMSZ);
#endif
	h = LWGET(OB_HEIGHT(APSCRLBA));
	LWSET(OB_HEIGHT(APFUPARO), gl_hbox + 2);
	LWSET(OB_Y(APFSVSLI), gl_hbox + 2);
	LWSET(OB_HEIGHT(APFSVSLI), h - (2 * (gl_hbox + 2)));
	LWSET(OB_Y(APFDNARO), h - (gl_hbox + 2));
	LWSET(OB_HEIGHT(APFDNARO), gl_hbox + 2);

	uninstalled = !is_installed(pa);
	LWSET(OB_STATE(APREMV), (uninstalled) ? DISABLED : NORMAL );
	/* stuff in appl name */
	fmt_str(pfname, &pname[0]);
	inf_sset(tree, APNAME, &pname[0]);
	/* stuff in docu types */
	insa_stypes(tree, pa->a_pdata);
	LWSET(OB_STATE(APYMEM), NORMAL);
	oflag = pa->a_flags;
	if (pa->a_flags & AF_ISCRYS)
	{
		field = APGEM;
		LWSET(OB_STATE(APYMEM), DISABLED);
	}
	else
		field = (pa->a_flags & AF_ISPARM) ? APPARMS : APDOS;
	LWSET(OB_STATE(field), SELECTED);

	field = (pa->a_flags & AF_ISFMEM) ? APYMEM : APNMEM;
	LWSET(OB_STATE(field), SELECTED);

	oicon = pa->a_aicon - IA_GENERIC;

#if MULTIAPP
	omemsz = pa->a_memreq;
	merge_str(&memszstr[0], "%W", &omemsz);
	inf_sset(tree, APMEMSZ, &memszstr[0]);
#endif

	insa_elev(tree, oicon, gl_numics);
	nicon = insa_dial(tree, oicon, gl_numics);
	change = FALSE;

#if MULTIAPP
	nmemsz = ins_latoi(LLGET(LLGET(OB_SPEC(APMEMSZ))));
#endif

	/* set memory flag */
	field = inf_gindex(tree, APYMEM, 2);
	nflag = (field == 0) ? AF_ISFMEM : 0;
	LWSET(OB_STATE(APYMEM + field), NORMAL);
	/* set type flags */
	field = inf_gindex(tree, APGEM, 3);
	if (field == 0)
		nflag = AF_ISCRYS | AF_ISGRAF;
	if (field == 2)
		nflag |= AF_ISPARM;
	LWSET(OB_STATE(APGEM + field), NORMAL);
	/* get button selection	*/
	field = inf_gindex(tree, APINST, 3);
	LWSET(OB_STATE(APINST + field), NORMAL);

	if ( field == 0 )
	{
		/* install the appl. if its uninstalled or has new types */
		insa_gtypes(tree, &ntypes[0]);
		if ( (uninstalled) || (!strcmp(&ntypes[0], pa->a_pdata)) )
		{
			newpa = (uninstalled) ? app_alloc(TRUE) : pa;

			if (newpa)
			{
				if ( (uninstalled) || (!strcmp(&ntypes[0], pa->a_pdata)) )
				{
					change = TRUE;
					ntypes[ strlen(&ntypes[0]) ] = '@';
					scan_str(&ntypes[0], &newpa->a_pdata);
				}

				if (newpa != pa)
				{
					uninstalled = change = TRUE;
					strcpy(&ntypes[0], pfname);
					ntypes[ strlen(&ntypes[0]) ] = '@';
					scan_str(&ntypes[0], &newpa->a_pappl);
					newpa->a_flags = nflag;
					newpa->a_type = AT_ISFILE;
					newpa->a_obid = NIL;
					newpa->a_letter = '\0';
					newpa->a_xspot = 0x0;
					newpa->a_yspot = 0x0;
				}
				pa = newpa;
			}
			else
				fun_alert(1, STAPGONE, NULL);
		}
		/* see if icon changed or flags changed */
		if ( (uninstalled) ||
#if MULTIAPP
			(omemsz != nmemsz) ||
#endif
			(oicon != nicon) ||
			(oflag != nflag) )
		{
			change = TRUE;
			pa->a_aicon = nicon + IA_GENERIC;
			pa->a_dicon = nicon + ID_GENERIC;
			pa->a_flags = nflag;
#if MULTIAPP
			pa->a_memreq = nmemsz;
#endif
		}
	}
	else if ( field == 1 )
	{
		/* remove installed app	*/
		if ( !uninstalled )
		{
			app_free(pa);
			change = TRUE;
		}
	}
	return(change);
} /* ins_app */
Beispiel #29
0
/* ins_disk */
WORD ins_disk(ANODE *pa)
{
	LONG	tree;
	WORD	change, icon, flop, hard, fld;
	BYTE	cletter[2], clabel[13];
	BYTE	nletter[2], nlabel[13];
	ANODE	*newpa;

	tree = G.a_trees[ADINSDIS];

	change = FALSE;
	cletter[0] = pa->a_letter;
	cletter[1] = '\0';
	strcpy(&clabel[0], pa->a_pappl);

	inf_sset(tree, DRID, &cletter[0]);
	inf_sset(tree, DRLABEL, &clabel[0]);

	flop = (pa->a_aicon == IG_FLOPPY) ? SELECTED : NORMAL;
	hard = (pa->a_aicon == IG_HARD) ? SELECTED : NORMAL;
	LWSET(OB_STATE(DRFLOPPY), flop);
	LWSET(OB_STATE(DRHARD), hard);
	LWSET(OB_STATE(DRREM), (lastdisk()) ? DISABLED : NORMAL ); 

	inf_show(tree, 0);	

	inf_sget(tree, DRID, &nletter[0]);
	inf_sget(tree, DRLABEL, &nlabel[0]);
	fld = inf_gindex(tree, DRINST, 3);	/* which exit button?	*/
	LWSET(OB_STATE(DRINST + fld), NORMAL);
	icon = ( LWGET(OB_STATE(DRFLOPPY)) & SELECTED );
	icon = (icon) ? IG_FLOPPY : IG_HARD;
	if ( fld == 0 )	/* Install */
	{
		if ( (cletter[0] != nletter[0]) && (nletter[0] != '\0') )
		{
			newpa = get_disk(nletter[0]);
			if (!newpa)
			{
				newpa = app_alloc(FALSE);
				if (newpa)
				{
					newpa->a_flags = pa->a_flags;
					newpa->a_type = pa->a_type;
					newpa->a_obid = pa->a_obid;
					newpa->a_pappl = pa->a_pappl;
					scan_str("@", &newpa->a_pdata);
					newpa->a_aicon = pa->a_aicon;
					newpa->a_dicon = NIL;
					newpa->a_letter = nletter[0];
				} /* if newpa */
				else
					fun_alert(1, STAPGONE, NULL);
			} /* if !newpa */
			if (newpa)
				pa = newpa;
			change = TRUE;
		} /* if cletter */
		/* see if icon changed	*/
		if (pa->a_aicon != icon)
		{
			pa->a_aicon = icon;
			change = TRUE;
		}
		/* see if label changed	*/
		if ( (!strcmp(&clabel[0], &nlabel[0])) && (nlabel[0] != '\0') )
		{
			nlabel[ strlen(&nlabel[0]) ] = '@';
			scan_str(&nlabel[0], &pa->a_pappl);
			change = TRUE;
		}
	} /* if INSTALL */
	else if ( fld == 1 )	/* Remove  */
	{
		/* find matching anode delete it */
		for (pa = G.g_ahead; pa; pa = pa->a_next)
		{
			if ( (pa->a_aicon == icon) && (pa->a_letter == nletter[0]) )
			{
				app_free(pa);
				change = TRUE;
			}
		} /* for */
	} /* if REMOVE */
	return(change);
} /* ins_disk */
void retro_deinit(void)
{
   app_free(); 
   Emu_uninit(); 
}