Source

evolve-keyboard-layout / layout_base.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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
#!/usr/bin/env python3
# encoding: utf-8

u"""Basic functions and constants for working with keyboard layouts."""

from __future__ import division
from codecs import open
def read_file(path):
    u"""Get the data from a file.

    >>> read_file("testfile")[:2]
    'ui'
    """

    f = open(path, encoding=u"utf-8")
    data = f.read()
    f.close()
    return data

### get the config

# check if we got one via the commandline (and remove the argument if yes). Otherwise use the default.
from sys import argv
#from io import open
if u"--config" in argv: 
    idx = argv.index(u"--config")
    # the config module is the file without the extension.
    cfg = argv[idx+1][:-3]
    # replace all / and \ with .
    cfg = cfg.replace(u"/", u".")
    cfg = cfg.replace(u"\\", u".")
    argv = argv[:idx] + argv[idx+2:]
    exec(u"from " + cfg + u" import *")
else: 
    from config import *

### Constants

#: Die Layout-Datei für Neo = Tastenbelegung - Großbuchstaben integriert. 
NEO_LAYOUT = [
    [(u"^", u"ˇ", u"↻", u"˙", u"˞", u"̣"),(u"1", u"°", u"¹", u"ª", u"₁", u"¬"),(u"2", u"§", u"²", u"º", u"₂", u"∨"),(u"3", u"ℓ", u"³", u"№", u"₃", u"∧"),
     (u"4", u"»", u"›", u"", u"♀", u"⊥"),(u"5", u"«", u"‹", u"·", u"♂", u"∡"),(u"6", u"$", u"¢", u"£", u"⚥", u"∥"),(u"7", u"€", u"¥", u"¤", u"ϰ", u"→"),
     (u"8", u"„", u"‚", u"⇥", u"⟨", u"∞"),(u"9", u"“", u"‘", u" /", u"⟩", u"∝"),(u"0", u"”", u"’", u"*", u"₀", u"∅"),(u"-", u"—", u"-", u"‑", u"­"),
     (u"`", u"¸", u"°", u"¨", u"", u"¯"),(u"←")], # Zahlenreihe (0)

    [(u"⇥"),(u"x", u"X", u"…", u"⇞", u"ξ", u"Ξ"),(u"v", u"V", u"_", u"⌫", u"", u"√"),(u"l", u"L", u"[", u"⇡", u"λ", u"Λ"),
     (u"c", u"C", u"]", u"Entf", u"χ", u"ℂ"),(u"w", u"W", u"^", u"⇟", u"ω", u"Ω"),(u"k", u"K", u"!", u"¡", u"κ", u"×"),(u"h", u"H", u"<", u"7", u"ψ", u"Ψ"),
     (u"g", u"G", u">", u"8", u"γ", u"Γ"),(u"f", u"F", u"=", u"9", u"φ", u"Φ"),(u"q", u"Q", u"&", u"+", u"ϕ", u"ℚ"),(u"ß", u"ẞ", u"ſ", u"−", u"ς", u"∘"),
     (u"´", u"~", u"/", u"˝", u"", u"˘"),()], # Reihe 1

    [(u"⇩"),(u"u", u"U", u"\\", u"⇱", u"", u"⊂"),(u"i", u"I", u"/", u"⇠", u"ι", u"∫"),(u"a", u"A", u"{",  u"⇣", u"α", u"∀"),
     (u"e", u"E", u"}", u"⇢", u"ε", u"∃"),(u"o", u"O", u"*", u"⇲", u"ο", u"∈"),(u"s", u"S", u"?", u"¿", u"σ", u"Σ"),(u"n", u"N", u"(", u"4", u"ν", u"ℕ"),
     (u"r", u"R", u")", u"5", u"ρ", u"ℝ"),(u"t", u"T", u"-", u"6", u"τ", u"∂"),(u"d", u"D", u":", u",", u"δ", u"Δ"),(u"y", u"Y", u"@", u".", u"υ", u"∇"),
     (u"⇘"),(u"\n")], # Reihe 2

    [(u"⇧"),(u"⇚"),(u"ü", u"Ü", u"#", u"", u"", u"∪"),(u"ö", u"Ö", u"$", u"", u"ϵ", u"∩"),(u"ä", u"Ä", u"|", u"⎀", u"η", u"ℵ"),
     (u"p", u"P", u"~", u"\n", u"π", u"Π"),(u"z", u"Z", u"`", u"↶", u"ζ", u"ℤ"),(u"b", u"B", u"+", u":", u"β", u"⇐"),(u"m", u"M", u"%", u"1", u"μ", u"⇔"),
     (u",", u"–", u'"', u"2", u"ϱ", u"⇒"),(u".", u"•", u"'", u"3", u"ϑ", u"↦"),(u"j", u"J", u";", u";", u"θ", u"Θ"),(u"⇗")],        # Reihe 3

    [(), (), (), (u" ", u" ", u" ", u"0", u" ", u" "), (u"⇙"), (), (), ()] # Reihe 4 mit Leertaste
]
NEO_LAYOUT_lx = [
    [(u"^", u"ˇ", u"↻", u"˙", u"˞", u"̣"),(u"1", u"°", u"¹", u"ª", u"₁", u"¬"),(u"2", u"§", u"²", u"º", u"₂", u"∨"),(u"3", u"ℓ", u"³", u"№", u"₃", u"∧"),
     (u"4", u"»", u"›", u"", u"♀", u"⊥"),(u"5", u"«", u"‹", u"·", u"♂", u"∡"),(u"6", u"$", u"¢", u"£", u"⚥", u"∥"),(u"7", u"€", u"¥", u"¤", u"ϰ", u"→"),
     (u"8", u"„", u"‚", u"⇥", u"⟨", u"∞"),(u"9", u"“", u"‘", u" /", u"⟩", u"∝"),(u"0", u"”", u"’", u"*", u"₀", u"∅"),(u"-", u"—", u"-", u"‑", u"­"),
     (u"`", u"¸", u"°", u"¨", u"", u"¯"),(u"←")], # Zahlenreihe (0)

    [(u"⇥"),(u"l", u"L", u"…", u"⇞", u"ξ", u"Ξ"),(u"v", u"V", u"_", u"⌫", u"", u"√"),(u"x", u"X", u"[", u"⇡", u"λ", u"Λ"),
     (u"c", u"C", u"]", u"Entf", u"χ", u"ℂ"),(u"w", u"W", u"^", u"⇟", u"ω", u"Ω"),(u"k", u"K", u"!", u"¡", u"κ", u"×"),(u"h", u"H", u"<", u"7", u"ψ", u"Ψ"),
     (u"g", u"G", u">", u"8", u"γ", u"Γ"),(u"f", u"F", u"=", u"9", u"φ", u"Φ"),(u"q", u"Q", u"&", u"+", u"ϕ", u"ℚ"),(u"ß", u"ẞ", u"ſ", u"−", u"ς", u"∘"),
     (u"´", u"~", u"/", u"˝", u"", u"˘"),()], # Reihe 1

    [(u"⇩"),(u"u", u"U", u"\\", u"⇱", u"", u"⊂"),(u"i", u"I", u"/", u"⇠", u"ι", u"∫"),(u"a", u"A", u"{",  u"⇣", u"α", u"∀"),
     (u"e", u"E", u"}", u"⇢", u"ε", u"∃"),(u"o", u"O", u"*", u"⇲", u"ο", u"∈"),(u"s", u"S", u"?", u"¿", u"σ", u"Σ"),(u"n", u"N", u"(", u"4", u"ν", u"ℕ"),
     (u"r", u"R", u")", u"5", u"ρ", u"ℝ"),(u"t", u"T", u"-", u"6", u"τ", u"∂"),(u"d", u"D", u":", u",", u"δ", u"Δ"),(u"y", u"Y", u"@", u".", u"υ", u"∇"),
     (u"⇘"),(u"\n")], # Reihe 2

    [(u"⇧"),(u"⇚"),(u"ü", u"Ü", u"#", u"", u"", u"∪"),(u"ö", u"Ö", u"$", u"", u"ϵ", u"∩"),(u"ä", u"Ä", u"|", u"⎀", u"η", u"ℵ"),
     (u"p", u"P", u"~", u"\n", u"π", u"Π"),(u"z", u"Z", u"`", u"↶", u"ζ", u"ℤ"),(u"b", u"B", u"+", u":", u"β", u"⇐"),(u"m", u"M", u"%", u"1", u"μ", u"⇔"),
     (u",", u"–", u'"', u"2", u"ϱ", u"⇒"),(u".", u"•", u"'", u"3", u"ϑ", u"↦"),(u"j", u"J", u";", u";", u"θ", u"Θ"),(u"⇗")],        # Reihe 3

    [(), (), (), (u" ", u" ", u" ", u"0", u" ", u" "), (u"⇙"), (), (), ()] # Reihe 4 mit Leertaste
]
NEO_LAYOUT_lxwq = [
    [(u"^", u"ˇ", u"↻", u"˙", u"˞", u"̣"),(u"1", u"°", u"¹", u"ª", u"₁", u"¬"),(u"2", u"§", u"²", u"º", u"₂", u"∨"),(u"3", u"ℓ", u"³", u"№", u"₃", u"∧"),
     (u"4", u"»", u"›", u"", u"♀", u"⊥"),(u"5", u"«", u"‹", u"·", u"♂", u"∡"),(u"6", u"$", u"¢", u"£", u"⚥", u"∥"),(u"7", u"€", u"¥", u"¤", u"ϰ", u"→"),
     (u"8", u"„", u"‚", u"⇥", u"⟨", u"∞"),(u"9", u"“", u"‘", u" /", u"⟩", u"∝"),(u"0", u"”", u"’", u"*", u"₀", u"∅"),(u"-", u"—", u"-", u"‑", u"­"),
     (u"`", u"¸", u"°", u"¨", u"", u"¯"),(u"←")], # Zahlenreihe (0)

    [(u"⇥"),(u"l", u"L", u"…", u"⇞", u"ξ", u"Ξ"),(u"v", u"V", u"_", u"⌫", u"", u"√"),(u"x", u"X", u"[", u"⇡", u"λ", u"Λ"),
     (u"c", u"C", u"]", u"Entf", u"χ", u"ℂ"),(u"q", u"Q", u"^", u"⇟", u"ω", u"Ω"),(u"k", u"K", u"!", u"¡", u"κ", u"×"),(u"h", u"H", u"<", u"7", u"ψ", u"Ψ"),
     (u"g", u"G", u">", u"8", u"γ", u"Γ"),(u"f", u"F", u"=", u"9", u"φ", u"Φ"),(u"w", u"W", u"&", u"+", u"ϕ", u"ℚ"),(u"ß", u"ẞ", u"ſ", u"−", u"ς", u"∘"),
     (u"´", u"~", u"/", u"˝", u"", u"˘"),()], # Reihe 1

    [(u"⇩"),(u"u", u"U", u"\\", u"⇱", u"", u"⊂"),(u"i", u"I", u"/", u"⇠", u"ι", u"∫"),(u"a", u"A", u"{",  u"⇣", u"α", u"∀"),
     (u"e", u"E", u"}", u"⇢", u"ε", u"∃"),(u"o", u"O", u"*", u"⇲", u"ο", u"∈"),(u"s", u"S", u"?", u"¿", u"σ", u"Σ"),(u"n", u"N", u"(", u"4", u"ν", u"ℕ"),
     (u"r", u"R", u")", u"5", u"ρ", u"ℝ"),(u"t", u"T", u"-", u"6", u"τ", u"∂"),(u"d", u"D", u":", u",", u"δ", u"Δ"),(u"y", u"Y", u"@", u".", u"υ", u"∇"),
     (u"⇘"),(u"\n")], # Reihe 2

    [(u"⇧"),(u"⇚"),(u"ü", u"Ü", u"#", u"", u"", u"∪"),(u"ö", u"Ö", u"$", u"", u"ϵ", u"∩"),(u"ä", u"Ä", u"|", u"⎀", u"η", u"ℵ"),
     (u"p", u"P", u"~", u"\n", u"π", u"Π"),(u"z", u"Z", u"`", u"↶", u"ζ", u"ℤ"),(u"b", u"B", u"+", u":", u"β", u"⇐"),(u"m", u"M", u"%", u"1", u"μ", u"⇔"),
     (u",", u"–", u'"', u"2", u"ϱ", u"⇒"),(u".", u"•", u"'", u"3", u"ϑ", u"↦"),(u"j", u"J", u";", u";", u"θ", u"Θ"),(u"⇗")],        # Reihe 3

    [(), (), (), (u" ", u" ", u" ", u"0", u" ", u" "), (u"⇙"), (), (), ()] # Reihe 4 mit Leertaste
]

