static gboolean
create_each_transaction_helper(Transaction *template_txn, void *user_data)
{
    Transaction *new_txn;
    GList *txn_splits, *template_splits;
    Split *copying_split;
    gnc_commodity *first_cmdty = NULL;
    gboolean err_flag = FALSE;
    SxTxnCreationData *creation_data;

    creation_data = (SxTxnCreationData*)user_data;

    /* FIXME: In general, this should [correctly] deal with errors such
       as not finding the approrpiate Accounts and not being able to
       parse the formula|credit/debit strings. */

    new_txn = xaccTransClone(template_txn);
    xaccTransBeginEdit(new_txn);

    g_debug("creating template txn desc [%s] for sx [%s]",
            xaccTransGetDescription(new_txn),
            xaccSchedXactionGetName(creation_data->instance->parent->sx));

    /* clear any copied KVP data */
    qof_instance_set_slots(QOF_INSTANCE(new_txn), kvp_frame_new());

    /* Bug#500427: copy the notes, if any */
    if (xaccTransGetNotes(template_txn) != NULL)
    {
        xaccTransSetNotes(new_txn, g_strdup(xaccTransGetNotes(template_txn)));
    }

    xaccTransSetDate(new_txn,
                     g_date_get_day(&creation_data->instance->date),
                     g_date_get_month(&creation_data->instance->date),
                     g_date_get_year(&creation_data->instance->date));

    /* the accounts and amounts are in the kvp_frames of the splits. */
    template_splits = xaccTransGetSplitList(template_txn);
    txn_splits = xaccTransGetSplitList(new_txn);
    if ((template_splits == NULL) || (txn_splits == NULL))
    {
        g_critical("transaction w/o splits for sx [%s]",
                   xaccSchedXactionGetName(creation_data->instance->parent->sx));
        xaccTransDestroy(new_txn);
        xaccTransCommitEdit(new_txn);
        return FALSE;
    }

    for (;
            txn_splits && template_splits;
            txn_splits = txn_splits->next, template_splits = template_splits->next)
    {
        Split *template_split;
        Account *split_acct;
        gnc_commodity *split_cmdty = NULL;

        /* FIXME: Ick.  This assumes that the split lists will be ordered
           identically. :( They are, but we'd rather not have to count on
           it. --jsled */
        template_split = (Split*)template_splits->data;
        copying_split = (Split*)txn_splits->data;

        if (!_get_template_split_account(creation_data->instance, template_split, &split_acct, creation_data->creation_errors))
        {
            err_flag = TRUE;
            break;
        }

        /* clear out any copied Split frame data. */
        qof_instance_set_slots(QOF_INSTANCE(copying_split), kvp_frame_new());

        split_cmdty = xaccAccountGetCommodity(split_acct);
        if (first_cmdty == NULL)
        {
            first_cmdty = split_cmdty;
            xaccTransSetCurrency(new_txn, first_cmdty);
        }

        xaccSplitSetAccount(copying_split, split_acct);

        {
            gnc_numeric credit_num, debit_num, final;
            gint gncn_error;

            credit_num = gnc_numeric_zero();
            debit_num = gnc_numeric_zero();

            _get_credit_formula_value(creation_data->instance, template_split, &credit_num, creation_data->creation_errors);
            _get_debit_formula_value(creation_data->instance, template_split, &debit_num, creation_data->creation_errors);

            final = gnc_numeric_sub_fixed( debit_num, credit_num );

            gncn_error = gnc_numeric_check(final);
            if (gncn_error != GNC_ERROR_OK)
            {
                GString *err = g_string_new("");
                g_string_printf(err, "error %d in SX [%s] final gnc_numeric value, using 0 instead",
                                gncn_error, xaccSchedXactionGetName(creation_data->instance->parent->sx));
                g_critical("%s", err->str);
                if (creation_data->creation_errors != NULL)
                    *creation_data->creation_errors = g_list_append(*creation_data->creation_errors, err);
                else
                    g_string_free(err, TRUE);
                final = gnc_numeric_zero();
            }
gnm_float
yearfrac (GDate const *from, GDate const *to, go_basis_t basis)
{
	int days;
	gnm_float peryear;

	if (!g_date_valid (from) || !g_date_valid (to))
		return gnm_nan;

	days = go_date_days_between_basis (from, to, basis);

	if (days < 0) {
		const GDate *tmp;
		days = -days;
		tmp = from; from = to; to = tmp;
	}

	switch (basis) {
	case GO_BASIS_ACT_ACT: {
		int y1 = g_date_get_year (from);
		int y2 = g_date_get_year (to);
		GDate d1, d2;
		int feb29s, years;

		d1 = *from;
		gnm_date_add_years (&d1, 1);
		if (g_date_compare (to, &d1) > 0) {
			/* More than one year.  */
			years = y2 + 1 - y1;

			g_date_clear (&d1, 1);
			g_date_set_dmy (&d1, 1, 1, y1);

			g_date_clear (&d2, 1);
			g_date_set_dmy (&d2, 1, 1, y2 + 1);

			feb29s = g_date_get_julian (&d2) - g_date_get_julian (&d1) -
				365 * (y2 + 1 - y1);
		} else {
			/* Less than one year.  */
			years = 1;

			if ((g_date_is_leap_year (y1) && g_date_get_month (from) < 3) ||
			    (g_date_is_leap_year (y2) &&
			     (g_date_get_month (to) * 0x100 + g_date_get_day (to) >= 2 * 0x100 + 29)))
				feb29s = 1;
			else
				feb29s = 0;
		}

		peryear = 365 + (gnm_float)feb29s / years;

		break;
	}

	default:
		peryear = annual_year_basis (NULL, basis, NULL);
	}

	return days / peryear;
}
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;
}
Exemple #4
0
/* This is the only real algorithm related to recurrences.  It goes:
   Step 1) Go forward one period from the reference date.
   Step 2) Back up to align to the phase of the start date.
*/
void
recurrenceNextInstance(const Recurrence *r, const GDate *ref, GDate *next)
{
    PeriodType pt;
    const GDate *start;
    guint mult;
    WeekendAdjust wadj;

    g_return_if_fail(r);
    g_return_if_fail(ref);
    g_return_if_fail(g_date_valid(&r->start));
    g_return_if_fail(g_date_valid(ref));

    /* If the ref date comes before the start date then the next
       occurrence is always the start date, and we're done. */
    start = &r->start;
    if (g_date_compare(ref, start) < 0)
    {
        g_date_set_julian(next, g_date_get_julian(start));
        return;
    }
    g_date_set_julian(next, g_date_get_julian(ref)); /* start at refDate */

    /* Step 1: move FORWARD one period, passing exactly one occurrence. */
    mult = r->mult;
    pt = r->ptype;
    wadj = r->wadj;
    switch (pt)
    {
    case PERIOD_YEAR:
        mult *= 12;             /* fall-through */
    case PERIOD_MONTH:
    case PERIOD_NTH_WEEKDAY:
    case PERIOD_LAST_WEEKDAY:
    case PERIOD_END_OF_MONTH:
        /* Takes care of short months. */
        if (r->wadj == WEEKEND_ADJ_BACK &&
                (pt == PERIOD_YEAR || pt == PERIOD_MONTH || pt == PERIOD_END_OF_MONTH) &&
                (g_date_get_weekday(next) == G_DATE_SATURDAY || g_date_get_weekday(next) == G_DATE_SUNDAY))
        {
            /* Allows the following Friday-based calculations to proceed if 'next'
               is between Friday and the target day. */
            g_date_subtract_days(next, g_date_get_weekday(next) == G_DATE_SATURDAY ? 1 : 2);
        }
        if (r->wadj == WEEKEND_ADJ_BACK &&
                (pt == PERIOD_YEAR || pt == PERIOD_MONTH || pt == PERIOD_END_OF_MONTH) &&
                g_date_get_weekday(next) == G_DATE_FRIDAY)
        {
            GDate tmp_sat;
            GDate tmp_sun;
            g_date_set_julian(&tmp_sat, g_date_get_julian(next));
            g_date_set_julian(&tmp_sun, g_date_get_julian(next));
            g_date_add_days(&tmp_sat, 1);
            g_date_add_days(&tmp_sun, 2);

            if (pt == PERIOD_END_OF_MONTH)
            {
                if (g_date_is_last_of_month(next) ||
                        g_date_is_last_of_month(&tmp_sat) ||
                        g_date_is_last_of_month(&tmp_sun))
                    g_date_add_months(next, mult);
                else
                    /* one fewer month fwd because of the occurrence in this month */
                    g_date_add_months(next, mult - 1);
            }
            else
            {
                if (g_date_get_day(&tmp_sat) == g_date_get_day(start))
                {
                    g_date_add_days(next, 1);
                    g_date_add_months(next, mult);
                }
                else if (g_date_get_day(&tmp_sun) == g_date_get_day(start))
                {
                    g_date_add_days(next, 2);
                    g_date_add_months(next, mult);
                }
                else if (g_date_get_day(next) >= g_date_get_day(start))
                {
                    g_date_add_months(next, mult);
                }
                else if (g_date_is_last_of_month(next))
                {
                    g_date_add_months(next, mult);
                }
                else if (g_date_is_last_of_month(&tmp_sat))
                {
                    g_date_add_days(next, 1);
                    g_date_add_months(next, mult);
                }
                else if (g_date_is_last_of_month(&tmp_sun))
                {
                    g_date_add_days(next, 2);
                    g_date_add_months(next, mult);
                }
                else
                {
                    /* one fewer month fwd because of the occurrence in this month */
                    g_date_add_months(next, mult - 1);
                }
            }
        }
        else if ( g_date_is_last_of_month(next) ||
                  ((pt == PERIOD_MONTH || pt == PERIOD_YEAR) &&
                   g_date_get_day(next) >= g_date_get_day(start)) ||
                  ((pt == PERIOD_NTH_WEEKDAY || pt == PERIOD_LAST_WEEKDAY) &&
                   nth_weekday_compare(start, next, pt) <= 0) )
            g_date_add_months(next, mult);
        else
            /* one fewer month fwd because of the occurrence in this month */
            g_date_add_months(next, mult - 1);
        break;
    case PERIOD_WEEK:
        mult *= 7;              /* fall-through */
    case PERIOD_DAY:
        g_date_add_days(next, mult);
        break;
    case PERIOD_ONCE:
        g_date_clear(next, 1);  /* We already caught the case where ref is */
        return;                 /* earlier than start, so this is invalid. */
    default:
        PERR("Invalid period type");
    }

    /* Step 2: Back up to align to the base phase. To ensure forward
       progress, we never subtract as much as we added (x % mult < mult). */
    switch (pt)
    {
    case PERIOD_YEAR:
    case PERIOD_MONTH:
    case PERIOD_NTH_WEEKDAY:
    case PERIOD_LAST_WEEKDAY:
    case PERIOD_END_OF_MONTH:
    {
        guint dim, n_months;

        n_months = 12 * (g_date_get_year(next) - g_date_get_year(start)) +
                   (g_date_get_month(next) - g_date_get_month(start));
        g_date_subtract_months(next, n_months % mult);

        /* Ok, now we're in the right month, so we just have to align
           the day in one of the three possible ways. */
        dim = g_date_get_days_in_month(g_date_get_month(next),
                                       g_date_get_year(next));
        if (pt == PERIOD_NTH_WEEKDAY || pt == PERIOD_LAST_WEEKDAY)
            g_date_add_days(next, nth_weekday_compare(start, next, pt));
        else if (pt == PERIOD_END_OF_MONTH || g_date_get_day(start) >= dim)
            g_date_set_day(next, dim);  /* last day in the month */
        else
            g_date_set_day(next, g_date_get_day(start)); /*same day as start*/

        /* Adjust for dates on the weekend. */
        if (pt == PERIOD_YEAR || pt == PERIOD_MONTH || pt == PERIOD_END_OF_MONTH)
        {
            if (g_date_get_weekday(next) == G_DATE_SATURDAY || g_date_get_weekday(next) == G_DATE_SUNDAY)
            {
                switch (wadj)
                {
                case WEEKEND_ADJ_BACK:
                    g_date_subtract_days(next, g_date_get_weekday(next) == G_DATE_SATURDAY ? 1 : 2);
                    break;
                case WEEKEND_ADJ_FORWARD:
                    g_date_add_days(next, g_date_get_weekday(next) == G_DATE_SATURDAY ? 2 : 1);
                    break;
                case WEEKEND_ADJ_NONE:
                default:
                    break;
                }
            }
        }

    }
    break;
    case PERIOD_WEEK:
    case PERIOD_DAY:
        g_date_subtract_days(next, g_date_days_between(start, next) % mult);
        break;
    default:
        PERR("Invalid period type");
    }
}
static void
log_manager_got_dates_cb (GObject *manager,
                          GAsyncResult *result,
                          gpointer user_data)
{
  EmpathyLogWindow *window = user_data;
  GList         *dates;
  GList         *l;
  guint          year_selected;
  guint          month_selected;
  gboolean       day_selected = FALSE;
  GDate         *date = NULL;
  GError        *error = NULL;

  if (log_window == NULL)
    return;

  if (!tpl_log_manager_get_dates_finish (TPL_LOG_MANAGER (manager),
        result, &dates, &error)) {
    DEBUG ("Unable to retrieve messages' dates: %s. Aborting",
        error->message);
    empathy_chat_view_append_event (window->chatview_find,
        "Unable to retrieve messages' dates");
      return;
  }

  for (l = dates; l; l = l->next) {
      GDate *d = l->data;

      gtk_calendar_get_date (GTK_CALENDAR (window->calendar_chats),
          &year_selected,
          &month_selected,
          NULL);

      month_selected++;

      if (!l->next) {
          date = d;
      }

      if (g_date_get_year (d) != year_selected ||
          g_date_get_month (d) != month_selected) {
          continue;
      }

      DEBUG ("Marking date: %04u-%02u-%02u", g_date_get_year (d),
          g_date_get_month (d), g_date_get_day (d));

      gtk_calendar_mark_day (GTK_CALENDAR (window->calendar_chats),
          g_date_get_day (d));

      if (l->next) {
          continue;
      }

      day_selected = TRUE;

      gtk_calendar_select_day (GTK_CALENDAR (window->calendar_chats),
          g_date_get_day (d));
  }

  if (!day_selected) {
      /* Unselect the day in the calendar */
      gtk_calendar_select_day (GTK_CALENDAR (window->calendar_chats), 0);
  }

  g_signal_handlers_unblock_by_func (window->calendar_chats,
      log_window_calendar_chats_day_selected_cb,
      window);

  if (date != NULL) {
      /* Show messages of the most recent date */
      log_window_get_messages_for_date (window, date);
  }

  g_list_foreach (dates, (GFunc) g_free, NULL);
  g_list_free (dates);
}
/**
 * Update the example calendar; make sure to take into account the end
 * specification.
 **/
static void
sxftd_update_example_cal( SXFromTransInfo *sxfti )
{
    time64 tmp_tt;
    GDate date, startDate, nextDate;
    GList *schedule = NULL;
    getEndTuple get;

    get = sxftd_get_end_info( sxfti );

    tmp_tt = gnc_date_edit_get_date( sxfti->startDateGDE );
    gnc_gdate_set_time64 (&date, tmp_tt);

    sxftd_update_schedule(sxfti, &date, &schedule);

    /* go one day before what's in the box so we can get the correct start
     * date. */
    startDate = date;
    g_date_subtract_days(&date, 1);
    g_date_clear(&nextDate, 1);
    recurrenceListNextInstance(schedule, &date, &nextDate);

    {
        gchar *name;
        /* get the name */
        name = NULL;
        name = gtk_editable_get_chars(GTK_EDITABLE(sxfti->name), 0, -1);
        gnc_dense_cal_store_update_name(sxfti->dense_cal_model, name);
        g_free(name);
    }

    {
        gchar *schedule_desc;
        schedule_desc = recurrenceListToCompactString(schedule);
        gnc_dense_cal_store_update_info(sxfti->dense_cal_model, schedule_desc);
        g_free(schedule_desc);
    }

    /* Set End date sensitivity */
    gtk_widget_set_sensitive( GTK_WIDGET(sxfti->endDateGDE), (get.type == END_ON_DATE) );
    gtk_widget_set_sensitive( GTK_WIDGET(sxfti->n_occurences), (get.type == END_AFTER_N_OCCS) );

    /* Use the day preceding the start date for the store to find the correct real start date */
    switch (get.type)
    {
    case NEVER_END:
        gnc_dense_cal_store_update_recurrences_no_end(sxfti->dense_cal_model, &date, schedule);
        break;
    case END_ON_DATE:
        gnc_dense_cal_store_update_recurrences_date_end(sxfti->dense_cal_model, &date, schedule, &get.end_date);
        break;
    case END_AFTER_N_OCCS:
        gnc_dense_cal_store_update_recurrences_count_end(sxfti->dense_cal_model, &date, schedule, get.n_occurrences);
        break;
    default:
        g_warning("unknown get.type [%d]\n", get.type);
        break;
    }

    gnc_dense_cal_set_month( sxfti->example_cal, g_date_get_month( &startDate ) );
    gnc_dense_cal_set_year( sxfti->example_cal, g_date_get_year( &startDate ) );

    recurrenceListFree(&schedule);
}
Exemple #7
0
static void check_valid(GDate *next, GDate *ref, GDate *start,
                        guint16 mult, PeriodType pt, WeekendAdjust wadj)
{
    gboolean valid;
    gint startToNext;
    /* FIXME: The WeekendAdjust argument is completely ignored for
       now. */

    valid = g_date_valid(next);
    if (pt == PERIOD_ONCE && g_date_compare(start, ref) <= 0)
        do_test(!valid, "incorrectly valid");
    else
        do_test(valid, "incorrectly invalid");

    if (!valid) return;

    do_test(g_date_compare(ref, next) < 0,
            "next date not strictly later than ref date");
    startToNext = g_date_get_julian(next) - g_date_get_julian(start);

    // Phase test
    switch (pt)
    {
    case PERIOD_YEAR:
        do_test((g_date_get_year(next) - g_date_get_year(start)) % mult == 0,
                "year period phase wrong"); // redundant
        mult *= 12;
        // fall through
    case PERIOD_END_OF_MONTH:
        if (pt == PERIOD_END_OF_MONTH)
            do_test(g_date_is_last_of_month(next), "end of month phase wrong");
        // fall through
    case PERIOD_LAST_WEEKDAY:
    case PERIOD_NTH_WEEKDAY:
    case PERIOD_MONTH:
    {
        gint monthdiff;
        GDateDay day_start, day_next;

        monthdiff = (g_date_get_month(next) - g_date_get_month(start)) +
                    12 * (g_date_get_year(next) - g_date_get_year(start));
        do_test(monthdiff % mult == 0, "month or year phase wrong");

        if (pt == PERIOD_NTH_WEEKDAY || pt == PERIOD_LAST_WEEKDAY)
        {
            guint sweek, nweek;

            do_test(g_date_get_weekday(next) == g_date_get_weekday(start),
                    "weekday phase wrong");
            sweek = (g_date_get_day(start) - 1) / 7;
            nweek = (g_date_get_day(next) - 1) / 7;

            /* 3 cases: either the weeks agree, OR 'next' didn't have
               5 of the weekday that 'start' did, so it's only the
               4th, OR 'start' didn't have 5 of the weekday that
               'next' does and we want the LAST weekday, so it's the
               5th of that weekday */
            do_test(sweek == nweek ||
                    (sweek == 4 && nweek == 3 && (g_date_get_day(next) + 7) >
                     g_date_get_days_in_month(
                         g_date_get_month(next), g_date_get_year(next))) ||
                    (sweek == 3 && nweek == 4 && (pt == PERIOD_LAST_WEEKDAY)),
                    "week of month phase wrong");

        }
        else
        {
            day_start = g_date_get_day(start);
            day_next = g_date_get_day(next);
            if (day_start < 28)
                do_test(day_start == day_next, "dom don't match");
            else if (pt != PERIOD_END_OF_MONTH)
            {
                // the end of month case was already checked above.  near
                // the end of the month, the days should still agree,
                // unless they can't because of a short month.
                do_test(day_start == day_next || g_date_is_last_of_month(next),
                        "dom don't match and next is not eom");
            }
        }
    }
    break;
    case PERIOD_WEEK:
        mult *= 7;
        // fall through
    case PERIOD_DAY:
        do_test((startToNext % mult) == 0, "week or day period phase wrong");
        break;
    case PERIOD_ONCE:
        do_test(startToNext == 0, "period once not on start date");
        break;
    default:
        do_test(FALSE, "invalid PeriodType");
        break;
    }

}
/** popup a calendar next to the entry
 *
 * \param entry the date entry
 *
 * \return a GtkWindow wich contains the calendar
 * */
GtkWidget *gsb_calendar_entry_popup ( GtkWidget *entry )
{
    GtkWidget *popup, *pVBox, *pCalendar, *button, *frame;
    GtkRequisition *popup_size;
    gint x, y;
    gint screen_width = gdk_screen_width ( );
    GDate * date;

    /* make the popup */
    popup = gtk_window_new ( GTK_WINDOW_TOPLEVEL );
    gtk_window_set_modal ( GTK_WINDOW ( popup ), TRUE );
    gtk_window_set_transient_for ( GTK_WINDOW ( popup ),
                        GTK_WINDOW ( run.window ) );
    gtk_window_set_decorated ( GTK_WINDOW ( popup ), FALSE );
    g_signal_connect_swapped ( G_OBJECT ( popup ),
				"destroy",
				G_CALLBACK ( gdk_pointer_ungrab ),
				GDK_CURRENT_TIME );

    /* set the decoration */
    frame = gtk_frame_new ( NULL );
    gtk_container_add ( GTK_CONTAINER ( popup ), frame );
    gtk_widget_show ( frame );

    pVBox = gtk_vbox_new ( FALSE, 5 );
    gtk_container_set_border_width ( GTK_CONTAINER ( pVBox ), 5 );
    gtk_container_add ( GTK_CONTAINER ( frame ), pVBox );
    gtk_widget_show ( pVBox );

    /* get the date */
    date = gsb_calendar_entry_get_date (entry);
    if (!date)
	date = gdate_today ();

    /* set the calendar */
    pCalendar = gtk_calendar_new();
    gtk_calendar_select_month ( GTK_CALENDAR ( pCalendar ), 
				g_date_get_month ( date ) - 1, 
				g_date_get_year ( date ) );
    gtk_calendar_select_day ( GTK_CALENDAR ( pCalendar ), g_date_get_day ( date ) );

    g_signal_connect ( G_OBJECT ( pCalendar ),
		       "day_selected_double_click",
		       G_CALLBACK ( gsb_calendar_entry_select_date ),
		       entry );
    g_signal_connect ( G_OBJECT ( pCalendar ),
		       "key-press-event",
		       G_CALLBACK ( gsb_calendar_entry_calendar_key_press ),
		       entry );
    gtk_box_pack_start ( GTK_BOX ( pVBox ),
			 pCalendar,
			 TRUE,
			 TRUE,
			 0 );
    gtk_widget_show ( pCalendar );

    /* cancel button */
    button = gtk_button_new_with_label ( _("Cancel") );
    g_signal_connect_swapped ( G_OBJECT ( button ),
			       "clicked",
			       G_CALLBACK ( gtk_widget_destroy ),
			       G_OBJECT ( popup ));
    gtk_box_pack_start ( GTK_BOX ( pVBox ),
			 button,
			 TRUE,
			 TRUE,
			 0 );
    gtk_widget_show ( button );

    /* set the position */
    gdk_window_get_origin ( GTK_WIDGET ( entry ) -> window,
			    &x,
			    &y );

    /* on récupère la taille de la popup */
    popup_size = g_malloc0 ( sizeof ( GtkRequisition ));
    gtk_widget_size_request ( GTK_WIDGET ( popup ), popup_size );

    /* pour la soustraire à la position de l'entrée date */
    y -= popup_size -> height;

    /* on décale le popup si on est trop près de bord droit de l'écran */
    if ( x > ( screen_width - popup_size -> width ) )
        x = screen_width - popup_size -> width - 10;

    /* si une des coordonnées est négative, alors la fonction
       gtk_window_move échoue et affiche la popup en 0,0 */
    if ( x < 0 )
	x = 0 ;

    if ( y < 0 )
	y = 0 ;

    gtk_window_move ( GTK_WINDOW ( popup ), x, y );
    gtk_widget_show ( popup );
    gtk_widget_grab_focus ( GTK_WIDGET ( pCalendar ) );
    return ( popup );
}
/**
 * called when a calendar receive a key-press-event
 *
 * \param pCalendar
 * \param ev
 * \param entry
 *
 * \return TRUE to block the signal
 * */
gboolean gsb_calendar_entry_calendar_key_press ( GtkCalendar *pCalendar,
						 GdkEventKey *ev,
						 GtkWidget *entry )
{
    guint day, month, year;
    GDate *date;
    GtkWidget *pTopLevelWidget;

    /* get the popup to destroy it if need */
    pTopLevelWidget = gtk_widget_get_toplevel ( GTK_WIDGET ( pCalendar ) );

    /* most of the time, we will use date so can get it here,
     * think about free it if not used */
    gtk_calendar_get_date ( pCalendar, &year, &month, &day );
    month++;
    date = g_date_new_dmy (day, month, year);

    switch ( ev -> keyval )
    {
	case GDK_Escape :
	    /* just close the calendar if it's a popup */
	    if ( GTK_WIDGET_TOPLEVEL ( pTopLevelWidget ) )
		gtk_widget_destroy ( pTopLevelWidget );
	    g_date_free (date);
	    return TRUE;
	    break ;

	case GDK_Return :
	case GDK_KP_Enter :
	    /* get the date an close the calendar */
	    gtk_entry_set_text ( GTK_ENTRY ( entry ),
				 gsb_format_date ( day, month, year ));
	    if ( GTK_WIDGET_TOPLEVEL ( pTopLevelWidget ) )
		gtk_widget_destroy ( pTopLevelWidget );
	    g_date_free (date);
	    return TRUE;
	    break ;

	    /* from now, it will change date so just use date, modify it and fill day, month, year
	     * we will set the calendar at the end of that function
	     * so after now, only keys which change the date */
	case GDK_Left :
	case GDK_KP_Left:
	case GDK_minus:
	case GDK_KP_Subtract:
	    /* day before */
	    g_date_subtract_days (date, 1);
	    break ;

	case GDK_Right :
	case GDK_KP_Right:
	case GDK_plus:
	case GDK_KP_Add:
	    /* day after */
	    g_date_add_days (date, 1);
	    break ;

	case GDK_Up :
	case GDK_KP_Up :
	    /* prev week */
	    g_date_subtract_days (date, 7);
	    break ;

	case GDK_Down :
	case GDK_KP_Down :
	    /* next week */
	    g_date_add_days (date, 7);
	    break ;

	case GDK_Home :
	case GDK_KP_Home :
	    /* go to first day of the month */
	    g_date_set_day (date, 1);
	    break ;

	case GDK_End :
	case GDK_KP_End :
	    /* go to last day of the month */
	    g_date_set_day (date,
			    g_date_get_days_in_month (month, year));
	    break ;

	case GDK_Page_Up :
	case GDK_KP_Page_Up :
	    /* prev month */
	    g_date_subtract_months (date, 1);
	    break ;

	case GDK_Page_Down :
	case GDK_KP_Page_Down :
	    /* next month */
	    g_date_add_months (date, 1);
	    break ;

	default:
	    return TRUE;
    }

    day = g_date_get_day (date);
    month = g_date_get_month (date);
    year = g_date_get_year (date);
    g_date_free (date);

    /* to avoid a warning */
    gtk_calendar_select_day( pCalendar , 15 );

    month--;
    gtk_calendar_select_month ( pCalendar , month, year );
    gtk_calendar_select_day( pCalendar , day );
    return TRUE;
}
void
ap_assistant_menu_prepare (GtkAssistant *assistant, gpointer user_data)
{
    int nperiods;
    GDate period_begin, period_end, date_now;
    char * str;

    AcctPeriodInfo *info = user_data;

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

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

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

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

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

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

    /* Display the results */
    str = g_strdup_printf (
              /* Translators: %s is a date string. %d is the number of books
               * that will be created. This is a ngettext(3) message (but
               * only for the %d part). */
              ngettext("The earliest transaction date found in this book is %s. "
                       "Based on the selection made above, this book will be split "
                       "into %d book.",
                       "The earliest transaction date found in this book is %s. "
                       "Based on the selection made above, this book will be split "
                       "into %d books.",
                       nperiods),
              info->earliest_str,
              nperiods);
    gtk_label_set_text (GTK_LABEL(info->period_remarks), str);
    g_free (str);
}
void
ap_assistant_book_prepare (GtkAssistant *assistant, gpointer user_data)
{
    QofBook *currbook;
    char close_date_str[MAX_DATE_LENGTH];
    char prev_close_date_str[MAX_DATE_LENGTH];
    const char *period_text;
    char *str;
    const char *cstr;
    int ntrans, nacc;
    GtkTextBuffer *buffer;

    AcctPeriodInfo *info = user_data;

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

    /* Tell user about how the previous book closing went. */
    cstr = get_close_status_str (info);
    gtk_label_set_text (GTK_LABEL(info->close_results), cstr);
    info->close_status = -1;

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

    qof_print_date_dmy_buff (close_date_str, MAX_DATE_LENGTH,
                             g_date_get_day(&info->closing_date),
                             g_date_get_month(&info->closing_date),
                             g_date_get_year(&info->closing_date));

    currbook = gnc_get_current_book();
    ntrans = get_num_xactions_before_date(currbook,
                                          gnc_time64_get_day_end_gdate (&info->closing_date));

    nacc = gnc_account_n_descendants (gnc_book_get_root_account (currbook));

    /* Display the book info */
    period_text =
        _("You have asked for a book to be created. This book "
          "will contain all transactions up to midnight %s "
          "(for a total of %d transactions spread over %d accounts).\n\n "
          "Amend the Title and Notes or Click on 'Forward' to proceed.\n "
          "Click on 'Back' to adjust the dates or 'Cancel'.");
    str = g_strdup_printf (period_text, close_date_str, ntrans, nacc);
    gtk_label_set_text (GTK_LABEL(info->book_details), str);
    g_free (str);

    gtk_widget_show (GTK_WIDGET (info->book_details));

    /* Create default settings for the title, notes fields */
    qof_print_date_dmy_buff (prev_close_date_str, MAX_DATE_LENGTH,
                             g_date_get_day(&info->prev_closing_date),
                             g_date_get_month(&info->prev_closing_date),
                             g_date_get_year(&info->prev_closing_date));

    str = g_strdup_printf (_("Period %s - %s"), prev_close_date_str, close_date_str);
    gtk_entry_set_text (GTK_ENTRY(info->book_title), str);

    buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(info->book_notes));
    gtk_text_buffer_set_text(buffer, str, -1);

    g_free (str);
}
/**
 * check the scheduled transactions if the are in time limit
 * and record the automatic transactions
 * 
 * \param
 * 
 * \return
 * */
void gsb_scheduler_check_scheduled_transactions_time_limit ( void )
{
    GDate *date;
    GSList *tmp_list;
    gboolean automatic_transactions_taken = FALSE;

    devel_debug (NULL);

    /* the scheduled transactions to take will be check here,
     * but the scheduled transactions taken will be add to the already appended ones */

    scheduled_transactions_to_take = NULL;

    /* get the date today + nb_days_before_scheduled */

    /* the date untill we execute the scheduled transactions is :
     * - either today + nb_days_before_scheduled if warn n days before the scheduled
     * - either the end of the month in nb_days_before_scheduled days (so current month or next month)
     *   */
    date = gdate_today ();
    g_date_add_days ( date,
		      nb_days_before_scheduled );
    /* now date is in nb_days_before_scheduled, if we want the transactions of the month,
     * we change date to the end of its month */
    if (execute_scheduled_of_month)
    {
	gint last_day;
	
	last_day = g_date_get_days_in_month ( g_date_get_month (date),
					      g_date_get_year (date));
	g_date_set_day (date, last_day);
    }

    /* check all the scheduled transactions,
     * if automatic, it's taken
     * if manual, appended into scheduled_transactions_to_take */
    tmp_list = gsb_data_scheduled_get_scheduled_list ();

    while ( tmp_list )
    {
	gint scheduled_number;

	scheduled_number = gsb_data_scheduled_get_scheduled_number (tmp_list -> data);

	/* we check that scheduled transaction only if it's not a child of a split */
	if ( !gsb_data_scheduled_get_mother_scheduled_number (scheduled_number)
	     &&
	     gsb_data_scheduled_get_date (scheduled_number)
	     &&
	     g_date_compare ( gsb_data_scheduled_get_date (scheduled_number),
			      date ) <= 0 )
	{
	    if ( gsb_data_scheduled_get_automatic_scheduled (scheduled_number))
	    {
		/* this is an automatic scheduled, we get it */
		gint transaction_number;

		/* take automatically the scheduled transaction untill today */
		transaction_number = gsb_scheduler_create_transaction_from_scheduled_transaction (scheduled_number,
												  0 );
		if ( gsb_data_scheduled_get_split_of_scheduled (scheduled_number))
		    gsb_scheduler_execute_children_of_scheduled_transaction ( scheduled_number,
									      transaction_number );

		scheduled_transactions_taken = g_slist_append ( scheduled_transactions_taken,
								GINT_TO_POINTER (transaction_number));
		automatic_transactions_taken = TRUE;

		/* set the scheduled transaction to the next date,
		 * if it's not finished, we check them again if it need to be
		 * executed more than one time (the easiest way is to check
		 * all again, i don't think it will have thousand of scheduled transactions, 
		 * so no much waste of time...) */
		if (gsb_scheduler_increase_scheduled (scheduled_number))
		{
		    scheduled_transactions_to_take = NULL;
		    tmp_list = gsb_data_scheduled_get_scheduled_list ();
		}
		else
		    /* the scheduled is finish, so we needn't to check it again ... */
		    tmp_list = tmp_list -> next;
	    }
	    else
	    {
		/* it's a manual scheduled transaction, we put it in the slist */
		scheduled_transactions_to_take = g_slist_append ( scheduled_transactions_to_take ,
								  GINT_TO_POINTER (scheduled_number));
		tmp_list = tmp_list -> next;
	    }
	}
	else
	    tmp_list = tmp_list -> next;
    }

    if ( automatic_transactions_taken )
    {
	mise_a_jour_liste_echeances_auto_accueil = 1;
        gsb_file_set_modified ( TRUE );
    }

    if ( scheduled_transactions_to_take )
	mise_a_jour_liste_echeances_manuelles_accueil = 1;

    g_date_free ( date );
}
Exemple #13
0
static gint
time_format_helper (const gchar *format,
		    MrpTime     *t,
		    gchar       *buffer)
{
	gint  len = 0;
	gchar str[5];
	gint  year, month, day;
	gint  hour, min, sec;
	gint  weekday;

	if (!format) {
		return 1;
	}

	year = g_date_get_year (&t->date);
	month = g_date_get_month (&t->date);
	day = g_date_get_day (&t->date);

	hour = t->hour;
	min = t->min;
	sec = t->sec;

	weekday = g_date_get_weekday (&t->date);
	if (weekday == 7) {
		weekday = 0;
	}

	while (*format) {
		register gchar c = *format++;
		register gint tmp;

		if (c != '%') {
			if (buffer) {
				buffer[len] = c;
			}

			len++;
			continue;
		}

		c = *format++;
		switch (c) {
		case 'a':
			/* The abbreviated weekday name (Mon, Tue, ...). */
			if (buffer) {
				strcpy (buffer + len, short_day_names[weekday]);
			}
			len += strlen (short_day_names[weekday]);
			break;
		case 'A':
			/* The full weekday name (Monday, Tuesday, ...). */
			if (buffer) {
				strcpy (buffer + len, day_names[weekday]);
			}
			len += strlen (day_names[weekday]);
			break;
		case 'b':
			/* The abbreviated month name (Jan, Feb, ...). */
			if (buffer) {
				strcpy (buffer + len, short_month_names[month-1]);
			}
			len += strlen (short_month_names[month-1]);
			break;
		case 'B':
			/* The full month name (January, February, ...). */
			if (buffer) {
				strcpy (buffer + len, month_names[month-1]);
			}
			len += strlen (month_names[month-1]);
			break;
		case 'd':
			/* The day of the month (01 - 31). */
			if (buffer) {
				buffer[len] = day / 10 + '0';
				buffer[len+1] = day - 10 * (day / 10) + '0';
			}
			len += 2;
			break;
		case 'e':
			/* The day of the month (1 - 31). */
			if (buffer) {
				if (day > 9) {
					buffer[len] = day / 10 + '0';
					buffer[len+1] = day - 10 * (day / 10) + '0';
				} else {
					buffer[len] = day + '0';
				}
			}
			len += day > 9 ? 2 : 1;
			break;
		case 'H':
			/* The hour using a 24-hour clock (00 - 23). */
			if (buffer) {
				buffer[len] = hour / 10 + '0';
				buffer[len+1] = hour - 10 * (hour / 10) + '0';
			}
			len += 2;
			break;
		case 'I':
			/* The hour using a 12-hour clock (01 - 12). */
			if (buffer) {
				tmp = hour % 12;

				if (tmp == 0) {
					tmp = 12;
				}

				buffer[len] = tmp / 10 + '0';
				buffer[len+1] = tmp - 10 * (tmp / 10) + '0';
			}
			len += 2;
			break;
		case 'j':
			/* The day of the year (001 - 366). */
			g_warning ("%%j not implemented.");
			if (buffer) {
				buffer[len] = ' ';
				buffer[len+1] = ' ';
				buffer[len+2] = ' ';
			}
			len += 3;
			break;
		case 'k':
			/* The hour using a 24-hour clock (0 to 23). */
			if (buffer) {
				if (hour > 9) {
					buffer[len] = hour / 10 + '0';
					buffer[len+1] = hour - 10 * (hour / 10) + '0';
				} else {
					buffer[len] = hour + '0';
				}
			}
			len += hour > 9 ? 2 : 1;
			break;
		case 'l':
			/* The hour using a 12-hour clock (1 - 12). */
			tmp = hour % 12;
			if (tmp == 0) {
				tmp = 12;
			}

			if (buffer) {
				if (tmp > 9) {
					buffer[len] = tmp / 10 + '0';
					buffer[len+1] = tmp - 10 * (tmp / 10) + '0';
				} else {
					buffer[len] = tmp + '0';
				}
			}
			len += tmp > 9 ? 2 : 1;
			break;
		case 'm':
			/* The month number (01 to 12). */
			if (buffer) {
				buffer[len] = month / 10 + '0';
				buffer[len+1] = month - 10 * (month / 10) + '0';
			}
			len += 2;
			break;
		case 'M':
			/* The minute (00 - 59). */
			if (buffer) {
				buffer[len] = min / 10 + '0';
				buffer[len+1] = min - 10 * (min / 10) + '0';
			}
			len += 2;
			break;
		case 'p':
			/* Either 'AM' or 'PM' according  to the given time value. */
			g_warning ("%%p not yet implemented.");
			if (buffer) {
				buffer[len] = ' ';
				buffer[len+1] = ' ';
			}
			len += 2;
			break;
		case 'P':
			/* Like %p but in lowercase. */
			g_warning ("%%P not yet implemented.");
			if (buffer) {
				buffer[len] = ' ';
				buffer[len+1] = ' ';
			}
			len += 2;
			break;
		case 'R':
			/* The time in 24 hour notation (%H:%M). FIXME: use locale. */
			if (buffer) {
				buffer[len] = hour / 10 + '0';
				buffer[len+1] = hour - 10 * (hour / 10) + '0';
			}
			len += 2;

			if (buffer) {
				buffer[len] = ':';
			}
			len++;

			if (buffer) {
				buffer[len] = min / 10 + '0';
				buffer[len+1] = min - 10 * (min / 10) + '0';
			}
			len += 2;
			break;
		case 'S':
			/* The second (00 - 61). */
			if (buffer) {
				buffer[len] = sec / 10 + '0';
				buffer[len+1] = sec - 10 * (sec / 10) + '0';
			}
			len += 2;
			break;
		case 'U':
			/* The week number, (1 - 53), starting with the first
			 * Sunday as the first day of week 1.
			 */
			g_warning ("%%W not implemented");
			break;
		case 'W':
			/* The week number, (1 - 53), starting with the first
			 *  Monday as the first day of week 1.
			 */
			snprintf (str, sizeof (str), "%d", mrp_time2_get_week_number (t, NULL));
			if (buffer) {
				strcpy (buffer + len, str);
			}
			len += strlen (str);
			break;
		case 'y':
			/* The year without a century (range 00 to 99). */
			if (buffer) {
				tmp = year % 100;
				buffer[len] = tmp / 10 + '0';
				tmp -= 10 * (tmp / 10);
				buffer[len+1] = tmp + '0';
			}
			len += 2;
			break;
		case 'Y':
			/* The year including the century. */
			if (buffer) {
				tmp = year;
				buffer[len] = tmp / 1000 + '0';
				tmp -= 1000 * (tmp / 1000);
				buffer[len+1] = tmp / 100 + '0';
				tmp -= 100 * (tmp / 100);
				buffer[len+2] = tmp / 10 + '0';
				tmp -= 10 * (tmp / 10);
				buffer[len+3] = tmp + '0';
			}
			len += 4;
			break;
		default:
			g_warning ("Failed to parse format string.");
			break;
		}
	}

	if (buffer) {
		buffer[len] = 0;
	}

	/* Include the terminating zero. */
	return len + 1;
}
Exemple #14
0
void
mrp_time2_align_next (MrpTime *t, MrpTimeUnit unit)
{
	GDateWeekday weekday;
	GDateMonth   month;

	g_return_if_fail (t != NULL);

	switch (unit) {
	case MRP_TIME_UNIT_HOUR:
		t->min = 0;
		t->sec = 0;
		mrp_time2_add_hours (t, 1);
		break;

	case MRP_TIME_UNIT_TWO_HOURS:
		t->min = 0;
		t->sec = 0;
		mrp_time2_add_hours (t, 2 - t->hour % 2);
		break;

	case MRP_TIME_UNIT_HALFDAY:
		t->min = 0;
		t->sec = 0;
		if (t->hour < 12) {
			t->hour = 12;
		} else {
			t->hour = 0;
			mrp_time2_add_days (t, 1);
		}
		break;

	case MRP_TIME_UNIT_DAY:
		t->hour = 0;
		t->min = 0;
		t->sec = 0;
		mrp_time2_add_days (t, 1);
		break;

	case MRP_TIME_UNIT_WEEK:
		/* FIXME: We currently hardcode monday as week start .*/
		weekday = g_date_get_weekday (&t->date);
		t->hour = 0;
		t->min = 0;
		t->sec = 0;
		mrp_time2_add_days (t, 8 - weekday);
		break;

	case MRP_TIME_UNIT_MONTH:
		t->hour = 0;
		t->min = 0;
		t->sec = 0;
		g_date_set_day (&t->date, 1);
		g_date_add_months (&t->date, 1);
		break;

	case MRP_TIME_UNIT_QUARTER:
		t->hour = 0;
		t->min = 0;
		t->sec = 0;
		g_date_set_day (&t->date, 1);
		month = g_date_get_month (&t->date);
		if (month >= 1 && month <= 3) {
			g_date_set_month (&t->date, 4);
		}
		else if (month >= 4 && month <= 6) {
			g_date_set_month (&t->date, 7);
		}
		else if (month >= 7 && month <= 9) {
			g_date_set_month (&t->date, 10);
		}
		else if (month >= 10 && month <= 12) {
			g_date_set_month (&t->date, 1);
			g_date_add_years (&t->date, 1);
		}
		break;

	case MRP_TIME_UNIT_HALFYEAR:
		g_date_set_day (&t->date, 1);
		t->hour = 0;
		t->min = 0;
		t->sec = 0;
		month = g_date_get_month (&t->date);
		if (month >= 1 && month <= 6) {
			g_date_set_month (&t->date, 7);
		} else if (month >= 7 && month <= 12) {
			g_date_set_month (&t->date, 1);
			g_date_add_years (&t->date, 1);
		}
		break;

	case MRP_TIME_UNIT_YEAR:
		t->hour = 0;
		t->min = 0;
		t->sec = 0;
		g_date_set_day (&t->date, 1);
		g_date_set_month (&t->date, 1);
		g_date_add_years (&t->date, 1);
		break;

	case MRP_TIME_UNIT_NONE:
	default:
		g_assert_not_reached ();
	}
}
Exemple #15
0
Timespec gdate_to_timespec (GDate d)
{
    return gnc_dmy2timespec(g_date_get_day(&d),
                            g_date_get_month(&d),
                            g_date_get_year(&d));
}
Exemple #16
0
static void
gval_write(FILE *file, GValue *gval)
{
	static gint indent = 0;
	gint ii;
	GType gtype;

	if (gval == NULL) return;
	gtype = G_VALUE_TYPE(gval);
	if (gtype == ghb_array_get_type())
	{
		GValue *val;
		gint count;

		indent_fprintf(file, indent, "<array>\n");
		indent++;
		count = ghb_array_len(gval);
		for (ii = 0; ii < count; ii++)
		{
			val = ghb_array_get_nth(gval, ii);
			gval_write(file, val);
		}
		indent--;
		indent_fprintf(file, indent, "</array>\n");
	}
	else if (gtype == ghb_dict_get_type())
	{
		GValue *val;
		GHashTable *dict = g_value_get_boxed(gval);
		GList *link, *keys;
		keys = g_hash_table_get_keys(dict);
		// Sort the dictionary.  Not really necessray, but it makes
		// finding things easier
		keys = g_list_sort(keys, key_cmp);
		link = keys;
		indent_fprintf(file, indent, "<dict>\n");
		indent++;
		while (link)
		{
			gchar *key = (gchar*)link->data;
			val = g_hash_table_lookup(dict, key);
			indent_fprintf(file, indent, "<key>%s</key>\n", key);
			gval_write(file, val);
			link = link->next;
		}
		indent--;
		indent_fprintf(file, indent, "</dict>\n");
		g_list_free(keys);
	}
	else if (gtype == G_TYPE_BOOLEAN)
	{
		gchar *tag;
		if (g_value_get_boolean(gval))
		{
			tag = "true";
		}
		else
		{
			tag = "false";
		}
		indent_fprintf(file, indent, "<%s />\n", tag);
	}
	else if (gtype == g_date_get_type())
	{
		GDate *date;
		date = g_value_get_boxed(gval);
		indent_fprintf(file, indent, "<date>%d-%d-%d</date>\n", 
			g_date_get_year(date),
			g_date_get_month(date),
			g_date_get_day(date)
		);
	}
	else if (gtype == ghb_rawdata_get_type())
	{
		ghb_rawdata_t *data;
		gchar *base64;
		data = g_value_get_boxed(gval);
		base64 = g_base64_encode(data->data, data->size);
		indent_fprintf(file, indent, "<data>\n");
		indent_fprintf(file, 0, "%s\n", base64);
		indent_fprintf(file, indent, "</data>\n");
		g_free(base64);
	}
	else if (gtype == G_TYPE_DOUBLE)
	{
		gdouble val = g_value_get_double(gval);
		indent_fprintf(file, indent, "<real>%.17g</real>\n", val);
	}
	else if (gtype == G_TYPE_INT64)
	{
		gint val = g_value_get_int64(gval);
		indent_fprintf(file, indent, "<integer>%d</integer>\n", val);
	}
	else if (gtype == G_TYPE_INT)
	{
		gint val = g_value_get_int(gval);
		indent_fprintf(file, indent, "<integer>%d</integer>\n", val);
	}
	else if (gtype == G_TYPE_STRING)
	{
		const gchar *str = g_value_get_string(gval);
		gchar *esc = g_markup_escape_text(str, -1);
		indent_fprintf(file, indent, "<string>%s</string>\n", esc);
		g_free(esc);
	}
	else
	{
		// Try to make anything thats unrecognized into a string
		const gchar *str;
		GValue val = {0,};
		g_value_init(&val, G_TYPE_STRING);
		if (g_value_transform(gval, &val))
		{
			str = g_value_get_string(&val);
			gchar *esc = g_markup_escape_text(str, -1);
			indent_fprintf(file, indent, "<string>%s</string>\n", esc);
			g_free(esc);
		}
		else
		{
			g_message("failed to transform");
		}
		g_value_unset(&val);
	}
}
Exemple #17
0
/**
 * export a transaction given in param in the file given in param
 *
 * \param transaction_number
 * \param csv_file
 * \param print_balance will set a balance for each transaction in the csv file
 * 		not set for archive export, set (but usefull ?) for account export
 *
 * \return TRUE ok, FALSE problem
 * */
static gboolean gsb_csv_export_transaction ( gint transaction_number,
					     FILE *csv_file,
					     gboolean print_balance )
{
    gsb_real amount;
    gint return_exponent;
    gint account_number;
	gchar* tmpstr;
	const GDate *value_date, *date;
	gint payment_method;

    account_number = gsb_data_transaction_get_account_number (transaction_number);

    /* Si c'est une ventilation d'opération (càd une opération fille),
    elle n'est pas traitée à la base du "if" mais plus loin, quand
    son opé ventilée sera exportée */
    if ( gsb_data_transaction_get_mother_transaction_number (transaction_number) )
        return TRUE;

    return_exponent = gsb_data_currency_get_floating_point (
                        gsb_data_account_get_currency (account_number));

	/* met la date */
	date = gsb_data_transaction_get_date ( transaction_number );
	if ( date )
	{
	    CSV_CLEAR_FIELD (csv_field_date);
	    csv_field_date = g_strdup_printf ("%d/%d/%d",
					      g_date_get_day ( date ),
					      g_date_get_month ( date ),
					      g_date_get_year ( date ) );
	}

	value_date = gsb_data_transaction_get_value_date ( transaction_number );
	if ( value_date )
	{
	    CSV_CLEAR_FIELD (csv_field_date_val);
	    csv_field_date_val = g_strdup_printf ("%d/%d/%d",
						  g_date_get_day ( value_date ),
						  g_date_get_month ( value_date ),
						  g_date_get_year ( value_date ) );
	}

	/* met le pointage */
        CSV_CLEAR_FIELD (csv_field_pointage);
	switch ( gsb_data_transaction_get_marked_transaction ( transaction_number ) )
	{
	    case OPERATION_NORMALE:
            csv_field_pointage = my_strdup ("");
		break;
	    case OPERATION_POINTEE:
            csv_field_pointage = my_strdup ("P");
		break;
	    case OPERATION_TELERAPPROCHEE:
            csv_field_pointage = my_strdup ("T");
		break;
	    case OPERATION_RAPPROCHEE:
            csv_field_pointage = my_strdup ("R");
		break;

	}

	/* met les notes */
	CSV_CLEAR_FIELD(csv_field_notes);
	if ( gsb_data_transaction_get_notes ( transaction_number ) )
	    csv_field_notes = my_strdup (gsb_data_transaction_get_notes ( transaction_number ));

	/* met le tiers */
	CSV_CLEAR_FIELD(csv_field_tiers);
	csv_field_tiers = g_strdup ( gsb_data_payee_get_name ( gsb_data_transaction_get_party_number ( transaction_number ), FALSE ) );

	/* met le numero du rapprochement */
	if ( gsb_data_transaction_get_reconcile_number ( transaction_number ) )
	{
	    CSV_CLEAR_FIELD (csv_field_rappro);
	    csv_field_rappro = my_strdup ( gsb_data_reconcile_get_name ( gsb_data_transaction_get_reconcile_number ( transaction_number ) ) );
	}

	/* Met les informations bancaires de l'opération. Elles n'existent
	   qu'au niveau de l'opération mère */
	CSV_CLEAR_FIELD(csv_field_info_bank);
	if ( gsb_data_transaction_get_bank_references ( transaction_number ) )
	{
	    csv_field_info_bank = my_strdup ( gsb_data_transaction_get_bank_references ( transaction_number ) );
	}

	/* met le montant, transforme la devise si necessaire */
	amount = gsb_data_transaction_get_adjusted_amount ( transaction_number,
							    return_exponent);
	CSV_CLEAR_FIELD (csv_field_credit);
	if (amount.mantissa >= 0 )
	    csv_field_credit = utils_real_get_string (amount);
	else
	    csv_field_debit  = utils_real_get_string (gsb_real_abs (amount));

	/* met le cheque si c'est un type à numerotation automatique */
	payment_method = gsb_data_transaction_get_method_of_payment_number ( transaction_number );
	CSV_CLEAR_FIELD (csv_field_cheque);
	if (gsb_data_payment_get_automatic_numbering (payment_method))
	    csv_field_cheque = my_strdup ( gsb_data_transaction_get_method_of_payment_content ( transaction_number ) );

	if ( gsb_data_transaction_get_budgetary_number ( transaction_number ) != -1 )
	{
	    CSV_CLEAR_FIELD (csv_field_imput);
	    csv_field_imput = my_strdup ( gsb_data_budget_get_name ( gsb_data_transaction_get_budgetary_number ( transaction_number ), 0, "" ) );

	    if ( gsb_data_transaction_get_sub_budgetary_number ( transaction_number ) != -1 )
	    {
		CSV_CLEAR_FIELD (csv_field_sous_imput);
		csv_field_sous_imput = my_strdup ( gsb_data_budget_get_sub_budget_name ( gsb_data_transaction_get_budgetary_number ( transaction_number ),
											 gsb_data_transaction_get_sub_budgetary_number ( transaction_number ),
											 NULL ) );
	    }
	}

	/* Piece comptable */
	CSV_CLEAR_FIELD (csv_field_piece);
	csv_field_piece = my_strdup ( gsb_data_transaction_get_voucher ( transaction_number ) );

	/* Balance */
	if (print_balance)
	{
	    current_balance = gsb_real_add ( current_balance,
					     amount );
	    CSV_CLEAR_FIELD (csv_field_solde);
	    csv_field_solde = utils_real_get_string (current_balance);
	}

	/* Number */
	CSV_CLEAR_FIELD (csv_field_operation);
	csv_field_operation = g_strdup_printf("%d", transaction_number );

	/* Account name */
	CSV_CLEAR_FIELD (csv_field_account);
	csv_field_account = my_strdup (gsb_data_account_get_name (account_number));

	/* Financial Year */
	if ( gsb_data_transaction_get_financial_year_number ( transaction_number ) != -1 )
	{
	    CSV_CLEAR_FIELD (csv_field_exercice );
	    csv_field_exercice  = my_strdup (gsb_data_fyear_get_name(gsb_data_transaction_get_financial_year_number ( transaction_number )));
	}

	/*  on met soit un virement, soit une ventilation, soit les catégories */

	/* Si c'est une opération ventilée, on recherche toutes les ventilations
	   de cette opération et on les traite immédiatement. */
	/* et les met à la suite */
	/* la catégorie de l'opé sera celle de la première opé de ventilation */
	if ( gsb_data_transaction_get_split_of_transaction ( transaction_number ) )
	{
	    GSList *pSplitTransactionList;

	    CSV_CLEAR_FIELD (csv_field_categ);
	    csv_field_categ = my_strdup (_("Split of transaction"));

	    csv_add_record(csv_file,FALSE, print_balance);

	    pSplitTransactionList = gsb_data_transaction_get_transactions_list ();

	    while ( pSplitTransactionList )
	    {
		gint pSplitTransaction;

		pSplitTransaction = gsb_data_transaction_get_transaction_number (
                        pSplitTransactionList -> data );

		if ( gsb_data_transaction_get_account_number (
         pSplitTransaction ) == gsb_data_transaction_get_account_number (transaction_number)
         &&
         gsb_data_transaction_get_mother_transaction_number (
         pSplitTransaction ) == transaction_number )
		{
		    /* on commence par mettre la catég et sous categ de l'opé et de l'opé de ventilation */
		    CSV_CLEAR_FIELD (csv_field_ventil);
		    csv_field_ventil = my_strdup (_("B")); /* -> mark */

		    CSV_CLEAR_FIELD (csv_field_operation);
		    csv_field_operation = g_strdup_printf("%d", pSplitTransaction );

		    if ( gsb_data_transaction_get_contra_transaction_number ( pSplitTransaction )  > 0)
		    {
			/* c'est un virement */
			CSV_CLEAR_FIELD (csv_field_categ);
			csv_field_categ = my_strdup (_("Transfer"));

			tmpstr = g_strconcat ( "[", gsb_data_account_get_name ( gsb_data_transaction_get_contra_transaction_account ( pSplitTransaction ) ), "]", NULL );
			/* TODO dOm : is it necessary to duplicate memory with my_strdup since it was already newly allocated memory ? */
			CSV_CLEAR_FIELD (csv_field_sous_categ);
			csv_field_sous_categ = my_strdup (tmpstr);
			g_free ( tmpstr );
		    }
		    else
		    {
			if ( gsb_data_transaction_get_category_number ( pSplitTransaction ) != -1 )
			{
			    CSV_CLEAR_FIELD (csv_field_categ);
			    csv_field_categ = my_strdup ( gsb_data_category_get_name ( gsb_data_transaction_get_category_number ( pSplitTransaction ), 0, "" ) );

			    if ( gsb_data_transaction_get_sub_category_number ( pSplitTransaction ) != -1 )
			    {
				CSV_CLEAR_FIELD (csv_field_sous_categ);
				csv_field_sous_categ = my_strdup ( gsb_data_category_get_sub_category_name ( gsb_data_transaction_get_category_number ( pSplitTransaction ),
													 gsb_data_transaction_get_sub_category_number ( pSplitTransaction ),
													 NULL ) );
			    }
			}

		    }

		    /* met les notes de la ventilation */
		    if ( gsb_data_transaction_get_notes ( pSplitTransaction ) )
		    {
			CSV_CLEAR_FIELD (csv_field_notes);
			csv_field_notes = my_strdup (gsb_data_transaction_get_notes ( pSplitTransaction ));
		    }

		    /* met le montant de la ventilation */
		    amount = gsb_data_transaction_get_adjusted_amount ( pSplitTransaction, return_exponent );
		    CSV_CLEAR_FIELD (csv_field_montant);
		    csv_field_montant = utils_real_get_string (amount);

		    /* met le rapprochement */
		    if ( gsb_data_transaction_get_reconcile_number ( pSplitTransaction ) )
		    {
			CSV_CLEAR_FIELD (csv_field_rappro);
			csv_field_rappro = my_strdup ( gsb_data_reconcile_get_name ( gsb_data_transaction_get_reconcile_number ( pSplitTransaction ) ) );
		    }

		    /* met le chèque si c'est un type à numéotation automatique */
		    payment_method = gsb_data_transaction_get_method_of_payment_number ( pSplitTransaction );
		    if (gsb_data_payment_get_automatic_numbering (payment_method))
		    {
			CSV_CLEAR_FIELD (csv_field_cheque);
			csv_field_cheque = my_strdup ( gsb_data_transaction_get_method_of_payment_content ( pSplitTransaction ) );
		    }

		    /* Budgetary lines */
		    if ( gsb_data_transaction_get_budgetary_number ( pSplitTransaction ) != -1 )
		    {
			CSV_CLEAR_FIELD (csv_field_imput);
			csv_field_imput = my_strdup ( gsb_data_budget_get_name ( gsb_data_transaction_get_budgetary_number ( pSplitTransaction ), 0, "" ) );

			if ( gsb_data_transaction_get_sub_budgetary_number ( pSplitTransaction ) != -1 )
			{
			    CSV_CLEAR_FIELD (csv_field_sous_imput);
			    csv_field_sous_imput = my_strdup ( gsb_data_budget_get_sub_budget_name ( gsb_data_transaction_get_budgetary_number ( pSplitTransaction ),
												     gsb_data_transaction_get_sub_budgetary_number ( pSplitTransaction ),
												     NULL ) );
			}
		    }

		    /* Piece comptable */
		    CSV_CLEAR_FIELD (csv_field_piece);
		    csv_field_piece = my_strdup ( gsb_data_transaction_get_voucher ( pSplitTransaction ) );

		    /* Financial Year */
		    if ( gsb_data_transaction_get_financial_year_number ( pSplitTransaction ) != -1 )
		    {
			CSV_CLEAR_FIELD (csv_field_exercice );
			csv_field_exercice  = my_strdup (gsb_data_fyear_get_name(gsb_data_transaction_get_financial_year_number ( pSplitTransaction )));
		    }

		    csv_add_record(csv_file,FALSE, print_balance);
		}

		pSplitTransactionList = pSplitTransactionList -> next;
	    }
	    csv_clear_fields(TRUE);
	}
	else
	{
	    gchar *tmpstr;
	    gint contra_transaction_number = gsb_data_transaction_get_contra_transaction_number ( transaction_number );

	    switch (contra_transaction_number)
	    {
		case 0:
		    /* normal category */
		    if ( gsb_data_transaction_get_category_number ( transaction_number ) != -1 )
		    {
			CSV_CLEAR_FIELD (csv_field_categ);
			csv_field_categ = my_strdup ( gsb_data_category_get_name ( gsb_data_transaction_get_category_number ( transaction_number ), 0, "" ) );

			if ( gsb_data_transaction_get_sub_category_number ( transaction_number ) != -1 )
			{
			    CSV_CLEAR_FIELD (csv_field_sous_categ);
			    csv_field_sous_categ = my_strdup ( gsb_data_category_get_sub_category_name ( gsb_data_transaction_get_category_number ( transaction_number ),
												     gsb_data_transaction_get_sub_category_number ( transaction_number ),
												     NULL ) );
			}
		    }
		    break;
		case -1:
		    /* transfer to deleted account */
		    CSV_CLEAR_FIELD (csv_field_categ);
		    csv_field_categ = my_strdup (_("Transfer"));

		    tmpstr = g_strconcat ( "[", _("Deleted account"), "]", NULL );
		    /* TODO dOm : is it necessary to duplicate memory with my_strdup since it was already newly allocated memory ? */
		    CSV_CLEAR_FIELD (csv_field_sous_categ);
		    csv_field_sous_categ = my_strdup (tmpstr);
		    g_free ( tmpstr );

		    break;
		default:
		    /* transfer */
		    CSV_CLEAR_FIELD (csv_field_categ);
		    csv_field_categ = my_strdup (_("Transfer"));

		    tmpstr = g_strconcat ( "[", gsb_data_account_get_name ( gsb_data_transaction_get_contra_transaction_account ( transaction_number ) ), "]", NULL );
		    /* TODO dOm : is it necessary to duplicate memory with my_strdup since it was already newly allocated memory ? */
		    CSV_CLEAR_FIELD (csv_field_sous_categ);
		    csv_field_sous_categ = my_strdup (tmpstr);
		    g_free ( tmpstr );
	    }
	    csv_add_record(csv_file,TRUE, print_balance);
	}
    return TRUE;
}
Exemple #18
0
void
calendar_draw_page (GtkPrintOperation *operation, GtkPrintContext *context, gint npage, gpointer user_data)
{
	PangoLayout *layout;
	PangoFontDescription *month_name_font, *day_name_font, *day_num_font, *event_font;
	cairo_t *cr;
	GDate *date;
	gdouble page_width, page_height, day_width, day_height;
	gint text_width, text_height, header_height, event_height, mnf_height, dnf_height, duf_height;
	gint day, month, i, j;
	guint32 julian;
	gboolean monday, actual;

	gchar buffer[BUFFER_SIZE];

	gint padding = config.cal_print_padding;

	GUI *appGUI = (GUI *) user_data;

	date = g_date_new_julian (g_date_get_julian (appGUI->cal->date));
	g_return_if_fail (date != NULL);

	cr = gtk_print_context_get_cairo_context (context);
	layout = gtk_print_context_create_pango_layout (context);

	month_name_font = pango_font_description_from_string (config.cal_print_month_name_font);
	day_name_font = pango_font_description_from_string (config.cal_print_day_name_font);
	day_num_font = pango_font_description_from_string (config.cal_print_day_num_font);
	event_font = pango_font_description_from_string (config.cal_print_event_font);

	pango_layout_set_text (layout, "Aj", -1);

	pango_layout_set_font_description (layout, month_name_font);
	pango_layout_get_pixel_size (layout, NULL, &mnf_height);
	mnf_height *= 1.2;

	pango_layout_set_font_description (layout, day_name_font);
	pango_layout_get_pixel_size (layout, NULL, &dnf_height);
	dnf_height *= 1.2;

	pango_layout_set_font_description (layout, day_num_font);
	pango_layout_get_pixel_size (layout, NULL, &duf_height);

	page_width = gtk_print_context_get_width (context);
	day_width = page_width / 7;

	page_height = gtk_print_context_get_height (context);
	header_height = mnf_height + dnf_height;
	day_height = (page_height - header_height) / 6;
	event_height = day_height - duf_height - padding * 3;

	cairo_set_line_width (cr, 1);
	monday = (config.display_options & GUI_CALENDAR_WEEK_START_MONDAY) ? TRUE : FALSE;


	/* Month and year */
	pango_layout_set_font_description (layout, month_name_font);
	g_date_strftime (buffer, BUFFER_SIZE, "%B %Y", date);
	pango_layout_set_text (layout, buffer, -1);
	pango_layout_get_pixel_size (layout, &text_width, NULL);

	cairo_move_to (cr, (page_width - text_width) / 2, 0);
	pango_cairo_show_layout (cr, layout);


	/* Day names */
	pango_layout_set_font_description (layout, day_name_font);

	for (i = 0; i < 7; i++) {
		g_snprintf (buffer, BUFFER_SIZE, "%s", utl_get_day_name (i + 7 + monday, FALSE));
		pango_layout_set_text (layout, buffer, -1);
		pango_layout_get_pixel_size (layout, &text_width, NULL);
		cairo_move_to (cr, day_width * i + (day_width - text_width) / 2, mnf_height);
		pango_cairo_show_layout (cr, layout);
	}


	/* Day */
	g_date_set_day (date, 1);
	day = g_date_get_weekday (date);
	month = g_date_get_month (date);

	day = monday ? day - 1 : day % 7;

	if (day > 0)
		g_date_subtract_days (date, day);

	day = g_date_get_day (date);
	julian = g_date_get_julian (date);

	pango_layout_set_wrap (layout, PANGO_WRAP_WORD_CHAR);
	pango_layout_set_width (layout, (day_width - padding * 2) * PANGO_SCALE);
	pango_layout_set_height (layout, event_height * PANGO_SCALE);
	pango_layout_set_ellipsize (layout, PANGO_ELLIPSIZE_END);
	pango_layout_set_indent (layout, -4 * PANGO_SCALE);

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

		for (j = 0; j < 7; j++) {

			actual = (month == g_date_get_month (date)) ? TRUE : FALSE;
			day = g_date_get_day (date);

			cairo_rectangle (cr, day_width * j, header_height + day_height * i, day_width, day_height);

			if (actual) {
				cairo_set_source_rgb (cr, 1.0, 1.0, 1.0);
			} else {
				cairo_set_source_rgb (cr, 0.8, 0.8, 0.8);
			}

			cairo_fill_preserve (cr);
			cairo_set_source_rgb (cr, 0, 0, 0);
			cairo_stroke (cr);

			pango_layout_set_font_description (layout, day_num_font);

			if (actual) {

				cairo_move_to (cr, day_width * j + padding, header_height + day_height * i + padding);

				if ((j == 0 && !monday) || (j == 5 && monday) || j == 6) {
					g_snprintf (buffer, BUFFER_SIZE, "<span color=\"red\">%d</span>", day);
				} else {
					g_snprintf (buffer, BUFFER_SIZE, "%d", day);
				}

				pango_layout_set_markup (layout, buffer, -1);
				pango_cairo_show_layout (cr, layout);

				cal_print_get_events (buffer, julian, appGUI);

				pango_layout_set_markup (layout, "", -1);
				pango_layout_set_text (layout, buffer, -1);
				pango_layout_set_font_description (layout, event_font);
				pango_layout_get_pixel_size (layout, NULL, &text_height);
				cairo_move_to (cr, day_width * j + padding, header_height + day_height * (i + 1) - text_height - padding);
				pango_cairo_show_layout (cr, layout);

			} else {

				cairo_move_to (cr, day_width * j + padding, header_height + day_height * i + padding);
				g_snprintf (buffer, BUFFER_SIZE, "<span color=\"white\">%d</span>", day);
				pango_layout_set_markup (layout, buffer, -1);
				pango_cairo_show_layout (cr, layout);

			}

			g_date_add_days (date, 1);
			julian++;

		}
	}

	g_date_free (date);
	pango_font_description_free (month_name_font);
	pango_font_description_free (day_name_font);
	pango_font_description_free (day_num_font);
	pango_font_description_free (event_font);
	g_object_unref (layout);
}
Exemple #19
0
/**
 * create a qif export, according to the filename, the account
 * and eventually, limit the export to the archive if exists
 * this will export all the transactions of the account (except if we ask for an archive...)
 * 	including the archived transactions
 *
 * \param filename that file will be checked and ask to overwrite if needed
 * \param account_nb
 * \param archive_number if 0, just export in qif the account transactions ; if non 0, export just the transactions for that archive and account
 *
 * \return TRUE ok, FALSE pb
 */
