Example #1
0
/**
 * korva_upnp_host_data_get_extension:
 *
 * Get the file extension for the current file.
 *
 * @self:  An instance of #KorvaUPnPHostData
 * Returns: (transfer none): The extension associated with the file.
 */
static const char *
korva_upnp_host_data_get_extension (KorvaUPnPHostData *self)
{
    GVariant *value;
    const char *dlna_profile, *content_type, *ext;
    char *path = NULL;

    if (self->priv->extension != NULL) {
        goto out;
    }

    path = g_file_get_path (self->priv->file);
    ext = g_strrstr (path, ".");
    if (!(ext == NULL || *ext == '\0' || strlen (++ext) > 4)) {
        self->priv->extension = g_strdup (ext);

        goto out;
    }

    value = g_hash_table_lookup (self->priv->meta_data, "DLNAProfile");
    if (value != NULL) {
        dlna_profile = g_variant_get_string (value, NULL);
        /* Images */
        if (g_strstr_len (dlna_profile, -1, "JPEG") != NULL) {
            self->priv->extension = g_strdup ("jpg");
        } else if (g_strstr_len (dlna_profile, -1, "PNG") != NULL) {
            self->priv->extension = g_strdup ("png");
        } else if (g_strstr_len (dlna_profile, -1, "GIF") != NULL) {
            self->priv->extension = g_strdup ("gif");
        } else if (g_strstr_len (dlna_profile, -1, "_MP4_") != NULL) {
            self->priv->extension = g_strdup ("mp4");
        } else if (g_strstr_len (dlna_profile, -1, "MP3") != NULL) {
            self->priv->extension = g_strdup ("mp3");
        } else if (g_strstr_len (dlna_profile, -1, "_ISO") != NULL) {
            self->priv->extension = g_strdup ("m4a");
        } else if (g_strstr_len (dlna_profile, -1, "ADTS") != NULL) {
            self->priv->extension = g_strdup ("adts");
        } else if (g_strstr_len (dlna_profile, -1, "WMV") != NULL) {
            self->priv->extension = g_strdup ("wmv");
        } else if (g_strstr_len (dlna_profile, -1, "WMA") != NULL) {
            self->priv->extension = g_strdup ("wma");
        } else if (g_strstr_len (dlna_profile, -1, "_TS_") != NULL ||
                   g_strstr_len (dlna_profile, -1, "_PS_") != NULL) {
            self->priv->extension = g_strdup ("mpg");
        } else if (g_strstr_len (dlna_profile, -1, "MKV") != NULL) {
            self->priv->extension = g_strdup ("mkv");
        }

        if (self->priv->extension != NULL) {
            goto out;
        }
    }

    value = g_hash_table_lookup (self->priv->meta_data, "ContentType");
    if (value != NULL) {
        content_type = g_variant_get_string (value, NULL);
        if (g_strcmp0 (content_type, "application/ogg") == 0 ||
            g_strstr_len (content_type, -1, "+ogg") != NULL) {
            self->priv->extension = g_strdup ("ogg");
        } else if (g_strcmp0 (content_type, "audio/ogg") == 0) {
            self->priv->extension = g_strdup ("oga");
        } else if (g_strcmp0 (content_type, "video/ogg") == 0) {
            self->priv->extension = g_strdup ("ogv");
        } else if (g_strcmp0 (content_type, "audio/x-matroska") == 0) {
            self->priv->extension = g_strdup ("mka");
        } else if (g_strcmp0 (content_type, "video/x-matroska") == 0) {
            self->priv->extension = g_strdup ("mkv");
        } else if (g_strcmp0 (content_type, "video/webm") == 0) {
            self->priv->extension = g_strdup ("webm");
        } else if (g_strcmp0 (content_type, "image/jpeg") == 0) {
            self->priv->extension = g_strdup ("jpg");
        } else if (g_strcmp0 (content_type, "image/png") == 0) {
            self->priv->extension = g_strdup ("png");
        } else if (g_strcmp0 (content_type, "image/gif") == 0) {
            self->priv->extension = g_strdup ("gif");
        } else if (g_strcmp0 (content_type, "audio/mpeg") == 0) {
            /* Could be anything, but let's use MP3 */
            self->priv->extension = g_strdup ("mp3");
        } else if (g_strrstr (content_type, "/mp4") != NULL) {
            self->priv->extension = g_strdup ("mp4");
        }

        if (self->priv->extension != NULL) {
            goto out;
        }
    }
    self->priv->extension = g_strdup ("dat");

out:
    if (path != NULL) {
        g_free (path);
    }

    return self->priv->extension;
}
Example #2
0
void eServiceMP3::gstBusCall(GstMessage *msg)
{
	if (!msg)
		return;
	gchar *sourceName;
	GstObject *source;
	source = GST_MESSAGE_SRC(msg);
	if (!GST_IS_OBJECT(source))
		return;
	sourceName = gst_object_get_name(source);
#if 0
	gchar *string;
	if (gst_message_get_structure(msg))
		string = gst_structure_to_string(gst_message_get_structure(msg));
	else
		string = g_strdup(GST_MESSAGE_TYPE_NAME(msg));
	eDebug("eTsRemoteSource::gst_message from %s: %s", sourceName, string);
	g_free(string);
#endif
	switch (GST_MESSAGE_TYPE (msg))
	{
		case GST_MESSAGE_EOS:
			m_event((iPlayableService*)this, evEOF);
			break;
		case GST_MESSAGE_STATE_CHANGED:
		{
			if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
				break;

			GstState old_state, new_state;
			gst_message_parse_state_changed(msg, &old_state, &new_state, NULL);
		
			if(old_state == new_state)
				break;
	
			eDebug("eServiceMP3::state transition %s -> %s", gst_element_state_get_name(old_state), gst_element_state_get_name(new_state));
	
			GstStateChange transition = (GstStateChange)GST_STATE_TRANSITION(old_state, new_state);
	
			switch(transition)
			{
				case GST_STATE_CHANGE_NULL_TO_READY:
				{
				}	break;
				case GST_STATE_CHANGE_READY_TO_PAUSED:
				{
					GstElement *subsink = gst_bin_get_by_name(GST_BIN(m_gst_playbin), "subtitle_sink");
					if (subsink)
					{
#ifdef GSTREAMER_SUBTITLE_SYNC_MODE_BUG
						/* 
						 * HACK: disable sync mode for now, gstreamer suffers from a bug causing sparse streams to loose sync, after pause/resume / skip
						 * see: https://bugzilla.gnome.org/show_bug.cgi?id=619434
						 * Sideeffect of using sync=false is that we receive subtitle buffers (far) ahead of their
						 * display time.
						 * Not too far ahead for subtitles contained in the media container.
						 * But for external srt files, we could receive all subtitles at once.
						 * And not just once, but after each pause/resume / skip.
						 * So as soon as gstreamer has been fixed to keep sync in sparse streams, sync needs to be re-enabled.
						 */
						g_object_set (G_OBJECT (subsink), "sync", FALSE, NULL);
#endif
#if 0
						/* we should not use ts-offset to sync with the decoder time, we have to do our own decoder timekeeping */
						g_object_set (G_OBJECT (subsink), "ts-offset", -2L * GST_SECOND, NULL);
						/* late buffers probably will not occur very often */
						g_object_set (G_OBJECT (subsink), "max-lateness", 0L, NULL);
						/* avoid prerolling (it might not be a good idea to preroll a sparse stream) */
						g_object_set (G_OBJECT (subsink), "async", TRUE, NULL);
#endif
						eDebug("eServiceMP3::subsink properties set!");
						gst_object_unref(subsink);
					}
					setAC3Delay(ac3_delay);
					setPCMDelay(pcm_delay);
				}	break;
				case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
				{
					if ( m_sourceinfo.is_streaming && m_streamingsrc_timeout )
						m_streamingsrc_timeout->stop();
				}	break;
				case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
				{
				}	break;
				case GST_STATE_CHANGE_PAUSED_TO_READY:
				{
				}	break;
				case GST_STATE_CHANGE_READY_TO_NULL:
				{
				}	break;
			}
			break;
		}
		case GST_MESSAGE_ERROR:
		{
			gchar *debug;
			GError *err;
			gst_message_parse_error (msg, &err, &debug);
			g_free (debug);
			eWarning("Gstreamer error: %s (%i) from %s", err->message, err->code, sourceName );
			if ( err->domain == GST_STREAM_ERROR )
			{
				if ( err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND )
				{
					if ( g_strrstr(sourceName, "videosink") )
						m_event((iPlayableService*)this, evUser+11);
					else if ( g_strrstr(sourceName, "audiosink") )
						m_event((iPlayableService*)this, evUser+10);
				}
			}
			g_error_free(err);
			break;
		}
		case GST_MESSAGE_INFO:
		{
			gchar *debug;
			GError *inf;
	
			gst_message_parse_info (msg, &inf, &debug);
			g_free (debug);
			if ( inf->domain == GST_STREAM_ERROR && inf->code == GST_STREAM_ERROR_DECODE )
			{
				if ( g_strrstr(sourceName, "videosink") )
					m_event((iPlayableService*)this, evUser+14);
			}
			g_error_free(inf);
			break;
		}
		case GST_MESSAGE_TAG:
		{
			GstTagList *tags, *result;
			gst_message_parse_tag(msg, &tags);
	
			result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_REPLACE);
			if (result)
			{
				if (m_stream_tags)
					gst_tag_list_free(m_stream_tags);
				m_stream_tags = result;
			}
	
			const GValue *gv_image = gst_tag_list_get_value_index(tags, GST_TAG_IMAGE, 0);
			if ( gv_image )
			{
				GstBuffer *buf_image;
				buf_image = gst_value_get_buffer (gv_image);
				int fd = open("/tmp/.id3coverart", O_CREAT|O_WRONLY|O_TRUNC, 0644);
				int ret = write(fd, GST_BUFFER_DATA(buf_image), GST_BUFFER_SIZE(buf_image));
				close(fd);
				eDebug("eServiceMP3::/tmp/.id3coverart %d bytes written ", ret);
				m_event((iPlayableService*)this, evUser+13);
			}
			gst_tag_list_free(tags);
			m_event((iPlayableService*)this, evUpdatedInfo);
			break;
		}
		case GST_MESSAGE_ASYNC_DONE:
		{
			if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
				break;

			GstTagList *tags;
			gint i, active_idx, n_video = 0, n_audio = 0, n_text = 0;

			g_object_get (m_gst_playbin, "n-video", &n_video, NULL);
			g_object_get (m_gst_playbin, "n-audio", &n_audio, NULL);
			g_object_get (m_gst_playbin, "n-text", &n_text, NULL);

			eDebug("eServiceMP3::async-done - %d video, %d audio, %d subtitle", n_video, n_audio, n_text);

			if ( n_video + n_audio <= 0 )
				stop();

			active_idx = 0;

			m_audioStreams.clear();
			m_subtitleStreams.clear();

			for (i = 0; i < n_audio; i++)
			{
				audioStream audio;
				gchar *g_codec, *g_lang;
				GstPad* pad = 0;
				g_signal_emit_by_name (m_gst_playbin, "get-audio-pad", i, &pad);
				GstCaps* caps = gst_pad_get_negotiated_caps(pad);
				if (!caps)
					continue;
				GstStructure* str = gst_caps_get_structure(caps, 0);
				const gchar *g_type = gst_structure_get_name(str);
				eDebug("AUDIO STRUCT=%s", g_type);
				audio.type = gstCheckAudioPad(str);
				g_codec = g_strdup(g_type);
				g_lang = g_strdup_printf ("und");
				g_signal_emit_by_name (m_gst_playbin, "get-audio-tags", i, &tags);
				if ( tags && gst_is_tag_list(tags) )
				{
					gst_tag_list_get_string(tags, GST_TAG_AUDIO_CODEC, &g_codec);
					gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
					gst_tag_list_free(tags);
				}
				audio.language_code = std::string(g_lang);
				audio.codec = std::string(g_codec);
				eDebug("eServiceMP3::audio stream=%i codec=%s language=%s", i, g_codec, g_lang);
				m_audioStreams.push_back(audio);
				g_free (g_lang);
				g_free (g_codec);
				gst_caps_unref(caps);
			}

			for (i = 0; i < n_text; i++)
			{	
				gchar *g_codec = NULL, *g_lang = NULL;
				g_signal_emit_by_name (m_gst_playbin, "get-text-tags", i, &tags);
				subtitleStream subs;

				g_lang = g_strdup_printf ("und");
				if ( tags && gst_is_tag_list(tags) )
				{
					gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang);
					gst_tag_list_get_string(tags, GST_TAG_SUBTITLE_CODEC, &g_codec);
					gst_tag_list_free(tags);
				}

				subs.language_code = std::string(g_lang);
				eDebug("eServiceMP3::subtitle stream=%i language=%s codec=%s", i, g_lang, g_codec);
				
				GstPad* pad = 0;
				g_signal_emit_by_name (m_gst_playbin, "get-text-pad", i, &pad);
				if ( pad )
					g_signal_connect (G_OBJECT (pad), "notify::caps", G_CALLBACK (gstTextpadHasCAPS), this);
				subs.type = getSubtitleType(pad, g_codec);

				m_subtitleStreams.push_back(subs);
				g_free (g_lang);
			}
			m_event((iPlayableService*)this, evUpdatedInfo);

			if ( m_errorInfo.missing_codec != "" )
			{
				if ( m_errorInfo.missing_codec.find("video/") == 0 || ( m_errorInfo.missing_codec.find("audio/") == 0 && getNumberOfTracks() == 0 ) )
					m_event((iPlayableService*)this, evUser+12);
			}
			break;
		}
		case GST_MESSAGE_ELEMENT:
		{
			if (const GstStructure *msgstruct = gst_message_get_structure(msg))
			{
				if ( gst_is_missing_plugin_message(msg) )
				{
					GstCaps *caps;
					gst_structure_get (msgstruct, "detail", GST_TYPE_CAPS, &caps, NULL); 
					std::string codec = (const char*) gst_caps_to_string(caps);
					gchar *description = gst_missing_plugin_message_get_description(msg);
					if ( description )
					{
						eDebug("eServiceMP3::m_errorInfo.missing_codec = %s", codec.c_str());
						m_errorInfo.error_message = "GStreamer plugin " + (std::string)description + " not available!\n";
						m_errorInfo.missing_codec = codec.substr(0,(codec.find_first_of(',')));
						g_free(description);
					}
					gst_caps_unref(caps);
				}
				else
				{
					const gchar *eventname = gst_structure_get_name(msgstruct);
					if ( eventname )
					{
						if (!strcmp(eventname, "eventSizeChanged") || !strcmp(eventname, "eventSizeAvail"))
						{
							gst_structure_get_int (msgstruct, "aspect_ratio", &m_aspect);
							gst_structure_get_int (msgstruct, "width", &m_width);
							gst_structure_get_int (msgstruct, "height", &m_height);
							if (strstr(eventname, "Changed"))
								m_event((iPlayableService*)this, evVideoSizeChanged);
						}
						else if (!strcmp(eventname, "eventFrameRateChanged") || !strcmp(eventname, "eventFrameRateAvail"))
						{
							gst_structure_get_int (msgstruct, "frame_rate", &m_framerate);
							if (strstr(eventname, "Changed"))
								m_event((iPlayableService*)this, evVideoFramerateChanged);
						}
						else if (!strcmp(eventname, "eventProgressiveChanged") || !strcmp(eventname, "eventProgressiveAvail"))
						{
							gst_structure_get_int (msgstruct, "progressive", &m_progressive);
							if (strstr(eventname, "Changed"))
								m_event((iPlayableService*)this, evVideoProgressiveChanged);
						}
					}
				}
			}
			break;
		}
		case GST_MESSAGE_BUFFERING:
		{
			GstBufferingMode mode;
			gst_message_parse_buffering(msg, &(m_bufferInfo.bufferPercent));
			gst_message_parse_buffering_stats(msg, &mode, &(m_bufferInfo.avgInRate), &(m_bufferInfo.avgOutRate), &(m_bufferInfo.bufferingLeft));
			m_event((iPlayableService*)this, evBuffering);
			break;
		}
		case GST_MESSAGE_STREAM_STATUS:
		{
			GstStreamStatusType type;
			GstElement *owner;
			gst_message_parse_stream_status (msg, &type, &owner);
			if ( type == GST_STREAM_STATUS_TYPE_CREATE && m_sourceinfo.is_streaming )
			{
				if ( GST_IS_PAD(source) )
					owner = gst_pad_get_parent_element(GST_PAD(source));
				else if ( GST_IS_ELEMENT(source) )
					owner = GST_ELEMENT(source);
				else
					owner = 0;
				if ( owner )
				{
					GstElementFactory *factory = gst_element_get_factory(GST_ELEMENT(owner));
					const gchar *name = gst_plugin_feature_get_name(GST_PLUGIN_FEATURE(factory));
					if (!strcmp(name, "souphttpsrc"))
					{
						m_streamingsrc_timeout->start(HTTP_TIMEOUT*1000, true);
						g_object_set (G_OBJECT (owner), "timeout", HTTP_TIMEOUT, NULL);
						eDebug("eServiceMP3::GST_STREAM_STATUS_TYPE_CREATE -> setting timeout on %s to %is", name, HTTP_TIMEOUT);
					}
					
				}
				if ( GST_IS_PAD(source) )
					gst_object_unref(owner);
			}
			break;
		}
		default:
			break;
	}
	g_free (sourceName);
}
Example #3
0
void
options_parse(int argc, const char *argv[])
{
	int i;
	const arg_opt_t *opt = NULL;
	option_callback_fn_t option_cb = handle_option;

	for (i = 1; i < argc; i++) {
		const char *arg = argv[i];
		size_t len = strlen(arg);

		/* check for a long option */
		if (g_str_has_prefix(arg, "--")) {
			char *name, *value;

			/* make sure we got an argument for the previous option */
			if( opt && opt->argument )
				option_error(ERROR_MISSING_ARGUMENT, opt->longopt, opt->argument);

			/* retrieve a option argument */
			if ((value=g_strrstr(arg+2, "="))) {
				*value = '\0';
				name = g_strdup(arg);
				*value = '=';
				value++;
			} else
				name = g_strdup(arg);

			/* check if the option exists */
			if( (opt=lookup_option(0, name+2)) == NULL )
				option_error(ERROR_UNKNOWN_OPTION, name, NULL);
			g_free(name);

			/* abort if we got an argument to the option and don't want one */
			if( value && opt->argument==NULL )
				option_error(ERROR_GOT_ARGUMENT, arg, value);

			/* execute option callback */
			if (value || opt->argument==NULL) {
				option_cb (opt->shortopt, value);
				opt = NULL;
			}
		}
		/* check for short options */
		else if (len>=2 && g_str_has_prefix(arg, "-")) {
			size_t j;

			for(j=1; j<len; j++) {
				/* make sure we got an argument for the previous option */
				if (opt && opt->argument)
					option_error(ERROR_MISSING_ARGUMENT,
						     opt->longopt, opt->argument);

				/* check if the option exists */
				if ((opt=lookup_option(arg[j], NULL)) == NULL)
					option_error(ERROR_UNKNOWN_OPTION, arg, NULL);

				/* if no option argument is needed execute callback */
				if (opt->argument == NULL) {
					option_cb (opt->shortopt, NULL);
					opt = NULL;
				}
			}
		} else {
			/* is this a option argument? */
			if (opt && opt->argument) {
				option_cb (opt->shortopt, arg);
				opt = NULL;
			} else
				option_error(ERROR_BAD_ARGUMENT, arg, NULL);
		}
	}

	if (opt && opt->argument == NULL)
		option_cb (opt->shortopt, NULL);
	else if (opt && opt->argument)
		option_error(ERROR_MISSING_ARGUMENT, opt->longopt, opt->argument);

	if (!options.host && getenv("MPD_HOST")) {
		g_free(options.host);
		options.host = g_strdup(getenv("MPD_HOST"));
	}
}
Example #4
0
static void remmina_ftp_client_action_upload(GObject *object, RemminaFTPClient *client)
{
	RemminaFTPClientPriv *priv = (RemminaFTPClientPriv*) client->priv;
	GtkListStore *store = GTK_LIST_STORE(priv->task_list_model);
	GtkTreeIter iter;
	GtkWidget *dialog;
	GtkWidget *upload_folder_check;
	gint type;
	GSList *files = NULL;
	GSList *element;
	gchar *path;
	gchar *dir, *name;
	struct stat st;

	dialog = gtk_file_chooser_dialog_new(_("Choose a file to upload"),
			GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(client))), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL,
			GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_ACCEPT, NULL);
	gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog), TRUE);
	if (priv->working_directory)
	{
		gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), priv->working_directory);
	}
	upload_folder_check = gtk_check_button_new_with_label(_("Upload folder"));
	gtk_widget_show(upload_folder_check);
	g_signal_connect(G_OBJECT(upload_folder_check), "toggled", G_CALLBACK(remmina_ftp_client_upload_folder_on_toggled),
			dialog);
	gtk_file_chooser_set_extra_widget(GTK_FILE_CHOOSER(dialog), upload_folder_check);
	if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT)
	{
		g_free(priv->working_directory);
		priv->working_directory = gtk_file_chooser_get_current_folder(GTK_FILE_CHOOSER(dialog));
		files = gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(dialog));
	}
	type = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(upload_folder_check)) ?
			REMMINA_FTP_FILE_TYPE_DIR : REMMINA_FTP_FILE_TYPE_FILE;
	gtk_widget_destroy(dialog);
	if (!files)
		return;

	for (element = files; element; element = element->next)
	{
		path = (gchar*) element->data;

		if (g_stat(path, &st) < 0)
			continue;

		name = g_strrstr(path, "/");
		if (name)
		{
			*name++ = '\0';
			dir = path;
		}
		else
		{
			name = path;
			dir = NULL;
		}

		gtk_list_store_append(store, &iter);
		gtk_list_store_set(store, &iter, REMMINA_FTP_TASK_COLUMN_TYPE, type, REMMINA_FTP_TASK_COLUMN_NAME, name,
				REMMINA_FTP_TASK_COLUMN_SIZE, (gfloat) st.st_size, REMMINA_FTP_TASK_COLUMN_TASKID,
				remmina_ftp_client_taskid++, REMMINA_FTP_TASK_COLUMN_TASKTYPE, REMMINA_FTP_TASK_TYPE_UPLOAD,
				REMMINA_FTP_TASK_COLUMN_REMOTEDIR, priv->current_directory, REMMINA_FTP_TASK_COLUMN_LOCALDIR,
				dir, REMMINA_FTP_TASK_COLUMN_STATUS, REMMINA_FTP_TASK_STATUS_WAIT,
				REMMINA_FTP_TASK_COLUMN_DONESIZE, 0.0, REMMINA_FTP_TASK_COLUMN_TOOLTIP, NULL, -1);

		g_free(path);
	}

	g_slist_free(files);

	g_signal_emit(G_OBJECT(client), remmina_ftp_client_signals[NEW_TASK_SIGNAL], 0);
}
gboolean
panel_object_iid_to_type (const char       *iid,
                          PanelObjectType  *type,
                          char            **detail)
{
	const char *instance_id;
	char       *factory_id;
	gboolean    is_applet;;
        int         i;

        if (detail)
                *detail = NULL;

	instance_id = g_strrstr (iid, "::");
        if (!instance_id)
                return FALSE;

	factory_id = g_strndup (iid, strlen (iid) - strlen (instance_id));
        is_applet = (g_strcmp0 (factory_id, PANEL_INTERNAL_FACTORY) != 0);
        g_free (factory_id);

        if (is_applet) {
                *type = PANEL_OBJECT_APPLET;
                return TRUE;
        }

	instance_id += 2;

        for (i = 0; i < G_N_ELEMENTS (panel_object_iid_map); i++) {
                if (!panel_object_iid_map[i].has_detail &&
                    g_strcmp0 (panel_object_iid_map[i].id,
                               instance_id) == 0) {
                        *type = panel_object_iid_map[i].type;
                        return TRUE;
                }

                if (panel_object_iid_map[i].has_detail) {
                        const char *d;

                        if (!g_str_has_prefix (instance_id,
                                               panel_object_iid_map[i].id))
                                continue;

                        d = instance_id + strlen (panel_object_iid_map[i].id);
                        if (d[0] != ':')
                                return FALSE;

                        d += 1;
                        if (d[0] == '\0')
                                return FALSE;

                        *type = panel_object_iid_map[i].type;
                        if (detail)
                                *detail = g_strdup (d);

                        return TRUE;
                }
        }

        /* We don't know this id; it could be provided by an applet now (for
         * features that moved from being internal to the panel to applets, and
         * that provide compatibility with the same id). So let's try it.  */
        *type = PANEL_OBJECT_APPLET;
        return TRUE;
}
Example #6
0
/* this actually does the work */
int store(dt_imageio_module_storage_t *self, struct 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_colorspaces_color_profile_type_t icc_type,
          const gchar *icc_filename, dt_iop_color_intent_t icc_intent)
{
  dt_storage_gphoto_gui_data_t *ui = self->gui_data;

  gint result = 1;
  dt_gphoto_context_t *ctx = (dt_gphoto_context_t *)sdata;

  const char *ext = format->extension(fdata);
  char fname[PATH_MAX] = { 0 };
  dt_loc_get_tmp_dir(fname, sizeof(fname));
  g_strlcat(fname, "/darktable.XXXXXX.", sizeof(fname));
  g_strlcat(fname, ext, sizeof(fname));

  gint fd = g_mkstemp(fname);
  if(fd == -1)
  {
    dt_control_log("failed to create temporary image for google photos export");
    return 1;
  }
  close(fd);

  // get metadata
  const dt_image_t *img = dt_image_cache_get(darktable.image_cache, imgid, 'r');
  char *title = NULL;
  char *summary = NULL;
  GList *meta_title = NULL;

  title = g_path_get_basename(img->filename);
  (g_strrstr(title, "."))[0] = '\0'; // Chop extension...

  meta_title = dt_metadata_get(img->id, "Xmp.dc.title", NULL);
  summary = meta_title != NULL ? meta_title->data : "";

  dt_image_cache_read_release(darktable.image_cache, img);

  if(dt_imageio_export(imgid, fname, format, fdata, high_quality, upscale, FALSE, icc_type, icc_filename, icc_intent,
                       self, sdata, num, total) != 0)
  {
    g_printerr("[gphoto] could not export to file: `%s'!\n", fname);
    dt_control_log(_("could not export to file `%s'!"), fname);
    result = 0;
    goto cleanup;
  }

  if(!*(ctx->album_id))
  {
    if(ctx->album_title == NULL)
    {
      dt_control_log(_("unable to create album, no title provided"));
      result = 0;
      goto cleanup;
    }
    const gchar *album_id  = gphoto_create_album(ui, ctx, ctx->album_title);
    if(album_id == NULL)
    {
      dt_control_log(_("unable to create album"));
      result = 0;
      goto cleanup;
    }
    g_snprintf(ctx->album_id, sizeof(ctx->album_id), "%s", album_id);
  }

  const char *photoid = gphoto_upload_photo_to_album(ctx, ctx->album_id, fname, title, summary, imgid);
  if(photoid == NULL)
  {
    dt_control_log(_("unable to export to google photos album"));
    result = 0;
    goto cleanup;
  }

cleanup:
  g_unlink(fname);
  g_free(title);
  g_list_free_full(meta_title, &g_free);

  if(result)
  {
    // this makes sense only if the export was successful
    dt_control_log(ngettext("%d/%d exported to google photos album", "%d/%d exported to google photos album", num), num, total);
  }
  return 0;
}
Example #7
0
/*!
  \brief read_log_header() First we read the first line,  try to determine 
  if the delimiter is a COMMA, or a TAB. 
  \param iochannel is the iochannel that represents the input file
  \param log_info is the the Log_Info structure
  */
