[
  {
    "path": "README.md",
    "content": "# ranwhen – Visualize when your system was running\n\nranwhen is a Python script that graphically shows **in your terminal** when your system was running in the past. Have a look:\n\n![Screenshot](Screenshot.png?raw=true)\n\n\n# Requirements\n\n* *nix system with [last(1)](http://linux.die.net/man/1/last) installed and supporting the -R and -F flags\n* [Python >= 3.2](http://www.python.org/)\n* Terminal emulator with support for Unicode and xterm's 256 color mode\n\nThe above requirements should be fulfilled by default on the majority of modern Linux distributions, where the only thing that needs to be done is usually to install Python 3.\n\n\n# License\n\nCopyright © 2013 Philipp Emanuel Weidmann (<pew@worldwidemann.com>)\n\nranwhen 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.\n\nranwhen 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.\n\nYou should have received a copy of the GNU General Public License along with ranwhen.  If not, see <http://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "ranwhen.py",
    "content": "#!/usr/bin/env python3\n\n# ranwhen – Visualize when your system was running\n#\n# Requirements:\n# - *nix system with last(1) installed and supporting the -R and -F flags\n# - Python >= 3.2\n# - Terminal emulator with support for Unicode and xterm's 256 color mode\n#\n#\n# Copyright © 2013 Philipp Emanuel Weidmann <pew@worldwidemann.com>\n#\n# Nemo vir est qui mundum non reddat meliorem.\n#\n#\n# ranwhen is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# ranwhen is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with ranwhen.  If not, see <http://www.gnu.org/licenses/>.\n\nimport subprocess\nimport re\nfrom datetime import datetime, timedelta\nimport sys\n\n\n# Line format of last's output\n# e.g. \"reboot   system boot  Wed Jan 16 21:36:54 2013 - Wed Jan 16 22:05:50 2013  (00:28)\"\nline_pattern = re.compile(\"reboot\\s+system\\s+boot\\s+\\w{3}\\s+([\\d\\w\\s:]{20})\\s+-\\s+\\w{3}\\s+([\\d\\w\\s:]{20})\")\n\n# Date format used by last\n# e.g. \"Jan 16 21:36:54 2013\"\ntime_format = \"%b %d %H:%M:%S %Y\"\n\n# Extracts start and end time from a line of last's output\ndef parse_line(line):\n\tresult = line_pattern.match(line)\n\tif result is None:\n\t\treturn None\n\telse:\n\t\tfrom_time = datetime.strptime(result.group(1), time_format)\n\t\tto_time   = datetime.strptime(result.group(2), time_format)\n\t\treturn { \"from\" : from_time, \"to\" : to_time }\n\n\n# Returns the length of time for which two time spans overlap\n# (i.e. the length of their intersection)\ndef time_overlap(time_span_1, time_span_2):\n\tif max(time_span_1[\"from\"], time_span_2[\"from\"]) >= \\\n\t   min(time_span_1[\"to\"], time_span_2[\"to\"]):\n\t\t# No overlap\n\t\treturn timedelta()\n\treturn min(time_span_1[\"to\"], time_span_2[\"to\"]) - \\\n\t       max(time_span_1[\"from\"], time_span_2[\"from\"])\n\n\n# Do not use escape sequences if output is piped\nuse_escape_sequences = sys.stdout.isatty()\n\n# Returns an xterm escape sequence that, if printed to the terminal,\n# will reset all character attributes to the default\ndef get_reset_sequence():\n\tif use_escape_sequences:\n\t\treturn \"\\033[0m\"\n\treturn \"\"\n\n# Returns an xterm escape sequence that, if printed to the terminal,\n# will set the specified character attributes\ndef get_escape_sequence(fgcolor = None, bgcolor = None, bold = False):\n\tif use_escape_sequences:\n\t\treturn get_reset_sequence() + \\\n\t\t       \"\\033[%s%s%sm\" % \\\n\t\t       (\"\" if fgcolor is None else (\"38;5;%d\" % fgcolor), \\\n\t\t       \t\"\" if bgcolor is None else (\";48;5;%d\" % bgcolor), \\\n\t\t       \t\";1\" if bold else \"\")\n\treturn \"\"\n\n# Output colors as xterm color codes\n# (see e.g. http://www.calmar.ws/vim/256-xterm-24bit-rgb-color-chart.html)\nforeground_color = 251\nheading_color = 208\nheading_line_color = 246\ntime_color = 231\ntime_text_color = 246\nhistogram_color = [ 57, 56, 126, 197 ]\nhistogram_color_grid = [ 99, 97, 169, 204 ]\nweekday_color = 245\nweekend_color = 231\nbar_color = 28\nbar_weekend_color = 82\nbar_color_grid = 77\nbar_weekend_color_grid = 156\nnight_color = 51\nsunrise_color = 228\nnoon_color = 226\nsunset_color = 214\ngrid_color = 238\n\n# Returns a string that, if printed to the terminal,\n# will display the specified text with the specified attributes\ndef style_text(text, fgcolor = foreground_color, bgcolor = None, bold = False):\n\treturn get_escape_sequence(fgcolor, bgcolor, bold) + text + \\\n\t       get_escape_sequence(fgcolor = foreground_color)\n\n\n# Computes the number of hours (total), minutes and seconds\n# in the specified timedelta object\ndef get_delta_fields(delta):\n\tfields = {}\n\tfields[\"hours\"], remainder = divmod(round(delta.total_seconds()), 3600)\n\tfields[\"minutes\"], fields[\"seconds\"] = divmod(remainder, 60)\n\treturn fields\n\n# Formats the specified timedelta object into a string\n# of the form \"X hours Y minutes\"\ndef format_delta(delta):\n\tfields = get_delta_fields(delta)\n\treturn style_text(\"%4d\" % fields[\"hours\"], fgcolor = time_color) + \\\n\t       style_text(\" hours \", fgcolor = time_text_color) + \\\n\t       style_text(\"%2d\" % fields[\"minutes\"], fgcolor = time_color) + \\\n\t       style_text(\" minutes\", fgcolor = time_text_color)\n\n# Formats the specified timedelta object into a string\n# of the form \"XX:YY\"\ndef format_delta_short(delta):\n\tfields = get_delta_fields(delta)\n\tif fields[\"hours\"] == 0 and fields[\"minutes\"] == 0:\n\t\treturn \"\"\n\tif fields[\"hours\"] == 0:\n\t\treturn style_text(\"  :\", fgcolor = time_text_color) + \\\n\t\t       style_text(\"%02d\" % fields[\"minutes\"], fgcolor = time_color)\n\treturn style_text(\"%2d\" % fields[\"hours\"], fgcolor = time_color) + \\\n\t       style_text(\":\", fgcolor = time_text_color) + \\\n\t\t   style_text(\"%02d\" % fields[\"minutes\"], fgcolor = time_color)\n\noutput_width = 61\n\n# Returns a styled section separator used to frame a calendar month\ndef format_heading(heading):\n\tpadded_heading = \" \" + heading + \" \"\n\theading_pos = int((output_width - len(padded_heading)) / 2)\n\tfull_heading = style_text(\"┌\" + (\"─\" * heading_pos), fgcolor = heading_line_color) + \\\n\t               style_text(padded_heading, fgcolor = heading_color)\n\tfull_heading += style_text((\"─\" * (output_width - heading_pos - len(padded_heading))) + \"┐\", \\\n\t\t                       fgcolor = heading_line_color)\n\treturn full_heading\n\n\n\n##### Program logic starts here #####\n\n\n\n# ranwhen parses the output of this command\ncommand = \"last -R -F reboot\"\n\n\n# Major time granularity (lines)\nday = timedelta(days = 1)\n\n# Minor time granularity (columns)\nhalf_hour = timedelta(minutes = 30)\n\n# Ratio of granularities (columns per line)\nhalf_hours_in_day = round(day / half_hour)\n\n\noutput = subprocess.check_output(command.split(), universal_newlines = True)\n\nlines = output.splitlines()\n\ntime_spans = []\n\n### Parse output\nfor line in lines:\n\tresult = parse_line(line)\n\tif result is not None:\n\t\ttime_spans.append(result)\n\nif not time_spans:\n\tsys.exit(\"Error: '%s' returned no parsable output\" % command)\n\n\n### Merge overlapping time spans (for unknown reasons, last sometimes outputs them)\ntime_spans_merged = True\nwhile time_spans_merged:\n\ttime_spans_merged = False\n\ttime_spans_new = []\n\ti = 0\n\twhile i < len(time_spans):\n\t\tif i < len(time_spans) - 1 and time_overlap(time_spans[i], time_spans[i + 1]) > timedelta():\n\t\t\t# Time spans overlap\n\t\t\ttime_spans_new.append({ \"from\" : min(time_spans[i][\"from\"], time_spans[i + 1][\"from\"]), \\\n\t\t\t                        \"to\"   : max(time_spans[i][\"to\"], time_spans[i + 1][\"to\"]) })\n\t\t\ti += 1\n\t\t\ttime_spans_merged = True\n\t\telse:\n\t\t\ttime_spans_new.append(time_spans[i])\n\t\ti += 1\n\ttime_spans = time_spans_new\n\n\n### Compute period\nlatest_time   = time_spans[0][\"to\"]\nearliest_time = time_spans[-1][\"from\"]\n\nlatest_time   = latest_time.replace(hour = 0, minute = 0, second = 0) + day\nearliest_time = earliest_time.replace(hour = 0, minute = 0, second = 0)\n\n\n### Compute runtime for each half hour time slot in period\ntime_slots = []\n\naggregated_time_slots = [ timedelta() ] * half_hours_in_day\n\ntotal_time = timedelta()\n\ncurrent_time = latest_time\nwhile current_time > earliest_time:\n\tcurrent_time -= half_hour\n\ttime_slot = { \"from\" : current_time, \"to\" : current_time + half_hour }\n\ttime_in_slot = timedelta()\n\tfor time_span in time_spans:\n\t\ttime_in_slot += time_overlap(time_slot, time_span)\n\ttime_slots.append({ \"time\" : current_time, \"time_in_slot\" : time_in_slot })\n\thalf_hour_index = current_time.hour * 2 + (1 if current_time.minute >= 30 else 0)\n\taggregated_time_slots[half_hour_index] += time_in_slot\n\ttotal_time += time_in_slot\n\n\n# Required because we want to process the individual days from the start of each one\ntime_slots.reverse()\n\n\ntime_header = \"       0:00 \" + style_text(\"☾\", fgcolor = night_color) + \\\n\t\t\t  \"      6:00 \" + style_text(\"☀\", fgcolor = sunrise_color) + \\\n\t\t\t  \"     12:00 \" + style_text(\"☀\", fgcolor = noon_color) + \\\n\t\t\t  \"     18:00 \" + style_text(\"☀\", fgcolor = sunset_color) + \\\n\t\t\t  \"     24:00 \" + style_text(\"☽\", fgcolor = night_color)\n\ngrid_header = style_text(\"▆           ▆           ▆           ▆           ▆\", fgcolor = grid_color)\ngrid_footer = style_text(\"▀           ▀           ▀           ▀           ▀\", fgcolor = grid_color)\n\nlevel_characters = [ \" \", \"▁\", \"▂\", \"▃\", \"▄\", \"▅\", \"▆\", \"▇\", \"█\" ]\n\n\n# Set default foreground color for output\nprint(get_escape_sequence(fgcolor = foreground_color), end = \"\")\n\n\n### Print summary\nnumber_of_days = (latest_time - earliest_time).days\n\nprint(style_text(\"Period:  \", bold = True) + \\\n\t  earliest_time.strftime(\"%B %d %Y\") + \" – \" + \\\n\t  (latest_time - day).strftime(\"%B %d %Y\") + \\\n\t  \" (\" + \\\n\t  style_text(\"%d\" % number_of_days, fgcolor = time_color) + \\\n\t  style_text(\" days\", fgcolor = time_text_color) + \")\")\n\nprint()\n\nprint(style_text(\"Total time running: \", bold = True) + format_delta(total_time))\nprint(style_text(\"Daily average:      \", bold = True) + format_delta(total_time / number_of_days))\n\nprint()\nprint()\n\n\n### Print histogram\nprint(style_text(\"Histogram:\", bold = True))\nprint()\nprint(time_header)\nprint(\"   max  \" + grid_header)\n\nnumber_of_lines = 4\n\nlevels = len(level_characters) - 1\n\nmin_level = (min(aggregated_time_slots) / number_of_days) / half_hour\nmax_level = (max(aggregated_time_slots) / number_of_days) / half_hour\n\ndef format_histogram_line(label, index):\n\tline = label + \"  \"\n\tslot_index = 0\n\tfor time_slot in aggregated_time_slots:\n\t\tlevel = (time_slot / number_of_days) / half_hour\n\t\t# Normalize level to increase resolution\n\t\tlevel = (level - min_level) / (max_level - min_level)\n\t\tlevel = round(level * (levels * number_of_lines)) - (index * levels)\n\t\t# Clamp level to permissible range\n\t\tlevel = max(0, min(levels, level))\n\t\tgrid = slot_index % 12 == 0\n\t\tslot_index += 1\n\t\tline += style_text(level_characters[level], \\\n\t\t\t               fgcolor = histogram_color_grid[index] if grid else histogram_color[index],\n\t\t\t               bgcolor = grid_color if grid else None)\n\tline += style_text(\" \", bgcolor = grid_color)\n\treturn line\n\nprint(format_histogram_line(\"      \", 3))\nprint(format_histogram_line(\"      \", 2))\nprint(format_histogram_line(\"      \", 1))\nprint(format_histogram_line(\"   min\", 0))\n\nprint(\"        \" + grid_footer)\n\nprint()\n\n\n### Print month views\ncurrent_time = latest_time\n\n# 0 is not a valid month index, so the \"month changed\" condition\n# will always be fulfilled in the first iteration\ncurrent_month = 0\n\n# Do not use full block character here to keep separation between lines\nlevels = len(level_characters) - 2\n\nwhile current_time > earliest_time:\n\tcurrent_time -= day\n\n\tmonth_changed = current_time.month != current_month\n\n\tif month_changed:\n\t\tcurrent_month = current_time.month\n\t\tprint()\n\t\tprint()\n\t\tprint(format_heading(current_time.strftime(\"%B %Y\")))\n\t\tprint()\n\t\tprint(time_header)\n\t\tprint(\"        \" + grid_header)\n\n\tweekend = current_time.weekday() in [5, 6]\n\tsunday  = current_time.weekday() == 6\n\n\ttime_text = style_text(current_time.strftime(\"%a\"), \\\n\t\t                   fgcolor = weekend_color if weekend else weekday_color, \\\n\t\t                   bold = sunday)\n\ttime_text += current_time.strftime(\" %d\").replace(\" 0\", \"  \")\n\n\toutput_line = time_text + \"  \"\n\n\ttime_sum = timedelta()\n\n\tbar_text = \"\"\n\n\tslot_index = 0\n\n\t### Build chart for day\n\tfor time_slot in time_slots:\n\t\tif time_slot[\"time\"] >= current_time and time_slot[\"time\"] < current_time + day:\n\t\t\ttime_sum += time_slot[\"time_in_slot\"]\n\t\t\tlevel = round((time_slot[\"time_in_slot\"] / half_hour) * levels)\n\t\t\tgrid = slot_index % 12 == 0\n\t\t\tslot_index += 1\n\t\t\tbar_text += style_text(level_characters[level], \\\n\t\t\t\t                   fgcolor = (bar_weekend_color_grid if grid else bar_weekend_color) if weekend \\\n\t\t\t\t                             else (bar_color_grid if grid else bar_color),\n\t\t\t\t                   bgcolor = grid_color if grid else None)\n\n\toutput_line += bar_text\n\n\toutput_line += style_text(\" \", bgcolor = grid_color)\n\n\toutput_line += \" \" + format_delta_short(time_sum)\n\n\tprint(output_line)\n\n\tif (current_time.day == 1) or \\\n\t   (current_time <= earliest_time):\n\t\t# End of month\n\t\tprint(\"        \" + grid_footer)\n\n\n# Reset text attributes\nprint(get_reset_sequence(), end = \"\")\n"
  }
]