/**
 * camel_vee_summary_load_check_unread_vfolder:
 *
 * Since: 2.26
 **/
void
camel_vee_summary_load_check_unread_vfolder (CamelVeeSummary *vs)
{
	static gint only_once = FALSE;
	static gchar *exp = NULL;
	gboolean hacked_unread_folder = FALSE;
	CamelVeeFolder *vf;

	g_return_if_fail (vs != NULL);

	vf = (CamelVeeFolder *) ((CamelFolderSummary *)vs)->folder;

	/* HACK: Ugliest of all hacks. Its virtually not possible now
	 * to maintain counts and the non matching uids of unread vfolder here.
	 * So, I hardcode unread vfolder expression and hack it. */
	if (!only_once) {
		exp =  g_getenv("CAMEL_VFOLDER_UNREAD_EXP") ? g_strcompress(g_getenv("CAMEL_VFOLDER_UNREAD_EXP")) : NULL;
		only_once = TRUE;
	}

	if (!exp || !*exp)
		exp = g_strcompress (unread_str);

	if (vf->expression && strstr (exp, vf->expression) &&  (vf->flags & CAMEL_STORE_VEE_FOLDER_SPECIAL) == 0)
		hacked_unread_folder = TRUE;

	if (hacked_unread_folder)
		camel_vee_folder_set_unread_vfolder (vf, 1);
	else
		camel_vee_folder_set_unread_vfolder (vf, 0);
}
Esempio n. 2
0
static int
hexchat_pluginpref_get_str_real (hexchat_plugin *pl, const char *var, char *dest, int dest_len)
{
	char *confname, *canon, *cfg, *unescaped_value;
	char buf[512];

	canon = g_strdup (pl->name);
	canonalize_key (canon);
	confname = g_strdup_printf ("%s%caddon_%s.conf", get_xdir(), G_DIR_SEPARATOR, canon);
	g_free (canon);

	if (!g_file_get_contents (confname, &cfg, NULL, NULL))
	{
		g_free (confname);
		return 0;
	}
	g_free (confname);

	if (!cfg_get_str (cfg, var, buf, sizeof(buf)))
	{
		g_free (cfg);
		return 0;
	}

	unescaped_value = g_strcompress (buf);
	g_strlcpy (dest, unescaped_value, dest_len);

	g_free (unescaped_value);
	g_free (cfg);
	return 1;
}
Esempio n. 3
0
/* Looks up the given index in the hash table and removes enclosing quotes,
 * if any. Those are added again by the autogen template. */
void
cg_transform_string (GHashTable *table,
                     const gchar *index)
{
	gchar *str;
	gchar *unescaped;
	size_t len;

	str = g_hash_table_lookup (table, index);

	if (str != NULL)
	{
		len = strlen (str);
		if (len >= 2 && str[0] == '\"' && str[len - 1] == '\"')
		{
			/* Unescape string because it was most likely already escaped
			 * by the user because s/he also added quotes around it. */
			str = g_strndup (str + 1, len - 2);
			unescaped = g_strcompress (str);
			g_free (str);

			g_hash_table_insert (table, (gpointer) index, unescaped);
		}
	}
}
Esempio n. 4
0
static gchar *
get_object_name (const gchar *dir,
                 gchar       *filename,
                 void        *context)
{
  gchar *ret = NULL, *unprocessed_line = NULL;
  gchar *full_path = NULL;

  /* First try to extract the object's name (= user-friendly description)
   * from the preset file
   * */

  full_path = g_build_filename (dir, filename, NULL);

  unprocessed_line = get_early_line_from_preset (full_path, "name=");
  if (unprocessed_line)
    {
      ret = g_strcompress (unprocessed_line);
      g_free (unprocessed_line);
    }
  else
    {
      /* The object name defaults to a filename-derived description */
      ret = g_filename_display_basename (full_path);
    }

  g_free (full_path);

  return ret;
}
Esempio n. 5
0
/** Converts unicode strings such as \003d into =
  * Code blatantly nicked from the Facebook plugin */
gchar *
convert_unicode(const gchar *input)
{
	gunichar unicode_char;
	gchar unicode_char_str[6];
	gint unicode_char_len;
	gchar *next_pos;
	gchar *input_string;
	gchar *output_string;

	if (input == NULL)
		return NULL;

	next_pos = input_string = g_strdup(input);

	while ((next_pos = strstr(next_pos, "\\u")))
	{
		/* grab the unicode */
		sscanf(next_pos, "\\u%4x", &unicode_char);
		/* turn it to a char* */
		unicode_char_len = g_unichar_to_utf8(unicode_char, unicode_char_str);
		/* shove it back into the string */
		g_memmove(next_pos, unicode_char_str, unicode_char_len);
		/* move all the data after the \u0000 along */
		g_stpcpy(next_pos + unicode_char_len, next_pos + 6);
	}

	output_string = g_strcompress(input_string);
	g_free(input_string);

	return output_string;
}
/* Load a section from a keyfile to a hash-table
   (replace existing keys in the hash) */
static void
section_to_hash (GKeyFile *file, const gchar *section, GHashTable *hash)
{
    GError *error;
    gchar **keys;
    gint i;

    error = NULL;
    keys = g_key_file_get_keys (file, section, NULL, &error);
    if (error) {
        g_printf ("Error: Couldn't load configuration section %s!\n", section);
    }

    for (i = 0; keys[i] != NULL; i++) {
        gchar *uncompressed_value;

        uncompressed_value = g_key_file_get_value (file, section, keys[i],
                             NULL);
        g_hash_table_insert (hash,
                             g_strdup (keys[i]),
                             g_strcompress (uncompressed_value));
        g_free (uncompressed_value);
    }
    g_strfreev (keys);
}
static void
datetime_apply_options_cb(GtkWidget *widget, gpointer data)
{
    DatetimePlugin *datetime;
    const gchar *font_name;
    const gchar *format;

    g_return_if_fail (data != NULL);

    datetime = (DatetimePlugin *)data;

    font_name = gtk_button_get_label(GTK_BUTTON(datetime->font_selector));
    if (font_name != NULL) {
	PangoFontDescription *font;

	g_free(datetime->font);
	datetime->font = g_strdup(font_name);
	font = pango_font_description_from_string(datetime->font);
	gtk_widget_modify_font(datetime->label, font);
    }

    format = (gchar *)gtk_entry_get_text(GTK_ENTRY(datetime->format_entry));
    if (format != NULL) {
	g_free(datetime->format);
	datetime->format = g_strcompress(format);
    }
    datetime_update(datetime);
}
Esempio n. 8
0
/*
 * get list of children 
 */
GList* get_children (gchar* path)
{
	GList *children = NULL;
	
	gchar command[1000];
	result_class rc;
	gchar *record = NULL;
	gchar *pos = NULL;

	/* children number */
	sprintf(command, "-var-info-num-children \"%s\"", path);
	rc = exec_sync_command(command, TRUE, &record);
	if (RC_DONE != rc)
		return NULL;
	pos = strstr(record, "numchild=\"") + strlen("numchild=\"");
	*(strchr(pos, '\"')) = '\0';
	int numchild = atoi(pos);
	g_free(record);
	if (!numchild)
		return NULL;
	
	/* recursive get children and put into list */
	sprintf(command, "-var-list-children \"%s\"", path);
	rc = exec_sync_command(command, TRUE, &record);
	if (RC_DONE == rc)
	{
		pos = record;
		while ( (pos = strstr(pos, "child={")) )
		{
			gchar *name, *internal;
			
			/* name */
			pos = strstr(pos, "name=\"") + strlen("name=\"");
			*(strstr(pos, "\",exp=\"")) = '\0';
			internal = pos;
			pos += strlen(pos) + 1;

			/* exp */
			pos = strstr(pos, "exp=\"") + strlen("exp=\"");
			*(strstr(pos, "\",numchild=\"")) = '\0';
			
			name = g_strcompress(pos);
			
			variable *var = variable_new2(name, internal, VT_CHILD);
			var->evaluated = TRUE;
			
			pos += strlen(pos) + 1;

			children = g_list_prepend(children, var);
		
			g_free(name);
		}
	}
	g_free(record);
	
	get_variables(children);

	return children;
}
Esempio n. 9
0
/*
 * unescapes hex values (\0xXXX) to readable chars
 * converting it from wide character value to char
 */