# TODO: Add higher layers (shift for the numbers, …)
QWERTZ_LAYOUT = [
    [(u"^"),(u"1"),(u"2"),(u"3"),(u"4"),(u"5"),(u"6"),(u"7"),(u"8"),(u"9"),(u"0"),(u"ß"),(u"´"),(u"←")], # Zahlenreihe (0)
    [(u"⇥"),(u"q"),(u"w"),(u"e"),(u"r"),(u"t"),(u"z"),(u"u"),(u"i"),(u"o"),(u"p"),(u"ü"),(u"+"),()], # Reihe 1
    [(u"⇩"),(u"a"),(u"s"),(u"d"),(u"f"),(u"g"),(u"h"),(u"j"),(u"k"),(u"l"),(u"ö"),(u"ä"),(u"#"),(u"\n")], # Reihe 2
    [(u"⇧"),(u"<"),(u"y"),(u"x"),(u"c"),(u"v"),(u"b"),(u"n"),(u"m"),(u",", u";"),(u".", u":"),(u"-"),(u"⇗")],        # Reihe 3
    [(), (), (), (u" "), (), (), (), ()] # Reihe 4 mit Leertaste
]

#NORDTAST_LAYOUT = [
#    [("^"),("1"),("2"),("3"),("4"),("5"),("6"),("7"),("8"),("9"),("0"),("ß"),("´"),("←")], # Zahlenreihe (0)
#    [("⇥"),("ä"),("u"),("o"),("b"),("p"),("k"),("g"),("l"),("m"),("f"),("x"),("+"),()], # Reihe 1
#    [("⇩"),("a"),("i"),("e"),("t"),("c"),("h"),("d"),("n"),("r"),("s"),("ß"),(),("\n")], # Reihe 2
#    [("⇧"),(),("."),(","),("ü"),("ö"),("q"),("y"),("z"),("w"),("v"),("j"),("⇗")],        # Reihe 3
#    [(), (), (), (" "), (), (), (), ()] # Reihe 4 mit Leertaste
#]

