Exemple #1
0
void
log_msg(log_level_t level, const char * const area, const char * const msg)
{
    if (level >= level_filter && logp != NULL) {
        dt = g_date_time_new_now(tz);

        char *level_str = _log_string_from_level(level);

        gchar *date_fmt = g_date_time_format(dt, "%d/%m/%Y %H:%M:%S");

        fprintf(logp, "%s: %s: %s: %s\n", date_fmt, area, level_str, msg);
        g_date_time_unref(dt);

        fflush(logp);
        g_free(date_fmt);

        if (prefs_get_boolean(PREF_LOG_ROTATE)) {
            long result = ftell(logp);
            if (result != -1 && result >= prefs_get_max_log_size()) {
                _rotate_log_file();
            }
        }
    }
}
Exemple #2
0
static void
_win_print(ProfWin *window, const char show_char, GDateTime *time,
    int flags, theme_item_t theme_item, const char * const from, const char * const message)
{
    // flags : 1st bit =  0/1 - me/not me
    //         2nd bit =  0/1 - date/no date
    //         3rd bit =  0/1 - eol/no eol
    //         4th bit =  0/1 - color from/no color from
    //         5th bit =  0/1 - color date/no date
    gboolean me_message = FALSE;
    int offset = 0;
    int colour = theme_attrs(THEME_ME);

    if ((flags & NO_DATE) == 0) {
        gchar *date_fmt = NULL;
        char *time_pref = prefs_get_string(PREF_TIME);
        if (g_strcmp0(time_pref, "minutes") == 0) {
            date_fmt = g_date_time_format(time, "%H:%M");
        } else if (g_strcmp0(time_pref, "seconds") == 0) {
            date_fmt = g_date_time_format(time, "%H:%M:%S");
        }
        free(time_pref);

        if (date_fmt) {
            if ((flags & NO_COLOUR_DATE) == 0) {
                wattron(window->win, theme_attrs(THEME_TIME));
            }
            wprintw(window->win, "%s %c ", date_fmt, show_char);
            if ((flags & NO_COLOUR_DATE) == 0) {
                wattroff(window->win, theme_attrs(THEME_TIME));
            }
        }
        g_free(date_fmt);
    }

    if (strlen(from) > 0) {
        if (flags & NO_ME) {
            colour = theme_attrs(THEME_THEM);
        }

        if (flags & NO_COLOUR_FROM) {
            colour = 0;
        }

        wattron(window->win, colour);
        if (strncmp(message, "/me ", 4) == 0) {
            wprintw(window->win, "*%s ", from);
            offset = 4;
            me_message = TRUE;
        } else {
            wprintw(window->win, "%s: ", from);
            wattroff(window->win, colour);
        }
    }

    if (!me_message) {
        wattron(window->win, theme_attrs(theme_item));
    }

    if (prefs_get_boolean(PREF_WRAP)) {
        _win_print_wrapped(window->win, message+offset);
    } else {
        wprintw(window->win, "%s", message+offset);
    }

    if ((flags & NO_EOL) == 0) {
        wprintw(window->win, "\n");
    }

    if (me_message) {
        wattroff(window->win, colour);
    } else {
        wattroff(window->win, theme_attrs(theme_item));
    }
}
/* Setup header fields (From:/To:/Date: etc) and message body for the e-mail.
 * This data is supposed to be sent to libcurl just before any media data.
 * This function is called once for each e-mail:
 * 1. we are about the send the first attachment
 * 2. we have sent all the attachments and continue sending new ones within
 *    a new e-mail (transfer options have been reset). */
static gboolean
gst_curl_smtp_sink_set_transfer_options_unlocked (GstCurlBaseSink * bcsink)
{
  GstCurlSmtpSink *sink = GST_CURL_SMTP_SINK (bcsink);
  GstCurlTlsSinkClass *parent_class;
  gchar *request_headers;
  GDateTime *date;
  gchar *date_str;
  gchar **tmp_list = NULL;
  gchar *subject_header = NULL;
  gchar *message_body = NULL;
  gchar *rcpt_header = NULL;
  gchar *enc_rcpt;
  gchar *from_header = NULL;
  gchar *enc_from;
  gint i;

  g_assert (sink->payload_headers == NULL);
  g_assert (sink->mail_rcpt != NULL);
  g_assert (sink->mail_from != NULL);

  /* time */
  date = g_date_time_new_now_local ();
  date_str = g_date_time_format (date, "%a %b %e %H:%M:%S %Y");
  g_date_time_unref (date);

  /* recipient, sender and subject are all UTF-8 strings, which are additionally
   * base64-encoded */

  /* recipient */
  enc_rcpt = generate_encoded_word (sink->mail_rcpt);
  rcpt_header = g_strdup_printf ("%s <%s>", enc_rcpt, sink->mail_rcpt);
  g_free (enc_rcpt);

  /* sender */
  enc_from = generate_encoded_word (sink->mail_from);
  from_header = g_strdup_printf ("%s <%s>", enc_from, sink->mail_from);
  g_free (enc_from);

  /* subject */
  if (sink->subject != NULL) {
    subject_header = generate_encoded_word (sink->subject);
  }

  /* message */
  if (sink->message_body != NULL) {
    message_body = g_base64_encode ((const guchar *) sink->message_body,
        strlen (sink->message_body));
  }

  request_headers = g_strdup_printf (
      /* headers */
      "To: %s\r\n"
      "From: %s\r\n"
      "Subject: %s\r\n"
      "Date: %s\r\n"
      MIME_VERSION "\r\n"
      "Content-Type: multipart/mixed; boundary=%s\r\n" "\r\n"
      /* body headers */
      "--" BOUNDARY_STRING "\r\n"
      "Content-Type: text/plain; charset=utf-8\r\n"
      "Content-Transfer-Encoding: BASE64\r\n"
      /* message body */
      "\r\n%s\r\n",
      rcpt_header,
      from_header,
      subject_header ? subject_header : "",
      date_str, BOUNDARY_STRING, message_body ? message_body : "");

  sink->payload_headers = g_byte_array_new ();

  g_byte_array_append (sink->payload_headers, (guint8 *) request_headers,
      strlen (request_headers));
  g_free (date_str);
  g_free (subject_header);
  g_free (message_body);
  g_free (rcpt_header);
  g_free (from_header);
  g_free (request_headers);

  curl_easy_setopt (bcsink->curl, CURLOPT_MAIL_FROM, sink->mail_from);

  if (sink->curl_recipients != NULL) {
    curl_slist_free_all (sink->curl_recipients);
    sink->curl_recipients = NULL;
  }

  tmp_list = g_strsplit_set (sink->mail_rcpt, MAIL_RCPT_DELIMITER, -1);
  for (i = 0; i < g_strv_length (tmp_list); i++) {
    sink->curl_recipients = curl_slist_append (sink->curl_recipients,
        tmp_list[i]);
  }
  g_strfreev (tmp_list);

  /* note that the CURLOPT_MAIL_RCPT takes a list, not a char array */
  curl_easy_setopt (bcsink->curl, CURLOPT_MAIL_RCPT, sink->curl_recipients);

  parent_class = GST_CURL_TLS_SINK_GET_CLASS (sink);

  if (sink->use_ssl) {
    return parent_class->set_options_unlocked (bcsink);
  }

  return TRUE;
}
static void indicator_rest_coupon_cb(GtkWidget *widget, gpointer data)
{
  IIJmioIndicatorOption *option = data;
  const gchar *access_token;
  gboolean enable_debug;
  CURL *curl;
  CURLcode res;
  struct curl_slist *chunk = NULL;
  FILE *json_file;
  gchar *json_path;
  gchar *json_dir;
  gchar *token_header;
  const gchar *home_dir;
  gchar *basename;
  GDateTime *datetime;

  access_token = gtk_entry_get_text(GTK_ENTRY(option->widgets.access_token));

  curl_global_init(CURL_GLOBAL_DEFAULT);
  curl = curl_easy_init();
  if (curl) {
    curl_easy_setopt(curl,
                     CURLOPT_URL,
                     "https://api.iijmio.jp/mobile/d/v1/coupon/");
    chunk = curl_slist_append(chunk,
                              "X-IIJmio-Developer: XpVuCioCmLzAeewwiDs");
    token_header = g_strdup_printf("%s: %s",
                                   "X-IIJmio-Authorization", access_token);
    chunk = curl_slist_append(chunk, token_header);
    res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);

    home_dir = g_get_home_dir();
    json_dir = g_build_path(G_DIR_SEPARATOR_S,
                            home_dir,
                            ".iijmio-appindicator",
                            "json",
                            NULL);
    g_mkdir_with_parents(json_dir, 0700);

    datetime = g_date_time_new_now_local();
    basename = g_date_time_format(datetime, "%Y%m%d-%H%M%S");
    json_path = g_strdup_printf("%s%s%s.json",
                                json_dir,
                                G_DIR_SEPARATOR_S,
                                basename);

    json_file = fopen(json_path, "w+");
    if (json_file) {

      curl_easy_setopt(curl, CURLOPT_FILE, json_file);

      res = curl_easy_perform(curl);
      if (res != CURLE_OK) {
        fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));
      }
      fclose(json_file);
    }
    g_free(token_header);
    curl_easy_cleanup(curl);
  }
  curl_global_cleanup();
}
int main() {

  // if final value remains 0 the test is passed otherwise return a -1: 
  gint retVal = 0;

  /************************************************/
  /* Create three time series for use in the tests: */
  /************************************************/

  // use the same time zone for all dates:
  GTimeZone *tz = (GTimeZone *)g_time_zone_new_local();
  
  //first time series:
  GSList* first_ts = NULL, *first_dates = NULL, *first_values = NULL;

  first_dates = g_slist_append(first_dates, g_date_time_new(tz, 2015, 10, 1, 1, 0, 0.0));
  first_dates = g_slist_append(first_dates, g_date_time_new(tz, 2015, 10, 1, 5, 0, 0.0));
  first_dates = g_slist_append(first_dates, g_date_time_new(tz, 2015, 10, 1, 6, 0, 0.0));

  // GSLists can only hold pointers to data so we need to init the
  // gfloats and then store their addresses in the GSList:
  gdouble p1 = 1.0;
  gdouble p2 = 1.0;
  gdouble p3 = 1.0;
  
  first_values = g_slist_append(first_values, &p1);
  first_values = g_slist_append(first_values, &p2);
  first_values = g_slist_append(first_values, &p3);

  first_ts = ts_gdt_double(first_dates, first_values);

  // second time series using different dates:
  GSList* second_ts = NULL, *second_dates = NULL, *second_values = NULL;

  second_dates = g_slist_append(second_dates, g_date_time_new(tz, 2015, 10, 1, 2, 0, 0.0));
  second_dates = g_slist_append(second_dates, g_date_time_new(tz, 2015, 10, 1, 5, 0, 0.0));
  second_dates = g_slist_append(second_dates, g_date_time_new(tz, 2015, 10, 1, 10, 0, 0.0));
  
  // GSLists can only hold pointers to data so we need to init the
  // gfloats and then store their addresses in the GSList:
  gdouble q1 = 1.0;
  gdouble q2 = 1.0;
  gdouble q3 = 1.0;
  
  second_values = g_slist_append(second_values, &q1);
  second_values = g_slist_append(second_values, &q2);
  second_values = g_slist_append(second_values, &q3);

  second_ts = ts_gdt_double(second_dates, second_values);

  // third time series using still different dates:
  GSList* third_ts = NULL, *third_dates = NULL, *third_values = NULL;

  third_dates = g_slist_append(third_dates, g_date_time_new(tz, 2015, 10, 1, 2, 0, 0.0));
  third_dates = g_slist_append(third_dates, g_date_time_new(tz, 2015, 10, 1, 5, 0, 0.0));
  third_dates = g_slist_append(third_dates, g_date_time_new(tz, 2015, 10, 1, 9, 0, 0.0));
  // GSLists can only hold pointers to data so we need to init the
  // gfloats and then store their addresses in the GSList:
  gdouble r1 = 1.0;
  gdouble r2 = 1.0;
  gdouble r3 = 1.0;
  
  third_values = g_slist_append(third_values, &r1);
  third_values = g_slist_append(third_values, &r2);
  third_values = g_slist_append(third_values, &r3);

  third_ts = ts_gdt_double(third_dates, third_values);

  // clean up that timezone that we used to create all the data:
  g_time_zone_unref(tz);
  
  /********************************************/
  /* Now let's look at our three time series: */
  /********************************************/
  g_printf("first ts: \n");
  ts_pretty_print(first_ts);
  g_printf("second ts: \n");
  ts_pretty_print(second_ts);
  g_printf("third ts: \n");
  ts_pretty_print(third_ts);
  
  /*******************************/
  /* Alignment test begins here: */
  /*******************************/

  // Put all the time series to be aligned into a single list:
  GSList *pre_aligned_list = NULL;
  pre_aligned_list = g_slist_append(pre_aligned_list, first_ts);
  pre_aligned_list = g_slist_append(pre_aligned_list, second_ts);
  pre_aligned_list = g_slist_append(pre_aligned_list, third_ts);

  // Alignment will create a new list of the same time series but they
  // all should now have the same domains:
  GSList *aligned_list = NULL, *iter_1 = NULL, *iter_2 = NULL, *iter_3 = NULL;

  // do the alignment:
  aligned_list = ts_align_hourly(pre_aligned_list);

  // now we do the check:
  GSList *al_first = (GSList *)g_slist_nth(aligned_list, 0)->data;
  GSList *al_second = (GSList *)g_slist_nth(aligned_list, 1)->data;
  GSList *al_third = (GSList *)g_slist_nth(aligned_list, 2)->data;

  // the resulting time series should all look like this:
  //date	first	second	third
  //2015-Oct-01	1	nan	nan
  //2015-Oct-02	nan	1	1
  //2015-Oct-03	nan	nan	nan
  //2015-Oct-04	nan	nan	nan
  //2015-Oct-05	1	1	1
  //2015-Oct-06	1	nan	nan
  //2015-Oct-07	nan	nan	nan
  //2015-Oct-08	nan	nan	nan
  //2015-Oct-09	nan	nan	1
  //2015-Oct-10	nan	1	nan

  // print out a table of the time series:
  g_printf("Date:\tfirst:\tsecond:\tthird:\n");
  for (iter_1 = al_first, iter_2 = al_second, iter_3 = al_third;	\
       iter_1 && iter_2 && iter_3;					\
       iter_1 = iter_1->next, iter_2 = iter_2->next, iter_3 = iter_3->next) {
    ts_datum_double *first_datum = iter_1->data;
    ts_datum_double *second_datum = iter_2->data;
    ts_datum_double *third_datum = iter_3->data;
    gchar *dt_str = (gchar *)g_date_time_format(first_datum->thedate, "%F %T");
    g_printf("%s\t%g\t%g\t%g\n",					\
	     dt_str, \
	     first_datum->thevalue,					\
	     second_datum->thevalue,					\
	     third_datum->thevalue);
    g_free(dt_str);
  }

  // clean up the lists that were used to create the pre_aligned time
  // series:
  g_slist_free_full(first_dates, g_date_time_free);
  g_slist_free(first_values);
  g_slist_free_full(second_dates, g_date_time_free);
  g_slist_free(second_values);
  g_slist_free_full(third_dates, g_date_time_free);
  g_slist_free(third_values);

  // clean up the lists that are in the pre_aligned list of time series:
  g_slist_free_full(first_ts, ts_datum_double_free);
  g_slist_free_full(second_ts, ts_datum_double_free);
  g_slist_free_full(third_ts, ts_datum_double_free);
  g_slist_free(pre_aligned_list);

  // clean up the lists that in the aligned list of time series:
  g_slist_free_full(al_first, ts_datum_double_free);
  g_slist_free_full(al_second, ts_datum_double_free);
  g_slist_free_full(al_third, ts_datum_double_free);
  g_slist_free(aligned_list);
  
  return retVal;

}
Exemple #6
0
void
sv_ev_lastactivity_response(const char *const from, const int seconds, const char *const msg)
{
    Jid *jidp = jid_create(from);

    if (!jidp) {
        return;
    }

    GDateTime *now = g_date_time_new_now_local();
    GDateTime *active = g_date_time_add_seconds(now, 0 - seconds);

    gchar *date_fmt = NULL;
    char *time_pref = prefs_get_string(PREF_TIME_LASTACTIVITY);
    date_fmt = g_date_time_format(active, time_pref);
    prefs_free_string(time_pref);
    assert(date_fmt != NULL);

    // full jid - last activity
    if (jidp->resourcepart) {
        if (seconds == 0) {
            if (msg) {
                cons_show("%s currently active, status: %s", from, msg);
            } else {
                cons_show("%s currently active", from);
            }
        } else {
            if (msg) {
                cons_show("%s last active %s, status: %s", from, date_fmt, msg);
            } else {
                cons_show("%s last active %s", from, date_fmt);
            }
        }

    // barejid - last logged in
    } else if (jidp->localpart) {
        if (seconds == 0) {
            if (msg) {
                cons_show("%s currently logged in, status: %s", from, msg);
            } else {
                cons_show("%s currently logged in", from);
            }
        } else {
            if (msg) {
                cons_show("%s last logged in %s, status: %s", from, date_fmt, msg);
            } else {
                cons_show("%s last logged in %s", from, date_fmt);
            }
        }

    // domain only - uptime
    } else {
        int left = seconds;
        int days = seconds / 86400;
        left = left - days * 86400;
        int hours = left / 3600;
        left = left - hours * 3600;
        int minutes = left / 60;
        left = left - minutes * 60;
        int seconds = left;

        cons_show("%s up since %s, uptime %d days, %d hrs, %d mins, %d secs", from, date_fmt, days, hours, minutes, seconds);
    }

    g_date_time_unref(now);
    g_date_time_unref(active);
    g_free(date_fmt);
    jid_destroy(jidp);
}
Exemple #7
0
void linphone_gtk_call_log_update(GtkWidget *w){
	GtkTreeView *v=GTK_TREE_VIEW(linphone_gtk_get_widget(w,"logs_view"));
	GtkTreeStore *store;
	const MSList *logs;
	GtkTreeSelection *select;
	GtkWidget *notebook=linphone_gtk_get_widget(w,"viewswitch");
	gint nb;

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

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

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

		if (linphone_call_log_get_quality(cl)!=-1){
			snprintf(quality,sizeof(quality),"%.1f",linphone_call_log_get_quality(cl));
		}else snprintf(quality,sizeof(quality)-1,"%s",_("n/a"));
		switch(linphone_call_log_get_status(cl)){
			case LinphoneCallAborted:
				status=_("Aborted");
			break;
			case LinphoneCallMissed:
				status=_("Missed");
			break;
			case LinphoneCallDeclined:
				status=_("Declined");
			break;
			default:
			break;
		}
		minutes=g_markup_printf_escaped(
			ngettext("%i minute", "%i minutes", duration/60),
			duration/60);
		seconds=g_markup_printf_escaped(
			ngettext("%i second", "%i seconds", duration%60),
			duration%60);
		if (status==NULL) {
				headtxt=g_markup_printf_escaped("<big><b>%s</b></big>\t%s",display,start_date ? start_date : "");
				logtxt=g_markup_printf_escaped(
				_("<small><i>%s</i>\t"
				  "<i>Quality: %s</i></small>\n%s\t%s\t"),
				addr, quality, minutes, seconds);
		} else {
			headtxt=g_markup_printf_escaped(_("<big><b>%s</b></big>\t%s"),display,start_date ? start_date : "");
			logtxt=g_markup_printf_escaped(
			"<small><i>%s</i></small>\t"
				"\n%s",addr, status);
		}
		g_free(minutes);
		g_free(seconds);
		if (start_date) g_free(start_date);
		gtk_tree_store_append (store,&iter,NULL);
		call_status_icon_name = linphone_call_log_get_dir(cl) == LinphoneCallOutgoing ?
			"linphone-call-status-outgoing" : "linphone-call-status-incoming";
		gtk_tree_store_set (store,&iter,
		               0, call_status_icon_name,
		               1, headtxt,2,cl,-1);
		gtk_tree_store_append (store,&iter2,&iter);
		gtk_tree_store_set (store,&iter2,1,logtxt,-1);
		ms_free(addr);
		g_free(logtxt);
		g_free(headtxt);
	}
}
Exemple #8
0
int main (int argc, char *argv[])
{
        HTTPMgmt *httpmgmt;
        HTTPStreaming *httpstreaming;
        GMainLoop *loop;
        GOptionContext *ctx;
        GError *err = NULL;
        gboolean foreground;
        struct rlimit rlim;
        GDateTime *datetime;
        gchar exe_path[512], *date;

        ctx = g_option_context_new (NULL);
        g_option_context_add_main_entries (ctx, options, NULL);
        g_option_context_add_group (ctx, gst_init_get_option_group ());
        if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
                g_print ("Error initializing: %s\n", GST_STR_NULL (err->message));
                exit (1);
        }
        g_option_context_free (ctx);
        GST_DEBUG_CATEGORY_INIT (GSTREAMILL, "gstreamill", 0, "gstreamill log");

        if (version) {
                print_version_info ();
                exit (0);
        }

        /* stop gstreamill. */
        if (stop) {
                gchar *pid_str;
                gint pid;

                g_file_get_contents (PID_FILE, &pid_str, NULL, NULL);
                if (pid_str == NULL) {
                        g_print ("File %s not found, check if gstreamill is running.\n", PID_FILE);
                        exit (1);
                }
                pid = atoi (pid_str);
                g_free (pid_str);
                g_print ("stoping gstreamill with pid %d ...\n", pid);
                kill (pid, SIGTERM);
                exit (0);
        }

        /* readlink exe path before setuid, on CentOS, readlink exe path after setgid/setuid failure on permission denied */
        memset (exe_path, '\0', sizeof (exe_path));
        if (readlink ("/proc/self/exe", exe_path, sizeof (exe_path)) == -1) {
                g_print ("Read /proc/self/exe error: %s", g_strerror (errno));
                exit (2);
        }

        if (prepare_gstreamill_run_dir () != 0) {
                g_print ("Can't create gstreamill run directory\n");
                exit (3);
        }