static gchar* unescape_hex_values(gchar *src)
{
	GString *dest = g_string_new("");
	
	gchar *slash;
	while ( (slash = strstr(src, "\\x")) )
	{
		char hex[4] = { 0, 0, 0, '\0' };
		wchar_t wc;

		/* append what has been missed
		unescaping it in advance */
		if (slash - src)
		{
			gchar *missed = g_strndup(src, slash - src);
			gchar *unescaped = g_strcompress(missed);
			g_string_append(dest, unescaped);
			g_free(missed);
			g_free(unescaped);
		}

		strncpy(hex, slash + 2, 3);
		wc = (wchar_t)strtol(hex, NULL, 16);

		if (iswalpha(wc))
		{
			gchar mb[5];
			int len = wctomb(mb, wc);
			mb[len] = '\0';
			g_string_append(dest, mb);
		}
		else
			g_string_append_len(dest, slash, 5);
		
		src = slash + 5;
	}
	
	if (strlen(src))
	{
		gchar *unescaped = g_strcompress(src);
		g_string_append(dest, unescaped);
		g_free(unescaped);
	}

	return g_string_free(dest, FALSE);
}
Esempio n. 10
0
static void
parse_desc (const gchar *str, gchar *d, gssize d_len)
{
  gchar *dest = g_strcompress (str);

  g_strlcpy (d, dest, d_len);

  g_free (dest);
}
Esempio n. 11
0
gboolean read_char_option(const gchar *option, const gchar *label, const gchar *value, gchar **text)
{
	if (g_ascii_strcasecmp(option, label) != 0) return FALSE;
	if (!text) return FALSE;

	g_free(*text);
	*text = g_strcompress(value);
	return TRUE;
}
Esempio n. 12
0
static gchar *
unquote(gchar * quoted)
{
	gint len = quoted ? strlen(quoted) : 0;
	if (len && (quoted[0] == '"') && (quoted[len - 1] == '"'))
	{
		gchar *tmp = g_strndup(quoted + 1, len - 2);
		gchar *rv = g_strcompress(tmp);
		g_free(tmp);
		return rv;
	}
	else
		return NULL;
}
Esempio n. 13
0
static void dt_int_verify(GtkWidget *entry)
{
     char *txt = gtk_editable_get_chars(GTK_EDITABLE(entry), 0, -1);
     gunichar c = 0;

     if (txt) {
	  char *t;
	  GString *s	= g_string_sized_new(strlen(txt));
	  int nope	= 0;

	  /* strip leading whitespace */
	  for(t = txt, c = g_utf8_get_char(t) ;
	      g_unichar_isspace(c) ;
	      t = g_utf8_next_char(t), c = g_utf8_get_char(t)) {
	  }

	  /* one leading minus is OK */
	  if (c == g_utf8_get_char("-")) {
	       g_string_append_unichar(s, c);
	       t = g_utf8_next_char(t);
	       c = g_utf8_get_char(t);
	  }

	  /* allow only digits, no leading zeroes */
	  for(c = g_utf8_get_char(t) ;
	      c ;
	      t = g_utf8_next_char(t), c = g_utf8_get_char(t)) {
	       if (g_unichar_isdigit(c)) {
		    g_string_append_unichar(s, c);
	       } else {
		    nope = 1;
	       }
	  }
	  g_free(txt);

	  txt = g_strcompress(s->str); /* one-byte chars only */
	  if (strcmp(txt, "0") != 0) {
	       for(t = txt ; *t == '0' ; t++) nope = 1;
	       if (*t == 0 && txt != t) t--; /* must have zeros-only string */
	  }

	  if (nope) {
	       gtk_entry_set_text(GTK_ENTRY(entry), t);
	  }

	  g_string_free(s, TRUE);
     }
     return;
}
Esempio n. 14
0
File: reader.c Progetto: kanaka/mal
MalVal *read_atom(Reader *reader) {
    char *token;
    GRegex *regex;
    GMatchInfo *matchInfo;
    GError *err = NULL;
    gint pos;
    MalVal *atom;

    token = reader_next(reader);
    //g_print("read_atom token: %s\n", token);
    
    regex = g_regex_new ("(^-?[0-9]+$)|(^-?[0-9][0-9.]*$)|(^nil$)|(^true$)|(^false$)|^\"(.*)\"?$|:(.*)|(^[^\"]*$)", 0, 0, &err);
    g_regex_match (regex, token, 0, &matchInfo);

    if (g_match_info_fetch_pos(matchInfo, 1, &pos, NULL) && pos != -1) {
        //g_print("read_atom integer\n");
        atom = malval_new_integer(g_ascii_strtoll(token, NULL, 10));
    } else if (g_match_info_fetch_pos(matchInfo, 2, &pos, NULL) && pos != -1) {
        //g_print("read_atom float\n");
        atom = malval_new_float(g_ascii_strtod(token, NULL));
    } else if (g_match_info_fetch_pos(matchInfo, 3, &pos, NULL) && pos != -1) {
        //g_print("read_atom nil\n");
        atom = &mal_nil;
    } else if (g_match_info_fetch_pos(matchInfo, 4, &pos, NULL) && pos != -1) {
        //g_print("read_atom true\n");
        atom = &mal_true;
    } else if (g_match_info_fetch_pos(matchInfo, 5, &pos, NULL) && pos != -1) {
        //g_print("read_atom false\n");
        atom = &mal_false;
    } else if (g_match_info_fetch_pos(matchInfo, 6, &pos, NULL) && pos != -1) {
        //g_print("read_atom string: %s\n", token);
        int end = strlen(token)-1;
        if (token[end] != '"') { abort("expected '\"', got EOF"); }
        token[end] = '\0';
        atom = malval_new_string(g_strcompress(g_match_info_fetch(matchInfo, 6)));
    } else if (g_match_info_fetch_pos(matchInfo, 7, &pos, NULL) && pos != -1) {
        //g_print("read_atom keyword\n");
        atom = malval_new_keyword(MAL_GC_STRDUP(g_match_info_fetch(matchInfo, 7)));
    } else if (g_match_info_fetch_pos(matchInfo, 8, &pos, NULL) && pos != -1) {
        //g_print("read_atom symbol\n");
        atom = malval_new_symbol(MAL_GC_STRDUP(g_match_info_fetch(matchInfo, 8)));
    } else {
        malval_free(atom);
        atom = NULL;
    }

    return atom;
}
Esempio n. 15
0
/*
 * unescapes string, handles octal characters representations
 */
gchar* unescape_octal_values(gchar *text)
{
	GString *value = g_string_new("");
	
	gboolean utf8 = g_str_has_suffix(getenv("LANG"), "UTF-8");

	gchar *tmp = g_strdup(text);
	gchar *unescaped = g_strcompress(tmp);

	gchar *pos = unescaped;
	while (*pos)
	{
		if (isvalidcharacter(pos, utf8))
		{
			if (utf8)
			{
				/* valid utf8 character, copy to output
				 and move to the next character */
				gchar *next = g_utf8_next_char(pos);
				g_string_append_len(value, pos, next - pos);
				pos = next;
			}
			else
			{
				g_string_append_len(value, pos++, 1);
			}
		}
		else
		{
			/* not a valid character, convert it to its octal representation
			 and append to the result string */
			gchar *invalid = g_strndup(pos, 1);
			gchar *escaped = g_strescape(invalid, NULL);

			g_string_append(value, escaped);

			g_free(escaped);
			g_free(invalid);

			pos += 1;
		}
	}

	g_free(tmp);

	return g_string_free (value, FALSE);
}
Esempio n. 16
0
static void
datetime_read_config(Control *control, xmlNodePtr node)
{
    DatetimePlugin *datetime;
    xmlChar *value;

    g_return_if_fail (control != NULL);
    g_return_if_fail (node != NULL);

    datetime = (DatetimePlugin*)control->data;

    node = node->children;
    if (node == NULL || !xmlStrEqual(node->name, (const xmlChar *)"Date"))
	return;

    node = node->children;
    while (node != NULL) {
	if (xmlStrEqual(node->name, (const xmlChar *)"Font")) {
	    value = xmlNodeListGetString(xmlconfig, node->children, 1);
	    if (value != NULL) {
		PangoFontDescription *font;

		g_free(datetime->font);
		datetime->font = g_strdup(value);
		xmlFree(value);

		font = pango_font_description_from_string(datetime->font);
		gtk_widget_modify_font(datetime->label, font);
	    }
	} else if (xmlStrEqual(node->name, (const xmlChar *)"Format")) {
	    value = xmlNodeListGetString(xmlconfig, node->children, 1);
	    if (value != NULL) {
		g_free(datetime->format);
		datetime->format = g_strcompress(value);
		xmlFree(value);
	    }
	}
	node = node->next;
    }
    datetime_update(datetime);
}
Esempio n. 17
0
static void
section_to_hash (GKeyFile *file, const gchar *section, GHashTable *hash)
{
	GError *error = NULL;
	gchar **keys;
	gint i;

	keys = g_key_file_get_keys (file, section, NULL, &error);

	/* Only asserts with broken hard coded configuration file. */
	g_assert (error == NULL);

	for (i = 0; keys[i] != NULL; i++) {
		gchar *value;

		value = g_key_file_get_value (file, section, keys[i], NULL);
		g_hash_table_insert (hash, g_strdup (keys[i]), g_strcompress (value));
		g_free (value);
	}
	g_strfreev (keys);
}
Esempio n. 18
0
/*
 * unescapes value string, handles hexidecimal and octal characters representations
 */