#: from Ulf Bro, http://nordtast.org – with added Neo-layers to be fair in the comparisions.
NORDTAST_LAYOUT = [
    [(u"^", u"ˇ", u"↻", u"˙", u"˞", u"̣"),(u"1", u"°", u"¹", u"ª", u"₁", u"¬"),(u"2", u"§", u"²", u"º", u"₂", u"∨"),(u"3", u"ℓ", u"³", u"№", u"₃", u"∧"),
     (u"4", u"»", u"›", u"", u"♀", u"⊥"),(u"5", u"«", u"‹", u"·", u"♂", u"∡"),(u"6", u"$", u"¢", u"£", u"⚥", u"∥"),(u"7", u"€", u"¥", u"¤", u"ϰ", u"→"),
     (u"8", u"„", u"‚", u"⇥", u"⟨", u"∞"),(u"9", u"“", u"‘", u" /", u"⟩", u"∝"),(u"0", u"”", u"’", u"*", u"₀", u"∅"),(u"-", u"—", u"-", u"‑", u"­"),
     (u"´", u"`", u"°", u"¨", u"", u"¯"),(u"←")], # Zahlenreihe (0)

    [(u"⇥"),(u"ä", u"Ä", u"…", u"⇞", u"ξ", u"Ξ"),(u"u", u"U", u"_", u"⌫", u"", u"√"),(u"o", u"O", u"[", u"⇡", u"λ", u"Λ"),
     (u"b", u"B", u"]", u"Entf", u"χ", u"ℂ"),(u"p", u"P", u"^", u"⇟", u"ω", u"Ω"),(u"k", u"K", u"!", u"¡", u"κ", u"×"),(u"g", u"G", u"<", u"7", u"ψ", u"Ψ"),
     (u"l", u"L", u">", u"8", u"γ", u"Γ"),(u"m", u"M", u"=", u"9", u"φ", u"Φ"),(u"f", u"F", u"&", u"+", u"ϕ", u"ℚ"),(u"x", u"X", u"ſ", u"−", u"ς", u"∘"),
     (u"+", u"~", u"/", u"˝", u"", u"˘"),()], # Reihe 1

    [(u"⇩"),(u"a", u"A", u"\\", u"⇱", u"", u"⊂"),(u"i", u"I", u"/", u"⇠", u"ι", u"∫"),(u"e", u"E", u"{",  u"⇣", u"α", u"∀"),
     (u"t", u"T", u"}", u"⇢", u"ε", u"∃"),(u"c", u"C", u"*", u"⇲", u"ο", u"∈"),(u"h", u"H", u"?", u"¿", u"σ", u"Σ"),(u"d", u"D", u"(", u"4", u"ν", u"ℕ"),
     (u"n", u"N", u")", u"5", u"ρ", u"ℝ"),(u"r", u"R", u"-", u"6", u"τ", u"∂"),(u"s", u"S", u":", u",", u"δ", u"Δ"),(u"ß", u"ẞ", u"@", u".", u"υ", u"∇"),
     (u"⇘"),(u"\n")], # Reihe 2

    [(u"⇧"),(u"⇚"),(u".", u"•", u"#", u"", u"", u"∪"),(u",", u"–", u"$", u"", u"ϵ", u"∩"),(u"ü", u"Ü", u"|", u"⎀", u"η", u"ℵ"),
     (u"p", u"P", u"~", u"\n", u"π", u"Π"),(u"ö", u"Ö", u"`", u"↶", u"ζ", u"ℤ"),(u"q", u"Q", u"+", u":", u"β", u"⇐"),(u"y", u"Y", u"%", u"1", u"μ", u"⇔"),
     (u"z", u"Z", u'"', u"2", u"ϱ", u"⇒"),(u"w", u"W", u"'", u"3", u"ϑ", u"↦"),(u"v", u"V", u";", u";", u"θ", u"Θ"),(u"⇗")],        # Reihe 3

    [(), (), (), (u" ", u" ", u" ", u"0", u" ", u" "), (u"⇙"), (), (), ()] # Reihe 4 mit Leertaste
]


# TODO: Add higher layers (shift for the numbers, …)
DVORAK_LAYOUT = [
    [(u"^"),(u"1"),(u"2"),(u"3"),(u"4"),(u"5"),(u"6"),(u"7"),(u"8"),(u"9"),(u"0"),(u"ß"),(u"´"),(u"←")], # Zahlenreihe (0)
    [(u"⇥"),(u"’"),(u","),(u"."),(u"p"),(u"y"),(u"f"),(u"g"),(u"c"),(u"r"),(u"l"),(u"/"),(u"="),()], # Reihe 1
    [(u"⇩"),(u"a"),(u"o"),(u"e"),(u"u"),(u"i"),(u"d"),(u"h"),(u"t"),(u"n"),(u"s"),(u"-"),(),(u"\n")], # Reihe 2
    [(u"⇧"),(),(u";"),(u"q"),(u"j"),(u"k"),(u"x"),(u"b"),(u"m"),(u"w"),(u"v"),(u"z"),(u"⇗")],        # Reihe 3
    [(), (), (), (u" "), (), (), (), ()] # Reihe 4 mit Leertaste
]

# TODO: Add higher layers (shift for the numbers, …)
COLEMAK_LAYOUT = [
    [(u"^"),(u"1"),(u"2"),(u"3"),(u"4"),(u"5"),(u"6"),(u"7"),(u"8"),(u"9"),(u"0"),(u"ß"),(u"´"),(u"←")], # Zahlenreihe (0)
    [(u"⇥"),(u"q"),(u"w"),(u"f"),(u"p"),(u"g"),(u"j"),(u"l"),(u"u"),(u"y"),(u";"),(u"["),(u"]"),(u"\\")], # Reihe 1
    [(u"⇩"),(u"a"),(u"r"),(u"s"),(u"t"),(u"d"),(u"h"),(u"n"),(u"e"),(u"i"),(u"o"),(u"`"),(),(u"\n")], # Reihe 2
    [(u"⇧"),(),(u"z"),(u"x"),(u"c"),(u"v"),(u"b"),(u"k"),(u"m"),(u","),(u"."),(u"/"),(u"⇗")],        # Reihe 3
    [(), (), (), (u" "), (), (), (), ()] # Reihe 4 mit Leertaste
]


