-
Notifications
You must be signed in to change notification settings - Fork 421
/
Copy pathSquirrelPanel.mm
5289 lines (4998 loc) · 222 KB
/
SquirrelPanel.mm
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
994
995
996
997
998
999
1000
#import "SquirrelPanel.hh"
#import "SquirrelApplicationDelegate.hh"
#import "SquirrelConfig.hh"
#import <QuartzCore/QuartzCore.h>
static NSString* const kDefaultCandidateFormat = @"%c. %@";
static NSString* const kTipSpecifier = @"%s";
static NSString* const kFullWidthSpace = @" ";
static const NSTimeInterval kShowStatusDuration = 2.0;
static const CGFloat kBlendedBackgroundColorFraction = 0.2;
static const CGFloat kDefaultFontSize = 24;
static const CGFloat kOffsetGap = 5;
@interface NSBezierPath (BezierPathQuartzUtilities)
@property(nonatomic, readonly) CGPathRef quartzPath;
@end
@implementation NSBezierPath (BezierPathQuartzUtilities)
- (CGPathRef)quartzPath {
if (@available(macOS 14.0, *)) {
return self.CGPath;
}
// Need to begin a path here.
CGPathRef immutablePath = NULL;
// Then draw the path elements.
NSInteger numElements = self.elementCount;
if (numElements > 0) {
CGMutablePathRef path = CGPathCreateMutable();
NSPoint points[3];
for (NSInteger i = 0; i < numElements; i++) {
switch ([self elementAtIndex:i associatedPoints:points]) {
case NSBezierPathElementMoveTo:
CGPathMoveToPoint(path, NULL, points[0].x, points[0].y);
break;
case NSBezierPathElementLineTo:
CGPathAddLineToPoint(path, NULL, points[0].x, points[0].y);
break;
case NSBezierPathElementCurveTo:
CGPathAddCurveToPoint(path, NULL, points[0].x, points[0].y,
points[1].x, points[1].y, points[2].x,
points[2].y);
break;
case NSBezierPathElementQuadraticCurveTo:
CGPathAddQuadCurveToPoint(path, NULL, points[0].x, points[0].y,
points[1].x, points[1].y);
break;
case NSBezierPathElementClosePath:
CGPathCloseSubpath(path);
break;
}
}
immutablePath = (CGPathRef)CFAutorelease(CGPathCreateCopy(path));
CGPathRelease(path);
}
return immutablePath;
}
@end // NSBezierPath (BezierPathQuartzUtilities)
__attribute__((objc_direct_members))
@implementation
NSMutableAttributedString(NSMutableAttributedStringMarkDownFormatting)
- (void)superscriptionRange:(NSRange)range {
[self
enumerateAttribute:NSFontAttributeName
inRange:range
options:
NSAttributedStringEnumerationLongestEffectiveRangeNotRequired
usingBlock:^(NSFont* _Nullable value, NSRange subRange,
BOOL* _Nonnull stop) {
NSFont* font =
[NSFont fontWithDescriptor:value.fontDescriptor
size:floor(value.pointSize * 0.55)];
[self addAttributes:@{
NSFontAttributeName : font,
(id)kCTBaselineClassAttributeName :
(id)kCTBaselineClassIdeographicCentered,
NSSuperscriptAttributeName : @(1)
}
range:subRange];
}];
}
- (void)subscriptionRange:(NSRange)range {
[self
enumerateAttribute:NSFontAttributeName
inRange:range
options:
NSAttributedStringEnumerationLongestEffectiveRangeNotRequired
usingBlock:^(NSFont* _Nullable value, NSRange subRange,
BOOL* _Nonnull stop) {
NSFont* font =
[NSFont fontWithDescriptor:value.fontDescriptor
size:floor(value.pointSize * 0.55)];
[self addAttributes:@{
NSFontAttributeName : font,
(id)kCTBaselineClassAttributeName :
(id)kCTBaselineClassIdeographicCentered,
NSSuperscriptAttributeName : @(-1)
}
range:subRange];
}];
}
static NSString* const kMarkDownPattern =
@"((\\*{1,2}|\\^|~{1,2})|((?<=\\b)_{1,2})|<(b|strong|i|em|u|sup|sub|s)>)(.+"
@"?)(\\2|\\3(?=\\b)|<\\/\\4>)";
- (void)formatMarkDown {
NSRegularExpression* regex = [NSRegularExpression.alloc
initWithPattern:kMarkDownPattern
options:NSRegularExpressionUseUnicodeWordBoundaries
error:nil];
NSInteger __block offset = 0;
[regex
enumerateMatchesInString:self.mutableString
options:0
range:NSMakeRange(0, self.length)
usingBlock:^(NSTextCheckingResult* _Nullable result,
NSMatchingFlags flags, BOOL* _Nonnull stop) {
result =
[result resultByAdjustingRangesWithOffset:offset];
NSString* tag = [self.mutableString
substringWithRange:[result rangeAtIndex:1]];
if ([tag isEqualToString:@"**"] ||
[tag isEqualToString:@"__"] ||
[tag isEqualToString:@"<b>"] ||
[tag isEqualToString:@"<strong>"]) {
[self applyFontTraits:NSBoldFontMask
range:[result rangeAtIndex:5]];
} else if ([tag isEqualToString:@"*"] ||
[tag isEqualToString:@"_"] ||
[tag isEqualToString:@"<i>"] ||
[tag isEqualToString:@"<em>"]) {
[self applyFontTraits:NSItalicFontMask
range:[result rangeAtIndex:5]];
} else if ([tag isEqualToString:@"<u>"]) {
[self addAttribute:NSUnderlineStyleAttributeName
value:@(NSUnderlineStyleSingle)
range:[result rangeAtIndex:5]];
} else if ([tag isEqualToString:@"~~"] ||
[tag isEqualToString:@"<s>"]) {
[self addAttribute:NSStrikethroughStyleAttributeName
value:@(NSUnderlineStyleSingle)
range:[result rangeAtIndex:5]];
} else if ([tag isEqualToString:@"^"] ||
[tag isEqualToString:@"<sup>"]) {
[self superscriptionRange:[result rangeAtIndex:5]];
} else if ([tag isEqualToString:@"~"] ||
[tag isEqualToString:@"<sub>"]) {
[self subscriptionRange:[result rangeAtIndex:5]];
}
[self deleteCharactersInRange:[result rangeAtIndex:6]];
[self deleteCharactersInRange:[result rangeAtIndex:1]];
offset -= [result rangeAtIndex:6].length +
[result rangeAtIndex:1].length;
}];
if (offset != 0) { // repeat until no more nested markdown
[self formatMarkDown];
}
}
static NSString* const kRubyPattern =
@"(\uFFF9\\s*)(\\S+?)(\\s*\uFFFA(.+?)\uFFFB)";
- (CGFloat)annotateRubyInRange:(NSRange)range
verticalOrientation:(BOOL)isVertical
maximumLength:(CGFloat)maxLength
scriptVariant:(NSString*)scriptVariant {
NSRegularExpression* regex =
[NSRegularExpression.alloc initWithPattern:kRubyPattern
options:0
error:nil];
CGFloat __block rubyLineHeight;
[regex
enumerateMatchesInString:self.mutableString
options:0
range:range
usingBlock:^(NSTextCheckingResult* _Nullable result,
NSMatchingFlags flags, BOOL* _Nonnull stop) {
NSRange baseRange = [result rangeAtIndex:2];
// no ruby annotation if the base string includes line
// breaks
if ([self
attributedSubstringFromRange:NSMakeRange(
0,
NSMaxRange(
baseRange))]
.size.width > maxLength - 0.1) {
[self deleteCharactersInRange:NSMakeRange(
NSMaxRange(
result.range) -
1,
1)];
[self
deleteCharactersInRange:NSMakeRange(
[result rangeAtIndex:3]
.location,
1)];
[self
deleteCharactersInRange:NSMakeRange(
[result rangeAtIndex:1]
.location,
1)];
} else {
// base string must use only one font so that all fall
// within one glyph run and the ruby annotation is
// aligned with no duplicates
NSFont* baseFont = [self attribute:NSFontAttributeName
atIndex:baseRange.location
effectiveRange:NULL];
baseFont =
CFBridgingRelease(CTFontCreateForStringWithLanguage(
(CTFontRef)baseFont,
(CFStringRef)self.mutableString,
CFRangeMake((CFIndex)baseRange.location,
(CFIndex)baseRange.length),
(CFStringRef)scriptVariant));
CGFloat rubyScale = 0.5;
CFStringRef rubyString =
(__bridge CFStringRef)[self.mutableString
substringWithRange:[result rangeAtIndex:4]];
CGFloat height =
isVertical
? (baseFont.verticalFont.ascender -
baseFont.verticalFont.descender)
: (baseFont.ascender - baseFont.descender);
rubyLineHeight = ceil(height * rubyScale);
CFStringRef rubyText[kCTRubyPositionCount];
rubyText[kCTRubyPositionBefore] = rubyString;
rubyText[kCTRubyPositionAfter] = NULL;
rubyText[kCTRubyPositionInterCharacter] = NULL;
rubyText[kCTRubyPositionInline] = NULL;
CTRubyAnnotationRef rubyAnnotation =
CTRubyAnnotationCreate(
kCTRubyAlignmentDistributeSpace,
kCTRubyOverhangNone, rubyScale, rubyText);
[self deleteCharactersInRange:[result rangeAtIndex:3]];
if (@available(macOS 12.0, *)) {
} else { // use U+008B as placeholder for line-forward
// spaces in case ruby is wider than base
[self replaceCharactersInRange:NSMakeRange(
NSMaxRange(
baseRange),
0)
withString:[NSString
stringWithFormat:
@"%C", 0x8B]];
}
[self addAttributes:@{
(id)kCTRubyAnnotationAttributeName :
CFBridgingRelease(rubyAnnotation),
NSFontAttributeName : baseFont,
NSVerticalGlyphFormAttributeName : @(isVertical)
}
range:baseRange];
[self deleteCharactersInRange:[result rangeAtIndex:1]];
}
}];
[self.mutableString replaceOccurrencesOfString:@"[\uFFF9-\uFFFB]"
withString:@""
options:NSRegularExpressionSearch
range:NSMakeRange(0, self.length)];
return ceil(rubyLineHeight);
}
@end // NSMutableAttributedString (NSMutableAttributedStringMarkDownFormatting)
__attribute__((objc_direct_members))
@implementation
NSAttributedString(NSAttributedStringHorizontalInVerticalForms)
- (NSAttributedString*)attributedStringHorizontalInVerticalForms {
NSMutableDictionary<NSAttributedStringKey, id>* attrs =
[[self attributesAtIndex:0 effectiveRange:NULL] mutableCopy];
NSFont* font = attrs[NSFontAttributeName];
CGFloat height = ceil(font.ascender - font.descender);
CGFloat width = fmax(height, ceil(self.size.width));
NSImage* image = [NSImage
imageWithSize:NSMakeSize(height, width)
flipped:YES
drawingHandler:^BOOL(NSRect dstRect) {
CGContextRef context = NSGraphicsContext.currentContext.CGContext;
CGContextSaveGState(context);
CGContextTranslateCTM(context, NSWidth(dstRect) * 0.5,
NSHeight(dstRect) * 0.5);
CGContextRotateCTM(context, -M_PI_2);
CGPoint origin =
CGPointMake(-self.size.width / width * NSHeight(dstRect) * 0.5,
-NSWidth(dstRect) * 0.5);
[self drawAtPoint:origin];
CGContextRestoreGState(context);
return YES;
}];
image.resizingMode = NSImageResizingModeStretch;
image.size = NSMakeSize(height, height);
NSTextAttachment* attm = NSTextAttachment.alloc.init;
attm.image = image;
attm.bounds = NSMakeRect(0, font.descender, height, height);
attrs[NSAttachmentAttributeName] = attm;
return [NSAttributedString.alloc
initWithString:[NSString
stringWithCharacters:(unichar[]){NSAttachmentCharacter}
length:1]
attributes:attrs];
}
@end // NSAttributedString (NSAttributedStringHorizontalInVerticalForms)
__attribute__((objc_direct_members))
@implementation
NSColorSpace(labColorSpace)
+ (NSColorSpace*)labColorSpace {
static NSColorSpace* labColorSpace;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
const CGFloat whitePoint[3] = {0.950489, 1.0, 1.088840};
const CGFloat blackPoint[3] = {0.0, 0.0, 0.0};
const CGFloat range[4] = {-127.0, 127.0, -127.0, 127.0};
labColorSpace = [NSColorSpace.alloc
initWithCGColorSpace:(CGColorSpaceRef)CFAutorelease(
CGColorSpaceCreateLab(whitePoint, blackPoint,
range))];
});
return labColorSpace;
}
@end // NSColorSpace (labColorSpace)
__attribute__((objc_direct_members))
@implementation
NSColor(semanticColors)
+ (NSColor*)secondaryTextColor {
if (@available(macOS 10.10, *)) {
return NSColor.secondaryLabelColor;
} else {
return NSColor.disabledControlTextColor;
}
}
+ (NSColor*)accentColor {
if (@available(macOS 10.14, *)) {
return NSColor.controlAccentColor;
} else {
return [NSColor colorForControlTint:NSColor.currentControlTint];
}
}
- (NSColor*)hooverColor {
if (@available(macOS 10.14, *)) {
return [self colorWithSystemEffect:NSColorSystemEffectRollover];
} else {
return [[NSAppearance.currentAppearance bestMatchFromAppearancesWithNames:@[
NSAppearanceNameAqua, NSAppearanceNameDarkAqua
]] isEqualToString:NSAppearanceNameDarkAqua]
? [self highlightWithLevel:0.3]
: [self shadowWithLevel:0.3];
}
}
- (NSColor*)disabledColor {
if (@available(macOS 10.14, *)) {
return [self colorWithSystemEffect:NSColorSystemEffectDisabled];
} else {
return [[NSAppearance.currentAppearance bestMatchFromAppearancesWithNames:@[
NSAppearanceNameAqua, NSAppearanceNameDarkAqua
]] isEqualToString:NSAppearanceNameDarkAqua]
? [self shadowWithLevel:0.3]
: [self highlightWithLevel:0.3];
}
}
@end // NSColor (semanticColors)
__attribute__((objc_direct_members))
@interface NSColor (NSColorWithLabColorSpace)
@property(nonatomic, readonly) CGFloat luminanceComponent;
@property(nonatomic, readonly) CGFloat aGnRdComponent;
@property(nonatomic, readonly) CGFloat bBuYlComponent;
@end
@implementation NSColor (NSColorWithLabColorSpace)
typedef NS_ENUM(NSInteger, ColorInversionExtent) {
kDefaultColorInversion = 0,
kAugmentedColorInversion = 1,
kModerateColorInversion = -1
};
+ (NSColor*)colorWithLabLuminance:(CGFloat)luminance
aGnRd:(CGFloat)aGnRd
bBuYl:(CGFloat)bBuYl
alpha:(CGFloat)alpha {
CGFloat components[4];
components[0] = fmax(fmin(luminance, 100.0), 0.0);
components[1] = fmax(fmin(aGnRd, 127.0), -127.0);
components[2] = fmax(fmin(bBuYl, 127.0), -127.0);
components[3] = fmax(fmin(alpha, 1.0), 0.0);
return [NSColor colorWithColorSpace:NSColorSpace.labColorSpace
components:components
count:4];
}
- (void)getLuminance:(CGFloat*)luminance
aGnRd:(CGFloat*)aGnRd
bBuYl:(CGFloat*)bBuYl
alpha:(CGFloat*)alpha {
static CGFloat luminanceComponent, aGnRdComponent, bBuYlComponent,
alphaComponent;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
CGFloat components[4] = {0.0, 0.0, 0.0, 1.0};
[([self.colorSpace isEqualTo:NSColorSpace.labColorSpace]
? self
: [self colorUsingColorSpace:NSColorSpace.labColorSpace])
getComponents:components];
luminanceComponent = components[0] / 100.0;
aGnRdComponent = components[1] / 127.0;
bBuYlComponent = components[2] / 127.0;
alphaComponent = components[3];
});
if (luminance != NULL)
*luminance = luminanceComponent;
if (aGnRd != NULL)
*aGnRd = aGnRdComponent;
if (bBuYl != NULL)
*bBuYl = bBuYlComponent;
if (alpha != NULL)
*alpha = alphaComponent;
}
- (CGFloat)luminanceComponent {
CGFloat luminance;
[self getLuminance:&luminance aGnRd:NULL bBuYl:NULL alpha:NULL];
return luminance;
}
- (CGFloat)aGnRdComponent {
CGFloat aGnRdComponent;
[self getLuminance:NULL aGnRd:&aGnRdComponent bBuYl:NULL alpha:NULL];
return aGnRdComponent;
}
- (CGFloat)bBuYlComponent {
CGFloat bBuYlComponent;
[self getLuminance:NULL aGnRd:NULL bBuYl:&bBuYlComponent alpha:NULL];
return bBuYlComponent;
}
- (NSColor*)colorByInvertingLuminanceToExtent:(ColorInversionExtent)extent {
NSColor* labColor = [self colorUsingColorSpace:NSColorSpace.labColorSpace];
CGFloat components[4] = {0.0, 0.0, 0.0, 1.0};
[labColor getComponents:components];
BOOL isDark = components[0] < 60;
switch (extent) {
case kAugmentedColorInversion:
components[0] = isDark ? 100.0 - components[0] * 2.0 / 3.0
: 150.0 - components[0] * 1.5;
break;
case kModerateColorInversion:
components[0] =
isDark ? 80.0 - components[0] / 3.0 : 135.0 - components[0] * 1.25;
break;
case kDefaultColorInversion:
components[0] =
isDark ? 90.0 - components[0] / 2.0 : 120.0 - components[0];
break;
}
NSColor* invertedColor =
[NSColor colorWithColorSpace:NSColorSpace.labColorSpace
components:components
count:4];
return [invertedColor colorUsingColorSpace:self.colorSpace];
}
@end // NSColor (colorWithLabColorSpace)
#pragma mark - Color scheme and other user configurations
__attribute__((objc_direct_members))
@interface SquirrelTheme : NSObject
typedef NS_ENUM(NSUInteger, SquirrelAppear) {
defaultAppear = 0,
lightAppear = 0,
darkAppear = 1
};
typedef NS_ENUM(NSUInteger, SquirrelStatusMessageType) {
kStatusMessageTypeMixed = 0,
kStatusMessageTypeShort = 1,
kStatusMessageTypeLong = 2
};
@property(nonatomic, strong, readonly, nonnull) NSColor* backColor;
@property(nonatomic, strong, readonly, nonnull) NSColor* preeditForeColor;
@property(nonatomic, strong, readonly, nonnull) NSColor* textForeColor;
@property(nonatomic, strong, readonly, nonnull) NSColor* commentForeColor;
@property(nonatomic, strong, readonly, nonnull) NSColor* labelForeColor;
@property(nonatomic, strong, readonly, nonnull)
NSColor* hilitedPreeditForeColor;
@property(nonatomic, strong, readonly, nonnull) NSColor* hilitedTextForeColor;
@property(nonatomic, strong, readonly, nonnull)
NSColor* hilitedCommentForeColor;
@property(nonatomic, strong, readonly, nonnull) NSColor* hilitedLabelForeColor;
@property(nonatomic, strong, readonly, nullable) NSColor* dimmedLabelForeColor;
@property(nonatomic, strong, readonly, nullable)
NSColor* hilitedCandidateBackColor;
@property(nonatomic, strong, readonly, nullable)
NSColor* hilitedPreeditBackColor;
@property(nonatomic, strong, readonly, nullable) NSColor* preeditBackColor;
@property(nonatomic, strong, readonly, nullable) NSColor* borderColor;
@property(nonatomic, strong, readonly, nullable) NSImage* backImage;
@property(nonatomic, readonly) CGFloat cornerRadius;
@property(nonatomic, readonly) CGFloat hilitedCornerRadius;
@property(nonatomic, readonly) CGFloat fullWidth;
@property(nonatomic, readonly) CGFloat linespace;
@property(nonatomic, readonly) CGFloat preeditLinespace;
@property(nonatomic, readonly) CGFloat opacity;
@property(nonatomic, readonly) CGFloat translucency;
@property(nonatomic, readonly) CGFloat lineLength;
@property(nonatomic, readonly) NSSize borderInsets;
@property(nonatomic, readonly) BOOL showPaging;
@property(nonatomic, readonly) BOOL rememberSize;
@property(nonatomic, readonly) BOOL tabular;
@property(nonatomic, readonly) BOOL linear;
@property(nonatomic, readonly) BOOL vertical;
@property(nonatomic, readonly) BOOL inlinePreedit;
@property(nonatomic, readonly) BOOL inlineCandidate;
@property(nonatomic, strong, readonly, nonnull)
NSDictionary<NSAttributedStringKey, id>* textAttrs;
@property(nonatomic, strong, readonly, nonnull)
NSDictionary<NSAttributedStringKey, id>* labelAttrs;
@property(nonatomic, strong, readonly, nonnull)
NSDictionary<NSAttributedStringKey, id>* commentAttrs;
@property(nonatomic, strong, readonly, nonnull)
NSDictionary<NSAttributedStringKey, id>* preeditAttrs;
@property(nonatomic, strong, readonly, nonnull)
NSDictionary<NSAttributedStringKey, id>* pagingAttrs;
@property(nonatomic, strong, readonly, nonnull)
NSDictionary<NSAttributedStringKey, id>* statusAttrs;
@property(nonatomic, strong, readonly, nonnull)
NSParagraphStyle* candidateParagraphStyle;
@property(nonatomic, strong, readonly, nonnull)
NSParagraphStyle* preeditParagraphStyle;
@property(nonatomic, strong, readonly, nonnull)
NSParagraphStyle* statusParagraphStyle;
@property(nonatomic, strong, readonly, nonnull)
NSParagraphStyle* pagingParagraphStyle;
@property(nonatomic, strong, readonly, nullable)
NSParagraphStyle* truncatedParagraphStyle;
@property(nonatomic, strong, readonly, nonnull) NSAttributedString* separator;
@property(nonatomic, strong, readonly, nonnull)
NSAttributedString* fullWidthPlaceholder;
@property(nonatomic, strong, readonly, nonnull)
NSAttributedString* symbolDeleteFill;
@property(nonatomic, strong, readonly, nonnull)
NSAttributedString* symbolDeleteStroke;
@property(nonatomic, strong, readonly, nullable)
NSAttributedString* symbolBackFill;
@property(nonatomic, strong, readonly, nullable)
NSAttributedString* symbolBackStroke;
@property(nonatomic, strong, readonly, nullable)
NSAttributedString* symbolForwardFill;
@property(nonatomic, strong, readonly, nullable)
NSAttributedString* symbolForwardStroke;
@property(nonatomic, strong, readonly, nullable)
NSAttributedString* symbolCompress;
@property(nonatomic, strong, readonly, nullable)
NSAttributedString* symbolExpand;
@property(nonatomic, strong, readonly, nullable) NSAttributedString* symbolLock;
@property(nonatomic, strong, readonly, nonnull) NSArray<NSString*>* labels;
@property(nonatomic, strong, readonly, nonnull)
NSAttributedString* candidateTemplate;
@property(nonatomic, strong, readonly, nonnull)
NSAttributedString* candidateHilitedTemplate;
@property(nonatomic, strong, readonly, nullable)
NSAttributedString* candidateDimmedTemplate;
@property(nonatomic, strong, readonly, nonnull) NSString* selectKeys;
@property(nonatomic, strong, readonly, nonnull) NSString* candidateFormat;
@property(nonatomic, strong, readonly, nonnull) NSString* scriptVariant;
@property(nonatomic, readonly) SquirrelStatusMessageType statusMessageType;
@property(nonatomic, readonly) NSUInteger pageSize;
- (void)updateLabelsWithConfig:(SquirrelConfig* _Nonnull)config
directUpdate:(BOOL)update;
- (void)setSelectKeys:(NSString* _Nonnull)selectKeys
labels:(NSArray<NSString*>* _Nonnull)labels
directUpdate:(BOOL)update;
- (void)setCandidateFormat:(NSString* _Nonnull)candidateFormat;
- (void)setStatusMessageType:(NSString* _Nullable)type;
- (void)updateWithConfig:(SquirrelConfig* _Nonnull)config
styleOptions:(NSSet<NSString*>* _Nonnull)styleOptions
scriptVariant:(NSString* _Nonnull)scriptVariant
forAppearance:(SquirrelAppear)appear;
- (void)setAnnotationHeight:(CGFloat)height;
- (void)setScriptVariant:(NSString* _Nonnull)scriptVariant;
@end
@implementation SquirrelTheme
static inline NSColor* blendColors(NSColor* foregroundColor,
NSColor* backgroundColor) {
return [[foregroundColor
blendedColorWithFraction:kBlendedBackgroundColorFraction
ofColor:backgroundColor ?: NSColor.lightGrayColor]
colorWithAlphaComponent:foregroundColor.alphaComponent];
}
static NSFontDescriptor* getFontDescriptor(NSString* fullname) {
if (fullname.length == 0) {
return nil;
}
NSArray<NSString*>* fontNames = [fullname componentsSeparatedByString:@","];
NSMutableArray<NSFontDescriptor*>* validFontDescriptors =
[NSMutableArray.alloc initWithCapacity:fontNames.count];
for (NSString* fontName in fontNames) {
NSFont* font = [NSFont
fontWithName:[fontName
stringByTrimmingCharactersInSet:
NSCharacterSet.whitespaceAndNewlineCharacterSet]
size:0.0];
if (font != nil) {
// If the font name is not valid, NSFontDescriptor will still create
// something for us. However, when we draw the actual text, Squirrel will
// crash if there is any font descriptor with invalid font name.
NSFontDescriptor* fontDescriptor = font.fontDescriptor;
NSFontDescriptor* UIFontDescriptor = [fontDescriptor
fontDescriptorWithSymbolicTraits:NSFontDescriptorTraitUIOptimized];
[validFontDescriptors
addObject:[NSFont fontWithDescriptor:UIFontDescriptor size:0.0] != nil
? UIFontDescriptor
: fontDescriptor];
}
}
if (validFontDescriptors.count == 0) {
return nil;
}
NSFontDescriptor* initialFontDescriptor = validFontDescriptors[0];
NSFontDescriptor* emojiFontDescriptor =
[NSFontDescriptor fontDescriptorWithName:@"AppleColorEmoji" size:0.0];
NSArray<NSFontDescriptor*>* fallbackDescriptors = [[validFontDescriptors
subarrayWithRange:NSMakeRange(1, validFontDescriptors.count - 1)]
arrayByAddingObject:emojiFontDescriptor];
return [initialFontDescriptor fontDescriptorByAddingAttributes:@{
NSFontCascadeListAttribute : fallbackDescriptors
}];
}
static CGFloat getLineHeight(NSFont* font, BOOL vertical) {
if (vertical) {
font = font.verticalFont;
}
CGFloat lineHeight = ceil(font.ascender - font.descender);
NSArray<NSFontDescriptor*>* fallbackList =
[font.fontDescriptor objectForKey:NSFontCascadeListAttribute];
for (NSFontDescriptor* fallback in fallbackList) {
NSFont* fallbackFont = [NSFont fontWithDescriptor:fallback
size:font.pointSize];
if (vertical) {
fallbackFont = fallbackFont.verticalFont;
}
lineHeight =
fmax(lineHeight, ceil(fallbackFont.ascender - fallbackFont.descender));
}
return lineHeight;
}
- (instancetype)init {
self = [super init];
if (self) {
NSMutableParagraphStyle* candidateParagraphStyle =
NSMutableParagraphStyle.alloc.init;
candidateParagraphStyle.alignment = NSTextAlignmentLeft;
candidateParagraphStyle.lineBreakStrategy = NSLineBreakStrategyNone;
// Use left-to-right marks to declare the default writing direction and
// prevent strong right-to-left characters from setting the writing
// direction in case the label are direction-less symbols
candidateParagraphStyle.baseWritingDirection =
NSWritingDirectionLeftToRight;
NSMutableParagraphStyle* preeditParagraphStyle =
candidateParagraphStyle.mutableCopy;
NSMutableParagraphStyle* pagingParagraphStyle =
candidateParagraphStyle.mutableCopy;
NSMutableParagraphStyle* statusParagraphStyle =
candidateParagraphStyle.mutableCopy;
candidateParagraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
preeditParagraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
statusParagraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
NSFontDescriptor* userFontDesc =
getFontDescriptor([NSFont userFontOfSize:0.0].fontName);
NSFontDescriptor* monoFontDesc =
getFontDescriptor([NSFont userFixedPitchFontOfSize:0.0].fontName);
NSFont* userFont = [NSFont fontWithDescriptor:userFontDesc
size:kDefaultFontSize];
NSFont* userMonoFont = [NSFont fontWithDescriptor:monoFontDesc
size:kDefaultFontSize];
NSFont* monoDigitFont =
[NSFont monospacedDigitSystemFontOfSize:kDefaultFontSize
weight:NSFontWeightRegular];
NSMutableDictionary<NSAttributedStringKey, id>* textAttrs =
NSMutableDictionary.alloc.init;
textAttrs[NSForegroundColorAttributeName] = NSColor.controlTextColor;
textAttrs[NSFontAttributeName] = userFont;
// Use left-to-right embedding to prevent right-to-left text from changing
// the layout of the candidate.
textAttrs[NSWritingDirectionAttributeName] = @[ @(0) ];
textAttrs[NSParagraphStyleAttributeName] = candidateParagraphStyle;
NSMutableDictionary<NSAttributedStringKey, id>* labelAttrs =
textAttrs.mutableCopy;
labelAttrs[NSForegroundColorAttributeName] = NSColor.accentColor;
labelAttrs[NSFontAttributeName] = userMonoFont;
labelAttrs[NSParagraphStyleAttributeName] = candidateParagraphStyle;
NSMutableDictionary<NSAttributedStringKey, id>* commentAttrs =
NSMutableDictionary.alloc.init;
commentAttrs[NSForegroundColorAttributeName] = NSColor.secondaryTextColor;
commentAttrs[NSFontAttributeName] = userFont;
commentAttrs[NSParagraphStyleAttributeName] = candidateParagraphStyle;
NSMutableDictionary<NSAttributedStringKey, id>* preeditAttrs =
NSMutableDictionary.alloc.init;
preeditAttrs[NSForegroundColorAttributeName] = NSColor.textColor;
preeditAttrs[NSFontAttributeName] = userFont;
preeditAttrs[NSLigatureAttributeName] = @(0);
preeditAttrs[NSParagraphStyleAttributeName] = preeditParagraphStyle;
NSMutableDictionary<NSAttributedStringKey, id>* pagingAttrs =
NSMutableDictionary.alloc.init;
pagingAttrs[NSFontAttributeName] = monoDigitFont;
pagingAttrs[NSForegroundColorAttributeName] = NSColor.textColor;
NSMutableDictionary<NSAttributedStringKey, id>* statusAttrs =
commentAttrs.mutableCopy;
statusAttrs[NSParagraphStyleAttributeName] = statusParagraphStyle;
_textAttrs = textAttrs;
_labelAttrs = labelAttrs;
_commentAttrs = commentAttrs;
_preeditAttrs = preeditAttrs;
_pagingAttrs = pagingAttrs;
_statusAttrs = statusAttrs;
_candidateParagraphStyle = candidateParagraphStyle;
_preeditParagraphStyle = preeditParagraphStyle;
_pagingParagraphStyle = pagingParagraphStyle;
_statusParagraphStyle = statusParagraphStyle;
_backColor = NSColor.controlBackgroundColor;
_preeditForeColor = NSColor.textColor;
_textForeColor = NSColor.controlTextColor;
_commentForeColor = NSColor.secondaryTextColor;
_labelForeColor = NSColor.accentColor;
_hilitedPreeditForeColor = NSColor.selectedTextColor;
_hilitedTextForeColor = NSColor.selectedMenuItemTextColor;
_hilitedCommentForeColor = NSColor.alternateSelectedControlTextColor;
_hilitedLabelForeColor = NSColor.alternateSelectedControlTextColor;
_selectKeys = @"12345";
_labels = @[ @"1", @"2", @"3", @"4", @"5" ];
_pageSize = 5;
_candidateFormat = kDefaultCandidateFormat;
_scriptVariant = @"zh";
[self updateCandidateFormatForAttributesOnly:NO];
[self updateSeperatorAndSymbolAttrs];
}
return self;
}
- (void)updateSeperatorAndSymbolAttrs {
NSMutableDictionary<NSAttributedStringKey, id>* sepAttrs =
_commentAttrs.mutableCopy;
sepAttrs[NSVerticalGlyphFormAttributeName] = @(NO);
_separator = [NSAttributedString.alloc
initWithString:_linear ? (_tabular ? @"\u3000\t\x1D" : @"\u3000\x1D")
: @"\n"
attributes:sepAttrs];
_fullWidthPlaceholder =
[NSAttributedString.alloc initWithString:kFullWidthSpace
attributes:_commentAttrs];
// Symbols for function buttons
NSString* attmCharacter =
[NSString stringWithCharacters:(unichar[1]){NSAttachmentCharacter}
length:1];
NSTextAttachment* attmDeleteFill = NSTextAttachment.alloc.init;
attmDeleteFill.image = [NSImage imageNamed:@"Symbols/delete.backward.fill"];
NSMutableDictionary<NSAttributedStringKey, id>* attrsDeleteFill =
_preeditAttrs.mutableCopy;
attrsDeleteFill[NSAttachmentAttributeName] = attmDeleteFill;
attrsDeleteFill[NSVerticalGlyphFormAttributeName] = @(NO);
_symbolDeleteFill = [NSAttributedString.alloc initWithString:attmCharacter
attributes:attrsDeleteFill];
NSTextAttachment* attmDeleteStroke = NSTextAttachment.alloc.init;
attmDeleteStroke.image = [NSImage imageNamed:@"Symbols/delete.backward"];
NSMutableDictionary<NSAttributedStringKey, id>* attrsDeleteStroke =
_preeditAttrs.mutableCopy;
attrsDeleteStroke[NSAttachmentAttributeName] = attmDeleteStroke;
attrsDeleteStroke[NSVerticalGlyphFormAttributeName] = @(NO);
_symbolDeleteStroke =
[NSAttributedString.alloc initWithString:attmCharacter
attributes:attrsDeleteStroke];
if (_tabular) {
NSTextAttachment* attmCompress = NSTextAttachment.alloc.init;
attmCompress.image =
[NSImage imageNamed:@"Symbols/rectangle.compress.vertical"];
NSMutableDictionary<NSAttributedStringKey, id>* attrsCompress =
_pagingAttrs.mutableCopy;
attrsCompress[NSAttachmentAttributeName] = attmCompress;
_symbolCompress = [NSAttributedString.alloc initWithString:attmCharacter
attributes:attrsCompress];
NSTextAttachment* attmExpand = NSTextAttachment.alloc.init;
attmExpand.image =
[NSImage imageNamed:@"Symbols/rectangle.expand.vertical"];
NSMutableDictionary<NSAttributedStringKey, id>* attrsExpand =
_pagingAttrs.mutableCopy;
attrsExpand[NSAttachmentAttributeName] = attmExpand;
_symbolExpand = [NSAttributedString.alloc initWithString:attmCharacter
attributes:attrsExpand];
NSTextAttachment* attmLock = NSTextAttachment.alloc.init;
attmLock.image = [NSImage
imageNamed:[NSString stringWithFormat:@"Symbols/lock%@.fill",
_vertical ? @".vertical" : @""]];
NSMutableDictionary<NSAttributedStringKey, id>* attrsLock =
_pagingAttrs.mutableCopy;
attrsLock[NSAttachmentAttributeName] = attmLock;
_symbolLock = [NSAttributedString.alloc initWithString:attmCharacter
attributes:attrsLock];
} else {
_symbolCompress = nil;
_symbolExpand = nil;
_symbolLock = nil;
}
if (_showPaging) {
NSTextAttachment* attmBackFill = NSTextAttachment.alloc.init;
attmBackFill.image = [NSImage
imageNamed:[NSString stringWithFormat:@"Symbols/chevron.%@.circle.fill",
_linear ? @"up" : @"left"]];
NSMutableDictionary<NSAttributedStringKey, id>* attrsBackFill =
_pagingAttrs.mutableCopy;
attrsBackFill[NSAttachmentAttributeName] = attmBackFill;
_symbolBackFill = [NSAttributedString.alloc initWithString:attmCharacter
attributes:attrsBackFill];
NSTextAttachment* attmBackStroke = NSTextAttachment.alloc.init;
attmBackStroke.image = [NSImage
imageNamed:[NSString stringWithFormat:@"Symbols/chevron.%@.circle",
_linear ? @"up" : @"left"]];
NSMutableDictionary<NSAttributedStringKey, id>* attrsBackStroke =
_pagingAttrs.mutableCopy;
attrsBackStroke[NSAttachmentAttributeName] = attmBackStroke;
_symbolBackStroke =
[NSAttributedString.alloc initWithString:attmCharacter
attributes:attrsBackStroke];
NSTextAttachment* attmForwardFill = NSTextAttachment.alloc.init;
attmForwardFill.image = [NSImage
imageNamed:[NSString stringWithFormat:@"Symbols/chevron.%@.circle.fill",
_linear ? @"down" : @"right"]];
NSMutableDictionary<NSAttributedStringKey, id>* attrsForwardFill =
_pagingAttrs.mutableCopy;
attrsForwardFill[NSAttachmentAttributeName] = attmForwardFill;
_symbolForwardFill =
[NSAttributedString.alloc initWithString:attmCharacter
attributes:attrsForwardFill];
NSTextAttachment* attmForwardStroke = NSTextAttachment.alloc.init;
attmForwardStroke.image = [NSImage
imageNamed:[NSString stringWithFormat:@"Symbols/chevron.%@.circle",
_linear ? @"down" : @"right"]];
NSMutableDictionary<NSAttributedStringKey, id>* attrsForwardStroke =
_pagingAttrs.mutableCopy;
attrsForwardStroke[NSAttachmentAttributeName] = attmForwardStroke;
_symbolForwardStroke =
[NSAttributedString.alloc initWithString:attmCharacter
attributes:attrsForwardStroke];
} else {
_symbolBackFill = nil;
_symbolBackStroke = nil;
_symbolForwardFill = nil;
_symbolForwardStroke = nil;
}
}
- (void)updateLabelsWithConfig:(SquirrelConfig*)config
directUpdate:(BOOL)update {
NSUInteger menuSize =
(NSUInteger)[config getIntForOption:@"menu/page_size"] ?: 5;
NSMutableArray<NSString*>* labels =
[NSMutableArray.alloc initWithCapacity:menuSize];
NSString* selectKeys =
[config getStringForOption:@"menu/alternative_select_keys"];
NSArray<NSString*>* selectLabels =
[config getListForOption:@"menu/alternative_select_labels"];
if (selectLabels.count > 0) {
[labels
addObjectsFromArray:[selectLabels
subarrayWithRange:NSMakeRange(0, menuSize)]];
}
if (selectKeys) {
if (selectLabels.count == 0) {
NSString* keyCaps = [selectKeys.uppercaseString
stringByApplyingTransform:NSStringTransformFullwidthToHalfwidth
reverse:YES];
for (NSUInteger i = 0; i < menuSize; ++i) {
labels[i] = [keyCaps substringWithRange:NSMakeRange(i, 1)];
}
}
} else {
selectKeys = [@"1234567890" substringToIndex:menuSize];
if (selectLabels.count == 0) {
NSString* numerals = [selectKeys
stringByApplyingTransform:NSStringTransformFullwidthToHalfwidth
reverse:YES];
for (NSUInteger i = 0; i < menuSize; ++i) {
labels[i] = [numerals substringWithRange:NSMakeRange(i, 1)];
}
}
}
[self setSelectKeys:selectKeys labels:labels directUpdate:update];
}
- (void)setSelectKeys:(NSString*)selectKeys
labels:(NSArray<NSString*>*)labels
directUpdate:(BOOL)update {
_selectKeys = selectKeys;
_labels = labels;
_pageSize = labels.count;
if (update) {
[self updateCandidateFormatForAttributesOnly:YES];
}
}
- (void)setCandidateFormat:(NSString*)candidateFormat {
BOOL attrsOnly = [candidateFormat isEqualToString:_candidateFormat];
if (!attrsOnly) {
_candidateFormat = candidateFormat;
}
[self updateCandidateFormatForAttributesOnly:attrsOnly];
[self updateSeperatorAndSymbolAttrs];
}
- (void)updateCandidateFormatForAttributesOnly:(BOOL)attrsOnly {
NSMutableAttributedString* candTemplate;
if (!attrsOnly) {
// validate candidate format: must have enumerator '%c' before candidate
// '%@'
NSMutableString* candidateFormat = _candidateFormat.mutableCopy;
if (![candidateFormat containsString:@"%@"]) {
[candidateFormat appendString:@"%@"];
}
NSRange labelRange = [candidateFormat rangeOfString:@"%c"
options:NSLiteralSearch];
if (labelRange.length == 0) {
[candidateFormat insertString:@"%c" atIndex:0];
}
NSRange textRange = [candidateFormat rangeOfString:@"%@"
options:NSLiteralSearch];
if (labelRange.location > textRange.location) {
candidateFormat.string = kDefaultCandidateFormat;
}
NSMutableArray<NSString*>* labels = _labels.mutableCopy;
NSRange enumRange = NSMakeRange(0, 0);
NSCharacterSet* labelCharacters = [NSCharacterSet
characterSetWithCharactersInString:[labels
componentsJoinedByString:@""]];
if ([[NSCharacterSet characterSetWithRange:NSMakeRange(0xFF10, 10)]
isSupersetOfSet:labelCharacters]) { // 01..9
if ((enumRange = [candidateFormat rangeOfString:@"%c\u20E3"
options:NSLiteralSearch])
.length > 0) { // 1︎⃣..9︎⃣0︎⃣