gchar *unescape(gchar *text)
{
	gchar *retval = NULL;

	/* create string copy */
	gchar *value = g_strdup(text);

	/* make first unescaping */
	gchar *tmp = g_strcompress(value);

	/* make first unescaping */
	if (strstr(tmp, "\\x"))
		retval = unescape_hex_values(tmp);
	else
		retval = unescape_octal_values(tmp);

	g_free(tmp);
	g_free(value);

	return retval;
}
Esempio n. 19
0
gboolean
gtk_scan_string (const char **pos, GString *out)
{
  const char *p = *pos, *q = *pos;
  char *tmp, *tmp2;
  gboolean quoted;

  while (g_ascii_isspace (*p))
    p++;

  if (!*p)
    return FALSE;
  else if (*p == '"')
    {
      p++;
      quoted = FALSE;
      for (q = p; (*q != '"') || quoted; q++)
        {
          if (!*q)
            return FALSE;
          quoted = (*q == '\\') && !quoted;
        }

      tmp = g_strndup (p, q - p);
      tmp2 = g_strcompress (tmp);
      g_string_truncate (out, 0);
      g_string_append (out, tmp2);
      g_free (tmp);
      g_free (tmp2);
    }

  q++;
  *pos = q;

  return TRUE;
}
Esempio n. 20
0
gint
yad_print_run (void)
{
  GtkWidget *dlg;
  GtkWidget *box, *img, *lbl;
  gchar *uri, *job_name = NULL;
  GtkPrintCapabilities pcap;
  GtkPrintOperationAction act = GTK_PRINT_OPERATION_ACTION_PRINT;
  gint resp, ret = 0;
  GError *err = NULL;

  /* check if file is exists */
  if (options.common_data.uri && options.common_data.uri[0])
    {
      if (!g_file_test (options.common_data.uri, G_FILE_TEST_EXISTS))
        {
          g_printerr (_("File %s not found.\n"), options.common_data.uri);
          return 1;
        }
    }
  else
    {
      g_printerr (_("Filename is not specified.\n"));
      return 1;
    }

  /* create print dialog */
  dlg = gtk_print_unix_dialog_new (options.data.dialog_title, NULL);
  gtk_window_set_type_hint (GTK_WINDOW (dlg), GDK_WINDOW_TYPE_HINT_NORMAL);
  gtk_print_unix_dialog_set_embed_page_setup (GTK_PRINT_UNIX_DIALOG (dlg), TRUE);
  pcap = GTK_PRINT_CAPABILITY_PAGE_SET | GTK_PRINT_CAPABILITY_COPIES |
    GTK_PRINT_CAPABILITY_COLLATE | GTK_PRINT_CAPABILITY_REVERSE |
    GTK_PRINT_CAPABILITY_NUMBER_UP | GTK_PRINT_CAPABILITY_NUMBER_UP_LAYOUT;
  if (options.common_data.preview && options.print_data.type != YAD_PRINT_RAW)
    pcap |= GTK_PRINT_CAPABILITY_PREVIEW;
  gtk_print_unix_dialog_set_manual_capabilities (GTK_PRINT_UNIX_DIALOG (dlg), pcap);

  if (!settings.print_settings)
    settings.print_settings = gtk_print_unix_dialog_get_settings (GTK_PRINT_UNIX_DIALOG (dlg));

  uri = g_build_filename (g_get_current_dir (), "yad.pdf", NULL);
  gtk_print_settings_set (settings.print_settings, "output-uri", g_filename_to_uri (uri, NULL, NULL));
  g_free (uri);

  gtk_print_unix_dialog_set_settings (GTK_PRINT_UNIX_DIALOG (dlg), settings.print_settings);

  if (settings.page_setup)
    gtk_print_unix_dialog_set_page_setup (GTK_PRINT_UNIX_DIALOG (dlg), settings.page_setup);

  /* set window behavior */
  gtk_widget_set_name (dlg, "yad-dialog-window");
  if (options.data.sticky)
    gtk_window_stick (GTK_WINDOW (dlg));
  gtk_window_set_resizable (GTK_WINDOW (dlg), !options.data.fixed);
  gtk_window_set_keep_above (GTK_WINDOW (dlg), options.data.ontop);
  gtk_window_set_decorated (GTK_WINDOW (dlg), !options.data.undecorated);
  gtk_window_set_skip_taskbar_hint (GTK_WINDOW (dlg), options.data.skip_taskbar);
  gtk_window_set_skip_pager_hint (GTK_WINDOW (dlg), options.data.skip_taskbar);

  /* set window size and position */
  if (!options.data.geometry)
    {
      gtk_window_set_default_size (GTK_WINDOW (dlg), options.data.width, options.data.height);
      if (options.data.center)
        gtk_window_set_position (GTK_WINDOW (dlg), GTK_WIN_POS_CENTER);
      else if (options.data.mouse)
        gtk_window_set_position (GTK_WINDOW (dlg), GTK_WIN_POS_MOUSE);
    }
  else
    {
      /* parse geometry, if given. must be after showing widget */
      gtk_widget_realize (dlg);
      gtk_window_parse_geometry (GTK_WINDOW (dlg), options.data.geometry);
    }

  /* create yad's top box */
  if (options.data.dialog_text || options.data.dialog_image)
    {
#if !GTK_CHECK_VERSION(3,0,0)
      box = gtk_hbox_new (FALSE, 0);
#else
      box = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
#endif

      if (options.data.dialog_image)
        {
          GdkPixbuf *pb = NULL;

          pb = get_pixbuf (options.data.dialog_image, YAD_BIG_ICON);
          img = gtk_image_new_from_pixbuf (pb);
          if (pb)
            g_object_unref (pb);

          gtk_widget_set_name (img, "yad-dialog-image");
          gtk_box_pack_start (GTK_BOX (box), img, FALSE, FALSE, 2);
        }
      if (options.data.dialog_text)
        {
          gchar *buf = g_strcompress (options.data.dialog_text);

          lbl = gtk_label_new (NULL);
          if (!options.data.no_markup)
            gtk_label_set_markup (GTK_LABEL (lbl), buf);
          else
            gtk_label_set_text (GTK_LABEL (lbl), buf);
          gtk_widget_set_name (lbl, "yad-dialog-label");
          gtk_label_set_selectable (GTK_LABEL (lbl), options.data.selectable_labels);
          gtk_misc_set_alignment (GTK_MISC (lbl), options.data.text_align, 0.5);
          if (options.data.geometry || options.data.width != -1)
            gtk_label_set_line_wrap (GTK_LABEL (lbl), TRUE);
          gtk_box_pack_start (GTK_BOX (box), lbl, TRUE, TRUE, 2);
          g_signal_connect (G_OBJECT (lbl), "size-allocate", G_CALLBACK (size_allocate_cb), NULL);
          g_free (buf);
        }

      /* add tob box to dialog */
      gtk_widget_show_all (box);
      gtk_box_pack_start (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (dlg))), box, TRUE, TRUE, 5);
      gtk_box_reorder_child (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (dlg))), box, 0);
    }

  do
    {
      resp = gtk_dialog_run (GTK_DIALOG (dlg));
      switch (resp)
        {
        case GTK_RESPONSE_APPLY:   /* ask for preview */
          act = GTK_PRINT_OPERATION_ACTION_PREVIEW;
        case GTK_RESPONSE_OK:      /* run print */
          settings.print_settings = gtk_print_unix_dialog_get_settings (GTK_PRINT_UNIX_DIALOG (dlg));
          settings.page_setup = gtk_print_unix_dialog_get_page_setup (GTK_PRINT_UNIX_DIALOG (dlg));
          job_name = g_strdup_printf ("yad-%s-%d", g_path_get_basename (options.common_data.uri), getpid ());
          if (options.print_data.type != YAD_PRINT_RAW)
            {
              /* print text or image */
              GtkPrintOperation *op = gtk_print_operation_new ();
              gtk_print_operation_set_unit (op, GTK_UNIT_POINTS);
              gtk_print_operation_set_print_settings (op, settings.print_settings);
              gtk_print_operation_set_default_page_setup (op, settings.page_setup);
              gtk_print_operation_set_job_name (op, job_name);

              switch (options.print_data.type)
                {
                case YAD_PRINT_TEXT:
                  g_signal_connect (G_OBJECT (op), "begin-print", G_CALLBACK (begin_print_text), NULL);
                  g_signal_connect (G_OBJECT (op), "draw-page", G_CALLBACK (draw_page_text), NULL);
                  break;
                case YAD_PRINT_IMAGE:
                  gtk_print_operation_set_n_pages (op, 1);
                  g_signal_connect (G_OBJECT (op), "draw-page", G_CALLBACK (draw_page_image), NULL);
                  break;
                default:;
                }

              if (gtk_print_operation_run (op, act, NULL, &err) == GTK_PRINT_OPERATION_RESULT_ERROR)
                {
                  g_printerr (_("Printing failed: %s\n"), err->message);
                  ret = 1;
                }
            }
          else
            {
              /* print raw ps or pdf data */
              GtkPrinter *prnt;
              GtkPrintJob *job;

              prnt = gtk_print_unix_dialog_get_selected_printer (GTK_PRINT_UNIX_DIALOG (dlg));

              if (g_str_has_suffix (options.common_data.uri, ".ps"))
                {
                  if (!gtk_printer_accepts_ps (prnt))
                    {
                      g_printerr (_("Printer doesn't support ps format.\n"));
                      ret = 1;
                    }
                }
              else if (g_str_has_suffix (options.common_data.uri, ".pdf"))
                {
                  if (!gtk_printer_accepts_pdf (prnt))
                    {
                      g_printerr (_("Printer doesn't support pdf format.\n"));
                      ret = 1;
                    }
                }
              else
                {
                  g_printerr (_("This file type is not supported for raw printing.\n"));
                  ret = 1;
                }
              if (ret == 1)
                break;

              job = gtk_print_job_new (job_name, prnt, settings.print_settings, settings.page_setup);
              if (gtk_print_job_set_source_file (job, options.common_data.uri, &err))
                {
                  gtk_print_job_send (job, (GtkPrintJobCompleteFunc) raw_print_done, &ret, NULL);
                  gtk_main ();
                }
              else
                {
                  g_printerr (_("Load source file failed: %s\n"), err->message);
                  ret = 1;
                }
            }
          break;
        default:
          ret = 1;
          break;
        }
    }
  while (resp == GTK_RESPONSE_APPLY);

  gtk_widget_destroy (dlg);
  write_settings ();
  return ret;
}
Esempio n. 21
0
void zenity_forms_dialog (ZenityData *data, ZenityFormsData *forms_data)
{
  GtkBuilder *builder = NULL;
  GtkWidget *dialog;
  GtkWidget *grid;
  GtkWidget *text;
  GtkWidget *button;

  GSList *tmp;

  int list_count = 0;
  int combo_count = 0;
  int i = 0;

  zen_data = data;

  builder = zenity_util_load_ui_file("zenity_forms_dialog", NULL);

  if (builder == NULL) {
    data->exit_code = zenity_util_return_exit_code (ZENITY_ERROR);
    return;
  }

  gtk_builder_connect_signals(builder, NULL);
  
  dialog = GTK_WIDGET (gtk_builder_get_object (builder, "zenity_forms_dialog"));

  g_signal_connect (G_OBJECT(dialog), "response",
                    G_CALLBACK (zenity_forms_dialog_response), forms_data);
  
  if (data->dialog_title)
    gtk_window_set_title (GTK_WINDOW (dialog), data->dialog_title);

  if (data->width > -1 || data->height > -1)
    gtk_window_set_default_size (GTK_WINDOW (dialog), data->width, data->height);

  if (data->extra_label) {
    gint i=0;
    while(data->extra_label[i]!=NULL){
      gtk_dialog_add_button (GTK_DIALOG (dialog), data->extra_label[i], i);
      i++;
    }
  }

  if (data->ok_label) {
    button = GTK_WIDGET (gtk_builder_get_object (builder, "zenity_forms_ok_button"));
    gtk_button_set_label (GTK_BUTTON (button), data->ok_label);
  }  

  if (data->cancel_label) {
    button = GTK_WIDGET (gtk_builder_get_object (builder, "zenity_forms_cancel_button"));
    gtk_button_set_label (GTK_BUTTON (button), data->cancel_label);
  }

  text = GTK_WIDGET (gtk_builder_get_object (builder, "zenity_forms_text"));

  if (forms_data->dialog_text)
    gtk_label_set_markup (GTK_LABEL (text), g_strcompress (forms_data->dialog_text));
  
  grid = GTK_WIDGET (gtk_builder_get_object (builder, "zenity_forms_grid"));

  for (tmp = forms_data->list; tmp; tmp = tmp->next) {
    ZenityFormsValue *zenity_value = (ZenityFormsValue *) tmp->data;
    GtkWidget *label;

    gchar **values = g_strsplit_set (zenity_value->option_value, "|", 2);
    gchar *label_text = values[0];
    gchar *prefill_text = values[1];
    
    label = gtk_label_new(label_text);
    gtk_widget_set_halign (label, GTK_ALIGN_START);
    gtk_grid_attach (GTK_GRID (grid),
                     label,
                     0, i,
                     1, 1);

    switch(zenity_value->type)
    {
      case ZENITY_FORMS_ENTRY:
        zenity_value->forms_widget = gtk_entry_new();
        if (prefill_text) {
          gtk_entry_set_text(GTK_ENTRY(zenity_value->forms_widget),
                               prefill_text);
        }
        break;
      case ZENITY_FORMS_PASSWORD:
        zenity_value->forms_widget = gtk_entry_new();
        gtk_entry_set_visibility(GTK_ENTRY(zenity_value->forms_widget), 
                                 FALSE);
        break;
      case ZENITY_FORMS_CALENDAR:
        zenity_value->forms_widget = gtk_calendar_new();
        break;
      case ZENITY_FORMS_LIST:
          zenity_value->forms_widget = zenity_forms_create_and_fill_list (forms_data, list_count,
                                                                          zenity_value->option_value);
          list_count++;                                                                           
        break;
      case ZENITY_FORMS_COMBO:
          zenity_value->forms_widget = zenity_forms_create_and_fill_combo (forms_data, combo_count);
          combo_count++;
        break;             
      default:
        zenity_value->forms_widget = gtk_entry_new();
        break;
    }

    g_strfreev(values);

    gtk_grid_attach_next_to (GTK_GRID (grid),
                             GTK_WIDGET (zenity_value->forms_widget),
                             label,
                             GTK_POS_RIGHT,
                             1, 1);
    
    i++;
  }

  gtk_widget_show_all (GTK_WIDGET (dialog));
  
  g_object_unref (builder);

  if (data->timeout_delay > 0) {
    g_timeout_add_seconds (data->timeout_delay, (GSourceFunc) zenity_util_timeout_handle, dialog);
  }

  gtk_main();
}
Esempio n. 22
0
gchar *dropbox_client_util_desanitize(const gchar *a) {
  return g_strcompress(a);
}
Esempio n. 23
0
/*
 * starts gdb, collects commands and start the first one
 */