AdNW_LAYOUT = [
    [("^", "ˇ", "↻", "˙", "˞", "̣"),("1", "°", "¹", "ª", "₁", "¬"),("2", "§", "²", "º", "₂", "∨"),("3", "ℓ", "³", "№", "₃", "∧"),
     ("4", "»", "›", "", "♀", "⊥"),("5", "«", "‹", "·", "♂", "∡"),("6", "$", "¢", "£", "⚥", "∥"),("7", "€", "¥", "¤", "ϰ", "→"),
     ("8", "„", "‚", "⇥", "⟨", "∞"),("9", "“", "‘", " /", "⟩", "∝"),("0", "”", "’", "*", "₀", "∅"),("-", "—", "-", "‑", "­"),
     ("`", "¸", "°", "¨", "", "¯"),("←")], # Zahlenreihe (0)

    [("⇥"),("k", "K", "…", "⇞", "κ", ""),("u", "U", "_", "⌫", "", "⊂"),("ü", "Ü", "[", "⇡", "", "∪"),
     (".", "•", "]", "Entf", "ϑ", "↦"),("ä", "Ä", "^", "⇟", "η", "ℵ"),("v", "V", "!", "¡", "", "√"),("g", "G", "<", "7", "γ", "Γ"),
     ("c", "C", ">", "8", "χ", "ℂ"),("l", "L", "=", "9", "λ", "Λ"),("j", "J", "&", "+", "θ", "Θ"),("f", "F", "ſ", "−", "φ", "Φ"),
     ("´", "~", "/", "˝", "", "˘"),()], # Reihe 1

    [("⇩"),("h", "H", "\\", "⇱", "ψ", "Ψ"),("i", "I", "/", "⇠", "ι", "∫"),("e", "E", "}", "⇢", "ε", "∃"),
     ("a", "A", "{",  "⇣", "α", "∀"),("o", "O", "*", "⇲", "ο", ""),("d", "D", "?", "¿", "δ", "Δ"),("t", "T", "(", "4", "τ", "∂"),
     ("r", "R", ")", "5", "ρ", "ℝ"),("n", "N", "-", "6", "ν", "ℕ"),("s", "S", ":", ",", "σ", ""),("ß", "ẞ", "@", ".", "ς", ""),
     ("⇘"),("\n")], # Reihe 2

    [("⇧"),("⇚"),("x", "X", "#", "", "ξ", "Ξ"),("y", "Y", "$", "", "υ", ""),("ö", "Ö", "|", "⎀", "", "∩"),
     (",", "–", "~", "\n", "ϱ", "⇒"),("q", "Q", "`", "↶", "ϕ", "ℚ"),("b", "B", "+", ":", "β", "⇐"),("p", "P", "%", "1", "π", "Π"),
     ("w", "W", '"', "2", "ω", ""),("m", "M", "'", "3", "μ", "⇔"),("z", "Z", ";", ";", "ζ", "ℤ"),("⇗")],        # Reihe 3

    [(), (), (), (" ", " ", " ", "0", " ", " "), ("⇙"), (), (), ()] # Reihe 4 mit Leertaste
]

HAEIU_LAYOUT = [
    [('^', 'ˇ', '↻', '˙', '˞', '̣'), ('1', '°', '¹', 'ª', '₁', '¬'), ('2', '§', '²', 'º', '₂', '∨'), ('3', 'ℓ', '³', '№', '₃', '∧'),
     ('4', '»', '›', '', '♀', '⊥'), ('5', '«', '‹', '·', '♂', '∡'), ('6', '$', '¢', '£', '⚥', '∥'), ('7', '€', '¥', '¤', 'ϰ', '→'),
     ('8', '„', '‚', '⇥', '⟨', '∞'), ('9', '“', '‘', ' /', '⟩', '∝'), ('0', '”', '’', '*', '₀', '∅'), ('-', '—', '-', '‑', '←'),
     ('`', '¸', '°', '¨', '', '¯'), '←'],

    [('⇥'), ('x', 'X', '…', '⇞', 'ξ', 'Ξ'), ('z', 'Z', '_', '⌫', 'ζ', 'ℤ'), ('o', 'O', '[', '⇡', 'ο', '∈'),
     ('.', '•', ']', 'Entf', 'ϑ', '↦'), (',', '–', '^', '⇟', 'ϱ', '⇒'), ('p', 'P', '!', '¡', 'π', 'Π'), ('c', 'C', '<', '7', 'χ', 'ℂ'),
     ('l', 'L', '>', '8', 'λ', 'Λ'), ('m', 'M', '=', '9', 'μ', '⇔'), ('v', 'V', '&', '+', '', '√'), ('ß', 'ẞ', 'ſ', '−', 'ς', '∘'),
     ('´', '~', '/', '˝', '', '˘'), ()],

    [('⇩'), ('h', 'H', '\\', '⇱', 'ψ', 'Ψ'), ('a', 'A', '/', '⇠', 'α', '∀'), ('e', 'E', '{', '⇣', 'ε', '∃'),
     ('i', 'I', '}', '⇢', 'ι', '∫'), ('u', 'U', '*', '⇲', '', '⊂'), ('d', 'D', '?', '¿', 'δ', 'Δ'), ('t', 'T', '(', '4', 'τ', '∂'),
     ('n', 'N', ')', '5', 'ν', 'ℕ'), ('r', 'R', '-', '6', 'ρ', 'ℝ'), ('s', 'S', ':', ',', 'σ', ''), ('w', 'W', '@', '.', 'ω', ''),
     ('⇘'), ('\n')],

    [('⇧'), ('⇚'), ('k', 'K', '#', '', 'κ', '×'), ('ö', 'Ö', '$', '', '', '∩'), ('ä', 'Ä', '|', '⎀', 'η', 'ℵ'),
     ('ü', 'Ü', '~', '\n', '', '∪'), ('y', 'Y', '`', '↶', 'υ', ''), ('b', 'B', '+', ':', 'β', '⇐'), ('g', 'G', '%', '1', 'γ', 'Γ'),
     ('j', 'J', '"', '2', 'θ', 'Θ'), ('q', 'Q', "'", '3', 'ϕ', 'ℚ'), ('f', 'F', ';', ';', 'φ', 'Φ'), ('⇗')],

    [(), (), (), (' ', ' ', ' ', '0', ' ', ' '), '⇙', (), (), ()],

]



# Ulfs All fingers equal but the small one
COST_PER_KEY_OLD  = [ # 0 heißt nicht beachtet
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0], # Zahlenreihe (0)
        [0,6,3,3,3,4,4,3,3,3,6,7,8,0], # Reihe 1
        [0,2,1,1,1,3,3,1,1,1,2,6,0,9], # Reihe 2
        [0,4,5,5,5,5,7,7,5,5,5,5,0],     # Reihe 3
        [0,0,0,     9     ,0,0,0,0] # Reihe 4 mit Leertaste
]

# First reweighting
COST_PER_KEY_OLD2  = [ # 0 heißt nicht beachtet
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0], # Zahlenreihe (0)
        [0,6,3,3,3,4,4,3,3,3,6,7,8,0], # Reihe 1
        [0,3,2,2,1,3,3,1,2,2,3,6,0,9], # Reihe 2
        [0,5,5,5,5,5,7,7,5,5,5,5,0],     # Reihe 3
        [0,0,0,     9     ,0,0,0,0] # Reihe 4 mit Leertaste
]

#: The names of the fingers from left to right
FINGER_NAMES = [u"Klein_L", u"Ring_L", u"Mittel_L", u"Zeige_L", u"Daumen_L",
                u"Daumen_R", u"Zeige_R", u"Mittel_R", u"Ring_R", u"Klein_R"]

# Optimized structure for accessing by position. key_to_finger gets 3 times faster than with a cache and doublechecking.
KEY_TO_FINGER = {}
for finger in FINGER_POSITIONS:
    for pos in FINGER_POSITIONS[finger]:
        KEY_TO_FINGER[pos] = finger

### Constants for testing

TEST_LAYOUT = [
    [(u"^", u"ˇ", u"↻")], # Zahlenreihe (0)

    [(u"⇥"),], # Reihe 1

    [(u"u", u"U", u"\\", u"⇱", u"", u"⊂"),(u"\n")], # Reihe 2

    [],        # Reihe 3

    [(), (), (), (u" "), (u"⇙"), (), (), ()] # Reihe 4 mit Leertaste
    ]
    

