コード例 #1
0
ファイル: gnc-period-select.c プロジェクト: Mechtilde/gnucash
/*  Set the fiscal year end on a GncPeriodSelect widget.  If set to a
 *  value other than NULL then widget will include fiscal accounting
 *  period like "this fiscal year".
 */
void
gnc_period_select_set_fy_end (GncPeriodSelect *period, const GDate *fy_end)
{
    GncPeriodSelectPrivate *priv;
    const gchar *label;
    gint i;

    g_return_if_fail(period != NULL);
    g_return_if_fail(GNC_IS_PERIOD_SELECT(period));

    priv = GNC_PERIOD_SELECT_GET_PRIVATE(period);
    if (priv->fy_end)
        g_date_free(priv->fy_end);

    if (fy_end)
    {
        priv->fy_end = g_date_new_dmy(g_date_get_day(fy_end),
                                      g_date_get_month(fy_end),
                                      G_DATE_BAD_YEAR);
    }
    else
    {
        priv->fy_end = NULL;
    }

    if (fy_end)
    {
        for (i = GNC_ACCOUNTING_PERIOD_CYEAR_LAST; i < GNC_ACCOUNTING_PERIOD_FYEAR_LAST; i++)
        {
            label = priv->start ? _(start_strings[i]) : _(end_strings[i]);
            gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(priv->selector), label);
        }
    }
    else
    {
        for (i = GNC_ACCOUNTING_PERIOD_FYEAR_LAST - 1; i >= GNC_ACCOUNTING_PERIOD_FYEAR_LAST; i--)
        {
            gtk_combo_box_text_remove(GTK_COMBO_BOX_TEXT(priv->selector), i);
        }
    }
}
コード例 #2
0
ファイル: testcalendar.c プロジェクト: sam-m888/gtk
static void
calendar_date_to_string (CalendarData *data,
			      char         *buffer,
			      gint          buff_len)
{
  GDate *date;
  guint year, month, day;

  gtk_calendar_get_date (GTK_CALENDAR(data->window),
			 &year, &month, &day);
  if (g_date_valid_dmy (day, month + 1, year))
    {
      date = g_date_new_dmy (day, month + 1, year);
      g_date_strftime (buffer, buff_len-1, "%x", date);
      g_date_free (date);
    }
  else
    {
      g_snprintf (buffer, buff_len - 1, "%d/%d/%d (invalid)", month + 1, day, year);
    }
}
コード例 #3
0
ファイル: gpakeyexpireop.c プロジェクト: gpg/gpa
static void 
gpa_key_expire_operation_done_cb (GpaContext *context,
                                  gpg_error_t err,
                                  GpaKeyExpireOperation *op)
{
  if (! err)
    /* The expiration was changed.  */
    g_signal_emit_by_name (op, "new_expiration", 
			   GPA_KEY_OPERATION (op)->current->data, op->date);

  /* Clean previous date.  */
  if (op->date)
    {
      g_date_free (op->date);
      op->date = NULL;
    }
  /* Go to the next key.  */
  GPA_KEY_OPERATION (op)->current = g_list_next
    (GPA_KEY_OPERATION (op)->current);
  gpa_key_expire_operation_next (op);
}
コード例 #4
0
ファイル: annum-shell-window.c プロジェクト: GNOME/annum
static void date_changed_cb (AnnumShellWindow *self,
			     GnomeCalendarViewType view,
			     AnnumShellView *shell_view)
{
	const char *view_id;
	ECalendar *date_navigator;
	GDate *today;
	GDate start;
	GDate end;

	if (view != GNOME_CAL_DAY_VIEW)
		return;

	/* Week_View also uses GNOME_CAL_DAY_VIEW, so make sure */
	view_id = e_shell_view_get_view_id (E_SHELL_VIEW (shell_view));
	if (!g_strcmp0 (view_id, "Week_View"))
		return;

	/* DAY_VIEW is treated specially, because we only want to have
	 * the button toggled if we are showing today, not any other
	 * day
	 */

	date_navigator = annum_shell_sidebar_get_date_navigator (ANNUM_SHELL_SIDEBAR (self->priv->sidebar));

	today = g_date_new ();
	g_date_set_time_t (today, time (NULL));

	e_calendar_item_get_selection (date_navigator->calitem,
				       &start, &end);

	if (g_date_compare (today, &start) || g_date_compare (&start, &end)) {
		GtkAction *action = gtk_action_group_get_action (self->priv->action_group,
								 "ShowDay");
		gtk_radio_action_set_current_value (GTK_RADIO_ACTION (action),
						    ANNUM_VIEW_DAY);
	}

	g_date_free (today);
}
コード例 #5
0
ファイル: libarchive_archive.c プロジェクト: SpOOnman/claws
gboolean before_date(time_t msg_mtime, const gchar* before) {
    gchar*      pos = NULL;
    GDate*      date;
    GDate*      file_t;
    gboolean    res;
#if !GLIB_CHECK_VERSION(2,10,0)
    GTime       gtime;
#endif

    debug_print("Cut-off date: %s\n", before);
    if ((date = iso2GDate(before)) == NULL) {
        g_warning("Bad date format: %s\n", before);
        return FALSE;
    }

    file_t = g_date_new();
#if GLIB_CHECK_VERSION(2,10,0)
    g_date_set_time_t(file_t, msg_mtime);
#else
    gtime = (GTime) msg_mtime;
    g_date_set_time(file_t, gtime);
#endif

    if (debug_get_mode()) {
        pos = g_new0(char, 100);
        g_date_strftime(pos, 100, "%F", file_t);
        fprintf(stderr, "File date: %s\n", pos);
        g_free(pos);
    }

    if (! g_date_valid(file_t)) {
        g_warning("Invalid msg date\n");
        return FALSE;
    }

    res = (g_date_compare(file_t, date) >= 0) ? FALSE : TRUE;
    g_date_free(file_t);
    return res;
}
コード例 #6
0
static void
dialog_response (GtkDialog *dialog,
    gint response,
    TpawCalendarButton *self)
{
  GDate *date;
  guint year, month, day;

  if (response != GTK_RESPONSE_OK)
    goto out;

  gtk_calendar_get_date (GTK_CALENDAR (self->priv->calendar),
      &year, &month, &day);
  date = g_date_new_dmy (day, month + 1, year);

  tpaw_calendar_button_set_date (self, date);

  g_date_free (date);

out:
  gtk_widget_hide (GTK_WIDGET (dialog));
}
コード例 #7
0
static void
on_calendar_entry_activated(GtkWidget *widget, GtkWidget *calendar)
{
    GDate *date;
    const gchar *text;

    date = g_date_new();

    text = gtk_entry_get_text(GTK_ENTRY(widget));
    g_date_set_parse(date, text);

    if (g_date_valid(date)) {
	gtk_calendar_freeze(GTK_CALENDAR(calendar));
	gtk_calendar_select_month(GTK_CALENDAR(calendar),
				  g_date_get_month(date) - 1,
				  g_date_get_year(date));
	gtk_calendar_select_day(GTK_CALENDAR(calendar),
				g_date_get_day(date));
	gtk_calendar_thaw(GTK_CALENDAR(calendar));
    }
    g_date_free(date);
}
コード例 #8
0
/**
 * set the final_date of the reconcile
 * the value is dupplicate in memory (so parameter can be freed after)
 *
 * \param reconcile_number the number of the reconcile
 * \param date the final_date of the reconcile
 *
 * \return TRUE if ok or FALSE if problem
 * */