gboolean run(const gchar* file, const gchar* commandline, GList* env, GList *witer, GList *biter, const gchar* terminal_device, dbg_callbacks* callbacks)
{
	GError *err = NULL;

	dbg_cbs = callbacks;

	/* spawn GDB */
	const gchar *exclude[] = { "LANG", NULL };
	gchar **gdb_env = utils_copy_environment(exclude, "LANG", "C", NULL);
	if (!g_spawn_async_with_pipes(NULL, (gchar**)gdb_args, gdb_env,
				     GDB_SPAWN_FLAGS, NULL,
				     NULL, &gdb_pid, &gdb_in, &gdb_out, NULL, &err))
	{
		dbg_cbs->report_error(_("Failed to spawn gdb process"));
		return FALSE;
	}
	g_strfreev(gdb_env);
	
	/* move gdb to it's own process group */
	setpgid(gdb_pid, 0);
	
	/* set handler for gdb process exit event */ 
	g_child_watch_add(gdb_pid, on_gdb_exit, NULL);
	gdb_src = g_child_watch_source_new(gdb_pid);

	/* create GDB GIO chanels */
	gdb_ch_in = g_io_channel_unix_new(gdb_in);
	gdb_ch_out = g_io_channel_unix_new(gdb_out);

	/* reading starting gdb messages */
	GList *lines = read_until_prompt();
	GList *line = lines;
	while (line)
	{
		gchar *unescaped = g_strcompress((gchar*)line->data);
		if (strlen(unescaped))
		{
			colorize_message((gchar*)line->data);
		}
		line = line->next;
	}
	g_list_foreach(lines, (GFunc)g_free, NULL);
	g_list_free(lines);

	/* add initial watches to the list */
	while (witer)
	{
		gchar *name = (gchar*)witer->data;

		variable *var = variable_new(name, VT_WATCH);
		watches = g_list_append(watches, var);
		
		witer = witer->next;
	}

	/* collect commands */
	GList *commands = NULL;

	/* loading file */
	GString *command = g_string_new("");
	g_string_printf(command, "-file-exec-and-symbols %s", file);
	commands = add_to_queue(commands, _("~\"Loading target file ...\""), command->str, _("Error loading file"), FALSE);
	g_string_free(command, TRUE);

	/* setting asyncronous mode */
	commands = add_to_queue(commands, NULL, "-gdb-set target-async 1", _("Error configuring GDB"), FALSE);

	/* setting null-stop array printing */
	commands = add_to_queue(commands, NULL, "-interpreter-exec console \"set print null-stop\"", _("Error configuring GDB"), FALSE);

	/* enable pretty printing */
	commands = add_to_queue(commands, NULL, "-enable-pretty-printing", _("Error configuring GDB"), FALSE);

	/* set locale */
	command = g_string_new("");
	g_string_printf(command, "-gdb-set environment LANG=%s", g_getenv("LANG"));
	commands = add_to_queue(commands, NULL, command->str, NULL, FALSE);
	g_string_free(command, TRUE);

	/* set arguments */
	command = g_string_new("");
	g_string_printf(command, "-exec-arguments %s", commandline);
	commands = add_to_queue(commands, NULL, command->str, NULL, FALSE);
	g_string_free(command, TRUE);

	/* set passed evironment */
	GList *iter = env;
	while (iter)
	{
		gchar *name = (gchar*)iter->data;
		iter = iter->next;
		
		gchar *value = (gchar*)iter->data;
	
		command = g_string_new("");
		g_string_printf(command, "-gdb-set environment %s=%s", name, value);

		commands = add_to_queue(commands, NULL, command->str, NULL, FALSE);
		g_string_free(command, TRUE);

		iter = iter->next;
	}

	/* set breaks */
	int bp_index = 1;
	while (biter)
	{
		breakpoint *bp = (breakpoint*)biter->data;
		command = g_string_new("");
		g_string_printf(command, "-break-insert -f %s:%i", bp->file, bp->line);

		GString *error_message = g_string_new("");
		g_string_printf(error_message, _("Breakpoint at %s:%i cannot be set\nDebugger message: %s"), bp->file, bp->line, "%s");
		
		commands = add_to_queue(commands, NULL, command->str, error_message->str, TRUE);

		g_string_free(command, TRUE);
		g_string_free(error_message, TRUE);

		if (bp->hitscount)
		{
			command = g_string_new("");
			g_string_printf(command, "-break-after %i %i", bp_index, bp->hitscount);
			commands = add_to_queue(commands, NULL, command->str, error_message->str, TRUE);
			g_string_free(command, TRUE);
		}
		if (strlen(bp->condition))
		{
			command = g_string_new("");
			g_string_printf (command, "-break-condition %i %s", bp_index, bp->condition);
			commands = add_to_queue(commands, NULL, command->str, error_message->str, TRUE);
			g_string_free(command, TRUE);
		}
		if (!bp->enabled)
		{
			command = g_string_new("");
			g_string_printf (command, "-break-disable %i", bp_index);
			commands = add_to_queue(commands, NULL, command->str, error_message->str, TRUE);
			g_string_free(command, TRUE);
		}

		bp_index++;
		biter = biter->next;
	}

	/* set debugging terminal */
	command = g_string_new("-inferior-tty-set ");
	g_string_append(command, terminal_device);
	commands = add_to_queue(commands, NULL, command->str, NULL, FALSE);
	g_string_free(command, TRUE);

	/* connect read callback to the output chanel */
	gdb_id_out = g_io_add_watch(gdb_ch_out, G_IO_IN, on_read_async_output, commands);

	queue_item *item = (queue_item*)commands->data;

	/* send message to debugger messages window */
	if (item->message)
	{
		dbg_cbs->send_message(item->message->str, "grey");
	}

	/* send first command */
	gdb_input_write_line(item->command->str);

	return TRUE;
}
Esempio n. 24
0
/*
 * execute "command" syncronously
 * i.e. reading output right
 * after execution
 */ 