# Weighting for the tests — DON’T CHANGE THIS, it’s necessary for correct testing
TEST_COST_PER_KEY  = [ # 0 heißt nicht beachtet
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0], # Zahlenreihe (0)
        [0, 12,9,6,4,10,10,4,6,9,12,15,18,0], # Reihe 1
        [0,  5,3,3,2,5,5,2,3,3,5,12,0,15], # Reihe 2 
        [15,0,10,11,11,7,12,10,7,11,11,10,15],     # Reihe 3
        [0,0,0,     5     ,0,0,0,0] # Reihe 4 mit Leertaste
]

# Gewichtung der unterschiedlichen Kosten
TEST_WEIGHT_FINGER_REPEATS = 8 #: higher than a switch from center to side, but lower than a switch from center to upper left.
TEST_WEIGHT_FINGER_REPEATS_TOP_BOTTOM = 16 #: 2 times a normal repeat, since it's really slow. Better two outside low or up than an up-down repeat. 
TEST_WEIGHT_POSITION = 1 #: reference
TEST_WEIGHT_FINGER_DISBALANCE = 5 #: multiplied with the standard deviation of the finger usage - value guessed and only valid for the 1gramme.txt corpus.
TEST_WEIGHT_TOO_LITTLE_HANDSWITCHING = 1 #: how high should it be counted, if the hands aren’t switched in a triple?
TEST_WEIGHT_INTENDED_FINGER_LOAD_LEFT_PINKY_TO_RIGHT_PINKY = [
    0.5,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    0.5] #: The intended load per finger. Inversed and then used as multiplier for the finger load before calculating the finger disbalance penalty. Any load distribution which strays from this optimum gives a penalty.

TEST_FINGER_SWITCH_COST = { # iu td < ui dt dr ua rd au < ai rt < nd eu
    u"Klein_L": {
        u"Ring_L": 3, 
        u"Mittel_L": 3
        }, 
    u"Ring_L": {
        u"Klein_L": 4,
        u"Mittel_L": 3
        }, 
    u"Mittel_L": {
        u"Klein_L": 1,
        u"Ring_L": 2
        }, 
    u"Zeige_L": {
        u"Klein_L": 1
        }, 
    u"Daumen_L": {
        },
    u"Daumen_R": {
        },
    u"Zeige_R": {
        u"Klein_R": 1
        },
    u"Mittel_R": {
        u"Ring_R": 2, 
        u"Klein_R": 1
        },
    u"Ring_R": {
        u"Mittel_R": 3,
        u"Klein_R": 4
        }, 
    u"Klein_R": {
        u"Mittel_R": 3,
        u"Ring_R": 3
        }
} # iutd, drua, uidt, rdau, airt, ndeu :)

TEST_WEIGHT_SECONDARY_BIGRAM_IN_TRIGRAM = 0.5 #: multiplier for the cost of secondary bigrams in trigrams. 


### Caches

# together with the more efficient datastructure for key_to_finger, these caches provide a performance boost by about factor 6.6

#_LETTER_TO_KEY_CACHE = {}

# TODO: Refresh directly when mutating. Then we don’t have to check anymore for the letter if it really is at the given position. 

### Imports

from copy import deepcopy


### Helper Functions

def format_layer_1_string(layout):
    u"""Format a string looking like this:

    öckäy zhmlß,´
    atieo dsnru.
    xpfüq bgvwj
    """
    l = u""
    l += u"".join((i[0] for i in layout[1][1:6])) + u" " + u"".join((i[0] for i in layout[1][6:-1])) + u"\n"
    l += u"".join((i[0] for i in layout[2][1:6])) + u" " + u"".join((i[0] for i in layout[2][6:-2])) + u"\n"
    if layout[3][1] and layout[3][1][0] != u"⇚": 
        l += u"".join((i[0] for i in layout[3][1:7])) + u" " + u"".join((i[0] for i in layout[3][7:-1]))
    else:
        l += u"".join((i[0] for i in layout[3][2:7])) + u" " + u"".join((i[0] for i in layout[3][7:-1]))
    return l


def get_key(pos, layout=NEO_LAYOUT):
    u"""Get the key at the given position.

    >>> get_key((2, 3, 0))
    'a'
    """
    try: 
        return layout[pos[0]][pos[1]][pos[2]]
    except: return None


def single_key_position_cost(pos, layout, cost_per_key=COST_PER_KEY):
    """Get the position_cost of a single key.

    @param pos: The position of the key.
    @type pos: tuple (row, col, layer).
    @return: the cost of that one position."""
    if pos is None: # not found
        return COST_PER_KEY_NOT_FOUND
    # shift, M3 and M4
    if COST_LAYER_ADDITION[pos[2]:]:
        return cost_per_key[pos[0]][pos[1]] + COST_LAYER_ADDITION[pos[2]]
    # layer has no addition cost ⇒ undefined layer (higher than layer 6!). Just take the base key…
    return cost_per_key[pos[0]][pos[1]]


def is_position_cost_lower(pos, new_pos, layout, doubled_layer=True):
    """
    >>> is_position_cost_lower((2, 10, 2), (3, 7, 3), NEO_LAYOUT)
    False
    """
    # use tripled layer cost, because it ignores the additional bigrams.
    new_cost = single_key_position_cost(new_pos, layout) + COST_LAYER_ADDITION[new_pos[2]]
    cost = single_key_position_cost(pos, layout) + 2*COST_LAYER_ADDITION[pos[2]]
    return new_cost < cost
        

def update_letter_to_key_cache(key, layout):
    u"""Update the cache entry for the given key."""
    try: LETTER_TO_KEY_CACHE = layout[5]
    except IndexError:
        layout.append({})
        LETTER_TO_KEY_CACHE = layout[5]
    pos = None
    for row in xrange(len(layout[:5])):
        for col in xrange(len(layout[row])):
            # if the key is found, use the key with the lowest cost.
            if key in layout[row][col]:
                #: the number of keys in the row
                key_num = len(layout[row][col])
                for idx in xrange(key_num):
                    # if the key exists in multiple places, use the position with the lowest cost.
                    idx_rev = key_num - idx -1
                    if layout[row][col][idx_rev] == key:
                        new_pos = (row, col, idx_rev)
                        if pos is None:
                            pos = new_pos
                        elif is_position_cost_lower(pos, new_pos, layout):
                            pos = new_pos
    LETTER_TO_KEY_CACHE[key] = pos
    return pos


def get_all_positions_in_layout(layout):
    u"""Get all positions for which there are keys in the layout. 

    >>> get_all_positions_in_layout(TEST_LAYOUT)
    [(0, 0, 0), (0, 0, 1), (0, 0, 2), (1, 0, 0), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 0, 3), (2, 0, 5), (2, 1, 0), (4, 3, 0), (4, 4, 0)]
    """
    positions = []
    for line in xrange(len(layout[:5])): # :5 to avoid finding a cache.
        for key in xrange(len(layout[line])):
            for letter in xrange(len(layout[line][key])):
                if layout[line][key][letter]: 
                    positions.append((line, key, letter))
    return positions


def get_all_keys_in_layout(layout):
    u"""Get all keys which are in the layout. Sorted the same way as the positions from get_all_positions_in_layout(). 

    >>> get_all_keys_in_layout(TEST_LAYOUT)
    ['^', 'ˇ', '↻', '⇥', 'u', 'U', '\\\\', '⇱', '⊂', '\\n', ' ', '⇙']
    """
    keys = []
    for line in layout[:5]:
        for key in line:
            for letter in key:
                if letter: 
                    keys.append(letter)
    return keys