gboolean qif_export ( const gchar *filename,
                        gint account_nb,
                        gint archive_number )
{
    FILE * fichier_qif;
    GSList *list_tmp_transactions;
    gint beginning;
    gint floating_point;
	gchar* tmpstr;

    if (!gsb_file_util_test_overwrite (filename))
	return FALSE;

    if ( !( fichier_qif = utf8_fopen ( filename, "w" ) ))
    {
	dialogue_error_hint ( g_strerror(errno),
			      g_strdup_printf ( _("Error opening file '%s'"),
						filename ) );
	return FALSE;
    }

    /* get the floating point of the currency of the amount,
     * ie the number of digits after the . */
    floating_point = gsb_data_currency_get_floating_point (gsb_data_account_get_currency (account_nb));

    /* kind of account */
    if ( gsb_data_account_get_kind (account_nb) == GSB_TYPE_CASH )
	fprintf ( fichier_qif,
		  "!Type:Cash\n" );
    else
	if ( gsb_data_account_get_kind (account_nb) == GSB_TYPE_LIABILITIES
	     ||
	     gsb_data_account_get_kind (account_nb) == GSB_TYPE_ASSET )
	    fprintf ( fichier_qif,
		      "!Type:Oth L\n" );
	else
	    fprintf ( fichier_qif,
		      "!Type:Bank\n" );


    list_tmp_transactions = gsb_data_transaction_get_complete_transactions_list ();
    beginning = 1;

    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_nb
	     &&
	     (!archive_number
	      ||
	      gsb_data_transaction_get_archive_number (transaction_number_tmp) == archive_number))
	{
	    if ( beginning )
	    {
		/* this is the beginning of the qif file, we set some beginnings things */
		fprintf ( fichier_qif,
			  "D%d/%d/%d\n",
			  g_date_get_day (gsb_data_transaction_get_date (transaction_number_tmp)),
			  g_date_get_month (gsb_data_transaction_get_date (transaction_number_tmp)),
			  g_date_get_year (gsb_data_transaction_get_date (transaction_number_tmp)));

		/* met le solde initial */
		tmpstr = utils_real_get_string (gsb_data_account_get_init_balance (account_nb, -1));
		fprintf ( fichier_qif,
			  "T%s\n",
			  tmpstr);
		g_free ( tmpstr );

		fprintf ( fichier_qif,
			  "CX\nPOpening Balance\n" );

		/* met le nom du imported_account */

		fprintf ( fichier_qif,
			  "L%s\n^\n",
			  g_strconcat ( "[",
					gsb_data_account_get_name (account_nb),
					"]",
					NULL ) );
		beginning = 0;
	    }

	    /* si c'est une opé de ventil, on la saute pas elle sera recherchée quand */
	    /* son opé ventilée sera exportée */

	    if ( !gsb_data_transaction_get_mother_transaction_number ( transaction_number_tmp))
	    {
		/* met la date */

		fprintf ( fichier_qif,
			  "D%d/%d/%d\n",
			  g_date_get_day (gsb_data_transaction_get_date (transaction_number_tmp)),
			  g_date_get_month (gsb_data_transaction_get_date (transaction_number_tmp)),
			  g_date_get_year (gsb_data_transaction_get_date (transaction_number_tmp)));

		/* met le pointage */

		if ( gsb_data_transaction_get_marked_transaction ( transaction_number_tmp)== OPERATION_POINTEE
		     ||
		     gsb_data_transaction_get_marked_transaction ( transaction_number_tmp)== OPERATION_TELERAPPROCHEE )
		    fprintf ( fichier_qif,
			      "C*\n" );
		else
		    if ( gsb_data_transaction_get_marked_transaction ( transaction_number_tmp)== OPERATION_RAPPROCHEE )
			fprintf ( fichier_qif,
				  "CX\n" );


		/* met les notes */

		if ( gsb_data_transaction_get_notes ( transaction_number_tmp))
		    fprintf ( fichier_qif,
			      "M%s\n",
			      gsb_data_transaction_get_notes ( transaction_number_tmp));


		/* met le montant, transforme la devise si necessaire */
		tmpstr = utils_real_get_string (gsb_data_transaction_get_adjusted_amount ( transaction_number_tmp, floating_point));
		fprintf ( fichier_qif,
			  "T%s\n",
			  tmpstr);
		g_free ( tmpstr );

		/* met le chèque si c'est un type à numérotation automatique */
		if ( gsb_data_payment_get_automatic_numbering (gsb_data_transaction_get_method_of_payment_number (transaction_number_tmp)))
		    fprintf ( fichier_qif,
			      "N%s\n",
			      gsb_data_transaction_get_method_of_payment_content ( transaction_number_tmp));

		/* met le tiers */

		fprintf ( fichier_qif,
			  "P%s\n",
			  gsb_data_payee_get_name ( gsb_data_transaction_get_party_number ( transaction_number_tmp),
						    FALSE ));

		/*  on met soit un virement, soit une ventil, soit les catégories */

		/* si c'est une imported_splitted, on recherche toutes les opés de cette imported_splitted */
		/* et les met à la suite */
		/* la catégorie de l'opé sera celle de la première opé de imported_splitted */

		if ( gsb_data_transaction_get_split_of_transaction ( transaction_number_tmp))
		{
		    /* it's a split of transactions, look for the children and append them */

		    gint mother_transaction_category_written;
		    GSList *list_tmp_transactions_2;

		    mother_transaction_category_written = 0;
		    list_tmp_transactions_2 = gsb_data_transaction_get_transactions_list ();

		    while ( list_tmp_transactions_2 )
		    {
			gint transaction_number_tmp_2;
			transaction_number_tmp_2 = gsb_data_transaction_get_transaction_number (list_tmp_transactions_2 -> data);

			if (gsb_data_transaction_get_mother_transaction_number (transaction_number_tmp_2) == transaction_number_tmp)
			{
			    /* we are on a child, for the first one, we set the mother category */
			    /*  the child can only be a normal category or a transfer */

			    if ( gsb_data_transaction_get_contra_transaction_number (transaction_number_tmp_2) > 0)
			    {
				/* the child is a transfer */

				if ( !mother_transaction_category_written )
				{
				    fprintf ( fichier_qif,
					      "L%s\n",
					      g_strconcat ( "[",
							    gsb_data_account_get_name (gsb_data_transaction_get_contra_transaction_account (transaction_number_tmp_2)),
							    "]",
							    NULL ));
				    mother_transaction_category_written = 1;
				}
				fprintf ( fichier_qif,
					  "S%s\n",
					  g_strconcat ( "[",
							gsb_data_account_get_name (gsb_data_transaction_get_contra_transaction_account ( transaction_number_tmp_2)),
							"]",
							NULL ));
			    }
			    else
			    {
				/* it's a category : sub-category */

				if ( !mother_transaction_category_written )
				{
				    fprintf ( fichier_qif,
					      "L%s\n",
					      gsb_data_category_get_name (gsb_data_transaction_get_category_number (transaction_number_tmp_2),
									  gsb_data_transaction_get_sub_category_number (transaction_number_tmp_2),
									  _("No category defined")));
				    mother_transaction_category_written = 1;
				}
				fprintf ( fichier_qif,
					  "S%s\n",
					  gsb_data_category_get_name (gsb_data_transaction_get_category_number (transaction_number_tmp_2),
								      gsb_data_transaction_get_sub_category_number (transaction_number_tmp_2),
								      _("No category defined")));
			    }

			    /* set the notes of the split child */

			    if ( gsb_data_transaction_get_notes (transaction_number_tmp_2))
				fprintf ( fichier_qif,
					  "E%s\n",
					  gsb_data_transaction_get_notes (transaction_number_tmp_2));

			    /* set the amount of the split child */

			    tmpstr = utils_real_get_string (gsb_data_transaction_get_adjusted_amount (transaction_number_tmp_2, floating_point));
			    fprintf ( fichier_qif,
				      "$%s\n",
				      tmpstr);
			    g_free ( tmpstr );
			}
			list_tmp_transactions_2 = list_tmp_transactions_2 -> next;
		    }
		}
		else
		{
		    /* if it's a transfer, the contra-account must exist, else we do
		     * as for a normal category */

		    if ( gsb_data_transaction_get_contra_transaction_number (transaction_number_tmp) > 0 )
		    {
			/* it's a transfer */

			fprintf ( fichier_qif,
				  "L%s\n",
				  g_strconcat ( "[",
						gsb_data_account_get_name (gsb_data_transaction_get_contra_transaction_account ( transaction_number_tmp)),
						"]",
						NULL ));
		    }
		    else
		    {
			/* it's a normal category */

			fprintf ( fichier_qif,
				  "L%s\n",
				  gsb_data_category_get_name (gsb_data_transaction_get_category_number (transaction_number_tmp),
							      gsb_data_transaction_get_sub_category_number (transaction_number_tmp),
							      FALSE ));
		    }
		}
		fprintf ( fichier_qif,
			  "^\n" );
	    }
	}
	list_tmp_transactions = list_tmp_transactions -> next;
    }

    if ( beginning )
    {
	/* there is no transaction in the account, so do the opening of the account, bug no date */
	/* met le solde initial */

	gchar* tmpstr = utils_real_get_string (gsb_data_account_get_init_balance (account_nb, -1));
	fprintf ( fichier_qif,
		  "T%s\n",
		  tmpstr);
	g_free ( tmpstr );

	fprintf ( fichier_qif,
		  "CX\nPOpening Balance\n" );

	/* met le nom du imported_account */

	fprintf ( fichier_qif,
		  "L%s\n^\n",
		  g_strconcat ( "[",
				gsb_data_account_get_name (account_nb),
				"]",
				NULL ) );
    }
    fclose ( fichier_qif );
    return TRUE;
}
Exemple #20
0
void
cal_print_get_events (gchar *buffer, guint32 julian, GUI *appGUI)
{
	GtkTreePath *path;
	GtkTreeIter iter;
	GtkTreeModel *model;
	GSList *lnode;
	struct note *a;
	gint i;

	gchar *wbuf1, *wbuf2;
	gchar buf1[BUFFER_SIZE], buf2[BUFFER_SIZE];
	GDate *date, *sdate;
	gint age, syear;
	guint32 tsk_julian;
	gint time;
	gint max_event_length;
	GRegex *reg;

	buffer[0] = '\0';
	max_event_length = (config.cal_print_event_length + 2 > BUFFER_SIZE) ? BUFFER_SIZE : config.cal_print_event_length + 2;


#ifdef TASKS_ENABLED

	/* tasks */
	if (config.cal_print_tasks) {

		model = GTK_TREE_MODEL (appGUI->tsk->tasks_list_store);
		g_return_if_fail (model != NULL);

		path = gtk_tree_path_new_first ();

		while (gtk_tree_model_get_iter (model, &iter, path) == TRUE) {
			gtk_tree_model_get (model, &iter, TA_COLUMN_DUE_DATE_JULIAN, &tsk_julian, TA_COLUMN_CATEGORY, &wbuf1, -1);

			if (tsk_julian == julian && tasks_category_get_state (wbuf1, STATE_CALENDAR, appGUI) == TRUE) {
				gtk_tree_model_get (model, &iter, TA_COLUMN_DUE_TIME, &time, TA_COLUMN_SUMMARY, &wbuf2, -1);

				if (time >= 0) {
					g_snprintf (buf1, max_event_length, "\n[%02d:%02d] %s", time / 3600, time / 60 % 60, wbuf2);
				} else {
					g_snprintf (buf1, max_event_length, "\n%s", wbuf2);
				}

				g_strlcat (buffer, buf1, BUFFER_SIZE);
				g_free (wbuf2);
			}

			g_free (wbuf1);
			gtk_tree_path_next (path);
		}

		gtk_tree_path_free (path);

	}

#endif  /* TASKS_ENABLED */

#ifdef CONTACTS_ENABLED

	/* birthdays */
	if (config.cal_print_birthdays) {

		model = GTK_TREE_MODEL (appGUI->cnt->contacts_list_store);
		g_return_if_fail (model != NULL);

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

		sdate = g_date_new_julian (julian);
		g_return_if_fail (sdate != NULL);

		syear = g_date_get_year (sdate);
		path = gtk_tree_path_new_first ();

		while (gtk_tree_model_get_iter (model, &iter, path) == TRUE) {
			gtk_tree_model_get (model, &iter, COLUMN_BIRTH_DAY_DATE, &tsk_julian, -1);

			if (g_date_valid_julian (tsk_julian)) {
				g_date_set_julian (date, tsk_julian);
				age = syear - g_date_get_year (date);

				if (age >= 0) {

					if (g_date_valid_dmy (g_date_get_day (date), g_date_get_month (date), syear) == FALSE) {
						g_date_subtract_days (date, 1);
					}
					g_date_set_year (date, syear);

					if (g_date_compare (date, sdate) == 0) {

						gtk_tree_model_get (model, &iter, COLUMN_FIRST_NAME, &wbuf1, COLUMN_LAST_NAME, &wbuf2, -1);
						utl_name_strcat (wbuf1, wbuf2, buf2);

						g_snprintf (buf1, max_event_length, "\n%s (%d)", buf2, age);
						g_strlcat (buffer, buf1, BUFFER_SIZE);
					}
				}
			}
			gtk_tree_path_next (path);
		}

		gtk_tree_path_free (path);
		g_date_free (sdate);
		g_date_free (date);

	}

	/* name days */
	if (config.cal_print_namedays) {

		model = GTK_TREE_MODEL (appGUI->cnt->contacts_list_store);
		g_return_if_fail (model != NULL);

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

		sdate = NULL;
		sdate = g_date_new_julian (julian);
		g_return_if_fail (sdate != NULL);

		syear = g_date_get_year (sdate);
		path = gtk_tree_path_new_first ();

		while (gtk_tree_model_get_iter (model, &iter, path) == TRUE) {
			gtk_tree_model_get (model, &iter, COLUMN_NAME_DAY_DATE, &tsk_julian, -1);

			if (g_date_valid_julian (tsk_julian)) {
				g_date_set_julian (date, tsk_julian);

				if (g_date_valid_dmy (g_date_get_day (date), g_date_get_month (date), syear) == TRUE) {
					g_date_set_year (date, syear);

					if (g_date_compare (date, sdate) == 0) {

						gtk_tree_model_get (model, &iter, COLUMN_FIRST_NAME, &wbuf1, COLUMN_LAST_NAME, &wbuf2, -1);
						utl_name_strcat (wbuf1, wbuf2, buf1);

						g_snprintf (buf2, max_event_length, "\n%s (%s)", buf1, _("Name day"));
						g_strlcat (buffer, buf2, BUFFER_SIZE);
					}
				}
			}
			gtk_tree_path_next (path);
		}

		gtk_tree_path_free (path);
		g_date_free (sdate);
		g_date_free (date);

	}

#endif  /* CONTACTS_ENABLED */

	/* day note */
	if (config.cal_print_day_notes) {

		if (appGUI->cal->notes_list != NULL) {

			wbuf1 = NULL;
			reg = g_regex_new ("\n", 0, 0, NULL);

			for (i = 0, lnode = appGUI->cal->notes_list; lnode != NULL; lnode = lnode->next, i++) {
				a = g_slist_nth_data (appGUI->cal->notes_list, i);

				if (a->date == julian) {
					wbuf1 = g_regex_replace_literal (reg, a->note, -1, 0, " ", 0, NULL);
					break;
				}
			}

			g_regex_unref (reg);
		}

		if (wbuf1 != NULL) {
			g_strstrip (wbuf1);
			g_snprintf (buf1, max_event_length, "\n%s", wbuf1);
			g_strlcat (buffer, buf1, BUFFER_SIZE);
			g_free (wbuf1);
		}

	}

#ifdef HAVE_LIBICAL

	/* ical */
	if (config.cal_print_ical) {


	}

#endif  /* HAVE_LIBICAL */

	g_strstrip (buffer);

}
Exemple #21
0
int main(int argc, char** argv)
{
  GDate* d;
  guint32 j;
  GDateMonth m;
  GDateYear y, prev_y;
  GDateDay day;
  gchar buf[101];
  gchar* loc;
  
  guint32 num_chars_written_to_buf;
  
  /* Try to get all the leap year cases. */
  GDateYear check_years[] = { 
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10
    // Less number of years to test on emulator as the time taken
    // on ATS is very large
#if !defined(__WINS__) && !defined(__WINSCW__)
    ,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
#endif    
  };
  
  
  

  guint n_check_years = sizeof(check_years)/sizeof(GDateYear);
  guint i;
  gboolean discontinuity;
	
  #ifdef SYMBIAN
  g_log_set_handler (NULL,  G_LOG_FLAG_FATAL| G_LOG_FLAG_RECURSION | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE | G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG, &mrtLogHandler, NULL);
  g_set_print_handler(mrtPrintHandler);
  #endif /*SYMBIAN*/
	  
  //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 unchanged\n");

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

  num_chars_written_to_buf = g_date_strftime(buf,100,"Today is a %A, %x\n", d);
  g_assert(num_chars_written_to_buf != 0);
  if(!num_chars_written_to_buf)
  		g_print("g_date_strftime is failed @ line = %d",__LINE__);

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

  num_chars_written_to_buf = g_date_strftime(buf,100,"1 second into the Unix epoch it was a %A, in the month of %B, %x\n", d);
  g_assert(num_chars_written_to_buf != 0);
  if(!num_chars_written_to_buf)
  		g_print("g_date_strftime is failed @ line = %d",__LINE__);

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

  num_chars_written_to_buf = g_date_strftime(buf,100,"Our \"Julian\" epoch begins on a %A, in the month of %B, %x\n",
		  d);
  g_assert(num_chars_written_to_buf != 0);
  if(!num_chars_written_to_buf)
  		g_print("g_date_strftime is failed @ line = %d",__LINE__);

  g_date_set_dmy(d, 10, 1, 2000);

  num_chars_written_to_buf = g_date_strftime(buf,100,"%x", d);
  g_assert(num_chars_written_to_buf != 0);
  if(!num_chars_written_to_buf)
  		g_print("g_date_strftime is failed @ line = %d",__LINE__);

  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);