gboolean gsb_data_reconcile_set_final_date ( gint reconcile_number,
                        const GDate *date )
{
    struct_reconcile *reconcile;

    reconcile = gsb_data_reconcile_get_structure ( reconcile_number );

    if (!reconcile)
	return FALSE;

    /* we free the last date */
    if ( reconcile -> reconcile_final_date )
        g_date_free (reconcile -> reconcile_final_date);

    /* and copy the new one */
    reconcile -> reconcile_final_date = gsb_date_copy (date);

    /* retrie la liste */
    reconcile_list = g_list_sort ( reconcile_list, (GCompareFunc) gsb_data_reconcile_cmp_int );

    return TRUE;
}
コード例 #9
0
ファイル: calendar_utils.c プロジェクト: rosedu/osmo
guint
month_name_to_number (gchar *month_str) {

GDate *cdate;
gint i;
gboolean found;
char tmpbuf[BUFFER_SIZE];

    found = FALSE;
    cdate = g_date_new_dmy (1, 1, 1);
	g_return_val_if_fail (cdate != NULL, -1);

	for (i = G_DATE_JANUARY; i <= G_DATE_DECEMBER; i++) {
		g_date_set_month (cdate, i);
		g_date_strftime (tmpbuf, BUFFER_SIZE, "%B", cdate);
		if (!strcmp (month_str, tmpbuf)) {
			found = TRUE;
			break;
		}
	}
	g_date_free (cdate);
	return (found == TRUE ? i : -1);
}
コード例 #10
0
ファイル: utils.c プロジェクト: rosedu/osmo
guint
utl_get_weekend_days_in_month (const GDate *date)
{
	GDate *tmpdate = NULL;
	guint i, day, days, weekend_days;

	tmpdate = g_date_new_dmy (1, g_date_get_month (date), g_date_get_year (date));
	g_return_val_if_fail (tmpdate != NULL, 0);

	days = utl_date_get_days_in_month (tmpdate);
	weekend_days = 0;

	for (i = 1; i <= days; i++) {
		g_date_set_day (tmpdate, i);
		day = g_date_get_weekday (tmpdate);
		if (day == G_DATE_SATURDAY || day == G_DATE_SUNDAY) {
			weekend_days++;
		}
	}

	g_date_free (tmpdate);
	return weekend_days;
}
コード例 #11
0
static void
accum_time_attribute (GString *buffer,
                      EContact *contact,
                      const gchar *html_label,
                      EContactField field,
                      const gchar *icon,
                      guint html_flags)
{
	EContactDate *date;
	GDate *gdate = NULL;
	gchar sdate[100];

	date = e_contact_get (contact, field);
	if (date) {
		gdate = g_date_new_dmy (
			date->day,
			date->month,
			date->year);
		g_date_strftime (sdate, 100, "%x", gdate);
		g_date_free (gdate);
		render_table_row (buffer, html_label, sdate, icon, html_flags);
		e_contact_date_free (date);
	}
}
コード例 #12
0
ファイル: bi_import.c プロジェクト: nishmu/gnucash
//! \brief try to fix some common errors in the csv representation of invoices
//! * corrects the date format
//! * corrects ambigous values in multi line invoices
//! * ensures customer exists
//! * if quantity is unset, set to 1
//! * if price is unset, delete row
void
gnc_bi_import_fix_bis (GtkListStore * store, guint * fixed, guint * deleted,
                       GString * info, gchar *type)
{
    GtkTreeIter iter;
    gboolean valid, row_deleted, row_fixed;
    gchar *id, *date_opened, *date_posted, *owner_id, *date, *quantity, *price;
    GString *prev_id, *prev_date_opened, *prev_date_posted, *prev_owner_id, *prev_date;	// needed to fix multi line invoices
    guint dummy;

    // allow the call to this function with only GtkListeStore* specified
    if (!fixed)
        fixed = &dummy;
    if (!deleted)
        deleted = &dummy;

    *fixed = 0;
    *deleted = 0;

    // init strings
    prev_id = g_string_new ("");
    prev_date_opened = g_string_new ("");
    prev_date_posted = g_string_new ("");
    prev_owner_id = g_string_new ("");
    prev_date = g_string_new ("");

    valid = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (store), &iter);
    while (valid)
    {
        row_deleted = FALSE;
        row_fixed = FALSE;

        // Walk through the list, reading each row
        gtk_tree_model_get (GTK_TREE_MODEL (store), &iter,
                            ID, &id,
                            DATE_OPENED, &date_opened,
                            DATE_POSTED, &date_posted,
                            OWNER_ID, &owner_id,
                            DATE, &date,
                            QUANTITY, &quantity, PRICE, &price, -1);

        if (strlen (price) == 0)
        {
            // invalid row (no price given)
            // no fix possible -> delete row
            gtk_list_store_remove (store, &iter);
            row_deleted = TRUE;
            g_string_append_printf (info,
                                    _("ROW DELETED, PRICE_NOT_SET: id=%s\n"),
                                    id);
        }
        else if (strlen (quantity) == 0)
        {
            // invalid row (no quantity given)
            // no fix possible -> delete row
            gtk_list_store_remove (store, &iter);
            row_deleted = TRUE;
            g_string_append_printf (info, _("ROW DELETED, QTY_NOT_SET: id=%s\n"),
                                    id);
        }
        else
        {
            if (strlen (id) == 0)
            {
                // no invoice id specified
                if (prev_id->len == 0)
                {
                    // cannot fix -> delete row
                    gtk_list_store_remove (store, &iter);
                    row_deleted = TRUE;
                    g_string_append_printf (info,
                                            _("ROW DELETED, ID_NOT_SET\n"));
                }
                else
                {
                    // this is a fixable multi line invoice
                    gtk_list_store_set (store, &iter, ID, prev_id->str, -1);
                    row_fixed = TRUE;
                }
            }
            else
            {
                // remember invoice id (to be able to fix multi line invoices)
                g_string_assign (prev_id, id);
                // new invoice => reset all other fixable entries
                g_string_assign (prev_date_opened, "");
                g_string_assign (prev_date_posted, "");
                g_string_assign (prev_owner_id, "");
                g_string_assign (prev_date, "");
            }
        }

        if (!row_deleted)
        {
            // the row is valid (price and id are valid)

            if (strlen (date_opened) == 0)
            {
                if (prev_date_opened->len == 0)
                {
                    // fix this by using the current date (why is this so complicated?)
                    gchar temp[20];
                    GDate *date;
                    time_t secs;
                    struct tm now;
                    time (&secs);
                    localtime_r (&secs, &now);
                    date =
                        g_date_new_dmy (now.tm_mday, now.tm_mon + 1,
                                        now.tm_year + 1900);
                    g_date_strftime (temp, 20, "%x", date);	// create a locale specific date string
                    g_string_assign (prev_date_opened, temp);
                    g_date_free (date);
                }
                // fix this by using the previous date_opened value (multi line invoice)
                gtk_list_store_set (store, &iter, DATE_OPENED,
                                    prev_date_opened->str, -1);
                row_fixed = TRUE;
            }
            else
            {
                // remember date_opened (to be able to fix multi line invoices)
                g_string_assign (prev_date_opened, date_opened);
            }

            // date_opened is valid

            if (strlen (date_posted) == 0)
            {
                if (prev_date_posted->len == 0)
                {
                    // this invoice will have to get posted manually
                }
                else
                {
                    // multi line invoice => fix it
                    gtk_list_store_set (store, &iter, DATE_POSTED,
                                        prev_date_posted->str, -1);
                    row_fixed = TRUE;
                }
            }
            else
            {
                // remember date_opened (to be able to fix multi line invoices)
                g_string_assign (prev_date_posted, date_posted);
            }

            // date_posted is valid

            if (strlen (quantity) == 0)
            {
                // quantity is unset => set to 1
                gtk_list_store_set (store, &iter, QUANTITY, "1", -1);
                row_fixed = TRUE;
            }

            // quantity is valid

            if (strlen (owner_id) == 0)
            {
                if (prev_owner_id->len == 0)
                {
                    // no customer given and not fixable => delete row
                    gtk_list_store_remove (store, &iter);
                    row_deleted = TRUE;
                    g_string_append_printf (info,
                                            _("ROW DELETED, OWNER_NOT_SET: id=%s\n"),
                                            id);
                }
                else
                {
                    gtk_list_store_set (store, &iter, owner_id,
                                        prev_owner_id->str, -1);
                    row_fixed = TRUE;
                }
            }
            else
            {
                // remember owner_id
                g_string_assign (prev_owner_id, owner_id);
            }
            if (g_ascii_strcasecmp (type, "BILL") == 0)
            {
                // BILL: check, if vendor exists
                if (!gnc_search_vendor_on_id
                        (gnc_get_current_book (), prev_owner_id->str))
                {
                    // vendor not found => delete row
                    gtk_list_store_remove (store, &iter);
                    row_deleted = TRUE;
                    g_string_append_printf (info,
                                            _("ROW DELETED, VENDOR_DOES_NOT_EXIST: id=%s\n"),
                                            id);
                }
            }
            else if (g_ascii_strcasecmp (type, "INVOICE") == 0)
            {
                // INVOICE: check, if customer exists
                if (!gnc_search_customer_on_id
                        (gnc_get_current_book (), prev_owner_id->str))
                {
                    // customer not found => delete row
                    gtk_list_store_remove (store, &iter);
                    row_deleted = TRUE;
                    g_string_append_printf (info,
                                            _("ROW DELETED, CUSTOMER_DOES_NOT_EXIST: id=%s\n"),
                                            id);
                }
            }

            // owner_id is valid
        }

        g_free (id);
        g_free (date_opened);
        g_free (date_posted);
        g_free (owner_id);
        g_free (date);
        g_free (quantity);
        g_free (price);
        if (row_deleted)
        {
            (*deleted)++;
            // reset all remembered values
            g_string_assign (prev_id, "");
            g_string_assign (prev_date_opened, "");
            g_string_assign (prev_date_posted, "");
            g_string_assign (prev_owner_id, "");
            g_string_assign (prev_date, "");
        }
        else if (row_fixed)
            (*fixed)++;
        valid = gtk_tree_model_iter_next (GTK_TREE_MODEL (store), &iter);
    }

    // deallocate strings
    g_string_free (prev_id, TRUE);
    g_string_free (prev_date_opened, TRUE);
    g_string_free (prev_date_posted, TRUE);
    g_string_free (prev_owner_id, TRUE);
    g_string_free (prev_date, TRUE);

    if (info && (info->len > 0))
    {
        g_string_prepend (info, "\n\n");
        g_string_prepend (info, _("These rows were deleted:"));
    }
}
コード例 #13
0
void
gnc_split_register_load (SplitRegister *reg, GList * slist,
                         Account *default_account)
{
    SRInfo *info;
    Transaction *pending_trans;
    CursorBuffer *cursor_buffer;
    GHashTable *trans_table = NULL;
    CellBlock *cursor_header;
    CellBlock *lead_cursor;
    CellBlock *split_cursor;
    Transaction *blank_trans;
    Transaction *find_trans;
    Transaction *trans;
    CursorClass find_class;
    Split *find_trans_split;
    Split *blank_split;
    Split *find_split;
    Split *split;
    Table *table;
    GList *node;

    gboolean start_primary_color = TRUE;
    gboolean found_pending = FALSE;
    gboolean need_divider_upper = FALSE;
    gboolean found_divider_upper = FALSE;
    gboolean found_divider = FALSE;
    gboolean has_last_num = FALSE;
    gboolean multi_line;
    gboolean dynamic;
    gboolean we_own_slist = FALSE;
    gboolean use_autoreadonly = qof_book_uses_autoreadonly(gnc_get_current_book());

    VirtualCellLocation vcell_loc;
    VirtualLocation save_loc;

    int new_trans_split_row = -1;
    int new_trans_row = -1;
    int new_split_row = -1;
    time64 present, autoreadonly_time = 0;

    g_return_if_fail(reg);
    table = reg->table;
    g_return_if_fail(table);
    info = gnc_split_register_get_info (reg);
    g_return_if_fail(info);

    ENTER("reg=%p, slist=%p, default_account=%p", reg, slist, default_account);

    blank_split = xaccSplitLookup (&info->blank_split_guid,
                                   gnc_get_current_book ());

    pending_trans = xaccTransLookup (&info->pending_trans_guid,
                                     gnc_get_current_book ());

    /* make sure we have a blank split */
    if (blank_split == NULL)
    {
	/* Wouldn't it be a bug to open the new transaction if there was
	 * already a pending transaction?
	*/
	g_assert(pending_trans == NULL);
	blank_split = create_blank_split (default_account, info);
    }
    blank_trans = xaccSplitGetParent (blank_split);

    DEBUG("blank_split=%p, blank_trans=%p, pending_trans=%p",
          blank_split, blank_trans, pending_trans);

    info->default_account = *xaccAccountGetGUID (default_account);

    // gnc_table_leave_update (table, table->current_cursor_loc);

    multi_line = (reg->style == REG_STYLE_JOURNAL);
    dynamic    = (reg->style == REG_STYLE_AUTO_LEDGER);

    lead_cursor = gnc_split_register_get_passive_cursor (reg);
    split_cursor = gnc_table_layout_get_cursor (table->layout, CURSOR_SPLIT);

    /* figure out where we are going to. */
    if (info->traverse_to_new)
    {
        find_trans = blank_trans;
        find_split = NULL;
        find_trans_split = blank_split;
        find_class = CURSOR_CLASS_SPLIT;
    }
    else
    {
        find_trans = info->cursor_hint_trans;
        find_split = info->cursor_hint_split;
        find_trans_split = info->cursor_hint_trans_split;
        find_class = info->cursor_hint_cursor_class;
    }

    save_loc = table->current_cursor_loc;

    /* If the current cursor has changed we save the values for later
     * possible restoration. */
    if (gnc_table_current_cursor_changed (table, TRUE) &&
            (find_split == gnc_split_register_get_current_split (reg)))
    {
        cursor_buffer = gnc_cursor_buffer_new ();
        gnc_table_save_current_cursor (table, cursor_buffer);
    }
    else
        cursor_buffer = NULL;

    /* disable move callback -- we don't want the cascade of
     * callbacks while we are fiddling with loading the register */
    gnc_table_control_allow_move (table->control, FALSE);

    /* invalidate the cursor */
    {
        VirtualLocation virt_loc;

        gnc_virtual_location_init(&virt_loc);
        gnc_table_move_cursor_gui (table, virt_loc);
    }

    /* make sure that the header is loaded */
    vcell_loc.virt_row = 0;
    vcell_loc.virt_col = 0;
    cursor_header = gnc_table_layout_get_cursor (table->layout, CURSOR_HEADER);
    gnc_table_set_vcell (table, cursor_header, NULL, TRUE, TRUE, vcell_loc);
    vcell_loc.virt_row++;

    /* get the current time and reset the dividing row */
    present = gnc_time64_get_today_end ();
    if (use_autoreadonly)
    {
        GDate *d = qof_book_get_autoreadonly_gdate(gnc_get_current_book());
        // "d" is NULL if use_autoreadonly is FALSE
        autoreadonly_time = d ? timespecToTime64(gdate_to_timespec(*d)) : 0;
        g_date_free(d);
    }

    if (info->first_pass)
    {
        if (default_account)
        {
            const char *last_num = xaccAccountGetLastNum (default_account);

            if (last_num)
            {
                NumCell *cell;

                cell = (NumCell *) gnc_table_layout_get_cell(table->layout, NUM_CELL);
                gnc_num_cell_set_last_num (cell, last_num);
                has_last_num = TRUE;
            }
        }

        /* load up account names into the transfer combobox menus */
        gnc_split_register_load_xfer_cells (reg, default_account);
        gnc_split_register_load_recn_cells (reg);
        gnc_split_register_load_type_cells (reg);
    }

    if (info->separator_changed)
	change_account_separator (info, table, reg);

    table->model->dividing_row_upper = -1;
    table->model->dividing_row = -1;

    // Ensure that the transaction and splits being edited are in the split
    // list we're about to load.
    if (pending_trans != NULL)
    {
        for (node = xaccTransGetSplitList(pending_trans); node; node = node->next)
        {
            Split *pending_split = (Split*)node->data;
            if (!xaccTransStillHasSplit(pending_trans, pending_split)) continue;
            if (g_list_find(slist, pending_split) != NULL)
                continue;

            if (g_list_find_custom(slist, pending_trans,
                                   _find_split_with_parent_txn) != NULL)
                continue;

            if (!we_own_slist)
            {
                // lazy-copy
                slist = g_list_copy(slist);
                we_own_slist = TRUE;
            }
            slist = g_list_append(slist, pending_split);
        }
    }

    if (multi_line)
        trans_table = g_hash_table_new (g_direct_hash, g_direct_equal);

    /* populate the table */
    for (node = slist; node; node = node->next)
    {
        split = node->data;
        trans = xaccSplitGetParent (split);

        if (!xaccTransStillHasSplit(trans, split))
            continue;

        if (pending_trans == trans)
            found_pending = TRUE;
	/* If the transaction has only one split, and it's not our
	 * pending_trans, then it's another register's blank split and
	 * we don't want to see it.
	 */
	else if (xaccTransCountSplits (trans) == 1 &&
		 xaccSplitGetAccount (split) == NULL)
	    continue;


        /* Do not load splits from the blank transaction. */
        if (trans == blank_trans)
            continue;

        if (multi_line)
        {
            /* Skip this split if its transaction has already been loaded. */
            if (g_hash_table_lookup (trans_table, trans))
                continue;

            g_hash_table_insert (trans_table, trans, trans);
        }

        if (info->show_present_divider &&
                use_autoreadonly &&
                !found_divider_upper)
        {
            if (xaccTransGetDate (trans) >= autoreadonly_time)
            {
                table->model->dividing_row_upper = vcell_loc.virt_row;
                found_divider_upper = TRUE;
            }
            else
            {
                need_divider_upper = TRUE;
            }
        }

        if (info->show_present_divider &&
                !found_divider &&
                (xaccTransGetDate (trans) > present))
        {
            table->model->dividing_row = vcell_loc.virt_row;
            found_divider = TRUE;
        }

        /* If this is the first load of the register,
         * fill up the quickfill cells. */
        if (info->first_pass)
            add_quickfill_completions(reg->table->layout, trans, split, has_last_num);

        if (trans == find_trans)
            new_trans_row = vcell_loc.virt_row;

        if (split == find_trans_split)
            new_trans_split_row = vcell_loc.virt_row;

        gnc_split_register_add_transaction (reg, trans, split,
                                            lead_cursor, split_cursor,
                                            multi_line, start_primary_color,
                                            TRUE,
                                            find_trans, find_split, find_class,
                                            &new_split_row, &vcell_loc);

        if (!multi_line)
            start_primary_color = !start_primary_color;
    }

    if (multi_line)
        g_hash_table_destroy (trans_table);

    /* add the blank split at the end. */
    if (pending_trans == blank_trans)
        found_pending = TRUE;

    /* No upper divider yet? Store it now */
    if (info->show_present_divider &&
            use_autoreadonly &&
            !found_divider_upper && need_divider_upper)
    {
        table->model->dividing_row_upper = vcell_loc.virt_row;
        found_divider_upper = TRUE;
    }

    if (blank_trans == find_trans)
        new_trans_row = vcell_loc.virt_row;

    if (blank_split == find_trans_split)
        new_trans_split_row = vcell_loc.virt_row;

    /* If we didn't find the pending transaction, it was removed
     * from the account. */
    if (!found_pending)
    {
        info->pending_trans_guid = *guid_null ();
        if (xaccTransIsOpen (pending_trans))
            xaccTransCommitEdit (pending_trans);
        else if (pending_trans)
            g_assert_not_reached();

        pending_trans = NULL;
    }

    /* go to blank on first pass */
    if (info->first_pass)
    {
        new_split_row = -1;
        new_trans_split_row = -1;
        new_trans_row = -1;

        save_loc.vcell_loc = vcell_loc;
        save_loc.phys_row_offset = 0;
        save_loc.phys_col_offset = 0;
    }

    gnc_split_register_add_transaction (reg, blank_trans, blank_split,
                                        lead_cursor, split_cursor,
                                        multi_line, start_primary_color,
                                        info->blank_split_edited, find_trans,
                                        find_split, find_class, &new_split_row,
                                        &vcell_loc);

    /* resize the table to the sizes we just counted above */
    /* num_virt_cols is always one. */
    gnc_table_set_size (table, vcell_loc.virt_row, 1);

    /* restore the cursor to its rightful position */
    {
        VirtualLocation trans_split_loc;

        if (new_split_row > 0)
            save_loc.vcell_loc.virt_row = new_split_row;
        else if (new_trans_split_row > 0)
            save_loc.vcell_loc.virt_row = new_trans_split_row;
        else if (new_trans_row > 0)
            save_loc.vcell_loc.virt_row = new_trans_row;

        trans_split_loc = save_loc;

	gnc_split_register_get_trans_split (reg, save_loc.vcell_loc,
					    &trans_split_loc.vcell_loc);

        if (dynamic || multi_line || info->trans_expanded)
        {
            gnc_table_set_virt_cell_cursor(
                table, trans_split_loc.vcell_loc,
                gnc_split_register_get_active_cursor (reg));
            gnc_split_register_set_trans_visible (reg, trans_split_loc.vcell_loc,
                                                  TRUE, multi_line);

            info->trans_expanded = (reg->style == REG_STYLE_LEDGER);
        }
        else
        {
            save_loc = trans_split_loc;
            info->trans_expanded = FALSE;
        }

        if (gnc_table_find_close_valid_cell (table, &save_loc, FALSE))
        {
            gnc_table_move_cursor_gui (table, save_loc);
            new_split_row = save_loc.vcell_loc.virt_row;

            if (find_split == gnc_split_register_get_current_split (reg))
                gnc_table_restore_current_cursor (table, cursor_buffer);
        }
    }
    gnc_cursor_buffer_destroy (cursor_buffer);
    cursor_buffer = NULL;

    update_info (info, reg);

    gnc_split_register_set_cell_fractions(
        reg, gnc_split_register_get_current_split (reg));

    gnc_table_refresh_gui (table, TRUE);

    gnc_split_register_show_trans (reg, table->current_cursor_loc.vcell_loc);

    /* enable callback for cursor user-driven moves */
    gnc_table_control_allow_move (table->control, TRUE);

    if (we_own_slist)
        g_list_free(slist);

    LEAVE(" ");
}
コード例 #14
0
ファイル: print-draw-page.c プロジェクト: Minoos/gimp
static void
draw_info_header (GtkPrintContext *context,
                  cairo_t         *cr,
                  PrintData       *data)
{
  PangoLayout          *layout;
  PangoFontDescription *desc;
  gdouble               text_height;
  gdouble               text_width;
  gdouble               fname_text_width;
  gint                  layout_height;
  gint                  layout_width;
  gchar                 date_buffer[100];
  GDate                *date;
  const gchar          *name_str;
  GimpParasite         *parasite;
  const gchar          *end_ptr;
  gchar                *filename;
  gdouble               cr_width;

  cairo_save (cr);

  cr_width  = gtk_print_context_get_width (context);
  cairo_rectangle (cr, 0, 0, cr_width, HEADER_HEIGHT);
  cairo_set_source_rgb (cr, 0.8, 0.8, 0.8);
  cairo_fill_preserve (cr);

  cairo_set_source_rgb (cr, 0, 0, 0);
  cairo_set_line_width (cr, 1);
  cairo_stroke (cr);

  layout = gtk_print_context_create_pango_layout (context);

  desc = pango_font_description_from_string ("sans 14");
  pango_layout_set_font_description (layout, desc);
  pango_font_description_free (desc);

  pango_layout_set_width (layout, -1);
  pango_layout_set_alignment (layout, PANGO_ALIGN_CENTER);

  /* image name */
  pango_layout_set_text (layout, gimp_image_get_name (data->image_id), -1);

  pango_layout_get_size (layout, &layout_width, &layout_height);
  text_height = (gdouble) layout_height / PANGO_SCALE;

  cairo_move_to (cr, 0.02 * cr_width,  (HEADER_HEIGHT - text_height) / 5);
  pango_cairo_show_layout (cr, layout);

  /* user name */
  name_str = g_get_real_name ();
  if (name_str && g_utf8_validate (name_str, -1, &end_ptr))
    {
      pango_layout_set_text (layout, name_str, -1);

      pango_layout_get_size (layout, &layout_width, &layout_height);
      text_height = (gdouble) layout_height / PANGO_SCALE;
      text_width = (gdouble) layout_width / PANGO_SCALE;

      cairo_move_to (cr, 0.5 * cr_width - 0.5 * text_width,
                     (HEADER_HEIGHT - text_height) / 5);
      pango_cairo_show_layout (cr, layout);
    }

  /* date */
  date = g_date_new ();
  g_date_set_time_t (date, time (NULL));
  g_date_strftime (date_buffer, 100, "%x", date);
  g_date_free (date);
  pango_layout_set_text (layout, date_buffer, -1);

  pango_layout_get_size (layout, &layout_width, &layout_height);
  text_height = (gdouble) layout_height / PANGO_SCALE;
  text_width = (gdouble) layout_width / PANGO_SCALE;

  cairo_move_to (cr,
                 0.98 * cr_width - text_width,
                 (HEADER_HEIGHT - text_height) / 5);
  pango_cairo_show_layout (cr, layout);

  /* file name if any */
  filename = gimp_image_get_filename (data->image_id);

  if (filename)
    {
      pango_layout_set_text (layout,
                             gimp_filename_to_utf8 (filename), -1);
      g_free (filename);

      pango_layout_get_size (layout, &layout_width, &layout_height);
      text_height = (gdouble) layout_height / PANGO_SCALE;
      fname_text_width = (gdouble) layout_width / PANGO_SCALE;

      cairo_move_to (cr,
                     0.02 * cr_width,  4 * (HEADER_HEIGHT - text_height) / 5);
      pango_cairo_show_layout (cr, layout);
    }
  else
    {
      fname_text_width = 0;
    }

  /* image comment if it is short */
  parasite = gimp_image_parasite_find (data->image_id, "gimp-comment");

  if (parasite)
    {
      pango_layout_set_text (layout, gimp_parasite_data (parasite), -1);

      pango_layout_get_size (layout, &layout_width, &layout_height);
      text_height = (gdouble) layout_height / PANGO_SCALE;
      text_width = (gdouble) layout_width / PANGO_SCALE;

      if (fname_text_width + text_width < 0.8 * cr_width &&
          text_height < 0.5 * HEADER_HEIGHT)
        {
          cairo_move_to (cr, 0.98 * cr_width - text_width,
                         4 * (HEADER_HEIGHT - text_height) / 5);
          pango_cairo_show_layout (cr, layout);
        }

      gimp_parasite_free (parasite);
    }

  g_object_unref (layout);

  cairo_restore (cr);
}
コード例 #15
0
ファイル: dialog-preferences.c プロジェクト: 814ckf0x/gnucash
/** Create the preferences dialog.  This function first reads the
 *  dialog-preferences.glade file to obtain the content and then
 *  the dialog is created with a set of common preferences.  It then
 *  runs the list of add-ins, calling a helper function to add each full/partial
 *  page to this dialog, Finally it builds the "interesting widgets"
 *  table that is used for connecting the widgets up to callback functions.
 *
 *  @internal
 *
 *  @return A pointer to the newly created dialog.
 */
static GtkWidget *
gnc_preferences_dialog_create(void)
{
    GtkBuilder *builder;
    GtkWidget *dialog, *notebook, *label, *image;
    GtkWidget *box, *date, *period, *currency;
    GHashTable *prefs_table;
    GDate* gdate = NULL;
    gchar buf[128];
    GtkListStore *store;
    GtkTreePath *path;
    GtkTreeIter iter;
    gnc_commodity *locale_currency;
    const gchar *currency_name;
    QofBook *book;
    KvpFrame *book_frame;
    gint64 month, day;
    GDate fy_end;
    gboolean date_is_valid = FALSE;

    ENTER("");
    DEBUG("Opening dialog-preferences.glade:");
    builder = gtk_builder_new();

    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "auto_decimal_places_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "autosave_interval_minutes_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "save_on_close_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "date_backmonth_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "max_transactions_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "key_length_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "new_search_limit_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "retain_days_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "tab_width_adj");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "date_formats");
    gnc_builder_add_from_file (builder, "dialog-preferences.glade", "GnuCash Preferences");

    dialog = GTK_WIDGET(gtk_builder_get_object (builder, "GnuCash Preferences"));

#ifndef REGISTER2_ENABLED
    /* Hide preferences that are related to register2 */
    box = GTK_WIDGET (gtk_builder_get_object (builder, "label14"));
    gtk_widget_hide (box);
    box = GTK_WIDGET (gtk_builder_get_object (builder, "pref/general.register/key-length"));
    gtk_widget_hide (box);
    box = GTK_WIDGET (gtk_builder_get_object (builder, "pref/general.register/show-extra-dates"));
    gtk_widget_hide (box);
    box = GTK_WIDGET (gtk_builder_get_object (builder, "pref/general.register/show-calendar-buttons"));
    gtk_widget_hide (box);
    box = GTK_WIDGET (gtk_builder_get_object (builder, "pref/general.register/selection-to-blank-on-expand"));
    gtk_widget_hide (box);
    box = GTK_WIDGET (gtk_builder_get_object (builder, "pref/general.register/show-extra-dates-on-selection"));
    gtk_widget_hide (box);