def update_letter_to_key_cache_multiple(keys, layout):
    u"""Update the cache entries for many keys.

    @param keys: the keys to update. If it’s None, update ALL.
    """
    if keys is None:
        keys = get_all_keys_in_layout(layout)
    for key in keys:
        update_letter_to_key_cache(key, layout=layout)
    

def find_key(key, layout): 
    u"""Find the position of the key in the layout.
    
    >>> find_key("a", NEO_LAYOUT)
    (2, 3, 0)
    >>> find_key("A", NEO_LAYOUT)
    (2, 3, 1)
    >>> find_key("e", NEO_LAYOUT)
    (2, 4, 0)
    >>> find_key(",", NEO_LAYOUT)
    (3, 9, 0)
    >>> find_key(".", NEO_LAYOUT)
    (3, 10, 0)
    >>> find_key(":", NEO_LAYOUT)
    (2, 10, 2)
    >>> find_key('#', NEO_LAYOUT)
    (3, 2, 2)
    >>> find_key("⇧", layout=NEO_LAYOUT)
    (3, 0, 0)
    >>> find_key("A", layout=QWERTZ_LAYOUT)
    (2, 1, 1)
    >>> find_key("a", layout=QWERTZ_LAYOUT)
    (2, 1, 0)
    >>> find_key("£", layout=NEO_LAYOUT)
    (0, 6, 3)
    >>> find_key("»", layout=NEO_LAYOUT)
    (0, 4, 1)
    >>> find_key("«", layout=NEO_LAYOUT)
    (0, 5, 1)
    >>> find_key("¤", layout=NEO_LAYOUT)
    (0, 7, 3)
    """
    # check, if the layout already has a cache. If not, create it.
    # this approach reduces the time to find a key by about 50%.
    # TODO: find out why this change affects the costs of layouts!
    # the cost is raised by a value between 1.2480213606 (NordTast)
    # and 1.2964878374 (Colemak).
    # a part of the change might be, that now uppercase keys
    # are properly taken into account. 
    #if key != key.lower():
    #    raise ValueError("You shall not ask me for upperkey letters (yet)!")

    try: LETTER_TO_KEY_CACHE = layout[5]
    except IndexError:
        layout.append({})
        LETTER_TO_KEY_CACHE = layout[5]
        update_letter_to_key_cache_multiple(None, layout=layout)
    # first check the caches
    try: pos = LETTER_TO_KEY_CACHE[key]
    except KeyError:
        # maybe we didn’t add the uppercase key, should only happen for incomplete layouts.
        try: 
            pos = LETTER_TO_KEY_CACHE[key.lower()]
            if not pos[2]: # == 0
                pos = pos[:2] + (1,) # this is an uppercase key.
        except KeyError: 
            pos = None # all keys are in there. None means, we don’t need to check by hand.
    return pos


def finger_keys(finger_name, layout=NEO_LAYOUT):
    u"""Get the keys corresponding to the given finger name.

    >>> for name in FINGER_NAMES:
    ...    name, finger_keys(name)
    ('Klein_L', ['x', '⇩', 'u', '⇧', '⇚', 'ü'])
    ('Ring_L', ['v', 'i', 'ö'])
    ('Mittel_L', ['l', 'a', 'ä'])
    ('Zeige_L', ['c', 'e', 'p', 'w', 'o', 'z'])
    ('Daumen_L', [' '])
    ('Daumen_R', [' ', '⇙'])
    ('Zeige_R', ['k', 's', 'b', 'h', 'n', 'm'])
    ('Mittel_R', ['g', 'r', ','])
    ('Ring_R', ['f', 't', '.'])
    ('Klein_R', ['q', 'd', 'j', 'ß', 'y', '´', '⇘', '\\n', '⇗'])
    """
    keys = [unicode(get_key(pos, layout=layout)) for pos in FINGER_POSITIONS[finger_name]]
    return keys


def key_to_finger(key, layout=NEO_LAYOUT):
    u"""Get the finger name used to hit the given key.

    >>> key_to_finger("a")
    'Mittel_L'
    >>> key_to_finger("A")
    'Mittel_L'
    >>> key_to_finger("«")
    ''
    >>> key_to_finger("⇩")
    'Klein_L'
    >>> key_to_finger("⇧")
    'Klein_L'
    """
    pos = find_key(key, layout=layout)
    try: pos = pos[:2] + (0, )
    except TypeError: return u"" # pos is None
    # check the cache
    try: return KEY_TO_FINGER[pos]
    except KeyError: return u""


def pos_is_left(pos):
    u"""check if the given position is on the left hand.

    >>> clear_left_positions = [(0, 0, 0), (1, 0, 0), (2, 0, 0), (3, 0, 0), (4, 0, 0)]
    >>> False in [pos_is_left(pos) for pos in clear_left_positions]
    False
    
    """
    return RIGHT_HAND_LOWEST_INDEXES[pos[0]] > pos[1]


def switch_positions(pos0, pos1, layout=NEO_LAYOUT):
    """Switch two positions in the layout.

    >>> lay = switch_positions((1, 1, 0), (1, 3, 0), layout=NEO_LAYOUT)
    >>> lay = switch_positions((1, 1, 1), (1, 3, 1), layout=lay)
    >>> lay[:5] == NEO_LAYOUT_lx[:5]
    True
    >>> print(lay[1][1])
    ('l', 'L', '…', '⇞', 'ξ', 'Ξ')
    >>> print(lay[1][3])
    ('x', 'X', '[', '⇡', 'λ', 'Λ')
    >>> lay = switch_positions((1, 1, 0), (1, 1, 1), layout=lay)
    >>> print(lay[1][1])
    ('L', 'l', '…', '⇞', 'ξ', 'Ξ')
    >>> find_key("l", lay)
    (1, 1, 1)
    """
    lay = deepcopy(layout)
    pos0_keys = lay[pos0[0]][pos0[1]]
    pos1_keys = lay[pos1[0]][pos1[1]]

    # if they are on the same physical key, just exchange both positions on the single key
    if pos0[:2] == pos1[:2]:
        tmp = list(pos0_keys)
        tmp[pos0[2]] = pos1_keys[pos1[2]]
        tmp[pos1[2]] = pos0_keys[pos0[2]]
        tmp = tuple(tmp)

        cache_update = "".join(tmp)
        lay[pos0[0]][pos0[1]] = tmp
        update_letter_to_key_cache_multiple(cache_update, layout=lay)
        return lay

    # generate new tuples for all layers, with tmp0 containing pos1 and tmp1 containing pos0
    tmp0 = list(pos0_keys)
    tmp0[pos0[2]] = pos1_keys[pos1[2]]
    tmp0 = tuple(tmp0)
    
    tmp1 = list(pos1_keys)
    tmp1[pos1[2]] = pos0_keys[pos0[2]]
    tmp1 = tuple(tmp1)
    
    cache_update = ""
    for letter in tmp0 + tmp1:
        cache_update += letter

    lay[pos0[0]][pos0[1]] = tmp0
    lay[pos1[0]][pos1[1]] = tmp1
    update_letter_to_key_cache_multiple(cache_update, layout=lay)
    return lay
    