/*
        if (set_user_and_group () != 0) {
                g_print ("set user and group failure\n");
                exit (4);
        }
*/
        if (job_file != NULL) {
                /* gstreamill command with job, run in foreground */
                foreground = TRUE;

        } else {
                /* gstreamill command without job, run in background */
                foreground = FALSE;
        }

        if (gst_debug_get_default_threshold () < GST_LEVEL_WARNING) {
                gst_debug_set_default_threshold (GST_LEVEL_WARNING);
        }

        /* initialize ts segment static plugin */
        if (!gst_plugin_register_static (GST_VERSION_MAJOR,
                                         GST_VERSION_MINOR,
                                         "tssegment",
                                         "ts segment plugin",
                                         ts_segment_plugin_init,
                                         "0.1.0",
                                         "GPL",
                                         "GStreamer",
                                         "GStreamer",
                                         "http://gstreamer.net/")) {
                GST_ERROR ("registe tssegment error");
                exit (17);
        }

        /* subprocess, create_job_process */
        if (shm_name != NULL) {
                gint fd;
                gchar *job_desc, *p;
                Job *job;
                gchar *log_path, *name;
                gint ret;

                /* set subprocess maximum of core file */
                rlim.rlim_cur = 0;
                rlim.rlim_max = 0;
                if (setrlimit (RLIMIT_CORE, &rlim) == -1) {
                        GST_ERROR ("setrlimit error: %s", g_strerror (errno));
                }

                /* read job description from share memory */
                job_desc = NULL;
                fd = shm_open (shm_name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
                if (ftruncate (fd, job_length) == -1) {
                        exit (5);
                }
                p = mmap (NULL, job_length, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
                job_desc = g_strdup (p);

                if ((job_desc != NULL) && (!jobdesc_is_valid (job_desc))) {
                        exit (6);
                }

                /* initialize log */
                name = (gchar *)jobdesc_get_name (job_desc);
                if (!jobdesc_is_live (job_desc)) {
                        gchar *p;

                        p = jobdesc_get_log_path (job_desc);
                        log_path = g_build_filename (p, "gstreamill.log", NULL);
                        g_free (p);

                } else {
                        log_path = g_build_filename (log_dir, name, "gstreamill.log", NULL);
                }
                ret = init_log (log_path);
                g_free (log_path);
                if (ret != 0) {
                        exit (7);
                }

                /* launch a job. */
                datetime = g_date_time_new_now_local ();
                date = g_date_time_format (datetime, "%b %d %H:%M:%S");
                fprintf (_log->log_hd, "\n*** %s : job %s starting ***\n\n", date, name);
                g_date_time_unref (datetime);
                g_free (date);
                job = job_new ("name", name, "job", job_desc, NULL);
                job->is_live = jobdesc_is_live (job_desc);
                job->eos = FALSE;
                loop = g_main_loop_new (NULL, FALSE);

                GST_INFO ("Initializing job ...");
                if (job_initialize (job, TRUE) != 0) {
                        GST_ERROR ("initialize job failure, exit");
                        exit (8);
                }
                GST_INFO ("Initializing job done");

                GST_INFO ("Initializing job's encoders output ...");
                if (job_encoders_output_initialize (job) != 0) {
                        GST_ERROR ("initialize job encoders' output failure, exit");
                        exit (8);
                }
                GST_INFO ("Initializing job's encoders output done");

                GST_INFO ("Starting job ...");
                if (job_start (job) != 0) {
                        GST_ERROR ("start livejob failure, exit");
                        exit (9);
                }
                datetime = g_date_time_new_now_local ();
                date = g_date_time_format (datetime, "%b %d %H:%M:%S");
                fprintf (_log->log_hd, "\n*** %s : job %s started ***\n\n", date, name);
                g_date_time_unref (datetime);
                g_free (date);
                g_free (name);
                g_free (job_desc);

                signal (SIGPIPE, SIG_IGN);
                signal (SIGUSR1, sighandler);
                signal (SIGTERM, stop_job);

                g_main_loop_run (loop);

        } else {
                /* set parent process maximum of core file */
                rlim.rlim_cur = RLIM_INFINITY;
                rlim.rlim_max = RLIM_INFINITY;
                if (setrlimit (RLIMIT_CORE, &rlim) == -1) {
                        GST_ERROR ("setrlimit error: %s", g_strerror (errno));
                }
        }

        /* run in background? */
        if (!foreground) {
                gchar *path;
                gint ret;

                /* pid file exist? */
                if (g_file_test (PID_FILE, G_FILE_TEST_EXISTS)) {
                        g_print ("file %s found, gstreamill already running !!!\n", PID_FILE);
                        exit (10);
                }

                /* media directory */
                path = g_strdup_printf ("%s/dvr", MEDIA_LOCATION);
                if (!g_file_test (path, G_FILE_TEST_EXISTS)) {
                        g_printf ("Create DVR directory: %s", path);
                        if (g_mkdir_with_parents (path, 0755) != 0) {
                                g_printf ("Create DVR directory failure: %s", path);
                        }
                }
                g_free (path);
                path = g_strdup_printf ("%s/transcode/in", MEDIA_LOCATION);
                if (!g_file_test (path, G_FILE_TEST_EXISTS)) {
                        g_printf ("Create transcode directory: %s", path);
                        if (g_mkdir_with_parents (path, 0755) != 0) {
                                g_printf ("Create transcode directory failure: %s", path);
                        }
                }
                g_free (path);
                path = g_strdup_printf ("%s/transcode/out", MEDIA_LOCATION);
                if (!g_file_test (path, G_FILE_TEST_EXISTS)) {
                        g_printf ("Create transcode directory: %s", path);
                        if (g_mkdir_with_parents (path, 0755) != 0) {
                                g_printf ("Create transcode directory failure: %s", path);
                        }
                }
                g_free (path);

                /* log to file */
                path = g_build_filename (log_dir, "gstreamill.log", NULL);
                ret = init_log (path);
                g_free (path);
                if (ret != 0) {
                        g_print ("Init log error, ret %d.\n", ret);
                        exit (11);
                }

                /* daemonize */
                if (daemon (0, 0) != 0) {
                        fprintf (_log->log_hd, "Failed to daemonize");
                        remove_pid_file ();
                        exit (1);
                }

                /* create pid file */
                if (create_pid_file () != 0) {
                        exit (1);
                }

                /* customize signal */
                signal (SIGUSR1, sighandler);
                signal (SIGTERM, stop_gstreamill);

                datetime = g_date_time_new_now_local ();
                date = g_date_time_format (datetime, "%b %d %H:%M:%S");
                fprintf (_log->log_hd, "\n*** %s : gstreamill started ***\n\n", date);
                g_free (date);
                g_date_time_unref (datetime);
        }

        /* ignore SIGPIPE */
        signal (SIGPIPE, SIG_IGN);

        loop = g_main_loop_new (NULL, FALSE);

        /* gstreamill */
        gstreamill = gstreamill_new ("daemon", !foreground, "log_dir", log_dir, "exe_path", exe_path, NULL);
        if (gstreamill_start (gstreamill) != 0) {
                GST_ERROR ("start gstreamill error, exit.");
                remove_pid_file ();
                exit (12);
        }

        /* httpstreaming, pull */
        httpstreaming = httpstreaming_new ("gstreamill", gstreamill, "address", http_streaming, NULL);
        if (httpstreaming_start (httpstreaming, 10) != 0) {
                GST_ERROR ("start httpstreaming error, exit.");
                remove_pid_file ();
                exit (13);
        }

        if (!foreground) {
                /* run in background, management via http */
                httpmgmt = httpmgmt_new ("gstreamill", gstreamill, "address", http_mgmt, NULL);
                if (httpmgmt_start (httpmgmt) != 0) {
                        GST_ERROR ("start http mangment error, exit.");
                        remove_pid_file ();
                        exit (14);
                }

        } else {
                /* run in foreground, start job */
                gchar *job, *p, *result;
                JSON_Value *val;
                JSON_Object *obj;

                /* ctrl-c, stop gstreamill */
                signal (SIGINT, stop_gstreamill);

                /* ctrl-\, stop gstreamill */
                signal (SIGQUIT, stop_gstreamill);

                if (!g_file_get_contents (job_file, &job, NULL, NULL)) {
                        GST_ERROR ("Read job file %s error.", job_file);
                        exit (15);
                }
                p = gstreamill_job_start (gstreamill, job);
                val = json_parse_string (p);
                obj = json_value_get_object (val);
                result = (gchar *)json_object_get_string (obj, "result");
                GST_INFO ("start job result: %s.", result);
                if (g_strcmp0 (result, "success") != 0) {
                        exit (16);
                }
                json_value_free (val);
                g_free (p);
        }

        g_main_loop_run (loop);

        return 0;
}
static void
get_spaces_cb (GObject      *object,
                GAsyncResult *result,
                gpointer      user_data)
{
   CatchResourceGroup *spaces;
   CatchResource *space;
   CatchSession *session = (CatchSession *)object;
   GDateTime *created_at;
   GDateTime *modified_at;
   GError *error = NULL;
   gchar *id;
   gchar *name;
   gchar *server_modified_at;
   gchar *created_str;
   gchar *modified_str;
   guint length;
   guint i;

   g_return_if_fail(CATCH_IS_SESSION(session));

   if (!(spaces = catch_session_get_spaces_finish(session, result, &error))) {
      g_printerr("%s\n", error->message);
      g_error_free(error);
      g_main_loop_quit(gMainLoop);
      return;
   }

   if (!catch_resource_group_get_count(spaces)) {
      g_print("No spaces found.\n");
      g_main_loop_quit(gMainLoop);
      return;
   }

   g_print(" %-24s | %-17s | %-17s | %-13s | %-20s\n",
           "Remote ID", "Created At", "Modified At",
           "Version", "Name");
   g_print("-------------------------------"
           "-------------------------------"
           "-------------------------------\n");

   /*
    * TODO: This should all be async, force load the entire range.
    */

   length = catch_resource_group_get_count(spaces);
   for (i = 0; i < length; i++) {
      space = catch_resource_group_get_resource(spaces, i);
      g_object_get(space,
                   "created-at", &created_at,
                   "modified-at", &modified_at,
                   "remote-id", &id,
                   "server_modified_at", &server_modified_at,
                   "name", &name,
                   NULL);
      created_str = g_date_time_format(created_at, "%x %X");
      modified_str = g_date_time_format(modified_at, "%x %X");
      g_printf(" %-24s | %-17s | %-17s | %-13s | %s\n",
               id, created_str, modified_str, server_modified_at, name);
      g_free(id);
      g_free(name);
      g_free(server_modified_at);
      g_free(created_str);
      g_free(modified_str);
   }

   g_object_unref(spaces);
   g_main_loop_quit(gMainLoop);
}
Exemple #10
0
void tui_main(tui_t *tui) {
  rfvm_t *vm = tui->vm;
  rfth_t *thread;
  int key, i;
  GDateTime *datetime;
  char *filename;
  rfword_t tmp;

  tui->running = TRUE;

  while (tui->running) {
    if (tui->autostep) {
      for (i=0; i<tui->cycles_per_frame; i++) {
        rf_vm_cycle(vm);
      }
    }

    tui_win_main(tui);

    key = getch();
    switch (key) {
      case 'q':
      case 27:
        tui->running = !tui_really_quit(tui);
        break;
      case KEY_UP:
        tui->mem_view += 0x10;
        break;
      case KEY_DOWN:
        tui->mem_view -= 0x10;
        break;
      case KEY_PPAGE:
        tui->mem_view -= RFMEM_PAGE_SIZE;
        break;
      case KEY_NPAGE:
        tui->mem_view += RFMEM_PAGE_SIZE;
        break;
      case KEY_LEFT:
        tui->mem_p--;
        break;
      case KEY_RIGHT:
        tui->mem_p++;
        break;
      case '+':
        tmp = rf_memory_read(vm, tui->mem_p, &tui->page_cache);
        rf_memory_write(vm, tui->mem_p, tmp+1, &tui->page_cache);
        break;
      case '-':
        tmp = rf_memory_read(vm, tui->mem_p, &tui->page_cache);
        rf_memory_write(vm, tui->mem_p, tmp-1, &tui->page_cache);
        break;
      case ',':
        tui->current_thread--;
        break;
      case '.':
        tui->current_thread++;
        break;
      case KEY_BACKSPACE:
      case '\b':
        tui->mem_view = 0;
        tui->mem_p = 0;
        break;
      case ' ':
        if (!tui->autostep) {
          rf_vm_cycle(vm);
        }
        break;
      case '\n':
        tui->autostep = !tui->autostep;
        break;
      case KEY_F(8):
        datetime = g_date_time_new_now_local();
        filename = g_date_time_format(datetime, "vmstates/%a %b %e %H:%M:%S %Y.RFm");
        if (!rf_vm_store(vm, filename)) {
          beep();
        }
        flash();
        g_date_time_unref(datetime);
        g_free(filename);
        break;
      case KEY_F(5):
        thread = rf_get_thread(vm, tui->current_thread);
        if (thread!=NULL) {
          tui_memview_goto(tui, thread->ip);
        }
        break;
      case KEY_F(6):
        thread = rf_get_thread(vm, tui->current_thread);
        if (thread!=NULL) {
          tui_memview_goto(tui, thread->dp);
        }
        break;
      case KEY_F(7):
        thread = rf_get_thread(vm, tui->current_thread);
        if (thread!=NULL) {
          tui_memview_goto(tui, thread->sp);
        }
        break;
      case KEY_F(3):
        if (tui->cycles_per_frame>1) {
          tui->cycles_per_frame /= 2;
        }
        break;
      case KEY_F(4):
        tui->cycles_per_frame *= 2;
        break;
      case KEY_F(1):
      case 'h':
        tui_show_help(tui);
        break;
      case -1:
        usleep(50000);
        break;
    }
  }
}
Exemple #11
0
static gboolean
dispose_item_in_model (GtkTreeModel *model,
                       const gchar *item_id,
                       GDateTime *date,
                       GtkTreeIter *iter)
{
	gint index;
	gint diff;
	gboolean found;
	gchar *date_str;
	gchar *test_id;
	GDateTime *test_date;
	GtkTreeStore *tstore;
	GtkTreeIter parent;

	found = FALSE;
	index = 0;
	tstore = GTK_TREE_STORE (model);

	if (gtk_tree_model_get_iter_first (model, &parent) == TRUE) {
		do {
			gtk_tree_model_get (model, &parent, ITEM_COLUMN_TIME, &test_date, -1);
			diff = date_time_day_difference (date, test_date);

			if (diff > 0) {
				break;
			}
			else if (diff == 0) {
				found = TRUE;
				break;
			}

			index++;

		} while (gtk_tree_model_iter_next (model, &parent));
	}

	if (found == FALSE) {
		date_str = g_date_time_format (date, "%x");

		gtk_tree_store_insert (tstore, &parent, NULL, index);
		gtk_tree_store_set (tstore, &parent,
		                    ITEM_COLUMN_TITLE, date_str,
		                    ITEM_COLUMN_TIME, date,
		                    ITEM_COLUMN_READ, TITLE_FONT_WEIGHT,
		                    ITEM_COLUMN_BG, "gray", -1);
		gtk_tree_store_prepend (tstore, iter, &parent);

		g_free (date_str);
	}
	else {
		found = FALSE;

		if (gtk_tree_model_iter_children (model, iter, &parent) == TRUE) {
			do {
				gtk_tree_model_get (model, iter, ITEM_COLUMN_ID, &test_id, -1);

				if (strcmp (test_id, item_id) == 0) {
					found = TRUE;
					break;
				}

				g_free (test_id);

			} while (gtk_tree_model_iter_next (model, iter));
		}

		if (found == FALSE)
			gtk_tree_store_prepend (tstore, iter, &parent);
	}

	return !found;
}
Exemple #12
0
static void
_win_print(ProfWin *window, const char show_char, int pad_indent, GDateTime *time,
    int flags, theme_item_t theme_item, const char *const from, const char *const message, DeliveryReceipt *receipt)
{
    // flags : 1st bit =  0/1 - me/not me
    //         2nd bit =  0/1 - date/no date
    //         3rd bit =  0/1 - eol/no eol
    //         4th bit =  0/1 - color from/no color from
    //         5th bit =  0/1 - color date/no date
    gboolean me_message = FALSE;
    int offset = 0;
    int colour = theme_attrs(THEME_ME);
    size_t indent = 0;

    char *time_pref = NULL;
    switch (window->type) {
        case WIN_CHAT:
            time_pref = prefs_get_string(PREF_TIME_CHAT);
            break;
        case WIN_MUC:
            time_pref = prefs_get_string(PREF_TIME_MUC);
            break;
        case WIN_MUC_CONFIG:
            time_pref = prefs_get_string(PREF_TIME_MUCCONFIG);
            break;
        case WIN_PRIVATE:
            time_pref = prefs_get_string(PREF_TIME_PRIVATE);
            break;
        case WIN_XML:
            time_pref = prefs_get_string(PREF_TIME_XMLCONSOLE);
            break;
        default:
            time_pref = prefs_get_string(PREF_TIME_CONSOLE);
            break;
    }

    gchar *date_fmt = NULL;
    if (g_strcmp0(time_pref, "off") == 0) {
        date_fmt = g_strdup("");
    } else {
        date_fmt = g_date_time_format(time, time_pref);
    }
    prefs_free_string(time_pref);
    assert(date_fmt != NULL);

    if(strlen(date_fmt) != 0){
        indent = 3 + strlen(date_fmt);
    }

    if ((flags & NO_DATE) == 0) {
        if (date_fmt && strlen(date_fmt)) {
            if ((flags & NO_COLOUR_DATE) == 0) {
                wbkgdset(window->layout->win, theme_attrs(THEME_TIME));
                wattron(window->layout->win, theme_attrs(THEME_TIME));
            }
            wprintw(window->layout->win, "%s %c ", date_fmt, show_char);
            if ((flags & NO_COLOUR_DATE) == 0) {
                wattroff(window->layout->win, theme_attrs(THEME_TIME));
            }
        }
    }

    if (from && strlen(from) > 0) {
        if (flags & NO_ME) {
            colour = theme_attrs(THEME_THEM);
        }

        if (flags & NO_COLOUR_FROM) {
            colour = 0;
        }

        if (receipt && !receipt->received) {
            colour = theme_attrs(THEME_RECEIPT_SENT);
        }

        wbkgdset(window->layout->win, colour);
        wattron(window->layout->win, colour);
        if (strncmp(message, "/me ", 4) == 0) {
            wprintw(window->layout->win, "*%s ", from);
            offset = 4;
            me_message = TRUE;
        } else {
            wprintw(window->layout->win, "%s: ", from);
            wattroff(window->layout->win, colour);
        }
    }

    if (!me_message) {
        if (receipt && !receipt->received) {
            wbkgdset(window->layout->win, theme_attrs(THEME_RECEIPT_SENT));
            wattron(window->layout->win, theme_attrs(THEME_RECEIPT_SENT));
        } else {
            wbkgdset(window->layout->win, theme_attrs(theme_item));
            wattron(window->layout->win, theme_attrs(theme_item));
        }
    }

    if (prefs_get_boolean(PREF_WRAP)) {
        _win_print_wrapped(window->layout->win, message+offset, indent, pad_indent);
    } else {
        wprintw(window->layout->win, "%s", message+offset);
    }

    if ((flags & NO_EOL) == 0) {
        int curx = getcurx(window->layout->win);
        if (curx != 0) {
            wprintw(window->layout->win, "\n");
        }
    }

    if (me_message) {
        wattroff(window->layout->win, colour);
    } else {
        if (receipt && !receipt->received) {
            wattroff(window->layout->win, theme_attrs(THEME_RECEIPT_SENT));
        } else {
            wattroff(window->layout->win, theme_attrs(theme_item));
        }
    }

    g_free(date_fmt);
}
/**
 * gcal_date_selector_set_date:
 * @selector:
 * @day:  (nullable): The day number.
 * @month: (nullable): The month number starting with 1
 * @year: (nullable): The year number
 *
 * Set the value of the date shown
 **/
void
gcal_date_selector_set_date (GcalDateSelector *selector,
                             gint              day,
                             gint              month,
                             gint              year)
{
  GcalDateSelectorPrivate *priv;
  GDateTime *dt;
  gchar *label;

  g_return_if_fail (GCAL_IS_DATE_SELECTOR (selector));
  priv = gcal_date_selector_get_instance_private (selector);
  day = CLAMP (day, 1, 31);
  month = CLAMP (month, 1, 12);
  /* since we're dealing only with the date, the tz shouldn't be a problem */
  dt = g_date_time_new_local (year, month, day, 0, 0, 0);

  /**
   * When it fails to be instances, it's
   * because edit dialog is cleaning it's
   * data. Thus, we should stop here.
   */
  if (dt == NULL)
    return;

  priv->day = day;
  priv->month = month;
  priv->year = year;

  month =  CLAMP (month - 1, 0, 11);

  /* set calendar's date */
  g_signal_handlers_block_by_func (priv->calendar, calendar_day_selected, selector);
  g_object_set (priv->calendar, "day", day, "month", month, "year", year, NULL);
  g_signal_handlers_unblock_by_func (priv->calendar, calendar_day_selected, selector);

  /* rebuild the date label */
  label = g_date_time_format (dt, priv->mask);

  gtk_label_set_label (GTK_LABEL (priv->date_label), label);
  g_free (label);

  /* set date entries' text */
  /* day entry */
  label = g_strdup_printf ("%.2d", day);

  gtk_entry_set_text (GTK_ENTRY (priv->entries[DAY]), label);
  g_free (label);

  /* month entry */
  label = g_strdup_printf ("%.2d", priv->month);

  gtk_entry_set_text (GTK_ENTRY (priv->entries[MONTH]), label);
  g_free (label);

  /* year entry */
  label = g_strdup_printf ("%.4d", year);

  gtk_entry_set_text (GTK_ENTRY (priv->entries[YEAR]), label);

  /* emit the MODIFIED signal */
  g_signal_emit (selector, signals[MODIFIED], 0);

  g_free (label);
  g_date_time_unref (dt);
}
Exemple #14
0
static void
call_raw_async_cb (GObject *     source_object,
                   GAsyncResult *res,
                   gpointer      data)
{
  BliptvOperation    *op = (BliptvOperation *) data;
  xmlDocPtr           doc = NULL;
  xmlXPathContextPtr  xpath = NULL;
  xmlXPathObjectPtr   obj = NULL;
  gint i, nb_items = 0;
  gchar *content = NULL;
  gchar *url;
  gsize length;

  GRL_DEBUG ("Response id=%u", op->operation_id);

  if (g_cancellable_is_cancelled (op->cancellable)) {
    goto finalize_send_last;
  }

  if (!grl_net_wc_request_finish (GRL_NET_WC (source_object),
                                  res,
                                  &content,
                                  &length,
                                  NULL)) {
    goto finalize_send_last;
  }

  doc = xmlParseMemory (content, (gint) length);

  if (!doc)
    goto finalize_send_last;

  xpath = xmlXPathNewContext (doc);
  if (!xpath)
    goto finalize_send_last;

  xmlXPathRegisterNs (xpath,
                      (xmlChar *) "blip",
                      (xmlChar *) BLIPTV_BACKEND "/dtd/blip/1.0");
  xmlXPathRegisterNs (xpath,
                      (xmlChar *) "media",
                      (xmlChar *) "http://search.yahoo.com/mrss/");

  obj = xmlXPathEvalExpression ((xmlChar *) "/rss/channel/item", xpath);
  if (obj)
    {
      nb_items = xmlXPathNodeSetGetLength (obj->nodesetval);
      xmlXPathFreeObject (obj);
    }

  if (nb_items == 0) {
    goto finalize_send_last;
  }

  /* Special case: when there are no results in a search, Blip.tv returns an
     element telling precisely that, no results found; so we need to report no
     results too */
  if (nb_items == 1) {
    obj = xmlXPathEvalExpression ((xmlChar *) "string(/rss/channel/item[0]/blip:item_id)", xpath);
    if (!obj || !obj->stringval || obj->stringval[0] == '\0') {
      g_clear_pointer (&obj, (GDestroyNotify) xmlXPathFreeObject);
      nb_items = 0;
      goto finalize_send_last;
    } else {
      xmlXPathFreeObject (obj);
    }
  }

  for (i = op->skip; i < nb_items; i++)
    {
      GList *mapping = bliptv_mappings;
      GrlMedia *media = grl_media_video_new ();

      while (mapping)
        {
          BliptvAssoc *assoc = (BliptvAssoc *) mapping->data;
          gchar *str;

          str = g_strdup_printf ("string(/rss/channel/item[%i]/%s)",
                                 i + 1, assoc->exp);

          obj = xmlXPathEvalExpression ((xmlChar *) str, xpath);
          if (obj)
            {
              if (obj->stringval && obj->stringval[0] != '\0')
                {
                  GType _type;
                  GRL_DEBUG ("\t%s -> %s", str, obj->stringval);
                  _type = grl_metadata_key_get_type (assoc->grl_key);
                  switch (_type)
                    {
                    case G_TYPE_STRING:
                      grl_data_set_string (GRL_DATA (media),
                                           assoc->grl_key,
                                           (gchar *) obj->stringval);
                      break;

                    case G_TYPE_INT:
                      grl_data_set_int (GRL_DATA (media),
                                        assoc->grl_key,
                                        (gint) atoi ((gchar *) obj->stringval));
                      break;

                    case G_TYPE_FLOAT:
                      grl_data_set_float (GRL_DATA (media),
                                          assoc->grl_key,
                                          (gfloat) atof ((gchar *) obj->stringval));
                      break;

                    default:
                      /* G_TYPE_DATE_TIME is not a constant, so this has to be
                       * in "default:" */
                      if (_type == G_TYPE_DATE_TIME) {
                        GDateTime *date =
                            grl_date_time_from_iso8601 ((gchar *) obj->stringval);
                        GRL_DEBUG ("Setting %s to %s",
                                   grl_metadata_key_get_name (assoc->grl_key),
                                   g_date_time_format (date, "%F %H:%M:%S"));
                        grl_data_set_boxed (GRL_DATA (media),
                                            assoc->grl_key, date);
                        g_date_time_unref (date);
                      } else {
                        GRL_DEBUG ("\tUnexpected data type: %s",
                                   g_type_name (_type));
                      }
                      break;
                    }
                }
              xmlXPathFreeObject (obj);
            }

          g_free (str);

          mapping = mapping->next;
        }

      op->callback (op->source,
                    op->operation_id,
                    media,
                    --op->count,
                    op->user_data,
                    NULL);

      if (op->count == 0)
        break;
    }

  if (op->count > 0) {
    /* Request next page */
    op->skip = 0;
    url = g_strdup_printf (op->url, ++op->page);

    GRL_DEBUG ("Operation %d: requesting page %d",
               op->operation_id,
               op->page);

    grl_net_wc_request_async (GRL_BLIPTV_SOURCE (op->source)->priv->wc,
                              url,
                              op->cancellable,
                              call_raw_async_cb,
                              op);
    g_free (url);

    goto finalize_free;
  }

 finalize_send_last:
  /* Signal the last element if it was not already signaled */
  if (nb_items == 0) {
    op->callback (op->source,
                  op->operation_id,
                  NULL,
                  0,
                  op->user_data,
                  NULL);
  }

 finalize_free:
  g_clear_pointer (&xpath, (GDestroyNotify) xmlXPathFreeContext);
  g_clear_pointer (&doc, (GDestroyNotify) xmlFreeDoc);
}
Exemple #15
0
void
ui_incoming_msg(const char * const from, const char * const message,
    GTimeVal *tv_stamp, gboolean priv)
{
    gboolean win_created = FALSE;
    char *display_from = NULL;
    win_type_t win_type;

    if (priv) {
        win_type = WIN_PRIVATE;
        display_from = get_nick_from_full_jid(from);
    } else {
        win_type = WIN_CHAT;
        PContact contact = roster_get_contact(from);
        if (contact != NULL) {
            if (p_contact_name(contact) != NULL) {
                display_from = strdup(p_contact_name(contact));
            } else {
                display_from = strdup(from);
            }
        } else {
            display_from = strdup(from);
        }
    }

    ProfWin *window = wins_get_by_recipient(from);
    if (window == NULL) {
        window = wins_new(from, win_type);
        win_created = TRUE;
    }

    int num = wins_get_num(window);

    // currently viewing chat window with sender
    if (wins_is_current(window)) {
        if (tv_stamp == NULL) {
            win_print_time(window, '-');
        } else {
            GDateTime *time = g_date_time_new_from_timeval_utc(tv_stamp);
            gchar *date_fmt = g_date_time_format(time, "%H:%M:%S");
            wattron(window->win, COLOUR_TIME);
            wprintw(window->win, "%s - ", date_fmt);
            wattroff(window->win, COLOUR_TIME);
            g_date_time_unref(time);
            g_free(date_fmt);
        }

        if (strncmp(message, "/me ", 4) == 0) {
            wattron(window->win, COLOUR_THEM);
            wprintw(window->win, "*%s ", display_from);
            waddstr(window->win, message + 4);
            wprintw(window->win, "\n");
            wattroff(window->win, COLOUR_THEM);
        } else {
            _win_show_user(window->win, display_from, 1);
            _win_show_message(window->win, message);
        }
        title_bar_set_typing(FALSE);
        title_bar_draw();
        status_bar_active(num);
        wins_refresh_current();

    // not currently viewing chat window with sender
    } else {
        status_bar_new(num);
        cons_show_incoming_message(display_from, num);
        if (prefs_get_boolean(PREF_FLASH))
            flash();

        window->unread++;
        if (prefs_get_boolean(PREF_CHLOG) && prefs_get_boolean(PREF_HISTORY)) {
            _win_show_history(window->win, num, from);
        }

        if (tv_stamp == NULL) {
            win_print_time(window, '-');
        } else {
            // show users status first, when receiving message via delayed delivery
            if (win_created) {
                PContact pcontact = roster_get_contact(from);
                if (pcontact != NULL) {
                    win_show_contact(window, pcontact);
                }
            }
            GDateTime *time = g_date_time_new_from_timeval_utc(tv_stamp);
            gchar *date_fmt = g_date_time_format(time, "%H:%M:%S");
            wattron(window->win, COLOUR_TIME);
            wprintw(window->win, "%s - ", date_fmt);
            wattroff(window->win, COLOUR_TIME);
            g_date_time_unref(time);
            g_free(date_fmt);
        }

        if (strncmp(message, "/me ", 4) == 0) {
            wattron(window->win, COLOUR_THEM);
            wprintw(window->win, "*%s ", display_from);
            waddstr(window->win, message + 4);
            wprintw(window->win, "\n");
            wattroff(window->win, COLOUR_THEM);
        } else {
            _win_show_user(window->win, display_from, 1);
            _win_show_message(window->win, message);
        }
    }

    int ui_index = num;
    if (ui_index == 10) {
        ui_index = 0;
    }

    if (prefs_get_boolean(PREF_BEEP))
        beep();
    if (prefs_get_boolean(PREF_NOTIFY_MESSAGE))
        notify_message(display_from, ui_index);

    free(display_from);
}
static gboolean
gst_test_http_src_start (GstBaseSrc * basesrc)
{
  GstTestHTTPSrc *src;
  GstStructure *http_headers;

  src = GST_TEST_HTTP_SRC (basesrc);
  g_mutex_lock (&src->mutex);
  gst_test_http_src_reset_input (src);
  if (!src->uri) {
    GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (("No URL set.")),
        ("Missing location property"));
    g_mutex_unlock (&src->mutex);
    return FALSE;
  }
  if (!gst_test_http_src_callbacks) {
    GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
        (("Callbacks not registered.")), ("Callbacks not registered"));
    g_mutex_unlock (&src->mutex);
    return FALSE;
  }
  if (!gst_test_http_src_callbacks->src_start) {
    GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
        (("src_start callback not defined.")),
        ("src_start callback not registered"));
    g_mutex_unlock (&src->mutex);
    return FALSE;
  }
  if (!gst_test_http_src_callbacks->src_start (src, src->uri, &src->input,
          gst_test_http_src_callback_user_data)) {
    if (src->input.status_code == 0) {
      src->input.status_code = 404;
    }
  } else {
    if (src->input.status_code == 0) {
      src->input.status_code = 200;
    }
    src->position = 0;
    src->segment_end = src->input.size;
    gst_base_src_set_dynamic_size (basesrc, FALSE);
    basesrc->segment.duration = src->input.size;
    src->duration_changed = TRUE;
  }
  http_headers = gst_structure_new_empty ("http-headers");
  gst_structure_set (http_headers, "uri", G_TYPE_STRING, src->uri, NULL);
  if (!src->input.request_headers) {
    src->input.request_headers = gst_structure_new_empty ("request-headers");
  }
  if (!gst_structure_has_field_typed (src->input.request_headers,
          "User-Agent", G_TYPE_STRING)) {
    gst_structure_set (src->input.request_headers,
        "User-Agent", G_TYPE_STRING,
        src->user_agent ? src->user_agent : DEFAULT_USER_AGENT, NULL);
  }
  if (!gst_structure_has_field_typed (src->input.request_headers,
          "Connection", G_TYPE_STRING)) {
    gst_structure_set (src->input.request_headers,
        "Connection", G_TYPE_STRING,
        src->keep_alive ? "Keep-Alive" : "Close", NULL);
  }
  if (src->compress
      && !gst_structure_has_field_typed (src->input.request_headers,
          "Accept-Encoding", G_TYPE_STRING)) {
    gst_structure_set (src->input.request_headers, "Accept-Encoding",
        G_TYPE_STRING, "compress, gzip", NULL);
  }
  gst_structure_set (http_headers, "request-headers", GST_TYPE_STRUCTURE,
      src->input.request_headers, NULL);
  if (!src->input.response_headers) {
    src->input.response_headers = gst_structure_new_empty ("response-headers");
  }
  if (!gst_structure_has_field_typed (src->input.response_headers,
          "Connection", G_TYPE_STRING)) {
    gst_structure_set (src->input.response_headers,
        "Connection", G_TYPE_STRING,
        src->keep_alive ? "keep-alive" : "close", NULL);
  }
  if (!gst_structure_has_field_typed (src->input.response_headers,
          "Date", G_TYPE_STRING)) {
    GDateTime *now;
    gchar *date_str;

    now = g_date_time_new_now_local ();
    fail_unless (now != NULL);
    date_str = g_date_time_format (now, "%a, %e %b %Y %T %Z");
    fail_unless (date_str != NULL);
    gst_structure_set (src->input.response_headers,
        "Date", G_TYPE_STRING, date_str, NULL);
    g_free (date_str);
    g_date_time_unref (now);
  }
  gst_structure_set (http_headers, "response-headers", GST_TYPE_STRUCTURE,
      src->input.response_headers, NULL);
  if (src->http_headers_event) {
    gst_event_unref (src->http_headers_event);
  }
  src->http_headers_event =
      gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_STICKY, http_headers);
  g_mutex_unlock (&src->mutex);
  return TRUE;
}
static void
update_jobs_list_cb (cups_job_t *jobs,
                     gint        num_of_jobs,
                     gpointer    user_data)
{
  GtkTreeSelection *selection;
  PpJobsDialog     *dialog = (PpJobsDialog *) user_data;
  GtkListStore     *store;
  GtkTreeView      *treeview;
  GtkTreeIter       select_iter;
  GtkTreeIter       iter;
  GSettings        *settings;
  gboolean          select_iter_set = FALSE;
  gint              i;
  gint              select_index = 0;

  treeview = (GtkTreeView*)
    gtk_builder_get_object (dialog->builder, "job-treeview");

  if (dialog->num_jobs > 0)
    cupsFreeJobs (dialog->num_jobs, dialog->jobs);

  dialog->num_jobs = num_of_jobs;
  dialog->jobs = jobs;

  store = gtk_list_store_new (JOB_N_COLUMNS,
                              G_TYPE_INT,
                              G_TYPE_STRING,
                              G_TYPE_STRING,
                              G_TYPE_STRING);

  if (dialog->current_job_id >= 0)
    {
      for (i = 0; i < dialog->num_jobs; i++)
        {
          select_index = i;
          if (dialog->jobs[i].id >= dialog->current_job_id)
            break;
        }
    }

  for (i = 0; i < dialog->num_jobs; i++)
    {
      GDesktopClockFormat  value;
      GDateTime           *time;
      struct tm *ts;
      gchar     *time_string;
      gchar     *state = NULL;

      ts = localtime (&(dialog->jobs[i].creation_time));
      time = g_date_time_new_local (ts->tm_year,
                                    ts->tm_mon,
                                    ts->tm_mday,
                                    ts->tm_hour,
                                    ts->tm_min,
                                    ts->tm_sec);

      settings = g_settings_new (CLOCK_SCHEMA);
      value = g_settings_get_enum (settings, CLOCK_FORMAT_KEY);

      if (value == G_DESKTOP_CLOCK_FORMAT_24H)
        time_string = g_date_time_format (time, "%k:%M");
      else
        time_string = g_date_time_format (time, "%l:%M %p");

      g_date_time_unref (time);

      switch (dialog->jobs[i].state)
        {
          case IPP_JOB_PENDING:
            /* Translators: Job's state (job is waiting to be printed) */
            state = g_strdup (C_("print job", "Pending"));
            break;
          case IPP_JOB_HELD:
            /* Translators: Job's state (job is held for printing) */
            state = g_strdup (C_("print job", "Held"));
            break;
          case IPP_JOB_PROCESSING:
            /* Translators: Job's state (job is currently printing) */
            state = g_strdup (C_("print job", "Processing"));
            break;
          case IPP_JOB_STOPPED:
            /* Translators: Job's state (job has been stopped) */
            state = g_strdup (C_("print job", "Stopped"));
            break;
          case IPP_JOB_CANCELED:
            /* Translators: Job's state (job has been canceled) */
            state = g_strdup (C_("print job", "Canceled"));
            break;
          case IPP_JOB_ABORTED:
            /* Translators: Job's state (job has aborted due to error) */
            state = g_strdup (C_("print job", "Aborted"));
            break;
          case IPP_JOB_COMPLETED:
            /* Translators: Job's state (job has completed successfully) */
            state = g_strdup (C_("print job", "Completed"));
            break;
        }

      gtk_list_store_append (store, &iter);
      gtk_list_store_set (store, &iter,
                          JOB_ID_COLUMN, dialog->jobs[i].id,
                          JOB_TITLE_COLUMN, dialog->jobs[i].title,
                          JOB_STATE_COLUMN, state,
                          JOB_CREATION_TIME_COLUMN, time_string,
                          -1);

      if (i == select_index)
        {
          select_iter = iter;
          select_iter_set = TRUE;
          dialog->current_job_id = dialog->jobs[i].id;
        }

      g_free (time_string);
      g_free (state);
    }

  gtk_tree_view_set_model (treeview, GTK_TREE_MODEL (store));

  if (select_iter_set &&
      (selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview))))
    {
      gtk_tree_selection_select_iter (selection, &select_iter);
    }

  g_object_unref (store);
  dialog->ref_count--;
}
static void
continuous_cb (RestProxyCall *call,
               const gchar   *buf,
               gsize          len,
               const GError  *error,
               GObject       *weak_object,
               gpointer       user_data)
{
  CbUserStream *self = user_data;

  if (buf == NULL)
    {
      /* buff == NULL && error != NULL is what happens when the message gets cancelled.
       * This might happen a few seconds after the CbUserStream instance is finalized, so
       * make sure we don't use it here. */
      if (error != NULL)
        return;

      if (self->state != STATE_STOPPING)
        {
          g_debug ("%u, buf(%s) == NULL. Starting timeout...", self->state, self->account_name);
          start_network_timeout (self);
        }
      return;
    }

  g_string_append_len (self->data, buf, len);

  /* Actual messages end with \r\n */
  if ((len >= 2 && buf[len - 1] == '\n' && buf[len - 2] == '\r') ||
      (len >= 1 && buf[len - 1] == '\r'))
    {
      if (self->restarting)
        {
          g_debug (G_STRLOC ": Resuming...");
          g_signal_emit (self, user_stream_signals[RESUMED], 0);
          self->restarting = FALSE;
        }

      self->state = STATE_RUNNING;

      /* Just \r\n messages are heartbeats. */
      if (len == 2 &&
          buf[0] == '\r' && buf[1] == '\n')
        {
#if DEBUG
          char *date;
          GDateTime *now = g_date_time_new_now_local ();

          date = g_date_time_format (now, "%k:%M:%S");

          g_debug ("%u HEARTBEAT (%s) %s", self->state, self->account_name, date);
          g_free (date);
          g_date_time_unref (now);
#endif
          g_string_erase (self->data, 0, -1);
          cb_clear_source (&self->heartbeat_timeout_id);

          start_heartbeat_timeout (self);
          return;
        }

      /* TODO: Bring "OK" check back? */
      {
        JsonParser *parser;
        JsonNode *root_node;
        JsonObject *root_object;
        CbStreamMessageType message_type;
        GError *error = NULL;
        guint i;

        parser = json_parser_new ();
        json_parser_load_from_data (parser, self->data->str, -1, &error);

        if (error != NULL)
          {
            if (g_str_has_prefix (error->message, "Exceeded connection limit for user"))
              {
                /* Ignore this one, let the next reconnect handle it */
                g_string_erase (self->data, 0, -1);
                return;
              }

            g_warning ("%s: %s", __FUNCTION__, error->message);
            g_warning ("\n%s\n", self->data->str);
            g_string_erase (self->data, 0, -1);
            return;
          }


        root_node = json_parser_get_root (parser);
        root_object = json_node_get_object (root_node);

        message_type = CB_STREAM_MESSAGE_UNSUPPORTED;

        if (json_object_has_member (root_object, "text"))
          {
            message_type = CB_STREAM_MESSAGE_TWEET;
          }
        else if (json_object_has_member (root_object, "delete"))
          {
            JsonObject *d = json_object_get_object_member (root_object, "delete");

            if (json_object_has_member (d, "direct_message"))
              message_type = CB_STREAM_MESSAGE_DM_DELETE;
            else
              message_type = CB_STREAM_MESSAGE_DELETE;
          }
        else if (json_object_has_member (root_object, "scrub_geo"))
          {
            message_type = CB_STREAM_MESSAGE_SCRUB_GEO;
          }
        else if (json_object_has_member (root_object, "limit"))
          {
            message_type = CB_STREAM_MESSAGE_LIMIT;
          }
        else if (json_object_has_member (root_object, "disconnect"))
          {
            message_type = CB_STREAM_MESSAGE_DISCONNECT;
          }
        else if (json_object_has_member (root_object, "friends"))
          {
            message_type = CB_STREAM_MESSAGE_FRIENDS;
          }
        else if (json_object_has_member (root_object, "event"))
          {
            const char *event_name = json_object_get_string_member (root_object, "event");

            message_type = get_event_type (event_name);
          }
        else if (json_object_has_member (root_object, "warning"))
          {
            message_type = CB_STREAM_MESSAGE_WARNING;
          }
        else if (json_object_has_member (root_object, "direct_message"))
          {
            message_type = CB_STREAM_MESSAGE_DIRECT_MESSAGE;
          }
        else if (json_object_has_member (root_object, "status_withheld"))
          {
            message_type = CB_STREAM_MESSAGE_UNSUPPORTED;
          }

#if DEBUG
        g_print ("Message with type %d on stream @%s\n", message_type, self->account_name);
        g_print ("%s\n\n", self->data->str);
#endif

        for (i = 0; i < self->receivers->len; i++)
          cb_message_receiver_stream_message_received (g_ptr_array_index (self->receivers, i),
                                                       message_type,
                                                       root_node);

        g_object_unref (parser);
        g_string_erase (self->data, 0, -1);
      } /* Local block */
    }
}
static void
photos_properties_dialog_constructed (GObject *object)
{
  PhotosPropertiesDialog *self = PHOTOS_PROPERTIES_DIALOG (object);
  PhotosPropertiesDialogPrivate *priv = self->priv;
  GDateTime *date_modified;
  GtkStyleContext *context;
  GtkWidget *author_w = NULL;
  GtkWidget *content_area;
  GtkWidget *date_created_w = NULL;
  GtkWidget *date_modified_data;
  GtkWidget *date_modified_w;
  GtkWidget *exposure_time_w = NULL;
  GtkWidget *flash_w = NULL;
  GtkWidget *fnumber_w = NULL;
  GtkWidget *focal_length_w = NULL;
  GtkWidget *height_w = NULL;
  GtkWidget *iso_speed_w = NULL;
  GtkWidget *item_type;
  GtkWidget *item_type_data;
  GtkWidget *source;
  GtkWidget *source_data;
  GtkWidget *title;
  GtkWidget *width_w = NULL;
  GQuark equipment;
  GQuark flash;
  PhotosBaseItem *item;
  const gchar *author;
  const gchar *name;
  const gchar *type_description;
  gchar *date_created_str = NULL;
  gchar *date_modified_str;
  gdouble exposure_time;
  gdouble fnumber;
  gdouble focal_length;
  gdouble iso_speed;
  gint64 ctime;
  gint64 height;
  gint64 mtime;
  gint64 width;

  G_OBJECT_CLASS (photos_properties_dialog_parent_class)->constructed (object);

  item = PHOTOS_BASE_ITEM (photos_base_manager_get_object_by_id (priv->item_mngr, priv->urn));

  mtime = photos_base_item_get_mtime (item);
  date_modified = g_date_time_new_from_unix_local (mtime);
  date_modified_str = g_date_time_format (date_modified, "%c");
  g_date_time_unref (date_modified);

  ctime = photos_base_item_get_date_created (item);
  if (ctime != -1)
    {
      GDateTime *date_created;

      date_created = g_date_time_new_from_unix_local (ctime);
      date_created_str = g_date_time_format (date_created, "%c");
      g_date_time_unref (date_created);
    }

  priv->grid = gtk_grid_new ();
  gtk_widget_set_halign (priv->grid, GTK_ALIGN_CENTER);
  gtk_widget_set_margin_start (priv->grid, 24);
  gtk_widget_set_margin_end (priv->grid, 24);
  gtk_widget_set_margin_bottom (priv->grid, 12);
  gtk_widget_set_margin_top (priv->grid, 12);
  gtk_orientable_set_orientation (GTK_ORIENTABLE (priv->grid), GTK_ORIENTATION_VERTICAL);
  gtk_grid_set_column_homogeneous (GTK_GRID (priv->grid), TRUE);
  gtk_grid_set_column_spacing (GTK_GRID (priv->grid), 24);
  gtk_grid_set_row_homogeneous (GTK_GRID (priv->grid), TRUE);
  gtk_grid_set_row_spacing (GTK_GRID (priv->grid), 6);

  content_area = gtk_dialog_get_content_area (GTK_DIALOG (self));
  gtk_box_pack_start (GTK_BOX (content_area), priv->grid, TRUE, TRUE, 2);

  /* Translators: this is the label next to the photo title in the
   * properties dialog
   */
  title = gtk_label_new (C_("Document Title", "Title"));
  gtk_widget_set_halign (title, GTK_ALIGN_END);
  context = gtk_widget_get_style_context (title);
  gtk_style_context_add_class (context, "dim-label");
  gtk_container_add (GTK_CONTAINER (priv->grid), title);

  author = photos_base_item_get_author (item);
  if (author != NULL && author[0] != '\0')
    {
      /* Translators: this is the label next to the photo author in
       * the properties dialog
       */
      author_w = gtk_label_new (C_("Document Author", "Author"));
      gtk_widget_set_halign (author_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (author_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (priv->grid), author_w);
    }

  source = gtk_label_new (_("Source"));
  gtk_widget_set_halign (source, GTK_ALIGN_END);
  context = gtk_widget_get_style_context (source);
  gtk_style_context_add_class (context, "dim-label");
  gtk_container_add (GTK_CONTAINER (priv->grid), source);

  date_modified_w = gtk_label_new (_("Date Modified"));
  gtk_widget_set_halign (date_modified_w, GTK_ALIGN_END);
  context = gtk_widget_get_style_context (date_modified_w);
  gtk_style_context_add_class (context, "dim-label");
  gtk_container_add (GTK_CONTAINER (priv->grid), date_modified_w);

  if (date_created_str != NULL)
    {
      date_created_w = gtk_label_new (_("Date Created"));
      gtk_widget_set_halign (date_created_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (date_created_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (priv->grid), date_created_w);
    }

  /* Translators: this is the label next to the photo type in the
   * properties dialog
   */
  item_type = gtk_label_new (C_("Document Type", "Type"));
  gtk_widget_set_halign (item_type, GTK_ALIGN_END);
  context = gtk_widget_get_style_context (item_type);
  gtk_style_context_add_class (context, "dim-label");
  gtk_container_add (GTK_CONTAINER (priv->grid), item_type);

  width = photos_base_item_get_width (item);
  if (width > 0)
    {
      width_w = gtk_label_new (_("Width"));
      gtk_widget_set_halign (width_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (width_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (priv->grid), width_w);
    }

  height = photos_base_item_get_height (item);
  if (height > 0)
    {
      height_w = gtk_label_new (_("Height"));
      gtk_widget_set_halign (height_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (height_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (priv->grid), height_w);
    }

  equipment = photos_base_item_get_equipment (item);
  photos_camera_cache_get_camera_async (priv->camera_cache,
                                        equipment,
                                        priv->cancellable,
                                        photos_properties_dialog_get_camera,
                                        self);
  if (equipment != 0)
    {
      priv->camera_w = gtk_label_new (_("Camera"));
      gtk_widget_set_halign (priv->camera_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (priv->camera_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (priv->grid), priv->camera_w);
    }

  exposure_time = photos_base_item_get_exposure_time (item);
  if (exposure_time > 0.0)
    {
      exposure_time_w = gtk_label_new (_("Exposure"));
      gtk_widget_set_halign (exposure_time_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (exposure_time_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (priv->grid), exposure_time_w);
    }

  fnumber = photos_base_item_get_fnumber (item);
  if (fnumber > 0.0)
    {
      fnumber_w = gtk_label_new (_("Aperture"));
      gtk_widget_set_halign (fnumber_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (fnumber_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (priv->grid), fnumber_w);
    }

  focal_length = photos_base_item_get_focal_length (item);
  if (focal_length > 0.0)
    {
      focal_length_w = gtk_label_new (_("Focal Length"));
      gtk_widget_set_halign (focal_length_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (focal_length_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (priv->grid), focal_length_w);
    }

  iso_speed = photos_base_item_get_iso_speed (item);
  if (iso_speed > 0.0)
    {
      iso_speed_w = gtk_label_new (_("ISO Speed"));
      gtk_widget_set_halign (iso_speed_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (iso_speed_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (priv->grid), iso_speed_w);
    }

  flash = photos_base_item_get_flash (item);
  if (flash != 0)
    {
      flash_w = gtk_label_new (_("Flash"));
      gtk_widget_set_halign (flash_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (flash_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (priv->grid), flash_w);
    }

  name = photos_base_item_get_name (item);

  if (PHOTOS_IS_LOCAL_ITEM (item))
    {
      priv->title_entry = gtk_entry_new ();
      gtk_widget_set_halign (priv->title_entry, GTK_ALIGN_START);
      gtk_widget_set_hexpand (priv->title_entry, TRUE);
      gtk_entry_set_activates_default (GTK_ENTRY (priv->title_entry), TRUE);
      gtk_entry_set_text (GTK_ENTRY (priv->title_entry), name);
      gtk_entry_set_width_chars (GTK_ENTRY (priv->title_entry), 40);
      gtk_editable_set_editable (GTK_EDITABLE (priv->title_entry), TRUE);

      g_signal_connect (priv->title_entry,
                        "changed",
                        G_CALLBACK (photos_properties_dialog_title_entry_changed),
                        self);
    }
  else
    {
      priv->title_entry = gtk_label_new (name);
      gtk_widget_set_halign (priv->title_entry, GTK_ALIGN_START);
    }

  gtk_grid_attach_next_to (GTK_GRID (priv->grid), priv->title_entry, title, GTK_POS_RIGHT, 2, 1);

  if (author_w != NULL)
    {
      GtkWidget *author_data;

      author_data = gtk_label_new (author);
      gtk_widget_set_halign (author_data, GTK_ALIGN_START);
      gtk_grid_attach_next_to (GTK_GRID (priv->grid), author_data, author_w, GTK_POS_RIGHT, 2, 1);
    }

  if (PHOTOS_IS_FACEBOOK_ITEM (item))
    {
      const gchar *source_name;

      source_name = photos_base_item_get_source_name (item);
      source_data = gtk_link_button_new_with_label ("https://www.facebook.com/", source_name);
      gtk_widget_set_halign (source_data, GTK_ALIGN_START);
    }
  else if (PHOTOS_IS_FLICKR_ITEM (item))
    {
      const gchar *source_name;

      source_name = photos_base_item_get_source_name (item);
      source_data = gtk_link_button_new_with_label ("https://www.flickr.com/", source_name);
      gtk_widget_set_halign (source_data, GTK_ALIGN_START);
    }
  else /* local item */
    {
      if (photos_base_item_is_collection (item))
        {
          const gchar *source_name;

          source_name = photos_base_item_get_source_name (item);
          source_data = gtk_label_new (source_name);
          gtk_widget_set_halign (source_data, GTK_ALIGN_START);
        }
      else
        {
          GFile *file;
          GFile *source_link;
          GtkWidget *label;
          const gchar *uri;
          gchar *source_path;
          gchar *source_uri;

          uri = photos_base_item_get_uri (item);
          file = g_file_new_for_uri (uri);
          source_link = g_file_get_parent (file);
          source_path = g_file_get_path (source_link);
          source_uri = g_file_get_uri (source_link);

          source_data = gtk_link_button_new_with_label (source_uri, source_path);
          gtk_widget_set_halign (source_data, GTK_ALIGN_START);

          label = gtk_bin_get_child (GTK_BIN (source_data));
          gtk_label_set_ellipsize (GTK_LABEL (label), PANGO_ELLIPSIZE_END);

          g_object_unref (source_link);
          g_object_unref (file);
        }
    }

  gtk_grid_attach_next_to (GTK_GRID (priv->grid), source_data, source, GTK_POS_RIGHT, 2, 1);

  date_modified_data = gtk_label_new (date_modified_str);
  gtk_widget_set_halign (date_modified_data, GTK_ALIGN_START);
  gtk_grid_attach_next_to (GTK_GRID (priv->grid), date_modified_data, date_modified_w, GTK_POS_RIGHT, 2, 1);

  if (date_created_w != NULL)
    {
      GtkWidget *date_created_data;

      date_created_data = gtk_label_new (date_created_str);
      gtk_widget_set_halign (date_created_data, GTK_ALIGN_START);
      gtk_grid_attach_next_to (GTK_GRID (priv->grid), date_created_data, date_created_w, GTK_POS_RIGHT, 2, 1);
    }

  type_description = photos_base_item_get_type_description (item);
  item_type_data = gtk_label_new (type_description);
  gtk_widget_set_halign (item_type_data, GTK_ALIGN_START);
  gtk_grid_attach_next_to (GTK_GRID (priv->grid), item_type_data, item_type, GTK_POS_RIGHT, 2, 1);

  if (width_w != NULL)
    {
      GtkWidget *width_data;
      gchar *width_str;

      width_str = g_strdup_printf ("%"G_GINT64_FORMAT" pixels", width);
      width_data = gtk_label_new (width_str);
      gtk_widget_set_halign (width_data, GTK_ALIGN_START);
      gtk_grid_attach_next_to (GTK_GRID (priv->grid), width_data, width_w, GTK_POS_RIGHT, 2, 1);
      g_free (width_str);
    }

  if (height_w != NULL)
    {
      GtkWidget *height_data;
      gchar *height_str;

      height_str = g_strdup_printf ("%"G_GINT64_FORMAT" pixels", height);
      height_data = gtk_label_new (height_str);
      gtk_widget_set_halign (height_data, GTK_ALIGN_START);
      gtk_grid_attach_next_to (GTK_GRID (priv->grid), height_data, height_w, GTK_POS_RIGHT, 2, 1);
      g_free (height_str);
    }

  if (exposure_time_w != NULL)
    {
      GtkWidget *exposure_time_data;
      gchar *exposure_time_str;

      exposure_time_str = g_strdup_printf ("%.3lf sec", exposure_time);
      exposure_time_data = gtk_label_new (exposure_time_str);
      gtk_widget_set_halign (exposure_time_data, GTK_ALIGN_START);
      gtk_grid_attach_next_to (GTK_GRID (priv->grid), exposure_time_data, exposure_time_w, GTK_POS_RIGHT, 2, 1);
      g_free (exposure_time_str);
    }

  if (fnumber_w != NULL)
    {
      GtkWidget *fnumber_data;
      gchar *fnumber_str;

      fnumber_str = g_strdup_printf ("f/%.1lf", fnumber);
      fnumber_data = gtk_label_new (fnumber_str);
      gtk_widget_set_halign (fnumber_data, GTK_ALIGN_START);
      gtk_grid_attach_next_to (GTK_GRID (priv->grid), fnumber_data, fnumber_w, GTK_POS_RIGHT, 2, 1);
      g_free (fnumber_str);
    }

  if (focal_length_w != NULL)
    {
      GtkWidget *focal_length_data;
      gchar *focal_length_str;

      focal_length_str = g_strdup_printf ("%.0lf mm", focal_length);
      focal_length_data = gtk_label_new (focal_length_str);
      gtk_widget_set_halign (focal_length_data, GTK_ALIGN_START);
      gtk_grid_attach_next_to (GTK_GRID (priv->grid), focal_length_data, focal_length_w, GTK_POS_RIGHT, 2, 1);
      g_free (focal_length_str);
    }

  if (iso_speed_w != NULL)
    {
      GtkWidget *iso_speed_data;
      gchar *iso_speed_str;

      iso_speed_str = g_strdup_printf ("%.0lf", iso_speed);
      iso_speed_data = gtk_label_new (iso_speed_str);
      gtk_widget_set_halign (iso_speed_data, GTK_ALIGN_START);
      gtk_grid_attach_next_to (GTK_GRID (priv->grid), iso_speed_data, iso_speed_w, GTK_POS_RIGHT, 2, 1);
      g_free (iso_speed_str);
    }

  if (flash_w != NULL)
    {
      GtkWidget *flash_data;
      gchar *flash_str;

      if (flash == PHOTOS_FLASH_OFF)
        flash_str = g_strdup (_("Off, did not fire"));
      else if (flash == PHOTOS_FLASH_ON)
        flash_str = g_strdup (_("On, fired"));
      else
        g_assert_not_reached ();

      flash_data = gtk_label_new (flash_str);
      gtk_widget_set_halign (flash_data, GTK_ALIGN_START);
      gtk_grid_attach_next_to (GTK_GRID (priv->grid), flash_data, flash_w, GTK_POS_RIGHT, 2, 1);
      g_free (flash_str);
    }

  g_free (date_created_str);
  g_free (date_modified_str);
}
Exemple #20
0
int main(int ac, char* av[])
{
  mega_session* s;
  gc_error_free GError *local_err = NULL;
  GSList *l = NULL, *i;
  gint j;

  tool_init(&ac, &av, "- list files stored at mega.nz", entries);

  s = tool_start_session();
  if (!s)
    return 1;

  // gather nodes
  if (ac == 1)
  {
    l = mega_session_ls_all(s);
    opt_names = FALSE;
  }
  else
  {
    if (ac > 2 || opt_recursive)
      opt_names = FALSE;

    for (j = 1; j < ac; j++)
    {
      gc_free gchar* path = tool_convert_filename(av[j], FALSE);

      mega_node* n = mega_session_stat(s, path);
      if (n && (n->type == MEGA_NODE_FILE || !opt_names))
        l = g_slist_append(l, n);

      l = g_slist_concat(l, mega_session_ls(s, path, opt_recursive));
    }
  }

  l = g_slist_sort(l, (GCompareFunc)compare_node);

  // export if requested
  if (opt_export && !mega_session_addlinks(s, l, &local_err))
  {
    g_printerr("ERROR: Can't read links info from mega.nz: %s\n", local_err->message);
    g_slist_free(l);
    tool_fini(s);
    return 1;
  }

  if (l && opt_long && opt_header && !opt_export)
  {
    g_print("===================================================================================\n");
    g_print("%-11s %-11s %-1s %13s %-19s %s\n", "Handle", "Owner", "T", "Size", "Mod. Date", opt_names ? "Filename" : "Path");
    g_print("===================================================================================\n");
  }

  for (i = l; i; i = i->next)
  {
    mega_node* n = i->data;
    gc_free gchar* node_path = mega_node_get_path_dup(n);

    if (opt_export)
      g_print("%73s ", n->link ? mega_node_get_link(n, TRUE) : "");

    if (opt_long)
    {
      GDateTime* dt = g_date_time_new_from_unix_local(n->timestamp);
      gc_free gchar* time_str = g_date_time_format(dt, "%Y-%m-%d %H:%M:%S");
      g_date_time_unref(dt);

      gc_free gchar* size_str = NULL;
      if (opt_human)
        size_str = n->size > 0 ? g_format_size_full(n->size, G_FORMAT_SIZE_IEC_UNITS) : g_strdup("-");
      else
        size_str = n->size > 0 ? g_strdup_printf("%" G_GUINT64_FORMAT, n->size) : g_strdup("-");

      g_print("%-11s %-11s %d %13s %19s %s\n",
        n->handle, 
        n->user_handle ? n->user_handle : "",
        n->type,
        size_str,
        n->timestamp > 0 ? time_str : "", 
        opt_names ? n->name : node_path
      );
    }
    else
      g_print("%s\n", opt_names ? n->name : node_path);
  }

  g_slist_free(l);
  tool_fini(s);
  return 0;
}
static void
get_folder_content_done_cb (GError   *error,
		            gpointer  user_data)
{
	LoadData             *load_data = user_data;
	FrFileSelectorDialog *self = load_data->dialog;
	GtkListStore         *list_store;
	GList                *scan;
	GtkTreeIter           iter;
	GDateTime            *today;
	int                   sort_column_id;
	GtkSortType           sort_order;
	GHashTable           *selected_files;

	if (error != NULL) {
		if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_MOUNTED)) {
			GMountOperation *operation;

			operation = gtk_mount_operation_new (GTK_WINDOW (self));
			g_file_mount_enclosing_volume (load_data->folder,
						       G_MOUNT_MOUNT_NONE,
						       operation,
						       load_data->cancellable,
						       folder_mount_enclosing_volume_ready_cb,
						       load_data);

			g_object_unref (operation);

			return;
		}

		if (! g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
			_gtk_error_dialog_run (GTK_WINDOW (self), _("Could not load the location"), "%s", error->message);

		if (load_data->dialog->priv->current_operation == load_data)
			load_data->dialog->priv->current_operation = NULL;
		load_data_free (load_data);

		return;
	}

	load_data->files = g_list_reverse (load_data->files);

	today = g_date_time_new_now_local ();

	gtk_tree_sortable_get_sort_column_id (GTK_TREE_SORTABLE (GET_WIDGET ("files_liststore")), &sort_column_id, &sort_order);
	gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (GET_WIDGET ("files_liststore")), GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID, 0);

	selected_files = g_hash_table_new (g_file_hash, (GEqualFunc) g_file_equal);
	for (scan = load_data->files_to_select; scan; scan = scan->next)
		g_hash_table_insert(selected_files, scan->data, GINT_TO_POINTER (1));

	list_store = GTK_LIST_STORE (GET_WIDGET ("files_liststore"));
	gtk_list_store_clear (list_store);
	for (scan = load_data->files; scan; scan = scan->next) {
		FileInfo  *file_info = scan->data;
		GdkPixbuf *icon_pixbuf;
		char      *size;
		GTimeVal   timeval;
		GDateTime *datetime;
		char      *modified;
		char      *collate_key;
		gboolean   is_folder;

		if (! self->priv->show_hidden && g_file_info_get_is_hidden (file_info->info))
			continue;

		gtk_list_store_append (list_store, &iter);

		icon_pixbuf = gth_icon_cache_get_pixbuf (self->priv->icon_cache, g_file_info_get_icon (file_info->info));
		size = g_format_size (g_file_info_get_size (file_info->info));
		g_file_info_get_modification_time (file_info->info, &timeval);
		datetime = g_date_time_new_from_timeval_local (&timeval);
		modified = g_date_time_format (datetime, _g_date_time_same_day (datetime, today) ? "%X" : "%x");
		collate_key = g_utf8_collate_key_for_filename (g_file_info_get_display_name (file_info->info), -1);
		is_folder = (g_file_info_get_file_type (file_info->info) == G_FILE_TYPE_DIRECTORY);

		gtk_list_store_set (list_store, &iter,
				    FILE_LIST_COLUMN_ICON, icon_pixbuf,
				    FILE_LIST_COLUMN_NAME, g_file_info_get_display_name (file_info->info),
				    FILE_LIST_COLUMN_SIZE, (is_folder ? "" : size),
				    FILE_LIST_COLUMN_MODIFIED, modified,
				    FILE_LIST_COLUMN_FILE, file_info->file,
				    FILE_LIST_COLUMN_NAME_ORDER, collate_key,
				    FILE_LIST_COLUMN_SIZE_ORDER, g_file_info_get_size (file_info->info),
				    FILE_LIST_COLUMN_MODIFIED_ORDER, timeval.tv_sec,
				    FILE_LIST_COLUMN_IS_FOLDER, is_folder,
				    FILE_LIST_COLUMN_IS_SELECTED, (g_hash_table_lookup (selected_files, file_info->file) != NULL),
				    -1);

		g_free (collate_key);
		g_free (modified);
		g_date_time_unref (datetime);
		g_free (size);
		_g_object_unref (icon_pixbuf);
	}

	gtk_tree_sortable_set_sort_column_id (GTK_TREE_SORTABLE (GET_WIDGET ("files_liststore")), sort_column_id, sort_order);
	set_current_folder (self, load_data->folder);

	if (load_data->dialog->priv->current_operation == load_data)
		load_data->dialog->priv->current_operation = NULL;

	g_hash_table_unref (selected_files);
	g_date_time_unref (today);
	load_data_free (load_data);
}
void
rpmhdrs_diff_prnt_block (gboolean changelogs, struct RpmHeadersDiff *diff)
{
  int num = 0;

  g_assert (diff->hs_mod_old->len == diff->hs_mod_new->len);

  if (diff->hs_mod_old->len)
    {
      gboolean done = FALSE;

      for (num = 0; num < diff->hs_mod_new->len; ++num)
        {
          Header ho = diff->hs_mod_old->pdata[num];
          Header hn = diff->hs_mod_new->pdata[num];
          struct rpmtd_s ochanges_date_s;
          _cleanup_rpmtddata_ rpmtd ochanges_date = NULL;
          struct rpmtd_s ochanges_name_s;
          _cleanup_rpmtddata_ rpmtd ochanges_name = NULL;
          struct rpmtd_s ochanges_text_s;
          _cleanup_rpmtddata_ rpmtd ochanges_text = NULL;
          struct rpmtd_s nchanges_date_s;
          _cleanup_rpmtddata_ rpmtd nchanges_date = NULL;
          struct rpmtd_s nchanges_name_s;
          _cleanup_rpmtddata_ rpmtd nchanges_name = NULL;
          struct rpmtd_s nchanges_text_s;
          _cleanup_rpmtddata_ rpmtd nchanges_text = NULL;
          int ocnum = 0;
          int ncnum = 0;
          uint64_t    ochange_date = 0;
          const char *ochange_name = NULL;
          const char *ochange_text = NULL;
          uint64_t    nchange_date = 0;
          const char *nchange_name = NULL;
          const char *nchange_text = NULL;

          g_assert (!header_name_cmp (ho, hn));
          if (rpmVersionCompare (ho, hn) > 0)
            continue;

          if (!done)
            {
              done = TRUE;
              g_print ("Upgraded:\n");
            }

          printf (" ");
          pkg_print (hn);

          if (!changelogs)
            continue;

          /* Load the old %changelog entries */
          ochanges_date = &ochanges_date_s;
          headerGet (ho, RPMTAG_CHANGELOGTIME, ochanges_date, HEADERGET_MINMEM);
          ochanges_name = &ochanges_name_s;
          headerGet (ho, RPMTAG_CHANGELOGNAME, ochanges_name, HEADERGET_MINMEM);
          ochanges_text = &ochanges_text_s;
          headerGet (ho, RPMTAG_CHANGELOGTEXT, ochanges_text, HEADERGET_MINMEM);

          ocnum = rpmtdCount (ochanges_date);
          if (!ocnum)
            continue;

          /* Load the new %changelog entries */
          nchanges_date = &nchanges_date_s;
          headerGet (hn, RPMTAG_CHANGELOGTIME, nchanges_date, HEADERGET_MINMEM);
          nchanges_name = &nchanges_name_s;
          headerGet (hn, RPMTAG_CHANGELOGNAME, nchanges_name, HEADERGET_MINMEM);
          nchanges_text = &nchanges_text_s;
          headerGet (hn, RPMTAG_CHANGELOGTEXT, nchanges_text, HEADERGET_MINMEM);

          ncnum = rpmtdCount (nchanges_date);
          if (!ncnum)
            continue;

          /* Load the latest old %changelog entry. */
          ochange_date = rpmtdGetNumber (ochanges_date);
          ochange_name = rpmtdGetString (ochanges_name);
          ochange_text = rpmtdGetString (ochanges_text);

          while (ncnum > 0)
            {
              GDateTime *dt = NULL;
              g_autofree char *date_time_str = NULL;

              /* Load next new %changelog entry, starting at the newest. */
              rpmtdNext (nchanges_date);
              rpmtdNext (nchanges_name);
              rpmtdNext (nchanges_text);
              nchange_date = rpmtdGetNumber (nchanges_date);
              nchange_name = rpmtdGetString (nchanges_name);
              nchange_text = rpmtdGetString (nchanges_text);

              /*  If we are now older than, or match, the latest old %changelog
               * then we are done. */
              if (ochange_date > nchange_date)
                break;
              if ((ochange_date == nchange_date) &&
                  g_str_equal (ochange_name, nchange_name) &&
                  g_str_equal (ochange_text, nchange_text))
                break;

              /* Otherwise, print. */
              dt = g_date_time_new_from_unix_utc (nchange_date);
              date_time_str = g_date_time_format (dt, "%a %b %d %Y");
              g_date_time_unref (dt);

              printf ("* %s %s\n%s\n\n", date_time_str, nchange_name,
                      nchange_text);

              --ncnum;
            }
        }

      done = FALSE;
      for (num = 0; num < diff->hs_mod_new->len; ++num)
        {
          Header ho = diff->hs_mod_old->pdata[num];
          Header hn = diff->hs_mod_new->pdata[num];

          g_assert (!header_name_cmp (ho, hn));
          if (rpmVersionCompare (ho, hn) < 0)
            continue;

          if (!done)
            {
              done = TRUE;
              g_print ("Downgraded:\n");
            }

          printf (" ");
          pkg_print (hn);
        }
    }

  if (diff->hs_del->len)
    {
      g_print ("Removed:\n");

      for (num = 0; num < diff->hs_del->len; ++num)
        {
          Header hd = diff->hs_del->pdata[num];

          printf (" ");
          pkg_print (hd);
        }
    }

  if (diff->hs_add->len)
    {
      g_print ("Added:\n");

      for (num = 0; num < diff->hs_add->len; ++num)
        {
          Header ha = diff->hs_add->pdata[num];

          printf (" ");
          pkg_print (ha);
        }
    }

  rpmhdrs_diff_free (diff);
}
Exemple #23
0
/**
 * gl_util_timestamp_to_display:
 * @microsecs: number of microseconds since the Unix epoch in UTC
 * @now: the time to compare with
 * @format: clock format (12 or 24 hour)
 *
 * Return a human readable time, corresponding to @microsecs, using an
 * appropriate @format after comparing it to @now and discarding unnecessary
 * elements (for example, return only time if the date is today).
 *
 * Returns: a newly-allocated human readable string which represents @microsecs
 */
gchar *
gl_util_timestamp_to_display (guint64 microsecs,
                              GDateTime *now,
                              GlUtilClockFormat format,
                              gboolean show_second)
{
    GDateTime *datetime;
    GDateTime *local;
    gchar *time = NULL;

    datetime = g_date_time_new_from_unix_utc (microsecs / G_TIME_SPAN_SECOND);

    if (datetime == NULL)
    {
        g_warning ("Error converting timestamp to time value");
        goto out;
    }

    local = g_date_time_to_local (datetime);

    switch (format)
    {
        case GL_UTIL_CLOCK_FORMAT_12HR:
            switch (compare_timestamps (local, now))
            {
                case GL_UTIL_TIMESTAMPS_SAME_DAY:
                    if (show_second)
                    {
                        /* Translators: timestamp format for events on the
                         * current day, showing the time with seconds in
                         * 12-hour format. */
                        time = g_date_time_format (local, _("%l:%M:%S %p"));
                    }
                    else
                    {
                        /* Translators: timestamp format for events on the
                         * current day, showing the time without seconds in
                         * 12-hour format. */
                        time = g_date_time_format (local, _("%l:%M %p"));
                    }
                    break;
                case GL_UTIL_TIMESTAMPS_SAME_YEAR:
                    if (show_second)
                    {
                        time = g_date_time_format (local,
                               /* Translators: timestamp format for events in
                                * the current year, showing the abbreviated
                                * month name, day of the month and the time
                                * with seconds in 12-hour format. */
                                                   _("%b %e %l:%M:%S %p"));
                    }
                    else
                    {
                        /* Translators: timestamp format for events in the
                         * current year, showing the abbreviated month name,
                         * day of the month and the time without seconds in
                         * 12-hour format. */
                        time = g_date_time_format (local, _("%b %e %l:%M %p"));
                    }
                    break;
                case GL_UTIL_TIMESTAMPS_DIFFERENT_YEAR:
                    if (show_second)
                    {
                        time = g_date_time_format (local,
                               /* Translators: timestamp format for events in
                                * a different year, showing the abbreviated
                                * month name, day of the month, year and the
                                * time with seconds in 12-hour format. */
                                                   _("%b %e %Y %l:%M:%S %p"));
                    }
                    else
                    {
                        time = g_date_time_format (local,
                               /* Translators: timestamp format for events in
                                * a different year, showing the abbreviated
                                * month name day of the month, year and the
                                * time without seconds in 12-hour format. */
                                                   _("%b %e %Y %l:%M %p"));
                    }
                    break;
                default:
                    g_assert_not_reached ();
            }

            break;
        case GL_UTIL_CLOCK_FORMAT_24HR:
            switch (compare_timestamps (local, now))
            {
                case GL_UTIL_TIMESTAMPS_SAME_DAY:
                    if (show_second)
                    {
                        /* Translators: timestamp format for events on the
                         * current day, showing the time with seconds in
                         * 24-hour format. */
                        time = g_date_time_format (local, _("%H:%M:%S"));
                    }
                    else
                    {
                        /* Translators: timestamp format for events on the
                         * current day, showing the time without seconds in
                         * 24-hour format. */
                        time = g_date_time_format (local, _("%H:%M"));
                    }
                    break;
                case GL_UTIL_TIMESTAMPS_SAME_YEAR:
                    if (show_second)
                    {
                        /* Translators: timestamp format for events in the
                         * current year, showing the abbreviated month name,
                         * day of the month and the time with seconds in
                         * 24-hour format. */
                        time = g_date_time_format (local, _("%b %e %H:%M:%S"));
                    }
                    else
                    {
                        /* Translators: timestamp format for events in the
                         * current year, showing the abbreviated month name,
                         * day of the month and the time without seconds in
                         * 24-hour format. */
                        time = g_date_time_format (local, _("%b %e %H:%M"));
                    }
                    break;
                case GL_UTIL_TIMESTAMPS_DIFFERENT_YEAR:
                    if (show_second)
                    {
                        time = g_date_time_format (local,
                               /* Translators: timestamp format for events in
                                * a different year, showing the abbreviated
                                * month name, day of the month, year and the
                                * time with seconds in 24-hour format. */
                                                   _("%b %e %Y %H:%M:%S"));
                    }
                    else
                    {
                        /* Translators: timestamp format for events in a
                         * different year, showing the abbreviated month name,
                         * day of the month, year and the time without seconds
                         * in 24-hour format. */
                        time = g_date_time_format (local, _("%b %e %Y %H:%M"));
                    }
                    break;
                default:
                    g_assert_not_reached ();
            }

            break;
        default:
            g_assert_not_reached ();
    }

    g_date_time_unref (datetime);
    g_date_time_unref (local);

    if (time == NULL)
    {
        g_warning ("Error converting datetime to string");
    }

out:
    return time;
}
Exemple #24
0
int
main (int argc, char *argv[])
{
	GError *error = NULL;
	GOptionGroup *option_group;
	GOptionContext *context;
	const gchar *simulation_filename, *introspection_filename;
	gchar *simulation_code, *introspection_xml;
	MainData data;
	GPtrArray/*<DfsmObject>*/ *simulated_objects;
	const gchar *test_program_name;
	GPtrArray/*<string>*/ *test_program_argv;
	guint i;
	gchar *time_str, *command_line, *log_header, *seed_str;
	GDateTime *date_time;
	GFile *working_directory_file, *dbus_daemon_config_file;

	/* Set up localisation. */
	setlocale (LC_ALL, "");
	bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);

#if !GLIB_CHECK_VERSION (2, 35, 0)
	g_type_init ();
#endif
	g_set_application_name (_("D-Bus Simulator"));

	/* Take a copy of the command line, for use in printing the log headers later. */
	command_line = g_strjoinv (" ", argv);

	/* Parse command line options */
	context = g_option_context_new (_("[simulation code file] [introspection XML file] -- [executable-file] [arguments]"));
	g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
	g_option_context_set_summary (context, _("Simulates the server in a D-Bus client–server conversation."));
	g_option_context_add_main_entries (context, main_entries, GETTEXT_PACKAGE);

	/* Logging option group */
	option_group = g_option_group_new ("logging", _("Logging Options:"), _("Show help options for output logging"), NULL, NULL);
	g_option_group_set_translation_domain (option_group, GETTEXT_PACKAGE);
	g_option_group_add_entries (option_group, logging_entries);
	g_option_context_add_group (context, option_group);

	/* Testing option group */
	option_group = g_option_group_new ("testing", _("Testing Options:"), _("Show help options for test runs and timeouts"), NULL, NULL);
	g_option_group_set_translation_domain (option_group, GETTEXT_PACKAGE);
	g_option_group_add_entries (option_group, testing_entries);
	g_option_context_add_group (context, option_group);

	/* Test program option group */
	option_group = g_option_group_new ("test-program", _("Test Program Options:"), _("Show help options for the program under test"), NULL, NULL);
	g_option_group_set_translation_domain (option_group, GETTEXT_PACKAGE);
	g_option_group_add_entries (option_group, test_program_entries);
	g_option_context_add_group (context, option_group);

	/* dbus-daemon option group */
	option_group = g_option_group_new ("dbus-daemon", _("D-Bus Daemon Options:"), _("Show help options for the dbus-daemon"), NULL, NULL);
	g_option_group_set_translation_domain (option_group, GETTEXT_PACKAGE);
	g_option_group_add_entries (option_group, dbus_daemon_entries);
	g_option_context_add_group (context, option_group);

	if (g_option_context_parse (context, &argc, &argv, &error) == FALSE) {
		g_printerr (_("Error parsing command line options: %s"), error->message);
		g_printerr ("\n");

		print_help_text (context);

		g_error_free (error);
		g_option_context_free (context);
		g_free (command_line);

		exit (STATUS_INVALID_OPTIONS);
	}

	/* Extract the simulation and the introspection filenames. */
	if (argc < 3) {
		g_printerr (_("Error parsing command line options: %s"), _("Simulation and introspection filenames must be provided"));
		g_printerr ("\n");

		print_help_text (context);

		g_option_context_free (context);
		g_free (command_line);

		exit (STATUS_INVALID_OPTIONS);
	}

	simulation_filename = argv[1];
	introspection_filename = argv[2];

	/* Extract the remaining arguments */
	if (argc < 4) {
		g_printerr (_("Error parsing command line options: %s"), _("Test program must be provided"));
		g_printerr ("\n");

		print_help_text (context);

		g_option_context_free (context);
		g_free (command_line);

		exit (STATUS_INVALID_OPTIONS);
	}

	/* Work out where the test program's command line starts. g_option_context_parse() sometimes leaves the ‘--’ in argv. */
	if (strcmp (argv[3], "--") == 0) {
		i = 4;
	} else {
		i = 3;
	}

	test_program_name = argv[i++];
	test_program_argv = g_ptr_array_new_with_free_func (g_free);

	for (; i < (guint) argc; i++) {
		g_ptr_array_add (test_program_argv, g_strdup (argv[i]));
	}

	g_option_context_free (context);

	/* Set up logging. */
	dsim_logging_init (test_program_log_file, test_program_log_fd, dbus_daemon_log_file, dbus_daemon_log_fd, simulator_log_file, simulator_log_fd,
	                   &error);

	if (error != NULL) {
		g_printerr (_("Error setting up logging: %s"), error->message);
		g_printerr ("\n");

		g_error_free (error);
		g_free (command_line);

		exit (STATUS_LOGGING_PROBLEM);
	}

	/* Output a log header to each of the log streams. */
	date_time = g_date_time_new_now_utc ();
	time_str = g_date_time_format (date_time, "%F %TZ");
	g_date_time_unref (date_time);

	log_header = g_strdup_printf (_("Bendy Bus (number %s) left the depot at %s using command line: %s"), PACKAGE_VERSION, time_str, command_line);

	g_log (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, "%s", log_header);
	g_log (dsim_logging_get_domain_name (DSIM_LOG_DBUS_DAEMON), G_LOG_LEVEL_MESSAGE, "%s", log_header);
	g_log (dsim_logging_get_domain_name (DSIM_LOG_TEST_PROGRAM), G_LOG_LEVEL_MESSAGE, "%s", log_header);

	g_free (log_header);
	g_free (time_str);
	g_free (command_line);

	/* Set up the random number generator. */
	if (random_seed == 0) {
		random_seed = g_get_real_time ();
	}

	seed_str = g_strdup_printf ("%" G_GINT64_FORMAT, random_seed);
	g_message (_("Note: Setting random number generator seed to %s."), seed_str);
	g_free (seed_str);

	g_random_set_seed ((guint32) random_seed);

	/* Load the files. */
	g_file_get_contents (simulation_filename, &simulation_code, NULL, &error);

	if (error != NULL) {
		g_printerr (_("Error loading simulation code from file ‘%s’: %s"), simulation_filename, error->message);
		g_printerr ("\n");

		g_error_free (error);

		exit (STATUS_UNREADABLE_FILE);
	}

	g_file_get_contents (introspection_filename, &introspection_xml, NULL, &error);

	if (error != NULL) {
		g_printerr (_("Error loading introspection XML from file ‘%s’: %s"), introspection_filename, error->message);
		g_printerr ("\n");

		g_error_free (error);
		g_free (simulation_code);

		exit (STATUS_UNREADABLE_FILE);
	}

	/* Build the DfsmObjects. */
	simulated_objects = dfsm_object_factory_from_data (simulation_code, introspection_xml, &error);

	g_free (introspection_xml);
	g_free (simulation_code);

	if (error != NULL) {
		g_printerr (_("Error creating simulated DFSMs: %s"), error->message);
		g_printerr ("\n");

		g_error_free (error);

		exit (STATUS_INVALID_CODE);
	}

	/* Prepare the main data struct, which will last for the lifetime of the program. */
	data.main_loop = g_main_loop_new (NULL, FALSE);
	data.exit_status = STATUS_SUCCESS;
	data.exit_signal = EXIT_SIGNAL_INVALID;
	data.test_program = NULL;
	data.connection = NULL;
	data.simulated_objects = g_ptr_array_ref (simulated_objects);
	data.outstanding_registration_callbacks = 0;
	data.test_run_inactivity_timeout_id = 0;
	data.test_program_spawn_end_signal = 0;
	data.test_program_process_died_signal = 0;
	data.test_program_sigkill_timeout_id = 0;

	if (run_infinitely == TRUE || (run_iters == 0 && run_time == 0)) {
		data.num_test_runs_remaining = -1;
	} else {
		data.num_test_runs_remaining = run_iters;
	}

	g_ptr_array_unref (simulated_objects);

	/* Store the test program name and argv, since we can only spawn it once we know the bus address. */
	data.test_program_name = g_strdup (test_program_name);
	data.test_program_argv = g_ptr_array_ref (test_program_argv);

	g_ptr_array_unref (test_program_argv);

	/* Set up signal handlers for SIGINT and SIGTERM so that we can close gracefully. */
	g_unix_signal_add (SIGINT, (GSourceFunc) sigint_handler_cb, &data);
	g_unix_signal_add (SIGTERM, (GSourceFunc) sigterm_handler_cb, &data);

	/* Create a working directory. */
	prepare_dbus_daemon_working_directory (&(data.working_directory_file), &working_directory_file, &dbus_daemon_config_file, &error);

	if (error != NULL) {
		g_printerr (_("Error creating dbus-daemon working directory: %s"), error->message);
		g_printerr ("\n");

		g_error_free (error);
		main_data_clear (&data);
		dsim_logging_finalise ();

		exit (STATUS_TMP_DIR_ERROR);
	}

	/* Start up our own private dbus-daemon instance. */
	data.dbus_daemon = dsim_dbus_daemon_new (working_directory_file, dbus_daemon_config_file);
	data.dbus_address = NULL;

	g_object_unref (dbus_daemon_config_file);
	g_object_unref (working_directory_file);

	g_signal_connect (data.dbus_daemon, "process-died", (GCallback) dbus_daemon_died_cb, &data);
	g_signal_connect (data.dbus_daemon, "notify::bus-address", (GCallback) dbus_daemon_notify_bus_address_cb, &data);

	dsim_program_wrapper_spawn (DSIM_PROGRAM_WRAPPER (data.dbus_daemon), &error);

	if (error != NULL) {
		g_printerr (_("Error spawning private dbus-daemon instance: %s"), error->message);
		g_printerr ("\n");

		g_error_free (error);
		main_data_clear (&data);
		dsim_logging_finalise ();

		exit (STATUS_DAEMON_SPAWN_ERROR);
	}

	/* Start the main loop and wait for the dbus-daemon to send us its address. */
	g_main_loop_run (data.main_loop);

	/* Free the main data struct. */
	main_data_clear (&data);
	dsim_logging_finalise ();

	if (data.exit_signal != EXIT_SIGNAL_INVALID) {
		struct sigaction action;

		/* Propagate the signal to the default handler. */
		action.sa_handler = SIG_DFL;
		sigemptyset (&action.sa_mask);
		action.sa_flags = 0;

		sigaction (data.exit_signal, &action, NULL);

		kill (getpid (), data.exit_signal);
	}

	return data.exit_status;
}
static void
photos_properties_dialog_constructed (GObject *object)
{
  PhotosPropertiesDialog *self = PHOTOS_PROPERTIES_DIALOG (object);
  GApplication *app;
  g_autoptr (GDateTime) date_modified = NULL;
  GtkStyleContext *context;
  GtkWidget *author_w = NULL;
  GtkWidget *content_area;
  GtkWidget *date_created_w = NULL;
  GtkWidget *date_modified_data;
  GtkWidget *date_modified_w;
  GtkWidget *dimensions_w = NULL;
  GtkWidget *exposure_time_w = NULL;
  GtkWidget *flash_w = NULL;
  GtkWidget *fnumber_w = NULL;
  GtkWidget *focal_length_w = NULL;
  GtkWidget *iso_speed_w = NULL;
  GtkWidget *item_type;
  GtkWidget *item_type_data;
  GtkWidget *modified_w = NULL;
  GtkWidget *source;
  GtkWidget *source_data;
  GtkWidget *title;
  GQuark equipment;
  GQuark flash;
  PhotosBaseItem *item;
  PhotosSearchContextState *state;
  const gchar *author;
  const gchar *location;
  const gchar *name;
  const gchar *type_description;
  g_autofree gchar *date_created_str = NULL;
  g_autofree gchar *date_modified_str = NULL;
  gdouble exposure_time;
  gdouble fnumber;
  gdouble focal_length;
  gdouble iso_speed;
  gint64 ctime;
  gint64 mtime;
  glong height;
  glong width;

  G_OBJECT_CLASS (photos_properties_dialog_parent_class)->constructed (object);

  app = g_application_get_default ();
  state = photos_search_context_get_state (PHOTOS_SEARCH_CONTEXT (app));

  self->item_mngr = g_object_ref (state->item_mngr);

  {
    g_autoptr (GError) error = NULL;

    self->queue = photos_tracker_queue_dup_singleton (NULL, &error);
    if (G_UNLIKELY (error != NULL))
      g_warning ("Unable to create PhotosTrackerQueue: %s", error->message);
  }

  item = PHOTOS_BASE_ITEM (photos_base_manager_get_object_by_id (self->item_mngr, self->urn));

  mtime = photos_base_item_get_mtime (item);
  date_modified = g_date_time_new_from_unix_local (mtime);
  date_modified_str = g_date_time_format (date_modified, "%c");

  ctime = photos_base_item_get_date_created (item);
  if (ctime >= 0)
    {
      g_autoptr (GDateTime) date_created = NULL;

      date_created = g_date_time_new_from_unix_local (ctime);
      date_created_str = g_date_time_format (date_created, "%c");
    }

  self->grid = gtk_grid_new ();
  gtk_widget_set_halign (self->grid, GTK_ALIGN_CENTER);
  gtk_widget_set_margin_start (self->grid, 24);
  gtk_widget_set_margin_end (self->grid, 24);
  gtk_widget_set_margin_bottom (self->grid, 12);
  gtk_widget_set_margin_top (self->grid, 12);
  gtk_orientable_set_orientation (GTK_ORIENTABLE (self->grid), GTK_ORIENTATION_VERTICAL);
  gtk_grid_set_column_homogeneous (GTK_GRID (self->grid), TRUE);
  gtk_grid_set_column_spacing (GTK_GRID (self->grid), 24);
  gtk_grid_set_row_homogeneous (GTK_GRID (self->grid), TRUE);
  gtk_grid_set_row_spacing (GTK_GRID (self->grid), 6);

  content_area = gtk_dialog_get_content_area (GTK_DIALOG (self));
  gtk_box_pack_start (GTK_BOX (content_area), self->grid, TRUE, TRUE, 2);

  /* Translators: this is the label next to the photo title in the
   * properties dialog
   */
  title = gtk_label_new (C_("Document Title", "Title"));
  gtk_widget_set_halign (title, GTK_ALIGN_END);
  context = gtk_widget_get_style_context (title);
  gtk_style_context_add_class (context, "dim-label");
  gtk_container_add (GTK_CONTAINER (self->grid), title);

  author = photos_base_item_get_author (item);
  if (author != NULL && author[0] != '\0')
    {
      /* Translators: this is the label next to the photo author in
       * the properties dialog
       */
      author_w = gtk_label_new (C_("Document Author", "Author"));
      gtk_widget_set_halign (author_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (author_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (self->grid), author_w);
    }

  source = gtk_label_new (_("Source"));
  gtk_widget_set_halign (source, GTK_ALIGN_END);
  context = gtk_widget_get_style_context (source);
  gtk_style_context_add_class (context, "dim-label");
  gtk_container_add (GTK_CONTAINER (self->grid), source);

  date_modified_w = gtk_label_new (_("Date Modified"));
  gtk_widget_set_halign (date_modified_w, GTK_ALIGN_END);
  context = gtk_widget_get_style_context (date_modified_w);
  gtk_style_context_add_class (context, "dim-label");
  gtk_container_add (GTK_CONTAINER (self->grid), date_modified_w);

  if (date_created_str != NULL)
    {
      date_created_w = gtk_label_new (_("Date Created"));
      gtk_widget_set_halign (date_created_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (date_created_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (self->grid), date_created_w);
    }

  /* Translators: this is the label next to the photo type in the
   * properties dialog
   */
  item_type = gtk_label_new (C_("Document Type", "Type"));
  gtk_widget_set_halign (item_type, GTK_ALIGN_END);
  context = gtk_widget_get_style_context (item_type);
  gtk_style_context_add_class (context, "dim-label");
  gtk_container_add (GTK_CONTAINER (self->grid), item_type);

  height = (glong) photos_base_item_get_height (item);
  width = (glong) photos_base_item_get_width (item);
  if (height > 0 && width > 0)
    {
      dimensions_w = gtk_label_new (_("Dimensions"));
      gtk_widget_set_halign (dimensions_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (dimensions_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (self->grid), dimensions_w);
    }

  location = photos_base_item_get_location (item);
  if (location != NULL && location[0] != '\0' && G_LIKELY (self->queue != NULL))
    {
      g_autoptr (PhotosQuery) query = NULL;

      self->location_w = gtk_label_new (_("Location"));
      gtk_widget_set_halign (self->location_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (self->location_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (self->grid), self->location_w);

      query = photos_query_builder_location_query (state, location);
      photos_tracker_queue_select (self->queue,
                                   query,
                                   NULL,
                                   photos_properties_dialog_location_query_executed,
                                   g_object_ref (self),
                                   g_object_unref);
    }

  equipment = photos_base_item_get_equipment (item);
  if (equipment != 0)
    {
      self->camera_w = gtk_label_new (_("Camera"));
      gtk_widget_set_halign (self->camera_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (self->camera_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (self->grid), self->camera_w);
    }

  exposure_time = photos_base_item_get_exposure_time (item);
  if (exposure_time > 0.0)
    {
      exposure_time_w = gtk_label_new (_("Exposure"));
      gtk_widget_set_halign (exposure_time_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (exposure_time_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (self->grid), exposure_time_w);
    }

  fnumber = photos_base_item_get_fnumber (item);
  if (fnumber > 0.0)
    {
      fnumber_w = gtk_label_new (_("Aperture"));
      gtk_widget_set_halign (fnumber_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (fnumber_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (self->grid), fnumber_w);
    }

  focal_length = photos_base_item_get_focal_length (item);
  if (focal_length > 0.0)
    {
      focal_length_w = gtk_label_new (_("Focal Length"));
      gtk_widget_set_halign (focal_length_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (focal_length_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (self->grid), focal_length_w);
    }

  iso_speed = photos_base_item_get_iso_speed (item);
  if (iso_speed > 0.0)
    {
      iso_speed_w = gtk_label_new (_("ISO Speed"));
      gtk_widget_set_halign (iso_speed_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (iso_speed_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (self->grid), iso_speed_w);
    }

  flash = photos_base_item_get_flash (item);
  if (flash != 0)
    {
      flash_w = gtk_label_new (_("Flash"));
      gtk_widget_set_halign (flash_w, GTK_ALIGN_END);
      context = gtk_widget_get_style_context (flash_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (self->grid), flash_w);
    }

  if (!photos_base_item_is_collection (item))
    {
      modified_w = gtk_label_new (_("Modifications"));
      gtk_widget_set_halign (modified_w, GTK_ALIGN_END);
      gtk_widget_set_valign (modified_w, GTK_ALIGN_BASELINE);
      gtk_widget_set_vexpand (modified_w, TRUE);
      context = gtk_widget_get_style_context (modified_w);
      gtk_style_context_add_class (context, "dim-label");
      gtk_container_add (GTK_CONTAINER (self->grid), modified_w);
    }

  name = photos_base_item_get_name (item);

  if (PHOTOS_IS_LOCAL_ITEM (item))
    {
      self->title_entry = gtk_entry_new ();
      gtk_widget_set_halign (self->title_entry, GTK_ALIGN_START);
      gtk_widget_set_hexpand (self->title_entry, TRUE);
      gtk_entry_set_activates_default (GTK_ENTRY (self->title_entry), TRUE);
      gtk_entry_set_text (GTK_ENTRY (self->title_entry), name);
      gtk_entry_set_width_chars (GTK_ENTRY (self->title_entry), 40);
      gtk_editable_set_editable (GTK_EDITABLE (self->title_entry), TRUE);

      g_signal_connect (self->title_entry,
                        "changed",
                        G_CALLBACK (photos_properties_dialog_title_entry_changed),
                        self);
    }
  else
    {
      self->title_entry = gtk_label_new (name);
      gtk_widget_set_halign (self->title_entry, GTK_ALIGN_START);
      gtk_label_set_ellipsize (GTK_LABEL (self->title_entry), PANGO_ELLIPSIZE_END);
      gtk_label_set_max_width_chars (GTK_LABEL (self->title_entry), 40);
    }

  gtk_grid_attach_next_to (GTK_GRID (self->grid), self->title_entry, title, GTK_POS_RIGHT, 2, 1);

  if (author_w != NULL)
    {
      GtkWidget *author_data;

      author_data = gtk_label_new (author);
      gtk_widget_set_halign (author_data, GTK_ALIGN_START);
      gtk_grid_attach_next_to (GTK_GRID (self->grid), author_data, author_w, GTK_POS_RIGHT, 2, 1);
    }

  source_data = photos_base_item_get_source_widget (item);
  gtk_grid_attach_next_to (GTK_GRID (self->grid), source_data, source, GTK_POS_RIGHT, 2, 1);

  date_modified_data = gtk_label_new (date_modified_str);
  gtk_widget_set_halign (date_modified_data, GTK_ALIGN_START);
  gtk_grid_attach_next_to (GTK_GRID (self->grid), date_modified_data, date_modified_w, GTK_POS_RIGHT, 2, 1);

  if (date_created_w != NULL)
    {
      GtkWidget *date_created_data;

      date_created_data = gtk_label_new (date_created_str);
      gtk_widget_set_halign (date_created_data, GTK_ALIGN_START);
      gtk_grid_attach_next_to (GTK_GRID (self->grid), date_created_data, date_created_w, GTK_POS_RIGHT, 2, 1);
    }

  type_description = photos_base_item_get_type_description (item);
  item_type_data = gtk_label_new (type_description);
  gtk_widget_set_halign (item_type_data, GTK_ALIGN_START);
  gtk_grid_attach_next_to (GTK_GRID (self->grid), item_type_data, item_type, GTK_POS_RIGHT, 2, 1);

  if (dimensions_w != NULL)
    {
      GtkWidget *dims_data;
      g_autofree gchar *dims_str = NULL;
      gulong n = (gulong) height;

      dims_str = g_strdup_printf (ngettext ("%ld × %ld pixel", "%ld × %ld pixels", n), width, height);
      dims_data = gtk_label_new (dims_str);
      gtk_widget_set_halign (dims_data, GTK_ALIGN_START);
      gtk_grid_attach_next_to (GTK_GRID (self->grid), dims_data, dimensions_w, GTK_POS_RIGHT, 2, 1);
    }

  if (self->camera_w != NULL)
    {
      photos_camera_cache_get_camera_async (self->camera_cache,
                                            equipment,
                                            self->cancellable,
                                            photos_properties_dialog_get_camera,
                                            self);
    }

  if (exposure_time_w != NULL)
    {
      GtkWidget *exposure_time_data;
      g_autofree gchar *exposure_time_str = NULL;

      exposure_time_str = g_strdup_printf ("%.3lf sec", exposure_time);
      exposure_time_data = gtk_label_new (exposure_time_str);
      gtk_widget_set_halign (exposure_time_data, GTK_ALIGN_START);
      gtk_grid_attach_next_to (GTK_GRID (self->grid), exposure_time_data, exposure_time_w, GTK_POS_RIGHT, 2, 1);
    }

  if (fnumber_w != NULL)
    {
      GtkWidget *fnumber_data;
      g_autofree gchar *fnumber_str = NULL;

      fnumber_str = g_strdup_printf ("f/%.1lf", fnumber);
      fnumber_data = gtk_label_new (fnumber_str);
      gtk_widget_set_halign (fnumber_data, GTK_ALIGN_START);
      gtk_grid_attach_next_to (GTK_GRID (self->grid), fnumber_data, fnumber_w, GTK_POS_RIGHT, 2, 1);
    }

  if (focal_length_w != NULL)
    {
      GtkWidget *focal_length_data;
      g_autofree gchar *focal_length_str = NULL;

      focal_length_str = g_strdup_printf ("%.0lf mm", focal_length);
      focal_length_data = gtk_label_new (focal_length_str);
      gtk_widget_set_halign (focal_length_data, GTK_ALIGN_START);
      gtk_grid_attach_next_to (GTK_GRID (self->grid), focal_length_data, focal_length_w, GTK_POS_RIGHT, 2, 1);
    }

  if (iso_speed_w != NULL)
    {
      GtkWidget *iso_speed_data;
      g_autofree gchar *iso_speed_str = NULL;

      iso_speed_str = g_strdup_printf ("%.0lf", iso_speed);
      iso_speed_data = gtk_label_new (iso_speed_str);
      gtk_widget_set_halign (iso_speed_data, GTK_ALIGN_START);
      gtk_grid_attach_next_to (GTK_GRID (self->grid), iso_speed_data, iso_speed_w, GTK_POS_RIGHT, 2, 1);
    }

  if (flash_w != NULL)
    {
      GtkWidget *flash_data;
      g_autofree gchar *flash_str = NULL;

      if (flash == PHOTOS_FLASH_OFF)
        flash_str = g_strdup (_("Off, did not fire"));
      else if (flash == PHOTOS_FLASH_ON)
        flash_str = g_strdup (_("On, fired"));
      else
        {
          const gchar *str;

          str = g_quark_to_string (flash);
          g_warning ("Unknown value for nmm:flash: %s", str);
        }

      flash_data = gtk_label_new (flash_str);
      gtk_widget_set_halign (flash_data, GTK_ALIGN_START);
      gtk_grid_attach_next_to (GTK_GRID (self->grid), flash_data, flash_w, GTK_POS_RIGHT, 2, 1);
    }

  if (modified_w != NULL)
    {
      GtkWidget *modified_grid;

      photos_base_item_pipeline_is_edited_async (item,
                                                 self->cancellable,
                                                 photos_properties_dialog_pipeline_is_edited,
                                                 self);

      modified_grid = gtk_grid_new ();
      gtk_widget_set_hexpand (modified_grid, TRUE);
      gtk_orientable_set_orientation (GTK_ORIENTABLE (modified_grid), GTK_ORIENTATION_HORIZONTAL);

      self->modified_data = gtk_label_new (NULL);
      gtk_widget_set_halign (self->modified_data, GTK_ALIGN_START);
      gtk_widget_set_hexpand (self->modified_data, TRUE);
      gtk_widget_set_no_show_all (self->modified_data, TRUE);
      gtk_widget_set_valign (self->modified_data, GTK_ALIGN_BASELINE);
      gtk_widget_set_vexpand (self->modified_data, TRUE);
      context = gtk_widget_get_style_context (self->modified_data);
      gtk_style_context_add_class (context, "photos-fade-out");
      gtk_container_add (GTK_CONTAINER (modified_grid), self->modified_data);

      self->revert_button = gtk_button_new_with_label (_("Discard all Edits"));
      gtk_widget_set_halign (self->revert_button, GTK_ALIGN_END);
      gtk_widget_set_hexpand (self->revert_button, TRUE);
      gtk_widget_set_no_show_all (self->revert_button, TRUE);
      context = gtk_widget_get_style_context (self->revert_button);
      gtk_style_context_add_class (context, "destructive-action");
      gtk_style_context_add_class (context, "photos-fade-out");
      gtk_container_add (GTK_CONTAINER (modified_grid), self->revert_button);

      g_signal_connect_swapped (self->revert_button,
                                "clicked",
                                G_CALLBACK (photos_properties_dialog_revert_clicked),
                                self);

      gtk_grid_attach_next_to (GTK_GRID (self->grid), modified_grid, modified_w, GTK_POS_RIGHT, 2, 1);
    }

}
Exemple #26
0
static void
load_chain (PatrolDialogWindow *self, PatrolDialogRecord *r,
            guint idx, GtkWidget *container)
{
    /* build tree model */
    GtkTreeStore *tree_store = gtk_tree_store_new(COLS_NUM, G_TYPE_STRING,
                                                  G_TYPE_BOOLEAN, G_TYPE_INT,
                                                  G_TYPE_POINTER, G_TYPE_POINTER);

    GtkTreeIter *parent = NULL, iter;
    gint i, num_certs = gcr_certificate_chain_get_length(r->chain);
    GcrCertificate *cert = NULL;

    for (i = num_certs - 1; i >= 0; i--) {
        cert = gcr_certificate_chain_get_certificate(r->chain, i);
        gchar *label = gcr_certificate_get_subject_name(cert);

        gtk_tree_store_append(tree_store, &iter, parent);
        gtk_tree_store_set(tree_store, &iter,
                           COL_NAME, label,
                           COL_PIN, i == r->pin_level,
                           COL_PIN_LEVEL, i,
                           COL_CERT, cert,
                           COL_REC, r,
                           -1);
        parent = &iter;
        g_free(label);
    }

    /* set hierarchy title */
    GtkWidget *title_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
    gtk_box_pack_start(GTK_BOX(container), title_box, FALSE, FALSE, 0);
    gchar *text, *str;
    GtkWidget *label = gtk_label_new(NULL);
    GtkWidget *value;

    if (idx == 0) {
        switch (self->pv->result) {
        case  PATROL_VERIFY_NEW:
        case  PATROL_VERIFY_CHANGE:
            text = g_strdup_printf("<b>%s</b>", _("New Certificate"));
            break;
        case  PATROL_VERIFY_REJECT:
            text = g_strdup_printf("<b>%s</b>", _("Rejected Certificate"));
            break;
        default:
            text = g_strdup_printf("<b>%s</b>", _("Selected Certificate"));
            break;
        }
    } else {
        text = g_strdup_printf("<b>%s #%d</b>", _("Stored Certificate"), idx);
        gtk_widget_set_margin_bottom(GTK_WIDGET(label), 2);
    }

    gtk_label_set_markup(GTK_LABEL(label), text);
    g_free(text);
    gtk_widget_set_halign(GTK_WIDGET(label), GTK_ALIGN_START);
    gtk_box_pack_start(GTK_BOX(title_box), label, FALSE, FALSE, 0);

    GtkWidget *grid = gtk_grid_new();
    gtk_widget_set_margin_left(GTK_WIDGET(grid), 5);
    gtk_box_pack_start(GTK_BOX(title_box), grid, FALSE, FALSE, 0);

    label = gtk_label_new(NULL);
    gtk_label_set_text(GTK_LABEL(label), _("Seen: "));
    str = g_strdup_printf("%" G_GINT64_FORMAT, r->rec.count_seen);
    text = g_strdup_printf(g_dngettext(textdomain(NULL),
                                       "%s time", "%s times",
                                       r->rec.count_seen), str);
    g_free(str);
    value = gtk_label_new(NULL);
    gtk_label_set_text(GTK_LABEL(value), text);
    g_free(text);
    gtk_widget_set_halign(GTK_WIDGET(label), GTK_ALIGN_START);
    gtk_widget_set_halign(GTK_WIDGET(value), GTK_ALIGN_START);
    gtk_grid_attach(GTK_GRID(grid), label, 0, 0, 1, 1);
    gtk_grid_attach(GTK_GRID(grid), value, 1, 0, 1, 1);

    label = gtk_label_new(NULL);
    gtk_label_set_text(GTK_LABEL(label), _("First seen: "));
    GDateTime *dtime = g_date_time_new_from_unix_local(r->rec.first_seen);
    text = g_date_time_format(dtime, "%c");
    g_date_time_unref(dtime);
    value = gtk_label_new(NULL);
    gtk_label_set_text(GTK_LABEL(value), text);
    g_free(text);
    gtk_widget_set_halign(GTK_WIDGET(label), GTK_ALIGN_START);
    gtk_widget_set_halign(GTK_WIDGET(value), GTK_ALIGN_START);
    gtk_grid_attach(GTK_GRID(grid), label, 0, 1, 1, 1);
    gtk_grid_attach(GTK_GRID(grid), value, 1, 1, 1, 1);

    if (r->rec.first_seen != r->rec.last_seen) {
        label = gtk_label_new(NULL);
        gtk_label_set_text(GTK_LABEL(label), _("Last seen: "));
        dtime = g_date_time_new_from_unix_local(r->rec.last_seen);
        text = g_date_time_format(dtime, "%c");
        g_date_time_unref(dtime);
        value = gtk_label_new(NULL);
        gtk_label_set_text(GTK_LABEL(value), text);
        g_free(text);
        gtk_widget_set_halign(GTK_WIDGET(label), GTK_ALIGN_START);
        gtk_widget_set_halign(GTK_WIDGET(value), GTK_ALIGN_START);
        gtk_grid_attach(GTK_GRID(grid), label, 0, 2, 1, 1);
        gtk_grid_attach(GTK_GRID(grid), value, 1, 2, 1, 1);
    }

    if (cert) {
        label = gtk_label_new(NULL);
        gtk_label_set_text(GTK_LABEL(label), _("Validity: "));

        GDate *expiry = gcr_certificate_get_expiry_date(cert);
        GDate *now = g_date_new();
        g_date_set_time_t(now, time(NULL));
        gint diff = g_date_days_between(now, expiry);
        g_date_free(now);
        g_date_free(expiry);

        if (diff > 0) {
            text = g_strdup_printf(g_dngettext(textdomain(NULL),
                                               "Certificate is valid for %d more day",
                                               "Certificate is valid for %d more days",
                                               diff), diff);
        } else if (diff < 0) {
            diff = abs(diff);
            text = g_strdup_printf(g_dngettext(textdomain(NULL),
                                               "Certificate <b>expired</b> %d day ago",
                                               "Certificate <b>expired</b> %d days ago",
                                               diff), diff);
        } else {
            text = g_strdup_printf("Certificate expires today");
        }

        value = gtk_label_new(NULL);
        gtk_label_set_markup(GTK_LABEL(value), text);
        g_free(text);

        gtk_widget_set_halign(GTK_WIDGET(label), GTK_ALIGN_START);
        gtk_widget_set_halign(GTK_WIDGET(value), GTK_ALIGN_START);
        gtk_grid_attach(GTK_GRID(grid), label, 0, 3, 1, 1);
        gtk_grid_attach(GTK_GRID(grid), value, 1, 3, 1, 1);
    }

    gtk_widget_show_all(title_box);

    /* build tree view */
    GtkWidget *tree_view;
    tree_view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(tree_store));
    gtk_tree_view_expand_all(GTK_TREE_VIEW(tree_view));
    gtk_box_pack_start(GTK_BOX(container), tree_view, FALSE, FALSE, 0);
    gtk_widget_show(tree_view);

    g_signal_connect(tree_view, "focus-in-event",
                     G_CALLBACK(on_tree_view_focus), self);
    g_signal_connect(self->pv->renderer, "data-changed",
                     G_CALLBACK(on_cert_changed), tree_view);
    GtkTreeSelection *tree_sel
        = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree_view));
    g_signal_connect(tree_sel, "changed", 
                     G_CALLBACK(on_tree_selection_changed), self);

    if (idx == 0) // new chain
        gtk_tree_selection_select_iter(tree_sel, &iter);

    /* first column */
    GtkCellRenderer *tree_renderer = gtk_cell_renderer_text_new();
    GtkTreeViewColumn *tree_column
        = gtk_tree_view_column_new_with_attributes(_("Certificate Hierarchy"),
                                                   tree_renderer, "text",
                                                   COL_NAME, NULL);
    gtk_tree_view_column_set_expand (tree_column, TRUE);
    gtk_tree_view_insert_column (GTK_TREE_VIEW (tree_view), tree_column, -1);

    /* second column */
    GtkCellRenderer *toggle_renderer = gtk_cell_renderer_toggle_new();
    g_signal_connect(toggle_renderer, "toggled",
                     G_CALLBACK(on_radio_toggled), tree_store);
    gtk_cell_renderer_toggle_set_radio(GTK_CELL_RENDERER_TOGGLE(toggle_renderer),
                                       TRUE);

    gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(tree_view), -1,
                                                _("Pin"), toggle_renderer,
                                                "active", COL_PIN, NULL);
    g_object_unref(tree_store);
}
/* Based on evolution/mail/message-list.c:filter_date() */
char *
rb_utf_friendly_time (time_t date)
{
    GDateTime *datetime, *now, *yesterday;
    int d, m, y;
    int nd, nm, ny;
    int yd, ym, yy;
    const char *format = NULL;
    char *str = NULL;

    if (date == 0) {
        return g_strdup (_("Never"));
    }

    now = g_date_time_new_now_local ();
    datetime = g_date_time_new_from_unix_local (date);

    g_date_time_get_ymd (datetime, &y, &m, &d);
    g_date_time_get_ymd (now, &ny, &nm, &nd);

    if (y == ny && m == nm && d == nd) {
        /* Translators: "friendly time" string for the current day, strftime format. like "Today 12:34 am" */
        format = _("Today %I:%M %p");
    }

    if (format == NULL) {
        yesterday = g_date_time_add_days (now, -1);

        g_date_time_get_ymd (yesterday, &yy, &ym, &yd);
        if (y == yy && m == ym && d == yd) {
            /* Translators: "friendly time" string for the previous day,
             * strftime format. e.g. "Yesterday 12:34 am"
             */
            format = _("Yesterday %I:%M %p");
        }
        g_date_time_unref (yesterday);
    }

    if (format == NULL) {
        int i;
        for (i = 2; i < 7; i++) {
            yesterday = g_date_time_add_days (now, -i);
            g_date_time_get_ymd (yesterday, &yy, &ym, &yd);
            if (y == yy && m == ym && d == yd) {
                /* Translators: "friendly time" string for a day in the current week,
                 * strftime format. e.g. "Wed 12:34 am"
                 */
                format = _("%a %I:%M %p");
                g_date_time_unref (yesterday);
                break;
            }
            g_date_time_unref (yesterday);
        }
    }

    if (format == NULL) {
        if (y == ny) {
            /* Translators: "friendly time" string for a day in the current year,
             * strftime format. e.g. "Feb 12 12:34 am"
             */
            format = _("%b %d %I:%M %p");
        } else {
            /* Translators: "friendly time" string for a day in a different year,
             * strftime format. e.g. "Feb 12 1997"
             */
            format = _("%b %d %Y");
        }
    }

    if (format != NULL) {
        str = g_date_time_format (datetime, format);
    }

    if (str == NULL) {
        /* impossible time or broken locale settings */
        str = g_strdup (_("Unknown"));
    }

    g_date_time_unref (datetime);
    g_date_time_unref (now);

    return str;
}
Exemple #28
0
/**
 * cheese_fileutil_get_new_media_filename:
 * @fileutil: a #CheeseFileUtil
 * @mode: the type of media to create a filename for
 *
 * Creates a filename for one of the three media types: photo, photo burst or
 * video. If a filename for a photo burst image was previously created, this
 * function increments the burst count automatically. To start a new burst,
 * first call cheese_fileutil_reset_burst().
 *
 * Returns: (transfer full) (type filename): a new filename
 */
gchar *
cheese_fileutil_get_new_media_filename (CheeseFileUtil *fileutil, CheeseMediaMode mode)
{
  GDateTime *datetime;
  gchar       *time_string;
  const gchar *path;
  gchar       *filename;
  GFile       *file;
  guint        num;
  CheeseFileUtilPrivate *priv;

  g_return_val_if_fail (CHEESE_IS_FILEUTIL (fileutil), NULL);

  priv = fileutil->priv;

  datetime = g_date_time_new_now_local ();

  g_assert (datetime != NULL);

  time_string = g_date_time_format (datetime, "%F-%H%M%S");
  g_date_time_unref (datetime);

  g_assert (time_string != NULL);

  switch (mode)
  {
    case CHEESE_MEDIA_MODE_PHOTO:
    case CHEESE_MEDIA_MODE_BURST:
      path = cheese_fileutil_get_photo_path (fileutil);
      break;
    case CHEESE_MEDIA_MODE_VIDEO:
      path = cheese_fileutil_get_video_path (fileutil);
      break;
    default:
      g_assert_not_reached ();
  }

  g_mkdir_with_parents (path, 0775);

  switch (mode)
  {
    case CHEESE_MEDIA_MODE_PHOTO:
      filename = g_strdup_printf ("%s%s%s%s", path, G_DIR_SEPARATOR_S, time_string, CHEESE_PHOTO_NAME_SUFFIX);
      break;
    case CHEESE_MEDIA_MODE_BURST:
      priv->burst_count++;
      if (strlen (priv->burst_raw_name) == 0)
        priv->burst_raw_name = g_strdup_printf ("%s%s%s", path, G_DIR_SEPARATOR_S, time_string);

      filename = g_strdup_printf ("%s_%d%s", priv->burst_raw_name, priv->burst_count, CHEESE_PHOTO_NAME_SUFFIX);
      break;
    case CHEESE_MEDIA_MODE_VIDEO:
      filename = g_strdup_printf ("%s%s%s%s", path, G_DIR_SEPARATOR_S, time_string, CHEESE_VIDEO_NAME_SUFFIX);
      break;
    default:
      g_assert_not_reached ();
  }

  file = g_file_new_for_path (filename);
  num = 0;

  while (g_file_query_exists (file, NULL))
  {
    num++;

    g_object_unref (file);
    g_free (filename);

    switch (mode)
    {
      case CHEESE_MEDIA_MODE_PHOTO:
        filename = g_strdup_printf ("%s%s%s (%d)%s", path, G_DIR_SEPARATOR_S, time_string, num, CHEESE_PHOTO_NAME_SUFFIX);
        break;
      case CHEESE_MEDIA_MODE_BURST:
        filename = g_strdup_printf ("%s_%d (%d)%s", priv->burst_raw_name, priv->burst_count, num, CHEESE_PHOTO_NAME_SUFFIX);
        break;
      case CHEESE_MEDIA_MODE_VIDEO:
        filename = g_strdup_printf ("%s%s%s (%d)%s", path, G_DIR_SEPARATOR_S, time_string, num, CHEESE_VIDEO_NAME_SUFFIX);
        break;
      default:
        g_assert_not_reached ();
    }

    file = g_file_new_for_path (filename);
  }

  g_free (time_string);
  g_object_unref (file);

  return filename;
}
Exemple #29
0
void spop_log_handler(const gchar* log_domain, GLogLevelFlags log_level, const gchar* message, gpointer user_data) {
    GString* log_line = NULL;
    GDateTime* datetime;
    gchar* timestr;

    GError* err = NULL;
    gchar* level = "";

    /* Convert log_level to a string */
    if (log_level & G_LOG_LEVEL_ERROR)
        level = "ERR ";
    else if (log_level & G_LOG_LEVEL_CRITICAL)
        level = "CRIT";
    else if (log_level & G_LOG_LEVEL_WARNING)
        level = "WARN";
    else if (log_level & G_LOG_LEVEL_MESSAGE)
        level = "MSG ";
    else if (log_level & G_LOG_LEVEL_INFO) {
        if (!verbose_mode) return;
        level = "INFO";
    }
    else if (log_level & G_LOG_LEVEL_DEBUG) {
        if (!debug_mode) return;
        level = "DBG ";
    }
    else if (log_level & G_LOG_LEVEL_LIBSPOTIFY)
        level = "SPTF";
    else
        g_warn_if_reached();

    /* Allocate memory and read date/time */
    log_line = g_string_sized_new(1024);
    if (!log_line)
        g_error("Can't allocate memory.");

    datetime = g_date_time_new_now_local();
    if (!datetime)
        g_error("Can't get the current date.");
    timestr = g_date_time_format(datetime, "%Y-%m-%d %H:%M:%S");
    if (!timestr)
        g_error("Can't format current date to a string.");

    /* Format the message that will be displayed and logged */
    if (log_domain)
        g_string_printf(log_line, "%s ", log_domain);
    g_string_append_printf(log_line, "%s [%s] %s\n", timestr, level, message);

    /* Free memory used by datetime and timestr */
    g_date_time_unref(datetime);
    g_free(timestr);

    /* First display to stderr... */
    fprintf(stderr, "%s", log_line->str);
    /* ... then to the log file. */
    if (g_log_channel) {
        if (g_io_channel_write_chars(g_log_channel, log_line->str, log_line->len, NULL, &err) != G_IO_STATUS_NORMAL)
            g_error("Can't write to log file: %s", err->message);
        if (g_io_channel_flush(g_log_channel, &err) != G_IO_STATUS_NORMAL)
            g_error("Can't flush log file: %s", err->message);
    }
}
static void
proxy_call_search_grlnet_async_cb (GObject *source_object,
                                   GAsyncResult *res,
                                   gpointer user_data)
{
  RaitvOperation    *op = (RaitvOperation *) user_data;
  xmlDocPtr           doc = NULL;
  xmlXPathContextPtr  xpath = NULL;
  xmlXPathObjectPtr   obj = NULL;
  gint i, nb_items = 0;
  gsize length;

  GRL_DEBUG ("Response id=%u", op->operation_id);

  GError *wc_error = NULL;
  GError *error = NULL;
  gchar *content = NULL;
  gboolean g_bVideoNotFound = TRUE;

  if (g_cancellable_is_cancelled (op->cancellable)) {
    goto finalize;
  }

  if (!grl_net_wc_request_finish (GRL_NET_WC (source_object),
                                  res,
                                  &content,
                                  &length,
                                  &wc_error)) {
    error = g_error_new (GRL_CORE_ERROR,
                         GRL_CORE_ERROR_SEARCH_FAILED,
                         _("Failed to search: %s"),
                         wc_error->message);

    op->callback (op->source,
                  op->operation_id,
                  NULL,
                  0,
                  op->user_data,
                  error);

   g_error_free (wc_error);
    g_error_free (error);

    return;
  }

  doc = xmlParseMemory (content, (gint) length);

  if (!doc) {
    GRL_DEBUG ("Doc failed");
    goto finalize;
  }

  xpath = xmlXPathNewContext (doc);
  if (!xpath) {
    GRL_DEBUG ("Xpath failed");
    goto finalize;
  }
  obj = xmlXPathEvalExpression ((xmlChar *) "/GSP/RES/R", xpath);
  if (obj)
    {
      nb_items = xmlXPathNodeSetGetLength (obj->nodesetval);
      xmlXPathFreeObject (obj);
    }

  for (i = 0; i < nb_items; i++)
    {
      //Search only videos
      gchar *str;
      str = g_strdup_printf ("string(/GSP/RES/R[%i]/MT[@N='videourl']/@V)",
                             i + 1);
      obj = xmlXPathEvalExpression ((xmlChar *) str, xpath);
      if (obj->stringval && obj->stringval[0] == '\0')
        continue;
      if(op->skip>0) {
        op->skip--;
        continue;
      }

      GrlRaitvSource *source = GRL_RAITV_SOURCE (op->source);
      GList *mapping = source->priv->raitv_search_mappings;
      GrlMedia *media = grl_media_video_new ();
      g_bVideoNotFound = FALSE;
      GRL_DEBUG ("Mappings count: %d",g_list_length(mapping));
      while (mapping)
        {
          RaitvAssoc *assoc = (RaitvAssoc *) mapping->data;
          str = g_strdup_printf ("string(/GSP/RES/R[%i]/%s)",
                                 i + 1, assoc->exp);

          GRL_DEBUG ("Xquery %s", str);
          gchar *strvalue;

          obj = xmlXPathEvalExpression ((xmlChar *) str, xpath);
          if (obj)
            {
              if (obj->stringval && obj->stringval[0] != '\0')
                {
                  strvalue = 	g_strdup((gchar *) obj->stringval);
                  //Sometimes GRL_METADATA_KEY_THUMBNAIL doesn't report complete url
                  if(assoc->grl_key == GRL_METADATA_KEY_THUMBNAIL && !g_str_has_prefix(strvalue,"http://www.rai.tv")) {
                    strvalue = g_strdup_printf("http://www.rai.tv%s",obj->stringval);
                  }

                  GType _type;
                  GRL_DEBUG ("\t%s -> %s", str, obj->stringval);
                  _type = grl_metadata_key_get_type (assoc->grl_key);
                  switch (_type)
                    {
                    case G_TYPE_STRING:
                      grl_data_set_string (GRL_DATA (media),
                                           assoc->grl_key,
                                           strvalue);
                      break;

                    case G_TYPE_INT:
                      grl_data_set_int (GRL_DATA (media),
                                        assoc->grl_key,
                                        (gint) atoi (strvalue));
                      break;

                    case G_TYPE_FLOAT:
                      grl_data_set_float (GRL_DATA (media),
                                          assoc->grl_key,
                                          (gfloat) atof (strvalue));
                      break;

                    default:
                      /* G_TYPE_DATE_TIME is not a constant, so this has to be
                       * in "default:" */
                      if (_type == G_TYPE_DATE_TIME) {
                        int year,month,day;
                        sscanf((const char*)obj->stringval, "%02d/%02d/%04d", &day, &month, &year);
                        GDateTime *date = g_date_time_new_local (year, month, day, 0, 0, 0);
                        GRL_DEBUG ("Setting %s to %s",
                                   grl_metadata_key_get_name (assoc->grl_key),
                                   g_date_time_format (date, "%F %H:%M:%S"));
                        grl_data_set_boxed (GRL_DATA (media),
                                            assoc->grl_key, date);
                        if(date) g_date_time_unref (date);
                      } else {
                        GRL_DEBUG ("\tUnexpected data type: %s",
                                   g_type_name (_type));
                      }
                      break;
                    }
                  g_free (strvalue);
                }
              xmlXPathFreeObject (obj);
            }

          g_free (str);

          mapping = mapping->next;
        }

      op->callback (op->source,
                    op->operation_id,
                    media,
                    --op->count,
                    op->user_data,
                    NULL);

      if (op->count == 0)
        break;
    }

 finalize:
  g_clear_pointer (&xpath, xmlXPathFreeContext);
  g_clear_pointer (&doc, xmlFreeDoc);

  /* Signal the last element if it was not already signaled */
  if (nb_items == 0 || g_bVideoNotFound) {
    op->callback (op->source,
                  op->operation_id,
                  NULL,
                  0,
                  op->user_data,
                  NULL);
  }
  else {
    //Continue the search
    if(op->count>0) {
		op->offset +=  nb_items;
		g_raitv_videos_search(op);
    }
  }

}