#ifdef SYMBIAN
  testResultXml("testgdate");
#endif /* EMULATOR */
  return 0;
}
/**
 * Update the example calendar; make sure to take into account the end
 * specification.
 **/
static void
sxftd_update_example_cal( SXFromTransInfo *sxfti )
{
    struct tm *tmpTm;
    time_t tmp_tt;
    GDate date, startDate, nextDate;
    GList *schedule = NULL;
    getEndTuple get;

    get = sxftd_get_end_info( sxfti );

    tmp_tt = gnc_date_edit_get_date( sxfti->startDateGDE );
    tmpTm = g_new0( struct tm, 1 );
    *tmpTm = *localtime( &tmp_tt );
    g_date_clear(&date, 1);
    g_date_set_day( &date, tmpTm->tm_mday );
    g_date_set_month( &date, tmpTm->tm_mon + 1 );
    g_date_set_year( &date, tmpTm->tm_year + 1900 );
    g_free( tmpTm );

    sxftd_update_schedule(sxfti, &date, &schedule);

    /* go one day before what's in the box so we can get the correct start
     * date. */
    startDate = date;
    g_date_subtract_days(&date, 1);
    g_date_clear(&nextDate, 1);
    recurrenceListNextInstance(schedule, &date, &nextDate);

    {
        GtkWidget *w;
        gchar *name;
        /* get the name */
        w = glade_xml_get_widget(sxfti->gxml, SXFTD_NAME_ENTRY);
        name = gtk_editable_get_chars(GTK_EDITABLE(w), 0, -1);
        gnc_dense_cal_store_update_name(sxfti->dense_cal_model, name);
        g_free(name);
    }

    {
        gchar *schedule_desc;
        schedule_desc = recurrenceListToCompactString(schedule);
        gnc_dense_cal_store_update_info(sxfti->dense_cal_model, schedule_desc);
        g_free(schedule_desc);
    }

    switch (get.type)
    {
    case NEVER_END:
        gnc_dense_cal_store_update_recurrences_no_end(sxfti->dense_cal_model, &startDate, schedule);
        break;
    case END_ON_DATE:
        gnc_dense_cal_store_update_recurrences_date_end(sxfti->dense_cal_model, &startDate, schedule, &get.end_date);
        break;
    case END_AFTER_N_OCCS:
        gnc_dense_cal_store_update_recurrences_count_end(sxfti->dense_cal_model, &startDate, schedule, get.n_occurrences);
        break;
    default:
        g_warning("unknown get.type [%d]\n", get.type);
        break;
    }

    gnc_dense_cal_set_month( sxfti->example_cal, g_date_get_month( &startDate ) );
    gnc_dense_cal_set_year( sxfti->example_cal, g_date_get_year( &startDate ) );

    recurrenceListFree(&schedule);
}
Exemple #23
0
static struct stats_record *process_file(struct stats_iter *iter,
					struct stats_file *temp_file,
					struct stats_record *cur,
					GDate *date_change_step_size,
					int account_period_offset)
{
	struct stats_record *home, *roaming;
	struct stats_record *next;

	home = NULL;
	roaming = NULL;

	if (!cur)
		cur = get_next_record(iter);
	next = get_next_record(iter);

	while (next) {
		GDate date_cur;
		GDate date_next;
		int append;

		append = FALSE;

		if (cur->roaming)
			roaming = cur;
		else
			home = cur;

		g_date_set_time_t(&date_cur, cur->ts);
		g_date_set_time_t(&date_next, next->ts);

		if (g_date_compare(&date_cur, date_change_step_size) < 0) {
			/* month period size */
			GDateDay day_cur, day_next;
			GDateMonth month_cur, month_next;

			month_cur = g_date_get_month(&date_cur);
			month_next = g_date_get_month(&date_next);

			day_cur = g_date_get_day(&date_cur);
			day_next = g_date_get_day(&date_next);

			if (day_cur == day_next && month_cur != month_next)
				append = TRUE;
			else if (day_cur < account_period_offset
					&& day_next >= account_period_offset)
				append = TRUE;
		} else {
			/* day period size */
			if (g_date_days_between(&date_cur, &date_next) > 0)
				append = TRUE;
		}

		if (append) {
			if (home) {
				append_record(temp_file, home);
				home = NULL;
			}

			if (roaming) {
				append_record(temp_file, roaming);
				roaming = NULL;
			}
		}

		cur = next;
		next = get_next_record(iter);
	}

	return cur;
}
QT_BEGIN_NAMESPACE