def switch_keys(keypairs, layout=NEO_LAYOUT, switch_layers = [0, 1, 4, 5]):
    u"""Switch keys in the layout, so we don't have to fiddle with actual layout files.

    @param keypairs: A list of keypairs to switch. The keys in these pairs MUST be the base layer keys.

    >>> lay = switch_keys([], layout = NEO_LAYOUT)
    >>> lay == NEO_LAYOUT
    True
    >>> lay = switch_keys(["lx", "wq"], layout = NEO_LAYOUT, switch_layers=[0,1])
    >>> get_key((1, 1, 0), layout=lay)
    'l'
    >>> get_key((1, 3, 0), layout=lay)
    'x'
    >>> get_key((1, 5, 0), layout=lay)
    'q'
    >>> get_key((1, 10, 0), layout=lay)
    'w'
    >>> get_key((1, 1, 1), layout=lay)
    'L'
    >>> get_key((1, 3, 1), layout=lay)
    'X'
    >>> get_key((1, 5, 1), layout=lay)
    'Q'
    >>> get_key((1, 10, 1), layout=lay)
    'W'
    >>> find_key("l", layout=lay) == (1, 1, 0)
    True
    >>> find_key("L", layout=lay) == (1, 1, 1)
    True
    >>> NEO_LAYOUT_lxwq == lay
    True
    >>> lay = switch_keys(["lx"], layout = NEO_LAYOUT, switch_layers=[0,1])
    >>> NEO_LAYOUT_lx == lay
    True
    >>> a = find_key("a", layout=lay)
    >>> A = find_key("A", layout=lay)
    >>> curly = find_key("{", layout=lay)
    >>> lay = switch_keys(["ae"], layout=lay, switch_layers = [0,1,2])
    >>> a == find_key("e", layout=lay)
    True
    >>> A == find_key("E", layout=lay)
    True
    >>> curly == find_key("}", layout=lay)
    True
    >>> "}" == get_key(find_key("}", layout=lay), layout=lay)
    True
    >>> dot = find_key(".", layout=NEO_LAYOUT)
    >>> d = find_key("d", layout=NEO_LAYOUT)
    >>> comma = find_key(",", layout=NEO_LAYOUT)
    >>> p = find_key("p", layout=NEO_LAYOUT)
    >>> lay = switch_keys([".d", ",p"], layout=NEO_LAYOUT)
    >>> d == find_key(".", layout=lay)
    True
    >>> dot == find_key("d", layout=lay)
    True
    >>> p == find_key(",", layout=lay)
    True
    >>> comma == find_key("p", layout=lay)
    True
    """
    lay = deepcopy(layout)
    from pprint import pprint
    #pprint(lay)
    for pair in keypairs:
            pos0 = find_key(pair[0], layout=lay)
            pos1 = find_key(pair[1], layout=lay)

            # both positions MUST be on the base layer. 
            if pos0[2] or pos1[2]:
                #info("one of the keys isn’t on the base layer. Ignoring the switch", pair)
                continue

            pos0_keys = lay[pos0[0]][pos0[1]]
            pos1_keys = lay[pos1[0]][pos1[1]]

            # add the supported layers.
            tmp0 = []
            for i in xrange(max(len(pos1_keys), len(pos0_keys))):
                if i in switch_layers:
                    try: 
                        tmp0.append(pos1_keys[i])
                    except IndexError: # not there: Fill the layer.
                        tmp0.append(u"")
                else:
                    try: 
                        tmp0.append(pos0_keys[i])
                    except IndexError: # not there: Fill the layer.
                        tmp0.append(u"")
            tmp0 = tuple(tmp0)

            tmp1 = []
            for i in xrange(max(len(pos1_keys), len(pos0_keys))):
                if i in switch_layers:
                    try: 
                        tmp1.append(pos0_keys[i])
                    except IndexError: # not there: Fill the layer.
                        tmp1.append(u"")
                else:
                    try: 
                        tmp1.append(pos1_keys[i])
                    except IndexError: # not there: Fill the layer.
                        tmp1.append(u"")
            tmp1 = tuple(tmp1)

            cache_update = u""
            for letter in tmp0 + tmp1:
                cache_update += letter

            lay[pos0[0]][pos0[1]] = tmp0
            lay[pos1[0]][pos1[1]] = tmp1
            update_letter_to_key_cache_multiple(cache_update, layout=lay)
        #except:
        #    pprint(lay)
        #    print(prev, pair, pos0, pos1, tmp0, tmp1)
        #    exit()
    
    return lay


def string_to_layout(layout_string, base_layout=NEO_LAYOUT):
    u"""Turn a layout_string into a layout.

    öckäy zhmlß,´
    atieo dsnru.
    xpfüq bgvwj

    """
    layer_0_keys = [get_key(pos, layout=base_layout) for pos in get_all_positions_in_layout(base_layout) if pos[2] == 0]
    to_replace_list = []
    def set_key(current_key, new_letter, pos_01, layout, base_layout=base_layout, changing_layers = [0,1,4,5]):
        u"""Set the new_letter into the pos_01 in the layout. Take the key from the position in the base_layout and from the position in the letter and merge them, using layer 3,4 from the position and the rest from the letter.

        @param pos_01: the key which is currently in the given position. Not needed anymore, except for debugging.
        @param current_key: The key which is currently in the position. Not needed anymore, except for debugging.
        @param new_letter: The letter which should be in the position.
        @param pos_01: The position where the key should be placed.
        @param changing_layers: The layers in the base layout which change when the keys get changed."""
        # first get the keys for all layers from position in the base_layout
        base_keys = base_layout[pos_01[0]][pos_01[1]]
        # then get the keys corresponding to the position of the new letter.
        letter_pos = find_key(new_letter, layout=layout)
        if letter_pos is None or letter_pos[2]:
            # the new letter is not in the base_layout or not in the base layer, just set it on layer 0.
            layout[pos_01[0]][pos_01[1]] = (new_letter, ) + tuple(base_keys[1:])
            return layout
            
        letter_keys = base_layout[letter_pos[0]][letter_pos[1]]
        # replace all changing_layers in the base_keys with the new_keys.
        tmp = []
        for i in range(6):
            try: 
                if i in changing_layers:
                    tmp.append(letter_keys[i])
                else:
                    tmp.append(base_keys[i])
            except IndexError: # key not found
                tmp.append("")
        layout[pos_01[0]][pos_01[1]] = tuple(tmp)
        return layout
        
    layout = deepcopy(base_layout)
    lines = layout_string.splitlines()
    # first and second letter row
    for i in xrange(1, 6):
        layout = set_key(layout[1][i][0], lines[0][i-1], (1, i), layout)
        layout = set_key(layout[1][i+5][0], lines[0][i+5], (1, i+5), layout)
        layout = set_key(layout[2][i][0], lines[1][i-1], (2, i), layout)
        layout = set_key(layout[2][i+5][0], lines[1][i+5], (2, i+5), layout)

    layout = set_key(layout[1][-3][0], lines[0][11], (1, -3), layout)
    layout = set_key(layout[2][-3][0], lines[1][11], (2, -3), layout)

    # third row
    if lines[0][12:]:
        layout = set_key(layout[1][-2][0], lines[0][12], (1, -2), layout)
    
    left, right = lines[2].split()[:2]
    for i in xrange(len(left)):
        layout = set_key(layout[3][6-i][0], left[-i-1], (3, 6-i), layout)
    for i in xrange(len(right)):
        layout = set_key(layout[3][7+i][0], right[i], (3, 7+i), layout)

    # finally update the cache
    update_letter_to_key_cache_multiple(None, layout)

    return deepcopy(layout)
    

