Skip to content

Commit

Permalink
work/play filter now works in history dialog
Browse files Browse the repository at this point in the history
  • Loading branch information
jokedst committed Jul 16, 2018
1 parent 1728607 commit ea6669c
Show file tree
Hide file tree
Showing 16 changed files with 201 additions and 57 deletions.
3 changes: 3 additions & 0 deletions ATray/ATray.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,9 @@
<DependentUpon>AddRepositoryForm.cs</DependentUpon>
</Compile>
<Compile Include="Config.cs" />
<Compile Include="Dialogs\AutoScrollPanel.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="Dialogs\DiskUsageForm.cs">
<SubType>Form</SubType>
</Compile>
Expand Down
7 changes: 4 additions & 3 deletions ATray/Activity/ActivityManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ internal class ActivityManager
private static readonly int ActivityFileFormatVersion = int.Parse(ConfigurationManager.AppSettings["ActivityFileFormatVersion"] ?? "1");

#if DEBUG
private static string SharedPath => Program.Configuration.SharedActivityStorage != null
? Path.Combine(Program.Configuration.SharedActivityStorage, "DEBUG")
: null;
private static string SharedPath => Program.Configuration.SharedActivityStorage == null ? null :
Program.Configuration.SharedActivityStorage.EndsWith("DEBUG")
? Program.Configuration.SharedActivityStorage
: Path.Combine(Program.Configuration.SharedActivityStorage, "DEBUG");
#else
private static string SharedPath => Program.Configuration.SharedActivityStorage;
#endif
Expand Down
2 changes: 2 additions & 0 deletions ATray/Activity/ActivityMonitor.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
Expand Down Expand Up @@ -62,6 +63,7 @@ public string CurrentlyActiveWindow
[NotifyPropertyChangedInvocator]
private void SetProperty<T>(ref T underlyingField, T newValue, [CallerMemberName] string propertyName = null)
{
// someone: if (EqualityComparer<T>.Default.Equals(underlyingField, newValue)) return;
if (newValue.Equals(underlyingField)) return;
underlyingField = newValue;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
Expand Down
2 changes: 1 addition & 1 deletion ATray/Activity/ActivitySpan.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public ActivitySpan(MonthActivities owner, byte day)
Day = owner.Days[day];
}

public ActivitySpan( DayActivityList day, uint startSecond, uint endSecond, bool wasActive, string applicationName, string windowTitle)
public ActivitySpan(DayActivityList day, uint startSecond, uint endSecond, bool wasActive, string applicationName, string windowTitle)
{
Owner = day.Owner;
Day = day;
Expand Down
5 changes: 5 additions & 0 deletions ATray/Activity/MonthActivities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,11 @@ public MonthActivities(string filepath)
if (fileNameParts.Length > 1 && fileNameParts[1].StartsWith("Acts"))
ComputerName = fileNameParts[0];
else ComputerName = Environment.MachineName;

if (Program.ActivityClassifyer != null)
{
Program.ActivityClassifyer.Classify(this, GuessWorkPlay.SameBlock);
}
}