G_MODULE_EXPORT void read_log_header(GIOChannel *iochannel, Log_Info *log_info )
{
	GString *a_line = g_string_new("\0");
	GIOStatus  status = G_IO_STATUS_ERROR;
	gchar *delimiter = NULL;
	gchar **fields = NULL;
	gint num_fields = 0;
	GArray *array = NULL;
	gconstpointer *object = NULL;
	Rtv_Map *rtv_map;
	extern gconstpointer *global_data;
	
	ENTER();
	rtv_map = (Rtv_Map *)DATA_GET(global_data,"rtv_map");

read_again:
	status = g_io_channel_read_line_string(iochannel,a_line,NULL,NULL); 

	if (status == G_IO_STATUS_NORMAL) /* good read */
	{
		/* This searched for a quoted string which should be the 
		 * ecu signature.  pre 0.9.15 versions of megatunix shoved the
		 * internal name of the firmware in there which is a problem as
		 * it makes the logs locked to megatunix which is a bad thing 
		 * as it hurts interoperability.  0.9.16+ changes this to use 
		 * the REAL signature returned by the firmware. 
		 */
		if (g_strrstr(a_line->str,"\"") != NULL)
		{
			log_info->signature = g_strdup(g_strstrip(g_strdelimit(a_line->str,"\"\n\r",' ')));
			/*printf(_("LOG signature is \"%s\"\n"),log_info->signature);*/
			if (DATA_GET(global_data,"offline"))
			{
				printf("rtv_map->applicable_signatures is \"%s\"\n",rtv_map->applicable_signatures);
				if (rtv_map->applicable_signatures)
				{
					if (strstr(rtv_map->applicable_signatures,log_info->signature) != NULL)
						printf(_("Good this firmware is compatible with the firmware we're using\n"));
					else
						printf(_("mismatch between datalog and current firmware, playback via full gui will probably not work like you expected\n"));
				}
			}
			goto read_again;
		}

		if (g_strrstr(a_line->str,",") != NULL)
			delimiter = g_strdup(",");
		else if (g_strrstr(a_line->str,"\t") != NULL)
			delimiter = g_strdup("\t");

		/* Store delimiter in structure */
		log_info->delimiter = g_strdup(delimiter);
		/* Store field names as well... 
		 * log_info->fields is a string vector (char **)
		 * that is NULL terminated thanks to g_strsplit(void)
		 */
		fields = parse_keys(a_line->str,&num_fields,delimiter);

		log_info->field_count = num_fields;
		/* Create objects, arrays and storage points... */
		for (gint i=0;i<num_fields;i++)
		{
			array = NULL;
			object = g_new0(gconstpointer, 1);
			array = g_array_sized_new(FALSE,TRUE,sizeof(gfloat),4096);
			DATA_SET(object,"data_array",(gpointer)array);
			g_free(DATA_GET(object,"lview_name"));
			DATA_SET_FULL(object,"lview_name",g_strdup(g_strstrip(fields[i])),g_free);
			g_ptr_array_add(log_info->log_list,object);
		}
		/* Enable parameter selection button */
		gtk_widget_set_sensitive(lookup_widget("logviewer_select_params_button"), TRUE);
		OBJ_SET(lookup_widget("logviewer_trace_darea"),"log_info",(gpointer)log_info);

	}
	g_free(delimiter);
	EXIT();
	return;
}
Example #8
0
int tgp_msg_send (struct tgl_state *TLS, const char *message, tgl_peer_id_t to) {

#ifndef __ADIUM_
  // search for outgoing embedded image tags and send them
  gchar *img = NULL;
  gchar *stripped = NULL;
  
  if ((img = g_strrstr (message, "<IMG")) || (img = g_strrstr (message, "<img"))) {
    if (tgl_get_peer_type(to) == TGL_PEER_ENCR_CHAT) {
      tgp_msg_err_out (TLS, _("Sorry, sending documents to encrypted chats not yet supported."), to);
      return 0;
    }
    debug ("img found: %s", img);
    gchar *id;
    if ((id = g_strrstr (img, "ID=\"")) || (id = g_strrstr (img, "id=\""))) {
      id += 4;
      int imgid = atoi (id);
      if (imgid > 0) {
        PurpleStoredImage *psi = purple_imgstore_find_by_id (imgid);
        if (! psi) {
          failure ("Img %d not found in imgstore", imgid);
          return -1;
        }
        gchar *tmp = g_build_filename (g_get_tmp_dir(), purple_imgstore_get_filename (psi), NULL) ;
        GError *err = NULL;
        gconstpointer data = purple_imgstore_get_data (psi);
        g_file_set_contents (tmp, data, purple_imgstore_get_size (psi), &err);
        if (! err) {
          stripped = g_strstrip(purple_markup_strip_html (message));
          tgl_do_send_document (TLS, to, tmp, stripped, (int)strlen (stripped),
                                TGL_SEND_MSG_FLAG_DOCUMENT_AUTO, send_inline_picture_done, NULL);
          g_free (stripped);
          
          // return 0 to assure that the picture is not echoed, since
          // it will already be echoed with the outgoing message
          return 0;
        } else {
          failure ("Storing %s in imagestore failed: %s\n", tmp, err->message);
          g_error_free (err);
          return -1;
        }
      }
    }
    // no image id found in image
    return -1;
  }
  
  /*
    Adium won't escape any HTML markup and just pass any user-input through,
    while Pidgin will replace special chars with the escape chars and also add 
    additional markup for RTL languages and such.

    First, we remove any HTML markup added by Pidgin, since Telegram won't handle it properly.
    User-entered HTML is still escaped and therefore won't be harmed.
   */
  stripped = purple_markup_strip_html (message);
  
   // now unescape the markup, so that html special chars will still show
   // up properly in Telegram
  gchar *unescaped = purple_unescape_text (stripped);
  int ret = tgp_msg_send_split (TLS, stripped, to);
  
  g_free (unescaped);
  g_free (stripped);
  return ret;
#endif
  
  // when the other peer receives a message it is obvious that the previous messages were read
  pending_reads_send_user (TLS, to);
  
  return tgp_msg_send_split (TLS, message, to);
}
Example #9
0
static xmlDocPtr
merge_specs (const gchar *xml_dir, GdaServerOperationType type, gboolean *op_supported, GError **error)
{
	xmlDocPtr doc = NULL;
	xmlNodePtr root = NULL;
	GDir *dir;
	const gchar *file;
	gchar *lcprov = NULL;
	dir = g_dir_open (xml_dir, 0, error);
	if (!dir)
		return NULL;

	if (prov)
		lcprov = g_ascii_strdown (prov, -1);
	*op_supported = FALSE;

	for (file = g_dir_read_name (dir); file; file = g_dir_read_name (dir)) {
		gchar *suffix, *lc;

		lc = g_ascii_strdown (gda_server_operation_op_type_to_string (type), -1);
		suffix = g_strdup_printf ("_specs_%s.xml", lc);
		g_free (lc);
		if (g_str_has_suffix (file, suffix)) {
			gchar *provider_end, *provider;

			xmlDocPtr pdoc;
			gchar *cfile = g_build_filename (xml_dir, file, NULL);

			provider = g_strdup (file);
			provider_end = g_strrstr (provider, suffix);
			*provider_end = 0;
			
			if (lcprov && strcmp (lcprov, provider)) {
				/* handle the name mismatch between the provider named "PostgreSQL" and
				 * the file names which start with "postgres" */
				if (strcmp (provider, "postgres") || strcmp (lcprov, "postgresql"))
					continue;
			}

			*op_supported = TRUE;
			pdoc = xmlParseFile (cfile);
			g_free (cfile);
			if (!pdoc) {
				g_warning (_("Can't parse file '%s', ignoring it"), file);
				continue;
			}

			remove_all_extra (xmlDocGetRootElement (pdoc));

			if (!doc) {
				doc = xmlNewDoc (BAD_CAST "1.0");
				root = xmlNewNode (NULL, BAD_CAST "server_op");
				xmlDocSetRootElement (doc, root);
			}
			merge_spec_from_root (root, provider, pdoc);
						
			xmlFreeDoc (pdoc);
			g_free (provider);
		}
		g_free (suffix);
	}
	g_dir_close (dir);
	g_free (lcprov);
	return doc;
}
Example #10
0
static const char * get_kcmdline_string(const char *entry)
{
  int fd;
  char cmdLine[1024];
  const char *ret = NULL;
  int len;
  gint argc = 0;
  gchar **argv = NULL;
  gchar **arg_tokens = NULL, **network_tokens = NULL;
  GError *optErr = NULL;
  int i;

  if ((fd = open("/proc/cmdline", O_RDONLY)) < 0)
  {
    log_debug("could not read /proc/cmdline");
    return(ret);
  }

  len = read(fd, cmdLine, sizeof(cmdLine) - 1);
  close(fd);

  if (len <= 0)
  {
    log_debug("kernel command line was empty");
    return(ret);
  }

  cmdLine[len] = '\0';

  /* we're looking for a piece of the kernel command line matching this:
    ip=192.168.3.100::192.168.3.1:255.255.255.0::usb0:on */
  if (!g_shell_parse_argv(cmdLine, &argc, &argv, &optErr)) 
  {
    g_error_free(optErr);
    return(ret);
  }

  /* find the ip token */
  for (i=0; i < argc; i++) 
  {
    arg_tokens = g_strsplit(argv[i], "=", 2);
    if (!g_ascii_strcasecmp(arg_tokens[0], "usb_moded_ip"))
    {
      network_tokens = g_strsplit(arg_tokens[1], ":", 7);
      /* check if it is for the usb or rndis interface */
      if(g_strrstr(network_tokens[5], "usb")|| (g_strrstr(network_tokens[5], "rndis")))
      {
	if(!strcmp(entry, NETWORK_IP_KEY))
	{
		ret = g_strdup(network_tokens[0]);
		log_debug("Command line ip = %s\n", ret);
	}
	if(!strcmp(entry, NETWORK_GATEWAY_KEY))
	{
		/* gateway might be empty, so we do not want to return an empty string */
		if(strlen(network_tokens[2]) > 2)
		{
		  ret = g_strdup(network_tokens[2]);
		  log_debug("Command line gateway = %s\n", ret);
		}
	}
      } 
    }
    g_strfreev(arg_tokens);
  }
  g_strfreev(argv);
  g_strfreev(network_tokens);

  return(ret);
}
static gboolean
emfpe_headers_format (EMailFormatterExtension *extension,
                      EMailFormatter *formatter,
                      EMailFormatterContext *context,
                      EMailPart *part,
                      GOutputStream *stream,
                      GCancellable *cancellable)
{
	EMailPartHeaders *headers_part;
	GtkTreeModel *tree_model;
	GtkTreeIter iter;
	gboolean iter_valid;
	GString *str, *tmp;
	gchar *subject;
	const gchar *buf;
	gint attachments_count;
	gchar *part_id_prefix;
	CamelMimePart *mime_part;
	GQueue queue = G_QUEUE_INIT;
	GList *head, *link;
	const gchar *part_id;

	g_return_val_if_fail (E_IS_MAIL_PART_HEADERS (part), FALSE);

	mime_part = e_mail_part_ref_mime_part (part);

	buf = camel_medium_get_header (CAMEL_MEDIUM (mime_part), "subject");
	subject = camel_header_decode_string (buf, "UTF-8");
	str = g_string_new ("");
	g_string_append_printf (str, "<h1>%s</h1>\n", subject);
	g_free (subject);

	g_string_append (
		str,
		"<table border=\"0\" cellspacing=\"5\" "
		"cellpadding=\"0\" class=\"printing-header\">\n");

	headers_part = E_MAIL_PART_HEADERS (part);
	tree_model = e_mail_part_headers_ref_print_model (headers_part);
	iter_valid = gtk_tree_model_get_iter_first (tree_model, &iter);

	while (iter_valid) {
		gchar *header_name = NULL;
		gchar *header_value = NULL;
		gboolean include = FALSE;

		gtk_tree_model_get (
			tree_model, &iter,
			E_MAIL_PART_HEADERS_PRINT_MODEL_COLUMN_INCLUDE,
			&include,
			E_MAIL_PART_HEADERS_PRINT_MODEL_COLUMN_HEADER_NAME,
			&header_name,
			E_MAIL_PART_HEADERS_PRINT_MODEL_COLUMN_HEADER_VALUE,
			&header_value,
			-1);

		if (include)
			e_mail_formatter_format_header (
				formatter, str,
				header_name, header_value,
				E_MAIL_FORMATTER_HEADER_FLAG_NOLINKS,
				"UTF-8");

		g_free (header_name);
		g_free (header_value);

		iter_valid = gtk_tree_model_iter_next (tree_model, &iter);
	}

	g_object_unref (tree_model);

	/* Get prefix of this PURI */
	part_id = e_mail_part_get_id (part);
	part_id_prefix = g_strndup (part_id, g_strrstr (part_id, ".") - part_id);

	/* Add encryption/signature header */
	tmp = g_string_new ("");

	e_mail_part_list_queue_parts (context->part_list, NULL, &queue);

	head = g_queue_peek_head_link (&queue);

	/* Find first secured part. */
	for (link = head; link != NULL; link = g_list_next (link)) {
		EMailPart *mail_part = link->data;

		if (!e_mail_part_has_validity (mail_part))
			continue;

		if (!e_mail_part_id_has_prefix (mail_part, part_id_prefix))
			continue;

		if (e_mail_part_get_validity (mail_part, E_MAIL_PART_VALIDITY_PGP | E_MAIL_PART_VALIDITY_SIGNED)) {
			g_string_append (tmp, _("GPG signed"));
		}

		if (e_mail_part_get_validity (mail_part, E_MAIL_PART_VALIDITY_PGP | E_MAIL_PART_VALIDITY_ENCRYPTED)) {
			if (tmp->len > 0)
				g_string_append (tmp, ", ");
			g_string_append (tmp, _("GPG encrpyted"));
		}

		if (e_mail_part_get_validity (mail_part, E_MAIL_PART_VALIDITY_SMIME | E_MAIL_PART_VALIDITY_SIGNED)) {
			if (tmp->len > 0)
				g_string_append (tmp, ", ");
			g_string_append (tmp, _("S/MIME signed"));
		}

		if (e_mail_part_get_validity (mail_part, E_MAIL_PART_VALIDITY_SMIME | E_MAIL_PART_VALIDITY_ENCRYPTED)) {
			if (tmp->len > 0)
				g_string_append (tmp, ", ");
			g_string_append (tmp, _("S/MIME encrpyted"));
		}

		break;
	}

	if (tmp->len > 0) {
		e_mail_formatter_format_header (
			formatter, str,
			_("Security"), tmp->str,
			E_MAIL_FORMATTER_HEADER_FLAG_BOLD |
			E_MAIL_FORMATTER_HEADER_FLAG_NOLINKS, "UTF-8");
	}
	g_string_free (tmp, TRUE);

	/* Count attachments and display the number as a header */
	attachments_count = 0;

	for (link = head; link != NULL; link = g_list_next (link)) {
		EMailPart *mail_part = E_MAIL_PART (link->data);

		if (!e_mail_part_id_has_prefix (mail_part, part_id_prefix))
			continue;

		if (!e_mail_part_get_is_attachment (mail_part))
			continue;

		if (mail_part->is_hidden)
			continue;

		if (e_mail_part_get_cid (mail_part) != NULL)
			continue;

		attachments_count++;
	}

	if (attachments_count > 0) {
		gchar *header_value;

		header_value = g_strdup_printf ("%d", attachments_count);
		e_mail_formatter_format_header (
			formatter, str,
			_("Attachments"), header_value,
			E_MAIL_FORMATTER_HEADER_FLAG_BOLD |
			E_MAIL_FORMATTER_HEADER_FLAG_NOLINKS, "UTF-8");
		g_free (header_value);
	}

	while (!g_queue_is_empty (&queue))
		g_object_unref (g_queue_pop_head (&queue));

	g_string_append (str, "</table>");

	g_output_stream_write_all (
		stream, str->str, str->len, NULL, cancellable, NULL);

	g_string_free (str, TRUE);
	g_free (part_id_prefix);

	g_object_unref (mime_part);

	return TRUE;
}
Example #12
0
static GList * gt_guitaretabs_parse (cb_object * capo)
{
    GList * result_list = NULL;
    gchar * begin_search = strstr (capo->cache->data,SEARCH_RESULTS_BEGIN);
    if (begin_search != NULL)
    {
        /* End need to assure we don't get over the search results */
        gchar * endin_search = strstr (begin_search,SEARCH_RESULTS_ENDIN);
        if (endin_search != NULL)
        {
            /* Go through all search results */
            gchar * node  = begin_search;
            gsize nodelen = (sizeof SEARCH_NODE) - 1;
            while (continue_search (g_list_length (result_list),capo->s) && (node = strstr (node + nodelen, SEARCH_NODE) ) != NULL && node <= endin_search)
            {
                gchar * artist = get_search_value (node,ARTIST_BEGIN,ARTIST_END);
                node = strstr (node + nodelen, SEARCH_NODE);
                if (node != NULL)
                {
                    gchar * url = get_search_value (node,SEARCH_NODE,URL_END);
                    gchar * title = get_search_value (node,TITLE_BEGIN,TITLE_ENDIN);

                    if (title != NULL)
                    {
                        gchar * delim = g_strrstr (title," chords");
                        if (delim == NULL)
                        {
                            delim = g_strrstr (title," tab");
                        }

                        if (delim != NULL)
                        {
                            delim[0] = 0;
                        }
                    }

                    /* Check if this is the item we actually search */
                    if (levenshtein_strnormcmp (capo->s,title, capo->s->title ) <= capo->s->fuzzyness &&
                            levenshtein_strnormcmp (capo->s,artist,capo->s->artist) <= capo->s->fuzzyness)
                    {
                        /* Build resulting url */
                        gchar * result_url = g_strdup_printf ("%s%s",GT_BASE,url);

                        /* Go and parse it */
                        GlyrMemCache * result = parse_single_page (capo->s,result_url);
                        if (result != NULL)
                        {
                            result_list = g_list_prepend (result_list,result);
                        }
                        g_free (result_url);
                    }
                    g_free (url);
                    g_free (title);

                }
                g_free (artist);
            }
        }
    }
    return result_list;
}
static void
do_get (OtTrivialHttpd    *self,
        SoupServer        *server,
        SoupMessage       *msg,
        const char        *path,
        SoupClientContext *context)
{
  char *slash;
  int ret;
  struct stat stbuf;
  g_autofree char *safepath = NULL;

  httpd_log (self, "serving %s\n", path);
  if (strstr (path, "../") != NULL)
    {
      soup_message_set_status (msg, SOUP_STATUS_FORBIDDEN);
      goto out;
    }

  if (opt_random_500s_percentage > 0 &&
      emitted_random_500s_count < opt_random_500s_max &&
      g_random_int_range (0, 100) < opt_random_500s_percentage)
    {
      emitted_random_500s_count++;
      soup_message_set_status (msg, SOUP_STATUS_INTERNAL_SERVER_ERROR);
      goto out;
    }

  if (path[0] == '/')
    path++;

  safepath = g_build_filename (gs_file_get_path_cached (self->root), path, NULL);

  do
    ret = stat (safepath, &stbuf);
  while (ret == -1 && errno == EINTR);
  if (ret == -1)
    {
      if (errno == EPERM)
        soup_message_set_status (msg, SOUP_STATUS_FORBIDDEN);
      else if (errno == ENOENT)
        soup_message_set_status (msg, SOUP_STATUS_NOT_FOUND);
      else
        soup_message_set_status (msg, SOUP_STATUS_INTERNAL_SERVER_ERROR);
      goto out;
    }

  if (!is_safe_to_access (&stbuf))
    {
      soup_message_set_status (msg, SOUP_STATUS_FORBIDDEN);
      goto out;
    }

  if (S_ISDIR (stbuf.st_mode))
    {
      slash = strrchr (safepath, '/');
      if (!slash || slash[1])
        {
          g_autofree char *redir_uri = NULL;

          redir_uri = g_strdup_printf ("%s/", soup_message_get_uri (msg)->path);
          soup_message_set_redirect (msg, SOUP_STATUS_MOVED_PERMANENTLY,
                                     redir_uri);
        }
      else
        {
          g_autofree char *index_realpath = g_strconcat (safepath, "/index.html", NULL);
          if (stat (index_realpath, &stbuf) != -1)
            {
              g_autofree char *index_path = g_strconcat (path, "/index.html", NULL);
              do_get (self, server, msg, index_path, context);
            }
          else
            {
              GString *listing = get_directory_listing (safepath);
              soup_message_set_response (msg, "text/html",
                                         SOUP_MEMORY_TAKE,
                                         listing->str, listing->len);
              soup_message_set_status (msg, SOUP_STATUS_OK);
              g_string_free (listing, FALSE);
            }
        }
    }
  else 
    {
      if (!S_ISREG (stbuf.st_mode))
        {
          soup_message_set_status (msg, SOUP_STATUS_FORBIDDEN);
          goto out;
        }
      
      if (msg->method == SOUP_METHOD_GET)
        {
          g_autoptr(GMappedFile) mapping = NULL;
          gsize buffer_length, file_size;
          SoupRange *ranges;
          int ranges_length;
          gboolean have_ranges;

          mapping = g_mapped_file_new (safepath, FALSE, NULL);
          if (!mapping)
            {
              soup_message_set_status (msg, SOUP_STATUS_INTERNAL_SERVER_ERROR);
              goto out;
            }

          file_size = g_mapped_file_get_length (mapping);
          have_ranges = soup_message_headers_get_ranges(msg->request_headers, file_size, &ranges, &ranges_length);
          if (opt_force_ranges && !have_ranges && g_strrstr (path, "/objects") != NULL)
            {
              SoupSocket *sock;
              buffer_length = file_size/2;
              soup_message_headers_set_content_length (msg->response_headers, file_size);
              soup_message_headers_append (msg->response_headers,
                                           "Connection", "close");

              /* soup-message-io will wait for us to add
               * another chunk after the first, to fill out
               * the declared Content-Length. Instead, we
               * forcibly close the socket at that point.
               */
              sock = soup_client_context_get_socket (context);
              g_signal_connect (msg, "wrote-chunk", G_CALLBACK (close_socket), sock);
            }
          else
            buffer_length = file_size;

          if (have_ranges)
            {
              if (ranges_length > 0 && ranges[0].start >= file_size)
                {
                  soup_message_set_status (msg, SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE);
                  soup_message_headers_free_ranges (msg->request_headers, ranges);
                  goto out;
                }
              soup_message_headers_free_ranges (msg->request_headers, ranges);
            }
          if (buffer_length > 0)
            {
              SoupBuffer *buffer;

              buffer = soup_buffer_new_with_owner (g_mapped_file_get_contents (mapping),
                                                   buffer_length,
                                                   g_mapped_file_ref (mapping),
                                                   (GDestroyNotify)g_mapped_file_unref);
              soup_message_body_append_buffer (msg->response_body, buffer);
              soup_buffer_free (buffer);
            }
        }
      else /* msg->method == SOUP_METHOD_HEAD */
        {
          g_autofree char *length = NULL;

          /* We could just use the same code for both GET and
           * HEAD (soup-message-server-io.c will fix things up).
           * But we'll optimize and avoid the extra I/O.
           */
          length = g_strdup_printf ("%lu", (gulong)stbuf.st_size);
          soup_message_headers_append (msg->response_headers,
                                       "Content-Length", length);
        }
      soup_message_set_status (msg, SOUP_STATUS_OK);
    }
 out:
  {
    guint status = 0;
    g_autofree gchar *reason = NULL;

    g_object_get (msg,
                  "status-code", &status,
                  "reason-phrase", &reason,
                  NULL);
    httpd_log (self, "  status: %s (%u)\n", reason, status);
  }
  return;
}
Example #14
0
gboolean _variable_get_value(dt_variables_params_t *params, gchar *variable, gchar *value, size_t value_len)
{
  const gchar *file_ext = NULL;
  gboolean got_value = FALSE;
  struct tm *tim = localtime(&params->data->time);

  const gchar *homedir = dt_loc_get_home_dir(NULL);

  gchar *pictures_folder = NULL;

  if(g_get_user_special_dir(G_USER_DIRECTORY_PICTURES) == NULL)
    pictures_folder = g_build_path(G_DIR_SEPARATOR_S, homedir, "Pictures", (char *)NULL);
  else
    pictures_folder = g_strdup(g_get_user_special_dir(G_USER_DIRECTORY_PICTURES));

  if(params->filename)
  {
    file_ext = (g_strrstr(params->filename, ".") + 1);
    if(file_ext == (gchar *)1) file_ext = params->filename + strlen(params->filename);
  }

  /* image exif time */
  gboolean have_exif_tm = FALSE;
  int exif_iso = 100;
  char camera_maker[64];
  char camera_alias[64];
  int version = 0;
  int stars = 0;
  struct tm exif_tm = { 0 };
  if(params->imgid)
  {
    const dt_image_t *img = dt_image_cache_get(darktable.image_cache, params->imgid, 'r');
    if(sscanf(img->exif_datetime_taken, "%d:%d:%d %d:%d:%d", &exif_tm.tm_year, &exif_tm.tm_mon,
              &exif_tm.tm_mday, &exif_tm.tm_hour, &exif_tm.tm_min, &exif_tm.tm_sec) == 6)
    {
      exif_tm.tm_year -= 1900;
      exif_tm.tm_mon--;
      have_exif_tm = TRUE;
    }
    exif_iso = img->exif_iso;
    g_strlcpy(camera_maker, img->camera_maker, sizeof(camera_maker));
    g_strlcpy(camera_alias, img->camera_alias, sizeof(camera_alias));
    version = img->version;
    stars = (img->flags & 0x7);
    if(stars == 6) stars = -1;

    dt_image_cache_read_release(darktable.image_cache, img);
  }

  if(g_strcmp0(variable, "$(YEAR)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%.4d", tim->tm_year + 1900);
  else if(g_strcmp0(variable, "$(MONTH)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%.2d", tim->tm_mon + 1);
  else if(g_strcmp0(variable, "$(DAY)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%.2d", tim->tm_mday);
  else if(g_strcmp0(variable, "$(HOUR)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%.2d", tim->tm_hour);
  else if(g_strcmp0(variable, "$(MINUTE)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%.2d", tim->tm_min);
  else if(g_strcmp0(variable, "$(SECOND)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%.2d", tim->tm_sec);

  else if(g_strcmp0(variable, "$(EXIF_YEAR)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%.4d", (have_exif_tm ? exif_tm.tm_year : tim->tm_year) + 1900);
  else if(g_strcmp0(variable, "$(EXIF_MONTH)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%.2d", (have_exif_tm ? exif_tm.tm_mon : tim->tm_mon) + 1);
  else if(g_strcmp0(variable, "$(EXIF_DAY)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%.2d", (have_exif_tm ? exif_tm.tm_mday : tim->tm_mday));
  else if(g_strcmp0(variable, "$(EXIF_HOUR)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%.2d", (have_exif_tm ? exif_tm.tm_hour : tim->tm_hour));
  else if(g_strcmp0(variable, "$(EXIF_MINUTE)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%.2d", (have_exif_tm ? exif_tm.tm_min : tim->tm_min));
  else if(g_strcmp0(variable, "$(EXIF_SECOND)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%.2d", (have_exif_tm ? exif_tm.tm_sec : tim->tm_sec));
  else if(g_strcmp0(variable, "$(EXIF_ISO)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%d", exif_iso);
  else if(g_strcmp0(variable, "$(MAKER)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%s", camera_maker);
  else if(g_strcmp0(variable, "$(MODEL)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%s", camera_alias);
  else if(g_strcmp0(variable, "$(ID)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%d", params->imgid);
  else if(g_strcmp0(variable, "$(VERSION)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%d", version);
  else if(g_strcmp0(variable, "$(JOBCODE)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%s", params->jobcode);
  else if(g_strcmp0(variable, "$(ROLL_NAME)") == 0 && params->filename && (got_value = TRUE))
  {
    gchar *dirname = g_path_get_dirname(params->filename);
    gchar *basename = g_path_get_basename(dirname);
    snprintf(value, value_len, "%s", basename);
    g_free(basename);
    g_free(dirname);
  }
  else if(g_strcmp0(variable, "$(FILE_DIRECTORY)") == 0 && params->filename && (got_value = TRUE))
  {
    gchar *dirname = g_path_get_dirname(params->filename);
    snprintf(value, value_len, "%s", dirname);
    g_free(dirname);
  } // undocumented : backward compatibility
  else if(g_strcmp0(variable, "$(FILE_FOLDER)") == 0 && params->filename && (got_value = TRUE))
  {
    gchar *dirname = g_path_get_dirname(params->filename);
    snprintf(value, value_len, "%s", dirname);
    g_free(dirname);
  }
  else if(g_strcmp0(variable, "$(FILE_NAME)") == 0 && params->filename && (got_value = TRUE))
  {
    gchar *basename = g_path_get_basename(params->filename);
    snprintf(value, value_len, "%s", basename);
    g_free(basename);
    if(g_strrstr(value, ".")) *(g_strrstr(value, ".")) = 0;
  }
  else if(g_strcmp0(variable, "$(FILE_EXTENSION)") == 0 && params->filename && (got_value = TRUE))
    snprintf(value, value_len, "%s", file_ext);
  else if(g_strcmp0(variable, "$(SEQUENCE)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%.4d", params->sequence >= 0 ? params->sequence : params->data->sequence);
  else if(g_strcmp0(variable, "$(USERNAME)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%s", g_get_user_name());
  else if(g_strcmp0(variable, "$(HOME_FOLDER)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%s", homedir); // undocumented : backward compatibility
  else if(g_strcmp0(variable, "$(HOME)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%s", homedir);
  else if(g_strcmp0(variable, "$(PICTURES_FOLDER)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%s", pictures_folder);
  else if(g_strcmp0(variable, "$(DESKTOP_FOLDER)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%s",
             g_get_user_special_dir(G_USER_DIRECTORY_DESKTOP)); // undocumented : backward compatibility
  else if(g_strcmp0(variable, "$(DESKTOP)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%s", g_get_user_special_dir(G_USER_DIRECTORY_DESKTOP));
  else if(g_strcmp0(variable, "$(STARS)") == 0 && (got_value = TRUE))
    snprintf(value, value_len, "%d", stars);
  else if(g_strcmp0(variable, "$(LABELS)") == 0 && (got_value = TRUE))
  {
    // TODO: currently we concatenate all the color labels with a ',' as a separator. Maybe it's better to
    // only use the first/last label?
    GList *res = dt_metadata_get(params->imgid, "Xmp.darktable.colorlabels", NULL);
    res = g_list_first(res);
    if(res != NULL)
    {
      GList *labels = NULL;
      do
      {
        labels = g_list_append(labels, (char *)(_(dt_colorlabels_to_string(GPOINTER_TO_INT(res->data)))));
      } while((res = g_list_next(res)) != NULL);
      char *str = dt_util_glist_to_str(",", labels);
      g_list_free(labels);
      snprintf(value, value_len, "%s", str);
      g_free(str);
    }
    else
    {
      snprintf(value, value_len, "%s", _("none"));
    }
    g_list_free(res);
  }
  else if(g_strcmp0(variable, "$(TITLE)") == 0 && params->filename && (got_value = TRUE))
  {
    GList *res = dt_metadata_get(params->imgid, "Xmp.dc.title", NULL);
    res = g_list_first(res);
    if(res != NULL)
    {
      snprintf(value, value_len, "%s", (char *)res->data);
    }
    else
    {
      snprintf(value, value_len, "%s", _("none"));
    }
    g_list_free_full(res, &g_free);
  }
  else if(g_strcmp0(variable, "$(CREATOR)") == 0 && params->filename && (got_value = TRUE))
  {
    GList *res = dt_metadata_get(params->imgid, "Xmp.dc.creator", NULL);
    res = g_list_first(res);
    if(res != NULL)
    {
      snprintf(value, value_len, "%s", (char *)res->data);
    }
    else
    {
      snprintf(value, value_len, "%s", _("none"));
    }
    g_list_free_full(res, &g_free);
  }
  else if(g_strcmp0(variable, "$(PUBLISHER)") == 0 && params->filename && (got_value = TRUE))
  {
    GList *res = dt_metadata_get(params->imgid, "Xmp.dc.publisher", NULL);
    res = g_list_first(res);
    if(res != NULL)
    {
      snprintf(value, value_len, "%s", (char *)res->data);
    }
    else
    {
      snprintf(value, value_len, "%s", _("none"));
    }
    g_list_free_full(res, &g_free);
  }
  else if(g_strcmp0(variable, "$(RIGHTS)") == 0 && params->filename && (got_value = TRUE))
  {
    GList *res = dt_metadata_get(params->imgid, "Xmp.dc.rights", NULL);
    res = g_list_first(res);
    if(res != NULL)
    {
      snprintf(value, value_len, "%s", (char *)res->data);
    }
    else
    {
      snprintf(value, value_len, "%s", _("none"));
    }
    g_list_free_full(res, &g_free);
  }

  g_free(pictures_folder);
  g_free((gchar *)homedir);

  return got_value;
}
int
main(int argc, char *argv[]) {
  GMainLoop *loop;
  GstRTSPServer *server;
  GstRTSPMediaMapping *mapping;
  GstRTSPMediaFactory *factory_h264, *factory_mpeg4;
  GstRTSPServerConfiguration * server_config = NULL;
  gchar * audio_profile_name = NULL;

  gst_init(&argc, &argv);

  loop = g_main_loop_new(NULL, FALSE);

  /* create a server instance */
  server = gst_rtsp_server_new();
  /* get the mapping for this server, every server has a default mapper object
   * that be used to map uri mount points to media factories */

  mapping = gst_rtsp_server_get_media_mapping(server);

  /* make a media factory for a h264 video stream and audio (aac, g711 or g726) stream. The default media factory can use
   * gst-launch syntax to create pipelines.
   * any launch line works as long as it contains elements named pay%d. Each
   * element with pay%d names will be a stream */
  factory_h264 = gst_rtsp_media_factory_new();
  factory_h264->two_streams = TRUE;
  /* set webcam source and port to listen for factory */
  gst_rtsp_factory_set_device_source(factory_h264, "v4l2src", "/dev/video0", 3000);

  /* Load server configuration for h264 stream */
  server_config = gst_rtsp_server_configuration_load(DEFAULT_PROFILE_FILE_VIDEO_H264);

  /* check to see if we need audio stream for our server */
  if (argc > 1 && server_config != NULL) {
    if (g_strrstr(argv[1], "aac")) {
      audio_profile_name = "audio AAC";
    } else if (g_strrstr(argv[1], "g726")) {
      audio_profile_name = "audio G726";
    } else if (g_strrstr(argv[1], "g711")) {
      audio_profile_name = "audio G711";
    }
    /* set default audio format for our configuration */
    if (audio_profile_name != NULL) {
      gst_rtsp_server_configuration_set_default_audio_pipeline(server_config, audio_profile_name);
    }
  }

  /* apply server config to the factory */
  gst_rtsp_media_factory_set_server_configuration(factory_h264, server_config);

  /* share the pipeline with multiple clients */
  gst_rtsp_media_factory_set_shared(factory_h264, TRUE);

  /* attach the test factory to the /h264 url */
  gst_rtsp_media_mapping_add_factory(mapping, "/h264", factory_h264);

  /* make a media factory for a mpeg 4 video stream and audio (aac, g711 or g726) stream. The default media factory can use
   * gst-launch syntax to create pipelines.
   * any launch line works as long as it contains elements named pay%d. Each
   * element with pay%d names will be a stream */
  factory_mpeg4 = gst_rtsp_media_factory_new();
  factory_mpeg4->two_streams = TRUE;
  /* set webcam source and port to listen for factory */
  /* gst_rtsp_factory_set_device_source (factory_jpg, "v4l2src", "/dev/video0", 3000); */
  factory_mpeg4->v4l2src_pipeline = factory_h264->v4l2src_pipeline;
  factory_mpeg4->v4l2src_port = factory_h264->v4l2src_port + 1;
  factory_mpeg4->multiudpsink = factory_h264->multiudpsink;

  /* prepare server configuration for mpeg4 stream */
  server_config = gst_rtsp_server_configuration_load(DEFAULT_PROFILE_FILE_VIDEO_MPEG4);

  /* set default audio profile fo mpeg4 stream */
  if (audio_profile_name != NULL) {
    gst_rtsp_server_configuration_set_default_audio_pipeline(server_config, audio_profile_name);
  }

  /* now, map server configuration to the factory */
  gst_rtsp_media_factory_set_server_configuration(factory_mpeg4, server_config);

  /* share the pipeline with multiple clients */
  gst_rtsp_media_factory_set_shared(factory_mpeg4, TRUE);

  /* attach the test factory to the /mp4 url */
  gst_rtsp_media_mapping_add_factory(mapping, "/mp4", factory_mpeg4);

  /* don't need the ref to the mapper anymore */
  g_object_unref(mapping);

  /* attach the server to the default maincontext */
  gst_rtsp_server_attach(server, NULL);

  g_timeout_add_seconds(2, (GSourceFunc) timeout, server);

  /* start serving */
  g_main_loop_run(loop);

  return 0;
}
Example #16
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)
{
  dt_imageio_gallery_t *d = (dt_imageio_gallery_t *)sdata;

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

    char tmp_dir[DT_MAX_PATH_LEN];

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

    // 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), DT_MAX_PATH_LEN-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), DT_MAX_PATH_LEN-strlen(d->filename), "_$(SEQUENCE)");
    }

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

    dt_variables_expand(d->vp, d->filename, TRUE);
    g_strlcpy(filename, dt_variables_get_result(d->vp), DT_MAX_PATH_LEN);
    g_strlcpy(dirname, filename, DT_MAX_PATH_LEN);

    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, DT_MAX_PATH_LEN, "%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[256], relthumbfilename[256];
    c = filename + strlen(filename);
    for(; c>filename && *c != '/' ; c--);
    if(*c == '/') c++;
    if(c <= filename) c = filename;
    snprintf(relfilename, 256, "%s", c);
    snprintf(relthumbfilename, 256, "%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[DT_MAX_PATH_LEN], relsubfilename[256];
    snprintf(subfilename, DT_MAX_PATH_LEN, "%s", d->cached_dirname);
    char* sc = subfilename + strlen(subfilename);
    sprintf(sc, "/img_%d.html", num);
    sprintf(relsubfilename, "img_%d.html", num);

    snprintf(pair->line, 4096,
             "\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[256];
    sprintf(next, "img_%d.html", (num)%total+1);

    char prev[256];
    sprintf(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) != 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) != 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(_("%d/%d exported to `%s%s'"), num, total, trunc != filename ? ".." : "", trunc);
  return 0;
}
/**
 * Copyright (C) 2008 Richard Hughes <*****@*****.**>
 * gpm_stats_format_cmdline:
 **/
static gchar *
gpm_stats_format_cmdline (const gchar *command, gboolean is_userspace)
{
	gchar *found;
	gchar *temp = NULL;
	gchar *cmdline;
	const gchar *temp_ptr;

	/* nothing */
	if (command == NULL) {
		/* TRANSLATORS: the command line was not provided */
		temp_ptr = _("No data");
		goto out;
	}

	/* common kernel cmd names */
	if (g_strcmp0 (command, "insmod") == 0) {
		/* TRANSLATORS: kernel module, usually a device driver */
		temp_ptr = _("Kernel module");
		goto out;
	}
	if (g_strcmp0 (command, "modprobe") == 0) {
		/* TRANSLATORS: kernel module, usually a device driver */
		temp_ptr = _("Kernel module");
		goto out;
	}
	if (g_strcmp0 (command, "swapper") == 0) {
		/* TRANSLATORS: kernel housekeeping */
		temp_ptr = _("Kernel core");
		goto out;
	}
	if (g_strcmp0 (command, "kernel-ipi") == 0) {
		/* TRANSLATORS: interrupt between processors */
		temp_ptr = _("Interprocessor interrupt");
		goto out;
	}
	if (g_strcmp0 (command, "interrupt") == 0) {
		/* TRANSLATORS: unknown interrupt */
		temp_ptr = _("Interrupt");
		goto out;
	}

	/* truncate at first space or ':' */
	temp = g_strdup (command);
	found = strstr (temp, ":");
	if (found != NULL)
		*found = '\0';
	found = strstr (temp, " ");
	if (found != NULL)
		*found = '\0';

	/* remove path */
	found = g_strrstr (temp, "/");
	if (found != NULL && strncmp (temp, "event", 5) != 0)
		temp_ptr = found + 1;
	else
		temp_ptr = temp;

out:
	/* format command line */
	if (is_userspace)
		cmdline = g_markup_escape_text (temp_ptr, -1);
	else
		cmdline = g_markup_printf_escaped ("<i>%s</i>", temp_ptr);
	g_free (temp);

	/* return */
	return cmdline;
}
Example #18
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_colorspaces_color_profile_type_t icc_type,
          const gchar *icc_filename, dt_iop_color_intent_t icc_intent)
{
  dt_imageio_disk_t *d = (dt_imageio_disk_t *)sdata;

  char filename[PATH_MAX] = { 0 };
  char input_dir[PATH_MAX] = { 0 };
  char pattern[DT_MAX_PATH_FOR_PARAMS];
  g_strlcpy(pattern, d->filename, sizeof(pattern));
  gboolean from_cache = FALSE;
  dt_image_full_path(imgid, input_dir, sizeof(input_dir), &from_cache);
  int fail = 0;
  // we're potentially called in parallel. have sequence number synchronized:
  dt_pthread_mutex_lock(&darktable.plugin_threadsafe);
  {
try_again:
    // avoid braindead export which is bound to overwrite at random:
    if(total > 1 && !g_strrstr(pattern, "$"))
    {
      snprintf(pattern + strlen(pattern), sizeof(pattern) - strlen(pattern), "_$(SEQUENCE)");
    }

    gchar *fixed_path = dt_util_fix_path(pattern);
    g_strlcpy(pattern, fixed_path, sizeof(pattern));
    g_free(fixed_path);

    d->vp->filename = input_dir;
    d->vp->jobcode = "export";
    d->vp->imgid = imgid;
    d->vp->sequence = num;

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

    // if filenamepattern is a directory just add ${FILE_NAME} as default..
    // this can happen if the filename component of the pattern is an empty variable
    char last_char = *(filename + strlen(filename) - 1);
    if(last_char == '/' || last_char == '\\')
    {
      // add to the end of the original pattern without caring about a
      // potentially added "_$(SEQUENCE)"
      if (snprintf(pattern, sizeof(pattern), "%s" G_DIR_SEPARATOR_S "$(FILE_NAME)", d->filename) < sizeof(pattern))
        goto try_again;
    }

    char *output_dir = g_path_get_dirname(filename);

    if(g_mkdir_with_parents(output_dir, 0755))
    {
      fprintf(stderr, "[imageio_storage_disk] could not create directory: `%s'!\n", output_dir);
      dt_control_log(_("could not create directory `%s'!"), output_dir);
      fail = 1;
      goto failed;
    }
    if(g_access(output_dir, W_OK | X_OK) != 0)
    {
      fprintf(stderr, "[imageio_storage_disk] could not write to directory: `%s'!\n", output_dir);
      dt_control_log(_("could not write to directory `%s'!"), output_dir);
      fail = 1;
      goto failed;
    }

    const char *ext = format->extension(fdata);
    char *c = filename + strlen(filename);
    size_t filename_free_space = sizeof(filename) - (c - filename);
    snprintf(c, filename_free_space, ".%s", ext);

  /* prevent overwrite of files */
  failed:
    g_free(output_dir);

    if(!fail && !d->overwrite)
    {
      int seq = 1;
      while(g_file_test(filename, G_FILE_TEST_EXISTS))
      {
        snprintf(c, filename_free_space, "_%.2d.%s", seq, ext);
        seq++;
      }
    }
  } // end of critical block
  dt_pthread_mutex_unlock(&darktable.plugin_threadsafe);
  if(fail) return 1;

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

  printf("[export_job] exported to `%s'\n", filename);
  dt_control_log(ngettext("%d/%d exported to `%s'", "%d/%d exported to `%s'", num),
                 num, total, filename);
  return 0;
}
Example #19
0
/**
 * media_art_strip_invalid_entities:
 * @original: original string
 *
 * Strip a albumname or artistname string to prepare it for calculating the
 * media art path with it. Certain characters and charactersets will be stripped
 * and a newly allocated string returned which you must free with g_free().
 *
 * Returns: copy of original but then stripped
 *
 * Since: 0.2.0
 */
gchar *
media_art_strip_invalid_entities (const gchar *original)
{
	GString *str_no_blocks;
	gchar **strv;
	gchar *str;
	gboolean blocks_done = FALSE;
	const gchar *p;
	const gchar *invalid_chars = "()[]<>{}_!@#$^&*+=|\\/\"'?~";
	const gchar *invalid_chars_delimiter = "*";
	const gchar *convert_chars = "\t";
	const gchar *convert_chars_delimiter = " ";
	const gunichar blocks[5][2] = {
		{ '(', ')' },
		{ '{', '}' },
		{ '[', ']' },
		{ '<', '>' },
		{  0,   0  }
	};

	str_no_blocks = g_string_new ("");

	p = original;

	while (!blocks_done) {
		gint pos1, pos2, i;

		pos1 = -1;
		pos2 = -1;

		for (i = 0; blocks[i][0] != 0; i++) {
			gint start, end;

			/* Go through blocks, find the earliest block we can */
			if (media_art_strip_find_next_block (p, blocks[i][0], blocks[i][1], &start, &end)) {
				if (pos1 == -1 || start < pos1) {
					pos1 = start;
					pos2 = end;
				}
			}
		}

		/* If either are -1 we didn't find any */
		if (pos1 == -1) {
			/* This means no blocks were found */
			g_string_append (str_no_blocks, p);
			blocks_done = TRUE;
		} else {
			/* Append the test BEFORE the block */
			if (pos1 > 0) {
				g_string_append_len (str_no_blocks, p, pos1);
			}

			p = g_utf8_next_char (p + pos2);

			/* Do same again for position AFTER block */
			if (*p == '\0') {
				blocks_done = TRUE;
			}
		}
	}

	/* Now convert chars to lower case */
	str = g_utf8_strdown (str_no_blocks->str, -1);
	g_string_free (str_no_blocks, TRUE);

	/* Now strip invalid chars */
	g_strdelimit (str, invalid_chars, *invalid_chars_delimiter);
	strv = g_strsplit (str, invalid_chars_delimiter, -1);
	g_free (str);
	str = g_strjoinv (NULL, strv);
	g_strfreev (strv);

	/* Now convert chars */
	g_strdelimit (str, convert_chars, *convert_chars_delimiter);
	strv = g_strsplit (str, convert_chars_delimiter, -1);
	g_free (str);
	str = g_strjoinv (convert_chars_delimiter, strv);
	g_strfreev (strv);

	while (g_strrstr (str, "  ") != NULL) {
		/* Now remove double spaces */
		strv = g_strsplit (str, "  ", -1);
		g_free (str);
		str = g_strjoinv (" ", strv);
		g_strfreev (strv);
	}

	/* Now strip leading/trailing white space */
	g_strstrip (str);

	return str;
}
Example #20
0
//G_MODULE_EXPORT gboolean lookuptable_changed(GtkCellRendererCombo *renderer, gchar *path, gchar * new_text, gpointer data)
G_MODULE_EXPORT gboolean lookuptable_changed(GtkCellRendererCombo *renderer, gchar *path, GtkTreeIter *new_iter, gpointer data)
{
	GtkTreeModel *combostore = NULL;
	GtkTreeIter iter;
	GtkTreeModel *model = (GtkTreeModel *)data;
	ConfigFile *cfgfile = NULL;
	gchar * new_text = NULL;
	gchar * int_name = NULL;
	gchar * old = NULL;
	gchar * new_name = NULL;
	gchar ** vector = NULL;
	const gchar * project = NULL;
	gboolean restart_tickler = FALSE;
	GAsyncQueue *io_data_queue = NULL;
	Firmware_Details *firmware = NULL;

	ENTER();
	firmware = (Firmware_Details *)DATA_GET(global_data,"firmware");
	io_data_queue = (GAsyncQueue *)DATA_GET(global_data,"io_data_queue");

	/* Get combo box model so we can set the combo to this new value */
	g_object_get(G_OBJECT(renderer),"model",&combostore,NULL);
	gtk_tree_model_get(combostore,new_iter,0,&new_text,-1);

	/* Get combo box model so we can set the combo to this new value */
	gtk_tree_model_get_iter_from_string(model,&iter,path);
	gtk_tree_model_get(model,&iter,INTERNAL_NAME_COL,&int_name,FILENAME_COL,&old,-1);
	//printf("New text is %s, int name associated %s, filename %s\n",new_text,int_name,old);
	if (g_ascii_strcasecmp(old,new_text) == 0) /* If no change, return */
	{
		g_free(int_name);
		g_free(old);
		EXIT();
		return TRUE;
	}

	if (g_ascii_strcasecmp(new_text,"Personal") == 0)
	{
		g_free(int_name);
		g_free(old);
		EXIT();
		return TRUE;
	}
	if (g_ascii_strcasecmp(new_text,"System") == 0)
	{
		g_free(int_name);
		g_free(old);
		EXIT();
		return TRUE;
	}
	if (DATA_GET(global_data,"realtime_id"))
	{
		gint count = 0;
		restart_tickler = TRUE;
		stop_tickler(RTV_TICKLER);
		while ((g_async_queue_length(io_data_queue) > 0) && (count < 30))
		{
			MTXDBG(CRITICAL,_("Draining I/O Queue, current length %i\n"),g_async_queue_length(io_data_queue));
			count++;
		}

	}
	get_table(int_name,new_text,NULL); /* Load the new one in it's place */
	gtk_list_store_set(GTK_LIST_STORE(model),&iter, FILENAME_COL, new_text,-1);
	if (restart_tickler)
		start_tickler(RTV_TICKLER);

	cfgfile = cfg_open_file(firmware->profile_filename);
	if (!cfgfile)
	{
		g_free(int_name);
		g_free(old);
		EXIT();
		return FALSE;
	}
	g_hash_table_foreach((GHashTable *)DATA_GET(global_data,"lookuptables"),update_lt_config,cfgfile);
	if (g_strrstr(firmware->profile_filename,"mtx"))
		cfg_write_file(cfgfile, firmware->profile_filename);
	else
	{
		project = (const gchar *)DATA_GET(global_data,"project_name");
		vector = g_strsplit(firmware->profile_filename,PSEP,-1);
		if (!project)
			project = DEFAULT_PROJECT;
		new_name = g_build_filename(HOME(),"mtx",project,INTERROGATOR_DATA_DIR,"Profiles",vector[g_strv_length(vector)-2],vector[g_strv_length(vector)-1],NULL);
		g_strfreev(vector);
		cfg_write_file(cfgfile, new_name);
		g_free(firmware->profile_filename);
		firmware->profile_filename=g_strdup(new_name);
		g_free(new_name);
	}
	cfg_free(cfgfile);

	/*printf("internal name %s, old table %s, new table %s\n",int_name,old,new_text);*/
	g_free(int_name);
	g_free(old);
	EXIT();
	return TRUE;
}
Example #21
0
/*! 
  \brief read_log_data() reads the log data and sticks it into the arrays in
  the log_info structure
  \param iochannel is the data source 
  \param log_info is the pointer to log information struct
  */
G_MODULE_EXPORT void read_log_data(GIOChannel *iochannel, Log_Info *log_info)
{
	GString *a_line = g_string_new("\0");
	gchar **data = NULL;
	guint i = 0;
	gint x = 0;
	gint precision = 0;
	gchar ** vector = NULL;
	GArray *tmp_array = NULL;
	gfloat val = 0.0;
	gconstpointer *object = NULL;

	ENTER();
	while(g_io_channel_read_line_string(iochannel,a_line,NULL,NULL) == G_IO_STATUS_NORMAL) 
	{
		if (g_strrstr(a_line->str,"MARK"))
		{
			/* Should insert some sort of marker at this index
			 * in the data arrays... 
			 */
			printf(_("MARK found in logfile. MTX doesn't do anything with these yet...!\n"));
			continue;
		}
		data = g_strsplit(a_line->str,log_info->delimiter,0);
		if ((!g_ascii_isdigit(data[0][0])) && (!g_ascii_isdigit(data[0][1])))
		{
			printf(_("non numerical line detected\n"));
			printf("text %s\n",data[0]);
			g_strfreev(data);
			continue;
		}
		if (g_strv_length(data) != log_info->field_count)
		{
			printf(_("Datalog error, field count assertion failure\nExpected %i fields, got %i instead, tossing this record!\n"),log_info->field_count,g_strv_length(data));
			g_strfreev(data);
			continue;
		}

		for (i=0;i<(log_info->field_count);i++)
		{
			object = (gconstpointer *)g_ptr_array_index(log_info->log_list, i);
			tmp_array = (GArray *)DATA_GET(object,"data_array");
			val = (gfloat)g_ascii_strtod(g_strdelimit(data[i],",.",'.'),NULL);
			g_array_append_val(tmp_array,val);

			/*printf("data[%i]=%s\n",i,data[i]);*/
			if (x == 0) /* only check first line */
			{
				if (g_strrstr(data[i], ".") != NULL)
				{
					vector = g_strsplit(data[i],".",-1);
					precision = strlen(vector[1]);
					g_strfreev(vector);
					DATA_SET(object,"precision",GINT_TO_POINTER(precision));
				}
			}

		}
		g_strfreev(data);
		x++;
	}
	EXIT();
	return;
}
Example #22
0
/*!
  \brief load_table() physically handles loading the table datafrom disk, 
  populating and array and sotring a pointer to that array in the lookuptables
  hashtable referenced by the table_name passed
  \param table_name is the key to lookuptables hashtable
  \param filename is the filename to load table data from
  \returns TRUE on success, FALSE on failure
  */
G_MODULE_EXPORT gboolean load_table(gchar *table_name, gchar *filename)
{
	GIOStatus status;
	GIOChannel *iochannel;
	gboolean done = FALSE;
	GHashTable *lookuptables = NULL;
	gchar * str = NULL;
	gchar * tmp = NULL;
	gchar * end = NULL;
	GString *a_line; 
	LookupTable *lookuptable = NULL;
	gint tmparray[2048]; /* bad idea being static!!*/
	gchar ** vector = NULL;
	gint i = 0;

	ENTER();
	iochannel = g_io_channel_new_file(filename,"r", NULL);
	status = g_io_channel_seek_position(iochannel,0,G_SEEK_SET,NULL);
	if (status != G_IO_STATUS_NORMAL)
	{
		MTXDBG(CRITICAL,_("Error seeking to beginning of the file\n"));
	}
	while (!done)	
	{
		a_line = g_string_new("\0");
		status = g_io_channel_read_line_string(iochannel, a_line, NULL, NULL);
		if (status == G_IO_STATUS_EOF)
			done = TRUE;
		else
		{
			/*	str = g_strchug(g_strdup(a_line->str));*/
			str = g_strchug(a_line->str);
			if (g_str_has_prefix(str,"DB"))
			{
				str+=2; /* move 2 places in	*/
				end = g_strrstr(str,"T");
				tmp = g_strndup(str,end-str);
				tmparray[i]=atoi(tmp);
				g_free(tmp);
				i++;
			}
		}
		g_string_free(a_line,TRUE);
	}
	g_io_channel_shutdown(iochannel,TRUE,NULL);
	g_io_channel_unref(iochannel);

	vector = g_strsplit(filename,PSEP,-1);
	lookuptable = g_new0(LookupTable, 1);
	lookuptable->array = (gint *)g_memdup(&tmparray,i*sizeof(gint));
	lookuptable->filename = g_strdup(vector[g_strv_length(vector)-1]);
	g_strfreev(vector);
	lookuptables = (GHashTable *)DATA_GET(global_data,"lookuptables");
	if (!lookuptables)
	{
		lookuptables = g_hash_table_new_full(g_str_hash,g_str_equal,g_free,dealloc_lookuptable);
		DATA_SET_FULL(global_data,"lookuptables",lookuptables,g_hash_table_destroy);
	}
	g_hash_table_replace((GHashTable *)DATA_GET(global_data,"lookuptables"),g_strdup(table_name),lookuptable);
	/*g_hash_table_foreach(DATA_GET(global_data,"lookuptables"),dump_lookuptables,NULL);*/

	EXIT();
	return TRUE;
}
Example #23
0
void dt_collection_get_makermodel(const gchar *filter, GList **sanitized, GList **exif)
{
  sqlite3_stmt *stmt;
  gchar *needle = NULL;

  GHashTable *names = NULL;
  if (sanitized)
    names = g_hash_table_new(g_str_hash, g_str_equal);

  if (filter && filter[0] != '\0')
    needle = g_utf8_strdown(filter, -1);

  DT_DEBUG_SQLITE3_PREPARE_V2(dt_database_get(darktable.db),
                              "select maker, model from images group by maker, model",
                              -1, &stmt, NULL);
  while(sqlite3_step(stmt) == SQLITE_ROW)
  {
    char *exif_maker = (char *)sqlite3_column_text(stmt, 0);
    char *exif_model = (char *)sqlite3_column_text(stmt, 1);

    char maker[64];
    char model[64];
    char alias[64];
    maker[0] = model[0] = alias[0] = '\0';
    dt_rawspeed_lookup_makermodel(exif_maker, exif_model,
                                  maker, sizeof(maker),
                                  model, sizeof(model),
                                  alias, sizeof(alias));

    // Create the makermodel by concatenation
    char makermodel[128];
    g_strlcpy(makermodel, maker, sizeof(makermodel));
    int maker_len = strlen(maker);
    makermodel[maker_len] = ' ';
    g_strlcpy(makermodel+maker_len+1, model, sizeof(makermodel)-maker_len-1);

    gchar *haystack = g_utf8_strdown(makermodel, -1);
    if (!needle || g_strrstr(haystack, needle) != NULL)
    {
      if (exif)
      {
        // Append a two element list with maker and model
        GList *inner_list = NULL;
        inner_list = g_list_append(inner_list, g_strdup(exif_maker));
        inner_list = g_list_append(inner_list, g_strdup(exif_model));
        *exif = g_list_append(*exif, inner_list);
      }

      if (sanitized)
      {
        gchar *key = g_strdup(makermodel);
        g_hash_table_add(names, key);
      }
    }
    g_free(haystack);
  }
  sqlite3_finalize(stmt);
  g_free(needle);

  if(sanitized)
  {
    *sanitized = g_list_sort(g_hash_table_get_keys(names), (GCompareFunc) strcmp);
    g_hash_table_destroy(names);
  }
}
Example #24
0
static void
sync_updated_folders (CamelEwsStore *store,
                      GSList *updated_folders)
{
	CamelEwsStoreSummary *ews_summary = store->summary;
	GSList *l;

	for (l = updated_folders; l != NULL; l = g_slist_next (l)) {
		EEwsFolder *ews_folder = (EEwsFolder *) l->data;
		EEwsFolderType ftype;
		gchar *folder_name;
		gchar *display_name;
		const EwsFolderId *fid, *pfid;

		ftype = e_ews_folder_get_folder_type (ews_folder);
		if (ftype != E_EWS_FOLDER_TYPE_MAILBOX)
			continue;

		fid = e_ews_folder_get_id (ews_folder);
		folder_name = camel_ews_store_summary_get_folder_full_name (
			ews_summary, fid->id, NULL);

		if (!folder_name) {
			/* in case the folder is not in the local store summary,
			   just add it as a new folder */
			add_folder_to_summary (store, ews_folder);
			continue;
		}

		pfid = e_ews_folder_get_parent_id (ews_folder);
		display_name = g_strdup (e_ews_folder_get_escaped_name (ews_folder));

		/* If the folder is moved or renamed (which are separate
		 * operations in Exchange, unfortunately, then the name
		 * or parent folder will change. Handle both... */
		if (pfid || display_name) {
			GError *error = NULL;
			gchar *new_fname = NULL;

			if (pfid) {
				gchar *pfname;

				/* If the display name wasn't changed, its basename is still
				 * the same as it was before... */
				if (!display_name)
					display_name = camel_ews_store_summary_get_folder_name (
						ews_summary, fid->id, NULL);
				if (!display_name)
					goto done;

				pfname = camel_ews_store_summary_get_folder_full_name (
					ews_summary, pfid->id, NULL);

				/* If the lookup failed, it'll be because the new parent folder
				 * is the message folder root. */
				if (pfname) {
					new_fname = g_strconcat (
						pfname, "/", display_name, NULL);
					g_free (pfname);
				} else
					new_fname = g_strdup (display_name);
			} else {
				/* Parent folder not changed; just basename */
				const gchar *last_slash;

				/* Append new display_name to old parent directory name... */
				last_slash = g_strrstr (folder_name, "/");
				if (last_slash)
					new_fname = g_strdup_printf (
						"%.*s/%s",
						(gint)(last_slash - folder_name),
						folder_name, display_name);
				else /* ...unless it was a child of the root folder */
					new_fname = g_strdup (display_name);
			}

			if (strcmp (new_fname, folder_name))
				ews_utils_rename_folder (
					store, ftype,
					fid->id, fid->change_key,
					pfid ? pfid->id : NULL,
					display_name, folder_name, &error);
			g_free (new_fname);
			g_clear_error (&error);
		}
 done:
		g_free (folder_name);
		g_free (display_name);
	}
}
GstBusSyncReply Gst_bus_call(GstBus * bus, GstMessage *msg, gpointer user_data)
{
	gchar * sourceName;
	
	// source
	GstObject * source;
	source = GST_MESSAGE_SRC(msg);
	
	if (!GST_IS_OBJECT(source))
		return GST_BUS_DROP;
	
	sourceName = gst_object_get_name(source);

	switch (GST_MESSAGE_TYPE(msg)) 
	{
		case GST_MESSAGE_EOS: 
		{
			g_message("End-of-stream");
			end_eof = 1;
			break;
		}
		
		case GST_MESSAGE_ERROR: 
		{
			gchar * debug;
			GError *err;
			gst_message_parse_error(msg, &err, &debug);
			g_free (debug);
			lt_info_c( "%s:%s - GST_MESSAGE_ERROR: %s (%i) from %s\n", FILENAME, __FUNCTION__, err->message, err->code, sourceName );
			if ( err->domain == GST_STREAM_ERROR )
			{
				if ( err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND )
				{
					if ( g_strrstr(sourceName, "videosink") )
						lt_info_c( "%s:%s - GST_MESSAGE_ERROR: videosink\n", FILENAME, __FUNCTION__ ); //FIXME: how shall playback handle this event???
					else if ( g_strrstr(sourceName, "audiosink") )
						lt_info_c( "%s:%s - GST_MESSAGE_ERROR: audioSink\n", FILENAME, __FUNCTION__ ); //FIXME: how shall playback handle this event???
				}
			}
			g_error_free(err);

			end_eof = 1; 		// NOTE: just to exit
			
			break;
		}
		
		case GST_MESSAGE_INFO:
		{
			gchar *debug;
			GError *inf;
	
			gst_message_parse_info (msg, &inf, &debug);
			g_free (debug);
			if ( inf->domain == GST_STREAM_ERROR && inf->code == GST_STREAM_ERROR_DECODE )
			{
				if ( g_strrstr(sourceName, "videosink") )
					lt_info_c( "%s:%s - GST_MESSAGE_INFO: videosink\n", FILENAME, __FUNCTION__ ); //FIXME: how shall playback handle this event???
			}
			g_error_free(inf);
			break;
		}
		
		case GST_MESSAGE_TAG:
		{
			GstTagList *tags, *result;
			gst_message_parse_tag(msg, &tags);
	
			result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_REPLACE);
			if (result)
			{
				if (m_stream_tags)
					gst_tag_list_free(m_stream_tags);
				m_stream_tags = result;
			}
	
			const GValue *gv_image = gst_tag_list_get_value_index(tags, GST_TAG_IMAGE, 0);
			if ( gv_image )
			{
				GstBuffer *buf_image;
				buf_image = gst_value_get_buffer (gv_image);
				int fd = open("/tmp/.id3coverart", O_CREAT|O_WRONLY|O_TRUNC, 0644);
				if(fd >= 0)
				{
					int ret = write(fd, GST_BUFFER_DATA(buf_image), GST_BUFFER_SIZE(buf_image));
					close(fd);
					lt_info_c( "%s:%s - GST_MESSAGE_INFO: cPlayback::state /tmp/.id3coverart %d bytes written\n", FILENAME, __FUNCTION__ , ret);
				}
				//FIXME: how shall playback handle this event???
			}
			gst_tag_list_free(tags);
			lt_info_c( "%s:%s - GST_MESSAGE_INFO: update info tags\n", FILENAME, __FUNCTION__);  //FIXME: how shall playback handle this event???
			break;
		}
		
		case GST_MESSAGE_STATE_CHANGED:
		{
			if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
				break;

			GstState old_state, new_state;
			gst_message_parse_state_changed(msg, &old_state, &new_state, NULL);
			
			if(old_state == new_state)
				break;
			lt_info_c( "%s:%s - GST_MESSAGE_STATE_CHANGED: state transition %s -> %s\n", FILENAME, __FUNCTION__, gst_element_state_get_name(old_state), gst_element_state_get_name(new_state));
		
			GstStateChange transition = (GstStateChange)GST_STATE_TRANSITION(old_state, new_state);
		
			switch(transition)
			{
				case GST_STATE_CHANGE_NULL_TO_READY:
				{
				}	break;
				case GST_STATE_CHANGE_READY_TO_PAUSED:
				{
					GstIterator *children;
					if (audioSink)
					{
						gst_object_unref(GST_OBJECT(audioSink));
						audioSink = NULL;
					}
					
					if (videoSink)
					{
						gst_object_unref(GST_OBJECT(videoSink));
						videoSink = NULL;
					}
					children = gst_bin_iterate_recurse(GST_BIN(m_gst_playbin));
					audioSink = GST_ELEMENT_CAST(gst_iterator_find_custom(children, (GCompareFunc)match_sinktype, (gpointer)"GstDVBAudioSink"));
					videoSink = GST_ELEMENT_CAST(gst_iterator_find_custom(children, (GCompareFunc)match_sinktype, (gpointer)"GstDVBVideoSink"));
					gst_iterator_free(children);
					
				}	break;
				case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
				{
				}	break;
				case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
				{
				}	break;
				case GST_STATE_CHANGE_PAUSED_TO_READY:
				{
					if (audioSink)
					{
						gst_object_unref(GST_OBJECT(audioSink));
						audioSink = NULL;
					}
					if (videoSink)
					{
						gst_object_unref(GST_OBJECT(videoSink));
						videoSink = NULL;
					}
				}	break;
				case GST_STATE_CHANGE_READY_TO_NULL:
				{
				}	break;
			}
			break;
		}
#if 0
		case GST_MESSAGE_ELEMENT:
		{
			if(gst_structure_has_name(gst_message_get_structure(msg), "prepare-xwindow-id")) 
			{
				// set window id
				gst_x_overlay_set_xwindow_id(GST_X_OVERLAY(GST_MESSAGE_SRC (msg)), glfb->getWindowID());
				
				// reshape window
				gst_x_overlay_set_render_rectangle(GST_X_OVERLAY(GST_MESSAGE_SRC (msg)), 0, 0, glfb->getOSDWidth(), glfb->getOSDHeight());
				
				// sync frames
				gst_x_overlay_expose(GST_X_OVERLAY(GST_MESSAGE_SRC (msg)));
			}
		}
#endif
		break;
		default:
			break;
	}

	return GST_BUS_DROP;
}
Example #26
0
gboolean _variable_get_value(dt_variables_params_t *params, gchar *variable,gchar *value)
{
  const gchar *file_ext=NULL;
  gboolean got_value=FALSE;
  struct tm *tim=localtime(&params->data->time);

  const gchar *homedir = dt_loc_get_home_dir(NULL);

  gchar *pictures_folder=NULL;

  if(g_get_user_special_dir(G_USER_DIRECTORY_PICTURES) == NULL)
    pictures_folder=g_build_path(G_DIR_SEPARATOR_S,homedir,"Pictures",(char *)NULL);
  else
    pictures_folder=g_strdup( g_get_user_special_dir(G_USER_DIRECTORY_PICTURES) );

  if(params->filename)
  {
    file_ext=(g_strrstr(params->filename,".")+1);
    if(file_ext == (gchar*)1) file_ext = params->filename + strlen(params->filename);
  }

  /* image exif time */
  gboolean have_exif_tm = FALSE;
  int exif_iso = 100;
  struct tm exif_tm= {0};
  if (params->imgid)
  {
    const dt_image_t *img = dt_image_cache_read_get(darktable.image_cache, params->imgid);
    if (sscanf (img->exif_datetime_taken,"%d:%d:%d %d:%d:%d",
                &exif_tm.tm_year,
                &exif_tm.tm_mon,
                &exif_tm.tm_mday,
                &exif_tm.tm_hour,
                &exif_tm.tm_min,
                &exif_tm.tm_sec
               ) == 6
       )
    {
      exif_tm.tm_year-=1900;
      exif_tm.tm_mon--;
      have_exif_tm = TRUE;
    }
    exif_iso = img->exif_iso;
    dt_image_cache_read_release(darktable.image_cache, img);
  }

  if( g_strcmp0(variable,"$(YEAR)") == 0 && (got_value=TRUE) )  sprintf(value,"%.4d",tim->tm_year+1900);
  else if( g_strcmp0(variable,"$(MONTH)") == 0&& (got_value=TRUE)  )   sprintf(value,"%.2d",tim->tm_mon+1);
  else if( g_strcmp0(variable,"$(DAY)") == 0 && (got_value=TRUE) )   sprintf(value,"%.2d",tim->tm_mday);
  else if( g_strcmp0(variable,"$(HOUR)") == 0 && (got_value=TRUE) )  sprintf(value,"%.2d",tim->tm_hour);
  else if( g_strcmp0(variable,"$(MINUTE)") == 0 && (got_value=TRUE) )   sprintf(value,"%.2d",tim->tm_min);
  else if( g_strcmp0(variable,"$(SECOND)") == 0 && (got_value=TRUE) )   sprintf(value,"%.2d",tim->tm_sec);

  else if( g_strcmp0(variable,"$(EXIF_YEAR)") == 0 && (got_value=TRUE)  )   			sprintf(value,"%.4d", (have_exif_tm?exif_tm.tm_year:tim->tm_year)+1900);
  else if( g_strcmp0(variable,"$(EXIF_MONTH)") == 0 && (got_value=TRUE)  )  		sprintf(value,"%.2d", (have_exif_tm?exif_tm.tm_mon:tim->tm_mon)+1);
  else if( g_strcmp0(variable,"$(EXIF_DAY)") == 0 && (got_value=TRUE) )  			sprintf(value,"%.2d", (have_exif_tm?exif_tm.tm_mday:tim->tm_mday));
  else if( g_strcmp0(variable,"$(EXIF_HOUR)") == 0 && (got_value=TRUE) )  			sprintf(value,"%.2d", (have_exif_tm?exif_tm.tm_hour:tim->tm_hour));
  else if( g_strcmp0(variable,"$(EXIF_MINUTE)") == 0 && (got_value=TRUE) )   		sprintf(value,"%.2d", (have_exif_tm?exif_tm.tm_min:tim->tm_min));
  else if( g_strcmp0(variable,"$(EXIF_SECOND)") == 0 && (got_value=TRUE) )   		sprintf(value,"%.2d", (have_exif_tm?exif_tm.tm_sec:tim->tm_sec));
  else if( g_strcmp0(variable,"$(EXIF_ISO)") == 0 && (got_value=TRUE) )   		sprintf(value,"%d", exif_iso);
  else if( g_strcmp0(variable,"$(ID)") == 0 && (got_value=TRUE) ) sprintf(value,"%d", params->imgid);
  else if( g_strcmp0(variable,"$(JOBCODE)") == 0 && (got_value=TRUE) )   sprintf(value,"%s",params->jobcode);
  else if( g_strcmp0(variable,"$(ROLL_NAME)") == 0 && params->filename && (got_value=TRUE) )   sprintf(value,"%s",g_path_get_basename(g_path_get_dirname(params->filename)));
  else if( g_strcmp0(variable,"$(FILE_DIRECTORY)") == 0 && params->filename && (got_value=TRUE) )   sprintf(value,"%s",g_path_get_dirname(params->filename)); // undocumented : backward compatibility
  else if( g_strcmp0(variable,"$(FILE_FOLDER)") == 0 && params->filename && (got_value=TRUE) )   sprintf(value,"%s",g_path_get_dirname(params->filename));
  else if( g_strcmp0(variable,"$(FILE_NAME)") == 0 && params->filename && (got_value=TRUE) )
  {
    sprintf(value,"%s",g_path_get_basename(params->filename));
    if (g_strrstr(value,".")) *(g_strrstr(value,"."))=0;
  }
  else if( g_strcmp0(variable,"$(FILE_EXTENSION)") == 0 && params->filename && (got_value=TRUE) )   sprintf(value,"%s",file_ext);
  else if( g_strcmp0(variable,"$(SEQUENCE)") == 0 && (got_value=TRUE) )   sprintf(value,"%.4d",params->sequence>=0?params->sequence:params->data->sequence);
  else if( g_strcmp0(variable,"$(USERNAME)") == 0 && (got_value=TRUE) )   sprintf(value,"%s",g_get_user_name());
  else if( g_strcmp0(variable,"$(HOME_FOLDER)") == 0 && (got_value=TRUE)  )    sprintf(value,"%s",homedir); // undocumented : backward compatibility
  else if( g_strcmp0(variable,"$(HOME)") == 0 && (got_value=TRUE)  )    sprintf(value,"%s",homedir);
  else if( g_strcmp0(variable,"$(PICTURES_FOLDER)") == 0 && (got_value=TRUE) )   sprintf(value,"%s",pictures_folder);
  else if( g_strcmp0(variable,"$(DESKTOP_FOLDER)") == 0 && (got_value=TRUE) )   sprintf(value,"%s",g_get_user_special_dir(G_USER_DIRECTORY_DESKTOP)); // undocumented : backward compatibility
  else if( g_strcmp0(variable,"$(DESKTOP)") == 0 && (got_value=TRUE) )   sprintf(value,"%s",g_get_user_special_dir(G_USER_DIRECTORY_DESKTOP));
#if 0
  else if( g_strcmp0(variable,"$(VC)") == 0 && (got_value=TRUE) )
  {
    sqlite3_stmt *stmt;
    DT_DEBUG_SQLITE3_PREPARE_V2(darktable.db, "select id from images where filename=?1", &stmt, NULL);
    DT_DEBUG_SQLITE3_BIND_TEXT(stmt, 1, params->filename);
    while(sqlite3_step(stmt) == SQLITE_ROW)
    {
      if(sqlite3_column_int(stmt) == )
      {
      }
    }
    sqlite3_finalize(stmt);
    sprintf(value,"%s",g_get_user_special_dir(G_USER_DIRECTORY_DESKTOP));
  }
Example #27
0
/* Search the given directory for candidate binaries matching the base binary.
 * Return a GHashTable of major/minor -> directory pairs
 */
static GHashTable *
get_candidates (const gchar * dir, const gchar * base)
{
  GDir *gdir;
  GError *error = NULL;
  const gchar *entry;
  gchar *path;
  gchar *suffix, *copy;

  gchar *pattern;
  GPatternSpec *spec, *specexe;

  gchar **dirs;
  gchar **cur;

  GHashTable *candidates = NULL;

  candidates = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);

  /* compile our pattern specs */
  pattern = g_strdup_printf ("%s-*.*", base);
  spec = g_pattern_spec_new (pattern);
  g_free (pattern);
  pattern = g_strdup_printf ("%s-*.*.exe", base);
  specexe = g_pattern_spec_new (pattern);
  g_free (pattern);

  /* get all dirs from the path and prepend with given dir */
  if (dir)
    path = g_strdup_printf ("%s%c%s",
        dir, G_SEARCHPATH_SEPARATOR, g_getenv ("PATH"));
  else
    path = (gchar *) g_getenv ("PATH");
  dirs = g_strsplit (path, G_SEARCHPATH_SEPARATOR_S, 0);
  if (dir)
    g_free (path);

  /* check all of these in reverse order by winding to bottom and going up  */
  cur = &dirs[0];
  while (*cur)
    ++cur;

  while (cur != &dirs[0]) {
    --cur;
    if (!g_file_test (*cur, G_FILE_TEST_EXISTS) ||
        !g_file_test (*cur, G_FILE_TEST_IS_DIR)) {
      continue;
    }

    gdir = g_dir_open (*cur, 0, &error);
    if (!gdir) {
      g_warning ("Could not open dir %s: %s", *cur, error->message);
      g_error_free (error);
      return NULL;
    }
    while ((entry = g_dir_read_name (gdir))) {
      if (g_pattern_match_string (spec, entry)
          || g_pattern_match_string (specexe, entry)) {
        gchar *full;

        /* is it executable ? */
        full = g_build_filename (*cur, entry, NULL);
        if (!g_file_test (full, G_FILE_TEST_IS_EXECUTABLE)) {
          g_free (full);
          continue;
        }
        g_free (full);

        /* strip base and dash from it */
        suffix = g_strdup (&(entry[strlen (base) + 1]));
        copy = g_strdup (suffix);

        /* strip possible .exe from copy */
        if (g_strrstr (copy, ".exe"))
          g_strrstr (copy, ".exe")[0] = '\0';

        /* stricter pattern check: check if it only contains digits or dots */
        g_strcanon (copy, "0123456789.", 'X');
        if (strstr (copy, "X")) {
          g_free (suffix);
          g_free (copy);
          continue;
        }
        g_free (copy);
        g_hash_table_insert (candidates, suffix, g_strdup (*cur));
      }
    }
  }

  g_strfreev (dirs);
  g_pattern_spec_free (spec);
  return candidates;
}
gchar *
ges_effect_assect_id_get_type_and_bindesc (const char *id,
    GESTrackType * track_type, GError ** error)
{
  GList *tmp;
  GstElement *effect;
  gchar **typebin_desc = NULL;
  gchar *bindesc = NULL;

  *track_type = GES_TRACK_TYPE_UNKNOWN;
  typebin_desc = g_strsplit (id, " ", 2);
  if (!g_strcmp0 (typebin_desc[0], "audio")) {
    *track_type = GES_TRACK_TYPE_AUDIO;
    bindesc = g_strdup (typebin_desc[1]);
  } else if (!g_strcmp0 (typebin_desc[0], "video")) {
    *track_type = GES_TRACK_TYPE_VIDEO;
    bindesc = g_strdup (typebin_desc[1]);
  } else {
    bindesc = g_strdup (id);
  }

  g_strfreev (typebin_desc);

  effect = gst_parse_bin_from_description (bindesc, TRUE, error);
  if (effect == NULL) {
    g_free (bindesc);

    GST_ERROR ("Could not create element from: %s", id);

    return NULL;
  }

  if (*track_type != GES_TRACK_TYPE_UNKNOWN) {
    gst_object_unref (effect);

    return bindesc;
  }

  for (tmp = GST_BIN_CHILDREN (effect); tmp; tmp = tmp->next) {
    GstElementFactory *factory =
        gst_element_get_factory (GST_ELEMENT (tmp->data));
    const gchar *klass =
        gst_element_factory_get_metadata (factory, GST_ELEMENT_METADATA_KLASS);

    if (g_strrstr (klass, "Effect")) {
      if (g_strrstr (klass, "Audio")) {
        *track_type = GES_TRACK_TYPE_AUDIO;
        break;
      } else if (g_strrstr (klass, "Video")) {
        *track_type = GES_TRACK_TYPE_VIDEO;
        break;
      }
    }
  }

  gst_object_unref (effect);

  if (*track_type == GES_TRACK_TYPE_UNKNOWN) {
    *track_type = GES_TRACK_TYPE_VIDEO;
    GST_ERROR ("Could not determine track type for %s, defaulting to video",
        id);
  }

  return bindesc;
}
Example #29
0
/* NOTE: Sticking to natural behavior of returning a list with the unchanged input_string, incase nothing can be substituted, however, this is expensive. A better way would be to return NULL incase of no changes, and let the caller handle the NULL case, which implies that there is no change in the input_string */
GPtrArray* substitute_parameters(gchar *input_string, FmFileInfoList *file_info_list)
{
	//printf("Input string is %s\n", input_string);
	GPtrArray *out_string_array = g_ptr_array_new();
	if(strchr(input_string, '%') == NULL){
		//printf("Found nothing to expand. Returning input_string.\n");
		g_ptr_array_add(out_string_array, g_string_new(input_string));
		return out_string_array;
	}

	gsize i, j;
	gsize len_file_list = fm_list_get_length(file_info_list);
	GString *out_string = g_string_new(NULL);
	gsize first_pos = strcspn(input_string, "%");
	gchar *pos = input_string + first_pos;
	g_string_append_len(out_string, input_string, first_pos);
	GString *g_string_i = NULL;
	gchar *base_name = NULL, *base_dir = NULL, *file_name = NULL, *host_name = NULL, *user_name = NULL, *port = NULL, *scheme = NULL, *uri = NULL, *file_name_wo_ext = NULL, *ext_pos = NULL;
	gboolean array_is_init = FALSE;
	FmFileInfo *file_info_i = NULL, *file_info_j = NULL;
	char temp[256];
	gboolean curr_dir_flag;

	while((pos = strchr(pos, '%')) != NULL){
		switch(pos[1]){
			case 'b':
				/* Works */
				if(array_is_init == FALSE){
					for(i=0; i<len_file_list; ++i){
						g_string_i = g_string_new(out_string->str);
						file_info_i = fm_list_peek_nth(file_info_list, i);
						base_name = (gchar *)fm_file_info_get_disp_name(file_info_i);
						g_string_append(g_string_i, base_name);
						g_string_append_c(g_string_i, ' ');

						g_ptr_array_add(out_string_array, g_string_new(g_string_i->str));
						g_string_free(g_string_i, TRUE);
					}
					break;
				}

				file_info_i = fm_list_peek_head(file_info_list);
				base_name = (gchar *)fm_file_info_get_disp_name(file_info_i);
				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					g_string_append(g_string_i, base_name);
					g_string_append_c(g_string_i, ' ');
				}

				break;
			case 'B':
				/* Works */
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					for(j=0; j<len_file_list; ++j){
						file_info_j= fm_list_peek_nth(file_info_list, j);
						base_name = (gchar *)fm_file_info_get_disp_name(file_info_j);
						g_string_append(g_string_i, base_name);
						g_string_append_c(g_string_i, ' ');
					}
				}

				break;
			case 'c':
				/* Works */
				memset(temp, 256, 0);
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					sprintf(temp, "%u", len_file_list);
					g_string_append(g_string_i, temp);
					g_string_append_c(g_string_i, ' ');
				}

				break;
			case 'd':
				/* Works */
				curr_dir_flag = FALSE;
				if(array_is_init == FALSE){
					for(i=0; i<len_file_list; ++i){
						g_string_i = g_string_new(out_string->str);
						file_info_i = fm_list_peek_nth(file_info_list, i);
						if(fm_file_info_is_dir(file_info_i) == TRUE){
							base_dir = fm_path_to_str(fm_file_info_get_path(file_info_i));
						} else {
							if(curr_dir_flag == FALSE){
								base_dir = g_get_current_dir();
								curr_dir_flag = TRUE;
							} else {
								continue;
							}
						}
						g_string_append(g_string_i, base_dir);
						g_string_append_c(g_string_i, ' ');

						g_ptr_array_add(out_string_array, g_string_new(g_string_i->str));

						g_free(base_dir);
						g_string_free(g_string_i, TRUE);
					}
					break;
				}

				file_info_i = fm_list_peek_head(file_info_list);
				if(fm_file_info_is_dir(file_info_i) == TRUE){
					base_dir = fm_path_to_str(fm_file_info_get_path(file_info_i));
				} else {
					if(curr_dir_flag == FALSE){
						base_dir = g_get_current_dir();
						curr_dir_flag = TRUE;
					} else {
						continue;
					}
				}
				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					g_string_append(g_string_i, base_dir);
					g_string_append_c(g_string_i, ' ');
				}

				g_free(base_dir);
				break;
			case 'D':
				/* Works */
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					curr_dir_flag = FALSE;
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					for(j=0; j<len_file_list; ++j){
						file_info_j= fm_list_peek_nth(file_info_list, j);
						if(fm_file_info_is_dir(file_info_j) == TRUE){
							base_dir = fm_path_to_str(fm_file_info_get_path(file_info_j));
						} else {
							if(curr_dir_flag == FALSE){
								base_dir = g_get_current_dir();
								curr_dir_flag = TRUE;
							} else {
								continue;
							}
						}
						g_string_append(g_string_i, base_dir);
						g_string_append_c(g_string_i, ' ');

						g_free(base_dir);
					}
				}

				break;
			case 'f':
				/* Works */
				if(array_is_init == FALSE){
					for(i=0; i<len_file_list; ++i){
						g_string_i = g_string_new(out_string->str);
						file_info_i = fm_list_peek_nth(file_info_list, i);
						file_name = (gchar *)fm_path_to_str(fm_file_info_get_path(file_info_i));
						g_string_append(g_string_i, file_name);
						g_string_append_c(g_string_i, ' ');

						g_ptr_array_add(out_string_array, g_string_new(g_string_i->str));

						g_free(file_name);
						g_string_free(g_string_i, TRUE);
					}
					break;
				}

				file_info_i = fm_list_peek_head(file_info_list);
				file_name = (gchar *)fm_path_to_str(fm_file_info_get_path(file_info_i));
				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					g_string_append(g_string_i, file_name);
					g_string_append_c(g_string_i, ' ');
				}

				g_free(file_name);
				break;
			case 'F':
				/* Works */
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					for(j=0; j<len_file_list; ++j){
						file_info_j= fm_list_peek_nth(file_info_list, j);
						file_name = (gchar *)fm_path_to_str(fm_file_info_get_path(file_info_j));
						g_string_append(g_string_i, file_name);
						g_string_append_c(g_string_i, ' ');

						g_free(file_name);
					}
				}

				break;
			case 'h':
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					file_info_i = fm_list_peek_nth(file_info_list, i);
					host_name = get_host_name(file_info_i);
					g_string_append(g_string_i, host_name);
					g_string_append_c(g_string_i, ' ');
				}
				break;
			case 'n':
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					file_info_i = fm_list_peek_nth(file_info_list, i);
					user_name = get_user_name(file_info_i);
					g_string_append(g_string_i, user_name);
					g_string_append_c(g_string_i, ' ');
				}
				break;
			case 'p':
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					file_info_i = fm_list_peek_nth(file_info_list, i);
					port = get_port(file_info_i);
					g_string_append(g_string_i, port);
					g_string_append_c(g_string_i, ' ');
				}
				break;
			case 's':
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					file_info_i = fm_list_peek_nth(file_info_list, i);
					scheme = get_scheme(file_info_i);
					g_string_append(g_string_i, scheme);
					g_string_append_c(g_string_i, ' ');
				}

				break;
			case 'u':
				/* Works */
				if(array_is_init == FALSE){
					for(i=0; i<len_file_list; ++i){
						g_string_i = g_string_new(out_string->str);
						file_info_i = fm_list_peek_nth(file_info_list, i);
						uri = fm_path_to_uri(fm_file_info_get_path(file_info_i));
						g_string_append(g_string_i, uri);
						g_string_append_c(g_string_i, ' ');

						g_ptr_array_add(out_string_array, g_string_new(g_string_i->str));
						g_string_free(g_string_i, TRUE);
					}
					break;
				}

				file_info_i = fm_list_peek_head(file_info_list);
				uri = fm_path_to_uri(fm_file_info_get_path(file_info_i));
				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					g_string_append(g_string_i, uri);
					g_string_append_c(g_string_i, ' ');
				}

				break;
			case 'U':
				/* Works */
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					for(j=0; j<len_file_list; ++j){
						file_info_j= fm_list_peek_nth(file_info_list, j);
						uri = fm_path_to_uri(fm_file_info_get_path(file_info_j));
						g_string_append(g_string_i, uri);
						g_string_append_c(g_string_i, ' ');
					}
				}

				break;
			case 'w':
				/* Works */
				if(array_is_init == FALSE){
					for(i=0; i<len_file_list; ++i){
						g_string_i = g_string_new(out_string->str);
						file_info_i = fm_list_peek_nth(file_info_list, i);
						file_name = (gchar *)fm_file_info_get_disp_name(file_info_i);
						//printf("%s\n", file_name);

						ext_pos = g_strrstr(fm_file_info_get_disp_name(fm_list_peek_nth(file_info_list, i)), ".");
						if(ext_pos != NULL)
							file_name_wo_ext = g_strndup(file_name, strlen(file_name) - strlen(ext_pos));
						else
							file_name_wo_ext = g_strdup(file_name);

						g_string_append(g_string_i, file_name_wo_ext);
						g_string_append_c(g_string_i, ' ');
						g_ptr_array_add(out_string_array, g_string_new(g_string_i->str));

						g_free(file_name_wo_ext);
						g_string_free(g_string_i, TRUE);
					}
					break;
				}

				file_info_i = fm_list_peek_head(file_info_list);
				file_name = (gchar *)fm_file_info_get_disp_name(file_info_i);
				ext_pos = g_strrstr(file_name, ".");
				if(ext_pos != NULL)
					file_name_wo_ext = g_strndup(file_name, strlen(file_name) - strlen(ext_pos));
				else
					file_name_wo_ext = g_strdup(file_name);

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					g_string_append(g_string_i, file_name_wo_ext);
					g_string_append_c(g_string_i, ' ');
				}
				g_free(file_name_wo_ext);
				break;
			case 'W':
				/* Works */
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					for(j=0; j<len_file_list; ++j){
						file_info_j= fm_list_peek_nth(file_info_list, j);
						file_name = (gchar *)fm_file_info_get_disp_name(file_info_j);
						ext_pos = g_strrstr(file_name, ".");
						if(ext_pos != NULL)
							file_name_wo_ext = g_strndup(file_name, strlen(file_name) - strlen(ext_pos));
						else
							file_name_wo_ext = g_strdup(file_name);
						g_string_append(g_string_i, file_name_wo_ext);
						g_string_append_c(g_string_i, ' ');
						g_free(file_name_wo_ext);
					}
				}
				break;
			case 'x':
				/* Works */
				if(array_is_init == FALSE){
					for(i=0; i<len_file_list; ++i){
						file_info_i = fm_list_peek_nth(file_info_list, i);
						file_name = (gchar *)fm_file_info_get_disp_name(file_info_i);
						ext_pos = g_strrstr(file_name, ".");
						if(ext_pos != NULL){
							g_string_i = g_string_new(out_string->str);
							g_string_append(g_string_i, ext_pos);
							g_string_append_c(g_string_i, ' ');
							g_ptr_array_add(out_string_array, g_string_new(g_string_i->str));

							g_free(file_name_wo_ext);
							g_string_free(g_string_i, TRUE);
						}
					}
					break;
				}

				file_info_i = fm_list_peek_head(file_info_list);
				file_name = (gchar *)fm_file_info_get_disp_name(file_info_i);
				ext_pos = g_strrstr(file_name, ".");
				if(ext_pos == NULL)
					break;

				for(i=0; i<out_string_array->len;++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					g_string_append(g_string_i, ext_pos);
					g_string_append_c(g_string_i, ' ');
				}

				break;
			case 'X':
				/* Works */
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					for(j=0; j<len_file_list; ++j){
						file_info_j= fm_list_peek_nth(file_info_list, j);
						file_name = (gchar *)fm_file_info_get_disp_name(file_info_j);
						ext_pos = g_strrstr(file_name, ".");
						if(ext_pos != NULL){
							g_string_append(g_string_i, ext_pos);
							g_string_append_c(g_string_i, ' ');
						}
					}
				}

				break;
			case '%':
				/* Works */
				if(array_is_init == FALSE)
					g_ptr_array_add(out_string_array, g_string_new(out_string->str));

				for(i=0; i<out_string_array->len; ++i){
					g_string_i = (GString *)g_ptr_array_index(out_string_array, i);
					g_string_append(g_string_i, "% ");
				}

				break;
			default:
				return NULL;
		}

		pos += 2;
		(array_is_init == FALSE)?array_is_init = TRUE:0;
	}

	return out_string_array;
}
Example #30
0
/*!
  \brief Binds remaing keys in cfgfile to the object
  \param object is the pointer to object where we bind the data to
  \param cfgfile is the pointer to configfile  where we pull the data from
  \param section is the section name within cfgfile to gt the data from
  \param keys is the array of char *'s, list of keys to read and store
  \param num_keys is the number of elements in the keys array
  */
G_MODULE_EXPORT void bind_keys(GObject *object, ConfigFile *cfgfile, gchar *section, gchar ** keys, gint num_keys)
{
	gint i = 0;
	gint tmpi = 0;
	gfloat tmpf = 0.0;
	gfloat *newfloat = NULL;
	gchar * tmpbuf = NULL;
	gchar * tmpstr = NULL;
	DataType keytype = MTX_STRING;

	for (i=0;i<num_keys;i++)
	{
		keytype = translate_string(keys[i]);
		switch(keytype)
		{
			case MTX_INT:
				if (cfg_read_int(cfgfile,section,keys[i],&tmpi))
				{
					MTXDBG(KEYPARSER,_("Binding INT \"%s\",\"%i\" to widget \"%s\"\n"),keys[i],tmpi,section);
					OBJ_SET(object,
							keys[i],
							GINT_TO_POINTER(tmpi));	
				}
				else
					MTXDBG(KEYPARSER|CRITICAL,_("MTX_INT: read of key \"%s\" from section \"%s\"  of file \"%s\" failed\n"),keys[i],section,cfgfile->filename);
				break;
			case MTX_ENUM:
				if (cfg_read_string(cfgfile,section,keys[i],&tmpbuf))
				{
					tmpi = translate_string(tmpbuf);
					MTXDBG(KEYPARSER,_("Binding ENUM \"%s\",\"%i\" to widget \"%s\"\n"),keys[i],tmpi,section);
					OBJ_SET(object,
							keys[i],
							GINT_TO_POINTER(tmpi));	
					g_free(tmpbuf);
				}
				else
					MTXDBG(KEYPARSER|CRITICAL,_("MTX_ENUM: read of key \"%s\" from section \"%s\" of file \"%s\" failed\n"),keys[i],section,cfgfile->filename);
				break;
			case MTX_BOOL:
				if (cfg_read_boolean(cfgfile,section,keys[i],&tmpi))
				{
					MTXDBG(KEYPARSER,_("Binding BOOL \"%s\",\"%i\" to widget \"%s\"\n"),keys[i],tmpi,section);
					if (tmpi)
					{
						OBJ_SET(object,
								keys[i],
								GINT_TO_POINTER(tmpi));	
						if (strstr(keys[i],"fromecu_complex"))
							load_complex_params_obj(object,cfgfile,section);
					}
				}
				else
					MTXDBG(KEYPARSER|CRITICAL,_("MTX_BOOL: read of key \"%s\" from section \"%s\" of file \"%s\" failed\n"),keys[i],section,cfgfile->filename);
				break;
			case MTX_FLOAT:
				if (cfg_read_float(cfgfile,section,keys[i],&tmpf))
				{
					newfloat = NULL;
					newfloat = g_new0(gfloat, 1);
					*newfloat = tmpf;
					OBJ_SET_FULL(object,
							keys[i],
							(gpointer)newfloat,g_free);
				}
				else
					MTXDBG(KEYPARSER|CRITICAL,_("MTX_FLOAT: read of key \"%s\" from section \"%s\" of file \"%s\" failed\n"),keys[i],section,cfgfile->filename);
				break;

			case MTX_STRING:
				if(cfg_read_string(cfgfile,section,keys[i],&tmpbuf))
				{
					MTXDBG(KEYPARSER,_("Binding STRING key:\"%s\" value:\"%s\" to widget \"%s\"\n"),keys[i],tmpbuf,section);
					tmpstr = DATA_GET(object,keys[i]);
					/* If data already on widget, append
					 * new data and store */
					if ((tmpstr) && (g_strrstr(keys[i],"bind_to_list")!= NULL))
					{
						tmpstr = g_strconcat(tmpstr,",",tmpbuf,NULL);
						OBJ_SET_FULL(object,
								keys[i],
								g_strdup(tmpstr),
								g_free);
						g_free(tmpstr);
					}
					else
						OBJ_SET_FULL(object,keys[i],g_strdup(tmpbuf),g_free);
								
					g_free(tmpbuf);
				}
				else
					MTXDBG(KEYPARSER|CRITICAL,_("MTX_STRING: read of key \"%s\" from section \"%s\" of file \"%s\" failed\n"),keys[i],section,cfgfile->filename);
				break;
			default:
				break;

		}
	}

	return;
}