def changed_keys(layout0, layout1):
    u"""Find the keys which are in different positions in the two layouts.

    >>> changed_keys(NEO_LAYOUT, NEO_LAYOUT_lx)
    ['X', 'l', 'x', 'L']
    >>> from check_neo import switch_keys
    >>> t = switch_keys(["u\\n"], layout=TEST_LAYOUT, switch_layers=[0,1])
    >>> changed_keys(TEST_LAYOUT, t)
    ['\\n', 'u', 'U']
    """
    # first make sure, we have the caches.
    try: cache0 = layout0[5]
    except IndexError:
        layout0.append({})
        cache0 = layout0[5]
        update_letter_to_key_cache_multiple(None, layout=layout0)

    try: cache1 = layout1[5]
    except IndexError:
        layout1.append({})
        cache1 = layout1[5]
        update_letter_to_key_cache_multiple(None, layout=layout1)

    return [l for l in cache0 if not l in cache1 or cache0[l] != cache1[l]] + [l for l in cache1 if not l in cache0]


def diff_dict(d1, d2):
    u"""find the difference between two dictionaries.

    >>> a = {1: 2, 3: 4}
    >>> b = {1:2, 7:8}
    >>> c = {}
    >>> diff_dict(a, b)
    {3: 4, 7: 8}
    >>> a == diff_dict(a, c)
    True
    """
    diff = {}
    for key in d1:
        if not key in d2: 
            diff[key] = d1[key]
    for key in d2:
        if not key in d1:
            diff[key] = d2[key]
    return diff


def layout_difference_weighted(layout0, layout1, letters=None, letter_dict=None, sum_keystrokes=None):
    u"""Find the difference between two layouts, weighted with the number of times the differing letters are used in the corpus.

    This only gives 1.0, if one layout contains all letters from the corpus and the other layout has none of them (or all of them in different positions). 

    >>> from ngrams import get_all_data
    >>> letters, datalen1, repeats, datalen2, trigrams, number_of_trigrams = get_all_data()
    >>> layout_difference_weighted(NEO_LAYOUT, NEO_LAYOUT, letters=letters)
    0.0
    """
    # disabled tests
    """>>> layout_difference_weighted(NEO_LAYOUT, NEO_LAYOUT_lx, letters=letters)
    0.036617925978240665
    >>> layout_difference_weighted(NEO_LAYOUT, NEO_LAYOUT_lxwq, letters=letters)
    0.050589766759669606
    >>> layout_difference_weighted(NEO_LAYOUT, QWERTZ_LAYOUT, letters=letters)
    0.9486182821801175
    >>> layout_difference_weighted(NEO_LAYOUT, NORDTAST_LAYOUT, letters=letters)
    0.8830111461330287
    >>> layout_difference_weighted(NORDTAST_LAYOUT, QWERTZ_LAYOUT, letters=letters)
    0.8983918828764104
    >>> layout_difference_weighted(NEO_LAYOUT, TEST_LAYOUT, letters=letters)
    0.9999201678764246
    >>> empty = [[], [], [], [], []]
    >>> layout_difference_weighted(NEO_LAYOUT, empty, letters=letters)
    0.9999202512375004
    """
    if letter_dict is None and letters is None:
        raise Exception(u"Need letters or a letter dict")
    elif letter_dict is None:
        letter_dict = dict((letter, num) for num, letter in letters)
    if sum_keystrokes is None: 
        sum_keystrokes = sum(letter_dict.values())
    return sum([letter_dict.get(c, 0) for c in changed_keys(layout0, layout1)])/sum_keystrokes


def find_layout_families(layouts, letters, max_diff=0.2):
    u"""Find layout families in a list of layouts using the difference in key-positions, weighted by the occurrance probability of each key.

    >>> from ngrams import get_all_data
    >>> letters, datalen1, repeats, datalen2, trigrams, number_of_trigrams = get_all_data()
    >>> len(find_layout_families([NEO_LAYOUT, NEO_LAYOUT_lx, NEO_LAYOUT_lxwq, QWERTZ_LAYOUT, NORDTAST_LAYOUT], letters=letters, max_diff=0.1))
    3
    >>> len(find_layout_families([NEO_LAYOUT, NEO_LAYOUT_lx, NEO_LAYOUT_lxwq, QWERTZ_LAYOUT, NORDTAST_LAYOUT], letters=letters, max_diff=0.9))
    1
    """
    families = []
    letter_dict = dict((letter, num) for num, letter in letters)
    sum_keystrokes = sum(letter_dict.values())
    for l in layouts:
        fits = False
        for f in families:
            if layout_difference_weighted(l, f[0], letter_dict=letter_dict, sum_keystrokes=sum_keystrokes) <= max_diff:
                fits = True
        if not fits:
            families.append([])
            families[-1].append(l)
       
    return families


def combine_genetically(layout1, layout2):
    u"""Combine two layouts genetically (randomly)."""
    from random import randint
    switchlist = []
    for letter in abc:
        if randint(0, 1) == 1:
            pos = find_key(letter, layout=layout1)
            replacement = get_key(pos, layout=layout2)
            switchlist.append(letter+replacement)
    res = deepcopy(switch_keys(switchlist, layout=layout1))
    return res


def mirror_position_horizontally(pos):
    """Mirror a position horizontally: (2, 1, 0) → (2, 10, 0)

    >>> m = mirror_position_horizontally
    >>> m((0,0,0))
    (0, 13, 0)
    >>> m((0,13,0))
    (0, 0, 0)
    >>> m((0,1,0))
    (0, 12, 0)
    >>> m((0,9,0))
    (0, 4, 0)
    >>> m((0,4,0))
    (0, 9, 0)
    >>> m((0,6,0))
    (0, 7, 0)
    >>> m((0,7,0))
    (0, 6, 0)
    >>> m((1,0,0))
    (1, 11, 0)
    >>> m((1,1,0))
    (1, 10, 0)
    >>> m((1,11,0))
    (1, 0, 0)
    >>> m((1,12,0))
    (1, 0, 0)
    >>> m((2,13,0))
    (2, 0, 0)
    >>> m((2,4,0))
    (2, 7, 0)
    >>> m((2,6,0))
    (2, 5, 0)
    >>> m((3,7,0))
    (3, 6, 0)
    >>> m(None)
    """
    if not pos: return None
    if pos[0] == 2: return pos[0], max(0, 6 + (-1)*(pos[1] - 5)), pos[2]
    if pos[0] == 1: return pos[0], max(0, 6 + (-1)*(pos[1] - 5)), pos[2]
    if pos[0] == 3: return pos[0], min(12, 7 + (-1)*(pos[1] - 6)), pos[2]
    if pos[0] == 0: return pos[0], 7 + (-1)*(pos[1] - 6), pos[2]
    if pos[0] == 4:
        if pos[1] == 3: return pos # no change
        if pos[1] == 0: p1 = 7
        elif pos[1] == 1: p1 = 5
        elif pos[1] == 2: p1 = 4
        elif pos[1] == 4: p1 = 2
        elif pos[1] == 5: p1 = 1
        elif pos[1] == 6: p1 = 0
        elif pos[1] == 7: p1 = 0
        else: p1 = pos[1]
        return pos[0], p1, pos[2]
    raise Exception("Position value out of bounds")

if __name__ == u"__main__":
    from doctest import testmod
    testmod()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.