// Copyright 2023 Daniel Martins
// License GPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation, either version 3 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// this program. If not, see .
// Compilation commands:
// - release : jai ttt.jai -import_dir . -quiet -x64 -release
// - debug : jai ttt.jai -import_dir . -quiet -x64
#import "Basic"()(MEMORY_DEBUGGER=true); // TODO Remove after final debug sessions.
#import "System";
#import "Math";
#import "POSIX";
#import "File";
#import "File_Utilities";
#import "String";
#import "curses";
VERSION :: "2.0"; // Use only 3 chars (to fit layouts).
YEAR :: "2023";
FIRST_DAY_OF_WEEK :: 1; // (0-6, Sunday = 0).
NUM_WEEK_DAYS :: 7; // TODO This has to go - Just to be more clear about what we're looping about.
NAME_SIZE :: 72; // TODO Use this instead of Task.name.count ?
APP_FOLDER_NAME :: ".task_time_tracker_v2"; // TODO Using _v2 to avoid erasing my work data.
DB_FILE_NAME :: "database.bin";
AR_FILE_NAME :: "archive.csv";
DB_FILE_SIGN_STR :: "TTT:B:02";
ASSERT_NOT_NULL :: "Parameter '%' is null.";
ASSERT_NOT_EMPTY :: "Parameter '%' is empty.";
ASSERT_NOT_CONTAIN :: "'%' does not contain '%'.";
SECONDS_IN_MINUTE :: cast(s64)60;
SECONDS_IN_HOUR :: cast(s64)60*SECONDS_IN_MINUTE;
SECONDS_IN_DAY :: cast(s64)24*SECONDS_IN_HOUR;
SECONDS_IN_YEAR :: cast(s64)365*SECONDS_IN_DAY;
MAX_DATABASE_TASKS :: S64_MAX;
Task :: struct {
times : [NUM_WEEK_DAYS] s64;
name : [72] u8;
}
Database :: struct {
modified_on : Apollo_Time;
active_idx : s64 = -1;
selected_idx : s64 = -1;
total_times : [NUM_WEEK_DAYS] s64;
tasks : [..] Task;
}
SIZE_OF_TASK :: #run size_of(Task);
// const char DB_FILE_SIGN[] = DB_FILE_SIGN_STR;
// const size_t DB_FILE_SIGN_LENGTH = sizeof(DB_FILE_SIGN_STR)-1;
// const size_t SIZEOF_TASK_ST = sizeof(task_st);
// const size_t SIZEOF_DATABASE_ST = sizeof(database_st);
// const size_t SIZEOF_CHAR = sizeof(char);
// const size_t SIZEOF_INT64 = sizeof(int64_t);
//
//
//
database : Database;
archive : Database;
is_autosave_enabled := true;
countdown_to_autosave := -1;
app_directory : string;
db_file_path : string;
ar_file_path : string;
// char *string_buffer = NULL; // A temporary buffer for localized actions. Please avoid data leaks and out-of-bounds errors.
// size_t string_buffer_size = 0;
size_x : s32;
size_y : s32;
pos_x : s32;
pos_y : s32;
Styles :: enum s16 {
SELECTED :: 1;
SELECTED_INVERTED;
ACTIVE;
ACTIVE_SELECTED;
ERROR;
}
Layouts :: enum u8 {
NORMAL;
COMPACT;
}
error_window : *WINDOW = null;
error_time_limit := Apollo_Time.{0, 0};
print_error :: (format :string, args : .. Any) {
if stdscr == null || isendwin() == true { // Not in ncurses mode?
print(format, ..args);
print("\n");
}
else {
CHAR_SPACE :: #char " ";
w_size_x: s32 = ifx size_x > 120 then 120 else size_x - 2;
w_size_y: s32 = 4;
if (error_window == null) {
error_window = newwin(w_size_y, w_size_x, (size_y - w_size_y) / 2, (size_x - w_size_x) / 2);
wattron(error_window, COLOR_PAIR(xx Styles.ERROR));
wborder(error_window, CHAR_SPACE, CHAR_SPACE, 0, 0, ACS_HLINE, ACS_HLINE, ACS_HLINE, ACS_HLINE);
mvwprintw(error_window, 0, 1, " Error ");
wmove(error_window, 1, 0);
}
else {
waddch(error_window, CHAR_SPACE);
}
vw_printw(error_window, to_c_string(format), args);
error_time_limit = current_time_monotonic() + seconds_to_apollo(5);
}
}
draw_error_window :: () {
if (error_window == null) return;
// Hide error window after time-limit or if terminal is shrank.
w_size_x: s32;
w_size_y: s32;
getmaxyx(error_window, *w_size_y, *w_size_x);
if (current_time_monotonic() >= error_time_limit
|| size_x - w_size_x < 2
|| size_y - w_size_y < 2
) {
delwin(error_window);
error_window = null;
return;
}
// Adjust error window position.
pos_x := (size_x - w_size_x) / 2;
pos_y := (size_y - w_size_y) / 2;
mvwin(error_window, pos_y, pos_x);
// Avoid being overwritten by main window content.
refresh();
touchwin(error_window);
wrefresh(error_window);
}
trigger_autosave :: () {
countdown_to_autosave = 13375; // ms
}
show_processing :: () {
mvaddch(0, 0, ACS_DIAMOND);
refresh();
}
// Returns true if string to_compare is equal to any of the other passed strings, false otherwise.
is_equal_to_any :: (to_compare :string, test_a :string, test_b :string) -> bool {
return to_compare == test_a || to_compare == test_b;
}
// Given an UTF8 encoded string, truncate it to length bytes without breaking any UTF8 character.
// The string should have capacity for at least length + 1.
// The terminating null byte ('\0') is not included in length.
// Returns the truncated string length.
Text_Encoding :: enum u8 #specified {
ASCII :: 1;
UTF8 :: 2;
}
// TODO Provide good description.
number_size :: (number: s64, base: s64 = 10) -> s64 {
if number == 0 return 1;
return cast(s64)floor(log(cast(float64)abs(number))/log(cast(float64)abs(base))) + 1; // TODO So many casts.
}
// WIP TODO Ues compiler time code to see the auto bake being used... just for fun, once! :D
truncate_string :: (str: string, length: s64, $encoding: Text_Encoding = .UTF8) -> length: s64 #no_abc { // TODO Should I use #no_abc ?
assert(str.data != null, ASSERT_NOT_NULL, "str");
assert(str.count >= length, "'str.count' should be equal or greater to 'length'.");
data := str.data;
count := str.count;
#if encoding == .UTF8 {
// Find index of first continuation byte.
idx := length;
while (idx > 0 && ((data[idx - 1] & 0xC0) == 0x80)) {
idx -= 1;
}
continuation_bytes := length - idx;
// If string starts with continuation bytes, it's an invalid UTF8 string.
if (idx == 0 && continuation_bytes > 0) {
length = 0;
}
// If length truncates some continuation bytes, remove incomplete UTF8 character.
else if (idx > 0 // string is not empty
// continuation bytes are not complete
&& !(continuation_bytes == 0 && (data[idx - 1] & 0x80) == 0x00)
&& !(continuation_bytes == 1 && (data[idx - 1] & 0xE0) == 0xC0)
&& !(continuation_bytes == 2 && (data[idx - 1] & 0xF0) == 0xE0)
&& !(continuation_bytes == 3 && (data[idx - 1] & 0xF8) == 0xF0)
) {
length -= (continuation_bytes + 1); // Remove '+ 1' start byte.
}
}
memset(data + length, 0, count - length);
return length;
}
// Returns true when the string is empty or consists of space characters.
is_empty_string :: (str: string) -> bool {
for 0..str.count-1 {
if str[it] == {
case #char "\0"; #through;
case #char "\t"; #through; // horizontal tab
case #char "\n"; #through; // line feed
case #char "\x0B"; #through; // vertical tabulation
case #char "\x0C"; #through; // form feed
case #char "\r"; #through; // carriage return
case #char " ";
continue;
case;
return false;
}
}
return true;
}
// Prints, on row y and column x, the time using 5 characters centered on space.
// Returns the result of a call to mvprintw.
mvprintw_time :: (y: s32, x: s32, time: s64, space: s32) -> int { // BUG Setting a timer to 99.9y shows 100y.
TIME_CHARS :: 5;
assert(space >= TIME_CHARS);
mul_f64_s64 :: inline (a: float64, b: s64) -> s64 {
return cast(s64)(a * cast(float64)b);
}
left_padding := (space - TIME_CHARS) / 2;
right_padding := space - TIME_CHARS - left_padding;
if time < 0 {
return mvprintw(y, x, "%*s - %*s", left_padding, "", right_padding, "");
}
else if time == 0 {
return mvprintw(y, x, "%*s 0 %*s", left_padding, "", right_padding, "");
}
else if time < SECONDS_IN_MINUTE {
return mvprintw(y, x, "%*s%3jds %*s", left_padding, "", time, right_padding, "");
}
else if time < #run mul_f64_s64(100, SECONDS_IN_HOUR) {
hours := time / SECONDS_IN_HOUR;
minutes := (time - (hours * SECONDS_IN_HOUR) ) / SECONDS_IN_MINUTE;
return mvprintw(y, x, "%*s%02jd:%02jd%*s", left_padding, "", hours, minutes, right_padding, "");
}
else if time < #run mul_f64_s64(9999.5, SECONDS_IN_DAY) {
value := cast(float64) time / SECONDS_IN_DAY;
decimals :=
ifx time >= #run mul_f64_s64(99.95, SECONDS_IN_DAY) then 0 else
ifx time >= #run mul_f64_s64(9.995, SECONDS_IN_DAY) then 1 else
2;
return mvprintw(y, x, "%*s%4.*fd%*s", left_padding, "", decimals, value, right_padding, "");
}
else if time < #run mul_f64_s64(9999.5, SECONDS_IN_YEAR) {
value := cast(float64) time / SECONDS_IN_YEAR;
decimals :=
ifx time >= #run mul_f64_s64(99.95, SECONDS_IN_YEAR) then 0 else
ifx time >= #run mul_f64_s64(9.995, SECONDS_IN_YEAR) then 1 else
2;
return mvprintw(y, x, "%*s%4.*fy%*s", left_padding, "", decimals, value, right_padding, "");
}
else {
return mvprintw(y, x, "%*s ∞ %*s", left_padding, "", right_padding, "");
}
}
add_int64 :: (x :s64, y: s64) -> s64 {
return
ifx (y > 0 && x > S64_MAX - y) then S64_MAX else
ifx (y < 0 && x < S64_MIN - y) then S64_MIN else
x + y;
}
sub_int64 :: (x :s64, y :s64) -> s64 {
return
ifx (y < 0 && x > S64_MAX + y) then S64_MAX else
ifx (y > 0 && x < S64_MIN + y) then S64_MIN else
x - y;
}
// Returns active task or NULL if none applies.
get_active_task :: inline (db: Database) -> *Task {
return ifx db.active_idx >= 0 then *db.tasks[db.active_idx] else null;
}
// Returns selected task or NULL if none applies.
get_selected_task :: inline (db: Database) -> *Task {
return ifx db.selected_idx >= 0 then *db.tasks[db.selected_idx] else null;
}
// TODO Add description.
contains_task :: inline (db: Database, task: *Task) -> bool {
return task >= db.tasks.data && task - db.tasks.data < db.tasks.count;
}
// Adds a task to the database and returns it.
// If necessary, expands database capacity.
add_task :: (db: *Database, task: Task = .{}) -> task: *Task {
assert(db != null, ASSERT_NOT_NULL, "db");
array_add(*db.tasks, task);
for * db.total_times {
< bool {
assert(db != null, ASSERT_NOT_NULL, "db");
assert(task != null, ASSERT_NOT_NULL, "task");
assert(contains_task(db, task), ASSERT_NOT_CONTAIN, "db", "task");
// Remove task timer values from total timers.
for task.times {
db.total_times[it_index] = sub_int64(db.total_times[it_index], it);
}
// Move tasks after the index position to their new positions.
index := task - db.tasks.data;
for index..db.tasks.count-2
db.tasks[it] = db.tasks[it+1];
db.tasks.count -= 1;
// Adjust selected task.
if (db.selected_idx >= db.tasks.count) {
db.selected_idx -= 1;
}
// Adjust active task.
if (db.active_idx > index) {
db.active_idx -= 1;
}
else if (db.active_idx == index) {
db.active_idx = -1;
}
// If possible, shrink database capacity.
// TODO Do we really want to make this fuss?
current_capacity := db.tasks.allocated;
if (db.tasks.count < (current_capacity >> 2)) {
new_capacity := 1 << (get_msb(db.tasks.count) + 2);
my_array_reserve_nonpoly(xx *db.tasks, new_capacity, SIZE_OF_TASK);
}
get_msb :: (value: s64) -> msb: s64, found: bool {
result: s64 = ---;
#asm {
mov val: gpr, value;
bsr result, val;
}
return result * xx cast(bool)value, xx value; // If value is zero: return `0, false`.
}
my_array_reserve_nonpoly :: (array: *[..] *void, desired_items: s64, size: s64) -> success: bool {
if !array.allocator.proc remember_allocators(array);
new_array_data := realloc(array.data, desired_items * size, array.allocated * size, array.allocator);
if new_array_data == null return false;
array.data = new_array_data;
array.allocated = desired_items;
return true;
}
return true;
}
// Moves task to index.
// Index gets clamped to [0, db->count[.
move_task_to_index :: (db: *Database, task: *Task, index: s64) {
assert(db != null, ASSERT_NOT_NULL, "db");
assert(task != null, ASSERT_NOT_NULL, "task");
assert(contains_task(db, task), ASSERT_NOT_CONTAIN, "db", "task");
target_index := clamp(index, 0, db.tasks.count-1);
target_task := *db.tasks[target_index];
if (target_task == task) return;
// Move task to new location.
temp_task := < task {
//memmove(task, task + 1, (target_task - task) * SIZEOF_TASK_ST); TODO Maybe simplify this moves.
offset := task - db.tasks.data;
size := target_task - task;
for 0..size-1
db.tasks[offset + it] = db.tasks[offset + it + 1];
}
else {
//memmove(target_task + 1, target_task, (task - target_task) * SIZEOF_TASK_ST); TODO Maybe simplify this moves.
offset := target_task - db.tasks.data;
size := task - target_task;
for < size-1..0
db.tasks[offset + it + 1] = db.tasks[offset + it];
}
< success: bool {
assert(xx path, ASSERT_NOT_EMPTY, "path");
// Open file.
file, open_success := file_open(path, for_writing = true); // log_errors: bool = true
if open_success == false {
print_error("Failed to open file '%' while storing database: ERROR_FROM_LOG", path); // TODO Get error from logger ?!
return false;
}
defer file_close(*file);
file_write(*file, DB_FILE_SIGN_STR);
file_write(*file, *db, size_of(Database));
file_write(*file, db.tasks.data, SIZE_OF_TASK * db.tasks.count);
return true;
}
// Loads data from binary file into database.
// Returns success.
load_database :: (db: *Database, path: string) -> success: bool {
assert(db != null, ASSERT_NOT_NULL, "db");
assert(xx path, ASSERT_NOT_EMPTY, "path");
// Open file.
file, open_success := file_open(path); // log_errors: bool = true
if open_success == false {
print_error("Failed to open file '%' while loading database: ERROR_FROM_LOG", path); // TODO Get error from logger ?!
return false;
}
defer file_close(*file);
// Validate file signature.
file_signature: [DB_FILE_SIGN_STR.count] u8;
read_success := file_read(file, *file_signature, DB_FILE_SIGN_STR.count);
if read_success == false print_error("Failed to read file signature from '%'.", path);
if cast(string)file_signature != DB_FILE_SIGN_STR {
print_error("Invalid file signature.");
return false;
}
// Read database structure.
read_success = file_read(file, db, size_of(Database));
// TODO Use print_error or assert?
if read_success == false {
print_error("Failed to read database info from '%'.", path);
return false;
}
assert(read_success == true, "Failed to read database info from '%'.", path);
// Reserve database capacity for tasks.
tasks_count := db.tasks.count;
Initialize(*db.tasks); // Cleanup whatever was read from file.
array_reserve(*db.tasks, tasks_count);
// Read database tasks.
file_read(file, db.tasks.data, SIZE_OF_TASK * tasks_count);
db.tasks.count = tasks_count;
// Make sure we are reading all the file.
buffer: u8;
success, bytes := file_read(file, *buffer, 1);
assert(bytes == 0, "Unexpected content found at the end of file '%'.", path);
return true;
}
// Exports data into CSV file.
// Returns success.
export_to_csv :: (db: Database, path: string) -> success: bool {
assert(xx path, ASSERT_NOT_EMPTY, "path");
// TODO Make sure (IN ALL PROCEDURES) we're not receiving an empty path.
builder: String_Builder;
defer reset(*builder);
CSV_HEADER :: string.[ "task", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ];
print_to_builder(*builder, "%\n", join(..CSV_HEADER, separator = ","));
buffer: [Task.name.count] u8;
name: string = xx buffer;
for db.tasks {
name.count = c_style_strlen(it.name.data);
memcpy(name.data, it.name.data, name.count);
replace_chars(name, ",", #char " ");
print_to_builder(*builder, "%,%,%,%,%,%,%,%\n",
name, it.times[0], it.times[1], it.times[2],
it.times[3], it.times[4], it.times[5], it.times[6]);
}
write_entire_file(path, *builder);
return true;
}
// Imports CSV file into database.
// Returns success.
import_from_csv :: (db: *Database, path: string) -> bool {
// TODO Review code.
assert(db != null, ASSERT_NOT_NULL, "db");
assert(xx path, ASSERT_NOT_EMPTY, "path");
error_code: s64;
// Check file size TODO Read based on file size
//file_info: stat_t;
//error_code = sys_stat(path, *file_info); // TODO Check for error.
//size := file_info.st_size;
size := 0;
success: bool;
map: Map_File_Info;
data: string;
is_using_map := false;
if size >= 1<<30 {
assert(false, "Parsing big files not implemented yet.");
}
else {
data, success = read_entire_file(path);
}
defer if is_using_map then map_entire_file_end(*map); else free(data.data);
csv := data;
if success == false {
print_error("Failed to read file '%' while loading database: ERROR_FROM_LOG", path); // TODO Get error from logger ?!
return false;
}
// TODO Helper function.
consume_next_line :: (sp: *string) -> string, bool {
// To find the end of the line, we look for a linefeed character.
// We will trim a carriage return off the end if there is one there also.
// Thus this works on both 'dos' and 'unix'-style files.
s := << sp;
found, result, right := split_from_left(s, 10);
if !found {
// This is the last line; there may not have been a linefeed after that,
// but we still want to handle that data, so we return true if there was
// a nonzero amount of stuff there.
<< sp = "";
return s, (s.count > 0);
}
// Chop the characters we are going to return from 'sp',
// which holds the remaining file data.
advance(sp, result.count + 1);
if result {
if result[result.count-1] == 13 result.count -= 1; // If there's a carriage return at the end, remove it by decrementing the string's length.
}
return result, true;
}
//Skip header line.
consume_next_line(*csv);
// TODO Helper function.
advance :: inline (array: *[] $T, amount: int = 1) {
assert(amount >= 0);
assert(array.count >= amount);
array.count -= amount;
array.data += amount;
}
next_line :: inline (csv: *string) -> line: string, success: bool {
for 0..csv.count {
if csv.data[it] == #char "\n" {
line: string = < (100<<20) {
// print("temp: %\n", context.temporary_storage.total_bytes_occupied >> 20);
// reset_temporary_storage();
// }
}
}
// Adjust selected task.
if (db.selected_idx < 0) db.selected_idx = 0;
return true;
}
// Appends task to the end of the CSV file.
// Returns success.
append_to_csv :: (task: Task, path: string) -> success: bool {
assert(xx path, ASSERT_NOT_EMPTY, "path");
file, file_success := file_open(path, true, true);
defer file_close(*file);
if file_success == false {
//print_error("Failed to open file '%s' while appending to CSV: %s.", path, strerror(errno)); // TODO Show internal error or something
return false;
}
file_size := file_length(file);
file_set_position(file, file_size-1);
last_char: u8;
file_read(file, *last_char, 1);
if (last_char != #char "\n") {
file_write(*file, "\n");
}
task_name := copy_temporary_string(xx task.name); // TODO Cleanup this temp mess.
replace_chars(task_name, ",", #char " ");
csv_line := tprint("%,%,%,%,%,%,%,%\n", task_name, task.times[0], task.times[1], task.times[2], task.times[3], task.times[4], task.times[5], task.times[6]);
file_write(*file, csv_line);
return true;
}
// Selects task by index.
// Index gets clamped to [0, db->count[.
select_task_by_index :: (db: *Database, index: s64) {
assert(db != null, ASSERT_NOT_NULL, "db");
db.selected_idx = ifx db.tasks.count == 0 then -1 else
ifx index < 0 then 0 else
ifx index >= db.tasks.count then db.tasks.count - 1 else
index;
}
// Selects task by delta relative to currently selected task.
select_task_by_delta :: (db: *Database, delta: s64) {
assert(db != null, ASSERT_NOT_NULL, "db");
// TODO I bet there's a better way to do this... maybe use a clamp or range or something.
idx :=
ifx (delta > 0 && db.selected_idx > S64_MAX - delta) then S64_MAX else
ifx (delta < 0 && db.selected_idx < S64_MIN - delta) then S64_MIN else
db.selected_idx + delta;
select_task_by_index(db, idx);
}
// Selects task.
select_task :: (db: *Database, task: *Task) {
assert(db != null, ASSERT_NOT_NULL, "db");
assert(task != null, ASSERT_NOT_NULL, "task");
assert(contains_task(db, task), ASSERT_NOT_CONTAIN, "db", "task");
db.selected_idx = task - db.tasks.data;
}
// Set active task.
// Passing task as NULL de-activates any previously active task.
set_active_task :: (db: *Database, task: *Task) {
assert(db != null, ASSERT_NOT_NULL, "db");
if task != null
assert(contains_task(db, task), ASSERT_NOT_CONTAIN, "db", "task");
update_times(db);
db.active_idx = ifx (task == null) then -1 else task - db.tasks.data;
}
// Returns true when database is full.
is_database_full :: inline (db: Database) -> bool {
return db.tasks.count >= MAX_DATABASE_TASKS;
}
INPUT_TIMEOUT_MS :: 1000;
INPUT_AWAIT_INF :: -1;
NUM_HEADER_ROWS :: 1;
NUM_FOOTER_ROWS :: 1;
NUM_COLUMNS :: 9;
L_TITLE_IDX :: 0;
L_DAYS_IDX :: 1;
L_TOTAL_IDX :: 8;
Column :: struct {
header : string;
width : int;
alignment_offset : int;
alignment : u8;
}
Layout :: struct {
columns : [NUM_COLUMNS] Column;
archive_title : string;
}
layouts : [#run type_info(Layouts).values.count] Layout;
layout_tasks_rows : int;
is_terminal_too_small := true;
initialize_tui :: () {
// Normal layout.
layouts[Layouts.NORMAL] = .{
archive_title = " Archive ",
columns = .[
.{ header = #run join(" Task Time Tracker v", VERSION, " "), width = -1, alignment = #char "L" },
.{ header = " Sun ", width = 7, alignment = #char "C" },
.{ header = " Mon ", width = 7, alignment = #char "C" },
.{ header = " Tue ", width = 7, alignment = #char "C" },
.{ header = " Wed ", width = 7, alignment = #char "C" },
.{ header = " Thu ", width = 7, alignment = #char "C" },
.{ header = " Fri ", width = 7, alignment = #char "C" },
.{ header = " Sat ", width = 7, alignment = #char "C" },
.{ header = " Total ", width = 9, alignment = #char "C" },
]
};
// Compact layout.
layouts[Layouts.COMPACT] = .{
archive_title = " Archive ",
columns = .[
.{ header = #run join(" TTT ", VERSION, " "), width = -1, alignment = #char "L" },
.{ header = " S ", width = 5, alignment = #char "C" },
.{ header = " M ", width = 5, alignment = #char "C" },
.{ header = " T ", width = 5, alignment = #char "C" },
.{ header = " W ", width = 5, alignment = #char "C" },
.{ header = " T ", width = 5, alignment = #char "C" },
.{ header = " F ", width = 5, alignment = #char "C" },
.{ header = " S ", width = 5, alignment = #char "C" },
.{ header = " # ", width = 5, alignment = #char "C" },
]
};
// Calculate alignment_offsets.
for * layout: layouts {
for * col: layout.columns {
offset: int;
if col.alignment == {
case #char "L";
offset = 0;
case #char "C";
offset = ((col.width - col.header.count) / 2);
case #char "R";
offset = (col.width - col.header.count);
}
col.alignment_offset = offset;
}
}
// TODO
//setlocale(LC_ALL, "C.UTF-8"); // Sets locale for C library functions; Allows usage of UTF-8.
stdscr = initscr(); // Start curses mode.
cbreak(); // Line buffering disabled; pass on everty thing to me.
keypad(stdscr, true); // I need those nifty F1..F12.
curs_set(0); // Set cursor invisible.
noecho(); // Disable echoing input characters.
// Initialize pairs of colors.
start_color();
use_default_colors(); // Using default (-1) instead of COLOR_BLACK.
init_pair(xx Styles.SELECTED, COLOR_BLACK, COLOR_CYAN);
init_pair(xx Styles.SELECTED_INVERTED, COLOR_CYAN, -1);
init_pair(xx Styles.ACTIVE, COLOR_BLUE, -1);
init_pair(xx Styles.ACTIVE_SELECTED, COLOR_WHITE, COLOR_BLUE);
init_pair(xx Styles.ERROR, COLOR_RED, -1);
}
update_layout :: () {
// Calculate number of available rows to display tasks.
layout_tasks_rows = (size_y - NUM_HEADER_ROWS - NUM_FOOTER_ROWS);
// Calculate first column width: expands to fill the remaining space dynamically.
for * layout: layouts {
layout.columns[0].width = size_x - (NUM_COLUMNS - 1) - 2;
for 1..layout.columns.count-1 {
layout.columns[0].width -= layout.columns[it].width;
}
}
}
draw_tui :: (db: *Database, layout: *Layout) {
adjust_first_day_of_week := int.[
(0 + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS,
(1 + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS,
(2 + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS,
(3 + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS,
(4 + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS,
(5 + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS,
(6 + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS,
];
x: int;
y: int;
col: *Column;
// Get context information.
active_task := get_active_task(db);
selected_task := get_selected_task(db);
now_utc := current_time_consensus();
now_week_day := to_calendar(now_utc, .LOCAL).day_of_week_starting_at_0;
// Reset theme and clear screen.
attrset(A_NORMAL);
erase();
// Draw outer border.
box(stdscr, 0, 0);
// Draw table grids.
// TODO Maybe this could be simplified?
y = 0;
x = 0;
for 0..layout.columns.count-2 {
column := layout.columns[it];
x += 1 + column.width;
mvaddch(xx y, xx x, ACS_TTEE);
for row: 1..size_y-1 {
mvaddch(xx row, xx x, ACS_VLINE);
}
mvaddch(size_y-1, xx x, ACS_BTEE);
}
///////////////////////////////////////////////////////////////////////////
// Draw headers.
y = 0;
x = 0;
// Headers : title
x += 1;
col = *layout.columns[L_TITLE_IDX];
mvaddstr(xx y, xx (x + col.alignment_offset), ifx db == *archive then layout.archive_title.data else col.header.data);
x += col.width;
// Headers : days
for 0..NUM_WEEK_DAYS-1 {
idx := adjust_first_day_of_week[it];
x += 1;
// Apply theme.
if (idx == now_week_day && active_task != null) {
attron(COLOR_PAIR(xx Styles.ACTIVE) | A_BOLD);
}
else if (idx == now_week_day) {
attron(COLOR_PAIR(xx Styles.SELECTED_INVERTED) | A_BOLD);
}
col = *layout.columns[L_DAYS_IDX + idx];
mvaddstr(xx y, xx (x + col.alignment_offset), col.header.data);
x += col.width;
// Reset theme.
attrset(A_NORMAL);
}
// Headers : total
x += 1;
col = *layout.columns[L_TOTAL_IDX];
mvaddstr(xx y, xx (x + col.alignment_offset), col.header.data);
///////////////////////////////////////////////////////////////////////////
// Draw tasks.
total_time := 0;
column_width: int;
y = 0;
// Pagination based on currently selected task (show page where selected task is).
idx_start := (db.selected_idx / layout_tasks_rows) * layout_tasks_rows;
// Display up to rows allowed by the layout, or less if reached end of database.
idx_stop := idx_start + (ifx layout_tasks_rows > db.tasks.count - idx_start then db.tasks.count - idx_start else layout_tasks_rows);
for task_idx: idx_start..idx_stop-1 {
//for (size_t idx = idx_start; idx < idx_stop; idx++) {
task := *db.tasks[task_idx];
y += 1;
x = 0;
// Apply theme.
if (task == active_task && task == selected_task) {
attron(COLOR_PAIR(xx Styles.ACTIVE_SELECTED) | A_BOLD);
}
else if (task == selected_task) {
attron(COLOR_PAIR(xx Styles.SELECTED));
}
else if (task == active_task) {
attron(COLOR_PAIR(xx Styles.ACTIVE) | A_BOLD);
}
// Task title.
x += 1;
column_width = layout.columns[L_TITLE_IDX].width;
mvprintw(xx y, xx x, "%-*.*s", column_width, column_width, task.name);
x += column_width;
// Task times.
total_time = 0;
for 0..NUM_WEEK_DAYS-1 {
x += 1;
day_idx := (it + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS;
column_width = layout.columns[L_DAYS_IDX + day_idx].width;
task_time := task.times[day_idx];
total_time = add_int64(total_time, task_time);
mvprintw_time(xx y, xx x, task_time, xx column_width);
x += column_width;
}
// Task total.
x += 1;
mvprintw_time(xx y, xx x, total_time, xx layout.columns[L_TOTAL_IDX].width);
// Reset theme.
attrset(A_NORMAL);
}
///////////////////////////////////////////////////////////////////////////
// Draw selected/total tasks.
size := 1 + number_size(db.selected_idx + 1) + 1 + number_size(db.tasks.count) + 1; // " XXX/YYY "
if (size <= layout.columns[L_TITLE_IDX].width) {
mvprintw(size_y - 1, 1, " %td/%zd ", db.selected_idx + 1, db.tasks.count);
}
else {
mvprintw(size_y - 1, 1, "%td", db.selected_idx + 1);
}
///////////////////////////////////////////////////////////////////////////
// Draw daily totals.
y = size_y - 1;
x = 0 + 1 + layout.columns[L_TITLE_IDX].width;
total_time = 0;
for 0..NUM_WEEK_DAYS-1 {
idx := adjust_first_day_of_week[it];
daily_total := db.total_times[idx];
x += 1;
// Apply theme.
if (idx == now_week_day && active_task != null) {
attron(COLOR_PAIR(xx Styles.ACTIVE) | A_BOLD);
}
else if (idx == now_week_day) {
attron(COLOR_PAIR(xx Styles.SELECTED_INVERTED) | A_BOLD);
}
column_width = layout.columns[L_DAYS_IDX + idx].width;
total_time = add_int64(total_time, daily_total);
mvprintw_time(xx y, xx x, daily_total, xx column_width);
x += column_width;
// Reset theme.
attrset(A_NORMAL);
}
x += 1;
mvprintw_time(xx y, xx x, total_time, xx layout.columns[L_TOTAL_IDX].width);
}
free_memory :: () {
reset_database(*database);
reset_database(*archive);
free(app_directory);
free(db_file_path);
free(ar_file_path);
//reset_temporary_storage();
}
read_input_string_padded :: (row: int, column: int, style: s32, length: int, padding: int) -> string {
str := talloc_string(length);
memset(str.data, 0, str.count);
attron(style | A_UNDERLINE);
mvprintw(xx row, xx column, "%*s", padding, "");
echo();
curs_set(1);
mvgetnstr(xx row, xx column, str.data, xx length);
truncate_string(str, length);
noecho();
curs_set(0);
attrset(A_NORMAL);
return str;
}
read_input_string :: (row: int, column: int, style: s32, length: int) -> string {
return read_input_string_padded(row, column, style, length, length);
}
// Returns success.
read_input_int :: (row: int, style: s32, message: string) -> value: int, success: bool {
attron(xx style);
move(xx row, 1);
addch(ACS_CKBOARD);
addstr(message.data); // TODO Convert to C type
attrset(A_NORMAL);
// Get line number.
input_pos_x := getcurx(stdscr);
input_width := size_x - input_pos_x - 1;
str := read_input_string(row, input_pos_x, style, input_width);
value, success := parse_int(*str);
return value, success;
}
// Retuns true if user presses enter, false otherwise.
read_enter_confirmation :: (row: int, style: int, message: string) -> bool {
assert(message.data != null, ASSERT_NOT_NULL, "message"); // TODO Improve this check?
attron(xx style);
move(xx row, 1);
for 0..size_x-3 {
//for (int idx = 0; idx < size_x - 2; idx++) {
addch(ACS_CKBOARD);
}
mvaddstr(xx row, 2, message.data);
attrset(A_NORMAL);
return getch() == #char "\n";
}
main :: () {
defer report_memory_leaks(); // TODO Remove after final debug sessions.
defer free_memory();
{ // Initialize app directory.
auto_release_temp();
home_dir, success_dir := get_home_directory(); // Returns system owned memory.
if success_dir == false {
home_dir = ".";
}
home_path, success_path := get_absolute_path(home_dir); // Returns temporary memory.
if success_path == false {
print_error("Failed to find home directory '%'.", home_dir);
exit(1);
}
app_directory = join(home_path, "/", APP_FOLDER_NAME);
db_file_path = join(app_directory, "/", DB_FILE_NAME);
ar_file_path = join(app_directory, "/", AR_FILE_NAME);
make_directory_if_it_does_not_exist(app_directory, recursive = true);
}
{ // Initialize database and archive files if needed.
auto_release_temp();
if (file_exists(db_file_path) == false) {
if (store_database(database, db_file_path) == false) {
print_error("Failed to initialize database.");
exit(1);
}
}
if (file_exists(ar_file_path) == false) {
if (export_to_csv(archive, ar_file_path) == false) {
print_error("Failed to initialize archive.");
exit(1);
}
}
}
args := get_command_line_arguments();
defer array_reset(*args);
if args.count > 1 {
is_exit_requested := false;
for 1..args.count-1 {
if is_equal_to_any(args[it], "--help", "-h") {
write_strings(
"Usage: ttt [OPTION]... [FILE]...\n",
" -i, --import-csv [FILE] Import CSV file to database (discard first row).\n",
" -e, --export-csv [FILE] Export database to CSV file.\n",
" -n, --no-autosave Disable autosave feature (only save on exit).\n",
" -h, --help Display this help and exit.\n",
" -v, --version Output version information and exit.\n",
"\n",
"In app commands\n",
" a, A Archive selected task (except if active).\n",
" r, R Restore selected task from archive.\n",
" t, T Select currently active task (if any).\n",
" d, D Duplicate selected task.\n",
" n, N Create new task.\n",
" m, M Move selected task to position.\n",
" g, G Select task by position.\n",
" q, Q Save changes and exit.\n",
" F2 Rename selected task.\n",
" F5 Recalculate total times.\n",
" TAB Toggle archive view.\n",
" BACKSPACE Reset times for selected task.\n",
" DELETE Delete selected task (except if active).\n",
" SPACE, ENTER Toggle selected task as active/inactive.\n",
" 1, 2, 3, 4, 5, 6, 7 Edit selected task time for the Nth day of week:\n",
" =# sets # seconds;\n",
" -# subtracts # seconds;\n",
" # adds # seconds;\n",
" #m specifies # as minutes;\n",
" #h specifies # as hours;\n",
" #d specifies # as days;\n",
" #y specifies # as years.\n",
" UP Select task above.\n",
" DOWN Select task below.\n",
" PAGE-UP Select task 1 page above.\n",
" PAGE-DOWN Select task 1 page below.\n",
" HOME Select first/top task.\n",
" END Select last/bottom task.\n",
"\n",
"Notes\n");
print("- All data files are stored in '%'.\n", app_directory);
print(" If the home directory is undefined, './%' will be used.\n", APP_FOLDER_NAME);
write_strings(
" The database entries are stored in binary format on the 'database.bin' file.\n",
" The archived entries are stored in CSV format on the 'archive.csv' file.\n",
"- During intensive tasks such as saving to file or recalculating totals times,\n",
" a diamond symbol is shown on the top left corner.\n"
);
exit(0);
}
if is_equal_to_any(args[it], "--version", "-v") {
print("Task Time Tracker version % \nCopyright % Daniel Martins\nLicense GPL-3.0-or-later\n", VERSION, YEAR);
exit(0);
}
if is_equal_to_any(args[it], "--import-csv", "-i") {
it += 1;
if it >= args.count {
print_error("Missing CSV file path to import.");
exit(1);
}
if (load_database(*database, db_file_path) == false) {
print_error("Failed to load database.");
exit(1);
}
if (import_from_csv(*database, args[it]) == false) {
print_error("Failed to import CSV file.");
exit(1);
}
if (store_database(*database, db_file_path) == false) {
print_error("Failed to store database.");
exit(1);
}
reset_database(*database);
is_exit_requested = true;
continue;
}
if is_equal_to_any(args[it], "--export-csv", "-e") {
it += 1;
if it >= args.count {
print_error("Missing CSV file path to export.");
exit(1);
}
if (load_database(*database, db_file_path) == false) {
print_error("Failed to load database.");
exit(1);
}
if (export_to_csv(*database, args[it]) == false) {
print_error("Failed to export CSV file.");
exit(1);
}
reset_database(*database);
is_exit_requested = true;
continue;
}
if is_equal_to_any(args[it], "--no-autosave", "-n") {
is_autosave_enabled = false;
continue;
}
print_error("%: invalid option '%'.\nTry '% --help' for more information.", args[0], args[it], args[0]);
exit(1);
}
if is_exit_requested {
exit(0);
}
}
if (load_database(*database, db_file_path) == false) {
print_error("Failed to load database.");
exit(1);
}
initialize_tui();
db := *database;
layout := *layouts[Layouts.COMPACT];
flushinp();
ungetch(KEY_RESIZE);
while (true) {
if (is_terminal_too_small) {
INVALID_WINDOW_MESSAGE :: "Terminal is too small: minimum 60x3.";
mvaddstr(size_y / 2, (size_x - xx INVALID_WINDOW_MESSAGE.count) / 2, INVALID_WINDOW_MESSAGE);
}
else {
draw_tui(db, layout);
draw_error_window();
}
reset_temporary_storage();
timeout(INPUT_TIMEOUT_MS);
key := getch();
if key == #char "q" || key == #char "Q" break;
update_times(*database);
timeout(INPUT_AWAIT_INF);
active_task := get_active_task(db);
selected_task := get_selected_task(db);
action_style := A_BOLD | COLOR_PAIR(xx ifx selected_task == active_task && selected_task != null
then Styles.ACTIVE
else Styles.SELECTED_INVERTED);
error_style := A_BOLD | COLOR_PAIR(xx Styles.ERROR);
selected_task_row : int = ifx is_terminal_too_small then 0
else ifx (db.selected_idx < 0) then 1
else (db.selected_idx % layout_tasks_rows) + NUM_HEADER_ROWS;
if key == {
// When getch() times out.
case ERR;
if (is_autosave_enabled && countdown_to_autosave > 0) {
countdown_to_autosave -= INPUT_TIMEOUT_MS;
if (countdown_to_autosave <= 0) {
show_processing();
if (db == *archive) {
export_to_csv(*archive, ar_file_path);
}
store_database(database, db_file_path);
}
}
// When terminal is resized.
case KEY_RESIZE;
clear();
getmaxyx(stdscr, *size_y, *size_x);
is_terminal_too_small = size_x < 60 || size_y < 3;
update_layout();
layout = *layouts[ifx size_x > 100 then Layouts.NORMAL else Layouts.COMPACT];
case #char "n"; #through;
case #char "N";
if is_database_full(db) {
read_enter_confirmation(selected_task_row, error_style, " Unable to create entry: database is full. ");
continue;
}
// Create new task.
now_utc := current_time_consensus();
now_local := to_calendar(now_utc, .LOCAL);
name := calendar_to_iso_string(now_local);
new_task := add_task(db);
memcpy(new_task.name.data, name.data, min(Task.name.count, name.count));
// Select new task.
select_task(db, new_task);
selected_task = get_selected_task(db);
trigger_autosave();
// Force rename action.
flushinp();
ungetch(KEY_F(2));
case KEY_F2;
if (selected_task == null) continue;
// Change task name.
input := read_input_string_padded(selected_task_row, 1, action_style, Task.name.count, size_x - 2);
if is_empty_string(input) == false {
replace_chars(input, "\t\x0B\x0C\r", #char " ");
memcpy(selected_task.name.data, input.data, min(Task.name.count, input.count));
trigger_autosave();
}
case KEY_BACKSPACE;
if (selected_task == null) continue;
if (read_enter_confirmation(selected_task_row, action_style, " Press enter to reset task. ") == true) {
reset_task_times(db, selected_task);
trigger_autosave();
}
case KEY_DC; // Delete
if (selected_task == null || selected_task == active_task) continue;
if (read_enter_confirmation(selected_task_row, action_style, " Press enter to delete task. ") == true) {
delete_task(db, selected_task);
trigger_autosave();
}
case #char "1"; #through;
case #char "2"; #through;
case #char "3"; #through;
case #char "4"; #through;
case #char "5"; #through;
case #char "6"; #through;
case #char "7";
if (selected_task == null) continue;
// Prepare position to input time operation.
selected_day := key - #char "1";
input_width := layout.columns[L_DAYS_IDX + selected_day].width;
input_pos_x := 1 + layout.columns[L_TITLE_IDX].width;
for 0..selected_day-1 {
input_pos_x += 1 + layout.columns[L_DAYS_IDX + it].width;
}
input_pos_x += 1;
// Get input string.
input := read_input_string(selected_task_row, input_pos_x, action_style, input_width); // TODO Temp stringzes.
// Abort if input if empty.
if is_empty_string(input) continue;
// Search for assign '=' operator and discard everything before it.
assign_idx := find_index_from_left(input, "=");
is_assign := assign_idx >= 0;
if is_assign advance(*input, assign_idx + 1);
// Try to parse a number and abort if it fails.
input_float, parse_success := string_to_float64(input);
if parse_success == false continue;
// Try to parse a character representing the time multiplier.
multiplier: float64 = 1.0;
for 0..input.count-1 {
ch := to_lower(input[it]);
if ch == {
case #char "m";
multiplier = xx SECONDS_IN_MINUTE;
break;
case #char "h";
multiplier = xx SECONDS_IN_HOUR;
break;
case #char "d";
multiplier = xx SECONDS_IN_DAY;
break;
case #char "y";
multiplier = xx SECONDS_IN_YEAR;
break;
}
}
// Process input and check if it's valid.
input_time := input_float * multiplier;
if (input_time > xx S64_MAX || input_time < xx S64_MIN) continue;
// Apply changes.
time := cast(s64)input_time;
day := (selected_day + FIRST_DAY_OF_WEEK) % NUM_WEEK_DAYS;
if is_assign set_task_time(db, selected_task, day, time);
else add_task_time(db, selected_task, day, time);
trigger_autosave();
case #char "m"; #through;
case #char "M";
if selected_task == null continue;
value, success := read_input_int(selected_task_row, action_style, " Move to: ");
if success == false continue;
target_index := clamp(value, 1, MAX_DATABASE_TASKS) - 1;
move_task_to_index(db, selected_task, target_index);
trigger_autosave();
case #char "g"; #through;
case #char "G";
if selected_task == null continue;
value, success := read_input_int(selected_task_row, action_style, " Go to: ");
if success == false continue;
target_index := clamp(value, 1, MAX_DATABASE_TASKS) - 1;
select_task_by_index(db, target_index);
case #char "d"; #through;
case #char "D";
if selected_task == null continue;
if is_database_full(db) {
read_enter_confirmation(selected_task_row, error_style, " Unable to duplicate entry: database is full. ");
continue;
}
if (add_task(db, selected_task) == null) continue; // TODO Show error?
trigger_autosave();
case KEY_F5;
update_total_times(db);
trigger_autosave();
case #char "t"; #through;
case #char "T";
if (active_task == null) continue;
select_task(db, active_task);
case #char "\n"; #through;
case #char " ";
if (db != *database || selected_task == null) continue;
set_active_task(db, ifx (active_task == selected_task) then null else selected_task);
active_task = get_active_task(db);
trigger_autosave();
case #char "\t";
if (db == *database) {
if (import_from_csv(*archive, ar_file_path) == false) {
reset_database(*archive);
print_error("Failed to load archive.");
continue;
}
db = *archive;
}
else {
if (export_to_csv(*archive, ar_file_path) == false) {
print_error("Failed to store archive.");
continue;
}
reset_database(*archive);
db = *database;
}
case #char "a"; #through;
case #char "A";
if (db != *database || selected_task == null || selected_task == active_task) continue;
if (append_to_csv(selected_task, ar_file_path) == false) {
print_error("Failed to archive entry.");
continue;
}
delete_task(*database, selected_task);
trigger_autosave();
case #char "r"; #through;
case #char "R";
if (db != *archive || selected_task == null) continue;
if is_database_full(*database) {
read_enter_confirmation(selected_task_row, error_style, " Unable to restore entry: database is full. ");
continue;
}
if (add_task(*database, selected_task) == null) {
print_error("Failed to restore entry.");
continue;
}
delete_task(*archive, selected_task);
trigger_autosave();
case KEY_HOME;
select_task_by_index(db, 0);
case KEY_UP;
select_task_by_delta(db, -1);
case KEY_PPAGE;
select_task_by_delta(db, -layout_tasks_rows);
case KEY_END;
select_task_by_index(db, db.tasks.count-1);
case KEY_DOWN;
select_task_by_delta(db, 1);
case KEY_NPAGE;
select_task_by_delta(db, layout_tasks_rows);
}
}
// Save any unsaved changes.
show_processing();
error_saving := false;
if (db == *archive) {
if (export_to_csv(archive, ar_file_path) == false) {
print_error("Failed to save archive.");
error_saving |= true;
}
}
if (countdown_to_autosave > 0 || is_autosave_enabled == false) {
if (store_database(database, db_file_path) == false) {
print_error("Failed to save database.");
error_saving |= true;
}
}
if (error_saving) {
print_error("Press any key to close.");
draw_error_window();
timeout(INPUT_AWAIT_INF);
getch();
}
endwin();
exit(xx ifx error_saving then 1 else 0);
}