//internal
static void addTagToMap(const GstTagList *list,
                        const gchar *tag,
                        gpointer user_data)
{
    QMap<QByteArray, QVariant> *map = reinterpret_cast<QMap<QByteArray, QVariant>* >(user_data);

    GValue val;
    val.g_type = 0;
    gst_tag_list_copy_value(&val,list,tag);

    switch( G_VALUE_TYPE(&val) ) {
        case G_TYPE_STRING:
        {
            const gchar *str_value = g_value_get_string(&val);
            map->insert(QByteArray(tag), QString::fromUtf8(str_value));
            break;
        }
        case G_TYPE_INT:
            map->insert(QByteArray(tag), g_value_get_int(&val));
            break;
        case G_TYPE_UINT:
            map->insert(QByteArray(tag), g_value_get_uint(&val));
            break;
        case G_TYPE_LONG:
            map->insert(QByteArray(tag), qint64(g_value_get_long(&val)));
            break;
        case G_TYPE_BOOLEAN:
            map->insert(QByteArray(tag), g_value_get_boolean(&val));
            break;
        case G_TYPE_CHAR:
#if GLIB_CHECK_VERSION(2,32,0)
            map->insert(QByteArray(tag), g_value_get_schar(&val));
#else
            map->insert(QByteArray(tag), g_value_get_char(&val));
#endif
            break;
        case G_TYPE_DOUBLE:
            map->insert(QByteArray(tag), g_value_get_double(&val));
            break;
        default:
            // GST_TYPE_DATE is a function, not a constant, so pull it out of the switch
#if GST_CHECK_VERSION(1,0,0)
            if (G_VALUE_TYPE(&val) == G_TYPE_DATE) {
                const GDate *date = (const GDate *)g_value_get_boxed(&val);
#else
            if (G_VALUE_TYPE(&val) == GST_TYPE_DATE) {
                const GDate *date = gst_value_get_date(&val);
#endif
                if (g_date_valid(date)) {
                    int year = g_date_get_year(date);
                    int month = g_date_get_month(date);
                    int day = g_date_get_day(date);
                    map->insert(QByteArray(tag), QDate(year,month,day));
                    if (!map->contains("year"))
                        map->insert("year", year);
                }
            } else if (G_VALUE_TYPE(&val) == GST_TYPE_FRACTION) {
                int nom = gst_value_get_fraction_numerator(&val);
                int denom = gst_value_get_fraction_denominator(&val);

                if (denom > 0) {
                    map->insert(QByteArray(tag), double(nom)/denom);
                }
            }
            break;
    }

    g_value_unset(&val);
}

/*!
  Convert GstTagList structure to QMap<QByteArray, QVariant>.

  Mapping to int, bool, char, string, fractions and date are supported.
  Fraction values are converted to doubles.
*/
QMap<QByteArray, QVariant> QGstUtils::gstTagListToMap(const GstTagList *tags)
{
    QMap<QByteArray, QVariant> res;
    gst_tag_list_foreach(tags, addTagToMap, &res);

    return res;
}
Exemple #25
0
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);
}
Exemple #26
0
static void hb_export_qif_elt_txn(GIOChannel *io, Account *acc)
{
GString *elt;
GList *list;
GDate *date;
char amountbuf[G_ASCII_DTOSTR_BUF_SIZE];
gchar *sbuf;
gint count, i;

	elt = g_string_sized_new(255);

	date = g_date_new ();
	
	list = g_queue_peek_head_link(acc->txn_queue);
	while (list != NULL)
	{
	Transaction *txn = list->data;
	Payee *payee;
	Category *cat;
	gchar *txt;

		g_date_set_julian (date, txn->date);
		//#1270876
		switch(PREFS->dtex_datefmt)
		{
			case 0: //"m-d-y"  
				g_string_append_printf (elt, "D%02d/%02d/%04d\n", 
					g_date_get_month(date),
					g_date_get_day(date),
					g_date_get_year(date)
					);
				break;
			case 1: //"d-m-y"
				g_string_append_printf (elt, "D%02d/%02d/%04d\n", 
					g_date_get_day(date),
					g_date_get_month(date),
					g_date_get_year(date)
					);
				break;
			case 2: //"y-m-d"
				g_string_append_printf (elt, "D%04d/%02d/%02d\n", 
					g_date_get_year(date),
					g_date_get_month(date),
					g_date_get_day(date)
					);
				break;
		}			

		//g_ascii_dtostr (amountbuf, sizeof (amountbuf), txn->amount);
		g_ascii_formatd (amountbuf, sizeof (amountbuf), "%.2f", txn->amount);
		g_string_append_printf (elt, "T%s\n", amountbuf);

		sbuf = "";
		if(txn->status == TXN_STATUS_CLEARED)
			sbuf = "c";
		else
		if(txn->status == TXN_STATUS_RECONCILED)
			sbuf = "R";

		g_string_append_printf (elt, "C%s\n", sbuf);

		if( txn->paymode == PAYMODE_CHECK)
			g_string_append_printf (elt, "N%s\n", txn->info);

		//Ppayee
		payee = da_pay_get(txn->kpay);
		if(payee)
			g_string_append_printf (elt, "P%s\n", payee->name);

		// Mmemo
		g_string_append_printf (elt, "M%s\n", txn->memo);

		// LCategory of transaction
		// L[Transfer account name]
		// LCategory of transaction/Class of transaction
		// L[Transfer account]/Class of transaction
		if( txn->paymode == PAYMODE_INTXFER && txn->kacc == acc->key)
		{
		//#579260
			Account *dstacc = da_acc_get(txn->kxferacc);
			if(dstacc)
				g_string_append_printf (elt, "L[%s]\n", dstacc->name);
		}
		else
		{
			cat = da_cat_get(txn->kcat);
			if(cat)
			{
				txt = da_cat_get_fullname(cat);
				g_string_append_printf (elt, "L%s\n", txt);
				g_free(txt);
			}
		}

		// splits
		count = da_splits_count(txn->splits);
		for(i=0;i<count;i++)
		{
		Split *s = txn->splits[i];
				
			cat = da_cat_get(s->kcat);
			if(cat)
			{
				txt = da_cat_get_fullname(cat);
				g_string_append_printf (elt, "S%s\n", txt);
				g_free(txt);
			}	
				
			g_string_append_printf (elt, "E%s\n", s->memo);
			
			g_ascii_formatd (amountbuf, sizeof (amountbuf), "%.2f", s->amount);
			g_string_append_printf (elt, "$%s\n", amountbuf);
		}
		
		g_string_append (elt, "^\n");


		list = g_list_next(list);
	}

	g_io_channel_write_chars(io, elt->str, -1, NULL, NULL);
	
	g_string_free(elt, TRUE);

	g_date_free(date);
	
}