#endif

    label = GTK_WIDGET(gtk_builder_get_object (builder, "sample_account"));
    g_object_set_data(G_OBJECT(dialog), "sample_account", label);

    image = GTK_WIDGET(gtk_builder_get_object (builder, "separator_error"));
    g_object_set_data(G_OBJECT(dialog), "separator_error", image);

    DEBUG("autoconnect");
    gtk_builder_connect_signals_full (builder, gnc_builder_connect_full_func, dialog);

    DEBUG("done");

    notebook = GTK_WIDGET(gtk_builder_get_object (builder, "notebook1"));
    prefs_table = g_hash_table_new(g_str_hash, g_str_equal);
    g_object_set_data(G_OBJECT(dialog), NOTEBOOK, notebook);
    g_object_set_data_full(G_OBJECT(dialog), PREFS_WIDGET_HASH,
                           prefs_table, (GDestroyNotify)g_hash_table_destroy);


    book = gnc_get_current_book();
    g_date_clear (&fy_end, 1);
    qof_instance_get (QOF_INSTANCE (book),
		      "fy-end", &fy_end,
		      NULL);
    box = GTK_WIDGET(gtk_builder_get_object (builder,
                     "pref/" GNC_PREFS_GROUP_ACCT_SUMMARY "/" GNC_PREF_START_PERIOD));
    period = gnc_period_select_new(TRUE);
    gtk_widget_show (period);
    gtk_box_pack_start (GTK_BOX (box), period, TRUE, TRUE, 0);
    if (date_is_valid)
        gnc_period_select_set_fy_end(GNC_PERIOD_SELECT (period), &fy_end);

    box = GTK_WIDGET(gtk_builder_get_object (builder,
                     "pref/" GNC_PREFS_GROUP_ACCT_SUMMARY "/" GNC_PREF_END_PERIOD));
    period = gnc_period_select_new(FALSE);
    gtk_widget_show (period);
    gtk_box_pack_start (GTK_BOX (box), period, TRUE, TRUE, 0);
    if (date_is_valid)
        gnc_period_select_set_fy_end(GNC_PERIOD_SELECT (period), &fy_end);

    box = GTK_WIDGET(gtk_builder_get_object (builder,
                     "pref/" GNC_PREFS_GROUP_ACCT_SUMMARY "/" GNC_PREF_START_DATE));
    date = gnc_date_edit_new(gnc_time (NULL), FALSE, FALSE);
    gtk_widget_show (date);
    gtk_box_pack_start (GTK_BOX (box), date, TRUE, TRUE, 0);

    box = GTK_WIDGET(gtk_builder_get_object (builder,
                     "pref/" GNC_PREFS_GROUP_ACCT_SUMMARY "/" GNC_PREF_END_DATE));
    date = gnc_date_edit_new(gnc_time (NULL), FALSE, FALSE);
    gtk_widget_show (date);
    gtk_box_pack_start (GTK_BOX (box), date, TRUE, TRUE, 0);

    box = GTK_WIDGET(gtk_builder_get_object (builder,
                     "pref/" GNC_PREFS_GROUP_GENERAL "/" GNC_PREF_CURRENCY_OTHER));
    currency = gnc_currency_edit_new();
    gnc_currency_edit_set_currency (GNC_CURRENCY_EDIT(currency), gnc_default_currency());
    gtk_widget_show (currency);
    gtk_box_pack_start(GTK_BOX (box), currency, TRUE, TRUE, 0);

    box = GTK_WIDGET(gtk_builder_get_object (builder,
                     "pref/" GNC_PREFS_GROUP_GENERAL_REPORT "/" GNC_PREF_CURRENCY_OTHER));
    currency = gnc_currency_edit_new();
    gnc_currency_edit_set_currency (GNC_CURRENCY_EDIT(currency), gnc_default_currency());
    gtk_widget_show (currency);
    gtk_box_pack_start(GTK_BOX (box), currency, TRUE, TRUE, 0);


    /* Add to the list of interesting widgets */
    gnc_prefs_build_widget_table(builder, dialog);

    g_slist_foreach(add_ins, gnc_preferences_build_page, dialog);

    /* Sort tabs alphabetically */
    gnc_prefs_sort_pages(GTK_NOTEBOOK(notebook));
    gtk_notebook_set_current_page(GTK_NOTEBOOK(notebook), 0);

    DEBUG("We have the following interesting widgets:");
    g_hash_table_foreach(prefs_table, (GHFunc)gnc_prefs_connect_one, dialog);
    DEBUG("Done with interesting widgets.");

    /* Other stuff */
    gdate = g_date_new_dmy(31, G_DATE_JULY, 2013);
    g_date_strftime(buf, sizeof(buf), "%x", gdate);
    store = GTK_LIST_STORE(gtk_builder_get_object (builder, "date_formats"));
    path = gtk_tree_path_new_from_indices (QOF_DATE_FORMAT_LOCALE, -1);
    if (gtk_tree_model_get_iter (GTK_TREE_MODEL (store), &iter, path))
            gtk_list_store_set (store, &iter, 1, buf, -1);
    g_date_free(gdate);

    locale_currency = gnc_locale_default_currency ();
    currency_name = gnc_commodity_get_printname(locale_currency);
    label = GTK_WIDGET(gtk_builder_get_object (builder, "locale_currency"));
    gtk_label_set_label(GTK_LABEL(label), currency_name);
    label = GTK_WIDGET(gtk_builder_get_object (builder, "locale_currency2"));
    gtk_label_set_label(GTK_LABEL(label), currency_name);

    g_object_unref(G_OBJECT(builder));

    LEAVE("dialog %p", dialog);
    return dialog;
}
コード例 #16
0
ファイル: paradox.c プロジェクト: nzinfo/gnumeric
G_MODULE_EXPORT void
paradox_file_open (GOFileOpener const *fo, GOIOContext *io_context,
                   WorkbookView *wb_view, GsfInput *input)
{
	Workbook  *wb;
	pxdoc_t	  *pxdoc;
	pxhead_t	*pxh;
	pxfield_t	*pxf;
	char	*data;
	char	  *name;
	Sheet	  *sheet;
	GnmCell	  *cell;
	GnmValue	  *val = NULL;
	GOErrorInfo *open_error = NULL;
	guint row, i, j, offset;

#ifdef PX_MEMORY_DEBUGGING
	PX_mp_init ();
#endif

#ifdef PX_MEMORY_DEBUGGING
	pxdoc = PX_new2 (gn_errorhandler, PX_mp_malloc, PX_mp_realloc, PX_mp_free);
#else
	pxdoc = PX_new2 (gn_errorhandler, gn_malloc, gn_realloc, gn_free);
#endif
	if (PX_open_gsf (pxdoc, input) < 0) {
		go_io_error_info_set (io_context, go_error_info_new_str_with_details (
					    _("Error while opening Paradox file."),
					    open_error));
		return;
	}
	pxh = pxdoc->px_head;

	PX_set_targetencoding (pxdoc, "UTF-8");

	wb = wb_view_get_workbook (wb_view);
	name = workbook_sheet_get_free_name (wb, pxh->px_tablename, FALSE, TRUE);
	sheet = sheet_new (wb, name, 256, 65536);
	g_free (name);
	workbook_sheet_attach (wb, sheet);

	pxf = pxh->px_fields;
	for (i = 0 ; i < (guint) pxh->px_numfields; i++) {
		char str[30], *str2;
		char ctypes[26] = {'?',
				   'A', 'D', 'S', 'I', '$', 'N', '?', '?',
				   'L', '?', '?', 'M', 'B', 'F', 'O', 'G',
				   '?', '?', '?', 'T', '@', '+', '#', 'Y',
				   };
		cell = sheet_cell_fetch (sheet, i, 0);
		if (pxf->px_ftype == pxfBCD)
			snprintf (str, 30, "%s,%c,%d", pxf->px_fname, ctypes[(int)pxf->px_ftype], pxf->px_fdc);
		else
			snprintf (str, 30, "%s,%c,%d", pxf->px_fname, ctypes[(int)pxf->px_ftype], pxf->px_flen);
#if PXLIB_MAJOR_VERSION == 0 && (PXLIB_MINOR_VERION < 3 || (PXLIB_MAJOR_VERSION == 3 && PXLIB_MICRO_VERSION == 0))
		/* Convert the field names to utf-8. This is actually in pxlib
		 * responsibility, but hasn't been implemented yet. For the mean time
		 * we *misuse* PX_get_data_alpha()
		 */
		PX_get_data_alpha (pxdoc, str, strlen (str), &str2);
		gnm_cell_set_text (cell, str2);
		pxdoc->free (pxdoc, str2);
#else
		gnm_cell_set_text (cell, str);
#endif
		pxf++;
	}
	{
		GnmRange r;
		GnmStyle *bold = gnm_style_new ();
		gnm_style_set_font_bold (bold, TRUE);
		sheet_style_apply_range	(sheet,
			range_init (&r, 0, 0, pxh->px_numfields-1, 0), bold);
	}

	if ((data = (char *) pxdoc->malloc (pxdoc, pxh->px_recordsize, _("Could not allocate memory for record."))) == NULL) {
		go_io_error_info_set (io_context, go_error_info_new_str_with_details (
					    _("Error while opening Paradox file."),
					    open_error));
		return;
	}
	row = 1;
	for (j = 0; j < (guint)pxh->px_numrecords; j++) {
		pxdatablockinfo_t pxdbinfo;
		int isdeleted = 0;
		if (NULL != PX_get_record2 (pxdoc, j, data, &isdeleted, &pxdbinfo)) {
			offset = 0;
			pxf = pxh->px_fields;
			for (i = 0; i < (guint) pxh->px_numfields ; i++) {
				cell = sheet_cell_fetch (sheet, i, row);
				val = NULL;
				switch (pxf->px_ftype) {
				case pxfAlpha: {
					char *value;
					if (0 < PX_get_data_alpha (pxdoc, &data[offset], pxf->px_flen, &value)) {
						val = value_new_string_nocopy (value);
/*							value_set_fmt (val, field->fmt); */
					}
					break;
				}
				case pxfShort: {
					short int value;
					if (0 < PX_get_data_short (pxdoc, &data[offset], pxf->px_flen, &value)) {
						val = value_new_int (value);
					}
					break;
				}
				case pxfAutoInc:
				case pxfLong: {
					long value;
					if (0 < PX_get_data_long (pxdoc, &data[offset], pxf->px_flen, &value)) {
						val = value_new_int (value);
					}
					break;
				}
				case pxfCurrency:
				case pxfNumber: {
					double value;
					if (0 < PX_get_data_double (pxdoc, &data[offset], pxf->px_flen, &value)) {
						val = value_new_float (value);
						if (pxf->px_ftype == pxfCurrency)
							value_set_fmt (val, go_format_default_money ());
					}
					break;
				}
				case pxfTimestamp: {
					double value;
					if (0 < PX_get_data_double (pxdoc, &data[offset], pxf->px_flen, &value)) {
						value = value / 86400000.0;
						/* 693594 = number of days up to 31.12.1899 */
						value -= 693594;
						val = value_new_float (value);
						value_set_fmt (val, go_format_default_date_time ());
					}
					break;
				}
				case  pxfLogical: {
					char value;
					if (0 < PX_get_data_byte (pxdoc, &data[offset], pxf->px_flen, &value)) {
						val = value_new_bool (value ? TRUE : FALSE);
					}
					break;
				}
				case pxfDate: {
					long value;
					int year, month, day;
					GDate *date;
					if (0 < PX_get_data_long (pxdoc, &data[offset], pxf->px_flen, &value)) {
						PX_SdnToGregorian (value+1721425, &year, &month, &day);
						date = g_date_new_dmy (day, month, year);
						val = value_new_int (go_date_g_to_serial (date, NULL));
						value_set_fmt (val, go_format_default_date ());
						g_date_free (date);
					}
					break;
				}
				case pxfTime: {
					long value;
					if (0 < PX_get_data_long (pxdoc, &data[offset], pxf->px_flen, &value)) {
						val = value_new_float (value/86400000.0);
						value_set_fmt (val, go_format_default_time ());
					}
					break;
				}
				case pxfBCD: {
					char *value;
					if (0 < PX_get_data_bcd (pxdoc, &data[offset], pxf->px_fdc, &value)) {
						val = value_new_string_nocopy (value);
					}
					break;
				}
				case pxfMemoBLOb: {
					char *value;
					int size, mod_nr;
					if (0 < PX_get_data_blob (pxdoc, &data[offset], pxf->px_flen, &mod_nr, &size, &value)) {
						val = value_new_string_nocopy (value);
					}
					break;
				}
				default:
					val = value_new_string_nocopy (
						g_strdup_printf (_("Field type %d is not supported."), pxf->px_ftype));
				}
				if (val)
					gnm_cell_set_value (cell, val);
				offset += pxf->px_flen;
				pxf++;
			}
			if (pxh->px_filetype == pxfFileTypPrimIndex) {
				short int value;
				cell = sheet_cell_fetch (sheet, i++, row);
				if (0 < PX_get_data_short (pxdoc, &data[offset], 2, &value)) {
					val = value_new_int (value);
					gnm_cell_set_value (cell, val);
				}
				offset += 2;
				cell = sheet_cell_fetch (sheet, i++, row);
				if (0 < PX_get_data_short (pxdoc, &data[offset], 2, &value)) {
					val = value_new_int (value);
					gnm_cell_set_value (cell, val);
				}
				offset += 2;
				cell = sheet_cell_fetch (sheet, i++, row);
				if (0 < PX_get_data_short (pxdoc, &data[offset], 2, &value)) {
					val = value_new_int (value);
					gnm_cell_set_value (cell, val);
				}
				cell = sheet_cell_fetch (sheet, i++, row);
				val = value_new_int (pxdbinfo.number);
				gnm_cell_set_value (cell, val);
			}
		}
		row++;
	}
	pxdoc->free (pxdoc, data);

	PX_close (pxdoc);
	PX_delete (pxdoc);

	sheet_flag_recompute_spans (sheet);
}
コード例 #17
0
/**
 * initialisation of all the variables of grisbi
 * if some are not empty, free them before set it to NULL
 *
 * \param
 *
 * \return
 * */
void init_variables ( void )
{
    gint bet_array_col_width_init[BET_ARRAY_COLUMNS] = {15, 40, 15, 15, 15 };
    gint transaction_col_align_init[CUSTOM_MODEL_VISIBLE_COLUMNS] = { 1, 1, 0, 1, 2, 2, 2 };
    gint i;

/* xxx on devrait séparer ça en 2 : les variables liées au fichier de compte, qui doivent être remises  à 0,
 * et les variables liées à grisbi (ex sauvegarde auto...) qui doivent rester */
    devel_debug (NULL);

    /* init the new crypted file */
    run.new_crypted_file = FALSE;

    /* init the format date */
    initialise_format_date ( );

    /* init the decimal point and the thousands separator. */
    initialise_number_separators ( );

    /* initialise l'ordre des pages du panneau de gauche */
    gsb_gui_navigation_init_pages_list ( );

    /* if ever there is still something from the previous list,
     * erase now */
    transaction_model_initialize();

    gsb_data_account_init_variables ();
    gsb_data_transaction_init_variables ();
    gsb_data_payee_init_variables ();
    payees_init_variables_list ();
    gsb_data_category_init_variables ();
    categories_init_variables_list ();
    gsb_data_budget_init_variables ();
    budgetary_lines_init_variables_list ();
    gsb_data_report_init_variables ();
    gsb_data_report_amount_comparison_init_variables ();
    gsb_data_report_text_comparison_init_variables ();
    gsb_data_scheduled_init_variables ();
    gsb_scheduler_list_init_variables ();
    gsb_data_currency_init_variables ();
    gsb_data_currency_link_init_variables ();
    gsb_data_fyear_init_variables ();
    gsb_data_bank_init_variables ();
    gsb_data_reconcile_init_variables ();
    gsb_data_payment_init_variables ();
    gsb_data_archive_init_variables ();
    gsb_data_archive_store_init_variables ();
    gsb_data_import_rule_init_variables ();
    gsb_import_associations_init_variables ( );
    gsb_data_partial_balance_init_variables ( );

    gsb_currency_init_variables ();
    gsb_fyear_init_variables ();
    gsb_report_init_variables ();
    gsb_regex_init_variables ();

    gsb_data_print_config_init ();

    /* no bank in memory for now */
    bank_list_model = NULL;

    run.mise_a_jour_liste_comptes_accueil = FALSE;
    run.mise_a_jour_liste_echeances_manuelles_accueil = FALSE;
    run.mise_a_jour_liste_echeances_auto_accueil = FALSE;
    run.mise_a_jour_soldes_minimaux = FALSE;
    run.mise_a_jour_fin_comptes_passifs = FALSE;

    orphan_child_transactions = NULL;

    /* the main notebook is set to NULL,
     * important because it's the checked variable in a new file
     * to know if the widgets are created or not */
    gsb_gui_init_general_notebook ( );

    if ( nom_fichier_comptes )
        g_free ( nom_fichier_comptes );
    nom_fichier_comptes = NULL;

    affichage_echeances = SCHEDULER_PERIODICITY_ONCE_VIEW;
    affichage_echeances_perso_nb_libre = 0;
    affichage_echeances_perso_j_m_a = PERIODICITY_DAYS;

    /* initialization of titles and logo part */
    if ( titre_fichier && strlen ( titre_fichier ) )
        g_free ( titre_fichier );
    titre_fichier = g_strdup( _("My accounts") );

    etat.is_pixmaps_dir = TRUE;
    if ( etat.name_logo && strlen ( etat.name_logo ) )
        g_free ( etat.name_logo );
    etat.name_logo = NULL;
    etat.utilise_logo = 1;
    gsb_select_icon_init_logo_variables ();

    etat.retient_affichage_par_compte = 0;

    /* reconcile (etat) */
    run.reconcile_account_number = -1;
    g_free ( run.reconcile_final_balance );
    if ( run.reconcile_new_date )
        g_date_free ( run.reconcile_new_date );
    run.reconcile_final_balance = NULL;
    run.reconcile_new_date = NULL;

    adresse_commune = NULL;
    adresse_secondaire = NULL;

    current_tree_view_width = 0;
    scheduler_current_tree_view_width = 0;

    initialise_tab_affichage_ope();

    valeur_echelle_recherche_date_import = 2;
    etat.get_fyear_by_value_date = FALSE;

    /* init default combofix values */
    etat.combofix_mixed_sort = FALSE;
    etat.combofix_max_item = 0;
    etat.combofix_case_sensitive = FALSE;
    etat.combofix_enter_select_completion = FALSE;
    etat.combofix_force_payee = FALSE;
    etat.combofix_force_category = FALSE;

    /* mis à NULL prévient un plantage aléatoire dans
     * gsb_currency_update_combobox_currency_list */
    detail_devise_compte = NULL;

    /* defaut value for width and align of columns */
    initialise_largeur_colonnes_tab_affichage_ope ( GSB_ACCOUNT_PAGE, transaction_col_width_init );
    initialise_largeur_colonnes_tab_affichage_ope ( GSB_SCHEDULER_PAGE, scheduler_col_width_init );
    for ( i = 0 ; i < CUSTOM_MODEL_VISIBLE_COLUMNS ; i++ )
        transaction_col_align[i] = transaction_col_align_init[i];

    if ( etat.transaction_column_width && strlen ( etat.transaction_column_width ) )
    {
        g_free ( etat.transaction_column_width );
        etat.transaction_column_width = NULL;
    }
    if ( etat.scheduler_column_width && strlen ( etat.scheduler_column_width ) )
    {
        g_free ( etat.scheduler_column_width );
        etat.scheduler_column_width = NULL;
    }

    gsb_gui_navigation_init_tree_view ( );

    /* free the form */
    gsb_form_widget_free_list ();
    gsb_form_scheduler_free_list ();

    /* set colors to default */
    gsb_color_set_colors_to_default ( );

    /* divers */
    etat.add_archive_in_total_balance = TRUE;   /* add the archived transactions by default */
    etat.get_fyear_by_value_date = 0;           /* By default use transaction-date */

    /* remove the timeout if necessary */
    if (id_timeout)
    {
    g_source_remove (id_timeout);
    id_timeout = 0;
    }

    /* initializes the variables for the estimate balance module */
    /* création de la liste des données à utiliser dans le tableau de résultats */
    bet_data_init_variables ( );
    /* initialisation des boites de dialogue */
    bet_future_initialise_dialog ( );
    etat.bet_deb_period = 1;
    /* defaut value for width of columns */
    for ( i = 0 ; i < BET_ARRAY_COLUMNS ; i++ )
        bet_array_col_width[i] = bet_array_col_width_init[i];

    bet_data_finance_data_simulator_init ( );

    bet_graph_set_configuration_variables ( NULL );

}
コード例 #18
0
ファイル: dialog-bi-import.c プロジェクト: frenzypony/gnucash
/***********************************************************************
 * @todo Maybe invoice checking should be done in gnc_bi_import_fix_bis (...)
 * rather than in here?  But that is more concerned with ensuring the csv is consistent.
 * @param GtkListStore *store
 * @param guint *n_invoices_created
 * @param guint *n_invoices_updated
 * @return void
 ***********************************************************************/