result_class exec_sync_command(const gchar* command, gboolean wait4prompt, gchar** command_record)
{

#ifdef DEBUG_OUTPUT
	dbg_cbs->send_message(command, "red");
#endif

	/* write command to gdb input channel */
	gdb_input_write_line(command);
	
	if (!wait4prompt)
		return RC_DONE;
	
	GList *lines = read_until_prompt();

#ifdef DEBUG_OUTPUT
	GList *line = lines;
	while (line)
	{
		dbg_cbs->send_message((gchar*)line->data, "red");
		line = line->next;
	}
#endif

	result_class rc = RC_ERROR;
	GList *iter = lines;

	while (iter)
	{
		gchar *line = (gchar*)iter->data;

		if ('^' == line[0])
		{
			gchar* coma = strchr(line, ',');
			if (coma)
			{
				*coma = '\0';
				coma++;
			}
			else
				coma = line + strlen(line);
			
			if (command_record)
			{
				*command_record = (gchar*)g_malloc(strlen(coma) + 1);
				strcpy(*command_record, coma);
			}
			
			if (!strcmp(line, "^done"))
				rc = RC_DONE;
			else if (!strcmp(line, "^error"))
			{
				/* save error message */
				gchar* msg = g_strcompress(strstr(coma, "msg=\"") + strlen("msg=\""));
				strcpy(err_message, msg);
				g_free(msg);
				
				rc = RC_ERROR;
			}
			else if (!strcmp(line, "^exit"))
				rc = RC_EXIT;
		}
		else if ('&' != line[0])
		{
			colorize_message (line);
		}

		iter = iter->next;
	}	
	
	g_list_foreach(lines, (GFunc)g_free, NULL);
	g_list_free(lines);
	
	return rc;
}
Esempio n. 25
0
static gboolean on_read_from_gdb(GIOChannel * src, GIOCondition cond, gpointer data)
{
	gchar *line;
	gsize length;
	
	if (G_IO_STATUS_NORMAL != g_io_channel_read_line(src, &line, NULL, &length, NULL))
		return TRUE;		

	gboolean prompt = !strcmp(line, GDB_PROMPT);
	
	*(line + length) = '\0';

	if (!prompt)
	{
		if ('~' == line[0])
		{
			colorize_message(line);
		}
		else
		{
			gchar *compressed = g_strcompress(line);
			colorize_message(compressed);
			g_free(compressed);
		}
	}
		
	if (!target_pid && g_str_has_prefix(line, "=thread-group-created"))
	{
		*(strrchr(line, '\"')) = '\0';
		target_pid = atoi(line + strlen("=thread-group-created,id=\""));
	}
	else if (g_str_has_prefix(line, "=thread-created"))
	{
		*(strrchr(line, ',') - 1) = '\0';
		int thread_id = atoi(line + strlen("=thread-created,id=\""));
		dbg_cbs->add_thread(thread_id);
	}
	else if (g_str_has_prefix(line, "=thread-exited"))
	{
		*(strrchr(line, ',') - 1) = '\0';
		int thread_id = atoi(line + strlen("=thread-exited,id=\""));
		dbg_cbs->remove_thread(thread_id);
	}
	else if (g_str_has_prefix(line, "=library-loaded") || g_str_has_prefix(line, "=library-unloaded"))
	{
		file_refresh_needed = TRUE;
	}
	else if (*line == '*')
	{
		/* asyncronous record found */
		char *record = NULL;
		if ( (record = strchr(line, ',')) )
		{
			*record = '\0';
			record++;
		}
		else
			record = line + strlen(line);
		
		if (!strcmp(line, "*running"))
			dbg_cbs->set_run();
		else if (!strcmp(line, "*stopped"))
		{
			/* removing read callback (will pulling all output left manually) */
			g_source_remove(gdb_id_out);

			/* looking for a reason to stop */
			char *next = NULL;
			char *reason = strstr(record, "reason=\"");
			if (reason)
			{
				reason += strlen("reason=\"");
				next = strstr(reason, "\"") + 1;
				*(next - 1) = '\0';
				if (!strcmp(reason, "breakpoint-hit"))
					stop_reason = SR_BREAKPOINT_HIT;
				else if (!strcmp(reason, "end-stepping-range"))
					stop_reason = SR_END_STEPPING_RANGE;
				else if (!strcmp(reason, "signal-received"))
					stop_reason = SR_SIGNAL_RECIEVED;
				else if (!strcmp(reason, "exited-normally"))
					stop_reason = SR_EXITED_NORMALLY;
				else if (!strcmp(reason, "exited-signalled"))
					stop_reason = SR_EXITED_SIGNALLED;
			}
			else
			{
				/* somehow, sometimes there can be no stop reason */
				stop_reason = SR_END_STEPPING_RANGE;
			}
			
			if (SR_BREAKPOINT_HIT == stop_reason || SR_END_STEPPING_RANGE == stop_reason || SR_SIGNAL_RECIEVED == stop_reason)
			{
				gchar *thread_id = strstr(reason + strlen(reason) + 1,"thread-id=\"") + strlen("thread-id=\"");
				*(strchr(thread_id, '\"')) = '\0'; 
				
				if (SR_BREAKPOINT_HIT == stop_reason || SR_END_STEPPING_RANGE == stop_reason)
				{
					/* update autos */
					update_autos();
			
					/* update watches */
					update_watches();
			
					/* update files */
					if (file_refresh_needed)
					{
						update_files();
						file_refresh_needed = FALSE;
					}

					dbg_cbs->set_stopped(atoi(thread_id));
				}
				else
				{
					if (!requested_interrupt)
						dbg_cbs->report_error(_("Program received a signal"));
					else
						requested_interrupt = FALSE;
						
					dbg_cbs->set_stopped(atoi(thread_id));
				}
			}
			else if (stop_reason == SR_EXITED_NORMALLY || stop_reason == SR_EXITED_SIGNALLED)
			{
				stop();
			}
		}
	}
	else if (g_str_has_prefix (line, "^error"))
	{
		/* removing read callback (will pulling all output left manually) */
		g_source_remove(gdb_id_out);

		/* set debugger stopped if is running */
		if (DBS_STOPPED != debug_get_state())
		{
			gchar *thread_id = strstr(line + strlen(line) + 1,"thread-id=\"");
			*(strchr(thread_id, '\"')) = '\0'; 

			dbg_cbs->set_stopped(atoi(thread_id));
		}

		/* get message */
		char *msg = strstr(line, "msg=\"") + strlen("msg=\"");
		*strrchr(msg, '\"') = '\0';
		msg = g_strcompress(msg);
		
		/* reading until prompt */
		GList *lines = read_until_prompt();
		GList *iter = lines;
		while(iter)
		{
			gchar *l = (gchar*)iter->data;
			if (strcmp(l, GDB_PROMPT))
				colorize_message(l);
			g_free(l);
			
			iter = iter->next;
		}
		g_list_free (lines);

		/* send error message */
		dbg_cbs->report_error(msg);

		g_free(msg);
	}

	g_free(line);

	return TRUE;
}
Esempio n. 26
0
static gboolean on_read_async_output(GIOChannel * src, GIOCondition cond, gpointer data)
{
	gchar *line;
	gsize length;
	
	if (G_IO_STATUS_NORMAL != g_io_channel_read_line(src, &line, NULL, &length, NULL))
		return TRUE;		

	*(line + length) = '\0';

	if ('^' == line[0])
	{
		/* got some result */

		g_source_remove(gdb_id_out);

		GList *lines = read_until_prompt();
		g_list_foreach(lines, (GFunc)g_free, NULL);
		g_list_free (lines);

		gchar* coma = strchr(line, ',');
		if (coma)
		{
			*coma = '\0';
			coma++;
		}
		else
			coma = line + strlen(line);
		
		GList *commands = (GList*)data;

		if (!strcmp(line, "^done"))
		{
			/* command completed succesfully - run next command if exists */
			if (commands->next)
			{
				/* if there are commads left */
				commands = commands->next;
				queue_item *item = (queue_item*)commands->data;

				/* send message to debugger messages window */
				if (item->message)
				{
					dbg_cbs->send_message(item->message->str, "grey");
				}

				gdb_input_write_line(item->command->str);

				gdb_id_out = g_io_add_watch(gdb_ch_out, G_IO_IN, on_read_async_output, commands);
			}
			else
			{
				/* all commands completed */
				free_commands_queue(commands);

				/* removing read callback */
				g_source_remove(gdb_id_out);

				/* update source files list */
				update_files();

				/* -exec-run */
				exec_async_command("-exec-run &");
			}
		}
		else
		{
			queue_item *item = (queue_item*)commands->data;
			if(item->error_message)
			{
				if (item->format_error_message)
				{
					gchar* gdb_msg = g_strcompress(strstr(coma, "msg=\"") + strlen("msg=\""));

					GString *msg = g_string_new("");
					g_string_printf(msg, item->error_message->str, gdb_msg);
					dbg_cbs->report_error(msg->str);

					g_free(gdb_msg);
					g_string_free(msg, FALSE);
				}
				else
				{
					dbg_cbs->report_error(item->error_message->str);
				}
			}
			
			/* free commands queue */
			free_commands_queue(commands);

			stop();
		}
	}

	g_free(line);

	return TRUE;
}
Esempio n. 27
0
void
create_plug (void)
{
    GtkWidget *win, *vbox, *text;
    GtkWidget *main_widget = NULL;

    tabs = get_tabs (options.plug, FALSE);
    while (!tabs)
    {
        usleep (1000);
        tabs = get_tabs (options.plug, FALSE);
    }

    win = gtk_plug_new (0);
    /* set window borders */
    if (options.data.borders == -1)
        options.data.borders = (gint) gtk_container_get_border_width (GTK_CONTAINER (win));
    gtk_container_set_border_width (GTK_CONTAINER (win), (guint) options.data.borders);

#if !GTK_CHECK_VERSION(3,0,0)
    vbox = gtk_vbox_new (FALSE, 0);
#else
    vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0);
