-
Notifications
You must be signed in to change notification settings - Fork 5
/
Software.py
499 lines (402 loc) · 17 KB
/
Software.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
from threading import Thread, Timer, Event
from package_control import events
from queue import Queue
import webbrowser
import os
import json
import sublime_plugin
import sublime
from datetime import *
from .lib.SoftwareHttp import *
from .lib.SoftwareUtil import *
from .lib.SoftwareRepo import *
from .lib.SoftwareOffline import *
from .lib.SoftwareSettings import *
from .lib.SoftwareWallClock import *
from .lib.SoftwareUserStatus import *
from .lib.SoftwareModels import *
from .lib.SoftwareSessionApp import *
from .lib.KpmManager import *
from .lib.Constants import *
from .lib.TrackerManager import *
from .lib.TreePanel import *
from .lib.ui_interactions import UI_INTERACTIONS
from .lib.SlackManager import *
from .lib.OsaScriptUtil import *
from .lib.Logger import *
DEFAULT_DURATION = 60
SETTINGS = {}
retry_counter = 0
activated = False
editor_focused = False
last_focus_event_sent = None
class ViewDashboard(sublime_plugin.TextCommand):
def run(self, edit):
launchCodeTimeDashboard()
def is_enabled(self):
return True
class EditPreferences(sublime_plugin.TextCommand):
def run(self, edit):
launchUpdatePreferences()
def is_enabled(self):
return True
class SwitchAccount(sublime_plugin.TextCommand):
def run(self, edit):
switchAccount()
def is_enabled(self):
return True
class SoftwareTopForty(sublime_plugin.TextCommand):
def run(self, edit):
webbrowser.open("https://api.software.com/music/top40")
def is_enabled(self):
return True
class ToggleStatusBarMetrics(sublime_plugin.TextCommand):
def run(self, edit):
logIt("toggling status bar metrics")
toggleStatus()
track_ui_event('toggle-status-bar-metrics')
class PauseKpmUpdatesCommand(sublime_plugin.TextCommand):
def run(self, edit):
logIt("software kpm metrics paused")
showStatus("Paused")
track_ui_event('pause-telemetry')
# set value must be below track_ui_event, otherwise we will not catch the event!
setValue("software_telemetry_on", False)
def is_enabled(self):
return (getValue("software_telemetry_on", True) is True)
# Command to re-enable kpm metrics
class EnableKpmUpdatesCommand(sublime_plugin.TextCommand):
def run(self, edit):
logIt("software kpm metrics enabled")
showStatus("Code Time")
setValue("software_telemetry_on", True)
track_ui_event('enable-telemetry')
def is_enabled(self):
return (getValue("software_telemetry_on", True) is False)
class ToggleFlowModeActionCommand(sublime_plugin.TextCommand):
def run(self, edit):
toggleFlow()
def is_enabled(self):
return True
class ToggleDockCommand(sublime_plugin.TextCommand):
def run(self, edit):
toggleDock()
def is_enabled(self):
return True
def check_and_send_unfocus_event(view):
global editor_focused
global last_focus_event_sent
if (editor_focused is False):
# set the 'isFocused' value within the SoftwareWallClock to False
blurWindow()
if (last_focus_event_sent is not 'unfocus'):
# this will send off codetime events
PluginData.send_all_datas()
track_editor_action(**editor_action_params(view, 'editor', 'unfocus'))
last_focus_event_sent = 'unfocus'
# Runs one instance per view (i.e. tab, or single file window)
class EventListener(sublime_plugin.EventListener):
def on_activated_async(self, view):
focusWindow()
global editor_focused
global last_focus_event_sent
editor_focused = True
if last_focus_event_sent is not 'focus':
track_editor_action(**editor_action_params(view, 'editor', 'focus'))
last_focus_event_sent = 'focus'
full_file_path = view.file_name()
if (full_file_path is None):
full_file_path = UNTITLED
active_data = PluginData.get_active_data(view)
# get the file info to increment the open metric
fileInfoData = PluginData.get_file_info_and_initialize_if_none(
active_data, full_file_path)
if fileInfoData is None:
return
fileInfoData['length'] = get_character_count(view)
fileInfoData['lines'] = get_line_count(view)
# this is called when the plugin initializes and
# when it's deactivated (put into the background)
def on_deactivated_async(self, view):
blurWindow()
global editor_focused
editor_focused = False
Timer(5, check_and_send_unfocus_event, [view]).start()
def on_load_async(self, view):
full_file_path = view.file_name()
if (full_file_path is None):
full_file_path = UNTITLED
active_data = PluginData.get_active_data(view)
# get the file info to increment the open metric
fileInfoData = PluginData.get_file_info_and_initialize_if_none(
active_data, full_file_path)
if fileInfoData is None:
return
fileInfoData['length'] = get_character_count(view)
# get the number of lines
fileInfoData['lines'] = get_line_count(view)
# we have the fileinfo, update the metric
fileInfoData['open'] += 1
logIt('Code Time: opened file %s' % full_file_path)
track_editor_action(**editor_action_params(view, 'file', 'open'))
updateStatusBarWithSummaryData()
def on_close(self, view):
full_file_path = view.file_name()
if (full_file_path is None):
full_file_path = UNTITLED
active_data = PluginData.get_active_data(view)
# get the file info to increment the close metric
fileInfoData = PluginData.get_file_info_and_initialize_if_none(
active_data, full_file_path)
if fileInfoData is None:
return
fileInfoData['length'] = get_character_count(view)
# get the number of lines
fileInfoData['lines'] = get_line_count(view)
# we have the fileInfo, update the metric
fileInfoData['close'] += 1
logIt('Code Time: closed file %s' % full_file_path)
Thread(target=track_file_closed, args=(full_file_path, get_syntax(view), get_line_count(view), get_character_count(view))).start()
updateStatusBarWithSummaryData()
def on_modified_async(self, view):
global PROJECT_DIR
# get active data will create the file info if it doesn't exist
active_data = PluginData.get_active_data(view)
if active_data is None or active_data.project is None:
return
# add the count for the file
full_file_path = view.file_name()
fileInfoData = {}
if (full_file_path is None):
full_file_path = UNTITLED
fileInfoData = PluginData.get_file_info_and_initialize_if_none(active_data, full_file_path)
if fileInfoData is None:
return
# project data
fileInfoData['project_name'] = active_data.project['name'] or NO_PROJ_NAME
fileInfoData['project_directory'] = active_data.project['directory']
# file data
fileInfoData['file_name'] = format_file_name(full_file_path, active_data.project['directory'])
fileInfoData['file_path'] = format_file_path(full_file_path)
resource_info = active_data.project.get('resource', {})
# repo data
fileInfoData['repo_identifier'] = resource_info.get('identifier', '')
fileInfoData['repo_name'] = resource_info.get('repo_name', '')
fileInfoData['repo_owner_id'] = resource_info.get('repo_owner_id', '')
fileInfoData['git_branch'] = resource_info.get('branch', '')
fileInfoData['git_tag'] = resource_info.get('tag', '')
# plugin data
fileInfoData['plugin_id'] = getPluginId()
fileInfoData['plugin_version'] = getVersion()
fileInfoData['plugin_name'] = getPluginName()
# If file is untitled then log that msg and set file open metrics to 1
if full_file_path == UNTITLED:
# logIt("Code Time: opened file untitled")
fileInfoData['open'] = 1
else:
pass
if fileInfoData is None:
return
fileSize = get_character_count(view)
lines = get_line_count(view)
fileInfoData['keystrokes'] += 1
prevLines = fileInfoData['lines']
if (prevLines == 0):
if (PluginData.line_counts.get(full_file_path) is None):
PluginData.line_counts[full_file_path] = prevLines
prevLines = PluginData.line_counts[full_file_path]
document_change_counts_and_type = analyzeDocumentChanges(fileInfoData, view)
if(fileInfoData.get('document_change_info', None) is None):
fileInfoData['document_change_info'] = {
'lines_added': document_change_counts_and_type['lines_added'],
'lines_deleted': document_change_counts_and_type['lines_deleted'],
'characters_added': document_change_counts_and_type['characters_added'],
'characters_deleted': document_change_counts_and_type['characters_deleted'],
'single_deletes': 0,
'is_net_change': False,
'multi_deletes': 0,
'single_adds': 0,
'multi_adds': 0,
'auto_indents': 0,
'replacements': 0,
}
else:
fileInfoData['document_change_info']['lines_added'] += document_change_counts_and_type['lines_added']
fileInfoData['document_change_info']['lines_deleted'] += document_change_counts_and_type['lines_deleted']
fileInfoData['document_change_info']['characters_added'] += document_change_counts_and_type['characters_added']
fileInfoData['document_change_info']['characters_deleted'] += document_change_counts_and_type['characters_deleted']
change_type = document_change_counts_and_type['change_type']
if (change_type == "single_delete"):
fileInfoData['document_change_info']['single_deletes'] +=1
if (change_type == "multi_delete"):
fileInfoData['document_change_info']['is_net_change'] = True
fileInfoData['document_change_info']['multi_deletes'] += 1
if (change_type == "single_add"):
fileInfoData['document_change_info']['single_adds'] += 1
if (change_type == "multi_add"):
fileInfoData['document_change_info']['is_net_change'] = True
fileInfoData['document_change_info']['multi_adds'] += 1
if (change_type == "auto_indent"):
fileInfoData['document_change_info']['auto_indents'] += 1
if (change_type == "replacement"):
fileInfoData['document_change_info']['replacements'] += 1
if (change_type == "net_zero_change"):
fileInfoData['document_change_info']['is_net_change'] = True
lineDiff = 0
if (prevLines > 0):
lineDiff = lines - prevLines
if (lineDiff > 0):
fileInfoData['linesAdded'] += lineDiff
logIt('Code Time: linesAdded incremented')
elif (lineDiff < 0):
fileInfoData['linesRemoved'] += abs(lineDiff)
logIt('Code Time: linesRemoved incremented')
if (lineDiff > 0):
fileInfoData['linesAdded'] += lineDiff
logIt('Code Time: linesAdded incremented')
elif (lineDiff < 0):
fileInfoData['linesRemoved'] += abs(lineDiff)
logIt('Code Time: linesRemoved incremented')
fileInfoData['lines'] = lines
# subtract the current size of the file from what we had before
currLen = fileInfoData['length']
charCountDiff = 0
if currLen > 0 or currLen == 0:
# currLen > 0 only worked for existing file, currlen==0 will work for new file
charCountDiff = fileSize - currLen
if (not fileInfoData["syntax"]):
fileInfoData["syntax"] = get_syntax(view)
PROJECT_DIR = active_data.project['directory']
# getResourceInfo is a SoftwareUtil function
if (active_data.project.get("identifier") is None):
resourceInfoDict = getResourceInfo(PROJECT_DIR)
if (resourceInfoDict.get("identifier") is not None):
active_data.project['identifier'] = resourceInfoDict['identifier']
active_data.project['resource'] = resourceInfoDict
fileInfoData['length'] = fileSize
if lineDiff == 0 and charCountDiff > 8:
fileInfoData['chars_pasted'] += charCountDiff
fileInfoData['paste'] += 1
logIt('Code Time: pasted incremented')
elif lineDiff == 0 and charCountDiff == -1:
fileInfoData['delete'] += 1
logIt('Code Time: delete incremented')
elif lineDiff == 0 and charCountDiff == 1:
fileInfoData['add'] += 1
logIt('Code Time: KPM incremented')
# increment the overall count
if (charCountDiff != 0 or lineDiff != 0):
active_data.keystrokes += 1
# update the netkeys and the keystrokes
# "netkeys" = add - delete
fileInfoData['netkeys'] = fileInfoData['add'] - fileInfoData['delete']
updateStatusBarWithSummaryData()
# Iniates the plugin tasks once the it's loaded into Sublime.
def plugin_loaded():
initializeUser()
def plugin_unloaded():
track_editor_action(
jwt=getJwt(),
entity='editor',
type='deactivate',
plugin_id=getPluginId(),
plugin_version=getVersion(),
plugin_name=getPluginName()
)
def initializeUser():
# check if the session file is there
jwt = getItem("jwt")
if (jwt is None):
result = createAnonymousUser()
# init
initializePlugin(True)
# init
initializePlugin(False)
initTracActivationThread = Thread(target=track_editor_activation, args=())
initTracActivationThread.start()
def track_editor_activation():
track_editor_action(
jwt=getJwt(),
entity='editor',
type='activate',
plugin_id=getPluginId(),
plugin_version=getVersion(),
plugin_name=getPluginName()
)
def initializePlugin(initializedAnonUser):
name = getPluginName()
version = getVersion()
logIt('Code Time: Loaded v%s of package name: %s' % (version, name))
showStatus("Code Time")
displayReadmeIfNotExists(False)
initWallClockThread = Thread(target=wallClockMgrInit, args=())
initWallClockThread.start()
# this check is required before the commits timer is started
initPrefsThread = Thread(target=initializeUserPreferences, args=())
initPrefsThread.start()
initialized = getItem('sublime_CtInit')
if not initialized:
setItem('sublime_CtInit', True)
initSessionSummaryThread = Thread(target=updateSessionSummaryFromServer, args=())
initSessionSummaryThread.start()
def plugin_unloaded():
# clean up the background worker
PluginData.background_worker.queue.join()
def showOfflinePrompt():
infoMsg = SERVICE_NOT_AVAIL
sublime.message_dialog(infoMsg)
def track_ui_event(command_lookup_key):
global UI_INTERACTIONS
try:
track_ui_interaction(
jwt=getJwt(),
plugin_id=getPluginId(),
plugin_version=getVersion(),
plugin_name=getPluginName(),
**UI_INTERACTIONS[command_lookup_key]
)
except Exception as ex:
print("Cannot track ui interaction for command: %s" % ex)
def track_file_closed(full_file_path, syntax, line_count, character_count):
track_editor_action(**editor_action_params(
None,
'file',
'close',
full_file_path=full_file_path,
syntax=syntax,
line_count=line_count,
character_count=character_count
))
def editor_action_params(view, entity, action_type, **kwargs):
project_directory = getProjectDirectory()
project_name = os.path.basename(project_directory)
resource_info = getResourceInfo(project_directory)
full_file_path = kwargs.get('full_file_path', "Untitled")
syntax = kwargs.get('syntax', "")
line_count = kwargs.get('line_count', 0)
character_count = kwargs.get('character_count', 0)
if(view):
full_file_path = view.file_name()
syntax = get_syntax(view)
line_count = get_line_count(view)
character_count = get_character_count(view)
return {
'jwt': getJwt(),
'entity': entity,
'type': action_type,
'file_name': format_file_name(full_file_path, project_directory),
'file_path': format_file_path(full_file_path),
'syntax': syntax,
'line_count': line_count,
'character_count': character_count,
'project_name': project_name,
'project_directory': project_directory,
'repo_identifier': resource_info.get('identifier', ''),
'repo_name': resource_info.get('repo_name', ''),
'owner_id': resource_info.get('repo_owner_id', ''),
'git_branch': resource_info.get('branch', ''),
'git_tag': resource_info.get('tag', ''),
'plugin_id': getPluginId(),
'plugin_version': getVersion(),
'plugin_name': getPluginName()
}