void
gnc_bi_import_create_bis (GtkListStore * store, QofBook * book,
                          guint * n_invoices_created,
                          guint * n_invoices_updated,
                          gchar * type, gchar * open_mode, GString * info)
{
    gboolean valid;
    GtkTreeIter iter;
    gchar *id, *date_opened, *owner_id, *billing_id, *notes;
    gchar *date, *desc, *action, *account, *quantity, *price, *disc_type,
          *disc_how, *discount, *taxable, *taxincluded, *tax_table;
    gchar *date_posted, *due_date, *account_posted, *memo_posted,
          *accumulatesplits;
    guint dummy;
    GncInvoice *invoice;
    GncEntry *entry;
    gint day, month, year;
    gnc_numeric value;
    GncOwner *owner;
    Account *acc;
    enum update {YES = GTK_RESPONSE_YES, NO = GTK_RESPONSE_NO} update;
    GtkWidget *dialog;
    Timespec today;
    InvoiceWindow *iw;
    gchar *new_id = NULL;
    gint64 denom = 0;
    gnc_commodity *currency;
    
    // these arguments are needed
    g_return_if_fail (store && book);
    // logic of this function only works for bills or invoices
    g_return_if_fail ((g_ascii_strcasecmp (type, "INVOICE") == 0) ||
            (g_ascii_strcasecmp (type, "BILL") == 0));

    // allow to call this function without statistics
    if (!n_invoices_created)
        n_invoices_created = &dummy;
    if (!n_invoices_updated)
        n_invoices_updated = &dummy;
    *n_invoices_created = 0;
    *n_invoices_updated = 0;

    invoice = NULL;
    update = NO;

    valid = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (store), &iter);
    while (valid)
    {
        // Walk through the list, reading each row
        gtk_tree_model_get (GTK_TREE_MODEL (store), &iter,
                            ID, &id,
                            DATE_OPENED, &date_opened,
                            DATE_POSTED, &date_posted,       // if autoposting requested
                            DUE_DATE, &due_date,             // if autoposting requested
                            ACCOUNT_POSTED, &account_posted, // if autoposting requested
                            MEMO_POSTED, &memo_posted,       // if autoposting requested
                            ACCU_SPLITS, &accumulatesplits,  // if autoposting requested
                            OWNER_ID, &owner_id,
                            BILLING_ID, &billing_id,
                            NOTES, &notes,
                            DATE, &date,
                            DESC, &desc,
                            ACTION, &action,
                            ACCOUNT, &account,
                            QUANTITY, &quantity,
                            PRICE, &price,
                            DISC_TYPE, &disc_type,
                            DISC_HOW, &disc_how,
                            DISCOUNT, &discount,
                            TAXABLE, &taxable,
                            TAXINCLUDED, &taxincluded,
                            TAX_TABLE, &tax_table, -1);

        // TODO:  Assign a new invoice number if one is absent.  BUT we don't want to assign a new invoice for every line!!
        // so we'd have to flag this up somehow or add an option in the import GUI.  The former implies that we make
        // an assumption about what the importer (person) wants to do.  It seems reasonable that a CSV file full of items with
        // If an invoice exists then we add to it in this current schema.
        // no predefined invoice number is a new invoice that's in need of a new number.
        // This was  not designed to satisfy the need for repeat invoices however, so maybe we need a another method for this, after all
        // It should be easier to copy an invoice with a new ID than to go through all this malarky.
        if (g_ascii_strcasecmp (type, "BILL") == 0)
            invoice = gnc_search_bill_on_id (book, id);
        else if (g_ascii_strcasecmp (type, "INVOICE") == 0)
            invoice = gnc_search_invoice_on_id (book, id);
        DEBUG( "Existing %s ID: %s\n", type, gncInvoiceGetID(invoice));

        // If the search is empty then there is no existing invoice so make a new one
        if (invoice == NULL)
        {
             DEBUG( "Creating a new : %s\n", type );
            // new invoice
            invoice = gncInvoiceCreate (book);
            /* Protect against thrashing the DB and trying to write the invoice
             * record prematurely */
            gncInvoiceBeginEdit (invoice);
            gncInvoiceSetID (invoice, id);
            owner = gncOwnerNew ();
            if (g_ascii_strcasecmp (type, "BILL") == 0)
                gncOwnerInitVendor (owner,
                                    gnc_search_vendor_on_id (book, owner_id));
            else if (g_ascii_strcasecmp (type, "INVOICE") == 0)
                gncOwnerInitCustomer (owner,
                                      gnc_search_customer_on_id (book, owner_id));
            gncInvoiceSetOwner (invoice, owner);
            gncInvoiceSetCurrency (invoice, gncOwnerGetCurrency (owner));	// Set the invoice currency based on the owner
            if (strlen (date_opened) != 0)	// If a date is specified in CSV
            {
                // FIXME: Must check for the return value of qof_scan_date!
                qof_scan_date (date_opened, &day, &month, &year);
                gncInvoiceSetDateOpened (invoice,
                                         gnc_dmy2timespec (day, month, year));
            }
            else			// If no date in CSV
            {
                time64 now = gnc_time (NULL);
                Timespec now_timespec;
                timespecFromTime64 (&now_timespec, now);
                gncInvoiceSetDateOpened (invoice, now_timespec);
            }
            gncInvoiceSetBillingID (invoice, billing_id ? billing_id : "");
            gncInvoiceSetNotes (invoice, notes ? notes : "");
            gncInvoiceSetActive (invoice, TRUE);
            //if (g_ascii_strcasecmp(type,"INVOICE"))gncInvoiceSetBillTo( invoice, billto );
            (*n_invoices_created)++;
            update = YES;

            // open new bill / invoice in a tab, if requested
            if (g_ascii_strcasecmp(open_mode, "ALL") == 0
                    || (g_ascii_strcasecmp(open_mode, "NOT_POSTED") == 0
                        && strlen(date_posted) == 0))
            {
                iw =  gnc_ui_invoice_edit (invoice);
                gnc_plugin_page_invoice_new (iw);
            }
            gncInvoiceCommitEdit (invoice);
        }
// I want to warn the user that an existing billvoice exists, but not every
// time.
// An import can contain many lines usually referring to the same invoice.
// NB: Posted invoices are NEVER updated.
        else			// if invoice exists
        {
            if (gncInvoiceIsPosted (invoice))	// Is it already posted?
            {
                valid =
                    gtk_tree_model_iter_next (GTK_TREE_MODEL (store), &iter);
                continue;		// If already posted then never import
            }
            if (update != YES)	// Pop up a dialog to ask if updates are the expected action
            {
                dialog = gtk_message_dialog_new (NULL,
                                                 GTK_DIALOG_MODAL,
                                                 GTK_MESSAGE_ERROR,
                                                 GTK_BUTTONS_YES_NO,
                                                 "%s",
                                                 _("Are you sure you have bills/invoices to update?"));
                update = gtk_dialog_run (GTK_DIALOG (dialog));
                gtk_widget_destroy (dialog);
                if (update == NO)
                {
                    // Cleanup and leave
                    g_free (id);
                    g_free (date_opened);
                    g_free (owner_id);
                    g_free (billing_id);
                    g_free (notes);
                    g_free (date);
                    g_free (desc);
                    g_free (action);
                    g_free (account);
                    g_free (quantity);
                    g_free (price);
                    g_free (disc_type);
                    g_free (disc_how);
                    g_free (discount);
                    g_free (taxable);
                    g_free (taxincluded);
                    g_free (tax_table);
                    g_free (date_posted);
                    g_free (due_date);
                    g_free (account_posted);
                    g_free (memo_posted);
                    g_free (accumulatesplits);
                    return;
                }
            }
            (*n_invoices_updated)++;
        }


        // add entry to invoice/bill
        entry = gncEntryCreate (book);
        gncEntryBeginEdit(entry);
        currency = gncInvoiceGetCurrency(invoice);
        if (currency) denom = gnc_commodity_get_fraction(currency);
        // FIXME: Must check for the return value of qof_scan_date!
        qof_scan_date (date, &day, &month, &year);
        {
            GDate *date = g_date_new_dmy(day, month, year);
            gncEntrySetDateGDate (entry, date);
            g_date_free (date);
        }
        timespecFromTime64 (&today, gnc_time (NULL));	// set today to the current date
        gncEntrySetDateEntered (entry, today);
        gncEntrySetDescription (entry, desc);
        gncEntrySetAction (entry, action);
        value = gnc_numeric_zero();
        gnc_exp_parser_parse (quantity, &value, NULL);
        gncEntrySetQuantity (entry, value);
        acc = gnc_account_lookup_for_register (gnc_get_current_root_account (),
                                               account);
        
        if (g_ascii_strcasecmp (type, "BILL") == 0)
        {
            gncEntrySetBillAccount (entry, acc);
            value = gnc_numeric_zero();
            gnc_exp_parser_parse (price, &value, NULL);
            gncEntrySetBillPrice (entry, value);
            gncEntrySetBillTaxable (entry, text2bool (taxable));
            gncEntrySetBillTaxIncluded (entry, text2bool (taxincluded));
            gncEntrySetBillTaxTable (entry, gncTaxTableLookupByName (book, tax_table));
            gncEntryCommitEdit(entry);
            gncBillAddEntry (invoice, entry);
        }
        else if (g_ascii_strcasecmp (type, "INVOICE") == 0)
        {
            gncEntrySetNotes (entry, notes);
            gncEntrySetInvAccount (entry, acc);
            value = gnc_numeric_zero();
            gnc_exp_parser_parse (price, &value, NULL);
            gncEntrySetInvPrice (entry, value);
            gncEntrySetInvTaxable (entry, text2bool (taxable));
            gncEntrySetInvTaxIncluded (entry, text2bool (taxincluded));
            gncEntrySetInvTaxTable (entry, gncTaxTableLookupByName (book, tax_table));
            value = gnc_numeric_zero();
            gnc_exp_parser_parse (discount, &value, NULL);
            gncEntrySetInvDiscount (entry, value);
            gncEntrySetInvDiscountType (entry, text2disc_type (disc_type));
            gncEntrySetInvDiscountHow (entry, text2disc_how (disc_how));
            gncEntryCommitEdit(entry);
            gncInvoiceAddEntry (invoice, entry);
        }
        valid = gtk_tree_model_iter_next (GTK_TREE_MODEL (store), &iter);

        // handle auto posting of invoices
    
        
        if (valid)
            gtk_tree_model_get (GTK_TREE_MODEL (store), &iter, ID, &new_id, -1);
        if (g_strcmp0 (id, new_id) != 0)
        {
            // the next invoice id is different => try to autopost this invoice
            if (qof_scan_date (date_posted, &day, &month, &year))
            {
                // autopost this invoice
                gboolean auto_pay;
                Timespec d1, d2;

                if (g_ascii_strcasecmp (type, "INVOICE") == 0)
                    auto_pay = gnc_prefs_get_bool (GNC_PREFS_GROUP_INVOICE, GNC_PREF_AUTO_PAY);
                else
                    auto_pay = gnc_prefs_get_bool (GNC_PREFS_GROUP_BILL, GNC_PREF_AUTO_PAY);

                d1 = gnc_dmy2timespec (day, month, year);
                // FIXME: Must check for the return value of qof_scan_date!
                qof_scan_date (due_date, &day, &month, &year);	// obtains the due date, or leaves it at date_posted
                d2 = gnc_dmy2timespec (day, month, year);
                acc = gnc_account_lookup_for_register
                      (gnc_get_current_root_account (), account_posted);
                gncInvoicePostToAccount (invoice, acc, &d1, &d2,
                                         memo_posted,
                                         text2bool (accumulatesplits),
                                         auto_pay);
            }

        }
        
        
    }
    // cleanup
    g_free (new_id);
    g_free (id);
    g_free (date_opened);
    g_free (owner_id);
    g_free (billing_id);
    g_free (notes);
    g_free (date);
    g_free (desc);
    g_free (action);
    g_free (account);
    g_free (quantity);
    g_free (price);
    g_free (disc_type);
    g_free (disc_how);
    g_free (discount);
    g_free (taxable);
    g_free (taxincluded);
    g_free (tax_table);
    g_free (date_posted);
    g_free (due_date);
    g_free (account_posted);
    g_free (memo_posted);
    g_free (accumulatesplits);
    
}
static GstTagList *
ape_demux_parse_tags (const guint8 * data, gint size)
{
  GstTagList *taglist = gst_tag_list_new ();

  GST_LOG ("Reading tags from chunk of size %u bytes", size);

  /* get rid of header/footer */
  if (size >= 32 && memcmp (data, "APETAGEX", 8) == 0) {
    data += 32;
    size -= 32;
  }
  if (size > 32 && memcmp (data + size - 32, "APETAGEX", 8) == 0) {
    size -= 32;
  }

  /* read actual tags - at least 10 bytes for tag header */
  while (size >= 10) {
    guint len, n = 8;
    gchar *tag, *val;
    const gchar *gst_tag;
    GType gst_tag_type;

    /* find tag type and size */
    len = GST_READ_UINT32_LE (data);
    while (n < size && data[n] != 0x0)
      n++;
    if (n == size)
      break;
    g_assert (data[n] == 0x0);
    n++;
    if (size - n < len)
      break;

    /* If the tag is empty, skip to the next one */
    if (len == 0)
      goto next_tag;

    /* read */
    tag = g_strndup ((gchar *) data + 8, n - 9);
    val = g_strndup ((gchar *) data + n, len);

    GST_LOG ("tag [%s], val[%s]", tag, val);

    /* special-case 'media' tag, could be e.g. "CD 1/2" */
    if (g_ascii_strcasecmp (tag, "media") == 0) {
      gchar *sp, *sp2;

      g_free (tag);
      tag = g_strdup ("discnumber");
      /* get rid of the medium in front */
      sp = strchr (val, ' ');
      while (sp != NULL && (sp2 = strchr (sp + 1, ' ')) != NULL)
        sp = sp2;
      if (sp) {
        g_memmove (val, sp + 1, strlen (sp + 1) + 1);
      }
    }

    if (ape_demux_get_gst_tag_from_tag (tag, &gst_tag, &gst_tag_type)) {
      GValue v = { 0, };

      switch (gst_tag_type) {
        case G_TYPE_INT:{
          gint v_int;

          if (sscanf (val, "%d", &v_int) == 1) {
            g_value_init (&v, G_TYPE_INT);
            g_value_set_int (&v, v_int);
          }
          break;
        }
        case G_TYPE_UINT:{
          guint v_uint, count;

          if (strcmp (gst_tag, GST_TAG_TRACK_NUMBER) == 0) {
            gint dummy;

            if (sscanf (val, "%u", &v_uint) == 1 && v_uint > 0) {
              g_value_init (&v, G_TYPE_UINT);
              g_value_set_uint (&v, v_uint);
            }
            GST_LOG ("checking for track count: %s", val);
            /* might be 0/N or -1/N to specify that there is only a count */
            if (sscanf (val, "%d/%u", &dummy, &count) == 2 && count > 0) {
              gst_tag_list_add (taglist, GST_TAG_MERGE_APPEND,
                  GST_TAG_TRACK_COUNT, count, NULL);
            }
          } else if (strcmp (gst_tag, GST_TAG_ALBUM_VOLUME_NUMBER) == 0) {
            gint dummy;

            if (sscanf (val, "%u", &v_uint) == 1 && v_uint > 0) {
              g_value_init (&v, G_TYPE_UINT);
              g_value_set_uint (&v, v_uint);
            }
            GST_LOG ("checking for volume count: %s", val);
            /* might be 0/N or -1/N to specify that there is only a count */
            if (sscanf (val, "%d/%u", &dummy, &count) == 2 && count > 0) {
              gst_tag_list_add (taglist, GST_TAG_MERGE_APPEND,
                  GST_TAG_ALBUM_VOLUME_COUNT, count, NULL);
            }
          } else if (sscanf (val, "%u", &v_uint) == 1) {
            g_value_init (&v, G_TYPE_UINT);
            g_value_set_uint (&v, v_uint);
          }
          break;
        }
        case G_TYPE_STRING:{
          g_value_init (&v, G_TYPE_STRING);
          g_value_set_string (&v, val);
          break;
        }
        case G_TYPE_DOUBLE:{
          gdouble v_double;
          gchar *endptr;

          /* floating point strings can be "4,123" or "4.123" depending on
           * the locale. We need to be able to parse and read either version
           * no matter what our current locale is */
          g_strdelimit (val, ",", '.');
          v_double = g_ascii_strtod (val, &endptr);
          if (endptr != val) {
            g_value_init (&v, G_TYPE_DOUBLE);
            g_value_set_double (&v, v_double);
          }

          break;
        }
        default:{
          if (gst_tag_type == GST_TYPE_DATE) {
            gint v_int;

            if (sscanf (val, "%d", &v_int) == 1) {
              GDate *date = g_date_new_dmy (1, 1, v_int);

              g_value_init (&v, GST_TYPE_DATE);
              gst_value_set_date (&v, date);
              g_date_free (date);
            }
          } else {
            GST_WARNING ("Unhandled tag type '%s' for tag '%s'",
                g_type_name (gst_tag_type), gst_tag);
          }
          break;
        }
      }
      if (G_VALUE_TYPE (&v) != 0) {
        gst_tag_list_add_values (taglist, GST_TAG_MERGE_APPEND,
            gst_tag, &v, NULL);
        g_value_unset (&v);
      }
    }
    GST_DEBUG ("Read tag %s: %s", tag, val);
    g_free (tag);
    g_free (val);

    /* move data pointer */
  next_tag:
    size -= len + n;
    data += len + n;
  }

  GST_DEBUG ("Taglist: %" GST_PTR_FORMAT, taglist);
  return taglist;
}
コード例 #20
0
/* Construct the status bar widget. */
static GtkWidget *
libre_impuesto_window_construct_headerbar (LibreImpuestoWindow *impuesto_window)
{
  gint size;
  time_t secs;
  GDate *today;
  struct tm *tm;
  GtkStateFlags state;
  GtkWidget *headerbar;
  gchar buffer[100] = "";
  GtkWidget *header_area;
  GtkWidget *grid_layout;
  GtkStyleContext *context;
  PangoFontDescription *font_desc;
  GtkWidget *label_libre_impuesto, *label_software_libre, *label_date;


  secs = time (NULL);
  tm = localtime (&secs);

  header_area = gtk_box_new (GTK_ORIENTATION_VERTICAL, 1);
  g_object_bind_property (
		impuesto_window, "headerbar-visible",
		header_area, "visible",
		G_BINDING_SYNC_CREATE);

  headerbar = gtk_event_box_new();
  gtk_box_pack_start (GTK_BOX (header_area), 
		      headerbar, FALSE, FALSE, 0);

  gtk_widget_set_name (headerbar, "libre-impuesto-header");
  gtk_widget_set_size_request (headerbar, -1, 56);

  grid_layout = gtk_grid_new ();
  gtk_container_add (GTK_CONTAINER (headerbar), grid_layout);
  gtk_grid_set_column_homogeneous (GTK_GRID(grid_layout), TRUE);
  gtk_grid_set_row_homogeneous (GTK_GRID (grid_layout), TRUE);

  label_libre_impuesto = gtk_label_new (_("Libre Impuestos"));
  gtk_grid_attach (GTK_GRID (grid_layout), label_libre_impuesto, 0, 0, 1, 1);  

  context = gtk_widget_get_style_context (label_libre_impuesto);
  state = gtk_widget_get_state_flags (label_libre_impuesto);
  size = pango_font_description_get_size (gtk_style_context_get_font (
								      context, 
								      state));
  font_desc = pango_font_description_new ();
  pango_font_description_set_weight (font_desc, PANGO_WEIGHT_BOLD);
  pango_font_description_set_size (font_desc, size * PANGO_SCALE_X_LARGE);
  gtk_widget_override_font (label_libre_impuesto, font_desc);
  pango_font_description_free (font_desc);

  gtk_misc_set_alignment (GTK_MISC (label_libre_impuesto), 0.2, 0.4);
  gtk_widget_show (label_libre_impuesto);

  label_software_libre = gtk_label_new (_("www.softwarelibre.org.bo"));
  gtk_grid_attach (GTK_GRID (grid_layout), label_software_libre, 1, 0, 1, 1);  
  gtk_misc_set_alignment (GTK_MISC (label_software_libre), 0.5, 0.8);
  gtk_widget_show (label_software_libre);

  today = g_date_new_dmy((gint)tm->tm_mday, 
			 (gint)tm->tm_mon + 1, 
			 1900 + tm->tm_year);

  g_date_strftime (buffer, 100-1, "%A, %d de %B de %Y", today);
  label_date = gtk_label_new (g_ascii_strup (buffer,100-1));
  g_date_free(today);

  gtk_grid_attach (GTK_GRID (grid_layout), label_date, 2, 0, 1, 1);  
  gtk_misc_set_alignment (GTK_MISC (label_date), 0.9, 0.5);

  return header_area;
}
コード例 #21
0
static GstTagList *
test_taglib_id3mux_create_tags (guint32 mask)
{
    GstTagList *tags;

    tags = gst_tag_list_new_empty ();

    if (mask & (1 << 0)) {
        gst_tag_list_add (tags, GST_TAG_MERGE_KEEP,
                          GST_TAG_ARTIST, TEST_ARTIST, NULL);
    }
    if (mask & (1 << 1)) {
        gst_tag_list_add (tags, GST_TAG_MERGE_KEEP,
                          GST_TAG_TITLE, TEST_TITLE, NULL);
    }
    if (mask & (1 << 2)) {
        gst_tag_list_add (tags, GST_TAG_MERGE_KEEP,
                          GST_TAG_ALBUM, TEST_ALBUM, NULL);
    }
    if (mask & (1 << 3)) {
        GDate *date;

        date = TEST_DATE;
        gst_tag_list_add (tags, GST_TAG_MERGE_KEEP, GST_TAG_DATE, date, NULL);
        g_date_free (date);
    }
    if (mask & (1 << 4)) {
        gst_tag_list_add (tags, GST_TAG_MERGE_KEEP,
                          GST_TAG_TRACK_NUMBER, TEST_TRACK_NUMBER, NULL);
    }
    if (mask & (1 << 5)) {
        gst_tag_list_add (tags, GST_TAG_MERGE_KEEP,
                          GST_TAG_TRACK_COUNT, TEST_TRACK_COUNT, NULL);
    }
    if (mask & (1 << 6)) {
        gst_tag_list_add (tags, GST_TAG_MERGE_KEEP,
                          GST_TAG_ALBUM_VOLUME_NUMBER, TEST_VOLUME_NUMBER, NULL);
    }
    if (mask & (1 << 7)) {
        gst_tag_list_add (tags, GST_TAG_MERGE_KEEP,
                          GST_TAG_ALBUM_VOLUME_COUNT, TEST_VOLUME_COUNT, NULL);
    }
    if (mask & (1 << 8)) {
        gst_tag_list_add (tags, GST_TAG_MERGE_KEEP,
                          GST_TAG_TRACK_GAIN, TEST_TRACK_GAIN, NULL);
    }
    if (mask & (1 << 9)) {
        gst_tag_list_add (tags, GST_TAG_MERGE_KEEP,
                          GST_TAG_ALBUM_GAIN, TEST_ALBUM_GAIN, NULL);
    }
    if (mask & (1 << 10)) {
        gst_tag_list_add (tags, GST_TAG_MERGE_KEEP,
                          GST_TAG_TRACK_PEAK, TEST_TRACK_PEAK, NULL);
    }
    if (mask & (1 << 11)) {
        gst_tag_list_add (tags, GST_TAG_MERGE_KEEP,
                          GST_TAG_ALBUM_PEAK, TEST_ALBUM_PEAK, NULL);
    }
    if (mask & (1 << 12)) {
        gst_tag_list_add (tags, GST_TAG_MERGE_KEEP,
                          GST_TAG_BEATS_PER_MINUTE, TEST_BPM, NULL);
    }
    if (mask & (1 << 13)) {
    }
    return tags;
}
コード例 #22
0
ファイル: gsb_reconcile.c プロジェクト: wazari972/Grisbi
/**
 * finish the reconciliation,
 * called by a click on the finish button
 *
 * \param button
 * \param null
 *
 * \return FALSE
 */
