1/*
2 * Copyright (c) 2002-2004, 2008 Apple Computer, Inc.  All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License").  You may not use this file except in compliance with the
9 * License.  Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
11 *
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
17 * License for the specific language governing rights and limitations
18 * under the License.
19 *
20 * @APPLE_LICENSE_HEADER_END@
21 */
22
23#include <sys/time.h>
24#include "timestat.h"
25#include "libtop.h"
26#include "generic.h"
27#include "preferences.h"
28
29static bool time_insert_cell(struct statistic *s, const void *sample) {
30    const libtop_psamp_t *psamp = sample;
31    struct timeval  tv;
32    unsigned int usec, sec, min, hour, day;
33    char buf[GENERIC_INT_SIZE];
34
35    if(STATMODE_ACCUM == top_prefs_get_mode()) {
36	timersub(&psamp->total_time, &psamp->b_total_time, &tv);
37    } else {
38	tv = psamp->total_time;
39    }
40
41    usec = tv.tv_usec;
42    sec = tv.tv_sec;
43    min = sec / 60;
44    hour = min / 60;
45    day = hour / 24;
46
47    if(min < 100) {
48	snprintf(buf, sizeof(buf), "%02u:%02u.%02u", min, sec % 60, usec / 10000);
49    } else if(hour < 100) {
50	snprintf(buf, sizeof(buf), "%02u:%02u:%02u", hour, min % 60, sec % 60);
51    } else {
52	snprintf(buf, sizeof(buf), "%u hrs", hour);
53    }
54
55#if 0
56    if(sec < 60) {
57	snprintf(buf, sizeof(buf), "%u.%02us", sec, usec / 10000);
58    } else if(min < 60) {
59	snprintf(buf, sizeof(buf), "%um%02us", min, sec - min * 60);
60    } else if(hour < 24) {
61	snprintf(buf, sizeof(buf), "%uh%02um", hour, min - hour * 60);
62    } else if(day < 100) {
63	snprintf(buf, sizeof(buf), "%ud%02uh", day, hour - day * 24);
64    } else {
65	snprintf(buf, sizeof(buf), "%ud", day);
66    }
67#endif
68
69    return generic_insert_cell(s, buf);
70}
71
72static struct statistic_callbacks callbacks = {
73    .draw = generic_draw,
74    .resize_cells = generic_resize_cells,
75    .move_cells = generic_move_cells,
76    .get_request_size = generic_get_request_size,
77    .get_minimum_size = generic_get_minimum_size,
78    .insert_cell = time_insert_cell,
79    .reset_insertion = generic_reset_insertion
80};
81
82struct statistic *top_time_create(WINDOW *parent, const char *name) {
83    return create_statistic(STATISTIC_TIME, parent, NULL, &callbacks, name);
84}
85