/// <summary>
Expand Down
37 changes: 29 additions & 8 deletions ATray/Activity/WorkPlayFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,36 +20,57 @@ public class WorkPlayFilter
{
protected class Pattern
{
public Regex Reg { get; }
public Regex RegularExpression { get; }
public int Prio { get; }
public bool IsWork { get; }

public Pattern(int prio, string pattern, bool isWork)
{
this.Prio = prio;
this.IsWork = isWork;
this.Reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
this.RegularExpression = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
}

public string OriginalPattern => Reg.ToString();
public string OriginalPattern => RegularExpression.ToString();
}

protected Dictionary<string, Pattern> WorkPlayPatterns = new Dictionary<string, Pattern>();

public void Classify(MonthActivities history)
public void Classify(MonthActivities history, GuessWorkPlay guessWhenUnknown = GuessWorkPlay.Agressive)
{
var patterns = WorkPlayPatterns.Values.OrderBy(x => x.Prio).ToList();
foreach (var day in history.Days)
{
WorkPlayType lastType = WorkPlayType.Unknown;
var unsureActs = new List<ActivitySpan>();
uint lastActiveSecond = 0;

for (var a = 0; a < day.Value.Count; a++)
{
var act = day.Value[a];
var akey = Key(history.ComputerName, act.ApplicationName(), act.WindowTitle());

var firstAfterGap = false;
if (act.WasActive)
{
if (lastActiveSecond==0||act.StartSecond - lastActiveSecond > 60 * 60)
{
// There has been a 1 hour gap - don't guess across it
firstAfterGap = true;
if (unsureActs.Any() && guessWhenUnknown == GuessWorkPlay.SameBlock)
{
if(lastType != WorkPlayType.Unknown)
foreach (var unsureAct in unsureActs)
unsureAct.Classification = lastType;
unsureActs.Clear();
lastType = WorkPlayType.Unknown;
}
}

lastActiveSecond = act.EndSecond;
}

var found = patterns.FirstOrDefault(x => x.Reg.IsMatch(akey));
var found = patterns.FirstOrDefault(x => x.RegularExpression.IsMatch(akey));
if (found == null)
{
unsureActs.Add(act);
Expand All @@ -58,7 +79,7 @@ public void Classify(MonthActivities history)
{
var thisActType = found.IsWork ? WorkPlayType.Work : WorkPlayType.Play;

if (unsureActs.Any())
if (guessWhenUnknown >= GuessWorkPlay.SameBlock && unsureActs.Any())
{
if(lastType == WorkPlayType.Unknown || lastType == thisActType)
foreach (var unsureAct in unsureActs)
Expand All @@ -81,7 +102,7 @@ public void Classify(MonthActivities history)
}
}

if (unsureActs.Count == 0) continue;
if (guessWhenUnknown == GuessWorkPlay.Never || unsureActs.Count == 0) continue;

if (lastType == WorkPlayType.Unknown)
{
Expand All @@ -99,7 +120,7 @@ public void Classify(MonthActivities history)
}
}

public string Key(string computer, string program, string title) => $"^{computer}\t{program}\t{title}$";
public string Key(string computer, string program, string title) => $"{computer}\t{program}\t{title}";
public string KeyPattern(string computer, string program, string title) => $"^{computer ?? ".*"}\t{program ?? ".*"}\t{title ?? ".*"}$";

protected void AddPattern(Pattern playPattern)
Expand Down
10 changes: 10 additions & 0 deletions ATray/Activity/WorkPlayType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,14 @@ public enum WorkPlayType
Play = 2,
Both = 3,
}

/// <summary>
/// How we guess work/play when we don't know
/// </summary>
public enum GuessWorkPlay
{
Never = 0,
SameBlock = 1,
Agressive = 2
}
}
5 changes: 5 additions & 0 deletions ATray/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ public class Configuration
[Description("Locks computer when the monitor is turned off (=laptop lid close)"), Category("General"), DefaultValue(false)]
public bool LockOnMonitorOff { get; set; }

[Description("Activate a web server that allows some remote control"), Category("Web Server"), DefaultValue(false)]
public bool ActivateWebserver { get; set; }
[Description("TCP port to use"), Category("Web Server"), DefaultValue(14754)]
public int Port { get; set; }

public Configuration(string filename = null)
{
// Set defaults
Expand Down
24 changes: 21 additions & 3 deletions ATray/Dialogs/ActivityHistoryForm.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

64 changes: 49 additions & 15 deletions ATray/Dialogs/ActivityHistoryForm.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
namespace ATray
using System.Diagnostics;

namespace ATray
{
using System;
using System.Collections.Generic;
Expand Down Expand Up @@ -27,6 +29,7 @@ public partial class ActivityHistoryForm : Form
private int _currentMonth = (DateTime.Now.Year * 100) + DateTime.Now.Month;

private bool _forceRedraw;
private bool _ignoreEvents;

private uint _graphWidth;
private uint _graphSeconds;
Expand Down Expand Up @@ -56,6 +59,7 @@ public ActivityHistoryForm()

private void InitComputerDropDown()
{
// Two magic strings: Empty string means current computer, '*' means all computers
var computers = ActivityManager.GetSharedHistoryComputers().Select(x =>new Tuple<string,string> (x, x)).ToList();
computers.RemoveAll(x => x.Item1 == Environment.MachineName);
computers.Add(new Tuple<string, string>(AllComputers, "All"));
Expand All @@ -64,7 +68,7 @@ private void InitComputerDropDown()
computerDropDown.ValueMember = "item1";
computerDropDown.DisplayMember = "item2";
computerDropDown.DataSource = computers;
computerDropDown.SelectedValue = _showSharedHistory ? AllComputers : string.Empty;
computerDropDown.SelectedValue = string.Empty;
computerDropDown.SelectedValueChanged += computerDropDown_SelectedValueChanged;
}

Expand All @@ -79,14 +83,29 @@ private void InitHistoryDropDown()
return;
}

var months = rawMonths.Select(x => Tuple.Create(x, new DateTime(x / 100, x % 100, 1).ToString("MMMM yyyy"))).ToList();
monthDropDown.ValueMember = "item1";
monthDropDown.DisplayMember = "item2";
monthDropDown.DataSource = months;
monthDropDown.SelectedValue = rawMonths.LastOrDefault();

nextMonthButton.Enabled = false;
lastMonthButton.Enabled = rawMonths.Count > 1;
try
{
_ignoreEvents = true;
var selectedMonth = monthDropDown.SelectedValue as int?;

var months = rawMonths
.Select(x => Tuple.Create(x, new DateTime(x / 100, x % 100, 1).ToString("MMMM yyyy"))).ToList();
monthDropDown.ValueMember = "item1";
monthDropDown.DisplayMember = "item2";
monthDropDown.DataSource = months;

var month = selectedMonth.HasValue && rawMonths.Contains(selectedMonth.Value)
? selectedMonth.Value
: rawMonths.LastOrDefault();
monthDropDown.SelectedValue = month;

nextMonthButton.Enabled = rawMonths.Any(x => x > month);
lastMonthButton.Enabled = rawMonths.Any(x => x < month);
}
finally
{
_ignoreEvents = false;
}
}

private void HistoryPictureOnMouseLeave(object sender, EventArgs eventArgs) => _tipLabel.Hide();
Expand Down Expand Up @@ -115,7 +134,7 @@ private void HistoryPictureOnMouseMove(object sender, MouseEventArgs e)
var second = (((uint)e.X - GraphStartPixel) * _graphSeconds / _graphWidth) + _graphFirstSecond;

var graphPixel = e.X - GraphStartPixel;
var slot= DaySlots.GetValueOrDefault(dayNumber).FirstOrDefault(d => d.EndX >= graphPixel);
var slot = DaySlots.GetValueOrDefault(dayNumber).FirstOrDefault(d => d.EndX >= graphPixel);
if (slot == null || slot.StartX > graphPixel)
_tipLabel.Text = $"{SecondToTime(second)} (no activity)";
else
Expand Down Expand Up @@ -152,19 +171,26 @@ private void ActivityHistoryForm_Paint(object sender, PaintEventArgs e)
{
return;
}
Debug.WriteLine("Redrawing history because " + (_forceRedraw?"forced to":(ClientRectangle.Width != _lastWindowWidth)?"width changed": imageGettingOld?"it's getting stale":(_historyGraph==null)?"there is none yet":"aliens"));

// Get activity for selected year/month
var year = (short)(_currentMonth / 100);
var month = (byte)(_currentMonth % 100);
Dictionary<string, MonthActivities> history;
if (_showSharedHistory)

var computer = (string) computerDropDown.SelectedValue;
if (string.IsNullOrEmpty(computer))
{
history = new Dictionary<string, MonthActivities>
{
[string.Empty] = ActivityManager.GetMonthActivity(year, month)
};
}
else
{
var computer = (string) computerDropDown.SelectedValue;
if (computer == AllComputers) computer = null;
history = ActivityManager.GetSharedMonthActivities(year, month, computer);
}
else
history = new Dictionary<string, MonthActivities>{[string.Empty] = ActivityManager.GetMonthActivity(year, month)};

// if(hidePlay)
//history = WorkPlayFilter.Filter(history, WorkPlayType.WorkOnly);
Expand Down Expand Up @@ -243,6 +269,7 @@ private void historyPicture_MouseEnter(object sender, EventArgs e)

private void monthDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
if (_ignoreEvents) return;
_currentMonth = (int)monthDropDown.SelectedValue;

var availableMonths = monthDropDown.Items.Cast<Tuple<int, string>>().Select(x => x.Item1);
Expand Down Expand Up @@ -277,5 +304,12 @@ private void computerDropDown_SelectedValueChanged(object sender, EventArgs e)
_forceRedraw = true;
Refresh();
}

private void OnShowWorkCheckboxChange(object sender, EventArgs e)
{
Trace.TraceInformation("work checkbox changed: " + showWork.Checked);
_forceRedraw = true;
Refresh();
}
}
}
Loading

0 comments on commit ea6669c

Please sign in to comment.