gboolean gsb_reconcile_finish_reconciliation ( GtkWidget *button,
					    gpointer null )
{
    GSList *list_tmp_transactions;
    GDate *date;
    gint account_number;
    gint reconcile_number;
    gsb_real real;
	gchar* tmpstr;

    account_number = gsb_gui_navigation_get_current_account ();

    if ( gsb_real_sub ( gsb_real_add ( utils_real_get_from_string (gtk_entry_get_text ( GTK_ENTRY ( reconcile_initial_balance_entry ))),
				       gsb_data_account_calculate_waiting_marked_balance (account_number)),
			utils_real_get_from_string (gtk_entry_get_text ( GTK_ENTRY ( reconcile_final_balance_entry )))).mantissa != 0 )
    {
	dialogue_warning_hint ( _("There is a variance in balances, check that both final balance and initial balance minus marked transactions are equal."),
				_("Reconciliation can't be completed.") );
	return FALSE;
    }

    /* get and check the reconcile name */
    reconcile_number = gsb_data_reconcile_get_number_by_name (gtk_entry_get_text ( GTK_ENTRY ( reconcile_number_entry )));
    if (reconcile_number)
    {
	dialogue_warning_hint ( _("There is already a reconcile with that name, you must use another name or let it free.\nIf the reconcile name is ending by a number,\nit will be automatically incremented."),
				_("Reconciliation can't be completed.") );
	return FALSE;
    }


    /* get and save the date */
    date = gsb_calendar_entry_get_date (reconcile_new_date_entry);
    if (!date)
    {
	gchar* tmpstr = g_strdup_printf ( _("Invalid date: '%s'"),
						  gtk_entry_get_text ( GTK_ENTRY ( reconcile_new_date_entry )));
	dialogue_warning_hint ( tmpstr,
				_("Reconciliation can't be completed.") );
	g_free ( tmpstr );
	return FALSE;
    }

    if (!strlen (gtk_entry_get_text ( GTK_ENTRY ( reconcile_number_entry ))))
    {
	dialogue_warning_hint ( _("You need to set a name to the reconciliation ; at least, set a number,\nit will be automatically incremented later"),
				_("Reconciliation can't be completed.") );
	return FALSE;
    }

    /* restore the good sort of the list */
    if (transaction_list_sort_get_reconcile_sort ())
    {
	gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON (reconcile_sort_list_button),
				       FALSE );
	gsb_reconcile_list_button_clicked (reconcile_sort_list_button, NULL);
    }

    tmpstr = g_strdup_printf ( _("Last statement: %s"), gsb_format_gdate (date));
    gtk_label_set_text ( GTK_LABEL ( label_last_statement ),
			 tmpstr);
    g_free ( tmpstr );

    /* create the new reconcile structure */
    reconcile_number = gsb_data_reconcile_new (gtk_entry_get_text (GTK_ENTRY (reconcile_number_entry)));
    gsb_data_reconcile_set_account ( reconcile_number, account_number );

    /* set the variables of the reconcile */
    gsb_data_reconcile_set_final_date ( reconcile_number, date );
    g_date_free (date);

    date = gsb_parse_date_string (gtk_label_get_text (GTK_LABEL (reconcile_last_date_label)));
    gsb_data_reconcile_set_init_date ( reconcile_number, date );
    g_free (date);

    real = utils_real_get_from_string ( gtk_entry_get_text (
                        GTK_ENTRY ( reconcile_initial_balance_entry ) ) );
    gsb_data_reconcile_set_init_balance ( reconcile_number, real );

    real = utils_real_get_from_string ( gtk_entry_get_text (
                        GTK_ENTRY ( reconcile_final_balance_entry ) ) );
    gsb_data_reconcile_set_final_balance ( reconcile_number,
					   real );

    /* modify the reconciled transactions */
    list_tmp_transactions = gsb_data_transaction_get_transactions_list ();

    while ( list_tmp_transactions )
    {
	gint transaction_number_tmp;
	transaction_number_tmp = gsb_data_transaction_get_transaction_number (
                        list_tmp_transactions -> data);

	if ( gsb_data_transaction_get_account_number (transaction_number_tmp) == account_number
	     &&
	     ( gsb_data_transaction_get_marked_transaction (transaction_number_tmp) == OPERATION_POINTEE
	       ||
	       gsb_data_transaction_get_marked_transaction (transaction_number_tmp) == OPERATION_TELERAPPROCHEE ))
	{
	    gsb_data_transaction_set_marked_transaction ( transaction_number_tmp,
							  OPERATION_RAPPROCHEE );
	    gsb_data_transaction_set_reconcile_number ( transaction_number_tmp,
							reconcile_number );
	}
	list_tmp_transactions = list_tmp_transactions -> next;
    }

    /* update the P and T to R in the list */
    transaction_list_update_element (ELEMENT_MARK);

    run.mise_a_jour_liste_comptes_accueil = TRUE;

    /* go back to the normal transactions list */
    gsb_reconcile_cancel (NULL, NULL);

    /* reset records in run: to do after gsb_reconcile_cancel */
    g_free (run.reconcile_final_balance);
    if (run.reconcile_new_date)
        g_date_free (run.reconcile_new_date);
    run.reconcile_final_balance = NULL;
    run.reconcile_new_date = NULL;
    run.reconcile_account_number = -1;

    gsb_file_set_modified ( TRUE );

    if ( reconcile_save_last_scheduled_convert )
    {
        gsb_gui_navigation_set_selection ( GSB_SCHEDULER_PAGE, 0, NULL );
        gsb_scheduler_list_select ( reconcile_save_last_scheduled_convert );
        gsb_scheduler_list_edit_transaction ( reconcile_save_last_scheduled_convert );
        reconcile_save_last_scheduled_convert = 0;
    }

    return FALSE;
}
コード例 #23
0
GDate *
gnc_accounting_period_end_gdate (GncAccountingPeriod which,
                                 const GDate *fy_end,
                                 const GDate *contains)
{
    GDate *date;

    if (contains)
    {
        date = g_date_new_dmy(g_date_get_day(contains),
                              g_date_get_month(contains),
                              g_date_get_year(contains));
    }
    else
    {
        date = g_date_new ();
        gnc_gdate_set_today (date);
    }

    switch (which)
    {
    default:
        g_message("Undefined relative time constant %d", which);
        g_date_free(date);
        return 0;

    case GNC_ACCOUNTING_PERIOD_TODAY:
        /* Already have today's date */
        break;

    case GNC_ACCOUNTING_PERIOD_MONTH:
        gnc_gdate_set_month_end(date);
        break;

    case GNC_ACCOUNTING_PERIOD_MONTH_PREV:
        gnc_gdate_set_prev_month_end(date);
        break;

    case GNC_ACCOUNTING_PERIOD_QUARTER:
        gnc_gdate_set_quarter_end(date);
        break;

    case GNC_ACCOUNTING_PERIOD_QUARTER_PREV:
        gnc_gdate_set_prev_quarter_end(date);
        break;

    case GNC_ACCOUNTING_PERIOD_CYEAR:
        gnc_gdate_set_year_end(date);
        break;

    case GNC_ACCOUNTING_PERIOD_CYEAR_PREV:
        gnc_gdate_set_prev_year_end(date);
        break;

    case GNC_ACCOUNTING_PERIOD_FYEAR:
        if (fy_end == NULL)
        {
            g_message("Request for fisal year value but no fiscal year end value provided.");
            g_date_free(date);
            return 0;
        }
        gnc_gdate_set_fiscal_year_end(date, fy_end);
        break;

    case GNC_ACCOUNTING_PERIOD_FYEAR_PREV:
        if (fy_end == NULL)
        {
            g_message("Request for fisal year value but no fiscal year end value provided.");
            g_date_free(date);
            return 0;
        }
        gnc_gdate_set_prev_fiscal_year_end(date, fy_end);
        break;
    }

    return date;
}
コード例 #24
0
ファイル: calendar_fullyear.c プロジェクト: rosedu/osmo
void
display_calendar (guint year, GUI *appGUI)
{
static MESSAGE selected_date[MAX_MONTHS * FULL_YEAR_COLS];

GDate *cdate;
gint calendar_table[MAX_MONTHS * FULL_YEAR_COLS];
guint current_day, current_month, current_year;
guint month;
gint i, idx, day, first_day, days;
gchar tmpbuf[BUFFER_SIZE], tmpbuf2[BUFFER_SIZE];

	for (i = 0; i < MAX_MONTHS * FULL_YEAR_COLS; i++) {
		calendar_table[i] = -1;
	}

	cdate = g_date_new ();
	g_return_if_fail (cdate != NULL);

	for (month = G_DATE_JANUARY; month <= G_DATE_DECEMBER; month++) {
		g_date_set_dmy (cdate, 1, month, year);
		first_day = g_date_get_weekday (cdate);
		days = g_date_get_days_in_month (month, year);

		for (i = 1; i <= days; i++) {
			calendar_table[(month - 1) * FULL_YEAR_COLS + first_day + i - 2] = i;
		}
	}

	g_date_set_time_t (cdate, time (NULL));
	current_day = g_date_get_day (cdate);
	current_month = g_date_get_month (cdate);
	current_year = g_date_get_year (cdate);

	for (month = G_DATE_JANUARY; month <= G_DATE_DECEMBER; month++) {

		for (i = 0; i < FULL_YEAR_COLS; i++) {

			idx = (month - 1) * FULL_YEAR_COLS + i;
			g_signal_handlers_disconnect_by_func (G_OBJECT (appGUI->cal->calendar_buttons[idx]),
			                                      G_CALLBACK (select_date_day_cb), &selected_date[idx]);
			day = calendar_table[idx];

			if (day > 0) {

				if (day == current_day && month == current_month && year == current_year) {
					g_snprintf (tmpbuf2, BUFFER_SIZE, "<b><u>%2d</u></b>", day);
				} else {
					g_snprintf (tmpbuf2, BUFFER_SIZE, "%2d", day);
				}

				if (i % 7 + 1 == G_DATE_SATURDAY || i % 7 + 1 == G_DATE_SUNDAY) {
					g_snprintf (tmpbuf, BUFFER_SIZE, "<span foreground='firebrick'>%s</span>", tmpbuf2);
				} else if (month % 2 == 0) {
					g_snprintf (tmpbuf, BUFFER_SIZE, "<span foreground='medium blue'>%s</span>", tmpbuf2);
				} else {
					g_strlcpy (tmpbuf, tmpbuf2, BUFFER_SIZE);
				}

				g_date_set_dmy (cdate, (GDateDay) day, month,
				                (GDateYear) gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON (appGUI->cal->fy_spinbutton)));
				selected_date[idx].data = (gpointer) g_date_get_julian (cdate);
				selected_date[idx].appGUI = appGUI;
				g_signal_connect (G_OBJECT (appGUI->cal->calendar_buttons[idx]), "clicked",
				                  G_CALLBACK (select_date_day_cb), &selected_date[idx]);
				gtk_button_set_label (GTK_BUTTON (appGUI->cal->calendar_buttons[idx]), "");
				gtk_label_set_markup (GTK_LABEL (GTK_BIN (appGUI->cal->calendar_buttons[idx])->child), tmpbuf);
				gtk_widget_show (appGUI->cal->calendar_buttons[idx]);

			} else {

				gtk_button_set_label (GTK_BUTTON (appGUI->cal->calendar_buttons[idx]), "");
				gtk_widget_hide (GTK_WIDGET (appGUI->cal->calendar_buttons[idx]));

			}
		}
	}

	g_date_free (cdate);
}
コード例 #25
0
ファイル: testgdate.c プロジェクト: 01org/android-bluez-glib
int main(int argc, char** argv)
{
  GDate* d;
  guint32 j;
  GDateMonth m;
  GDateYear y, prev_y;
  GDateDay day;
  gchar buf[101];
  gchar* loc;
  /* Try to get all the leap year cases. */
  GDateYear check_years[] = { 
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
    11, 12, 13, 14, 98, 99, 100, 101, 102, 103, 397, 
    398, 399, 400, 401, 402, 403, 404, 405, 406,
    1598, 1599, 1600, 1601, 1602, 1650, 1651,
    1897, 1898, 1899, 1900, 1901, 1902, 1903, 
    1961, 1962, 1963, 1964, 1965, 1967,
    1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976,
    1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 
    1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 
    1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 
    2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012,
    3000, 3001, 3002, 3998, 3999, 4000, 4001, 4002, 4003
  };
  guint n_check_years = sizeof(check_years)/sizeof(GDateYear);
  guint i;
  gboolean discontinuity;

  g_print("checking GDate...");
  
  TEST("sizeof(GDate) is not more than 8 bytes on this platform", sizeof(GDate) < 9);

  d = g_date_new();

  TEST("Empty constructor produces invalid date", !g_date_valid(d));

  g_date_free(d);

  d = g_date_new_dmy(1,1,1);

  TEST("January 1, Year 1 created and valid", g_date_valid(d));

  j = g_date_get_julian(d);
  
  TEST("January 1, Year 1 is Julian date 1", j == 1);

  TEST("Returned month is January", g_date_get_month(d) == G_DATE_JANUARY);
  TEST("Returned day is 1", g_date_get_day(d) == 1);
  TEST("Returned year is 1", g_date_get_year(d) == 1);

  TEST("Bad month is invalid", !g_date_valid_month(G_DATE_BAD_MONTH));
  TEST("Month 13 is invalid",  !g_date_valid_month(13));
  TEST("Bad day is invalid",   !g_date_valid_day(G_DATE_BAD_DAY));
  TEST("Day 32 is invalid",     !g_date_valid_day(32));
  TEST("Bad year is invalid",  !g_date_valid_year(G_DATE_BAD_YEAR));
  TEST("Bad julian is invalid", !g_date_valid_julian(G_DATE_BAD_JULIAN));
  TEST("Bad weekday is invalid", !g_date_valid_weekday(G_DATE_BAD_WEEKDAY));
  TEST("Year 2000 is a leap year", g_date_is_leap_year(2000));
  TEST("Year 1999 is not a leap year", !g_date_is_leap_year(1999));
  TEST("Year 1996 is a leap year", g_date_is_leap_year(1996));
  TEST("Year 1600 is a leap year", g_date_is_leap_year(1600));
  TEST("Year 2100 is not a leap year", !g_date_is_leap_year(2100));
  TEST("Year 1800 is not a leap year", !g_date_is_leap_year(1800));

  g_date_free(d);
  
  loc = setlocale(LC_ALL,"");
  if (loc) 
    g_print("\nLocale set to %s\n", loc);
  else 
    g_print("\nLocale unchanged\n");

  d = g_date_new();
  g_date_set_time(d, time(NULL));
  TEST("Today is valid", g_date_valid(d));

  g_date_strftime(buf,100,"Today is a %A, %x\n", d);
  g_print("%s", buf);

  g_date_set_time(d, 1);
  TEST("Beginning of Unix epoch is valid", g_date_valid(d));

  g_date_strftime(buf,100,"1 second into the Unix epoch it was a %A, in the month of %B, %x\n", d);
  g_print("%s", buf);

  g_date_set_julian(d, 1);
  TEST("GDate's \"Julian\" epoch's first day is valid", g_date_valid(d));

  g_date_strftime(buf,100,"Our \"Julian\" epoch begins on a %A, in the month of %B, %x\n",
		  d);
  g_print("%s", buf);

  g_date_set_dmy(d, 10, 1, 2000);

  g_date_strftime(buf,100,"%x", d);

  g_date_set_parse(d, buf);
  /* Note: this test will hopefully work, but no promises. */
  TEST("Successfully parsed a %x-formatted string", 
       g_date_valid(d) && 
       g_date_get_month(d) == 1 && 
       g_date_get_day(d) == 10 && 
       g_date_get_year(d) == 2000);
  if (failed)
    g_date_debug_print(d);
  
  g_date_free(d);

  j = G_DATE_BAD_JULIAN;

  i = 0;
  discontinuity = TRUE;
  y      = check_years[0];
  prev_y = G_DATE_BAD_YEAR;
  while (i < n_check_years) 
    {
      guint32 first_day_of_year = G_DATE_BAD_JULIAN;
      guint16 days_in_year = g_date_is_leap_year(y) ? 366 : 365;
      guint   sunday_week_of_year = 0;
      guint   sunday_weeks_in_year = g_date_get_sunday_weeks_in_year(y);
      guint   monday_week_of_year = 0;
      guint   monday_weeks_in_year = g_date_get_monday_weeks_in_year(y);
      guint   iso8601_week_of_year = 0;

      if (discontinuity)
        g_print(" (Break in sequence of requested years to check)\n");

      g_print("Checking year %u", y);

      TEST("Year is valid", g_date_valid_year(y));

      TEST("Number of Sunday weeks in year is 52 or 53", 
	   sunday_weeks_in_year == 52 || sunday_weeks_in_year == 53);
      
      TEST("Number of Monday weeks in year is 52 or 53", 
	   monday_weeks_in_year == 52 || monday_weeks_in_year == 53);
	   
      m = 1;
      while (m < 13) 
	{
	  guint8 dim = g_date_get_days_in_month(m,y);
	  GDate days[31];         /* This is the fast way, no allocation */

	  TEST("Sensible number of days in month", (dim > 0 && dim < 32));

	  TEST("Month between 1 and 12 is valid", g_date_valid_month(m));

	  day = 1;

	  g_date_clear(days, 31);

	  while (day <= dim) 
	    {
	      guint i;
              GDate tmp;

	      TEST("DMY triplet is valid", g_date_valid_dmy(day,m,y));

	      /* Create GDate with triplet */
	      
	      d = &days[day-1];

	      TEST("Cleared day is invalid", !g_date_valid(d));

	      g_date_set_dmy(d,day,m,y);

	      TEST("Set day is valid", g_date_valid(d));

	      if (m == G_DATE_JANUARY && day == 1) 
		{
		  first_day_of_year = g_date_get_julian(d);
		}

	      g_assert(first_day_of_year != G_DATE_BAD_JULIAN);

	      TEST("Date with DMY triplet is valid", g_date_valid(d));
	      TEST("Month accessor works", g_date_get_month(d) == m);
	      TEST("Year accessor works", g_date_get_year(d) == y);
	      TEST("Day of month accessor works", g_date_get_day(d) == day);

	      TEST("Day of year is consistent with Julian dates",
		   ((g_date_get_julian(d) + 1 - first_day_of_year) ==
		    (g_date_get_day_of_year(d))));

	      if (failed) 
		{
		  g_print("first day: %u this day: %u day of year: %u\n", 
			  first_day_of_year, 
			  g_date_get_julian(d),
			  g_date_get_day_of_year(d));
		}
	      
	      if (m == G_DATE_DECEMBER && day == 31) 
		{
		  TEST("Last day of year equals number of days in year", 
		       g_date_get_day_of_year(d) == days_in_year);
		  if (failed) 
		    {
		      g_print("last day: %u days in year: %u\n", 
			      g_date_get_day_of_year(d), days_in_year);
		    }
		}

	      TEST("Day of year is not more than number of days in the year",
		   g_date_get_day_of_year(d) <= days_in_year);

	      TEST("Monday week of year is not more than number of weeks in the year",
		   g_date_get_monday_week_of_year(d) <= monday_weeks_in_year);
	      if (failed)
		{
		  g_print("Weeks in year: %u\n", monday_weeks_in_year);
		  g_date_debug_print(d);
		}
	      TEST("Monday week of year is >= than last week of year",
		   g_date_get_monday_week_of_year(d) >= monday_week_of_year);

	      if (g_date_get_weekday(d) == G_DATE_MONDAY) 
		{
		  
		  TEST("Monday week of year on Monday 1 more than previous day's week of year",
		       (g_date_get_monday_week_of_year(d) - monday_week_of_year) == 1);
		  if ((m == G_DATE_JANUARY && day <= 4) ||
		      (m == G_DATE_DECEMBER && day >= 29)) {
		    TEST("ISO 8601 week of year on Monday Dec 29 - Jan 4 is 1",
			 (g_date_get_iso8601_week_of_year(d) == 1));
		  } else {
		    TEST("ISO 8601 week of year on Monday 1 more than previous day's week of year",
			 (g_date_get_iso8601_week_of_year(d) - iso8601_week_of_year) == 1);
		  }
		}
	      else 
		{
		  TEST("Monday week of year on non-Monday 0 more than previous day's week of year",
		       (g_date_get_monday_week_of_year(d) - monday_week_of_year) == 0);
		  if (!(day == 1 && m == G_DATE_JANUARY)) {
		    TEST("ISO 8601 week of year on non-Monday 0 more than previous day's week of year (",
			 (g_date_get_iso8601_week_of_year(d) - iso8601_week_of_year) == 0);
		  }
		}


	      monday_week_of_year = g_date_get_monday_week_of_year(d);
	      iso8601_week_of_year = g_date_get_iso8601_week_of_year(d);


	      TEST("Sunday week of year is not more than number of weeks in the year",
		   g_date_get_sunday_week_of_year(d) <= sunday_weeks_in_year);
	      if (failed)
		{
		  g_date_debug_print(d);
		}
	      TEST("Sunday week of year is >= than last week of year",
		   g_date_get_sunday_week_of_year(d) >= sunday_week_of_year);

	      if (g_date_get_weekday(d) == G_DATE_SUNDAY) 
		{
		  TEST("Sunday week of year on Sunday 1 more than previous day's week of year",
		       (g_date_get_sunday_week_of_year(d) - sunday_week_of_year) == 1);
		}
	      else 
		{
		  TEST("Sunday week of year on non-Sunday 0 more than previous day's week of year",
		       (g_date_get_sunday_week_of_year(d) - sunday_week_of_year) == 0);
		}

	      sunday_week_of_year = g_date_get_sunday_week_of_year(d);

	      TEST("Date is equal to itself",
		   g_date_compare(d,d) == 0);


	      /*************** Increments ***********/

              i = 1;
              while (i < 402) /* Need to get 400 year increments in */ 
                {
	      
                  /***** Days ******/
                  tmp = *d;
                  g_date_add_days(d, i);

                  TEST("Adding days gives a value greater than previous",
                       g_date_compare(d, &tmp) > 0);

                  g_date_subtract_days(d, i);
                  TEST("Forward days then backward days returns us to current day",
                       g_date_get_day(d) == day);

                  if (failed) 
                    {
                      g_print("  (increment %u, dmy %u %u %u) ", i, day, m, y);
                      g_date_debug_print(d);
                    }

                  TEST("Forward days then backward days returns us to current month",
                       g_date_get_month(d) == m);

                  if (failed) 
                    {
                      g_print("  (increment %u, dmy %u %u %u) ", i, day, m, y);
                      g_date_debug_print(d);
                    }

                  TEST("Forward days then backward days returns us to current year",
                       g_date_get_year(d) == y);

                  if (failed) 
                    {
                      g_print("  (increment %u, dmy %u %u %u) ", i, day, m, y);
                      g_date_debug_print(d);
                    }

                  /******* Months ********/

                  tmp = *d;
                  g_date_add_months(d, i);
                  TEST("Adding months gives a larger value",
                       g_date_compare(d, &tmp) > 0);
                  g_date_subtract_months(d, i);

                  TEST("Forward months then backward months returns us to current month",
                       g_date_get_month(d) == m);

                  if (failed) 
                    {
                      g_print("  (increment %u, dmy %u %u %u) ", i, day, m, y);
                      g_date_debug_print(d);
                    }

                  TEST("Forward months then backward months returns us to current year",
                       g_date_get_year(d) == y);

                  if (failed) 
                    {
                      g_print("  (increment %u, dmy %u %u %u) ", i, day, m, y);
                      g_date_debug_print(d);
                    }

		  
                  if (day < 29) 
                    {
                      /* Day should be unchanged */
		      
                      TEST("Forward months then backward months returns us to current day",
                           g_date_get_day(d) == day);
		      
                      if (failed) 
                        {
                          g_print("  (increment %u, dmy %u %u %u) ", i, day, m, y);
                          g_date_debug_print(d);
                        }
                    }
                  else 
                    {
                      /* reset the day for later tests */
                      g_date_set_day(d, day);
                    }

                  /******* Years ********/

                  tmp = *d;
                  g_date_add_years(d, i);

                  TEST("Adding years gives a larger value",
                       g_date_compare(d,&tmp) > 0);
		      
                  g_date_subtract_years(d, i);

                  TEST("Forward years then backward years returns us to current month",
                       g_date_get_month(d) == m);

                  if (failed) 
                    {
                      g_print("  (increment %u, dmy %u %u %u) ", i, day, m, y);
                      g_date_debug_print(d);
                    }

                  TEST("Forward years then backward years returns us to current year",
                       g_date_get_year(d) == y);

                  if (failed) 
                    {
                      g_print("  (increment %u, dmy %u %u %u) ", i, day, m, y);
                      g_date_debug_print(d);
                    }

                  if (m != 2 && day != 29) 
                    {
                      TEST("Forward years then backward years returns us to current day",
                           g_date_get_day(d) == day);
		      
                      if (failed) 
                        {
                          g_print("  (increment %u, dmy %u %u %u) ", i, day, m, y);
                          g_date_debug_print(d);
                        }
                    }
                  else 
                    {
                      g_date_set_day(d, day); /* reset */
                    }

                  i += 10;
                }

	      /*****  increment test relative to our local Julian count */

              if (!discontinuity) {

                /* We can only run sequence tests between sequential years */
                
                TEST("Julians are sequential with increment 1",
                     j+1 == g_date_get_julian(d));
                if (failed) 
                  {
                    g_print("Out of sequence, prev: %u expected: %u got: %u\n",
                            j, j+1, g_date_get_julian(d));
                  }

                g_date_add_days(d,1);
                TEST("Next day has julian 1 higher",
                     g_date_get_julian(d) == j + 2);
                g_date_subtract_days(d, 1);
                
                if (j != G_DATE_BAD_JULIAN) 
                  {
                    g_date_subtract_days(d, 1);
                    
                    TEST("Previous day has julian 1 lower",
                         g_date_get_julian(d) == j);
                    
                    g_date_add_days(d, 1); /* back to original */
                  }
              }    
              discontinuity = FALSE; /* goes away now */            

              fflush(stdout);
              fflush(stderr);

	      j = g_date_get_julian(d); /* inc current julian */

	      ++day;
	    } 
	  ++m;
	}
      g_print(" done\n");
      ++i;
      prev_y = y;
      y = check_years[i];
      if (prev_y == G_DATE_BAD_YEAR || 
          (prev_y + 1) != y) discontinuity = TRUE;
    }
  
  
  g_print("\n%u tests passed, %u failed\n",passed, notpassed);

  return 0;
}
コード例 #26
0
ファイル: contacts_birthdays.c プロジェクト: rosedu/osmo
void
contacts_create_birthdays_window (GUI *appGUI)
{
GtkWidget           *vbox1;
GtkWidget           *hseparator;
GtkWidget           *hbuttonbox;
GtkWidget           *close_button;
GtkTreeViewColumn   *column;
GtkCellRenderer     *renderer;
GtkWidget           *scrolledwindow;
gint i, n, id, age;
guint32 date;
gchar *text, buffer[BUFFER_SIZE], buff[BUFFER_SIZE];
GtkTreeIter iter, n_iter;
GDate *cdate_birthday, *cdate_current;
guint b_day, b_month, b_year;
guint c_day, c_month, c_year;
gboolean flag, leap;

	cdate_birthday = g_date_new ();
	g_return_if_fail (cdate_birthday != NULL);

	cdate_current = g_date_new ();
	g_return_if_fail (cdate_current != NULL);

	i = n = 0;
	while (gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (appGUI->cnt->contacts_list_store), &iter, NULL, i++)) {
		gtk_tree_model_get (GTK_TREE_MODEL (appGUI->cnt->contacts_list_store), &iter, COLUMN_BIRTH_DAY_DATE, &date, -1);
		if (date) n++;
	}

	if (n == 0) {
		gui_create_dialog (GTK_MESSAGE_INFO, _("No birthdays defined"), GTK_WINDOW (appGUI->main_window));
		return;
	}

	appGUI->cnt->birthdays_window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
	gtk_window_set_title (GTK_WINDOW (appGUI->cnt->birthdays_window), _("Birthdays list"));
	gtk_window_set_position (GTK_WINDOW (appGUI->cnt->birthdays_window), GTK_WIN_POS_CENTER_ON_PARENT);
	gtk_window_set_default_size (GTK_WINDOW (appGUI->cnt->birthdays_window), 
                                 config.contacts_birthdays_win_w, config.contacts_birthdays_win_h);
	gtk_window_set_modal (GTK_WINDOW (appGUI->cnt->birthdays_window), TRUE);
	g_signal_connect (G_OBJECT (appGUI->cnt->birthdays_window), "delete_event",
	                  G_CALLBACK (birthdays_window_close_cb), appGUI);
	gtk_window_set_transient_for (GTK_WINDOW (appGUI->cnt->birthdays_window), GTK_WINDOW (appGUI->main_window));
	gtk_container_set_border_width (GTK_CONTAINER (appGUI->cnt->birthdays_window), 8);
	g_signal_connect (G_OBJECT (appGUI->cnt->birthdays_window), "key_press_event",
	                  G_CALLBACK (birthdays_key_press_cb), appGUI);

	vbox1 = gtk_vbox_new (FALSE, 0);
	gtk_widget_show (vbox1);
	gtk_container_add (GTK_CONTAINER (appGUI->cnt->birthdays_window), vbox1);

	scrolledwindow = gtk_scrolled_window_new (NULL, NULL);
	gtk_widget_show (scrolledwindow);
	gtk_box_pack_start (GTK_BOX (vbox1), scrolledwindow, TRUE, TRUE, 0);

	gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolledwindow), GTK_SHADOW_IN);
	gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolledwindow), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);

	appGUI->cnt->birthdays_list_store = gtk_list_store_new (BIRTHDAYS_NUM_COLUMNS,
	                                                        G_TYPE_STRING, G_TYPE_INT, G_TYPE_STRING,
	                                                        G_TYPE_INT, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INT);

	appGUI->cnt->birthdays_list = gtk_tree_view_new_with_model (GTK_TREE_MODEL (appGUI->cnt->birthdays_list_store));
	gtk_tree_view_set_rules_hint (GTK_TREE_VIEW (appGUI->cnt->birthdays_list), config.contacts_rules_hint);
	gtk_widget_show (appGUI->cnt->birthdays_list);
	GTK_WIDGET_SET_FLAGS (appGUI->cnt->birthdays_list, GTK_CAN_DEFAULT);
	gtk_container_add (GTK_CONTAINER (scrolledwindow), appGUI->cnt->birthdays_list);

	appGUI->cnt->birthdays_list_selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (appGUI->cnt->birthdays_list));

	g_signal_connect (G_OBJECT (appGUI->cnt->birthdays_list), "button_press_event",
	                  G_CALLBACK (birthdays_list_dbclick_cb), appGUI);

	/* create columns */
	renderer = gtk_cell_renderer_text_new ();
	g_object_set (G_OBJECT (renderer), "xpad", 8, NULL);
	column = gtk_tree_view_column_new_with_attributes (_("Name"), renderer, "text", B_COLUMN_NAME, NULL);
	gtk_tree_view_column_set_visible (column, TRUE);
	gtk_tree_view_column_set_expand (column, TRUE);
	gtk_tree_view_append_column (GTK_TREE_VIEW (appGUI->cnt->birthdays_list), column);
	gtk_tree_view_column_set_sort_column_id (column, B_COLUMN_NAME);

	renderer = gtk_cell_renderer_text_new ();
	column = gtk_tree_view_column_new_with_attributes (_("Days to birthday"), renderer, "text", B_COLUMN_DAYS_NUM, NULL);
	gtk_tree_view_column_set_visible (column, FALSE);
	gtk_tree_view_append_column (GTK_TREE_VIEW (appGUI->cnt->birthdays_list), column);

	renderer = gtk_cell_renderer_text_new ();
	g_object_set (G_OBJECT (renderer), "xalign", 1.0, NULL);
	g_object_set (G_OBJECT (renderer), "xpad", 8, NULL);
	column = gtk_tree_view_column_new_with_attributes (_("Days to birthday"), renderer, "text", B_COLUMN_DAYS, NULL);
	gtk_tree_view_column_set_visible (column, TRUE);
	gtk_tree_view_append_column (GTK_TREE_VIEW (appGUI->cnt->birthdays_list), column);
	gtk_tree_view_column_set_sort_column_id (column, B_COLUMN_DAYS_NUM);
	g_signal_emit_by_name (column, "clicked");

	column = gtk_tree_view_column_new_with_attributes (_("Age"), renderer, "text", B_COLUMN_AGE, NULL);
	gtk_tree_view_column_set_visible (column, config.visible_age_column);
	gtk_tree_view_append_column (GTK_TREE_VIEW (appGUI->cnt->birthdays_list), column);
	gtk_tree_view_column_set_sort_column_id (column, B_COLUMN_AGE);

	column = gtk_tree_view_column_new_with_attributes (_("Birthday date"), renderer, "text", B_COLUMN_DATE, NULL);
	gtk_tree_view_column_set_visible (column, config.visible_birthday_date_column);
	gtk_tree_view_append_column (GTK_TREE_VIEW (appGUI->cnt->birthdays_list), column);

	renderer = gtk_cell_renderer_text_new ();
	column = gtk_tree_view_column_new_with_attributes (_("Zodiac sign"), renderer, "text", B_COLUMN_ZODIAC, NULL);
	gtk_tree_view_column_set_visible (column, config.visible_zodiac_sign_column);
	gtk_tree_view_append_column (GTK_TREE_VIEW (appGUI->cnt->birthdays_list), column);

	renderer = gtk_cell_renderer_text_new ();
	column = gtk_tree_view_column_new_with_attributes ("ID", renderer, "text", B_COLUMN_ID, NULL);
	gtk_tree_view_column_set_visible (column, FALSE);
	gtk_tree_view_append_column (GTK_TREE_VIEW (appGUI->cnt->birthdays_list), column);

	gtk_tree_view_set_enable_search (GTK_TREE_VIEW (appGUI->cnt->birthdays_list), FALSE);

	i = 0;

	g_date_set_julian (cdate_current, utl_get_current_julian ());
	c_day = g_date_get_day (cdate_current);
	c_month = g_date_get_month (cdate_current);
	c_year = g_date_get_year (cdate_current);

	while (gtk_tree_model_iter_nth_child (GTK_TREE_MODEL (appGUI->cnt->contacts_list_store), &iter, NULL, i++)) {
		gtk_tree_model_get (GTK_TREE_MODEL (appGUI->cnt->contacts_list_store), &iter, COLUMN_BIRTH_DAY_DATE, &date, -1);

		if (g_date_valid_julian (date)) {

			/* calculate age */
			g_date_set_julian (cdate_birthday, date);
			b_day = g_date_get_day (cdate_birthday);
			b_month = g_date_get_month (cdate_birthday);
			b_year = g_date_get_year (cdate_birthday);

			age = (gint) c_year - b_year;
			if (b_month < c_month || (b_month == c_month && b_day < c_day)) age++;

			if (age < 1) continue;

			/* name */
			flag = FALSE;
			g_snprintf (buff, BUFFER_SIZE, "(%s)", _("None"));

			gtk_tree_model_get (GTK_TREE_MODEL (appGUI->cnt->contacts_list_store), &iter, COLUMN_LAST_NAME, &text, -1);
			if (text != NULL) {
				flag = TRUE;
				if (strcmp (text, buff) == 0) {
					text[0] = '\0';
					flag = FALSE;
				}
				g_strlcpy (buffer, text, BUFFER_SIZE);
				g_free (text);
			}

			gtk_tree_model_get (GTK_TREE_MODEL (appGUI->cnt->contacts_list_store), &iter, COLUMN_FIRST_NAME, &text, -1);
			if (text != NULL) {
				if (strcmp (text, buff) == 0) {
					text[0] = '\0';
				}
				if (flag == TRUE) {
					g_strlcat (buffer, " ", BUFFER_SIZE);
					g_strlcat (buffer, text, BUFFER_SIZE);
				} else {
					g_strlcpy (buffer, text, BUFFER_SIZE);
				}
				g_free (text);
			}

			gtk_tree_model_get (GTK_TREE_MODEL (appGUI->cnt->contacts_list_store), &iter, COLUMN_ID, &id, -1);
			gtk_list_store_append (appGUI->cnt->birthdays_list_store, &n_iter);
			gtk_list_store_set (appGUI->cnt->birthdays_list_store, &n_iter,
			                    B_COLUMN_ID, id, B_COLUMN_NAME, buffer, B_COLUMN_AGE, age, -1);

			/* calculate days to birthday */
			b_year = c_year;
			if ((b_month < c_month) || (b_month == c_month && b_day < c_day)) b_year++;

			leap = FALSE;
			if (g_date_valid_dmy (b_day, b_month, b_year) == FALSE) {
				g_date_set_day (cdate_birthday, b_day - 1);
				leap = TRUE;
			}
			g_date_set_year (cdate_birthday, b_year);

			date = g_date_days_between (cdate_current, cdate_birthday);
			if (date == 0) {
				g_snprintf (buffer, BUFFER_SIZE, "%s", _("today"));
			} else {
				g_snprintf (buffer, BUFFER_SIZE, leap ? "%d + 1" : "%d", date);
			}

			g_date_strftime (buff, BUFFER_SIZE, "%A, ", cdate_birthday);
			g_strlcat (buff, julian_to_str (g_date_get_julian (cdate_birthday), config.date_format), BUFFER_SIZE);

			gtk_list_store_set (appGUI->cnt->birthdays_list_store, &n_iter,
			                    B_COLUMN_DAYS_NUM, date, B_COLUMN_DAYS, buffer,
			                    B_COLUMN_DATE, buff, B_COLUMN_ZODIAC, utl_get_zodiac_name (b_day, b_month), -1);
		}

	}
	g_date_free (cdate_birthday);
	g_date_free (cdate_current);

	hseparator = gtk_hseparator_new ();
	gtk_widget_show (hseparator);
	gtk_box_pack_start (GTK_BOX (vbox1), hseparator, FALSE, TRUE, 4);

	hbuttonbox = gtk_hbutton_box_new ();
	gtk_widget_show (hbuttonbox);
	gtk_box_pack_start (GTK_BOX (vbox1), hbuttonbox, FALSE, TRUE, 0);
	gtk_button_box_set_layout (GTK_BUTTON_BOX (hbuttonbox), GTK_BUTTONBOX_END);
	gtk_box_set_spacing (GTK_BOX (hbuttonbox), 4);

	if (config.default_stock_icons) {
		close_button = gtk_button_new_from_stock (GTK_STOCK_CLOSE);
	} else {
		close_button = gtk_button_new_from_stock (OSMO_STOCK_BUTTON_CLOSE);
	}
	gtk_widget_show (close_button);
	g_signal_connect (close_button, "clicked", G_CALLBACK (button_birthdays_window_close_cb), appGUI);
	gtk_container_add (GTK_CONTAINER (hbuttonbox), close_button);

	gtk_widget_show (appGUI->cnt->birthdays_window);
	gtk_widget_grab_focus (close_button);
}
コード例 #27
0
ファイル: gsb_reconcile.c プロジェクト: wazari972/Grisbi
/**
 * start the reconciliation, called by a click on the
 * reconcile button
 *
 * \param button the button we click to come here
 * \param null not used
 *
 * \return FALSE
 * */
