Beispiel #1
0
//------ Begin of function News::migrate -------//
//
// nation_name1() - from nation
// nation_name2() - to nation
//
// short_para1 = the town name id. that the worker migrates from
// short_para2 = the town name id. that the worker migrates to
// short_para3 = race id. of the migrated worker/peasant
// short_para4 = no. of people migrated
// short_para5 = the firm id. that the worker works for
//
void News::migrate()
{
	//---------------- Text Format -----------------//
	//
	// A <racial> <worker name>/Peasant has emigrated from your
	// village of <town name> to <town name> in <nation name>.
	//
	// A <racial> <worker name>/Peasant has immigrated from
	// <town name> in <nation name> to your village of <town name>.
	//
	//----------------------------------------------//

	if( nation_array.player_recno && nation_name_id1 == (~nation_array)->nation_name_id )		// from player nation to another nation
	{
		if( nation_name_id2 )		// only if it is not an independent town
		{
			if( short_para5 )
			{
				snprintf(str,
					 MAX_STR_LEN+1,
					 // TRANSLATORS: A <Race> <Worker> has emigrated from your village of <Town> to <Town> in <King's Kingdom>.
					 // <Number> <Race> <Worker>s have emigrated from your village of <Town> to <Town> in <King's Kingdom>.
					 ngettext("%d %s %s has emigrated from your village of %s to %s in %s.",
						  "%d %s %ss have emigrated from your village of %s to %s in %s.",
						  short_para4),
					 short_para4,
					 race_res[short_para3]->name,
					 firm_res[short_para5]->worker_title,
					 town_res.get_name(short_para1),
					 town_res.get_name(short_para2),
					 nation_name2());
			}
			else
			{
				snprintf(str,
					 MAX_STR_LEN+1,
					 // TRANSLATORS: A <Race> Peasant has emigrated from your village of <Town> to <Town> in <King's Kingdom>.
					 // <Number> <Race> Peasants have emigrated from your village of <Town> to <Town> in <King's Kingdom>.
					 ngettext("%d %s Peasant has emigrated from your village of %s to %s in %s.",
						  "%d %s Peasants have emigrated from your village of %s to %s in %s.",
						  short_para4),
					 short_para4,
					 race_res[short_para3]->name,
					 town_res.get_name(short_para1),
					 town_res.get_name(short_para2),
					 nation_name2());
			}
		}
		else
		{
			if( short_para5 )
			{
				snprintf(str,
					 MAX_STR_LEN+1,
					 // TRANSLATORS: A <Race> <Worker> has emigrated from your village of <Town> to <Town>.
					 // <Number> <Race> <Worker>s have emigrated from your village of <Town> to <Town>.
					 ngettext("%d %s %s has emigrated from your village of %s to %s.",
						  "%d %s %ss have emigrated from your village of %s to %s.",
						  short_para4),
					 short_para4,
					 race_res[short_para3]->name,
					 firm_res[short_para5]->worker_title,
					 town_res.get_name(short_para1),
					 town_res.get_name(short_para2));
			}
			else
			{
				snprintf(str,
					 MAX_STR_LEN+1,
					 // TRANSLATORS: A <Race> Peasant has emigrated from your village of <Town> to <Town>.
					 // <Number> <Race> Peasants have emigrated from your village of <Town> to <Town>.
					 ngettext("%d %s Peasant has emigrated from your village of %s to %s.",
						  "%d %s Peasants have emigrated from your village of %s to %s.",
						  short_para4),
					 short_para4,
					 race_res[short_para3]->name,
					 town_res.get_name(short_para1),
					 town_res.get_name(short_para2));
			}
		}
	}
	else
	{
		if( nation_name_id1 )		// only if it is not an independent town
		{
			if( short_para5 )
			{
				snprintf(str,
					 MAX_STR_LEN+1,
					 // TRANSLATORS: A <Race> <Worker> has immigrated from <Town> in <King's Kingdom> to your village of <Town>.
					 // <Number> <Race> <Worker>s have immigrated from <Town> in <King's Kingdom> to your village of <Town>.
					 ngettext("%d %s %s has immigrated from %s in %s to your village of %s.",
						  "%d %s %ss have immigrated from %s in %s to your village of %s.",
						  short_para4),
					 short_para4,
					 race_res[short_para3]->name,
					 firm_res[short_para5]->worker_title,
					 town_res.get_name(short_para1),
					 nation_name1(),
					 town_res.get_name(short_para2));
			}
			else
			{
				snprintf(str,
					 MAX_STR_LEN+1,
					 // TRANSLATORS: A <Race> Peasant has immigrated from <Town> in <King's Kingdom> to your village of <Town>.
					 // <Number> <Race> Peasants have immigrated from <Town> in <King's Kingdom> to your village of <Town>.
					 ngettext("%d %s Peasant has immigrated from %s in %s to your village of %s.",
						  "%d %s Peasants have immigrated from %s in %s to your village of %s.",
						  short_para4),
					 short_para4,
					 race_res[short_para3]->name,
					 town_res.get_name(short_para1),
					 nation_name1(),
					 town_res.get_name(short_para2));
			}
		}
		else
		{
			if( short_para5 )
			{
				snprintf(str,
					 MAX_STR_LEN+1,
					 // TRANSLATORS: A <Race> <Worker> has immigrated from <Town> to your village of <Town>.
					 // <Number> <Race> <Worker>s have immigrated from <Town> to your village of <Town>.
					 ngettext("%d %s %s has immigrated from %s to your village of %s.",
						  "%d %s %ss have immigrated from %s to your village of %s.",
						  short_para4),
					 short_para4,
					 race_res[short_para3]->name,
					 firm_res[short_para5]->worker_title,
					 town_res.get_name(short_para1),
					 town_res.get_name(short_para2));
			}
			else
			{
				snprintf(str,
					 MAX_STR_LEN+1,
					 // TRANSLATORS: A <Race> Peasant has immigrated from <Town> to your village of <Town>.
					 // <Number> <Race> Peasants have immigrated from <Town> to your village of <Town>.
					 ngettext("%d %s Peasant has immigrated from %s to your village of %s.",
						  "%d %s Peasants have immigrated from %s to your village of %s.",
						  short_para4),
					 short_para4,
					 race_res[short_para3]->name,
					 town_res.get_name(short_para1),
					 town_res.get_name(short_para2));
			}
		}
	}
}
Beispiel #2
0
std::string mtype::nname( unsigned int quantity ) const
{
    return ngettext( name.c_str(), name_plural.c_str(), quantity );
}
Beispiel #3
0
int vehicle::automatic_fire_turret( vehicle_part &pt )
{
    auto gun = turret_query( pt );
    if( gun.query() != turret_data::status::ready ) {
        return 0;
    }

    tripoint pos = global_part_pos3( pt );

    npc tmp;
    tmp.set_fake( true );
    tmp.name = rmp_format( _( "<veh_player>The %s" ), pt.name().c_str() );
    tmp.set_skill_level( gun.base()->gun_skill(), 8 );
    tmp.set_skill_level( skill_id( "gun" ), 4 );
    tmp.recoil = abs( velocity ) / 100 / 4;
    tmp.setpos( pos );
    tmp.str_cur = 16;
    tmp.dex_cur = 8;
    tmp.per_cur = 12;
    // Assume vehicle turrets are friendly to the player.
    tmp.attitude = NPCATT_FOLLOW;

    int area = aoe_size( gun.ammo_effects() );
    if( area > 0 ) {
        area += area == 1 ? 1 : 2; // Pad a bit for less friendly fire
    }

    tripoint targ = pos;
    auto &target = pt.target;
    if( target.first == target.second ) {
        // Manual target not set, find one automatically
        const bool u_see = g->u.sees( pos );
        int boo_hoo;

        // @todo calculate chance to hit and cap range based upon this
        int range = std::min( gun.range(), 12 );
        Creature *auto_target = tmp.auto_find_hostile_target( range, boo_hoo, area );
        if( auto_target == nullptr ) {
            if( u_see && boo_hoo ) {
                add_msg( m_warning, ngettext( "%s points in your direction and emits an IFF warning beep.",
                                              "%s points in your direction and emits %d annoyed sounding beeps.",
                                              boo_hoo ),
                         tmp.name.c_str(), boo_hoo );
            }
            return 0;
        }

        targ = auto_target->pos();
    } else if( target.first != target.second ) {
        // Target set manually
        // Make sure we didn't move between aiming and firing (it's a bug if we did)
        if( targ != target.first ) {
            target.second = target.first;
            return 0;
        }

        targ = target.second;
        // Remove the target
        target.second = target.first;
    } else {
        // Shouldn't happen
        target.first = target.second;
        return 0;
    }

    auto shots = gun.fire( tmp, targ );

    if( g->u.sees( pos ) && shots ) {
        add_msg( _( "The %1$s fires its %2$s!" ), name.c_str(), pt.name().c_str() );
    }

    return shots;
}
Beispiel #4
0
void Pickup::pick_one_up( const tripoint &pickup_target, item &newit, vehicle *veh,
                          int cargo_part, int index, int quantity, bool &got_water,
                          bool &offered_swap, PickupMap &mapPickup, bool autopickup )
{
    player &u = g->u;
    int moves_taken = 100;
    bool picked_up = false;
    pickup_answer option = CANCEL;
    item leftovers = newit;

    if( newit.invlet != '\0' &&
        u.invlet_to_position( newit.invlet ) != INT_MIN ) {
        // Existing invlet is not re-usable, remove it and let the code in player.cpp/inventory.cpp
        // add a new invlet, otherwise keep the (usable) invlet.
        newit.invlet = '\0';
    }

    if( quantity != 0 && newit.count_by_charges() ) {
        // Reinserting leftovers happens after item removal to avoid stacking issues.
        leftovers.charges = newit.charges - quantity;
        if( leftovers.charges > 0 ) {
            newit.charges = quantity;
        }
    } else {
        leftovers.charges = 0;
    }

    if( newit.made_of( LIQUID ) ) {
        got_water = true;
    } else if( !u.can_pickWeight( newit, false ) ) {
        add_msg( m_info, _( "The %s is too heavy!" ), newit.display_name().c_str() );
    } else if( newit.is_ammo() && ( newit.ammo_type() == ammotype( "arrow" ) ||
                                    newit.ammo_type() == ammotype( "bolt" ) ) ) {
        // @todo Make quiver code generic so that ammo pouches can use it too
        //add ammo to quiver
        int quivered = handle_quiver_insertion( newit, moves_taken, picked_up );

        if( quivered > 0 ) {
            quantity = quivered;
            //already picked up some for quiver so use special case handling
            picked_up = true;
            option = NUM_ANSWERS;
        }
        if( newit.charges > 0 ) {
            if( !u.can_pickVolume( newit ) ) {
                if( !autopickup ) {
                    // Silence some messaging if we're doing autopickup.
                    add_msg( m_info, ngettext( "There's no room in your inventory for the %s.",
                                               "There's no room in your inventory for the %s.",
                                               newit.charges ), newit.tname( newit.charges ).c_str() );
                }
            } else {
                // Add to inventory instead
                option = STASH;
            }
        }
        if( option == NUM_ANSWERS ) {
            //not picking up the rest so
            //update the charges for the item that gets re-added to the game map
            leftovers.charges = newit.charges;
        }
    } else if( newit.is_bucket() && !newit.is_container_empty() ) {
        if( !autopickup ) {
            const std::string &explain = string_format( _( "Can't stash %s while it's not empty" ),
                                         newit.display_name().c_str() );
            option = handle_problematic_pickup( newit, offered_swap, explain );
        } else {
            option = CANCEL;
        }
    } else if( !u.can_pickVolume( newit ) ) {
        if( !autopickup ) {
            const std::string &explain = string_format( _( "Not enough capacity to stash %s" ),
                                         newit.display_name().c_str() );
            option = handle_problematic_pickup( newit, offered_swap, explain );
        } else {
            option = CANCEL;
        }
    } else {
        option = STASH;
    }

    switch( option ) {
        case NUM_ANSWERS:
            // Some other option
            break;
        case CANCEL:
            picked_up = false;
            break;
        case WEAR:
            picked_up = u.wear_item( newit );
            break;
        case WIELD:
            picked_up = u.wield( newit );
            if( !picked_up ) {
                break;
            }

            if( u.weapon.invlet ) {
                add_msg( m_info, _( "Wielding %c - %s" ), u.weapon.invlet,
                         u.weapon.display_name().c_str() );
            } else {
                add_msg( m_info, _( "Wielding - %s" ), u.weapon.display_name().c_str() );
            }
            break;
        case SPILL:
            if( newit.is_container_empty() ) {
                debugmsg( "Tried to spill contents from an empty container" );
                break;
            }

            picked_up = newit.spill_contents( u );
            if( !picked_up ) {
                break;
            }
        // Intentional fallthrough
        case STASH:
            auto &entry = mapPickup[newit.tname()];
            entry.second += newit.count_by_charges() ? newit.charges : 1;
            entry.first = u.i_add( newit );
            picked_up = true;
            break;
    }

    if( picked_up ) {
        Pickup::remove_from_map_or_vehicle( pickup_target, veh, cargo_part, moves_taken, index );
    }
    if( leftovers.charges > 0 ) {
        bool to_map = veh == nullptr;
        if( !to_map ) {
            to_map = !veh->add_item( cargo_part, leftovers );
        }
        if( to_map ) {
            g->m.add_item_or_charges( pickup_target, leftovers );
        }
    }
}
Beispiel #5
0
static void
drag_data_received_callback (GtkWidget *widget,
		       	     GdkDragContext *context,
		       	     int x,
		       	     int y,
		       	     GtkSelectionData *data,
		             guint info,
		             guint32 time,
			     gpointer callback_data)
{
	char **names;
	NemoApplication *application;
	int name_count;
	NemoWindow *new_window, *window;
	GdkScreen      *screen;
	gboolean new_windows_for_extras;
	char *prompt;
	char *detail;
	GFile *location;
	NemoLocationBar *self = NEMO_LOCATION_BAR (widget);

	g_assert (data != NULL);
	g_assert (callback_data == NULL);

	names = g_uri_list_extract_uris ((const gchar *) gtk_selection_data_get_data (data));

	if (names == NULL || *names == NULL) {
		g_warning ("No D&D URI's");
		g_strfreev (names);
		gtk_drag_finish (context, FALSE, FALSE, time);
		return;
	}

	window = nemo_location_bar_get_window (widget);
	new_windows_for_extras = FALSE;
	/* Ask user if they really want to open multiple windows
	 * for multiple dropped URIs. This is likely to have been
	 * a mistake.
	 */
	name_count = g_strv_length (names);
	if (name_count > 1) {
		prompt = g_strdup_printf (ngettext("Do you want to view %d location?",
						   "Do you want to view %d locations?",
						   name_count),
					  name_count);
		detail = g_strdup_printf (ngettext("This will open %d separate window.",
						   "This will open %d separate windows.",
						   name_count),
					  name_count);
		/* eel_run_simple_dialog should really take in pairs
		 * like gtk_dialog_new_with_buttons() does. */
		new_windows_for_extras = eel_run_simple_dialog
			(GTK_WIDGET (window),
			 TRUE,
			 GTK_MESSAGE_QUESTION,
			 prompt,
			 detail,
			 GTK_STOCK_CANCEL, GTK_STOCK_OK,
			 NULL) != 0 /* GNOME_OK */;

		g_free (prompt);
		g_free (detail);

		if (!new_windows_for_extras) {
			g_strfreev (names);
			gtk_drag_finish (context, FALSE, FALSE, time);
			return;
		}
	}

	nemo_location_bar_set_location (self, names[0]);
	emit_location_changed (self);

	if (new_windows_for_extras) {
		int i;

		application = nemo_application_get_singleton ();
		screen = gtk_window_get_screen (GTK_WINDOW (window));

		for (i = 1; names[i] != NULL; ++i) {
			new_window = nemo_application_create_window (application, screen);
			location = g_file_new_for_uri (names[i]);
			nemo_window_go_to (new_window, location);
			g_object_unref (location);
		}
	}

	g_strfreev (names);

	gtk_drag_finish (context, TRUE, FALSE, time);
}
Beispiel #6
0
int store(dt_imageio_module_storage_t *self, dt_imageio_module_data_t *sdata, const int imgid,
          dt_imageio_module_format_t *format, dt_imageio_module_data_t *fdata, const int num, const int total,
          const gboolean high_quality, const gboolean upscale)
{
  dt_imageio_gallery_t *d = (dt_imageio_gallery_t *)sdata;

  char filename[PATH_MAX] = { 0 };
  char dirname[PATH_MAX] = { 0 };
  gboolean from_cache = FALSE;
  dt_image_full_path(imgid, dirname, sizeof(dirname), &from_cache);
  // we're potentially called in parallel. have sequence number synchronized:
  dt_pthread_mutex_lock(&darktable.plugin_threadsafe);
  {

    char tmp_dir[PATH_MAX] = { 0 };

    d->vp->filename = dirname;
    d->vp->jobcode = "export";
    d->vp->imgid = imgid;
    d->vp->sequence = num;
    dt_variables_expand(d->vp, d->filename, TRUE);

    gchar *result_tmp_dir = dt_variables_get_result(d->vp);
    g_strlcpy(tmp_dir, result_tmp_dir, sizeof(tmp_dir));
    g_free(result_tmp_dir);

    // if filenamepattern is a directory just let att ${FILE_NAME} as default..
    if(g_file_test(tmp_dir, G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)
       || ((d->filename + strlen(d->filename) - 1)[0] == '/'
           || (d->filename + strlen(d->filename) - 1)[0] == '\\'))
      snprintf(d->filename + strlen(d->filename), sizeof(d->filename) - strlen(d->filename), "/$(FILE_NAME)");

    // avoid braindead export which is bound to overwrite at random:
    if(total > 1 && !g_strrstr(d->filename, "$"))
    {
      snprintf(d->filename + strlen(d->filename), sizeof(d->filename) - strlen(d->filename), "_$(SEQUENCE)");
    }

    gchar *fixed_path = dt_util_fix_path(d->filename);
    g_strlcpy(d->filename, fixed_path, sizeof(d->filename));
    g_free(fixed_path);

    dt_variables_expand(d->vp, d->filename, TRUE);

    gchar *result_filename = dt_variables_get_result(d->vp);
    g_strlcpy(filename, result_filename, sizeof(filename));
    g_free(result_filename);

    g_strlcpy(dirname, filename, sizeof(dirname));

    const char *ext = format->extension(fdata);
    char *c = dirname + strlen(dirname);
    for(; c > dirname && *c != '/'; c--)
      ;
    if(*c == '/') *c = '\0';
    if(g_mkdir_with_parents(dirname, 0755))
    {
      fprintf(stderr, "[imageio_storage_gallery] could not create directory: `%s'!\n", dirname);
      dt_control_log(_("could not create directory `%s'!"), dirname);
      dt_pthread_mutex_unlock(&darktable.plugin_threadsafe);
      return 1;
    }

    // store away dir.
    snprintf(d->cached_dirname, sizeof(d->cached_dirname), "%s", dirname);

    c = filename + strlen(filename);
    for(; c > filename && *c != '.' && *c != '/'; c--)
      ;
    if(c <= filename || *c == '/') c = filename + strlen(filename);

    sprintf(c, ".%s", ext);

    // save image to list, in order:
    pair_t *pair = malloc(sizeof(pair_t));

    char *title = NULL, *description = NULL;
    GList *res_title, *res_desc;

    res_title = dt_metadata_get(imgid, "Xmp.dc.title", NULL);
    if(res_title)
    {
      title = res_title->data;
    }

    res_desc = dt_metadata_get(imgid, "Xmp.dc.description", NULL);
    if(res_desc)
    {
      description = res_desc->data;
    }

    char relfilename[PATH_MAX] = { 0 }, relthumbfilename[PATH_MAX] = { 0 };
    c = filename + strlen(filename);
    for(; c > filename && *c != '/'; c--)
      ;
    if(*c == '/') c++;
    if(c <= filename) c = filename;
    snprintf(relfilename, sizeof(relfilename), "%s", c);
    snprintf(relthumbfilename, sizeof(relthumbfilename), "%s", relfilename);
    c = relthumbfilename + strlen(relthumbfilename);
    for(; c > relthumbfilename && *c != '.'; c--)
      ;
    if(c <= relthumbfilename) c = relthumbfilename + strlen(relthumbfilename);
    sprintf(c, "-thumb.%s", ext);

    char subfilename[PATH_MAX] = { 0 }, relsubfilename[PATH_MAX] = { 0 };
    snprintf(subfilename, sizeof(subfilename), "%s", d->cached_dirname);
    char *sc = subfilename + strlen(subfilename);
    sprintf(sc, "/img_%d.html", num);
    snprintf(relsubfilename, sizeof(relsubfilename), "img_%d.html", num);

    snprintf(pair->line, sizeof(pair->line),
             "\n"
             "      <div><a class=\"dia\" rel=\"lightbox[viewer]\" title=\"%s - %s\" "
             "href=\"%s\"><span></span><img src=\"%s\" alt=\"img%d\" class=\"img\"/></a>\n"
             "      <h1>%s</h1>\n"
             "      %s</div>\n",
             title ? title : relfilename, description ? description : "&nbsp;", relfilename, relthumbfilename,
             num, title ? title : "&nbsp;", description ? description : "&nbsp;");

    char next[PATH_MAX] = { 0 };
    snprintf(next, sizeof(next), "img_%d.html", (num) % total + 1);

    char prev[PATH_MAX] = { 0 };
    snprintf(prev, sizeof(prev), "img_%d.html", (num == 1) ? total : num - 1);

    pair->pos = num;
    if(res_title) g_list_free_full(res_title, &g_free);
    if(res_desc) g_list_free_full(res_desc, &g_free);
    d->l = g_list_insert_sorted(d->l, pair, (GCompareFunc)sort_pos);
  } // end of critical block
  dt_pthread_mutex_unlock(&darktable.plugin_threadsafe);

  /* export image to file */
  if(dt_imageio_export(imgid, filename, format, fdata, high_quality, upscale, FALSE, self, sdata, num, total) != 0)
  {
    fprintf(stderr, "[imageio_storage_gallery] could not export to file: `%s'!\n", filename);
    dt_control_log(_("could not export to file `%s'!"), filename);
    return 1;
  }

  /* also export thumbnail: */
  // write with reduced resolution:
  const int max_width = fdata->max_width;
  const int max_height = fdata->max_height;
  fdata->max_width = 200;
  fdata->max_height = 200;
  // alter filename with -thumb:
  char *c = filename + strlen(filename);
  for(; c > filename && *c != '.' && *c != '/'; c--)
    ;
  if(c <= filename || *c == '/') c = filename + strlen(filename);
  const char *ext = format->extension(fdata);
  sprintf(c, "-thumb.%s", ext);
  if(dt_imageio_export(imgid, filename, format, fdata, FALSE, TRUE, FALSE, self, sdata, num, total) != 0)
  {
    fprintf(stderr, "[imageio_storage_gallery] could not export to file: `%s'!\n", filename);
    dt_control_log(_("could not export to file `%s'!"), filename);
    return 1;
  }
  // restore for next image:
  fdata->max_width = max_width;
  fdata->max_height = max_height;

  printf("[export_job] exported to `%s'\n", filename);
  char *trunc = filename + strlen(filename) - 32;
  if(trunc < filename) trunc = filename;
  dt_control_log(ngettext("%d/%d exported to `%s%s'", "%d/%d exported to `%s%s'", num),
                 num, total, trunc != filename ? ".." : "", trunc);
  return 0;
}
std::string item_comp::to_string( int batch ) const
{
    const int c = std::abs( count ) * batch;
    //~ <item-count> <item-name>
    return string_format( ngettext( "%d %s", "%d %s", c ), c, item::nname( type, c ).c_str() );
}
Beispiel #8
0
int
main (int argc, char **argv)
{
	int result = STATE_UNKNOWN;
	char input_buffer[MAX_INPUT_BUFFER];
	unsigned long latest_entry_time = 0L;
	unsigned long temp_entry_time = 0L;
	int proc_entries = 0;
	time_t current_time;
	char *temp_ptr;
	FILE *fp;
	int procuid = 0;
	int procpid = 0;
	int procppid = 0;
	int procvsz = 0;
	int procrss = 0;
	float procpcpu = 0;
	char procstat[8];
#ifdef PS_USES_PROCETIME
	char procetime[MAX_INPUT_BUFFER];
#endif /* PS_USES_PROCETIME */
	char procprog[MAX_INPUT_BUFFER];
	char *procargs;
	int pos, cols;
	int expected_cols = PS_COLS - 1;
	const char *zombie = "Z";
	char *temp_string;
	output chld_out, chld_err;
	size_t i;

	setlocale (LC_ALL, "");
	bindtextdomain (PACKAGE, LOCALEDIR);
	textdomain (PACKAGE);

	/* Parse extra opts if any */
	argv=np_extra_opts (&argc, argv, progname);

	if (process_arguments (argc, argv) == ERROR)
		usage_va(_("Could not parse arguments"));

	/* Set signal handling and alarm timeout */
	if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) {
		usage_va(_("Cannot catch SIGALRM"));
	}

	/* handle timeouts gracefully... */
	alarm (timeout_interval);

	/* open the status log */
	fp = fopen (status_log, "r");
	if (fp == NULL) {
		die (STATE_CRITICAL, "NAGIOS %s: %s\n", _("CRITICAL"), _("Cannot open status log for reading!"));
	}

	/* get the date/time of the last item updated in the log */
	while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
		if ((temp_ptr = strstr (input_buffer, "created=")) != NULL) {
			temp_entry_time = strtoul (temp_ptr + 8, NULL, 10);
			latest_entry_time = temp_entry_time;
			break;
		} else if ((temp_ptr = strtok (input_buffer, "]")) != NULL) {
			temp_entry_time = strtoul (temp_ptr + 1, NULL, 10);
			if (temp_entry_time > latest_entry_time)
				latest_entry_time = temp_entry_time;
		}
	}
	fclose (fp);

	if (verbose >= 2)
		printf("command: %s\n", PS_COMMAND);

	/* run the command to check for the Nagios process.. */
	if((result = np_runcmd(PS_COMMAND, &chld_out, &chld_err, 0)) != 0)
		result = STATE_WARNING;

	/* count the number of matching Nagios processes... */
	for(i = 0; i < chld_out.lines; i++) {
		cols = sscanf (chld_out.line[i], PS_FORMAT, PS_VARLIST);
		/* Zombie processes do not give a procprog command */
		if ( cols == (expected_cols - 1) && strstr(procstat, zombie) ) {
			cols = expected_cols;
			/* Set some value for procargs for the strip command further below
			 * Seen to be a problem on some Solaris 7 and 8 systems */
			chld_out.line[i][pos] = '\n';
			chld_out.line[i][pos+1] = 0x0;
		}
		if ( cols >= expected_cols ) {
			xasprintf (&procargs, "%s", chld_out.line[i] + pos);
			strip (procargs);

			/* Some ps return full pathname for command. This removes path */
			temp_string = strtok ((char *)procprog, "/");
			while (temp_string) {
				strcpy(procprog, temp_string);
				temp_string = strtok (NULL, "/");
			}

			/* May get empty procargs */
			if (!strstr(procargs, argv[0]) && strstr(procargs, process_string) && strcmp(procargs,"")) {
				proc_entries++;
				if (verbose >= 2) {
					printf (_("Found process: %s %s\n"), procprog, procargs);
				}
			}
		}
	}

	/* If we get anything on stderr, at least set warning */
	if(chld_err.buflen)
		result = max_state (result, STATE_WARNING);

	/* reset the alarm handler */
	alarm (0);

	if (proc_entries == 0) {
		die (STATE_CRITICAL, "NAGIOS %s: %s\n", _("CRITICAL"), _("Could not locate a running Nagios process!"));
	}

	if (latest_entry_time == 0L) {
		die (STATE_CRITICAL, "NAGIOS %s: %s\n", _("CRITICAL"), _("Cannot parse Nagios log file for valid time"));
	}

	time (&current_time);
	if ((int)(current_time - latest_entry_time) > (expire_minutes * 60)) {
		result = STATE_WARNING;
	} else {
		result = STATE_OK;
	}

	printf ("NAGIOS %s: ", (result == STATE_OK) ? _("OK") : _("WARNING"));
	printf (ngettext ("%d process", "%d processes", proc_entries), proc_entries);
	printf (", ");
	printf (
	  ngettext ("status log updated %d second ago",
	    "status log updated %d seconds ago",
	    (int) (current_time - latest_entry_time) ),
	    (int) (current_time - latest_entry_time) );
	printf ("\n");

	return result;
}
Beispiel #9
0
void test_pattern(int iCurrentPage, int iCurrentLine)
{
    std::vector<std::string> vMatchingItems;
    std::string sItemName = "";

    if (vAutoPickupRules[iCurrentPage][iCurrentLine].sRule == "") {
        return;
    }

    //Loop through all itemfactory items
    for (int i = 0; i < standard_itype_ids.size(); i++) {
        sItemName = item_controller->find_template(standard_itype_ids[i])->name;
        if (vAutoPickupRules[iCurrentPage][iCurrentLine].bActive && auto_pickup_match(sItemName, vAutoPickupRules[iCurrentPage][iCurrentLine].sRule)) {
            vMatchingItems.push_back(sItemName);
        }
    }

    const int iOffsetX = 15 + ((TERMX > FULL_SCREEN_WIDTH) ? (TERMX-FULL_SCREEN_WIDTH)/2 : 0);
    const int iOffsetY = 5 + ((TERMY > FULL_SCREEN_HEIGHT) ? (TERMY-FULL_SCREEN_HEIGHT)/2 : 0);

    int iStartPos = 0;
    const int iContentHeight = FULL_SCREEN_HEIGHT - 8;
    const int iContentWidth = FULL_SCREEN_WIDTH - 30;
    char ch;
    std::stringstream sTemp;

    WINDOW* w_test_rule_border = newwin(iContentHeight + 2, iContentWidth, iOffsetY, iOffsetX);
    WINDOW* w_test_rule_content = newwin(iContentHeight, iContentWidth - 2, 1 + iOffsetY, 1 + iOffsetX);

    wborder(w_test_rule_border, LINE_XOXO, LINE_XOXO, LINE_OXOX, LINE_OXOX, LINE_OXXO, LINE_OOXX, LINE_XXOO, LINE_XOOX);

    int nmatch = vMatchingItems.size();
    std::string buf = string_format(ngettext("%1$d item matches: %2$s", "%1$d items match: %2$s", nmatch), nmatch, vAutoPickupRules[iCurrentPage][iCurrentLine].sRule.c_str());
    mvwprintz(w_test_rule_border, 0, iContentWidth/2 - utf8_width(buf.c_str())/2, hilite(c_white), buf.c_str());

    wrefresh(w_test_rule_border);

    iCurrentLine = 0;

    do {
        // Clear the lines
        for (int i = 0; i < iContentHeight; i++) {
            for (int j = 0; j < 79; j++) {
                mvwputch(w_test_rule_content, i, j, c_black, ' ');
            }
        }

        calcStartPos(iStartPos, iCurrentLine, iContentHeight, vMatchingItems.size());

        // display auto pickup
        for (int i = iStartPos; i < vMatchingItems.size(); i++) {
            if (i >= iStartPos && i < iStartPos + ((iContentHeight > vMatchingItems.size()) ? vMatchingItems.size() : iContentHeight)) {
                nc_color cLineColor = c_white;

                sTemp.str("");
                sTemp << i + 1;
                mvwprintz(w_test_rule_content, i - iStartPos, 0, cLineColor, sTemp.str().c_str());
                mvwprintz(w_test_rule_content, i - iStartPos, 4, cLineColor, "");

                if (iCurrentLine == i) {
                    wprintz(w_test_rule_content, c_yellow, ">> ");
                } else {
                    wprintz(w_test_rule_content, c_yellow, "   ");
                }

                wprintz(w_test_rule_content, (iCurrentLine == i) ? hilite(cLineColor) : cLineColor, vMatchingItems[i].c_str());
            }
        }

        wrefresh(w_test_rule_content);

        ch = input();

        switch(ch) {
            case 'j': //move down
                iCurrentLine++;
                if (iCurrentLine >= vMatchingItems.size()) {
                    iCurrentLine = 0;
                }
                break;
            case 'k': //move up
                iCurrentLine--;
                if (iCurrentLine < 0) {
                    iCurrentLine = vMatchingItems.size()-1;
                }
                break;
        }
    } while(ch == 'j' || ch == 'k');

    werase(w_test_rule_border);
    werase(w_test_rule_content);
}
Beispiel #10
0
void
ap_assistant_menu_prepare (GtkAssistant *assistant, gpointer user_data)
{
    int nperiods;
    GDate period_begin, period_end, date_now;
    char * str;

    AcctPeriodInfo *info = user_data;

    ENTER ("info=%p", info);

    /* Pull info from widget, push into freq spec */
    //gnc_frequency_save_state (info->period_menu, info->period, &info->closing_date);
    recurrenceListFree(&info->period);
    gnc_frequency_save_to_recurrence(info->period_menu, &info->period, &info->closing_date);

    /* Count the number of periods that would be generated. */
    g_date_clear (&period_begin, 1);
    g_date_clear (&period_end, 1);
    g_date_clear (&date_now, 1);
    nperiods = 0;
    period_end = info->closing_date;
    gnc_gdate_set_time64 (&date_now, gnc_time (NULL));

    while (0 > g_date_compare(&period_end, &date_now ))
    {
        nperiods ++;
        PINFO ("Period = %d and End date is %d/%d/%d", nperiods,
               g_date_get_month(&period_end),
               g_date_get_day(&period_end),
               g_date_get_year(&period_end));
        period_begin = period_end;
        recurrenceListNextInstance(info->period, &period_begin, &period_end);

        /* FIXME Check for valid period_end, not sure why it won't be!!! */
        if (g_date_valid (&period_end) != TRUE)
            break;
    }

    /* Find the date of the earliest transaction in the current book.
     * Note that this could have changed since last time, since
     * we may have closed books since last time. */
    info->earliest = get_earliest_in_book (gnc_get_current_book());
    info->earliest_str = qof_print_date(info->earliest);
    PINFO ("Date of earliest transaction is %" G_GINT64_FORMAT " %s",
	   info->earliest, gnc_ctime (&info->earliest));

    /* Display the results */
    str = g_strdup_printf (
              /* Translators: %s is a date string. %d is the number of books
               * that will be created. This is a ngettext(3) message (but
               * only for the %d part). */
              ngettext("The earliest transaction date found in this book is %s. "
                       "Based on the selection made above, this book will be split "
                       "into %d book.",
                       "The earliest transaction date found in this book is %s. "
                       "Based on the selection made above, this book will be split "
                       "into %d books.",
                       nperiods),
              info->earliest_str,
              nperiods);
    gtk_label_set_text (GTK_LABEL(info->period_remarks), str);
    g_free (str);
}
Beispiel #11
0
void dt_lightroom_import (int imgid, dt_develop_t *dev, gboolean iauto)
{
    gboolean refresh_needed = FALSE;
    char imported[256] = {0};

    // Get full pathname
    char *pathname = dt_get_lightroom_xmp(imgid);

    if (!pathname)
    {
        if (!iauto) dt_control_log(_("cannot find lightroom XMP!"));
        return;
    }

    // Load LR xmp

    xmlDocPtr doc;
    xmlNodePtr entryNode;

    // Parse xml document

    doc = xmlParseEntity(pathname);

    if (doc == NULL)
    {
        g_free(pathname);
        return;
    }

    // Enter first node, xmpmeta

    entryNode = xmlDocGetRootElement(doc);

    if (entryNode == NULL)
    {
        g_free(pathname);
        xmlFreeDoc(doc);
        return;
    }

    if (xmlStrcmp(entryNode->name, (const xmlChar *)"xmpmeta"))
    {
        if (!iauto) dt_control_log(_("`%s' not a lightroom XMP!"), pathname);
        g_free(pathname);
        return;
    }

    // Check that this is really a Lightroom document

    xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);

    if (xpathCtx == NULL)
    {
        g_free(pathname);
        xmlFreeDoc(doc);
        return;
    }

    xmlXPathRegisterNs(xpathCtx, BAD_CAST "stEvt", BAD_CAST "http://ns.adobe.com/xap/1.0/sType/ResourceEvent#");

    xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression((const xmlChar *)"//@stEvt:softwareAgent", xpathCtx);

    if (xpathObj == NULL)
    {
        if (!iauto) dt_control_log(_("`%s' not a lightroom XMP!"), pathname);
        xmlXPathFreeContext(xpathCtx);
        g_free(pathname);
        xmlFreeDoc(doc);
        return;
    }

    xmlNodeSetPtr xnodes = xpathObj->nodesetval;

    if (xnodes != NULL && xnodes->nodeNr > 0)
    {
        xmlNodePtr xnode = xnodes->nodeTab[0];
        xmlChar *value = xmlNodeListGetString(doc, xnode->xmlChildrenNode, 1);

        if (!strstr((char *)value,"Lightroom"))
        {
            xmlXPathFreeContext(xpathCtx);
            xmlXPathFreeObject(xpathObj);
            xmlFreeDoc(doc);
            xmlFree(value);
            if (!iauto) dt_control_log(_("`%s' not a lightroom XMP!"), pathname);
            g_free(pathname);
            return;
        }
        xmlFree(value);
    }
    else
    {
        xmlXPathFreeObject(xpathObj);
        xmlXPathFreeContext(xpathCtx);
        if (!iauto) dt_control_log(_("`%s' not a lightroom XMP!"), pathname);
        g_free(pathname);
        return;
    }

    xmlXPathFreeObject(xpathObj);
    xmlXPathFreeContext(xpathCtx);

    // Go safely to Description node

    if (entryNode)
        entryNode = entryNode->xmlChildrenNode;
    if (entryNode)
        entryNode = entryNode->next;
    if (entryNode)
        entryNode = entryNode->xmlChildrenNode;
    if (entryNode)
        entryNode = entryNode->next;

    if (!entryNode || xmlStrcmp(entryNode->name, (const xmlChar *)"Description"))
    {
        if (!iauto) dt_control_log(_("`%s' not a lightroom XMP!"), pathname);
        g_free(pathname);
        return;
    }
    g_free(pathname);

    //  Look for attributes in the Description

    dt_iop_clipping_params_t pc;
    memset(&pc, 0, sizeof(pc));
    gboolean has_crop = FALSE;

    dt_iop_flip_params_t pf;
    memset(&pf, 0, sizeof(pf));
    gboolean has_flip = FALSE;

    dt_iop_exposure_params_t pe;
    memset(&pe, 0, sizeof(pe));
    gboolean has_exposure = FALSE;

    dt_iop_vignette_params_t pv;
    memset(&pv, 0, sizeof(pv));
    gboolean has_vignette = FALSE;

    dt_iop_grain_params_t pg;
    memset(&pg, 0, sizeof(pg));
    gboolean has_grain = FALSE;

    dt_iop_spots_params_t ps;
    memset(&ps, 0, sizeof(ps));
    gboolean has_spots = FALSE;

    typedef enum lr_curve_kind_t
    {
        linear = 0,
        medium_contrast = 1,
        string_contrast = 2,
        custom = 3
    } lr_curve_kind_t;