#endif
    gtk_container_add (GTK_CONTAINER (win), vbox);

    /* add dialog text */
    if (options.data.dialog_text)
    {
        gchar *buf = g_strcompress (options.data.dialog_text);

        text = gtk_label_new (NULL);
        if (!options.data.no_markup)
            gtk_label_set_markup (GTK_LABEL (text), buf);
        else
            gtk_label_set_text (GTK_LABEL (text), buf);
        gtk_widget_set_name (text, "yad-dialog-label");
        gtk_label_set_line_wrap (GTK_LABEL (text), TRUE);
        gtk_label_set_selectable (GTK_LABEL (text), options.data.selectable_labels);
        gtk_label_set_justify (GTK_LABEL (text), options.data.text_align);
        switch (options.data.text_align)
        {
        case GTK_JUSTIFY_LEFT:
        case GTK_JUSTIFY_FILL:
            gtk_misc_set_alignment (GTK_MISC (text), 0.0, 0.5);
            break;
        case GTK_JUSTIFY_CENTER:
            gtk_misc_set_alignment (GTK_MISC (text), 0.5, 0.5);
            break;
        case GTK_JUSTIFY_RIGHT:
            gtk_misc_set_alignment (GTK_MISC (text), 1.0, 0.5);
            break;
        }
        gtk_box_pack_start (GTK_BOX (vbox), text, FALSE, FALSE, 2);
#if !GTK_CHECK_VERSION(3,0,0)
        g_signal_connect (G_OBJECT (text), "size-allocate", G_CALLBACK (text_size_allocate_cb), NULL);
#endif

        g_free (buf);
    }

    /* add main widget */
    switch (options.mode)
    {
    case YAD_MODE_CALENDAR:
        main_widget = calendar_create_widget (win);
        break;
    case YAD_MODE_COLOR:
        main_widget = color_create_widget (win);
        break;
    case YAD_MODE_ENTRY:
        main_widget = entry_create_widget (win);
        break;
    case YAD_MODE_FILE:
        main_widget = file_create_widget (win);
        break;
    case YAD_MODE_FONT:
        main_widget = font_create_widget (win);
        break;
    case YAD_MODE_FORM:
        main_widget = form_create_widget (win);
        break;
#ifdef HAVE_HTML
    case YAD_MODE_HTML:
        main_widget = html_create_widget (win);
        break;
#endif
    case YAD_MODE_ICONS:
        main_widget = icons_create_widget (win);
        break;
    case YAD_MODE_LIST:
        main_widget = list_create_widget (win);
        break;
    case YAD_MODE_MULTI_PROGRESS:
        main_widget = multi_progress_create_widget (win);
        break;
    case YAD_MODE_PROGRESS:
        main_widget = progress_create_widget (win);
        break;
    case YAD_MODE_SCALE:
        main_widget = scale_create_widget (win);
        break;
    case YAD_MODE_TEXTINFO:
        main_widget = text_create_widget (win);
        break;
    default:
        ;
    }
    if (main_widget)
        gtk_box_pack_start (GTK_BOX (vbox), main_widget, TRUE, TRUE, 2);

    gtk_widget_show_all (win);

    /* add plug data */
    tabs[options.tabnum].pid = getpid ();
    tabs[options.tabnum].xid = gtk_plug_get_id (GTK_PLUG (win));
    /* FIXME: may be a race here */
    tabs[0].xid++;
    shmdt (tabs);
}
Esempio n. 28
0
static gboolean
handle_stdin (GIOChannel * channel, GIOCondition condition, gpointer data)
{
  if ((condition & G_IO_IN) != 0)
    {
      GString *string;
      GError *err = NULL;

      string = g_string_new (NULL);
      while (channel->is_readable == FALSE);

      do
        {
          gint status;
          gchar *command = NULL, *value = NULL, **args;

          do
            {
              status = g_io_channel_read_line_string (channel, string, NULL, &err);

              while (gdk_events_pending ())
                gtk_main_iteration ();
            }
          while (status == G_IO_STATUS_AGAIN);

          if (status != G_IO_STATUS_NORMAL)
            {
              if (err)
                {
                  g_printerr ("yad_notification_handle_stdin(): %s\n", err->message);
                  g_error_free (err);
                  err = NULL;
                }
              /* stop handling but not exit */
              g_io_channel_shutdown (channel, TRUE, NULL);
              return FALSE;
            }

          strip_new_line (string->str);
          if (!string->str[0])
            continue;

          args = g_strsplit (string->str, ":", 2);
          command = g_strdup (args[0]);
          if (args[1])
            value = g_strdup (args[1]);
          g_strfreev (args);
          if (value)
            g_strstrip (value);

          if (!g_ascii_strcasecmp (command, "icon") && value)
            {
              g_free (icon);
              icon = g_strdup (value);

              if (gtk_status_icon_get_visible (status_icon) && gtk_status_icon_is_embedded (status_icon))
                set_icon ();
            }
          else if (!g_ascii_strcasecmp (command, "tooltip"))
            {
              if (g_utf8_validate (value, -1, NULL))
                {
                  gchar *message = g_strcompress (value);
                  if (!options.data.no_markup)
                    gtk_status_icon_set_tooltip_markup (status_icon, message);
                  else
                    gtk_status_icon_set_tooltip_text (status_icon, message);
                  g_free (message);
                }
              else
                g_printerr (_("Invalid UTF-8 in tooltip!\n"));
            }
          else if (!g_ascii_strcasecmp (command, "visible"))
            {
#if !GTK_CHECK_VERSION(2,22,0)
              if (!g_ascii_strcasecmp (value, "blink"))
                {
                  gboolean state = gtk_status_icon_get_blinking (status_icon);
                  gtk_status_icon_set_blinking (status_icon, !state);
                }
              else
#endif
              if (!g_ascii_strcasecmp (value, "false"))
                {
                  gtk_status_icon_set_visible (status_icon, FALSE);
#if !GTK_CHECK_VERSION(2,22,0)
                  gtk_status_icon_set_blinking (status_icon, FALSE);
#endif
                }
              else
                {
                  gtk_status_icon_set_visible (status_icon, TRUE);
#if !GTK_CHECK_VERSION(2,22,0)
                  gtk_status_icon_set_blinking (status_icon, FALSE);
#endif
                }
            }
          else if (!g_ascii_strcasecmp (command, "action"))
            {
              g_free (action);
              if (value)
                action = g_strdup (value);
            }
          else if (!g_ascii_strcasecmp (command, "quit"))
            {
              exit_code = YAD_RESPONSE_OK;
              gtk_main_quit ();
            }
          else if (!g_ascii_strcasecmp (command, "menu"))
            {
              if (value)
                parse_menu_str (value);
            }
          else
            g_printerr (_("Unknown command '%s'\n"), command);

          g_free (command);
          g_free (value);
        }
      while (g_io_channel_get_buffer_condition (channel) == G_IO_IN);
      g_string_free (string, TRUE);
    }

  if ((condition & G_IO_HUP) != 0)
    {
      g_io_channel_shutdown (channel, TRUE, NULL);
      gtk_main_quit ();
      return FALSE;
    }

  return TRUE;
}
Esempio n. 29
0
gint
main (gint argc, gchar ** argv)
{
    GOptionContext *ctx;
    GError *err = NULL;
    gint w, h;
    gchar *str;
    gint ret = 0;

    setlocale (LC_ALL, "");

#ifdef ENABLE_NLS
    bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
    bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
    textdomain (GETTEXT_PACKAGE);
#endif

#if !GLIB_CHECK_VERSION(2,36,0)
    g_type_init ();
#endif
    read_settings ();

    gtk_init (&argc, &argv);
    g_set_application_name ("YAD");
    yad_options_init ();

    ctx = yad_create_context ();
    /* parse YAD_OPTIONS */
    if (g_getenv ("YAD_OPTIONS"))
    {
        gchar *cmd, **args = NULL;
        gint cnt;

        cmd = g_strdup_printf ("yad %s", g_getenv ("YAD_OPTIONS"));

        if (g_shell_parse_argv (cmd, &cnt, &args, &err))
        {
            g_option_context_parse (ctx, &cnt, &args, &err);
            if (err)
            {
                g_printerr (_("Unable to parse YAD_OPTIONS: %s\n"), err->message);
                g_error_free (err);
                err = NULL;
            }
        }
        else
        {
            g_printerr (_("Unable to parse YAD_OPTIONS: %s\n"), err->message);
            g_error_free (err);
            err = NULL;
        }

        g_free (cmd);
    }
    /* parse command line */
    g_option_context_parse (ctx, &argc, &argv, &err);
    if (err)
    {
        g_printerr (_("Unable to parse command line: %s\n"), err->message);
        return -1;
    }
    yad_set_mode ();

    /* parse custom gtkrc */
    if (options.gtkrc_file)
        gtk_rc_parse (options.gtkrc_file);

    /* set default icons and icon theme */
    if (options.data.icon_theme)
    {
        settings.icon_theme = gtk_icon_theme_new ();
        gtk_icon_theme_set_custom_theme (settings.icon_theme, options.data.icon_theme);
    }
    else
        settings.icon_theme = gtk_icon_theme_get_default ();
    gtk_icon_size_lookup (GTK_ICON_SIZE_DIALOG, &w, &h);
    settings.big_fallback_image =
        gtk_icon_theme_load_icon (settings.icon_theme, "yad", MIN (w, h), GTK_ICON_LOOKUP_GENERIC_FALLBACK, NULL);
    gtk_icon_size_lookup (GTK_ICON_SIZE_MENU, &w, &h);
    settings.small_fallback_image =
        gtk_icon_theme_load_icon (settings.icon_theme, "yad", MIN (w, h), GTK_ICON_LOOKUP_GENERIC_FALLBACK, NULL);

    /* correct separators */
    str = g_strcompress (options.common_data.separator);
    options.common_data.separator = str;
    str = g_strcompress (options.common_data.item_separator);
    options.common_data.item_separator = str;

    /* loads an extra arguments, if specified */
    if (options.rest_file)
    {
        GIOChannel *ioc;
        gchar *buf;
        guint len, line = 0;

        g_strfreev (options.extra_data);
        options.extra_data = NULL;

        ioc = g_io_channel_new_file (options.rest_file, "r", NULL);
        while (TRUE)
        {
            gint status = g_io_channel_read_line (ioc, &buf, NULL, NULL, NULL);

            if (status != G_IO_STATUS_NORMAL)
                break;

            /* remove \n at the end of string */
            len = strlen (buf);
            if (buf[len - 1] == '\n')
                buf[len - 1] = '\0';

            /* add line to arguments array */
            options.extra_data = g_realloc (options.extra_data, (line + 2) * sizeof (gchar *));
            options.extra_data[line] = g_strcompress (buf);
            options.extra_data[line + 1] = NULL;

            g_free (buf);
            line++;
        }
        g_io_channel_shutdown (ioc, FALSE, NULL);
    }

#ifndef G_OS_WIN32
    /* add YAD_PID variable */
    str = g_strdup_printf ("%d", getpid ());
    g_setenv ("YAD_PID", str, TRUE);
    /* set signal handlers */
    signal (SIGUSR1, sa_usr1);
    signal (SIGUSR2, sa_usr2);
#endif

    /* plug mode */
    if (options.plug != -1)
    {
        create_plug ();
        gtk_main ();
        shmdt (tabs);
        return ret;
    }

    switch (options.mode)
    {
    case YAD_MODE_ABOUT:
        ret = yad_about ();
        break;

    case YAD_MODE_VERSION:
        g_print ("%s (GTK+ %d.%d.%d)\n", VERSION, gtk_major_version, gtk_minor_version, gtk_micro_version);
        break;

    case YAD_MODE_NOTIFICATION:
        ret = yad_notification_run ();
        break;

    case YAD_MODE_PRINT:
        ret = yad_print_run ();
        break;

#ifdef HAVE_HTML
    case YAD_MODE_HTML:
        /* Webkit doesn't handle focus for child dialogs when gtk_dialog_run() is used */
        /* FIXME: maybe this solution must be expanded to all dialogs */
        dialog = create_dialog ();
        g_signal_connect (G_OBJECT (dialog), "response", G_CALLBACK (html_response_cb), &ret);

        gtk_widget_show_all (dialog);

        gtk_main ();
        break;
#endif

    default:
        dialog = create_dialog ();

#ifndef G_OS_WIN32
        /* add YAD_XID variable */
        str = g_strdup_printf ("0x%X", GDK_WINDOW_XID (gtk_widget_get_window (dialog)));
        g_setenv ("YAD_XID", str, TRUE);
#endif

        if (options.mode == YAD_MODE_FILE)
        {
            /* show custom confirmation dialog */
            g_signal_connect (G_OBJECT (dialog), "response", G_CALLBACK (confirm_overwrite_cb), NULL);
        }
        else if (options.mode == YAD_MODE_NOTEBOOK)
            notebook_swallow_childs ();
        else if (options.mode == YAD_MODE_PANED)
            paned_swallow_childs ();

        ret = gtk_dialog_run (GTK_DIALOG (dialog));
        if (options.data.always_print)
            print_result ();
        else if (ret != YAD_RESPONSE_TIMEOUT && ret != YAD_RESPONSE_ESC)
        {
            /* standard OK button pressed */
            if (ret == YAD_RESPONSE_OK && options.data.buttons == NULL)
                print_result ();
            /* custom even button pressed */
            else if (options.data.buttons && !(ret & 1))
                print_result ();
        }
#ifndef G_OS_WIN32
        if (options.mode == YAD_MODE_NOTEBOOK)
            notebook_close_childs ();
        else if (options.mode == YAD_MODE_PANED)
            paned_close_childs ();
        /* autokill option for progress dialog */
        if (!options.kill_parent)
        {
            if ((options.mode == YAD_MODE_PROGRESS || options.mode == YAD_MODE_MULTI_PROGRESS) &&
                    options.progress_data.autokill && ret != YAD_RESPONSE_OK)
                kill (getppid (), SIGHUP);
        }
#endif
    }

#ifndef G_OS_WIN32
    /* NSIG defined in signal.h */
    if (options.kill_parent > 0 && options.kill_parent < NSIG)
        kill (getppid (), options.kill_parent);
#endif

    return ret;
}
Esempio n. 30
0
int
main (int argc, char *argv[])
{
        static const char  *summary = NULL;
        char               *body;
        static const char  *type = NULL;
        static char        *app_name = NULL;
        static char        *icon_str = NULL;
        static char        *icons = NULL;
        static char       **n_text = NULL;
        static char       **hints = NULL;
        static gboolean     do_version = FALSE;
        static gboolean     hint_error = FALSE;
        static glong        expire_timeout = NOTIFY_EXPIRES_DEFAULT;
        GOptionContext     *opt_ctx;
        NotifyNotification *notify;
        GError             *error = NULL;
        gboolean            retval;

        static const GOptionEntry entries[] = {
                {"urgency", 'u', 0, G_OPTION_ARG_CALLBACK,
                 g_option_arg_urgency_cb,
                 N_("Specifies the urgency level (low, normal, critical)."),
                 N_("LEVEL")},
                {"expire-time", 't', 0, G_OPTION_ARG_INT, &expire_timeout,
                 N_
                 ("Specifies the timeout in milliseconds at which to expire the "
                  "notification."), N_("TIME")},
                {"app-name", 'a', 0, G_OPTION_ARG_STRING, &app_name,
                 N_("Specifies the app name for the icon"), N_("APP_NAME")},
                {"icon", 'i', 0, G_OPTION_ARG_FILENAME, &icons,
                 N_("Specifies an icon filename or stock icon to display."),
                 N_("ICON[,ICON...]")},
                {"category", 'c', 0, G_OPTION_ARG_FILENAME, &type,
                 N_("Specifies the notification category."),
                 N_("TYPE[,TYPE...]")},
                {"hint", 'h', 0, G_OPTION_ARG_FILENAME_ARRAY, &hints,
                 N_
                 ("Specifies basic extra data to pass. Valid types are int, double, string and byte."),
                 N_("TYPE:NAME:VALUE")},
                {"version", 'v', 0, G_OPTION_ARG_NONE, &do_version,
                 N_("Version of the package."),
                 NULL},
                {G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY,
                 &n_text, NULL,
                 NULL},
                {NULL}
        };

        body = NULL;

        g_type_init ();

        g_set_prgname (argv[0]);
        g_log_set_always_fatal (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL);

        opt_ctx = g_option_context_new (N_("<SUMMARY> [BODY] - "
                                           "create a notification"));
        g_option_context_add_main_entries (opt_ctx, entries, GETTEXT_PACKAGE);
        retval = g_option_context_parse (opt_ctx, &argc, &argv, &error);
        g_option_context_free (opt_ctx);

        if (!retval) {
                fprintf (stderr, "%s\n", error->message);
                g_error_free (error);
                exit (1);
        }

        if (do_version) {
                g_printf ("%s %s\n", g_get_prgname (), VERSION);
                exit (0);
        }

        if (n_text != NULL && n_text[0] != NULL && *n_text[0] != '\0')
                summary = n_text[0];

        if (summary == NULL) {
                fprintf (stderr, "%s\n", N_("No summary specified."));
                exit (1);
        }

        if (n_text[1] != NULL) {
                body = g_strcompress (n_text[1]);

                if (n_text[2] != NULL) {
                        fprintf (stderr, "%s\n",
                                 N_("Invalid number of options."));
                        exit (1);
                }
        }

        if (icons != NULL) {
                char           *c;

                /* XXX */
                if ((c = strchr (icons, ',')) != NULL)
                        *c = '\0';

                icon_str = icons;
        }

        if (!notify_init ("notify-send"))
                exit (1);

        notify = notify_notification_new (summary,
                                          body,
                                          icon_str);
        notify_notification_set_category (notify, type);
        notify_notification_set_urgency (notify, urgency);
        notify_notification_set_timeout (notify, expire_timeout);
        notify_notification_set_app_name (notify, app_name);

        g_free (body);

        /* Set hints */
        if (hints != NULL) {
                gint            i = 0;
                gint            l;
                char          *hint = NULL;
                char         **tokens = NULL;

                while ((hint = hints[i++])) {
                        tokens = g_strsplit (hint, ":", -1);
                        l = g_strv_length (tokens);

                        if (l != 3) {
                                fprintf (stderr, "%s\n",
                                         N_("Invalid hint syntax specified. "
                                            "Use TYPE:NAME:VALUE."));
                                hint_error = TRUE;
                        } else {
                                retval = notify_notification_set_hint_variant (notify,
                                                                               tokens[0],
                                                                               tokens[1],
                                                                               tokens[2],
                                                                               &error);

                                if (!retval) {
                                        fprintf (stderr, "%s\n", error->message);
                                        g_error_free (error);
                                        hint_error = TRUE;
                                }
                        }

                        g_strfreev (tokens);
                        if (hint_error)
                                break;
                }
        }

        if (!hint_error)
                notify_notification_show (notify, NULL);

        g_object_unref (G_OBJECT (notify));

        notify_uninit ();

        exit (hint_error);
}