gboolean gsb_reconcile_run_reconciliation ( GtkWidget *button,
                        gpointer null )
{
    GDate *date;
    gint account_number;
    gint reconcile_number;
    gchar *label;
    gchar *string;
    gchar* tmpstr;

    account_number = gsb_gui_navigation_get_current_account ();
    reconcile_number = gsb_data_reconcile_get_account_last_number (account_number);

    label = gsb_reconcile_build_label ( reconcile_number );
    gtk_entry_set_text ( GTK_ENTRY ( reconcile_number_entry ), label );
    g_free ( label );

    /* reset records in run structure if user has changed of account */
    if (run.reconcile_account_number != account_number)
    {
        g_free (run.reconcile_final_balance);
        if (run.reconcile_new_date)
            g_date_free (run.reconcile_new_date);
        run.reconcile_final_balance = NULL;
        run.reconcile_new_date = NULL;
        run.reconcile_account_number = -1;
    }

    /* set last input date/amount if available */
    if (run.reconcile_new_date)
    {
        date = run.reconcile_new_date;
    }
    else
    {
        /* increase the last date of 1 month */
        date = gsb_date_copy (gsb_data_reconcile_get_final_date (reconcile_number));
        if (date)
        {
            GDate *today;
            gchar *string ;

            string = gsb_format_gdate ( date );
            gtk_label_set_text ( GTK_LABEL ( reconcile_last_date_label ),
                    string);
            gtk_widget_set_sensitive ( GTK_WIDGET ( reconcile_last_date_label ),
                    FALSE );
            g_free (string);
            g_date_add_months ( date, 1 );

            /* if etat.reconcile_end_date or the new date is after today, set today */
            today = gdate_today();
            if ( etat.reconcile_end_date || g_date_compare ( date, today) > 0 )
            {
                g_date_free (date);
                date = gdate_today();
            }
            else
                g_date_free (today);

            /* it's not the first reconciliation, set the old balance and unsensitive the old balance entry */
            tmpstr = utils_real_get_string (gsb_data_reconcile_get_final_balance (reconcile_number));
            gtk_entry_set_text ( GTK_ENTRY ( reconcile_initial_balance_entry ), tmpstr);
            g_free ( tmpstr );
            gtk_widget_set_sensitive ( GTK_WIDGET ( reconcile_initial_balance_entry ),
                    FALSE );
        }
        else
        {
            gtk_label_set_text ( GTK_LABEL ( reconcile_last_date_label ), _("None") );

            date = gdate_today();

            /* it's the first reconciliation, set the initial balance and make sensitive the old balance to change
             * it if necessary */
            tmpstr = utils_real_get_string ( gsb_data_account_get_init_balance (account_number, -1));
            gtk_entry_set_text ( GTK_ENTRY ( reconcile_initial_balance_entry ), tmpstr);
            g_free ( tmpstr );
            gtk_widget_set_sensitive ( GTK_WIDGET ( reconcile_initial_balance_entry ), TRUE );
        }
    }

    string = gsb_format_gdate (date);
    gtk_entry_set_text ( GTK_ENTRY ( reconcile_new_date_entry ),
			 string );
    g_free (string);
    g_date_free (date);

    /* set last input amount if available and if the account is the good one */
    gtk_entry_set_text ( GTK_ENTRY ( reconcile_final_balance_entry ),
            (run.reconcile_final_balance) ? run.reconcile_final_balance : "");
    g_free(run.reconcile_final_balance);

    /* set the title */
    tmpstr = g_markup_printf_escaped ( _(" <b>%s reconciliation</b> "),
					     gsb_data_account_get_name (account_number));
    gtk_label_set_markup ( GTK_LABEL (gtk_frame_get_label_widget (GTK_FRAME (reconcile_panel))),
			   tmpstr );
    g_free ( tmpstr );

    /* we go to the reconciliation mode */
    run.equilibrage = 1;

    /* set all the balances for reconciliation */
    gsb_reconcile_update_amounts (NULL, NULL);

    /* set the transactions list to reconciliation mode */
    /* only change the current account */
    reconcile_save_account_display = etat.retient_affichage_par_compte;
    etat.retient_affichage_par_compte = 1;

    /* hide the marked R transactions */
    reconcile_save_show_marked = gsb_data_account_get_r (account_number);
    if (reconcile_save_show_marked)
    {
        gsb_data_account_set_r (account_number, FALSE );
        mise_a_jour_affichage_r (FALSE);
    }

    /* 1 line on the transaction list */
    reconcile_save_rows_number = gsb_data_account_get_nb_rows (account_number);
    if (reconcile_save_rows_number != 1)
        gsb_transactions_list_set_visible_rows_number ( 1 );

    /* sort by method of payment if in conf */
    if (gsb_data_account_get_reconcile_sort_type (account_number))
	gtk_toggle_button_set_active ( GTK_TOGGLE_BUTTON (reconcile_sort_list_button),
				       TRUE );

    gtk_widget_show_all ( reconcile_panel );

    transaction_list_show_toggle_mark (TRUE);

    /* unsensitive all that could change the account number */
    gsb_reconcile_sensitive (FALSE);

    gtk_widget_grab_focus ( GTK_WIDGET ( reconcile_number_entry ) );
    return FALSE;
}
コード例 #28
0
gboolean cd_clock_update_with_time (GldiModuleInstance *myApplet)
{
	CD_APPLET_ENTER;
	//\________________ On recupere l'heure courante.
	time_t epoch = (time_t) time (NULL);
	_get_current_time (epoch, myApplet);
	
	//\________________ On change la date si necessaire.
	int iWidth, iHeight;
	CD_APPLET_GET_MY_ICON_EXTENT (&iWidth, &iHeight);
	gboolean bNewDate = (myData.currentTime.tm_mday != myData.iLastCheckedDay || myData.currentTime.tm_mon != myData.iLastCheckedMonth || myData.currentTime.tm_year != myData.iLastCheckedYear);
	if (bNewDate)
	{
		strftime (s_cDateBuffer, CD_CLOCK_DATE_BUFFER_LENGTH, "%a %d %b", &myData.currentTime);
		myData.iLastCheckedDay = myData.currentTime.tm_mday;
		myData.iLastCheckedMonth = myData.currentTime.tm_mon;
		myData.iLastCheckedYear = myData.currentTime.tm_year;
	}
	if (CD_APPLET_MY_CONTAINER_IS_OPENGL && myConfig.bOldStyle && myConfig.iShowDate == CAIRO_DOCK_INFO_ON_ICON)
	{
		if (bNewDate || myData.iDateTexture == 0)
		{
			if (myData.iDateTexture != 0)
				_cairo_dock_delete_texture (myData.iDateTexture);
			
			double fScale = (double) iWidth / (double) myData.DimensionData.width;
			GldiTextDescription labelDescription;
			memset (&labelDescription, 0, sizeof (GldiTextDescription));
			gldi_text_description_set_font (&labelDescription, (gchar*)"Sans 8");  // casted and then set to null
			labelDescription.fColorStart.rgba.red = myConfig.fDateColor[0];
			labelDescription.fColorStart.rgba.green = myConfig.fDateColor[1];
			labelDescription.fColorStart.rgba.blue = myConfig.fDateColor[2];
			labelDescription.fColorStart.rgba.alpha = 1.;
			labelDescription.bNoDecorations = TRUE;
			cairo_surface_t *pDateSurface = cairo_dock_create_surface_from_text_full (s_cDateBuffer,
				&labelDescription,
				fScale,
				iWidth,
				&myData.iDateWidth, &myData.iDateHeight);
			//g_print ("date : %dx%d\n", myData.iDateWidth, myData.iDateHeight);
			myData.iDateTexture = cairo_dock_create_texture_from_surface (pDateSurface);
			cairo_surface_destroy (pDateSurface);
			labelDescription.cFont = NULL;
			gldi_text_description_reset (&labelDescription);
		}
	}
	if (bNewDate && myConfig.iShowDate == CAIRO_DOCK_INFO_ON_LABEL)
	{
		CD_APPLET_SET_NAME_FOR_MY_ICON (s_cDateBuffer);
	}
	
	//\________________ On dessine avec cette heure.
	myData.iSmoothAnimationStep = 0;
	if (myConfig.bOldStyle)
	{
		if (CD_APPLET_MY_CONTAINER_IS_OPENGL)
			cd_clock_render_analogic_to_texture (myApplet, iWidth, iHeight, &myData.currentTime, 0.);
		else
			cd_clock_draw_analogic (myApplet, iWidth, iHeight, &myData.currentTime);
	}
	else
	{
		cd_clock_draw_text (myApplet, iWidth, iHeight, &myData.currentTime);
		///if (CD_APPLET_MY_CONTAINER_IS_OPENGL)  // on ne sait pas bien dessiner du texte, donc on le fait en cairo, et on transfere tout sur notre texture.
		///	cairo_dock_update_icon_texture (myIcon);
	}
	
	///CD_APPLET_REDRAW_MY_ICON;
	
	//\________________ On teste les alarmes et les taches.
	if (!myConfig.bShowSeconds || myData.currentTime.tm_min != myData.iLastCheckedMinute)  // un g_timeout de 1min ne s'effectue pas forcement a exectement 1 minute d'intervalle, et donc pourrait "sauter" la minute de l'alarme, d'ou le test sur bShowSeconds dans le cas ou l'applet ne verifie que chaque minute.
	{
		myData.iLastCheckedMinute = myData.currentTime.tm_min;
		
		// les alarmes.
		CDClockAlarm *pAlarm;
		guint i;
		for (i = 0; i < myConfig.pAlarms->len; i ++)
		{
			pAlarm = g_ptr_array_index (myConfig.pAlarms, i);
			
			if (myData.currentTime.tm_hour == pAlarm->iHour && myData.currentTime.tm_min == pAlarm->iMinute)
			{
				gboolean bShowAlarm = FALSE, bRemoveAlarm = FALSE;
				if (pAlarm->iDayOfWeek > 0)
				{
					if (pAlarm->iDayOfWeek == 1)
						bShowAlarm = TRUE;
					else if (pAlarm->iDayOfWeek - 1 == myData.currentTime.tm_wday)
						bShowAlarm = TRUE;
					else if (myData.currentTime.tm_wday == 0 || myData.currentTime.tm_wday == 6)  // week-end
					{
						if (pAlarm->iDayOfWeek == 9)
							bShowAlarm = TRUE;
					}
					else if (pAlarm->iDayOfWeek == 8)
						bShowAlarm = TRUE;
				}
				else if (pAlarm->iDayOfMonth > 0)
					bShowAlarm = (pAlarm->iDayOfMonth - 1 == myData.currentTime.tm_mday);
				else  // c'est une alarme qui ne se repete pas.
				{
					bShowAlarm = TRUE;
					bRemoveAlarm = TRUE;
				}
				
				if (bShowAlarm)
				{
					cd_message ("Dring ! %s", pAlarm->cMessage);
					gldi_dialog_show_temporary (pAlarm->cMessage, myIcon, myContainer, 60e3);
					if (pAlarm->cCommand != NULL)
					{
						if (myData.iAlarmPID > 0)
						{
							kill (myData.iAlarmPID, 1);
							myData.iAlarmPID = 0;
						}
						GError *erreur = NULL;
						gchar **argv = g_strsplit (pAlarm->cCommand, " ", -1);
						g_spawn_async (NULL,
							argv,
							NULL,
							0,
							NULL,
							NULL,
							&myData.iAlarmPID,
							&erreur);
						if (erreur != NULL)
						{
							cd_warning ("clock : when trying to execute '%s' : %s", pAlarm->cCommand, erreur->message);
							g_error_free (erreur);
							myData.iAlarmPID = 0;
						}
						g_strfreev (argv);
						cd_message (" --> child_pid : %d", myData.iAlarmPID);
					}
				}
				
				if (bRemoveAlarm)
				{
					cd_message ("Cette alarme ne sera pas repetee");
					g_ptr_array_remove_index (myConfig.pAlarms, i);
					cd_clock_free_alarm (pAlarm);
					/// A FAIRE : effacer l'heure dans le fichier de conf pour cette alarme.
				}
			}
		}
		
		// display missed tasks.
		if (!myData.bTaskCheckedOnce)
		{
			myData.bTaskCheckedOnce = TRUE;
			myData.pMissedTasks = cd_clock_get_missed_tasks (myApplet);
		}
		if (myData.pMissedTasks != NULL)  // so if the dialog was closed before we could acknowledge all the tasks, it will re-open.
		{
			CDClockTask *pTask = myData.pMissedTasks->data;
			gchar *cMessage = _make_missed_task_message (pTask, myApplet);
			CairoDialogAttr attr;
			memset (&attr, 0, sizeof (CairoDialogAttr));
			attr.cText = cMessage;
			attr.bUseMarkup = TRUE;
			attr.cImageFilePath = (gchar *)MY_APPLET_SHARE_DATA_DIR"/icon-task.png";
			const gchar *cButtonsImage[3] = {"ok", NULL, NULL};
			if (myData.pMissedTasks->next != NULL)
			{
				cButtonsImage[0] = "cancel";
				cButtonsImage[1] = "next.png";
			}
			attr.cButtonsImage = cButtonsImage;
			attr.pActionFunc = (CairoDockActionOnAnswerFunc)_on_next_missed_task;
			attr.pUserData = myApplet;
			attr.pFreeDataFunc = NULL;
			attr.iTimeLength = 0;
			attr.pIcon = myIcon;
			attr.pContainer = myContainer;
			gldi_dialog_new (&attr);
			
			g_free (cMessage);
		}
		
		// display next task.
		if (myData.pNextTask != NULL)
		{
			//g_print ("next task : %s\n", myData.pNextTask->cTitle);
			struct tm st;
			st.tm_min = myData.pNextTask->iMinute;
			st.tm_hour = myData.pNextTask->iHour;
			st.tm_mday = myData.pNextTask->iDay;
			st.tm_mon = myData.pNextTask->iMonth;
			st.tm_year = myData.pNextTask->iYear - 1900;
			st.tm_sec = 0;
			st.tm_isdst = myData.currentTime.tm_isdst;
			time_t t = mktime (&st);
			//g_print ("time : %ld, task : %ld\n", epoch, t);
			if (t < epoch)  // la tache est depassee.
			{
				// acknowledge this task
				myData.pNextTask->bAcknowledged = TRUE;
				myData.pBackend->update_task (myData.pNextTask, myApplet);
				
				// look for next task.
				myData.pNextTask = cd_clock_get_next_scheduled_task (myApplet);
			}
			else if (t < epoch + 15*60 && t >= epoch)
			{
				if (t < epoch + 60)
				{
					if (! myData.pNextTask->bFirstWarning)
					{
						//g_print ("first warning\n");
						myData.pNextTask->bFirstWarning = TRUE;
						gchar *cText = g_strdup_printf ("%s\n<b>%s</b>\n %s\n\n%s",
							D_("It's time for the following task:"),
							myData.pNextTask->cTitle?myData.pNextTask->cTitle:D_("No title"),
							myData.pNextTask->cText?myData.pNextTask->cText:"",
							D_("Repeat this message every:"));
						_task_warning (myData.pNextTask, cText);
						g_free (cText);
					}
				}
				else if (! myData.pNextTask->b15mnWarning)
				{
					//g_print ("15 mn warning\n");
					myData.pNextTask->b15mnWarning = TRUE;
					
					gchar *cText = g_strdup_printf ("%s\n<b>%s</b>\n %s",
						D_("This task will begin in 15 minutes:"),
						myData.pNextTask->cTitle?myData.pNextTask->cTitle:D_("No title"),
						myData.pNextTask->cText?myData.pNextTask->cText:"");
					
					CairoDialogAttr attr;
					memset (&attr, 0, sizeof (CairoDialogAttr));
					attr.cText = (gchar *)cText;
					attr.cImageFilePath = (gchar *)MY_APPLET_SHARE_DATA_DIR"/icon-task.png";
					attr.iTimeLength = 60e3;
					attr.bUseMarkup = TRUE;
					attr.pIcon = myIcon;
					attr.pContainer = myContainer;
					gldi_dialog_new (&attr);
					CD_APPLET_DEMANDS_ATTENTION (NULL, 60);
				}
			}
			
			// display next anniversary if it is scheduled in less than 1 day, because anniversary require time to prepare.
			if (myData.pNextAnniversary != NULL)
			{
				if (!myData.pNextAnniversary->b1DayWarning && ! myData.pNextAnniversary->bFirstWarning && ! myData.pNextAnniversary->b15mnWarning)
				{
					GDate* pCurrentDate = g_date_new_dmy (myData.currentTime.tm_mday, myData.currentTime.tm_mon + 1, myData.currentTime.tm_year+1900);
					GDate* pAnnivDate = g_date_new_dmy (myData.pNextAnniversary->iDay, myData.pNextAnniversary->iMonth + 1, myData.currentTime.tm_year+1900);
					gint iDaysToNextAnniversary = g_date_days_between (pCurrentDate, pAnnivDate);
					if (iDaysToNextAnniversary >= 0 && iDaysToNextAnniversary <= 1)
					{
						myData.pNextAnniversary->b1DayWarning = TRUE;
						gchar *cText = g_strdup_printf ("%s\n<b>%s</b>\n %s\n\n%s",
							iDaysToNextAnniversary == 0 ? D_("Today is the following anniversary:") : D_("Tomorrow is the following anniversary:"),
							myData.pNextTask->cTitle?myData.pNextTask->cTitle:D_("No title"),
							myData.pNextTask->cText?myData.pNextTask->cText:"",
							D_("Repeat this message every:"));
						_task_warning (myData.pNextTask, cText);
						g_free (cText);
						myData.pNextAnniversary = cd_clock_get_next_anniversary (myApplet);
					}
					g_date_free (pCurrentDate);
					g_date_free (pAnnivDate);
				}
			}
		}
	}
	
	CD_APPLET_LEAVE(TRUE);
}
コード例 #29
0
ファイル: main.c プロジェクト: wellth/Demo-02
static GtkWidget*
create_window1 (void)
{
	GtkWidget *window, *button1; 
	GtkImage *imageClient, *imageWellth, *imageBG;	
	GError** error = NULL;
	GTimeVal  time;
	GDate    *date_heap;
	
	GDate     date_stack;
	gchar     tmp_buffer[256];

	g_get_current_time( &time );
	date_heap = g_date_new();

	GDate* mod_date = g_date_new ();
	
	g_date_set_time_val( date_heap, &time );
	g_date_strftime( tmp_buffer, 256, "%x", date_heap );
	g_print( "Current date (heap):  %s\n", tmp_buffer );

	//g_date_set_year (mod_date, atoi (parts[2]));
	
	g_date_free( date_heap );
	
	/* Load UI from file */
	MainBuilder = gtk_builder_new ();
	if (!gtk_builder_add_from_file (MainBuilder, UI_FILE, error))
	{
		g_critical ("Couldn't load builder file: %s", (*error)->message);
		g_error_free (*error);
	}

	/* Auto-connect signal handlers */
	gtk_builder_connect_signals (MainBuilder, NULL);

	/* Get the window object from the ui file */
	window = GTK_WIDGET (gtk_builder_get_object (MainBuilder, TOP_WINDOW));
        if (!window)
        {
                g_critical ("Widget \"%s\" is missing in file %s.",
				TOP_WINDOW,
				UI_FILE);
        }

	//GdkPixbufAnimation * pixbufclntanm = gdk_pixbuf_animation_new_from_file(CLIENT_LOGO, error);
	GdkPixbufAnimation * pixbufwlthanm = gdk_pixbuf_animation_new_from_file(WELLTH_LOGO, error);
	//imageClient = (GtkImage *) GTK_WIDGET (gtk_builder_get_object (MainBuilder, "clnt_logo"));
	imageWellth = (GtkImage *) GTK_WIDGET (gtk_builder_get_object (MainBuilder, "wellth_logo"));
	//gtk_image_set_from_animation(GTK_IMAGE(imageClient), pixbufclntanm);
	gtk_image_set_from_animation (GTK_IMAGE(imageWellth), pixbufwlthanm);

	//GdkPixbufAnimation * pixbufBGanm = gdk_pixbuf_animation_new_from_file(BG1, error);
	imageBG = (GtkImage *) GTK_WIDGET (gtk_builder_get_object (MainBuilder, "image1"));
	gtk_image_set_from_animation(GTK_IMAGE(imageBG), pixbufBGanm);
#ifdef DISPLAY_ADD
	GdkPixbufAnimation * pixbufaddanm = gdk_pixbuf_animation_new_from_file(ADDS2, error);
	GtkImage *add = (GtkImage *) GTK_WIDGET (gtk_builder_get_object (MainBuilder, "adds"));
	gtk_image_set_from_animation(GTK_IMAGE(add), pixbufaddanm);
#endif
	button1 = GTK_WIDGET (gtk_builder_get_object (MainBuilder, "main_start_btn"));
 	 g_signal_connect (G_OBJECT (button1), "clicked", G_CALLBACK (start_button_clicked), NULL);

		
	
	priv = g_malloc (sizeof (struct _Private));
	/* ANJUTA: Widgets initialization for WindowMain.ui - DO NOT REMOVE */

	//g_object_unref (MainBuilder);
	
	return window;
}
コード例 #30
0
static void
test_taglib_id3mux_check_tags (GstTagList * tags, guint32 mask)
{
    if (mask & (1 << 0)) {
        gchar *s = NULL;

        fail_unless (gst_tag_list_get_string (tags, GST_TAG_ARTIST, &s));
        fail_unless (g_str_equal (s, TEST_ARTIST));
        g_free (s);
    }
    if (mask & (1 << 1)) {
        gchar *s = NULL;

        fail_unless (gst_tag_list_get_string (tags, GST_TAG_TITLE, &s));
        fail_unless (g_str_equal (s, TEST_TITLE));
        g_free (s);
    }
    if (mask & (1 << 2)) {
        gchar *s = NULL;

        fail_unless (gst_tag_list_get_string (tags, GST_TAG_ALBUM, &s));
        fail_unless (g_str_equal (s, TEST_ALBUM));
        g_free (s);
    }
    if (mask & (1 << 3)) {
        GDate *shouldbe, *date = NULL;

        shouldbe = TEST_DATE;
        fail_unless (gst_tag_list_get_date (tags, GST_TAG_DATE, &date));
        fail_unless (g_date_compare (shouldbe, date) == 0);
        g_date_free (shouldbe);
        g_date_free (date);
    }
    if (mask & (1 << 4)) {
        guint num;

        fail_unless (gst_tag_list_get_uint (tags, GST_TAG_TRACK_NUMBER, &num));
        fail_unless (num == TEST_TRACK_NUMBER);
    }
    if (mask & (1 << 5)) {
        guint count;

        fail_unless (gst_tag_list_get_uint (tags, GST_TAG_TRACK_COUNT, &count));
        fail_unless (count == TEST_TRACK_COUNT);
    }
    if (mask & (1 << 6)) {
        guint num;

        fail_unless (gst_tag_list_get_uint (tags, GST_TAG_ALBUM_VOLUME_NUMBER,
                                            &num));
        fail_unless (num == TEST_VOLUME_NUMBER);
    }
    if (mask & (1 << 7)) {
        guint count;

        fail_unless (gst_tag_list_get_uint (tags, GST_TAG_ALBUM_VOLUME_COUNT,
                                            &count));
        fail_unless (count == TEST_VOLUME_COUNT);
    }
    if (mask & (1 << 8)) {
        gdouble gain;

        fail_unless (gst_tag_list_get_double (tags, GST_TAG_TRACK_GAIN, &gain));
        fail_unless_sorta_equals_float (gain, TEST_TRACK_GAIN);
    }
    if (mask & (1 << 9)) {
        gdouble gain;

        fail_unless (gst_tag_list_get_double (tags, GST_TAG_ALBUM_GAIN, &gain));
        fail_unless_sorta_equals_float (gain, TEST_ALBUM_GAIN);
    }
    if (mask & (1 << 10)) {
        gdouble peak;

        fail_unless (gst_tag_list_get_double (tags, GST_TAG_TRACK_PEAK, &peak));
        fail_unless_sorta_equals_float (peak, TEST_TRACK_PEAK);
    }
    if (mask & (1 << 11)) {
        gdouble peak;

        fail_unless (gst_tag_list_get_double (tags, GST_TAG_ALBUM_PEAK, &peak));
        fail_unless_sorta_equals_float (peak, TEST_ALBUM_PEAK);
    }
    if (mask & (1 << 12)) {
        gdouble bpm;

        fail_unless (gst_tag_list_get_double (tags, GST_TAG_BEATS_PER_MINUTE,
                                              &bpm));
        fail_unless_sorta_equals_float (bpm, TEST_BPM);
    }
    if (mask & (1 << 13)) {
    }
}