]> git.donarmstrong.com Git - kiibohd-kll.git/blob - kll_lib/containers.py
Adding support for USB Code trigger assignment
[kiibohd-kll.git] / kll_lib / containers.py
1 #!/usr/bin/env python3
2 # KLL Compiler Containers
3 #
4 # Copyright (C) 2014 by Jacob Alexander
5 #
6 # This file is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This file is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this file.  If not, see <http://www.gnu.org/licenses/>.
18
19 ### Imports ###
20
21
22
23 ### Decorators ###
24
25  ## Print Decorator Variables
26 ERROR = '\033[5;1;31mERROR\033[0m:'
27
28
29
30 ### Parsing ###
31
32  ## Containers
33 class Capabilities:
34         # Container for capabilities dictionary and convenience functions
35         def __init__( self ):
36                 self.capabilities = dict()
37
38         def __getitem__( self, name ):
39                 return self.capabilities[ name ]
40
41         def __setitem__( self, name, contents ):
42                 self.capabilities[ name ] = contents
43
44         def __repr__( self ):
45                 return "Capabilities => {0}\nIndexed Capabilities => {1}".format( self.capabilities, sorted( self.capabilities, key = self.capabilities.get ) )
46
47
48         # Total bytes needed to store arguments
49         def totalArgBytes( self, name ):
50                 totalBytes = 0
51
52                 # Iterate over the arguments, summing the total bytes
53                 for arg in self.capabilities[ name ][ 1 ]:
54                         totalBytes += int( arg[ 1 ] )
55
56                 return totalBytes
57
58         # Name of the capability function
59         def funcName( self, name ):
60                 return self.capabilities[ name ][ 0 ]
61
62
63         # Only valid while dictionary keys are not added/removed
64         def getIndex( self, name ):
65                 return sorted( self.capabilities, key = self.capabilities.get ).index( name )
66
67         def getName( self, index ):
68                 return sorted( self.capabilities, key = self.capabilities.get )[ index ]
69
70         def keys( self ):
71                 return sorted( self.capabilities, key = self.capabilities.get )
72
73
74 class Macros:
75         # Container for Trigger Macro : Result Macro correlation
76         # Layer selection for generating TriggerLists
77         #
78         # Only convert USB Code list once all the ResultMacros have been accumulated (does a macro reduction; not reversible)
79         # Two staged list for ResultMacros:
80         #  1) USB Code/Non-converted (may contain capabilities)
81         #  2) Capabilities
82         def __init__( self ):
83                 # Default layer (0)
84                 self.layer = 0
85
86                 # Macro Storage
87                 self.macros = [ dict() ]
88
89                 # Correlated Macro Data
90                 self.resultsIndex = dict()
91                 self.triggersIndex = dict()
92                 self.resultsIndexSorted = []
93                 self.triggersIndexSorted = []
94                 self.triggerList = []
95                 self.maxScanCode = []
96
97                 # USBCode Assignment Cache
98                 self.assignmentCache = []
99
100         def __repr__( self ):
101                 return "{0}".format( self.macros )
102
103         def setLayer( self, layer ):
104                 self.layer = layer
105
106         # Use for ScanCode trigger macros
107         def appendScanCode( self, trigger, result ):
108                 if not trigger in self.macros[ self.layer ]:
109                         self.replaceScanCode( trigger, result )
110                 else:
111                         self.macros[ self.layer ][ trigger ].append( result )
112
113         # Remove the given trigger/result pair
114         def removeScanCode( self, trigger, result ):
115                 # Remove all instances of the given trigger/result pair
116                 while result in self.macros[ self.layer ][ trigger ]:
117                         self.macros[ self.layer ][ trigger ].remove( result )
118
119         # Replaces the given trigger with the given result
120         # If multiple results for a given trigger, clear, then add
121         def replaceScanCode( self, trigger, result ):
122                 self.macros[ self.layer ][ trigger ] = [ result ]
123
124         # Return a list of ScanCode triggers with the given USB Code trigger
125         def lookupUSBCodes( self, usbCode ):
126                 scanCodeList = []
127
128                 # Scan current layer for USB Codes
129                 for macro in self.macros[ self.layer ].keys():
130                         if usbCode in self.macros[ self.layer ][ macro ]:
131                                 scanCodeList.append( macro )
132
133                 return scanCodeList
134
135         # Cache USBCode Assignment
136         def cacheAssignment( self, operator, scanCode, result ):
137                 self.assignmentCache.append( [ operator, scanCode, result ] )
138
139         # Assign cached USBCode Assignments
140         def replayCachedAssignments( self ):
141                 # Iterate over each item in the assignment cache
142                 for item in self.assignmentCache:
143                         # Check operator, and choose the specified assignment action
144                         # Append Case
145                         if item[0] == ":+":
146                                 self.appendScanCode( item[1], item[2] )
147
148                         # Remove Case
149                         elif item[0] == ":-":
150                                 self.removeScanCode( item[1], item[2] )
151
152                         # Replace Case
153                         elif item[0] == ":":
154                                 self.replaceScanCode( item[1], item[2] )
155
156                 # Clear assignment cache
157                 self.assignmentCache = []
158
159         # Generate/Correlate Layers
160         def generate( self ):
161                 self.generateIndices()
162                 self.sortIndexLists()
163                 self.generateTriggerLists()
164
165         # Generates Index of Results and Triggers
166         def generateIndices( self ):
167                 # Iterate over every trigger result, and add to the resultsIndex and triggersIndex
168                 for layer in range( 0, len( self.macros ) ):
169                         for trigger in self.macros[ layer ].keys():
170                                 # Each trigger has a list of results
171                                 for result in self.macros[ layer ][ trigger ]:
172                                         # Only add, with an index, if result hasn't been added yet
173                                         if not result in self.resultsIndex:
174                                                 self.resultsIndex[ result ] = len( self.resultsIndex )
175
176                                         # Then add a trigger for each result, if trigger hasn't been added yet
177                                         triggerItem = tuple( [ trigger, self.resultsIndex[ result ] ] )
178                                         if not triggerItem in self.triggersIndex:
179                                                 self.triggersIndex[ triggerItem ] = len( self.triggersIndex )
180
181         # Sort Index Lists using the indices rather than triggers/results
182         def sortIndexLists( self ):
183                 self.resultsIndexSorted = [ None ] * len( self.resultsIndex )
184                 # Iterate over the resultsIndex and sort by index
185                 for result in self.resultsIndex.keys():
186                         self.resultsIndexSorted[ self.resultsIndex[ result ] ] = result
187
188                 self.triggersIndexSorted = [ None ] * len( self.triggersIndex )
189                 # Iterate over the triggersIndex and sort by index
190                 for trigger in self.triggersIndex.keys():
191                         self.triggersIndexSorted[ self.triggersIndex[ trigger ] ] = trigger
192
193         # Generates Trigger Lists per layer using index lists
194         def generateTriggerLists( self ):
195                 for layer in range( 0, len( self.macros ) ):
196                         # Set max scancode to 0xFF (255)
197                         # But keep track of the actual max scancode and reduce the list size
198                         self.triggerList.append( [ [] ] * 0xFF )
199                         self.maxScanCode.append( 0x00 )
200
201                         # Iterate through triggersIndex to locate necessary ScanCodes and corresponding triggerIndex
202                         for triggerItem in self.triggersIndex.keys():
203                                 # Iterate over the trigger portion of the triggerItem (other part is the index)
204                                 for sequence in triggerItem[ 0 ]:
205                                         for combo in sequence:
206                                                 # Append triggerIndex for each found scanCode of the Trigger List
207                                                 # Do not re-add if triggerIndex is already in the Trigger List
208                                                 if not triggerItem[1] in self.triggerList[ layer ][ combo ]:
209                                                         # Append is working strangely with list pre-initialization
210                                                         # Doing a 0 check replacement instead -HaaTa
211                                                         if len( self.triggerList[ layer ][ combo ] ) == 0:
212                                                                 self.triggerList[ layer ][ combo ] = [ triggerItem[ 1 ] ]
213                                                         else:
214                                                                 self.triggerList[ layer ][ combo ].append( triggerItem[1] )
215
216                                                 # Look for max Scan Code
217                                                 if combo > self.maxScanCode[ layer ]:
218                                                         self.maxScanCode[ layer ] = combo
219
220                         # Shrink triggerList to actual max size
221                         self.triggerList[ layer ] = self.triggerList[ layer ][ : self.maxScanCode[ layer ] + 1 ]
222
223                 # Determine overall maxScanCode
224                 self.overallMaxScanCode = 0x00
225                 for maxVal in self.maxScanCode:
226                         if maxVal > self.overallMaxScanCode:
227                                 self.overallMaxScanCode = maxVal
228