#define MAX_PTS 20
    dt_iop_tonecurve_params_t ptc;
    memset(&ptc, 0, sizeof(ptc));
    int ptc_value[4] = {0, 0, 0, 0};
    float ptc_split[3] = {0.0, 0.0, 0.0};
    lr_curve_kind_t curve_kind = linear;
    int curve_pts[MAX_PTS][2];
    int n_pts = 0;

    dt_iop_colorzones_params_t pcz;
    memset(&pcz, 0, sizeof(pcz));
    gboolean has_colorzones = FALSE;

    dt_iop_splittoning_params_t pst;
    memset(&pst, 0, sizeof(pst));
    gboolean has_splittoning = FALSE;

    dt_iop_bilat_params_t pbl;
    memset(&pbl, 0, sizeof(pbl));
    gboolean has_bilat = FALSE;

    gboolean has_tags = FALSE;

    int rating = 0;
    gboolean has_rating = FALSE;

    gdouble lat = 0, lon = 0;
    gboolean has_gps = FALSE;

    int color = 0;
    gboolean has_colorlabel = FALSE;

    float fratio = 0;                // factor ratio image
    float crop_roundness = 0;        // from lightroom
    int n_import = 0;                // number of iop imported
    const float hfactor = 3.0 / 9.0; // hue factor adjustment (use 3 out of 9 boxes in colorzones)
    const float lfactor = 4.0 / 9.0; // lightness factor adjustment (use 4 out of 9 boxes in colorzones)
    int iwidth = 0, iheight = 0;     // image width / height
    int orientation = 1;

    xmlAttr* attribute = entryNode->properties;

    while(attribute && attribute->name && attribute->children)
    {
        xmlChar* value = xmlNodeListGetString(entryNode->doc, attribute->children, 1);
        if (!xmlStrcmp(attribute->name, (const xmlChar *) "CropTop"))
            pc.cy = g_ascii_strtod((char *)value, NULL);
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "CropRight"))
            pc.cw = g_ascii_strtod((char *)value, NULL);
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "CropLeft"))
            pc.cx = g_ascii_strtod((char *)value, NULL);
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "CropBottom"))
            pc.ch = g_ascii_strtod((char *)value, NULL);
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "CropAngle"))
            pc.angle = -g_ascii_strtod((char *)value, NULL);
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "ImageWidth"))
            iwidth = atoi((char *)value);
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "ImageLength"))
            iheight = atoi((char *)value);
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "Orientation"))
        {
            orientation = atoi((char *)value);
            if (dev!=NULL &&
                    ((dev->image_storage.orientation == 6 && orientation != 6)
                     || (dev->image_storage.orientation == 5 && orientation != 8)
                     || (dev->image_storage.orientation == 0 && orientation != 1))) has_flip = TRUE;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "HasCrop"))
        {
            if (!xmlStrcmp(value, (const xmlChar *)"True"))
                has_crop = TRUE;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "Blacks2012"))
        {
            int v = atoi((char *)value);
            if (v != 0)
            {
                has_exposure = TRUE;
                pe.black = lr2dt_blacks((float)v);
            }
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "Exposure2012"))
        {
            float v = g_ascii_strtod((char *)value, NULL);
            if (v != 0.0)
            {
                has_exposure = TRUE;
                pe.exposure = lr2dt_exposure(v);
            }
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "PostCropVignetteAmount"))
        {
            int v = atoi((char *)value);
            if (v != 0)
            {
                has_vignette = TRUE;
                pv.brightness = lr2dt_vignette_gain((float)v);
            }
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "PostCropVignetteMidpoint"))
        {
            int v = atoi((char *)value);
            pv.scale = lr2dt_vignette_midpoint((float)v);
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "PostCropVignetteStyle"))
        {
            int v = atoi((char *)value);
            if (v == 1) // Highlight Priority
                pv.saturation = -0.300;
            else // Color Priority & Paint Overlay
                pv.saturation = -0.200;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "PostCropVignetteFeather"))
        {
            int v = atoi((char *)value);
            if (v != 0)
                pv.falloff_scale = (float)v;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "PostCropVignetteRoundness"))
        {
            int v = atoi((char *)value);
            crop_roundness = (float)v;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "GrainAmount"))
        {
            int v = atoi((char *)value);
            if (v != 0)
            {
                has_grain = TRUE;
                pg.strength = lr2dt_grain_amount((float)v);
            }
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "GrainFrequency"))
        {
            int v = atoi((char *)value);
            if (v != 0)
                pg.scale = lr2dt_grain_frequency((float)v);
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "ParametricShadows"))
        {
            ptc_value[0] = atoi((char *)value);
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "ParametricDarks"))
        {
            ptc_value[1] = atoi((char *)value);
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "ParametricLights"))
        {
            ptc_value[2] = atoi((char *)value);
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "ParametricHighlights"))
        {
            ptc_value[3] = atoi((char *)value);
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "ParametricShadowSplit"))
        {
            ptc_split[0] = g_ascii_strtod((char *)value, NULL) / 100.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "ParametricMidtoneSplit"))
        {
            ptc_split[1] = g_ascii_strtod((char *)value, NULL) / 100.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "ParametricHighlightSplit"))
        {
            ptc_split[2] = g_ascii_strtod((char *)value, NULL) / 100.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "ToneCurveName2012"))
        {
            if (!xmlStrcmp(value, (const xmlChar *)"Linear"))
                curve_kind = linear;
            else if (!xmlStrcmp(value, (const xmlChar *)"Medium Contrast"))
                curve_kind = medium_contrast;
            else if (!xmlStrcmp(value, (const xmlChar *)"Strong Contrast"))
                curve_kind = medium_contrast;
            else if (!xmlStrcmp(value, (const xmlChar *)"Custom"))
                curve_kind = custom;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "SaturationAdjustmentRed"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[1][0] = 0.5 + (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "SaturationAdjustmentOrange"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[1][1] = 0.5 + (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "SaturationAdjustmentYellow"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[1][2] = 0.5 + (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "SaturationAdjustmentGreen"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[1][3] = 0.5 + (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "SaturationAdjustmentAqua"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[1][4] = 0.5 + (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "SaturationAdjustmentBlue"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[1][5] = 0.5 + (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "SaturationAdjustmentPurple"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[1][6] = 0.5 + (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "SaturationAdjustmentMagenta"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[1][7] = 0.5 + (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "LuminanceAdjustmentRed"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[0][0] = 0.5 + lfactor * (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "LuminanceAdjustmentOrange"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[0][1] = 0.5 + lfactor * (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "LuminanceAdjustmentYellow"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[0][2] = 0.5 + lfactor * (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "LuminanceAdjustmentGreen"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[0][3] = 0.5 + lfactor * (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "LuminanceAdjustmentAqua"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[0][4] = 0.5 + lfactor * (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "LuminanceAdjustmentBlue"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[0][5] = 0.5 + lfactor * (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "LuminanceAdjustmentPurple"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[0][6] = 0.5 + lfactor * (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "LuminanceAdjustmentMagenta"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[0][7] = 0.5 + lfactor * (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "HueAdjustmentRed"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[2][0] = 0.5 + hfactor * (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "HueAdjustmentOrange"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[2][1] = 0.5 + hfactor * (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "HueAdjustmentYellow"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[2][2] = 0.5 + hfactor * (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "HueAdjustmentGreen"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[2][3] = 0.5 + hfactor * (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "HueAdjustmentAqua"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[2][4] = 0.5 + hfactor * (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "HueAdjustmentBlue"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[2][5] = 0.5 + hfactor * (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "HueAdjustmentPurple"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[2][6] = 0.5 + hfactor * (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "HueAdjustmentMagenta"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_colorzones = TRUE;
            pcz.equalizer_y[2][7] = 0.5 + hfactor * (float)v / 200.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "SplitToningShawowHue"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_splittoning = TRUE;
            pst.shadow_hue = (float)v / 255.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "SplitToningShawowSaturation"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_splittoning = TRUE;
            pst.shadow_saturation = (float)v / 100.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "SplitToningHighlightHue"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_splittoning = TRUE;
            pst.highlight_hue = (float)v / 255.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "SplitToningHighlightSaturation"))
        {
            int v = atoi((char *)value);
            if (v!=0)
                has_splittoning = TRUE;
            pst.highlight_saturation = (float)v / 100.0;
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "SplitToningBalance"))
        {
            float v = g_ascii_strtod((char *)value, NULL);
            pst.balance = lr2dt_splittoning_balance(v);
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "Clarity2012"))
        {
            int v = atoi((char *)value);
            if (v!=0)
            {
                has_bilat = TRUE;
                pbl.detail = lr2dt_clarity((float)v);
            }
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "Rating"))
        {
            int v = atoi((char *)value);
            if (v!=0)
            {
                rating = v;
                has_rating = TRUE;
            }
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "GPSLatitude"))
        {
            int deg;
            double msec;
            char d;

            if (sscanf((const char *)value, "%d,%lf%c", &deg, &msec, &d))
            {
                lat = deg + msec / 60.0;
                if (d == 'S') lat = -lat;
                has_gps = TRUE;
            }
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "GPSLongitude"))
        {
            int deg;
            double msec;
            char d;

            if (sscanf((const char *)value, "%d,%lf%c", &deg, &msec, &d))
            {
                lon = deg + msec / 60.0;
                if (d == 'W') lon = -lon;
                has_gps = TRUE;
            }
        }
        else if (!xmlStrcmp(attribute->name, (const xmlChar *) "Label"))
        {
            for(int i=0; value[i]; i++)
                value[i] = tolower(value[i]);

            if (!strcmp((char *)value, _("red")))
                color = 0;
            else if (!strcmp((char *)value, _("yellow")))
                color = 1;
            else if (!strcmp((char *)value, _("green")))
                color = 2;
            else if (!strcmp((char *)value, _("blue")))
                color = 3;
            else
                // just an else here to catch all other cases as on lightroom one can
                // change the names of labels. So purple and the user's defined labels
                // will be mapped to purple on darktable.
                color = 4;

            has_colorlabel = TRUE;
        }

        xmlFree(value);
        attribute = attribute->next;
    }

    //  Look for tags (subject/Bag/* and RetouchInfo/seq/*)

    entryNode = entryNode->xmlChildrenNode;
    if (entryNode) entryNode = entryNode->next;

    while (entryNode)
    {
        if (dev == NULL
                && (!xmlStrcmp(entryNode->name, (const xmlChar *) "subject")
                    ||!xmlStrcmp(entryNode->name, (const xmlChar *) "hierarchicalSubject")))
        {
            xmlNodePtr tagNode = entryNode;

            tagNode = tagNode->xmlChildrenNode;
            tagNode = tagNode->next;
            tagNode = tagNode->xmlChildrenNode;
            tagNode = tagNode->next;

            while (tagNode)
            {
                if (!xmlStrcmp(tagNode->name, (const xmlChar *) "li"))
                {
                    xmlChar *value= xmlNodeListGetString(doc, tagNode->xmlChildrenNode, 1);
                    guint tagid = 0;

                    if (!dt_tag_exists((char *)value, &tagid))
                        dt_tag_new((char *)value, &tagid);

                    dt_tag_attach(tagid, imgid);
                    has_tags = TRUE;
                    xmlFree(value);
                }
                tagNode = tagNode->next;
            }
        }
        else if (dev != NULL && !xmlStrcmp(entryNode->name, (const xmlChar *) "RetouchInfo"))
        {
            xmlNodePtr riNode = entryNode;

            riNode = riNode->xmlChildrenNode;
            riNode = riNode->next;
            riNode = riNode->xmlChildrenNode;
            riNode = riNode->next;

            while (riNode)
            {
                if (!xmlStrcmp(riNode->name, (const xmlChar *) "li"))
                {
                    xmlChar *value= xmlNodeListGetString(doc, riNode->xmlChildrenNode, 1);
                    spot_t *p = &ps.spot[ps.num_spots];
                    if (sscanf((const char *)value, "centerX = %f, centerY = %f, radius = %f, sourceState = %*[a-zA-Z], sourceX = %f, sourceY = %f", &(p->x), &(p->y), &(p->radius), &(p->xc), &(p->yc)))
                    {
                        ps.num_spots++;
                        has_spots = TRUE;
                    }
                    xmlFree(value);
                }
                if (ps.num_spots == MAX_SPOTS) break;
                riNode = riNode->next;
            }
        }
        else if (dev != NULL && !xmlStrcmp(entryNode->name, (const xmlChar *) "ToneCurvePV2012"))
        {
            xmlNodePtr tcNode = entryNode;

            tcNode = tcNode->xmlChildrenNode;
            tcNode = tcNode->next;
            tcNode = tcNode->xmlChildrenNode;
            tcNode = tcNode->next;

            while (tcNode)
            {
                if (!xmlStrcmp(tcNode->name, (const xmlChar *) "li"))
                {
                    xmlChar *value= xmlNodeListGetString(doc, tcNode->xmlChildrenNode, 1);

                    if (sscanf((const char *)value, "%d, %d", &(curve_pts[n_pts][0]), &(curve_pts[n_pts][1])))
                        n_pts++;
                    xmlFree(value);
                }
                if (n_pts == MAX_PTS) break;
                tcNode = tcNode->next;
            }
        }
        entryNode = entryNode->next;
    }

    xmlFreeDoc(doc);

    //  Integrates into the history all the imported iop

    if (dev != NULL && dt_image_is_raw(&dev->image_storage))
    {
        // set colorin to cmatrix which is the default from Adobe (so closer to what Lightroom does)
        dt_iop_colorin_params_t pci = (dt_iop_colorin_params_t)
        {
            "cmatrix", DT_INTENT_PERCEPTUAL
        };

        dt_add_hist (imgid, "colorin", (dt_iop_params_t *)&pci, sizeof(dt_iop_colorin_params_t), imported, sizeof(imported), LRDT_COLORIN_VERSION, &n_import);
        refresh_needed=TRUE;
    }

    if (dev != NULL && has_crop)
    {
        pc.k_sym = 0;
        pc.k_apply = 0;
        pc.crop_auto = 0;
        pc.k_h = pc.k_v = 0;
        pc.k_type = 0;
        pc.kxa = pc.kxd = 0.2f;
        pc.kxc = pc.kxb = 0.8f;
        pc.kya = pc.kyb = 0.2f;
        pc.kyc = pc.kyd = 0.8f;
        float tmp;

        if (has_crop)
        {
            // adjust crop data according to the rotation

            switch (dev->image_storage.orientation)
            {
            case 5: // portrait - counter-clockwise
                tmp = pc.ch;
                pc.ch = 1.0 - pc.cx;
                pc.cx = pc.cy;
                pc.cy = 1.0 - pc.cw;
                pc.cw = tmp;
                break;
            case 6: // portrait - clockwise
                tmp = pc.ch;
                pc.ch = pc.cw;
                pc.cw = 1.0 - pc.cy;
                pc.cy = pc.cx;
                pc.cx = 1.0 - tmp;
                break;
            default:
                break;
            }

            if (pc.angle != 0)
            {
                const float rangle = -pc.angle * (3.141592 / 180);
                float x, y;

                // do the rotation (rangle) using center of image (0.5, 0.5)

                x = pc.cx - 0.5;
                y = 0.5 - pc.cy;
                pc.cx = 0.5 + x * cos(rangle) - y * sin(rangle);
                pc.cy = 0.5 - (x * sin(rangle) + y * cos(rangle));

                x = pc.cw - 0.5;
                y = 0.5 - pc.ch;
                pc.cw = 0.5 + x * cos(rangle) - y * sin(rangle);
                pc.ch = 0.5 - (x * sin(rangle) + y * cos(rangle));
            }
        }
        else
        {
            pc.angle = 0;
            pc.cx = 0;
            pc.cy = 0;
            pc.cw = 1;
            pc.ch = 1;
        }

        fratio = (pc.cw - pc.cx) / (pc.ch - pc.cy);

        dt_add_hist (imgid, "clipping", (dt_iop_params_t *)&pc, sizeof(dt_iop_clipping_params_t), imported, sizeof(imported), LRDT_CLIPPING_VERSION, &n_import);
        refresh_needed=TRUE;
    }

    if (dev != NULL && has_flip)
    {
        pf.orientation = 0;

        if (dev->image_storage.orientation == 5)
            // portrait
            switch (orientation)
            {
            case 8:
                pf.orientation = 0;
                break;
            case 3:
                pf.orientation = 5;
                break;
            case 6:
                pf.orientation = 3;
                break;
            case 1:
                pf.orientation = 6;
                break;

            // with horizontal flip
            case 7:
                pf.orientation = 1;
                break;
            case 2:
                pf.orientation = 4;
                break;
            case 5:
                pf.orientation = 2;
                break;
            case 4:
                pf.orientation = 7;
                break;
            }

        else if (dev->image_storage.orientation == 6)
            // portrait
            switch (orientation)
            {
            case 8:
                pf.orientation = 3;
                break;
            case 3:
                pf.orientation = 6;
                break;
            case 6:
                pf.orientation = 0;
                break;
            case 1:
                pf.orientation = 5;
                break;

            // with horizontal flip
            case 7:
                pf.orientation = 2;
                break;
            case 2:
                pf.orientation = 7;
                break;
            case 5:
                pf.orientation = 1;
                break;
            case 4:
                pf.orientation = 4;
                break;
            }

        else
            // landscape
            switch (orientation)
            {
            case 8:
                pf.orientation = 5;
                break;
            case 3:
                pf.orientation = 3;
                break;
            case 6:
                pf.orientation = 6;
                break;
            case 1:
                pf.orientation = 0;
                break;

            // with horizontal flip
            case 7:
                pf.orientation = 7;
                break;
            case 2:
                pf.orientation = 1;
                break;
            case 5:
                pf.orientation = 4;
                break;
            case 4:
                pf.orientation = 2;
                break;
            }

        dt_add_hist (imgid, "flip", (dt_iop_params_t *)&pf, sizeof(dt_iop_flip_params_t), imported, sizeof(imported), LRDT_FLIP_VERSION, &n_import);
        refresh_needed=TRUE;
    }

    if (dev != NULL && has_exposure)
    {
        dt_add_hist (imgid, "exposure", (dt_iop_params_t *)&pe, sizeof(dt_iop_exposure_params_t), imported, sizeof(imported), LRDT_EXPOSURE_VERSION, &n_import);
        refresh_needed=TRUE;
    }

    if (dev != NULL && has_grain)
    {
        pg.channel = 0;

        dt_add_hist (imgid, "grain", (dt_iop_params_t *)&pg, sizeof(dt_iop_grain_params_t), imported, sizeof(imported), LRDT_GRAIN_VERSION, &n_import);
        refresh_needed=TRUE;
    }

    if (dev != NULL && has_vignette)
    {
        const float base_ratio = 1.325 / 1.5;

        pv.autoratio = FALSE;
        pv.dithering = DITHER_8BIT;
        pv.center.x = 0.0;
        pv.center.y = 0.0;
        pv.shape = 1.0;

        // defensive code, should not happen, but just in case future Lr version
        // has not ImageWidth/ImageLength XML tag.
        if (iwidth == 0 || iheight == 0)
            pv.whratio = base_ratio;
        else
            pv.whratio = base_ratio * ((float)iwidth / (float)iheight);

        if (has_crop)
            pv.whratio = pv.whratio * fratio;

        //  Adjust scale and ratio based on the roundness. On Lightroom changing
        //  the roundness change the width and the height of the vignette.

        if (crop_roundness > 0)
        {
            float newratio = pv.whratio - (pv.whratio - 1) * (crop_roundness / 100.0);
            float dscale = (1 - (newratio / pv.whratio)) / 2.0;

            pv.scale -= dscale * 100.0;
            pv.whratio = newratio;
        }

        dt_add_hist (imgid, "vignette", (dt_iop_params_t *)&pv, sizeof(dt_iop_vignette_params_t), imported, sizeof(imported), LRDT_VIGNETTE_VERSION, &n_import);
        refresh_needed=TRUE;
    }

    if (dev != NULL && has_spots)
    {
        // Check for orientation, rotate when in portrait mode
        if (orientation > 4)
            for (int k=0; k<ps.num_spots; k++)
            {
                float tmp = ps.spot[k].y;
                ps.spot[k].y  = 1.0 - ps.spot[k].x;
                ps.spot[k].x = tmp;
                tmp = ps.spot[k].yc;
                ps.spot[k].yc  = 1.0 - ps.spot[k].xc;
                ps.spot[k].xc = tmp;
            }

        dt_add_hist (imgid, "spots", (dt_iop_params_t *)&ps, sizeof(dt_iop_spots_params_t), imported, sizeof(imported), LRDT_SPOTS_VERSION, &n_import);
        refresh_needed=TRUE;
    }

    if (curve_kind != linear || ptc_value[0] != 0 || ptc_value[1] != 0 || ptc_value[2] != 0 || ptc_value[3] != 0)
    {
        ptc.tonecurve_nodes[ch_L] = 6;
        ptc.tonecurve_nodes[ch_a] = 7;
        ptc.tonecurve_nodes[ch_b] = 7;
        ptc.tonecurve_type[ch_L] = CUBIC_SPLINE;
        ptc.tonecurve_type[ch_a] = CUBIC_SPLINE;
        ptc.tonecurve_type[ch_b] = CUBIC_SPLINE;
        ptc.tonecurve_autoscale_ab = 1;
        ptc.tonecurve_preset = 0;

        float linear_ab[7] = {0.0, 0.08, 0.3, 0.5, 0.7, 0.92, 1.0};

        // linear a, b curves
        for(int k=0; k<7; k++) ptc.tonecurve[ch_a][k].x = linear_ab[k];
        for(int k=0; k<7; k++) ptc.tonecurve[ch_a][k].y = linear_ab[k];
        for(int k=0; k<7; k++) ptc.tonecurve[ch_b][k].x = linear_ab[k];
        for(int k=0; k<7; k++) ptc.tonecurve[ch_b][k].y = linear_ab[k];

        // Set the base tonecurve

        if (curve_kind == linear)
        {
            ptc.tonecurve[ch_L][0].x = 0.0;
            ptc.tonecurve[ch_L][0].y = 0.0;
            ptc.tonecurve[ch_L][1].x = ptc_split[0] / 2.0;
            ptc.tonecurve[ch_L][1].y = ptc_split[0] / 2.0;
            ptc.tonecurve[ch_L][2].x = ptc_split[1] - (ptc_split[1] - ptc_split[0]) / 2.0;
            ptc.tonecurve[ch_L][2].y = ptc_split[1] - (ptc_split[1] - ptc_split[0]) / 2.0;
            ptc.tonecurve[ch_L][3].x = ptc_split[1] + (ptc_split[2] - ptc_split[1]) / 2.0;
            ptc.tonecurve[ch_L][3].y = ptc_split[1] + (ptc_split[2] - ptc_split[1]) / 2.0;
            ptc.tonecurve[ch_L][4].x = ptc_split[2] + (1.0 - ptc_split[2]) / 2.0;
            ptc.tonecurve[ch_L][4].y = ptc_split[2] + (1.0 - ptc_split[2]) / 2.0;
            ptc.tonecurve[ch_L][5].x = 1.0;
            ptc.tonecurve[ch_L][5].y = 1.0;
        }
        else
        {
            for (int k=0; k<6; k++)
            {
                ptc.tonecurve[ch_L][k].x = curve_pts[k][0] / 255.0;
                ptc.tonecurve[ch_L][k].y = curve_pts[k][1] / 255.0;
            }
        }

        if (curve_kind != custom)
        {
            // set shadows/darks/lights/highlight adjustments

            ptc.tonecurve[ch_L][1].y += ptc.tonecurve[ch_L][1].y * ((float)ptc_value[0] / 100.0);
            ptc.tonecurve[ch_L][2].y += ptc.tonecurve[ch_L][1].y * ((float)ptc_value[1] / 100.0);
            ptc.tonecurve[ch_L][3].y += ptc.tonecurve[ch_L][1].y * ((float)ptc_value[2] / 100.0);
            ptc.tonecurve[ch_L][4].y += ptc.tonecurve[ch_L][1].y * ((float)ptc_value[3] / 100.0);

            if (ptc.tonecurve[ch_L][1].y > ptc.tonecurve[ch_L][2].y)
                ptc.tonecurve[ch_L][1].y = ptc.tonecurve[ch_L][2].y;
            if (ptc.tonecurve[ch_L][3].y > ptc.tonecurve[ch_L][4].y)
                ptc.tonecurve[ch_L][4].y = ptc.tonecurve[ch_L][3].y;
        }

        dt_add_hist (imgid, "tonecurve",  (dt_iop_params_t *)&ptc, sizeof(dt_iop_tonecurve_params_t), imported, sizeof(imported), LRDT_TONECURVE_VERSION, &n_import);
        refresh_needed=TRUE;
    }

    if (dev != NULL && has_colorzones)
    {
        pcz.channel = DT_IOP_COLORZONES_h;

        for (int i=0; i<3; i++)
            for (int k=0; k<8; k++)
                pcz.equalizer_x[i][k] = k/(DT_IOP_COLORZONES_BANDS-1.0);

        dt_add_hist (imgid, "colorzones", (dt_iop_params_t *)&pcz, sizeof(dt_iop_colorzones_params_t), imported, sizeof(imported), LRDT_COLORZONES_VERSION, &n_import);
        refresh_needed=TRUE;
    }

    if (dev != NULL && has_splittoning)
    {
        pst.compress = 50.0;

        dt_add_hist (imgid, "splittoning", (dt_iop_params_t *)&pst, sizeof(dt_iop_splittoning_params_t), imported, sizeof(imported), LRDT_SPLITTONING_VERSION, &n_import);
        refresh_needed=TRUE;
    }

    if (dev != NULL && has_bilat)
    {
        pbl.sigma_r = 100.0;
        pbl.sigma_s = 100.0;

        dt_add_hist (imgid, "bilat", (dt_iop_params_t *)&pbl, sizeof(dt_iop_bilat_params_t), imported, sizeof(imported), LRDT_BILAT_VERSION, &n_import);
        refresh_needed=TRUE;
    }

    if (has_tags)
    {
        if (imported[0]) g_strlcat(imported, ", ", sizeof(imported));
        g_strlcat(imported, _("tags"), sizeof(imported));
        n_import++;
    }

    if (dev == NULL && has_rating)
    {
        dt_ratings_apply_to_image(imgid, rating);

        if (imported[0]) g_strlcat(imported, ", ", sizeof(imported));
        g_strlcat(imported, _("rating"), sizeof(imported));
        n_import++;
    }

    if (dev == NULL && has_gps)
    {
        dt_image_set_location(imgid, lon, lat);

        if (imported[0]) g_strlcat(imported, ", ", sizeof(imported));
        g_strlcat(imported, _("geotagging"), sizeof(imported));
        n_import++;
    }

    if (dev == NULL && has_colorlabel)
    {
        dt_colorlabels_set_label(imgid, color);

        if (imported[0]) g_strlcat(imported, ", ", sizeof(imported));
        g_strlcat(imported, _("color label"), sizeof(imported));
        n_import++;
    }

    if(dev != NULL && refresh_needed && dev->gui_attached)
    {
        char message[512];

        g_snprintf
        (message, sizeof(message),
         ngettext("%s has been imported", "%s have been imported", n_import), imported);
        dt_control_log(message);

        if (!iauto)
        {
            /* signal history changed */
            dt_dev_reload_history_items(dev);
            dt_dev_modulegroups_set(darktable.develop, dt_dev_modulegroups_get(darktable.develop));
            /* update xmp file */
            dt_image_synch_xmp(imgid);
            dt_control_signal_raise(darktable.signals,DT_SIGNAL_DEVELOP_HISTORY_CHANGE);
        }
    }
}
Beispiel #12
0
char* fm_file_size_to_str( char* buf, goffset size, gboolean si_prefix )
{
    const char * unit;
    gdouble val;

	if( si_prefix ) /* 1000 based SI units */
	{
		if(size < (goffset)SI_KB)
		{
			sprintf( buf, ngettext("%u byte", "%u bytes", (guint)size), (guint)size);
			return buf;
		}
		val = (gdouble)size;
		if(val < SI_MB)
		{
			val /= SI_KB;
			unit = _("KB");
		}
		else if(val < SI_GB)
		{
			val /= SI_MB;
			unit = _("MB");
		}
		else if(val < SI_TB)
		{
			val /= SI_GB;
			unit = _("GB");
		}
		else
		{
			val /= SI_TB;
			unit = _("TB");
		}
	}
	else /* 1024-based binary prefix */
	{
		if(size < (goffset)BI_KiB)
		{
			sprintf( buf, ngettext("%u byte", "%u bytes", (guint)size), (guint)size);
			return buf;
		}
		val = (gdouble)size;
		if(val < BI_MiB)
		{
			val /= BI_KiB;
			unit = _("KiB");
		}
		else if(val < BI_GiB)
		{
			val /= BI_MiB;
			unit = _("MiB");
		}
		else if(val < BI_TiB)
		{
			val /= BI_GiB;
			unit = _("GiB");
		}
		else
		{
			val /= BI_TiB;
			unit = _("TiB");
		}
	}
    sprintf( buf, "%.1f %s", val, unit );
	return buf;
}
Beispiel #13
0
void safemode::test_pattern( const int tab_in, const int row_in )
{
    std::vector<std::string> creature_list;
    std::string creature_name;

    auto &temp_rules = ( tab_in == GLOBAL_TAB ) ? global_rules : character_rules;

    if( temp_rules[row_in].rule.empty() ) {
        return;
    }

    if( g->u.name.empty() ) {
        popup( _( "No monsters loaded. Please start a game first." ) );
        return;
    }

    //Loop through all monster mtypes
    for( const auto &mtype : MonsterGenerator::generator().get_all_mtypes() ) {
        creature_name = mtype.nname();
        if( wildcard_match( creature_name, temp_rules[row_in].rule ) ) {
            creature_list.push_back( creature_name );
        }
    }

    const int offset_x = 15 + ( ( TERMX > FULL_SCREEN_WIDTH ) ? ( TERMX - FULL_SCREEN_WIDTH ) / 2 : 0 );
    const int offset_y = 5 + ( ( TERMY > FULL_SCREEN_HEIGHT ) ? ( TERMY - FULL_SCREEN_HEIGHT ) / 2 :
                               0 );

    int start_pos = 0;
    const int content_height = FULL_SCREEN_HEIGHT - 8;
    const int content_width = FULL_SCREEN_WIDTH - 30;

    WINDOW *w_test_rule_border = newwin( content_height + 2, content_width, offset_y, offset_x );
    WINDOW_PTR w_test_rule_borderptr( w_test_rule_border );
    WINDOW *w_test_rule_content = newwin( content_height, content_width - 2, 1 + offset_y,
                                          1 + offset_x );
    WINDOW_PTR w_test_rule_contentptr( w_test_rule_content );

    draw_border( w_test_rule_border );

    int nmatch = creature_list.size();
    std::string buf = string_format( ngettext( "%1$d monster matches: %2$s",
                                     "%1$d monsters match: %2$s",
                                     nmatch ), nmatch, temp_rules[row_in].rule.c_str() );
    mvwprintz( w_test_rule_border, 0, content_width / 2 - utf8_width( buf ) / 2, hilite( c_white ),
               "%s", buf.c_str() );

    mvwprintz( w_test_rule_border, content_height + 1, 1, red_background( c_white ),
               _( "Lists monsters regardless of their attitude." ) );

    wrefresh( w_test_rule_border );

    int line = 0;

    input_context ctxt( "SAFEMODE_TEST" );
    ctxt.register_updown();
    ctxt.register_action( "QUIT" );

    while( true ) {
        // Clear the lines
        for( int i = 0; i < content_height; i++ ) {
            for( int j = 0; j < 79; j++ ) {
                mvwputch( w_test_rule_content, i, j, c_black, ' ' );
            }
        }

        calcStartPos( start_pos, line, content_height, creature_list.size() );

        // display safe mode
        for( int i = start_pos; i < ( int )creature_list.size(); i++ ) {
            if( i >= start_pos &&
                i < start_pos + std::min( content_height, static_cast<int>( creature_list.size() ) ) ) {
                nc_color line_color = c_white;

                mvwprintz( w_test_rule_content, i - start_pos, 0, line_color, "%d", i + 1 );
                mvwprintz( w_test_rule_content, i - start_pos, 4, line_color, "" );

                wprintz( w_test_rule_content, c_yellow, ( line == i ) ? ">> " : "   " );

                wprintz( w_test_rule_content, ( line == i ) ? hilite( line_color ) : line_color, "%s",
                         creature_list[i].c_str() );
            }
        }

        wrefresh( w_test_rule_content );

        const std::string action = ctxt.handle_input();
        if( action == "DOWN" ) {
            line++;
            if( line >= ( int )creature_list.size() ) {
                line = 0;
            }
        } else if( action == "UP" ) {
            line--;
            if( line < 0 ) {
                line = creature_list.size() - 1;
            }
        } else {
            break;
        }
    }
}
Beispiel #14
0
gint proc_mbox(FolderItem *dest, const gchar *mbox, gboolean apply_filter,
	       PrefsAccount *account)
/* return values: -1 error, >=0 number of msgs added */
{
	FILE *mbox_fp;
	gchar buf[MESSAGEBUFSIZE];
	gchar *tmp_file;
	gint msgs = 0;
	gint lines;
	MsgInfo *msginfo;
	gboolean more;
	GSList *to_filter = NULL, *filtered = NULL, *unfiltered = NULL, *cur, *to_add = NULL;
	gboolean printed = FALSE;
	FolderItem *dropfolder;

	cm_return_val_if_fail(dest != NULL, -1);
	cm_return_val_if_fail(mbox != NULL, -1);

	debug_print("Getting messages from %s into %s...\n", mbox, dest->path);

	if ((mbox_fp = g_fopen(mbox, "rb")) == NULL) {
		FILE_OP_ERROR(mbox, "fopen");
		alertpanel_error(_("Could not open mbox file:\n%s\n"), mbox);
		return -1;
	}

	/* ignore empty lines on the head */
	do {
		if (fgets(buf, sizeof(buf), mbox_fp) == NULL) {
			g_warning("can't read mbox file.\n");
			fclose(mbox_fp);
			return -1;
		}
	} while (buf[0] == '\n' || buf[0] == '\r');

	if (strncmp(buf, "From ", 5) != 0) {
		g_warning("invalid mbox format: %s\n", mbox);
		fclose(mbox_fp);
		return -1;
	}

	tmp_file = get_tmp_file();

	folder_item_update_freeze();

	if (apply_filter)
		dropfolder = folder_get_default_processing();
	else
		dropfolder = dest;
	
	do {
		FILE *tmp_fp;
		gint empty_lines;
		gint msgnum;
		
		if (msgs > 0 && msgs%500 == 0) {
			if (printed)
				statusbar_pop_all();
			statusbar_print_all(
					ngettext("Importing from mbox... (%d mail imported)",
						"Importing from mbox... (%d mails imported)", msgs), msgs);
			printed=TRUE;
			GTK_EVENTS_FLUSH();
		}
	
		if ((tmp_fp = g_fopen(tmp_file, "wb")) == NULL) {
			FILE_OP_ERROR(tmp_file, "fopen");
			g_warning("can't open temporary file\n");
			fclose(mbox_fp);
			g_free(tmp_file);
			return -1;
		}
		if (change_file_mode_rw(tmp_fp, tmp_file) < 0) {
			FILE_OP_ERROR(tmp_file, "chmod");
		}

		empty_lines = 0;
		lines = 0;

		/* process all lines from mboxrc file */
		while (fgets(buf, sizeof(buf), mbox_fp) != NULL) {
			int offset;

			/* eat empty lines */
			if (buf[0] == '\n' || buf[0] == '\r') {
				empty_lines++;
				continue;
			}

			/* From separator or quoted From */
			offset = 0;
			/* detect leading '>' char(s) */
			while ((buf[offset] == '>')) {
				offset++;
			}
			if (!strncmp(buf+offset, "From ", 5)) {
				/* From separator: */
				if (offset == 0) {
					/* expect next mbox item */
					break;
				}

				/* quoted From: */
				/* flush any eaten empty line */
				if (empty_lines > 0) {
					while (empty_lines-- > 0) {
						FPUTS_TO_TMP_ABORT_IF_FAIL("\n");
				}
					empty_lines = 0;
				}
				/* store the unquoted line */
				FPUTS_TO_TMP_ABORT_IF_FAIL(buf + 1);
				continue;
			}

			/* other line */
			/* flush any eaten empty line */
			if (empty_lines > 0) {			
				while (empty_lines-- > 0) {
					FPUTS_TO_TMP_ABORT_IF_FAIL("\n");
			}
				empty_lines = 0;
			}
			/* store the line itself */
					FPUTS_TO_TMP_ABORT_IF_FAIL(buf);
		}
		/* end of mbox item or end of mbox */

		/* flush any eaten empty line (but the last one) */
		if (empty_lines > 0) {
			while (--empty_lines > 0) {
				FPUTS_TO_TMP_ABORT_IF_FAIL("\n");
			}
		}

		/* more emails to expect? */
		more = !feof(mbox_fp);

		/* warn if email part is empty (it's the minimum check 
		   we can do */
		if (lines == 0) {
			g_warning("malformed mbox: %s: message %d is empty\n", mbox, msgs);
			fclose(tmp_fp);
			fclose(mbox_fp);
			claws_unlink(tmp_file);
			return -1;
		}

		if (fclose(tmp_fp) == EOF) {
			FILE_OP_ERROR(tmp_file, "fclose");
			g_warning("can't write to temporary file\n");
			fclose(mbox_fp);
			claws_unlink(tmp_file);
			g_free(tmp_file);
			return -1;
		}

		if (apply_filter) {
			if ((msgnum = folder_item_add_msg(dropfolder, tmp_file, NULL, TRUE)) < 0) {
				fclose(mbox_fp);
				claws_unlink(tmp_file);
				g_free(tmp_file);
				return -1;
			}
			msginfo = folder_item_get_msginfo(dropfolder, msgnum);
			to_filter = g_slist_prepend(to_filter, msginfo);
		} else {
			MsgFileInfo *finfo = g_new0(MsgFileInfo, 1);
			finfo->file = tmp_file;
			
			to_add = g_slist_prepend(to_add, finfo);
			tmp_file = get_tmp_file();
			
			/* flush every 500 */
			if (msgs > 0 && msgs % 500 == 0) {
				folder_item_add_msgs(dropfolder, to_add, TRUE);
				procmsg_message_file_list_free(to_add);
				to_add = NULL;
			}
		}
		msgs++;
	} while (more);

	if (printed)
		statusbar_pop_all();

	if (apply_filter) {

		folder_item_set_batch(dropfolder, FALSE);
		procmsg_msglist_filter(to_filter, account, 
				&filtered, &unfiltered, TRUE);
		folder_item_set_batch(dropfolder, TRUE);

		filtering_move_and_copy_msgs(to_filter);
		for (cur = filtered; cur; cur = g_slist_next(cur)) {
			MsgInfo *info = (MsgInfo *)cur->data;
			procmsg_msginfo_free(info);
		}

		unfiltered = g_slist_reverse(unfiltered);
		if (unfiltered) {
			folder_item_move_msgs(dest, unfiltered);
			for (cur = unfiltered; cur; cur = g_slist_next(cur)) {
				MsgInfo *info = (MsgInfo *)cur->data;
				procmsg_msginfo_free(info);
			}
		}

		g_slist_free(unfiltered);
		g_slist_free(filtered);
		g_slist_free(to_filter);
	} else if (to_add) {
		folder_item_add_msgs(dropfolder, to_add, TRUE);
		procmsg_message_file_list_free(to_add);
		to_add = NULL;
	}

	folder_item_update_thaw();
	
	g_free(tmp_file);
	fclose(mbox_fp);
	debug_print("%d messages found.\n", msgs);

	return msgs;
}
static void
getStatusString( GString           * gstr,
                 const tr_torrent  * tor,
                 const tr_stat     * st,
                 const double        uploadSpeed_KBps,
                 const double        downloadSpeed_KBps )
{
    if( st->error )
    {
        const char * fmt[] = { NULL, N_( "Tracker gave a warning: \"%s\"" ),
                                     N_( "Tracker gave an error: \"%s\"" ),
                                     N_( "Error: %s" ) };
        g_string_append_printf( gstr, _( fmt[st->error] ), st->errorString );
    }
    else switch( st->activity )
    {
        case TR_STATUS_STOPPED:
        case TR_STATUS_CHECK_WAIT:
        case TR_STATUS_CHECK:
        case TR_STATUS_DOWNLOAD_WAIT:
        case TR_STATUS_SEED_WAIT:
        {
            getShortStatusString( gstr, tor, st, uploadSpeed_KBps, downloadSpeed_KBps );
            break;
        }

        case TR_STATUS_DOWNLOAD:
        {
            if( tr_torrentHasMetadata( tor ) )
            {
                g_string_append_printf( gstr,
                    ngettext( "Downloading from %1$'d of %2$'d connected peer",
                              "Downloading from %1$'d of %2$'d connected peers",
                              st->webseedsSendingToUs + st->peersSendingToUs ),
                    st->webseedsSendingToUs + st->peersSendingToUs,
                    st->webseedsSendingToUs + st->peersConnected );
            }
            else
            {
                g_string_append_printf( gstr,
                    ngettext( "Downloading metadata from %1$'d peer (%2$d%% done)",
                              "Downloading metadata from %1$'d peers (%2$d%% done)",
                              st->peersConnected + st->peersConnected ),
                    st->peersConnected + st->webseedsSendingToUs,
                    (int)(100.0*st->metadataPercentComplete) );
            }
            break;
        }

        case TR_STATUS_SEED:
            g_string_append_printf( gstr,
                ngettext( "Seeding to %1$'d of %2$'d connected peer",
                          "Seeding to %1$'d of %2$'d connected peers",
                          st->peersConnected ),
                st->peersGettingFromUs,
                st->peersConnected );
                break;
    }

    if( ( st->activity != TR_STATUS_CHECK_WAIT ) &&
        ( st->activity != TR_STATUS_CHECK ) &&
        ( st->activity != TR_STATUS_DOWNLOAD_WAIT ) &&
        ( st->activity != TR_STATUS_SEED_WAIT ) &&
        ( st->activity != TR_STATUS_STOPPED ) )
    {
        char buf[256];
        getShortTransferString( tor, st, uploadSpeed_KBps, downloadSpeed_KBps, buf, sizeof( buf ) );
        if( *buf )
            g_string_append_printf( gstr, " - %s", buf );
    }
}
Beispiel #16
0
void linphone_gtk_call_log_update(GtkWidget *w){
	GtkTreeView *v=GTK_TREE_VIEW(linphone_gtk_get_widget(w,"logs_view"));
	GtkTreeStore *store;
	const MSList *logs;
	GtkTreeSelection *select;
	GtkWidget *notebook=linphone_gtk_get_widget(w,"viewswitch");
	gint nb;

	store=(GtkTreeStore*)gtk_tree_view_get_model(v);
	if (store==NULL){
		store=gtk_tree_store_new(3,G_TYPE_STRING,G_TYPE_STRING,G_TYPE_POINTER,G_TYPE_STRING);
		gtk_tree_view_set_model(v,GTK_TREE_MODEL(store));
		g_object_unref(G_OBJECT(store));
		fill_renderers(GTK_TREE_VIEW(linphone_gtk_get_widget(w,"logs_view")));
		select=gtk_tree_view_get_selection(v);
		gtk_tree_selection_set_mode(select, GTK_SELECTION_SINGLE);
		g_signal_connect_swapped(G_OBJECT(select),"changed",(GCallback)call_log_selection_changed,v);
		g_signal_connect(G_OBJECT(notebook),"focus-tab",(GCallback)linphone_gtk_call_log_reset_missed_call,NULL);
		g_signal_connect(G_OBJECT(v),"button-press-event",(GCallback)linphone_gtk_call_log_button_pressed,NULL);
	}
	nb=linphone_core_get_missed_calls_count(linphone_gtk_get_core());
	if(nb > 0)
		linphone_gtk_call_log_display_missed_call(nb);
	gtk_tree_store_clear (store);

	for (logs=linphone_core_get_call_logs(linphone_gtk_get_core());logs!=NULL;logs=logs->next){
		LinphoneCallLog *cl=(LinphoneCallLog*)logs->data;
		GtkTreeIter iter, iter2;
		LinphoneAddress *la=linphone_call_log_get_dir(cl)==LinphoneCallIncoming ? linphone_call_log_get_from(cl) : linphone_call_log_get_to(cl);
		char *addr= linphone_address_as_string(la);
		const char *display;
		gchar *logtxt, *headtxt, *minutes, *seconds;
		gchar quality[20];
		const char *status=NULL;
		gchar *start_date=NULL;
		LinphoneFriend *lf=NULL;
		int duration=linphone_call_log_get_duration(cl);
		time_t start_date_time=linphone_call_log_get_start_date(cl);
		const gchar *call_status_icon_name;

#if GLIB_CHECK_VERSION(2,30,0) // The g_date_time_format function exists since 2.26.0 but the '%c' format is only supported since 2.30.0
		if (start_date_time){
			GDateTime *dt=g_date_time_new_from_unix_local(start_date_time);
			start_date=g_date_time_format(dt,"%c");
			g_date_time_unref(dt);
		}
#else
		start_date=g_strdup(ctime(&start_date_time));
		if (start_date[strlen(start_date) - 1] == '\n') {
			start_date[strlen(start_date) - 1] = '\0';
		}
#endif
		lf=linphone_core_get_friend_by_address(linphone_gtk_get_core(),addr);
		if(lf != NULL){
			/*update display name from friend*/
			display = linphone_friend_get_name(lf);
			if (display != NULL) linphone_address_set_display_name(la, display);
		} else {
			display=linphone_address_get_display_name(la);
		}
		if (display==NULL){
			display=linphone_address_get_username (la);
			if (display==NULL){
				display=linphone_address_get_domain (la);
			}
		}

		if (linphone_call_log_get_quality(cl)!=-1){
			snprintf(quality,sizeof(quality),"%.1f",linphone_call_log_get_quality(cl));
		}else snprintf(quality,sizeof(quality)-1,"%s",_("n/a"));
		switch(linphone_call_log_get_status(cl)){
			case LinphoneCallAborted:
				status=_("Aborted");
			break;
			case LinphoneCallMissed:
				status=_("Missed");
			break;
			case LinphoneCallDeclined:
				status=_("Declined");
			break;
			default:
			break;
		}
		minutes=g_markup_printf_escaped(
			ngettext("%i minute", "%i minutes", duration/60),
			duration/60);
		seconds=g_markup_printf_escaped(
			ngettext("%i second", "%i seconds", duration%60),
			duration%60);
		if (status==NULL) {
				headtxt=g_markup_printf_escaped("<big><b>%s</b></big>\t%s",display,start_date ? start_date : "");
				logtxt=g_markup_printf_escaped(
				_("<small><i>%s</i>\t"
				  "<i>Quality: %s</i></small>\n%s\t%s\t"),
				addr, quality, minutes, seconds);
		} else {
			headtxt=g_markup_printf_escaped(_("<big><b>%s</b></big>\t%s"),display,start_date ? start_date : "");
			logtxt=g_markup_printf_escaped(
			"<small><i>%s</i></small>\t"
				"\n%s",addr, status);
		}
		g_free(minutes);
		g_free(seconds);
		if (start_date) g_free(start_date);
		gtk_tree_store_append (store,&iter,NULL);
		call_status_icon_name = linphone_call_log_get_dir(cl) == LinphoneCallOutgoing ?
			"linphone-call-status-outgoing" : "linphone-call-status-incoming";
		gtk_tree_store_set (store,&iter,
		               0, call_status_icon_name,
		               1, headtxt,2,cl,-1);
		gtk_tree_store_append (store,&iter2,&iter);
		gtk_tree_store_set (store,&iter2,1,logtxt,-1);
		ms_free(addr);
		g_free(logtxt);
		g_free(headtxt);
	}
}
static void
pd_update_general_tab (EomPropertiesDialog *prop_dlg,
                       EomImage            *image)
{
    gchar *bytes_str, *dir_str, *uri_str;
    gchar *width_str, *height_str;
    GFile *file;
    GFileInfo *file_info;
    const char *mime_str;
    char *type_str;
    gint width, height;
    goffset bytes;

    g_object_set (G_OBJECT (prop_dlg->priv->thumbnail_image),
                  "pixbuf", eom_image_get_thumbnail (image),
                  NULL);

    gtk_label_set_text (GTK_LABEL (prop_dlg->priv->name_label),
                        eom_image_get_caption (image));

    eom_image_get_size (image, &width, &height);

    width_str = g_strdup_printf ("%d %s", width,
                                 ngettext ("pixel", "pixels", width));
    height_str = g_strdup_printf ("%d %s", height,
                                  ngettext ("pixel", "pixels", height));

    gtk_label_set_text (GTK_LABEL (prop_dlg->priv->width_label), width_str);

    gtk_label_set_text (GTK_LABEL (prop_dlg->priv->height_label),
                        height_str);

    g_free (height_str);
    g_free (width_str);

    file = eom_image_get_file (image);
    file_info = g_file_query_info (file,
                                   G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
                                   0, NULL, NULL);
    if (file_info == NULL) {
        type_str = g_strdup (_("Unknown"));
    } else {
        mime_str = g_file_info_get_content_type (file_info);
        type_str = g_content_type_get_description (mime_str);
        g_object_unref (file_info);
    }

    gtk_label_set_text (GTK_LABEL (prop_dlg->priv->type_label), type_str);

    bytes = eom_image_get_bytes (image);
    bytes_str = g_format_size_for_display (bytes);

    gtk_label_set_text (GTK_LABEL (prop_dlg->priv->bytes_label), bytes_str);

    uri_str = eom_image_get_uri_for_display (image);
    dir_str = g_path_get_dirname (uri_str);
    gtk_label_set_text (GTK_LABEL (prop_dlg->priv->location_label),
                        dir_str);

    g_free (type_str);
    g_free (bytes_str);
    g_free (dir_str);
    g_free (uri_str);
}
Beispiel #18
0
static gint inc_start(IncProgressDialog *inc_dialog)
{
	IncSession *session;
	GList *qlist;
	Pop3Session *pop3_session;
	IncState inc_state;
	gint error_num = 0;
	gint new_msgs = 0;
	gchar *msg;
	gchar *fin_msg;
	FolderItem *processing, *inbox;
	GSList *msglist, *msglist_element;
	gboolean cancelled = FALSE;

	qlist = inc_dialog->queue_list;
	while (qlist != NULL) {
		GList *next = qlist->next;

		session = qlist->data;
		pop3_session = POP3_SESSION(session->session); 
		pop3_session->user = g_strdup(pop3_session->ac_prefs->userid);
		if (pop3_session->ac_prefs->passwd)
			pop3_session->pass =
				g_strdup(pop3_session->ac_prefs->passwd);
		else {
			gchar *pass;

			if (inc_dialog->show_dialog)
				manage_window_focus_in
					(inc_dialog->dialog->window,
					 NULL, NULL);

			pass = input_dialog_query_password_keep
				(pop3_session->ac_prefs->recv_server,
				 pop3_session->user,
				 &(pop3_session->ac_prefs->session_passwd));

			if (inc_dialog->show_dialog)
				manage_window_focus_out
					(inc_dialog->dialog->window,
					 NULL, NULL);

			if (pass) {
				pop3_session->pass = pass;
			}
		}

		qlist = next;
	}

#define SET_PIXMAP_AND_TEXT(pix, str)					   \
{									   \
	progress_dialog_list_set(inc_dialog->dialog,			   \
				 inc_dialog->cur_row,			   \
				 pix,					   \
				 NULL,					   \
				 str);					   \
}

	for (; inc_dialog->queue_list != NULL && !cancelled; inc_dialog->cur_row++) {
		session = inc_dialog->queue_list->data;
		pop3_session = POP3_SESSION(session->session);
		GSList *filtered, *unfiltered;

		if (pop3_session->pass == NULL) {
			SET_PIXMAP_AND_TEXT(okpix, _("Cancelled"));
			inc_session_destroy(session);
			inc_dialog->queue_list =
				g_list_remove(inc_dialog->queue_list, session);
			continue;
		}

		inc_progress_dialog_clear(inc_dialog);
		progress_dialog_scroll_to_row(inc_dialog->dialog,
					      inc_dialog->cur_row);

		SET_PIXMAP_AND_TEXT(currentpix, _("Retrieving"));

		/* begin POP3 session */
		inc_state = inc_pop3_session_do(session);

		switch (inc_state) {
		case INC_SUCCESS:
			if (pop3_session->cur_total_num > 0)
				msg = g_strdup_printf(
					ngettext("Done (%d message (%s) received)",
						 "Done (%d messages (%s) received)",
					 pop3_session->cur_total_num),
					 pop3_session->cur_total_num,
					 to_human_readable((goffset)pop3_session->cur_total_recv_bytes));
			else
				msg = g_strdup_printf(_("Done (no new messages)"));
			SET_PIXMAP_AND_TEXT(okpix, msg);
			g_free(msg);
			break;
		case INC_CONNECT_ERROR:
			SET_PIXMAP_AND_TEXT(errorpix, _("Connection failed"));
			break;
		case INC_AUTH_FAILED:
			SET_PIXMAP_AND_TEXT(errorpix, _("Auth failed"));
			if (pop3_session->ac_prefs->session_passwd) {
				g_free(pop3_session->ac_prefs->session_passwd);
				pop3_session->ac_prefs->session_passwd = NULL;
			}
			break;
		case INC_LOCKED:
			SET_PIXMAP_AND_TEXT(errorpix, _("Locked"));
			break;
		case INC_ERROR:
		case INC_NO_SPACE:
		case INC_IO_ERROR:
		case INC_SOCKET_ERROR:
		case INC_EOF:
			SET_PIXMAP_AND_TEXT(errorpix, _("Error"));
			break;
		case INC_TIMEOUT:
			SET_PIXMAP_AND_TEXT(errorpix, _("Timeout"));
			break;
		case INC_CANCEL:
			SET_PIXMAP_AND_TEXT(okpix, _("Cancelled"));
			if (!inc_dialog->show_dialog)
				cancelled = TRUE;
			break;
		default:
			break;
		}
		
		if (pop3_session->error_val == PS_AUTHFAIL) {
			if(!prefs_common.no_recv_err_panel) {
				if((prefs_common.recv_dialog_mode == RECV_DIALOG_ALWAYS) ||
				    ((prefs_common.recv_dialog_mode == RECV_DIALOG_MANUAL) && focus_window))
					manage_window_focus_in(inc_dialog->dialog->window, NULL, NULL);
			}
		}

		/* CLAWS: perform filtering actions on dropped message */
		/* CLAWS: get default inbox (perhaps per account) */
		if (pop3_session->ac_prefs->inbox) {
			/* CLAWS: get destination folder / mailbox */
			inbox = folder_find_item_from_identifier(pop3_session->ac_prefs->inbox);
			if (!inbox)
				inbox = folder_get_default_inbox();
		} else
			inbox = folder_get_default_inbox();

		/* get list of messages in processing */
		processing = folder_get_default_processing();
		folder_item_scan(processing);
		msglist = folder_item_get_msg_list(processing);

		/* process messages */
		folder_item_update_freeze();
		
		procmsg_msglist_filter(msglist, pop3_session->ac_prefs, 
				&filtered, &unfiltered, 
				pop3_session->ac_prefs->filter_on_recv);

		filtering_move_and_copy_msgs(msglist);
		if (unfiltered != NULL)		
			folder_item_move_msgs(inbox, unfiltered);

		for(msglist_element = msglist; msglist_element != NULL; 
		    msglist_element = msglist_element->next) {
			MsgInfo *msginfo = (MsgInfo *)msglist_element->data;
			procmsg_msginfo_free(msginfo);
		}
		folder_item_update_thaw();
		
		g_slist_free(msglist);
		g_slist_free(filtered);
		g_slist_free(unfiltered);

		statusbar_pop_all();

		new_msgs += pop3_session->cur_total_num;

		pop3_write_uidl_list(pop3_session);

		if (inc_state != INC_SUCCESS && inc_state != INC_CANCEL) {
			error_num++;
			if (inc_dialog->show_dialog)
				manage_window_focus_in
					(inc_dialog->dialog->window,
					 NULL, NULL);
			inc_put_error(inc_state, pop3_session);
			if (inc_dialog->show_dialog)
				manage_window_focus_out
					(inc_dialog->dialog->window,
					 NULL, NULL);
			if (inc_state == INC_NO_SPACE ||
			    inc_state == INC_IO_ERROR)
				break;
		}
		folder_item_free_cache(processing, TRUE);

		inc_session_destroy(session);
		inc_dialog->queue_list =
			g_list_remove(inc_dialog->queue_list, session);
	}

#undef SET_PIXMAP_AND_TEXT

	if (new_msgs > 0)
		fin_msg = g_strdup_printf(ngettext("Finished (%d new message)",
					  	   "Finished (%d new messages)",
					  	   new_msgs), new_msgs);
	else
		fin_msg = g_strdup_printf(_("Finished (no new messages)"));

	progress_dialog_set_label(inc_dialog->dialog, fin_msg);

	while (inc_dialog->queue_list != NULL) {
		session = inc_dialog->queue_list->data;
		inc_session_destroy(session);
		inc_dialog->queue_list =
			g_list_remove(inc_dialog->queue_list, session);
	}

	if (prefs_common.close_recv_dialog || !inc_dialog->show_dialog)
		inc_progress_dialog_destroy(inc_dialog);
	else {
		gtk_window_set_title(GTK_WINDOW(inc_dialog->dialog->window),
				     fin_msg);
		gtk_button_set_label(GTK_BUTTON(inc_dialog->dialog->cancel_btn),
				     GTK_STOCK_CLOSE);
	}

	g_free(fin_msg);

	return new_msgs;
}
static void
load_finished (NautilusImagePropertiesPage *page)
{
	GdkPixbufFormat *format;
	char *name, *desc;

	gtk_widget_destroy (page->details->loading_label);

	if (page->details->loader != NULL) {
		gdk_pixbuf_loader_close (page->details->loader, NULL);
	}

	if (page->details->got_size) {
#ifdef HAVE_EXIF
                ExifData *exif_data;
#endif

		format = gdk_pixbuf_loader_get_format (page->details->loader);
	
		name = gdk_pixbuf_format_get_name (format);
		desc = gdk_pixbuf_format_get_description (format);
		append_label_take_str
			(page->details->vbox,
			 g_strdup_printf ("<b>%s</b> %s (%s)",
					  _("Image Type:"), name, desc));
		append_label_take_str
			(page->details->vbox,
			 g_strdup_printf (ngettext ("<b>Width:</b> %d pixel",
						    "<b>Width:</b> %d pixels",
						    page->details->width),
					  page->details->width));
		append_label_take_str
			(page->details->vbox,
			 g_strdup_printf (ngettext ("<b>Height:</b> %d pixel",
						    "<b>Height:</b> %d pixels",
						    page->details->height),
					  page->details->height));
		g_free (name);
		g_free (desc);
		
#ifdef HAVE_EXIF
		exif_data = exif_loader_get_data (page->details->exifldr);
                append_exifdata_string (exif_data, page);
                exif_data_unref (exif_data);
#endif /*HAVE_EXIF*/
#ifdef HAVE_EXEMPI
		append_xmpdata_string (page->details->xmp, page);
#endif /*HAVE EXEMPI*/		
	} else {
		append_label (page->details->vbox,
			      _("Failed to load image information"));
	}

	if (page->details->loader != NULL) {
		g_object_unref (page->details->loader);
		page->details->loader = NULL;
	}
#ifdef HAVE_EXIF
	if (page->details->exifldr != NULL) {
		exif_loader_unref (page->details->exifldr);
		page->details->exifldr = NULL;
	}
#endif /*HAVE_EXIF*/
#ifdef HAVE_EXEMPI
	if (page->details->xmp != NULL) {
		xmp_free(page->details->xmp);
		page->details->xmp = NULL;
	}
#endif
}
Beispiel #20
0
G_MODULE_EXPORT void
paradox_file_save (GOFileSaver const *fs, GOIOContext *io_context,
		   WorkbookView const *wb_view, GsfOutput *output)
{
	Sheet *sheet;
	GnmRange r;
	gint row, col, i;

	pxdoc_t *pxdoc = NULL;
	pxfield_t *pxf;
	char *data;
	char *tmpfilename;

	sheet = wb_view_cur_sheet (wb_view);
	if (sheet == NULL) {
		go_io_error_string (io_context, _("Cannot get default sheet."));
		return;
	}

	r = sheet_get_extent (sheet, FALSE, TRUE);

#ifdef PX_MEMORY_DEBUGGING
	pxdoc = PX_new2 (gn_errorhandler, PX_mp_malloc, PX_mp_realloc, PX_mp_free);
#else
	pxdoc = PX_new2 (gn_errorhandler, gn_malloc, gn_realloc, gn_free);
#endif

	/* Read the field specification and build the field array for
	 * PX_create_fp(). The memory is freed by PX_delete() including
	 * the memory for the field name. */
	if ((pxf = (pxfield_t *) pxdoc->malloc (pxdoc, (r.end.col+1)*sizeof (pxfield_t), _("Allocate memory for field definitions."))) == NULL){
		go_io_error_string (io_context, _("Cannot allocate memory for field definitions."));
		PX_delete (pxdoc);
		return;
	}

	for (col = r.start.col; col <= r.end.col; col++) {
		GnmCell *cell = sheet_cell_get (sheet, col, 0);
		if (gnm_cell_is_empty (cell)) {
			go_io_error_string (io_context, _("First line of sheet must contain database specification."));
			PX_delete (pxdoc);
			return;
		} else {
			gchar *fieldstr, *tmp;
			int len, needsize, needprecision;

			i = col;
			fieldstr = gnm_cell_get_rendered_text (cell);
			needsize = 0;
			needprecision = 0;

			/* Search for the first comma which is the end of the field name. */
			tmp = strchr (fieldstr, ',');
			if (NULL == tmp) {
				g_warning (_("Field specification must be a comma separated value (Name,Type,Size,Prec)."));
				PX_delete (pxdoc);
				return;
			}
			len = tmp-fieldstr;
			if (NULL == (pxf[i].px_fname = pxdoc->malloc (pxdoc, len+1, _("Allocate memory for column name.")))) {
				g_warning (_("Could not allocate memory for %d. field name."), i);
				PX_delete (pxdoc);
				return;
			}
			strncpy (pxf[i].px_fname, fieldstr, len);
			pxf[i].px_fname[len] = '\0';

			/* Get the field Type */
			fieldstr = tmp+1;
			if (*fieldstr == '\0') {
				g_warning (_("%d. field specification ended unexpectedly."), i);
				PX_delete (pxdoc);
				return;
			}
			if (*fieldstr == ',') {
				g_warning (_("%d. field specification misses type."), i);
				PX_delete (pxdoc);
				return;
			}
			switch ((int) *fieldstr) {
			case 'S':
				pxf[i].px_ftype = pxfShort;
				pxf[i].px_flen = 2;
				break;
			case 'I':
				pxf[i].px_ftype = pxfLong;
				pxf[i].px_flen = 4;
				break;
			case 'A':
			case 'C':
				pxf[i].px_ftype = pxfAlpha;
				needsize = 1;
				break;
			case 'N':
				pxf[i].px_ftype = pxfNumber;
				pxf[i].px_flen = 8;
				break;
			case '$':
				pxf[i].px_ftype = pxfCurrency;
				pxf[i].px_flen = 8;
				break;
			case 'L':
				pxf[i].px_ftype = pxfLogical;
				pxf[i].px_flen = 1;
				break;
			case 'D':
				pxf[i].px_ftype = pxfDate;
				pxf[i].px_flen = 4;
				break;
			case '+':
				pxf[i].px_ftype = pxfAutoInc;
				pxf[i].px_flen = 4;
				break;
			case '@':
				pxf[i].px_ftype = pxfTimestamp;
				pxf[i].px_flen = 8;
				break;
			case 'T':
				pxf[i].px_ftype = pxfTime;
				pxf[i].px_flen = 4;
				break;
			case '#':
				pxf[i].px_ftype = pxfBCD;
				pxf[i].px_flen = 17;
				needprecision = 1;
				break;
			case 'M':
				pxf[i].px_ftype = pxfMemoBLOb;
				needsize = 1;
				break;
			case 'B':
				pxf[i].px_ftype = pxfBLOb;
				needsize = 1;
				break;
			case 'F':
				pxf[i].px_ftype = pxfFmtMemoBLOb;
				needsize = 1;
				break;
			case 'Y':
				pxf[i].px_ftype = pxfBytes;
				needsize = 1;
				break;
			default:
				g_warning (_("%d. field type '%c' is unknown."), i, *fieldstr);
				pxdoc->free (pxdoc, pxf);
				PX_delete (pxdoc);
				return;
			}

			if (needsize || needprecision) {
				char *endptr;
				/* find end of type definition */
				tmp = strchr (fieldstr, ',');
				if (NULL == tmp || *(tmp+1) == '\0') {
					g_warning (_("Field specification misses the column size."));
					PX_delete (pxdoc);
					return;
				}
				fieldstr = tmp+1;
				if (needsize)
					pxf[i].px_flen = strtol (fieldstr, &endptr, 10);
				else
					pxf[i].px_fdc = strtol (fieldstr, &endptr, 10);
				if ((endptr == NULL) || (fieldstr == endptr)) {
					g_warning (_("Field specification misses the column size."));
					PX_delete (pxdoc);
					return;
				}
				if (*endptr != '\0') {
					/* There is also precision which we do not care about. */
					fieldstr = endptr+1;
					g_warning (_("The remainder '%s' of the specification for field %d is being disregarded."), fieldstr, i+1);
				}
			}
		}
	}

	/* Create the paradox file */
	tmpfilename = tempnam ("/tmp", NULL);
	if (0 > PX_create_file (pxdoc, pxf, r.end.col+1, tmpfilename, pxfFileTypNonIndexDB)) {
		g_warning (_("Could not create output file."));
		PX_delete (pxdoc);
		return;
	}

	PX_set_inputencoding (pxdoc, "UTF-8");
	PX_set_parameter (pxdoc, "targetencoding", "CP1252");
	PX_set_tablename (pxdoc, sheet->name_unquoted);

	if ((data = (char *) pxdoc->malloc (pxdoc, pxdoc->px_head->px_recordsize, _("Allocate memory for record data."))) == NULL) {
		g_warning (_("Could not allocate memory for record data."));
		PX_close (pxdoc);
		PX_delete (pxdoc);
		return;
	}
	/* Process all cells */
	for (row = r.start.row+1; row <= r.end.row; row++) {
		int i;
		int offset;
		offset = 0;
		memset (data, 0, pxdoc->px_head->px_recordsize);
		for (col = r.start.col, i = 0; col <= r.end.col; col++) {
			GnmCell *cell = sheet_cell_get (sheet, col, row);
			if (!gnm_cell_is_empty (cell)) {
				char *fieldstr = gnm_cell_get_rendered_text (cell);
				switch (pxf[i].px_ftype) {
				case pxfShort: {
					int value = value_get_as_int (cell->value);
					PX_put_data_short (pxdoc, &data[offset], 2, (short int) value);
					break;
				}
				case pxfLong:
				case pxfAutoInc: {
					int value = value_get_as_int (cell->value);
					PX_put_data_long (pxdoc, &data[offset], 4, value);
					break;
				}
				case pxfTimestamp: {
					double value = value_get_as_float (cell->value);
					/* 60 would be 29.2.1900 which didn't exist. */
					if (value < 60)
						value += 1.0;
					value += 693594;
					value *= 86400000.0;
					PX_put_data_double (pxdoc, &data[offset], 8, value);
					break;
				}
				case pxfCurrency:
				case pxfNumber: {
					double value = value_get_as_float (cell->value);
					PX_put_data_double(pxdoc, &data[offset], 8, value);
					break;
				}
				case pxfAlpha: {
					char *value = fieldstr;
					int nlen = strlen (value);
					if (nlen > pxf[i].px_flen)
						/* xgettext : last %d gives the number of characters.*/
						/* This is input to ngettext. */
						g_warning
							(ngettext
							 ("Field %d in line %d has possibly "
							  "been cut off. Data has %d character.",
							  "Field %d in line %d has possibly "
							  "been cut off. Data has %d characters.",
							  nlen),
							 i+1, row+1, nlen);
					PX_put_data_alpha (pxdoc, &data[offset], pxf[i].px_flen, value);
					break;
				}
				case pxfMemoBLOb:
				case pxfFmtMemoBLOb: {
					char *value = fieldstr;
					if (0 > PX_put_data_blob (pxdoc, &data[offset], pxf[i].px_flen, value, strlen (value))) {
						g_warning (_("Field %d in row %d could not be written."), i+1, row+1);
					}
					break;
				}
				case pxfDate: {
					long value = value_get_as_int (cell->value);
					/* 60 would be 29.2.1900 which didn't exist. */
					if (value < 60)
						value++;
					value += 693594;
					PX_put_data_long (pxdoc, &data[offset], 4, value);
					break;
				}
				case pxfTime: {
					double dtmp;
					int value;
					dtmp  = value_get_as_float (cell->value);
					dtmp -= ((int) dtmp);
					value = (int) (dtmp * 86400000.0);
					PX_put_data_long (pxdoc, &data[offset], 4, value);
					break;
				}
				case pxfLogical: {
					gboolean err; /* Ignored */
					gboolean value = value_get_as_bool (cell->value, &err);
					PX_put_data_byte (pxdoc, &data[offset], 1, value ? 1 : 0);
					break;
				}
				case pxfBCD:
					PX_put_data_bcd (pxdoc, &data[offset], pxf[i].px_fdc, fieldstr);
					break;
				}
			}
			offset += pxf[i].px_flen;
			i++;
		}
		if ((i > 0) && (0 > PX_put_record (pxdoc, data))) {
			g_warning (_("Could not write record number %d."), i+1);
			pxdoc->free (pxdoc, data);
			PX_close (pxdoc);
			PX_delete (pxdoc);
			return;
		}
	}
	pxdoc->free (pxdoc, data);
	PX_close (pxdoc);
	PX_delete (pxdoc);

#ifdef PX_MEMORY_DEBUGGING
	PX_mp_list_unfreed ();
#endif

	{
		FILE *fp;
		size_t size;
		fp = fopen (tmpfilename, "r");
		if (fp) {
			data = g_malloc (8192);
			while (0 != (size = fread (data, 1, 8192, fp)))
				gsf_output_write (output, size, data);
			fclose (fp);
			g_free (data);
		} else
			g_warning ("Cannot open %s\n", tmpfilename);

		unlink (tmpfilename);
	}
}
std::string quality_requirement::to_string( int ) const
{
    return string_format( ngettext( "%d tool with %s of %d or more.",
                                    "%d tools with %s of %d or more.", count ),
                          count, type.obj().name.c_str(), level );
}
Beispiel #22
0
int32_t dt_control_merge_hdr_job_run(dt_job_t *job)
{
  long int imgid = -1;
  dt_control_image_enumerator_t *t1 = (dt_control_image_enumerator_t *)job->param;
  GList *t = t1->index;
  int total = g_list_length(t);
  char message[512]= {0};
  double fraction=0;
  snprintf(message, 512, ngettext ("merging %d image", "merging %d images", total), total );

  const guint *jid = dt_control_backgroundjobs_create(darktable.control, 1, message);

  float *pixels = NULL;
  float *weight = NULL;
  int wd = 0, ht = 0, first_imgid = -1;
  uint32_t filter = 0;
  float whitelevel = 0.0f;
  total ++;
  while(t)
  {
    imgid = (long int)t->data;
    dt_mipmap_buffer_t buf;
    dt_mipmap_cache_read_get(darktable.mipmap_cache, &buf, imgid, DT_MIPMAP_FULL, DT_MIPMAP_BLOCKING);
    // just take a copy. also do it after blocking read, so filters and bpp will make sense.
    const dt_image_t *img = dt_image_cache_read_get(darktable.image_cache, imgid);
    dt_image_t image = *img;
    dt_image_cache_read_release(darktable.image_cache, img);
    if(image.filters == 0 || image.bpp != sizeof(uint16_t))
    {
      dt_control_log(_("exposure bracketing only works on raw images"));
      dt_mipmap_cache_read_release(darktable.mipmap_cache, &buf);
      free(pixels);
      free(weight);
      goto error;
    }
    filter = dt_image_flipped_filter(img);
    if(buf.size != DT_MIPMAP_FULL)
    {
      dt_control_log(_("failed to get raw buffer from image `%s'"), image.filename);
      dt_mipmap_cache_read_release(darktable.mipmap_cache, &buf);
      free(pixels);
      free(weight);
      goto error;
    }

    if(!pixels)
    {
      first_imgid = imgid;
      pixels = (float *)malloc(sizeof(float)*image.width*image.height);
      weight = (float *)malloc(sizeof(float)*image.width*image.height);
      memset(pixels, 0x0, sizeof(float)*image.width*image.height);
      memset(weight, 0x0, sizeof(float)*image.width*image.height);
      wd = image.width;
      ht = image.height;
    }
    else if(image.width != wd || image.height != ht)
    {
      dt_control_log(_("images have to be of same size!"));
      free(pixels);
      free(weight);
      dt_mipmap_cache_read_release(darktable.mipmap_cache, &buf);
      goto error;
    }
    // if no valid exif data can be found, assume peleng fisheye at f/16, 8mm, with half of the light lost in the system => f/22
    const float eap = image.exif_aperture > 0.0f ? image.exif_aperture : 22.0f;
    const float efl = image.exif_focal_length > 0.0f ? image.exif_focal_length : 8.0f;
    const float rad = .5f * efl/eap;
    const float aperture = M_PI * rad * rad;
    const float iso = image.exif_iso > 0.0f ? image.exif_iso : 100.0f;
    const float exp = image.exif_exposure > 0.0f ? image.exif_exposure : 1.0f;
    const float cal = 100.0f/(aperture*exp*iso);
    // about proportional to how many photons we can expect from this shot:
    const float photoncnt = 100.0f*aperture*exp/iso;
    // stupid, but we don't know the real sensor saturation level:
    uint16_t saturation = 0;
    for(int k=0; k<wd*ht; k++)
      saturation = MAX(saturation, ((uint16_t *)buf.buf)[k]);
    // seems to be around 64500--64700 for 5dm2
    // fprintf(stderr, "saturation: %u\n", saturation);
    whitelevel = fmaxf(whitelevel, saturation*cal);
#ifdef _OPENMP
    #pragma omp parallel for schedule(static) default(none) shared(buf, pixels, weight, wd, ht, saturation)
#endif
    for(int k=0; k<wd*ht; k++)
    {
      const uint16_t in = ((uint16_t *)buf.buf)[k];
      // weights based on siggraph 12 poster
      // zijian zhu, zhengguo li, susanto rahardja, pasi fraenti
      // 2d denoising factor for high dynamic range imaging
      float w = envelope(in/(float)saturation) * photoncnt;
      // in case we are black and drop to zero weight, give it something
      // just so numerics don't collapse. blown out whites are handled below.
      if(w < 1e-3f && in < saturation/3) w = 1e-3f;
      pixels[k] += w * in * cal;
      weight[k] += w;
    }

    t = g_list_delete_link(t, t);

    /* update backgroundjob ui plate */
    fraction+=1.0/total;
    dt_control_backgroundjobs_progress(darktable.control, jid, fraction);

    dt_mipmap_cache_read_release(darktable.mipmap_cache, &buf);
  }
  // normalize by white level to make clipping at 1.0 work as expected (to be sure, scale down one more stop, thus the 0.5):
#ifdef _OPENMP
  #pragma omp parallel for schedule(static) default(none) shared(pixels, wd, ht, weight, whitelevel)
#endif
  for(int k=0; k<wd*ht; k++)
  {
    // in case w == 0, all pixels were overexposed (too dark would have been clamped to w >= eps above)
    if(weight[k] < 1e-3f)
      pixels[k] = 1.f; // mark as blown out.
    else // normalize:
      pixels[k] = fmaxf(0.0f, pixels[k]/(whitelevel*weight[k]));
  }

  // output hdr as digital negative with exif data.
  uint8_t exif[65535];
  char pathname[DT_MAX_PATH_LEN];
  dt_image_full_path(first_imgid, pathname, DT_MAX_PATH_LEN);
  // last param is dng mode
  const int exif_len = dt_exif_read_blob(exif, pathname, first_imgid, 0, wd, ht, 1);
  char *c = pathname + strlen(pathname);
  while(*c != '.' && c > pathname) c--;
  g_strlcpy(c, "-hdr.dng", sizeof(pathname)-(c-pathname));
  dt_imageio_write_dng(pathname, pixels, wd, ht, exif, exif_len, filter, 1.0f);

  dt_control_backgroundjobs_progress(darktable.control, jid, 1.0f);

  while(*c != '/' && c > pathname) c--;
  dt_control_log(_("wrote merged hdr `%s'"), c+1);

  // import new image
  gchar *directory = g_path_get_dirname((const gchar *)pathname);
  dt_film_t film;
  const int filmid = dt_film_new(&film, directory);
  dt_image_import(filmid, pathname, TRUE);
  g_free (directory);

  free(pixels);
  free(weight);
error:
  dt_control_backgroundjobs_destroy(darktable.control, jid);
  dt_control_queue_redraw_center();
  return 0;
}
void activity_handlers::pulp_do_turn( player_activity *act, player *p )
{
    const tripoint &pos = act->placement;
    static const int full_pulp_threshold = 4;
    const int move_cost = int(p->weapon.is_null() ? 80 : p->weapon.attack_time() * 0.8);

    // numbers logic: a str 8 character with a butcher knife (4 bash, 18 cut)
    // should have at least a 50% chance of damaging an intact zombie corpse (75 volume).
    // a str 8 character with a baseball bat (28 bash, 0 cut) should have around a 25% chance.

    int cut_power = p->weapon.type->melee_cut;
    // stabbing weapons are a lot less effective at pulping
    if( p->weapon.has_flag("STAB") || p->weapon.has_flag("SPEAR") ) {
        cut_power /= 2;
    }
    double pulp_power = sqrt((double)(p->str_cur + p->weapon.type->melee_dam)) *
        std::min(1.0, sqrt((double)(cut_power + 1)));
    pulp_power = std::min(pulp_power, (double)p->str_cur);
    pulp_power *= 20; // constant multiplier to get the chance right
    int moves = 0;
    int &num_corpses = act->index; // use this to collect how many corpse are pulped
    auto corpse_pile = g->m.i_at(pos);
    for( auto corpse = corpse_pile.begin(); corpse != corpse_pile.end(); ++corpse ) {
        if( !(corpse->is_corpse() && corpse->damage < full_pulp_threshold) ) {
            continue; // no corpse or already pulped
        }
        int damage = pulp_power / corpse->volume();
        //Determine corpse's blood type.
        field_id type_blood = corpse->get_mtype()->bloodType();
        do {
            moves += move_cost;
            const int mod_sta = ( (p->weapon.weight() / 100 ) + 20) * -1;
            p->mod_stat("stamina", mod_sta);
            // Increase damage as we keep smashing,
            // to insure that we eventually smash the target.
            if( x_in_y(pulp_power, corpse->volume())  ) {
                corpse->damage++;
                p->handle_melee_wear();
            }
            // Splatter some blood around
            tripoint tmp = pos;
            if( type_blood != fd_null ) {
                for( tmp.x = pos.x - 1; tmp.x <= pos.x + 1; tmp.x++ ) {
                    for( tmp.y = pos.y - 1; tmp.y <= pos.y + 1; tmp.y++ ) {
                        if( !one_in(damage + 1) && type_blood != fd_null ) {
                            g->m.add_field( tmp, type_blood, 1, 0 );
                        }
                    }
                }
            }
            if( corpse->damage >= full_pulp_threshold ) {
                corpse->damage = full_pulp_threshold;
                corpse->active = false;
                num_corpses++;
            }
            if( moves >= p->moves ) {
                // enough for this turn;
                p->moves -= moves;
                return;
            }
        } while( corpse->damage < full_pulp_threshold );
    }
    // If we reach this, all corpses have been pulped, finish the activity
    act->moves_left = 0;
    // TODO: Factor in how long it took to do the smashing.
    add_msg(ngettext("The corpse is thoroughly pulped.",
                     "The corpses are thoroughly pulped.", num_corpses));
}
Beispiel #24
0
int32_t dt_control_delete_images_job_run(dt_job_t *job)
{
  long int imgid = -1;
  dt_control_image_enumerator_t *t1 = (dt_control_image_enumerator_t *)job->param;
  GList *t = t1->index;
  int total = g_list_length(t);
  char message[512]= {0};
  double fraction=0;
  snprintf(message, 512, ngettext ("deleting %d image", "deleting %d images", total), total );
  const guint *jid = dt_control_backgroundjobs_create(darktable.control, 0, message);

  sqlite3_stmt *stmt;

  char query[1024];
  sprintf(query, "update images set flags = (flags | %d) where id in (select imgid from selected_images)",DT_IMAGE_REMOVE);
  DT_DEBUG_SQLITE3_EXEC(dt_database_get(darktable.db), query, NULL, NULL, NULL);

  dt_collection_update(darktable.collection);

  // We need a list of files to regenerate .xmp files if there are duplicates
  GList *list = NULL;

  DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "select distinct folder || '/' || filename from images, film_rolls where images.film_id = film_rolls.id and images.id in (select imgid from selected_images)", -1, &stmt, NULL);

  if(sqlite3_step(stmt) == SQLITE_ROW)
  {
    list = g_list_append(list, g_strdup((const gchar *)sqlite3_column_text(stmt, 0)));
  }
  sqlite3_finalize(stmt);

  DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "select count(id) from images where filename in (select filename from images where id = ?1) and film_id in (select film_id from images where id = ?1)", -1, &stmt, NULL);
  while(t)
  {
    imgid = (long int)t->data;
    char filename[DT_MAX_PATH_LEN];
    dt_image_full_path(imgid, filename, DT_MAX_PATH_LEN);

    int duplicates = 0;
    DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, imgid);
    if(sqlite3_step(stmt) == SQLITE_ROW)
      duplicates = sqlite3_column_int(stmt, 0);
    sqlite3_reset(stmt);
    sqlite3_clear_bindings(stmt);

    // remove from disk:
    if(duplicates == 1) // don't remove the actual data if there are (other) duplicates using it
      (void)g_unlink(filename);
    dt_image_path_append_version(imgid, filename, DT_MAX_PATH_LEN);
    char *c = filename + strlen(filename);
    sprintf(c, ".xmp");
    (void)g_unlink(filename);

    dt_image_remove(imgid);

    t = g_list_delete_link(t, t);
    fraction=1.0/total;
    dt_control_backgroundjobs_progress(darktable.control, jid, fraction);
  }
  sqlite3_finalize(stmt);

  char *imgname;
  while(list)
  {
    imgname = (char *)list->data;
    dt_image_synch_all_xmp(imgname);
    list = g_list_delete_link(list, list);
  }
  g_list_free(list);
  dt_control_backgroundjobs_destroy(darktable.control, jid);
  dt_film_remove_empty();
  dt_control_queue_redraw_center();
  return 0;
}
Beispiel #25
0
static void
subscription_prop_dialog_load (SubscriptionPropDialog *spd, 
                               subscriptionPtr subscription) 
{
	gint 		interval;
	gint		default_update_interval;
	gint		defaultInterval, spinSetInterval;
	gchar 		*defaultIntervalStr;
	nodePtr		node = subscription->node;
	feedPtr		feed = (feedPtr)node->data;

	spd->priv->subscription = subscription;

	/* General */
	gtk_entry_set_text(GTK_ENTRY(spd->priv->feedNameEntry), node_get_title(node));

	spd->priv->refreshInterval = liferea_dialog_lookup(spd->priv->dialog,"refreshIntervalSpinButton");
	
	interval = subscription_get_update_interval(subscription);
	defaultInterval = subscription_get_default_update_interval(subscription);
	conf_get_int_value (DEFAULT_UPDATE_INTERVAL, &default_update_interval);
	spinSetInterval = defaultInterval > 0 ? defaultInterval : default_update_interval;
	
	if (-2 >= interval) {
		gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (liferea_dialog_lookup(spd->priv->dialog, "updateIntervalNever")), TRUE);
	} else if (-1 == interval) {
		gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (liferea_dialog_lookup(spd->priv->dialog, "updateIntervalDefault")), TRUE);
	} else {
		gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (liferea_dialog_lookup(spd->priv->dialog, "updateIntervalSpecific")), TRUE);
		spinSetInterval = interval;
	}
	
	/* Set refresh interval spin button and combo box */
	if (spinSetInterval % 1440 == 0) {	/* days */
		gtk_combo_box_set_active (GTK_COMBO_BOX (spd->priv->refreshIntervalUnit), 2);
		spinSetInterval /= 1440;
	} else if (spinSetInterval % 60 == 0) {	/* hours */
		gtk_combo_box_set_active (GTK_COMBO_BOX (spd->priv->refreshIntervalUnit), 1);
		spinSetInterval /= 60;
	} else {
		gtk_combo_box_set_active (GTK_COMBO_BOX (spd->priv->refreshIntervalUnit), 0);
	}
	gtk_spin_button_set_value (GTK_SPIN_BUTTON (spd->priv->refreshInterval), spinSetInterval);

	gtk_widget_set_sensitive (spd->priv->refreshInterval, interval > 0);
	gtk_widget_set_sensitive (spd->priv->refreshIntervalUnit, interval > 0);
	
	/* setup info label about default update interval */
	if(-1 != defaultInterval)
		defaultIntervalStr = g_strdup_printf(ngettext("The provider of this feed suggests an update interval of %d minute.", 
		                                              "The provider of this feed suggests an update interval of %d minutes.",
		                                              defaultInterval), defaultInterval);
	else
		defaultIntervalStr = g_strdup(_("This feed specifies no default update interval."));

	gtk_label_set_text(GTK_LABEL(liferea_dialog_lookup(spd->priv->dialog, "feedUpdateInfo")), defaultIntervalStr);
	g_free(defaultIntervalStr);

	/* Source (only for feeds) */
	if (SUBSCRIPTION_TYPE(subscription) == feed_get_subscription_type ()) {
		if(subscription_get_source(subscription)[0] == '|') {
			gtk_entry_set_text(GTK_ENTRY(spd->priv->sourceEntry), &(subscription_get_source(subscription)[1]));
			gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(spd->priv->cmdRadio), TRUE);
			ui_subscription_prop_enable_httpauth(spd->priv, FALSE);
			gtk_widget_set_sensitive(spd->priv->selectFile, TRUE);
		} else if(strstr(subscription_get_source(subscription), "://") != NULL) {
			xmlURIPtr uri = xmlParseURI(BAD_CAST subscription_get_source(subscription));
			xmlChar *parsedUrl;
			if(uri) {
				if(uri->user) {
					gchar *user = uri->user;
					gchar *pass = strstr(user, ":");
					if(pass) {
						pass[0] = '\0';
						pass++;
						gtk_entry_set_text(GTK_ENTRY(spd->priv->password), pass);
					}
					gtk_entry_set_text(GTK_ENTRY(spd->priv->username), user);
					xmlFree(uri->user);
					uri->user = NULL;
					gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(spd->priv->authcheckbox), TRUE);
				}
				parsedUrl = xmlSaveUri(uri);
				gtk_entry_set_text(GTK_ENTRY(spd->priv->sourceEntry), parsedUrl);
				xmlFree(parsedUrl);
				xmlFreeURI(uri);
			} else {
				gtk_entry_set_text(GTK_ENTRY(spd->priv->sourceEntry), subscription_get_source(subscription));
			}
			ui_subscription_prop_enable_httpauth(spd->priv, TRUE);
			gtk_widget_set_sensitive(spd->priv->selectFile, FALSE);
		} else {
			/* File */
			gtk_entry_set_text(GTK_ENTRY(spd->priv->sourceEntry), subscription_get_source(subscription));
			gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(spd->priv->fileRadio), TRUE);
			ui_subscription_prop_enable_httpauth(spd->priv, FALSE);
			gtk_widget_set_sensitive(spd->priv->selectFile, TRUE);
		}

		if(subscription_get_filter(subscription)) {
			gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(liferea_dialog_lookup(spd->priv->dialog, "filterCheckbox")), TRUE);
			gtk_entry_set_text(GTK_ENTRY(liferea_dialog_lookup(spd->priv->dialog, "filterEntry")), subscription_get_filter(subscription));
		}
	}

	/* Archive */
	if(feed->cacheLimit == CACHE_DISABLE) {
		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(liferea_dialog_lookup(spd->priv->dialog, "feedCacheDisable")), TRUE);
	} else if(feed->cacheLimit == CACHE_DEFAULT) {
		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(liferea_dialog_lookup(spd->priv->dialog, "feedCacheDefault")), TRUE);
	} else if(feed->cacheLimit == CACHE_UNLIMITED) {
		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(liferea_dialog_lookup(spd->priv->dialog, "feedCacheUnlimited")), TRUE);
	} else {
		gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(liferea_dialog_lookup(spd->priv->dialog, "feedCacheLimited")), TRUE);
		gtk_spin_button_set_value(GTK_SPIN_BUTTON(liferea_dialog_lookup(spd->priv->dialog, "cacheItemLimit")), feed->cacheLimit);
	}

	gtk_widget_set_sensitive(liferea_dialog_lookup(spd->priv->dialog, "cacheItemLimit"), feed->cacheLimit > 0);

	on_feed_prop_filtercheck(GTK_TOGGLE_BUTTON(liferea_dialog_lookup(spd->priv->dialog, "filterCheckbox")), spd->priv);
	
	/* Download */
	gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(liferea_dialog_lookup(spd->priv->dialog, "dontUseProxyCheck")), subscription->updateOptions->dontUseProxy);

	/* Advanced */	
	gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (liferea_dialog_lookup (spd->priv->dialog, "enclosureDownloadCheck")), feed->encAutoDownload);
	gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (liferea_dialog_lookup (spd->priv->dialog, "loadItemLinkCheck")), node->loadItemLink);
	gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (liferea_dialog_lookup (spd->priv->dialog, "ignoreCommentFeeds")), feed->ignoreComments);
	gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (liferea_dialog_lookup (spd->priv->dialog, "enforcePopupCheck")), feed->enforcePopup);
	gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (liferea_dialog_lookup (spd->priv->dialog, "preventPopupCheck")), feed->preventPopup);
	gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (liferea_dialog_lookup (spd->priv->dialog, "markAsReadCheck")), feed->markAsRead);

	/* Remove tabs we do not need... */
	if (SUBSCRIPTION_TYPE(subscription) != feed_get_subscription_type ()) {
		/* Remove "Allgemein", "Source" and "Download" tab */
		gtk_notebook_remove_page (GTK_NOTEBOOK (liferea_dialog_lookup (spd->priv->dialog, "subscriptionPropNotebook")), 0);
		gtk_notebook_remove_page (GTK_NOTEBOOK (liferea_dialog_lookup (spd->priv->dialog, "subscriptionPropNotebook")), 0);
		gtk_notebook_remove_page (GTK_NOTEBOOK (liferea_dialog_lookup (spd->priv->dialog, "subscriptionPropNotebook")), 1);
	}
}
Beispiel #26
0
static int32_t dt_control_export_job_run(dt_job_t *job)
{
  long int imgid = -1;
  dt_control_image_enumerator_t *t1 = (dt_control_image_enumerator_t *)job->param;
  dt_control_export_t *settings = (dt_control_export_t*)t1->data;
  GList *t = t1->index;
  const int total = g_list_length(t);
  int size = 0;
  dt_imageio_module_format_t  *mformat  = dt_imageio_get_format_by_index(settings->format_index);
  g_assert(mformat);
  dt_imageio_module_storage_t *mstorage = dt_imageio_get_storage_by_index(settings->storage_index);
  g_assert(mstorage);

  // Get max dimensions...
  uint32_t w,h,fw,fh,sw,sh;
  fw=fh=sw=sh=0;
  mstorage->dimension(mstorage, &sw,&sh);
  mformat->dimension(mformat, &fw,&fh);

  if( sw==0 || fw==0) w=sw>fw?sw:fw;
  else w=sw<fw?sw:fw;

  if( sh==0 || fh==0) h=sh>fh?sh:fh;
  else h=sh<fh?sh:fh;

  // get shared storage param struct (global sequence counter, one picasa connection etc)
  dt_imageio_module_data_t *sdata = mstorage->get_params(mstorage, &size);
  if(sdata == NULL)
  {
    dt_control_log(_("failed to get parameters from storage module, aborting export.."));
    g_free(t1->data);
    return 1;
  }
  dt_control_log(ngettext ("exporting %d image..", "exporting %d images..", total), total);
  char message[512]= {0};
  snprintf(message, 512, ngettext ("exporting %d image to %s", "exporting %d images to %s", total), total, mstorage->name(mstorage) );

  /* create a cancellable bgjob ui template */
  const guint *jid = dt_control_backgroundjobs_create(darktable.control, 0, message );
  dt_control_backgroundjobs_set_cancellable(darktable.control, jid, job);
  const dt_control_t *control = darktable.control;

  double fraction=0;
#ifdef _OPENMP
  // limit this to num threads = num full buffers - 1 (keep one for darkroom mode)
  // use min of user request and mipmap cache entries
  const int full_entries = dt_conf_get_int ("parallel_export");
  // GCC won't accept that this variable is used in a macro, considers
  // it set but not used, which makes for instance Fedora break.
  const __attribute__((__unused__)) int num_threads = MAX(1, MIN(full_entries, 8));
#if !defined(__SUNOS__) && !defined(__NetBSD__)
  #pragma omp parallel default(none) private(imgid, size) shared(control, fraction, w, h, stderr, mformat, mstorage, t, sdata, job, jid, darktable, settings) num_threads(num_threads) if(num_threads > 1)
#else
  #pragma omp parallel private(imgid, size) shared(control, fraction, w, h, mformat, mstorage, t, sdata, job, jid, darktable, settings) num_threads(num_threads) if(num_threads > 1)
#endif
  {
#endif
    // get a thread-safe fdata struct (one jpeg struct per thread etc):
    dt_imageio_module_data_t *fdata = mformat->get_params(mformat, &size);
    fdata->max_width = settings->max_width;
    fdata->max_height = settings->max_height;
    fdata->max_width = (w!=0 && fdata->max_width >w)?w:fdata->max_width;
    fdata->max_height = (h!=0 && fdata->max_height >h)?h:fdata->max_height;
    strcpy(fdata->style,settings->style);
    int num = 0;
    // Invariant: the tagid for 'darktable|changed' will not change while this function runs. Is this a sensible assumption?
    guint tagid = 0,
          etagid = 0;
    dt_tag_new("darktable|changed",&tagid);
    dt_tag_new("darktable|exported",&etagid);

    while(t && dt_control_job_get_state(job) != DT_JOB_STATE_CANCELLED)
    {
#ifdef _OPENMP
      #pragma omp critical
#endif
      {
        if(!t)
          imgid = 0;
        else
        {
          imgid = (long int)t->data;
          t = g_list_delete_link(t, t);
          num = total - g_list_length(t);
        }
      }
      // remove 'changed' tag from image
      dt_tag_detach(tagid, imgid);
      // make sure the 'exported' tag is set on the image
      dt_tag_attach(etagid, imgid);
      // check if image still exists:
      char imgfilename[DT_MAX_PATH_LEN];
      const dt_image_t *image = dt_image_cache_read_get(darktable.image_cache, (int32_t)imgid);
      if(image)
      {
        dt_image_full_path(image->id, imgfilename, DT_MAX_PATH_LEN);
        if(!g_file_test(imgfilename, G_FILE_TEST_IS_REGULAR))
        {
          dt_control_log(_("image `%s' is currently unavailable"), image->filename);
          fprintf(stderr, _("image `%s' is currently unavailable"), imgfilename);
          // dt_image_remove(imgid);
          dt_image_cache_read_release(darktable.image_cache, image);
        }
        else
        {
          dt_image_cache_read_release(darktable.image_cache, image);
          mstorage->store(mstorage,sdata, imgid, mformat, fdata, num, total, settings->high_quality);
        }
      }
#ifdef _OPENMP
      #pragma omp critical
#endif
      {
        fraction+=1.0/total;
        dt_control_backgroundjobs_progress(control, jid, fraction);
      }
    }
#ifdef _OPENMP
    #pragma omp barrier
    #pragma omp master
#endif
    {
      dt_control_backgroundjobs_destroy(control, jid);
      if(mstorage->finalize_store) mstorage->finalize_store(mstorage, sdata);
      mstorage->free_params(mstorage, sdata);
    }
    // all threads free their fdata
    mformat->free_params (mformat, fdata);
#ifdef _OPENMP
  }
#endif
  g_free(t1->data);
  return 0;
}
Beispiel #27
0
static void
delete_button_clicked (GtkButton *button, gpointer user_data)
{
  dt_lib_module_t *self = (dt_lib_module_t *)user_data;
  dt_lib_tagging_t *d   = (dt_lib_tagging_t *)self->data;

  int res = GTK_RESPONSE_YES;

  guint tagid;
  GtkTreeIter iter;
  GtkTreeModel *model = NULL;
  GtkTreeView *view = d->related;
  GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(view));
  if(!gtk_tree_selection_get_selected(selection, &model, &iter)) return;
  gtk_tree_model_get (model, &iter,
                      DT_LIB_TAGGING_COL_ID, &tagid,
                      -1);

  // First check how many images are affected by the remove
  int count = dt_tag_remove(tagid,FALSE);
  if( count > 0 && dt_conf_get_bool("plugins/lighttable/tagging/ask_before_delete_tag") )
  {
    GtkWidget *dialog;
    GtkWidget *win = dt_ui_main_window(darktable.gui->ui);
    gchar *tagname=dt_tag_get_name(tagid);
    dialog = gtk_message_dialog_new(GTK_WINDOW(win),
                                    GTK_DIALOG_DESTROY_WITH_PARENT,
                                    GTK_MESSAGE_QUESTION,
                                    GTK_BUTTONS_YES_NO,
                                    ngettext("do you really want to delete the tag `%s'?\n%d image is assigned this tag!",
                                        "do you really want to delete the tag `%s'?\n%d images are assigned this tag!", count),
                                    tagname,count);
    gtk_window_set_title(GTK_WINDOW(dialog), _("delete tag?"));
    res = gtk_dialog_run(GTK_DIALOG(dialog));
    gtk_widget_destroy(dialog);
    free(tagname);
  }
  if(res != GTK_RESPONSE_YES) return;

  GList *tagged_images = NULL;
  sqlite3_stmt *stmt;
  DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db), "select imgid from tagged_images where tagid=?1", -1, &stmt, NULL);
  DT_DEBUG_SQLITE3_BIND_INT(stmt, 1, tagid);
  while(sqlite3_step(stmt) == SQLITE_ROW)
  {
    tagged_images = g_list_append(tagged_images, GINT_TO_POINTER(sqlite3_column_int(stmt, 0)));
  }
  sqlite3_finalize(stmt);

  dt_tag_remove(tagid,TRUE);

  GList *list_iter;
  if((list_iter = g_list_first(tagged_images)) != NULL)
  {
    do
    {
      dt_image_synch_xmp(GPOINTER_TO_INT(list_iter->data));
    }
    while((list_iter=g_list_next(list_iter)) != NULL);
  }
  g_list_free(g_list_first(tagged_images));

  update(self, 0);
  update(self, 1);

  dt_control_signal_raise(darktable.signals, DT_SIGNAL_TAG_CHANGED);
}
Beispiel #28
0
void Pickup::pick_one_up( const tripoint &pickup_target, item &newit, vehicle *veh,
                          int cargo_part, int index, int quantity, bool &got_water,
                          bool &offered_swap, PickupMap &mapPickup, bool autopickup )
{
    int moves_taken = 100;
    bool picked_up = false;
    item leftovers = newit;

    if( newit.invlet != '\0' &&
        g->u.invlet_to_position( newit.invlet ) != INT_MIN ) {
        // Existing invlet is not re-usable, remove it and let the code in player.cpp/inventory.cpp
        // add a new invlet, otherwise keep the (usable) invlet.
        newit.invlet = '\0';
    }

    if( quantity != 0 && newit.count_by_charges() ) {
        // Reinserting leftovers happens after item removal to avoid stacking issues.
        leftovers.charges = newit.charges - quantity;
        if( leftovers.charges > 0 ) {
            newit.charges = quantity;
        }
    } else {
        leftovers.charges = 0;
    }

    if( newit.made_of(LIQUID) ) {
        got_water = true;
    } else if (!g->u.can_pickWeight(newit.weight(), false)) {
        add_msg(m_info, _("The %s is too heavy!"), newit.display_name().c_str());
    } else if( newit.is_ammo() && (newit.ammo_type() == "arrow" || newit.ammo_type() == "bolt")) {
        //add ammo to quiver
        int quivered = handle_quiver_insertion( newit, moves_taken, picked_up);
        if( newit.charges > 0) {
            if(!g->u.can_pickVolume( newit.volume())) {
                if(quivered > 0) {
                    //update the charges for the item that gets re-added to the game map
                    quantity = quivered;
                    leftovers.charges = newit.charges;
                }
                if( !autopickup ) {
                    // Silence some messaging if we're doing autopickup.
                    add_msg(m_info, ngettext("There's no room in your inventory for the %s.",
                                             "There's no room in your inventory for the %s.",
                                             newit.charges), newit.tname(newit.charges).c_str());
                }
            } else {
                //add to inventory instead
                item &it = g->u.i_add(newit);
                picked_up = true;

                //display output message
                PickupMap map_pickup;
                int charges = (newit.count_by_charges()) ? newit.charges : 1;
                map_pickup.insert(std::pair<std::string, ItemCount>(newit.tname(), ItemCount(it, charges)));
                show_pickup_message(map_pickup);
            }
        }
    } else if (!g->u.can_pickVolume(newit.volume())) {
        if( !autopickup ) {
            // Armor can be instantly worn
            if (newit.is_armor() &&
                query_yn(_("Put on the %s?"),
                         newit.display_name().c_str())) {
                if (g->u.wear_item(newit)) {
                    picked_up = true;
                }
            } else if (g->u.is_armed()) {
                if (!g->u.weapon.has_flag("NO_UNWIELD")) {
                    if( !offered_swap ) {
                        offered_swap = true;
                        if ( g->u.weapon.type->id != newit.type->id &&
                             query_yn(_("No space for %1$s; wield instead? (drops %2$s)"),
                                      newit.display_name().c_str(),
                                      g->u.weapon.display_name().c_str()) ) {
                            picked_up = true;
                            g->m.add_item_or_charges( pickup_target,
                                                      g->u.remove_weapon(), 1 );
                            g->u.inv.assign_empty_invlet( newit, true ); // force getting an invlet.
                            g->u.wield( &( g->u.i_add(newit) ) );

                            if (newit.invlet) {
                                add_msg(m_info, _("Wielding %c - %s"), newit.invlet,
                                        newit.display_name().c_str());
                            } else {
                                add_msg(m_info, _("Wielding - %s"), newit.display_name().c_str());
                            }
                        }
                    }
                } else {
                    add_msg(m_info, _("There's no room in your inventory for the %s "
                                      "and you can't unwield your %s."),
                            newit.display_name().c_str(),
                            g->u.weapon.display_name().c_str());
                }
            } else if( !g->u.is_armed()  ) {
                if (g->u.keep_hands_free) {
                    add_msg(m_info, _("There's no room in your inventory for the %s "
                                      "and you have decided to keep your hands free."),
                            newit.display_name().c_str());
                } else {
                    g->u.inv.assign_empty_invlet(newit, true);  // force getting an invlet.
                    g->u.wield(&(g->u.i_add(newit)));
                    picked_up = true;

                    if (newit.invlet) {
                        add_msg(m_info, _("Wielding %c - %s"), newit.invlet,
                                newit.display_name().c_str());
                    } else {
                        add_msg(m_info, _("Wielding - %s"), newit.display_name().c_str());
                    }
                }
            } // end of if unarmed
        } // end of if !autopickup
    } else {
        auto &entry = mapPickup[newit.tname()];
        entry.second += newit.count_by_charges() ? newit.charges : 1;
        entry.first = g->u.i_add(newit);
        picked_up = true;
    }

    if(picked_up) {
        Pickup::remove_from_map_or_vehicle(pickup_target,
                                           veh, cargo_part, moves_taken, index);
    }
    if( leftovers.charges > 0 ) {
        bool to_map = veh == nullptr;
        if( !to_map ) {
            to_map = !veh->add_item( cargo_part, leftovers );
        }
        if( to_map ) {
            g->m.add_item_or_charges( pickup_target, leftovers );
        }
    }
}
Beispiel #29
0
int
main (int argc, char **argv)
{
  char *command_line = NULL;
  char input_buffer[MAX_INPUT_BUFFER];
  char *address = NULL; /* comma seperated str with addrs/ptrs (sorted) */
  char **addresses = NULL;
  int n_addresses = 0;
  char *msg = NULL;
  char *temp_buffer = NULL;
  int non_authoritative = FALSE;
  int result = STATE_UNKNOWN;
  double elapsed_time;
  long microsec;
  struct timeval tv;
  int multi_address;
  int parse_address = FALSE; /* This flag scans for Address: but only after Name: */
  output chld_out, chld_err;
  size_t i;

  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  /* Set signal handling and alarm */
  if (signal (SIGALRM, runcmd_timeout_alarm_handler) == SIG_ERR) {
    usage_va(_("Cannot catch SIGALRM"));
  }

  /* Parse extra opts if any */
  argv=np_extra_opts (&argc, argv, progname);

  if (process_arguments (argc, argv) == ERROR) {
    usage_va(_("Could not parse arguments"));
  }

  /* get the command to run */
  xasprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server);

  alarm (timeout_interval);
  gettimeofday (&tv, NULL);

  if (verbose)
    printf ("%s\n", command_line);

  /* run the command */
  if((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) {
    msg = (char *)_("nslookup returned an error status");
    result = STATE_WARNING;
  }

  /* scan stdout */
  for(i = 0; i < chld_out.lines; i++) {
    if (addresses == NULL)
      addresses = malloc(sizeof(*addresses)*10);
    else if (!(n_addresses % 10))
      addresses = realloc(addresses,sizeof(*addresses) * (n_addresses + 10));

    if (verbose)
      puts(chld_out.line[i]);

    if (strstr (chld_out.line[i], ".in-addr.arpa")) {
      if ((temp_buffer = strstr (chld_out.line[i], "name = ")))
        addresses[n_addresses++] = strdup (temp_buffer + 7);
      else {
        msg = (char *)_("Warning plugin error");
        result = STATE_WARNING;
      }
    }

    /* the server is responding, we just got the host name... */
    if (strstr (chld_out.line[i], "Name:"))
      parse_address = TRUE;
    else if (parse_address == TRUE && (strstr (chld_out.line[i], "Address:") ||
             strstr (chld_out.line[i], "Addresses:"))) {
      temp_buffer = index (chld_out.line[i], ':');
      temp_buffer++;

      /* Strip leading spaces */
      for (; *temp_buffer != '\0' && *temp_buffer == ' '; temp_buffer++)
        /* NOOP */;

      strip(temp_buffer);
      if (temp_buffer==NULL || strlen(temp_buffer)==0) {
        die (STATE_CRITICAL,
             _("DNS CRITICAL - '%s' returned empty host name string\n"),
             NSLOOKUP_COMMAND);
      }

      addresses[n_addresses++] = strdup(temp_buffer);
    }
    else if (strstr (chld_out.line[i], _("Non-authoritative answer:"))) {
      non_authoritative = TRUE;
    }


    result = error_scan (chld_out.line[i]);
    if (result != STATE_OK) {
      msg = strchr (chld_out.line[i], ':');
      if(msg) msg++;
      break;
    }
  }

  /* scan stderr */
  for(i = 0; i < chld_err.lines; i++) {
    if (verbose)
      puts(chld_err.line[i]);

    if (error_scan (chld_err.line[i]) != STATE_OK) {
      result = max_state (result, error_scan (chld_err.line[i]));
      msg = strchr(input_buffer, ':');
      if(msg) msg++;
    }
  }

  if (addresses) {
    int i,slen;
    char *adrp;
    qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp);
    for(i=0, slen=1; i < n_addresses; i++) {
      slen += strlen(addresses[i])+1;
    }
    adrp = address = malloc(slen);
    for(i=0; i < n_addresses; i++) {
      if (i) *adrp++ = ',';
      strcpy(adrp, addresses[i]);
      adrp += strlen(addresses[i]);
    }
    *adrp = 0;
  } else
    die (STATE_CRITICAL,
         _("DNS CRITICAL - '%s' msg parsing exited with no address\n"),
         NSLOOKUP_COMMAND);

  /* compare to expected address */
  if (result == STATE_OK && expected_address_cnt > 0) {
    result = STATE_CRITICAL;
    temp_buffer = "";
    for (i=0; i<expected_address_cnt; i++) {
      /* check if we get a match and prepare an error string */
      if (strcmp(address, expected_address[i]) == 0) result = STATE_OK;
      xasprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]);
    }
    if (result == STATE_CRITICAL) {
      /* Strip off last semicolon... */
      temp_buffer[strlen(temp_buffer)-2] = '\0';
      xasprintf(&msg, _("expected '%s' but got '%s'"), temp_buffer, address);
    }
  }

  /* check if authoritative */
  if (result == STATE_OK && expect_authority && non_authoritative) {
    result = STATE_CRITICAL;
    xasprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address);
  }

  microsec = deltime (tv);
  elapsed_time = (double)microsec / 1.0e6;

  if (result == STATE_OK) {
    if (strchr (address, ',') == NULL)
      multi_address = FALSE;
    else
      multi_address = TRUE;

    result = get_status(elapsed_time, time_thresholds);
    if (result == STATE_OK) {
      printf ("DNS %s: ", _("OK"));
    } else if (result == STATE_WARNING) {
      printf ("DNS %s: ", _("WARNING"));
    } else if (result == STATE_CRITICAL) {
      printf ("DNS %s: ", _("CRITICAL"));
    }
    printf (ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time), elapsed_time);
    printf (_(". %s returns %s"), query_address, address);
    printf ("|%s\n", fperfdata ("time", elapsed_time, "s", FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
  }
  else if (result == STATE_WARNING)
    printf (_("DNS WARNING - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
  else if (result == STATE_CRITICAL)
    printf (_("DNS CRITICAL - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
  else
    printf (_("DNS UNKNOWN - %s\n"),
            !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);

  return result;
}
Beispiel #30
0
//------ Begin of function News::earthquake_damage -----//
//
void News::earthquake_damage()
{
	//---------------- Text Format -----------------//
	//
	// <number> of your units has/have been injured and <number> killed
	// in an earthquake.
	//
	// <number> of your villagers has/have been killed in an earthquake.
	//
	// <number> of your buildings has/have been damaged and <number> destroyed
	// in an earthquake.
	//
	//----------------------------------------------//

	str = "";

	// ###### begin Gilbert 12/9 ##########//
	if( short_para1 == 1)
	{
		if( short_para3 > 0)
		{
			snprintf(str,
				 MAX_STR_LEN+1,
				 // TRANSLATORS: <Number> of your units has been injured and <Number> killed in an earthquake.
				 // <Number> of your units have been injured and <Number> killed in an earthquake.
				 ngettext("%d of your units has been injured and %d killed in an earthquake.",
					  "%d of your units have been injured and %d killed in an earthquake.",
					  short_para2),
				 short_para2,
				 short_para3);
		}
		else
		{
			snprintf(str,
				 MAX_STR_LEN+1,
				 // TRANSLATORS: <Number> of your units has been injured in an earthquake.
				 // <Number> of your units have been injured in an earthquake.
				 ngettext("%d of your units has been injured in an earthquake.",
					  "%d of your units have been injured in an earthquake.",
					  short_para2),
				 short_para2);
		}
	}
	else if( short_para1 == 2 )
	{
		if( short_para2 > 0)
		{
			snprintf(str,
				 MAX_STR_LEN+1,
				 // TRANSLATORS: <Number> of your villagers has been killed in an earthquake.
				 // <Number> of your villagers have been killed in an earthquake.
				 ngettext("%d of your villagers has been killed in an earthquake.",
					  "%d of your villagers have been killed in an earthquake.",
					  short_para2),
				 short_para2);
		}
	}
	else if( short_para1 == 3)
	{
		if( short_para3 > 0)
		{
			snprintf(str,
				 MAX_STR_LEN+1,
				 // TRANSLATORS: <Number> of your buildings has been damaged and <Number> destroyed in an earthquake.
				 // <Number> of your buildings have been damaged and <Number> destroyed in an earthquake.
				 ngettext("%d of your buildings has been damaged and %d destroyed in an earthquake.",
					  "%d of your buildings have been damaged and %d destroyed in an earthquake.",
					  short_para2),
				 short_para2,
				 short_para3);
		}
		else
		{
			snprintf(str,
				 MAX_STR_LEN+1,
				 // TRANSLATORS: <Number> of your buildings has been damaged in an earthquake.
				 // TRANSLATORS: <Number> of your buildings have been damaged in an earthquake.
				 ngettext("%d of your buildings has been damaged in an earthquake.",
					  "%d of your buildings have been damaged in an earthquake.",
					  short_para2),
				 short_para2);
		}
	}
	else
		err_here();
	// ###### end Gilbert 12/9 ##########//
}